@andares/pi-toolkits 0.9.8 → 0.10.0
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/README.md +34 -5
- package/README.zh-CN.md +35 -5
- package/package.json +2 -1
- package/src/features/permission/audit.test.ts +159 -0
- package/src/features/permission/audit.ts +145 -0
- package/src/features/permission/index.test.ts +138 -3
- package/src/features/permission/index.ts +108 -12
- package/src/features/permission/policy.ts +39 -3
- package/src/index.ts +6 -2
- package/src/lib/approval-log.test.ts +289 -0
- package/src/lib/approval-log.ts +724 -0
- package/src/lib/gates.audit.test.ts +343 -0
- package/src/lib/gates.ts +291 -10
package/README.md
CHANGED
|
@@ -69,7 +69,7 @@ After installing, verify in any pi session:
|
|
|
69
69
|
| Feature | Entry point | One-line description |
|
|
70
70
|
| --- | --- | --- |
|
|
71
71
|
| 🛡️ **ask** read-only consult mode | `/ask` | enter consult mode: `write`/`edit`/`powershell` hard-disabled, `bash` runs in a read-only sandbox, `grep`/`find`/`ls` activated, and `scratchpad` allowed to write throwaway notes into the session's temp directory |
|
|
72
|
-
| 🔐 **permission** session-scoped boundary checks | `/ask-perm` | four in/out × read/write modes, off by default and never persisted; outside writes ask, credentials are denied, destructive commands always ask; composes with `/ask
|
|
72
|
+
| 🔐 **permission** session-scoped boundary checks | `/ask-perm` | four in/out × read/write modes, off by default and never persisted; outside writes ask, credentials are denied, destructive commands always ask; composes with `/ask`; a capped JSONL approval log feeds later rule mining |
|
|
73
73
|
| ⭐ **favorites** model favorites | `ctrl+A` / `ctrl+J` inside `/model` | favorite the models you use most (marked in bold bright yellow), `ctrl+p` cycles only among favorites |
|
|
74
74
|
| 📥 **stash** prompt stash | `ctrl+alt+y` | a stash slot for one prompt: press to swap, press twice to stash and clear the input box |
|
|
75
75
|
| 🔎 **review** third-party code review | `/third-review` | summon the configured review model to check + fix the task just finished, focusing on "is this round's requirement implemented / is anything missing / is anything wrong" |
|
|
@@ -104,7 +104,7 @@ Enter with `/ask` (press it again to exit). Meant for the case where you only wa
|
|
|
104
104
|
|
|
105
105
|
<a name="permission"></a>
|
|
106
106
|
|
|
107
|
-
`/ask-perm` turns on boundary checks for the **current session only**. Every piece of state — the on/off flag, the four modes, the session grants — lives in the extension's memory
|
|
107
|
+
`/ask-perm` turns on boundary checks for the **current session only**. Every piece of state — the on/off flag, the four modes, the session grants — lives in the extension's memory and is never persisted: the feature is off by default and leaves no status behind when disabled. Toggling it on can never silently follow you into the next session. Separately, decisions worth keeping are appended to a capped local **approval log** for later rule mining (see below); it is write-only telemetry and is never consulted while deciding.
|
|
108
108
|
|
|
109
109
|
**Enable**
|
|
110
110
|
|
|
@@ -137,9 +137,36 @@ Repeating the argument form with the modes already in force is a **no-op**: no s
|
|
|
137
137
|
- **credentials are denied in every mode** — `~/.ssh`, `~/.gnupg`, `~/.aws`, `~/.pi/agent/auth*.json`, `.env` files (templates excepted). Without this, `out read = allow` would hand out `~/.ssh/id_rsa`.
|
|
138
138
|
- **destructive commands always ask** — `rm` of `/`, the home directory, or the working directory; `git reset --hard`; `git clean -f`; `git push --force`; package `publish`; `dd` to a raw device; `mkfs*`; shutdown/reboot; `chmod -R 777`; anything through `sudo`. Scope alone cannot express "destructive".
|
|
139
139
|
|
|
140
|
+
**Approval log** (write-only telemetry, on by default)
|
|
141
|
+
|
|
142
|
+
Every decision worth keeping becomes one JSON object per line (JSONL) in `~/.pi/agent/approval-log/audit-NNNNNN.jsonl`. The policy never reads the log: deleting it or making the directory read-only changes no verdict.
|
|
143
|
+
|
|
144
|
+
- **Scope**: blocks from `/ask` mode are approval decisions too, so they are recorded as well (with the gate name and the model-facing reason).
|
|
145
|
+
- **What is recorded**: interactive asks (the exact dialog lines, the bash decomposition, the chosen answer, the grant and its latency), automatic denials and blocks, session-grant allows, `/ask-perm` mode changes, and one `session` summary with call/ask/block counters. Plain mode-allowed `read`/`grep` calls are skipped by default so the ring buffer is not buried in noise; `PI_APPROVAL_LOG=all` also logs plain mode-allowed calls, `PI_APPROVAL_LOG=off` disables the log.
|
|
146
|
+
- **Rotation**: 1000 records **or** 8 MiB per file, at most 10 files; creating an 11th deletes the lowest-numbered one. Typical retention is 15–30 MB (hard ceiling 80 MB) and roughly the last 10,000 records.
|
|
147
|
+
- **Fidelity**: the four modes, session roots, tool call, every command unit (including `opaque` units and parser notes), each target's canonical path / effect / in-or-out scope, the deciding rule layer, the dialog lines, the answer and the resulting grant. `write`/`edit` file **contents are never logged** (only path and byte count); bearer tokens, `token=`/`password=`, URL credentials and known key prefixes are redacted.
|
|
148
|
+
- **Failure and privacy**: directory `0700`, files `0600`, local only, safe to delete at any time. A logging failure is reported once and swallowed — the verdict path never fails because the log is unavailable. `PI_APPROVAL_LOG_DIR` relocates the directory.
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
# focus on the prompts that became session grants
|
|
152
|
+
jq -r 'select(.event=="ask" and .answer.choice=="allow-session")
|
|
153
|
+
| [.ts,.tool,.verdict.target,.input.command] | @tsv' \
|
|
154
|
+
~/.pi/agent/approval-log/*.jsonl
|
|
155
|
+
|
|
156
|
+
# target roots × answers — the shortest path to a "safe temp dir" rule
|
|
157
|
+
jq -r 'select(.event=="ask") | [.verdict.grantRoot,.answer.choice] | @tsv' \
|
|
158
|
+
~/.pi/agent/approval-log/*.jsonl | sort | uniq -c | sort -rn
|
|
159
|
+
|
|
160
|
+
# parser gaps (opaque units) worth teaching units.ts
|
|
161
|
+
jq -r 'select(.event=="ask") | .units[] | select(.opaque) | [.command,.note] | @tsv' \
|
|
162
|
+
~/.pi/agent/approval-log/*.jsonl | sort | uniq -c | sort -rn
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
See the repository's `pnpm approval-report` for a read-only summary (answer mix, target roots, rule candidates, opaque gaps, playwright patterns).
|
|
166
|
+
|
|
140
167
|
**Composition with `/ask`**: the two features are independent gates on one bus. Each answers only its own question — ask: "does this mutate?", permission: "does this cross the boundary?" — and either can block. Ask mode still denies credential reads, and permission still applies while the read-only sandbox is active. Neither feature needs to know the other exists. The one exception is ask's `scratchpad`: that tool is self-jailed (relative names only, one temp directory), so ask marks it while active and permission skips the boundary dialog that would otherwise fire for an "outside write" on every note.
|
|
141
168
|
|
|
142
|
-
**Enable it for every session** (the state itself is never persisted — this is the opt-in):
|
|
169
|
+
**Enable it for every session** (the state itself is never persisted — this is the opt-in; the audit log is independent and on by default):
|
|
143
170
|
|
|
144
171
|
```toml
|
|
145
172
|
# <project>/.pi/autostart.toml, or <agent-dir>/autostart.toml for all projects
|
|
@@ -147,7 +174,7 @@ Repeating the argument form with the modes already in force is a **no-op**: no s
|
|
|
147
174
|
run = ["/ask-perm allow allow allow ask"]
|
|
148
175
|
```
|
|
149
176
|
|
|
150
|
-
> **Implementation notes**: a new session resets the state on `session_start` (a repeated emission for the same session keeps it); the footer shows `perm i:A/A o:A/ask` while on (`A` allow, `a` ask, `D` deny). Subagent sessions start with their own state and do not inherit the parent's mode — when child sessions must be gated too, enable it through the project's autostart file. POSIX hosts (Linux / macOS / WSL) are the tested target; native Windows Git-Bash path spellings are approximated, not verified. bash decomposition uses `shell-quote`; unknown variables expand to a sentinel that makes the unit ask instead of silently becoming an empty path. Added directories are read from pi-add-dir's session entry (`add-dir:state`). Heuristic, not a sandbox: project-internal destructive commands are covered by the fixed table, not by a sandbox. One known blind spot: a *read* command's bare filename operand (`cat notes.txt`) is not collected as a target, so with `out read = ask` only absolute-path-shaped read operands are questioned — reads never write, so the four modes' write side is unaffected.
|
|
177
|
+
> **Implementation notes**: a new session resets the state on `session_start` (a repeated emission for the same session keeps it); the footer shows `perm i:A/A o:A/ask` while on (`A` allow, `a` ask, `D` deny). Subagent sessions start with their own state and do not inherit the parent's mode — when child sessions must be gated too, enable it through the project's autostart file. The approval log is appended by the gate bus (asks/blocks/session summaries) and by the permission gate (mode changes and session-grant allows); the writer is lazy, keeps no state across processes, and never participates in a decision. POSIX hosts (Linux / macOS / WSL) are the tested target; native Windows Git-Bash path spellings are approximated, not verified. bash decomposition uses `shell-quote`; unknown variables expand to a sentinel that makes the unit ask instead of silently becoming an empty path. Added directories are read from pi-add-dir's session entry (`add-dir:state`). Heuristic, not a sandbox: project-internal destructive commands are covered by the fixed table, not by a sandbox. One known blind spot: a *read* command's bare filename operand (`cat notes.txt`) is not collected as a target, so with `out read = ask` only absolute-path-shaped read operands are questioned — reads never write, so the four modes' write side is unaffected.
|
|
151
178
|
|
|
152
179
|
---
|
|
153
180
|
|
|
@@ -353,6 +380,7 @@ pnpm test # vitest (all feature unit tests)
|
|
|
353
380
|
|
|
354
381
|
pnpm check:keybindings # audit this plugin's keys against the host's own dispatch table
|
|
355
382
|
pnpm check:compat # mandatory 4-line window + backward probe (4 more lines) → public floor
|
|
383
|
+
pnpm approval-report # summarize the local approval log (answer mix, targets, rule candidates)
|
|
356
384
|
```
|
|
357
385
|
|
|
358
386
|
### Project structure
|
|
@@ -363,6 +391,7 @@ src/
|
|
|
363
391
|
├── lib/ # shared infrastructure (tool-set snapshot/restore,
|
|
364
392
|
│ # gate bus composing tool_call policies, jailed-tool
|
|
365
393
|
│ # registry the boundary gate consults,
|
|
394
|
+
│ # rolling JSONL approval log,
|
|
366
395
|
│ # model-key resolution shared by review & compact)
|
|
367
396
|
└── features/ # feature modules — one directory per feature
|
|
368
397
|
├── ask/ # ask mode: command + state machine, bash sandbox,
|
|
@@ -377,7 +406,7 @@ src/
|
|
|
377
406
|
│ # persisted store, tests
|
|
378
407
|
├── permission/ # session-scoped boundary permission: modes, panel,
|
|
379
408
|
│ # bash units, policy, session grants, prompt,
|
|
380
|
-
│ # tests
|
|
409
|
+
│ # audit payload, tests
|
|
381
410
|
├── review/ # third-party review: input/command triggers,
|
|
382
411
|
│ # review-model config store, prompt, tests
|
|
383
412
|
└── stash/ # prompt stash: hotkey state machine + tests
|
package/README.zh-CN.md
CHANGED
|
@@ -69,7 +69,7 @@ pi -e ./src/index.ts
|
|
|
69
69
|
| 功能 | 入口 | 一句话说明 |
|
|
70
70
|
| --- | --- | --- |
|
|
71
71
|
| 🛡️ **ask** 只读咨询模式 | `/ask` | 进入咨询模式:`write`/`edit`/`powershell` 硬禁用,`bash` 只读沙箱,临时启用 `grep`/`find`/`ls`,并开放 `scratchpad` 把草稿写进会话临时目录 |
|
|
72
|
-
| 🔐 **permission** 会话级边界权限 | `/ask-perm` | 项目内/外 × 读/写四格模式,默认关闭且从不落盘;项目外写询问、凭据路径硬拒、破坏性命令必问;与 `/ask`
|
|
72
|
+
| 🔐 **permission** 会话级边界权限 | `/ask-perm` | 项目内/外 × 读/写四格模式,默认关闭且从不落盘;项目外写询问、凭据路径硬拒、破坏性命令必问;与 `/ask` 并行组合;另有滚动 JSONL 审批日志供事后挖规则 |
|
|
73
73
|
| ⭐ **favorites** 模型收藏 | `/model` 内 `ctrl+A` / `ctrl+J` | 收藏常用模型(加粗亮黄标记),`ctrl+p` 仅在收藏间循环 |
|
|
74
74
|
| 📥 **stash** 提示词暂存 | `ctrl+alt+y` | 一段提示词的暂存槽,按键交换 / 连按两次暂存并清空输入框 |
|
|
75
75
|
| 🔎 **review** 第三方代码评审 | `/third-review` | 召唤配置的评审模型,对刚完成的任务做查+修,重点检查「本轮需求实现 / 是否有遗漏 / 是否有错误」 |
|
|
@@ -104,7 +104,7 @@ pi -e ./src/index.ts
|
|
|
104
104
|
|
|
105
105
|
<a name="permission"></a>
|
|
106
106
|
|
|
107
|
-
`/ask-perm`
|
|
107
|
+
`/ask-perm` 只在**当前会话**开启边界检查。开关状态、四项模式、会话授权全部只存在扩展内存里:权限**状态**不落盘、默认关闭、关闭后不留任何状态。开启一次不会悄悄跟到下一个会话。另外,值得留档的判定会追加到本地**审批日志**(见下),供事后挖规则用;它是只写的遥测数据,判定时永远不会被读取。
|
|
108
108
|
|
|
109
109
|
**开启**
|
|
110
110
|
|
|
@@ -137,9 +137,36 @@ pi -e ./src/index.ts
|
|
|
137
137
|
- **凭据路径任何模式都拒绝** —— `~/.ssh`、`~/.gnupg`、`~/.aws`、`~/.pi/agent/auth*.json`、`.env` 文件(模板除外)。没有这一条,默认的「项目外读放行」就等于把 `~/.ssh/id_rsa` 交出去
|
|
138
138
|
- **破坏性命令永远询问** —— 对 `/`、家目录或工作目录的 `rm`;`git reset --hard`;`git clean -f`;`git push --force`;包 `publish`;`dd` 写裸设备;`mkfs*`;关机/重启;`chmod -R 777`;任何经 `sudo` 的命令。作用域本身表达不了「破坏性」
|
|
139
139
|
|
|
140
|
+
**审批日志**(只写遥测,默认开启)
|
|
141
|
+
|
|
142
|
+
每个值得留档的判定都会写成一行 JSON(JSONL),落在 `~/.pi/agent/approval-log/audit-NNNNNN.jsonl`。策略层从不读它:删掉日志或把目录改成只读,不会改变任何判定结果。
|
|
143
|
+
|
|
144
|
+
- **范围**:`/ask` 模式的拦截同样算审批决定,也会记录(带闸门名与模型可见理由)。
|
|
145
|
+
- **记录什么**:交互弹窗(用户看到的原始行、bash 拆解结果、答复、授权与决策耗时)、自动拒绝/拦截、会话授权放行、`/ask-perm` 模式切换,以及每个会话一条 `session` 摘要(调用/弹窗/拦截计数)。普通自动放行的 `read`/`grep` 默认不记,避免把环形缓冲淹在噪声里;`PI_APPROVAL_LOG=all` 连普通自动放行也记,`PI_APPROVAL_LOG=off` 关闭日志。
|
|
146
|
+
- **滚动**:每文件 1000 条**或** 8 MiB,最多 10 个文件;创建第 11 个时删掉序号最小的那个。典型体积 15–30 MB(硬上限 80 MB),约保留最近 1 万条判定。
|
|
147
|
+
- **保真度**:四格模式、会话根目录、工具调用、每个命令单元(含 `opaque` 单元与解析器备注)、每个目标规范化后的路径/读或写/项目内或外、命中哪条规则层、弹窗原文、答复与产生的授权。`write`/`edit` 的文件**正文永不记录**(只记路径与字节数);bearer token、`token=`/`password=`、URL 内嵌凭据与已知密钥前缀会脱敏。
|
|
148
|
+
- **失败与隐私**:目录 `0700`、文件 `0600`,只在本机,可随时删除。日志故障只警告一次并被吞掉——判定链路不会因为日志不可用而失败。`PI_APPROVAL_LOG_DIR` 可改目录。
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
# 只看"本会话允许"的弹窗
|
|
152
|
+
jq -r 'select(.event=="ask" and .answer.choice=="allow-session")
|
|
153
|
+
| [.ts,.tool,.verdict.target,.input.command] | @tsv' \
|
|
154
|
+
~/.pi/agent/approval-log/*.jsonl
|
|
155
|
+
|
|
156
|
+
# 目标根目录 × 答复 —— 找「临时目录直接放行」规则的最短路径
|
|
157
|
+
jq -r 'select(.event=="ask") | [.verdict.grantRoot,.answer.choice] | @tsv' \
|
|
158
|
+
~/.pi/agent/approval-log/*.jsonl | sort | uniq -c | sort -rn
|
|
159
|
+
|
|
160
|
+
# 解析不了的单元:定位 units.ts 的缺口
|
|
161
|
+
jq -r 'select(.event=="ask") | .units[] | select(.opaque) | [.command,.note] | @tsv' \
|
|
162
|
+
~/.pi/agent/approval-log/*.jsonl | sort | uniq -c | sort -rn
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
仓库内可用 `pnpm approval-report` 生成只读汇总(答复分布、目标根目录、候选规则、opaque 缺口、playwright 模式)。
|
|
166
|
+
|
|
140
167
|
**与 `/ask` 的组合**:两者是同一总线上的独立闸门,各自只回答自己的问题 —— ask 回答「会不会产生变更」,permission 回答「有没有越过边界」,任一拦截都生效。所以 ask 模式下凭据仍然读不到,permission 在只读沙箱下也照常工作;两个功能互不需要知道对方存在。
|
|
141
168
|
|
|
142
|
-
**每个会话自动开启**(
|
|
169
|
+
**每个会话自动开启**(状态本身不落盘,这就是持久化的替身;审批日志独立于它、默认开启):
|
|
143
170
|
|
|
144
171
|
```toml
|
|
145
172
|
# <项目>/.pi/autostart.toml;想对所有项目生效则用 <agent-dir>/autostart.toml
|
|
@@ -147,7 +174,7 @@ pi -e ./src/index.ts
|
|
|
147
174
|
run = ["/ask-perm allow allow allow ask"]
|
|
148
175
|
```
|
|
149
176
|
|
|
150
|
-
> **实现说明**:新会话在 `session_start` 重置状态(同一会话的重复 emission 保持状态);开启时 footer 显示 `perm i:A/A o:A/ask`(`A` allow、`a` ask、`D` deny)。子代理会话有自己的状态、不继承父会话的模式;需要子会话也受控时,通过项目 autostart
|
|
177
|
+
> **实现说明**:新会话在 `session_start` 重置状态(同一会话的重复 emission 保持状态);开启时 footer 显示 `perm i:A/A o:A/ask`(`A` allow、`a` ask、`D` deny)。子代理会话有自己的状态、不继承父会话的模式;需要子会话也受控时,通过项目 autostart 再开启一次。审批日志由闸门总线(弹窗/拦截/会话摘要)与 permission 闸门(模式切换、会话授权放行)追加;写入器懒初始化、不跨进程保存状态,也从不参与判定。实测目标是 POSIX 宿主(Linux/macOS/WSL);原生 Windows Git-Bash 的路径拼写只做了近似,未验证。bash 拆解使用 `shell-quote`;未知变量会展开成哨兵而不是空字符串,使该命令转为询问而不是被悄悄当成空路径。add-dir 目录从 pi-add-dir 的会话条目 `add-dir:state` 读取。启发式,不是沙箱:项目内的破坏性操作由固定表兜底,而不是靠沙箱。已知盲区一处:**读命令的裸文件名参数**(`cat notes.txt`)不被收集为目标,所以把 `out read` 调成 `ask` 时只有绝对路径形状的读目标会被问——读本身不会写,四格模式的写侧不受影响。
|
|
151
178
|
|
|
152
179
|
---
|
|
153
180
|
|
|
@@ -353,6 +380,7 @@ pnpm test # vitest(全部功能单元测试)
|
|
|
353
380
|
|
|
354
381
|
pnpm check:keybindings # 用宿主自己的分发表审计本插件的按键
|
|
355
382
|
pnpm check:compat # 校验声明的 pi 下限:强制 4 条线窗口 + 向后 4 条线探针 → public floor
|
|
383
|
+
pnpm approval-report # 汇总本地审批日志(答复分布、目标目录、候选规则)
|
|
356
384
|
```
|
|
357
385
|
|
|
358
386
|
### 项目结构
|
|
@@ -363,6 +391,7 @@ src/
|
|
|
363
391
|
├── lib/ # 共享基础设施(工具集快照/恢复、
|
|
364
392
|
│ # 组合 tool_call 策略的闸门总线、
|
|
365
393
|
│ # 边界闸门会查询的自封闭工具登记表、
|
|
394
|
+
│ # 滚动 JSONL 审批日志、
|
|
366
395
|
│ # review 与 compact 共用的模型 key 解析)
|
|
367
396
|
└── features/ # 功能模块 —— 一个功能一个目录
|
|
368
397
|
├── ask/ # ask 模式:命令 + 状态机、bash 沙箱、
|
|
@@ -375,7 +404,8 @@ src/
|
|
|
375
404
|
├── favorites/ # 模型收藏:选择器与循环 patch、
|
|
376
405
|
│ # 持久化存储、测试
|
|
377
406
|
├── permission/ # 会话级边界权限:模式、面板、bash 拆解、
|
|
378
|
-
│ #
|
|
407
|
+
│ # 策略、会话授权、确认对话框、
|
|
408
|
+
│ # 审计 payload、测试
|
|
379
409
|
├── review/ # 第三方评审:输入/指令触发、
|
|
380
410
|
│ # 评审模型配置存储、提示词、测试
|
|
381
411
|
└── stash/ # 提示词暂存:热键状态机 + 测试
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andares/pi-toolkits",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Integrated toolkit extension for pi — ask mode (read-only Q&A), session-scoped permission checks, model favorites, prompt stash, third-party code review, session autostart, and a dedicated compaction model",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
"test": "vitest run",
|
|
62
62
|
"check:keybindings": "node ./scripts/check-keybindings.mjs",
|
|
63
63
|
"check:compat": "node ./scripts/check-compat.mjs",
|
|
64
|
+
"approval-report": "node ./scripts/approval-report.mjs",
|
|
64
65
|
"release:github": "node ./scripts/release-github.mjs",
|
|
65
66
|
"release": "node ./scripts/publish.mjs",
|
|
66
67
|
"tag-current": "node ./scripts/tag-current.mjs"
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission audit payload: the decomposition, the scope/effect of every
|
|
3
|
+
* target, and the machine-readable rule layer must survive into the log.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdtempSync, realpathSync } from "node:fs";
|
|
6
|
+
import { homedir, tmpdir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { describe, expect, it } from "vitest";
|
|
9
|
+
import { buildPermissionAudit, commandDigest } from "./audit.js";
|
|
10
|
+
import { DEFAULT_MODES, type PermissionModes } from "./constants.js";
|
|
11
|
+
import { canonicalize } from "./paths.js";
|
|
12
|
+
import {
|
|
13
|
+
decideProgram,
|
|
14
|
+
decideUnit,
|
|
15
|
+
type PolicyContext,
|
|
16
|
+
} from "./policy.js";
|
|
17
|
+
import { SessionRules } from "./session-rules.js";
|
|
18
|
+
import { parseCommandUnits } from "./units.js";
|
|
19
|
+
|
|
20
|
+
function project(): string {
|
|
21
|
+
return realpathSync(mkdtempSync(join(tmpdir(), "pi-perm-audit-")));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function makeContext(
|
|
25
|
+
cwd: string,
|
|
26
|
+
modes: PermissionModes = DEFAULT_MODES,
|
|
27
|
+
rules = new SessionRules(),
|
|
28
|
+
): PolicyContext {
|
|
29
|
+
return { modes, roots: [canonicalize(cwd)], rules };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function audit(command: string, ctx: PolicyContext, prompt?: readonly string[]) {
|
|
33
|
+
const units = parseCommandUnits(command, ctx.roots[0] ?? "/");
|
|
34
|
+
return buildPermissionAudit({
|
|
35
|
+
cwd: ctx.roots[0] ?? "/",
|
|
36
|
+
modes: ctx.modes,
|
|
37
|
+
roots: ctx.roots,
|
|
38
|
+
units,
|
|
39
|
+
unitDecisions: units.map((unit) => decideUnit(unit, ctx)),
|
|
40
|
+
decision: decideProgram(units, ctx),
|
|
41
|
+
...(prompt === undefined ? {} : { prompt }),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe("permission audit payload", () => {
|
|
46
|
+
it("records the decomposition, target scope and deciding layer", () => {
|
|
47
|
+
const cwd = project();
|
|
48
|
+
const payload = audit("rm -rf /tmp/outside/x", makeContext(cwd));
|
|
49
|
+
|
|
50
|
+
expect(payload.modes).toEqual({
|
|
51
|
+
inRead: "allow",
|
|
52
|
+
inWrite: "allow",
|
|
53
|
+
outRead: "allow",
|
|
54
|
+
outWrite: "ask",
|
|
55
|
+
});
|
|
56
|
+
expect(payload.roots).toEqual([canonicalize(cwd)]);
|
|
57
|
+
expect(payload.units).toEqual([
|
|
58
|
+
expect.objectContaining({
|
|
59
|
+
head: "rm",
|
|
60
|
+
command: "rm",
|
|
61
|
+
args: ["-rf", "/tmp/outside/x"],
|
|
62
|
+
base: canonicalize(cwd),
|
|
63
|
+
effect: "write",
|
|
64
|
+
opaque: false,
|
|
65
|
+
action: "ask",
|
|
66
|
+
layer: "mode",
|
|
67
|
+
targets: [
|
|
68
|
+
{
|
|
69
|
+
path: "/tmp/outside/x",
|
|
70
|
+
canonical: "/tmp/outside/x",
|
|
71
|
+
effect: "write",
|
|
72
|
+
source: "operand",
|
|
73
|
+
scope: "out",
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
}),
|
|
77
|
+
]);
|
|
78
|
+
expect(payload.verdict).toMatchObject({
|
|
79
|
+
action: "ask",
|
|
80
|
+
layer: "mode",
|
|
81
|
+
unit: 0,
|
|
82
|
+
target: "/tmp/outside/x",
|
|
83
|
+
effect: "write",
|
|
84
|
+
scope: "out",
|
|
85
|
+
grantScope: "root",
|
|
86
|
+
grantRoot: "/tmp/outside",
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("keeps the secret-table layer for a denied credential read", () => {
|
|
91
|
+
const cwd = project();
|
|
92
|
+
const payload = audit(`cat ${homedir()}/.ssh/id_rsa`, makeContext(cwd));
|
|
93
|
+
expect(payload.verdict).toMatchObject({
|
|
94
|
+
action: "deny",
|
|
95
|
+
layer: "secret",
|
|
96
|
+
scope: "out",
|
|
97
|
+
effect: "read",
|
|
98
|
+
});
|
|
99
|
+
expect(String((payload.verdict as Record<string, unknown>).reason)).toContain(
|
|
100
|
+
"fixed safety table",
|
|
101
|
+
);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("marks an opaque command and records a command-scoped grant", () => {
|
|
105
|
+
const cwd = project();
|
|
106
|
+
const command = 'git -C "$DIR" log';
|
|
107
|
+
const ctx = makeContext(cwd);
|
|
108
|
+
const units = parseCommandUnits(command, cwd);
|
|
109
|
+
const payload = audit(command, ctx);
|
|
110
|
+
|
|
111
|
+
expect(units[0]?.opaque).toBe(true);
|
|
112
|
+
expect((payload.units as Array<Record<string, unknown>>)[0]).toMatchObject({
|
|
113
|
+
opaque: true,
|
|
114
|
+
action: "ask",
|
|
115
|
+
layer: "opaque",
|
|
116
|
+
});
|
|
117
|
+
expect(payload.verdict).toMatchObject({
|
|
118
|
+
action: "ask",
|
|
119
|
+
layer: "opaque",
|
|
120
|
+
grantScope: "command",
|
|
121
|
+
grantDigest: commandDigest(units),
|
|
122
|
+
});
|
|
123
|
+
expect(
|
|
124
|
+
(payload.verdict as Record<string, unknown>).grantRoot,
|
|
125
|
+
).toBeUndefined();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("records an in-project mode allow with its layer", () => {
|
|
129
|
+
const cwd = project();
|
|
130
|
+
const payload = audit(`rm -rf ${cwd}/build`, makeContext(cwd));
|
|
131
|
+
expect(payload.verdict).toMatchObject({
|
|
132
|
+
action: "allow",
|
|
133
|
+
layer: "mode",
|
|
134
|
+
scope: "in",
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("carries the exact prompt lines when asked", () => {
|
|
139
|
+
const cwd = project();
|
|
140
|
+
const payload = audit("rm -rf /tmp/outside/x", makeContext(cwd), [
|
|
141
|
+
"Permission required",
|
|
142
|
+
"Command: rm -rf /tmp/outside/x",
|
|
143
|
+
]);
|
|
144
|
+
expect(payload.prompt).toEqual([
|
|
145
|
+
"Permission required",
|
|
146
|
+
"Command: rm -rf /tmp/outside/x",
|
|
147
|
+
]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("clips long arguments but keeps the target", () => {
|
|
151
|
+
const cwd = project();
|
|
152
|
+
const longArg = `--flag=${"x".repeat(2000)}`;
|
|
153
|
+
const payload = audit(`rm -rf /tmp/outside/x ${longArg}`, makeContext(cwd));
|
|
154
|
+
const unit = (payload.units as Array<Record<string, unknown>>)[0];
|
|
155
|
+
const args = unit.args as string[];
|
|
156
|
+
expect(args[2]).toContain("[+");
|
|
157
|
+
expect(unit.targets).toHaveLength(1);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* permission feature — the audit payload.
|
|
3
|
+
*
|
|
4
|
+
* The gate bus owns the record envelope (session, tool call, answer, outcome);
|
|
5
|
+
* this module contributes the part only the permission layer knows: the four
|
|
6
|
+
* modes and session roots in force, the bash decomposition, and which rule
|
|
7
|
+
* produced the verdict.
|
|
8
|
+
*
|
|
9
|
+
* The payload is deliberately lossless for *policy analysis* — every unit and
|
|
10
|
+
* every target survives, including the parser's `opaque` note — while being
|
|
11
|
+
* bounded: units, targets, args and long strings are capped, and the final
|
|
12
|
+
* serializer drops detail with a visible `truncated` marker rather than
|
|
13
|
+
* silently cutting a field. File contents never enter this payload.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import type { ApprovalRecord } from "../../lib/approval-log.js";
|
|
17
|
+
import { clipText } from "../../lib/approval-log.js";
|
|
18
|
+
import type { PermissionModes } from "./constants.js";
|
|
19
|
+
import { canonicalize, insideAnyRoot } from "./paths.js";
|
|
20
|
+
import {
|
|
21
|
+
decisionGrantRoot,
|
|
22
|
+
type PolicyDecision,
|
|
23
|
+
} from "./policy.js";
|
|
24
|
+
import type { CommandUnit } from "./units.js";
|
|
25
|
+
|
|
26
|
+
const MAX_UNITS = 32;
|
|
27
|
+
const MAX_TARGETS = 32;
|
|
28
|
+
const MAX_ARGS = 64;
|
|
29
|
+
const ARG_CHARS = 512;
|
|
30
|
+
const RAW_CHARS = 8192;
|
|
31
|
+
const PATH_CHARS = 1024;
|
|
32
|
+
const NOTE_CHARS = 512;
|
|
33
|
+
const REASON_CHARS = 2048;
|
|
34
|
+
|
|
35
|
+
export interface PermissionAuditInput {
|
|
36
|
+
readonly cwd: string;
|
|
37
|
+
readonly modes: PermissionModes;
|
|
38
|
+
/** Canonical session roots (working directory plus added directories). */
|
|
39
|
+
readonly roots: readonly string[];
|
|
40
|
+
readonly units: readonly CommandUnit[];
|
|
41
|
+
/** Verdict for each unit, in the same order as {@link units}. */
|
|
42
|
+
readonly unitDecisions: readonly PolicyDecision[];
|
|
43
|
+
/** Aggregate verdict (the strictest unit wins). */
|
|
44
|
+
readonly decision: PolicyDecision;
|
|
45
|
+
/** Exact dialog lines, when this payload belongs to an ask. */
|
|
46
|
+
readonly prompt?: readonly string[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Short digest of the command text, for grouping opaque grants. */
|
|
50
|
+
export function commandDigest(units: readonly CommandUnit[]): string {
|
|
51
|
+
return createHash("sha256")
|
|
52
|
+
.update(units.map((unit) => unit.raw).join(" ; "))
|
|
53
|
+
.digest("hex")
|
|
54
|
+
.slice(0, 16);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function serializeUnit(
|
|
58
|
+
unit: CommandUnit,
|
|
59
|
+
decision: PolicyDecision | undefined,
|
|
60
|
+
roots: readonly string[],
|
|
61
|
+
): ApprovalRecord {
|
|
62
|
+
const targets = unit.targets.slice(0, MAX_TARGETS).map((target) => {
|
|
63
|
+
const canonical = canonicalize(target.path);
|
|
64
|
+
return {
|
|
65
|
+
path: clipText(target.path, PATH_CHARS),
|
|
66
|
+
canonical: clipText(canonical, PATH_CHARS),
|
|
67
|
+
effect: target.effect,
|
|
68
|
+
source: target.source,
|
|
69
|
+
scope: insideAnyRoot(roots, canonical) ? "in" : "out",
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
return {
|
|
73
|
+
raw: clipText(unit.raw, RAW_CHARS),
|
|
74
|
+
head: unit.headWord,
|
|
75
|
+
command: unit.command,
|
|
76
|
+
args: unit.args.slice(0, MAX_ARGS).map((arg) => clipText(arg, ARG_CHARS)),
|
|
77
|
+
base: unit.base === null ? null : clipText(canonicalize(unit.base), PATH_CHARS),
|
|
78
|
+
effect: unit.effect,
|
|
79
|
+
opaque: unit.opaque,
|
|
80
|
+
...(unit.note === undefined ? {} : { note: clipText(unit.note, NOTE_CHARS) }),
|
|
81
|
+
...(decision === undefined
|
|
82
|
+
? {}
|
|
83
|
+
: { action: decision.action, layer: decision.layer }),
|
|
84
|
+
targets,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function serializeVerdict(
|
|
89
|
+
input: PermissionAuditInput,
|
|
90
|
+
): ApprovalRecord {
|
|
91
|
+
const decision = input.decision;
|
|
92
|
+
const unitIndex = input.units.indexOf(decision.unit);
|
|
93
|
+
const target = decision.target;
|
|
94
|
+
const grantScope = decision.unit.opaque ? "command" : "root";
|
|
95
|
+
return {
|
|
96
|
+
action: decision.action,
|
|
97
|
+
layer: decision.layer,
|
|
98
|
+
...(unitIndex < 0 ? {} : { unit: unitIndex }),
|
|
99
|
+
...(target === undefined
|
|
100
|
+
? {}
|
|
101
|
+
: {
|
|
102
|
+
target: clipText(target.path, PATH_CHARS),
|
|
103
|
+
effect: target.effect,
|
|
104
|
+
scope: target.scope,
|
|
105
|
+
}),
|
|
106
|
+
grantScope,
|
|
107
|
+
...(grantScope === "root"
|
|
108
|
+
? {
|
|
109
|
+
grantRoot: clipText(
|
|
110
|
+
decisionGrantRoot(decision, () => input.cwd),
|
|
111
|
+
PATH_CHARS,
|
|
112
|
+
),
|
|
113
|
+
}
|
|
114
|
+
: { grantDigest: commandDigest(input.units) }),
|
|
115
|
+
...(decision.reason === undefined
|
|
116
|
+
? {}
|
|
117
|
+
: { reason: clipText(decision.reason, REASON_CHARS) }),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Structured audit fields for one permission decision. */
|
|
122
|
+
export function buildPermissionAudit(
|
|
123
|
+
input: PermissionAuditInput,
|
|
124
|
+
): ApprovalRecord {
|
|
125
|
+
const unitDecisions = input.unitDecisions;
|
|
126
|
+
return {
|
|
127
|
+
modes: {
|
|
128
|
+
inRead: input.modes.inRead,
|
|
129
|
+
inWrite: input.modes.inWrite,
|
|
130
|
+
outRead: input.modes.outRead,
|
|
131
|
+
outWrite: input.modes.outWrite,
|
|
132
|
+
},
|
|
133
|
+
roots: input.roots
|
|
134
|
+
.slice(0, 16)
|
|
135
|
+
.map((root) => clipText(root, PATH_CHARS)),
|
|
136
|
+
units: input.units
|
|
137
|
+
.slice(0, MAX_UNITS)
|
|
138
|
+
.map((unit, index) => serializeUnit(unit, unitDecisions[index], input.roots)),
|
|
139
|
+
...(input.units.length > MAX_UNITS
|
|
140
|
+
? { unitsOmitted: input.units.length - MAX_UNITS }
|
|
141
|
+
: {}),
|
|
142
|
+
verdict: serializeVerdict(input),
|
|
143
|
+
...(input.prompt === undefined ? {} : { prompt: [...input.prompt] }),
|
|
144
|
+
};
|
|
145
|
+
}
|