Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",
"@modelcontextprotocol/sdk": "^1.32.2",
"quickjs-emscripten-core": "^0.32.0",
"smol-toml": "^1.9.1",
"zod": "^4.6.7"
},
"devDependencies": {
Expand Down
70 changes: 70 additions & 0 deletions src/core/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,76 @@ describe('Dispatcher', () => {
expect(adapter.staticChecked).toHaveLength(2);
});

describe('a rewrite bound to the prepared file', () => {
it('commits the rewrite when the file is unchanged', async () => {
const { dispatcher, tools } = await setup(
{ hook: { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true } },
{ files: { 'a.txt': 'old' } },
);
expect((await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' })).ok).toBe(true);
expect(tools.read('a.txt')).toBe('rewritten');
});

it('commits a bound rewrite of a write that creates the file', async () => {
const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { path: 'new.txt', content: 'rewritten' }, bindsPreparedFile: true } });
expect((await dispatcher.dispatch('write', { path: 'new.txt', content: 'x' })).ok).toBe(true);
expect(tools.read('new.txt')).toBe('rewritten');
});

it('denies when the file changed between the hook and the second preparation', async () => {
let runtime: MemoryToolRuntime | undefined;
const { dispatcher, tools } = await setup(
{
hook: () => {
// The file moves on after the hook evaluated the first version.
runtime?.externalWrite('a.txt', 'changed meanwhile');
return { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true };
},
},
{ files: { 'a.txt': 'old' } },
);
runtime = tools;
const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' }));
expect(err).toMatchObject({ name: 'PermissionDenied', source: 'hook' });
expect(err.message).toContain('changed after the hook evaluated it');
expect(tools.read('a.txt')).toBe('changed meanwhile');
expect(tools.commits).toHaveLength(0);
});

it('denies when the file was created between the hook and the second preparation', async () => {
let runtime: MemoryToolRuntime | undefined;
const { dispatcher, tools } = await setup({
hook: () => {
runtime?.externalWrite('a.txt', 'created meanwhile');
return { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true };
},
});
runtime = tools;
expect(errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' }))).toMatchObject({ source: 'hook' });
expect(tools.read('a.txt')).toBe('created meanwhile');
expect(tools.commits).toHaveLength(0);
});

it('denies a bound rewrite that targets another file with the same bytes', async () => {
const { dispatcher, tools } = await setup(
{ hook: { kind: 'updatedArgs', args: { path: 'b.txt', content: 'rewritten' }, bindsPreparedFile: true } },
{ files: { 'a.txt': 'same', 'b.txt': 'same' } },
);
const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' }));
expect(err).toMatchObject({ name: 'PermissionDenied', source: 'hook' });
expect(err.message).toContain('destination');
expect(tools.read('a.txt')).toBe('same');
expect(tools.read('b.txt')).toBe('same');
expect(tools.commits).toHaveLength(0);
});

it('denies a bound rewrite of a call that has no file effect', async () => {
const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { command: 'echo b' }, bindsPreparedFile: true } });
expect(errorOf(await dispatcher.dispatch('bash', { command: 'echo a' }))).toMatchObject({ source: 'hook' });
expect(tools.commits).toHaveLength(0);
});
});

it('refuses updatedArgs that point outside the workspace', async () => {
const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { path: '../etc/passwd', content: 'x' } } });
const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }));
Expand Down
25 changes: 24 additions & 1 deletion src/core/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,23 @@ function containmentEquals(a: BashContainment, b: BashContainment): boolean {
);
}

/**
* For a hook rewrite bound to the prepared file: why the re-prepared call is
* not the file version the hook evaluated, or undefined when it is.
*/
function boundFileMismatch(first: PreparedCall, second: PreparedCall): string | undefined {
if ((first.tool !== 'write' && first.tool !== 'edit') || (second.tool !== 'write' && second.tool !== 'edit') || first.tool !== second.tool) {
return 'hook bound its rewrite to a file version, but the call has no file effect';
}
if (second.effect.absPath !== first.effect.absPath) {
return `hook rewrite changed the destination after the hook evaluated ${first.effect.absPath}`;
}
if (second.effect.beforeHash !== first.effect.beforeHash) {
return `${first.effect.absPath} changed after the hook evaluated it; the rewrite was not applied`;
}
return undefined;
}

