context.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /**
  2. * ToolPermissionContext management — immutable permission state.
  3. *
  4. * The context holds the in-memory representation of all permission rules,
  5. * the current mode, and environment settings. It is the single source of
  6. * truth for the {@link PermissionEngine} at query time.
  7. *
  8. * All mutations go through {@link applyPermissionUpdate}, which returns a
  9. * new frozen object (the original is never mutated).
  10. *
  11. * Reference: permission_design.md §3 (Persistence Layer) and §4.2 (Design Decisions).
  12. */
  13. import { logger } from './host-utils.js';
  14. import type {
  15. PermissionBehavior,
  16. PermissionMode,
  17. PermissionRule,
  18. PermissionRuleSource,
  19. PermissionRuleValue,
  20. PermissionUpdate,
  21. } from './types.js';
  22. // ---------------------------------------------------------------------------
  23. // DeepReadonly utility type
  24. // ---------------------------------------------------------------------------
  25. /** Recursively marks every property as readonly. */
  26. export type DeepReadonly<T> = T extends (infer U)[]
  27. ? ReadonlyArray<DeepReadonly<U>>
  28. : T extends Map<infer K, infer V>
  29. ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
  30. : T extends Set<infer U>
  31. ? ReadonlySet<DeepReadonly<U>>
  32. : T extends object
  33. ? { readonly [P in keyof T]: DeepReadonly<T[P]> }
  34. : T;
  35. // ---------------------------------------------------------------------------
  36. // ToolPermissionContext
  37. // ---------------------------------------------------------------------------
  38. /**
  39. * Complete runtime permission context.
  40. *
  41. * Held in memory by the daemon; rebuilt from disk on startup and updated
  42. * immutably whenever the user grants / revokes permissions.
  43. */
  44. export interface ToolPermissionContext {
  45. /** Current permission mode. */
  46. readonly mode: PermissionMode;
  47. /** Merged rules from all sources (global + agent + session). */
  48. readonly rules: readonly PermissionRule[];
  49. /** Whether the sandbox environment is available. */
  50. readonly sandboxEnabled: boolean;
  51. /** If true AND sandbox is enabled, bash commands skip tool-level ask rules. */
  52. readonly autoAllowBashIfSandboxed: boolean;
  53. /** Host platform used for platform-specific parser and launcher semantics. */
  54. readonly platform: NodeJS.Platform;
  55. /** Actual shell family used for platform-specific command semantics. */
  56. readonly shellFamily: 'posix' | 'cmd' | 'powershell' | 'unknown';
  57. /** Primary working directory (CWD of the agent session). */
  58. readonly workingDirectory: string;
  59. /** Additional allowed working paths beyond `workingDirectory`. */
  60. readonly allowedWorkingPaths: readonly string[];
  61. /** Paths the sandbox is allowed to write to. */
  62. readonly sandboxAllowPaths: readonly string[];
  63. /** Turn-scoped exact write targets issued by the trusted execution owner. */
  64. readonly trustedExactWritePaths: readonly string[];
  65. /** Root data directory resolved from daemon runtime config. */
  66. readonly dataDir: string;
  67. /** User home directory. */
  68. readonly homeDir: string;
  69. /** Host-owned file probe used by conservative local-script permission checks. */
  70. readonly isFile?: (filePath: string) => boolean;
  71. /** Agent name (for agent-scoped rules). */
  72. readonly agentName?: string;
  73. /** Session ID (for session-scoped rules). */
  74. readonly sessionId?: string;
  75. /** Whether managed permission rules are the only ones shown to the user. */
  76. readonly allowManagedPermissionRulesOnly: boolean;
  77. /**
  78. * Tools that require user interaction and should always be ASK.
  79. * (e.g. "question" tool).
  80. */
  81. readonly interactiveTools: ReadonlySet<string>;
  82. }
  83. // ---------------------------------------------------------------------------
  84. // Configuration input (the shape callers provide)
  85. // ---------------------------------------------------------------------------
  86. /** Input configuration used to construct a ToolPermissionContext. */
  87. export interface ToolPermissionContextConfig {
  88. mode?: PermissionMode;
  89. rules?: PermissionRule[];
  90. sandboxEnabled?: boolean;
  91. autoAllowBashIfSandboxed?: boolean;
  92. platform?: NodeJS.Platform;
  93. shellFamily?: 'posix' | 'cmd' | 'powershell' | 'unknown';
  94. workingDirectory: string;
  95. allowedWorkingPaths?: string[];
  96. sandboxAllowPaths?: string[];
  97. trustedExactWritePaths?: readonly string[];
  98. dataDir: string;
  99. homeDir: string;
  100. isFile?: (filePath: string) => boolean;
  101. agentName?: string;
  102. sessionId?: string;
  103. allowManagedPermissionRulesOnly?: boolean;
  104. interactiveTools?: Set<string>;
  105. }
  106. // ---------------------------------------------------------------------------
  107. // Factory
  108. // ---------------------------------------------------------------------------
  109. /**
  110. * Create a new {@link ToolPermissionContext} from a configuration object.
  111. *
  112. * The returned object is deeply frozen. Any future mutations must go through
  113. * {@link applyPermissionUpdate}.
  114. */
  115. export function createToolPermissionContext(
  116. config: ToolPermissionContextConfig,
  117. ): ToolPermissionContext {
  118. const ctx: ToolPermissionContext = Object.freeze({
  119. mode: config.mode ?? 'default',
  120. rules: Object.freeze([...(config.rules ?? [])]),
  121. sandboxEnabled: config.sandboxEnabled ?? false,
  122. autoAllowBashIfSandboxed: config.autoAllowBashIfSandboxed ?? false,
  123. platform: config.platform ?? process.platform,
  124. shellFamily: config.shellFamily ?? 'unknown',
  125. workingDirectory: config.workingDirectory,
  126. allowedWorkingPaths: Object.freeze([...(config.allowedWorkingPaths ?? [])]),
  127. sandboxAllowPaths: Object.freeze([...(config.sandboxAllowPaths ?? [])]),
  128. trustedExactWritePaths: Object.freeze([...(config.trustedExactWritePaths ?? [])]),
  129. dataDir: config.dataDir,
  130. homeDir: config.homeDir,
  131. isFile: config.isFile,
  132. agentName: config.agentName,
  133. sessionId: config.sessionId,
  134. allowManagedPermissionRulesOnly: config.allowManagedPermissionRulesOnly ?? false,
  135. interactiveTools: Object.freeze(new Set(config.interactiveTools ?? ['question'])),
  136. });
  137. logger.info(
  138. {
  139. mode: ctx.mode,
  140. ruleCount: ctx.rules.length,
  141. sandboxEnabled: ctx.sandboxEnabled,
  142. workingDirectory: ctx.workingDirectory,
  143. },
  144. 'Created ToolPermissionContext',
  145. );
  146. return ctx;
  147. }
  148. // ---------------------------------------------------------------------------
  149. // Immutable update
  150. // ---------------------------------------------------------------------------
  151. /**
  152. * Apply a {@link PermissionUpdate} to a context, returning a **new** frozen
  153. * context. The original `ctx` is never mutated.
  154. *
  155. * Supported update types:
  156. * - `addRules` — append new rules (deduplicated)
  157. * - `replaceRules` — replace all rules of a given behavior+source
  158. * - `removeRules` — remove matching rules
  159. */
  160. export function applyPermissionUpdate(
  161. ctx: ToolPermissionContext,
  162. update: PermissionUpdate,
  163. ): ToolPermissionContext {
  164. switch (update.type) {
  165. case 'addRules':
  166. return addRules(ctx, update.source, update.rules, update.behavior);
  167. case 'replaceRules':
  168. return replaceRules(ctx, update.source, update.rules, update.behavior);
  169. case 'removeRules':
  170. return removeRules(ctx, update.source, update.rules, update.behavior);
  171. }
  172. }
  173. // ---------------------------------------------------------------------------
  174. // Internal helpers
  175. // ---------------------------------------------------------------------------
  176. function cloneContextWith(
  177. ctx: ToolPermissionContext,
  178. patch: Partial<Pick<ToolPermissionContext, 'mode' | 'rules'>>,
  179. ): ToolPermissionContext {
  180. return Object.freeze({
  181. mode: patch.mode ?? ctx.mode,
  182. rules: Object.freeze([...(patch.rules ?? ctx.rules)]),
  183. sandboxEnabled: ctx.sandboxEnabled,
  184. autoAllowBashIfSandboxed: ctx.autoAllowBashIfSandboxed,
  185. platform: ctx.platform,
  186. shellFamily: ctx.shellFamily,
  187. workingDirectory: ctx.workingDirectory,
  188. allowedWorkingPaths: ctx.allowedWorkingPaths,
  189. sandboxAllowPaths: ctx.sandboxAllowPaths,
  190. trustedExactWritePaths: ctx.trustedExactWritePaths,
  191. dataDir: ctx.dataDir,
  192. homeDir: ctx.homeDir,
  193. isFile: ctx.isFile,
  194. agentName: ctx.agentName,
  195. sessionId: ctx.sessionId,
  196. allowManagedPermissionRulesOnly: ctx.allowManagedPermissionRulesOnly,
  197. interactiveTools: ctx.interactiveTools,
  198. });
  199. }
  200. /** Check if two rule values are semantically equal. */
  201. function ruleValueEquals(a: PermissionRuleValue, b: PermissionRuleValue): boolean {
  202. if (a.toolName !== b.toolName || (a.ruleContent ?? '') !== (b.ruleContent ?? '')) return false;
  203. if (!a.matcher || !b.matcher) return a.matcher === b.matcher;
  204. if (a.matcher.kind !== b.matcher.kind) return false;
  205. if (a.matcher.kind === 'tool' || b.matcher.kind === 'tool') return true;
  206. if (a.matcher.pattern !== b.matcher.pattern) return false;
  207. if (a.matcher.kind === 'command' || b.matcher.kind === 'command') return true;
  208. const aActions = a.matcher.actions;
  209. const bActions = b.matcher.actions;
  210. if (!aActions || !bActions) return aActions === bActions;
  211. return (
  212. aActions.length === bActions.length && aActions.every((action) => bActions.includes(action))
  213. );
  214. }
  215. function addRules(
  216. ctx: ToolPermissionContext,
  217. source: PermissionRuleSource,
  218. values: readonly PermissionRuleValue[],
  219. behavior: PermissionBehavior,
  220. ): ToolPermissionContext {
  221. const existing = [...ctx.rules];
  222. for (const value of values) {
  223. // Deduplicate: skip if an identical rule already exists
  224. const duplicate = existing.some(
  225. (r) =>
  226. r.source === source && r.ruleBehavior === behavior && ruleValueEquals(r.ruleValue, value),
  227. );
  228. if (!duplicate) {
  229. existing.push({ source, ruleBehavior: behavior, ruleValue: value });
  230. }
  231. }
  232. logger.info(
  233. { source, behavior, added: values.length, totalAfter: existing.length },
  234. 'Added permission rules',
  235. );
  236. return cloneContextWith(ctx, { rules: existing });
  237. }
  238. function replaceRules(
  239. ctx: ToolPermissionContext,
  240. source: PermissionRuleSource,
  241. values: readonly PermissionRuleValue[],
  242. behavior: PermissionBehavior,
  243. ): ToolPermissionContext {
  244. // Remove existing rules that match the given source + behavior
  245. const kept = ctx.rules.filter((r) => !(r.source === source && r.ruleBehavior === behavior));
  246. // Append the new rules
  247. const newRules = values.map((value) => ({
  248. source,
  249. ruleBehavior: behavior,
  250. ruleValue: value,
  251. }));
  252. logger.info(
  253. { source, behavior, removed: ctx.rules.length - kept.length, added: newRules.length },
  254. 'Replaced permission rules',
  255. );
  256. return cloneContextWith(ctx, { rules: [...kept, ...newRules] });
  257. }
  258. function removeRules(
  259. ctx: ToolPermissionContext,
  260. source: PermissionRuleSource,
  261. values: readonly PermissionRuleValue[],
  262. behavior: PermissionBehavior,
  263. ): ToolPermissionContext {
  264. const remaining = ctx.rules.filter((r) => {
  265. if (r.source !== source || r.ruleBehavior !== behavior) return true;
  266. return !values.some((v) => ruleValueEquals(r.ruleValue, v));
  267. });
  268. logger.info(
  269. { source, behavior, removed: ctx.rules.length - remaining.length },
  270. 'Removed permission rules',
  271. );
  272. return cloneContextWith(ctx, { rules: remaining });
  273. }
  274. // ---------------------------------------------------------------------------
  275. // Query helpers
  276. // ---------------------------------------------------------------------------
  277. /**
  278. * Check whether a tool has a whole-tool rule (no ruleContent) for a given behavior.
  279. *
  280. * Used in the engine's three-step flow to quickly determine if the entire tool
  281. * is in deny / ask / allow lists.
  282. */
  283. export function hasWholeToolRule(
  284. ctx: ToolPermissionContext,
  285. toolName: string,
  286. behavior: PermissionBehavior,
  287. ): PermissionRule | undefined {
  288. return ctx.rules.find(
  289. (r) =>
  290. r.ruleValue.toolName === toolName && r.ruleBehavior === behavior && !r.ruleValue.ruleContent,
  291. );
  292. }
  293. /**
  294. * Get all content-specific rules for a tool + behavior.
  295. * These are rules WITH ruleContent (not whole-tool rules).
  296. */
  297. export function getContentRulesForTool(
  298. ctx: ToolPermissionContext,
  299. toolName: string,
  300. behavior: PermissionBehavior,
  301. ): readonly PermissionRule[] {
  302. return ctx.rules.filter(
  303. (r) =>
  304. r.ruleValue.toolName === toolName &&
  305. r.ruleBehavior === behavior &&
  306. r.ruleValue.ruleContent !== undefined,
  307. );
  308. }
  309. /**
  310. * Check if the context is in bypass mode.
  311. */
  312. export function isBypassMode(ctx: ToolPermissionContext): boolean {
  313. return ctx.mode === 'bypassPermissions';
  314. }
  315. /**
  316. * Check if a tool is registered as requiring user interaction.
  317. */
  318. export function isInteractiveTool(ctx: ToolPermissionContext, toolName: string): boolean {
  319. return ctx.interactiveTools.has(toolName);
  320. }