execution-plan.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import { snapshotPermissionEffectiveInput, snapshotPermissionInput } from './effective-input.js';
  2. import type {
  3. CommandIntent,
  4. ExecutionPlan,
  5. ExecutionTransform,
  6. PermissionAction,
  7. PermissionEvaluationInput,
  8. PathValue,
  9. ShellFamily,
  10. } from './permission-core.js';
  11. import { resolvePermissionPath } from './path-resolver.js';
  12. import { readWindowsTrashExecution } from './windows-trash-execution.js';
  13. import { isRmCommand, parseRmTargets } from './tools/bash-permission.js';
  14. import { splitCommand } from './tools/bash-split.js';
  15. import { shellTokenize } from './tools/shell-tokenize.js';
  16. import { parseWindowsNativeDelete } from './tools/windows-native-delete.js';
  17. export type { ExecutionPlan } from './permission-core.js';
  18. const SHELL_FAMILIES = new Set<ShellFamily>(['posix', 'cmd', 'powershell', 'unknown']);
  19. const FILESYSTEM_ACTIONS = new Set(['read', 'write', 'delete']);
  20. export type CreatePermissionExecutionPlanInput = Pick<
  21. PermissionEvaluationInput,
  22. 'toolName' | 'input'
  23. > & {
  24. shell?: ShellFamily;
  25. context?: Pick<PermissionEvaluationInput['context'], 'workingDirectory' | 'homeDir'>;
  26. rewrittenInput?: Readonly<Record<string, unknown>>;
  27. };
  28. /** Build the complete immutable plan consumed by production permission gates. */
  29. export function createPermissionExecutionPlan(
  30. input: CreatePermissionExecutionPlanInput,
  31. ): Readonly<ExecutionPlan> {
  32. const originalInput = snapshotPermissionInput(input.input);
  33. const intents = inferPermissionCommandIntents(input);
  34. const effectiveInput =
  35. snapshotPermissionEffectiveInput(originalInput, input.rewrittenInput) ?? originalInput;
  36. const targets = collectRecoverableDeleteTargets(intents);
  37. const transforms: ExecutionPlan['transforms'] =
  38. input.rewrittenInput && targets.length > 0 ? [{ type: 'recoverable-delete', targets }] : [];
  39. return validatePermissionExecutionPlan(
  40. { originalInput, effectiveInput, intents, transforms },
  41. originalInput,
  42. );
  43. }
  44. /** Shared intent inference used by the production plan builder and legacy parity adapter. */
  45. export function inferPermissionCommandIntents(
  46. input: CreatePermissionExecutionPlanInput,
  47. ): CommandIntent[] {
  48. const shell = input.shell ?? 'unknown';
  49. if (input.toolName === 'bash' && typeof input.input.command === 'string') {
  50. const command = input.input.command;
  51. const segments = splitCommand(command);
  52. if (segments.length > 1) {
  53. return segments.flatMap((segment) => inferBashSegmentIntent(segment, input, shell));
  54. }
  55. return inferBashSegmentIntent(command, input, shell);
  56. }
  57. const pathCandidates = extractPathCandidates(input.input);
  58. if (pathCandidates.length > 0) {
  59. const action: PermissionAction =
  60. input.toolName === 'delete'
  61. ? 'delete'
  62. : ['edit', 'write', 'append'].includes(input.toolName)
  63. ? 'write'
  64. : 'read';
  65. return [
  66. {
  67. kind: 'filesystem',
  68. action,
  69. paths: pathCandidates.map((candidate) => toPathValue(candidate, input)),
  70. shell,
  71. },
  72. ];
  73. }
  74. return [
  75. {
  76. kind: 'opaque',
  77. shell,
  78. raw: JSON.stringify(input.input),
  79. reason: 'legacy adapter could not identify a capability',
  80. },
  81. ];
  82. }
  83. /**
  84. * Validate the plan at the execution boundary and return a detached immutable copy.
  85. * The returned `effectiveInput` is the only input a permission gate may install.
  86. */
  87. export function validatePermissionExecutionPlan(
  88. value: unknown,
  89. expectedOriginalInput: Readonly<Record<string, unknown>>,
  90. ): Readonly<ExecutionPlan> {
  91. const plan = readRecord(value, 'Permission execution plan must be an object.');
  92. const originalInput = readRecord(
  93. readDataProperty(plan, 'originalInput'),
  94. 'Permission execution plan requires originalInput.',
  95. );
  96. const effectiveInput = readRecord(
  97. readDataProperty(plan, 'effectiveInput'),
  98. 'Permission execution plan requires effectiveInput.',
  99. );
  100. const intents = readDataProperty(plan, 'intents');
  101. const transforms = readDataProperty(plan, 'transforms');
  102. if (!Array.isArray(intents) || !intents.every(isCommandIntent)) {
  103. throw new TypeError('Permission execution plan contains invalid intents.');
  104. }
  105. if (!Array.isArray(transforms) || !transforms.every(isExecutionTransform)) {
  106. throw new TypeError('Permission execution plan contains an invalid transform.');
  107. }
  108. const expectedSnapshot = snapshotPermissionInput(expectedOriginalInput);
  109. const originalSnapshot = snapshotPermissionInput(originalInput);
  110. const effectiveSnapshot = snapshotPermissionInput(effectiveInput);
  111. if (!permissionValuesEqual(originalSnapshot, expectedSnapshot)) {
  112. throw new TypeError('Permission execution plan original input does not match the tool call.');
  113. }
  114. if (!hasEveryInputField(effectiveSnapshot, originalSnapshot)) {
  115. throw new TypeError('Permission execution plan effective input must be complete.');
  116. }
  117. validateTransformConsistency(originalSnapshot, effectiveSnapshot, intents, transforms);
  118. const metadata = snapshotPermissionInput({ intents, transforms });
  119. return Object.freeze({
  120. originalInput: originalSnapshot as Record<string, unknown>,
  121. effectiveInput: effectiveSnapshot as Record<string, unknown>,
  122. intents: metadata.intents as CommandIntent[],
  123. transforms: metadata.transforms as ExecutionTransform[],
  124. });
  125. }
  126. function inferBashSegmentIntent(
  127. command: string,
  128. input: CreatePermissionExecutionPlanInput,
  129. shell: ShellFamily,
  130. ): CommandIntent[] {
  131. const effectiveShell = shell === 'unknown' ? 'posix' : shell;
  132. const nativeDelete =
  133. effectiveShell === 'cmd' || effectiveShell === 'powershell'
  134. ? parseWindowsNativeDelete(command, effectiveShell)
  135. : undefined;
  136. if (nativeDelete && nativeDelete.shell === effectiveShell) {
  137. return [
  138. {
  139. kind: 'filesystem',
  140. action: 'delete',
  141. paths: nativeDelete.targets.map((raw) => toPathValue(raw, input)),
  142. ...(nativeDelete.recursive ? { recursive: true } : {}),
  143. ...(nativeDelete.force ? { force: true } : {}),
  144. shell: effectiveShell,
  145. },
  146. ];
  147. }
  148. if (isRmCommand(command)) {
  149. return [
  150. {
  151. kind: 'filesystem',
  152. action: 'delete',
  153. paths: parseRmTargets(command).map((raw) => toPathValue(raw, input)),
  154. shell: effectiveShell,
  155. },
  156. ];
  157. }
  158. const tokens = shellTokenize(command);
  159. const scriptIntent = inferScriptIntent(tokens, input, effectiveShell);
  160. if (scriptIntent) return [scriptIntent];
  161. const networkIntent = inferNetworkIntent(tokens, effectiveShell);
  162. if (networkIntent) return [networkIntent];
  163. return [
  164. { kind: 'execute', argv: [command], shell: effectiveShell, dynamic: /[$`*;]/.test(command) },
  165. ];
  166. }
  167. const SCRIPT_INTERPRETERS = new Set([
  168. 'bash',
  169. 'sh',
  170. 'zsh',
  171. 'fish',
  172. 'ksh',
  173. 'dash',
  174. 'node',
  175. 'deno',
  176. 'python',
  177. 'python3',
  178. 'ruby',
  179. ]);
  180. function inferScriptIntent(
  181. tokens: string[],
  182. input: CreatePermissionExecutionPlanInput,
  183. shell: ShellFamily,
  184. ): CommandIntent | undefined {
  185. const interpreter = tokens[0]?.split('/').at(-1);
  186. if (!interpreter || !SCRIPT_INTERPRETERS.has(interpreter)) return undefined;
  187. if (interpreter === 'deno' && tokens[1] !== 'run') return undefined;
  188. const operand = interpreter === 'deno' ? tokens[2] : tokens[1];
  189. if (
  190. !operand ||
  191. operand.startsWith('-') ||
  192. operand.includes('$') ||
  193. operand.includes('`') ||
  194. /[*?[\]]/.test(operand)
  195. ) {
  196. return undefined;
  197. }
  198. return {
  199. kind: 'script',
  200. interpreter,
  201. path: toPathValue(operand, input),
  202. shell,
  203. dynamic: false,
  204. };
  205. }
  206. function inferNetworkIntent(tokens: string[], shell: ShellFamily): CommandIntent | undefined {
  207. const program = tokens[0]?.split('/').at(-1);
  208. if (program !== 'curl' && program !== 'wget') return undefined;
  209. const targets = tokens.filter((token) => /^https?:\/\/[^$`*?[\]]+$/.test(token));
  210. if (targets.length === 0) return undefined;
  211. return {
  212. kind: 'network',
  213. targets,
  214. method: program === 'wget' ? 'GET' : undefined,
  215. shell,
  216. dynamic: false,
  217. };
  218. }
  219. function collectRecoverableDeleteTargets(intents: readonly CommandIntent[]): string[] {
  220. return intents.flatMap((intent) =>
  221. intent.kind === 'filesystem' && intent.action === 'delete'
  222. ? intent.paths.map((pathValue) => pathValue.resolved ?? pathValue.raw)
  223. : [],
  224. );
  225. }
  226. function toPathValue(raw: string, input: CreatePermissionExecutionPlanInput): PathValue {
  227. return resolvePermissionPath(raw, input.context, input.shell ?? 'unknown');
  228. }
  229. function extractPathCandidates(input: Record<string, unknown>): string[] {
  230. for (const key of ['filePath', 'file_path', 'path', 'pattern', 'paths']) {
  231. const value = input[key];
  232. if (typeof value === 'string') return [value];
  233. if (Array.isArray(value) && value.every((item): item is string => typeof item === 'string')) {
  234. return value;
  235. }
  236. }
  237. return [];
  238. }
  239. function validateTransformConsistency(
  240. originalInput: Readonly<Record<string, unknown>>,
  241. effectiveInput: Readonly<Record<string, unknown>>,
  242. intents: readonly CommandIntent[],
  243. transforms: readonly ExecutionTransform[],
  244. ): void {
  245. const changed = !permissionValuesEqual(originalInput, effectiveInput);
  246. const deleteIntents = intents.filter(
  247. (intent): intent is Extract<CommandIntent, { kind: 'filesystem' }> =>
  248. intent.kind === 'filesystem' && intent.action === 'delete',
  249. );
  250. if (deleteIntents.length > 0 && transforms.length === 0) {
  251. throw new TypeError('Delete execution plan requires a recoverable-delete transform.');
  252. }
  253. if (changed && transforms.length === 0) {
  254. throw new TypeError('Permission execution plan changed input without a declared transform.');
  255. }
  256. if (transforms.length === 0) return;
  257. const recoverableTargets = transforms.flatMap((transform) => transform.targets);
  258. const executedTargets = readRecoverableDeleteTargets(effectiveInput);
  259. if (!executedTargets) {
  260. throw new TypeError('Recoverable-delete execution plan must execute mavis-trash.');
  261. }
  262. if (!changed) {
  263. throw new TypeError('Permission execution plan declares a transform for unchanged input.');
  264. }
  265. const intentTargets = deleteIntents.flatMap((intent) =>
  266. intent.paths.map((pathValue) => pathValue.resolved ?? pathValue.raw),
  267. );
  268. if (!sameStringSet(recoverableTargets, intentTargets)) {
  269. throw new TypeError('Recoverable-delete transform targets do not match delete intents.');
  270. }
  271. const windowsTrash = readWindowsTrashExecution(effectiveInput);
  272. if (windowsTrash) {
  273. if (!sameStringSet(windowsTrash.targets, recoverableTargets)) {
  274. throw new TypeError(
  275. 'Windows recoverable-delete plan requires the targets-only trash marker.',
  276. );
  277. }
  278. return;
  279. }
  280. const usesWindowsShell = deleteIntents.some(
  281. (intent) => intent.shell === 'cmd' || intent.shell === 'powershell',
  282. );
  283. if (usesWindowsShell) {
  284. throw new TypeError('Windows recoverable-delete plan requires the targets-only trash marker.');
  285. }
  286. if (!targetsMatchIntentPaths(executedTargets, deleteIntents)) {
  287. throw new TypeError('Recoverable-delete effective input targets do not match delete intents.');
  288. }
  289. }
  290. function readRecoverableDeleteTargets(
  291. input: Readonly<Record<string, unknown>>,
  292. ): string[] | undefined {
  293. const command = readDataProperty(input, 'command');
  294. if (typeof command !== 'string') return undefined;
  295. const targets = splitCommand(command).flatMap((segment) => {
  296. const tokens = shellTokenize(segment);
  297. const executable = readExecutableBasename(segment, tokens[0]);
  298. if (executable !== 'mavis-trash' && executable !== 'mavis-trash.cmd') return [];
  299. return tokens.slice(tokens[1] === '--' ? 2 : 1);
  300. });
  301. return targets.length > 0 || readWindowsTrashExecution(input) ? targets : undefined;
  302. }
  303. function readExecutableBasename(segment: string, tokenizedExecutable: string | undefined): string {
  304. const trimmed = segment.trimStart();
  305. const quote = trimmed[0];
  306. const rawExecutable =
  307. quote === "'" || quote === '"'
  308. ? trimmed.slice(1, trimmed.indexOf(quote, 1) === -1 ? undefined : trimmed.indexOf(quote, 1))
  309. : trimmed.match(/^\S+/)?.[0];
  310. return (rawExecutable ?? tokenizedExecutable ?? '').split(/[\\/]/).at(-1)?.toLowerCase() ?? '';
  311. }
  312. function targetsMatchIntentPaths(
  313. executedTargets: readonly string[],
  314. deleteIntents: readonly Extract<CommandIntent, { kind: 'filesystem' }>[],
  315. ): boolean {
  316. const paths = deleteIntents.flatMap((intent) => intent.paths);
  317. return (
  318. executedTargets.length === paths.length &&
  319. executedTargets.every((target) =>
  320. paths.some((pathValue) => target === pathValue.raw || target === pathValue.resolved),
  321. ) &&
  322. paths.every((pathValue) =>
  323. executedTargets.some((target) => target === pathValue.raw || target === pathValue.resolved),
  324. )
  325. );
  326. }
  327. function hasEveryInputField(
  328. effectiveInput: Readonly<Record<string, unknown>>,
  329. originalInput: Readonly<Record<string, unknown>>,
  330. ): boolean {
  331. return enumerableDataKeys(originalInput).every((key) =>
  332. Object.prototype.hasOwnProperty.call(effectiveInput, key),
  333. );
  334. }
  335. function isExecutionTransform(value: unknown): value is ExecutionTransform {
  336. if (!isRecord(value) || readDataProperty(value, 'type') !== 'recoverable-delete') return false;
  337. const targets = readDataProperty(value, 'targets');
  338. return Array.isArray(targets) && targets.length > 0 && targets.every(isNonBlankString);
  339. }
  340. function isCommandIntent(value: unknown): value is CommandIntent {
  341. if (!isRecord(value)) return false;
  342. const kind = readDataProperty(value, 'kind');
  343. const shell = readDataProperty(value, 'shell');
  344. if (!isShellFamily(shell)) return false;
  345. if (kind === 'filesystem') return isFilesystemIntent(value);
  346. if (kind === 'execute') {
  347. return isStringArray(readDataProperty(value, 'argv')) && isBoolean(value, 'dynamic');
  348. }
  349. if (kind === 'network') {
  350. return isStringArray(readDataProperty(value, 'targets')) && isBoolean(value, 'dynamic');
  351. }
  352. if (kind === 'script') return isBoolean(value, 'dynamic') && isOptionalPathValue(value, 'path');
  353. return kind === 'opaque' && isNonBlankString(readDataProperty(value, 'reason'));
  354. }
  355. function isFilesystemIntent(
  356. value: Record<PropertyKey, unknown>,
  357. ): value is Extract<CommandIntent, { kind: 'filesystem' }> {
  358. const action = readDataProperty(value, 'action');
  359. const paths = readDataProperty(value, 'paths');
  360. return (
  361. typeof action === 'string' &&
  362. FILESYSTEM_ACTIONS.has(action) &&
  363. Array.isArray(paths) &&
  364. paths.length > 0 &&
  365. paths.every(isPathValue)
  366. );
  367. }
  368. function isPathValue(value: unknown): value is PathValue {
  369. if (!isRecord(value)) return false;
  370. const raw = readDataProperty(value, 'raw');
  371. const dynamic = readDataProperty(value, 'dynamic');
  372. const resolved = readDataProperty(value, 'resolved');
  373. return (
  374. typeof raw === 'string' &&
  375. typeof dynamic === 'boolean' &&
  376. (resolved === undefined || typeof resolved === 'string')
  377. );
  378. }
  379. function isOptionalPathValue(value: Record<PropertyKey, unknown>, key: PropertyKey): boolean {
  380. const pathValue = readDataProperty(value, key);
  381. return pathValue === undefined || isPathValue(pathValue);
  382. }
  383. function isBoolean(value: Record<PropertyKey, unknown>, key: PropertyKey): boolean {
  384. return typeof readDataProperty(value, key) === 'boolean';
  385. }
  386. function isShellFamily(value: unknown): value is ShellFamily {
  387. return typeof value === 'string' && SHELL_FAMILIES.has(value as ShellFamily);
  388. }
  389. function isStringArray(value: unknown): value is string[] {
  390. return Array.isArray(value) && value.every((item) => typeof item === 'string');
  391. }
  392. function isNonBlankString(value: unknown): value is string {
  393. return typeof value === 'string' && Boolean(value.trim());
  394. }
  395. function sameStringSet(left: readonly string[], right: readonly string[]): boolean {
  396. const a = [...new Set(left)].sort();
  397. const b = [...new Set(right)].sort();
  398. return a.length === b.length && a.every((value, index) => value === b[index]);
  399. }
  400. function permissionValuesEqual(left: unknown, right: unknown): boolean {
  401. if (Object.is(left, right)) return true;
  402. if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
  403. if (Array.isArray(left) || Array.isArray(right)) {
  404. return (
  405. Array.isArray(left) &&
  406. Array.isArray(right) &&
  407. left.length === right.length &&
  408. left.every((item, index) => permissionValuesEqual(item, right[index]))
  409. );
  410. }
  411. if (!isRecord(left) || !isRecord(right)) return false;
  412. const leftKeys = enumerableDataKeys(left);
  413. const rightKeys = enumerableDataKeys(right);
  414. return (
  415. leftKeys.length === rightKeys.length &&
  416. leftKeys.every(
  417. (key) =>
  418. rightKeys.includes(key) &&
  419. permissionValuesEqual(readDataProperty(left, key), readDataProperty(right, key)),
  420. )
  421. );
  422. }
  423. function enumerableDataKeys(value: object): PropertyKey[] {
  424. return Reflect.ownKeys(value).filter((key) => {
  425. const descriptor = Object.getOwnPropertyDescriptor(value, key);
  426. if (!descriptor?.enumerable) return false;
  427. if (!('value' in descriptor)) {
  428. throw new TypeError('Permission execution plan must not contain accessors.');
  429. }
  430. return true;
  431. });
  432. }
  433. function readDataProperty(value: object, key: PropertyKey): unknown {
  434. const descriptor = Object.getOwnPropertyDescriptor(value, key);
  435. if (!descriptor) return undefined;
  436. if (!('value' in descriptor)) {
  437. throw new TypeError('Permission execution plan must not contain accessors.');
  438. }
  439. return descriptor.value;
  440. }
  441. function readRecord(value: unknown, message: string): Record<PropertyKey, unknown> {
  442. if (!isRecord(value)) throw new TypeError(message);
  443. return value;
  444. }
  445. function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
  446. if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  447. const prototype = Object.getPrototypeOf(value);
  448. return prototype === Object.prototype || prototype === null;
  449. }