Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
feat(policy): Windows read-only commands run without a card; YOLO runs ordinary commands
leen.zhoud3f62efce187
diff --git a/packages/brain/src/core/approval-display.ts b/packages/brain/src/core/approval-display.tsindex 236ae9c..1e0534e 100644--- a/packages/brain/src/core/approval-display.ts+++ b/packages/brain/src/core/approval-display.ts@@ -34,8 +34,8 @@ const warnings: Record<string, [string, string]> = {"The operation cannot be fully determined; permission cannot be remembered",],windows_unisolated: [- "Windows 命令没有系统隔离,每次都需审批",- "Windows commands have no system isolation and require approval every time",+ "此命令将在 Windows 上以你的权限运行,没有系统隔离",+ "This command runs on Windows with your permissions and without system isolation",],outside_sandbox_login: ["这个程序要用你自己的登录或配置(如 aws、gh、kubectl、ssh 的凭据),在沙箱里跑不通,所以直接请你批准在沙箱外运行",diff --git a/packages/brain/src/core/approvals.ts b/packages/brain/src/core/approvals.tsindex 2c6dcb5..d3c3d93 100644--- a/packages/brain/src/core/approvals.ts+++ b/packages/brain/src/core/approvals.ts@@ -233,7 +233,7 @@ export class ApprovalService {onAllowed?: () => void,lifecycle?: {requested(approval: Approval): void;- resolved(approval: Approval): void;+ resolved(approval: Approval, by: ResolvedBy): void;resuming?(choice: unknown): void;},consent?: { available: boolean; allow(approval: Approval): void },@@ -767,7 +767,7 @@ export class ApprovalService {const resolvedApproval = this.repo.get(approval.id);if (resolvedApproval) {try {- lifecycle?.resolved(resolvedApproval);+ lifecycle?.resolved(resolvedApproval, by);} catch (error) {reject(error);throw error;diff --git a/packages/brain/src/core/auto-allow.ts b/packages/brain/src/core/auto-allow.tsindex d63bd9b..7b91525 100644--- a/packages/brain/src/core/auto-allow.ts+++ b/packages/brain/src/core/auto-allow.ts@@ -4,6 +4,7 @@ import {EDITOR_SESSION_REASON,EDITOR_TERMINAL_READONLY_REASON,type PolicyResult,+ WINDOWS_READ_ONLY,} from "@pibot/policy";import type { Grant } from "@pibot/protocol-base";import { BotsRepo } from "@pibot/storage";@@ -21,6 +22,7 @@ import { toolPermissionCategory } from "./tool-category.ts";*/const AUTO_ALLOW_REASONS = new Set(["readonly_command",+ WINDOWS_READ_ONLY,"sandboxed_command",EDITOR_TERMINAL_READONLY_REASON,EDITOR_SESSION_REASON,diff --git a/packages/brain/src/runtime/external-agents/delegated-authorization.ts b/packages/brain/src/runtime/external-agents/delegated-authorization.tsindex ba531fe..2c4c33f 100644--- a/packages/brain/src/runtime/external-agents/delegated-authorization.ts+++ b/packages/brain/src/runtime/external-agents/delegated-authorization.ts@@ -1,5 +1,12 @@import type { LocalToolCall } from "@pibot/agent";-import { applyYolo, explainPolicyResult, type PolicyResult } from "@pibot/policy";+import {+ applyWindowsCommandConsent,+ applyYolo,+ explainPolicyResult,+ type PolicyResult,+ WINDOWS_READ_ONLY,+ WINDOWS_REQUIRES_APPROVAL,+} from "@pibot/policy";import type { ApprovalFact } from "@pibot/protocol-base";import { SettingsRepo } from "@pibot/storage";import { auditAutoAllow } from "../../core/auto-allow.ts";@@ -56,15 +63,27 @@ export async function authorizeDelegatedAction(const prepared = await prepareTool(local, { ...context, signal }, call, signal);if (!options.unisolated || call.tool !== "run_command" || prepared.result.decision === "deny")return prepared.result;- const bounded = explainPolicyResult(- { ...prepared.result, decision: "ask", reason: "windows_unisolated", canRemember: false },- "boundary",- "windows_unisolated",- );- return applyYolo(- bounded,+ if (prepared.result.reason === WINDOWS_READ_ONLY) {+ // The ACP agent owns the shell and its startup state. The native PowerShell proof+ // does not describe that process.+ return explainPolicyResult(+ { ...prepared.result, decision: "ask", reason: WINDOWS_REQUIRES_APPROVAL },+ "boundary",+ WINDOWS_REQUIRES_APPROVAL,+ );+ }+ const consent =runYolo(local, context) &&- new SettingsRepo(local.deps.db).get().yoloUnisolatedCommands === true,+ new SettingsRepo(local.deps.db).get().yoloUnisolatedCommands === true;+ if (local.deps.platform === "win32")+ return applyWindowsCommandConsent(prepared.result, consent);+ return applyYolo(+ explainPolicyResult(+ { ...prepared.result, decision: "ask", reason: "windows_unisolated", canRemember: false },+ "boundary",+ "windows_unisolated",+ ),+ consent,{ unisolatedCommands: true },);};@@ -74,6 +93,7 @@ export async function authorizeDelegatedAction(auditAutoAllow(local, context, call, result);return { allowed: true, reason: result.reason };}+ let answeredByYolo = false;const status = await local.approvals.request(cardScope(context, options.cardContext, signal),call,@@ -81,10 +101,23 @@ export async function authorizeDelegatedAction({ available: !options.unisolated },judge,undefined,- undefined,+ {+ requested() {},+ resolved: (_approval, by) => {+ answeredByYolo = by === "yolo";+ },+ },undefined,{ title: options.title, facts: requestedFacts(call, result) },);+ if (+ status === "allowed" &&+ options.unisolated &&+ local.deps.platform === "win32" &&+ answeredByYolo &&+ (await judge()).reason !== "yolo"+ )+ return { allowed: false, reason: "changed" };return { allowed: status === "allowed", reason: status === "allowed" ? "approved" : status };}diff --git a/packages/brain/src/runtime/tools/local-prepare.ts b/packages/brain/src/runtime/tools/local-prepare.tsindex 351103d..3618e35 100644--- a/packages/brain/src/runtime/tools/local-prepare.ts+++ b/packages/brain/src/runtime/tools/local-prepare.ts@@ -799,12 +799,9 @@ async function prepareToolCurrent(}// Never weaken an existing hard deny (e.g. a never-level or invalid workspace).if (result.decision !== "deny") {- const automatic =- docker &&- result.risk !== "danger" &&- local.deps.platform === "win32" &&- (yolo || settings.levels.run_command === "always");- result.decision = reason ? "deny" : automatic ? "allow" : "ask";+ // Explicit Docker selection does not make an opaque native Windows command safe+ // for automatic release. Keep the Docker consent and its dedicated dispatch checks.+ result.decision = reason ? "deny" : "ask";result.reason = reason ?? "docker_access";recordPolicyStep(result, "boundary", reason ?? "docker_access");result.canRemember = false;diff --git a/packages/brain/src/runtime/tools/local-run/local-run-authorization.ts b/packages/brain/src/runtime/tools/local-run/local-run-authorization.tsindex 93808a9..f60fba9 100644--- a/packages/brain/src/runtime/tools/local-run/local-run-authorization.ts+++ b/packages/brain/src/runtime/tools/local-run/local-run-authorization.ts@@ -2,6 +2,7 @@ import type { LocalToolCall } from "@pibot/agent";import { ExecError, type ExecutionTarget, linuxIsolationRemedy } from "@pibot/execution";import {applyEditorTerminal,+ applyWindowsCommandConsent,applyYolo,browserSecretPolicy,EDITOR_TERMINAL_UNISOLATED,@@ -12,6 +13,8 @@ import {type PolicyResult,REVEAL_CONFIRMATION_REASON,recordPolicyStep,+ WINDOWS_ORDINARY_COMMAND,+ WINDOWS_READ_ONLY,} from "@pibot/policy";import { BrowserNetworkConsentText, RpcError } from "@pibot/protocol-base";import { BotsRepo, SettingsRepo } from "@pibot/storage";@@ -79,26 +82,21 @@ export function applyExplicitUnisolatedTarget((reason !== "windows_unisolated" && reason !== EDITOR_TERMINAL_UNISOLATED))return;+ const consent =+ runYolo(this.local, this.context) &&+ new SettingsRepo(this.local.deps.db).get().yoloUnisolatedCommands === true;const bounded =reason === EDITOR_TERMINAL_UNISOLATED- ? applyEditorTerminal(prepared.result, {- ...editorTerminalScope.call(this, prepared),- sessionShapes: this.local.approvals.editorSessionShapes(this.context),- })- : explainPolicyResult(- { ...prepared.result, decision: "ask", reason, canRemember: false },- "boundary",- reason,- );- prepared.result = browserSecretPolicy(- applyYolo(- bounded,- runYolo(this.local, this.context) &&- new SettingsRepo(this.local.deps.db).get().yoloUnisolatedCommands === true,- { unisolatedCommands: true },- ),- prepared.browserSecretUses?.length ?? 0,- );+ ? applyYolo(+ applyEditorTerminal(prepared.result, {+ ...editorTerminalScope.call(this, prepared),+ sessionShapes: this.local.approvals.editorSessionShapes(this.context),+ }),+ consent,+ { unisolatedCommands: true },+ )+ : applyWindowsCommandConsent(prepared.result, consent);+ prepared.result = browserSecretPolicy(bounded, prepared.browserSecretUses?.length ?? 0);}export async function authorizeStep(@@ -335,7 +333,11 @@ export async function authorizeStep(// An explicitly unisolated execution target is an ask; YOLO approves it only when the// user has turned on "YOLO auto-approves commands (no isolation)".applyExplicitUnisolatedTarget.call(this, prepared, unisolatedReason);- if (allowedByYolo(prepared.result)) state.unisolatedApproved = true;+ if (+ allowedByYolo(prepared.result) ||+ (prepared.result.decision === "allow" && prepared.result.reason === WINDOWS_READ_ONLY)+ )+ state.unisolatedApproved = true;}// Isolation inspection may yield while the user enables YOLO. Re-check immediately before// creating a card, otherwise the newly created card would miss releasePending().@@ -450,6 +452,7 @@ export async function authorizeStep(const approvedFingerprint = fingerprint(original);let receipt: SearchConsentReceipt | undefined;let folderAdded = false;+ let windowsYoloCard = false;const lifecycle = this.local.unattended?.approvalLifecycle(this.context,call,@@ -521,7 +524,13 @@ export async function authorizeStep(lifecycle?.requested(approval);linkSandboxApproval(this.local, this.context, original, approval);},- resolved: (approval) => lifecycle?.resolved(approval),+ resolved: (approval, by) => {+ windowsYoloCard =+ by === "yolo" &&+ isolation.reason === "windows_unisolated" &&+ original.result.explanation.some((step) => step.code === WINDOWS_ORDINARY_COMMAND);+ lifecycle?.resolved(approval);+ },},{available:@@ -587,6 +596,7 @@ export async function authorizeStep(prepared.result = applyYolo(prepared.result, runYolo(this.local, this.context));if (prepared.result.decision === "deny" ||+ (windowsYoloCard && !allowedByYolo(prepared.result)) ||!approvedUnchanged(prepared, original, approvedFingerprint))return refuse("changed", blockedReason("changed"));diff --git a/packages/brain/src/runtime/tools/local-run/local-run-execution.ts b/packages/brain/src/runtime/tools/local-run/local-run-execution.tsindex 2ec87c8..74d5ec9 100644--- a/packages/brain/src/runtime/tools/local-run/local-run-execution.ts+++ b/packages/brain/src/runtime/tools/local-run/local-run-execution.ts@@ -6,8 +6,11 @@ import {explainPolicyResult,REVEAL_CONFIRMATION_REASON,secretWriteOutDenied,+ WINDOWS_ORDINARY_COMMAND,+ WINDOWS_READ_ONLY,} from "@pibot/policy";import { officeRenderOutputPath } from "@pibot/protocol-base";+import { SettingsRepo } from "@pibot/storage";import { auditAutoAllow, isAutoAllowed } from "../../../core/auto-allow.ts";import type { PreparedTool } from "../../../core/local-types.ts";import { allowedByYolo, runYolo } from "../../../core/yolo.ts";@@ -146,7 +149,9 @@ export async function executeStep(}if (fingerprint(checked) !== state.fingerprint ||- (allowedByYolo(state.prepared.result) && checked.result.decision !== "allow")+ (allowedByYolo(state.prepared.result) && checked.result.decision !== "allow") ||+ (state.prepared.result.reason === WINDOWS_READ_ONLY &&+ checked.result.reason !== WINDOWS_READ_ONLY)) {state.auditFacts = {...state.auditFacts,@@ -380,7 +385,10 @@ export function assertDispatchStep(this: LocalRunOperations, prepared: PreparedT!this.local.execution.allows(this.context, prepared.call.tool) ||authorizationSnapshot(this.local, this.context.botId, this.context) !==prepared.authorization ||- ((state.yolo || allowedByYolo(prepared.result)) && !runYolo(this.local, this.context))+ ((state.yolo || allowedByYolo(prepared.result)) && !runYolo(this.local, this.context)) ||+ (allowedByYolo(prepared.result) &&+ prepared.result.explanation.some((step) => step.code === WINDOWS_ORDINARY_COMMAND) &&+ new SettingsRepo(this.local.deps.db).get().yoloUnisolatedCommands !== true))throw new ToolAuthorizationError("Tool authorization changed");if (diff --git a/packages/client-core/src/approvals/explanation.ts b/packages/client-core/src/approvals/explanation.tsindex 6f049c8..3ef41a4 100644--- a/packages/client-core/src/approvals/explanation.ts+++ b/packages/client-core/src/approvals/explanation.ts@@ -79,6 +79,8 @@ const reasonKeys: Record<string, TranslationKey> = {privilege_escalation_denied: "policy.reason.privilege_escalation_denied",incomplete_analysis: "policy.reason.incomplete_analysis",windows_requires_approval: "policy.reason.windows_requires_approval",+ windows_ordinary_command: "policy.reason.windows_ordinary_command",+ windows_read_only: "policy.reason.windows_read_only",windows_unisolated: "policy.reason.windows_unisolated",outside_sandbox_once: "policy.reason.outside_sandbox_once",outside_sandbox_strict: "policy.reason.outside_sandbox_strict",diff --git a/packages/i18n/src/sections/permissions.ts b/packages/i18n/src/sections/permissions.tsindex cf267a6..6134e84 100644--- a/packages/i18n/src/sections/permissions.ts+++ b/packages/i18n/src/sections/permissions.ts@@ -240,7 +240,7 @@ export const permissionsZh = {"facts.value.topic_writable_scope":"选择「以后允许」会覆盖本话题当前的所有可写文件夹,不适用于其他话题;移除文件夹后不再覆盖。","facts.value.incomplete_analysis": "无法完全确定会做什么,不能记住授权",- "facts.value.windows_unisolated": "Windows 命令没有系统隔离,每次都需审批",+ "facts.value.windows_unisolated": "此命令将在 Windows 上以你的权限运行,没有系统隔离","facts.value.local_service": "只放行这一个端口或套接字;其他端口和外网仍被沙箱拦。","facts.value.outside_sandbox_login":"这个程序要用你自己的登录或配置(如 aws、gh、kubectl、ssh 的凭据),在沙箱里跑不通,所以直接请你批准在沙箱外运行",@@ -728,7 +728,7 @@ export const permissionsEn: { [K in keyof typeof permissionsZh]: string } = {"facts.value.incomplete_analysis":"The operation cannot be fully determined; permission cannot be remembered","facts.value.windows_unisolated":- "Windows commands have no system isolation and require approval every time",+ "This command runs on Windows with your permissions and without system isolation","facts.value.local_service":"Only this port or socket is allowed; other ports and the internet remain blocked by the sandbox.","facts.value.outside_sandbox_login":diff --git a/packages/i18n/src/sections/policy-explanation.ts b/packages/i18n/src/sections/policy-explanation.tsindex 340c0cb..793f311 100644--- a/packages/i18n/src/sections/policy-explanation.ts+++ b/packages/i18n/src/sections/policy-explanation.ts@@ -112,6 +112,9 @@ export const policyExplanationZh = {"policy.reason.privilege_escalation_denied": "不能提升系统权限","policy.reason.incomplete_analysis": "命令无法完整分析,需要逐次确认","policy.reason.windows_requires_approval": "当前 Windows 命令需要逐次确认",+ "policy.reason.windows_ordinary_command":+ "普通 Windows 命令仍需确认,除非已开启 YOLO 并同意无隔离执行",+ "policy.reason.windows_read_only": "已检查 Windows 命令的只读操作和读取范围","policy.reason.command_home_unavailable": "无法确认目标终端的主目录,请使用绝对路径","policy.reason.windows_unisolated": "命令没有系统隔离,需要单独确认","policy.reason.outside_sandbox_once": "这条命令刚被沙箱拦截,要在沙箱外运行一次,需要你当场确认",@@ -420,6 +423,10 @@ export const policyExplanationEn: Record<keyof typeof policyExplanationZh, strin"policy.reason.privilege_escalation_denied": "System privilege escalation is prohibited","policy.reason.incomplete_analysis": "The command cannot be fully analyzed and needs approval","policy.reason.windows_requires_approval": "This Windows command needs approval",+ "policy.reason.windows_ordinary_command":+ "This Windows command needs approval unless YOLO and consent to unisolated commands are both enabled",+ "policy.reason.windows_read_only":+ "Windows command checked for read-only operations and file access","policy.reason.command_home_unavailable":"Target terminal home is unverified; use an absolute path","policy.reason.windows_unisolated": "The command is not isolated and needs separate consent",diff --git a/packages/policy/src/commands/powershell-directories.ts b/packages/policy/src/commands/powershell-directories.tsindex 77daf42..1aca318 100644--- a/packages/policy/src/commands/powershell-directories.ts+++ b/packages/policy/src/commands/powershell-directories.ts@@ -1,4 +1,7 @@import { win32 } from "node:path";+import { powershellSegments } from "./powershell-segments.ts";++type Piece = ReturnType<typeof powershellSegments>["pieces"][number];/*** Cmdlets that only read, format or forward objects already in the pipeline. Exempting them keeps@@ -32,50 +35,6 @@ const dataHead = (token: string) => /^'(?:[^']|'')*'$/.test(token) || /^"[^"$`]**/const argumentRuns = /[()@$[\]`{]/;-/** `afterPipeOrCall`: the token sits right after `|` or `&`, where PowerShell expects a program. */-type Piece = { tokens: string[]; afterPipeOrCall: boolean };--/** Split on unquoted separators while remembering which one, so call operators stay commands. */-function segments(command: string) {- const pieces: Piece[] = [{ tokens: [], afterPipeOrCall: false }];- let word = "";- let quote = "";- const flush = () => {- if (word) pieces.at(-1)?.tokens.push(word);- word = "";- };- for (let i = 0; i < command.length && i < 32_768; i++) {- const char = command[i] ?? "";- if (quote) {- word += char;- if (char === quote) {- if (command[i + 1] === quote) word += command[++i];- else quote = "";- } else if (char === "`" && quote === '"' && command[i + 1]) word += command[++i];- continue;- }- if (char === "'" || char === '"') {- quote = char;- word += char;- } else if (char === ">") {- // `echo hi>notes.txt` attaches the redirect to the word; split it so the target is a path.- const prefix = /(?:\d+|\*)$/.exec(word)?.[0] ?? "";- word = word.slice(0, word.length - prefix.length);- flush();- pieces.at(-1)?.tokens.push(prefix + (command[i + 1] === ">" ? ">>" : ">"));- if (command[i + 1] === ">") i += 1;- } else if (/[;\r\n|&]/.test(char)) {- flush();- // `&` is the call operator and `|` puts the next token in command position; only `;` and a- // newline start a statement whose head may be a plain value.- pieces.push({ tokens: [], afterPipeOrCall: char === "&" || char === "|" });- } else if (/\s/.test(char)) flush();- else word += char;- }- flush();- return { pieces, unclosed: Boolean(quote), tooLong: command.length > 32_768 };-}-const literal = (raw: string | undefined) => {if (!raw) return undefined;if (/^'(?:[^']|'')*'$/.test(raw)) return raw.slice(1, -1).replaceAll("''", "'");@@ -196,7 +155,7 @@ export function powershellDirectoryWrites(command: string, cwd: string) {let unknown = false;let changed = false;let unknownWrite = false;- const parsed = segments(command);+ const parsed = powershellSegments(command);if (parsed.unclosed || parsed.tooLong) unknown = true;const tainted = parsed.pieces.some((piece) => !exempt(piece));for (const piece of parsed.pieces) {@@ -242,6 +201,7 @@ export function powershellDirectoryWrites(command: string, cwd: string) {if (changed) unknownWrite = true;});for (const operand of operands) {+ if (redirect >= 0 && /^\$null$/i.test(operand)) continue;const value = literal(operand);// A provider target (`HKCU:`, `Env:`, `Function:` …) is outside every folder model, so it is// an unknown location even without a directory switch.diff --git a/packages/policy/src/commands/powershell-segments.ts b/packages/policy/src/commands/powershell-segments.tsnew file mode 100644index 0000000..cf0c549--- /dev/null+++ b/packages/policy/src/commands/powershell-segments.ts@@ -0,0 +1,44 @@+// Share the literal token boundaries between Windows risk hints and approval checks.+/** `afterPipeOrCall`: the token sits right after `|` or `&`, where PowerShell expects a program. */+type Piece = { tokens: string[]; afterPipeOrCall: boolean; separator: string };++/** Split on unquoted separators while remembering which one, so call operators stay commands. */+export function powershellSegments(command: string) {+ const pieces: Piece[] = [{ tokens: [], afterPipeOrCall: false, separator: "" }];+ let word = "";+ let quote = "";+ const flush = () => {+ if (word) pieces.at(-1)?.tokens.push(word);+ word = "";+ };+ for (let i = 0; i < command.length && i < 32_768; i++) {+ const char = command[i] ?? "";+ if (quote) {+ word += char;+ if (char === quote) {+ if (command[i + 1] === quote) word += command[++i];+ else quote = "";+ } else if (char === "`" && quote === '"' && command[i + 1]) word += command[++i];+ continue;+ }+ if (char === "'" || char === '"') {+ quote = char;+ word += char;+ } else if (char === ">") {+ // `echo hi>notes.txt` attaches the redirect to the word; split it so the target is a path.+ const prefix = /(?:\d+|\*)$/.exec(word)?.[0] ?? "";+ word = word.slice(0, word.length - prefix.length);+ flush();+ pieces.at(-1)?.tokens.push(prefix + (command[i + 1] === ">" ? ">>" : ">"));+ if (command[i + 1] === ">") i += 1;+ } else if (/[;\r\n|&]/.test(char)) {+ flush();+ // `&` is the call operator and `|` puts the next token in command position; only `;` and a+ // newline start a statement whose head may be a plain value.+ pieces.push({ tokens: [], afterPipeOrCall: char === "&" || char === "|", separator: char });+ } else if (/\s/.test(char)) flush();+ else word += char;+ }+ flush();+ return { pieces, unclosed: Boolean(quote), tooLong: command.length > 32_768 };+}diff --git a/packages/policy/src/commands/windows-approval-shape.ts b/packages/policy/src/commands/windows-approval-shape.tsnew file mode 100644index 0000000..7765d3b--- /dev/null+++ b/packages/policy/src/commands/windows-approval-shape.ts@@ -0,0 +1,175 @@+// Prove the small set of Windows command shapes that need no consent to run without isolation.+import { isOutputTarget } from "./output-targets.ts";+import { powershellSegments } from "./powershell-segments.ts";++type Read = {+ path: string;+ category: "read_file" | "list_dir";+ enumerates?: boolean;+ recurse?: boolean;+ readEntries?: boolean;+};++const child = /^(?:get-childitem|gci|ls|dir)$/;+const content = /^(?:get-content|gc|cat|type)$/;+const item = /^(?:get-item|resolve-path|test-path)$/;+const location = /^(?:get-location|pwd)$/;+const plain = /^[\p{L}\p{M}\p{N}_.+:/\\-]+$/u;+const quoted = /^(?:'([\p{L}\p{M}\p{N}_.+:/\\ -]+)'|"([\p{L}\p{M}\p{N}_.+:/\\ -]+)")$/u;++export function windowsLiteralToken(token: string) {+ if (plain.test(token)) return token;+ const match = quoted.exec(token);+ return match?.[1] ?? match?.[2];+}++export function windowsLiteralPath(value: string) {+ const local = value.replace(/^[a-z]:[\\/]/i, "");+ return (+ !/^[\\/]/.test(value) &&+ !/[:*?~[\]]/.test(local) &&+ local+ .split(/[\\/]/)+ .every(+ (part) =>+ part === "." ||+ (part !== ".." &&+ !/[. ]$/.test(part) &&+ !/^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\.|$)/i.test(part)),+ )+ );+}++function pathRead(program: string, args: string[]): Read | undefined {+ const category = child.test(program) || item.test(program) ? "list_dir" : "read_file";+ const values = [...args];+ const enumerates = child.test(program);+ const recurse = enumerates && values[0]?.toLowerCase() === "-recurse";+ if (recurse) values.shift();+ if (/^-(?:path|literalpath)$/i.test(values[0] ?? "")) {+ values.shift();+ if (!values.length) return undefined;+ }+ if (!values.length && enumerates) return { path: ".", category, enumerates, recurse };+ if (values.length !== 1) return undefined;+ const token = values[0] ?? "";+ const path = windowsLiteralToken(token);+ if (!path || token.startsWith("-") || !windowsLiteralPath(path)) return undefined;+ return { path, category, enumerates, recurse };+}++function readSegment(program: string, args: string[], piped: boolean): Read[] | undefined {+ if (piped) {+ if (/^(?:measure-object|measure)$/.test(program) && !args.length) return [];+ if (+ program === "select-string" &&+ args.length === 1 &&+ windowsLiteralToken(args[0] ?? "") &&+ !args[0]?.startsWith("-")+ )+ return [];+ return undefined;+ }+ if (child.test(program) || content.test(program) || item.test(program)) {+ const read = pathRead(program, args);+ return read ? [read] : undefined;+ }+ if (+ (location.test(program) || /^(?:get-date|measure-object|measure)$/.test(program)) &&+ !args.length+ )+ return [];+ if (+ /^(?:echo|write-output)$/.test(program) &&+ args.every((arg) => windowsLiteralToken(arg) && !arg.startsWith("-"))+ )+ return [];+ if (+ program === "get-command" &&+ args.length === 2 &&+ args[0]?.toLowerCase() === "-listimported" &&+ /^[a-z][a-z0-9-]*$/i.test(args[1] ?? "")+ )+ return [];+ if (+ program === "select-string" &&+ args.length === 2 &&+ windowsLiteralToken(args[0] ?? "") &&+ !args[0]?.startsWith("-")+ ) {+ const read = pathRead(program, args.slice(1));+ return read ? [read] : undefined;+ }+ return undefined;+}++function cmdRead(args: string[]): Read[] | undefined {+ // /d suppresses cmd's inherited AutoRun. Restrict cmd to its own literal built-ins.+ const [disableAutoRun, execute, ...body] = args;+ if (disableAutoRun?.toLowerCase() !== "/d" || execute?.toLowerCase() !== "/c") return undefined;+ const quotedBody =+ body.length === 1 ? /^"([a-z0-9_.:+/\\ -]+) > ([a-z]+)"$/i.exec(body[0] ?? "") : undefined;+ const command =+ quotedBody && isOutputTarget(quotedBody[2] ?? "", "win32")+ ? (quotedBody[1] ?? "").trim().split(/ +/)+ : body;+ const [name, ...operands] = command;+ if (!operands.every((arg) => /^[a-z0-9_.:+/\\-]+$/i.test(arg))) return undefined;+ const program = name?.toLowerCase();+ if (program === "echo" && operands.every((arg) => !/[/\\:]/.test(arg))) return [];+ if (program !== "dir" && program !== "type") return undefined;+ if (operands.some((arg) => /^[/-]/.test(arg))) return undefined;+ const read = pathRead(program, operands);+ return read ? [read] : undefined;+}++function withoutNullSink(tokens: string[]) {+ if (tokens.length >= 3 && tokens.at(-2) === ">" && /^\$null$/i.test(tokens.at(-1) ?? ""))+ return tokens.slice(0, -2);+ return tokens;+}++export function windowsReadShape(command: string): Read[] | undefined {+ // PowerShell recognizes smart quotes as delimiters. Treat expansion/call syntax and comments+ // as unknown, including line continuations and cmd expansion, before using the shared lexer.+ if (+ /[\u2018-\u201f\x60#%&<^(){}@!*?[\],]|[/\\]{2}|[^\S \t\r\n]|\p{Cc}/u.test(+ command.replaceAll(/[\t\r\n]/g, " "),+ )+ )+ return undefined;+ const parsed = powershellSegments(command);+ if (parsed.unclosed || parsed.tooLong || parsed.pieces.length > 16) return undefined;+ const reads: Read[] = [];+ let previousRead = false;+ let pipelineSource: Read | undefined;+ let previousProgram = "";+ for (const { tokens, separator } of parsed.pieces) {+ if (!tokens.length) {+ if (separator === "|") return undefined;+ previousRead = false;+ continue;+ }+ const program = tokens[0]?.toLowerCase() ?? "";+ const cmd = program === "cmd.exe" || program === "cmd";+ const shape = withoutNullSink(tokens);+ const args = shape.slice(1);+ const piped = separator === "|";+ if (piped && (!previousRead || cmd)) return undefined;+ const found = cmd ? cmdRead(args) : readSegment(program, args, piped);+ if (!found) return undefined;+ if (piped && program === "select-string") {+ if (pipelineSource?.enumerates) pipelineSource.readEntries = true;+ else if (+ pipelineSource?.category !== "read_file" &&+ !/^(?:echo|write-output)$/.test(previousProgram)+ )+ return undefined;+ }+ pipelineSource = found.at(-1);+ previousProgram = program;+ reads.push(...found);+ previousRead = true;+ }+ return previousRead || reads.length ? reads : undefined;+}diff --git a/packages/policy/src/core/command-path-risk.ts b/packages/policy/src/core/command-path-risk.tsindex 0395165..c799ccc 100644--- a/packages/policy/src/core/command-path-risk.ts+++ b/packages/policy/src/core/command-path-risk.ts@@ -1,4 +1,5 @@import { canonicalPath, containsPath, pathApi } from "../paths/paths.ts";+import { windowsProtectedPathNames } from "../paths/protected-paths.ts";import type { EvaluationInput, PathContext, Platform } from "./types.ts";export interface CommandPathScope {@@ -65,3 +66,15 @@ export async function verifiedCommandPaths(}return verified;}++export function windowsProtectedCommandPath(path: string, roots: readonly string[]) {+ return (+ roots.some((root) => containsPath(root, path, "win32")) ||+ windowsProtectedPathNames().some((name) =>+ `\\${path.replaceAll("/", "\\").toLowerCase()}\\`.includes(+ `\\${name.replaceAll("/", "\\").toLowerCase()}\\`,+ ),+ ) ||+ /(?:^|[\\/])\.git(?:[\\/]|$)/i.test(path)+ );+}diff --git a/packages/policy/src/core/confirmation-reasons.ts b/packages/policy/src/core/confirmation-reasons.tsindex 1bab0bc..d4b01f8 100644--- a/packages/policy/src/core/confirmation-reasons.ts+++ b/packages/policy/src/core/confirmation-reasons.ts@@ -7,3 +7,7 @@ export const OUTSIDE_WRITE_REASON = "outside_workplace_write";* per target and task; never remembered, preauthorized or answered by YOLO.*/export const PRIVATE_NETWORK_REASON = "private_network_confirmation";++export const WINDOWS_READ_ONLY = "windows_read_only";+export const WINDOWS_ORDINARY_COMMAND = "windows_ordinary_command";+export const WINDOWS_REQUIRES_APPROVAL = "windows_requires_approval";diff --git a/packages/policy/src/core/connection-confirmation.ts b/packages/policy/src/core/connection-confirmation.tsindex 6c1d45a..5e1bb71 100644--- a/packages/policy/src/core/connection-confirmation.ts+++ b/packages/policy/src/core/connection-confirmation.ts@@ -5,7 +5,11 @@ import {type ConnectorTool,connectionConfirmation,} from "@pibot/protocol-base";-import { PRIVATE_NETWORK_REASON } from "./confirmation-reasons.ts";+import {+ PRIVATE_NETWORK_REASON,+ WINDOWS_ORDINARY_COMMAND,+ WINDOWS_REQUIRES_APPROVAL,+} from "./confirmation-reasons.ts";import { GIT_CONFIGURATION_CONFIRMATION_REASON } from "./git-configuration-policy.ts";import { GIT_ENTRY_CONFIRMATION_REASON } from "./git-entry-policy.ts";import { GIT_HOOK_CONFIRMATION_REASON } from "./git-hook-policy.ts";@@ -48,7 +52,8 @@ export function mustAskNow((result.risk === "danger" ||result.reason === "browser_sensitive_confirmation" ||result.reason === "browser_secret_confirmation" ||- result.reason === "windows_requires_approval" ||+ result.reason === WINDOWS_REQUIRES_APPROVAL ||+ result.reason === WINDOWS_ORDINARY_COMMAND ||result.reason === "windows_unisolated" ||result.reason === "command_network_confirmation" ||result.reason === "command_install_confirmation" ||diff --git a/packages/policy/src/core/finish-shared.ts b/packages/policy/src/core/finish-shared.tsindex 3799ed7..e6454b0 100644--- a/packages/policy/src/core/finish-shared.ts+++ b/packages/policy/src/core/finish-shared.ts@@ -11,6 +11,7 @@ import {GIT_HOOK_CONFIRMATION_REASON,GIT_HOOKS_PATH_CONFIRMATION_REASON,OUTSIDE_WRITE_REASON,+ WINDOWS_READ_ONLY,} from "./confirmation-reasons.ts";import { deny } from "./deny.ts";import type { PolicyTrace } from "./explain.ts";@@ -329,6 +330,14 @@ export function finishShared(}const commandConsent = commandConfirmation(input, result);if (commandConsent) return confirmCommand(result, commandConsent, trace);+ if (+ result.reason === WINDOWS_READ_ONLY &&+ category === "run_command" &&+ options.platform === "win32"+ ) {+ result.decision = "allow";+ return trace.result(result, "boundary");+ }if (incomplete) {if (options.platform !== "win32") {result.facts.push({ kind: "warning", value: "incomplete_analysis" });diff --git a/packages/policy/src/core/request-facts.ts b/packages/policy/src/core/request-facts.tsindex b2e9391..90227bf 100644--- a/packages/policy/src/core/request-facts.ts+++ b/packages/policy/src/core/request-facts.ts@@ -18,12 +18,14 @@ import { isAiConfigPath } from "../paths/ai-config-paths.ts";import { canonicalPath, containsPath, expandHome, pathApi, resolvePath } from "../paths/paths.ts";import { privateNetworkOrigin } from "../targets/private-network.ts";import { website } from "../targets/web.ts";+import { commandPathScope, isWritableCommandPath } from "./command-path-risk.ts";import {- commandPathScope,- isWritableCommandPath,- verifiedCommandPaths,-} from "./command-path-risk.ts";-import type { PolicyTrace } from "./explain.ts";+ WINDOWS_ORDINARY_COMMAND,+ WINDOWS_READ_ONLY,+ WINDOWS_REQUIRES_APPROVAL,+} from "./confirmation-reasons.ts";+import { createPolicyTrace, type PolicyTrace } from "./explain.ts";+import { finish } from "./finish.ts";import {prepareGitConfigurationFacts,selectedGitConfiguration,@@ -37,7 +39,8 @@ import { prepareHostSshPolicy } from "./host-ssh-policy.ts";import { judgeOutsideWrites } from "./outside-write.ts";import { scriptPreauthScope } from "./script-consent.ts";import type { CommandAnalysis, EvaluationInput, PathContext, PolicyResult } from "./types.ts";-import { scanWindowsCommand } from "./windows-command-scan.ts";+import { proveWindowsReadOnly } from "./windows-command-approval.ts";+import { prepareWindowsCommandScan } from "./windows-command-scan.ts";export interface RequestFacts {gitHook?: true;@@ -203,18 +206,20 @@ export async function prepareRequestFacts(}context.signal.throwIfAborted();const scope = commandPathScope(input);- const scan = scanWindowsCommand(- request.command,- extra,- scope,- await verifiedCommandPaths(request.command, scope, context),+ const cwd =request.cwd ??- input.cwd ??- (input.workplace.currentId === "home"- ? input.workplace.home- : input.workplace.folders.find((folder) => folder.id === input.workplace.currentId)- ?.path),- );+ input.cwd ??+ (input.workplace.currentId === "home"+ ? input.workplace.home+ : input.workplace.folders.find((folder) => folder.id === input.workplace.currentId)?.path);+ const protectedRoots = [...(extra ?? []), ...(input.sensitiveReadRoots ?? [])];+ const scan = await prepareWindowsCommandScan(request.command, {+ protectedRoots,+ scope,+ cwd,+ writePaths: request.writePaths,+ context: runner && !extra?.length ? undefined : context,+ });result.command = request.command;result.facts.push({ kind: "warning", value: "windows_unisolated" });if (scan.fragments.length) {@@ -233,8 +238,39 @@ export async function prepareRequestFacts(result: deny(result, "runner_command_protection_unavailable", trace),incomplete: true,};- result.reason = "windows_requires_approval";- trace.step("boundary", "windows_requires_approval", "ask");+ const readOnly = scan.fragments.length+ ? undefined+ : await proveWindowsReadOnly(+ { ...input, request },+ context,+ cwd,+ protectedRoots,+ async (file) => {+ const fileTrace = createPolicyTrace();+ const fileInput = { ...input, request: file };+ const facts = await prepareRequestFacts(fileInput, { ...context }, analyze, fileTrace);+ finish(+ fileInput,+ { platform: "win32", userHome: context.protectionHome ?? context.home },+ facts,+ fileTrace,+ );+ return facts;+ },+ );+ if (readOnly) {+ result.reason = WINDOWS_READ_ONLY;+ result.facts.push(...readOnly);+ return { result, incomplete: false };+ }+ const ordinary =+ !scan.needsConfirmation &&+ !scan.fragments.length &&+ !request.stdin &&+ !request.outsideSandbox &&+ !input.boundary?.location?.target.startsWith("acp:");+ result.reason = ordinary ? WINDOWS_ORDINARY_COMMAND : WINDOWS_REQUIRES_APPROVAL;+ if (ordinary) result.facts.push(...scan.facts);return { result, incomplete: true };}if (!("path" in request) && request.category !== "run_command")diff --git a/packages/policy/src/core/types.ts b/packages/policy/src/core/types.tsindex 7d0011f..2afcd27 100644--- a/packages/policy/src/core/types.ts+++ b/packages/policy/src/core/types.ts@@ -159,6 +159,8 @@ export interface FileSystem {* directory cannot be listed or holds more. Local only, like readScript.*/listNames?(directory: string, signal: AbortSignal): Promise<readonly string[] | undefined>;+ /** Bounded local Windows traversal; unsupported or non-regular entries keep the card. */+ windowsReadEntries?: typeof import("../paths/windows-read-tree.ts").windowsReadEntries;}export interface PathContext {platform: Platform;diff --git a/packages/policy/src/core/windows-command-approval.ts b/packages/policy/src/core/windows-command-approval.tsnew file mode 100644index 0000000..2530d03--- /dev/null+++ b/packages/policy/src/core/windows-command-approval.ts@@ -0,0 +1,138 @@+// Keep implicit Windows approval tied to the same paths and permissions as file tools.+import { win32 } from "node:path";+import type { ApprovalFact } from "@pibot/protocol-base";+import { windowsLiteralPath, windowsReadShape } from "../commands/windows-approval-shape.ts";+import { canonicalPath, containsPath, withAbort } from "../paths/paths.ts";+import { windowsProtectedCommandPath } from "./command-path-risk.ts";+import { PolicyTargetError } from "./errors.ts";+import type { RequestFacts } from "./request-facts.ts";+import type { EvaluationInput, PathContext } from "./types.ts";++type FileRead = {+ category: "read_file" | "list_dir";+ path: string;+};++function localDrivePath(path: string) {+ return /^[a-z]:[\\/]/i.test(path) && windowsLiteralPath(path);+}++async function approvedPath(path: string, context: PathContext, roots: readonly string[]) {+ const absolute = win32.resolve(context.cwd, path);+ if (!localDrivePath(absolute) || windowsProtectedCommandPath(absolute, roots)) return undefined;+ const resolved = await canonicalPath(absolute, context);+ if (!localDrivePath(resolved.path) || windowsProtectedCommandPath(resolved.path, roots))+ return undefined;+ return resolved;+}++type CommandInput = EvaluationInput & {+ request: Extract<EvaluationInput["request"], { category: "run_command" }>;+};+type ReadPolicy = (request: FileRead) => Promise<RequestFacts>;++export async function proveWindowsReadOnly(+ input: CommandInput,+ context: PathContext,+ cwd: string | undefined,+ protectedRoots: readonly string[],+ readPolicy: ReadPolicy,+): Promise<ApprovalFact[] | undefined> {+ if (!cwd || !localDrivePath(cwd) || input.request.stdin || input.request.outsideSandbox) return;+ if (+ input.request.background ||+ input.request.writePaths?.length ||+ input.boundary?.location?.target.startsWith("acp:")+ )+ return;+ const reads = windowsReadShape(input.request.command);+ if (!reads) return;++ try {+ const work = input.boundary?.readRoots ?? [+ input.workplace.home,+ ...input.workplace.folders.map((folder) => folder.path),+ ];+ const directory = await approvedPath(cwd, context, protectedRoots);+ if (!directory?.exists || !work.some((root) => containsPath(root, directory.path, "win32")))+ return;+ const checked = { ...context, cwd: directory.path };+ return await readFacts(reads, checked, protectedRoots, readPolicy);+ } catch (error) {+ context.signal.throwIfAborted();+ // A filesystem proof may fail on a disconnected target or inaccessible path. Keep the card.+ if (+ error instanceof PolicyTargetError ||+ (error instanceof Error &&+ "code" in error &&+ ["ENOENT", "ENOTDIR", "EACCES", "EPERM", "ELOOP", "ENAMETOOLONG"].includes(+ String(error.code),+ ))+ )+ return;+ throw error;+ }+}++async function readFacts(+ reads: readonly (FileRead & { recurse?: boolean; readEntries?: boolean })[],+ context: PathContext,+ protectedRoots: readonly string[],+ readPolicy: ReadPolicy,+): Promise<ApprovalFact[] | undefined> {+ const facts: ApprovalFact[] = [];+ for (const read of reads) {+ const path = await approvedPath(read.path, context, protectedRoots);+ if (!path) return;+ const lexical = win32.resolve(context.cwd, read.path);+ if (!readAllowed(await readPolicy({ category: read.category, path: lexical }))) return;+ if (+ (read.recurse || read.readEntries) &&+ (!path.exists ||+ !(await entriesAllowed(path.path, read, context, protectedRoots, readPolicy)))+ )+ return;+ facts.push({ kind: "read", value: path.path });+ }+ return facts;+}++function readAllowed(facts: RequestFacts) {+ const { result, outside } = facts;+ return (+ result.decision !== "deny" &&+ result.category !== "read_ai_config" &&+ (!outside || result.decision === "allow")+ );+}++async function entriesAllowed(+ path: string,+ read: { recurse?: boolean; readEntries?: boolean },+ context: PathContext,+ protectedRoots: readonly string[],+ readPolicy: ReadPolicy,+) {+ const enumerate = context.fs.windowsReadEntries;+ if (!enumerate) return false;+ const entries = await withAbort(+ () =>+ enumerate(+ path,+ read.recurse === true,+ context.signal,+ (entry) => localDrivePath(entry) && !windowsProtectedCommandPath(entry, protectedRoots),+ ),+ context.signal,+ );+ if (!entries) return false;+ for (const entry of entries) {+ if (+ read.readEntries &&+ !entry.directory &&+ !readAllowed(await readPolicy({ category: "read_file", path: entry.path }))+ )+ return false;+ }+ return true;+}diff --git a/packages/policy/src/core/windows-command-exceptions.ts b/packages/policy/src/core/windows-command-exceptions.tsnew file mode 100644index 0000000..77854ad--- /dev/null+++ b/packages/policy/src/core/windows-command-exceptions.ts@@ -0,0 +1,86 @@+// Keep commands with opaque execution or sensitive Windows path syntax on the one-time card.+import { win32 } from "node:path";+import { powershellSegments } from "../commands/powershell-segments.ts";+import { windowsLiteralPath, windowsLiteralToken } from "../commands/windows-approval-shape.ts";+import { containsPath } from "../paths/paths.ts";+import {+ type CommandPathScope,+ isWritableCommandPath,+ windowsProtectedCommandPath,+} from "./command-path-risk.ts";++const WINDOWS_DELETE = /^(?:remove-item|ri|rm|rmdir|rd|del|erase)$/i;+const inlineType =+ /\badd-type\b(?!\s+[-\u2013-\u2015](?:path|literalpath|assemblyname)(?=[ :\t]))|\badd-type\b[^\r\n]*[-\u2013-\u2015](?:typedefinition|memberdefinition)(?=[\s:=])/i;+const dynamicExecution =+ /\b(?:invoke-expression|iex)\b|[-\u2013-\u2015](?:enc(?:odedcommand)?|encodedarguments)(?=$|[\s"'=:])|\[\s*(?:system\.management\.automation\.)?scriptblock\s*\]\s*::\s*create\b|\$\s*\(|(?:^|[;|\r\n])\s*[.&]\s*(?:\$|[(])|[-\u2013-\u2015]scriptblock(?=$|[\s:=])|--%/i;+const cmdExpansion = /\bcmd(?:\.exe)?\b[^\r\n]*?\/[ck]\s+[^\r\n]*(?:%[^%\s]+%|![^!\s]+!)/i;++function encodedShellArgument(command: string) {+ const launch = /\b(?:powershell|pwsh)(?:\.exe)?\b/i.exec(command);+ if (!launch) return false;+ const args = command.slice(launch.index + launch[0].length);+ for (const match of args.matchAll(+ /(?:^|[\s"'])(?:--?|[/\u2013-\u2015])([a-z]+)(?=$|[\s"'=:])/gi,+ )) {+ const flag = match[1]?.toLowerCase();+ if (flag && (flag === "ec" || "encodedcommand".startsWith(flag))) return true;+ }+ return false;+}++/** Forward-slash UNC is valid too, but the slashes in a URL scheme are not UNC. */+export function windowsNetworkOrDevicePath(text: string) {+ return /\\[\\/]|\/\\|(?<!:)\/\/|\bfile:\/\/(?=[^/])|\\(?:\?\?|device|global\?\?)\\/i.test(text);+}++export function windowsObfuscatedCommand(command: string) {+ const parsed = powershellSegments(command);+ return (+ parsed.tooLong ||+ parsed.unclosed ||+ command.includes("`") ||+ dynamicExecution.test(command) ||+ encodedShellArgument(command) ||+ cmdExpansion.test(command) ||+ parsed.pieces.some(+ ({ separator, tokens }) =>+ separator === "&" && tokens.length > 0 && !windowsLiteralToken(tokens[0] ?? ""),+ ) ||+ inlineType.test(command)+ );+}++/** Exempt only an unchanged, literal PowerShell delete of one strict work-folder descendant. */+export function windowsDeleteTarget(command: string, cwd: string) {+ const { pieces } = powershellSegments(command);+ if (pieces.some((piece) => piece.afterPipeOrCall)) return undefined;+ const statements = pieces.filter((piece) => piece.tokens.length);+ const [program, ...args] = statements[0]?.tokens ?? [];+ if (statements.length !== 1 || !WINDOWS_DELETE.test(program ?? "")) return undefined;+ const operands: string[] = [];+ for (const arg of args) {+ if (/^-(?:recurse|force|literalpath|path)$/i.test(arg)) continue;+ if (/^[-/]/.test(arg)) return undefined;+ const value = windowsLiteralToken(arg);+ if (!value) return undefined;+ operands.push(value);+ }+ const target = operands[0];+ if (operands.length !== 1 || !target || !windowsLiteralPath(target)) return undefined;+ return win32.resolve(cwd, target);+}++export function safeWindowsDeletePath(+ path: string,+ protectedRoots: readonly string[],+ scope: CommandPathScope,+) {+ return (+ !windowsProtectedCommandPath(path, protectedRoots) &&+ isWritableCommandPath(path, "win32", scope) &&+ ![...scope.writeRoots, ...scope.denyWriteRoots, ...protectedRoots].some((root) =>+ containsPath(path, root, "win32"),+ )+ );+}diff --git a/packages/policy/src/core/windows-command-scan.ts b/packages/policy/src/core/windows-command-scan.tsindex 7e0affe..ef79308 100644--- a/packages/policy/src/core/windows-command-scan.ts+++ b/packages/policy/src/core/windows-command-scan.ts@@ -1,11 +1,25 @@+// Retain Windows danger hints and verify known targets before the stored Windows consent can release the call.++import type { ApprovalFact } from "@pibot/protocol-base";import { powershellDirectoryWrites } from "../commands/powershell-directories.ts";+import { canonicalPath, expandHome } from "../paths/paths.ts";import { windowsProtectedPathNames } from "../paths/protected-paths.ts";import {type CommandPathScope,commandLiteralPaths,isWritableCommandPath,+ verifiedCommandPaths,+ windowsProtectedCommandPath,} from "./command-path-risk.ts";+import type { PathContext } from "./types.ts";+import {+ safeWindowsDeletePath,+ windowsDeleteTarget,+ windowsNetworkOrDevicePath,+ windowsObfuscatedCommand,+} from "./windows-command-exceptions.ts";+const MAX_FRAGMENTS = 16;const MAX_FRAGMENT_LENGTH = 160;const boundary = /[\\\s"'`;&|(){}=:%]/;@@ -17,7 +31,8 @@ export function scanWindowsCommand(protectedRoots: readonly string[] = [],scope: CommandPathScope = { writeRoots: [], denyWriteRoots: [] },verifiedPaths: ReadonlySet<string> = new Set(),- cwd?: string,+ directoryWrites?: ReturnType<typeof powershellDirectoryWrites>,+ verifiedDelete = false,) {const fragments = new Set<string>();let privilegeEscalation = false;@@ -25,19 +40,22 @@ export function scanWindowsCommand(if (fragments.size < MAX_FRAGMENTS) fragments.add(value.slice(0, MAX_FRAGMENT_LENGTH));};for (const match of command.matchAll(- /\b(?:sudo|runas)(?:\.exe)?\b|-verb\s*(?:[:=]\s*)?["']?runas\b/gi,+ /\b(?:sudo|runas)(?:\.exe)?\b|[-\u2013-\u2015]verb\s*(?:[:=]\s*)?["']?runas\b/gi,)) {privilegeEscalation = true;add(match[0]);}- for (const match of command.matchAll(- /\b(?:remove-item|ri|rm|rmdir|rd|del|erase)\b(?:[ \t]+(?:-recurse\b|-force\b|-[rf]+\b|\/[sq]\b))*/gi,- ))- add(match[0]);+ if (!verifiedDelete) {+ for (const match of command.matchAll(+ /\b(?:remove-item|ri|rm|rmdir|rd|del|erase)\b(?:[ \t]+(?:-recurse\b|-force\b|-[rf]+\b|\/[sq]\b))*/gi,+ ))+ add(match[0]);+ }// Slash folding preserves offsets so fragments remain the exact text shown by the caller.const folded = command.replaceAll("/", "\\");const paths = commandLiteralPaths(command);- for (const name of [...windowsProtectedPathNames(), ...protectedRoots]) {+ const systemNames = windowsProtectedPathNames();+ for (const name of [...systemNames, ".git", ...protectedRoots]) {const needle = name.replaceAll("/", "\\").replace(/\\+$/, "");if (!needle) continue;let pathIndex = 0;@@ -51,6 +69,7 @@ export function scanWindowsCommand(while (paths[pathIndex] && (paths[pathIndex]?.end ?? 0) <= start) pathIndex++;const literal = paths[pathIndex];if (+ systemNames.includes(name) &&literal &&literal.start <= start &&literal.end >= end &&@@ -66,11 +85,104 @@ export function scanWindowsCommand(/%(?:systemroot|windir|programfiles(?:\(x86\))?|programdata)%|\$env:(?:systemroot|windir|programfiles|programdata)\b/gi,))add(match[0]);- if (cwd) {- const directoryWrites = powershellDirectoryWrites(command, cwd);+ if (directoryWrites) {for (const path of directoryWrites.writes)- if (!isWritableCommandPath(path, "win32", scope)) add(path);+ if (+ !isWritableCommandPath(path, "win32", scope) ||+ windowsProtectedCommandPath(path, protectedRoots)+ )+ add(path);if (directoryWrites.unknownWrite) add("unknown_command_directory");}return { privilegeEscalation, fragments: [...fragments] };}++export async function prepareWindowsCommandScan(+ command: string,+ options: {+ protectedRoots: readonly string[];+ scope: CommandPathScope;+ writePaths?: readonly string[];+ cwd: string | undefined;+ context: PathContext | undefined;+ },+) {+ const { protectedRoots, scope, cwd, context } = options;+ const needsConfirmation =+ windowsNetworkOrDevicePath(command) ||+ (cwd !== undefined && windowsNetworkOrDevicePath(cwd)) ||+ options.writePaths?.some(windowsNetworkOrDevicePath) === true ||+ windowsObfuscatedCommand(command);+ const directoryWrites = cwd ? powershellDirectoryWrites(command, cwd) : undefined;+ const declaredWrites = options.writePaths?.map((path) =>+ expandHome(path, context?.home ?? cwd ?? ""),+ );+ const writes = new Set([...(directoryWrites?.writes ?? []), ...(declaredWrites ?? [])]);+ const deleteTarget = cwd ? windowsDeleteTarget(command, cwd) : undefined;+ const verifiedPaths =+ context && !needsConfirmation+ ? await verifiedCommandPaths(command, scope, context)+ : new Set<string>();+ const confirmed = await checkWindowsWrites(writes, deleteTarget, {+ protectedRoots,+ scope,+ context: context && !needsConfirmation && cwd ? { ...context, cwd } : undefined,+ });+ const scan = scanWindowsCommand(+ command,+ protectedRoots,+ scope,+ verifiedPaths,+ directoryWrites,+ confirmed.verifiedDelete,+ );+ return {+ privilegeEscalation: scan.privilegeEscalation,+ fragments: [...new Set([...scan.fragments, ...confirmed.fragments])].slice(0, MAX_FRAGMENTS),+ needsConfirmation,+ facts: confirmed.facts,+ };+}++async function checkWindowsWrites(+ paths: ReadonlySet<string>,+ deleteTarget: string | undefined,+ options: { protectedRoots: readonly string[]; scope: CommandPathScope; context?: PathContext },+) {+ const { protectedRoots, scope, context } = options;+ const facts: ApprovalFact[] = [];+ const fragments: string[] = [];+ let verifiedDelete = false;+ if (!context) return { facts, fragments, verifiedDelete };+ for (const path of paths) {+ context.signal.throwIfAborted();+ if (facts.length + fragments.length >= 32) {+ fragments.push("unknown_command_directory");+ break;+ }+ if (windowsProtectedCommandPath(path, protectedRoots)) {+ fragments.push(path.slice(0, MAX_FRAGMENT_LENGTH));+ continue;+ }+ try {+ const resolved = await canonicalPath(path, context);+ if (+ windowsNetworkOrDevicePath(resolved.path) ||+ windowsProtectedCommandPath(resolved.path, protectedRoots)+ ) {+ fragments.push(path.slice(0, MAX_FRAGMENT_LENGTH));+ continue;+ }+ facts.push({ kind: "write", value: resolved.path });+ if (path === deleteTarget)+ verifiedDelete =+ safeWindowsDeletePath(path, protectedRoots, scope) &&+ safeWindowsDeletePath(resolved.path, protectedRoots, scope);+ } catch {+ // An unreadable target cannot rule out a junction into a protected directory.+ context.signal.throwIfAborted();+ fragments.push("unknown_command_directory");+ }+ }+ return { facts, fragments, verifiedDelete };+}diff --git a/packages/policy/src/core/yolo.ts b/packages/policy/src/core/yolo.tsindex 1b0530c..2560890 100644--- a/packages/policy/src/core/yolo.ts+++ b/packages/policy/src/core/yolo.ts@@ -1,5 +1,6 @@+import { WINDOWS_ORDINARY_COMMAND } from "./confirmation-reasons.ts";import { yoloMustAsk } from "./connection-confirmation.ts";-import { createPolicyTrace } from "./explain.ts";+import { createPolicyTrace, explainPolicyResult } from "./explain.ts";import type { PolicyResult } from "./types.ts";/** Reason code for a decision the conversation's YOLO switch allowed. */@@ -12,14 +13,14 @@ export const YOLO_REASON = "yolo";* and nothing becomes rememberable: YOLO writes no grant and no routine preauthorization.* Dangerous calls keep asking, including when YOLO releases already pending cards; install,* background and network command consents are answered by YOLO (`yoloMustAsk`). Only brain's- * explicit F39 path supplies unisolatedCommands; generic callers cannot answer that question.+ * explicit Windows-consent path supplies unisolatedCommands; generic callers cannot answer that question.*/export function applyYolo(result: PolicyResult,yolo: boolean | undefined,options: { unisolatedCommands?: boolean } = {},): PolicyResult {- // F39 is explicit consent for ordinary unisolated commands, never for danger or other cards.+ // The stored Windows consent is explicit consent for ordinary unisolated commands, never for danger or other cards.const explicitUnisolated =options.unisolatedCommands === true && result.reason === "windows_unisolated";const unchanged =@@ -50,3 +51,19 @@ export function applyYolo(if (result.category === "read_ai_config") delete allowed.grantScope;return allowed;}++/** The stored Windows consent covers ordinary Windows commands after the Windows risk and confirmation checks. */+export function applyWindowsCommandConsent(result: PolicyResult, consent: boolean): PolicyResult {+ if (+ result.decision !== "ask" ||+ result.risk !== "normal" ||+ result.reason !== WINDOWS_ORDINARY_COMMAND+ )+ return result;+ const bounded = explainPolicyResult(+ { ...result, reason: "windows_unisolated", canRemember: false },+ "boundary",+ "windows_unisolated",+ );+ return applyYolo(bounded, consent, { unisolatedCommands: true });+}diff --git a/packages/policy/src/index.ts b/packages/policy/src/index.tsindex 8af242f..1a54490 100644--- a/packages/policy/src/index.ts+++ b/packages/policy/src/index.ts@@ -40,7 +40,12 @@ export { createCommandAnalyzer } from "./commands/commands.ts";export { DANGEROUS_RULES, dangerousReasons } from "./commands/dangerous.ts";export { isReadonlyCommand, READONLY_PROGRAMS } from "./commands/readonly-programs.ts";export { agentLaunchPolicy } from "./core/agent-launch.ts";-export { PRIVATE_NETWORK_REASON } from "./core/confirmation-reasons.ts";+export {+ PRIVATE_NETWORK_REASON,+ WINDOWS_ORDINARY_COMMAND,+ WINDOWS_READ_ONLY,+ WINDOWS_REQUIRES_APPROVAL,+} from "./core/confirmation-reasons.ts";export {CONNECTION_CONFIRMATION_REASON,CONNECTION_READ_ONLY_REASON,@@ -95,7 +100,7 @@ export {} from "./core/outside-write.ts";export { pinnedScriptFile, scriptPinnedScope } from "./core/script-consent.ts";export type * from "./core/types.ts";-export { applyYolo, YOLO_REASON } from "./core/yolo.ts";+export { applyWindowsCommandConsent, applyYolo, YOLO_REASON } from "./core/yolo.ts";export { createGrantScope, matchesGrant, siteCovers } from "./grants/grants.ts";export {matchesRoutinePreauth,diff --git a/packages/policy/src/paths/paths.ts b/packages/policy/src/paths/paths.tsindex b1f44a7..b83035d 100644--- a/packages/policy/src/paths/paths.ts+++ b/packages/policy/src/paths/paths.ts@@ -3,6 +3,7 @@ import { posix, win32 } from "node:path";import { SCRIPT_MAX_BYTES } from "../commands/scripts.ts";import { PolicyTargetError } from "../core/errors.ts";import type { FileSystem, PathContext, Platform, ResolvedPath } from "../core/types.ts";+import { windowsReadEntries } from "./windows-read-tree.ts";/*** A name the kernel refuses as too long cannot be an existing file and no command can open it, so@@ -108,7 +109,8 @@ export function decisionFileSystem(platform: Platform): FileSystem {},};// Keep Windows' component handling for drive/UNC aliases until its native path is verified.- if (platform !== process.platform || platform === "win32") return walk;+ if (platform === "win32" && process.platform === "win32") return { ...walk, windowsReadEntries };+ if (platform !== process.platform) return walk;return {...walk,async canonicalize(path, signal) {@@ -150,7 +152,7 @@ export function expandHome(value: string, home: string): string {if (value.startsWith("~")) throw new PolicyTargetError("path_resolution_failed");return value;}-async function withAbort<T>(operation: () => Promise<T>, signal: AbortSignal): Promise<T> {+export async function withAbort<T>(operation: () => Promise<T>, signal: AbortSignal): Promise<T> {signal.throwIfAborted();return new Promise((accept, reject) => {const abort = () => {diff --git a/packages/policy/src/paths/windows-read-tree.ts b/packages/policy/src/paths/windows-read-tree.tsnew file mode 100644index 0000000..fde2e55--- /dev/null+++ b/packages/policy/src/paths/windows-read-tree.ts@@ -0,0 +1,36 @@+// Directory-producing PowerShell commands can implicitly read descendants through a pipe.+import { lstat, opendir } from "node:fs/promises";+import { win32 } from "node:path";++export interface WindowsReadEntry {+ path: string;+ directory: boolean;+}++/** Only the local filesystem can attest that each visited entry is a regular file or directory. */+export async function windowsReadEntries(+ directory: string,+ recurse: boolean,+ signal: AbortSignal,+ canVisit: (path: string) => boolean,+): Promise<WindowsReadEntry[] | undefined> {+ const directories = [directory];+ const entries: WindowsReadEntry[] = [];+ while (directories.length) {+ const path = directories.pop();+ if (!path) return;+ signal.throwIfAborted();+ if (!(await lstat(path)).isDirectory()) return;+ signal.throwIfAborted();+ // The iterator closes its directory handle on completion, early return or cancellation.+ for await (const entry of await opendir(path, { bufferSize: 32 })) {+ signal.throwIfAborted();+ if (entries.length >= 256 || (!entry.isDirectory() && !entry.isFile())) return;+ const child = win32.join(path, entry.name);+ if (!canVisit(child)) return;+ entries.push({ path: child, directory: entry.isDirectory() });+ if (recurse && entry.isDirectory()) directories.push(child);+ }+ }+ return entries;+}diff --git a/tools/dev/policy-matrix/expected.tsv b/tools/dev/policy-matrix/expected.tsvindex 0461192..3cc3829 100644--- a/tools/dev/policy-matrix/expected.tsv+++ b/tools/dev/policy-matrix/expected.tsv@@ -2,7 +2,7 @@ case darwin/never darwin/ask darwin/always linux/never linux/ask linux/always wiread_file deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_alwayslist_dir deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_alwayswrite_file deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_always deny:permission_never ask:permission_ask allow:permission_always-run_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval+run_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:windows_read_only allow:windows_read_onlyconnector deny:permission_never allow:connector_metadata allow:connector_metadata deny:permission_never allow:connector_metadata allow:connector_metadata deny:permission_never allow:connector_metadata allow:connector_metadatacomputer deny:permission_never ask:permission_ask ask:computer_app_not_in_always_list deny:permission_never ask:permission_ask ask:computer_app_not_in_always_list deny:permission_never ask:permission_ask ask:computer_app_not_in_always_listread_ai_config deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable deny:category_unavailable@@ -33,77 +33,77 @@ list_dir/protected deny:sensitive_path deny:sensitive_path deny:sensitive_path dlist_dir/skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skill allow:bot_skillwrite_file/outside deny:permission_never ask:outside_workplace_write ask:outside_workplace_write deny:permission_never ask:outside_workplace_write ask:outside_workplace_write deny:permission_never ask:outside_workplace_write ask:outside_workplace_writewrite_file/protected deny:protected_path deny:protected_path deny:protected_path deny:protected_path deny:protected_path deny:protected_path deny:protected_path deny:protected_path deny:protected_path-run_command/outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/environment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval+run_command/outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/environment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_commandconnector/unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailable deny:connector_unavailableread_messages/unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailable deny:message_scope_unavailablememory/untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrusted ask:memory_after_untrustedweb/private deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_denied deny:local_network_deniedweb/unlisted deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowedweb/invalid deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed deny:url_resolution_failed-script/pure_shell deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval+script/pure_shell deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_commandscript/shell_rm deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:dangerous_operation ask:dangerous_operation-script/curl_allowed deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/curl_allowed_web_always deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/curl_pipe_sh deny:permission_never ask:dangerous_operation ask:dangerous_operation deny:permission_never ask:dangerous_operation ask:dangerous_operation deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/written_first deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval+script/curl_allowed deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/curl_allowed_web_always deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/curl_pipe_sh deny:permission_never ask:dangerous_operation ask:dangerous_operation deny:permission_never ask:dangerous_operation ask:dangerous_operation deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/written_first deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_commandscript/after_cd deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:dangerous_operation ask:dangerous_operation-script/outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/too_large deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/link_outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/python_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/python_os deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/python_getattr deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/remembered_same deny:permission_never allow:grant_matched allow:grant_matched deny:permission_never allow:grant_matched allow:grant_matched deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/remembered_changed deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c1_quoted_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c1_continued_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c1_if_false_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c1_string_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c2_python_shadow deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c2_python_c_shadow deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c2_python_c_isolated deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c2_python_c_clean deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c3_python_utf7 deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/c4_shebang_env_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/low_invalid_utf8 deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/low_nul deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_export_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_declare_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_readonly_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_typeset_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_printf_v_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_env_wrapper deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_timeout_wrapper deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_outside_export deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n1_outside_readonly_sh deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n4_path_quoted deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n4_path_escaped deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n4_ifs_quoted deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n4_ifs_printf_v deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-script/n4_ifs_readonly_sh deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/node_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/node_require deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/node_builtin_global deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/lua_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/php_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/ruby_inline deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/curl_get deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/curl_get_web_always deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/curl_unlisted deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/curl_data deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:windows_requires_approval ask:windows_requires_approval-run_command/curl_output deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:windows_requires_approval ask:windows_requires_approval+script/outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/too_large deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/link_outside deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/python_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/python_os deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/python_getattr deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/remembered_same deny:permission_never allow:grant_matched allow:grant_matched deny:permission_never allow:grant_matched allow:grant_matched deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/remembered_changed deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c1_quoted_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c1_continued_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c1_if_false_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c1_string_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c2_python_shadow deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c2_python_c_shadow deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c2_python_c_isolated deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c2_python_c_clean deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c3_python_utf7 deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/c4_shebang_env_assignment deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/low_invalid_utf8 deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/low_nul deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_export_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_declare_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_readonly_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_typeset_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_printf_v_quoted_name deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_env_wrapper deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_timeout_wrapper deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_outside_export deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n1_outside_readonly_sh deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n4_path_quoted deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n4_path_escaped deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n4_ifs_quoted deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n4_ifs_printf_v deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+script/n4_ifs_readonly_sh deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/node_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/node_require deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/node_builtin_global deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/lua_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/php_pure deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/ruby_inline deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:incomplete_analysis allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/curl_get deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:permission_ask allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/curl_get_web_always deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never allow:readonly_command allow:sandboxed_command deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/curl_unlisted deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:domain_not_allowed deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/curl_data deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_command+run_command/curl_output deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:command_network_confirmation ask:command_network_confirmation deny:permission_never ask:windows_ordinary_command ask:windows_ordinary_commandroutine/script_rm deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none-routine/script_pure deny:permission_never:none allow:readonly_command:none allow:sandboxed_command:none deny:permission_never:none allow:readonly_command:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/script_curl_pipe_sh deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none+routine/script_pure deny:permission_never:none allow:readonly_command:none allow:sandboxed_command:none deny:permission_never:none allow:readonly_command:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/script_curl_pipe_sh deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:noneroutine/script_after_cd deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:dangerous_operation:none ask:dangerous_operation:none-routine/python_os deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_python_local_import deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_node_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_lua_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_php_include deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_ruby_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_perl_use deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_powershell_dot_source deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none-routine/m1_shell_dynamic_c deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_requires_approval:none ask:windows_requires_approval:none+routine/python_os deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:pinned allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_python_local_import deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_node_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_lua_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_php_include deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_ruby_require deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_perl_use deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_powershell_dot_source deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:none+routine/m1_shell_dynamic_c deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:incomplete_analysis:none allow:sandboxed_command:none deny:permission_never:none ask:windows_ordinary_command:none ask:windows_ordinary_command:noneroutine/script_changed none same_matches/changed_no_match none none same_matches/changed_no_match none none none nonediff --git a/tools/dev/policy-matrix/matrix.ts b/tools/dev/policy-matrix/matrix.tsindex 27351c1..6772a14 100644--- a/tools/dev/policy-matrix/matrix.ts+++ b/tools/dev/policy-matrix/matrix.ts@@ -1,6 +1,8 @@import { readFile } from "node:fs/promises";import { posix, win32 } from "node:path";import {+ applyWindowsCommandConsent,+ applyYolo,createPolicy,type EvaluationInput,type Platform,@@ -37,6 +39,7 @@ function inputs(platform: Platform) {const fs = {async realpath(value: string, signal: AbortSignal) {signal.throwIfAborted();+ if (platform === "win32" && path.basename(value) === "junction") return protectedRoot;if (path.basename(value) === "inaccessible")throw Object.assign(new Error("synthetic path access error"), { code: "EACCES" });return value;@@ -131,6 +134,105 @@ function inputs(platform: Platform) {return { base, home, fs, remoteBoundary, root, work, cases: { ...scenarios, ...extra } };}+// Synthetic Windows paths and entries exercise classification without starting a shell.+async function windowsApprovalCases(+ evaluate: (+ name: string,+ level: "ask",+ request: PolicyRequest,+ extra?: { boundary?: EvaluationInput["boundary"] },+ ) => Promise<import("../../../packages/policy/src/index.ts").PolicyResult>,+ remoteBoundary: NonNullable<EvaluationInput["boundary"]>,+) {+ const cases = [+ ["dir", "windows_read_only", "allow"],+ ["Get-ChildItem -Recurse src", "windows_read_only", "allow"],+ ["gci | Select-String foo", "windows_read_only", "allow"],+ ["TYPE file.txt; Get-Date", "windows_read_only", "allow"],+ ["Get-Content file.txt > $null", "windows_read_only", "allow"],+ ['cmd.exe /d /c "type file.txt > NUL"', "windows_read_only", "allow"],+ ["npm test", "windows_ordinary_command", "allow"],+ ["node build.js", "windows_ordinary_command", "allow"],+ ["python build.py", "windows_ordinary_command", "allow"],+ ["git commit -m x", "windows_ordinary_command", "allow"],+ ["git status", "windows_ordinary_command", "allow"],+ ["cargo build", "windows_ordinary_command", "allow"],+ ["npm run dev", "windows_ordinary_command", "allow"],+ ["git clone https://example.com/repo.git", "windows_ordinary_command", "allow"],+ ["Set-Content file.txt 'hello world'", "windows_ordinary_command", "allow"],+ [String.raw`Remove-Item .\dist -Recurse`, "windows_ordinary_command", "allow"],+ ["Remove-Item . -Recurse", "dangerous_operation", "ask"],+ [String.raw`Remove-Item ..\outside -Recurse`, "dangerous_operation", "ask"],+ [String.raw`Remove-Item .\junction -Recurse`, "dangerous_operation", "ask"],+ [String.raw`Set-Content .git\config text`, "dangerous_operation", "ask"],+ [String.raw`Set-Content junction\config text`, "dangerous_operation", "ask"],+ [String.raw`Set-Content C:\matrix\protected\db x`, "dangerous_operation", "ask"],+ [String.raw`Set-Content .ssh\config x`, "dangerous_operation", "ask"],+ [String.raw`Get-Content \\server\share\file.txt`, "windows_requires_approval", "ask"],+ [String.raw`python build.py "\\?\UNC\server\share"`, "windows_requires_approval", "ask"],+ [String.raw`python build.py "\\.\pipe\example"`, "windows_requires_approval", "ask"],+ ["python build.py //server/share", "windows_requires_approval", "ask"],+ ["python build.py file://server/share", "windows_requires_approval", "ask"],+ ['& "$env:PIBOT_FIXTURE_COMMAND"', "windows_requires_approval", "ask"],+ ["iex 'Get-Date'", "windows_requires_approval", "ask"],+ ["powershell -enc fixture", "windows_requires_approval", "ask"],+ ["pwsh -EncodedCommand fixture", "windows_requires_approval", "ask"],+ ["[scriptblock]::Create('Get-Date')", "windows_requires_approval", "ask"],+ ["iwr https://example.com/example | iex", "windows_requires_approval", "ask"],+ ["Add-Type -TypeDefinition 'fixture'", "windows_requires_approval", "ask"],+ ["Get-Item provider:file.txt", "windows_ordinary_command", "allow"],+ ["Get-Content file.txt > output.txt", "windows_ordinary_command", "allow"],+ ["Get-Content file.txt | Set-Content output.txt", "windows_ordinary_command", "allow"],+ ["Get-Command Example", "windows_ordinary_command", "allow"],+ ["Get-Command -ListImported Example | Select-String foo", "windows_ordinary_command", "allow"],+ ["cmd /c dir", "windows_ordinary_command", "allow"],+ ["cmd /d /c dir -Recurse src", "windows_ordinary_command", "allow"],+ ["Start-Process cmd -Verb RunAs", "privilege_escalation_denied", "deny"],+ ["sudo whoami", "privilege_escalation_denied", "deny"],+ ] as const;+ for (const [command, reason, consentDecision] of cases) {+ const result = await evaluate("windows_approval", "ask", { category: "run_command", command });+ const withConsent = applyWindowsCommandConsent(result, true);+ const withoutConsent = applyWindowsCommandConsent(result, false);+ if (+ result.reason !== reason ||+ withConsent.decision !== consentDecision ||+ (reason === "windows_ordinary_command" &&+ (withoutConsent.decision !== "ask" || applyYolo(result, true).decision !== "ask"))+ )+ throw new Error(+ `Windows policy matrix: ${command}: ${result.reason}/${withConsent.decision}`,+ );+ }+ const requests: [Partial<Extract<PolicyRequest, { category: "run_command" }>>, string, string][] =+ [+ [{ background: true }, "windows_ordinary_command", "allow"],+ [{ stdin: true }, "dangerous_operation", "ask"],+ [{ outsideSandbox: true }, "outside_sandbox_unsupported", "deny"],+ [{ writePaths: [String.raw`junction\config`] }, "dangerous_operation", "ask"],+ ];+ for (const [flags, reason, decision] of requests) {+ const result = await evaluate("windows_request_flags", "ask", {+ category: "run_command",+ command: "python build.py",+ ...flags,+ });+ if (result.reason !== reason || applyWindowsCommandConsent(result, true).decision !== decision)+ throw new Error(`Windows request flags: ${JSON.stringify(flags)}: ${result.reason}`);+ }+ const missingProtection = await evaluate(+ "windows_runner_protection",+ "ask",+ { category: "run_command", command: "cargo build" },+ { boundary: remoteBoundary },+ );+ if (+ missingProtection.reason !== "runner_command_protection_unavailable" ||+ applyWindowsCommandConsent(missingProtection, true).decision !== "deny"+ )+ throw new Error("Windows runner without protection metadata must refuse native commands");+}+const header = ["case",...platforms.flatMap((platform) => levels.map((level) => `${platform}/${level}`)),@@ -147,6 +249,15 @@ for (const platform of platforms) {fs.realpath(await scripts.fs.realpath(value), signal),readScript: scripts.fs.readScript,listNames: scripts.fs.listNames,+ ...(platform === "win32"+ ? {+ windowsReadEntries: async (directory, _recurse, signal, canVisit) => {+ signal.throwIfAborted();+ const path = win32.join(directory, "file.txt");+ return canVisit(path) ? [{ path, directory: false }] : undefined;+ },+ }+ : {}),},});const evaluate = async (@@ -180,6 +291,7 @@ for (const platform of platforms) {return result;};try {+ if (platform === "win32") await windowsApprovalCases(evaluate, remoteBoundary);for (const [name, request] of Object.entries(cases)) {const row = rows.get(name) ?? [];for (const level of levels) {