// src/cli/commands/check.ts // PreToolUse hook handler — evaluates a tool call before execution. // Registered as `node9 check` by cli.ts. import type { Command } from 'commander'; import chalk from 'chalk'; import fs from 'fs'; import { spawn } from 'child_process'; import path from 'path'; import os from 'os'; import { authorizeHeadless } from '../../auth/orchestrator'; import { checkPause } from '../../auth/state'; import { isDaemonRunning, notifyUserMentions } from '../../auth/daemon'; import { extractContentDestinations, levelOf, catalogSettingsFromConfig, checkValue, } from '@node9/policy-engine'; import { budgetNoticeLine, claimBudgetNotice, judgeSpendBudget } from '../../auth/spend-budget'; import { openStartupLogFd, recordStartupState } from '../../daemon/startup-log'; import { getConfig, type Config } from '../../config'; import { buildNegotiationMessage, buildReviewMessage, userLineOf, isHumanDecision, } from '../../policy/negotiation'; import { autoStartDaemonAndWait, isTestingMode, logAutostartSkipThrottled, } from '../daemon-starter'; import { defaultSkillRoots, resolveUserSkillRoot, verifyAndPinRoots } from '../../skill-pin'; import { scanArgs, matchCanaryArgs } from '../../dlp'; import { canaryValues, loadCanaries } from '../../canary/registry'; import { appendLocalAudit, isTestCall, lastDenyAudit } from '../../audit'; import { isKeyedForPolicy } from '../../config/keyed-guard'; import { reviewCorrelationKey, recordPendingReview, discardPendingReview, } from '../../review-pending'; import { blockedCallKey, noteBlockedCall } from '../../blocked-calls'; import { extractToolName, extractToolInput, canonicalToolName, canonicalToolInput, agentLabelFromFlag, } from '../../utils/hook-payload'; import { stripControlChars } from '../../utils/safe-text'; import { atomicWriteSync } from '../../utils/atomic-write'; import { ensureOwnDir, isSameOwnDir, removeOldFlag, SESSION_FLAG_SUFFIX, } from '../../utils/own-dir'; import { claimSessionNotice, closeSessionNotice, sessionNoticeEnabled, sessionNoticeClosedOutput, sessionNoticeOutput, budgetNoticeOutput, NO_DAEMON_SUFFIX, } from '../../notices/session-notice'; /** * Identify the AI agent running this tool call. Source of truth for the * SaaS Report's "AI Agents" breakdown — the value flows: detected here → * passed in `meta.agent` → backend stores as the row's hostname column. * * Detection layers, ordered by signal strength: * * 1. Hook payload fingerprint — most reliable. Claude Code's hook * sends `PreToolUse` event names + `tool_use_id`; Gemini CLI sends * `BeforeTool` + `timestamp`. These are deterministic. * * 2. Environment variables — a process running under an AI host often * sets identifying env vars even when the call doesn't come through * the hook (e.g. user runs `node9 check` directly inside a Claude * Code subshell). These are softer but useful when the payload is * absent. * * 3. Final fallback — "Terminal" for bare-shell calls, "Unknown Agent" * when there's a tool-name signal but no AI hint at all. * * Exported for unit testing — pure function over (payload, process.env). */ export function detectAiAgent(payload: Record): string { // Layer 0: explicit meta.agent tag set by a node9-authored plugin // shim (Opencode, Pi, and any future agent we wire up by dropping a // plugin file). The shim controls both ends — it shapes the payload // and sets meta.agent — so we trust the tag absolutely when present // and well-formed. Must precede Layer 1 because these shims still // include hook_event_name: "PreToolUse" in the payload to match the // shape `node9 check` already understands. const meta = payload.meta; if (meta && typeof meta === 'object') { const tagged = (meta as { agent?: unknown }).agent; if (typeof tagged === 'string' && tagged.length > 0) return tagged; } // Layer 1: payload fingerprint (existing, most reliable). // Codex's payload is Claude-compatible (same hook_event_name, tool_use_id, // permission_mode) PLUS a Codex-specific `turn_id` field per // openai/codex pre-tool-use.command.input.schema.json ("Codex extension: // expose the active turn id"). Must run before the Claude branch or every // Codex tool call gets misattributed. if (payload.turn_id !== undefined) { return 'Codex'; } // Antigravity (agy) — third dialect, verified against agy 1.0.6 // spy-hook captures: tool name/args nest under `toolCall`, the // conversation id is `conversationId`, and there is NO // hook_event_name field at all — so no overlap with the Claude // branch below. `toolCall !== undefined` also matches the // `toolCall: null` non-tool PostToolUse payloads. if (payload.toolCall !== undefined || payload.conversationId !== undefined) { return 'Antigravity'; } if ( payload.hook_event_name === 'PreToolUse' || payload.hook_event_name === 'PostToolUse' || payload.tool_use_id !== undefined || payload.permission_mode !== undefined ) { return 'Claude Code'; } if ( payload.hook_event_name === 'BeforeTool' || payload.hook_event_name === 'AfterTool' || payload.timestamp !== undefined ) { return 'Gemini CLI'; } // Hermes Agent uses lowercase snake_case hook event names per // agent/shell_hooks.py:_serialize_payload — distinct from Claude's // PascalCase and Gemini's BeforeTool/AfterTool so no overlap. if (payload.hook_event_name === 'pre_tool_call' || payload.hook_event_name === 'post_tool_call') { return 'Hermes'; } // Layer 2: env-var fallback. Order matters — most specific first. // CLAUDECODE is set by the Claude Code CLI on session start. Gemini's // CLI sets GEMINI_API_KEY (often present) or GEMINI_CLI_VERSION (newer // versions). Cursor sets CURSOR_TRACE_ID for tool-call attribution. // Aider sets AIDER_VERSION when running under aider. Hermes sets // HERMES_SESSION_ID on every session before tool dispatch // (run_agent.py:1913). if (process.env.CLAUDECODE === '1' || process.env.CLAUDE_CODE_SESSION_ID) { return 'Claude Code'; } if (process.env.HERMES_SESSION_ID || process.env.HERMES_HOME || process.env.HERMES_INTERACTIVE) { return 'Hermes'; } // agy sets ANTIGRAVITY_CONVERSATION_ID in every hook's environment // (verified, agy 1.0.6). Must precede the Gemini check — a machine // with a leftover GEMINI_API_KEY in the shell profile would otherwise // misattribute agy calls to the (EOL'd) Gemini CLI. if (process.env.ANTIGRAVITY_CONVERSATION_ID) { return 'Antigravity'; } if (process.env.GEMINI_CLI_VERSION || process.env.GEMINI_API_KEY) { return 'Gemini CLI'; } if (process.env.CURSOR_TRACE_ID || process.env.CURSOR_SESSION_ID) { return 'Cursor'; } if (process.env.AIDER_VERSION) { return 'Aider'; } // Layer 3: payload has a tool name but no AI fingerprint — call came // from somewhere we don't recognise yet. if (payload.tool_name !== undefined || payload.name !== undefined) { return 'Unknown Agent'; } return 'Terminal'; } // Agents whose PreToolUse hook contract can render an inline approve/deny prompt // from a `permissionDecision:"ask"` verdict. EMPIRICALLY VERIFIED (2026-06-23): // Claude Code (nested envelope) and GitHub Copilot (flat envelope). Codex errors // on "ask", Antigravity/Gemini/Hermes fail open or have no ask verdict — they must // NEVER receive an ask (it would silently bypass the review); they fall back to the // routed approver. See doc/roadmap/active/review-ask-inline-v1-spec.md §8. function agentSupportsAsk(agent: string): boolean { return agent === 'Claude Code' || agent === 'GitHub Copilot'; } // node9Firewall#473: Codex reads a hook's exit 2 as a block only when stderr // carries the reason; it ignores stdout on exit 2, and with an empty stderr it // marks the hook failed and runs the tool. Verified in openai/codex // rust-v0.154.0 (hooks/src/events/pre_tool_use.rs and user_prompt_submit.rs, // parse_completed); the same rule since at least rust-v0.120.0. The reason is // written synchronously so process.exit cannot cut it off (pipes are // asynchronous on macOS), in a loop because a pipe write can be partial. function exitCodexBlock(reason: string): never { try { const buf = Buffer.from(reason + '\n', 'utf-8'); let off = 0; while (off < buf.length) { const n = fs.writeSync(2, buf, off, buf.length - off); if (n <= 0) break; off += n; } } catch { // Exit 2 regardless: an unread reason makes Codex mark the hook failed, but // node9 must never turn its own block into an allow. } process.exit(2); } // Whether a `review` verdict for this call is deferred to the agent's inline // prompt (true) vs. node9's own approver (false). Precedence (v2 — the cloud // carve-out is deleted, see review-ask-inline-v2-spec.md: cloud is the record, // not a gate; admins force routed approval via managed reviewChannel): // 1. agent not ask-capable → approver (false) // 2. ADMIN-SET (managed) reviewChannel → wins — the org's routing lever (and // the documented v2 rollback) must not be defeatable by a --ask flag in a // per-machine hook registration (/code-review fix) // 3. --ask / --no-ask flag → wins (local/debug override) // 4. local settings.reviewChannel → 'ask' | 'approver' // 5. default → ASK function resolveAskMode(agent: string, opts: { ask?: boolean }, config: Config): boolean { if (!agentSupportsAsk(agent)) return false; if (config.settings.reviewChannelManaged === true) { if (config.settings.reviewChannel === 'ask') return true; if (config.settings.reviewChannel === 'approver') return false; } if (opts.ask === true) return true; if (opts.ask === false) return false; if (config.settings.reviewChannel === 'ask') return true; if (config.settings.reviewChannel === 'approver') return false; return true; } export function registerCheckCommand(program: Command): void { program .command('check', { hidden: true }) .description('Hook handler — evaluates a tool call before execution') .argument('[data]', 'JSON string of the tool call') .option( '--agent ', 'Agent identity override, set by node9-authored hook registrations (e.g. antigravity)' ) .option( '--ask', 'Route review verdicts to the agent’s native inline approve/deny prompt (Claude Code / GitHub Copilot only)' ) .option('--no-ask', 'Force node9’s own approver for review verdicts (override default-on)') .action(async (data, opts: { agent?: string; ask?: boolean }) => { const agentOverride = agentLabelFromFlag(opts?.agent); const processPayload = async (raw: string) => { try { if (!raw || raw.trim() === '') process.exit(0); let payload = JSON.parse(raw) as { tool_name?: string; tool_input?: unknown; name?: string; args?: unknown; cwd?: string; session_id?: string; // Path to the agent's session JSONL/transcript file. Both Claude // Code and Gemini CLI populate this in the hook payload. Forwarded // to the SaaS so the dashboard can correlate audit rows to the // session content — essential for Gemini, where session_id can // drift across resumes but transcript_path is stable. transcript_path?: string; hook_event_name?: string; // Claude: "PreToolUse" | Gemini: "BeforeTool" tool_use_id?: string; // Claude-only permission_mode?: string; // Claude-only timestamp?: string; // Gemini-only turn_id?: string; // Codex-only (#178 fingerprint) prompt?: string; // UserPromptSubmit payload body // Antigravity (agy) dialect — verified against agy 1.0.6: toolCall?: { name?: string; args?: unknown } | null; conversationId?: string; // agy's session_id equivalent transcriptPath?: string; // agy's transcript_path equivalent workspacePaths?: string[]; // agy has no top-level cwd; [0] is the workspace root }; try { payload = JSON.parse(raw); } catch (err) { // If JSON is broken (e.g. half-sent due to timeout), log it and fail open. // We load config temporarily just to check if debug logging is on. const tempConfig = getConfig(); if (process.env.NODE9_DEBUG === '1' || tempConfig.settings.enableHookLogDebug) { const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); const errMsg = err instanceof Error ? err.message : String(err); fs.appendFileSync( logPath, `[${new Date().toISOString()}] JSON_PARSE_ERROR: ${errMsg}\nRAW: ${raw}\n` ); } process.exit(0); } // A Codex session starts: tell the user, once per session, that node9 // is on and at which level, before the first prompt (Claude Code gets // the same line on its first allowed call). The payload has no // turn_id, so the hook is registered with --agent codex. UX only: // always exit 0, nothing on stderr, never `continue` (Codex would // stop the session). if (payload.hook_event_name === 'SessionStart') { try { const start = payload as Record; const isSubagent = typeof start.agent_id === 'string' && start.agent_id !== ''; if ( (agentOverride ?? detectAiAgent(payload)) === 'Codex' && start.source !== 'compact' && !isSubagent && sessionNoticeEnabled() && process.env.NODE9_PAUSED !== '1' && !checkPause().paused ) { const startCwd = typeof payload.cwd === 'string' && path.isAbsolute(payload.cwd) ? payload.cwd : undefined; const config = getConfig(startCwd); const daemonStaysDown = !isDaemonRunning() && config.settings.autoStartDaemon === false; const kind = claimSessionNotice( typeof payload.session_id === 'string' ? payload.session_id : undefined, os.homedir(), levelOf(config.settings.mode) + (daemonStaysDown ? NO_DAEMON_SUFFIX : ''), true ); if (kind) { fs.writeSync( 1, sessionNoticeOutput( config.settings.mode, kind, daemonStaysDown, null, 'SessionStart' ) + '\n' ); } } } catch { /* UX only */ } process.exit(0); } // UserPromptSubmit — paste-into-prompt DLP. The payload has `prompt` // but no tool_name / tool_input, so the tool-call codepath below // would reach the "tool name missing" sendBlock. Handle it here: // scan the prompt for credentials and block before the prompt ever // reaches the model. No tool-call config/orchestrator path needed — // DLP is enabled by default for these patterns. if (payload.hook_event_name === 'UserPromptSubmit') { const prompt = typeof payload.prompt === 'string' ? payload.prompt : ''; // Debug logging — sanitize the prompt before persisting so a // pasted secret never lands on disk via hook-debug.log. We early- // exit before the generic debug log at line ~212, so this is the // only place that records UserPromptSubmit telemetry. if (process.env.NODE9_DEBUG === '1') { try { const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); if (!fs.existsSync(path.dirname(logPath))) fs.mkdirSync(path.dirname(logPath), { recursive: true }); const sanitized = JSON.stringify({ ...payload, prompt: ``, }); fs.appendFileSync(logPath, `[${new Date().toISOString()}] STDIN: ${sanitized}\n`); } catch { // Non-fatal — debug logging is best-effort. } } // node9Firewall#442: a session notice asked the agent to open its // reply with node9's line; the user's next prompt tells it the line // was shown, before the next reply is written. On every exit that // lets the prompt through (a paused node9 included: the ask is // already in the conversation), never on a blocked prompt, which // the agent does not see. const allowPrompt = (): never => { if ( sessionNoticeEnabled() && closeSessionNotice( typeof payload.session_id === 'string' ? payload.session_id : undefined, os.homedir() ) ) { try { fs.writeSync(1, sessionNoticeClosedOutput() + '\n'); } catch { /* UX only */ } } process.exit(0); }; if (!prompt) allowPrompt(); // `node9 pause` must silence this gate too — the tool-call path // honors it in authorizeHeadless (orchestrator.ts:273); without // this, prompts stayed BLOCKED while everything else was paused // (dogfound 2026-07-05). Same guard pair as the orchestrator. if (process.env.NODE9_PAUSED === '1' || checkPause().paused) allowPrompt(); const dlpMatch = scanArgs({ prompt }); // Decoy credentials: a planted value pasted into a prompt is the same // value on the same path as one in a reply (canary-design.md H10). // Registry read failure means "no canaries"; never crash the gate. let canaryVals: ReturnType = []; try { canaryVals = canaryValues(); } catch { canaryVals = []; } const canaryHit = canaryVals.length > 0 ? matchCanaryArgs({ prompt }, canaryVals) : null; if (!dlpMatch && !canaryHit) { // fw#318 (design 5.3): an address, host or IBAN the user typed is // known for this session, so a later send to it is not held. // Best-effort and awaited: the process exits right after. try { const sid = typeof payload.session_id === 'string' ? payload.session_id : typeof payload.conversationId === 'string' ? payload.conversationId : ''; const promptCwd = typeof payload.cwd === 'string' && path.isAbsolute(payload.cwd) ? payload.cwd : undefined; if (sid && getConfig(promptCwd).policy.untrustedContent?.enabled) { await notifyUserMentions(sid, extractContentDestinations(prompt)); } } catch { /* never block the prompt on this */ } allowPrompt(); } let canaryRec: ReturnType[number] | null = null; if (canaryHit) { try { canaryRec = loadCanaries().find((r) => r.id === canaryHit.id) ?? null; } catch { canaryRec = null; } } const shownPattern = canaryHit ? 'Decoy credential (planted by node9)' : dlpMatch!.patternName; const shownSample = canaryHit ? (canaryRec?.path ?? 'decoy file') : dlpMatch!.redactedSample; // Audit FIRST — the block record must survive any downstream error. // Force argsHash so the secret value never lands in the audit log. // Honour the --agent flag (agentOverride) before fingerprinting — // mirrors the tool-call sendBlock path. Without this, a blocked // Copilot prompt is mis-attributed to "Claude Code" (its payload // is byte-identical to Claude), under-counting prompt-DLP blocks // in the SaaS breakdown. Affects any flag-registered agent whose // payload collides with another's. const agent = agentOverride ?? detectAiAgent(payload); const sessionId = typeof payload.session_id === 'string' ? payload.session_id : undefined; appendLocalAudit( 'UserPromptSubmit', { prompt }, 'deny', canaryHit ? 'dlp-canary-block' : 'dlp-block', { agent, sessionId, ...(canaryHit ? { canaryId: canaryHit.id, canaryHash: canaryRec?.valueHash, canaryKind: canaryRec?.kind, canaryPath: canaryRec?.path, canaryView: canaryHit.view, canaryRetired: canaryHit.retired, } : {}), }, true ); const reason = `🚨 Node9 DLP: ${shownPattern} detected in prompt ` + `(${shownSample}). Prompt was not submitted — ` + `remove the credential and try again.`; // /dev/tty banner for the human, mirroring sendBlock's UX. Never // stderr (Codex parses stderr for the block reason and would echo // the entire banner back as the LLM-visible message). try { const ttyFd = fs.openSync('/dev/tty', 'w'); fs.writeSync( ttyFd, chalk.bgRed.white.bold(`\n 🚨 NODE9 DLP — PROMPT BLOCKED \n`) + chalk.red(` ${shownPattern} detected in your prompt.\n`) + chalk.gray(` Match: ${shownSample}\n`) + chalk.cyan(` Edit the prompt to remove the credential and resubmit.\n\n`) ); fs.closeSync(ttyFd); } catch { // /dev/tty unavailable (CI, non-interactive) — skip visual output. } // Codex ignores stdout on exit 2 and reads the reason from stderr // only; the prompt is not submitted (#473). if (agent === 'Codex') exitCodexBlock(reason); process.stdout.write( JSON.stringify({ decision: 'block', reason, systemMessage: reason, hookSpecificOutput: { hookEventName: 'UserPromptSubmit', permissionDecision: 'deny', permissionDecisionReason: reason, }, }) + '\n' ); // Exit 2 signals a block to Claude Code. process.exit(2); } // Antigravity payloads carry no top-level cwd; the workspace root // in workspacePaths[0] is the correct base for per-project config // resolution (verified payload shape, agy 1.0.6). const payloadCwd = typeof payload.cwd === 'string' ? payload.cwd : Array.isArray(payload.workspacePaths) && typeof payload.workspacePaths[0] === 'string' ? payload.workspacePaths[0] : undefined; // Pass payload.cwd directly to getConfig() instead of mutating process.chdir — // process.chdir is process-global and would race with concurrent hook invocations. // CLAUDE.md: validate with path.isAbsolute() before passing to getConfig() to // prevent a hook payload from steering config resolution at a traversal path. // Matches the pattern already used at the other payload.cwd sites in this file. const safeCwdForConfig = typeof payloadCwd === 'string' && path.isAbsolute(payloadCwd) ? payloadCwd : undefined; const config = getConfig(safeCwdForConfig); // Eagerly start the daemon for activity logging (fire-and-forget). // Without this, tool events never reach `node9 tail` if the daemon // wasn't already running when the Claude Code session started. // Probe once — isDaemonRunning() reads the pid file + process.kill and // self-cleans a stale pid, so avoid calling it twice per tool call. const daemonDown = !isDaemonRunning(); if (config.settings.autoStartDaemon && daemonDown && !process.env.NODE9_NO_AUTO_DAEMON) { try { const scriptPath = process.argv[1]; if (typeof scriptPath !== 'string' || !path.isAbsolute(scriptPath)) throw new Error('node9: argv[1] is not an absolute path'); // Security: verify argv[1] lives inside this package's own dist/ // directory — prevents spawn from executing an attacker-controlled // script if the process is invoked via a malicious wrapper. // We check directory prefix (not exact path equality) so the check // survives different install roots: nvm, global npm, local installs, // and symlinked bin entries all resolve to the same dist/ tree. const resolvedScript = fs.realpathSync(scriptPath); const packageDist = fs.realpathSync(path.resolve(__dirname, '../..')); if ( !resolvedScript.startsWith(packageDist + path.sep) && resolvedScript !== packageDist ) throw new Error( `node9: daemon spawn aborted — argv[1] (${resolvedScript}) is outside package dist (${packageDist})` ); // Strip env vars that can inject code into the spawned Node.js process. const safeEnv = { ...process.env }; for (const key of [ 'NODE_OPTIONS', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'DYLD_INSERT_LIBRARIES', 'NODE_PATH', 'ELECTRON_RUN_AS_NODE', ]) { delete safeEnv[key]; } // A4b (policy-sync-commit2-liveness): capture the child's STDERR to // daemon-startup.log instead of 'ignore'. A daemon that dies during // startup — e.g. an ERR_REQUIRE_ESM at module-load, before any in-daemon // try/catch — prints its stack to stderr before exiting; routing that fd // here is the only way it leaves a trace. openStartupLogFd caps the file // so a crash loop can't grow it without bound. SAFE to close in the parent // right after spawn(): spawn() does fork/exec + fd-dup synchronously, so the // child already holds its own copy. Close in finally so a spawn() throw // (→ outer catch) can't leak the fd. const startupFd = openStartupLogFd(); // Mark the attempt BEFORE spawning. If the child dies at module load // (the ERR_REQUIRE_ESM class), it never runs a line of our code and // cannot report anything itself — this marker plus "daemon still // down" is the only evidence that a start was even attempted. recordStartupState('starting'); try { const d = spawn(process.execPath, [scriptPath, 'daemon'], { detached: true, stdio: ['ignore', 'ignore', startupFd ?? 'ignore'], env: { ...safeEnv, NODE9_AUTO_STARTED: '1' }, }); // MANDATORY, and not merely for diagnostics: spawn() reports exec // failures (EMFILE/EAGAIN under load) on this event, and an 'error' // event with NO listener is an uncaught exception. That would print a // stack to stderr — and this file's own comments (:515, :634) record // that Claude Code treats ANY stderr from the hook as a hook error and // FAILS OPEN, letting the tool call through unenforced. Without this // listener a transient resource failure becomes an enforcement bypass. d.on('error', (err: Error) => { // Best-effort: the hook may exit before this runs, which is why the // 'starting' marker remains the real backstop on this path. recordStartupState('failed', 'spawn-failed', err.message); }); d.unref(); } finally { if (startupFd !== undefined) { try { fs.closeSync(startupFd); } catch { /* non-fatal */ } } } } catch (spawnErr) { // Log spawn failures so they're visible in hook-debug.log instead // of silently swallowed — makes install-path mismatches diagnosable. const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); const msg = spawnErr instanceof Error ? spawnErr.message : String(spawnErr); // The validation throws above (argv[1] not absolute, or resolving // outside the package dist — a real install-path mismatch) happen // BEFORE the 'starting' marker is written, so without this an aborted // start leaves no state at all and doctor says nothing. Record it as // the conclusive failure it is; 'starting' would be a lie, since no // spawn was ever attempted. recordStartupState('failed', 'spawn-aborted', msg); // NOTE: deliberately no recordStartupState() for the SPAWN itself here. // spawn() reports exec // failures on the child's 'error' event, not by throwing, so this catch // only sees synchronous TypeErrors — a recording here looked like a // safety net while being unreachable for every failure it named. An // 'error' listener is no better on this path: the target is // process.execPath (so ENOENT is near-impossible) and the hook exits // abruptly at several points, so the listener may never run. The // 'starting' marker is the backstop — nothing resolves it, and doctor // reports the start did not come up once the grace window passes. try { fs.appendFileSync( logPath, `[${new Date().toISOString()}] daemon-autostart-failed: ${msg}\n` ); } catch { /* non-fatal */ } } } else if (daemonDown && !isTestingMode()) { // A4a: daemon is down but we will NOT auto-start it — record WHY // (throttled), so "why didn't the daemon come up?" is answerable. logAutostartSkipThrottled( !config.settings.autoStartDaemon ? 'autoStartDaemon=false' : process.env.NODE9_NO_AUTO_DAEMON ? 'NODE9_NO_AUTO_DAEMON' : 'unknown' ); } // Debug logging — controlled by Env Var OR new Settings config if (process.env.NODE9_DEBUG === '1' || config.settings.enableHookLogDebug) { const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); if (!fs.existsSync(path.dirname(logPath))) fs.mkdirSync(path.dirname(logPath), { recursive: true }); // JSON-encode: `raw` is agent-supplied and a literal newline in it // would forge a second journal line. Matches the sibling at :277. fs.appendFileSync( logPath, `[${new Date().toISOString()}] STDIN: ${JSON.stringify(raw)}\n` ); } const rawToolName = stripControlChars(extractToolName(payload)); const toolName = canonicalToolName(rawToolName); // Normalise agent-native arg shapes (agy run_command: // CommandLine/Cwd → command/cwd) before shields, DLP and // snapshot inspect them. const toolInput = canonicalToolInput(rawToolName, extractToolInput(payload)); const agent = agentOverride ?? detectAiAgent(payload); const mcpMatch = toolName.match(/^mcp__([^_](?:[^_]|_(?!_))*?)__/i); const mcpServer = mcpMatch?.[1]; // ── THE NEGOTIATION LOOP (TALKING BACK TO THE AI) ─────────────── const sendBlock = ( msg: string, result?: { blockedBy?: string; changeHint?: string; blockedByLabel?: string; recoveryCommand?: string; ruleDescription?: string; blockKind?: 'protected-path'; blockedPath?: string; /** Who decided (DecisionRecord): only 'person' is a human decision. */ decidedBy?: string; /** A person's instruction to the agent instead of the call. */ redirect?: string; /** The gate's own naming of the block, when it wrote no stop row. */ checkId?: string; ruleHit?: string; } ) => { // Proof that the block held (blocked-calls.ts): note this call, so // its after-run hook, should one ever fire, records that the agent // ran it anyway. Before any output; never able to change the block. // The marker holds the block's check and rule, never an argument. try { const blockedKey = blockedCallKey(payload as Record, agent); if (blockedKey) { const stop = lastDenyAudit(); const sid = (payload as Record).session_id; const checkId = stop?.checkId ?? result?.checkId; const ruleName = stop?.ruleName ?? result?.ruleHit; noteBlockedCall({ key: blockedKey, tool: toolName || 'unknown', agent, ...(typeof sid === 'string' && sid && { sessionId: sid }), ...(checkId && { checkId }), ...(ruleName && { ruleName }), ...(isTestCall(toolName, toolInput) && { testRun: true }), ts: Date.now(), }); } } catch { /* the proof is best-effort; the block is not */ } // 1. Determine the context (User vs Policy). I6: the fallback // names where the verdict came from — on a workspace-governed // machine that is the workspace policy, not a local one. const blockedByContext = result?.blockedByLabel || result?.blockedBy || (isKeyedForPolicy() ? 'Workspace Policy' : 'Local Security Policy'); // 2. Identify if it was a human decision or an automated rule const humanDecision = isHumanDecision( blockedByContext, result?.blockedBy, result?.decidedBy ); // 3. Print to the human terminal for visibility. // MUST NOT use stderr (console.error) — Claude Code treats any stderr // output as a hook error and fails open, allowing the tool to proceed // regardless of the JSON block payload. Write directly to /dev/tty so // the message appears on the developer's screen without touching the // Claude Code pipe. (Codex is the one agent that reads its block // reason from stderr; step 5 writes only that reason there.) let ttyFd: number | null = null; try { ttyFd = fs.openSync('/dev/tty', 'w'); const writeTty = (line: string) => fs.writeSync(ttyFd!, line + '\n'); if (result?.blockKind === 'protected-path') { // MSG-1: the credential banner below said "A sensitive secret was // found in the tool arguments!" for a protected file, on the // developer's own screen. writeTty( chalk.red.bold( `\n🛑 node9 protected ${result.blockedPath ?? 'a file'} from "${toolName}"` ) ); writeTty(chalk.white(` Protected files stay out of the agent's reach.`)); } else if ( blockedByContext.includes('DLP') || blockedByContext.includes('Secret Detected') || blockedByContext.includes('Credential Review') ) { writeTty(chalk.bgRed.white.bold(`\n 🚨 NODE9 DLP ALERT — CREDENTIAL DETECTED `)); writeTty(chalk.red.bold(` A sensitive secret was found in the tool arguments!`)); } else { writeTty(chalk.red(`\n🛑 Node9 blocked "${toolName}"`)); } if (result?.ruleDescription) writeTty(chalk.white(` ${result.ruleDescription}`)); writeTty(chalk.gray(` Triggered by: ${blockedByContext}`)); if (result?.changeHint) writeTty(chalk.cyan(` To change: ${result.changeHint}`)); if (result?.recoveryCommand) writeTty(chalk.green(` 💡 Run: ${result.recoveryCommand}`)); writeTty(''); } catch { // /dev/tty unavailable (CI, non-interactive) — skip visual output } finally { if (ttyFd !== null) try { fs.closeSync(ttyFd); } catch { /* ignore */ } } // 4. THE NEGOTIATION PROMPT: Context-specific instruction for the AI const aiFeedbackMessage = buildNegotiationMessage( blockedByContext, humanDecision, msg, result?.recoveryCommand, { kind: result?.blockKind, path: result?.blockedPath, redirect: !!result?.redirect, ruleDescription: result?.ruleDescription, } ); // 5. Send the structured JSON back to the LLM agent if (agent === 'Antigravity') { // Antigravity honours ONLY `decision: "deny"` — verified live // against agy 1.0.6: the Claude shape below (`decision: // "block"` + exit 2) is silently ignored and the tool RUNS // (fail-open). The reason string is surfaced to the model as // "Tool call denied with reason: …", so the negotiation // message still works. Exit code is ignored by agy; exit 0 // matches the verified capture exactly. process.stdout.write( JSON.stringify({ decision: 'deny', reason: aiFeedbackMessage }) + '\n' ); process.exit(0); } if (agent === 'GitHub Copilot') { // GitHub Copilot CLI's preToolUse decision is a flat // `permissionDecision`/`permissionDecisionReason` (NOT Claude's // nested hookSpecificOutput). Verified live against Copilot CLI // 1.0.60: this shape with exit 0 blocks and surfaces the reason // to the model as "Denied by preToolUse hook: …". The Claude // shape below also blocks here (preToolUse is fail-closed on // non-zero exit), but the reason then shows only as a bare // warning — the native shape gives the clean negotiation UX. process.stdout.write( JSON.stringify({ permissionDecision: 'deny', permissionDecisionReason: aiFeedbackMessage, }) + '\n' ); process.exit(0); } // Codex: the reason on stderr, exit 2, nothing on stdout (#473). if (agent === 'Codex') exitCodexBlock(aiFeedbackMessage); // fw#420: the CLI shows systemMessage to the user directly, so a // Claude Code user sees node9's own line even if the agent does not // quote it. Claude Code only: other agents' schemas are unverified, // and an unknown field must never put a block at risk. const userLine = userLineOf(aiFeedbackMessage); process.stdout.write( JSON.stringify({ decision: 'block', reason: aiFeedbackMessage, // This is the core instruction ...(agent === 'Claude Code' && userLine ? { systemMessage: userLine } : {}), hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: aiFeedbackMessage, }, }) + '\n' ); // Exit code 2 signals a block to Claude Code. Exit 0 = allow, non-zero = block. process.exit(2); }; // Inline-ask: route a `review` verdict to the agent's native approve/deny // prompt instead of node9's own approver. Only reached for ask-capable // agents (Claude Code / GitHub Copilot) — see resolveAskMode/agentSupportsAsk. const sendAsk = (result: { blockedByLabel?: string; ruleDescription?: string; reason?: string; exposureKeys?: string[]; exposureFromEid?: string; }) => { const msg = buildReviewMessage( result.blockedByLabel, result.ruleDescription, result.reason ); // Phase 4: record a pending-review marker so the matching PostToolUse can // capture the approve outcome. Best-effort — never block the ask emit. try { const key = reviewCorrelationKey(payload as Record); if (key) { const sid = typeof payload.session_id === 'string' ? payload.session_id : typeof payload.conversationId === 'string' ? payload.conversationId : undefined; recordPendingReview({ key, agent, tool: toolName, sessionId: sid, ts: Date.now(), label: result.blockedByLabel, ...(result.exposureKeys?.length ? { exposureKeys: result.exposureKeys } : {}), ...(result.exposureFromEid ? { exposureFromEid: result.exposureFromEid } : {}), }); } } catch { /* outcome capture is best-effort */ } // Human-terminal breadcrumb (parity with sendBlock). Never stderr — // Claude Code treats any stderr output as a hook error and fails open. try { const ttyFd = fs.openSync('/dev/tty', 'w'); fs.writeSync( ttyFd, chalk.yellow( `\n⚠️ Node9: review requested for "${toolName}" — answer in the prompt.\n` ) ); fs.closeSync(ttyFd); } catch { // /dev/tty unavailable (CI, non-interactive) — skip visual output. } if (agent === 'GitHub Copilot') { // Copilot honours a FLAT permissionDecision (verified live 2026-06-23). process.stdout.write( JSON.stringify({ permissionDecision: 'ask', permissionDecisionReason: msg }) + '\n' ); } else { // Claude Code: nested hookSpecificOutput (verified live, incl. bypass mode). process.stdout.write( JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: msg, }, }) + '\n' ); } // Exit 0 = hand the prompt to the agent (NOT a block). process.exit(0); }; if (!toolName) { sendBlock('Node9: unrecognised hook payload — tool name missing.'); return; } // Antigravity aliases: conversationId ≙ session_id, // transcriptPath ≙ transcript_path. const sessionId = typeof payload.session_id === 'string' ? payload.session_id : typeof payload.conversationId === 'string' ? payload.conversationId : undefined; const transcriptPath = typeof payload.transcript_path === 'string' ? payload.transcript_path : typeof payload.transcriptPath === 'string' ? payload.transcriptPath : undefined; const meta = { agent, mcpServer, sessionId, transcriptPath }; // ── Skill pinning — supply chain & update drift defense (AST 02 + AST 07) ── // Off by default; opt-in via config.policy.skillPinning.enabled. // mode 'warn': /dev/tty notification on drift, tool call allowed (exit 0). // mode 'block': hard quarantine on drift, tool call blocked (exit 2). // Per-session memoisation in ~/.node9/skill-sessions/ so hashing // runs at most once per Claude/Gemini session id. const skillPinCfg = config.policy.skillPinning; const rawSessionId = sessionId ?? ''; const safeSessionId = /^[A-Za-z0-9_\-]{1,128}$/.test(rawSessionId) ? rawSessionId : ''; if (skillPinCfg.enabled && safeSessionId) { try { const sessionsDir = path.join(os.homedir(), '.node9', 'skill-sessions'); const flagPath = path.join(sessionsDir, `${safeSessionId}${SESSION_FLAG_SUFFIX}`); // The memo is used only in a real directory of this user: a link // planted under ~/.node9 must not supply a "verified" flag, receive // writes or steer the clean-up. Without it the check runs every call. const memo = ensureOwnDir(sessionsDir); let flag: { state?: string; detail?: string } | null = null; try { // One name only: a hard link or a moved file is not node9's flag. const st = memo ? fs.lstatSync(flagPath) : null; if (st && st.isFile() && st.nlink === 1) flag = JSON.parse(fs.readFileSync(flagPath, 'utf-8')); } catch { /* missing/unreadable — treat as fresh */ } // Temp file + rename: a link planted at the flag path is replaced, // never written through. const writeFlag = (data: { state: string; detail?: string }) => { if (!memo || !isSameOwnDir(sessionsDir, memo)) return; try { atomicWriteSync( flagPath, JSON.stringify({ ...data, timestamp: new Date().toISOString() }, null, 2), { mode: 0o600 } ); } catch { /* best effort */ } }; // /dev/tty notification — non-blocking (warn mode only). const sendSkillWarn = (detail: string, recoveryCmd?: string) => { let ttyFd: number | null = null; try { ttyFd = fs.openSync('/dev/tty', 'w'); const w = (line: string) => fs.writeSync(ttyFd!, line + '\n'); w(chalk.yellow(`\n⚠️ Node9: installed skill drift detected`)); w(chalk.gray(` ${detail}`)); w( chalk.gray( ` If you updated a plugin, acknowledge the change to clear this warning.` ) ); if (recoveryCmd) w(chalk.green(` 💡 Run: ${recoveryCmd}`)); w(''); } catch { /* /dev/tty unavailable in CI — skip */ } finally { if (ttyFd !== null) try { fs.closeSync(ttyFd); } catch { /* ignore */ } } }; // Memoised states: 'verified' / 'warned' → skip. // 'quarantined' → only block in block mode; in warn mode, re-verify. if (flag && flag.state === 'quarantined' && skillPinCfg.mode === 'block') { sendBlock( `Node9: session quarantined — installed skill changed. Open a separate terminal and run: node9 skill pin list (to see what changed) then: node9 skill pin update (to acknowledge). If you updated a plugin intentionally, this is expected.`, { blockedByLabel: 'Skill Pin Quarantine', recoveryCommand: 'node9 skill pin list', } ); return; } if (!flag || (flag.state !== 'verified' && flag.state !== 'warned')) { const absoluteCwd = typeof payloadCwd === 'string' && path.isAbsolute(payloadCwd) ? payloadCwd : undefined; const extraRoots = skillPinCfg.roots; const resolvedExtra = extraRoots .map((r) => resolveUserSkillRoot(r, absoluteCwd)) .filter((r): r is string => typeof r === 'string'); const roots = [...defaultSkillRoots(absoluteCwd), ...resolvedExtra]; const result = verifyAndPinRoots(roots); if (result.kind === 'corrupt') { if (skillPinCfg.mode === 'block') { writeFlag({ state: 'quarantined', detail: `pin file corrupt: ${result.detail}`, }); sendBlock('Node9: skill pin file is corrupt — fail-closed.', { blockedByLabel: 'Skill Pin Quarantine', recoveryCommand: 'node9 skill pin reset', }); return; } // warn mode: notify, allow writeFlag({ state: 'warned', detail: `pin file corrupt: ${result.detail}` }); sendSkillWarn( `Skill pin file is corrupt: ${result.detail}`, 'node9 skill pin reset' ); } else if (result.kind === 'drift') { if (skillPinCfg.mode === 'block') { writeFlag({ state: 'quarantined', detail: result.summary }); sendBlock( `Node9: installed skill changed — ${result.summary}. If you updated a plugin, open a separate terminal and run: node9 skill pin update ${result.changedRootKey}`, { blockedByLabel: 'Skill Pin Quarantine', recoveryCommand: `node9 skill pin update ${result.changedRootKey}`, } ); return; } // warn mode: notify, allow writeFlag({ state: 'warned', detail: result.summary }); sendSkillWarn(result.summary, `node9 skill pin update ${result.changedRootKey}`); } else { writeFlag({ state: 'verified' }); } // Best-effort GC of session flags older than 7 days: only regular // files named .node9-flag, and only while the directory is // still the one checked above (a swap mid-call stops it). if (memo) try { const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000; for (const name of fs.readdirSync(sessionsDir)) removeOldFlag(sessionsDir, memo, name, cutoff); } catch { /* ignore */ } } } catch (err) { if (process.env.NODE9_DEBUG === '1') { try { const dbg = path.join(os.homedir(), '.node9', 'hook-debug.log'); const msg = err instanceof Error ? err.message : String(err); fs.appendFileSync(dbg, `[${new Date().toISOString()}] SKILL_PIN_ERROR: ${msg}\n`); } catch { /* ignore */ } } } } const safeCwdForAuth = typeof payloadCwd === 'string' && path.isAbsolute(payloadCwd) ? payloadCwd : undefined; const askMode = resolveAskMode(agent, opts, config); const result = await authorizeHeadless(toolName, toolInput, meta, { cwd: safeCwdForAuth, deferReview: askMode, }); // A decision by any channel OTHER than an inline defer supersedes any // stale pending-ask marker for this correlation key (/code-review // fix): without this, a Copilot command denied at an earlier inline // ask and later allowed on the ordinary path (taint expired, rule // changed) resolves the old marker in PostToolUse and ships a // fabricated "dev approved inline" row. Claude Code's tuid keys are // per-call unique, so this is a no-op there. Best-effort. if (!result.review) { try { const key = reviewCorrelationKey(payload as Record); if (key) discardPendingReview(key); } catch { /* marker hygiene must never affect the decision */ } } // fw#420: once per Claude Code or Codex session, the first ALLOWED call tells // the user node9 is on and at which level (Audit says nothing is // blocked). Never on a block or a review, never with a decision, and a // failure here only drops the notice. // A subagent's call (payload agent_id) shares the session id, but its // reply goes to the parent agent, not the user: it must not spend the // flag. The write is synchronous so exit cannot cut it off (pipes are // asynchronous on macOS) after the flag is already claimed. const isSubagentCall = typeof (payload as { agent_id?: unknown }).agent_id === 'string' && (payload as { agent_id: string }).agent_id !== ''; // Codex accepts this output on an allowed PreToolUse (systemMessage and // additionalContext are in its schema); after its SessionStart notice // this says nothing unless the level changes. const noticeAgent = agent === 'Claude Code' || agent === 'Codex'; // A paused node9 checks nothing: no "is on" notice, and the flag stays // free for the first checked call after the pause. const allowExit = (checkedBy?: string): never => { // Once per session, and once more when the level changes mid-session // or the daemon stays down (automatic start off: with it on, this // call already started the daemon; node9Firewall#445 follow-up). const daemonStaysDown = daemonDown && config.settings.autoStartDaemon === false; const notice = checkedBy !== 'paused' && noticeAgent && !isSubagentCall && sessionNoticeEnabled() ? claimSessionNotice( safeSessionId, os.homedir(), levelOf(config.settings.mode) + (daemonStaysDown ? NO_DAEMON_SUFFIX : '') ) : null; // node9Firewall#427: past 75%, 90% or 100% of the person's monthly // budget, one line per session and level on an allowed call (a // stop at 100% is the orchestrator's). Same audience as the // notice above: the user of a Claude Code or Codex session, not a subagent. let budgetLine: string | null = null; if ( checkedBy !== 'paused' && noticeAgent && !isSubagentCall && sessionNoticeEnabled() ) { try { const spend = judgeSpendBudget( config.policy.spendBudget, checkValue( catalogSettingsFromConfig(config.settings, config.policy), 'behavior.spend-budget' ), agent, Date.now() ); if (spend && claimBudgetNotice(safeSessionId, `${spend.month}:${spend.level}`)) budgetLine = budgetNoticeLine(spend); } catch { /* UX only */ } } if (notice || budgetLine) { try { fs.writeSync( 1, (notice ? sessionNoticeOutput(config.settings.mode, notice, daemonStaysDown, budgetLine) : budgetNoticeOutput(budgetLine!)) + '\n' ); } catch { /* UX only */ } } process.exit(0); }; if (result.approved) { // Only write to stderr in debug mode — Claude Code treats any stderr // output as a hook error regardless of exit code (see GitHub issue). if (result.checkedBy && process.env.NODE9_DEBUG === '1') process.stderr.write(`✓ node9 [${result.checkedBy}]: "${toolName}" allowed\n`); allowExit(result.checkedBy); } // Inline-ask: a deferred review → hand the approve/deny prompt to the // agent (only set when askMode + ask-capable agent; v2 defers every // review verdict except a downgraded hard block — see the orchestrator // defer guard). Must precede the block path below. if (result.review) { sendAsk(result); return; } // Auto-start daemon if allowed if ( result.noApprovalMechanism && !isDaemonRunning() && !process.env.NODE9_NO_AUTO_DAEMON && !process.stdout.isTTY && config.settings.autoStartDaemon ) { try { const tty = fs.openSync('/dev/tty', 'w'); fs.writeSync( tty, chalk.cyan('\n🛡️ Node9: Starting approval daemon automatically...\n') ); fs.closeSync(tty); } catch { /* non-interactive env */ } const daemonReady = await autoStartDaemonAndWait(); if (daemonReady) { const retry = await authorizeHeadless(toolName, toolInput, meta, { cwd: safeCwdForAuth, }); if (retry.approved) { if (retry.checkedBy && process.env.NODE9_DEBUG === '1') process.stderr.write(`✓ node9 [${retry.checkedBy}]: "${toolName}" allowed\n`); allowExit(retry.checkedBy); } // sendBlock speaks each agent's block contract (Codex: stderr). sendBlock(retry.reason ?? `Node9 blocked "${toolName}".`, { ...retry, blockedByLabel: retry.blockedByLabel, }); return; } } // sendBlock speaks each agent's block contract (Codex: stderr). sendBlock(result.reason ?? `Node9 blocked "${toolName}".`, { ...result, blockedByLabel: result.blockedByLabel, }); } catch (err: unknown) { if (process.env.NODE9_DEBUG === '1') { const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); const errMsg = err instanceof Error ? err.message : String(err); fs.appendFileSync(logPath, `[${new Date().toISOString()}] ERROR: ${errMsg}\n`); } process.exit(0); // Fail open so we never break Claude on a parse error } }; if (data) { await processPayload(data); } else { let raw = ''; let processed = false; let inactivityTimer: NodeJS.Timeout | null = null; const done = async () => { // Atomic check: prevents double-processing if 'end' and 'timeout' fire together if (processed) return; processed = true; // Kill the timer so it doesn't fire while we are waiting for human approval if (inactivityTimer) clearTimeout(inactivityTimer); if (!raw.trim()) return process.exit(0); await processPayload(raw); }; process.stdin.setEncoding('utf-8'); process.stdin.on('data', (chunk) => { raw += chunk; // Sliding window: reset timer every time data arrives if (inactivityTimer) clearTimeout(inactivityTimer); inactivityTimer = setTimeout(() => void done(), 2000); }); process.stdin.on('end', () => { void done(); }); // Initial safety: if no data arrives at all within 5s, exit. inactivityTimer = setTimeout(() => void done(), 5000); } }); }