mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* feat(devcontainer): provision the Claude Code and Codex agent setup The dev container seeds ~/.claude and ~/.codex once from the host. A config copied from a Windows host names MCP servers, a notify program and plugin marketplaces by C:\ paths that fail on every start in the Linux container, and Codex's bubblewrap sandbox cannot start where the container cannot create user namespaces. Fixing that by hand is lost on a volume reset, a fresh clone or another machine. post-create.sh now ends with agent-setup.cjs, which is idempotent and safe to re-run: - drop Windows-only MCP servers, marketplaces and notify from the seeded Codex config, and Windows-only MCP servers from ~/.claude.json - default Codex to full access with ask-on-request when user namespaces are unavailable and the config chooses no sandbox mode - install codex-guard.cjs as a Codex PreToolUse hook that refuses recursive deletes of protected roots, force pushes, pushes to main, git clean -x, npm publish and similar - install the side-panels mod for Claude Code - refetch the marketplace snapshots the seeded Codex config names, and give Codex compound-engineering and claude-mem when they are enabled in Claude Code - track the pr-tri-review skill and write its Codex entry, so the review runs from either CLI with the other as the second engine A failed step is reported and the rest still run; GITNEXUS_AGENT_SETUP=off skips the step. Hook trust in Codex stays a manual step. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * docs(pr-tri-review): run the Codex legs on gpt-6-astra or gpt-6.1-sol at xhigh The skill still named gpt-5.5 for every Codex leg. One variable now sets the model for all three legs: CODEX_MODEL, gpt-6-astra unless set, with gpt-6.1-sol as the cheaper tier. Both take --effort xhigh on the task legs; adversarial-review still takes a model and no effort. The digest names the model actually used. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(devcontainer): address PR review feedback (#3946) - codex-guard: drop redirections before reading the command word, so `2>/dev/null rm -rf /` is refused like the plain command - agent-setup: a TOML table header or string value followed by a comment is still a header or a value; a header with a trailing comment no longer crashes the Codex config step - side-panels bus: entries carry the key of the event they record; only a second report of the same event is skipped, so the same words sent twice are two entries - side-panels board: the claude-mem list is closed at session end when this session relayed to it, also after the board was switched off - side-panels review run: runs started in the same second are ordered by folder time, not by their random suffix - side-panels worktrees: a worktree whose status cannot be read is shown as unreadable, and one with no upstream as "push state unknown", instead of clean; a failed `git worktree list` or `git status` fails the read rather than showing an empty result Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(devcontainer): judge a guarded command wherever it stands (#3946) The guard read only the first word of a simple command, after a fixed list of prefixes. What may precede a command is open-ended, so each spelling the list missed was a bypass: `2>& 1 rm -rf /`, `timeout 10 rm -rf /`, `! rm -rf /`, `(rm -rf /)`. A watched command is now judged at any position in a simple command. Grouping and substitution marks end a command, so what stands inside `( )`, `{ }`, `$( )` and backticks is read too, and `eval` is followed like `sh -c`. `rm` right after a tool with its own rm subcommand (`git rm`, `docker rm`) is left alone. The cost is that an unquoted mention is refused as well (`echo rm -rf /`); a quoted one is not. shutdown/reboot/halt/poweroff are no longer watched: they do no harm in a container and are common words as arguments. Also note in the mod test that a session.send event names its recipient as a string. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(devcontainer): close the relative-path gap and state the guard's limit (#3946) - codex-guard: a leading `./` is stripped before a target is matched, and `..`, `../*` and `.*` are protected, so `rm -rf ./*` in the workspace is refused like `rm -rf *` - codex-guard and README: describe the guard as a best-effort check on command text, not a boundary. A target or command built from a variable or a substitution is not seen; refusing every such form would refuse routine cleanup. The two computed-target forms are in the test table as allowed, marked as the stated limit - side-panels review run: show the newest run that has a lane written in the last six hours, instead of nothing when the newest is stale - side-panels agents: an idle agent is not dimmed; it counts as active Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(devcontainer): address the fourth round of review feedback (#3946) agent-setup: - an approval_policy the Codex config already sets is kept instead of being written a second time (TOML refuses a duplicate key) - a missing config.toml still gets the sandbox default: the file is created when the container cannot sandbox - a quoted table name with dots (`[mcp_servers."win.tool"]`) is read as one entry, so its Windows-only server is removed with its subtables codex-guard: - `.` and `..` segments in an rm target are resolved before matching, so `/workspace/../*` is `/*` - a hidden-file glob (`dir/.*`) is refused wherever it stands - `-f` clustered with other short options (`git push -fu`) is a force push - a shell nested past the depth the guard follows is refused unread - the malformed-payload test no longer inherits CODEX_GUARD side-panels: - a message that was not delivered is not put on the bus or relayed Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(devcontainer): simplify the agent setup code without changing behaviour (#3946) - agent-setup: one writeText under the backup-keeping writer replaces two inline compare-then-write copies - codex-guard: hoist nameOf, normalise an rm target once per target - side-panels: one isLive predicate, one block for the worktree name lists, the lane dimming derived from statusOf, named review-run time windows, one default for a pane's note, one helper to split git output into lines, MARKER no longer exported - side-panels: a pane's independent reads run together, and `git status` runs with --no-optional-locks so reading never takes the index lock from a git command the person is running The committed and the simplified script produce the same config files on identical scratch homes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(devcontainer): close gaps a fifth review pass found (#3946) - codex-guard: refuse `git push --mirror`, which overwrites and deletes remote refs without a force flag. - agent-setup: a `]` inside a string no longer ends a multi-line `notify` array early, so a Windows notify program is removed whole. - side-panels: `/panels` closes only the panes this mod opened, whatever `$.ui.panes()` lists. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
248 lines
9.6 KiB
JavaScript
248 lines
9.6 KiB
JavaScript
#!/usr/bin/env node
|
|
// Codex PreToolUse hook: refuses the common shell commands that destroy work or
|
|
// publish irreversibly. In this dev container Codex runs without its sandbox
|
|
// (the container cannot create user namespaces) and `codex exec` never asks.
|
|
//
|
|
// It is a best-effort check on the command text, not a boundary. It reads
|
|
// literal commands and literal targets. It cannot see a target or a command
|
|
// built from a variable or a substitution (`rm -rf "$DIR"`,
|
|
// `rm -rf "$(printf /workspace)"`), and a tool that deletes by other means
|
|
// (`find -delete`, a script) passes. Refusing every such form would refuse
|
|
// routine cleanup, so the limit is stated here instead.
|
|
//
|
|
// agent-setup.cjs copies this file to ~/.codex/hooks/guard/deny-destructive.cjs
|
|
// and registers it in ~/.codex/hooks.json. It must stay self-contained: no
|
|
// requires beyond Node's own.
|
|
//
|
|
// Contract (Codex hooks): the call arrives as JSON on stdin with the command at
|
|
// tool_input.command; exit 2 with the reason on stderr blocks it; exit 0 lets it
|
|
// run. CODEX_GUARD=off in the environment Codex was started with turns it off.
|
|
'use strict';
|
|
|
|
const path = require('node:path');
|
|
|
|
// Deleting any of these recursively is never what a task needs.
|
|
const PROTECTED = [
|
|
/^\/\*?$/, // / and /*
|
|
/^~\/?\*?$/, // ~ ~/ ~/*
|
|
/^\$\{?HOME\}?\/?\*?$/,
|
|
/^\/home(\/\*|\/node\/?\*?)?\/?$/,
|
|
/^\/workspace\/?\*?$/,
|
|
/^\/(etc|usr|var|bin|lib|opt|root)(\/.*)?$/,
|
|
/^\.\.?(\/\*?)?$/, // . .. ./ ../ ../*
|
|
/^\*$/, // a bare * deletes whatever the current folder happens to be
|
|
/(^|\/)\.\*$/, // a hidden-file glob reaches .git and the tool folders, wherever it stands
|
|
/(^|\/)\.git\/?$/,
|
|
/(^|\/)\.(claude|codex|claude-mem)(\/\*?)?$/,
|
|
];
|
|
|
|
const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash']);
|
|
// git options that take a value, so the word after them is not the subcommand.
|
|
const GIT_VALUE_OPTIONS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
|
|
// Tools whose own `rm` subcommand is not the shell's rm (`git rm -r --cached .`).
|
|
const HAVE_RM_SUBCOMMAND = new Set([
|
|
'git',
|
|
'docker',
|
|
'podman',
|
|
'npm',
|
|
'pnpm',
|
|
'yarn',
|
|
'gh',
|
|
'kubectl',
|
|
'helm',
|
|
]);
|
|
|
|
/**
|
|
* Splits a command line into simple commands, each a list of words, honouring
|
|
* quotes: `git commit -m "rm -rf /"` is one command whose last word is text.
|
|
* Grouping and substitution marks end a command too, so what stands inside
|
|
* `( ... )`, `{ ...; }`, `$( ... )` and backticks is read as commands of its own.
|
|
* ponytail: no variable expansion. A command built from variables (`$X -rf /`)
|
|
* is not seen; a real shell parser is the upgrade if that matters.
|
|
*/
|
|
function simpleCommands(line) {
|
|
const commands = [];
|
|
let words = [];
|
|
let word = '';
|
|
let hasWord = false;
|
|
let quote = '';
|
|
const endWord = () => {
|
|
if (hasWord) words.push(word);
|
|
word = '';
|
|
hasWord = false;
|
|
};
|
|
const endCommand = () => {
|
|
endWord();
|
|
if (words.length > 0) commands.push(words);
|
|
words = [];
|
|
};
|
|
for (let at = 0; at < line.length; at += 1) {
|
|
const char = line[at];
|
|
if (quote === "'") {
|
|
if (char === quote) quote = '';
|
|
else word += char;
|
|
} else if (quote === '"') {
|
|
// A substitution inside double quotes still runs. Its text is read as
|
|
// commands from there on; losing track of the closing quote only splits
|
|
// the rest into more words, which fails closed.
|
|
if (char === quote) quote = '';
|
|
else if (char === '`' || (char === '$' && line[at + 1] === '(')) {
|
|
endCommand();
|
|
quote = '';
|
|
} else word += char;
|
|
} else if (char === "'" || char === '"') {
|
|
quote = char;
|
|
hasWord = true;
|
|
} else if (char === '\\' && at + 1 < line.length) {
|
|
word += line[(at += 1)];
|
|
hasWord = true;
|
|
} else if (/\s/.test(char) && char !== '\n') {
|
|
endWord();
|
|
} else if (';|&\n(){}`'.includes(char)) {
|
|
endCommand();
|
|
} else {
|
|
word += char;
|
|
hasWord = true;
|
|
}
|
|
}
|
|
endCommand();
|
|
|
|
return commands;
|
|
}
|
|
|
|
/**
|
|
* Drops redirections, which may stand anywhere in a command, before its name
|
|
* included: `2>/dev/null rm -rf /` runs rm. An operator written apart from its
|
|
* target (`> out.txt`) takes the next word with it.
|
|
*/
|
|
function withoutRedirections(words) {
|
|
const kept = [];
|
|
for (let at = 0; at < words.length; at += 1) {
|
|
const redirection = /^\d*(?:>>?|<<?<?)(.*)$/.exec(words[at]);
|
|
if (redirection === null) kept.push(words[at]);
|
|
else if (redirection[1] === '') at += 1;
|
|
}
|
|
return kept;
|
|
}
|
|
|
|
/** A command word without its folder: `/usr/bin/rm` is `rm`. A missing word is ''. */
|
|
const nameOf = (word) => (word ?? '').split('/').pop();
|
|
|
|
/** Why `name args...` is refused, when `name` is a command this guard watches. */
|
|
function judge(name, args, before, depth) {
|
|
if (SHELLS.has(name) || name === 'eval') {
|
|
// `sh -c '<script>'` and `eval <words>` run their argument as a command line.
|
|
// Past a few levels the script is refused unread: any fixed depth can be out-nested.
|
|
if (depth >= 3) return 'a shell nested too deep to check';
|
|
const flag = args.findIndex((arg) => /^-[a-z]*c$/.test(arg));
|
|
const script = name === 'eval' ? args.join(' ') : flag === -1 ? '' : (args[flag + 1] ?? '');
|
|
return refusal(script, depth + 1);
|
|
}
|
|
|
|
if (name === 'rm' && !HAVE_RM_SUBCOMMAND.has(before)) {
|
|
const flags = args.filter((arg) => arg.startsWith('-')).join(' ');
|
|
// An empty word is what is left of a quoted substitution: a computed target, not `.`.
|
|
const targets = args.filter((arg) => arg !== '' && !arg.startsWith('-'));
|
|
const isRecursive = /(^|\s)-[a-zA-Z]*[rR]|--recursive/.test(flags);
|
|
// `.` and `..` segments are resolved before matching: `./*` is `*`, `././.git`
|
|
// is `.git`, and `/workspace/../*` is `/*`.
|
|
const hit = targets.find((target) => {
|
|
const plain = path.posix.normalize(target);
|
|
return PROTECTED.some((root) => root.test(plain));
|
|
});
|
|
if (isRecursive && hit !== undefined) return `rm -r on ${hit}`;
|
|
const memory = targets.find((target) => /\.claude-mem(\/|$)|claude-mem\.db/.test(target));
|
|
if (memory !== undefined) return `rm on the claude-mem store (${memory})`;
|
|
}
|
|
|
|
if (name === 'git') {
|
|
let at = 0;
|
|
while (at < args.length && args[at].startsWith('-')) {
|
|
at += GIT_VALUE_OPTIONS.has(args[at]) ? 2 : 1;
|
|
}
|
|
const verb = args[at];
|
|
const rest = args.slice(at + 1);
|
|
if (verb === 'push') {
|
|
// `-f` may be clustered with other short options: `git push -fu origin x`.
|
|
const isForce = (arg) => arg === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg);
|
|
if (rest.some((arg) => isForce(arg) || /^\+/.test(arg))) {
|
|
return 'git push --force (use --force-with-lease on your own branch)';
|
|
}
|
|
// --mirror overwrites and deletes remote refs without any force flag.
|
|
if (rest.includes('--mirror'))
|
|
return 'git push --mirror (it overwrites and deletes remote refs)';
|
|
const refs = rest.filter((arg) => !arg.startsWith('-')).slice(1);
|
|
if (refs.some((ref) => /(^|:)(refs\/heads\/)?(main|master)$/.test(ref))) {
|
|
return 'git push to main (work goes through a pull request)';
|
|
}
|
|
}
|
|
if (verb === 'clean' && rest.some((arg) => /^-[a-zA-Z]*[xX]/.test(arg))) {
|
|
return 'git clean -x (it deletes ignored files: local skills, indexes, node_modules)';
|
|
}
|
|
}
|
|
|
|
if (name === 'dd' && args.some((arg) => /^of=\/dev\//.test(arg))) return 'dd onto a device';
|
|
if (/^mkfs(\.\w+)?$/.test(name)) return 'a disk format command';
|
|
if (name === 'chmod' || name === 'chown') {
|
|
const isRecursive = args.some((arg) => /^-[a-zA-Z]*R|--recursive/.test(arg));
|
|
const hit = args.find((arg) => /^(\/|~\/?|\$\{?HOME\}?\/?|\/home\/?)$/.test(arg));
|
|
if (isRecursive && hit !== undefined) return `${name} -R on ${hit}`;
|
|
}
|
|
if (name === 'npm' && args[0] === 'publish') return 'npm publish';
|
|
if (name === 'gh' && /^(repo|release)$/.test(args[0] ?? '') && args[1] === 'delete') {
|
|
return `gh ${args[0]} delete`;
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Why the command line is refused, or undefined when it may run.
|
|
*
|
|
* A watched command is judged wherever it stands in a simple command, not only
|
|
* as its first word. What may precede a command is open-ended (`timeout 10`,
|
|
* `stdbuf -o0`, `!`, `then`, a redirection in any spelling), so a list of
|
|
* allowed prefixes is a list of bypasses. The price is that an unquoted
|
|
* mention is refused too (`echo rm -rf /`): the guard fails closed.
|
|
*/
|
|
function refusal(line, depth = 0) {
|
|
if (/:\(\)\s*\{[^}]*\|\s*:\s*&/.test(line)) return 'a fork bomb';
|
|
for (const all of simpleCommands(line)) {
|
|
const words = withoutRedirections(all);
|
|
for (let at = 0; at < words.length; at += 1) {
|
|
const why = judge(nameOf(words[at]), words.slice(at + 1), nameOf(words[at - 1]), depth);
|
|
if (why !== undefined) return why;
|
|
}
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
function main() {
|
|
if (process.env.CODEX_GUARD === 'off') process.exit(0);
|
|
let input = '';
|
|
process.stdin.on('data', (chunk) => (input += chunk));
|
|
process.stdin.on('end', () => {
|
|
let command = '';
|
|
try {
|
|
const call = JSON.parse(input);
|
|
if (call.tool_name === 'Bash' && typeof call.tool_input?.command === 'string') {
|
|
command = call.tool_input.command;
|
|
}
|
|
} catch {
|
|
// An unreadable payload is not a shell command this guard can judge: let Codex go on.
|
|
}
|
|
const why = refusal(command);
|
|
if (why === undefined) process.exit(0);
|
|
console.error(
|
|
`Blocked by the destructive-command guard: ${why}. ` +
|
|
'If the person asked for exactly this, tell them; they can run it themselves ' +
|
|
'or start Codex with CODEX_GUARD=off.',
|
|
);
|
|
process.exit(2);
|
|
});
|
|
}
|
|
|
|
module.exports = { refusal };
|
|
|
|
if (require.main === module) main();
|