atp-hermes-hook 0.1.0 → 0.2.0

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/README.md CHANGED
@@ -2,9 +2,65 @@
2
2
 
3
3
  A fail-closed [Hermes Agent](https://github.com/NousResearch/hermes-agent) `pre_tool_call` shell hook that enforces **Agent Trust Protocol (ATP)** security profiles at the tool boundary. Before Hermes runs a matched tool, the hook evaluates it against an [`atp-profiles`](https://www.npmjs.com/package/atp-profiles) profile and a path scope you configure, then lets the call through, blocks it, or sends it to Hermes' human-approval gate.
4
4
 
5
- Requires Node.js 20 or newer.
5
+ Requires Node.js 20 or newer. Want to see the decisions before changing Hermes settings? Start with the [local walkthrough](https://github.com/agent-trust-protocol/atp-core/tree/main/examples/hermes-hook), which runs the hook without starting Hermes or calling a model.
6
6
 
7
- ## Install
7
+ ## One-command setup (macOS/Linux)
8
+
9
+ Requires Hermes on your PATH and Node.js 20 or newer. From any directory, run:
10
+
11
+ ```bash
12
+ npx --yes atp-hermes-hook@0.2.0 setup
13
+ ```
14
+
15
+ This creates an `atp-pilot` Hermes profile if needed, installs a fixed copy under
16
+ `~/.hermes/agent-hooks/atp`, and creates a `safe-default` policy that allows reads
17
+ only within a disposable test folder. Terminal, write and patch calls are blocked.
18
+ It runs standalone read/terminal/write decision checks, backs up the profile's
19
+ `config.yaml`, and merges a fail-closed hook while preserving other hooks and
20
+ settings. It does not install packages into your current directory.
21
+
22
+ Hermes runs the persistent local copy, with no `npx` network fetch per tool call.
23
+ Setup does not restart gateways, import OpenClaw data, configure a model/provider,
24
+ or bypass Hermes' first-use consent. If the new profile needs a provider, run
25
+ `hermes -p atp-pilot setup` and skip unrelated migrations and messaging setup.
26
+
27
+ Verify Hermes' wiring next:
28
+
29
+ ```bash
30
+ hermes -p atp-pilot hooks test pre_tool_call --for-tool terminal
31
+ hermes -p atp-pilot chat
32
+ ```
33
+
34
+ Review and approve the exact local hook when Hermes asks. Expect an ATP terminal
35
+ block in the hook test. Complete the [live tool-call check](../../examples/hermes-hook/README.md#check-blocking-in-your-own-test-profile)
36
+ using this installation's `test-files/atp-setup-fixture.txt` as the allowed file.
37
+ Standalone checks do not prove live enforcement or signed mandate verification.
38
+
39
+ To choose another profile and read scope:
40
+
41
+ ```bash
42
+ npx --yes atp-hermes-hook@0.2.0 setup --hermes-profile my-test-profile --read /absolute/path/to/docs
43
+ ```
44
+
45
+ `--read` may be repeated; it replaces the default test-folder read scope on first
46
+ setup. No write scope is granted. Custom or existing policies receive terminal and
47
+ write checks; the fixture read check runs only when the test folder is an explicit
48
+ read root. Profiles configured by setup share this installation's policy file;
49
+ use manual installation for different policies per profile. `--hermes-home` selects
50
+ a custom Hermes root. Setup rejects malformed YAML, preserves existing ATP policies,
51
+ and refuses to replace their read scope implicitly. Rerunning setup does not add
52
+ duplicate copies of the same command. Existing manually configured ATP commands
53
+ are preserved with other hooks; review them separately if migrating. Other tool
54
+ names are outside the default four-tool matcher. Use WSL on Windows.
55
+
56
+ To undo the YAML change, restore the exact backup path printed by setup. This
57
+ restores the whole pre-setup file, so preserve later configuration edits first.
58
+ Revoke consent with `hermes -p <profile> hooks revoke '<exact command>'` if needed.
59
+ Running gateways require a deliberate restart to pick up changes; setup never
60
+ restarts them. Package files and the ATP policy remain available for inspection
61
+ after a failed or undone setup.
62
+
63
+ ## Manual install
8
64
 
9
65
  Install it locally (not through `npx`) so Hermes runs a fixed, reviewed copy without a network fetch on every tool call:
10
66
 
@@ -58,6 +114,12 @@ hooks:
58
114
 
59
115
  Hermes asks for consent the first time it sees this hook. Review the installed code before you approve it. Hermes keys consent on the exact command string, not the script's contents, so re-review after upgrading. Keep `fail_closed: true`.
60
116
 
117
+ Verify the hook in a test profile: [allow one test-file read and confirm that the terminal attempt is blocked](https://github.com/agent-trust-protocol/atp-core/blob/main/examples/hermes-hook/README.md#check-blocking-in-your-own-test-profile). If that helped you protect a tool action, [star ATP Core](https://github.com/agent-trust-protocol/atp-core) to follow the project. [Share your result or setup blocker](https://github.com/agent-trust-protocol/atp-core/blob/main/docs/launch/developer-pilot.md).
118
+
119
+ ## Feedback and support
120
+
121
+ [Rate your setup experience](https://github.com/agent-trust-protocol/atp-core/blob/main/docs/package-feedback.md#hermes), leave a comment, or report a reproducible issue. Include `atp-hermes-hook`, its installed version, your runtime, and what you expected to happen. Remove secrets and private data from examples and logs. For vulnerabilities, follow the [private reporting guidance](https://github.com/agent-trust-protocol/atp-core/blob/main/SECURITY.md#reporting-a-vulnerability).
122
+
61
123
  ## How a call is decided
62
124
 
63
125
  1. Anything that is not a `pre_tool_call` event, or a tool missing from `tools`, is **blocked**.
@@ -9,6 +9,8 @@ const BLOCK_EXIT = 2;
9
9
  const USAGE = `Usage: atp-hermes-hook --config <file> (reads a Hermes pre_tool_call event on stdin)
10
10
  atp-hermes-hook --check --config <file>
11
11
  atp-hermes-hook --version
12
+ atp-hermes-hook setup [--hermes-profile atp-pilot] [--read <directory>]
13
+ [--hermes-home <directory>]
12
14
 
13
15
  The configuration file can also be set with ATP_HERMES_HOOK_CONFIG.`;
14
16
 
@@ -88,4 +90,14 @@ function main() {
88
90
  }
89
91
  }
90
92
 
91
- main();
93
+ if (process.argv[2] === 'setup') {
94
+ try {
95
+ const { parseSetupArgs, setupHermes } = await import('../src/setup.mjs');
96
+ setupHermes(parseSetupArgs(process.argv.slice(3)));
97
+ } catch (error) {
98
+ process.stderr.write(`atp-hermes-hook setup: ${error.message}\n`);
99
+ process.exitCode = 1;
100
+ }
101
+ } else {
102
+ main();
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "atp-hermes-hook",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Fail-closed Hermes Agent pre_tool_call hook that enforces Agent Trust Protocol (ATP) security profiles at the tool boundary",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -42,7 +42,8 @@
42
42
  "url": "https://github.com/agent-trust-protocol/atp-core/issues"
43
43
  },
44
44
  "dependencies": {
45
- "atp-profiles": "^3.0.0"
45
+ "atp-profiles": "^3.0.0",
46
+ "yaml": "^2.9.1"
46
47
  },
47
48
  "engines": {
48
49
  "node": ">=20.0.0"
package/src/setup.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { parseDocument } from 'yaml';
8
+ import { loadConfig } from './index.mjs';
9
+
10
+ const MATCHER = '^(read_file|terminal|write_file|patch)$';
11
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
12
+
13
+ function run(command, args, options = {}) {
14
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 120_000, ...options });
15
+ if (result.error || result.status !== 0) {
16
+ throw new Error(`${command} ${args[0] ?? ''} failed: ${result.error?.message ?? result.stderr?.trim() ?? result.status}`);
17
+ }
18
+ return result;
19
+ }
20
+
21
+ function atomicWrite(file, content) {
22
+ const temp = `${file}.${randomUUID()}.tmp`;
23
+ try {
24
+ writeFileSync(temp, content, { mode: 0o600, flag: 'wx' });
25
+ renameSync(temp, file);
26
+ } finally {
27
+ rmSync(temp, { force: true });
28
+ }
29
+ }
30
+
31
+ function readProfile(file) {
32
+ const source = readFileSync(file, 'utf8');
33
+ const doc = parseDocument(source);
34
+ if (doc.errors.length) throw new Error(`Invalid Hermes YAML: ${doc.errors[0].message}`);
35
+ const config = doc.toJS({ maxAliasCount: 100 });
36
+ if (config !== null && (typeof config !== 'object' || Array.isArray(config))) {
37
+ throw new Error('Hermes config.yaml must contain a mapping');
38
+ }
39
+ const hooks = config?.hooks;
40
+ if (hooks != null && (typeof hooks !== 'object' || Array.isArray(hooks))) {
41
+ throw new Error('Existing hooks must be a mapping; no configuration was changed');
42
+ }
43
+ const entries = hooks?.pre_tool_call ?? [];
44
+ if (!Array.isArray(entries) || entries.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry))) {
45
+ throw new Error('Existing hooks.pre_tool_call must be a list of mappings');
46
+ }
47
+ return { doc, source, entries };
48
+ }
49
+
50
+ /** Install a fixed local hook, merge it into one Hermes profile, and test its wire contract.
51
+ * The injected runner/package source are for packed-package tests, never CLI options.
52
+ */
53
+ export function setupHermes({ profile = 'atp-pilot', hermesHome = process.env.HERMES_HOME || join(homedir(), '.hermes'), read = [] } = {}, {
54
+ execute = run, packageSource, output = console.log,
55
+ } = {}) {
56
+ if (process.platform === 'win32') throw new Error('Run setup in WSL; native Windows setup is not supported yet');
57
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(profile)) throw new Error('Invalid Hermes profile name');
58
+ const home = resolve(hermesHome);
59
+ const profileDir = profile === 'default' ? home : join(home, 'profiles', profile);
60
+ const profileFile = join(profileDir, 'config.yaml');
61
+ const installDir = join(home, 'agent-hooks', 'atp');
62
+ const policyFile = join(installDir, 'atp-hermes.json');
63
+ // Hermes profile resolution and creation must use the same root as our file edits.
64
+ const hermesEnv = { ...process.env, HERMES_HOME: home };
65
+ const hermes = (args) => execute('hermes', args, { env: hermesEnv });
66
+ hermes(['--version']);
67
+ for (const path of read) {
68
+ if (!existsSync(resolve(path))) throw new Error(`Read scope does not exist: ${path}`);
69
+ }
70
+ if (existsSync(policyFile)) {
71
+ loadConfig(policyFile); // Keep a valid existing policy; never silently broaden it.
72
+ if (read.length) throw new Error(`An ATP policy already exists at ${policyFile}; edit its read scope explicitly`);
73
+ }
74
+ if (!existsSync(profileFile)) {
75
+ if (existsSync(profileDir)) throw new Error(`Profile directory exists without config.yaml: ${profileDir}`);
76
+ hermes(['profile', 'create', profile]);
77
+ }
78
+ const before = readProfile(profileFile); // Reject malformed/duplicate YAML before installing.
79
+ const version = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).version;
80
+ mkdirSync(installDir, { recursive: true, mode: 0o700 });
81
+ output(`Installing a fixed local copy of atp-hermes-hook@${version}…`);
82
+ execute('npm', ['install', '--prefix', installDir, '--ignore-scripts', '--save-exact', '--no-fund', '--no-audit',
83
+ packageSource ?? `atp-hermes-hook@${version}`]);
84
+ const stableBin = join(installDir, 'node_modules', 'atp-hermes-hook', 'bin', 'atp-hermes-hook.mjs');
85
+ const fixtureDir = join(installDir, 'test-files');
86
+ mkdirSync(fixtureDir, { recursive: true, mode: 0o700 });
87
+ const fixture = join(fixtureDir, 'atp-setup-fixture.txt');
88
+ if (!existsSync(fixture)) writeFileSync(fixture, 'ATP Hermes read test.\n', { flag: 'wx', mode: 0o600 });
89
+ if (!existsSync(policyFile)) {
90
+ const policy = { profile: 'safe-default', state: 'executing', onApproval: 'block',
91
+ paths: { read: read.length ? read.map((path) => resolve(path)) : [fixtureDir], write: [] } };
92
+ writeFileSync(policyFile, `${JSON.stringify(policy, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
93
+ }
94
+ const config = loadConfig(policyFile);
95
+ execute(process.execPath, [stableBin, '--check', '--config', policyFile]);
96
+ const tests = [
97
+ ['terminal blocked', { tool_name: 'terminal', tool_input: { command: 'echo ATP-test' } }, 2],
98
+ ['write blocked', { tool_name: 'write_file', tool_input: { path: fixture, content: 'must not be written' } }, 2],
99
+ ];
100
+ // The default fixture is the only read scope we can prove without reading a user's files.
101
+ if (config.roots.read.includes(fixtureDir)) {
102
+ tests.unshift(['fixture read allowed', { tool_name: 'read_file', tool_input: { path: fixture } }, 0]);
103
+ }
104
+ for (const [label, payload, expected] of tests) {
105
+ const result = spawnSync(process.execPath, [stableBin, '--config', policyFile], {
106
+ input: JSON.stringify({ hook_event_name: 'pre_tool_call', ...payload }), encoding: 'utf8', timeout: 10_000,
107
+ });
108
+ let directive;
109
+ try { directive = JSON.parse(result.stdout); } catch { /* report below */ }
110
+ if (result.status !== expected || !directive ||
111
+ (expected === 2 ? directive.action !== 'block' : Object.keys(directive).length !== 0)) {
112
+ throw new Error(`Self-test failed: ${label}; Hermes configuration was not changed`);
113
+ }
114
+ output(`PASS: ${label}`);
115
+ }
116
+ const command = [process.execPath, stableBin, '--config', policyFile].map((part) => JSON.stringify(part)).join(' ');
117
+ // Re-read after npm finishes: do not overwrite edits made during installation.
118
+ const current = readProfile(profileFile);
119
+ if (current.source !== before.source) throw new Error('Hermes configuration changed during setup; rerun setup');
120
+ const entry = { matcher: MATCHER, command, timeout: 10, fail_closed: true };
121
+ const entries = current.entries.filter((existing) => existing.command !== command);
122
+ entries.push(entry);
123
+ current.doc.setIn(['hooks', 'pre_tool_call'], entries);
124
+ const updated = current.doc.toString();
125
+ let backup = null;
126
+ if (updated !== current.source) {
127
+ backup = `${profileFile}.before-atp-${randomUUID()}`;
128
+ writeFileSync(backup, current.source, { flag: 'wx', mode: 0o600 });
129
+ atomicWrite(profileFile, updated);
130
+ }
131
+ output(`Configured Hermes profile: ${profile}`);
132
+ if (backup) output(`Backup: ${backup}`);
133
+ output(`Policy: ${policyFile}`);
134
+ output('Scope: read_file, terminal, write_file and patch only. Other tools are outside this matcher.');
135
+ output('Standalone self-tests passed. Live Hermes enforcement is not verified yet.');
136
+ output(`Next: hermes -p ${profile} hooks test pre_tool_call --for-tool terminal`);
137
+ output('Review and approve the local hook when Hermes requests first-use consent.');
138
+ output(`Then: hermes -p ${profile} chat (run setup for this profile first if its provider is not configured).`);
139
+ output('No gateway was restarted and hook consent was not bypassed.');
140
+ return { profileFile, policyFile, stableBin, command, backup };
141
+ }
142
+
143
+ export function parseSetupArgs(args) {
144
+ const options = { read: [] };
145
+ for (let index = 0; index < args.length; index += 1) {
146
+ const flag = args[index];
147
+ if (!['--hermes-profile', '--hermes-home', '--read'].includes(flag)) throw new Error(`Unknown setup option: ${flag}`);
148
+ const value = args[++index];
149
+ if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
150
+ if (flag === '--read') options.read.push(value);
151
+ else options[flag === '--hermes-profile' ? 'profile' : 'hermesHome'] = value;
152
+ }
153
+ return options;
154
+ }