@jackice/pi-approval-gate 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +78 -2
- package/index.ts +279 -0
- package/package.json +53 -4
- package/src/bash-hook.ts +23 -0
- package/src/binding.ts +30 -0
- package/src/dialog.ts +96 -0
- package/src/gate.ts +225 -0
- package/src/native-dialog.ts +156 -0
- package/src/policy.ts +287 -0
- package/src/uv-guard.ts +57 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
- 内建可选 uv 命令拦截(`--approval-guard uv` 或 `approvalGate.guard: "uv"`),默认关闭。
|
|
6
|
+
- 移除 `guard`/`sourcePath` 宿主复用选项:审批包自己注册 `bash`,不再需要第二个扩展。
|
|
7
|
+
|
|
8
|
+
## 0.1.2
|
|
9
|
+
|
|
10
|
+
- 加固原生审批视图:保留软换行空格、转义不可见字符,并在窄屏显示风险与分页状态;视图内容被裁切时拒绝批准。
|
|
11
|
+
- 原生选择列表成为默认审批 UI,`--approval-ui panel` 可切回面板。
|
|
12
|
+
- 新增 `guard` 与 `sourcePath` 选项,允许宿主扩展持有唯一的 `bash` 注册并复用审批;`guard` 在对话框之前拦截。
|
|
13
|
+
- 将 `glab mr merge/close` 纳入远端写入审批。
|
|
14
|
+
|
|
15
|
+
## 0.1.1
|
|
16
|
+
|
|
17
|
+
- 新增 `--approval-ui native`:用 Pi 原生选择列表回滚新版面板,保留默认拒绝、确认延迟和 Gate 决策。
|
|
18
|
+
- 将 `@jackice/pi-ui` 固定为运行时依赖;Pi 省略 peer 安装时仍能加载候选扩展。
|
|
19
|
+
- 按真实文件路径验证 `bash` 注册来源,避免符号链接安装误阻断自身工具;无法确认来源时仍拒绝。
|
|
20
|
+
- 安全评审 C1/H1/H2/H3 修复:线性 quote-aware 策略、包装命令递归、fail-closed、git/gh 全局选项、fullscreen 分页
|
|
21
|
+
- M1/M2/M3/M4/M5 修复:移除超线性正则、继承 shell 前缀、拦截 user_bash、bidi 清洗、影子注册自检
|
|
22
|
+
- L1/L3/L4/L6 修复:关闭清理指纹、maxCommandLines 兜底、分页键位、配置 clamp
|
|
23
|
+
- 66 个测试;真实 TUI/fullscreen/user_bash/RPC/子代理验证
|
|
24
|
+
|
|
25
|
+
## 0.1.0
|
|
26
|
+
|
|
27
|
+
- 新增 ApprovalGate:FIFO 队列、120s 超时、abort/shutdown 幂等取消、最多 16 个待请求
|
|
28
|
+
- 新增 `bash` 执行边界替换:审批后写入一次性 command+cwd 指纹,spawnHook 消费
|
|
29
|
+
- 新增 `ApprovalView` 对话框:完整命令、cwd、reason、风险、Allow once/Deny、滚动、500ms arm
|
|
30
|
+
- RPC/headless/子代理默认拒绝
|
|
31
|
+
- 真实 Pi RPC 与 `PI_SUBAGENT_CHILD=1` 验证默认拒绝
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @jackice/pi-approval-gate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An approval extension for Pi's supported Bash execution paths. It binds user approval to the final command and working directory, after `tool_call` handlers have run.
|
|
4
|
+
|
|
5
|
+
- Verified with Pi `1.6.0` and `@jackice/pi-ui` `0.4.2`. The native selection list is the default approval UI.
|
|
6
|
+
- Commands that require approval are denied when no supported interactive UI is available, in subagents, or on timeout, abort, reload, or shutdown.
|
|
7
|
+
- Registers a replacement `bash` tool through Pi's extension API. No Pi source changes are required.
|
|
8
|
+
- Commands the policy cannot parse require approval.
|
|
9
|
+
- Honors `shellCommandPrefix` and `shellPath` settings and shows the final command before execution.
|
|
10
|
+
- Known limit: Pi `1.6.0` has no synchronous pre-spawn hook, so a cancellation in the gap between authorization and `spawn()` can still start the command. See the [review notes](docs/security-review.md). This is not a sandbox.
|
|
11
|
+
|
|
12
|
+
## How it works
|
|
13
|
+
|
|
14
|
+
1. The extension creates a Bash tool with `createBashToolDefinition` and a `spawnHook`.
|
|
15
|
+
2. When the policy requires approval, the tool waits for the user after all `tool_call` changes.
|
|
16
|
+
3. Approval authorizes one execution of the exact command in the exact working directory. The spawn hook consumes it before Bash starts.
|
|
17
|
+
4. A mismatch stops execution before the command runs.
|
|
18
|
+
5. Commands not flagged by the policy do not prompt.
|
|
19
|
+
6. Pi's `user_bash` (`!`) uses the same approval and parameter binding for flagged commands.
|
|
20
|
+
7. The extension checks the active `bash` registration against its own file's real path and blocks the tool if the source cannot be verified. Pi `1.6.0` rejects duplicate `bash` registrations.
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
```text
|
|
25
|
+
--approval-timeout-ms <ms> # Default: 120000; includes time spent in the queue.
|
|
26
|
+
--approval-arm-ms <ms> # Default: 500; minimum delay before allowing.
|
|
27
|
+
--approval-ui panel # Use the styled panel instead of the native selection list.
|
|
28
|
+
--approval-guard uv # Block pip/pip3/poetry/venv/py_compile and suggest uv.
|
|
29
|
+
PI_APPROVAL_TIMEOUT_MS
|
|
30
|
+
PI_APPROVAL_ARM_MS
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Pi parses extension flags after loading the extension. Settings are read when each request is created.
|
|
34
|
+
|
|
35
|
+
The native-list view is the default. It starts on **Deny** and supports Page Up and Page Down for long commands. It uses the same approval gate, confirmation delay, and cancellation rules as the styled panel.
|
|
36
|
+
|
|
37
|
+
### Optional uv guard
|
|
38
|
+
|
|
39
|
+
`--approval-guard uv`, or the same value in settings, blocks Python package-manager commands before any approval dialog and prints the uv equivalent:
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{ "approvalGate": { "guard": "uv" } }
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
It is off by default. The guard is separate from approval: it runs first for both the tool and `user_bash`, and a returned message stops the command.
|
|
46
|
+
|
|
47
|
+
## Verification
|
|
48
|
+
|
|
49
|
+
Verified with Pi `1.6.0` in a real TUI, using a test provider and a disposable fixture:
|
|
50
|
+
|
|
51
|
+
| Scenario | Result |
|
|
52
|
+
|---|---|
|
|
53
|
+
| Esc / Deny | The command does not run. |
|
|
54
|
+
| Allow once | The command runs after the arming delay. |
|
|
55
|
+
| Timeout after 1000 ms | The dialog closes without executing the command. |
|
|
56
|
+
| Headless `-p` | The command is denied by default. |
|
|
57
|
+
| RPC `--mode rpc` | The command is denied by default with `Blocked by approval gate`. |
|
|
58
|
+
| Subagent environment | `PI_SUBAGENT_CHILD=1` denies the command without a dialog. |
|
|
59
|
+
| Long command in fullscreen | Page Down reveals lines below the initial viewport. |
|
|
60
|
+
| `user_bash` | The `!` command prompts and executes only if allowed. |
|
|
61
|
+
| `shellCommandPrefix` | The configured prefix is applied. |
|
|
62
|
+
| Duplicate Bash registration | Pi reports a tool conflict rather than silently replacing the approval tool. |
|
|
63
|
+
|
|
64
|
+
Unit tests:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pnpm install
|
|
68
|
+
pnpm typecheck
|
|
69
|
+
pnpm test
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Limitations
|
|
73
|
+
|
|
74
|
+
- RPC has no verified external approval channel. Commands that require approval are denied by default.
|
|
75
|
+
- Subagent requests are denied, not escalated to the parent session.
|
|
76
|
+
- This is not a sandbox. It covers only the supported Bash paths, not `pi.exec`, `write`, `edit`, MCP, or `powershell`.
|
|
77
|
+
- The dialog does not show an arming countdown. Pressing Enter before the delay expires provides no feedback.
|
|
78
|
+
- Approval decisions are not stored in an audit log.
|
|
79
|
+
- The [review notes](docs/security-review.md) list the unresolved execution-boundary and release blockers.
|
package/index.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
createBashToolDefinition,
|
|
8
|
+
createLocalBashOperations,
|
|
9
|
+
type BashSpawnContext,
|
|
10
|
+
type BashToolOptions,
|
|
11
|
+
type ExtensionAPI,
|
|
12
|
+
} from "@earendil-works/pi-coding-agent";
|
|
13
|
+
|
|
14
|
+
import { createApprovalPrompt } from "./src/dialog.ts";
|
|
15
|
+
import { createBashSpawnHook } from "./src/bash-hook.ts";
|
|
16
|
+
import { verifyFinalBinding } from "./src/binding.ts";
|
|
17
|
+
import { ApprovalGate, type ApprovalAuthorization, type ApprovalRequest } from "./src/gate.ts";
|
|
18
|
+
import { dangerReason } from "./src/policy.ts";
|
|
19
|
+
import { uvGuard } from "./src/uv-guard.ts";
|
|
20
|
+
|
|
21
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
22
|
+
const DEFAULT_ARM_MS = 500;
|
|
23
|
+
const MAX_PENDING = 16;
|
|
24
|
+
const MAX_COMMAND_LINES = 8;
|
|
25
|
+
|
|
26
|
+
type CommandGuard = (command: string) => string | undefined;
|
|
27
|
+
|
|
28
|
+
export default function approvalGateExtension(pi: ExtensionAPI): void {
|
|
29
|
+
pi.registerFlag("approval-timeout-ms", {
|
|
30
|
+
description: "Pending bash approval timeout in milliseconds",
|
|
31
|
+
type: "string",
|
|
32
|
+
});
|
|
33
|
+
pi.registerFlag("approval-arm-ms", {
|
|
34
|
+
description: "Confirmation arm delay for Allow once",
|
|
35
|
+
type: "string",
|
|
36
|
+
});
|
|
37
|
+
pi.registerFlag("approval-ui", {
|
|
38
|
+
description: "Approval dialog style (native by default; panel optional)",
|
|
39
|
+
type: "string",
|
|
40
|
+
});
|
|
41
|
+
pi.registerFlag("approval-guard", {
|
|
42
|
+
description: "Command guard before approval (uv)",
|
|
43
|
+
type: "string",
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const promptOptions = () => ({
|
|
47
|
+
armMs: numberFlag(pi, "approval-arm-ms", "PI_APPROVAL_ARM_MS", DEFAULT_ARM_MS),
|
|
48
|
+
maxCommandLines: MAX_COMMAND_LINES,
|
|
49
|
+
...(pi.getFlag("approval-ui") === "panel" ? {} : { ui: "native" as const }),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** 每次调用重新解析,flag 与 settings 都可能在扩展加载后才可读。 */
|
|
53
|
+
const commandGuard = (): CommandGuard | undefined => {
|
|
54
|
+
if (pi.getFlag("approval-guard") === "uv") return uvGuard;
|
|
55
|
+
const settings = pi.getSettings() as { approvalGate?: { guard?: unknown } } | undefined;
|
|
56
|
+
return settings?.approvalGate?.guard === "uv" ? uvGuard : undefined;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const timeoutMs = () =>
|
|
60
|
+
numberFlag(pi, "approval-timeout-ms", "PI_APPROVAL_TIMEOUT_MS", DEFAULT_TIMEOUT_MS);
|
|
61
|
+
const gate = new ApprovalGate({ timeoutMs, maxPending: MAX_PENDING });
|
|
62
|
+
const selfPath = fileURLToPath(import.meta.url);
|
|
63
|
+
let shadowed = false;
|
|
64
|
+
|
|
65
|
+
const template = createBashToolDefinition(process.cwd(), {
|
|
66
|
+
spawnHook: (context) => verifyFinalBinding(undefined, undefined, context),
|
|
67
|
+
});
|
|
68
|
+
pi.registerTool({
|
|
69
|
+
...template,
|
|
70
|
+
executionMode: "sequential",
|
|
71
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
72
|
+
const command = params.command;
|
|
73
|
+
const cwd = ctx.cwd;
|
|
74
|
+
const shell = shellSettings(pi);
|
|
75
|
+
const guard = commandGuard();
|
|
76
|
+
const finalCommand = shell.commandPrefix ? `${shell.commandPrefix}\n${command}` : command;
|
|
77
|
+
const blocked = guard?.(finalCommand);
|
|
78
|
+
if (blocked !== undefined) {
|
|
79
|
+
return {
|
|
80
|
+
content: [{ type: "text", text: blocked }],
|
|
81
|
+
isError: true,
|
|
82
|
+
details: undefined,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const reason = dangerReason(finalCommand);
|
|
86
|
+
let authorization: ApprovalAuthorization | undefined;
|
|
87
|
+
let approvalRequest: ApprovalRequest | undefined;
|
|
88
|
+
if (reason !== undefined) {
|
|
89
|
+
const approved = await gate.request(
|
|
90
|
+
{
|
|
91
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
92
|
+
toolCallId,
|
|
93
|
+
toolName: "bash",
|
|
94
|
+
command: finalCommand,
|
|
95
|
+
cwd,
|
|
96
|
+
reason,
|
|
97
|
+
risk: "high",
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
...(signal === undefined ? {} : { signal }),
|
|
101
|
+
prompt: (request) => createApprovalPrompt(request, ctx, promptOptions()),
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
if (approved.decision !== "allow_once" || approved.authorization === undefined) {
|
|
105
|
+
return {
|
|
106
|
+
content: [{ type: "text", text: `Blocked by approval gate (${approved.decision}); command was not executed.` }],
|
|
107
|
+
isError: true,
|
|
108
|
+
details: undefined,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
authorization = approved.authorization;
|
|
112
|
+
approvalRequest = approved.request;
|
|
113
|
+
if (signal?.aborted) {
|
|
114
|
+
authorization.revoke();
|
|
115
|
+
return {
|
|
116
|
+
content: [{ type: "text", text: "Blocked by approval gate (cancelled); command was not executed." }],
|
|
117
|
+
isError: true,
|
|
118
|
+
details: undefined,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const options = bashOptions(shell, createBashSpawnHook({
|
|
124
|
+
guard,
|
|
125
|
+
authorization,
|
|
126
|
+
request: approvalRequest,
|
|
127
|
+
signal,
|
|
128
|
+
}));
|
|
129
|
+
try {
|
|
130
|
+
return await createBashToolDefinition(cwd, options).execute(
|
|
131
|
+
toolCallId,
|
|
132
|
+
{ ...params, command },
|
|
133
|
+
signal,
|
|
134
|
+
onUpdate,
|
|
135
|
+
ctx,
|
|
136
|
+
);
|
|
137
|
+
} finally {
|
|
138
|
+
authorization?.revoke();
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
pi.on("session_start", (_event, ctx) => {
|
|
144
|
+
const active = pi.getAllTools().find((tool) => tool.name === "bash");
|
|
145
|
+
shadowed = active === undefined || !sameSourceFile(active.sourceInfo.path, selfPath);
|
|
146
|
+
if (shadowed && ctx.hasUI) {
|
|
147
|
+
ctx.ui.notify(
|
|
148
|
+
"approval gate is not active: could not verify the registered bash source; bash is blocked",
|
|
149
|
+
"error",
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
pi.on("tool_call", (event) => {
|
|
155
|
+
if (shadowed && event.toolName === "bash") {
|
|
156
|
+
return { block: true, reason: "approval gate is not active (bash registration shadowed)" };
|
|
157
|
+
}
|
|
158
|
+
return undefined;
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
pi.on("user_bash", async (event, ctx) => {
|
|
162
|
+
const shell = shellSettings(pi);
|
|
163
|
+
const guard = commandGuard();
|
|
164
|
+
const command = shell.commandPrefix ? `${shell.commandPrefix}\n${event.command}` : event.command;
|
|
165
|
+
const blocked = guard?.(command);
|
|
166
|
+
if (blocked !== undefined) {
|
|
167
|
+
return {
|
|
168
|
+
result: { output: blocked, exitCode: 1, cancelled: true, truncated: false },
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const reason = dangerReason(command);
|
|
172
|
+
let authorization: ApprovalAuthorization | undefined;
|
|
173
|
+
let request: ApprovalRequest | undefined;
|
|
174
|
+
if (reason !== undefined) {
|
|
175
|
+
const approved = await gate.request(
|
|
176
|
+
{
|
|
177
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
178
|
+
toolCallId: randomUUID(),
|
|
179
|
+
toolName: "user_bash",
|
|
180
|
+
command,
|
|
181
|
+
cwd: event.cwd,
|
|
182
|
+
reason,
|
|
183
|
+
risk: "high",
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
prompt: (promptRequest) => createApprovalPrompt(promptRequest, ctx, promptOptions()),
|
|
187
|
+
},
|
|
188
|
+
);
|
|
189
|
+
if (approved.decision !== "allow_once" || approved.authorization === undefined) {
|
|
190
|
+
return {
|
|
191
|
+
result: {
|
|
192
|
+
output: `Blocked by approval gate (${approved.decision}); command was not executed.`,
|
|
193
|
+
exitCode: 1,
|
|
194
|
+
cancelled: true,
|
|
195
|
+
truncated: false,
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
authorization = approved.authorization;
|
|
200
|
+
request = approved.request;
|
|
201
|
+
} else if (guard === undefined) {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const local = createLocalBashOperations(shell.shellPath === undefined ? undefined : { shellPath: shell.shellPath });
|
|
206
|
+
return {
|
|
207
|
+
operations: {
|
|
208
|
+
async exec(command: string, cwd: string, options: Parameters<typeof local.exec>[2]) {
|
|
209
|
+
const spawnHook = createBashSpawnHook({
|
|
210
|
+
guard,
|
|
211
|
+
authorization,
|
|
212
|
+
request,
|
|
213
|
+
signal: options.signal,
|
|
214
|
+
});
|
|
215
|
+
try {
|
|
216
|
+
const context = spawnHook({ command, cwd, env: options.env ?? process.env });
|
|
217
|
+
return await local.exec(context.command, context.cwd, options);
|
|
218
|
+
} finally {
|
|
219
|
+
authorization?.revoke();
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
pi.on("session_shutdown", () => gate.cancelAll());
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function sameSourceFile(actual: string, expected: string): boolean {
|
|
230
|
+
try {
|
|
231
|
+
return realpathSync(actual) === realpathSync(expected);
|
|
232
|
+
} catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
interface ShellSettings {
|
|
238
|
+
commandPrefix?: string;
|
|
239
|
+
shellPath?: string;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function shellSettings(pi: ExtensionAPI): ShellSettings {
|
|
243
|
+
const raw: unknown = pi.getSettings();
|
|
244
|
+
if (typeof raw !== "object" || raw === null) return {};
|
|
245
|
+
const record = raw as Record<string, unknown>;
|
|
246
|
+
return {
|
|
247
|
+
...(typeof record.shellCommandPrefix === "string" && record.shellCommandPrefix.length > 0
|
|
248
|
+
? { commandPrefix: record.shellCommandPrefix }
|
|
249
|
+
: {}),
|
|
250
|
+
...(typeof record.shellPath === "string" && record.shellPath.length > 0
|
|
251
|
+
? { shellPath: record.shellPath }
|
|
252
|
+
: {}),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function bashOptions(
|
|
257
|
+
shell: ShellSettings,
|
|
258
|
+
spawnHook: (context: BashSpawnContext) => BashSpawnContext,
|
|
259
|
+
): BashToolOptions {
|
|
260
|
+
return {
|
|
261
|
+
spawnHook,
|
|
262
|
+
...(shell.commandPrefix === undefined ? {} : { commandPrefix: shell.commandPrefix }),
|
|
263
|
+
...(shell.shellPath === undefined ? {} : { shellPath: shell.shellPath }),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function numberFlag(
|
|
268
|
+
pi: ExtensionAPI,
|
|
269
|
+
flag: string,
|
|
270
|
+
env: string,
|
|
271
|
+
fallback: number,
|
|
272
|
+
): number {
|
|
273
|
+
const raw = pi.getFlag(flag);
|
|
274
|
+
const value = typeof raw === "string" ? raw : process.env[env];
|
|
275
|
+
if (value === undefined || value === "") return fallback;
|
|
276
|
+
const parsed = Number.parseInt(value, 10);
|
|
277
|
+
if (!Number.isFinite(parsed)) return fallback;
|
|
278
|
+
return Math.min(Math.max(parsed, 1), 2_147_483_647);
|
|
279
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jackice/pi-approval-gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"description": "Dangerous bash approval gate for Pi with final execution-parameter binding.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "jackice",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/jackice/pi-approval-gate.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/jackice/pi-approval-gate/issues"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/jackice/pi-approval-gate#readme",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"pi",
|
|
18
|
+
"pi-coding-agent",
|
|
19
|
+
"extension",
|
|
20
|
+
"approval",
|
|
21
|
+
"bash"
|
|
22
|
+
],
|
|
23
|
+
"main": "./index.ts",
|
|
24
|
+
"types": "./index.ts",
|
|
25
|
+
"pi": {
|
|
26
|
+
"extensions": [
|
|
27
|
+
"./index.ts"
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"index.ts",
|
|
32
|
+
"src",
|
|
33
|
+
"README.md",
|
|
34
|
+
"CHANGELOG.md"
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
38
|
+
"test": "vitest run",
|
|
39
|
+
"prepublishOnly": "pnpm test && pnpm typecheck"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@jackice/pi-ui": "0.4.2"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
46
|
+
"@earendil-works/pi-tui": "*"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
50
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
51
|
+
"@types/node": "^24.0.0",
|
|
52
|
+
"typescript": "^5.9.0",
|
|
53
|
+
"vitest": "^3.2.0"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/bash-hook.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { BashSpawnContext, BashSpawnHook } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import { verifyFinalBinding } from "./binding.ts";
|
|
4
|
+
import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
|
|
5
|
+
|
|
6
|
+
export interface BashGuardOptions {
|
|
7
|
+
/** 返回拦截说明时阻止执行;在消费审批之前运行。 */
|
|
8
|
+
guard?: ((command: string) => string | undefined) | undefined;
|
|
9
|
+
authorization?: ApprovalAuthorization | undefined;
|
|
10
|
+
request?: ApprovalRequest | undefined;
|
|
11
|
+
signal?: AbortSignal | undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 组合命令拦截与最终审批绑定,供 Bash 工具的 spawn hook 使用。
|
|
16
|
+
*/
|
|
17
|
+
export function createBashSpawnHook(options: BashGuardOptions): BashSpawnHook {
|
|
18
|
+
return (context: BashSpawnContext): BashSpawnContext => {
|
|
19
|
+
const blocked = options.guard?.(context.command);
|
|
20
|
+
if (blocked !== undefined) throw new Error(blocked);
|
|
21
|
+
return verifyFinalBinding(options.authorization, options.request, context, options.signal);
|
|
22
|
+
};
|
|
23
|
+
}
|
package/src/binding.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { BashSpawnContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
|
|
4
|
+
import { isDangerousBash } from "./policy.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 在真正 spawn 前校验最终 command/cwd。
|
|
8
|
+
* 危险命令必须消费绑定到本次调用的一次性批准。
|
|
9
|
+
*/
|
|
10
|
+
export function verifyFinalBinding(
|
|
11
|
+
authorization: ApprovalAuthorization | undefined,
|
|
12
|
+
request: ApprovalRequest | undefined,
|
|
13
|
+
context: BashSpawnContext,
|
|
14
|
+
signal?: AbortSignal,
|
|
15
|
+
): BashSpawnContext {
|
|
16
|
+
if (signal?.aborted) throw new Error("aborted");
|
|
17
|
+
if (authorization !== undefined || isDangerousBash(context.command)) {
|
|
18
|
+
const bound = authorization !== undefined
|
|
19
|
+
&& request !== undefined
|
|
20
|
+
&& authorization.consume({
|
|
21
|
+
requestId: request.id,
|
|
22
|
+
sessionId: request.sessionId,
|
|
23
|
+
toolCallId: request.toolCallId,
|
|
24
|
+
command: context.command,
|
|
25
|
+
cwd: context.cwd,
|
|
26
|
+
});
|
|
27
|
+
if (!bound) throw new Error("approval binding mismatch: final command/cwd was not approved");
|
|
28
|
+
}
|
|
29
|
+
return context;
|
|
30
|
+
}
|
package/src/dialog.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { ApprovalView, fromPiTheme } from "@jackice/pi-ui";
|
|
3
|
+
|
|
4
|
+
import type { ApprovalRequest, PromptChoice, PromptHandle } from "./gate.ts";
|
|
5
|
+
import { createNativeApprovalView } from "./native-dialog.ts";
|
|
6
|
+
|
|
7
|
+
export interface ApprovalPromptOptions {
|
|
8
|
+
armMs: number;
|
|
9
|
+
maxCommandLines?: number;
|
|
10
|
+
ui?: "native";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createApprovalPrompt(
|
|
14
|
+
request: ApprovalRequest,
|
|
15
|
+
ctx: ExtensionContext,
|
|
16
|
+
options: ApprovalPromptOptions,
|
|
17
|
+
): PromptHandle {
|
|
18
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || process.env.PI_SUBAGENT_CHILD === "1") {
|
|
19
|
+
return { promise: Promise.resolve("deny"), cancel: () => {} };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const { promise, resolve } = Promise.withResolvers<PromptChoice>();
|
|
23
|
+
let finished = false;
|
|
24
|
+
let doneFn: ((choice: PromptChoice) => void) | undefined;
|
|
25
|
+
let nativeView: ReturnType<typeof createNativeApprovalView> | undefined;
|
|
26
|
+
|
|
27
|
+
const finish = (choice: PromptChoice): void => {
|
|
28
|
+
if (finished) return;
|
|
29
|
+
finished = true;
|
|
30
|
+
resolve(choice);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const custom = ctx.ui.custom<PromptChoice>(
|
|
34
|
+
(tui, theme: Theme, keybindings, done) => {
|
|
35
|
+
doneFn = done;
|
|
36
|
+
const view = options.ui === "native"
|
|
37
|
+
? (nativeView = createNativeApprovalView(request, tui, theme, options.maxCommandLines))
|
|
38
|
+
: new ApprovalView(fromPiTheme(theme), {
|
|
39
|
+
request: {
|
|
40
|
+
toolName: request.toolName,
|
|
41
|
+
command: request.command,
|
|
42
|
+
cwd: request.cwd,
|
|
43
|
+
reason: request.reason,
|
|
44
|
+
risk: request.risk,
|
|
45
|
+
},
|
|
46
|
+
...(options.maxCommandLines === undefined ? {} : { maxCommandLines: options.maxCommandLines }),
|
|
47
|
+
});
|
|
48
|
+
const started = performance.now();
|
|
49
|
+
return {
|
|
50
|
+
capturesViewportInput: true,
|
|
51
|
+
render: (width: number) => view.render(width),
|
|
52
|
+
handleInput: (data: string) => {
|
|
53
|
+
if (finished) return;
|
|
54
|
+
const choice = view.handleInput(data, keybindings);
|
|
55
|
+
if (choice === undefined) {
|
|
56
|
+
tui.requestRender();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (choice === "allow_once" && performance.now() - started < options.armMs) {
|
|
60
|
+
tui.requestRender();
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
done(choice);
|
|
64
|
+
finish(choice);
|
|
65
|
+
},
|
|
66
|
+
invalidate: () => view.invalidate(),
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
blocked: { kind: "permission", message: "bash approval" },
|
|
71
|
+
...(options.ui === "native" ? {
|
|
72
|
+
overlay: true,
|
|
73
|
+
overlayOptions: { width: "90%", maxHeight: "90%", margin: 1 },
|
|
74
|
+
onHandle: (handle) => nativeView?.setOverlayHandle(handle),
|
|
75
|
+
} : {}),
|
|
76
|
+
},
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
custom.then(
|
|
80
|
+
(choice) => finish(choice),
|
|
81
|
+
() => finish("deny"),
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
promise,
|
|
86
|
+
cancel: () => {
|
|
87
|
+
if (finished) return;
|
|
88
|
+
finish("deny");
|
|
89
|
+
try {
|
|
90
|
+
doneFn?.("deny");
|
|
91
|
+
} catch {
|
|
92
|
+
// 组件可能已因 reload/switch 被销毁。
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
package/src/gate.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import type { ApprovalRisk } from "@jackice/pi-ui";
|
|
4
|
+
|
|
5
|
+
export type ApprovalDecision = "allow_once" | "deny" | "timeout" | "cancelled";
|
|
6
|
+
export type PromptChoice = "allow_once" | "deny";
|
|
7
|
+
|
|
8
|
+
export interface ApprovalRequest {
|
|
9
|
+
id: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
toolCallId: string;
|
|
12
|
+
toolName: string;
|
|
13
|
+
command: string;
|
|
14
|
+
cwd: string;
|
|
15
|
+
reason: string;
|
|
16
|
+
risk: ApprovalRisk;
|
|
17
|
+
fingerprint: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ApprovalBinding {
|
|
21
|
+
requestId: string;
|
|
22
|
+
sessionId: string;
|
|
23
|
+
toolCallId: string;
|
|
24
|
+
command: string;
|
|
25
|
+
cwd: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ApprovalAuthorization {
|
|
29
|
+
consume(binding: ApprovalBinding): boolean;
|
|
30
|
+
revoke(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ApprovalResult {
|
|
34
|
+
decision: ApprovalDecision;
|
|
35
|
+
request: ApprovalRequest;
|
|
36
|
+
authorization?: ApprovalAuthorization;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PromptHandle {
|
|
40
|
+
promise: Promise<PromptChoice>;
|
|
41
|
+
cancel: () => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface GateOptions {
|
|
45
|
+
timeoutMs: number | (() => number);
|
|
46
|
+
maxPending: number;
|
|
47
|
+
createId?: () => string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface QueuedRequest {
|
|
51
|
+
request: ApprovalRequest;
|
|
52
|
+
prompt: (request: ApprovalRequest) => PromptHandle;
|
|
53
|
+
resolve: (result: ApprovalResult) => void;
|
|
54
|
+
settled: boolean;
|
|
55
|
+
deadline: number;
|
|
56
|
+
timer: NodeJS.Timeout;
|
|
57
|
+
signal?: AbortSignal;
|
|
58
|
+
onAbort?: () => void;
|
|
59
|
+
cancelPrompt?: () => void;
|
|
60
|
+
authorization?: ApprovalAuthorization;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function fingerprint(command: string, cwd: string): string {
|
|
64
|
+
return crypto.createHash("sha256").update(`${cwd}\0${command}`).digest("hex");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 单写者审批队列。超时/abort/shutdown 都走同一幂等 settle 路径,
|
|
69
|
+
* 不依赖 custom<T> 的 Promise 结算。
|
|
70
|
+
*/
|
|
71
|
+
export class ApprovalGate {
|
|
72
|
+
private readonly timeoutMs: number | (() => number);
|
|
73
|
+
private readonly maxPending: number;
|
|
74
|
+
private readonly createId: () => string;
|
|
75
|
+
private readonly queue: QueuedRequest[] = [];
|
|
76
|
+
private readonly authorizations = new Set<ApprovalAuthorization>();
|
|
77
|
+
private active: QueuedRequest | undefined;
|
|
78
|
+
private closed = false;
|
|
79
|
+
|
|
80
|
+
constructor(options: GateOptions) {
|
|
81
|
+
this.timeoutMs = options.timeoutMs;
|
|
82
|
+
this.maxPending = Math.max(1, options.maxPending);
|
|
83
|
+
this.createId = options.createId ?? (() => crypto.randomUUID());
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
request(
|
|
87
|
+
request: Omit<ApprovalRequest, "id" | "fingerprint">,
|
|
88
|
+
options: { signal?: AbortSignal; prompt: (request: ApprovalRequest) => PromptHandle },
|
|
89
|
+
): Promise<ApprovalResult> {
|
|
90
|
+
if (this.closed) return Promise.resolve({ decision: "deny", request: { ...request, id: "", fingerprint: "" } });
|
|
91
|
+
const pending = this.queue.length + (this.active === undefined ? 0 : 1);
|
|
92
|
+
if (pending >= this.maxPending) {
|
|
93
|
+
return Promise.resolve({ decision: "deny", request: { ...request, id: "", fingerprint: "" } });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const full: ApprovalRequest = {
|
|
97
|
+
...request,
|
|
98
|
+
id: this.createId(),
|
|
99
|
+
fingerprint: fingerprint(request.command, request.cwd),
|
|
100
|
+
};
|
|
101
|
+
const timeoutMs = typeof this.timeoutMs === "function" ? this.timeoutMs() : this.timeoutMs;
|
|
102
|
+
const { promise, resolve } = Promise.withResolvers<ApprovalResult>();
|
|
103
|
+
const entry: QueuedRequest = {
|
|
104
|
+
request: full,
|
|
105
|
+
prompt: options.prompt,
|
|
106
|
+
resolve,
|
|
107
|
+
settled: false,
|
|
108
|
+
deadline: performance.now() + timeoutMs,
|
|
109
|
+
timer: setTimeout(() => this.settle(entry, "timeout"), timeoutMs),
|
|
110
|
+
};
|
|
111
|
+
entry.timer.unref?.();
|
|
112
|
+
if (options.signal !== undefined) {
|
|
113
|
+
entry.signal = options.signal;
|
|
114
|
+
entry.onAbort = () => {
|
|
115
|
+
if (entry.authorization !== undefined) entry.authorization.revoke();
|
|
116
|
+
else this.settle(entry, "cancelled");
|
|
117
|
+
};
|
|
118
|
+
if (options.signal.aborted) {
|
|
119
|
+
this.settle(entry, "cancelled");
|
|
120
|
+
return promise;
|
|
121
|
+
}
|
|
122
|
+
options.signal.addEventListener("abort", entry.onAbort, { once: true });
|
|
123
|
+
}
|
|
124
|
+
this.queue.push(entry);
|
|
125
|
+
this.pump();
|
|
126
|
+
return promise;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
cancelAll(): void {
|
|
130
|
+
this.closed = true;
|
|
131
|
+
for (const authorization of this.authorizations) authorization.revoke();
|
|
132
|
+
const entries = this.active === undefined ? [...this.queue] : [this.active, ...this.queue];
|
|
133
|
+
for (const entry of entries) this.settle(entry, "cancelled", false);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
get pendingCount(): number {
|
|
137
|
+
return this.queue.length + (this.active === undefined ? 0 : 1);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private createAuthorization(entry: QueuedRequest): ApprovalAuthorization {
|
|
141
|
+
let active = true;
|
|
142
|
+
const revoke = (): void => {
|
|
143
|
+
if (!active) return;
|
|
144
|
+
active = false;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
if (entry.signal !== undefined && entry.onAbort !== undefined) {
|
|
147
|
+
entry.signal.removeEventListener("abort", entry.onAbort);
|
|
148
|
+
}
|
|
149
|
+
this.authorizations.delete(authorization);
|
|
150
|
+
};
|
|
151
|
+
const authorization: ApprovalAuthorization = {
|
|
152
|
+
consume: (binding) => {
|
|
153
|
+
const valid = active
|
|
154
|
+
&& !this.closed
|
|
155
|
+
&& entry.signal?.aborted !== true
|
|
156
|
+
&& performance.now() < entry.deadline
|
|
157
|
+
&& binding.requestId === entry.request.id
|
|
158
|
+
&& binding.sessionId === entry.request.sessionId
|
|
159
|
+
&& binding.toolCallId === entry.request.toolCallId
|
|
160
|
+
&& fingerprint(binding.command, binding.cwd) === entry.request.fingerprint;
|
|
161
|
+
revoke();
|
|
162
|
+
return valid;
|
|
163
|
+
},
|
|
164
|
+
revoke,
|
|
165
|
+
};
|
|
166
|
+
const timer = setTimeout(revoke, Math.max(0, entry.deadline - performance.now()));
|
|
167
|
+
timer.unref?.();
|
|
168
|
+
this.authorizations.add(authorization);
|
|
169
|
+
return authorization;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private pump(): void {
|
|
173
|
+
if (this.active !== undefined) return;
|
|
174
|
+
const entry = this.queue.shift();
|
|
175
|
+
if (entry === undefined) return;
|
|
176
|
+
if (entry.settled) {
|
|
177
|
+
this.pump();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this.active = entry;
|
|
181
|
+
let handle: PromptHandle;
|
|
182
|
+
try {
|
|
183
|
+
handle = entry.prompt(entry.request);
|
|
184
|
+
} catch {
|
|
185
|
+
this.settle(entry, "deny");
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
entry.cancelPrompt = handle.cancel;
|
|
189
|
+
void handle.promise.then(
|
|
190
|
+
(choice) => this.settle(entry, choice),
|
|
191
|
+
() => this.settle(entry, "deny"),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private settle(entry: QueuedRequest, decision: ApprovalDecision, pump = true): void {
|
|
196
|
+
if (entry.settled) return;
|
|
197
|
+
if (decision === "allow_once") {
|
|
198
|
+
if (this.closed) decision = "cancelled";
|
|
199
|
+
else if (entry.signal?.aborted) decision = "cancelled";
|
|
200
|
+
else if (performance.now() >= entry.deadline) decision = "timeout";
|
|
201
|
+
}
|
|
202
|
+
entry.settled = true;
|
|
203
|
+
clearTimeout(entry.timer);
|
|
204
|
+
try {
|
|
205
|
+
entry.cancelPrompt?.();
|
|
206
|
+
} catch {
|
|
207
|
+
// 宿主组件可能已销毁;结算不依赖关闭 UI。
|
|
208
|
+
}
|
|
209
|
+
if (this.active === entry) this.active = undefined;
|
|
210
|
+
const index = this.queue.indexOf(entry);
|
|
211
|
+
if (index >= 0) this.queue.splice(index, 1);
|
|
212
|
+
if (decision === "allow_once") {
|
|
213
|
+
entry.authorization = this.createAuthorization(entry);
|
|
214
|
+
} else if (entry.signal !== undefined && entry.onAbort !== undefined) {
|
|
215
|
+
entry.signal.removeEventListener("abort", entry.onAbort);
|
|
216
|
+
}
|
|
217
|
+
entry.resolve({
|
|
218
|
+
decision,
|
|
219
|
+
request: entry.request,
|
|
220
|
+
...(entry.authorization === undefined ? {} : { authorization: entry.authorization }),
|
|
221
|
+
});
|
|
222
|
+
if (pump) this.pump();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Key, SelectList, matchesKey, truncateToWidth, visibleWidth, type OverlayHandle, type TUI } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
import type { ApprovalRequest, PromptChoice } from "./gate.ts";
|
|
5
|
+
|
|
6
|
+
type ApprovalKeys = Parameters<Parameters<ExtensionUIContext["custom"]>[0]>[2];
|
|
7
|
+
|
|
8
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
9
|
+
|
|
10
|
+
export function createNativeApprovalView(
|
|
11
|
+
request: ApprovalRequest,
|
|
12
|
+
tui: TUI,
|
|
13
|
+
theme: Theme,
|
|
14
|
+
maxCommandLines: number | undefined,
|
|
15
|
+
) {
|
|
16
|
+
const selection = new SelectList([
|
|
17
|
+
{ label: "Deny", value: "deny" },
|
|
18
|
+
{ label: "Allow once", value: "allow_once" },
|
|
19
|
+
], 2, {
|
|
20
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
21
|
+
selectedText: (text) => theme.fg("accent", text),
|
|
22
|
+
description: (text) => theme.fg("muted", text),
|
|
23
|
+
scrollInfo: (text) => theme.fg("muted", text),
|
|
24
|
+
noMatch: (text) => theme.fg("muted", text),
|
|
25
|
+
});
|
|
26
|
+
const limit = maxCommandLines !== undefined && Number.isFinite(maxCommandLines) && maxCommandLines >= 1
|
|
27
|
+
? Math.floor(maxCommandLines) : 8;
|
|
28
|
+
const title = `Bash approval · ${escapeControls(request.toolName)}`;
|
|
29
|
+
const risk = `Risk: ${request.risk.toUpperCase()}`;
|
|
30
|
+
const fields = [
|
|
31
|
+
`cwd: ${escapeControls(request.cwd)}`,
|
|
32
|
+
`reason: ${escapeControls(request.reason)}`,
|
|
33
|
+
`command: ${escapeControls(request.command)}`,
|
|
34
|
+
];
|
|
35
|
+
let overlayHandle: OverlayHandle | undefined;
|
|
36
|
+
let lines: string[] = [];
|
|
37
|
+
let lastWidth = 0;
|
|
38
|
+
let offset = 0;
|
|
39
|
+
let pageRows = 1;
|
|
40
|
+
let renderedWidth = 0;
|
|
41
|
+
let renderedRows = 0;
|
|
42
|
+
let renderedContextFits = false;
|
|
43
|
+
|
|
44
|
+
const canAllow = (): boolean => {
|
|
45
|
+
const bounds = overlayHandle?.getBounds();
|
|
46
|
+
const columns = tui.terminal.columns;
|
|
47
|
+
return renderedContextFits
|
|
48
|
+
&& bounds !== undefined
|
|
49
|
+
&& bounds.width === renderedWidth
|
|
50
|
+
&& bounds.height >= renderedRows
|
|
51
|
+
&& bounds.row + bounds.height <= tui.terminal.rows
|
|
52
|
+
&& (columns === undefined || bounds.col + bounds.width <= columns);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
setOverlayHandle(handle: OverlayHandle | undefined): void {
|
|
57
|
+
overlayHandle = handle;
|
|
58
|
+
},
|
|
59
|
+
render(width: number): readonly string[] {
|
|
60
|
+
if (width <= 0) {
|
|
61
|
+
renderedContextFits = false;
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
if (lastWidth !== width) {
|
|
65
|
+
lastWidth = width;
|
|
66
|
+
lines = fields.flatMap((field) => wrapCodeText(field, width));
|
|
67
|
+
}
|
|
68
|
+
pageRows = Math.max(1, Math.min(limit, Math.floor(tui.terminal.rows * 0.75) - 6));
|
|
69
|
+
offset = Math.min(offset, Math.max(0, lines.length - pageRows));
|
|
70
|
+
const end = Math.min(lines.length, offset + pageRows);
|
|
71
|
+
const fullPage = `Page ${offset + 1}-${end}/${lines.length}`;
|
|
72
|
+
const compactRange = `${offset + 1}-${end}/${lines.length}`;
|
|
73
|
+
const currentPage = `${offset + 1}/${lines.length}`;
|
|
74
|
+
const page = visibleWidth(fullPage) <= width
|
|
75
|
+
? fullPage
|
|
76
|
+
: visibleWidth(compactRange) <= width
|
|
77
|
+
? compactRange
|
|
78
|
+
: visibleWidth(currentPage) <= width
|
|
79
|
+
? currentPage
|
|
80
|
+
: String(offset + 1);
|
|
81
|
+
const riskLabel = visibleWidth(risk) <= width
|
|
82
|
+
? risk
|
|
83
|
+
: visibleWidth(`Risk: ${request.risk[0]!.toUpperCase()}`) <= width
|
|
84
|
+
? `Risk: ${request.risk[0]!.toUpperCase()}`
|
|
85
|
+
: request.risk[0]!.toUpperCase();
|
|
86
|
+
const hint = "PgUp/PgDn: scroll · Esc: deny";
|
|
87
|
+
const choices = selection.render(width);
|
|
88
|
+
const output = [
|
|
89
|
+
truncateToWidth(theme.fg("warning", title), width),
|
|
90
|
+
truncateToWidth(theme.fg("warning", riskLabel), width),
|
|
91
|
+
truncateToWidth(theme.fg("muted", page), width),
|
|
92
|
+
...lines.slice(offset, end),
|
|
93
|
+
truncateToWidth(theme.fg("muted", hint), width),
|
|
94
|
+
...choices,
|
|
95
|
+
];
|
|
96
|
+
renderedWidth = width;
|
|
97
|
+
renderedRows = output.length;
|
|
98
|
+
renderedContextFits = [title, riskLabel, page, hint].every((line) => visibleWidth(line) <= width)
|
|
99
|
+
&& choices.length > 0
|
|
100
|
+
&& choices.every((line) => visibleWidth(line) <= width)
|
|
101
|
+
&& choices.some((line) => line.includes("Allow once"));
|
|
102
|
+
return output;
|
|
103
|
+
},
|
|
104
|
+
invalidate(): void {
|
|
105
|
+
lastWidth = 0;
|
|
106
|
+
renderedContextFits = false;
|
|
107
|
+
},
|
|
108
|
+
handleInput(data: string, keys: ApprovalKeys): PromptChoice | undefined {
|
|
109
|
+
if (keys.matches(data, "tui.select.cancel")) return "deny";
|
|
110
|
+
if (keys.matches(data, "tui.select.confirm")) {
|
|
111
|
+
return canAllow() && selection.getSelectedItem()?.value === "allow_once" ? "allow_once" : "deny";
|
|
112
|
+
}
|
|
113
|
+
if (keys.matches(data, "tui.select.up")) selection.setSelectedIndex(0);
|
|
114
|
+
else if (keys.matches(data, "tui.select.down")) selection.setSelectedIndex(1);
|
|
115
|
+
else if (matchesKey(data, Key.pageUp) || keys.matches(data, "tui.select.pageUp")) offset = Math.max(0, offset - pageRows);
|
|
116
|
+
else if (matchesKey(data, Key.pageDown) || keys.matches(data, "tui.select.pageDown")) offset = Math.min(Math.max(0, lines.length - pageRows), offset + pageRows);
|
|
117
|
+
return undefined;
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function wrapCodeText(text: string, width: number): string[] {
|
|
123
|
+
const segments = Array.from(segmenter.segment(text), ({ segment }) => segment);
|
|
124
|
+
if (segments.length === 0) return [""];
|
|
125
|
+
|
|
126
|
+
const lines: string[] = [];
|
|
127
|
+
let index = 0;
|
|
128
|
+
while (index < segments.length) {
|
|
129
|
+
let line = "";
|
|
130
|
+
let usedWidth = 0;
|
|
131
|
+
const first = index;
|
|
132
|
+
while (index < segments.length) {
|
|
133
|
+
const segment = segments[index]!;
|
|
134
|
+
const segmentWidth = visibleWidth(segment);
|
|
135
|
+
const continuation = index + 1 < segments.length;
|
|
136
|
+
const maxWidth = continuation ? Math.max(1, width - 1) : width;
|
|
137
|
+
if (usedWidth + segmentWidth > maxWidth && index > first) break;
|
|
138
|
+
line += segment;
|
|
139
|
+
usedWidth += segmentWidth;
|
|
140
|
+
index++;
|
|
141
|
+
if (usedWidth > maxWidth) break;
|
|
142
|
+
}
|
|
143
|
+
lines.push(index < segments.length ? `${line}>` : line);
|
|
144
|
+
}
|
|
145
|
+
return lines;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function escapeControls(text: string): string {
|
|
149
|
+
return text.replace(/\\|[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Surrogate}]/gv, (char) => {
|
|
150
|
+
if (char === "\\") return "\\\\";
|
|
151
|
+
if (char === "\n") return "\\n";
|
|
152
|
+
if (char === "\r") return "\\r";
|
|
153
|
+
if (char === "\t") return "\\t";
|
|
154
|
+
return `\\u{${char.codePointAt(0)!.toString(16)}}`;
|
|
155
|
+
});
|
|
156
|
+
}
|
package/src/policy.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
const MAX_COMMAND_LENGTH = 8192;
|
|
2
|
+
|
|
3
|
+
const DANGEROUS_COMMANDS = new Set([
|
|
4
|
+
"rm",
|
|
5
|
+
"rmdir",
|
|
6
|
+
"sudo",
|
|
7
|
+
"dd",
|
|
8
|
+
"truncate",
|
|
9
|
+
"kill",
|
|
10
|
+
"killall",
|
|
11
|
+
"pkill",
|
|
12
|
+
"shutdown",
|
|
13
|
+
"reboot",
|
|
14
|
+
"mkfs",
|
|
15
|
+
"fdisk",
|
|
16
|
+
"parted",
|
|
17
|
+
"chmod",
|
|
18
|
+
"chown",
|
|
19
|
+
"chroot",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
|
|
23
|
+
const INTERPRETERS = new Set(["python", "python3", "node", "perl", "ruby", "php", "deno", "bun"]);
|
|
24
|
+
const WRAPPERS = new Set(["command", "exec", "nohup", "builtin"]);
|
|
25
|
+
|
|
26
|
+
const GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"]);
|
|
27
|
+
const GH_VALUE_OPTIONS = new Set(["-R", "--repo", "--hostname", "--config"]);
|
|
28
|
+
|
|
29
|
+
function basename(value: string): string {
|
|
30
|
+
const parts = value.split("/");
|
|
31
|
+
return parts[parts.length - 1] ?? value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 线性、quote-aware 分词;遇到 shell 展开、重定向、未闭合引号时返回 undefined,
|
|
36
|
+
* 调用方按危险命令处理(fail-closed)。
|
|
37
|
+
*/
|
|
38
|
+
function splitSegments(command: string): string[][] | undefined {
|
|
39
|
+
const segments: string[][] = [];
|
|
40
|
+
let current: string[] = [];
|
|
41
|
+
let token = "";
|
|
42
|
+
let started = false;
|
|
43
|
+
let quote: "'" | '"' | null = null;
|
|
44
|
+
let escaped = false;
|
|
45
|
+
|
|
46
|
+
const flushToken = () => {
|
|
47
|
+
if (!started) return;
|
|
48
|
+
current.push(token);
|
|
49
|
+
token = "";
|
|
50
|
+
started = false;
|
|
51
|
+
};
|
|
52
|
+
const flushSegment = () => {
|
|
53
|
+
flushToken();
|
|
54
|
+
if (current.length > 0) segments.push(current);
|
|
55
|
+
current = [];
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
for (let index = 0; index < command.length; index++) {
|
|
59
|
+
const char = command[index] ?? "";
|
|
60
|
+
if (escaped) {
|
|
61
|
+
token += char;
|
|
62
|
+
escaped = false;
|
|
63
|
+
started = true;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (quote === "'") {
|
|
67
|
+
if (char === "'") quote = null;
|
|
68
|
+
else token += char;
|
|
69
|
+
started = true;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (quote === '"') {
|
|
73
|
+
if (char === '"') quote = null;
|
|
74
|
+
else if (char === "\\") escaped = true;
|
|
75
|
+
else if (char === "$" || char === "`") return undefined;
|
|
76
|
+
else token += char;
|
|
77
|
+
started = true;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (char === "\\") {
|
|
81
|
+
escaped = true;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (char === "'" || char === '"') {
|
|
85
|
+
quote = char;
|
|
86
|
+
started = true;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (char === " " || char === "\t") {
|
|
90
|
+
flushToken();
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (char === "\n" || char === ";" || char === "&" || char === "|") {
|
|
94
|
+
flushSegment();
|
|
95
|
+
const next = command[index + 1];
|
|
96
|
+
if (next === char || (char === "&" && next === "&") || (char === "|" && next === "|")) index++;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (char === "(" || char === ")" || char === "{" || char === "}") {
|
|
100
|
+
flushSegment();
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (char === ">" || char === "<" || char === "$" || char === "`" || char === "\0" || char === "\r") {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
token += char;
|
|
107
|
+
started = true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (escaped || quote !== null) return undefined;
|
|
111
|
+
flushSegment();
|
|
112
|
+
return segments;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function analyzeSegment(tokens: string[]): string | undefined {
|
|
116
|
+
let index = 0;
|
|
117
|
+
|
|
118
|
+
while (index < tokens.length) {
|
|
119
|
+
const value = tokens[index] ?? "";
|
|
120
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(value)) {
|
|
121
|
+
index++;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const current = basename(value).toLowerCase();
|
|
125
|
+
if (current === "env") {
|
|
126
|
+
index++;
|
|
127
|
+
while (index < tokens.length) {
|
|
128
|
+
const next = tokens[index] ?? "";
|
|
129
|
+
if (next.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(next)) index++;
|
|
130
|
+
else break;
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (WRAPPERS.has(current)) {
|
|
135
|
+
index++;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (current === "time") {
|
|
139
|
+
index++;
|
|
140
|
+
while (index < tokens.length && (tokens[index] ?? "").startsWith("-")) index++;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (current === "nice" || current === "ionice" || current === "stdbuf" || current === "timeout") {
|
|
144
|
+
index++;
|
|
145
|
+
if (current === "timeout") index++;
|
|
146
|
+
while (index < tokens.length && (tokens[index] ?? "").startsWith("-")) {
|
|
147
|
+
const option = tokens[index] ?? "";
|
|
148
|
+
index++;
|
|
149
|
+
if (["-n", "-P", "-s", "-I", "-o", "-e"].includes(option)) index++;
|
|
150
|
+
}
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (index >= tokens.length) return undefined;
|
|
157
|
+
const command = basename(tokens[index] ?? "").toLowerCase();
|
|
158
|
+
const args = tokens.slice(index + 1);
|
|
159
|
+
|
|
160
|
+
if (command === "rm" || command === "rmdir") return "recursive/forced file removal";
|
|
161
|
+
if (command === "sudo") return "privilege escalation";
|
|
162
|
+
if (command === "source") return "shell sourcing";
|
|
163
|
+
if (DANGEROUS_COMMANDS.has(command)) return `dangerous command: ${command}`;
|
|
164
|
+
|
|
165
|
+
if (SHELLS.has(command)) {
|
|
166
|
+
const codeFlag = args.findIndex((arg) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(arg));
|
|
167
|
+
if (codeFlag >= 0 && args[codeFlag + 1] !== undefined) return analyzeCommand(args[codeFlag + 1] ?? "");
|
|
168
|
+
return `shell execution: ${command}`;
|
|
169
|
+
}
|
|
170
|
+
if (command === "eval") return analyzeCommand(args.join(" "));
|
|
171
|
+
if (command === "xargs") return "xargs execution";
|
|
172
|
+
if (command === "find") {
|
|
173
|
+
if (args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir"].includes(arg))) {
|
|
174
|
+
return "find destructive action";
|
|
175
|
+
}
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
if (command === "git") return analyzeGit(args);
|
|
179
|
+
if (command === "gh" || command === "glab") return analyzeGh(args);
|
|
180
|
+
if (command === "npm" || command === "pnpm" || command === "yarn") {
|
|
181
|
+
if (args.some((arg) => arg === "publish" || arg === "unpublish")) return "package publish";
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
if (command === "kubectl" || command === "helm" || command === "terraform") {
|
|
185
|
+
if (args.some((arg) => arg === "delete" || arg === "destroy" || arg === "uninstall")) {
|
|
186
|
+
return "cluster destructive action";
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
if (command === "docker" || command === "podman") {
|
|
191
|
+
if (args[0] === "rm" || args[0] === "prune" || args[0] === "system") return "container destructive action";
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
if (command === "mv") {
|
|
195
|
+
if (args.some((arg) => arg.startsWith("/dev/"))) return "overwrite device";
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
if (INTERPRETERS.has(command)) return `interpreter execution: ${command}`;
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function analyzeGit(args: string[]): string | undefined {
|
|
203
|
+
let index = 0;
|
|
204
|
+
while (index < args.length) {
|
|
205
|
+
const arg = args[index] ?? "";
|
|
206
|
+
if (arg === "--") {
|
|
207
|
+
index++;
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
if (GIT_VALUE_OPTIONS.has(arg)) {
|
|
211
|
+
index += 2;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (arg.startsWith("-")) {
|
|
215
|
+
index++;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
const sub = (args[index] ?? "").toLowerCase();
|
|
221
|
+
const rest = args.slice(index + 1);
|
|
222
|
+
if (sub === "push") return "remote git write";
|
|
223
|
+
if (sub === "reset" && (rest.includes("--hard") || rest.includes("--merge") || rest.includes("--keep"))) {
|
|
224
|
+
return "git history reset";
|
|
225
|
+
}
|
|
226
|
+
if (sub === "clean" && rest.some((arg) => /^-[a-zA-Z]*f/.test(arg) || arg === "--force")) {
|
|
227
|
+
return "git worktree clean";
|
|
228
|
+
}
|
|
229
|
+
if (sub === "branch" && rest.some((arg) => arg === "-D" || arg === "--delete" || arg === "-d")) {
|
|
230
|
+
return "git branch delete";
|
|
231
|
+
}
|
|
232
|
+
if (sub === "stash" && (rest[0] === "drop" || rest[0] === "clear")) return "git stash delete";
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function analyzeGh(args: string[]): string | undefined {
|
|
237
|
+
let index = 0;
|
|
238
|
+
while (index < args.length) {
|
|
239
|
+
const arg = args[index] ?? "";
|
|
240
|
+
if (GH_VALUE_OPTIONS.has(arg)) {
|
|
241
|
+
index += 2;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (arg.startsWith("-")) {
|
|
245
|
+
index++;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
const scope = (args[index] ?? "").toLowerCase();
|
|
251
|
+
const action = (args[index + 1] ?? "").toLowerCase();
|
|
252
|
+
if (scope === "repo" && ["create", "delete", "rename", "archive", "unarchive", "edit", "set-default", "deploy-key"].includes(action)) {
|
|
253
|
+
return "remote repository write";
|
|
254
|
+
}
|
|
255
|
+
if ((scope === "pr" || scope === "mr") && ["merge", "close"].includes(action)) {
|
|
256
|
+
return "remote pull request write";
|
|
257
|
+
}
|
|
258
|
+
if (scope === "issue" && ["close", "delete"].includes(action)) return "remote issue write";
|
|
259
|
+
if (scope === "secret" && ["set", "delete", "remove"].includes(action)) return "remote secret write";
|
|
260
|
+
if (scope === "variable" && ["set", "delete", "remove"].includes(action)) return "remote variable write";
|
|
261
|
+
if (scope === "release" && ["create", "delete", "edit"].includes(action)) return "remote release write";
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function analyzeCommand(command: string): string | undefined {
|
|
266
|
+
if (command.length > MAX_COMMAND_LENGTH) return "command too long";
|
|
267
|
+
if (/:\(\)\s*\{/.test(command)) return "fork bomb";
|
|
268
|
+
const segments = splitSegments(command);
|
|
269
|
+
if (segments === undefined) return "unparseable command";
|
|
270
|
+
for (const segment of segments) {
|
|
271
|
+
const reason = analyzeSegment(segment);
|
|
272
|
+
if (reason !== undefined) return reason;
|
|
273
|
+
}
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function hasRmInvocation(command: string): boolean {
|
|
278
|
+
return analyzeCommand(command) === "recursive/forced file removal";
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function dangerReason(command: string): string | undefined {
|
|
282
|
+
return analyzeCommand(command);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function isDangerousBash(command: string): boolean {
|
|
286
|
+
return analyzeCommand(command) !== undefined;
|
|
287
|
+
}
|
package/src/uv-guard.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const PIP_MESSAGE = [
|
|
2
|
+
"Error: pip is disabled. Use uv instead:",
|
|
3
|
+
"",
|
|
4
|
+
" To install a package for a script: uv run --with PACKAGE python script.py",
|
|
5
|
+
" To add a dependency to the project: uv add PACKAGE",
|
|
6
|
+
"",
|
|
7
|
+
].join("\n");
|
|
8
|
+
|
|
9
|
+
const PIP3_MESSAGE = PIP_MESSAGE.replace("pip is disabled", "pip3 is disabled");
|
|
10
|
+
|
|
11
|
+
const POETRY_MESSAGE = [
|
|
12
|
+
"Error: poetry is disabled. Use uv instead:",
|
|
13
|
+
"",
|
|
14
|
+
" To initialize a project: uv init",
|
|
15
|
+
" To add a dependency: uv add PACKAGE",
|
|
16
|
+
" To sync dependencies: uv sync",
|
|
17
|
+
" To run commands: uv run COMMAND",
|
|
18
|
+
"",
|
|
19
|
+
].join("\n");
|
|
20
|
+
|
|
21
|
+
const VENV_MESSAGE = [
|
|
22
|
+
"Error: 'python -m venv' is disabled. Use uv instead:",
|
|
23
|
+
"",
|
|
24
|
+
" To create a virtual environment: uv venv",
|
|
25
|
+
"",
|
|
26
|
+
].join("\n");
|
|
27
|
+
|
|
28
|
+
const PY_COMPILE_MESSAGE = [
|
|
29
|
+
"Error: 'python -m py_compile' is disabled because it writes .pyc files to __pycache__.",
|
|
30
|
+
"",
|
|
31
|
+
" To verify syntax without bytecode output: uv run python -m ast path/to/file.py >/dev/null",
|
|
32
|
+
"",
|
|
33
|
+
].join("\n");
|
|
34
|
+
|
|
35
|
+
// 只在命令位置匹配(行首、换行、; && || | 之后),避免 grep/echo 参数误报。
|
|
36
|
+
const SEGMENT_PREFIX = String.raw`(?:^|\n|[;|&]{1,2})\s*(?:\S+\/)?`;
|
|
37
|
+
|
|
38
|
+
const PIP_PATTERN = new RegExp(`${SEGMENT_PREFIX}pip\\s*(?:$|\\s)`, "m");
|
|
39
|
+
const PIP3_PATTERN = new RegExp(`${SEGMENT_PREFIX}pip3\\s*(?:$|\\s)`, "m");
|
|
40
|
+
const POETRY_PATTERN = new RegExp(`${SEGMENT_PREFIX}poetry\\s*(?:$|\\s)`, "m");
|
|
41
|
+
const PYTHON_PREFIX = `${SEGMENT_PREFIX}python(?:3(?:\\.\\d+)?)?\\b[^\\n;|&]*`;
|
|
42
|
+
const PYTHON_PIP_PATTERN = new RegExp(`${PYTHON_PREFIX}(?:\\s-m\\s*pip\\b|\\s-mpip\\b)`, "m");
|
|
43
|
+
const PYTHON_VENV_PATTERN = new RegExp(`${PYTHON_PREFIX}(?:\\s-m\\s*venv\\b|\\s-mvenv\\b)`, "m");
|
|
44
|
+
const PYTHON_PY_COMPILE_PATTERN = new RegExp(`${PYTHON_PREFIX}(?:\\s-m\\s*py_compile\\b|\\s-mpy_compile\\b)`, "m");
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 阻止被禁用的 Python 包管理命令,并提示 uv 等价写法。
|
|
48
|
+
*/
|
|
49
|
+
export function uvGuard(command: string): string | undefined {
|
|
50
|
+
if (PIP_PATTERN.test(command)) return PIP_MESSAGE;
|
|
51
|
+
if (PIP3_PATTERN.test(command)) return PIP3_MESSAGE;
|
|
52
|
+
if (POETRY_PATTERN.test(command)) return POETRY_MESSAGE;
|
|
53
|
+
if (PYTHON_PIP_PATTERN.test(command)) return PIP_MESSAGE.replace("pip is disabled", "'python -m pip' is disabled");
|
|
54
|
+
if (PYTHON_VENV_PATTERN.test(command)) return VENV_MESSAGE;
|
|
55
|
+
if (PYTHON_PY_COMPILE_PATTERN.test(command)) return PY_COMPILE_MESSAGE;
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|