@jackice/pi-approval-gate 0.1.2 → 0.1.4

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,26 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ - English code comments, changelog, and review notes. No behavior change.
6
+
7
+ ## 0.1.3
8
+
9
+ - Built-in optional uv command guard (`--approval-guard uv` or `approvalGate.guard: "uv"`), off by default.
10
+ - Removed the `guard`/`sourcePath` host options: the package registers `bash` itself, so no second extension is needed.
11
+
3
12
  ## 0.1.2
4
13
 
5
- - 加固原生审批视图:保留软换行空格、转义不可见字符,并在窄屏显示风险与分页状态;视图内容被裁切时拒绝批准。
6
- - 原生选择列表成为默认审批 UI,`--approval-ui panel` 可切回面板。
7
- - 新增 `guard` 与 `sourcePath` 选项,允许宿主扩展持有唯一的 `bash` 注册并复用审批;`guard` 在对话框之前拦截。
8
- - 将 `glab mr merge/close` 纳入远端写入审批。
14
+ - Hardened the native approval view: keeps soft-wrap spaces, escapes invisible characters, shows risk and page status on narrow screens, and refuses approval when the view is clipped.
15
+ - The native selection list is now the default approval UI; `--approval-ui panel` switches back to the styled panel.
16
+ - Added `guard` and `sourcePath` options so a host extension can own the single `bash` registration and reuse approval; `guard` ran before the dialog.
17
+ - `glab mr merge/close` now counts as a remote write.
9
18
 
10
19
  ## 0.1.1
11
20
 
12
- - 新增 `--approval-ui native`:用 Pi 原生选择列表回滚新版面板,保留默认拒绝、确认延迟和 Gate 决策。
13
- - 将 `@jackice/pi-ui` 固定为运行时依赖;Pi 省略 peer 安装时仍能加载候选扩展。
14
- - 按真实文件路径验证 `bash` 注册来源,避免符号链接安装误阻断自身工具;无法确认来源时仍拒绝。
15
- - 安全评审 C1/H1/H2/H3 修复:线性 quote-aware 策略、包装命令递归、fail-closed、git/gh 全局选项、fullscreen 分页
16
- - M1/M2/M3/M4/M5 修复:移除超线性正则、继承 shell 前缀、拦截 user_bash、bidi 清洗、影子注册自检
17
- - L1/L3/L4/L6 修复:关闭清理指纹、maxCommandLines 兜底、分页键位、配置 clamp
18
- - 66 个测试;真实 TUI/fullscreen/user_bash/RPC/子代理验证
21
+ - Added `--approval-ui native`: the Pi native selection list replaces the styled panel while keeping default-deny, the arming delay, and Gate decisions.
22
+ - Pinned `@jackice/pi-ui` as a runtime dependency so the candidate extension still loads when Pi omits peer installs.
23
+ - Verify the `bash` registration source by real file path so symlinked installs do not block their own tool; refuse when the source cannot be confirmed.
24
+ - Security review C1/H1/H2/H3: linear quote-aware policy, recursive wrapper parsing, fail-closed behavior, git/gh global options, fullscreen paging.
25
+ - M1/M2/M3/M4/M5: removed the superlinear regex, inherited the shell prefix, intercepted `user_bash`, bidi cleanup, shadow-registration self-check.
26
+ - L1/L3/L4/L6: fingerprint cleanup on close, `maxCommandLines` fallback, paging keys, config clamp.
27
+ - 66 tests; real TUI/fullscreen/user_bash/RPC/subagent verification.
19
28
 
20
29
  ## 0.1.0
21
30
 
22
- - 新增 ApprovalGate:FIFO 队列、120s 超时、abort/shutdown 幂等取消、最多 16 个待请求
23
- - 新增 `bash` 执行边界替换:审批后写入一次性 command+cwd 指纹,spawnHook 消费
24
- - 新增 `ApprovalView` 对话框:完整命令、cwd、reason、风险、Allow once/Deny、滚动、500ms arm
25
- - RPC/headless/子代理默认拒绝
26
- - 真实 Pi RPC 与 `PI_SUBAGENT_CHILD=1` 验证默认拒绝
31
+ - Added ApprovalGate: FIFO queue, 120s timeout, idempotent abort/shutdown cancellation, up to 16 pending requests.
32
+ - Replaced the `bash` execution boundary: after approval a one-shot command+cwd fingerprint is written and consumed by the spawn hook.
33
+ - Added the `ApprovalView` dialog: full command, cwd, reason, risk, Allow once/Deny, scrolling, 500ms arm.
34
+ - RPC/headless/subagent requests are denied by default.
35
+ - Verified default denial on real Pi RPC and with `PI_SUBAGENT_CHILD=1`.
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
+ /** Resolved per call: flags and settings are only readable after the extension loads. */
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.4",
4
4
  "description": "Dangerous bash approval gate for Pi with final execution-parameter binding.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/bash-hook.ts CHANGED