function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | typeof ABORTED> {
if (signal.aborted) {
promise.catch(() => undefined);
Expand Down Expand Up @@ -103,7 +120,9 @@ function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | typ
* `authorize`. `ask` becomes deny `ask-unavailable`. A throwing or malformed
* adapter becomes deny `hook-error`.
* - `updatedArgs` are re-parsed, re-prepared and re-checked statically; a
* failure there is a deny (source `hook`).
* failure there is a deny (source `hook`). With `bindsPreparedFile`, the
* re-prepared write/edit must keep the first preparation's `absPath` and
* `beforeHash`, or it is denied (source `hook`) and nothing is committed.
* - write/edit on a protected path is refused even if the tool runtime missed
* it; a bash call whose containment differs from the policy is denied
* `containment-unavailable`.
Expand Down Expand Up @@ -314,6 +333,10 @@ export class Dispatcher<P = unknown> {
const reason = second.kind === 'deny' ? second.reason : second.error.message;
return fail({ kind: 'deny', source: second.kind === 'deny' ? second.source : 'hook', reason: `hook updated input was refused: ${reason}` });
}
if (decision.bindsPreparedFile === true) {
const unbound = boundFileMismatch(prepared, second.prepared);
if (unbound !== undefined) return fail({ kind: 'deny', source: 'hook', reason: unbound });
}
const recheck = this.#checkStatic(second.prepared, policy);
if (recheck) return fail(recheck);
prepared = second.prepared;
Expand Down
12 changes: 11 additions & 1 deletion src/core/schemas.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { ToolError } from './errors.js';
import { parseRunArgs, parseToolCall } from './schemas.js';
import { DecisionSchema, parseRunArgs, parseToolCall } from './schemas.js';

describe('parseToolCall', () => {
it('returns a typed call for valid args', () => {
Expand Down Expand Up @@ -41,3 +41,13 @@ describe('parseRunArgs', () => {
expect(parseRunArgs({ code: 'x', timeoutMs: -1 }).ok).toBe(false);
});
});

describe('DecisionSchema', () => {
it('accepts an allow bound to the prepared file', () => {
expect(DecisionSchema.safeParse({ kind: 'allow', updatedArgs: { path: 'a', content: 'x' }, bindsPreparedFile: true }).success).toBe(true);
});

it.each([false, 'true', 1, null])('rejects bindsPreparedFile %j', (value) => {
expect(DecisionSchema.safeParse({ kind: 'allow', updatedArgs: { path: 'a', content: 'x' }, bindsPreparedFile: value }).success).toBe(false);
});
});
7 changes: 6 additions & 1 deletion src/core/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ export function isToolName(tool: string): tool is ToolName {
}

export const DecisionSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('allow'), reason: z.string().optional(), updatedArgs: z.unknown().optional() }),
z.object({
kind: z.literal('allow'),
reason: z.string().optional(),
updatedArgs: z.unknown().optional(),
bindsPreparedFile: z.literal(true).optional(),
}),
z.object({ kind: z.literal('ask'), reason: z.string() }),
z.object({
kind: z.literal('deny'),
Expand Down
7 changes: 6 additions & 1 deletion src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,11 +382,16 @@ export type DenySource =
* this project's camelCase args shape for the same tool (the adapter maps
* from the host's native shape). It is untrusted: the dispatcher re-validates,
* re-prepares and re-checks it statically.
* - `bindsPreparedFile: true` (only meaningful with `updatedArgs`): the hook
* evaluated a write/edit against the file version the first preparation
* read. The re-prepared call must then target the same `absPath` with the
* same `beforeHash` (null included), or the dispatcher denies it (source
* `hook`). Without it, a rewrite may point anywhere the static rules allow.
* - `ask`: the host would prompt the user. Without an interactive channel the
* dispatcher turns it into `deny` with source `ask-unavailable`.
*/
export type Decision =
| { readonly kind: 'allow'; readonly updatedArgs?: unknown; readonly reason?: string }
| { readonly kind: 'allow'; readonly updatedArgs?: unknown; readonly bindsPreparedFile?: true; readonly reason?: string }
| { readonly kind: 'deny'; readonly reason: string; readonly source: DenySource }
| { readonly kind: 'ask'; readonly reason: string };

Expand Down
Loading
Loading