import type { EngineInterface, On, PluginOptions } from 'claude-code' import Outbound from './outbound' /** * Registers the hooks. At `tool.check`, a call whose outgoing text, or a script * its line names, holds the account's or git's address beside a word that declares * who is calling, or a fetch with the address in its URL, is refused, with no prompt. * A line that only touches files reads no script. A deny beneath keeps its reason. * * At `session.identity`, a `user`-tier caller is refused, and the address the * context hands the model is left off the answer of a caller outside `builtin`. * * @param on the engine's registrar * @param options the plugin's options; `shellTools` names more tools that run a line */ export function register(on: On, options: PluginOptions): void { const named = [options.shellTools] .flat() .flatMap(one => (typeof one === 'string' ? one.split(/[\s,]+/) : [])) .filter(one => one !== '' && one.length <= Outbound.MOST_NAME_CHARS) .slice(0, Outbound.MOST_NAMED_TOOLS) const shells = [...Outbound.SHELL_TOOLS, ...named] const tool = [...shells, ...Outbound.FIELD_TOOLS, Outbound.MCP_TOOL] on('tool.check', { tool }, async ($, e, next) => { const verdict = await next(e) // A refused settings hook is skipped, and what it guards goes on unjudged. if (verdict.decision === 'deny' || next.origin.hookOwner !== undefined) { return verdict } const text = Outbound.outgoingText(e.tool, e.input) // The line that runs, not a field that only talks about it, such as `description`. // For any other tool, its outgoing text. const line = !Outbound.SHELL_TOOLS.includes(e.tool) ? text : Outbound.onlyTouches(e.tool, e.input) ? '' : Outbound.fieldText(e.input, 'command', Outbound.GIT_COMMAND) const scripts = shells.includes(e.tool) ? Outbound.scriptNames(line) : [] if (scripts.length === 0 && !Outbound.mayHoldAddress(text)) { return verdict } const identity = await $.session.identity() const email = identity.contextEmail ?? identity.email const refusal = { decision: 'deny', reason: Outbound.REFUSAL } as const if (Outbound.isRefused(e.tool, e.input, email)) { return refusal } // One it can't read holds nothing: nobody can answer a refusal. One the engine // could not hold is there to run, so it may hold anything. const read = await Promise.all(scripts.map(name => plainText($, '.', name))) if (read.includes(undefined)) { return { decision: 'deny', reason: 'This call was refused: a script it names could not be read ' + "here to check it for the person's email address. The " + 'person can run the command with `!`.', } } const texts = read.map(Outbound.textOf) // Ahead of any read of git's address, so that none can cost the account's test. if (texts.some(one => Outbound.namesUserAgentWithAddress(one, email))) { return refusal } const isFetch = e.tool === Outbound.WEB_FETCH_TOOL const own = Outbound.textBesideGit(e.tool, e.input) const carried = e.tool === Outbound.EDIT_TOOL ? Outbound.fieldText(e.input, 'old_string') : '' const isMet = (test: (one: string) => boolean): boolean => (test(own) && !test(carried)) || texts.some(test) if (!email && !isFetch && isMet(Outbound.readsAddressAsIdentity)) { return refusal } if ( ![own, ...texts].some( one => /@|%40/.test(one) && (isFetch || Outbound.namesIdentity(one)), ) ) { return verdict } // Asked anew each time, since the root and git's settings change. A read that // fails says nothing. const said = await Promise.all( [ async () => { const root = await $.session.root() // In no repository: this runs before any approval, and git opens what a // repository's own files point to. const { exitCode, stdout } = await $.process.run( [ ...['git', `--git-dir=${Outbound.NO_REPOSITORY}`], ...['config', '--get', 'user.email'], ], { cwd: root, timeoutMs: Outbound.GIT_TIMEOUT_MS }, ) // As text, at the root, which no `cd` moves. Only where git ran, since a // host that starts no program keeps the session's files elsewhere. const config = (await plainText($, root, '.git/config')) ?? '' return [ exitCode === 0 ? stdout : undefined, ...[...config.matchAll(Outbound.EMAIL_LINE)] .slice(-Outbound.MOST_EMAIL_LINES) .map(([, value]) => value), ] }, async () => $.env.get('GIT_AUTHOR_EMAIL'), async () => $.env.get('GIT_COMMITTER_EMAIL'), ].map(ask => ask().catch(() => undefined)), ) // Unquoted too, as it is looked for: `'@x.test` would match all of `x.test`. const addresses = [ ...new Set(said.flat().map(one => one?.trim() ?? '')), ].filter( one => Outbound.ADDRESS_SHAPE.test(one) && Outbound.ADDRESS_SHAPE.test(one.replace(Outbound.QUOTING, '')) && !Outbound.NO_REPLY.test(one) && one.toLowerCase() !== email?.toLowerCase(), ) // Git's other addresses stay in the text: one may be written to span a word. return addresses.some(address => isMet(one => isFetch ? Outbound.holdsAddress(one, address) : Outbound.holdsAddressAsIdentity(one, [address, email || address]), ), ) ? refusal : verdict }) // No call on `$` here: a hook that call reached would run with this one left out. // A refusal is a value, so that the call resolves with `deny` and never rejects. on('session.identity', async ($, e, next) => { if (next.origin.tier === 'user') { return { value: { deny: '$.session.identity answers only a mod that managed settings ' + 'enable and that is loaded in place from a source they name; ' + `${next.origin.plugin} is not one`, }, } } const answer = await next(e) if ( next.origin.tier === 'builtin' || answer.value?.contextEmail === undefined ) { return answer } const { contextEmail: _handed, ...rest } = answer.value return { value: rest } }).catch(() => ({ value: { deny: 'privacy could not read the identity' } })) } /** * This runs before any approval, so it opens only a plain file that its walk from * a folder found free of links. * * @returns the text, empty where it can't be read, and none where it can't be held */ async function plainText( $: EngineInterface, from: string, name: string, ): Promise { try { let path = from let kind = 'dir' for (const part of name .split(/[/\\]+/) .filter(one => one !== '' && one !== '.')) { const entries = kind === 'dir' ? await $.fs.list(path) : [] const entry = entries.find(one => one.name === part) if (entry === undefined || entry.isLink) { return '' } path = `${path}/${part}` kind = entry.kind } return kind === 'file' ? await $.fs.read(path) : '' } catch (error) { return / failed: (UNHELD|RULES_MOVED)$/.test(String(error)) ? undefined : '' } }