/** * Generates the JavaScript plugin file dropped into * `~/.config/opencode/plugins/node9.js` by setupOpencode. * * Why this lives in its own file: * - Keeps setup.ts from carrying ~80 lines of embedded JS source text. * - Makes the shim contract testable in isolation. * * The generated shim wires three Opencode plugin hooks (contract verified * in /home/nadav/node9/opensources/opencode-dev/packages/plugin/src/index.ts): * * • tool.execute.before — pre-execution block (throws on deny verdict) * • tool.execute.after — fire-and-forget audit log * • chat.message — prompt DLP (paste-into-prompt secret scan) * * The shim spawnSyncs the node9 CLI via an embedded NODE9_ARGV array. * setupOpencode resolves that argv at install time so a stripped $PATH at * Opencode launch doesn't break interception. */ export interface OpencodeShimInput { /** * The argv prefix used to invoke node9. Two production shapes: * * • Global npm install — `["/usr/local/bin/node9"]` (the bin script * created by npm, has a shebang and the executable bit set). * * • Dev / npm-link — `["/path/to/node", "/path/to/dist/cli.js"]` * (node executes the cli.js directly). * * Resolved by setupOpencode via process.argv[1] / process.execPath at * `node9 init` time. The shim then invokes * `spawnSync(argv[0], [...argv.slice(1), "check"], ...)` which works * cross-platform without going through a shell. */ node9Argv: string[]; /** * Current node9 version. Embedded as a constant so subsequent inits * can detect mismatched shims and self-heal. */ version: string; } export function renderOpencodeShim(input: OpencodeShimInput): string { const { node9Argv, version } = input; // Plain JavaScript — Opencode's plugin loader uses Bun's native // import(), which handles CommonJS module.exports transparently. We // intentionally avoid `import` statements because user-dropped plugin // files have no node_modules resolution context. return `// Auto-generated by \`node9 init\`. Do not edit — re-run init to upgrade. // NODE9_SHIM_VERSION = "${version}" // // node9 protection shim for Opencode. Wires three hooks against the // agent's plugin API and shells out to the node9 CLI for verdicts. // // Block by throwing from a hook handler; Opencode's plugin trigger // (packages/opencode/src/plugin/index.ts:273) propagates the error and // halts the tool call. const { spawnSync } = require("node:child_process"); // argv prefix for invoking the node9 CLI. argv[0] is the executable // (either the npm-installed wrapper script or the node binary); the // remaining entries (if any) are passed as the leading args before // the subcommand name (e.g. ["/path/to/dist/cli.js"] for dev mode). const NODE9_ARGV = ${JSON.stringify(node9Argv)}; const HOOK_TIMEOUT_MS = 30000; const LOG_TIMEOUT_MS = 5000; function parseReason(stdout) { // node9 check emits {decision, reason, message} JSON on stdout when // blocking. Fall back to a generic string if anything goes wrong. try { const v = JSON.parse(stdout || ""); return v && (v.reason || v.message); } catch (e) { return null; } } function extractPromptText(parts) { // chat.message gives us parts: Part[]. We only DLP-scan text parts // (image / tool_use parts can't contain pasted secrets in any form // node9's scanner currently recognizes). if (!Array.isArray(parts)) return ""; return parts .filter((p) => p && p.type === "text") .map((p) => (p && p.text) || "") .join("\\n"); } module.exports = { id: "node9", server: async (input) => ({ "tool.execute.before": async (ctx, mutable) => { const payload = { hook_event_name: "PreToolUse", tool_name: ctx.tool, tool_input: mutable.args, session_id: ctx.sessionID, cwd: input.directory, meta: { agent: "Opencode" }, }; const r = spawnSync(NODE9_ARGV[0], [...NODE9_ARGV.slice(1), "check"], { input: JSON.stringify(payload), encoding: "utf-8", timeout: HOOK_TIMEOUT_MS, }); if (r.status === 0) return; const reason = parseReason(r.stdout) || "blocked by node9"; throw new Error("[node9] " + reason); }, "tool.execute.after": async (ctx, out) => { // Audit + gap1 Mode A response-channel DLP: scan the tool OUTPUT and, on a // secret, redact it before the model consumes it. The host returns this // same \`out\` object after the hook (opencode session/tools.ts), so // mutating out.output replaces what the model sees. Must NEVER throw — the // tool already ran. const toolOutput = out && typeof out.output === "string" ? out.output : ""; const payload = { hook_event_name: "PostToolUse", tool_name: ctx.tool, session_id: ctx.sessionID, cwd: input.directory, tool_response: { output: toolOutput }, meta: { agent: "Opencode" }, }; try { const r = spawnSync(NODE9_ARGV[0], [...NODE9_ARGV.slice(1), "log", "--redact-output"], { input: JSON.stringify(payload), encoding: "utf-8", timeout: LOG_TIMEOUT_MS, }); if (r.status === 0 && r.stdout && out && typeof out.output === "string") { const resp = JSON.parse(r.stdout); // A secret was redacted OR the text was framed as injected: either way the // model must get the redacted text, not the original (a frame alone has found=[]). if (resp && typeof resp.redacted === "string" && ((Array.isArray(resp.found) && resp.found.length > 0) || resp.injection)) { out.output = resp.redacted; } } } catch (e) { // Swallow: a redaction/audit failure must not crash the agent. } }, "chat.message": async (ctx, mutable) => { const prompt = extractPromptText(mutable.parts); if (!prompt) return; const payload = { hook_event_name: "UserPromptSubmit", prompt, session_id: ctx.sessionID, meta: { agent: "Opencode" }, }; const r = spawnSync(NODE9_ARGV[0], [...NODE9_ARGV.slice(1), "check"], { input: JSON.stringify(payload), encoding: "utf-8", timeout: HOOK_TIMEOUT_MS, }); if (r.status === 0) return; const reason = parseReason(r.stdout) || "prompt blocked"; throw new Error("[node9] " + reason); }, }), }; `; }