// src/auth/daemon.ts // Daemon interaction helpers: PID check, entry registration, long-polling, viewer cards. import fs from 'fs'; import http from 'http'; import net from 'net'; import path from 'path'; import os from 'os'; import { type RiskMetadata } from '../context-sniper'; import { forecastRun } from './forecast-context'; import { isTrustedActivitySocket } from '../utils/activity-socket'; import { CARD_PROTOCOL, legacyWaitFields, parseDecisionRecord, type Channel, type DecisionRecord, } from './decision-record'; /** * The activity socket the running daemon recorded in ~/.node9/daemon.pid * (mode 0600), when it is one this user owns. Null: no daemon, a daemon from * before 2.48.3 that records none, or a socket that fails the owner check; the * caller then tells the daemon over HTTP. There is no fallback to the old * shared /tmp path: that fallback would be the hole this closes. */ export function daemonActivitySocket(home = os.homedir()): string | null { try { const raw = fs.readFileSync(path.join(home, '.node9', 'daemon.pid'), 'utf-8'); const p = (JSON.parse(raw) as Record).activitySocket; return typeof p === 'string' && isTrustedActivitySocket(p) ? p : null; } catch { return null; } } /** How long a hook waits for the daemon to take an activity line. A healthy * local socket closes in a few milliseconds; the same bound as * isDaemonReachable. */ export const ACTIVITY_SOCKET_TIMEOUT_MS = 500; /** * Write a message to the activity Unix socket (flight recorder + session counters). * Returns true if the send succeeded, false if the daemon is not reachable. * Callers that set fromCLI=true on POST /check must check this return value — * if it's false, pass fromCLI=false so the daemon emits the activity event itself. * * Bounded: every hook awaits this before the gate judges and again after, so a * daemon that accepts the connection and never closes it (event loop blocked, * a debugger, SIGSTOP) used to hold every agent tool call. After `timeoutMs` * the socket is destroyed and the answer is false. On the review path the * daemon then emits the line itself (it may show twice in `node9 tail`); an * allow or block line that times out mid-write can be lost. Either is a * flight-recorder gap, never a gating one. */ export function notifyActivitySocket( data: Record, opts: { timeoutMs?: number; socketPath?: string } = {} ): Promise { // A forecast run never opens the socket. if (forecastRun()) return Promise.resolve(false); // `socketPath` is the tests' own listener; otherwise the daemon's socket, // only if this user owns it. const target = opts.socketPath ?? daemonActivitySocket(); if (!target) return Promise.resolve(false); return new Promise((resolve) => { let settled = false; let sock: net.Socket | null = null; const finish = (ok: boolean) => { if (settled) return; settled = true; clearTimeout(timer); if (!ok) sock?.destroy(); resolve(ok); }; const timer = setTimeout(() => finish(false), opts.timeoutMs ?? ACTIVITY_SOCKET_TIMEOUT_MS); try { const payload = JSON.stringify(data); sock = net.createConnection(target); sock.on('connect', () => { sock!.on('close', () => finish(true)); sock!.end(payload); }); sock.on('error', () => finish(false)); } catch { finish(false); } }); } /** * Query daemon state predicates for stateful smart rules. * Returns a map of predicate → boolean, or null if daemon unreachable. */ export async function checkStatePredicates( predicates: string[] ): Promise | null> { if (predicates.length === 0) return {}; // A forecast has no daemon state to ask: fail open, as a down daemon does. if (forecastRun()) return null; try { const qs = predicates.map(encodeURIComponent).join(','); const res = await fetch(`http://${DAEMON_HOST}:${DAEMON_PORT}/state/check?predicates=${qs}`, { signal: AbortSignal.timeout(100), }); if (!res.ok) return null; return (await res.json()) as Record; } catch { return null; } } const DEFAULT_DAEMON_PORT = 7391; /** * The daemon's loopback port. Fixed at 7391 for every real install. * * `NODE9_DAEMON_PORT` overrides it under NODE9_TESTING=1 only, so a test or a * benchmark can run its own daemon in an isolated HOME next to the developer's * live one. Outside test mode the variable is ignored: an inherited * environment variable must not be able to point the hooks at a lookalike * daemon that answers "not tainted" (the same rule supply-chain/net.ts applies * to its endpoint overrides). Every process reads this once at startup, so * the daemon and the hooks that talk to it must share the environment. */ export function resolveDaemonPort(env: NodeJS.ProcessEnv = process.env): number { if (env.NODE9_TESTING !== '1') return DEFAULT_DAEMON_PORT; const raw = env.NODE9_DAEMON_PORT; if (raw === undefined || raw === '') return DEFAULT_DAEMON_PORT; const port = Number(raw); // Unprivileged, valid TCP ports only; anything else keeps the default. if (!Number.isInteger(port) || port < 1024 || port > 65535) return DEFAULT_DAEMON_PORT; return port; } export const DAEMON_PORT = resolveDaemonPort(); export const DAEMON_HOST = '127.0.0.1'; /** * Reads the internal token from the daemon PID file. * Used by notifyDaemonViewer / resolveViaDaemon so the Slack flow can * register and clear viewer-mode cards without needing the CSRF token. */ export function getInternalToken(): string | null { if (forecastRun()) return null; try { const pidFile = path.join(os.homedir(), '.node9', 'daemon.pid'); if (!fs.existsSync(pidFile)) return null; const data = JSON.parse(fs.readFileSync(pidFile, 'utf-8')) as Record; process.kill(data.pid as number, 0); // verify alive return (data.internalToken as string) ?? null; } catch { return null; } } export function isDaemonRunning(): boolean { // A forecast run has no daemon: every state query in this module answers // from the replayed session state before it gets here, and with no daemon // the gate reaches no human, so a hard block stays a block (review item 1). if (forecastRun()) return false; const pidFile = path.join(os.homedir(), '.node9', 'daemon.pid'); if (fs.existsSync(pidFile)) { let pid: unknown; let port: unknown; try { const data = JSON.parse(fs.readFileSync(pidFile, 'utf-8')) as Record; pid = data.pid; port = data.port; } catch { // Unreadable or invalid JSON — treat as no daemon running. // Do NOT delete: the file may be mid-write by the daemon process. return false; } // Validate port before comparing — never trust file content blindly. if (port !== DAEMON_PORT) { // Wrong port — stale file from a config change. // Do NOT delete here: deleting based on attacker-controlled content creates // a TOCTOU attack where a malicious file causes us to remove the real PID file. // The daemon manages its own PID file; we only read it. return false; } // Validate pid strictly before passing to process.kill. // pid=0 signals the entire process group; pid=-1 signals all reachable processes. // Both are denial-of-service primitives available to any local user who can // write ~/.node9/daemon.pid. Reject anything outside the valid PID range. const MAX_PID = 4_194_304; // Linux kernel default max_pid (2^22) if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { return false; } try { // Signal 0 is a pure existence probe — it sends no signal and cannot // affect the target process. The only outcomes are: success (process // exists and we have permission to signal it), ESRCH (no such process), // or EPERM (process exists but owned by a different uid). We never call // process.kill with any other signal number via this code path. process.kill(pid, 0); } catch (err: unknown) { // ESRCH = no such process (truly dead). Clean up the stale PID file only // in this case so the next call doesn't re-read it. // Do not clean up for EPERM (process exists but we can't signal it) — // that would remove a valid PID file for a daemon running as a different uid. if ( err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ESRCH' ) { try { fs.unlinkSync(pidFile); } catch { /* non-fatal */ } } return false; } // PID file present, JSON valid, port matches, PID validates, process exists. // We treat that as "running". A previous version also spawned `ss` to verify // the TCP port was bound — but `ss` is Linux-only (iproute2), causing this // function to always return false on macOS even when the daemon was up. // Callers that genuinely need HTTP-liveness (e.g. daemon-starter polling) // should use isDaemonReachable() instead. return true; } // No PID file — daemon not running. Detecting orphaned daemons (process up, // PID file lost) requires a port probe; that probe is portable only via // spawning `lsof`/`ss`, which we deliberately avoid here to keep this hot // path sync, fast, and cross-platform. The orphan case is recovered at // daemon startup via the EADDRINUSE handler in src/daemon/server.ts. return false; } /** * Async HTTP-liveness probe. Use this when a caller genuinely needs to know * the daemon's HTTP server is accepting requests right now (e.g. after * spawning the daemon, before issuing the first /check call). isDaemonRunning() * is the cheap sync check — sufficient for most call sites. */ export async function isDaemonReachable(timeoutMs = 500): Promise { try { const res = await fetch(`http://${DAEMON_HOST}:${DAEMON_PORT}/settings`, { signal: AbortSignal.timeout(timeoutMs), }); return res.ok; } catch { return false; } } /** GET /health outcome, three-valued because the CASES mean different things * (task #18): a daemon that answers /health names its build; a daemon that * serves but 404s /health is provably OLDER than this (installed) build, * which implements it; unreachable says nothing about builds at all. */ export type DaemonHealthProbe = | { kind: 'health'; health: { version?: unknown; buildId?: unknown; pid?: unknown } } | { kind: 'no-health' } | { kind: 'unreachable' }; export async function probeDaemonHealth(timeoutMs = 800): Promise { try { const res = await fetch(`http://${DAEMON_HOST}:${DAEMON_PORT}/health`, { signal: AbortSignal.timeout(timeoutMs), }); if (!res.ok) return { kind: 'no-health' }; const j = (await res.json().catch(() => null)) as Record | null; return j && typeof j === 'object' ? { kind: 'health', health: j } : { kind: 'no-health' }; } catch { return { kind: 'unreachable' }; } } /** * Is a genuine human approver reachable right now — i.e. is an input-capable * client (`node9 tail`) connected to the daemon? Used by the orchestrator to * decide whether a shield hard-block may be downgraded to a review. Fails * CLOSED (returns false) on any error/timeout: if we can't confirm a human is * watching, a hard block must stay hard rather than become an auto-allowable * review in a non-interactive context. */ export async function daemonHasInteractiveApprover(timeoutMs = 400): Promise { if (forecastRun()) return false; try { const res = await fetch(`http://${DAEMON_HOST}:${DAEMON_PORT}/approver`, { signal: AbortSignal.timeout(timeoutMs), }); if (!res.ok) return false; const body = (await res.json()) as { interactive?: unknown }; return body.interactive === true; } catch { return false; } } /** * Register a new approval entry with the daemon and return its ID. * Both the browser racer (GET /wait) and the terminal racer (POST /decision) * share this entry — it must be created before the race starts. */ export async function registerDaemonEntry( toolName: string, args: unknown, meta?: { agent?: string; mcpServer?: string }, riskMetadata?: RiskMetadata, activityId?: string, cwd?: string, recoveryCommand?: string, /** When true, the daemon skips background authorizeHeadless and holds the entry * open until the caller resolves it via resolveViaDaemon. Use for recovery menu * entries where check.ts is the sole decision maker via the tty menu. */ skipBackgroundAuth?: boolean, /** When true, the tail shows the card for context only (no interactive keypress). */ viewOnly?: boolean, /** When true, the daemon skips cloud's immediate-allow for the background auth pass. * Set when a local smart rule with verdict "review" matched in the hook process. */ localSmartRuleMatched?: boolean, /** When false, the socket send of the activity event failed — daemon must emit it. */ socketActivitySent?: boolean, /** The agent session, so a "trust this address" decision can clear its exposure (fw#318 P5). */ sessionId?: string, /** The card: who may answer it, and the caller's approval timeout (0 = none). */ card?: CardOptions ): Promise { const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 5000); try { const res = await fetch(`${base}/check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ toolName, args, agent: meta?.agent, mcpServer: meta?.mcpServer, // fromCLI=true tells the daemon the CLI already sent the activity event via // socket. If the socket send failed (socketActivitySent=false), set fromCLI=false // so the daemon emits the activity event itself — tail never misses an entry. fromCLI: socketActivitySent !== false, // Pass the flight-recorder ID so the daemon uses the same UUID for // activity-result as the CLI used for the pending activity event. activityId, ...(riskMetadata && { riskMetadata }), ...(cwd && { cwd }), ...(recoveryCommand && { recoveryCommand }), ...(skipBackgroundAuth && { skipBackgroundAuth: true }), ...(viewOnly && { viewOnly: true }), ...(localSmartRuleMatched && { localSmartRuleMatched: true }), ...(sessionId && { sessionId }), ...cardFields(card), }), signal: ctrl.signal, }); if (!res.ok) throw new Error('Daemon fail'); return registeredCard(await res.json()); } finally { clearTimeout(timer); } } /** What the hook tells the daemon about a card it registers. */ export interface CardOptions { channels?: Channel[]; /** The caller's approval timeout in ms (project-aware); 0 = no timer. */ timeoutMs?: number; } /** The daemon's answer to a registration. `protocol` and `deadline` are absent * on a daemon older than the card protocol. */ export interface RegisteredCard { id: string; allowCount: number; protocol?: number; /** Epoch ms when the card's timer decides it, or null for none. */ deadline?: number | null; } function cardFields(card?: CardOptions): Record { return { // A review card: the hook already decided this call needs a person; the // daemon never checks it again (approval-card design, defect 1). kind: 'review', // Protocol 2 makes the card's /wait require the internal token: claim it // only when this process can read the token (a daemon under another uid // is running but its pid file probe fails with EPERM), or every wait // would get 403 and the review would be denied unseen. ...(getInternalToken() && { protocol: CARD_PROTOCOL }), ...(card?.channels && { channels: card.channels }), ...(typeof card?.timeoutMs === 'number' && { timeoutMs: card.timeoutMs }), }; } function registeredCard(body: unknown): RegisteredCard { const b = body as { id: string; allowCount?: number; protocol?: unknown; deadline?: unknown }; return { id: b.id, allowCount: b.allowCount ?? 1, ...(b.protocol === CARD_PROTOCOL && { protocol: CARD_PROTOCOL, deadline: typeof b.deadline === 'number' ? b.deadline : null, }), }; } /** Long-poll the daemon for a decision on an already-registered entry. * node:http, not fetch: undici ends a request with no response headers * after 300 s (headersTimeout), and the daemon answers /wait only when the * card is decided, so a fetch-based wait cut every review longer than 300 s, * including the "no timer" of approvalTimeoutMs 0 (review of 232b7e8). */ export async function waitForDaemonDecision( id: string, signal?: AbortSignal, /** Give up after this long; 0 waits for the daemon's answer however long it takes. */ maxWaitMs = 120_000 ): Promise { const waitCtrl = new AbortController(); let capped = false; const waitTimer = maxWaitMs > 0 ? setTimeout(() => { capped = true; waitCtrl.abort(); }, maxWaitMs) : undefined; const onAbort = () => waitCtrl.abort(); if (signal) signal.addEventListener('abort', onAbort); try { // The body is read inside this catch too: a cap that fired while the body // was read used to escape as an AbortError. const { status, body } = await daemonGet(`/wait/${id}`, waitCtrl.signal).catch( (err: unknown) => { // Our own cap is a failed channel, not the race aborting this racer: // the race ignores an AbortError, and a race with no other racer // then never ended. if (capped && !signal?.aborted) throw new Error('node9 daemon did not answer in time'); throw err; } ); // The card was withdrawn (its asker gave up): no decision to report. if (status === 409) throw new Error('node9 card was withdrawn'); if (status !== 200) return { decision: 'deny' }; const parsed = JSON.parse(body) as { decision: string; source?: string; reason?: string; record?: unknown; }; // A protocol-2 daemon sends the whole DecisionRecord; the old fields are // kept for hooks of earlier releases. const record = parseDecisionRecord(parsed.record); if (record) return { ...legacyWaitFields(record), record }; const { decision, source, reason } = parsed; if (decision === 'allow') return { decision: 'allow', source }; if (decision === 'abandoned') return { decision: 'abandoned', source }; return { decision: 'deny', source, reason }; } finally { clearTimeout(waitTimer); if (signal) signal.removeEventListener('abort', onAbort); } } export interface WaitResult { decision: 'allow' | 'deny' | 'abandoned'; source?: string; reason?: string; /** Who decided, from a protocol-2 daemon. */ record?: DecisionRecord; } /** A GET on the daemon with no client-side timeout; only `signal` ends it. * Its own socket (agent: false), so a long-held wait stays out of the * keep-alive pool. */ function daemonGet( urlPath: string, signal: AbortSignal, token: string | null = getInternalToken() ): Promise<{ status: number; body: string }> { return new Promise((resolve, reject) => { const req = http.get( { host: DAEMON_HOST, port: DAEMON_PORT, path: urlPath, signal, agent: false, headers: token ? { 'X-Node9-Internal': token } : {}, }, (res) => { let body = ''; res.setEncoding('utf8'); res.on('data', (chunk: string) => (body += chunk)); res.on('end', () => resolve({ status: res.statusCode ?? 0, body })); res.on('error', reject); } ); req.on('error', reject); }); } /** Register a viewer-mode card on the daemon (Slack is the real authority). * * Mirrors registerDaemonEntry's fromCLI/activityId contract: when the CLI * has already sent the 'activity' event via the Unix socket, we tell the * daemon to skip its own 'activity' broadcast and reuse the same id. * Without this, the cloud-enforced path produced TWO 'activity' SSE * events per logical command — one from state.ts:688 (socket handler) * and one from server.ts:274 (/check handler with fromCLI=false). */ export async function notifyDaemonViewer( toolName: string, args: unknown, meta?: { agent?: string; mcpServer?: string }, riskMetadata?: RiskMetadata, activityId?: string, /** When false, the socket send of the activity event failed — daemon must emit it. */ socketActivitySent?: boolean, /** The same card fields as registerDaemonEntry: the viewer card used to send * none, so a recovery card lost its menu and "trust this address" could not * clear the session on the cloud path (approval-card design, defect 11). */ extra?: { cwd?: string; recoveryCommand?: string; sessionId?: string; card?: CardOptions } ): Promise { const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; const res = await fetch(`${base}/check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ toolName, args, slackDelegated: true, agent: meta?.agent, mcpServer: meta?.mcpServer, ...(riskMetadata && { riskMetadata }), // fromCLI=true tells the daemon the CLI already sent the activity // event via socket. Same contract as registerDaemonEntry — without // it the daemon double-emits 'activity' for cloud-enforced flows. fromCLI: socketActivitySent !== false, activityId, ...(extra?.cwd && { cwd: extra.cwd }), ...(extra?.recoveryCommand && { recoveryCommand: extra.recoveryCommand }), ...(extra?.sessionId && { sessionId: extra.sessionId }), ...cardFields(extra?.card), }), signal: AbortSignal.timeout(3000), }); if (!res.ok) throw new Error('Daemon unreachable'); return registeredCard(await res.json()); } /** * Notify the daemon to taint a file path after a DLP write-block. * Must be awaited before the hook process exits — fire-and-forget loses the * taint because the process exits before the fetch completes. */ export async function notifyTaint( filePath: string, source: string, fromEid?: string ): Promise { const forecast = forecastRun(); if (forecast) { forecast.session.taintPath(filePath, source, forecast.now, fromEid); return; } if (!isDaemonRunning()) return; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { await fetch(`${base}/taint`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, // Phase D2 — fromEid is the audit eid that created this taint (edge source). body: JSON.stringify({ path: filePath, source, ...(fromEid && { fromEid }) }), signal: AbortSignal.timeout(1000), }); } catch { // Taint is best-effort — daemon unreachable is non-fatal } } /** * Notify the daemon to propagate taint from src to dest (cp/mv semantics). * clearSource=true implements mv: the source taint is removed after propagation. */ export async function notifyTaintPropagate( src: string, dest: string, clearSource = false ): Promise { const forecast = forecastRun(); if (forecast) { const r = forecast.session.taintedPaths.get(src); if (r) forecast.session.taintPath(dest, r.source, forecast.now, r.fromEid); if (r && clearSource) forecast.session.taintedPaths.delete(src); return; } if (!isDaemonRunning()) return; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { await fetch(`${base}/taint/propagate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ src, dest, clearSource }), signal: AbortSignal.timeout(1000), }); } catch { // Propagation is best-effort — daemon unreachable is non-fatal } } // Re-export TaintRecord so callers share one canonical type instead of an inline duplicate. export type { TaintRecord } from '../daemon/taint-store.js'; import type { TaintRecord, SessionTaintRecord } from '../daemon/taint-store.js'; import type { SessionExposureRecord } from '../daemon/exposure-store.js'; export interface SessionTaintCheckResult { tainted: boolean; record?: SessionTaintRecord; /** fw#318: the session read outside content (the daemon's exposure record). */ exposed?: boolean; /** True when the daemon was unreachable — caller treats as untainted (fail-open). */ daemonUnavailable?: boolean; } export interface TaintCheckResult { tainted: boolean; record?: TaintRecord; /** * True when the taint daemon was unreachable and the check could not be * completed. The caller should treat this as a soft warning: files may be * tainted but the status is unknown. Distinct from tainted:false, which * means the daemon was reachable and confirmed the paths are clean. */ daemonUnavailable?: boolean; } /** * Ask the daemon if any of the given file paths are tainted. * Returns the first tainted record found, or { tainted: false }. * * Fail-open: returns { tainted: false } on network error so a daemon blip * doesn't stall the agent. The error is logged to hook-debug.log so it's * visible without being fatal. */ export async function checkTaint(paths: string[]): Promise { if (paths.length === 0) return { tainted: false }; const forecast = forecastRun(); if (forecast) { const record = forecast.session.checkTaint(paths, forecast.now); return record ? { tainted: true, record } : { tainted: false }; } if (!isDaemonRunning()) return { tainted: false, daemonUnavailable: true }; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/taint/check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paths }), signal: AbortSignal.timeout(2000), }); return (await res.json()) as TaintCheckResult; } catch (err) { // Fail-open: a taint check failure must not block the agent entirely. // Log so the operator can diagnose daemon instability without user impact. try { const { appendToLog, HOOK_DEBUG_LOG } = await import('../audit/index.js'); appendToLog(HOOK_DEBUG_LOG, { ts: new Date().toISOString(), event: 'checkTaint-error', error: String(err), paths, }); } catch { /* audit write failure is non-fatal */ } return { tainted: false, daemonUnavailable: true }; } } /** * Record files this call writes, so a script among them that is run later is * judged from its content (fw#372 A3). Best-effort, like notifyTaint. */ export async function notifyWritten(paths: readonly string[]): Promise { const forecast = forecastRun(); if (forecast) { forecast.session.noteWritten(paths); return; } if (paths.length === 0 || !isDaemonRunning()) return; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { await fetch(`${base}/written`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify({ paths: paths.slice(0, 64) }), signal: AbortSignal.timeout(1000), }); } catch { // Best-effort: a daemon blip leaves the script unexamined, as before. } } export interface WrittenCheckResult { /** The paths among those asked that an agent session wrote (absolute). */ written: string[]; daemonUnavailable?: boolean; } /** Which of these paths an agent session wrote. Fail-open: no daemon, none. */ export async function checkWritten(paths: readonly string[]): Promise { if (paths.length === 0) return { written: [] }; const forecast = forecastRun(); if (forecast) return { written: forecast.session.written(paths) }; if (!isDaemonRunning()) return { written: [], daemonUnavailable: true }; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/written/check`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify({ paths: paths.slice(0, 64) }), signal: AbortSignal.timeout(2000), }); const body = (await res.json()) as { written?: unknown }; return { written: Array.isArray(body.written) ? body.written.filter((p): p is string => typeof p === 'string') : [], }; } catch { return { written: [], daemonUnavailable: true }; } } /** * Taint a session after its tool output was flagged (gap1). Best-effort, must be * awaited before the PostToolUse hook exits (same reason as notifyTaint). */ export async function notifySessionTaint(sessionId: string, source: string): Promise { const forecast = forecastRun(); if (forecast) { forecast.session.noteOutputSecret(source.replace(/^output-secret:/, ''), forecast.now); return; } if (!sessionId || !isDaemonRunning()) return; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { await fetch(`${base}/session-taint`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify({ sessionId, source }), signal: AbortSignal.timeout(1000), }); } catch { // Session taint is best-effort — daemon unreachable is non-fatal. } } /** * Ask the daemon whether a session is tainted (gap1). Fail-open: a daemon blip * returns { tainted: false } so it never stalls the agent — same contract as * checkTaint. */ export async function checkSessionTaint(sessionId: string): Promise { const forecast = forecastRun(); if (forecast) { const record = forecast.session.checkSessionTaint(forecast.now); const exposed = forecast.session.checkExposure(forecast.now) !== null; return record ? { tainted: true, record, exposed } : { tainted: false, exposed }; } if (!sessionId || !isDaemonRunning()) return { tainted: false }; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/session-taint/check`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify({ sessionId }), signal: AbortSignal.timeout(2000), }); return (await res.json()) as SessionTaintCheckResult; } catch { // Fail-open: a session-taint check failure must not block the agent. return { tainted: false, daemonUnavailable: true }; } } /** * List currently tainted sessions (gap1). Taint lives in daemon memory, so a * stopped daemon means there are no active taints — returns []. For `node9 * session-taint list` / the clear command's prefix resolution. */ export async function listSessionTaints(): Promise { if (!isDaemonRunning()) return []; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/session-taint/list`, { headers: exposureHeaders(), signal: AbortSignal.timeout(2000), }); const json = (await res.json()) as { records?: SessionTaintRecord[] }; return json.records ?? []; } catch { return []; } } /** * Clear a session taint (or all). For `node9 session-taint clear` — lets a user * who has resolved a flagged output release the session so its next high-risk * action isn't held for review. daemonUnavailable distinguishes "no daemon" * (nothing to clear) from "cleared 0" (daemon up, id wasn't tainted). */ export async function clearSessionTaint(opts: { sessionId?: string; all?: boolean; }): Promise<{ ok: boolean; cleared: number; daemonUnavailable?: boolean }> { if (!isDaemonRunning()) return { ok: false, cleared: 0, daemonUnavailable: true }; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/session-taint/clear`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify(opts), signal: AbortSignal.timeout(2000), }); return (await res.json()) as { ok: boolean; cleared: number }; } catch { return { ok: false, cleared: 0, daemonUnavailable: true }; } } // ── Session exposure (fw#318) ─────────────────────────────────────────────── // The session READ outside content. Same contracts as the taint client above: // notify is best-effort and awaited before the hook exits; check fails open. // Every route takes the daemon's internal token (read from daemon.pid). export interface SessionExposureCheckResult { exposed: boolean; record?: SessionExposureRecord; daemonUnavailable?: boolean; } function exposureHeaders(): Record { return { 'Content-Type': 'application/json', 'X-Node9-Internal': getInternalToken() ?? '', }; } async function exposurePost(route: string, body: unknown, timeoutMs: number): Promise { const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; const res = await fetch(`${base}${route}`, { method: 'POST', headers: exposureHeaders(), body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), }); // A 403 (stale daemon.pid after a restart) or a 400 must read as "the // daemon did not answer", never as a record. if (!res.ok) throw new Error(`session-exposure ${route}: HTTP ${res.status}`); return res.json(); } /** The session read a source. */ export async function notifySessionExposure( sessionId: string, source: { tool: string; server?: string; word?: string; eid?: string }, destinations: readonly string[] ): Promise { const forecast = forecastRun(); if (forecast) { forecast.session.noteOutsideContent({ ...source, at: forecast.now }, [...destinations]); return; } if (!sessionId || !isDaemonRunning()) return; try { await exposurePost('/session-exposure', { sessionId, source, destinations }, 1000); } catch { // Best-effort — daemon unreachable is non-fatal. } } /** The user named these destinations in a prompt. */ export async function notifyUserMentions( sessionId: string, destinations: readonly string[] ): Promise { const forecast = forecastRun(); if (forecast) { if (forecast.session.exposure) for (const d of destinations) if (!forecast.session.exposure.userMentioned.includes(d)) forecast.session.exposure.userMentioned.push(d); return; } if (!sessionId || destinations.length === 0 || !isDaemonRunning()) return; try { await exposurePost('/session-exposure/user-mentioned', { sessionId, destinations }, 1000); } catch { // Best-effort. } } /** Fail-open: a daemon blip returns { exposed: false }. No daemon at all says * so (daemonUnavailable), so the gate can record it and Strict can hold * (node9Firewall#445 follow-up). */ export async function checkSessionExposure(sessionId: string): Promise { const forecast = forecastRun(); if (forecast) { const record = forecast.session.checkExposure(forecast.now); return record ? { exposed: true, record } : { exposed: false }; } if (!sessionId) return { exposed: false }; if (!isDaemonRunning()) return { exposed: false, daemonUnavailable: true }; try { return (await exposurePost( '/session-exposure/check', { sessionId }, 2000 )) as SessionExposureCheckResult; } catch { return { exposed: false, daemonUnavailable: true }; } } /** An approval cleared these '|' keys (ask-once). */ export async function approveSessionExposure( sessionId: string, keys: readonly string[] ): Promise { const forecast = forecastRun(); if (forecast) { forecast.session.approveExposure(keys); return; } if (!sessionId || keys.length === 0 || !isDaemonRunning()) return; try { await exposurePost('/session-exposure/approve', { sessionId, keys }, 1000); } catch { // Best-effort. } } export async function listSessionExposures(): Promise { if (!isDaemonRunning()) return []; const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; try { const res = await fetch(`${base}/session-exposure/list`, { headers: exposureHeaders(), signal: AbortSignal.timeout(2000), }); const json = (await res.json()) as { records?: SessionExposureRecord[] }; return json.records ?? []; } catch { return []; } } export async function clearSessionExposure(opts: { sessionId?: string; all?: boolean; }): Promise<{ ok: boolean; cleared: number; daemonUnavailable?: boolean }> { if (!isDaemonRunning()) return { ok: false, cleared: 0, daemonUnavailable: true }; try { return (await exposurePost('/session-exposure/clear', opts, 2000)) as { ok: boolean; cleared: number; }; } catch { return { ok: false, cleared: 0, daemonUnavailable: true }; } } /** Report the hook's own winning racer (native popup, cloud poller, its * timer) to the card. First decision wins at the card: the reply says * whether this one won, and if not, which decision did (a person in node9 * tail a moment earlier). Null from a daemon older than the card protocol, * or when the card is gone. */ export async function resolveViaDaemon( id: string, decision: 'allow' | 'deny', internalToken: string, source?: string, record?: DecisionRecord ): Promise<{ won: boolean; record: DecisionRecord } | null> { const base = `http://${DAEMON_HOST}:${DAEMON_PORT}`; const res = await fetch(`${base}/resolve/${id}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Node9-Internal': internalToken }, body: JSON.stringify({ decision, ...(source && { source }), ...(record && { record }) }), signal: AbortSignal.timeout(3000), }); if (!res.ok) return null; const body = (await res.json().catch(() => null)) as { won?: unknown; record?: unknown } | null; const winner = parseDecisionRecord(body?.record); return winner && typeof body?.won === 'boolean' ? { won: body.won, record: winner } : null; }