@@ -4,7 +4,7 @@ import { verifyFinalBinding } from "./binding.ts";
4
4
  import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
5
5
 
6
6
  export interface BashGuardOptions {
7
- /** 返回拦截说明时阻止执行;在消费审批之前运行。 */
7
+ /** Returns a message to block the command; runs before the approval is consumed. */
8
8
  guard?: ((command: string) => string | undefined) | undefined;
9
9
  authorization?: ApprovalAuthorization | undefined;
10
10
  request?: ApprovalRequest | undefined;
@@ -12,7 +12,7 @@ export interface BashGuardOptions {
12
12
  }
13
13
 
14
14
  /**
15
- * 组合命令拦截与最终审批绑定,供 Bash 工具的 spawn hook 使用。
15
+ * Combines the command guard with final approval binding for a Bash spawn hook.
16
16
  */
17
17
  export function createBashSpawnHook(options: BashGuardOptions): BashSpawnHook {
18
18
  return (context: BashSpawnContext): BashSpawnContext => {
package/src/binding.ts CHANGED
@@ -4,8 +4,8 @@ import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
4
4
  import { isDangerousBash } from "./policy.ts";
5
5
 
6
6
  /**
7
- * 在真正 spawn 前校验最终 command/cwd。
8
- * 危险命令必须消费绑定到本次调用的一次性批准。
7
+ * Verifies the final command and working directory right before spawn.
8
+ * Dangerous commands must consume an approval bound to this exact call.
9
9
  */
10
10
  export function verifyFinalBinding(
11
11
  authorization: ApprovalAuthorization | undefined,
package/src/dialog.ts CHANGED
@@ -89,7 +89,7 @@ export function createApprovalPrompt(
89
89
  try {
90
90
  doneFn?.("deny");
91
91
  } catch {
92
- // 组件可能已因 reload/switch 被销毁。
92
+ // The host component may already be gone after a reload or session switch.
93
93
  }
94
94
  },
95
95
  };
package/src/gate.ts CHANGED
@@ -65,8 +65,8 @@ export function fingerprint(command: string, cwd: string): string {
65
65
  }
66
66
 
67
67
  /**
68
- * 单写者审批队列。超时/abort/shutdown 都走同一幂等 settle 路径,
69
- * 不依赖 custom<T> 的 Promise 结算。
68
+ * Single-writer approval queue. Timeout, abort, and shutdown share one idempotent
69
+ * settle path and never depend on the custom<T> promise settling.
70
70
  */
71
71
  export class ApprovalGate {
72
72
  private readonly timeoutMs: number | (() => number);
@@ -204,7 +204,7 @@ export class ApprovalGate {
204
204
  try {
205
205
  entry.cancelPrompt?.();
206
206
  } catch {
207
- // 宿主组件可能已销毁;结算不依赖关闭 UI。
207
+ // The host component may be gone; settling must not depend on closing the UI.
208
208
  }
209
209
  if (this.active === entry) this.active = undefined;
210
210
  const index = this.queue.indexOf(entry);
package/src/policy.ts CHANGED
@@ -32,8 +32,8 @@ function basename(value: string): string {
32
32
  }
33
33
 
34
34
  /**
35
- * 线性、quote-aware 分词;遇到 shell 展开、重定向、未闭合引号时返回 undefined,
36
- * 调用方按危险命令处理(fail-closed)。
35
+ * Linear, quote-aware tokenizer. Shell expansion, redirection, or an unclosed quote
36
+ * returns undefined so callers fail closed and treat the command as dangerous.
37
37
  */
38
38
  function splitSegments(command: string): string[][] | undefined {
39
39
  const segments: string[][] = [];
@@ -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
+ // Match only in command position (start, newline, after ; && || |) to avoid grep/echo arguments.
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
+ * Blocks disabled Python package-manager commands and suggests the uv equivalent.
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
+ }