| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490 |
- import { snapshotPermissionEffectiveInput, snapshotPermissionInput } from './effective-input.js';
- import type {
- CommandIntent,
- ExecutionPlan,
- ExecutionTransform,
- PermissionAction,
- PermissionEvaluationInput,
- PathValue,
- ShellFamily,
- } from './permission-core.js';
- import { resolvePermissionPath } from './path-resolver.js';
- import { readWindowsTrashExecution } from './windows-trash-execution.js';
- import { isRmCommand, parseRmTargets } from './tools/bash-permission.js';
- import { splitCommand } from './tools/bash-split.js';
- import { shellTokenize } from './tools/shell-tokenize.js';
- import { parseWindowsNativeDelete } from './tools/windows-native-delete.js';
- export type { ExecutionPlan } from './permission-core.js';
- const SHELL_FAMILIES = new Set<ShellFamily>(['posix', 'cmd', 'powershell', 'unknown']);
- const FILESYSTEM_ACTIONS = new Set(['read', 'write', 'delete']);
- export type CreatePermissionExecutionPlanInput = Pick<
- PermissionEvaluationInput,
- 'toolName' | 'input'
- > & {
- shell?: ShellFamily;
- context?: Pick<PermissionEvaluationInput['context'], 'workingDirectory' | 'homeDir'>;
- rewrittenInput?: Readonly<Record<string, unknown>>;
- };
- /** Build the complete immutable plan consumed by production permission gates. */
- export function createPermissionExecutionPlan(
- input: CreatePermissionExecutionPlanInput,
- ): Readonly<ExecutionPlan> {
- const originalInput = snapshotPermissionInput(input.input);
- const intents = inferPermissionCommandIntents(input);
- const effectiveInput =
- snapshotPermissionEffectiveInput(originalInput, input.rewrittenInput) ?? originalInput;
- const targets = collectRecoverableDeleteTargets(intents);
- const transforms: ExecutionPlan['transforms'] =
- input.rewrittenInput && targets.length > 0 ? [{ type: 'recoverable-delete', targets }] : [];
- return validatePermissionExecutionPlan(
- { originalInput, effectiveInput, intents, transforms },
- originalInput,
- );
- }
- /** Shared intent inference used by the production plan builder and legacy parity adapter. */
- export function inferPermissionCommandIntents(
- input: CreatePermissionExecutionPlanInput,
- ): CommandIntent[] {
- const shell = input.shell ?? 'unknown';
- if (input.toolName === 'bash' && typeof input.input.command === 'string') {
- const command = input.input.command;
- const segments = splitCommand(command);
- if (segments.length > 1) {
- return segments.flatMap((segment) => inferBashSegmentIntent(segment, input, shell));
- }
- return inferBashSegmentIntent(command, input, shell);
- }
- const pathCandidates = extractPathCandidates(input.input);
- if (pathCandidates.length > 0) {
- const action: PermissionAction =
- input.toolName === 'delete'
- ? 'delete'
- : ['edit', 'write', 'append'].includes(input.toolName)
- ? 'write'
- : 'read';
- return [
- {
- kind: 'filesystem',
- action,
- paths: pathCandidates.map((candidate) => toPathValue(candidate, input)),
- shell,
- },
- ];
- }
- return [
- {
- kind: 'opaque',
- shell,
- raw: JSON.stringify(input.input),
- reason: 'legacy adapter could not identify a capability',
- },
- ];
- }
- /**
- * Validate the plan at the execution boundary and return a detached immutable copy.
- * The returned `effectiveInput` is the only input a permission gate may install.
- */
- export function validatePermissionExecutionPlan(
- value: unknown,
- expectedOriginalInput: Readonly<Record<string, unknown>>,
- ): Readonly<ExecutionPlan> {
- const plan = readRecord(value, 'Permission execution plan must be an object.');
- const originalInput = readRecord(
- readDataProperty(plan, 'originalInput'),
- 'Permission execution plan requires originalInput.',
- );
- const effectiveInput = readRecord(
- readDataProperty(plan, 'effectiveInput'),
- 'Permission execution plan requires effectiveInput.',
- );
- const intents = readDataProperty(plan, 'intents');
- const transforms = readDataProperty(plan, 'transforms');
- if (!Array.isArray(intents) || !intents.every(isCommandIntent)) {
- throw new TypeError('Permission execution plan contains invalid intents.');
- }
- if (!Array.isArray(transforms) || !transforms.every(isExecutionTransform)) {
- throw new TypeError('Permission execution plan contains an invalid transform.');
- }
- const expectedSnapshot = snapshotPermissionInput(expectedOriginalInput);
- const originalSnapshot = snapshotPermissionInput(originalInput);
- const effectiveSnapshot = snapshotPermissionInput(effectiveInput);
- if (!permissionValuesEqual(originalSnapshot, expectedSnapshot)) {
- throw new TypeError('Permission execution plan original input does not match the tool call.');
- }
- if (!hasEveryInputField(effectiveSnapshot, originalSnapshot)) {
- throw new TypeError('Permission execution plan effective input must be complete.');
- }
- validateTransformConsistency(originalSnapshot, effectiveSnapshot, intents, transforms);
- const metadata = snapshotPermissionInput({ intents, transforms });
- return Object.freeze({
- originalInput: originalSnapshot as Record<string, unknown>,
- effectiveInput: effectiveSnapshot as Record<string, unknown>,
- intents: metadata.intents as CommandIntent[],
- transforms: metadata.transforms as ExecutionTransform[],
- });
- }
- function inferBashSegmentIntent(
- command: string,
- input: CreatePermissionExecutionPlanInput,
- shell: ShellFamily,
- ): CommandIntent[] {
- const effectiveShell = shell === 'unknown' ? 'posix' : shell;
- const nativeDelete =
- effectiveShell === 'cmd' || effectiveShell === 'powershell'
- ? parseWindowsNativeDelete(command, effectiveShell)
- : undefined;
- if (nativeDelete && nativeDelete.shell === effectiveShell) {
- return [
- {
- kind: 'filesystem',
- action: 'delete',
- paths: nativeDelete.targets.map((raw) => toPathValue(raw, input)),
- ...(nativeDelete.recursive ? { recursive: true } : {}),
- ...(nativeDelete.force ? { force: true } : {}),
- shell: effectiveShell,
- },
- ];
- }
- if (isRmCommand(command)) {
- return [
- {
- kind: 'filesystem',
- action: 'delete',
- paths: parseRmTargets(command).map((raw) => toPathValue(raw, input)),
- shell: effectiveShell,
- },
- ];
- }
- const tokens = shellTokenize(command);
- const scriptIntent = inferScriptIntent(tokens, input, effectiveShell);
- if (scriptIntent) return [scriptIntent];
- const networkIntent = inferNetworkIntent(tokens, effectiveShell);
- if (networkIntent) return [networkIntent];
- return [
- { kind: 'execute', argv: [command], shell: effectiveShell, dynamic: /[$`*;]/.test(command) },
- ];
- }
- const SCRIPT_INTERPRETERS = new Set([
- 'bash',
- 'sh',
- 'zsh',
- 'fish',
- 'ksh',
- 'dash',
- 'node',
- 'deno',
- 'python',
- 'python3',
- 'ruby',
- ]);
- function inferScriptIntent(
- tokens: string[],
- input: CreatePermissionExecutionPlanInput,
- shell: ShellFamily,
- ): CommandIntent | undefined {
- const interpreter = tokens[0]?.split('/').at(-1);
- if (!interpreter || !SCRIPT_INTERPRETERS.has(interpreter)) return undefined;
- if (interpreter === 'deno' && tokens[1] !== 'run') return undefined;
- const operand = interpreter === 'deno' ? tokens[2] : tokens[1];
- if (
- !operand ||
- operand.startsWith('-') ||
- operand.includes('$') ||
- operand.includes('`') ||
- /[*?[\]]/.test(operand)
- ) {
- return undefined;
- }
- return {
- kind: 'script',
- interpreter,
- path: toPathValue(operand, input),
- shell,
- dynamic: false,
- };
- }
- function inferNetworkIntent(tokens: string[], shell: ShellFamily): CommandIntent | undefined {
- const program = tokens[0]?.split('/').at(-1);
- if (program !== 'curl' && program !== 'wget') return undefined;
- const targets = tokens.filter((token) => /^https?:\/\/[^$`*?[\]]+$/.test(token));
- if (targets.length === 0) return undefined;
- return {
- kind: 'network',
- targets,
- method: program === 'wget' ? 'GET' : undefined,
- shell,
- dynamic: false,
- };
- }
- function collectRecoverableDeleteTargets(intents: readonly CommandIntent[]): string[] {
- return intents.flatMap((intent) =>
- intent.kind === 'filesystem' && intent.action === 'delete'
- ? intent.paths.map((pathValue) => pathValue.resolved ?? pathValue.raw)
- : [],
- );
- }
- function toPathValue(raw: string, input: CreatePermissionExecutionPlanInput): PathValue {
- return resolvePermissionPath(raw, input.context, input.shell ?? 'unknown');
- }
- function extractPathCandidates(input: Record<string, unknown>): string[] {
- for (const key of ['filePath', 'file_path', 'path', 'pattern', 'paths']) {
- const value = input[key];
- if (typeof value === 'string') return [value];
- if (Array.isArray(value) && value.every((item): item is string => typeof item === 'string')) {
- return value;
- }
- }
- return [];
- }
- function validateTransformConsistency(
- originalInput: Readonly<Record<string, unknown>>,
- effectiveInput: Readonly<Record<string, unknown>>,
- intents: readonly CommandIntent[],
- transforms: readonly ExecutionTransform[],
- ): void {
- const changed = !permissionValuesEqual(originalInput, effectiveInput);
- const deleteIntents = intents.filter(
- (intent): intent is Extract<CommandIntent, { kind: 'filesystem' }> =>
- intent.kind === 'filesystem' && intent.action === 'delete',
- );
- if (deleteIntents.length > 0 && transforms.length === 0) {
- throw new TypeError('Delete execution plan requires a recoverable-delete transform.');
- }
- if (changed && transforms.length === 0) {
- throw new TypeError('Permission execution plan changed input without a declared transform.');
- }
- if (transforms.length === 0) return;
- const recoverableTargets = transforms.flatMap((transform) => transform.targets);
- const executedTargets = readRecoverableDeleteTargets(effectiveInput);
- if (!executedTargets) {
- throw new TypeError('Recoverable-delete execution plan must execute mavis-trash.');
- }
- if (!changed) {
- throw new TypeError('Permission execution plan declares a transform for unchanged input.');
- }
- const intentTargets = deleteIntents.flatMap((intent) =>
- intent.paths.map((pathValue) => pathValue.resolved ?? pathValue.raw),
- );
- if (!sameStringSet(recoverableTargets, intentTargets)) {
- throw new TypeError('Recoverable-delete transform targets do not match delete intents.');
- }
- const windowsTrash = readWindowsTrashExecution(effectiveInput);
- if (windowsTrash) {
- if (!sameStringSet(windowsTrash.targets, recoverableTargets)) {
- throw new TypeError(
- 'Windows recoverable-delete plan requires the targets-only trash marker.',
- );
- }
- return;
- }
- const usesWindowsShell = deleteIntents.some(
- (intent) => intent.shell === 'cmd' || intent.shell === 'powershell',
- );
- if (usesWindowsShell) {
- throw new TypeError('Windows recoverable-delete plan requires the targets-only trash marker.');
- }
- if (!targetsMatchIntentPaths(executedTargets, deleteIntents)) {
- throw new TypeError('Recoverable-delete effective input targets do not match delete intents.');
- }
- }
- function readRecoverableDeleteTargets(
- input: Readonly<Record<string, unknown>>,
- ): string[] | undefined {
- const command = readDataProperty(input, 'command');
- if (typeof command !== 'string') return undefined;
- const targets = splitCommand(command).flatMap((segment) => {
- const tokens = shellTokenize(segment);
- const executable = readExecutableBasename(segment, tokens[0]);
- if (executable !== 'mavis-trash' && executable !== 'mavis-trash.cmd') return [];
- return tokens.slice(tokens[1] === '--' ? 2 : 1);
- });
- return targets.length > 0 || readWindowsTrashExecution(input) ? targets : undefined;
- }
- function readExecutableBasename(segment: string, tokenizedExecutable: string | undefined): string {
- const trimmed = segment.trimStart();
- const quote = trimmed[0];
- const rawExecutable =
- quote === "'" || quote === '"'
- ? trimmed.slice(1, trimmed.indexOf(quote, 1) === -1 ? undefined : trimmed.indexOf(quote, 1))
- : trimmed.match(/^\S+/)?.[0];
- return (rawExecutable ?? tokenizedExecutable ?? '').split(/[\\/]/).at(-1)?.toLowerCase() ?? '';
- }
- function targetsMatchIntentPaths(
- executedTargets: readonly string[],
- deleteIntents: readonly Extract<CommandIntent, { kind: 'filesystem' }>[],
- ): boolean {
- const paths = deleteIntents.flatMap((intent) => intent.paths);
- return (
- executedTargets.length === paths.length &&
- executedTargets.every((target) =>
- paths.some((pathValue) => target === pathValue.raw || target === pathValue.resolved),
- ) &&
- paths.every((pathValue) =>
- executedTargets.some((target) => target === pathValue.raw || target === pathValue.resolved),
- )
- );
- }
- function hasEveryInputField(
- effectiveInput: Readonly<Record<string, unknown>>,
- originalInput: Readonly<Record<string, unknown>>,
- ): boolean {
- return enumerableDataKeys(originalInput).every((key) =>
- Object.prototype.hasOwnProperty.call(effectiveInput, key),
- );
- }
- function isExecutionTransform(value: unknown): value is ExecutionTransform {
- if (!isRecord(value) || readDataProperty(value, 'type') !== 'recoverable-delete') return false;
- const targets = readDataProperty(value, 'targets');
- return Array.isArray(targets) && targets.length > 0 && targets.every(isNonBlankString);
- }
- function isCommandIntent(value: unknown): value is CommandIntent {
- if (!isRecord(value)) return false;
- const kind = readDataProperty(value, 'kind');
- const shell = readDataProperty(value, 'shell');
- if (!isShellFamily(shell)) return false;
- if (kind === 'filesystem') return isFilesystemIntent(value);
- if (kind === 'execute') {
- return isStringArray(readDataProperty(value, 'argv')) && isBoolean(value, 'dynamic');
- }
- if (kind === 'network') {
- return isStringArray(readDataProperty(value, 'targets')) && isBoolean(value, 'dynamic');
- }
- if (kind === 'script') return isBoolean(value, 'dynamic') && isOptionalPathValue(value, 'path');
- return kind === 'opaque' && isNonBlankString(readDataProperty(value, 'reason'));
- }
- function isFilesystemIntent(
- value: Record<PropertyKey, unknown>,
- ): value is Extract<CommandIntent, { kind: 'filesystem' }> {
- const action = readDataProperty(value, 'action');
- const paths = readDataProperty(value, 'paths');
- return (
- typeof action === 'string' &&
- FILESYSTEM_ACTIONS.has(action) &&
- Array.isArray(paths) &&
- paths.length > 0 &&
- paths.every(isPathValue)
- );
- }
- function isPathValue(value: unknown): value is PathValue {
- if (!isRecord(value)) return false;
- const raw = readDataProperty(value, 'raw');
- const dynamic = readDataProperty(value, 'dynamic');
- const resolved = readDataProperty(value, 'resolved');
- return (
- typeof raw === 'string' &&
- typeof dynamic === 'boolean' &&
- (resolved === undefined || typeof resolved === 'string')
- );
- }
- function isOptionalPathValue(value: Record<PropertyKey, unknown>, key: PropertyKey): boolean {
- const pathValue = readDataProperty(value, key);
- return pathValue === undefined || isPathValue(pathValue);
- }
- function isBoolean(value: Record<PropertyKey, unknown>, key: PropertyKey): boolean {
- return typeof readDataProperty(value, key) === 'boolean';
- }
- function isShellFamily(value: unknown): value is ShellFamily {
- return typeof value === 'string' && SHELL_FAMILIES.has(value as ShellFamily);
- }
- function isStringArray(value: unknown): value is string[] {
- return Array.isArray(value) && value.every((item) => typeof item === 'string');
- }
- function isNonBlankString(value: unknown): value is string {
- return typeof value === 'string' && Boolean(value.trim());
- }
- function sameStringSet(left: readonly string[], right: readonly string[]): boolean {
- const a = [...new Set(left)].sort();
- const b = [...new Set(right)].sort();
- return a.length === b.length && a.every((value, index) => value === b[index]);
- }
- function permissionValuesEqual(left: unknown, right: unknown): boolean {
- if (Object.is(left, right)) return true;
- if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
- if (Array.isArray(left) || Array.isArray(right)) {
- return (
- Array.isArray(left) &&
- Array.isArray(right) &&
- left.length === right.length &&
- left.every((item, index) => permissionValuesEqual(item, right[index]))
- );
- }
- if (!isRecord(left) || !isRecord(right)) return false;
- const leftKeys = enumerableDataKeys(left);
- const rightKeys = enumerableDataKeys(right);
- return (
- leftKeys.length === rightKeys.length &&
- leftKeys.every(
- (key) =>
- rightKeys.includes(key) &&
- permissionValuesEqual(readDataProperty(left, key), readDataProperty(right, key)),
- )
- );
- }
- function enumerableDataKeys(value: object): PropertyKey[] {
- return Reflect.ownKeys(value).filter((key) => {
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
- if (!descriptor?.enumerable) return false;
- if (!('value' in descriptor)) {
- throw new TypeError('Permission execution plan must not contain accessors.');
- }
- return true;
- });
- }
- function readDataProperty(value: object, key: PropertyKey): unknown {
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
- if (!descriptor) return undefined;
- if (!('value' in descriptor)) {
- throw new TypeError('Permission execution plan must not contain accessors.');
- }
- return descriptor.value;
- }
- function readRecord(value: unknown, message: string): Record<PropertyKey, unknown> {
- if (!isRecord(value)) throw new TypeError(message);
- return value;
- }
- function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
- const prototype = Object.getPrototypeOf(value);
- return prototype === Object.prototype || prototype === null;
- }
|