diff --git a/package-lock.json b/package-lock.json index 596f70d..13cc300 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "sh-syntax": "^0.8.7", "zod": "^4.6.7" }, "bin": { @@ -2381,6 +2382,18 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/sh-syntax": { + "version": "0.8.7", + "resolved": "https://registry.npmjs.org/sh-syntax/-/sh-syntax-0.8.7.tgz", + "integrity": "sha512-zaJUdXFCbDFgtREm3KiqvX3dBlngGY0tumPzHvC5RqX67UuaBLIIZqb16MCbYLGyk5rPYrM+5FlghF+w6WdVUw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "url": "https://opencollective.com/sh-syntax" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/package.json b/package.json index 1d1997d..817729f 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "sh-syntax": "^0.8.7", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/hosts/claude/adapter.test.ts b/src/hosts/claude/adapter.test.ts new file mode 100644 index 0000000..566a323 --- /dev/null +++ b/src/hosts/claude/adapter.test.ts @@ -0,0 +1,674 @@ +import { mkdir, mkdtemp, readFile, realpath, symlink, writeFile } from 'node:fs/promises'; +import { createServer, type Server } from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, describe, expect, it } from 'vitest'; +import { Dispatcher } from '../../core/dispatcher.js'; +import type { Decision, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { MemoryToolRuntime, makeContext } from '../../testing/index.js'; +import { ClaudeHostAdapter, type ClaudePolicy } from './adapter.js'; + +const posix = process.platform !== 'win32'; +const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures'); +const HOOK = path.join(FIXTURES, 'example-hook.mjs'); + +/** A command hook handler running the example hook in `mode`. */ +function exampleHook(mode: string, arg?: string, extra: Record = {}): Record { + return { type: 'command', command: process.execPath, args: [HOOK, mode, ...(arg === undefined ? [] : [arg])], ...extra }; +} + +function preHooks(matcher: string, ...hooks: Record[]): Record { + return { hooks: { PreToolUse: [{ matcher, hooks }] } }; +} + +interface Setup { + readonly adapter: ClaudeHostAdapter; + readonly ctx: SessionContext; + readonly policy: PolicySnapshot; + readonly project: string; + readonly home: string; + readonly base: string; +} + +interface SetupOptions { + readonly project?: Record; + readonly local?: Record; + readonly user?: Record; + /** Extra Claude CLI args seen on the parent process. */ + readonly argv?: readonly string[]; + readonly trusted?: boolean; + /** Live permission mode from the companion hook. */ + readonly mode?: string; + readonly env?: Record; + readonly files?: Record; +} + +async function setup(o: SetupOptions = {}): Promise { + const base = await realpath(await mkdtemp(path.join(os.tmpdir(), 'acm-claude-'))); + const home = path.join(base, 'home'); + const project = path.join(base, 'project'); + await mkdir(path.join(home, '.claude'), { recursive: true }); + await mkdir(path.join(project, '.claude'), { recursive: true }); + if (o.project) await writeFile(path.join(project, '.claude', 'settings.json'), JSON.stringify(o.project)); + if (o.local) await writeFile(path.join(project, '.claude', 'settings.local.json'), JSON.stringify(o.local)); + if (o.user) await writeFile(path.join(home, '.claude', 'settings.json'), JSON.stringify(o.user)); + if (o.trusted !== false) await writeFile(path.join(home, '.claude.json'), JSON.stringify({ projects: { [project]: { hasTrustDialogAccepted: true } } })); + for (const [rel, content] of Object.entries(o.files ?? {})) { + await mkdir(path.dirname(path.join(project, rel)), { recursive: true }); + await writeFile(path.join(project, rel), content); + } + const adapter = new ClaudeHostAdapter({ + env: o.env ?? {}, + home, + managedDir: null, + stateDir: path.join(base, 'state'), + readParent: async () => (o.argv ? { argv: ['claude', ...o.argv], cwd: project } : undefined), + }); + const ctx = makeContext(project, { + host: 'claude', + sessionId: 'session-1', + toolUseId: 'toolu_1', + transcriptPath: path.join(base, 't.jsonl'), + permissionMode: o.mode ?? 'default', + sources: o.mode === undefined ? { cwd: 'roots' } : { cwd: 'roots', permissionMode: 'ctx-file' }, + }); + const policy = await adapter.loadPolicy(ctx); + if ('error' in policy) throw new Error(policy.error); + return { adapter, ctx, policy, project, home, base }; +} + +const containment = { mode: 'none' } as const; + +function bash(command: string, cwd: string): PreparedCall { + return { id: 'c1', tool: 'bash', args: { command, cwd, timeoutMs: 120_000 }, effect: { command, cwd, timeoutMs: 120_000, containment } }; +} +function read(p: string, real = p): PreparedCall { + return { id: 'c1', tool: 'read', args: { path: p, offset: 1, limit: 2000 }, effect: { absPath: real, offset: 1, limit: 2000 } }; +} +function write(p: string, content = 'x'): PreparedCall { + return { id: 'c1', tool: 'write', args: { path: p, content }, effect: { absPath: p, beforeHash: null, afterContent: content, diff: '' } }; +} +function edit(p: string, matched: string, newString: string): PreparedCall { + return { + id: 'c1', + tool: 'edit', + args: { path: p, oldString: matched.trim(), newString }, + effect: { absPath: p, beforeHash: 'h', afterContent: newString, diff: '', matchedOldString: matched, matchStrategy: 'line-trimmed', replacements: 1 }, + }; +} +function grep(root: string): PreparedCall { + return { id: 'c1', tool: 'grep', args: { pattern: 'x', path: root }, effect: { absRoot: root, pattern: 'x', glob: '*.ts', ignoreCase: true, maxResults: 50 } }; +} +function glob(root: string): PreparedCall { + return { id: 'c1', tool: 'glob', args: { pattern: '**/*.ts', path: root }, effect: { absRoot: root, pattern: '**/*.ts', maxResults: 50 } }; +} + +function check(s: Setup, prepared: PreparedCall): Decision['kind'] { + return s.adapter.checkStatic(prepared, s.ctx, s.policy).kind; +} + +function authorize(s: Setup, prepared: PreparedCall, signal = new AbortController().signal): Promise { + return s.adapter.authorize(prepared, s.ctx, s.policy, signal); +} + +describe('Bash rules', () => { + it.each([ + ['echo ok && rm -rf x', 'deny'], + ['echo $(rm -rf x)', 'deny'], + ['echo `rm x`', 'deny'], + ['FOO=1 rm x', 'deny'], + ['timeout 5 rm x', 'deny'], + ['sudo rm x', 'deny'], + ['sudo -u root rm x', 'deny'], + ["bash -c 'rm x'", 'deny'], + ['sh -ec "echo a; rm x"', 'deny'], + ['nice -n 5 nohup rm x', 'deny'], + ['env A=1 rm x', 'deny'], + ['/bin/rm -rf build', 'deny'], + ['ls | xargs rm', 'deny'], + ['ls | xargs -n1 rm', 'deny'], + ['find . -name a -exec rm {} \\;', 'deny'], + ['cat <(rm z)', 'deny'], + ['(cd sub && rm x)', 'deny'], + ['for f in a b; do rm "$f"; done', 'deny'], + ['rm', 'deny'], + ['rm $TARGET', 'deny'], + ['echo ok', 'allow'], + ['rmdir x', 'allow'], + ['echo rm', 'allow'], + ['echo "unbalanced', 'ask'], + ['eval "$X"', 'ask'], + ['cat < { + const s = await setup({ user: { permissions: { deny: ['Bash(rm:*)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash(command, s.project))).toBe(expected); + }); + + it('applies ask rules after deny rules, in every mode', async () => { + const s = await setup({ user: { permissions: { deny: ['Bash(git push --force *)'], ask: ['Bash(git push *)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash('git push --force origin', s.project))).toBe('deny'); + expect(check(s, bash('git push origin main', s.project))).toBe('ask'); + expect(check(s, bash('cd x && echo "$(git push)"', s.project))).toBe('ask'); + expect(check(s, bash('git status', s.project))).toBe('allow'); + }); + + it('matches a parameter rule and the ambiguous timeout command', async () => { + const s = await setup({ user: { permissions: { deny: ['Bash(timeout:*)'] } }, mode: 'bypassPermissions' }); + // `timeout:*` is both a parameter rule (any timeout) and a `timeout` prefix rule: strict reading denies. + expect(check(s, bash('echo hi', s.project))).toBe('deny'); + }); + + it('allow rules approve only when every subcommand is approved', async () => { + const s = await setup({ user: { permissions: { allow: ['Bash(npm run *)', 'Bash(git status)'] } }, mode: 'default' }); + expect(check(s, bash('npm run build', s.project))).toBe('allow'); + expect(check(s, bash('npm run build && git status', s.project))).toBe('allow'); + expect(check(s, bash('timeout 30 npm run test', s.project))).toBe('allow'); + expect(check(s, bash('npm run build && rm -rf x', s.project))).toBe('ask'); + expect(check(s, bash('NODE_ENV=x npm run build', s.project))).toBe('ask'); + expect(check(s, bash('sudo npm run build', s.project))).toBe('ask'); + expect(check(s, bash('npm install', s.project))).toBe('ask'); + expect(check(s, bash('npm run build > /tmp/out.log', s.project))).toBe('ask'); + expect(check(s, bash('npm run build > out.log', s.project))).toBe('allow'); + }); + + it('checks redirect and file-reader targets against Read/Edit rules', async () => { + const s = await setup({ user: { permissions: { deny: ['Read(./.env)', 'Edit(./locked/**)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash('cat .env', s.project))).toBe('deny'); + expect(check(s, bash('wc -l < .env', s.project))).toBe('deny'); + expect(check(s, bash('echo x > .env', s.project))).toBe('deny'); // a Read deny also blocks writes + expect(check(s, bash('echo x > locked/a.txt', s.project))).toBe('deny'); + expect(check(s, bash('echo x | tee locked/a.txt', s.project))).toBe('deny'); + expect(check(s, bash('echo x > "$OUT"', s.project))).toBe('ask'); + expect(check(s, bash('cd sub && cat .env', s.project))).toBe('ask'); + expect(check(s, bash('echo x > notes.txt', s.project))).toBe('allow'); + expect(check(s, bash('cat README.md 2>/dev/null', s.project))).toBe('allow'); + }); +}); + +describe('path rules', () => { + it('anchors //, ~/, /, ./ and bare patterns like gitignore', async () => { + const s = await setup({ + project: { permissions: { deny: ['Read(./.env)', 'Edit(/src/generated/**)', 'Read(secrets/**)', 'Read(*.pem)'] } }, + user: { permissions: { deny: ['Read(~/notes/secret.txt)', 'Read(//etc/example-shadow)', 'Read(/private/**)'] } }, + mode: 'bypassPermissions', + }); + const p = (rel: string): string => path.join(s.project, rel); + expect(check(s, read(p('.env')))).toBe('deny'); + expect(check(s, read(p('sub/.env')))).toBe('allow'); // ./ is anchored + expect(check(s, read(path.join(s.home, 'notes', 'secret.txt')))).toBe('deny'); + expect(check(s, read('/etc/example-shadow'))).toBe('deny'); + expect(check(s, write(p('src/generated/a.ts')))).toBe('deny'); + expect(check(s, edit(p('src/generated/deep/b.ts'), 'a', 'b'))).toBe('deny'); + expect(check(s, write(p('src/a.ts')))).toBe('allow'); + expect(check(s, write(p('vendor/src/generated/a.ts')))).toBe('allow'); + expect(check(s, read(p('a/b/secrets/key')))).toBe('deny'); // single-dir deny matches at any depth + expect(check(s, read(p('certs/x.pem')))).toBe('deny'); // bare name: any depth + expect(check(s, read(path.join(s.home, '.claude', 'private', 'x')))).toBe('deny'); // `/` in user settings → config dir + expect(check(s, read(p('private/x')))).toBe('allow'); + expect(check(s, write(p('.env')))).toBe('deny'); // Read deny blocks Write + expect(check(s, grep(p('a/secrets')))).toBe('deny'); // Read rules govern Grep + expect(check(s, glob(p('secrets')))).toBe('deny'); // and Glob + expect(check(s, grep(p('src')))).toBe('allow'); + }); + + it.skipIf(!posix)('checks the real path, so a symlink cannot dodge a deny', async () => { + const s = await setup({ project: { permissions: { deny: ['Read(./.env)'] } }, mode: 'bypassPermissions', files: { '.env': 'SECRET=1' } }); + await symlink(path.join(s.project, '.env'), path.join(s.project, 'innocent.txt')); + const real = await realpath(path.join(s.project, 'innocent.txt')); + expect(check(s, read(path.join(s.project, 'innocent.txt'), real))).toBe('deny'); + }); + + it.skipIf(!posix)('applies a rule written through a symlinked directory to the real location', async () => { + const s0 = await setup(); + const realDir = path.join(s0.base, 'real-secrets'); + await mkdir(realDir); + await symlink(realDir, path.join(s0.base, 'alias')); + const s = await setup({ user: { permissions: { deny: [`Read(/${path.join(s0.base, 'alias')}/**)`] } }, mode: 'bypassPermissions' }); + expect(check(s, read(path.join(realDir, 'k')))).toBe('deny'); + }); + + it('allow rules need both the requested and the real path to match', async () => { + const s = await setup({ user: { permissions: { allow: ['Read(//opt/shared/**)'] } }, mode: 'default' }); + expect(check(s, read('/opt/shared/a'))).toBe('allow'); + expect(check(s, read('/opt/shared/link', '/etc/passwd'))).toBe('ask'); + }); +}); + +describe('permission modes (no rule matches)', () => { + const cases: Record> = { + default: { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + acceptEdits: { readIn: 'allow', readOut: 'ask', writeIn: 'allow', writeOut: 'ask', editIn: 'allow', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + plan: { readIn: 'allow', readOut: 'ask', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' }, + dontAsk: { readIn: 'allow', readOut: 'deny', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' }, + auto: { readIn: 'allow', readOut: 'ask', writeIn: 'allow', writeOut: 'ask', editIn: 'allow', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + bypassPermissions: { readIn: 'allow', readOut: 'allow', writeIn: 'allow', writeOut: 'allow', editIn: 'allow', bash: 'allow', grepIn: 'allow', globIn: 'allow' }, + 'not-a-mode': { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + }; + for (const [mode, expected] of Object.entries(cases)) { + it(`${mode}`, async () => { + const s = await setup({ mode }); + const inside = path.join(s.project, 'a.ts'); + const outside = path.join(s.base, 'elsewhere', 'b.ts'); + const got = { + readIn: check(s, read(inside)), + readOut: check(s, read(outside)), + writeIn: check(s, write(inside)), + writeOut: check(s, write(outside)), + editIn: check(s, edit(inside, 'a', 'b')), + bash: check(s, bash('ls', s.project)), + grepIn: check(s, grep(s.project)), + globIn: check(s, glob(s.project)), + }; + // On Windows no trusted record carries an unreadable mode: only what every mode allows runs. + const unknown = !posix && mode === 'not-a-mode'; + expect(got).toEqual(unknown ? Object.fromEntries(Object.entries(expected).map(([k, v]) => [k, v === 'allow' ? v : 'deny'])) : expected); + }); + } + + it('ask rules still ask in bypassPermissions and deny in dontAsk', async () => { + const ask = { user: { permissions: { ask: ['Read(./a.ts)'] } } }; + const bypass = await setup({ ...ask, mode: 'bypassPermissions' }); + expect(check(bypass, read(path.join(bypass.project, 'a.ts')))).toBe('ask'); + const dontAsk = await setup({ ...ask, mode: 'dontAsk' }); + expect(check(dontAsk, read(path.join(dontAsk.project, 'a.ts')))).toBe('deny'); + }); + + it('takes the mode from the companion hook, else the CLI flag, else settings defaultMode', async () => { + const fromFlag = await setup({ argv: ['--permission-mode', 'acceptEdits'], user: { permissions: { defaultMode: 'plan' } } }); + // Windows has no trusted live mode, so neither the flag nor settings authorize a write there. + expect(check(fromFlag, write(path.join(fromFlag.project, 'a.ts')))).toBe(posix ? 'allow' : 'deny'); + const fromSettings = await setup({ user: { permissions: { defaultMode: 'plan' } } }); + expect(check(fromSettings, write(path.join(fromSettings.project, 'a.ts')))).toBe('deny'); + const fromCtx = await setup({ mode: 'bypassPermissions', argv: ['--permission-mode', 'plan'] }); + expect(check(fromCtx, bash('ls', fromCtx.project))).toBe('allow'); + const locked = await setup({ mode: 'bypassPermissions', user: { permissions: { disableBypassPermissionsMode: 'disable' } } }); + expect(check(locked, bash('ls', locked.project))).toBe('ask'); + }); + + it('additionalDirectories count as working directories', async () => { + const s = await setup({ user: { permissions: { additionalDirectories: ['~/shared'] } } }); + expect(check(s, read(path.join(s.home, 'shared', 'x')))).toBe('allow'); + }); +}); + +describe.skipIf(!posix)('PreToolUse hooks', () => { + const anyBash = (s: Setup): PreparedCall => bash('ls -la', s.project); + + it('exit 2 denies with stderr as the reason', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('exit2')) }); + expect(await authorize(s, anyBash(s))).toEqual({ kind: 'deny', source: 'hook', reason: 'blocked by example hook' }); + }); + + it('a shell-form hook script denies', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'command', command: `"${path.join(FIXTURES, 'deny-rm.sh')}"` }) }); + expect(await authorize(s, bash('rm -rf build', s.project))).toMatchObject({ kind: 'deny', source: 'hook', reason: 'rm is not allowed' }); + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' }); + }); + + it.each([ + ['deny', { kind: 'deny', source: 'hook' }], + ['legacy-block', { kind: 'deny', source: 'hook', reason: 'legacy block' }], + ['stop', { kind: 'deny', source: 'hook', reason: 'stop requested' }], + ['ask', { kind: 'ask' }], + ['defer', { kind: 'ask' }], + ['allow', { kind: 'allow' }], + ['empty', { kind: 'allow' }], + ['exit1', { kind: 'deny', source: 'hook-error' }], + ['crash', { kind: 'deny', source: 'hook-error' }], + ['invalid', { kind: 'deny', source: 'hook-error' }], + ['bad-decision', { kind: 'deny', source: 'hook-error' }], + ])('JSON/exit behavior %s', async (mode, expected) => { + const s = await setup({ user: preHooks('Bash', exampleHook(mode)) }); + expect(await authorize(s, anyBash(s))).toMatchObject(expected); + }); + + it('a hook that cannot start denies', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'command', command: path.join(s0Dir(), 'missing-hook.sh') }) }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + }); + + it('a PreToolUse failure still denies with onFailure: continue', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('crash', undefined, { onFailure: 'continue' })) }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + }); + + it('times out, kills the hook and denies with hook-timeout', async () => { + const pidFile = path.join(os.tmpdir(), `acm-hook-pid-${process.pid}-${Date.now()}`); + const s = await setup({ user: preHooks('Bash', { type: 'command', command: `echo $$ > "${pidFile}"; exec sleep 30`, timeout: 0.5 }) }); + const started = Date.now(); + const decision = await authorize(s, anyBash(s)); + expect(decision).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + expect(Date.now() - started).toBeLessThan(5_000); + const pid = Number((await readFile(pidFile, 'utf8')).trim()); + await new Promise((r) => setTimeout(r, 100)); + expect(() => process.kill(pid, 0)).toThrow(); + }); + + it('rewrites the call with updatedInput (mapped back to binding args)', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'echo safe', timeout: 5000 }))) }); + expect(await authorize(s, anyBash(s))).toEqual({ + kind: 'allow', + reason: 'example allow', + updatedArgs: { command: 'echo safe', cwd: s.project, timeoutMs: 5000 }, + }); + const w = await setup({ user: preHooks('Write', exampleHook('update-only', JSON.stringify({ file_path: '/x/y', content: 'clean' }))) }); + expect(await authorize(w, write(path.join(w.project, 'a')))).toMatchObject({ kind: 'allow', updatedArgs: { path: '/x/y', content: 'clean' } }); + const bad = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'ls', run_in_background: true }))) }); + expect(await authorize(bad, anyBash(bad))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('matches tool names exactly or by regex', async () => { + const exact = await setup({ user: preHooks('Edit|Write', exampleHook('deny')) }); + expect((await authorize(exact, write(path.join(exact.project, 'a')))).kind).toBe('deny'); + expect((await authorize(exact, read(path.join(exact.project, 'a')))).kind).toBe('allow'); + const partial = await setup({ user: preHooks('Bas', exampleHook('deny')) }); + expect((await authorize(partial, anyBash(partial))).kind).toBe('allow'); + const regex = await setup({ user: preHooks('^(Bash|Read)$', exampleHook('deny')) }); + expect((await authorize(regex, read(path.join(regex.project, 'a')))).kind).toBe('deny'); + expect((await authorize(regex, glob(regex.project))).kind).toBe('allow'); + const all = await setup({ user: preHooks('*', exampleHook('deny')) }); + expect((await authorize(all, grep(all.project))).kind).toBe('deny'); + }); + + it('combines parallel hooks: deny > ask > allow; two updatedInputs are refused', async () => { + const denyWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('deny'), exampleHook('ask')) }); + expect((await authorize(denyWins, anyBash(denyWins))).kind).toBe('deny'); + const askWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('ask')) }); + expect((await authorize(askWins, anyBash(askWins))).kind).toBe('ask'); + const twoUpdates = await setup({ + user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'a' })), exampleHook('update', JSON.stringify({ command: 'b' }))), + }); + expect(await authorize(twoUpdates, anyBash(twoUpdates))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + const started = Date.now(); + const slow = await setup({ user: preHooks('Bash', exampleHook('sleep', '600'), exampleHook('sleep', '600'), exampleHook('sleep', '600')) }); + expect((await authorize(slow, anyBash(slow))).kind).toBe('allow'); + expect(Date.now() - started).toBeLessThan(1_700); // ran in parallel, not 1.8 s in sequence + }); + + it('merges hooks from every source and runs a duplicate once', async () => { + const record = path.join(os.tmpdir(), `acm-dup-${process.pid}-${Date.now()}`); + const hook = { type: 'command', command: `echo run >> "${record}"` }; + const s = await setup({ user: preHooks('Bash', hook), project: preHooks('Bash', hook) }); + await authorize(s, anyBash(s)); + expect((await readFile(record, 'utf8')).trim().split('\n')).toEqual(['run']); + }); + + it('disableAllHooks turns hooks off', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('deny')), project: { disableAllHooks: true } }); + expect((await authorize(s, anyBash(s))).kind).toBe('allow'); + }); + + it('a hook type it cannot evaluate denies matching calls with unsupported-config', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'prompt', prompt: 'Is this safe? $ARGUMENTS' }) }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + expect((await authorize(s, read(path.join(s.project, 'a')))).kind).toBe('allow'); // matcher does not match + const weird = await setup({ user: preHooks('Bash', { type: 'teleport' }) }); + expect(await authorize(weird, anyBash(weird))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + }); + + it('honors the `if` filter', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('deny', undefined, { if: 'Bash(git push *)' })) }); + expect((await authorize(s, bash('git status', s.project))).kind).toBe('allow'); + expect((await authorize(s, bash('npm test && git push origin', s.project))).kind).toBe('deny'); + expect((await authorize(s, bash('echo $(date)', s.project))).kind).toBe('deny'); // dynamic: runs anyway + }); + + it('exec form substitutes ${CLAUDE_PROJECT_DIR} and exports it', async () => { + const s = await setup({ files: { '.claude/hooks/check.mjs': "process.stderr.write(process.env.CLAUDE_PROJECT_DIR + '|' + process.argv[2]); process.exit(2);" } }); + const s2 = await setup({ user: preHooks('Bash', { type: 'command', command: process.execPath, args: [`${s.project}/.claude/hooks/check.mjs`, '${CLAUDE_PROJECT_DIR}'] }) }); + const d = await authorize(s2, anyBash(s2)); + expect(d).toEqual({ kind: 'deny', source: 'hook', reason: `${s2.project}|${s2.project}` }); + }); + + it('runs hooks of enabled plugins', async () => { + const s0 = await setup(); + const pluginRoot = path.join(s0.base, 'plugin'); + await mkdir(path.join(pluginRoot, 'hooks'), { recursive: true }); + await writeFile(path.join(pluginRoot, 'hooks', 'hooks.json'), JSON.stringify(preHooks('Bash', exampleHook('deny')))); + const configDir = path.join(s0.base, 'config'); + await mkdir(path.join(configDir, 'plugins'), { recursive: true }); + await writeFile(path.join(configDir, 'plugins', 'installed_plugins.json'), JSON.stringify({ plugins: { 'guard@example': [{ installPath: pluginRoot }] } })); + await writeFile(path.join(configDir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'guard@example': true } })); + const s = await setup({ env: { CLAUDE_CONFIG_DIR: configDir } }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('sends the exact native payload (byte-identical command)', async () => { + const out = path.join(os.tmpdir(), `acm-payload-${process.pid}-${Date.now()}.json`); + const s = await setup({ user: preHooks('*', exampleHook('record', out)) }); + const command = 'printf "%s" \'héllo "wörld"\' && echo ✓\nline two\t$HOME \\n'; + expect((await authorize(s, bash(command, path.join(s.project, 'sub')))).kind).toBe('allow'); + const payload: unknown = JSON.parse(await readFile(out, 'utf8')); + expect(payload).toEqual({ + session_id: 'session-1', + transcript_path: path.join(s.base, 't.jsonl'), + cwd: path.join(s.project, 'sub'), + permission_mode: 'default', + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command, timeout: 120_000, description: 'agent-code-mode script call c1', run_in_background: false }, + tool_use_id: 'toolu_1/c1', + }); + + await authorize(s, edit(path.join(s.project, 'a.ts'), ' const a = 1;', 'const a = 2;')); + expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({ + tool_name: 'Edit', + tool_input: { file_path: path.join(s.project, 'a.ts'), old_string: ' const a = 1;', new_string: 'const a = 2;', replace_all: false }, + }); + await authorize(s, grep(s.project)); + expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({ + tool_name: 'Grep', + tool_input: { pattern: 'x', path: s.project, glob: '*.ts', '-i': true, output_mode: 'content', '-n': true, head_limit: 50 }, + }); + }); + + it('kills running hooks when the signal aborts', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('sleep', '30000')) }); + const controller = new AbortController(); + const started = Date.now(); + const pending = authorize(s, anyBash(s), controller.signal); + setTimeout(() => controller.abort(), 200); + expect((await pending).kind).toBe('deny'); + expect(Date.now() - started).toBeLessThan(5_000); + }); +}); + +function s0Dir(): string { + return os.tmpdir(); +} + +describe('HTTP hooks', () => { + let server: Server | undefined; + let url = ''; + let reply: { status: number; body: string } = { status: 200, body: '' }; + let lastBody = ''; + let lastAuth: string | undefined; + + async function start(): Promise { + if (server) return; + server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + lastBody = Buffer.concat(chunks).toString('utf8'); + lastAuth = req.headers['authorization']; + res.writeHead(reply.status, { 'content-type': 'application/json' }); + res.end(reply.body); + }); + }); + await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (address === null || typeof address === 'string') throw new Error('no address'); + url = `http://127.0.0.1:${address.port}/hook`; + } + + afterAll(async () => { + await new Promise((r) => server?.close(r)); + }); + + it('POSTs the input and applies the JSON decision', async () => { + await start(); + reply = { status: 200, body: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'http says no' } }) }; + const s = await setup({ + user: preHooks('Bash', { type: 'http', url, headers: { Authorization: 'Bearer $HOOK_TOKEN', 'X-Other': '$NOT_ALLOWED' }, allowedEnvVars: ['HOOK_TOKEN'] }), + }); + process.env['HOOK_TOKEN'] = 'tok'; + try { + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'deny', source: 'hook', reason: 'http says no' }); + } finally { + delete process.env['HOOK_TOKEN']; + } + expect(JSON.parse(lastBody)).toMatchObject({ tool_name: 'Bash', tool_input: { command: 'ls' } }); + expect(lastAuth).toBe('Bearer tok'); + }); + + it('treats a non-2xx status or a non-JSON body as a failure (deny), even with onFailure: continue', async () => { + await start(); + reply = { status: 500, body: 'oops' }; + const s = await setup({ user: preHooks('Bash', { type: 'http', url }) }); + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + reply = { status: 200, body: 'plain text' }; + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + reply = { status: 200, body: '' }; + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' }); + reply = { status: 503, body: '' }; + const lenient = await setup({ user: preHooks('Bash', { type: 'http', url, onFailure: 'continue', async: true }) }); + expect(await authorize(lenient, bash('ls', lenient.project))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + }); + + it('enforces allowedHttpHookUrls before sending and limits header variables to httpHookAllowedEnvVars', async () => { + await start(); + reply = { status: 200, body: '' }; + lastBody = ''; + const blocked = await setup({ user: { allowedHttpHookUrls: ['https://hooks.example.com/*'], ...preHooks('Bash', { type: 'http', url }) } }); + expect(await authorize(blocked, bash('ls', blocked.project))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + expect(lastBody).toBe(''); + const hook = { type: 'http', url, headers: { Authorization: 'Bearer $HOOK_TOKEN' }, allowedEnvVars: ['HOOK_TOKEN'] }; + const s = await setup({ user: { allowedHttpHookUrls: ['http://127.0.0.1:*'], httpHookAllowedEnvVars: [], ...preHooks('Bash', hook) } }); + process.env['HOOK_TOKEN'] = 'tok'; + try { + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' }); + } finally { + delete process.env['HOOK_TOKEN']; + } + expect(lastAuth).toBe('Bearer'); + }); + + it('names an http hook by its host only in caller-visible errors', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'http', url: 'http://127.0.0.1:9/hook?label=hidden-value', timeout: 5 }) }); + const decision = await authorize(s, bash('ls', s.project)); + expect(decision.kind).toBe('deny'); + expect(JSON.stringify(decision)).not.toContain('hidden-value'); + }); + + it('times out', async () => { + const hang = createServer(() => undefined); + await new Promise((resolve) => hang.listen(0, '127.0.0.1', resolve)); + const address = hang.address(); + if (address === null || typeof address === 'string') throw new Error('no address'); + const s = await setup({ user: preHooks('Bash', { type: 'http', url: `http://127.0.0.1:${address.port}/`, timeout: 0.3 }) }); + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + hang.closeAllConnections(); + await new Promise((r) => hang.close(r)); + }); +}); + +describe.skipIf(!posix)('PostToolUse hooks', () => { + it('reports a block as an error the dispatcher turns into a warning', async () => { + const s = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('exit2')] }] } } }); + const result = { exitCode: 0, signal: null, stdout: 'ok', stderr: '', truncated: false, timedOut: false }; + const signal = new AbortController().signal; + await expect(s.adapter.postToolUse(bash('ls', s.project), result, s.ctx, s.policy, signal)).rejects.toThrow(/blocked after the call ran.*blocked by example hook/); + const quiet = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('empty')] }] } } }); + await expect(quiet.adapter.postToolUse(bash('ls', quiet.project), result, quiet.ctx, quiet.policy, signal)).resolves.toBeUndefined(); + }); + + it('cancelling the run through the dispatcher kills a running PostToolUse hook', async () => { + const s0 = await setup(); + const pidFile = path.join(s0.base, 'post.pid'); + const s = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: `echo $$ > "${pidFile}"; exec sleep 30` }] }] } }, mode: 'bypassPermissions' }); + const tools = new MemoryToolRuntime({ root: '/workspace' }); + const dispatcher = new Dispatcher({ adapter: s.adapter, tools, ctx: { ...s.ctx, cwd: '/workspace', roots: ['/workspace'] }, policy: s.policy }); + const call = dispatcher.dispatch('bash', { command: 'echo hi' }); + for (let i = 0; i < 100 && !(await readFile(pidFile, 'utf8').catch(() => '')); i++) await new Promise((r) => setTimeout(r, 50)); + const pid = Number(await readFile(pidFile, 'utf8')); + await dispatcher.stop('cancelled'); + await call; + await new Promise((r) => setTimeout(r, 300)); + expect(() => process.kill(pid, 0)).toThrow(); + }); +}); + +describe('policy snapshot', () => { + it('lists protected paths and no containment without the sandbox', async () => { + const s = await setup(); + expect(s.policy.bashContainment).toEqual({ mode: 'none' }); + expect(s.policy.protectedPaths).toEqual( + expect.arrayContaining([ + path.join(s.project, '.claude', 'settings*.json'), + path.join(s.project, '.claude', 'hooks', '**'), + path.join(s.project, '.claude', 'agents', '**'), + path.join(s.project, '.mcp.json'), + path.join(s.home, '.claude', '**'), + path.join(s.base, 'state', '**'), + ]), + ); + }); + + it('returns a sandbox containment when Claude sandboxing is enabled', async () => { + const s = await setup({ user: { sandbox: { enabled: true, filesystem: { allowWrite: ['~/.cache/tool', '/opt/build'] } }, permissions: { additionalDirectories: ['/opt/extra'] } } }); + expect(s.policy.bashContainment).toEqual({ + mode: 'sandbox', + readOnly: false, + writableRoots: [s.project, path.resolve(s.project, '/opt/extra'), path.join(s.home, '.cache', 'tool'), path.resolve(s.project, '/opt/build')], + network: false, + }); + }); +}); + +describe.skipIf(!posix)('with the dispatcher', () => { + it('re-prepares and re-checks a hook rewrite; a rewrite into a denied command is refused', async () => { + const s = await setup({ + user: { + permissions: { deny: ['Bash(rm:*)'] }, + hooks: { + PreToolUse: [ + { matcher: 'Write', hooks: [exampleHook('update', JSON.stringify({ file_path: '/workspace/a.txt', content: 'sanitized' }))] }, + { matcher: 'Bash', hooks: [exampleHook('update', JSON.stringify({ command: 'rm -rf /workspace' }))] }, + ], + }, + }, + mode: 'bypassPermissions', + }); + const tools = new MemoryToolRuntime({ root: '/workspace' }); + const ctx: SessionContext = { ...s.ctx, cwd: '/workspace', roots: ['/workspace'] }; + const dispatcher = new Dispatcher({ adapter: s.adapter, tools, ctx, policy: s.policy }); + const wrote = await dispatcher.dispatch('write', { path: 'a.txt', content: 'secret' }); + expect(wrote.ok).toBe(true); + expect(tools.read('a.txt')).toBe('sanitized'); + const ran = await dispatcher.dispatch('bash', { command: 'echo hi' }); + expect(ran).toMatchObject({ ok: false, error: { name: 'PermissionDenied', source: 'rule' } }); + }); +}); + +describe('hook selection and execution context', () => { + it('denies with unsupported-config when a hook matcher is not a valid regular expression', async () => { + const s = await setup({ user: preHooks('(Bash', exampleHook('allow')) }); + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + }); + + it.skipIf(!posix)('runs `shell: bash` hooks under bash in the session directory, with CLAUDE_PROJECT_DIR at the project', async () => { + const command = '[ -n "$BASH_VERSION" ] && [ "$(pwd -P)" = "$CLAUDE_PROJECT_DIR/sub" ] || exit 2'; + const s = await setup({ user: preHooks('Bash', { type: 'command', command, shell: 'bash' }) }); + const sub = path.join(s.project, 'sub'); + await mkdir(sub); + const ctx: SessionContext = { ...s.ctx, cwd: sub }; + const policy = await s.adapter.loadPolicy(ctx); + if ('error' in policy) throw new Error(policy.error); + expect(await s.adapter.authorize(bash('ls', sub), ctx, policy, new AbortController().signal)).toEqual({ kind: 'allow' }); + }); +}); diff --git a/src/hosts/claude/adapter.ts b/src/hosts/claude/adapter.ts new file mode 100644 index 0000000..d573798 --- /dev/null +++ b/src/hosts/claude/adapter.ts @@ -0,0 +1,824 @@ +import { lstat, realpath } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { errorMessage } from '../../core/errors.js'; +import { findMatchingPattern } from '../../core/paths.js'; +import { stateDirPath } from '../../core/state-dir.js'; +import type { + BashContainment, + Decision, + HostAdapter, + PolicyLoadError, + PolicySnapshot, + PreparedCall, + SessionContext, + ToolResult, +} from '../../core/types.js'; +import { BashAnalyzer, type BashAnalysis } from './bash.js'; +import { + NATIVE_TOOL, + combineOutcomes, + mapUpdatedInput, + invalidMatcher, + matcherMatches, + nativeCall, + nativeResponse, + runHook, + unsupportedReason, + type CompiledHook, + type HookOutcome, + type NativeCall, +} from './hooks.js'; +import { conservativeFlags, parseClaudeFlags, readParentClaudeProcess, type ClaudeCliFlags, type ParentArgsReader } from './parent-args.js'; +import { + bashSpecMayMatchDynamic, + isInsidePath, + isValidRuleSyntax, + matchesBashSpec, + matchesParamValue, + matchesPath, + matchesToolName, + parseRule, + resolveCommandPath, + toPosixPath, + type NativeToolName, + type PathPattern, + type Rule, + type RuleKind, +} from './rules.js'; +import { claudeConfigDir, firstSetting, loadSettings, managedSettingsDir, type LoadedSettings, type SettingsDoc } from './settings.js'; +import type { HookMatcherEntry } from './settings.js'; + +/** + * Claude Code host adapter. + * + * Static check (`checkStatic`, no I/O): permission rules from every settings + * source, deny → ask → allow, first match wins, then the permission mode for + * calls no rule decides. Hooks (`authorize`): the PreToolUse hooks that match + * the native tool name, run in parallel with the JSON Claude Code would send. + */ + +/** Claude permission modes. Unknown values are treated as `default`. */ +export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'dontAsk' | 'auto' | 'bypassPermissions'; + +const MODES: readonly PermissionMode[] = ['default', 'acceptEdits', 'plan', 'dontAsk', 'auto', 'bypassPermissions']; + +function toMode(value: string | undefined): PermissionMode | undefined { + if (value === 'manual') return 'default'; + return MODES.find((m) => m === value); +} + +export interface ClaudePolicy { + readonly projectRoot: string; + readonly cwd: string; + readonly home: string; + readonly configDir: string; + readonly mode: PermissionMode; + readonly rules: { readonly deny: readonly Rule[]; readonly ask: readonly Rule[]; readonly allow: readonly Rule[] }; + /** Project root, MCP roots and additional directories: reads there need no approval. */ + readonly workingDirs: readonly string[]; + /** Working directories for the block-outside settings: directories only repository settings add do not count. */ + readonly blockDirs: readonly string[]; + /** On Windows no trusted record carries the live permission mode: only calls every mode allows may run. */ + readonly modeUnknown: boolean; + readonly preHooks: readonly CompiledHook[]; + readonly postHooks: readonly CompiledHook[]; + /** Env added for every hook. */ + readonly hookEnv: Readonly>; + /** Set when a sandbox restriction cannot be expressed as bash containment: every bash call is denied. */ + readonly bashUnsupported: string | undefined; + /** `blockReadsOutsideWorkingDirectories` / `blockWritesOutsideWorkingDirectories` from any source. */ + readonly blockReadsOutside: boolean; + readonly blockWritesOutside: boolean; + /** + * Whether a Read deny rule covers a real absolute path. The tool runtime + * must drop such files from grep and glob results: a recursive search + * otherwise returns what `read` would refuse. + */ + readonly isReadDenied: (absPath: string) => boolean; +} + +export interface ClaudeHostAdapterOptions { + readonly env?: Readonly>; + readonly home?: string; + /** Managed settings directory; `null` disables managed settings (tests). Defaults to the platform path. */ + readonly managedDir?: string | null; + /** Server state directory (protected). Defaults to `stateDirPath()`. */ + readonly stateDir?: string; + /** Reads the parent Claude process argv. Defaults to the platform reader. */ + readonly readParent?: ParentArgsReader; + readonly platform?: NodeJS.Platform; +} + +const NO_FLAGS: ClaudeCliFlags = { settings: [], allowedTools: [], disallowedTools: [], addDirs: [] }; + +/** Which native tools a rule's tool name governs. */ +function governs(rule: Rule, tool: NativeToolName): boolean { + if (matchesToolName(rule.tool, tool)) return true; + if (rule.tool === 'Read') return tool === 'Grep' || tool === 'Glob' || (rule.kind === 'deny' && (tool === 'Write' || tool === 'Edit')); + if (rule.tool === 'Edit') return tool === 'Write'; + return false; +} + +/** Paths a file call touches: the path as given in args (may be the requested path) and the real path of the effect. */ +function callPaths(prepared: PreparedCall): string[] { + switch (prepared.tool) { + case 'read': + case 'write': + case 'edit': + return [...new Set([prepared.args.path, prepared.effect.absPath])]; + case 'grep': + case 'glob': + return [...new Set([...(prepared.args.path === undefined ? [] : [prepared.args.path]), prepared.effect.absRoot])]; + case 'bash': + return []; + } +} + +type Verdict = 'match' | 'maybe' | 'no'; + +interface CallView { + readonly prepared: PreparedCall; + readonly native: NativeCall; + readonly analysis: BashAnalysis | undefined; + /** Resolved file targets of a bash command; undefined path = only known at run time. */ + readonly bashFiles: readonly { readonly access: 'read' | 'write'; readonly path: string | undefined }[]; +} + +function pathRuleVerdict(patterns: readonly PathPattern[], paths: readonly string[], kind: RuleKind): Verdict { + if (paths.length === 0) return 'no'; + const hits = paths.map((p) => matchesPath(p, patterns)); + // Deny/ask: either the requested or the real path. Allow: both. + return (kind === 'allow' ? hits.every(Boolean) : hits.some(Boolean)) ? 'match' : 'no'; +} + +/** Evaluates one deny/ask rule against a call. */ +function restrictVerdict(rule: Rule, view: CallView): Verdict { + const { prepared, native } = view; + const m = rule.matcher; + if (m.type === 'never') return 'no'; + if (prepared.tool === 'bash' && view.analysis) { + // File targets of the command (redirects, tee, cat ...) against Read/Edit rules. + let fileVerdict: Verdict = 'no'; + const targetTool = (access: 'read' | 'write'): NativeToolName => (access === 'read' ? 'Read' : 'Edit'); + for (const target of view.bashFiles) { + const asTool = targetTool(target.access); + if (!(matchesToolName(rule.tool, asTool) || (rule.tool === 'Read' && rule.kind === 'deny' && asTool === 'Edit'))) continue; + if (m.type === 'all') return 'match'; + if (m.type !== 'path') continue; + if (target.path === undefined) fileVerdict = 'maybe'; + else if (matchesPath(target.path, m.patterns)) return 'match'; + } + if (!governs(rule, 'Bash')) return fileVerdict; + if (m.type === 'all') return 'match'; + if (m.type === 'param') { + if (matchesParamValue(m.value, native.toolInput[m.name])) return 'match'; + if (m.bashSpec === undefined) return fileVerdict; + } + const spec = m.type === 'bash' ? m.spec : m.type === 'param' ? m.bashSpec : undefined; + if (spec === undefined) return fileVerdict; + let verdict: Verdict = fileVerdict; + for (const cmd of view.analysis.commands) { + if (cmd.denyForms.some((form) => matchesBashSpec(spec, form))) return 'match'; + if (cmd.dynamic && cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(spec, prefix))) verdict = 'maybe'; + } + return verdict; + } + if (!governs(rule, native.toolName)) return 'no'; + switch (m.type) { + case 'all': + return 'match'; + case 'param': + return matchesParamValue(m.value, native.toolInput[m.name]) ? 'match' : 'no'; + case 'path': + return pathRuleVerdict(m.patterns, callPaths(prepared), rule.kind); + case 'bash': + return 'no'; + } +} + +function insideWorkingDirs(paths: readonly string[], dirs: readonly string[]): boolean { + return paths.length > 0 && paths.every((p) => dirs.some((d) => isInsidePath(p, d))); +} + +/** Whether allow rules approve the call. */ +function allowedByRule(view: CallView, rules: readonly Rule[], policy: ClaudePolicy): boolean { + const { prepared, native } = view; + // Auto mode drops shell allow rules broader than one exact command. + const broadShell = (r: Rule): boolean => governs(r, 'Bash') && (r.matcher.type === 'all' || (r.matcher.type === 'bash' && r.matcher.spec.includes('*'))); + const applicable = rules.filter((r) => r.matcher.type !== 'never' && !(policy.mode === 'auto' && broadShell(r))); + if (prepared.tool === 'bash') { + const analysis = view.analysis; + const blanket = applicable.some((r) => governs(r, 'Bash') && r.matcher.type === 'all'); + // Files the command names must be inside the working directories, whatever approves the command. + const filesInside = view.bashFiles.every((f) => f.path !== undefined && policy.workingDirs.some((d) => isInsidePath(f.path ?? '', d))); + if (!analysis || analysis.uncertain.length > 0 || analysis.commands.length === 0) return blanket && filesInside; + if (blanket && view.bashFiles.length === 0) return true; + // Every subcommand must be approved; files it names must be inside the working directories. + const everyCommand = analysis.commands.every((cmd) => { + const form = cmd.allowForm; + if (form === undefined) return false; + // An exec wrapper or effectful `find` needs an exact rule, not a wildcard one. + return applicable.some((r) => governs(r, 'Bash') && (r.matcher.type === 'all' || (r.matcher.type === 'bash' && !(cmd.exactOnly && r.matcher.spec.includes('*')) && matchesBashSpec(r.matcher.spec, form)))); + }); + return everyCommand && filesInside; + } + const paths = callPaths(prepared); + return applicable.some((r) => { + if (!governs(r, native.toolName) || r.kind !== 'allow') return false; + if (r.matcher.type === 'all') return true; + if (r.matcher.type === 'path') return pathRuleVerdict(r.matcher.patterns, paths, 'allow') === 'match'; + return false; + }); +} + +/** What the permission mode does with a call that no rule decided. */ +function modeDecision(view: CallView, policy: ClaudePolicy): Decision { + const { prepared } = view; + const mode = policy.mode; + const tool = NATIVE_TOOL[prepared.tool]; + const isRead = prepared.tool === 'read' || prepared.tool === 'grep' || prepared.tool === 'glob'; + const isEdit = prepared.tool === 'write' || prepared.tool === 'edit'; + const inside = isRead || isEdit ? insideWorkingDirs(callPaths(prepared), policy.workingDirs) : false; + if (mode === 'bypassPermissions') return { kind: 'allow' }; + if (mode === 'auto') { + // No classifier verdict reaches this server: only step 2 (reads and edits inside the working directories) applies. + if ((isRead || isEdit) && inside) return { kind: 'allow' }; + return { + kind: 'ask', + reason: `auto mode: no classifier verdict covers this script; ${tool}${isRead || isEdit ? ' outside the working directories' : ''} needs approval`, + }; + } + if (isRead) { + if (inside) return { kind: 'allow' }; + if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} outside the working directories is not pre-approved by an allow rule` }; + return { kind: 'ask', reason: `${tool} outside the working directories needs approval in ${mode} mode` }; + } + if (mode === 'plan') return { kind: 'deny', source: 'rule', reason: `plan mode does not allow ${tool}` }; + if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} is not pre-approved by an allow rule` }; + if (isEdit && mode === 'acceptEdits' && inside) return { kind: 'allow' }; + return { kind: 'ask', reason: `${tool} needs approval in ${mode} mode` }; +} + +/** Limits no rule or mode lifts: protected host paths and the block-outside settings; an unknown bash target asks. */ +function hardLimit(view: CallView, policy: ClaudePolicy, protectedPaths: readonly string[]): Decision | undefined { + const { prepared } = view; + const outside = (p: string): boolean => !policy.blockDirs.some((d) => isInsidePath(p, d)); + const blocked = (access: 'read' | 'write'): boolean => (access === 'read' ? policy.blockReadsOutside : policy.blockWritesOutside); + const deny = (reason: string): Decision => ({ kind: 'deny', source: 'rule', reason }); + if (prepared.tool !== 'bash') { + const access = prepared.tool === 'write' || prepared.tool === 'edit' ? 'write' : 'read'; + return blocked(access) && callPaths(prepared).some(outside) ? deny(`${NATIVE_TOOL[prepared.tool]} outside the working directories is blocked by settings`) : undefined; + } + for (const f of view.bashFiles) { + if (f.path === undefined) { + if (f.access === 'write' || blocked('read')) return { kind: 'ask', reason: `the command ${f.access === 'write' ? 'writes' : 'reads'} a file only known at run time, which cannot be checked statically` }; + continue; + } + if (f.access === 'write' && findMatchingPattern(nativePath(f.path), protectedPaths) !== undefined) return deny(`the command writes ${f.path}, a protected host policy path`); + if (blocked(f.access) && outside(f.path)) return deny(`the command ${f.access === 'write' ? 'writes' : 'reads'} ${f.path} outside the working directories, which settings block`); + } + return undefined; +} + +const TOP_LEVEL = /^\/[^/]+$/; + +/** + * A recognized `rm`/`rmdir` removal of a critical path (filesystem root, a + * top-level directory, home, the working directory or a parent of it, a bare + * `*` glob under a working directory, a recursive removal of a target only + * known at run time). No allow rule, mode or hook approves one + * (https://code.claude.com/docs/en/permission-modes, "Critical paths"). + */ +function criticalRemoval(view: CallView, policy: ClaudePolicy): string | undefined { + const analysis = view.analysis; + if (!analysis || view.prepared.tool !== 'bash') return undefined; + const cwd = view.prepared.effect.cwd; + const anchors = [cwd, policy.projectRoot]; + const isCritical = (p: string, glob: boolean): boolean => { + const posix = toPosixPath(p); + if (posix === '/' || TOP_LEVEL.test(posix)) return true; + if (isInsidePath(toPosixPath(policy.home), posix) && isInsidePath(posix, toPosixPath(policy.home))) return true; + if (anchors.some((a) => isInsidePath(a, posix))) return true; // the working directory or one of its parents + return glob && policy.workingDirs.some((d) => isInsidePath(d, posix)); + }; + for (const removal of analysis.removals) { + for (const target of removal.targets) { + if (target.value === undefined) { + if (removal.recursive || target.glob) return `\`rm ${target.raw}\` removes a target only known at run time`; + continue; + } + let value = target.value; + let glob = false; + if (target.glob) { + const segments = value.split('/'); + const stars = segments.filter((seg) => /[*?[]/.test(seg)); + if (stars.length > 1) return `\`rm ${target.raw}\` reaches directories that cannot be known before it runs`; + const at = segments.findIndex((seg) => seg === '*'); + if (at === -1) continue; + value = segments.slice(0, at).join('/') || (value.startsWith('/') ? '/' : '.'); + glob = true; + } + const relative = !(value.startsWith('/') || value.startsWith('~') || path.isAbsolute(value)); + if (relative && analysis.changesDirectory) { + if (glob || value === '.' || value === '..' || value.startsWith('../')) return `\`rm ${target.raw}\` after \`cd\` may remove a working directory`; + continue; + } + if (isCritical(resolveCommandPath(value, cwd, policy.home), glob)) return `\`rm ${target.raw}\` removes a critical path`; + } + } + return undefined; +} + +/** A POSIX-form path (`/c/x`) in the platform's own form (`c:/x` on Windows). */ +function nativePath(p: string): string { + return process.platform === 'win32' ? p.replace(/^\/([A-Za-z])(\/|$)/, '$1:/') : p; +} + +function errnoCode(err: unknown): unknown { + return err !== null && typeof err === 'object' && 'code' in err ? err.code : undefined; +} + +/** Resolves links (symlinks, junctions) of a command's file target: its deepest existing ancestor, plus the missing rest; undefined when unknown. */ +async function realTarget(p: string): Promise { + const missing: string[] = []; + for (let dir = p; ; ) { + try { + return path.posix.join(toPosixPath(await realpath(nativePath(dir))), ...missing); + } catch (err) { + // Only an absent name is a missing suffix: a dangling link (also ENOENT for `realpath`) or another error is unknown. + if (errnoCode(err) !== 'ENOENT' || (await lstat(nativePath(dir)).then(() => true, (e: unknown) => errnoCode(e) !== 'ENOENT'))) return undefined; + const parent = path.posix.dirname(dir); + if (parent === dir) return undefined; + missing.unshift(path.posix.basename(dir)); + dir = parent; + } + } +} + +/** The canonical location of a protected pattern written through a link (`~/.claude/**` under a linked home), if different. */ +async function canonicalPattern(pattern: string): Promise { + const { head, rest } = literalHead(toPosixPath(pattern)); + if (head === '') return undefined; + const real = await realTarget(head); + return real === undefined || real === head ? undefined : path.join(nativePath(real), rest); +} + +function describe(rule: Rule): string { + return `${rule.kind} rule ${JSON.stringify(rule.raw)} from ${rule.source} settings`; +} + +function compileHooks(entries: readonly HookMatcherEntry[] | undefined, origin: string, env: Readonly>, platform: NodeJS.Platform, seen: Set, http: { readonly urls: readonly string[][]; readonly envVars: readonly string[][] }, blocked?: string): CompiledHook[] { + const out: CompiledHook[] = []; + for (const entry of entries ?? []) { + for (const configured of entry.hooks) { + // The same handler defined in several settings files runs once. + const key = JSON.stringify([entry.matcher ?? '', configured, env]); + if (seen.has(key)) continue; + seen.add(key); + let unsupported = blocked ?? invalidMatcher(entry.matcher) ?? unsupportedReason(configured, platform); + let handler = configured; + if (configured.type === 'http') { + // The allowlists are matched against the URL fetch will request (`https://h` names `https://h/` too), and fetch gets that URL. + const raw = configured.url ?? ''; + const href = URL.canParse(raw) ? new URL(raw).href : undefined; + const forms = href === `${raw}/` ? [href, raw] : [href ?? '']; + if (unsupported === undefined && href === undefined) unsupported = 'http hook url cannot be parsed'; + else if (unsupported === undefined && !http.urls.every((list) => list.some((pattern) => forms.some((form) => matchesParamValue(pattern, form))))) unsupported = 'http hook url is not allowed by allowedHttpHookUrls'; + // A header may interpolate only variables every applicable list allows. + handler = { ...configured, ...(href === undefined ? {} : { url: href }), allowedEnvVars: (configured.allowedEnvVars ?? []).filter((name) => http.envVars.every((list) => list.includes(name))) }; + } + out.push({ handler, matcher: entry.matcher, origin, env, unsupported }); + } + } + return out; +} + +/** Literal leading directory of a glob pattern (before the first segment with a glob character). */ +function literalHead(pattern: string): { head: string; rest: string } { + const segments = pattern.split('/'); + const i = segments.findIndex((s) => /[*?[]/.test(s)); + const cut = i === -1 ? Math.max(0, segments.length - 1) : i; + return { head: segments.slice(0, cut).join('/'), rest: segments.slice(cut).join('/') }; +} + +/** Adds the real location of rules written through a symlinked directory (`//etc/**` → `/private/etc/**`). */ +async function withRealAnchors(rule: Rule): Promise { + if (rule.matcher.type !== 'path' || rule.kind === 'allow') return rule; + const extra: PathPattern[] = []; + for (const p of rule.matcher.patterns) { + if (p.pattern.startsWith('**')) continue; + const { head, rest } = literalHead(p.pattern); + const dir = path.posix.join(p.anchor, head); + try { + const real = toPosixPath(await realpath(dir)); + if (real !== dir && rest !== '') extra.push({ anchor: real, pattern: rest }); + else if (real !== dir) extra.push({ anchor: path.posix.dirname(real), pattern: path.posix.basename(real) }); + } catch { + // Missing directory: nothing to alias. + } + } + return extra.length === 0 ? rule : { ...rule, matcher: { type: 'path', patterns: [...rule.matcher.patterns, ...extra] } }; +} + +function resolveDir(p: string, base: string, home: string): string { + if (p === '~') return home; + if (p.startsWith('~/')) return path.join(home, p.slice(2)); + return path.resolve(base, p); +} + +export class ClaudeHostAdapter implements HostAdapter { + readonly host = 'claude' as const; + readonly #opts: ClaudeHostAdapterOptions; + + constructor(opts: ClaudeHostAdapterOptions = {}) { + this.#opts = opts; + } + + async loadPolicy(ctx: SessionContext): Promise | PolicyLoadError> { + try { + return await this.#load(ctx); + } catch (err) { + return { error: errorMessage(err) }; + } + } + + async #load(ctx: SessionContext): Promise> { + const env = this.#opts.env ?? process.env; + const home = this.#opts.home ?? os.homedir(); + const platform = this.#opts.platform ?? process.platform; + const configDir = claudeConfigDir(env, home); + const projectRoot = ctx.roots[0] ?? ctx.cwd; + const stateDir = this.#opts.stateDir ?? stateDirPath(env, home); + const managedDir = this.#opts.managedDir === null ? undefined : (this.#opts.managedDir ?? managedSettingsDir(platform)); + const parent = await (this.#opts.readParent ?? readParentClaudeProcess)(); + // A joined command line (macOS `ps`) is never run through the exact-argv parser. + const flags = parent === undefined ? NO_FLAGS : parent.lossy === true ? conservativeFlags(parent.argv) : parseClaudeFlags(parent.argv); + const parentCwd = parent?.cwd !== undefined && path.isAbsolute(parent.cwd) ? parent.cwd : undefined; + const liveCwd = ctx.sources['cwd'] === 'ctx-file' ? ctx.cwd : undefined; + // Project and local settings and their rules anchor at the primary directory: Claude's process directory, else the + // companion record's cwd, else the first MCP root. Hooks run in the session's cwd. CLAUDE_PROJECT_DIR stays the startup root. + const primaryDir = parentCwd ?? liveCwd ?? projectRoot; + const sessionCwd = liveCwd ?? parentCwd ?? ctx.cwd; + const settings: LoadedSettings = await loadSettings({ projectRoot: primaryDir, home, configDir, managedDir, env, flags, parentCwd: parent?.cwd }); + const docs = settings.docs; + + // Permission rules. + const managedOnly = firstSetting(docs.filter((d) => d.source === 'managed'), (s) => s.allowManagedPermissionRulesOnly) === true; + const ruleDocs = managedOnly ? docs.filter((d) => d.source === 'managed') : docs; + const holdsCapability = (doc: SettingsDoc): boolean => (doc.source === 'project' || doc.source === 'local') && !settings.projectTrusted; + const rules: { deny: Rule[]; ask: Rule[]; allow: Rule[] } = { deny: [], ask: [], allow: [] }; + // A malformed rule would match nothing; refuse the whole policy instead of failing open. + for (const doc of docs) { + for (const kind of ['deny', 'ask', 'allow'] as const) { + for (const raw of doc.data.permissions?.[kind] ?? []) { + if (!isValidRuleSyntax(raw)) { + throw new Error(`${kind} rule ${JSON.stringify(raw)} in ${doc.file ?? `${doc.source} settings`} is not a valid \`Tool\` or \`Tool(specifier)\` rule`); + } + } + } + } + for (const doc of ruleDocs) { + const anchors = { cwd: ctx.cwd, sourceDir: doc.anchorDir, home }; + for (const kind of ['deny', 'ask', 'allow'] as const) { + if (kind === 'allow' && holdsCapability(doc)) continue; + for (const raw of doc.data.permissions?.[kind] ?? []) { + const rule = parseRule(raw, kind, doc.source, anchors); + if (!rule) throw new Error(`${kind} rule ${JSON.stringify(raw)} in ${doc.file ?? doc.source} cannot be parsed`); + rules[kind].push(await withRealAnchors(rule)); + } + } + } + + // Working directories. The block-outside settings ignore directories only repository settings add. + const startDirs = [projectRoot, primaryDir, ctx.cwd, sessionCwd, ...ctx.roots]; + const workingDirs = new Set(startDirs); + const blockDirs = new Set(startDirs); + for (const doc of docs) { + if (holdsCapability(doc)) continue; + for (const dir of doc.data.permissions?.additionalDirectories ?? []) { + const resolved = resolveDir(dir, primaryDir, home); + workingDirs.add(resolved); + if (doc.source !== 'project' && doc.source !== 'local') blockDirs.add(resolved); + } + } + + // Permission mode: the live mode from the companion hook, else the CLI flag, else the highest settings default. + // Project and local settings cannot start auto or bypassPermissions, nor acceptEdits before the workspace is trusted: + // a rejected one starts Manual (default) mode, it does not fall through to a lower source. + const fromCtx = ctx.sources['permissionMode'] !== undefined && ctx.sources['permissionMode'] !== 'default' ? toMode(ctx.permissionMode) : undefined; + const defaultDoc = docs.find((d) => toMode(d.data.permissions?.defaultMode) !== undefined); + const settingsMode = toMode(defaultDoc?.data.permissions?.defaultMode); + const rejected = (defaultDoc?.source === 'project' || defaultDoc?.source === 'local') && (settingsMode === 'auto' || settingsMode === 'bypassPermissions' || (settingsMode === 'acceptEdits' && !settings.projectTrusted)); + let mode: PermissionMode = fromCtx ?? toMode(flags.permissionMode) ?? (rejected ? 'default' : settingsMode) ?? 'default'; + if (mode === 'bypassPermissions' && firstSetting(docs, (s) => s.permissions?.disableBypassPermissionsMode) === 'disable') mode = 'default'; + if (mode === 'auto' && firstSetting(docs, (s) => s.permissions?.disableAutoMode) === 'disable') mode = 'default'; + + // Hooks, under the controls the loader resolved. + const controls = settings.hookControls; + // A handler defined in several sources runs once per event, never across events. + const seenPre = new Set(); + const seenPost = new Set(); + const pre: CompiledHook[] = []; + const post: CompiledHook[] = []; + // `allowedHttpHookUrls` / `httpHookAllowedEnvVars` of every source that sets them: each list must allow. + const http = { + urls: docs.flatMap((d) => (d.data.allowedHttpHookUrls === undefined ? [] : [d.data.allowedHttpHookUrls])), + envVars: docs.flatMap((d) => (d.data.httpHookAllowedEnvVars === undefined ? [] : [d.data.httpHookAllowedEnvVars])), + }; + for (const doc of docs) { + if (controls.allOff) break; + if (doc.source !== 'managed' && controls.managedOnly) continue; + const origin = `${doc.source} settings`; + pre.push(...compileHooks(doc.data.hooks?.PreToolUse, origin, {}, platform, seenPre, http)); + post.push(...compileHooks(doc.data.hooks?.PostToolUse, origin, {}, platform, seenPost, http)); + } + // The loader already applied the hook controls to plugins; an unverifiable plugin source makes its hooks deny. + const unverified = controls.commandPluginsBlocked ? 'the plugin installation source cannot be verified while command-sourced plugins are disabled' : undefined; + for (const plugin of settings.plugins) { + const env = { CLAUDE_PLUGIN_ROOT: plugin.root }; + pre.push(...compileHooks(plugin.hooks.PreToolUse, `plugin ${plugin.plugin}`, env, platform, seenPre, http, unverified)); + post.push(...compileHooks(plugin.hooks.PostToolUse, `plugin ${plugin.plugin}`, env, platform, seenPost, http, unverified)); + } + + // Bash containment: Claude's sandbox when enabled. + let bashContainment: BashContainment = { mode: 'none' }; + let bashUnsupported: string | undefined; + const blockReadsOutside = docs.some((d) => d.data.permissions?.blockReadsOutsideWorkingDirectories === true); + if (firstSetting(docs, (s) => s.sandbox?.enabled) === true) { + const roots = new Set([projectRoot, ...workingDirs]); + // Managed filesystem settings lock the key: lower sources cannot turn the filesystem sandbox off. + const managedFs = docs.some((d) => d.source === 'managed' && d.data.sandbox?.filesystem !== undefined); + const fsDisabled = firstSetting( + docs.filter((d) => d.source === 'managed' || (!managedFs && (d.source === 'user' || d.source === 'flag-settings'))), + (s) => s.sandbox?.filesystem?.disabled, + ); + // Containment has writable roots only: no read or write exclusion the sandbox would enforce can be expressed. + // Claude adds Read and Edit deny rules to denyRead/denyWrite, and the read block narrows sandbox reads. + const projected = fsDisabled !== true && (blockReadsOutside || rules.deny.some((r) => (governs(r, 'Read') || governs(r, 'Edit')) && (r.matcher.type === 'path' || r.matcher.type === 'all'))); + if (projected || docs.some((d) => (d.data.sandbox?.filesystem?.denyWrite?.length ?? 0) > 0 || (d.data.sandbox?.filesystem?.denyRead?.length ?? 0) > 0)) { + bashUnsupported = 'sandbox filesystem exclusions (denyRead/denyWrite, Read and Edit deny rules, blockReadsOutsideWorkingDirectories) cannot be enforced by bash containment'; + } + // Sandbox paths: `//` or `/` absolute, `~/` home, others relative to the settings file's anchor (project root or + // config directory); a relative path from a source without a documented anchor adds no root. + for (const doc of docs) { + const anchored = doc.source === 'project' || doc.source === 'local' || doc.source === 'user'; + for (const entry of doc.data.sandbox?.filesystem?.allowWrite ?? []) { + const e = entry.startsWith('//') ? entry.slice(1) : entry; + if (anchored || path.isAbsolute(e) || e === '~' || e.startsWith('~/')) roots.add(path.resolve(resolveDir(e, doc.anchorDir, home))); + } + } + bashContainment = { + mode: 'sandbox', + readOnly: false, + writableRoots: fsDisabled === true ? [path.parse(projectRoot).root] : [...roots], + // Claude's sandbox filters network by domain through a proxy; a boolean + // cannot express an allowlist, so network stays off (strict). + network: false, + }; + } + + const lexicalProtected = [ + ...new Set([ + ...[projectRoot, primaryDir, ctx.cwd, sessionCwd].flatMap((root) => [ + path.join(root, '.claude', 'settings*.json'), + path.join(root, '.claude', 'hooks', '**'), + path.join(root, '.claude', 'agents', '**'), + path.join(root, '.mcp.json'), + ]), + path.join(configDir, '**'), + path.join(home, '.claude', '**'), + path.join(home, '.claude.json'), + ...(managedDir === undefined ? [] : [path.join(managedDir, '**')]), + path.join(stateDir, '**'), + ...docs.flatMap((d) => ((d.source === 'flag-settings' || d.source === 'local') && d.file !== undefined ? [d.file] : [])), + ]), + ]; + // A write that resolves through a link is checked at its canonical location: protect that location too. + const canonical = await Promise.all(lexicalProtected.map(canonicalPattern)); + const protectedPaths = [...new Set([...lexicalProtected, ...canonical.filter((p) => p !== undefined)])]; + + return { + host: 'claude', + bashContainment, + protectedPaths, + payload: { + projectRoot, + cwd: sessionCwd, + home, + configDir, + mode, + rules, + workingDirs: [...workingDirs], + blockDirs: [...blockDirs], + modeUnknown: platform === 'win32' && fromCtx === undefined, + preHooks: pre, + postHooks: post, + hookEnv: { CLAUDE_PROJECT_DIR: projectRoot }, + bashUnsupported, + blockReadsOutside, + blockWritesOutside: docs.some((d) => d.data.permissions?.blockWritesOutsideWorkingDirectories === true), + isReadDenied: (absPath: string): boolean => + rules.deny.some((r) => governs(r, 'Read') && (r.matcher.type === 'all' || (r.matcher.type === 'path' && matchesPath(absPath, r.matcher.patterns)))), + }, + }; + } + + #view(prepared: PreparedCall, policy: ClaudePolicy): CallView { + const native = nativeCall(prepared); + if (prepared.tool !== 'bash') return { prepared, native, analysis: undefined, bashFiles: [] }; + const analysis = BashAnalyzer.analyze(prepared.effect.command); + const bashFiles = analysis.files.map((f) => { + if (f.path === undefined) return { access: f.access, path: undefined }; + const relative = !(f.path.startsWith('/') || f.path.startsWith('~') || path.isAbsolute(f.path)); + // After a `cd`, a relative target cannot be resolved statically. + if (relative && analysis.changesDirectory) return { access: f.access, path: undefined }; + return { access: f.access, path: resolveCommandPath(f.path, prepared.effect.cwd, policy.home) }; + }); + return { prepared, native, analysis, bashFiles }; + } + + /** Deny and ask rules. Undefined when none decides. */ + #restrictions(view: CallView, policy: ClaudePolicy): Decision | undefined { + const askOrDeny = (reason: string): Decision => + policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason }; + for (const rule of policy.rules.deny) { + const v = restrictVerdict(rule, view); + if (v === 'match') return { kind: 'deny', source: 'rule', reason: `denied by ${describe(rule)}` }; + } + // A deny rule that may match once run-time values are known: cannot be settled statically. + for (const rule of policy.rules.deny) { + if (restrictVerdict(rule, view) === 'maybe') return askOrDeny(`${describe(rule)} may match parts of the command that are only known at run time`); + } + for (const rule of policy.rules.ask) { + const v = restrictVerdict(rule, view); + if (v !== 'no') return askOrDeny(`${describe(rule)} matches`); + } + return undefined; + } + + checkStatic(prepared: PreparedCall, _ctx: SessionContext, snapshot: PolicySnapshot): Decision { + return this.#decide(this.#view(prepared, snapshot.payload), snapshot); + } + + #decide(view: CallView, snapshot: PolicySnapshot): Decision { + const decision = this.#decideInMode(view, snapshot); + if (!snapshot.payload.modeUnknown || decision.kind === 'deny') return decision; + // Unknown live mode (Windows): only what every mode allows runs, which is a read that needs no prompt. + const readOnly = view.prepared.tool === 'read' || view.prepared.tool === 'grep' || view.prepared.tool === 'glob'; + if (decision.kind === 'allow' && readOnly) return decision; + return { + kind: 'deny', + source: 'unsupported-config', + reason: `the live Claude Code permission mode is unknown on Windows (no trusted session record), so ${NATIVE_TOOL[view.prepared.tool]} cannot be authorized`, + }; + } + + #decideInMode(view: CallView, snapshot: PolicySnapshot): Decision { + const policy = snapshot.payload; + const askOrDeny = (reason: string): Decision => + policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason }; + if (view.prepared.tool === 'bash' && policy.bashUnsupported !== undefined) return { kind: 'deny', source: 'unsupported-config', reason: policy.bashUnsupported }; + const restricted = this.#restrictions(view, policy); + if (restricted) return restricted; + if (view.analysis && view.analysis.uncertain.length > 0) { + return askOrDeny(`the command cannot be checked statically (${view.analysis.uncertain.join('; ')})`); + } + const limit = hardLimit(view, policy, snapshot.protectedPaths); + if (limit) return limit.kind === 'ask' ? askOrDeny(limit.reason) : limit; + const critical = criticalRemoval(view, policy); + if (critical !== undefined) return askOrDeny(`${critical}; no rule or mode approves it`); + // Plan mode allows no change before the plan is approved, whatever the allow rules say. + const readOnly = view.prepared.tool === 'read' || view.prepared.tool === 'grep' || view.prepared.tool === 'glob'; + if (policy.mode === 'plan' && !readOnly) return modeDecision(view, policy); + if (allowedByRule(view, policy.rules.allow, policy)) return { kind: 'allow' }; + return modeDecision(view, policy); + } + + /** + * Re-decides a bash command on its file targets with links resolved (I/O, so not in `checkStatic`): + * `cat link` where `link -> .env` is denied, a target resolving outside the working dirs loses its allow. + */ + async #realFiles(prepared: PreparedCall, snapshot: PolicySnapshot): Promise { + if (prepared.tool !== 'bash') return undefined; + const view = this.#view(prepared, snapshot.payload); + const real = await Promise.all(view.bashFiles.map(async (f) => ({ access: f.access, path: f.path === undefined ? undefined : await realTarget(f.path) }))); + if (real.every((f, i) => f.path === view.bashFiles[i]?.path)) return undefined; + const again = this.#decide({ ...view, bashFiles: real }, snapshot); + return again.kind === 'allow' ? undefined : again; + } + + #select(hooks: readonly CompiledHook[], view: CallView, policy: ClaudePolicy): CompiledHook[] { + return hooks.filter((hook) => matcherMatches(hook.matcher, view.native.toolName) && this.#ifMatches(hook, view, policy)); + } + + /** The `if` filter: a hook is skipped only when the call certainly does not match its rule. */ + #ifMatches(hook: CompiledHook, view: CallView, policy: ClaudePolicy): boolean { + const condition = hook.handler.if; + if (condition === undefined) return true; + const rule = parseRule(condition, 'allow', 'project', { cwd: policy.cwd, sourceDir: policy.projectRoot, home: policy.home }); + if (!rule || rule.matcher.type === 'never') return true; + if (!matchesToolName(rule.tool, view.native.toolName) && !governs(rule, view.native.toolName)) return false; + const m = rule.matcher; + if (m.type === 'all') return true; + if (m.type === 'bash') { + const a = view.analysis; + if (!a || a.uncertain.length > 0) return true; + // Documented: a pattern naming more than the command (`Bash(git push *)`) runs the hook on any `$()`, backticks or `$VAR`. + const specific = (m.spec.split('*')[0] ?? '').trim().split(/\s+/).length > 1; + return a.commands.some( + (cmd) => cmd.denyForms.some((f) => matchesBashSpec(m.spec, f)) || (cmd.dynamic && (specific || cmd.staticPrefixes.some((prefix) => bashSpecMayMatchDynamic(m.spec, prefix)))), + ); + } + if (m.type === 'path') return pathRuleVerdict(m.patterns, callPaths(view.prepared), 'deny') === 'match'; + if (m.type === 'param') return matchesParamValue(m.value, view.native.toolInput[m.name]); + return true; + } + + #input(view: CallView, ctx: SessionContext, policy: ClaudePolicy, event: 'PreToolUse' | 'PostToolUse'): Record { + const { prepared, native } = view; + return { + session_id: ctx.sessionId ?? null, + transcript_path: ctx.transcriptPath ?? null, + // For bash the command runs in the effect's cwd, so that is what the hook is told. + cwd: prepared.tool === 'bash' ? prepared.effect.cwd : policy.cwd, + permission_mode: policy.mode, + hook_event_name: event, + tool_name: native.toolName, + tool_input: native.toolInput, + tool_use_id: `${ctx.toolUseId ?? 'unknown'}/${prepared.id}`, + ...(ctx.agentId === undefined ? {} : { agent_id: ctx.agentId }), + ...(ctx.agentType === undefined ? {} : { agent_type: ctx.agentType }), + }; + } + + async authorize(prepared: PreparedCall, ctx: SessionContext, snapshot: PolicySnapshot, signal: AbortSignal): Promise { + const policy = snapshot.payload; + const realFiles = await this.#realFiles(prepared, snapshot); + if (realFiles) return realFiles; + const view = this.#view(prepared, policy); + const hooks = this.#select(policy.preHooks, view, policy); + const unsupported = hooks.find((h) => h.unsupported !== undefined); + if (unsupported) { + return { kind: 'deny', source: 'unsupported-config', reason: `${unsupported.origin}: ${unsupported.unsupported ?? 'unsupported hook'}` }; + } + if (hooks.length === 0) return { kind: 'allow' }; + const input = this.#input(view, ctx, policy, 'PreToolUse'); + const opts = { event: 'PreToolUse' as const, input, cwd: policy.cwd, env: policy.hookEnv, signal }; + const blocking: Promise[] = []; + for (const hook of hooks) { + if (hook.handler.type === 'command' && (hook.handler.async === true || hook.handler.asyncRewake === true)) { + // Background hooks cannot block natively either; run them and ignore the result. + void runHook(hook, opts); + continue; + } + blocking.push(runHook(hook, opts)); + } + const combined = combineOutcomes(await Promise.all(blocking)); + switch (combined.kind) { + case 'deny': + return combined; + case 'ask': + return { kind: 'ask', reason: combined.reason }; + case 'none': + case 'allow': { + if (combined.updatedInput === undefined) return { kind: 'allow', ...(combined.reason === undefined ? {} : { reason: combined.reason }) }; + const mapped = mapUpdatedInput(prepared, combined.updatedInput); + if ('error' in mapped) return { kind: 'deny', source: 'hook', reason: mapped.error }; + if (prepared.tool === 'bash' && 'command' in mapped.args) { + // The dispatcher re-checks the rewrite statically; the symlink check needs I/O, so it runs here. + const command = mapped.args.command; + const rewritten: PreparedCall = { ...prepared, args: { ...prepared.args, command }, effect: { ...prepared.effect, command } }; + const again = await this.#realFiles(rewritten, snapshot); + if (again) return again.kind === 'deny' ? again : { kind: 'ask', reason: `hook rewrite: ${again.reason}` }; + } + return { kind: 'allow', updatedArgs: mapped.args, ...(combined.reason === undefined ? {} : { reason: combined.reason }) }; + } + } + } + + async postToolUse(prepared: PreparedCall, result: ToolResult, ctx: SessionContext, snapshot: PolicySnapshot, signal: AbortSignal): Promise { + const policy = snapshot.payload; + const view = this.#view(prepared, policy); + const hooks = this.#select(policy.postHooks, view, policy); + if (hooks.length === 0) return; + const input = { ...this.#input(view, ctx, policy, 'PostToolUse'), tool_response: nativeResponse(prepared, result) }; + const opts = { event: 'PostToolUse' as const, input, cwd: policy.cwd, env: policy.hookEnv, signal }; + const notes: string[] = []; + const outcomes = await Promise.all( + hooks.map(async (hook) => { + if (hook.unsupported !== undefined) return { hook, outcome: { kind: 'failure', source: 'hook-error', reason: hook.unsupported } satisfies HookOutcome }; + if (hook.handler.type === 'command' && (hook.handler.async === true || hook.handler.asyncRewake === true)) { + void runHook(hook, opts); + return { hook, outcome: { kind: 'none' } satisfies HookOutcome }; + } + return { hook, outcome: await runHook(hook, opts) }; + }), + ); + for (const { hook, outcome } of outcomes) { + if (outcome.kind === 'deny') notes.push(`${hook.origin} PostToolUse hook blocked after the call ran (it was not undone): ${outcome.reason}`); + else if (outcome.kind === 'failure') notes.push(`${hook.origin} PostToolUse hook failed: ${outcome.reason}`); + } + if (notes.length > 0) throw new Error(notes.join('; ')); + } +} diff --git a/src/hosts/claude/bash.ts b/src/hosts/claude/bash.ts new file mode 100644 index 0000000..e103327 --- /dev/null +++ b/src/hosts/claude/bash.ts @@ -0,0 +1,742 @@ +import { parse, walk } from 'sh-syntax/sync'; +import type { CallExpr, DeclClause, File, Node, Redirect, Word, WordPart } from 'sh-syntax/sync'; + +/** + * Splits a Bash command line into the simple commands it would run, the way + * Claude Code does before it matches Bash permission rules, but stricter. + * + * Parser: `sh-syntax` (mvdan/sh, the parser behind shfmt, compiled to WASM + * with a synchronous Node entry). It understands the full bash grammar, so + * commands nested in `&&`, `||`, `;`, `|`, `&`, subshells, blocks, control + * flow, `$(...)`, backticks, process substitution and here-documents are all + * found. On top of the parse tree this module: + * - strips leading `VAR=value` assignments and process wrappers (`timeout`, + * `time`, `nice`, `nohup`, `stdbuf`, `command`, `builtin`, `noglob`, `exec`, + * `env`, `sudo`, `xargs`, `find -exec`) and offers every stripped form to + * deny/ask matching; + * - parses the inner string of `bash -c`/`sh -c` (and other shells) and adds + * its commands; + * - collects redirection targets (`> f`, `< f`, `tee f`) so file rules can + * check them; + * - reports constructs it cannot evaluate statically (`eval`, `source`, a + * dynamic command name, a shell reading commands from stdin, a here-document + * with substitutions, a parse error) as `uncertain`, which callers treat as + * `ask`. + */ + +/** One simple command, as matching sees it. */ +export interface SimpleCommand { + /** Source text of the command as written (assignments included). */ + readonly raw: string; + /** Every text deny/ask rules are matched against: normalized forms with and without wrappers. */ + readonly denyForms: readonly string[]; + /** + * Text allow rules are matched against: the command after stripping only + * the wrappers Claude Code documents (`timeout`, `time`, `nice`, `nohup`, + * `stdbuf`, `command`, `builtin`, `noglob`, bare `xargs`). Undefined when the + * command cannot be approved by an allow rule (dynamic words, leading + * assignments, unknown command name). + */ + readonly allowForm: string | undefined; + /** + * For each form (as written, each stripped wrapper level, each basename + * variant): the words before the first word only known at run time. + */ + readonly staticPrefixes: readonly string[]; + /** True when some word's value is only known at run time. */ + readonly dynamic: boolean; + /** An exec wrapper or an effectful `find` action: only an exact allow rule approves it. */ + readonly exactOnly: boolean; +} + +/** A file a command reads or writes by name (redirection or `tee`). */ +export interface FileTarget { + readonly access: 'read' | 'write'; + /** The path as written, or undefined when it is only known at run time. */ + readonly path: string | undefined; +} + +export interface BashAnalysis { + readonly commands: readonly SimpleCommand[]; + readonly files: readonly FileTarget[]; + /** Reasons the command cannot be evaluated statically. Non-empty means `ask`. */ + readonly uncertain: readonly string[]; + /** True when a `cd` appears, so relative file targets may not resolve against the call's cwd. */ + readonly changesDirectory: boolean; + /** Every `rm`/`rmdir` invocation, for the critical-path check. */ + readonly removals: readonly Removal[]; +} + +/** An operand of a command: its value when static, else undefined. */ +export interface Operand { + readonly value: string | undefined; + readonly raw: string; + /** Unquoted glob characters appear. */ + readonly glob: boolean; + /** A leading `~` that is quoted or escaped (a file name), or a prefix other than `~`, `~/` (`~user`, `~+`) that expands to an unknown directory. */ + readonly tilde?: 'literal' | 'unknown'; +} + +/** One `rm` or `rmdir` call. */ +export interface Removal { + readonly recursive: boolean; + readonly targets: readonly Operand[]; +} + +/** Commands longer than this are not analyzed (treated as uncertain). */ +export const MAX_ANALYZED_COMMAND_CHARS = 100_000; + +/** How deep `bash -c '...'` strings are followed. */ +const MAX_SHELL_NESTING = 4; + +const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'ash', 'fish', 'busybox']); + +/** Shell options followed by a separate operand (`bash -O extglob -c ...`). */ +const SHELL_OPTIONS_WITH_OPERAND = new Set(['-o', '+o', '-O', '+O', '--rcfile', '--init-file', '--debugger-file']); + +/** Builtins whose arguments become shell code: always uncertain. */ +const CODE_EVALUATORS = new Set(['eval', 'source', '.', 'trap', 'fc']); + +type Access = 'read' | 'write' | 'both'; + +/** + * How a command touches the files it names. `operands` is the access of positional operands: `copy` writes + * the last one and reads the others, `pair` reads the first and writes the second (`uniq in out`). `files` + * are options whose value is a file; `values` are options whose value is not one. Any other option with a + * value attached (`-Xvalue`) may name a file: unknown. + */ +interface FileSpec { + readonly operands: Access | 'copy' | 'pair'; + readonly files?: Readonly>; + readonly values?: readonly string[]; +} + +const BOTH: FileSpec = { operands: 'both' }; +const FROM_FILE: FileSpec = { operands: 'read', files: { '-f': 'read', '--file': 'read' } }; +const COPY: FileSpec = { operands: 'copy', files: { '-t': 'write', '--target-directory': 'write' } }; + +/** + * Commands whose operands may be files. A non-option operand that is not a file (a `sed` script, a `grep` + * pattern) is checked as a path too: matching a pattern text against path rules is harmless, missing a file is not. + */ +const FILE_SPECS: ReadonlyMap = new Map([ + ...['cat', 'head', 'tail', 'less', 'more', 'most', 'nl', 'tac', 'rev', 'strings', 'od', 'hexdump', 'base32', 'zcat', 'zless', 'bzcat', 'xzcat', 'wc', 'diff', 'cmp', 'comm', 'join', 'paste', 'column', 'fold', 'fmt', 'pr', 'expand', 'unexpand', 'file', 'md5sum', 'sha1sum', 'sha256sum', 'sha512sum', 'cksum', 'b2sum', 'wget'].map((c) => [c, { operands: 'read' }] as const), + ...['grep', 'egrep', 'fgrep', 'zgrep', 'rg', 'ag', 'ack', 'sed'].map((c) => [c, FROM_FILE] as const), + ...['awk', 'gawk', 'mawk', 'nawk'].map((c) => [c, { ...FROM_FILE, values: ['-F'] }] as const), + ...['tee', 'touch', 'truncate', 'rm', 'rmdir', 'unlink', 'shred', 'mkdir', 'chmod', 'chown', 'chgrp', 'ln'].map((c) => [c, { operands: 'write' }] as const), + ...['dos2unix', 'zip', 'gzip', 'gunzip', 'bzip2', 'xz', 'openssl', 'yq', 'vi', 'vim', 'nano', 'view', 'emacs', 'mv'].map((c) => [c, BOTH] as const), + ...['cp', 'install'].map((c) => [c, COPY] as const), + ...['rsync', 'scp'].map((c) => [c, { operands: 'copy' }] as const), + ['cut', { operands: 'read', values: ['-d'] }], + ['sort', { operands: 'read', files: { '-o': 'write', '--output': 'write', '-T': 'write', '--temporary-directory': 'write' }, values: ['-t'] }], + ['uniq', { operands: 'pair', values: ['-f', '-s', '-w'] }], + ['xxd', { operands: 'pair', values: ['-c', '-g', '-l', '-s'] }], + ['iconv', { operands: 'read', files: { '-o': 'write', '--output': 'write' } }], + ['base64', { operands: 'read', files: { '-i': 'read', '-o': 'write' } }], + ['jq', { operands: 'read', files: { '-f': 'read', '--from-file': 'read' } }], + ['xmllint', { operands: 'read', files: { '-o': 'write', '--output': 'write' } }], + ['gpg', { operands: 'both', files: { '-o': 'write', '--output': 'write' } }], + ['tar', { operands: 'both', files: { '-f': 'both', '--file': 'both', '-C': 'both', '--directory': 'both' } }], + ['unzip', { operands: 'both', files: { '-d': 'write' } }], + ['curl', { operands: 'read', files: { '-o': 'write', '--output': 'write', '-D': 'write', '--dump-header': 'write', '-c': 'write', '--cookie-jar': 'write', '-K': 'read', '--config': 'read', '-T': 'read', '--upload-file': 'read', '-b': 'read', '--cookie': 'read' } }], +]); + +/** `find` actions that run, write or delete, and `-files0-from`, which reads its paths from a file: only an exact allow rule approves them. */ +const FIND_ACTIONS = new Set(['-exec', '-execdir', '-ok', '-okdir', '-delete', '-rm', '-fprint', '-fprint0', '-fprintf', '-fls', '-files0-from']); + +/** Exec wrappers that run their arguments as a command (https://code.claude.com/docs/en/permissions, "Exec wrappers"): only an exact allow rule approves them. */ +const EXEC_WRAPPERS = new Set(['watch', 'setsid', 'ionice', 'flock']); + +/** Wrapper levels stripped before the command is reported as uncertain. */ +const MAX_WRAPPER_LEVELS = 64; + +/** Builtins that rebind a command name: the commands after them cannot be matched by name. */ +const NAME_REBINDERS = new Set(['alias', 'hash', 'enable']); + +// Redirect operators (sh-syntax RedirOperator values). +const REDIR_OUT = new Set([63, 64, 68, 69, 70, 74, 75, 76, 77]); // > >> >& >| >>| &> &>| &>> &>>| +const REDIR_IN = new Set([65, 67]); // < <& +const REDIR_INOUT = new Set([66]); // <> +const REDIR_HDOC = new Set([71, 72]); // << <<- +const REDIR_DUP = new Set([67, 68]); // <& >& + +type WordValue = Operand; + +function decodeUnquoted(lit: string): string { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + if (ch === '\\' && i + 1 < lit.length) { + const next = lit[i + 1]; + i++; + if (next !== '\n') out += next; + } else { + out += ch; + } + } + return out; +} + +function decodeDoubleQuoted(lit: string): string { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + const next = lit[i + 1]; + if (ch === '\\' && next !== undefined && '$`"\\\n'.includes(next)) { + i++; + if (next !== '\n') out += next; + } else { + out += ch; + } + } + return out; +} + +const ANSI_ESCAPES: Record = { n: '\n', t: '\t', r: '\r', '\\': '\\', "'": "'", '"': '"', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v' }; + +/** Decodes `$'...'`; undefined when an escape is not a simple one. */ +function decodeAnsi(lit: string): string | undefined { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + if (ch !== '\\') { + out += ch; + continue; + } + const next = lit[i + 1]; + const mapped = next === undefined ? undefined : ANSI_ESCAPES[next]; + if (mapped === undefined) return undefined; + out += mapped; + i++; + } + return out; +} + +/** Whether raw unquoted text has one of `chars` that no backslash escapes (escape parity counted). */ +function hasUnescaped(lit: string, chars: string): boolean { + for (let i = 0; i < lit.length; i++) { + const ch = lit[i] ?? ''; + if (ch === '\\') i++; + else if (chars.includes(ch)) return true; + } + return false; +} + +/** A file path an operand names, or undefined when the shell may expand it into something else. */ +function pathOf(o: Operand): string | undefined { + if (o.value === undefined || o.glob || o.tilde === 'unknown') return undefined; + return o.tilde === 'literal' ? `./${o.value}` : o.value; +} + +/** The path in an option's attached value (`-ofile`, `--file=x`); a leading `~` there may or may not expand. */ +function attachedPath(value: string, o: Operand): string | undefined { + return o.glob || value.startsWith('~') ? undefined : value; +} + +type Ctx = { readonly bytes: Buffer; readonly depth: number }; + +function partsValue(parts: readonly WordPart[], quoted: boolean): { value: string | undefined; glob: boolean } { + let value: string | undefined = ''; + let glob = false; + for (const part of parts) { + let piece: string | undefined; + switch (part.type) { + case 'Lit': + if (!quoted && hasUnescaped(part.value, '*?[')) glob = true; + piece = quoted ? decodeDoubleQuoted(part.value) : decodeUnquoted(part.value); + break; + case 'SglQuoted': + piece = part.dollar ? decodeAnsi(part.value) : part.value; + break; + case 'DblQuoted': { + if (part.dollar) { + piece = undefined; // $"..." is locale translation + break; + } + const inner = partsValue(part.parts, true); + piece = inner.value; + break; + } + default: + piece = undefined; + } + if (piece === undefined || value === undefined) value = undefined; + else value += piece; + } + return { value, glob }; +} + +export class BashAnalyzer { + readonly #commands: SimpleCommand[] = []; + readonly #files: FileTarget[] = []; + readonly #uncertain: string[] = []; + #changesDirectory = false; + readonly #removals: Removal[] = []; + + static analyze(command: string): BashAnalysis { + const analyzer = new BashAnalyzer(); + analyzer.#analyzeSource(command, 0); + return { + commands: analyzer.#commands, + files: analyzer.#files, + uncertain: [...new Set(analyzer.#uncertain)], + changesDirectory: analyzer.#changesDirectory, + removals: analyzer.#removals, + }; + } + + #analyzeSource(source: string, depth: number): void { + if (source.includes('\0')) { + this.#uncertain.push('command contains a NUL byte'); + return; + } + if (source.length > MAX_ANALYZED_COMMAND_CHARS) { + this.#uncertain.push(`command is longer than ${MAX_ANALYZED_COMMAND_CHARS} characters`); + return; + } + let file: File; + try { + file = parse(source); + } catch (err) { + this.#uncertain.push(`command could not be parsed: ${err instanceof Error ? err.message : String(err)}`); + return; + } + // Node offsets are UTF-8 byte offsets: slice the encoded source, never the JavaScript string. + const ctx: Ctx = { bytes: Buffer.from(source, 'utf8'), depth }; + walk(file, (node) => { + switch (node.type) { + case 'CallExpr': + this.#callExpr(node, ctx); + break; + case 'DeclClause': + this.#declClause(node, ctx); + break; + case 'Redirect': + this.#redirect(node, ctx); + break; + case 'Stmt': + if (node.coprocess) this.#uncertain.push('coprocesses are not analyzed'); + break; + case 'CoprocClause': + this.#uncertain.push('coprocesses are not analyzed'); + break; + default: + break; + } + }); + } + + #text(node: Node, ctx: Ctx): string { + return ctx.bytes.subarray(node.start, node.end).toString('utf8'); + } + + #word(word: Word, ctx: Ctx): WordValue { + const { value, glob } = partsValue(word.parts, false); + const raw = this.#text(word, ctx); + // Brace expansion (`{a,b}`, `{1..3}`) can turn one word into several: only known at run time. + const brace = word.parts.some((p) => p.type === 'Lit' && hasUnescaped(p.value, '{')) && /\{[\s\S]*(,|\.\.)[\s\S]*\}/.test(raw); + if (brace) return { value: undefined, raw, glob }; + // Bash expands a leading `~` only when it is unquoted: `~` alone or `~/` is home; other prefixes are unknown here. + let tilde: Operand['tilde']; + if (value?.startsWith('~')) { + const first = word.parts[0]; + const lit = first?.type === 'Lit' ? first.value : ''; + if (!lit.startsWith('~')) tilde = 'literal'; + else if (!(lit === value ? /^~(\/|$)/.test(lit) : lit.startsWith('~/'))) tilde = 'unknown'; + } + return { value, raw, glob, ...(tilde === undefined ? {} : { tilde }) }; + } + + #declClause(decl: DeclClause, ctx: Ctx): void { + // `export`, `declare`, `local`, `readonly`, `typeset`, `nameref`: their own + // words are assignments; nested substitutions are walked generically. + const name = decl.variant?.value ?? 'declare'; + const raw = this.#text(decl, ctx); + this.#commands.push({ raw, denyForms: [raw, name], allowForm: undefined, staticPrefixes: [name], dynamic: true, exactOnly: false }); + } + + #redirect(redir: Redirect, ctx: Ctx): void { + if (REDIR_HDOC.has(redir.op)) { + const body = redir.hdoc; + if (body && body.parts.some((p) => p.type !== 'Lit')) { + this.#uncertain.push('here-document with substitutions'); + } + return; + } + if (redir.word === null) return; + const target = this.#word(redir.word, ctx); + // `>&2`, `<&0`, `>&-` duplicate or close descriptors; `>& file` opens a file. + if (REDIR_DUP.has(redir.op) && target.value !== undefined && /^(\d+-?|-)$/.test(target.value)) return; + const path = pathOf(target); + if (path === '/dev/null' || path === '/dev/stdout' || path === '/dev/stderr') return; + if (REDIR_OUT.has(redir.op)) this.#files.push({ access: 'write', path }); + else if (REDIR_IN.has(redir.op)) this.#files.push({ access: 'read', path }); + else if (REDIR_INOUT.has(redir.op)) { + this.#files.push({ access: 'read', path }); + this.#files.push({ access: 'write', path }); + } + // Here-strings (`<<<`) carry no file. + } + + #callExpr(call: CallExpr, ctx: Ctx): void { + const raw = this.#text(call, ctx); + const words = call.args.map((w) => this.#word(w, ctx)); + if (words.length === 0) return; // pure assignment, e.g. `A=$(rm x)`: nested commands are walked + this.#addCommand(raw, words, call.assigns.length > 0, ctx); + } + + #fileOperands(base: string, operands: readonly WordValue[]): void { + const push = (access: Access, path: string | undefined): void => { + if (access !== 'write') this.#files.push({ access: 'read', path }); + if (access !== 'read') this.#files.push({ access: 'write', path }); + }; + if (base === 'dd') { + // `if=` is read and `of=` written; other operands are not files. + for (const o of operands) { + const m = o.value === undefined ? undefined : /^(if|of)=(.*)$/s.exec(o.value); + if (o.value === undefined) push('both', undefined); + else if (m?.[2] !== undefined) push(m[1] === 'if' ? 'read' : 'write', attachedPath(m[2], o)); + } + return; + } + let spec = FILE_SPECS.get(base); + if (spec === undefined) return; + if (base === 'sed' && operands.some((o) => o.value !== undefined && /^(-[a-zA-Z]*i|--in-place)/.test(o.value))) spec = BOTH; + if (base === 'rsync' && operands.some((o) => o.value === undefined || o.value.startsWith('--remove-source'))) spec = BOTH; + // `wget url`, `curl -O url`: the file name comes from the server. + if (base === 'wget' || (base === 'curl' && operands.some((o) => o.value === undefined || /^-[a-zA-Z]*[OJ]|^--remote-name/.test(o.value)))) { + this.#files.push({ access: 'write', path: undefined }); + } + const { operands: mode, files = {}, values = [] } = spec; + const unknownAccess: Access = mode === 'read' ? 'read' : 'both'; + const positional: (string | undefined)[] = []; + let options = true; + for (let i = 0; i < operands.length; i++) { + const o = operands[i]; + if (!o || o.raw.startsWith('<(') || o.raw.startsWith('>(')) continue; + const v = o.value; + if (v === '-') continue; + if (options && v === '--') { + options = false; + continue; + } + if (!options || v === undefined || !v.startsWith('-')) { + positional.push(pathOf(o)); + continue; + } + if (v.startsWith('--')) { + const eq = v.indexOf('='); + const access = files[eq === -1 ? v : v.slice(0, eq)]; + if (eq !== -1) push(access ?? unknownAccess, attachedPath(v.slice(eq + 1), o)); + else if (access !== undefined) { + const next = operands[++i]; + if (next) push(access, pathOf(next)); + } + continue; + } + // A short cluster: flags up to the first option that takes a value, attached or as the next word. + for (let k = 1; k < v.length; k++) { + const flag = `-${v[k] ?? ''}`; + const access = files[flag]; + const rest = v.slice(k + 1); + if (access !== undefined || values.includes(flag)) { + const next = rest === '' ? operands[++i] : undefined; + if (access !== undefined) push(access, rest !== '' ? attachedPath(rest, o) : next ? pathOf(next) : undefined); + break; + } + if (!/[A-Za-z]/.test(v[k] ?? '')) { + // An option outside the tables with a value attached: a count (`-n5`) is no file, anything else may be. + if (!/^[0-9][0-9,.:+-]*$/.test(v.slice(k))) push(unknownAccess, undefined); + break; + } + } + } + positional.forEach((p, n) => push(mode === 'copy' ? (n === positional.length - 1 ? 'write' : 'read') : mode === 'pair' ? (n === 1 ? 'write' : 'read') : mode, p)); + } + + #addCommand(raw: string, words: readonly WordValue[], hasAssigns: boolean, ctx: Ctx): void { + const denyForms = new Set([raw]); + const staticPrefixes = new Set(); + const dynamic = words.some((w) => w.value === undefined); + const text = (ws: readonly WordValue[]): string => ws.map((w) => w.value ?? w.raw).join(' '); + const prefix = (ws: readonly WordValue[]): string => { + const i = ws.findIndex((w) => w.value === undefined); + return (i === -1 ? ws : ws.slice(0, i)).map((w) => w.value ?? '').join(' '); + }; + const addForm = (ws: readonly WordValue[]): void => { + denyForms.add(text(ws)); + staticPrefixes.add(prefix(ws)); + const head = ws[0]; + if (head?.value !== undefined) { + const base = basename(head.value); + if (base !== head.value) { + // `/usr/bin/git push` is matched as `git push` too. + const renamed = [{ ...head, value: base, raw: base }, ...ws.slice(1)]; + denyForms.add(text(renamed)); + staticPrefixes.add(prefix(renamed)); + } + } + }; + addForm(words); + + // Strip wrappers one level at a time; every level is a deny/ask candidate. + let current = words; + let allowStripped: readonly WordValue[] | undefined = hasAssigns ? undefined : words; + let allowChainIntact = !hasAssigns; + let exactOnly = false; + for (let level = 0; ; level++) { + if (level >= MAX_WRAPPER_LEVELS) { + this.#uncertain.push(`more than ${MAX_WRAPPER_LEVELS} nested command wrappers`); + allowStripped = undefined; + break; + } + const head = current[0]; + if (!head) break; + if (head.value === undefined || head.glob) { + this.#uncertain.push(`command name ${JSON.stringify(head.raw)} is only known at run time`); + allowStripped = undefined; + break; + } + const base = basename(head.value); + const operands = current.slice(1); + if (base === 'cd' || base === 'pushd' || base === 'popd' || changesChildDir(base, operands)) this.#changesDirectory = true; + if (base === 'find' && operands.some((o) => o.value === undefined || FIND_ACTIONS.has(o.value))) exactOnly = true; + if (CODE_EVALUATORS.has(base)) this.#uncertain.push(`\`${base}\` runs code that is only known at run time`); + if (NAME_REBINDERS.has(base) && operands.length > 0) this.#uncertain.push(`\`${base}\` rebinds command names, so later commands cannot be matched by name`); + this.#fileOperands(base, operands); + if (base === 'rm' || base === 'rmdir') { + // An unquoted run-time word may split into flags such as `-rf`. + const recursive = operands.some((o) => (o.value === undefined ? !/^["']/.test(o.raw) : /^-[a-zA-Z]*[rR]/.test(o.value) || o.value === '--recursive')); + const targets = operands.filter((o) => o.value === undefined || !o.value.startsWith('-')); + this.#removals.push({ recursive, targets: targets.map((o) => (o.tilde === undefined ? o : { ...o, value: pathOf(o) })) }); + } + if (SHELLS.has(base)) this.#shell(current, ctx); + if (base === 'find') this.#findExec(current, ctx); + if (base === 'env' && this.#envSplitString(current, ctx)) { + allowStripped = undefined; + break; + } + + const unwrapped = unwrap(base, current); + if (unwrapped === undefined) break; + if (unwrapped.inner.length === 0) break; + current = unwrapped.inner; + addForm(current); + if (allowChainIntact && unwrapped.documented) allowStripped = current; + else allowChainIntact = false; + // `timeout 1 A=1 rm x`: strip assignment-like words too (strict: the wrapper would run `A=1`). + let skip = 0; + while (skip < current.length - 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(current[skip]?.value ?? '')) skip++; + if (skip > 0) { + current = current.slice(skip); + addForm(current); + allowChainIntact = false; + allowStripped = undefined; + } + } + + // An exec wrapper left after stripping the documented ones runs another command. + const allowHead = allowStripped?.[0]?.value; + if (allowStripped !== undefined && allowHead !== undefined && (EXEC_WRAPPERS.has(basename(allowHead)) || unwrap(basename(allowHead), allowStripped) !== undefined)) exactOnly = true; + // Allow rules see the words as written, so word boundaries survive (`a 'b c'` is not `a b c`). + const allowForm = allowStripped !== undefined && !dynamic ? allowStripped.map((w) => w.raw).join(' ') : undefined; + this.#commands.push({ raw, denyForms: [...denyForms], allowForm, staticPrefixes: [...staticPrefixes], dynamic, exactOnly }); + } + + /** + * `env -S 'cmd args'` / `env --split-string=...`: the string is split into a + * command line. Returns true when the invocation had one (it was analyzed). + */ + #envSplitString(words: readonly WordValue[], ctx: Ctx): boolean { + for (let i = 1; i < words.length; i++) { + const w = words[i]; + if (!w) break; + const v = w.value; + if (v === undefined) return false; + let script: WordValue | undefined; + let restFrom = i + 1; + if (v === '-S' || v === '--split-string') { + script = words[i + 1]; + restFrom = i + 2; + } else if (v.startsWith('--split-string=')) { + script = { value: v.slice('--split-string='.length), raw: v, glob: false }; + } else if (/^-[a-zA-Z]*S./s.test(v) && !v.startsWith('--')) { + script = { value: v.slice(v.indexOf('S') + 1), raw: v, glob: false }; + } else if (v.startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(v)) { + continue; + } else { + return false; + } + if (!script || script.value === undefined) { + this.#uncertain.push('`env -S` string is only known at run time'); + return true; + } + if (ctx.depth >= MAX_SHELL_NESTING) { + this.#uncertain.push('`env -S` nested too deeply'); + return true; + } + const rest = words.slice(restFrom).map((r) => r.raw); + this.#analyzeSource([script.value, ...rest].join(' '), ctx.depth + 1); + return true; + } + return false; + } + + #shell(words: readonly WordValue[], ctx: Ctx): void { + // Find `-c