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
63 changes: 63 additions & 0 deletions src/agent-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
writeAgentConfig,
installKitPermissions,
installInstallGate,
installBrokerGates,
installInstallGateCodex,
installInstallGateAmazonQ,
installInstallGateKiro,
Expand Down Expand Up @@ -397,6 +398,68 @@ describe("installInstallGate", () => {
});
});

describe("installBrokerGates (Pillar 3, opt-in)", () => {
it("wires PreToolUse gate-egress (Bash) + gate-fs (Write|Edit|NotebookEdit), idempotently", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-broker-gate-"));
try {
mkdirSync(join(dir, ".claude"), { recursive: true });
const r1 = await installBrokerGates(dir);
assert.equal(r1.action, "created");
const s = JSON.parse(readFileSync(join(dir, ".claude", "settings.json"), "utf-8"));
const groups = s.hooks.PreToolUse;
assert.equal(groups.length, 2);
const egress = groups.find((g: { matcher: string }) => g.matcher === "Bash");
const fs = groups.find((g: { matcher: string }) => g.matcher === "Write|Edit|NotebookEdit");
assert.ok(egress.hooks[0].command.endsWith("gate-egress"));
assert.ok(fs.hooks[0].command.endsWith("gate-fs"));

const r2 = await installBrokerGates(dir);
assert.equal(r2.action, "unchanged");
const s2 = JSON.parse(readFileSync(join(dir, ".claude", "settings.json"), "utf-8"));
assert.equal(s2.hooks.PreToolUse.length, 2, "no duplicate groups on re-run");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it("adds only the missing gate when one is already wired", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-broker-gate2-"));
try {
mkdirSync(join(dir, ".claude"), { recursive: true });
writeFileSync(
join(dir, ".claude", "settings.json"),
JSON.stringify({
hooks: {
PreToolUse: [
{ matcher: "Bash", hooks: [{ type: "command", command: "kit gate-egress" }] },
],
},
}),
);
const r = await installBrokerGates(dir);
assert.equal(r.action, "updated");
const s = JSON.parse(readFileSync(join(dir, ".claude", "settings.json"), "utf-8"));
assert.equal(s.hooks.PreToolUse.length, 2);
assert.ok(
s.hooks.PreToolUse.some((g: { hooks: { command: string }[] }) =>
g.hooks[0].command.endsWith("gate-fs"),
),
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it("skips when no Claude Code project is present", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-broker-gate3-"));
try {
assert.equal((await installBrokerGates(dir)).action, "skipped");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

describe("kitGateInvocation / kitGateArgv (prefer the self-healing wrapper)", () => {
// The gate hook should point at the stable ~/.kit/bin/kit wrapper rather than
// bake a volatile absolute node path into every agent's config: the wrapper
Expand Down
59 changes: 59 additions & 0 deletions src/agent-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,65 @@
}
}

/**
* Install the exec-broker PreToolUse gates (Pillar 3) into `.claude/settings.json`:
* `kit gate-egress` (matcher `Bash`) blocks network targets outside the signed [scope].egress,
* and `kit gate-fs` (matcher `Write|Edit|NotebookEdit`) blocks writes outside [scope].fs.
*
* Unlike the install/env gates this is OPT-IN (`kit agent-config --broker-gate`), NOT default:
* the broker is fail-closed, so a wired egress-gate with no verified scope denies ALL network
* — desirable only once the operator has declared + signed a `[scope]`/RoE. Wiring it is that
* deliberate opt-in. Claude Code only today (the settings schema we know); idempotent (keyed on
* each gate command); preserves other hooks.
*/
export async function installBrokerGates(cwd: string = process.cwd()): Promise<HookInstallResult> {
const file = ".claude/settings.json";
const path = resolve(cwd, file);

const { isReadOnlyMode } = await import("./read-only-mode.js");
if (isReadOnlyMode()) return { file, action: "skipped", detail: "read-only mode" };
if (!existsSync(resolve(cwd, ".claude")) && !existsSync(resolve(cwd, "CLAUDE.md"))) {
return { file, action: "skipped", detail: "no Claude Code project detected" };
}

let settings: { hooks?: Record<string, SettingsHookGroup[]>; [k: string]: unknown } = {};
let existed = false;
try {
settings = JSON.parse(await readFile(path, "utf-8")) as typeof settings;
existed = true;
} catch {
settings = {};
}

const hooks = (settings.hooks ??= {});
const pre = (hooks.PreToolUse ??= []);
const wired = (sub: string) => pre.some((g) => g.hooks?.some((h) => h.command?.endsWith(sub)));
const hasEgress = wired("gate-egress");
const hasFs = wired("gate-fs");
if (hasEgress && hasFs) {
return { file, action: "unchanged", detail: "broker gates already wired" };
}
if (!hasEgress) {
pre.push({
matcher: "Bash",
hooks: [{ type: "command", command: kitSubcommandInvocation("gate-egress") }],
});
}
if (!hasFs) {
pre.push({
matcher: "Write|Edit|NotebookEdit",
hooks: [{ type: "command", command: kitSubcommandInvocation("gate-fs") }],
});
}
try {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, JSON.stringify(settings, null, 2) + "\n", "utf-8");
return { file, action: existed ? "updated" : "created" };
} catch (err) {
return { file, action: "failed", detail: err instanceof Error ? err.message : String(err) };
}
}

/**
* Codex install-gate: a `[[hooks.PreToolUse]]` block in `.codex/config.toml`
* (matcher `^Bash$`) that runs `kit gate-bash` and exits 2 to block. We APPEND
Expand Down Expand Up @@ -909,7 +968,7 @@
cwd: string = process.cwd(),
): Promise<HookInstallResult> {
const file = ".opencode/plugin/kit-install-gate.js";
const path = resolve(cwd, file);

Check warning on line 971 in src/agent-config.ts

View workflow job for this annotation

GitHub Actions / build-and-test

File has too many lines (930). Maximum allowed is 700
const { isReadOnlyMode } = await import("./read-only-mode.js");
if (isReadOnlyMode()) return { file, action: "skipped", detail: "read-only mode" };
const detected =
Expand Down
19 changes: 19 additions & 0 deletions src/commands/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
detectAgentTargets,
installKitPermissions,
installAllInstallGates,
installBrokerGates,
installAiderRules,
} from "../agent-config.js";

Expand Down Expand Up @@ -170,6 +171,24 @@ export async function cmdAgentConfig(): Promise<boolean> {
}
}
}
// Opt-in: the exec-broker gates (Pillar 3). NOT default — a wired egress-gate is fail-closed
// (no verified [scope] ⇒ deny all network), so it's only wanted once the operator has declared
// + signed a scope/RoE. `--broker-gate` is that deliberate opt-in.
if (hasFlag(process.argv, "--broker-gate")) {
console.log(
`\n ${c.bold}exec-broker gates${c.reset} ${c.dim}(block network/writes outside the signed [scope]/RoE; fail-closed — declare + sign a scope first with ${c.reset}${c.bold}kit profile sign${c.reset}${c.dim}):${c.reset}`,
);
const r = await installBrokerGates();
if (r.action === "created" || r.action === "updated") {
console.log(
` ${c.green}✓${c.reset} Claude Code ${c.dim}→ ${r.file} (gate-egress + gate-fs)${c.reset}`,
);
} else if (r.action === "unchanged") {
console.log(` ${c.dim}= Claude Code already wired (${r.file})${c.reset}`);
} else {
console.log(` ${c.dim}· Claude Code skipped: ${r.detail ?? r.action}${c.reset}`);
}
}
console.log(
`\n${c.dim}Blocks regenerate in place on re-run; edit outside the markers freely. ` +
`Mutating kit commands (secrets/fix/hooks) still prompt by design.${c.reset}`,
Expand Down
Loading