{"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../../src/core/permissions/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,EAAE,KAAK,cAAc,EAAe,MAAM,YAAY,CAAC;AAE9D,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE7D,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,iBAAiB;IACjC,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAC3B,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,KAAK,CAAC,EAAE,cAAc,EAAE,CAAC;CACzB;AAED,MAAM,WAAW,cAAc;IAC9B,6EAA6E;IAC7E,cAAc,EAAE,OAAO,CAAC;IACxB,MAAM,EAAE,iBAAiB,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IACjC,sFAAsF;IACtF,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAkCD,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,cAAc,CAsBvF;AAED,0CAA0C;AAC1C,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAiCD,wBAAgB,MAAM,CACrB,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,OAAO,EACf,YAAY,CAAC,EAAE,cAAc,GAC3B;IAAE,QAAQ,EAAE,kBAAkB,CAAC;IAAC,IAAI,EAAE,cAAc,CAAC;IAAC,WAAW,CAAC,EAAE,cAAc,CAAA;CAAE,CAmBtF","sourcesContent":["/**\n * Permission policy engine. Merges user config (<agentDir>/permissions.json)\n * and project config (<cwd>/.phi/permissions.json).\n *\n * Security model:\n * - The project file is read only for TRUSTED projects (a cloned repo must not\n *   be able to relax the user's policy).\n * - Even when trusted, the project can only TIGHTEN the policy: tier decisions\n *   take the strictest of user and project, and project \"allow\" rules are ignored.\n *\n * Default behavior when NO config exists: everything allowed. This preserves\n * the pre-permissions behavior of Phi Code (non-regression requirement).\n */\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { type PermissionTier, tierForTool } from \"./tiers.ts\";\n\nexport type PermissionDecision = \"allow\" | \"deny\" | \"prompt\";\n\nexport interface PermissionRule {\n\ttool: string;\n\tpattern?: string;\n\tdecision: PermissionDecision;\n}\n\nexport interface PermissionsConfig {\n\tread?: PermissionDecision;\n\twrite?: PermissionDecision;\n\texec?: PermissionDecision;\n\trules?: PermissionRule[];\n}\n\nexport interface ResolvedPolicy {\n\t/** True when no config file existed at all (legacy allow-everything mode) */\n\tlegacyAllowAll: boolean;\n\tconfig: PermissionsConfig;\n}\n\nexport interface LoadPolicyOptions {\n\t/** Whether <cwd>/.phi/permissions.json may be read. Defaults to false (untrusted). */\n\tprojectTrusted?: boolean;\n}\n\nlet cached: { key: string; policy: ResolvedPolicy } | undefined;\n\nfunction loadConfigFile(path: string): PermissionsConfig | undefined {\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\treturn JSON.parse(readFileSync(path, \"utf8\").replace(/^\\uFEFF/, \"\")) as PermissionsConfig;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Cache key component that changes whenever the file is created, edited or deleted. */\nfunction fileStamp(path: string): string {\n\ttry {\n\t\tconst st = statSync(path);\n\t\treturn `${st.mtimeMs}:${st.size}`;\n\t} catch {\n\t\treturn \"absent\";\n\t}\n}\n\nconst STRICTNESS: Record<PermissionDecision, number> = { allow: 0, prompt: 1, deny: 2 };\n\nfunction stricter(\n\ta: PermissionDecision | undefined,\n\tb: PermissionDecision | undefined,\n): PermissionDecision | undefined {\n\tif (a === undefined) return b;\n\tif (b === undefined) return a;\n\treturn STRICTNESS[a] >= STRICTNESS[b] ? a : b;\n}\n\nexport function loadPolicy(cwd: string, options: LoadPolicyOptions = {}): ResolvedPolicy {\n\tconst userPath = join(getAgentDir(), \"permissions.json\");\n\tconst projectPath = options.projectTrusted ? join(cwd, \".phi\", \"permissions.json\") : undefined;\n\tconst key = [userPath, fileStamp(userPath), projectPath ?? \"-\", projectPath ? fileStamp(projectPath) : \"-\"].join(\n\t\t\"|\",\n\t);\n\tif (cached?.key === key) return cached.policy;\n\n\tconst user = loadConfigFile(userPath);\n\tconst project = projectPath ? loadConfigFile(projectPath) : undefined;\n\tconst legacyAllowAll = !user && !project;\n\n\tconst config: PermissionsConfig = {\n\t\tread: stricter(user?.read, project?.read),\n\t\twrite: stricter(user?.write, project?.write),\n\t\texec: stricter(user?.exec, project?.exec),\n\t\t// Project rules come first but may only add \"prompt\"/\"deny\": an \"allow\" from a\n\t\t// project file would override the user's own restrictions.\n\t\trules: [...(project?.rules ?? []).filter((rule) => rule.decision !== \"allow\"), ...(user?.rules ?? [])],\n\t};\n\tcached = { key, policy: { legacyAllowAll, config } };\n\treturn cached.policy;\n}\n\n/** Test helper / runtime invalidation. */\nexport function resetPolicyCache(): void {\n\tcached = undefined;\n}\n\nfunction isCommandTool(_toolName: string, params: unknown): boolean {\n\treturn !!params && typeof params === \"object\" && typeof (params as Record<string, unknown>).command === \"string\";\n}\n\n/** Shell operators that chain, substitute or redirect commands. */\nfunction hasShellControlOperators(command: string): boolean {\n\treturn /[;&|`<>\\n\\r]|\\$\\(/.test(command);\n}\n\nfunction globToRegex(glob: string): RegExp {\n\tconst escaped = glob\n\t\t.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\t\t.replace(/\\*/g, \".*\")\n\t\t.replace(/\\?/g, \".\");\n\treturn new RegExp(`^${escaped}$`, \"i\");\n}\n\n/** Extract the string a rule pattern matches against (bash: the command). */\nfunction subjectForTool(_toolName: string, params: unknown): string {\n\tif (params && typeof params === \"object\") {\n\t\tconst p = params as Record<string, unknown>;\n\t\tif (typeof p.command === \"string\") return p.command;\n\t\tif (typeof p.path === \"string\") return p.path;\n\t}\n\ttry {\n\t\treturn JSON.stringify(params) ?? \"\";\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nexport function decide(\n\tpolicy: ResolvedPolicy,\n\ttoolName: string,\n\tparams: unknown,\n\tdeclaredTier?: PermissionTier,\n): { decision: PermissionDecision; tier: PermissionTier; matchedRule?: PermissionRule } {\n\tif (policy.legacyAllowAll) {\n\t\treturn { decision: \"allow\", tier: tierForTool(toolName, declaredTier) };\n\t}\n\n\tconst subject = subjectForTool(toolName, params);\n\tconst chained = isCommandTool(toolName, params) && hasShellControlOperators(subject);\n\tfor (const rule of policy.config.rules ?? []) {\n\t\tif (rule.tool !== toolName && rule.tool !== \"*\") continue;\n\t\tif (rule.pattern && !globToRegex(rule.pattern).test(subject)) continue;\n\t\t// `allow bash \"git *\"` must not approve `git status; rm -rf ~`: an allow\n\t\t// pattern only vouches for a single simple command.\n\t\tif (rule.decision === \"allow\" && rule.pattern && chained) continue;\n\t\treturn { decision: rule.decision, tier: tierForTool(toolName, declaredTier), matchedRule: rule };\n\t}\n\n\tconst tier = tierForTool(toolName, declaredTier);\n\tconst tierDecision = policy.config[tier] ?? \"prompt\";\n\treturn { decision: tierDecision, tier };\n}\n"]}