@jackice/pi-approval-gate 0.1.2 → 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 CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3
4
+
5
+ - 内建可选 uv 命令拦截(`--approval-guard uv` 或 `approvalGate.guard: "uv"`),默认关闭。
6
+ - 移除 `guard`/`sourcePath` 宿主复用选项:审批包自己注册 `bash`,不再需要第二个扩展。
7
+
3
8
  ## 0.1.2
4
9
 
5
10
  - 加固原生审批视图:保留软换行空格、转义不可见字符,并在窄屏显示风险与分页状态;视图内容被裁切时拒绝批准。
package/README.md CHANGED
@@ -25,6 +25,7 @@ An approval extension for Pi's supported Bash execution paths. It binds user app
25
25
  --approval-timeout-ms <ms> # Default: 120000; includes time spent in the queue.
26
26
  --approval-arm-ms <ms> # Default: 500; minimum delay before allowing.
27
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.
28
29
  PI_APPROVAL_TIMEOUT_MS
29
30
  PI_APPROVAL_ARM_MS
30
31
  ```
@@ -33,23 +34,15 @@ Pi parses extension flags after loading the extension. Settings are read when ea
33
34
 
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.
35
36
 
36
- ## Reuse from another extension
37
+ ### Optional uv guard
37
38
 
38
- Pi `1.6.0` allows only one `bash` registration per session. When another extension must own that registration (for example a host that already wraps `bash`), pass its options instead of loading this extension twice:
39
+ `--approval-guard uv`, or the same value in settings, blocks Python package-manager commands before any approval dialog and prints the uv equivalent:
39
40
 
40
- ```ts
41
- import approvalGateExtension from "./pi-approval-gate/index.ts";
42
-
43
- export default function (pi) {
44
- approvalGateExtension(pi, {
45
- guard: (command) => (command.startsWith("pip ") ? "use uv instead" : undefined),
46
- sourcePath: fileURLToPath(import.meta.url),
47
- });
48
- }
41
+ ```json
42
+ { "approvalGate": { "guard": "uv" } }
49
43
  ```
50
44
 
51
- - `guard` runs before the approval dialog for both the tool and `user_bash`; a returned message blocks the command.
52
- - `sourcePath` must be the file that registers the tool, otherwise the source check blocks `bash`.
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.
53
46
 
54
47
  ## Verification
55
48
 
package/index.ts CHANGED
@@ -16,20 +16,16 @@ import { createBashSpawnHook } from "./src/bash-hook.ts";
16
16
  import { verifyFinalBinding } from "./src/binding.ts";
17
17
  import { ApprovalGate, type ApprovalAuthorization, type ApprovalRequest } from "./src/gate.ts";
18
18
  import { dangerReason } from "./src/policy.ts";
19
+ import { uvGuard } from "./src/uv-guard.ts";
19
20
 
20
21
  const DEFAULT_TIMEOUT_MS = 120_000;
21
22
  const DEFAULT_ARM_MS = 500;
22
23
  const MAX_PENDING = 16;
23
24
  const MAX_COMMAND_LINES = 8;
24
25
 
25
- export interface ApprovalGateOptions {
26
- /** 返回拦截说明时阻止执行;先于审批对话框。 */
27
- guard?: ((command: string) => string | undefined) | undefined;
28
- /** 实际注册 bash 的扩展文件路径;由其他扩展复用时必须传入。 */
29
- sourcePath?: string | undefined;
30
- }
26
+ type CommandGuard = (command: string) => string | undefined;
31
27
 
32
- export default function approvalGateExtension(pi: ExtensionAPI, config: ApprovalGateOptions = {}): void {
28
+ export default function approvalGateExtension(pi: ExtensionAPI): void {
33
29
  pi.registerFlag("approval-timeout-ms", {
34
30
  description: "Pending bash approval timeout in milliseconds",
35
31
  type: "string",
@@ -42,6 +38,10 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
42
38
  description: "Approval dialog style (native by default; panel optional)",
43
39
  type: "string",
44
40
  });
41
+ pi.registerFlag("approval-guard", {
42
+ description: "Command guard before approval (uv)",
43
+ type: "string",
44
+ });
45
45
 
46
46
  const promptOptions = () => ({
47
47
  armMs: numberFlag(pi, "approval-arm-ms", "PI_APPROVAL_ARM_MS", DEFAULT_ARM_MS),
@@ -49,10 +49,17 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
49
49
  ...(pi.getFlag("approval-ui") === "panel" ? {} : { ui: "native" as const }),
50
50
  });
51
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
+
52
59
  const timeoutMs = () =>
53
60
  numberFlag(pi, "approval-timeout-ms", "PI_APPROVAL_TIMEOUT_MS", DEFAULT_TIMEOUT_MS);
54
61
  const gate = new ApprovalGate({ timeoutMs, maxPending: MAX_PENDING });
55
- const selfPath = config.sourcePath ?? fileURLToPath(import.meta.url);
62
+ const selfPath = fileURLToPath(import.meta.url);
56
63
  let shadowed = false;
57
64
 
58
65
  const template = createBashToolDefinition(process.cwd(), {
@@ -65,8 +72,9 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
65
72
  const command = params.command;
66
73
  const cwd = ctx.cwd;
67
74
  const shell = shellSettings(pi);
75
+ const guard = commandGuard();
68
76
  const finalCommand = shell.commandPrefix ? `${shell.commandPrefix}\n${command}` : command;
69
- const blocked = config.guard?.(finalCommand);
77
+ const blocked = guard?.(finalCommand);
70
78
  if (blocked !== undefined) {
71
79
  return {
72
80
  content: [{ type: "text", text: blocked }],
@@ -113,7 +121,7 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
113
121
  }
114
122
 
115
123
  const options = bashOptions(shell, createBashSpawnHook({
116
- guard: config.guard,
124
+ guard,
117
125
  authorization,
118
126
  request: approvalRequest,
119
127
  signal,
@@ -152,8 +160,9 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
152
160
 
153
161
  pi.on("user_bash", async (event, ctx) => {
154
162
  const shell = shellSettings(pi);
163
+ const guard = commandGuard();
155
164
  const command = shell.commandPrefix ? `${shell.commandPrefix}\n${event.command}` : event.command;
156
- const blocked = config.guard?.(command);
165
+ const blocked = guard?.(command);
157
166
  if (blocked !== undefined) {
158
167
  return {
159
168
  result: { output: blocked, exitCode: 1, cancelled: true, truncated: false },
@@ -189,7 +198,7 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
189
198
  }
190
199
  authorization = approved.authorization;
191
200
  request = approved.request;
192
- } else if (config.guard === undefined) {
201
+ } else if (guard === undefined) {
193
202
  return undefined;
194
203
  }
195
204
 
@@ -198,7 +207,7 @@ export default function approvalGateExtension(pi: ExtensionAPI, config: Approval
198
207
  operations: {
199
208
  async exec(command: string, cwd: string, options: Parameters<typeof local.exec>[2]) {
200
209
  const spawnHook = createBashSpawnHook({
201
- guard: config.guard,
210
+ guard,
202
211
  authorization,
203
212
  request,
204
213
  signal: options.signal,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jackice/pi-approval-gate",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Dangerous bash approval gate for Pi with final execution-parameter binding.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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
+ }