@leiyi-works/dsh-session-tmpdir 0.11.0 → 0.12.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 +20 -2
- package/client.js +130 -16
- package/index.js +141 -76
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -73,7 +73,7 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
|
|
|
73
73
|
3. 用户选长期 + 给路径 → 模型调 `longterm_approve({ path, reason, basis })` 登记:**默认 `mode: 'file'` 只批准这一个文件**;用户明确要"整个目录都行"时才用 `mode: 'dir'`。工作区外路径也能登记(例如鸿蒙的 `Download/<包名>/`),但不能登记磁盘根目录、用户主目录本身或层级过浅的目录;
|
|
74
74
|
4. 之后 `write`/`edit`、shell 命令、`publish` 交付、python 等代码工具才能**新建**该位置的文件;用户否定 → 模型改用 `task_tmpdir` 写 `_tmp`。**改写已存在文件不需要登记**(`allowOverwrite`)。
|
|
75
75
|
|
|
76
|
-
白名单**持久保存**在 `<DSH_HOME>/data/tmpdir-guard/approvals.json
|
|
76
|
+
白名单**持久保存**在 `<DSH_HOME>/data/tmpdir-guard/approvals.json`:**按会话生效**——同一会话重启、同一会话换机续用都继续有效;其他会话即使路径相同也不会自动放行;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。面板还会列出**最近被 guard 拦下的写操作**(v0.12.0),侧栏图标上的红点表示有新的拦截未看过;记录同时追加到 `<DSH_HOME>/data/tmpdir-guard/denials.jsonl`。
|
|
77
77
|
|
|
78
78
|
## guard 行为边界(v0.11)
|
|
79
79
|
|
|
@@ -342,8 +342,26 @@ v0.10.3 变更(2026-11-16):
|
|
|
342
342
|
4. **顺带修掉一处误报**:`echo x > $log` / `> "$env:TEMP\a.txt"` 以前会把变量原文当成工作区里的相对路径(`<工作区>/$log`)而误拒,现在按真实目标判定(`_tmp`/系统临时目录放行,长期位置照拦)。
|
|
343
343
|
5. **别名**:`ni`(`New-Item` 的别名)补进创建动词表,与 `mkdir`/`md` 一致。
|
|
344
344
|
6. **文案更正**:注入说明与 README 里「一次批准、多机生效」的表述不准确——白名单条目按**会话**生效(同一会话重启/换机续用仍有效),其他会话不会因路径相同自动放行;条目文件本身仍跨机同步,供面板展示与合并。
|
|
345
|
-
7. **嵌入脚本 / 注释 / 引号**:PowerShell here-string(`@"…"@` / `@'…'@`)和 POSIX heredoc(`<<EOF`)的**内容**在分段前被屏蔽(视为数据;起始行的 `@"`/`@'` 两个字符也会被抹掉,避免留下未闭合引号把后续语句吞进字符串;结束行允许 `"@; 后续代码` 并保留后续代码参与判定;未闭合按“其余都是数据”处理,语法错误的命令本来也跑不起来);行注释与 `<# … #>`
|
|
345
|
+
7. **嵌入脚本 / 注释 / 引号**:PowerShell here-string(`@"…"@` / `@'…'@`)和 POSIX heredoc(`<<EOF`)的**内容**在分段前被屏蔽(视为数据;起始行的 `@"`/`@'` 两个字符也会被抹掉,避免留下未闭合引号把后续语句吞进字符串;结束行允许 `"@; 后续代码` 并保留后续代码参与判定;未闭合按“其余都是数据”处理,语法错误的命令本来也跑不起来);行注释与 `<# … #>` 块注释在判定前剥掉;**引号内的文本只用整条命令的引号区间做动态目标屏蔽**(`-Value "a; Set-Content …"` 里的 `-Path` 不会当真),语句分段语义仍与 0.10.16 完全一致(不改变字面量/代码通道的旧判定)。
|
|
346
346
|
8. **只读惯用法不误伤**:`> $null` / `2> $null` 这类动态重定向不再把只读命令拖进字面量扫描(`Test-Path … > $null`、`Get-Content … 2> $null`、`node -e "…" > $null` 均放行,动态重定向目标本身仍照常判定);copy 类的 `-Path`/`-LiteralPath` 一律是读源;`-Value (Get-Content -Path $x)` 里的 `-Path` 也是读;`rg -ni` / `grep -ni` 不再因 `ni` 别名误触发。
|
|
347
347
|
9. **回归测试**:`test/guard.test.mjs` 110 条(原有字面量行为 + 新拦截 + 不误伤 + 嵌入脚本文本 + 只读惯用法/注释/引号/here-string 后续语句等评审回归);另用 0.10.16 与 0.11.0 对同一批 **76 条真实任务命令**做差分,除预期的严格化/误报修复外判定完全一致(脚本见 `test/diff.test.mjs`)。
|
|
348
348
|
10. **超长单行命令性能**:旧版在「一行 5 万字符且不含 `://`」的输入上会因 URL 正则回溯耗时约 800ms;现在只在确实出现 `://` 时才做 URL 剥离,同输入 <1ms;40KB here-string 的生成命令也在 2ms 内(判定结果不变)。
|
|
349
349
|
|
|
350
|
+
## v0.11.1 变更(2026-11-20):按历史命令回放修正误伤
|
|
351
|
+
|
|
352
|
+
0.11.0 把语句分段改成“引号感知”后,`node -e "…;…"` 这类多语句代码不再被切碎,代码静态扫描会把 `'package.json'`、`orig/package/index.js` 这类**相对路径字面量**解析到会话目录并误拦。用本机 27 个历史会话的 **2798 条真实 pwsh 命令**回放对比 0.10.16,0.11.0 新增了 155 条拒绝,其中多数属于这类误伤。
|
|
353
|
+
|
|
354
|
+
1. **恢复 0.10.16 的分段语义**(`;` / `&&` / `||` / `|` / 换行切分);引号内文本只通过**整条命令的引号区间**参与“动态写目标屏蔽”,不改变字面量通道与代码静态扫描的旧判定。
|
|
355
|
+
2. **保留 0.11.0 的全部收益**:变量/环境变量/`~` 写目标解析、注释剥离、here-string/heredoc 内容屏蔽、`> $null` 处理、`ni`/`md` 修正等都不变。
|
|
356
|
+
3. **回放结果**:2798 条历史命令里新旧判定只有 **16 条不同**——13 条是“变量指向工作区根新文件/新建工作区子目录”(这些写法换成字面量在 0.10.16 本来就会被拒,属规则内),另 3 条是本次测试探针;`_tmp`/审批目录/DSH home 没有新增拒绝。另有 **13 条旧版误报被修好**(`> $null` 被当成 `D:\dev\null`、`> $dir\…` 被当工作区相对路径等)。
|
|
357
|
+
4. **回归测试**:`test/guard.test.mjs` **115 条**;`test/diff.test.mjs` **79 条**(含历史回放的代表性写法)。
|
|
358
|
+
|
|
359
|
+
## v0.12.0 变更(2026-11-20):被 guard 拦下的写操作在面板里可见
|
|
360
|
+
|
|
361
|
+
背景:用户不读工具调用细节,无法判断 guard 是否误拦了正常任务。现在每次拦截都会留下用户可见的记录。
|
|
362
|
+
|
|
363
|
+
1. 侧栏「临时目录」图标右上角显示红点数字 = **未看过的新拦截数**(最多显示 99+),每 8 秒刷新;打开面板即视为看过并清除红点。
|
|
364
|
+
2. 面板新增「最近被拦下的写操作」:时间、目标路径、拦截类别(工作区外/工作区根/工作区目录/长期位置)、工具名、会话标题、命令片段(最长 200 字符);内存里保留最近 100 条。
|
|
365
|
+
3. 同时 best-effort 追加审计文件 `<DSH_HOME>/data/tmpdir-guard/denials.jsonl`(每行一条 JSON;文件写不进去不影响判定)。
|
|
366
|
+
4. `GET /__dsh-session-tmpdir/state` 返回 `denials` 字段;`POST /__dsh-session-tmpdir/ack-denials` 标记已看过。**guard 判定逻辑本身未改**。
|
|
367
|
+
5. 提醒:拦截 ≠ 任务失败——模型收到拒绝提示后会改用 `_tmp` 或先征求同意再继续;面板里的记录用于让你判断"这次是不是误拦"。
|
package/client.js
CHANGED
|
@@ -91,6 +91,30 @@ window.__ModuleLoader__.load({
|
|
|
91
91
|
},
|
|
92
92
|
empty: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', margin: '8px 0 0' },
|
|
93
93
|
err: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #d14a4a)', margin: 0 },
|
|
94
|
+
subTitle: { margin: '10px 0 0', fontSize: 13, fontWeight: 600 },
|
|
95
|
+
badge: {
|
|
96
|
+
position: 'absolute',
|
|
97
|
+
top: -3,
|
|
98
|
+
right: -4,
|
|
99
|
+
minWidth: 14,
|
|
100
|
+
height: 14,
|
|
101
|
+
padding: '0 3px',
|
|
102
|
+
boxSizing: 'border-box',
|
|
103
|
+
borderRadius: 999,
|
|
104
|
+
background: 'var(--dsw-alias-state-error-primary, #d14a4a)',
|
|
105
|
+
color: '#fff',
|
|
106
|
+
fontSize: 9,
|
|
107
|
+
lineHeight: '14px',
|
|
108
|
+
textAlign: 'center',
|
|
109
|
+
fontWeight: 600,
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function denialKindLabel(kind) {
|
|
114
|
+
if (kind === 'outside') return '工作区外'
|
|
115
|
+
if (kind === 'workspace-root') return '工作区根'
|
|
116
|
+
if (kind === 'workspace-dir') return '工作区目录'
|
|
117
|
+
return '长期位置'
|
|
94
118
|
}
|
|
95
119
|
|
|
96
120
|
function fmtTime(ms) {
|
|
@@ -167,6 +191,63 @@ window.__ModuleLoader__.load({
|
|
|
167
191
|
|
|
168
192
|
const data = state.data
|
|
169
193
|
const rows = data && Array.isArray(data.approvals) ? data.approvals : []
|
|
194
|
+
const denials = data && data.denials && typeof data.denials === 'object' ? data.denials : null
|
|
195
|
+
const denialItems = denials && Array.isArray(denials.items) ? denials.items : []
|
|
196
|
+
const unseenDenials = denials ? Math.max(0, Number(denials.unseen) || 0) : 0
|
|
197
|
+
|
|
198
|
+
// v0.12.0:打开面板即视为“看过”拦截记录 —— 清掉侧栏红点,但列表保留本次显示。
|
|
199
|
+
React.useEffect(() => {
|
|
200
|
+
if (!denials || unseenDenials <= 0) return undefined
|
|
201
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return undefined
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
void fetch(`${API}/ack-denials`, { method: 'POST' })
|
|
204
|
+
.then(() => load(true))
|
|
205
|
+
.catch(() => {})
|
|
206
|
+
}, 1200)
|
|
207
|
+
return () => clearTimeout(timer)
|
|
208
|
+
}, [denials, unseenDenials, load])
|
|
209
|
+
|
|
210
|
+
const denialNodes = denialItems.map((item) =>
|
|
211
|
+
h(
|
|
212
|
+
'div',
|
|
213
|
+
{ key: item.id, style: styles.row },
|
|
214
|
+
h(
|
|
215
|
+
'div',
|
|
216
|
+
{ style: styles.rowMain },
|
|
217
|
+
h('div', { style: styles.path }, item.path || '(未解析出路径)'),
|
|
218
|
+
h(
|
|
219
|
+
'div',
|
|
220
|
+
{ style: styles.rowMeta },
|
|
221
|
+
h('span', { style: styles.tagWarn }, denialKindLabel(item.kind)),
|
|
222
|
+
h(
|
|
223
|
+
'span',
|
|
224
|
+
{ style: styles.meta },
|
|
225
|
+
`${item.tool || '工具'}${item.sessionTitle ? ` · 会话「${item.sessionTitle}」` : ''}`,
|
|
226
|
+
),
|
|
227
|
+
h('span', { style: styles.meta }, fmtTime(item.at)),
|
|
228
|
+
),
|
|
229
|
+
item.command ? h('div', { style: styles.meta }, item.command) : null,
|
|
230
|
+
),
|
|
231
|
+
),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
const denialsSection = h(
|
|
235
|
+
'div',
|
|
236
|
+
null,
|
|
237
|
+
h(
|
|
238
|
+
'h2',
|
|
239
|
+
{ style: styles.subTitle },
|
|
240
|
+
`最近被拦下的写操作${denials && denials.total > 0 ? `(共 ${denials.total} 次,未看 ${unseenDenials})` : ''}`,
|
|
241
|
+
),
|
|
242
|
+
denialItems.length === 0
|
|
243
|
+
? h('p', { style: styles.empty }, '没有拦截记录 —— 插件没有打断任何写入。')
|
|
244
|
+
: h('div', { style: styles.table }, ...denialNodes),
|
|
245
|
+
h(
|
|
246
|
+
'p',
|
|
247
|
+
{ style: styles.meta },
|
|
248
|
+
'这些是 guard 为“新建文件先问 / 改用 _tmp”而拒绝的操作,模型会自动换正确路径继续。侧栏图标上的红点 = 有新的拦截未看过;打开本面板即清除。',
|
|
249
|
+
),
|
|
250
|
+
)
|
|
170
251
|
|
|
171
252
|
const metaLine = data
|
|
172
253
|
? h(
|
|
@@ -233,6 +314,8 @@ window.__ModuleLoader__.load({
|
|
|
233
314
|
),
|
|
234
315
|
),
|
|
235
316
|
state.error ? h('p', { style: styles.err }, state.error) : null,
|
|
317
|
+
denialsSection,
|
|
318
|
+
h('h2', { style: styles.subTitle }, '长期落点白名单'),
|
|
236
319
|
rows.length === 0
|
|
237
320
|
? h('p', { style: styles.empty }, state.loading ? '' : '白名单为空。')
|
|
238
321
|
: h('div', { style: styles.table }, ...rowNodes),
|
|
@@ -242,23 +325,54 @@ window.__ModuleLoader__.load({
|
|
|
242
325
|
|
|
243
326
|
function TempDirIcon(props) {
|
|
244
327
|
const size = typeof props?.size === 'number' && props.size > 0 ? props.size : 18
|
|
328
|
+
// v0.12.0:未看过的 guard 拦截数 → 图标红点(用户不必读工具调用细节也能看到)。
|
|
329
|
+
const [unseen, setUnseen] = React.useState(0)
|
|
330
|
+
React.useEffect(() => {
|
|
331
|
+
let alive = true
|
|
332
|
+
const tick = async () => {
|
|
333
|
+
try {
|
|
334
|
+
const res = await fetch(`${API}/state`, { cache: 'no-store' })
|
|
335
|
+
const data = await res.json()
|
|
336
|
+
if (alive && data && data.ok === true) {
|
|
337
|
+
setUnseen(Math.max(0, Number(data?.denials?.unseen) || 0))
|
|
338
|
+
}
|
|
339
|
+
} catch {
|
|
340
|
+
// 面板接口不可用时保持原状
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
void tick()
|
|
344
|
+
const timer = setInterval(tick, 8000)
|
|
345
|
+
return () => {
|
|
346
|
+
alive = false
|
|
347
|
+
clearInterval(timer)
|
|
348
|
+
}
|
|
349
|
+
}, [])
|
|
350
|
+
const badge =
|
|
351
|
+
unseen > 0
|
|
352
|
+
? h('span', { style: styles.badge, title: `${unseen} 条新的拦截记录` }, unseen > 99 ? '99+' : String(unseen))
|
|
353
|
+
: null
|
|
245
354
|
return h(
|
|
246
|
-
'
|
|
247
|
-
{
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
355
|
+
'span',
|
|
356
|
+
{ style: { position: 'relative', display: 'inline-flex' } },
|
|
357
|
+
h(
|
|
358
|
+
'svg',
|
|
359
|
+
{
|
|
360
|
+
width: size,
|
|
361
|
+
height: size,
|
|
362
|
+
viewBox: '0 0 24 24',
|
|
363
|
+
fill: 'none',
|
|
364
|
+
'aria-hidden': true,
|
|
365
|
+
style: { display: 'block' },
|
|
366
|
+
},
|
|
367
|
+
h('path', {
|
|
368
|
+
d: 'M6.5 4.5h11M6.5 19.5h11M8.3 4.5v3.4c0 1.9 1.7 3.4 3.7 5 2-1.6 3.7-3.1 3.7-5V4.5M8.3 19.5v-3.4c0-1.9 1.7-3.4 3.7-5 2 1.6 3.7 3.1 3.7 5v3.4',
|
|
369
|
+
stroke: 'currentColor',
|
|
370
|
+
strokeWidth: 1.6,
|
|
371
|
+
strokeLinecap: 'round',
|
|
372
|
+
strokeLinejoin: 'round',
|
|
373
|
+
}),
|
|
374
|
+
),
|
|
375
|
+
badge,
|
|
262
376
|
)
|
|
263
377
|
}
|
|
264
378
|
|
package/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { homedir, hostname, tmpdir } from 'node:os'
|
|
4
4
|
import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
|
|
@@ -136,6 +136,8 @@ const CREATE_VERB_PATTERN =
|
|
|
136
136
|
*/
|
|
137
137
|
const DOWNLOAD_WRITE_PATTERN =
|
|
138
138
|
/\bInvoke-(?:WebRequest|RestMethod)\b[^;|&\n]*\s-(?:OutFile|OutFileList)\b|\bcurl\b[^;|&\n]*\s(?:-o|--output|-O)\b|\bwget\b[^;|&\n]*\s(?:-O|--output-document)\b|\bStart-Process\b[^;|&\n]*\s-(?:RedirectStandardOutput|RedirectStandardError)\b/i
|
|
139
|
+
/** v0.9.4: judge a script statement by statement, so a read-only segment cannot be misread as a write. */
|
|
140
|
+
const COMMAND_SEGMENT_SPLIT = /(?:\r?\n|;|&&|\|\||\|)+/
|
|
139
141
|
/**
|
|
140
142
|
* v0.10.1: invoking a code interpreter (`node`, `python`, `perl`, `ruby`) is not itself a
|
|
141
143
|
* file write. Such a segment is judged by the code static scan (write signals paired with
|
|
@@ -679,11 +681,10 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
679
681
|
}
|
|
680
682
|
|
|
681
683
|
/** Judge one statement segment (`;` / `&&` / `||` / `|` / newline separated). */
|
|
682
|
-
function judgeSegment(segment, symbols) {
|
|
684
|
+
function judgeSegment(segment, symbols, segmentStart = 0, quoteRanges = []) {
|
|
683
685
|
// v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
|
|
684
686
|
// parsed as one token instead of leaving a second `>` behind. Quoted text such as
|
|
685
687
|
// `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
|
|
686
|
-
const quoteRanges = quotedRanges(segment)
|
|
687
688
|
const redirectTokens = new Set()
|
|
688
689
|
const dynamicRedirectTokens = []
|
|
689
690
|
for (const match of segment.matchAll(REDIRECT_ALL_PATTERN)) {
|
|
@@ -695,7 +696,9 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
695
696
|
// raw text must not be resolved against the workspace cwd (it always looked like
|
|
696
697
|
// `<workspace>/$log`, which produced a bogus "workspace root entry" denial).
|
|
697
698
|
const dynamic =
|
|
698
|
-
match[2] === undefined &&
|
|
699
|
+
match[2] === undefined &&
|
|
700
|
+
isDynamicPathToken(cleaned) &&
|
|
701
|
+
!indexInsideRanges(segmentStart + match.index, quoteRanges)
|
|
699
702
|
// Dynamic redirects never count as `hasRedirect`: `… > $null` / `2> $null` are the
|
|
700
703
|
// usual "silence output" idiom of read-only commands and must not drag the segment
|
|
701
704
|
// into the literal scan (they are judged separately, and `$null` resolves to none).
|
|
@@ -710,7 +713,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
710
713
|
/** v0.11.0: dynamic redirection targets are writes even in read-only statements. */
|
|
711
714
|
const judgeDynamicRedirects = () => {
|
|
712
715
|
if (dynamicRedirectTokens.length === 0) return undefined
|
|
713
|
-
|
|
716
|
+
const options = { platform, dynamicRedirectTokens, quoteRanges, quoteOffset: segmentStart }
|
|
717
|
+
for (const abs of dynamicWriteTargets(segment, symbols, options)) {
|
|
714
718
|
const reason = judgeTargetPath(abs)
|
|
715
719
|
if (reason) return reason
|
|
716
720
|
}
|
|
@@ -782,23 +786,31 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
782
786
|
}
|
|
783
787
|
// v0.11.0: variable / environment / `~` paths in write-target positions. Only target
|
|
784
788
|
// positions are resolved, so read sources and content strings are never blamed.
|
|
785
|
-
for (const abs of dynamicWriteTargets(segment, symbols, {
|
|
789
|
+
for (const abs of dynamicWriteTargets(segment, symbols, {
|
|
790
|
+
platform,
|
|
791
|
+
dynamicRedirectTokens,
|
|
792
|
+
quoteRanges,
|
|
793
|
+
quoteOffset: segmentStart,
|
|
794
|
+
})) {
|
|
786
795
|
const reason = judgeTargetPath(abs)
|
|
787
796
|
if (reason) return reason
|
|
788
797
|
}
|
|
789
798
|
return undefined
|
|
790
799
|
}
|
|
791
800
|
|
|
792
|
-
// v0.11.0: embedded script text is data (blanked)
|
|
793
|
-
// splitting
|
|
801
|
+
// v0.11.0: embedded script text is data (blanked) and comments are not statements.
|
|
802
|
+
// Statement splitting itself stays the pre-0.11 splitter (quoted-content pieces are
|
|
803
|
+
// still scanned by the old literal path only), while dynamic write targets are masked
|
|
804
|
+
// by the whole command's quote ranges.
|
|
794
805
|
const commandText = stripComments(blankEmbeddedScripts(String(command)))
|
|
795
|
-
const
|
|
806
|
+
const quoteRanges = quotedRanges(commandText)
|
|
796
807
|
// v0.11.0: paths assigned in earlier statements of the same command (best effort).
|
|
797
808
|
const symbols = new Map()
|
|
798
|
-
for (const
|
|
799
|
-
const reason = judgeSegment(
|
|
809
|
+
for (const entry of splitSegmentsWithOffsets(commandText)) {
|
|
810
|
+
const reason = judgeSegment(entry.text, symbols, entry.start, quoteRanges)
|
|
800
811
|
if (reason) return reason
|
|
801
|
-
|
|
812
|
+
// A segment that starts inside an opened quote is quoted content, not a statement.
|
|
813
|
+
if (!indexInsideRanges(entry.start, quoteRanges)) collectPathAssignment(entry.text, symbols, platform)
|
|
802
814
|
}
|
|
803
815
|
return undefined
|
|
804
816
|
}
|
|
@@ -960,67 +972,28 @@ function stripComments(command) {
|
|
|
960
972
|
}
|
|
961
973
|
|
|
962
974
|
/**
|
|
963
|
-
* v0.11.0: split
|
|
964
|
-
*
|
|
965
|
-
*
|
|
975
|
+
* v0.11.0: split exactly like the pre-0.11 splitter (`;` / `&&` / `||` / `|` / newline)
|
|
976
|
+
* but keep each segment's offset in the command, because quoted-content masking is done
|
|
977
|
+
* on the whole command: a segment that starts inside an opened quote may only be scanned
|
|
978
|
+
* by the old literal path, never as a dynamic write target.
|
|
966
979
|
*/
|
|
967
|
-
function
|
|
980
|
+
function splitSegmentsWithOffsets(command) {
|
|
968
981
|
const text = String(command ?? '')
|
|
969
982
|
const segments = []
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
continue
|
|
983
|
-
}
|
|
984
|
-
if (ch === quote) {
|
|
985
|
-
if (text[i + 1] === quote) {
|
|
986
|
-
i += 2
|
|
987
|
-
continue
|
|
988
|
-
}
|
|
989
|
-
quote = ''
|
|
990
|
-
}
|
|
991
|
-
i += 1
|
|
992
|
-
continue
|
|
993
|
-
}
|
|
994
|
-
if (ch === '`') {
|
|
995
|
-
i += 2
|
|
996
|
-
continue
|
|
997
|
-
}
|
|
998
|
-
if (ch === '"' || ch === "'") {
|
|
999
|
-
quote = ch
|
|
1000
|
-
i += 1
|
|
1001
|
-
continue
|
|
1002
|
-
}
|
|
1003
|
-
if (ch === '\n' || ch === ';') {
|
|
1004
|
-
push(i)
|
|
1005
|
-
i += 1
|
|
1006
|
-
start = i
|
|
1007
|
-
continue
|
|
1008
|
-
}
|
|
1009
|
-
if (ch === '&' && text[i + 1] === '&') {
|
|
1010
|
-
push(i)
|
|
1011
|
-
i += 2
|
|
1012
|
-
start = i
|
|
1013
|
-
continue
|
|
1014
|
-
}
|
|
1015
|
-
if (ch === '|') {
|
|
1016
|
-
push(i)
|
|
1017
|
-
i += text[i + 1] === '|' ? 2 : 1
|
|
1018
|
-
start = i
|
|
1019
|
-
continue
|
|
1020
|
-
}
|
|
1021
|
-
i += 1
|
|
983
|
+
const push = (start, end) => {
|
|
984
|
+
const raw = text.slice(start, end)
|
|
985
|
+
const trimmed = raw.trim()
|
|
986
|
+
if (!trimmed) return
|
|
987
|
+
segments.push({ text: trimmed, start: start + raw.indexOf(trimmed) })
|
|
988
|
+
}
|
|
989
|
+
const separator = new RegExp(COMMAND_SEGMENT_SPLIT.source, 'g')
|
|
990
|
+
let last = 0
|
|
991
|
+
let match
|
|
992
|
+
while ((match = separator.exec(text))) {
|
|
993
|
+
push(last, match.index)
|
|
994
|
+
last = match.index + match[0].length
|
|
1022
995
|
}
|
|
1023
|
-
push(text.length)
|
|
996
|
+
push(last, text.length)
|
|
1024
997
|
return segments
|
|
1025
998
|
}
|
|
1026
999
|
|
|
@@ -1028,12 +1001,12 @@ function splitCommandSegments(command) {
|
|
|
1028
1001
|
* Parenthesis depth for every character of a segment (quotes ignored), so a read-only
|
|
1029
1002
|
* `-Path` inside `-Value (Get-Content -Path $x)` is not blamed as a write target.
|
|
1030
1003
|
*/
|
|
1031
|
-
function parenDepthMap(text, quoteRanges) {
|
|
1004
|
+
function parenDepthMap(text, quoteRanges = [], offset = 0) {
|
|
1032
1005
|
const depth = new Int32Array(text.length + 1)
|
|
1033
1006
|
let current = 0
|
|
1034
1007
|
for (let i = 0; i < text.length; i += 1) {
|
|
1035
1008
|
depth[i] = current
|
|
1036
|
-
if (indexInsideRanges(i, quoteRanges)) continue
|
|
1009
|
+
if (indexInsideRanges(offset + i, quoteRanges)) continue
|
|
1037
1010
|
const ch = text[i]
|
|
1038
1011
|
if (ch === '(') current += 1
|
|
1039
1012
|
else if (ch === ')') current = Math.max(0, current - 1)
|
|
@@ -1194,11 +1167,11 @@ function stripArgEdge(text) {
|
|
|
1194
1167
|
* the write command) are deliberately ignored.
|
|
1195
1168
|
*/
|
|
1196
1169
|
function dynamicWriteTargets(segment, symbols, options = {}) {
|
|
1197
|
-
const { platform = process.platform, dynamicRedirectTokens = [], quoteRanges =
|
|
1170
|
+
const { platform = process.platform, dynamicRedirectTokens = [], quoteRanges = [], quoteOffset = 0 } = options
|
|
1198
1171
|
const found = new Set()
|
|
1199
1172
|
const firstWrite = firstWriteSignalIndex(segment)
|
|
1200
1173
|
const copyLike = COPY_LIKE_VERB_PATTERN.test(segment)
|
|
1201
|
-
const depthAt = segment.includes('(') ? parenDepthMap(segment, quoteRanges) : undefined
|
|
1174
|
+
const depthAt = segment.includes('(') ? parenDepthMap(segment, quoteRanges, quoteOffset) : undefined
|
|
1202
1175
|
/** Resolve a token only when it is dynamic AND not inside quoted content text. */
|
|
1203
1176
|
const push = (raw) => {
|
|
1204
1177
|
if (raw === undefined || raw === null) return
|
|
@@ -1207,7 +1180,8 @@ function dynamicWriteTargets(segment, symbols, options = {}) {
|
|
|
1207
1180
|
const abs = resolveDynamicPathExpression(text, symbols, platform)
|
|
1208
1181
|
if (abs) found.add(abs)
|
|
1209
1182
|
}
|
|
1210
|
-
const inTargetRegion = (index) =>
|
|
1183
|
+
const inTargetRegion = (index) =>
|
|
1184
|
+
firstWrite >= 0 && index >= firstWrite && !indexInsideRanges(quoteOffset + index, quoteRanges)
|
|
1211
1185
|
// A) redirection targets (`> $log`, `4> $d\out.txt`)
|
|
1212
1186
|
for (const raw of dynamicRedirectTokens) push(raw)
|
|
1213
1187
|
// B) first argument of a .NET write API
|
|
@@ -1445,9 +1419,27 @@ export function outsideWriteDenialReason(abs, options = {}) {
|
|
|
1445
1419
|
)
|
|
1446
1420
|
}
|
|
1447
1421
|
|
|
1422
|
+
/**
|
|
1423
|
+
* v0.12.0: extract the denied target path from a guard denial message, so the panel can
|
|
1424
|
+
* show "what was blocked" without parsing log lines by hand.
|
|
1425
|
+
*/
|
|
1426
|
+
export function denialTargetPath(reason) {
|
|
1427
|
+
const text = String(reason ?? '')
|
|
1428
|
+
const match = /(((?:[A-Za-z]:[\\/]|\/|\\\\)[^)]{1,500}))/.exec(text)
|
|
1429
|
+
return match ? match[1].trim() : ''
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
/** v0.12.0: classify a denial message (used by the panel's denial list). */
|
|
1433
|
+
export function denialKind(reason) {
|
|
1434
|
+
const text = String(reason ?? '')
|
|
1435
|
+
if (text.includes('工作区之外')) return 'outside'
|
|
1436
|
+
if (text.includes('工作区根目录')) return 'workspace-root'
|
|
1437
|
+
if (text.includes('工作区里的')) return 'workspace-dir'
|
|
1438
|
+
return 'long-term'
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1448
1441
|
/** Argument names that name a write destination strongly (bare file names are allowed). */
|
|
1449
|
-
const STRONG_TARGET_KEYS = new Set([
|
|
1450
|
-
'target',
|
|
1442
|
+
const STRONG_TARGET_KEYS = new Set([ 'target',
|
|
1451
1443
|
'targets',
|
|
1452
1444
|
'target_path',
|
|
1453
1445
|
'destination',
|
|
@@ -3065,6 +3057,72 @@ export function apply(ctx, config) {
|
|
|
3065
3057
|
})
|
|
3066
3058
|
}
|
|
3067
3059
|
|
|
3060
|
+
// ── v0.12.0: guard denial audit(面板可见 + 侧栏红点)────────────────────
|
|
3061
|
+
// 用户不读工具调用细节,所以被 guard 拦下的写操作要有一个用户能一眼看到的出口:
|
|
3062
|
+
// 左侧「临时目录」图标上的红点(未看过的新拦截数)+ 面板里的「最近拦截」列表。
|
|
3063
|
+
// 内存里保留最近 100 条;同时 best-effort 追加到 data/tmpdir-guard/denials.jsonl。
|
|
3064
|
+
const DENIAL_LOG_LIMIT = 100
|
|
3065
|
+
const denialLog = []
|
|
3066
|
+
const denialLogFile = join(resolveDshHome(), 'data', 'tmpdir-guard', 'denials.jsonl')
|
|
3067
|
+
let denialSeenAt = 0
|
|
3068
|
+
let denialTotal = 0
|
|
3069
|
+
let denialSeq = 0
|
|
3070
|
+
|
|
3071
|
+
function recordGuardDenial({ toolName, label, reason, session, execution }) {
|
|
3072
|
+
try {
|
|
3073
|
+
denialSeq += 1
|
|
3074
|
+
denialTotal += 1
|
|
3075
|
+
const args = execution && typeof execution.arguments === 'object' ? execution.arguments : undefined
|
|
3076
|
+
const command = (() => {
|
|
3077
|
+
if (!args || typeof args !== 'object') return ''
|
|
3078
|
+
const value =
|
|
3079
|
+
typeof args.command === 'string'
|
|
3080
|
+
? args.command
|
|
3081
|
+
: typeof args.file_path === 'string'
|
|
3082
|
+
? args.file_path
|
|
3083
|
+
: typeof args.path === 'string'
|
|
3084
|
+
? args.path
|
|
3085
|
+
: typeof args.code === 'string'
|
|
3086
|
+
? args.code
|
|
3087
|
+
: ''
|
|
3088
|
+
return String(value).replace(/\s+/g, ' ').trim().slice(0, 200)
|
|
3089
|
+
})()
|
|
3090
|
+
const entry = {
|
|
3091
|
+
id: `deny-${Date.now().toString(36)}-${denialSeq.toString(36)}`,
|
|
3092
|
+
at: Date.now(),
|
|
3093
|
+
tool: String(toolName ?? '').slice(0, 40),
|
|
3094
|
+
label: String(label ?? '').slice(0, 60),
|
|
3095
|
+
kind: denialKind(reason),
|
|
3096
|
+
path: denialTargetPath(reason).slice(0, 260),
|
|
3097
|
+
sessionId: sessionKey(session),
|
|
3098
|
+
sessionTitle: titleOf(session) ?? '',
|
|
3099
|
+
command,
|
|
3100
|
+
}
|
|
3101
|
+
denialLog.push(entry)
|
|
3102
|
+
if (denialLog.length > DENIAL_LOG_LIMIT) denialLog.splice(0, denialLog.length - DENIAL_LOG_LIMIT)
|
|
3103
|
+
try {
|
|
3104
|
+
mkdirSync(dirname(denialLogFile), { recursive: true })
|
|
3105
|
+
appendFileSync(denialLogFile, `${JSON.stringify(entry)}\n`)
|
|
3106
|
+
} catch {
|
|
3107
|
+
// the audit file is best-effort
|
|
3108
|
+
}
|
|
3109
|
+
} catch {
|
|
3110
|
+
// recording must never change a guard verdict
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
|
|
3114
|
+
function denialSnapshot() {
|
|
3115
|
+
const lastAt = denialLog.length > 0 ? denialLog[denialLog.length - 1].at : 0
|
|
3116
|
+
return {
|
|
3117
|
+
seenAt: denialSeenAt,
|
|
3118
|
+
total: denialTotal,
|
|
3119
|
+
unseen: denialLog.filter((entry) => entry.at > denialSeenAt).length,
|
|
3120
|
+
lastAt,
|
|
3121
|
+
file: denialLogFile,
|
|
3122
|
+
items: denialLog.slice(-50).reverse(),
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
|
|
3068
3126
|
// 面板接口:GET /__dsh-session-tmpdir/state(白名单清单)、POST /__dsh-session-tmpdir/revoke(移除一条)。
|
|
3069
3127
|
ctx.inject(['webServer'], (webScope) => {
|
|
3070
3128
|
webScope.effect(
|
|
@@ -3105,9 +3163,15 @@ export function apply(ctx, config) {
|
|
|
3105
3163
|
rootDirName,
|
|
3106
3164
|
allowOverwrite,
|
|
3107
3165
|
approvals,
|
|
3166
|
+
denials: denialSnapshot(),
|
|
3108
3167
|
})
|
|
3109
3168
|
return
|
|
3110
3169
|
}
|
|
3170
|
+
if (pathname.endsWith('/ack-denials') && req.method === 'POST') {
|
|
3171
|
+
denialSeenAt = Date.now()
|
|
3172
|
+
sendJson(200, { ok: true, denials: denialSnapshot() })
|
|
3173
|
+
return
|
|
3174
|
+
}
|
|
3111
3175
|
if (pathname.endsWith('/revoke') && req.method === 'POST') {
|
|
3112
3176
|
const body = await readRequestBody(req)
|
|
3113
3177
|
const id = typeof body?.id === 'string' ? body.id.trim() : ''
|
|
@@ -3392,6 +3456,7 @@ export function apply(ctx, config) {
|
|
|
3392
3456
|
}
|
|
3393
3457
|
const deny = (label, reason) => {
|
|
3394
3458
|
console.info(`[session-task-tmpdir] ${label} denied: ${reason}`)
|
|
3459
|
+
recordGuardDenial({ toolName, label, reason, session, execution })
|
|
3395
3460
|
return reason
|
|
3396
3461
|
}
|
|
3397
3462
|
const outsideWarn = (label, abs) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-session-tmpdir",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Per-session task temp folder with a long-term write guard. v0.9 (方案3): creating a new file outside _tmp requires the user's approval (per file by default, per directory with mode=dir), overwriting an existing file is allowed without asking, every write channel is guarded (write/edit, shell including ffmpeg/pandoc/Export-*/IO APIs, publish copies, code runtimes, unknown tools), and the persisted whitelist is shown in a left-sidebar panel「临时目录」 where entries can be removed. Every session also gets _tmp/<session title>/ in its working directory, cleaned 7 days after the session is deleted; the same tick reclaims the attachment store.",
|
|
6
6
|
"exports": {
|