@xtrom-ai/sdk 0.0.0-stage → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +185 -2
- package/dist/allowances.js +74 -0
- package/dist/cli.js +268 -0
- package/dist/credentials.js +37 -0
- package/dist/directive.js +57 -0
- package/dist/enforce.js +972 -0
- package/dist/index.js +31 -0
- package/dist/inspect.js +135 -0
- package/dist/local/agents.js +378 -0
- package/dist/local/appliers.js +61 -0
- package/dist/local/browser.js +135 -0
- package/dist/local/discover.js +154 -0
- package/dist/local/hook.js +778 -0
- package/dist/local/install.js +238 -0
- package/dist/local/inventory.js +219 -0
- package/dist/local/reasonText.js +29 -0
- package/dist/local/shipper.js +251 -0
- package/dist/local/spool.js +178 -0
- package/dist/local/updateKeys.js +3 -0
- package/dist/local/updater.js +224 -0
- package/dist/local/view.js +110 -0
- package/dist/memory.js +172 -0
- package/dist/reporter.js +336 -0
- package/dist/session.js +439 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +72 -0
- package/package.json +23 -4
- package/src/allowances.ts +74 -0
- package/src/cli.ts +268 -0
- package/src/credentials.ts +37 -0
- package/src/directive.ts +57 -0
- package/src/enforce.ts +972 -0
- package/src/index.ts +31 -0
- package/src/inspect.ts +135 -0
- package/src/local/agents.ts +378 -0
- package/src/local/appliers.ts +61 -0
- package/src/local/browser.ts +135 -0
- package/src/local/discover.ts +154 -0
- package/src/local/hook.ts +778 -0
- package/src/local/install.ts +238 -0
- package/src/local/inventory.ts +219 -0
- package/src/local/reasonText.ts +29 -0
- package/src/local/shipper.ts +251 -0
- package/src/local/spool.ts +178 -0
- package/src/local/updateKeys.ts +3 -0
- package/src/local/updater.ts +224 -0
- package/src/local/view.ts +110 -0
- package/src/memory.ts +172 -0
- package/src/reporter.ts +336 -0
- package/src/session.ts +439 -0
- package/src/version.ts +2 -0
- package/src/workspace.ts +72 -0
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
// Coding-agent PreToolUse/PostToolUse hook — port of xtrom_sdk/local/hook.py. One decision engine
|
|
2
|
+
// for every supported agent; agents.ts adapts each agent's payload and verdict protocol.
|
|
3
|
+
// Shares state, config and audit format with the Python hook (~/.xtrom/local), so either runtime
|
|
4
|
+
// honours taint the other recorded.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import {
|
|
7
|
+
appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
|
|
8
|
+
unlinkSync, writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { homedir, hostname, userInfo } from "node:os";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import {
|
|
13
|
+
decide as engineDecide, defaultPolicy, looksLikeSecret, matchesSecretPattern, originTag, secret, SECRET_RX,
|
|
14
|
+
type Decision, type Policy, type Value, type Verdict,
|
|
15
|
+
} from "../enforce.ts";
|
|
16
|
+
import { attribution, decisionEvent } from "../reporter.ts";
|
|
17
|
+
import { parseWorkspaceMode, resolveWorkspaceMode, type WorkspaceMode } from "../workspace.ts";
|
|
18
|
+
import { ensureShipper, spoolEvent } from "./spool.ts";
|
|
19
|
+
import { inspectResult } from "../inspect.ts";
|
|
20
|
+
import { DEFAULT_AGENT, getAdapter, POST, PRE, type HookOutput } from "./agents.ts";
|
|
21
|
+
import { classifyBrowser, type BrowserKind, type BrowserOp } from "./browser.ts";
|
|
22
|
+
|
|
23
|
+
export const STATE_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
24
|
+
const MAX_ORIGINS = 64;
|
|
25
|
+
const SAFE_ID = /[^A-Za-z0-9_.-]/g;
|
|
26
|
+
const OUTBOUND_RE = /(^|[;&|()\s])(curl|wget|nc|netcat|ssh|scp|rsync|ftp|sftp)\b|(^|[;&|()\s])git\s+push\b/i;
|
|
27
|
+
// Matched against mcpWords(toolName): camelCase and kebab-case become snake_case first.
|
|
28
|
+
const WRITE_MCP_RE = /(^|_)(send|post|create|update|write|delete|remove|publish|push|merge|invite|upload|edit|add|set|put|patch|insert|execute|exec|run|comment|reply|transfer|share|assign|close|approve|submit|deploy|trigger|move|rename|archive|drop|revoke|grant)(_|$)/i;
|
|
29
|
+
export const mcpWords = (toolName: string) => toolName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replaceAll("-", "_");
|
|
30
|
+
const DESTRUCTIVE_RE = /(^|[;&|()\s])(rm\s+-[A-Za-z]*[rf]|sudo\b|chmod\b|chown\b|dd\b|mkfs|git\s+(reset\s+--hard|clean\s+-[A-Za-z]*f|push\s+.*--force))/i;
|
|
31
|
+
// Context taint gates what can LEAVE the machine or destroy state. Local edits and benign shell stay
|
|
32
|
+
// visible in the developer's diff/terminal, so prompting on every one after a web fetch is noise.
|
|
33
|
+
const LOCAL_ONLY = new Set(["write_file", "local_shell", "list_dir", "read_file"]);
|
|
34
|
+
const SECRET_PATH_RE = /(~?\/\.ssh\/(id_[A-Za-z0-9_-]+|.*key)|\.env\b|credentials|token|secret)/i;
|
|
35
|
+
// URLs are matched only against precise credential patterns (?api_key=…, AKIA…, ghp_…). The path
|
|
36
|
+
// and entropy heuristics run on the rest: a long docs URL is high-entropy, and "tokenizers" in a
|
|
37
|
+
// path is not a credential — treating either as a secret denied ordinary WebFetch/curl calls.
|
|
38
|
+
const URL_RE = /https?:\/\/[^\s'")\\]+/gi;
|
|
39
|
+
|
|
40
|
+
// Tamper protection (see hook.py): ~/.xtrom is off-limits to the agent; every supported coding
|
|
41
|
+
// agent's hook and permission settings need a human.
|
|
42
|
+
const XTROM_HOME_RE = /(^|[^A-Za-z0-9_-])\.xtrom(?![A-Za-z0-9_-])/i;
|
|
43
|
+
// The env vars that move or loosen protection. They are only honored with XTROM_DEV_OVERRIDES=1, but
|
|
44
|
+
// setting any of them — or the flag itself — is still a protection change, so ask.
|
|
45
|
+
const XTROM_ENV_RE = /(?<![A-Za-z0-9_])XTROM_(MODE|LOCAL_HOME|SHIPPER_DISABLE|DEV_OVERRIDES)(?![A-Za-z0-9_])/;
|
|
46
|
+
// Shell startup files and persistent-environment commands: where an agent would plant an env var so
|
|
47
|
+
// every later agent session inherits it.
|
|
48
|
+
const SHELL_STARTUP_RE = new RegExp(
|
|
49
|
+
"(^|[^A-Za-z0-9_-])\\.(bashrc|bash_profile|bash_login|bash_logout|profile|zshrc|zshenv|zprofile|zlogin"
|
|
50
|
+
+ "|kshrc|cshrc|tcshrc|envrc)(?![A-Za-z0-9_-])|fish[/\\\\]+config\\.fish|[/\\\\]etc[/\\\\]+(profile|environment"
|
|
51
|
+
+ "|zshenv|zshrc|bash\\.bashrc)(?![A-Za-z0-9_-])|profile\\.ps1|launchctl\\s+setenv|\\bsetx\\b", "i");
|
|
52
|
+
// Shell can reach a config without spelling its path (`cd ~/.cursor && rm hooks.json`).
|
|
53
|
+
const SHELL_AGENT_DIR_RE = /\.(claude|cursor|copilot|codex|gemini|codeium|devin|windsurf)(?![A-Za-z0-9_-])|\.github[/\\]+hooks|github-copilot|gemini-cli|COPILOT_HOME|CODEX_HOME/i;
|
|
54
|
+
const SHELL_AGENT_FILE_RE = /(^|[^A-Za-z0-9_-])(settings(\.local)?\.json|managed-settings\.json|hooks(\.json)?|config\.(json|toml)|xtrom\.json)(?![A-Za-z0-9_-])/i;
|
|
55
|
+
// Re-running the installer can switch to monitor mode or remove the hooks entirely.
|
|
56
|
+
// `connect` can switch the team's reporting off or send this machine's decisions to someone else's console.
|
|
57
|
+
const SELF_MANAGE_RE = /(^|[^A-Za-z0-9_-])xtrom[A-Za-z0-9_.-]*[^;&|\n]*\s((un)?install|connect)(?![A-Za-z0-9_-])|xtrom_sdk\.local\.(cli|install)/i;
|
|
58
|
+
const AGENT_SETTINGS_RE = new RegExp([
|
|
59
|
+
String.raw`\.claude[/\\]+settings(\.local)?\.json|managed-settings\.json`,
|
|
60
|
+
String.raw`\.cursor[/\\]+hooks\.json|Cursor[/\\]+hooks\.json`,
|
|
61
|
+
String.raw`\.copilot[/\\]+(hooks([/\\]|\b)|settings\.json|config\.json)|\.github[/\\]+hooks([/\\]|\b)|github-copilot[/\\]+policy`,
|
|
62
|
+
String.raw`\.codex[/\\]+(hooks\.json|config\.toml)`,
|
|
63
|
+
String.raw`\.gemini[/\\]+settings\.json|gemini-cli[/\\]+settings\.json`,
|
|
64
|
+
String.raw`\.codeium[/\\]+(windsurf[/\\]+)?hooks\.json|\.(devin|windsurf)[/\\]+hooks\.json|Devin[/\\]+hooks\.json`,
|
|
65
|
+
].join("|"), "i");
|
|
66
|
+
|
|
67
|
+
// After untrusted input, shell runs silently only if every segment is a recognised local developer
|
|
68
|
+
// command; anything else asks. Mirrors hook.py rule for rule (checked by the differential test).
|
|
69
|
+
const SHELL_META_RE = /\$\(|`|<\(|>\(|\/dev\/(tcp|udp)\/|(^|[\s;&|(])(eval|exec|source|xargs)\b/;
|
|
70
|
+
const SEGMENT_SPLIT_RE = /&&|\|\||[;|&\n]/;
|
|
71
|
+
const ENV_PREFIX_RE = /^(\s*[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;
|
|
72
|
+
const SAFE_HEADS = new Set([
|
|
73
|
+
"ls", "pwd", "echo", "printf", "cat", "head", "tail", "wc", "grep", "rg", "sort", "uniq", "cut",
|
|
74
|
+
"tr", "diff", "tree", "which", "file", "stat", "du", "df", "date", "true", "false", "cd", "mkdir",
|
|
75
|
+
"touch", "cp", "mv", "ln", "jq", "basename", "dirname", "realpath", "find",
|
|
76
|
+
"tsc", "eslint", "prettier", "ruff", "mypy", "black", "pytest", "jest", "vitest", "make",
|
|
77
|
+
]);
|
|
78
|
+
const SAFE_SUBCOMMANDS: Record<string, Set<string>> = {
|
|
79
|
+
git: new Set(["status", "diff", "log", "show", "add", "commit", "branch", "checkout", "switch",
|
|
80
|
+
"restore", "stash", "rev-parse", "merge", "rebase", "blame", "ls-files", "mv", "rm", "init", "tag"]),
|
|
81
|
+
npm: new Set(["test", "t", "run", "lint", "build"]),
|
|
82
|
+
pnpm: new Set(["test", "t", "run", "lint", "build"]),
|
|
83
|
+
yarn: new Set(["test", "run", "lint", "build"]),
|
|
84
|
+
bun: new Set(["test", "run"]),
|
|
85
|
+
cargo: new Set(["test", "build", "check", "fmt", "clippy"]),
|
|
86
|
+
go: new Set(["test", "build", "vet", "fmt"]),
|
|
87
|
+
};
|
|
88
|
+
const PY_SAFE_MODULES = new Set(["pytest", "unittest", "mypy", "ruff", "black"]);
|
|
89
|
+
const FIND_EXEC = new Set(["-exec", "-execdir", "-delete", "-ok", "-okdir"]);
|
|
90
|
+
const GH_RE = /(^|[;&|()\s])gh\s+\S/i;
|
|
91
|
+
|
|
92
|
+
export function isKnownLocal(command: string): boolean {
|
|
93
|
+
if (SHELL_META_RE.test(command)) return false;
|
|
94
|
+
const segments = command.split(SEGMENT_SPLIT_RE).map((x) => x.trim());
|
|
95
|
+
if (!segments.some(Boolean)) return false;
|
|
96
|
+
for (const seg of segments) {
|
|
97
|
+
if (!seg) continue;
|
|
98
|
+
const toks = (seg + " ").replace(ENV_PREFIX_RE, "").split(/\s+/).filter(Boolean);
|
|
99
|
+
if (!toks.length) continue;
|
|
100
|
+
const [head, ...rest] = toks;
|
|
101
|
+
if (Object.hasOwn(SAFE_SUBCOMMANDS, head)) {
|
|
102
|
+
if (!rest.length || !SAFE_SUBCOMMANDS[head].has(rest[0])) return false;
|
|
103
|
+
} else if (head === "python" || head === "python3") {
|
|
104
|
+
if (rest.length < 2 || rest[0] !== "-m" || !PY_SAFE_MODULES.has(rest[1])) return false;
|
|
105
|
+
} else if (head === "node") {
|
|
106
|
+
if (rest[0] !== "--test") return false;
|
|
107
|
+
} else if (!SAFE_HEADS.has(head)) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
if (head === "find" && rest.some((t) => FIND_EXEC.has(t))) return false;
|
|
111
|
+
}
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function secretHint(text: string): boolean {
|
|
116
|
+
if (matchesSecretPattern(text)) return true;
|
|
117
|
+
const rest = text.replace(URL_RE, " ");
|
|
118
|
+
return SECRET_PATH_RE.test(rest) || looksLikeSecret(rest);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type Json = Record<string, unknown>;
|
|
122
|
+
|
|
123
|
+
export interface LocalPaths { base: string; sessions: string; audit: string; config: string }
|
|
124
|
+
|
|
125
|
+
// Environment overrides that could weaken or relocate protection (XTROM_LOCAL_HOME, XTROM_MODE=monitor,
|
|
126
|
+
// XTROM_SHIPPER_DISABLE) are honored ONLY with this explicit developer flag. The agent runs inside the
|
|
127
|
+
// trust boundary and can shape its own environment (shell profiles, agent settings), so the 0600 config
|
|
128
|
+
// under ~/.xtrom is authoritative; an env var may only make enforcement stricter.
|
|
129
|
+
export const DEV_OVERRIDES_ENV = "XTROM_DEV_OVERRIDES";
|
|
130
|
+
export const devOverrides = (): boolean => (process.env[DEV_OVERRIDES_ENV] ?? "").trim() === "1";
|
|
131
|
+
|
|
132
|
+
export function paths(home?: string): LocalPaths {
|
|
133
|
+
const override = devOverrides() ? process.env.XTROM_LOCAL_HOME : undefined;
|
|
134
|
+
const base = override ? resolve(override.replace(/^~(?=$|\/)/, homedir())) : join(home ?? homedir(), ".xtrom", "local");
|
|
135
|
+
return { base, sessions: join(base, "sessions"), audit: join(base, "audit.jsonl"), config: join(base, "config.json") };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function chmodQuiet(p: string, mode: number) {
|
|
139
|
+
try { chmodSync(p, mode); } catch { /* best-effort on non-POSIX filesystems */ }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function ensurePrivateDirs(p: LocalPaths) {
|
|
143
|
+
mkdirSync(p.sessions, { recursive: true });
|
|
144
|
+
chmodQuiet(p.base, 0o700);
|
|
145
|
+
chmodQuiet(p.sessions, 0o700);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function sessionKey(sessionId: string): string {
|
|
149
|
+
const id = sessionId || "unknown";
|
|
150
|
+
const clean = id.replace(SAFE_ID, "-").slice(0, 80).replace(/^[.-]+|[.-]+$/g, "") || "unknown";
|
|
151
|
+
const digest = createHash("sha256").update(id).digest("hex").slice(0, 12);
|
|
152
|
+
return `${clean}-${digest}.json`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function cleanupStale(p: LocalPaths, now = Date.now() / 1000) {
|
|
156
|
+
if (!existsSync(p.sessions)) return;
|
|
157
|
+
for (const name of readdirSync(p.sessions)) {
|
|
158
|
+
if (!name.endsWith(".json")) continue;
|
|
159
|
+
const f = join(p.sessions, name);
|
|
160
|
+
try {
|
|
161
|
+
if (now - statSync(f).mtimeMs / 1000 > STATE_TTL_SECONDS) unlinkSync(f);
|
|
162
|
+
} catch { /* raced with another hook */ }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface State { session_id: string; origins: string[]; updated_at: number; corrupt?: boolean; [k: string]: unknown }
|
|
167
|
+
|
|
168
|
+
function readState(file: string): State {
|
|
169
|
+
const data = JSON.parse(readFileSync(file, "utf8"));
|
|
170
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) throw new Error("state is not an object");
|
|
171
|
+
const origins = data.origins ?? [];
|
|
172
|
+
if (!Array.isArray(origins) || origins.some((x: unknown) => typeof x !== "string")) throw new Error("invalid origins");
|
|
173
|
+
data.origins = origins.slice(0, MAX_ORIGINS);
|
|
174
|
+
return data as State;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function loadState(sessionId: string, p: LocalPaths): [State, boolean] {
|
|
178
|
+
ensurePrivateDirs(p);
|
|
179
|
+
cleanupStale(p);
|
|
180
|
+
const file = join(p.sessions, sessionKey(sessionId));
|
|
181
|
+
if (!existsSync(file)) return [{ session_id: sessionId, origins: [], updated_at: Date.now() / 1000 }, true];
|
|
182
|
+
try {
|
|
183
|
+
return [readState(file), true];
|
|
184
|
+
} catch {
|
|
185
|
+
return [{ session_id: sessionId, origins: [], updated_at: Date.now() / 1000, corrupt: true }, false];
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function saveState(sessionId: string, state: State, p: LocalPaths) {
|
|
190
|
+
ensurePrivateDirs(p);
|
|
191
|
+
const file = join(p.sessions, sessionKey(sessionId));
|
|
192
|
+
// Parallel tool calls run hooks concurrently: merge with what's on disk so no origin is lost.
|
|
193
|
+
try {
|
|
194
|
+
const onDisk = readState(file);
|
|
195
|
+
state.origins = [...new Set([...onDisk.origins, ...state.origins])].slice(0, MAX_ORIGINS);
|
|
196
|
+
if (Array.isArray(onDisk.result_flags) || Array.isArray(state.result_flags)) {
|
|
197
|
+
const all = [...(Array.isArray(onDisk.result_flags) ? onDisk.result_flags : []),
|
|
198
|
+
...(Array.isArray(state.result_flags) ? state.result_flags : [])].filter((f) => typeof f === "string");
|
|
199
|
+
state.result_flags = [...new Set(all as string[])].sort();
|
|
200
|
+
}
|
|
201
|
+
} catch { /* absent or corrupt — ours wins */ }
|
|
202
|
+
state.updated_at = Date.now() / 1000;
|
|
203
|
+
const tmp = `${file}.${process.pid}.new`;
|
|
204
|
+
writeFileSync(tmp, sortedJson(state), { mode: 0o600 });
|
|
205
|
+
renameSync(tmp, file);
|
|
206
|
+
chmodQuiet(file, 0o600);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export type Mode = "monitor" | "enforce";
|
|
210
|
+
export type ModeSource = "config" | "default" | "env" | "dev_override" | "env_ignored" | "workspace" | "workspace_stale";
|
|
211
|
+
|
|
212
|
+
/** The workspace mode the shipper last heard (0600, beside the config, inside the tamper guard). */
|
|
213
|
+
export const WORKSPACE_FILE = "workspace.json";
|
|
214
|
+
|
|
215
|
+
/** Persist the workspace mode from an ingest answer for the hook to apply (atomic, private). */
|
|
216
|
+
export function writeWorkspaceMode(p: LocalPaths, wm: WorkspaceMode, now = Date.now()): void {
|
|
217
|
+
try {
|
|
218
|
+
const file = join(p.base, WORKSPACE_FILE), tmp = `${file}.${process.pid}.new`;
|
|
219
|
+
// received_at in epoch SECONDS: the Python hook shares this file (~/.xtrom/local) and reads seconds.
|
|
220
|
+
writeFileSync(tmp, JSON.stringify({ mode: wm.mode, expires_at: wm.expires_at, received_at: now / 1000 }), { mode: 0o600 });
|
|
221
|
+
renameSync(tmp, file);
|
|
222
|
+
chmodQuiet(file, 0o600);
|
|
223
|
+
} catch { /* the hook keeps what it had */ }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function workspaceDecision(p: LocalPaths, now: number): [Mode, ModeSource] | null {
|
|
227
|
+
let raw: Record<string, unknown>;
|
|
228
|
+
try { raw = JSON.parse(readFileSync(join(p.base, WORKSPACE_FILE), "utf8")); } catch { return null; }
|
|
229
|
+
const wm = raw && typeof raw === "object" ? parseWorkspaceMode({ workspace_mode: raw }) : null;
|
|
230
|
+
if (!wm) return null;
|
|
231
|
+
const at = typeof raw.received_at === "number" ? raw.received_at * 1000 : null; // seconds on disk
|
|
232
|
+
const [mode, source] = resolveWorkspaceMode("enforce", wm, at, now);
|
|
233
|
+
return [mode, source === "local" ? "workspace" : source];
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** [mode, source] the hook enforces in. The workspace mode wins when this install has heard one (source
|
|
237
|
+
* workspace, or workspace_stale for a monitor too old or past its end → enforce). Otherwise the config
|
|
238
|
+
* decides; XTROM_MODE=enforce can tighten it, and XTROM_MODE=monitor counts only under
|
|
239
|
+
* XTROM_DEV_OVERRIDES=1. source: config | default | env (tightened) | dev_override (loosened by the dev
|
|
240
|
+
* flag) | env_ignored (a refused loosening attempt — a tamper signal surfaced on the heartbeat).
|
|
241
|
+
* Mirrors state.resolve_mode in the Python SDK. */
|
|
242
|
+
export function resolveMode(p: LocalPaths, now = Date.now()): [Mode, ModeSource] {
|
|
243
|
+
const ws = workspaceDecision(p, now);
|
|
244
|
+
if (ws) return ws;
|
|
245
|
+
let cfg: Mode | null = null;
|
|
246
|
+
try {
|
|
247
|
+
const m = String(JSON.parse(readFileSync(p.config, "utf8")).mode ?? "").toLowerCase();
|
|
248
|
+
if (m === "monitor" || m === "enforce") cfg = m;
|
|
249
|
+
} catch { /* no config yet */ }
|
|
250
|
+
const env = (process.env.XTROM_MODE ?? "").trim().toLowerCase();
|
|
251
|
+
if (env === "enforce" && cfg !== "enforce") return ["enforce", "env"];
|
|
252
|
+
if (env === "monitor" && cfg !== "monitor") return devOverrides() ? ["monitor", "dev_override"] : [cfg ?? "enforce", "env_ignored"];
|
|
253
|
+
return [cfg ?? "enforce", cfg ? "config" : "default"];
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The enforced mode (kept for callers that only need the mode). */
|
|
257
|
+
export function configMode(p: LocalPaths): Mode {
|
|
258
|
+
return resolveMode(p)[0];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function localUser(): string | undefined {
|
|
262
|
+
for (const k of ["LOGNAME", "USER", "LNAME", "USERNAME"]) if (process.env[k]) return process.env[k];
|
|
263
|
+
try { return userInfo().username; } catch { return undefined; }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** This machine as attribution and the local inventory name it: the short host label, made safe. */
|
|
267
|
+
export function deviceLabel(): string {
|
|
268
|
+
let host = "";
|
|
269
|
+
try { host = (hostname() || "").split(".", 1)[0]; } catch { /* sandboxed */ }
|
|
270
|
+
return host.replace(SAFE_ID, "-").slice(0, 64).replace(/^[._-]+|[._-]+$/g, "") || "device";
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function localAttribution(client = "claude-code") {
|
|
274
|
+
return attribution(localUser(), deviceLabel(), client);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Deterministic JSON with sorted keys and Python json.dumps separators (", " / ": "). */
|
|
278
|
+
export function sortedJson(value: unknown): string {
|
|
279
|
+
const seen = new WeakSet<object>();
|
|
280
|
+
const enc = (v: unknown): string => {
|
|
281
|
+
if (v === null || v === undefined || typeof v === "function" || typeof v === "symbol") return "null";
|
|
282
|
+
if (typeof v === "bigint") return JSON.stringify(v.toString());
|
|
283
|
+
if (typeof v !== "object") return JSON.stringify(v) ?? "null";
|
|
284
|
+
if (seen.has(v)) return JSON.stringify("[circular]");
|
|
285
|
+
seen.add(v);
|
|
286
|
+
try {
|
|
287
|
+
if (Array.isArray(v)) return "[" + v.map(enc).join(", ") + "]";
|
|
288
|
+
const o = v as Json;
|
|
289
|
+
return "{" + Object.keys(o).sort().map((k) => JSON.stringify(k) + ": " + enc(o[k])).join(", ") + "}";
|
|
290
|
+
} finally {
|
|
291
|
+
seen.delete(v);
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
return enc(value);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function toolText(value: unknown): string {
|
|
298
|
+
try { return sortedJson(value); } catch { return String(value); }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function hostFromInput(input: Json): string | null {
|
|
302
|
+
for (const key of ["url", "uri", "endpoint", "host"]) {
|
|
303
|
+
const val = input[key];
|
|
304
|
+
if (typeof val === "string" && val) {
|
|
305
|
+
const m = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/.exec(val);
|
|
306
|
+
return m ? m[1] : val.split("/", 1)[0];
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function originForEvent(toolName: string, input: Json): string {
|
|
313
|
+
if (toolName === "Bash" || toolName === "PowerShell") {
|
|
314
|
+
const cmd = String(input.command ?? "");
|
|
315
|
+
const m = /https?:\/\/[^\s'")\\]+/i.exec(cmd);
|
|
316
|
+
if (m) {
|
|
317
|
+
const host = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/.exec(m[0])?.[1] || "unknown";
|
|
318
|
+
return `web:${host.slice(0, 48)}`;
|
|
319
|
+
}
|
|
320
|
+
return GH_RE.test(cmd) ? "tool:gh" : "tool:shell-fetch";
|
|
321
|
+
}
|
|
322
|
+
if (toolName === "WebFetch") return `web:${(hostFromInput(input) || "unknown").slice(0, 48)}`;
|
|
323
|
+
if (toolName === "WebSearch") return "web:search";
|
|
324
|
+
const bop = classifyBrowser(toolName, input);
|
|
325
|
+
if (bop?.kind === "navigate" && bop.url) {
|
|
326
|
+
const host = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/.exec(bop.url)?.[1] || "unknown";
|
|
327
|
+
return `web:${host.slice(0, 48)}`;
|
|
328
|
+
}
|
|
329
|
+
if (toolName === "computer") return "browser:computer";
|
|
330
|
+
if (toolName.startsWith("mcp__")) {
|
|
331
|
+
const parts = toolName.split("__");
|
|
332
|
+
return `mcp:${(parts.length > 2 ? parts[1] : "unknown").slice(0, 48)}`;
|
|
333
|
+
}
|
|
334
|
+
return `tool:${toolName}`;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Tool output that may carry someone else's instructions: web, every MCP server, shell fetches. */
|
|
338
|
+
export function isUntrustedSource(toolName: string, input: Json = {}): boolean {
|
|
339
|
+
if (toolName === "WebFetch" || toolName === "WebSearch" || toolName === "computer" || toolName.startsWith("mcp__")) return true;
|
|
340
|
+
if (toolName === "Bash" || toolName === "PowerShell") {
|
|
341
|
+
const cmd = String(input.command ?? "");
|
|
342
|
+
const a = bashAction(cmd);
|
|
343
|
+
return a === "http_fetch" || a === "http_post" || GH_RE.test(cmd);
|
|
344
|
+
}
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function bashAction(command: string): string {
|
|
349
|
+
if (/(^|[;&|()\s])git\s+push\b/i.test(command)) return "git_push";
|
|
350
|
+
if (OUTBOUND_RE.test(command)) {
|
|
351
|
+
if (/\b(curl|wget)\b.*\s(-d|--data|--data-raw|--form|-F|--upload-file|-T)\b/i.test(command)) return "http_post";
|
|
352
|
+
return "http_fetch";
|
|
353
|
+
}
|
|
354
|
+
if (DESTRUCTIVE_RE.test(command)) return "local_destructive";
|
|
355
|
+
return "local_shell";
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Browser op kind -> engine action (see hook.py). Navigation is an HTTP fetch for the engine.
|
|
359
|
+
const BROWSER_ACTION: Record<BrowserKind, string> = {
|
|
360
|
+
observe: "browser_observe", input: "browser_input", interact: "browser_interact", submit: "browser_submit",
|
|
361
|
+
navigate: "http_fetch", exec: "browser_exec", upload: "browser_upload", credentials: "browser_credentials",
|
|
362
|
+
};
|
|
363
|
+
const BROWSER_NON_SINK = new Set(["browser_observe", "browser_input", "browser_interact"]);
|
|
364
|
+
const BROWSER_PENDING = "browser_input_pending";
|
|
365
|
+
const PAGE_STORAGE_RE = /document\.cookie|localStorage|sessionStorage|indexedDB|cookieStore/i;
|
|
366
|
+
|
|
367
|
+
// ── Signal fidelity (reporting only — never changes a verdict). Mirrors hook.py signal_detail. ──
|
|
368
|
+
const SHELL_RANK = ["shell.read", "shell.vcs", "shell.build_test", "shell.fs_write", "shell.other"];
|
|
369
|
+
const SHELL_FS_WRITE = new Set(["mkdir", "touch", "cp", "mv", "ln"]);
|
|
370
|
+
const SHELL_BUILD = new Set(["tsc", "eslint", "prettier", "ruff", "mypy", "black", "pytest", "jest", "vitest", "make"]);
|
|
371
|
+
const MCP_VERB_CLASS: Array<[string, string[]]> = [
|
|
372
|
+
["delete", ["delete", "remove", "drop", "revoke", "archive", "close"]],
|
|
373
|
+
["send", ["send", "post", "publish", "push", "reply", "comment", "share", "invite", "transfer", "upload"]],
|
|
374
|
+
["execute", ["execute", "exec", "run", "trigger", "deploy"]],
|
|
375
|
+
["create", ["create", "add", "insert", "write"]],
|
|
376
|
+
["update", ["update", "edit", "set", "put", "patch", "rename", "move", "merge", "assign", "approve", "submit", "grant"]],
|
|
377
|
+
];
|
|
378
|
+
const SERVICE_RX = /^[A-Za-z0-9_.-]{1,48}$/;
|
|
379
|
+
const SECRET_TYPES_BY_INDEX = ["aws_key", "aws_key", "github_token", "openai_key", "private_key", "assignment", "db_url"];
|
|
380
|
+
|
|
381
|
+
function shellSegmentClass(seg: string): string {
|
|
382
|
+
const toks = (seg + " ").replace(ENV_PREFIX_RE, "").split(/\s+/).filter(Boolean);
|
|
383
|
+
if (!toks.length) return "shell.read";
|
|
384
|
+
const head = toks[0];
|
|
385
|
+
if (head === "git") return "shell.vcs";
|
|
386
|
+
if (head in SAFE_SUBCOMMANDS || SHELL_BUILD.has(head) || ["python", "python3", "node"].includes(head)) return "shell.build_test";
|
|
387
|
+
if (SHELL_FS_WRITE.has(head)) return "shell.fs_write";
|
|
388
|
+
return "shell.read";
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function shellClass(command: string): string {
|
|
392
|
+
const action = bashAction(command);
|
|
393
|
+
if (action === "git_push") return "shell.vcs_push";
|
|
394
|
+
if (action === "http_post" || action === "http_fetch") return "shell.network";
|
|
395
|
+
if (action === "local_destructive") return "shell.destructive";
|
|
396
|
+
if (!isKnownLocal(command)) return "shell.other";
|
|
397
|
+
const classes = command.split(SEGMENT_SPLIT_RE).map((x) => x.trim()).filter(Boolean).map(shellSegmentClass);
|
|
398
|
+
return classes.length ? classes.reduce((a, b) => (SHELL_RANK.indexOf(b) > SHELL_RANK.indexOf(a) ? b : a)) : "shell.read";
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export function signalDetail(toolName: string, input: Json): Json {
|
|
402
|
+
if (toolName === "Bash" || toolName === "PowerShell") {
|
|
403
|
+
const detail = shellClass(String(input.command ?? ""));
|
|
404
|
+
if (detail === "shell.destructive") return { action_detail: detail, sink_class: "destructive" };
|
|
405
|
+
if (detail === "shell.vcs_push" || detail === "shell.network") return { action_detail: detail, sink_class: "egress" };
|
|
406
|
+
return { action_detail: detail };
|
|
407
|
+
}
|
|
408
|
+
const fixed: Record<string, string> = {
|
|
409
|
+
Read: "file.read", Glob: "file.search", Grep: "file.search", Write: "file.write", Edit: "file.edit",
|
|
410
|
+
MultiEdit: "file.edit", NotebookEdit: "file.edit", WebFetch: "web.fetch", WebSearch: "web.search",
|
|
411
|
+
};
|
|
412
|
+
if (Object.hasOwn(fixed, toolName)) return { action_detail: fixed[toolName] };
|
|
413
|
+
const op = classifyBrowser(toolName, input);
|
|
414
|
+
if (op) {
|
|
415
|
+
const out: Json = { action_detail: `browser.${op.kind}` };
|
|
416
|
+
if (op.kind === "credentials") out.sink_class = "credential";
|
|
417
|
+
else if (op.kind === "submit" || op.kind === "upload") out.sink_class = "egress";
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
if (toolName.startsWith("mcp__")) {
|
|
421
|
+
const parts = toolName.split("__");
|
|
422
|
+
const server = parts.length > 2 ? parts[1] : null;
|
|
423
|
+
const words = new Set(mcpWords(parts[parts.length - 1]).toLowerCase().split("_"));
|
|
424
|
+
const verb = MCP_VERB_CLASS.find(([, vs]) => vs.some((v) => words.has(v)))?.[0] ?? "read";
|
|
425
|
+
const out: Json = { action_detail: `mcp.${verb}` };
|
|
426
|
+
if (server && SERVICE_RX.test(server)) out.target_service = server;
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
return { action_detail: "tool.other" };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** WHICH secret detectors fired (closed enum). Mirrors hook.py secret_types. */
|
|
433
|
+
export function secretTypes(text: string): string[] {
|
|
434
|
+
const found = new Set<string>();
|
|
435
|
+
SECRET_TYPES_BY_INDEX.forEach((t, i) => { if (SECRET_RX[i].test(text)) found.add(t); });
|
|
436
|
+
const rest = text.replace(URL_RE, " ");
|
|
437
|
+
if (SECRET_PATH_RE.test(rest)) found.add("path_hint");
|
|
438
|
+
if (!found.size && looksLikeSecret(rest)) found.add("high_entropy");
|
|
439
|
+
return [...found].sort();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export function classifyTool(toolName: string, input: Json): [string, boolean] {
|
|
443
|
+
if (toolName === "Read") return ["read_file", false];
|
|
444
|
+
if (toolName === "Glob" || toolName === "Grep") return ["list_dir", false];
|
|
445
|
+
if (toolName === "WebFetch" || toolName === "WebSearch") return ["http_fetch", false];
|
|
446
|
+
if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(toolName)) return ["write_file", true];
|
|
447
|
+
if (toolName === "Bash" || toolName === "PowerShell") return [bashAction(String(input.command ?? "")), true];
|
|
448
|
+
const bop = classifyBrowser(toolName, input);
|
|
449
|
+
if (bop) {
|
|
450
|
+
const action = BROWSER_ACTION[bop.kind];
|
|
451
|
+
return [action, !BROWSER_NON_SINK.has(action)];
|
|
452
|
+
}
|
|
453
|
+
if (toolName.startsWith("mcp__")) {
|
|
454
|
+
const write = WRITE_MCP_RE.test(mcpWords(toolName));
|
|
455
|
+
return [write ? "mcp_write" : "mcp_read", write];
|
|
456
|
+
}
|
|
457
|
+
return ["tool_call", true];
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function localPolicy(): Policy {
|
|
461
|
+
const p = defaultPolicy();
|
|
462
|
+
for (const a of ["local_shell", "local_destructive", "write_file", "git_push", "mcp_read", "mcp_write", "tool_call",
|
|
463
|
+
"execute_shell", "shell_unrecognized", ...Object.values(BROWSER_ACTION)]) p.capabilities.add(a);
|
|
464
|
+
Object.assign(p.sensitivity!, {
|
|
465
|
+
local_shell: 1, local_destructive: 2, write_file: 1, git_push: 2, mcp_read: 0, mcp_write: 2, tool_call: 2,
|
|
466
|
+
shell_unrecognized: 2, browser_observe: 0, browser_input: 0, browser_interact: 0, browser_submit: 2,
|
|
467
|
+
browser_exec: 2, browser_upload: 2, browser_credentials: 2,
|
|
468
|
+
});
|
|
469
|
+
return p;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function inputOf(payload: Json): Json {
|
|
473
|
+
const ti = payload.tool_input;
|
|
474
|
+
return ti && typeof ti === "object" && !Array.isArray(ti) ? (ti as Json) : {};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const typedSecret = (t: string) => matchesSecretPattern(t) || looksLikeSecret(t);
|
|
478
|
+
|
|
479
|
+
// Content that tries to steer the model taints the session even from a local file (see hook.py
|
|
480
|
+
// _STEERING_FLAGS); "truncated" is left out because large local files are routinely truncated.
|
|
481
|
+
const STEERING_FLAGS = new Set(["instruction", "hidden_unicode"]);
|
|
482
|
+
|
|
483
|
+
/** Secrets leaving by routes the engine can't see as egress (see hook.py secret_guard). */
|
|
484
|
+
export function secretGuard(toolName: string, input: Json, action: string, origins: string[]): Decision | null {
|
|
485
|
+
const tainted = origins.length > 0;
|
|
486
|
+
if ((toolName === "Bash" || toolName === "PowerShell") && (action === "local_shell" || action === "shell_unrecognized")) {
|
|
487
|
+
const cmd = String(input.command ?? "");
|
|
488
|
+
if (secretHint(cmd) && !(toolName === "Bash" && isKnownLocal(cmd))) {
|
|
489
|
+
return localDecision(tainted ? "BLOCK" : "STEP_UP", action, "local:secret",
|
|
490
|
+
"This command uses what looks like a secret and isn't a recognised local developer command, so it may "
|
|
491
|
+
+ "send it somewhere" + (tainted ? " after the session read untrusted content." : ". Confirm it's something you asked for."),
|
|
492
|
+
"local.secret_unrecognized_command", origins);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (action === "mcp_write" && matchesSecretPattern(toolText(input))) {
|
|
496
|
+
return localDecision(tainted ? "BLOCK" : "STEP_UP", action, "local:secret",
|
|
497
|
+
"This sends what looks like a credential through an MCP tool"
|
|
498
|
+
+ (tainted ? " after the session read untrusted content." : ". Confirm it's something you asked for."),
|
|
499
|
+
"local.secret_mcp_write", origins);
|
|
500
|
+
}
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Browser checks the engine can't express (see hook.py browser_guard). */
|
|
505
|
+
export function browserGuard(op: BrowserOp, origins: string[]): Decision | null {
|
|
506
|
+
if (op.kind === "upload" && op.files.some((f) => secretHint(f))) {
|
|
507
|
+
return localDecision("BLOCK", "browser_upload", "local:browser", "This uploads what looks like a credential "
|
|
508
|
+
+ "file to a web page. Xtrom blocks that; upload it yourself if it's really meant to go there.",
|
|
509
|
+
"local.browser_secret_upload", origins);
|
|
510
|
+
}
|
|
511
|
+
if (op.kind === "credentials" || (op.kind === "exec" && op.typed.some((t) => PAGE_STORAGE_RE.test(t)))) {
|
|
512
|
+
return localDecision("STEP_UP", "browser_credentials", "local:browser", "This reads or changes the site's "
|
|
513
|
+
+ "cookies or storage, where signed-in sessions live. Confirm it's something you asked for.",
|
|
514
|
+
"local.browser_credentials", origins);
|
|
515
|
+
}
|
|
516
|
+
if (op.typed.some(typedSecret)) {
|
|
517
|
+
const tainted = origins.length > 0;
|
|
518
|
+
return localDecision(tainted ? "BLOCK" : "STEP_UP", "browser_secret_entry", "local:browser",
|
|
519
|
+
"This puts what looks like a secret into a web page"
|
|
520
|
+
+ (tainted ? " after the session read untrusted content." : ". Confirm it's something you asked for."),
|
|
521
|
+
"local.browser_secret_entry", origins);
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export function decide(payload: Json, state: State, stateOk: boolean, client = "claude-code"): Decision {
|
|
527
|
+
const toolName = String(payload.tool_name ?? "");
|
|
528
|
+
const input = inputOf(payload);
|
|
529
|
+
let [action, isSink] = classifyTool(toolName, input);
|
|
530
|
+
if (state.origins.length && (toolName === "Bash" || toolName === "PowerShell") && action === "local_shell"
|
|
531
|
+
&& !(toolName === "Bash" && isKnownLocal(String(input.command ?? "")))) {
|
|
532
|
+
action = "shell_unrecognized";
|
|
533
|
+
}
|
|
534
|
+
const secretGuarded = secretGuard(toolName, input, action, [...state.origins]);
|
|
535
|
+
if (secretGuarded) return secretGuarded;
|
|
536
|
+
const bop = classifyBrowser(toolName, input);
|
|
537
|
+
if (bop) {
|
|
538
|
+
const guarded = browserGuard(bop, [...state.origins]);
|
|
539
|
+
if (guarded) return guarded;
|
|
540
|
+
// A click after data entry may be the one that sends it, whatever the button is called.
|
|
541
|
+
if (action === "browser_interact" && state[BROWSER_PENDING]) { action = "browser_submit"; isSink = true; }
|
|
542
|
+
}
|
|
543
|
+
const policy = localPolicy();
|
|
544
|
+
const text = toolText(input);
|
|
545
|
+
// Labeled directly when not a hint: trusted() would re-run the entropy backstop over URLs.
|
|
546
|
+
const val = (name: string, data: unknown, hint: boolean): Value =>
|
|
547
|
+
hint ? secret(data, `secret_hint:${name}`) : { data, label: { trust: "TRUSTED", isSecret: false, origin: `agent:${name}` } };
|
|
548
|
+
const args: Record<string, Value> = { input: val("input", text, secretHint(text)) };
|
|
549
|
+
if (action === "http_post" || action === "http_fetch") {
|
|
550
|
+
const cmd = String(input.command || input.url || text);
|
|
551
|
+
const m = /https?:\/\/[^\s'")]+/.exec(cmd);
|
|
552
|
+
if (m) args.url = val("url", m[0], false);
|
|
553
|
+
}
|
|
554
|
+
if (!stateOk && isSink) throw new Error("session taint state unreadable");
|
|
555
|
+
const tainted = state.origins.length > 0 && !LOCAL_ONLY.has(action);
|
|
556
|
+
return engineDecide(action, args, policy, 0, { identity: `${client}-local`, contextTainted: tainted });
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function auditLine(payload: Json, d: Decision, origins: string[], p: LocalPaths, mode: string, client: string) {
|
|
560
|
+
ensurePrivateDirs(p);
|
|
561
|
+
const line = {
|
|
562
|
+
ts: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
563
|
+
session_id: String(payload.session_id ?? ""),
|
|
564
|
+
tool_name: String(payload.tool_name ?? ""),
|
|
565
|
+
hook_event_name: String(payload.hook_event_name ?? ""),
|
|
566
|
+
verdict: d.verdict,
|
|
567
|
+
reason_code: d.reasonCode,
|
|
568
|
+
taint_origins: origins.slice(0, 16),
|
|
569
|
+
mode,
|
|
570
|
+
...localAttribution(client),
|
|
571
|
+
};
|
|
572
|
+
appendFileSync(p.audit, sortedJson(line) + "\n", { mode: 0o600 });
|
|
573
|
+
chmodQuiet(p.audit, 0o600);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export function readConfig(p: LocalPaths): Json {
|
|
577
|
+
try {
|
|
578
|
+
const c = JSON.parse(readFileSync(p.config, "utf8"));
|
|
579
|
+
return c && typeof c === "object" && !Array.isArray(c) ? c : {};
|
|
580
|
+
} catch { return {}; }
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** The session's untrusted origins as coarse telemetry tags ('web:evil.example' → 'web', 'mcp:jira' →
|
|
584
|
+
* 'mcp:jira'). Never a host, path or content — the raw origins stay in the local audit. */
|
|
585
|
+
function originTags(origins: string[], limit = 8): string[] {
|
|
586
|
+
const tags: string[] = [];
|
|
587
|
+
for (const o of origins) {
|
|
588
|
+
const t = originTag(o);
|
|
589
|
+
if (!tags.includes(t)) tags.push(t);
|
|
590
|
+
if (tags.length >= limit) break;
|
|
591
|
+
}
|
|
592
|
+
return tags;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function report(payload: Json, d: Decision, mode: string, p: LocalPaths, client: string,
|
|
596
|
+
contextFlags: string[] = [], origins: string[] = [], taintSource = false): void {
|
|
597
|
+
// Prefer the 0600 config written by `install --token` (the tamper guard keeps the agent out of
|
|
598
|
+
// ~/.xtrom); env vars are the fallback, but the agent's own shell can read those.
|
|
599
|
+
const cfg = readConfig(p);
|
|
600
|
+
const url = process.env.XTROM_CONTROL_PLANE_URL || (cfg.control_plane_url as string | undefined);
|
|
601
|
+
const token = process.env.XTROM_TOKEN || (cfg.token as string | undefined);
|
|
602
|
+
if (!url || !token) return;
|
|
603
|
+
try {
|
|
604
|
+
const event = decisionEvent(`${client}-local`, d, {
|
|
605
|
+
sessionId: String(payload.session_id ?? ""), mode, contextFlags, taintSource, ...localAttribution(client),
|
|
606
|
+
});
|
|
607
|
+
// The engine only knows proven per-arg taint (none here: the hook can't trace data across tool
|
|
608
|
+
// calls), so name the session's origins as coarse tags on a context-tainted decision.
|
|
609
|
+
const sources = event.taint_sources as unknown[] | undefined;
|
|
610
|
+
if (event.context_tainted && !(sources && sources.length) && origins.length) event.taint_sources = originTags(origins);
|
|
611
|
+
Object.assign(event, signalDetail(String(payload.tool_name ?? ""), inputOf(payload)));
|
|
612
|
+
if (event.secret_in_args) {
|
|
613
|
+
const kinds = secretTypes(toolText(inputOf(payload)));
|
|
614
|
+
if (kinds.length) {
|
|
615
|
+
event.secret_types = kinds;
|
|
616
|
+
// present vs LEAVING: a secret in a local edit is not the same event as one in a push/upload
|
|
617
|
+
event.secret_at_egress = event.sink_class === "egress";
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
// Decouple delivery from this short-lived hook process: a cold HTTPS round-trip outlives the hook,
|
|
621
|
+
// so spool the event locally (fast, durable) and ensure a detached shipper delivers it. Non-blocking.
|
|
622
|
+
if (spoolEvent(p, event)) ensureShipper(p);
|
|
623
|
+
} catch { /* never affects the developer's tool call */ }
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** A hook-level verdict that never reached the engine (tamper guard, fail-safe). */
|
|
627
|
+
function localDecision(verdict: Verdict, action: string, layer: string, reason: string, reasonCode: string, origins: string[]): Decision {
|
|
628
|
+
return {
|
|
629
|
+
verdict, action, layer, identity: "", reason, reasonCode, policyVersion: "", sinkClass: "",
|
|
630
|
+
// No proven per-arg taint at hook level; the session's taint is CONTEXT taint, as coarse tags.
|
|
631
|
+
tainted: false, taintSources: originTags(origins), secretInArgs: false,
|
|
632
|
+
contextTainted: origins.length > 0, latencyUs: 0,
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function failSafe(action: string, toolName: string, origins: string[]): Decision {
|
|
637
|
+
return localDecision("STEP_UP", action, "local:fail-safe",
|
|
638
|
+
`Xtrom local state unavailable; ask before running ${toolName || "tool"}`, "local.fail_safe_state", origins);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export function tamperCheck(toolName: string, input: Json, origins: string[]): Decision | null {
|
|
642
|
+
const text = toolText(input);
|
|
643
|
+
if (XTROM_HOME_RE.test(text)) {
|
|
644
|
+
return localDecision("BLOCK", "xtrom_tamper", "local:tamper", "Xtrom's own state, config and runtime "
|
|
645
|
+
+ "(~/.xtrom) are off-limits to the agent. Change them yourself in a terminal.", "local.tamper_protected", origins);
|
|
646
|
+
}
|
|
647
|
+
const shell = toolName === "Bash" || toolName === "PowerShell";
|
|
648
|
+
const writes = ["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(toolName);
|
|
649
|
+
if ((shell || writes) && XTROM_ENV_RE.test(text)) {
|
|
650
|
+
return localDecision("STEP_UP", "xtrom_env", "local:tamper", "This sets an Xtrom environment override, "
|
|
651
|
+
+ "which can relocate or loosen protection. Confirm it's something you asked for.", "local.env_override", origins);
|
|
652
|
+
}
|
|
653
|
+
const target = shell ? text : String(input.file_path ?? input.notebook_path ?? "");
|
|
654
|
+
if ((shell || writes) && SHELL_STARTUP_RE.test(target)) {
|
|
655
|
+
return localDecision("STEP_UP", "shell_startup", "local:tamper", "This changes a shell startup file or "
|
|
656
|
+
+ "persistent environment, which every later agent session inherits. Confirm it's something you asked for.",
|
|
657
|
+
"local.shell_startup", origins);
|
|
658
|
+
}
|
|
659
|
+
if (shell && SELF_MANAGE_RE.test(text)) {
|
|
660
|
+
return localDecision("STEP_UP", "xtrom_self_manage", "local:tamper", "This reinstalls, removes or reconnects "
|
|
661
|
+
+ "Xtrom, which can switch protection or reporting off. Confirm it's something you asked for.", "local.self_manage", origins);
|
|
662
|
+
}
|
|
663
|
+
if (AGENT_SETTINGS_RE.test(text) || (shell && SHELL_AGENT_DIR_RE.test(text) && SHELL_AGENT_FILE_RE.test(text))) {
|
|
664
|
+
return localDecision("STEP_UP", "agent_settings", "local:tamper", "This touches a coding agent's hook or "
|
|
665
|
+
+ "permission settings, which control whether Xtrom runs. Confirm it's something you asked for.",
|
|
666
|
+
"local.settings_change", origins);
|
|
667
|
+
}
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const decisionWord = (v: Verdict): "deny" | "ask" | null => (v === "BLOCK" ? "deny" : v === "STEP_UP" ? "ask" : null);
|
|
672
|
+
|
|
673
|
+
/** Canonical payload in, [deny|ask|null, reason] out. Records taint on PostToolUse. */
|
|
674
|
+
export async function evaluate(payload: Json, p: LocalPaths = paths(), client = "claude-code"): Promise<["deny" | "ask" | null, string]> {
|
|
675
|
+
const sessionId = String(payload.session_id || "unknown");
|
|
676
|
+
const [state, stateOk] = loadState(sessionId, p);
|
|
677
|
+
const origins = [...state.origins];
|
|
678
|
+
const mode = configMode(p);
|
|
679
|
+
const event = String(payload.hook_event_name ?? "");
|
|
680
|
+
const toolName = String(payload.tool_name ?? "");
|
|
681
|
+
if (event === POST) {
|
|
682
|
+
// What the tool RETURNED, reduced to flags. They ride on later decisions as `context_flags`; content
|
|
683
|
+
// that tries to steer the model (injected instructions, hidden Unicode) also taints, even from a local read.
|
|
684
|
+
const flags = "tool_response" in payload
|
|
685
|
+
? inspectResult(payload.tool_response).flags.filter((f) => f !== "truncated") : [];
|
|
686
|
+
const untrusted = isUntrustedSource(toolName, inputOf(payload)) || flags.some((f) => STEERING_FLAGS.has(f));
|
|
687
|
+
if (flags.length) {
|
|
688
|
+
const prior = Array.isArray(state.result_flags) ? (state.result_flags as string[]) : [];
|
|
689
|
+
state.result_flags = [...new Set([...prior, ...flags])].sort();
|
|
690
|
+
}
|
|
691
|
+
if (untrusted) {
|
|
692
|
+
const origin = originForEvent(toolName, inputOf(payload));
|
|
693
|
+
if (!origins.includes(origin)) origins.push(origin);
|
|
694
|
+
state.origins = origins.slice(0, MAX_ORIGINS);
|
|
695
|
+
delete state.corrupt;
|
|
696
|
+
const bop = classifyBrowser(toolName, inputOf(payload));
|
|
697
|
+
if (bop?.kind === "input") state[BROWSER_PENDING] = true;
|
|
698
|
+
else if (bop && ["interact", "submit", "navigate"].includes(bop.kind)) delete state[BROWSER_PENDING];
|
|
699
|
+
}
|
|
700
|
+
if (untrusted || flags.length) saveState(sessionId, state, p);
|
|
701
|
+
return [null, ""];
|
|
702
|
+
}
|
|
703
|
+
if (event !== PRE) return [null, ""];
|
|
704
|
+
let d: Decision;
|
|
705
|
+
try {
|
|
706
|
+
d = tamperCheck(toolName, inputOf(payload), origins) ?? decide(payload, state, stateOk, client);
|
|
707
|
+
} catch {
|
|
708
|
+
const [action, isSink] = classifyTool(toolName, inputOf(payload));
|
|
709
|
+
if (!isSink) return [null, ""];
|
|
710
|
+
d = failSafe(action, toolName, origins);
|
|
711
|
+
}
|
|
712
|
+
d = { ...d, identity: `${client}-local` };
|
|
713
|
+
try { auditLine(payload, d, origins, p, mode, client); } catch { /* audit is best-effort; the verdict still applies */ }
|
|
714
|
+
// A web/MCP/shell-fetch call is where untrusted content ENTERS the session: mark it a taint source.
|
|
715
|
+
report(payload, d, mode, p, client, Array.isArray(state.result_flags) ? state.result_flags as string[] : [],
|
|
716
|
+
origins, isUntrustedSource(toolName, inputOf(payload)));
|
|
717
|
+
if (mode === "monitor") return [null, ""];
|
|
718
|
+
return [decisionWord(d.verdict), d.reason || "Xtrom policy decision"];
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Any supported agent's native payload in, that agent's enforcement output out. */
|
|
722
|
+
export async function handleAgent(raw: Json, agent: string = DEFAULT_AGENT, eventHint: string | null = null,
|
|
723
|
+
p: LocalPaths = paths()): Promise<HookOutput> {
|
|
724
|
+
const adapter = getAdapter(agent);
|
|
725
|
+
const payload = adapter.normalize(raw, eventHint);
|
|
726
|
+
const [word, reason] = await evaluate(payload, p, adapter.client);
|
|
727
|
+
return adapter.render(String(payload.hook_event_name ?? ""), word, reason);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** Claude Code protocol: stdout JSON or null. */
|
|
731
|
+
export async function handle(payload: Json, p: LocalPaths = paths()): Promise<Json | null> {
|
|
732
|
+
return (await handleAgent(payload, "claude", null, p)).stdout;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
async function readStdin(): Promise<string> {
|
|
736
|
+
const chunks: Buffer[] = [];
|
|
737
|
+
for await (const c of process.stdin) chunks.push(c as Buffer);
|
|
738
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export function parseHookArgs(argv: string[]): { agent: string; event: string | null } {
|
|
742
|
+
let agent = DEFAULT_AGENT, event: string | null = null;
|
|
743
|
+
argv.forEach((tok, i) => {
|
|
744
|
+
for (const flag of ["--agent", "--event"]) {
|
|
745
|
+
const val = tok.startsWith(flag + "=") ? tok.slice(flag.length + 1) : tok === flag && i + 1 < argv.length ? argv[i + 1] : null;
|
|
746
|
+
if (val !== null) { if (flag === "--agent") agent = val; else event = val; }
|
|
747
|
+
}
|
|
748
|
+
});
|
|
749
|
+
return { agent, event };
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function emit(o: HookOutput): number {
|
|
753
|
+
if (o.stdout) process.stdout.write(JSON.stringify(o.stdout) + "\n");
|
|
754
|
+
if (o.stderr) process.stderr.write(o.stderr + "\n");
|
|
755
|
+
return o.exitCode;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** Hook entrypoint. Returns the process exit code (2 = block, for agents that deny by exit status). */
|
|
759
|
+
export async function main(argv: string[] = []): Promise<number> {
|
|
760
|
+
const { agent, event } = parseHookArgs(argv);
|
|
761
|
+
let payload: Json = {};
|
|
762
|
+
try {
|
|
763
|
+
const raw = await readStdin();
|
|
764
|
+
const parsed = raw.trim() ? JSON.parse(raw) : {};
|
|
765
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return 0;
|
|
766
|
+
payload = parsed;
|
|
767
|
+
return emit(await handleAgent(payload, agent, event));
|
|
768
|
+
} catch {
|
|
769
|
+
try {
|
|
770
|
+
const adapter = getAdapter(agent);
|
|
771
|
+
const canon = adapter.normalize(payload, event);
|
|
772
|
+
const [, isSink] = classifyTool(String(canon.tool_name ?? ""), inputOf(canon));
|
|
773
|
+
return emit(adapter.render(String(canon.hook_event_name ?? ""), isSink ? "ask" : null,
|
|
774
|
+
"Xtrom local hook failed safely; ask before running this sink tool"));
|
|
775
|
+
} catch { /* nothing safe left to do */ }
|
|
776
|
+
}
|
|
777
|
+
return 0;
|
|
778
|
+
}
|