hmcp-gateway 0.1.0 → 0.2.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/dist/guard.js ADDED
@@ -0,0 +1,975 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parse as parseYaml } from "yaml";
6
+ import { ApprovalBroker, ApprovalStore, AuditLog, EXPOSURE_RULE, NO_TENANT, classifyByName, decide, expandPath, exposureDeniedReason, parsePolicy, policyDigest, toolErrorText } from "hmcp-core";
7
+ import { scanResult } from "hmcp-scanner";
8
+ import { clientCommand } from "./adopt-cli.js";
9
+ import { readClientConfig } from "./client-config.js";
10
+ import { loadGatewayConfig } from "./config.js";
11
+ import { resolveProcessTenant } from "./gateway.js";
12
+ /**
13
+ * The Claude Code guard: the same policy the gateway enforces, applied to
14
+ * every tool Claude Code itself runs.
15
+ *
16
+ * The gateway only sees calls to MCP servers it fronts. Claude Code also has
17
+ * a terminal, file edits, web fetches, plugins and claude.ai connectors, none
18
+ * of which go through it. Claude Code runs a `PreToolUse` hook before every
19
+ * one of those, and this is what that hook asks: one call, one decision, from
20
+ * the same `decide()`, the same approvals database and the same audit log.
21
+ *
22
+ * What it deliberately does *not* do is say "allow". A hook that allows skips
23
+ * Claude Code's own permission prompts, and a guard that switched those off
24
+ * would be loosening what the person already had. So a call policy permits
25
+ * gets no opinion at all, and Claude Code's own rules still apply on top.
26
+ */
27
+ /** The audit `component`, and half of the approvals scope, for everything the guard writes. */
28
+ export const GUARD_COMPONENT = "guard:claude-code";
29
+ /**
30
+ * What a Claude Code tool is called in policy: `claude-code__Bash`,
31
+ * `claude-code__mcp__github__create_issue`. A rule matches it like any other
32
+ * tool (`match: "claude-code__Bash"`, `match: "claude-code__*"`).
33
+ *
34
+ * The hyphen is on purpose. An upstream name is lowercase letters, digits and
35
+ * underscores only, so no tool the gateway serves can ever be called this.
36
+ */
37
+ export const GUARD_TOOL_PREFIX = "claude-code__";
38
+ /** What the toolbox is called in Claude Code's config, unless `adopt --entry-name` said otherwise. */
39
+ export const GUARD_DEFAULT_ENTRY = "hmcp";
40
+ /**
41
+ * How long a held call waits for a person before Claude Code is told to try
42
+ * again. Longer than the gateway's, because a hook may take up to ten minutes
43
+ * where an MCP client gives up after one.
44
+ */
45
+ export const GUARD_DEFAULT_WAIT_SECONDS = 120;
46
+ /** Rule ids the guard writes that are not policy rules. */
47
+ export const GUARD_RELAY_RULE = "guard.own-toolbox";
48
+ export const GUARD_OUTCOME_RULE = "guard.outcome";
49
+ export const GUARD_ERROR_RULE = "guard.error";
50
+ /** A tool named like the toolbox's that is not one of its tools: checked, not exempt. */
51
+ export const GUARD_LOOKALIKE_RULE = "guard.lookalike-toolbox";
52
+ /** A Claude Code call that would change what the guard is, held for a person whatever policy says. */
53
+ export const GUARD_PROTECT_RULE = "guard.protect-self";
54
+ /**
55
+ * Built-in tools whose effect is known by name. Everything else, including
56
+ * every MCP tool, is classified by the same verb heuristic the gateway uses,
57
+ * and a name that says nothing stays unclassified.
58
+ *
59
+ * Bash is a write, always. A command line can do anything, and a short list
60
+ * of "read-only" prefixes (`ls`, `cat`, `git status`) is one `; rm -rf` away
61
+ * from being wrong. A person who wants it to run unasked writes a rule.
62
+ *
63
+ * Agent (Task) is a read because it does nothing itself: every call the
64
+ * subagent makes comes through this hook too.
65
+ *
66
+ * Claude Code's own session tools -- plan mode, asking the person a question,
67
+ * its task list, reading a background job's output, loading a skill -- change
68
+ * nothing outside the session, so they are reads. Left to the name heuristic
69
+ * they were unclassified, and under `on_unclassified: deny` Claude Code could
70
+ * not even leave plan mode. Stopping a background job it started is a read
71
+ * too, for the same reason; `kill` in the name would otherwise make it a
72
+ * delete. Scheduling work for later is a change.
73
+ *
74
+ * WebFetch is a read, and it can still carry data out in the address it
75
+ * fetches. The guard does not stop that unless a rule names
76
+ * `claude-code__WebFetch`; the README says so.
77
+ */
78
+ const BUILT_IN = {
79
+ Read: "read",
80
+ Glob: "read",
81
+ Grep: "read",
82
+ LS: "read",
83
+ NotebookRead: "read",
84
+ WebSearch: "read",
85
+ WebFetch: "read",
86
+ TodoWrite: "read",
87
+ ToolSearch: "read",
88
+ BashOutput: "read",
89
+ Agent: "read",
90
+ Task: "read",
91
+ AskUserQuestion: "read",
92
+ EnterPlanMode: "read",
93
+ ExitPlanMode: "read",
94
+ Skill: "read",
95
+ SlashCommand: "read",
96
+ TaskOutput: "read",
97
+ TaskCreate: "read",
98
+ TaskUpdate: "read",
99
+ TaskList: "read",
100
+ TaskGet: "read",
101
+ TaskStop: "read",
102
+ KillShell: "read",
103
+ KillBash: "read",
104
+ LSP: "read",
105
+ Monitor: "read",
106
+ CronCreate: "write",
107
+ CronDelete: "write",
108
+ ScheduleWakeup: "write",
109
+ Edit: "write",
110
+ Write: "write",
111
+ MultiEdit: "write",
112
+ NotebookEdit: "write",
113
+ Bash: "write"
114
+ };
115
+ /** The name and effect policy judges a Claude Code tool by. */
116
+ export function guardTool(toolName) {
117
+ const tool = `${GUARD_TOOL_PREFIX}${toolName}`;
118
+ const known = BUILT_IN[toolName];
119
+ if (known)
120
+ return { tool, effect: known };
121
+ // `mcp__<server>__<tool>`: the verb is in the tool's own name, after the server's.
122
+ if (toolName.startsWith("mcp__")) {
123
+ const rest = toolName.slice("mcp__".length);
124
+ const cut = rest.indexOf("__");
125
+ const own = cut === -1 ? rest : rest.slice(cut + 2);
126
+ return { tool, effect: own ? classifyByName(own, { namespaced: false }) : undefined };
127
+ }
128
+ return { tool, effect: classifyByName(toolName, { namespaced: false }) };
129
+ }
130
+ /** How Claude Code writes a server's name into its tool names: anything but letters, digits, `_` and `-` becomes `_`. */
131
+ function normalizedServerName(name) {
132
+ return name.replace(/[^A-Za-z0-9_-]/g, "_");
133
+ }
134
+ /** This build's own `cli.js`, which sits beside this file in `dist`: the program a local hook runs. */
135
+ function ownCliPath() {
136
+ return fileURLToPath(new URL("./cli.js", import.meta.url));
137
+ }
138
+ function realOrNull(path) {
139
+ try {
140
+ return realpathSync(path);
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
146
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
147
+ /** `[("serve",)? "-c"|"--config", <absolute path that is this gateway.yaml>]`, and nothing after it. */
148
+ function servesThisConfig(rest, toolbox) {
149
+ const tail = rest[0] === "serve" ? rest.slice(1) : rest;
150
+ if (tail.length !== 2)
151
+ return false;
152
+ const [flag, path] = tail;
153
+ if (flag !== "-c" && flag !== "--config")
154
+ return false;
155
+ // A relative path means whatever folder Claude Code was started in. Never ours.
156
+ if (!isAbsolute(path))
157
+ return false;
158
+ const want = realOrNull(toolbox.configPath);
159
+ return want !== null && realOrNull(path) === want;
160
+ }
161
+ /**
162
+ * Whether a server entry is exactly the toolbox, launched one of the two ways
163
+ * `adopt` and the console write it, and no other:
164
+ *
165
+ * - `npx -y hmcp-gateway@<version> [serve] -c <this gateway.yaml>`, with
166
+ * `npx` by name or by absolute path, and an exact pinned version;
167
+ * - `<absolute node> <this build's cli.js> [serve] -c <this gateway.yaml>`,
168
+ * the very file the guard's own hook runs.
169
+ *
170
+ * Anything that merely mentions the gateway -- a package whose name contains
171
+ * it, a script named after it, a `cli.js` a repository ships, a relative
172
+ * config path -- is not it.
173
+ */
174
+ function isOurToolboxEntry(entry, toolbox, ownCli) {
175
+ if (typeof entry !== "object" || entry === null)
176
+ return false;
177
+ const { command, args, url, type } = entry;
178
+ if (url !== undefined || (type !== undefined && type !== "stdio"))
179
+ return false;
180
+ if (typeof command !== "string" || !Array.isArray(args) || !args.every((a) => typeof a === "string"))
181
+ return false;
182
+ const words = args;
183
+ if (command === "npx" || (isAbsolute(command) && /^npx(\.cmd)?$/.test(basename(command)))) {
184
+ const pinned = /^hmcp-gateway@(.+)$/.exec(words[1] ?? "");
185
+ return words[0] === "-y" && pinned !== null && SEMVER.test(pinned[1]) && servesThisConfig(words.slice(2), toolbox);
186
+ }
187
+ if (isAbsolute(command) && /^node(\.exe)?$/i.test(basename(command))) {
188
+ const cli = words[0];
189
+ const want = realOrNull(ownCli);
190
+ return (cli !== undefined && isAbsolute(cli) && want !== null && realOrNull(cli) === want && servesThisConfig(words.slice(1), toolbox));
191
+ }
192
+ return false;
193
+ }
194
+ /** Every folder from `cwd` up to the root, nearest first: where a `.mcp.json` or a per-project entry may live. */
195
+ function ancestors(cwd) {
196
+ const out = [];
197
+ for (let at = resolve(cwd);; at = dirname(at)) {
198
+ out.push(at);
199
+ if (dirname(at) === at)
200
+ return out;
201
+ }
202
+ }
203
+ /**
204
+ * Every folder a project defining servers for this session could be in.
205
+ *
206
+ * Not only where Claude Code is now (`event.cwd`): it can `cd` out of the
207
+ * project, into a folder added with `--add-dir`, and a project's `.mcp.json`
208
+ * would then no longer be above it. So also the project Claude Code was
209
+ * started for (`CLAUDE_PROJECT_DIR`, which it sets for hooks) and the hook
210
+ * process's own folder, each with every folder above it, and each both as
211
+ * written and through its links -- `~/.claude.json` keys a project by
212
+ * whichever spelling Claude Code used.
213
+ */
214
+ function projectFolders(event, ctx) {
215
+ const roots = [
216
+ event.cwd,
217
+ ctx.claudeProjectDir !== undefined ? ctx.claudeProjectDir : process.env["CLAUDE_PROJECT_DIR"],
218
+ ctx.hookCwd ?? process.cwd()
219
+ ].filter((r) => typeof r === "string" && r !== "");
220
+ const out = new Set();
221
+ for (const root of roots) {
222
+ for (const dir of ancestors(root))
223
+ out.add(dir);
224
+ for (const dir of ancestors(realish(root)))
225
+ out.add(dir);
226
+ }
227
+ return [...out];
228
+ }
229
+ /**
230
+ * Whether a tool is one the toolbox itself serves, and so already decided by
231
+ * the gateway.
232
+ *
233
+ * A name is not enough: any server can be called `hmcp`, and a project's
234
+ * `.mcp.json` is written by whoever wrote the project. So the exemption needs
235
+ * three things, and anything less is a "lookalike" whose calls are checked
236
+ * like any other tool's:
237
+ *
238
+ * - the name has the toolbox's exact shape, `mcp__<entry>__<upstream>__<tool>`
239
+ * for one of this gateway's own upstreams (or `mcp__<entry>__<tool>`, with
240
+ * no further `__`, when it does not namespace);
241
+ * - the `<entry>` server is in the user's own config (`~/.claude.json`
242
+ * `mcpServers`, where `adopt` and the console put it) and is exactly the
243
+ * toolbox (`isOurToolboxEntry`);
244
+ * - no project defines `<entry>` at all -- not a `.mcp.json` in this folder
245
+ * or any folder above it, nor `projects[<folder>]` in `~/.claude.json` --
246
+ * whatever it says, because a project's files are whoever wrote the
247
+ * project's to write, and a copy of the real entry is still theirs;
248
+ * - no other server's name could produce the same prefix.
249
+ *
250
+ * Config that cannot be read exempts nothing.
251
+ */
252
+ function ownToolbox(name, event, ctx) {
253
+ const entry = (ctx.entryNames ?? [GUARD_DEFAULT_ENTRY]).find((e) => name.startsWith(`mcp__${e}__`));
254
+ if (entry === undefined)
255
+ return { kind: "other" };
256
+ const lookalike = (why) => ({ kind: "lookalike", why });
257
+ const toolbox = ctx.toolbox;
258
+ if (!toolbox)
259
+ return lookalike("the guard was given a policy, not a toolbox, so it has no toolbox's tools to recognise");
260
+ const rest = name.slice(`mcp__${entry}__`.length);
261
+ const shaped = toolbox.namespace
262
+ ? toolbox.upstreams.some((u) => rest.startsWith(`${u}__`) && rest.length > u.length + 2)
263
+ : rest.length > 0 && !rest.includes("__");
264
+ if (!shaped)
265
+ return lookalike(`"${name}" is not the name of one of this toolbox's tools`);
266
+ // [where the servers were read from, the servers, whether this place may hold the toolbox]
267
+ const sources = [];
268
+ try {
269
+ if (ctx.mcpServers) {
270
+ // An Agent SDK program's own `query({ mcpServers })`: the program's to define, like the user's config.
271
+ sources.push(["the Agent SDK's mcpServers", { ...ctx.mcpServers }, true]);
272
+ }
273
+ else {
274
+ const home = ctx.home ?? homedir();
275
+ const user = readClientConfig("user", { home, cwd: event.cwd ?? ctx.hookCwd ?? process.cwd() });
276
+ sources.push([`${user.target.path} (mcpServers)`, user.servers, true]);
277
+ const projects = (user.raw["projects"] ?? {});
278
+ for (const dir of projectFolders(event, ctx)) {
279
+ const local = projects[dir]?.mcpServers;
280
+ if (local !== undefined) {
281
+ if (typeof local !== "object" || local === null)
282
+ throw new Error(`projects[${dir}].mcpServers is not an object`);
283
+ sources.push([`${user.target.path} (projects[${dir}])`, local, false]);
284
+ }
285
+ const project = readClientConfig("project", { home, cwd: dir });
286
+ if (project.exists)
287
+ sources.push([project.target.path, project.servers, false]);
288
+ }
289
+ }
290
+ }
291
+ catch (err) {
292
+ return lookalike(`Claude Code's config could not be read (${err.message}), so the toolbox could not be confirmed`);
293
+ }
294
+ const ownCli = ctx.ownCliPath ?? ownCliPath();
295
+ let found = false;
296
+ for (const [where, servers, mayHoldToolbox] of sources) {
297
+ for (const [serverName, def] of Object.entries(servers)) {
298
+ if (serverName === entry) {
299
+ if (!mayHoldToolbox) {
300
+ return lookalike(`a project defines a "${entry}" server (${where}), so no "${entry}" tool is taken as the toolbox's own`);
301
+ }
302
+ if (!isOurToolboxEntry(def, toolbox, ownCli)) {
303
+ return lookalike(`the "${entry}" server in ${where} is not exactly this toolbox, so its tools are checked like any other`);
304
+ }
305
+ found = true;
306
+ }
307
+ else if (normalizedServerName(serverName).startsWith(`${entry}__`) || normalizedServerName(serverName) === entry) {
308
+ return lookalike(`the server "${serverName}" in ${where} makes tool names that look like this toolbox's`);
309
+ }
310
+ }
311
+ }
312
+ return found ? { kind: "own" } : lookalike(`no "${entry}" server in Claude Code's config runs this toolbox`);
313
+ }
314
+ /** One line, capped: the session id is Claude Code's, and it ends up in prose in the console. */
315
+ function flat(text, max = 128) {
316
+ if (text === undefined)
317
+ return undefined;
318
+ // eslint-disable-next-line no-control-regex
319
+ const one = text.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
320
+ if (one.length === 0)
321
+ return undefined;
322
+ return one.length > max ? one.slice(0, max) : one;
323
+ }
324
+ /** Who a record says made the call: Claude Code, or one of its subagents. */
325
+ function actorOf(event) {
326
+ const sub = flat(event.agent_type ?? (event.agent_id ? "subagent" : undefined), 64);
327
+ return sub ? `claude-code:${sub}` : "claude-code";
328
+ }
329
+ function toolNameOf(event) {
330
+ const name = event.tool_name;
331
+ if (typeof name !== "string" || name.length === 0 || name.length > 256) {
332
+ throw new Error("the hook event did not name the tool being called");
333
+ }
334
+ return name;
335
+ }
336
+ function argsOf(event) {
337
+ const input = event.tool_input ?? {};
338
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
339
+ throw new Error("the hook event's tool_input is not an object");
340
+ }
341
+ return input;
342
+ }
343
+ /**
344
+ * A path as the filesystem will see it, whether or not it exists yet: the
345
+ * nearest folder that does exist is resolved through its links, and the rest
346
+ * is put back on. So `/var/…` and `/private/var/…`, or a link into `~/.hmcp`,
347
+ * compare equal to what they point at.
348
+ */
349
+ function realish(path) {
350
+ const missing = [];
351
+ let at = resolve(path);
352
+ while (!existsSync(at) && dirname(at) !== at) {
353
+ missing.unshift(basename(at));
354
+ at = dirname(at);
355
+ }
356
+ return join(realOrNull(at) ?? at, ...missing);
357
+ }
358
+ function isUnder(path, dir) {
359
+ const rel = relative(dir, path);
360
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
361
+ }
362
+ /** The tools that write a file, and where each says which file. */
363
+ const FILE_WRITERS = {
364
+ Edit: ["file_path"],
365
+ Write: ["file_path"],
366
+ MultiEdit: ["file_path"],
367
+ NotebookEdit: ["notebook_path", "file_path"]
368
+ };
369
+ /**
370
+ * Why this call would change the guard itself, or null.
371
+ *
372
+ * The guard is a hook in Claude Code's settings, pointed at a config and
373
+ * writing to a database and a log. A model that can edit any of those, or run
374
+ * a command that does, can switch the guard off -- with a call policy may well
375
+ * allow, since editing files is what Claude Code is for. So these calls are
376
+ * held for a person before policy is asked, in observe mode too, the way the
377
+ * kill switch is applied in both modes:
378
+ *
379
+ * - Claude Code's settings (`.claude/settings.json`, `settings.local.json`,
380
+ * `managed-settings.json`) wherever they are, and `~/.claude.json`;
381
+ * - the guard's gateway.yaml and policy, its approvals database and audit
382
+ * log, and everything under `~/.hmcp`;
383
+ * - a terminal command that names any of those, or runs `guard uninstall`.
384
+ *
385
+ * The command check is a mention, not a parse: a command line can reach a
386
+ * file a hundred ways, and the honest promise is only that the plain ones ask.
387
+ */
388
+ function protectSelf(name, args, event, ctx) {
389
+ const home = ctx.home ?? homedir();
390
+ const cwd = event.cwd ?? process.cwd();
391
+ const hmcpDir = realish(join(home, ".hmcp"));
392
+ const own = (ctx.ownFiles ?? []).map(realish);
393
+ const fields = FILE_WRITERS[name];
394
+ if (fields) {
395
+ for (const field of fields) {
396
+ const raw = args[field];
397
+ if (typeof raw !== "string" || raw === "")
398
+ continue;
399
+ const path = realish(resolve(cwd, raw.startsWith("~/") ? join(home, raw.slice(2)) : raw));
400
+ const file = basename(path);
401
+ const what = basename(dirname(path)) === ".claude" && /^settings(\.local)?\.json$/.test(file)
402
+ ? "Claude Code's settings"
403
+ : file === "managed-settings.json"
404
+ ? "Claude Code's managed settings"
405
+ : file === ".claude.json"
406
+ ? "Claude Code's config"
407
+ : isUnder(path, hmcpDir)
408
+ ? "hardened-mcp's own files"
409
+ : own.some((f) => path === f || path.startsWith(`${f}-`))
410
+ ? "the guard's own config, database or log"
411
+ : null;
412
+ if (what)
413
+ return `this would change ${what} (${path}), which can switch the guard off, so a person has to approve it`;
414
+ }
415
+ return null;
416
+ }
417
+ if (name === "Bash") {
418
+ const command = typeof args["command"] === "string" ? args["command"] : "";
419
+ if (/\bguard\s+uninstall\b/.test(command))
420
+ return "this command would switch the guard off, so a person has to approve it";
421
+ /*
422
+ * Claude Code's own folder, named as a whole path segment: `~/.claude`,
423
+ * `$HOME/.claude/…`, `cd .claude`. Not `.clauderc`, and not a word that
424
+ * merely ends in it.
425
+ */
426
+ const claudeDir = /(?:^|[\s/'"`=:;(|&<>])\.claude(?=$|[\s/'"`;|&)<>])/;
427
+ if (claudeDir.test(command)) {
428
+ return "this command names Claude Code's .claude folder, which holds the guard's hooks, so a person has to approve it";
429
+ }
430
+ const mentions = [".claude/settings", `.claude${sep}settings`, ".claude.json", "managed-settings"];
431
+ for (const file of ctx.ownFiles ?? []) {
432
+ mentions.push(file, realish(file));
433
+ if (isUnder(file, home))
434
+ mentions.push(`~/${relative(home, file)}`);
435
+ // Named bare, from its own folder.
436
+ if (realish(cwd) === realish(dirname(file)))
437
+ mentions.push(basename(file));
438
+ }
439
+ const hit = mentions.find((m) => m !== "" && command.includes(m));
440
+ if (hit)
441
+ return `this command names ${hit}, which can switch the guard off, so a person has to approve it`;
442
+ /*
443
+ * The person's own hmcp folder, and only that: `~/.hmcp`, `$HOME/.hmcp`,
444
+ * or its absolute path, ending there or at a `/`. A project's
445
+ * `packages/web/.hmcp/backups` or a `~/.hmcprc` is somebody else's file.
446
+ */
447
+ const ends = "(?=$|[\\s/'\"`;|&)<>])";
448
+ const hmcp = [
449
+ "~/\\.hmcp",
450
+ "\\$HOME/\\.hmcp",
451
+ "\\$\\{HOME\\}/\\.hmcp",
452
+ escapeRegExp(join(home, ".hmcp")),
453
+ escapeRegExp(realish(join(home, ".hmcp")))
454
+ ];
455
+ if (new RegExp(`(?:${hmcp.join("|")})${ends}`).test(command)) {
456
+ return "this command names hardened-mcp's own folder (~/.hmcp), which can switch the guard off, so a person has to approve it";
457
+ }
458
+ }
459
+ return null;
460
+ }
461
+ function escapeRegExp(text) {
462
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
463
+ }
464
+ /**
465
+ * What the model is told when the guard itself could not decide.
466
+ *
467
+ * A guard that cannot work refuses every call, including the terminal and the
468
+ * file edits someone would use to fix it from inside Claude Code. So the
469
+ * refusal always carries the way out, for the person to do by hand.
470
+ */
471
+ export function guardFailureReason(err, wayOut) {
472
+ return (`hardened-mcp could not check this call (${err?.message ?? String(err)}), so it was blocked ` +
473
+ `rather than let through unchecked. Tell the person their toolbox's Claude Code guard needs a look. ` +
474
+ (wayOut ?? guardWayOut({})));
475
+ }
476
+ /**
477
+ * How to switch the guard off from outside Claude Code, in words for a person.
478
+ *
479
+ * The command is the one that runs this guard (a published version, or this
480
+ * build on disk), so it works whichever the hook was installed with.
481
+ */
482
+ export function guardWayOut(where) {
483
+ const launch = clientCommand({});
484
+ const cli = [launch.command, ...launch.args].join(" ");
485
+ const home = where.home ?? homedir();
486
+ if (where.scope === "user" || (where.scope === "project" && where.projectDir)) {
487
+ const settings = where.scope === "user"
488
+ ? join(home, ".claude", "settings.json")
489
+ : join(where.projectDir, ".claude", "settings.local.json");
490
+ const flags = where.scope === "user" ? "--scope user" : `--scope project --project-dir ${where.projectDir}`;
491
+ return (`To turn the guard off, run \`${cli} guard uninstall ${flags}\` in a terminal, or delete the hmcp-gateway ` +
492
+ `guard entries under "hooks" in ${settings}.`);
493
+ }
494
+ return (`To turn the guard off, run \`${cli} guard uninstall\` in a terminal (with \`--scope project --project-dir <folder>\` ` +
495
+ `for a project), or delete the hmcp-gateway guard entries under "hooks" in your Claude Code settings.`);
496
+ }
497
+ /**
498
+ * Decides one `PreToolUse` event.
499
+ *
500
+ * Mirrors `enforceCall` in core, step for step, with one difference: the call
501
+ * is not run here. A permitted call is recorded as `relayed` and handed back
502
+ * to Claude Code, and the `PostToolUse` hook records what became of it.
503
+ *
504
+ * Fails closed: anything that throws is a refusal, never a pass.
505
+ */
506
+ export async function guardDecision(event, ctx,
507
+ /** Aborted when whoever runs the hook gives up on it (the Agent SDK's timeout): the wait stops, and it is a refusal. */
508
+ signal) {
509
+ const started = Date.now();
510
+ let toolForRecord = "(unknown)";
511
+ try {
512
+ const { policy, audit } = ctx;
513
+ const name = toolNameOf(event);
514
+ const args = argsOf(event);
515
+ const actor = actorOf(event);
516
+ const session = flat(event.session_id) ?? "unknown";
517
+ const { args_hash, args_redacted } = audit.prepareArgs(args);
518
+ const tenant = ctx.tenantValue ?? NO_TENANT;
519
+ const base = { args_hash, args_redacted, tenant: ctx.tenantValue ?? null, actor, session };
520
+ /*
521
+ * The toolbox's own tools have already been decided by the gateway, and
522
+ * checking them here as well would ask a person twice about one call.
523
+ * Recorded, so the log still says the guard saw it. A name that only
524
+ * looks like the toolbox's is checked below, and noted beside the
525
+ * decision (see `record`).
526
+ */
527
+ const own = ownToolbox(name, event, ctx);
528
+ if (own.kind === "own") {
529
+ toolForRecord = `${GUARD_TOOL_PREFIX}${name}`;
530
+ audit.append({
531
+ ...base,
532
+ tool: toolForRecord,
533
+ effect: null,
534
+ decision: "allow",
535
+ rule_id: GUARD_RELAY_RULE,
536
+ reason: "one of the toolbox's own tools: the toolbox decides it, so the guard lets it through unchecked",
537
+ outcome: "relayed",
538
+ duration_ms: Date.now() - started
539
+ });
540
+ return { kind: "pass" };
541
+ }
542
+ const mapped = guardTool(name);
543
+ toolForRecord = mapped.tool;
544
+ const scope = { component: GUARD_COMPONENT, tenant };
545
+ const scoped = ctx.store.scoped(scope);
546
+ const switchedOff = scoped.toolExposure(mapped.tool);
547
+ let decision = decide({
548
+ tool: mapped.tool,
549
+ effect: mapped.effect,
550
+ args,
551
+ policy,
552
+ tenant: policy.tenant ? { expected: ctx.tenantValue } : undefined,
553
+ ...(switchedOff ? { disabled: true, disabledReason: exposureDeniedReason(switchedOff) } : {})
554
+ });
555
+ /*
556
+ * A call that would change the guard itself waits for a person, whatever
557
+ * policy said -- unless policy refuses it outright, which is stricter. In
558
+ * observe mode a refusal is not applied, so there the hold is.
559
+ */
560
+ const protect = protectSelf(name, args, event, ctx);
561
+ const refusedAnyway = decision.kind === "deny" && (decision.ruleId === EXPOSURE_RULE || policy.enforcement !== "observe");
562
+ if (protect && !refusedAnyway) {
563
+ decision = { kind: "approve", effect: decision.effect ?? mapped.effect ?? "write", ruleId: GUARD_PROTECT_RULE, reason: protect };
564
+ }
565
+ /*
566
+ * One record per decision. For a name that only looks like the toolbox's,
567
+ * a note goes beside it saying why it was not exempt: recorded as relayed
568
+ * with the decision that was made, so it is not a second refusal in the
569
+ * log -- or, for an allowed call, a refusal at all.
570
+ */
571
+ const record = (entry) => {
572
+ if (own.kind === "lookalike") {
573
+ audit.append({
574
+ ...base,
575
+ tool: mapped.tool,
576
+ effect: decision.effect,
577
+ decision: entry.decision,
578
+ rule_id: GUARD_LOOKALIKE_RULE,
579
+ reason: `not exempt as the toolbox's own tool: ${own.why}`,
580
+ outcome: "relayed",
581
+ duration_ms: Date.now() - started
582
+ });
583
+ }
584
+ return audit.append({ ...base, tool: mapped.tool, effect: decision.effect, duration_ms: Date.now() - started, ...entry });
585
+ };
586
+ /*
587
+ * Observe mode, exactly as the gateway reads it: recorded, not applied --
588
+ * except the kill switch, and the hold on a call that would switch the
589
+ * guard off.
590
+ */
591
+ const observing = policy.enforcement === "observe" && decision.ruleId !== EXPOSURE_RULE && decision.ruleId !== GUARD_PROTECT_RULE;
592
+ if (!observing && decision.kind === "deny") {
593
+ record({ decision: "deny", rule_id: decision.ruleId, reason: decision.reason, outcome: "denied" });
594
+ return {
595
+ kind: "deny",
596
+ reason: `Refused by policy (${decision.ruleId}): ${decision.agentReason ?? decision.reason}. ` +
597
+ `The person's protection settings in hardened-mcp block this, so it cannot be approved; trying again ` +
598
+ `will not help. Tell them it was blocked.`
599
+ };
600
+ }
601
+ let approvalId = null;
602
+ let grantId = null;
603
+ if (!observing && decision.kind === "approve") {
604
+ /*
605
+ * The approvals machinery the gateway uses, unchanged: the request is
606
+ * bound to the tool and its exact arguments, parked once in the
607
+ * database the console reads, and released only for that binding.
608
+ * There is no host to prompt from a hook, so it is always the
609
+ * out-of-band ("cli") path -- unless approvals are switched off, which
610
+ * stays a refusal.
611
+ */
612
+ /*
613
+ * The broker parks the request and returns at once (`wait_seconds: 0`);
614
+ * the waiting happens here, so it can stop the moment the hook's caller
615
+ * gives up. The broker's own wait could not be interrupted, and a wait
616
+ * that outlived the hook would go on to spend an approval given after
617
+ * the call had already been refused -- leaving the retry it was meant
618
+ * for to ask again.
619
+ */
620
+ const now = ctx.now ?? Date.now;
621
+ const broker = new ApprovalBroker({
622
+ config: { ...policy.approvals, mode: policy.approvals.mode === "deny" ? "deny" : "cli", wait_seconds: 0 },
623
+ store: scoped,
624
+ redactKeys: policy.audit.redact,
625
+ now
626
+ });
627
+ const request = {
628
+ tool: mapped.tool,
629
+ effect: decision.effect,
630
+ args,
631
+ reason: decision.reason,
632
+ actor,
633
+ session,
634
+ target: `Claude Code → ${name}`,
635
+ ruleId: decision.ruleId,
636
+ policyDigest: policyDigest(policy),
637
+ ...(decision.violations ? { violations: decision.violations } : {}),
638
+ ...(decision.heldArgs ? { heldArgs: decision.heldArgs } : {})
639
+ };
640
+ let outcome = await broker.request(request);
641
+ if (!outcome.granted && outcome.parked && outcome.approvalId) {
642
+ const deadline = now() + (ctx.waitSeconds ?? GUARD_DEFAULT_WAIT_SECONDS) * 1000;
643
+ const decided = await waitForDecision(scoped, outcome.approvalId, deadline, now, signal);
644
+ // Asked again, so the broker spends the approval (or reports the "no") exactly as it would on a retry.
645
+ if (decided && !signal?.aborted)
646
+ outcome = await broker.request(request);
647
+ }
648
+ if (!outcome.granted) {
649
+ record({
650
+ decision: "approve",
651
+ rule_id: decision.ruleId,
652
+ reason: decision.violations?.length ? `${outcome.reason} — ${decision.reason}` : outcome.reason,
653
+ outcome: outcome.refusedByPerson ? "denied" : "pending-approval",
654
+ approval_id: outcome.approvalId
655
+ });
656
+ return {
657
+ kind: "deny",
658
+ reason: [
659
+ outcome.refusedByPerson
660
+ ? `Refused by the person: ${outcome.reason}`
661
+ : `Approval required (${decision.ruleId}): ${outcome.reason}`,
662
+ outcome.instructions
663
+ ]
664
+ .filter(Boolean)
665
+ .join("\n\n")
666
+ };
667
+ }
668
+ approvalId = outcome.approvalId;
669
+ grantId = outcome.via === "standing" ? (outcome.grantId ?? null) : null;
670
+ }
671
+ /*
672
+ * Permitted. As in `enforceCall`: if policy says a call must not run
673
+ * unrecorded, check the record can be written before handing it on.
674
+ * Throwing here is a refusal, by the catch below.
675
+ */
676
+ if (policy.audit.enabled && policy.audit.on_failure === "refuse")
677
+ audit.assertWritable();
678
+ record({
679
+ ...(observing ? { observe: true } : {}),
680
+ decision: decision.kind,
681
+ rule_id: grantId ? "standing_grant.use" : decision.ruleId,
682
+ reason: grantId ? `released by standing grant ${grantId} without asking a human: ${decision.reason}` : decision.reason,
683
+ outcome: "relayed",
684
+ approval_id: approvalId,
685
+ grant_id: grantId
686
+ });
687
+ return { kind: "pass" };
688
+ }
689
+ catch (err) {
690
+ try {
691
+ ctx.audit.append({
692
+ tool: toolForRecord,
693
+ decision: "deny",
694
+ rule_id: GUARD_ERROR_RULE,
695
+ reason: ctx.audit.prepareText(`the guard could not decide this call: ${err?.message ?? String(err)}`),
696
+ outcome: "error",
697
+ actor: actorOf(event),
698
+ session: flat(event.session_id) ?? "unknown",
699
+ duration_ms: Date.now() - started
700
+ });
701
+ }
702
+ catch {
703
+ /* the refusal below stands whether or not it could be written down */
704
+ }
705
+ return { kind: "deny", reason: guardFailureReason(err, ctx.wayOut) };
706
+ }
707
+ }
708
+ const WAIT_POLL_MS = 250;
709
+ /**
710
+ * Polls one parked request until a person decides it, the deadline passes, or
711
+ * `signal` aborts. Returns whether it was decided; never consumes anything.
712
+ */
713
+ async function waitForDecision(scoped, id, deadline, now, signal) {
714
+ for (;;) {
715
+ if (signal?.aborted)
716
+ return false;
717
+ const state = scoped.get(id)?.state;
718
+ if (state === "granted" || state === "used" || state === "denied")
719
+ return true;
720
+ if (state !== "pending")
721
+ return false;
722
+ const left = deadline - now();
723
+ if (left <= 0)
724
+ return false;
725
+ await new Promise((done) => {
726
+ const timer = setTimeout(finish, Math.min(WAIT_POLL_MS, left));
727
+ function finish() {
728
+ clearTimeout(timer);
729
+ signal?.removeEventListener("abort", finish);
730
+ done();
731
+ }
732
+ signal?.addEventListener("abort", finish, { once: true });
733
+ });
734
+ }
735
+ }
736
+ /**
737
+ * Records what became of a call Claude Code ran (`PostToolUse`).
738
+ *
739
+ * The result itself is not kept: it is whatever a file or a command printed.
740
+ * It is scanned, the way the gateway scans an upstream's results, and only
741
+ * what was found is written down. Never throws: the call has already happened,
742
+ * and there is nothing left to refuse.
743
+ */
744
+ export function guardOutcome(event, ctx) {
745
+ try {
746
+ const name = toolNameOf(event);
747
+ const args = argsOf(event);
748
+ const { args_hash, args_redacted } = ctx.audit.prepareArgs(args);
749
+ const mapped = guardTool(name);
750
+ const response = event.tool_response;
751
+ const failed = event.hook_event_name === "PostToolUseFailure" ||
752
+ (typeof response === "object" &&
753
+ response !== null &&
754
+ (response.is_error === true || response.success === false)) ||
755
+ toolErrorText(response) !== null;
756
+ const results = ctx.policy.results;
757
+ const scan = results.on_injection === "allow" && results.on_secret === "allow" ? null : scanResult(response);
758
+ const found = scan && !scan.clean
759
+ ? [
760
+ ...(scan.injection.length > 0 ? [`instructions (${[...new Set(scan.injection.map((h) => h.patternId))].join(", ")})`] : []),
761
+ ...(scan.secrets.length > 0 ? [`secrets (${scan.secrets.map((s) => s.id).join(", ")})`] : [])
762
+ ].join(" and ")
763
+ : null;
764
+ ctx.audit.append({
765
+ tool: mapped.tool,
766
+ effect: mapped.effect ?? null,
767
+ decision: "allow",
768
+ rule_id: GUARD_OUTCOME_RULE,
769
+ reason: `Claude Code reported that ${name} ${failed ? "failed" : "finished"}` +
770
+ (found ? `; what it returned contains ${found}, recorded and passed on` : ""),
771
+ outcome: failed ? "error" : "completed",
772
+ // `PostToolUseFailure` says what went wrong in `error`; redacted, and cut short like an upstream's.
773
+ ...(typeof event.error === "string" && event.error
774
+ ? { error: ctx.audit.prepareText(event.error.length > 500 ? `${event.error.slice(0, 500)}…` : event.error, args) }
775
+ : {}),
776
+ args_hash,
777
+ args_redacted,
778
+ tenant: ctx.tenantValue ?? null,
779
+ actor: actorOf(event),
780
+ session: flat(event.session_id) ?? "unknown"
781
+ });
782
+ }
783
+ catch (err) {
784
+ process.stderr.write(`[hmcp guard] could not record the outcome: ${err?.message ?? String(err)}\n`);
785
+ }
786
+ }
787
+ /** The hook's answer, in Claude Code's shape. `{}` is no opinion. */
788
+ export function hookOutput(verdict) {
789
+ if (verdict.kind === "pass")
790
+ return {};
791
+ return {
792
+ hookSpecificOutput: {
793
+ hookEventName: "PreToolUse",
794
+ permissionDecision: "deny",
795
+ permissionDecisionReason: verdict.reason
796
+ }
797
+ };
798
+ }
799
+ /**
800
+ * Opens the policy, the approvals database and the audit log a guard uses.
801
+ *
802
+ * `configPath` is a toolbox's gateway.yaml or a policy.yaml on its own. Every
803
+ * relative path inside it means "beside this file", as it does for the
804
+ * gateway (see `openGateway`), so the guard and the toolbox share one log
805
+ * and one database and the console shows both.
806
+ */
807
+ export function openGuard(configPath) {
808
+ const full = expandPath(configPath);
809
+ const base = dirname(full);
810
+ const raw = parseYaml(readFileSync(full, "utf8"));
811
+ const isGateway = typeof raw === "object" && raw !== null && "upstreams" in raw;
812
+ const gateway = isGateway ? loadGatewayConfig(full, { typed: true }) : undefined;
813
+ const policy = gateway ? gateway.policy : parsePolicy(raw, full);
814
+ const toolbox = gateway
815
+ ? { configPath: full, upstreams: gateway.config.upstreams.map((u) => u.name), namespace: gateway.config.namespace }
816
+ : undefined;
817
+ const tenantValue = resolveProcessTenant(policy);
818
+ const store = new ApprovalStore(policy.approvals.store_path, base);
819
+ // What a Claude Code tool may not change unasked (see `protectSelf`).
820
+ const ownFiles = [
821
+ full,
822
+ ...(gateway && typeof gateway.config.policy === "string" ? [expandPath(gateway.config.policy, base)] : []),
823
+ store.path,
824
+ expandPath(policy.audit.path, base)
825
+ ];
826
+ return {
827
+ policy,
828
+ base,
829
+ context: (options = {}) => ({
830
+ policy,
831
+ store,
832
+ tenantValue,
833
+ toolbox,
834
+ ownFiles,
835
+ ...(options.ownCliPath !== undefined ? { ownCliPath: options.ownCliPath } : {}),
836
+ ...(options.hookCwd !== undefined ? { hookCwd: options.hookCwd } : {}),
837
+ ...(options.claudeProjectDir !== undefined ? { claudeProjectDir: options.claudeProjectDir } : {}),
838
+ ...(options.home !== undefined ? { home: options.home } : {}),
839
+ ...(options.mcpServers !== undefined ? { mcpServers: options.mcpServers } : {}),
840
+ ...(options.wayOut !== undefined ? { wayOut: options.wayOut } : {}),
841
+ audit: new AuditLog({
842
+ config: policy.audit,
843
+ component: GUARD_COMPONENT,
844
+ actor: "claude-code",
845
+ ...(options.session ? { session: options.session } : {}),
846
+ cwd: base
847
+ }),
848
+ ...(options.waitSeconds !== undefined ? { waitSeconds: options.waitSeconds } : {}),
849
+ ...(options.entryNames ? { entryNames: options.entryNames } : {})
850
+ }),
851
+ close: () => store.close()
852
+ };
853
+ }
854
+ /** What `policy.approvals.wait_seconds` says, or the guard's own default when it says nothing. */
855
+ export function guardWaitSeconds(policy) {
856
+ return policy.approvals.wait_seconds > 0 ? policy.approvals.wait_seconds : GUARD_DEFAULT_WAIT_SECONDS;
857
+ }
858
+ /**
859
+ * One run of `hmcp-gateway guard`: the hook event in, Claude Code's answer out.
860
+ *
861
+ * Before a call (`pre`), every way this can go wrong -- no config, a config
862
+ * that does not load, input that is not a hook event -- is answered with a
863
+ * refusal, exit 0, so Claude Code reads it as one. After a call (`post`)
864
+ * nothing is left to refuse, so a failure is only reported on stderr.
865
+ */
866
+ export async function runGuardHook(options) {
867
+ const post = options.event === "post";
868
+ const wayOut = guardWayOut({ scope: options.scope, projectDir: options.projectDir, home: options.home });
869
+ const refuse = (err) => ({
870
+ stdout: `${JSON.stringify(hookOutput({ kind: "deny", reason: guardFailureReason(err, wayOut) }))}\n`,
871
+ stderr: `[hmcp guard] ${err?.message ?? String(err)}\n`,
872
+ exitCode: 0
873
+ });
874
+ let opened;
875
+ try {
876
+ if (options.event !== undefined && options.event !== "pre" && options.event !== "post") {
877
+ throw new Error(`--event must be pre or post, not ${JSON.stringify(options.event)}`);
878
+ }
879
+ if (!options.config)
880
+ throw new Error("no --config was given, so there is no policy to check against");
881
+ let event;
882
+ try {
883
+ event = JSON.parse(options.input);
884
+ }
885
+ catch {
886
+ throw new Error("what Claude Code sent was not JSON");
887
+ }
888
+ if (typeof event !== "object" || event === null || Array.isArray(event)) {
889
+ throw new Error("what Claude Code sent was not a hook event");
890
+ }
891
+ const expected = post ? ["PostToolUse", "PostToolUseFailure"] : ["PreToolUse"];
892
+ if (event.hook_event_name !== undefined && !expected.includes(event.hook_event_name)) {
893
+ throw new Error(`this hook is for ${expected[0]}, and was run for ${String(event.hook_event_name)}`);
894
+ }
895
+ const wait = options.waitSeconds === undefined ? undefined : Number(options.waitSeconds);
896
+ if (wait !== undefined && (!Number.isInteger(wait) || wait < 0)) {
897
+ throw new Error(`--wait must be a whole number of seconds, not ${JSON.stringify(options.waitSeconds)}`);
898
+ }
899
+ opened = openGuard(options.config);
900
+ const ctx = opened.context({
901
+ waitSeconds: wait ?? guardWaitSeconds(opened.policy),
902
+ wayOut,
903
+ ...(options.home !== undefined ? { home: options.home } : {}),
904
+ ...(options.entryNames && options.entryNames.length > 0 ? { entryNames: options.entryNames } : {})
905
+ });
906
+ if (post) {
907
+ guardOutcome(event, ctx);
908
+ return { stdout: "", stderr: "", exitCode: 0 };
909
+ }
910
+ const verdict = await guardDecision(event, ctx);
911
+ return { stdout: verdict.kind === "pass" ? "" : `${JSON.stringify(hookOutput(verdict))}\n`, stderr: "", exitCode: 0 };
912
+ }
913
+ catch (err) {
914
+ if (post)
915
+ return { stdout: "", stderr: `[hmcp guard] ${err?.message ?? String(err)}\n`, exitCode: 0 };
916
+ return refuse(err);
917
+ }
918
+ finally {
919
+ try {
920
+ opened?.close();
921
+ }
922
+ catch {
923
+ /* closing a database is not a reason to change the answer */
924
+ }
925
+ }
926
+ }
927
+ /** How much longer than the wait a hook is given, so the guard answers before the SDK gives up on it. */
928
+ export const GUARD_TIMEOUT_MARGIN_SECONDS = 30;
929
+ /**
930
+ * The guard as Agent SDK hooks, for an agent a company runs itself:
931
+ *
932
+ * query({ prompt, options: { hooks: hmcpGuardHooks({ config: "gateway.yaml" }) } })
933
+ *
934
+ * The same `guardDecision` the Claude Code hook runs, in-process. The SDK runs
935
+ * hooks even under `bypassPermissions`, which is what makes this the one place
936
+ * every tool call passes through.
937
+ *
938
+ * Each matcher carries its own `timeout`, always longer than the wait, so the
939
+ * guard is the one that answers a held call -- and `onFailure: "block"`, so a
940
+ * callback that throws stops the call rather than letting it through. If the
941
+ * SDK gives up anyway and aborts the signal, the wait stops at once and the
942
+ * answer is a refusal; an approval given after that is left for the retry.
943
+ *
944
+ * `mcpServers` is what the program passes to `query()`: the guard reads it to
945
+ * tell the toolbox's own tools from a server that only shares its name. Without
946
+ * it, Claude Code's config files are read instead.
947
+ */
948
+ export function hmcpGuardHooks(options) {
949
+ const opened = openGuard(options.config);
950
+ const waitSeconds = options.waitSeconds ?? guardWaitSeconds(opened.policy);
951
+ const ctx = opened.context({
952
+ waitSeconds,
953
+ ...(options.entryNames ? { entryNames: options.entryNames } : {}),
954
+ ...(options.mcpServers ? { mcpServers: options.mcpServers } : {}),
955
+ ...(options.home !== undefined ? { home: options.home } : {})
956
+ });
957
+ const pre = async (input, _id, { signal } = {}) => {
958
+ const verdict = await guardDecision(input, ctx, signal);
959
+ // Given up on while waiting: whatever the wait ended with, the call does not run.
960
+ if (signal?.aborted && verdict.kind === "pass") {
961
+ return hookOutput({ kind: "deny", reason: "the approval wait was cut short, so this call was not run. Try it again." });
962
+ }
963
+ return hookOutput(verdict);
964
+ };
965
+ const post = async (input) => {
966
+ guardOutcome(input, ctx);
967
+ return {};
968
+ };
969
+ const matcher = (hook) => ({
970
+ hooks: [hook],
971
+ timeout: waitSeconds + GUARD_TIMEOUT_MARGIN_SECONDS,
972
+ onFailure: "block"
973
+ });
974
+ return { PreToolUse: [matcher(pre)], PostToolUse: [matcher(post)], PostToolUseFailure: [matcher(post)] };
975
+ }