@leiyi-works/dsh-session-tmpdir 0.10.16 → 0.11.1
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 +30 -6
- package/index.js +561 -46
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -73,16 +73,16 @@ 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/
|
|
76
|
+
白名单**持久保存**在 `<DSH_HOME>/data/tmpdir-guard/approvals.json`:**按会话生效**——同一会话重启、同一会话换机续用都继续有效;其他会话即使路径相同也不会自动放行;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。
|
|
77
77
|
|
|
78
|
-
## guard 行为边界(v0.
|
|
78
|
+
## guard 行为边界(v0.11)
|
|
79
79
|
|
|
80
80
|
判定顺序:`_tmp` 段(只在**工作区内或系统临时目录**里算临时区)→ 已审批文件/目录 → **已存在文件(改写放行,`allowOverwrite`)** → 白名单;其余按"新建产物"处理:工作区内 → 拒绝并提示先问;工作区外 → 按外部落点处理。
|
|
81
81
|
|
|
82
82
|
| 通道 | 判定方式 | 说明 |
|
|
83
83
|
|---|---|---|
|
|
84
84
|
| `write` / `edit` | 完整判定 | 新建工作区根条目、未审批位置、工作区外新文件 → 拒绝;目标已存在 → 放行(改写) |
|
|
85
|
-
| `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`cp`/`mv`/`sed`/`tee`…)、重定向(`>`/`>>`)或 **v0.9 写程序**(`ffmpeg`/`pandoc`/`Export-Csv`/`WriteAllText`/`Start-Process`…)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);**已存在的路径按改写放行**,不存在且未审批 →
|
|
85
|
+
| `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`ni`/`cp`/`mv`/`sed`/`tee`…)、重定向(`>`/`>>`)或 **v0.9 写程序**(`ffmpeg`/`pandoc`/`Export-Csv`/`WriteAllText`/`Start-Process`…)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);**已存在的路径按改写放行**,不存在且未审批 → 拒绝。v0.11.0 起还会解析**写目标位置**上的简单变量/环境变量/`~`:同一命令里 `$var = '<绝对路径>'`、`$env:USERPROFILE`、`$HOME`、`%USERPROFILE%`、`~/…`(只解析目标位,读源和内容参数不解析) |
|
|
86
86
|
| `publish` | 复制目标判定 | 只检查 `target`/`destination`/`to`/`output`/`save_path` 等(`source` 是读侧,不拦);目标不存在且未审批 → 拒绝并提示先问用户 |
|
|
87
87
|
| `present` | 不拦 | 只声明已有文件为交付物,不复制、不落盘 |
|
|
88
88
|
| `python` / `node` 等 | 静态扫描 | 写信号(`open(...,'w')`、`write_text`、`shutil.copy`、`json.dump`、`Image.save`…)与同语句路径字面量(含 `sub/x.md` 这类相对路径)配对;动态拼路径拦不到(默认边界) |
|
|
@@ -92,7 +92,7 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
|
|
|
92
92
|
|
|
93
93
|
工作区外"天然允许"范围(无需审批,`outsideAllow` 可追加):`<DSH_HOME>`(`~/.dsh`,含插件/密钥/配置)、`~/.cache`、`~/.npm`、`~/.config`、`~/.local/share`、`~/.flova`、系统临时目录;POSIX 设备上另有 `/tmp`、`/var/tmp`、`/dev/shm`、`/run/user`、`/data/local/tmp`、`/storage/emulated/0/Android/data`。`/dev/null`、`NUL`、`$null` 之类伪路径直接放行。
|
|
94
94
|
|
|
95
|
-
拦不到(fail-open
|
|
95
|
+
拦不到(fail-open,**不是安全边界**):运行时才确定的动态拼接(`Join-Path`/`$(…)` 的结果、循环变量、跨语句/跨工具调用传值、脚本内部逻辑)、**被括号包裹的写命令参数**(`(Set-Content -Path $env:… 'x')` 这种少见写法)、多行普通字符串续行以 `#` 开头的内容、含 `://` 且同段有超长连续字母数字的极端输入、外部程序产物、GUI 操作、绕过工具的 fs 调用;**v0.11.0 起,同一命令内的简单赋值、`$env:USERPROFILE`/`$HOME`/`%USERPROFILE%`/`~` 这类常见写法会按写目标解析**(仍只判「新建文件」,已存在文件照旧改写放行);`warn` 模式只记日志不拦(`guardOutsideWorkspace`/`publishGuard`/`commandGuard` 的 `warn` 在四个通道统一生效)。
|
|
96
96
|
|
|
97
97
|
其它:**工作区内**的规则只在会话工作目录 = 已注册工作区根时生效(会话 `cd` 到子目录时不把项目顶层文件当成"工作区根新建条目");**工作区外**的判定不受 cwd 限制,`cd` 到子目录也照拦(v0.7 修复);guard 是**全局**的——队友/子代理/定时任务会话同样受约束。
|
|
98
98
|
|
|
@@ -245,12 +245,12 @@ v0.9.10 变更(2026-11-16):**面板默认只显示当前机器的白名单
|
|
|
245
245
|
|
|
246
246
|
v0.9.11 变更(2026-11-16):**修复 0.9.10 客户端语法错误**(`client.js` 少一个括号,面板无法加载)。面板渲染重写为更简单的数组结构(同样的功能:右侧边栏标签页、5 秒自动刷新、当前机器白名单展示/移除、目标不存在标记)。
|
|
247
247
|
|
|
248
|
-
v0.9.12 变更(2026-11-16
|
|
248
|
+
v0.9.12 变更(2026-11-16):文案澄清——面板**默认只显示当前机器的白名单**(不是“机器隔离”)。界面过滤只是显示策略;白名单判定仍按绝对路径,其他机器同步来的条目如果路径在本机存在,仍然会生效。(**v0.11.0 更正**:白名单判定实际按**会话**生效,其他机器的条目只有在**同一个会话**于本机续用时才生效——见 v0.11.0 变更说明。)
|
|
249
249
|
|
|
250
250
|
v0.10.0 变更(2026-11-16):**白名单条目的路径可移植 + 全机队统一展示**(“N 台机器像一个 DSH”)。
|
|
251
251
|
|
|
252
252
|
1. **可移植路径**:home 下的目标在写入时存成 `~/...`(例如 `~/Desktop/x.exe`);读取/匹配/回收时按**当前机器**的 home 展开。工作区等不在 home 下的路径仍存绝对路径(各机一致即可共享)。
|
|
253
|
-
2. **一次批准、多机生效**:A 机批准 `~/Desktop/x.exe` → 同步后 B 机展开成 `C:\Users\<B用户名>\Desktop\x.exe`,同样免审批(前提是该逻辑位置在 B
|
|
253
|
+
2. **一次批准、多机生效**:A 机批准 `~/Desktop/x.exe` → 同步后 B 机展开成 `C:\Users\<B用户名>\Desktop\x.exe`,同样免审批(前提是该逻辑位置在 B 机也有意义)。(**v0.11.0 更正**:仅适用于**同一会话换机续用**;条目按会话生效,不会授权其他会话。)
|
|
254
254
|
3. **界面去掉机器过滤**:面板显示整份共享白名单(不是“本机专属”);**本机没有的路径**标记「本机无此路径」(可能存在于其他机器),不会因此自动删除;可移植路径额外标「可移植」。
|
|
255
255
|
4. 旧条目(绝对路径、home 下)在加载时自动归一为 `~/...` 并落盘;墓碑/合并/按机器回收逻辑不变。
|
|
256
256
|
5. 仍无法自动统一:盘符/工作区路径不同、机器独有路径——这类按各自绝对路径判定。
|
|
@@ -331,3 +331,27 @@ v0.10.3 变更(2026-11-16):
|
|
|
331
331
|
- 按用户要求把问询卡片里的两个选项顺序对调:第 1 项改为「长期保存」(description 仍是本会话工作目录的真实绝对路径),第 2 项改为「不长期保存」(description 仍是 `task_tmpdir` 返回的临时目录真实绝对路径 + 随会话删除后 N 天清理)。
|
|
332
332
|
- 选项标签与说明文案本身不动,只调换先后;`compact` 注入的固定问法、`full` 注入的 A/B 两项及其说明、guard 的 5 处拦截提示全部按新顺序改写。
|
|
333
333
|
- 只改提示文案顺序;guard 判定、审批、清理逻辑未改。
|
|
334
|
+
|
|
335
|
+
## v0.11.0 变更(2026-11-20):shell 写目标支持简单变量 / 环境变量 / 波浪号
|
|
336
|
+
|
|
337
|
+
背景:2026-11-20 的《临时目录插件问题报告》实测 `$out = "…\Desktop\START-WEB.cmd"` + `[IO.File]::WriteAllLines($out, …)` 可绕过 guard(旧实现只扫描同一语句段内的字面量路径),同类写法还有 `$d` + `"$d\a.txt"`、`Out-File $d\b.txt`、`Copy-Item .\x $d\y.txt`、`$env:USERPROFILE\Desktop\x` 等。本版只补齐「新建文件落到长期位置」这一项,**不改变任何放行口径**:已存在文件的改写仍放行、`_tmp`/审批目录/DSH home/缓存/系统临时目录仍放行;也**不新增破坏性操作拦截**(按用户要求,插件只为整齐监控新文件的落盘位置,不能影响正常任务)。
|
|
338
|
+
|
|
339
|
+
1. **简单赋值回溯**:同一命令文本里 `$var = '<绝对路径>'` / `NAME=<绝对路径>` / `set VAR=<绝对路径>` 记入符号表;只收单行、值必须像绝对路径的赋值,内容字符串、here-string、命令替换(`$(…)`)、数组、相对路径都不进表。
|
|
340
|
+
2. **只解析写目标位置**:`.NET WriteAllText/WriteAllLines/WriteAllBytes/AppendAllText/…` 的第一个参数、`-Path/-LiteralPath/-FilePath/-OutFile/-Destination/…` 参数、`Set-Content/Add-Content/Out-File/tee/mkdir/md/ni` 的首个位置参数、copy 类命令的 destination、重定向目标、`curl -o`/`wget -O`/`Invoke-WebRequest -OutFile`、`ffmpeg` 最后一个参数。读源(`Copy-Item $src …`、`Get-Content $src`)与内容参数(`-Value $content`)不解析,引号内的文本也不算目标——「生成脚本内容里提到桌面路径」不会被误拦。
|
|
341
|
+
3. **环境变量 / `~` 展开**:`$env:USERPROFILE`、`$HOME`、`%USERPROFILE%`、`~/…` 按本机展开后参与判定(只展开白名单内的环境名)。解析不出来的(`Join-Path` 结果、循环变量、跨命令赋值)保持原样放行,仍是 fail-open。
|
|
342
|
+
4. **顺带修掉一处误报**:`echo x > $log` / `> "$env:TEMP\a.txt"` 以前会把变量原文当成工作区里的相对路径(`<工作区>/$log`)而误拒,现在按真实目标判定(`_tmp`/系统临时目录放行,长期位置照拦)。
|
|
343
|
+
5. **别名**:`ni`(`New-Item` 的别名)补进创建动词表,与 `mkdir`/`md` 一致。
|
|
344
|
+
6. **文案更正**:注入说明与 README 里「一次批准、多机生效」的表述不准确——白名单条目按**会话**生效(同一会话重启/换机续用仍有效),其他会话不会因路径相同自动放行;条目文件本身仍跨机同步,供面板展示与合并。
|
|
345
|
+
7. **嵌入脚本 / 注释 / 引号**:PowerShell here-string(`@"…"@` / `@'…'@`)和 POSIX heredoc(`<<EOF`)的**内容**在分段前被屏蔽(视为数据;起始行的 `@"`/`@'` 两个字符也会被抹掉,避免留下未闭合引号把后续语句吞进字符串;结束行允许 `"@; 后续代码` 并保留后续代码参与判定;未闭合按“其余都是数据”处理,语法错误的命令本来也跑不起来);行注释与 `<# … #>` 块注释在判定前剥掉;**引号内的文本只用整条命令的引号区间做动态目标屏蔽**(`-Value "a; Set-Content …"` 里的 `-Path` 不会当真),语句分段语义仍与 0.10.16 完全一致(不改变字面量/代码通道的旧判定)。
|
|
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
|
+
9. **回归测试**:`test/guard.test.mjs` 110 条(原有字面量行为 + 新拦截 + 不误伤 + 嵌入脚本文本 + 只读惯用法/注释/引号/here-string 后续语句等评审回归);另用 0.10.16 与 0.11.0 对同一批 **76 条真实任务命令**做差分,除预期的严格化/误报修复外判定完全一致(脚本见 `test/diff.test.mjs`)。
|
|
348
|
+
10. **超长单行命令性能**:旧版在「一行 5 万字符且不含 `://`」的输入上会因 URL 正则回溯耗时约 800ms;现在只在确实出现 `://` 时才做 URL 剥离,同输入 <1ms;40KB here-string 的生成命令也在 2ms 内(判定结果不变)。
|
|
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 条**(含历史回放的代表性写法)。
|
package/index.js
CHANGED
|
@@ -129,7 +129,7 @@ const DEFAULT_COMMAND_GUARD = 'deny'
|
|
|
129
129
|
const DEFAULT_PUBLISH_GUARD = 'deny'
|
|
130
130
|
/** Command text that can create a directory/file; used before scanning for paths (v0.7: POSIX verbs). */
|
|
131
131
|
const CREATE_VERB_PATTERN =
|
|
132
|
-
/\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
|
|
132
|
+
/\b(?:New-Item|mkdir|(?<!-)md(?=\s)|(?<!-)ni(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
|
|
133
133
|
/**
|
|
134
134
|
* v0.9.4: download commands only write files when they name an output target.
|
|
135
135
|
* `Invoke-RestMethod …` / `curl https://…` without `-OutFile`/`-o` are pure reads.
|
|
@@ -146,7 +146,7 @@ const COMMAND_SEGMENT_SPLIT = /(?:\r?\n|;|&&|\|\||\|)+/
|
|
|
146
146
|
const INTERPRETER_SEGMENT_PATTERN = /(?:^|[\\/\s"'=$&])(?:node(?:\.exe)?|python3?(?:\.exe)?|perl|ruby)\b/i
|
|
147
147
|
/** Create verbs excluding the interpreters above (other real write commands in the same segment). */
|
|
148
148
|
const OTHER_CREATE_VERB_PATTERN =
|
|
149
|
-
/\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed)\b/i
|
|
149
|
+
/\b(?:New-Item|mkdir|(?<!-)md(?=\s)|(?<!-)ni(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed)\b/i
|
|
150
150
|
/**
|
|
151
151
|
* v0.9.5: copy-like commands read their source arguments — only the destination is a
|
|
152
152
|
* write target. A missing source must never make the guard blame the destination check.
|
|
@@ -171,6 +171,48 @@ const REDIRECT_ALL_PATTERN = new RegExp(REDIRECT_SOURCE, 'g')
|
|
|
171
171
|
const WIN_ABS_PATH_PATTERN = /(?<![A-Za-z0-9])([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
|
|
172
172
|
/** POSIX absolute path tokens inside a command string (HarmonyOS/POSIX Hosts). */
|
|
173
173
|
const POSIX_ABS_PATH_PATTERN = /(?:^|[\s'"`(=])(\/(?!\/)[^\s'"`,;|&)}\]<>]+)/g
|
|
174
|
+
// ── v0.11.0: light data-flow for shell commands ─────────────────────────────
|
|
175
|
+
/**
|
|
176
|
+
* A path held in a variable used to bypass the guard entirely: only literal paths
|
|
177
|
+
* inside the *same* statement segment were scanned, so
|
|
178
|
+
* `$out = "C:\Users\me\Desktop\x.cmd"` + `[IO.File]::WriteAllLines($out, …)` passed.
|
|
179
|
+
* The patterns below let the guard resolve a path assigned in one statement and later
|
|
180
|
+
* used in a write *target position* (first argument of a write API, a path parameter,
|
|
181
|
+
* the destination of a copy, a redirection target), while never treating a read source
|
|
182
|
+
* or a content variable as a write target — ordinary scripts keep working.
|
|
183
|
+
*/
|
|
184
|
+
const SIMPLE_ASSIGNMENT =
|
|
185
|
+
/^\s*(?:\$([A-Za-z_][A-Za-z0-9_]*)|set\s+([A-Za-z_][A-Za-z0-9_]*)|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*([\s\S]*)$/
|
|
186
|
+
/** First argument of a .NET write API (`[IO.File]::WriteAllLines($out, …)`). */
|
|
187
|
+
const WRITE_API_FIRST_ARG =
|
|
188
|
+
/\b(?:WriteAllText|WriteAllBytes|WriteAllLines|AppendAllText|AppendAllBytes|AppendAllLines|CreateText|OpenWrite)\s*\(\s*\(*\s*([^,()\r\n]+)/gi
|
|
189
|
+
/** Explicit write-target parameters (`-Path`, `-LiteralPath`, `-OutFile`, `-Destination`…). */
|
|
190
|
+
const TARGET_PARAM_ARG =
|
|
191
|
+
/-(Path|LiteralPath|FilePath|OutFile|OutFilePath|Destination|DestinationPath|Dest|Target|TargetPath|OutputFile|OutputPath|SavePath|To)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&"']+))/gi
|
|
192
|
+
/** First positional argument of the path-first write cmdlets. */
|
|
193
|
+
const FIRST_POSITIONAL_TARGET_ARG =
|
|
194
|
+
/\b(?:Set-Content|Add-Content|Out-File|tee|mkdir|md|ni)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&"'-][^\s;|&"']*))/gi
|
|
195
|
+
/** `New-Item` positional form: the first quoted argument after the cmdlet. */
|
|
196
|
+
const NEW_ITEM_QUOTED_ARG = /\bNew-Item\b[^;|&\r\n]*?(?:"([^"\r\n]*)"|'([^'\r\n]*)')/gi
|
|
197
|
+
/** curl / wget output flags. */
|
|
198
|
+
const CURL_OUTPUT_ARG = /\bcurl\b[^;|&\r\n]*?\s(?:-o|--output)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&]+))/gi
|
|
199
|
+
const WGET_OUTPUT_ARG = /\bwget\b[^;|&\r\n]*?\s(?:-O|--output-document)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&]+))/gi
|
|
200
|
+
/** ffmpeg: the last argument is the output file. */
|
|
201
|
+
const FFMPEG_TAIL = /\bffmpeg(?:\.exe)?\b([^;|&\r\n]*)$/i
|
|
202
|
+
/** Values that can be a real path: drive / UNC / root / tilde / env var / `$HOME` anchored. */
|
|
203
|
+
const PATH_VALUE_ANCHOR = /^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/]|\$\{?env:|\$HOME\b|%[A-Za-z_][A-Za-z0-9_]*%)/
|
|
204
|
+
/** Only these environment variable names may be expanded into a path. */
|
|
205
|
+
const EXPANDABLE_ENV_NAMES = new Set([
|
|
206
|
+
'USERPROFILE',
|
|
207
|
+
'HOME',
|
|
208
|
+
'HOMEDRIVE',
|
|
209
|
+
'HOMEPATH',
|
|
210
|
+
'TEMP',
|
|
211
|
+
'TMP',
|
|
212
|
+
'APPDATA',
|
|
213
|
+
'LOCALAPPDATA',
|
|
214
|
+
'PUBLIC',
|
|
215
|
+
])
|
|
174
216
|
/** v0.8 claim-on-write: relative `<rootDirName>/<dir>` mentions in a shell command. */
|
|
175
217
|
const TMP_RELATIVE_PATTERN = /(?:^|[\s'"`(=,;|&])(\.{0,2}[\\/]?_tmp[\\/][^\s'"`,;|&)}\]>]+)/g
|
|
176
218
|
/** v0.8: shell verbs that create a directory (so an exact `<root>/<dir>` target is a folder). */
|
|
@@ -347,11 +389,11 @@ export function buildPromptText(cfg) {
|
|
|
347
389
|
'After the user agrees, call `longterm_approve` with that file path, then write it; add mode=dir only when the user explicitly wants the whole directory writable.',
|
|
348
390
|
`If the user declines, says temporary, or the content is scratch: call \`task_tmpdir\` and write under \`${rootDirName}/<会话标题>/\`. Never invent a workspace-root file or folder instead.`,
|
|
349
391
|
'',
|
|
350
|
-
`The write guard denies creating new files outside \`${rootDirName}/\` that this session has not approved: \`write\`/\`edit\`, shell commands (\`pwsh\`/\`bash\`, including \`ffmpeg\`/\`pandoc\`/\`Export-*\` and .NET write APIs), \`publish\` copies, embedded code runtimes and any other tool that declares path arguments. Allowed without approval: \`${rootDirName}/\`, approved files/directories, existing files (overwrite), existing plugin-source trees (${allowRootPatterns.join(', ')}), root files ${allowRootFiles.join(', ') || '(none)'}, DSH's own home, caches and the OS temp directory.`,
|
|
392
|
+
`The write guard denies creating new files outside \`${rootDirName}/\` that this session has not approved: \`write\`/\`edit\`, shell commands (\`pwsh\`/\`bash\`, including paths held in variables, environment variables or \`~\`, \`ffmpeg\`/\`pandoc\`/\`Export-*\` and .NET write APIs), \`publish\` copies, embedded code runtimes and any other tool that declares path arguments. Allowed without approval: \`${rootDirName}/\`, approved files/directories, existing files (overwrite), existing plugin-source trees (${allowRootPatterns.join(', ')}), root files ${allowRootFiles.join(', ') || '(none)'}, DSH's own home, caches and the OS temp directory.`,
|
|
351
393
|
'',
|
|
352
394
|
'### Whitelist panel',
|
|
353
395
|
'',
|
|
354
|
-
`Every approval is stored in the **cloud-synced** file \`<DSH_HOME>/data/tmpdir-guard/approvals.json\` (outside cloud-sync's \`data/session-tmpdir-*\` exclusions).
|
|
396
|
+
`Every approval is stored in the **cloud-synced** file \`<DSH_HOME>/data/tmpdir-guard/approvals.json\` (outside cloud-sync's \`data/session-tmpdir-*\` exclusions). Paths under the user's home are stored **portably** (\`~/...\`) and expanded against each machine's home. Entries carry their origin machine and are merged by id (with tombstones for removals); each machine only auto-prunes entries it created, and entries whose target no longer exists are pruned when the panel refreshes (foreign-machine entries are kept unless never seen anywhere for 7 days). The panel lists the whole shared whitelist and marks entries whose expanded path is missing on this machine as 「本机无此路径」. **An approval authorizes only the session that created it** (resuming that same session on another machine keeps it); an identical path approved by a different session does NOT open the guard — this matters when reading the shared panel.`,
|
|
355
397
|
].join('\n')
|
|
356
398
|
}
|
|
357
399
|
|
|
@@ -599,21 +641,85 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
599
641
|
guardOutsideWorkspace,
|
|
600
642
|
}
|
|
601
643
|
|
|
644
|
+
/** Judge one resolved absolute target; returns a denial reason or undefined. */
|
|
645
|
+
function judgeTargetPath(abs) {
|
|
646
|
+
if (isDevicePath(abs)) return undefined
|
|
647
|
+
// v0.8 claim-on-write: report every resolved target so the caller can attribute
|
|
648
|
+
// unmarked `<rootDirName>/<dir>/` folders to the acting session.
|
|
649
|
+
if (typeof options.onTarget === 'function') {
|
|
650
|
+
try {
|
|
651
|
+
options.onTarget(abs)
|
|
652
|
+
} catch {
|
|
653
|
+
// a reporting callback never changes the verdict
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const verdict = classifyWriteTarget(abs, base, classifyOptions)
|
|
657
|
+
if (verdict.kind === 'allowed' || verdict.kind === 'skip') return undefined
|
|
658
|
+
// v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
|
|
659
|
+
if (allowOverwrite && pathExists(abs)) return undefined
|
|
660
|
+
if (verdict.kind === 'outside') {
|
|
661
|
+
if (guardOutsideWorkspace === 'warn') {
|
|
662
|
+
console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
|
|
663
|
+
return undefined
|
|
664
|
+
}
|
|
665
|
+
return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
|
|
666
|
+
}
|
|
667
|
+
// inside the workspace but not approved / not scratch
|
|
668
|
+
if (skipInside) return undefined
|
|
669
|
+
const first = firstSegmentUnder(base, abs)
|
|
670
|
+
if (samePath(dirname(abs), base)) {
|
|
671
|
+
return (
|
|
672
|
+
`命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),` +
|
|
673
|
+
`同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
|
|
674
|
+
)
|
|
675
|
+
}
|
|
676
|
+
return (
|
|
677
|
+
`命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
|
|
678
|
+
`若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),同意后 longterm_approve 登记目录再执行;` +
|
|
679
|
+
`临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
|
|
680
|
+
)
|
|
681
|
+
}
|
|
682
|
+
|
|
602
683
|
/** Judge one statement segment (`;` / `&&` / `||` / `|` / newline separated). */
|
|
603
|
-
function judgeSegment(segment) {
|
|
684
|
+
function judgeSegment(segment, symbols, segmentStart = 0, quoteRanges = []) {
|
|
604
685
|
// v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
|
|
605
686
|
// parsed as one token instead of leaving a second `>` behind. Quoted text such as
|
|
606
687
|
// `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
|
|
607
688
|
const redirectTokens = new Set()
|
|
689
|
+
const dynamicRedirectTokens = []
|
|
608
690
|
for (const match of segment.matchAll(REDIRECT_ALL_PATTERN)) {
|
|
609
691
|
const token = match[1] ?? match[2] ?? match[3]
|
|
610
692
|
if (!token) continue
|
|
611
693
|
const cleaned = token.replace(/["'`]+$/, '')
|
|
612
694
|
if (!cleaned || /^>+$/.test(cleaned)) continue
|
|
695
|
+
// v0.11.0: `> $log` / `> $d\out.txt` is resolved through the assigned value; the
|
|
696
|
+
// raw text must not be resolved against the workspace cwd (it always looked like
|
|
697
|
+
// `<workspace>/$log`, which produced a bogus "workspace root entry" denial).
|
|
698
|
+
const dynamic =
|
|
699
|
+
match[2] === undefined &&
|
|
700
|
+
isDynamicPathToken(cleaned) &&
|
|
701
|
+
!indexInsideRanges(segmentStart + match.index, quoteRanges)
|
|
702
|
+
// Dynamic redirects never count as `hasRedirect`: `… > $null` / `2> $null` are the
|
|
703
|
+
// usual "silence output" idiom of read-only commands and must not drag the segment
|
|
704
|
+
// into the literal scan (they are judged separately, and `$null` resolves to none).
|
|
705
|
+
if (dynamic) {
|
|
706
|
+
dynamicRedirectTokens.push(token)
|
|
707
|
+
continue
|
|
708
|
+
}
|
|
613
709
|
if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
|
|
614
710
|
redirectTokens.add(token)
|
|
615
711
|
}
|
|
616
712
|
const hasRedirect = redirectTokens.size > 0
|
|
713
|
+
/** v0.11.0: dynamic redirection targets are writes even in read-only statements. */
|
|
714
|
+
const judgeDynamicRedirects = () => {
|
|
715
|
+
if (dynamicRedirectTokens.length === 0) return undefined
|
|
716
|
+
const options = { platform, dynamicRedirectTokens, quoteRanges, quoteOffset: segmentStart }
|
|
717
|
+
for (const abs of dynamicWriteTargets(segment, symbols, options)) {
|
|
718
|
+
const reason = judgeTargetPath(abs)
|
|
719
|
+
if (reason) return reason
|
|
720
|
+
}
|
|
721
|
+
return undefined
|
|
722
|
+
}
|
|
617
723
|
// v0.10.1:只调用解释器(node/python/perl/ruby)的段落用“代码静态扫描”判定,
|
|
618
724
|
// 不把命令文本里的任意绝对路径当成写目标(否则字符串里的示例路径会误伤)。
|
|
619
725
|
if (
|
|
@@ -623,6 +729,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
623
729
|
!WRITE_PROGRAM_PATTERN.test(segment) &&
|
|
624
730
|
!DOWNLOAD_WRITE_PATTERN.test(segment)
|
|
625
731
|
) {
|
|
732
|
+
const redirectReason = judgeDynamicRedirects()
|
|
733
|
+
if (redirectReason) return redirectReason
|
|
626
734
|
return codeToolGuardReason(segment, base, {
|
|
627
735
|
...classifyOptions,
|
|
628
736
|
guardOutsideWorkspace,
|
|
@@ -635,12 +743,15 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
635
743
|
!WRITE_PROGRAM_PATTERN.test(segment) &&
|
|
636
744
|
!DOWNLOAD_WRITE_PATTERN.test(segment)
|
|
637
745
|
) {
|
|
638
|
-
// v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged
|
|
639
|
-
|
|
746
|
+
// v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged,
|
|
747
|
+
// except for a dynamic redirection target (`Test-Path $p > $log`).
|
|
748
|
+
return judgeDynamicRedirects()
|
|
640
749
|
}
|
|
641
750
|
// v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
|
|
642
|
-
// Windows drive-path pattern would otherwise treat as a directory.
|
|
643
|
-
|
|
751
|
+
// Windows drive-path pattern would otherwise treat as a directory. v0.11.0: only run
|
|
752
|
+
// the replace when a URL scheme is actually present (the URL regex backtracks badly
|
|
753
|
+
// on a very long single-line argument without `://`).
|
|
754
|
+
const scanText = segment.includes('://') ? segment.replace(URL_PATTERN, ' ') : segment
|
|
644
755
|
const ordered = []
|
|
645
756
|
for (const match of scanText.matchAll(pathPattern)) ordered.push(match[1])
|
|
646
757
|
const tokens = new Set([...redirectTokens, ...ordered])
|
|
@@ -670,54 +781,458 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
|
|
|
670
781
|
} catch {
|
|
671
782
|
continue
|
|
672
783
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
784
|
+
const reason = judgeTargetPath(abs)
|
|
785
|
+
if (reason) return reason
|
|
786
|
+
}
|
|
787
|
+
// v0.11.0: variable / environment / `~` paths in write-target positions. Only target
|
|
788
|
+
// positions are resolved, so read sources and content strings are never blamed.
|
|
789
|
+
for (const abs of dynamicWriteTargets(segment, symbols, {
|
|
790
|
+
platform,
|
|
791
|
+
dynamicRedirectTokens,
|
|
792
|
+
quoteRanges,
|
|
793
|
+
quoteOffset: segmentStart,
|
|
794
|
+
})) {
|
|
795
|
+
const reason = judgeTargetPath(abs)
|
|
796
|
+
if (reason) return reason
|
|
797
|
+
}
|
|
798
|
+
return undefined
|
|
799
|
+
}
|
|
800
|
+
|
|
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.
|
|
805
|
+
const commandText = stripComments(blankEmbeddedScripts(String(command)))
|
|
806
|
+
const quoteRanges = quotedRanges(commandText)
|
|
807
|
+
// v0.11.0: paths assigned in earlier statements of the same command (best effort).
|
|
808
|
+
const symbols = new Map()
|
|
809
|
+
for (const entry of splitSegmentsWithOffsets(commandText)) {
|
|
810
|
+
const reason = judgeSegment(entry.text, symbols, entry.start, quoteRanges)
|
|
811
|
+
if (reason) return reason
|
|
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)
|
|
814
|
+
}
|
|
815
|
+
return undefined
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// ── v0.11.0: helpers for the light shell data-flow ──────────────────────────
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Blank the *content* of embedded scripts (PowerShell here-strings `@"…"@` / `@'…'@`
|
|
822
|
+
* and POSIX heredocs `<<EOF`) before statement segmentation. Models generate
|
|
823
|
+
* `.ps1`/`.cmd`/`.sh` files this way; their content is data, not commands of this
|
|
824
|
+
* invocation, so a path or `$var = '…'` line inside it must never be judged as a write.
|
|
825
|
+
* The opening line keeps its prefix (the real command) and code that follows the
|
|
826
|
+
* closing delimiter is kept too; only the data lines are blanked. Newlines are
|
|
827
|
+
* preserved so line-accurate segmentation still works. An unclosed block is treated as
|
|
828
|
+
* "everything after it is data" — such a command cannot run anyway (syntax error).
|
|
829
|
+
*/
|
|
830
|
+
function blankEmbeddedScripts(command) {
|
|
831
|
+
const text = String(command ?? '')
|
|
832
|
+
if (!text.includes('@"') && !text.includes("@'") && !text.includes('<<')) return text
|
|
833
|
+
const lines = text.split('\n')
|
|
834
|
+
const out = []
|
|
835
|
+
const blank = (line) => line.replace(/[^\r]/g, ' ')
|
|
836
|
+
/** Odd number of quotes before `end` means the `@`/`<<` sits inside a quoted string. */
|
|
837
|
+
const quoteParity = (line, end) => {
|
|
838
|
+
let count = 0
|
|
839
|
+
for (let i = 0; i < end; i += 1) {
|
|
840
|
+
const ch = line[i]
|
|
841
|
+
if (ch === '`') {
|
|
842
|
+
i += 1
|
|
843
|
+
continue
|
|
844
|
+
}
|
|
845
|
+
if (ch === '"' || ch === "'") count += 1
|
|
846
|
+
}
|
|
847
|
+
return count % 2
|
|
848
|
+
}
|
|
849
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
850
|
+
const line = lines[index]
|
|
851
|
+
const bare = line.replace(/\r$/, '')
|
|
852
|
+
// PowerShell here-string opening: `@"` / `@'` ends the line, outside another quote.
|
|
853
|
+
const open = /(?<!["'\w])@(["'])\s*$/.exec(bare)
|
|
854
|
+
if (open && quoteParity(bare, open.index) === 0) {
|
|
855
|
+
const quote = open[1]
|
|
856
|
+
const closePattern = quote === '"' ? /^\s*"\s*@\s*/ : /^\s*'\s*@\s*/
|
|
857
|
+
let closeIndex = -1
|
|
858
|
+
for (let j = index + 1; j < lines.length; j += 1) {
|
|
859
|
+
if (closePattern.test(lines[j].replace(/\r$/, ''))) {
|
|
860
|
+
closeIndex = j
|
|
861
|
+
break
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
// Blank the opening `@"` / `@'` as well: keeping it would leave an unterminated
|
|
865
|
+
// quote behind, and every later statement would be swallowed as "quoted text".
|
|
866
|
+
out.push(line.slice(0, open.index) + ' ' + line.slice(open.index + 2))
|
|
867
|
+
if (closeIndex === -1) {
|
|
868
|
+
for (let j = index + 1; j < lines.length; j += 1) out.push(blank(lines[j]))
|
|
869
|
+
index = lines.length
|
|
870
|
+
break
|
|
871
|
+
}
|
|
872
|
+
for (let j = index + 1; j < closeIndex; j += 1) out.push(blank(lines[j]))
|
|
873
|
+
// Keep code that follows the terminator on its line (`"@; Set-Content …`).
|
|
874
|
+
const closeBare = lines[closeIndex]
|
|
875
|
+
const head = closePattern.exec(closeBare.replace(/\r$/, ''))
|
|
876
|
+
out.push(head ? blank(head[0]) + closeBare.slice(head[0].length) : blank(closeBare))
|
|
877
|
+
index = closeIndex
|
|
878
|
+
continue
|
|
879
|
+
}
|
|
880
|
+
// POSIX heredoc opening: `<< EOF` / `<<'EOF'`, outside another quote.
|
|
881
|
+
const heredoc = /(?<!<)<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(bare)
|
|
882
|
+
if (heredoc && quoteParity(bare, heredoc.index) === 0) {
|
|
883
|
+
const tag = heredoc[2]
|
|
884
|
+
let closeIndex = -1
|
|
885
|
+
for (let j = index + 1; j < lines.length; j += 1) {
|
|
886
|
+
if (lines[j].replace(/\r$/, '').trim() === tag) {
|
|
887
|
+
closeIndex = j
|
|
888
|
+
break
|
|
681
889
|
}
|
|
682
890
|
}
|
|
683
|
-
|
|
684
|
-
if (
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
891
|
+
out.push(line)
|
|
892
|
+
if (closeIndex === -1) {
|
|
893
|
+
for (let j = index + 1; j < lines.length; j += 1) out.push(blank(lines[j]))
|
|
894
|
+
index = lines.length
|
|
895
|
+
break
|
|
896
|
+
}
|
|
897
|
+
for (let j = index + 1; j < closeIndex; j += 1) out.push(blank(lines[j]))
|
|
898
|
+
out.push(blank(lines[closeIndex]))
|
|
899
|
+
index = closeIndex
|
|
900
|
+
continue
|
|
901
|
+
}
|
|
902
|
+
out.push(line)
|
|
903
|
+
}
|
|
904
|
+
return out.join('\n')
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* v0.11.0: drop PowerShell/POSIX comments before segmentation. A commented-out command
|
|
909
|
+
* (`# Set-Content -Path $env:APPDATA\x …`) is not a write target; block comments
|
|
910
|
+
* (`<# … #>`) count too. Quoted text is kept; quote state is tracked per line (here-string
|
|
911
|
+
* content is already blanked) and block comments may span lines.
|
|
912
|
+
*/
|
|
913
|
+
function stripComments(command) {
|
|
914
|
+
const text = String(command ?? '')
|
|
915
|
+
if (!text.includes('#')) return text
|
|
916
|
+
const out = text.split('')
|
|
917
|
+
let block = false
|
|
918
|
+
for (let i = 0; i < out.length; i += 1) {
|
|
919
|
+
if (out[i] === '\n') continue
|
|
920
|
+
let quote = ''
|
|
921
|
+
let j = i
|
|
922
|
+
while (j < out.length && out[j] !== '\n') {
|
|
923
|
+
const ch = out[j]
|
|
924
|
+
if (block) {
|
|
925
|
+
if (ch === '#' && out[j + 1] === '>') {
|
|
926
|
+
out[j] = ' '
|
|
927
|
+
out[j + 1] = ' '
|
|
928
|
+
j += 2
|
|
929
|
+
block = false
|
|
690
930
|
continue
|
|
691
931
|
}
|
|
692
|
-
|
|
932
|
+
out[j] = ' '
|
|
933
|
+
j += 1
|
|
934
|
+
continue
|
|
693
935
|
}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
936
|
+
if (quote) {
|
|
937
|
+
if (quote === '"' && ch === '`') {
|
|
938
|
+
j += 2
|
|
939
|
+
continue
|
|
940
|
+
}
|
|
941
|
+
if (ch === quote) quote = ''
|
|
942
|
+
j += 1
|
|
943
|
+
continue
|
|
702
944
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
945
|
+
if (ch === '"' || ch === "'") {
|
|
946
|
+
quote = ch
|
|
947
|
+
j += 1
|
|
948
|
+
continue
|
|
949
|
+
}
|
|
950
|
+
if (ch === '<' && out[j + 1] === '#') {
|
|
951
|
+
out[j] = ' '
|
|
952
|
+
out[j + 1] = ' '
|
|
953
|
+
j += 2
|
|
954
|
+
block = true
|
|
955
|
+
continue
|
|
956
|
+
}
|
|
957
|
+
if (ch === '#') {
|
|
958
|
+
const prev = j > 0 ? out[j - 1] : ' '
|
|
959
|
+
if (!prev || /[\s;|&(){},=]/.test(prev)) {
|
|
960
|
+
while (j < out.length && out[j] !== '\n') {
|
|
961
|
+
out[j] = ' '
|
|
962
|
+
j += 1
|
|
963
|
+
}
|
|
964
|
+
continue
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
j += 1
|
|
968
|
+
}
|
|
969
|
+
i = j - 1
|
|
970
|
+
}
|
|
971
|
+
return out.join('')
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
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.
|
|
979
|
+
*/
|
|
980
|
+
function splitSegmentsWithOffsets(command) {
|
|
981
|
+
const text = String(command ?? '')
|
|
982
|
+
const segments = []
|
|
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
|
|
995
|
+
}
|
|
996
|
+
push(last, text.length)
|
|
997
|
+
return segments
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Parenthesis depth for every character of a segment (quotes ignored), so a read-only
|
|
1002
|
+
* `-Path` inside `-Value (Get-Content -Path $x)` is not blamed as a write target.
|
|
1003
|
+
*/
|
|
1004
|
+
function parenDepthMap(text, quoteRanges = [], offset = 0) {
|
|
1005
|
+
const depth = new Int32Array(text.length + 1)
|
|
1006
|
+
let current = 0
|
|
1007
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
1008
|
+
depth[i] = current
|
|
1009
|
+
if (indexInsideRanges(offset + i, quoteRanges)) continue
|
|
1010
|
+
const ch = text[i]
|
|
1011
|
+
if (ch === '(') current += 1
|
|
1012
|
+
else if (ch === ')') current = Math.max(0, current - 1)
|
|
1013
|
+
}
|
|
1014
|
+
depth[text.length] = current
|
|
1015
|
+
return depth
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** True for tokens that must be resolved (variables, environment markers, `~`). */
|
|
1019
|
+
function isDynamicPathToken(text) {
|
|
1020
|
+
const value = String(text ?? '')
|
|
1021
|
+
return /[$%]/.test(value) || /^~(?:[\\/]|$)/.test(value)
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/** Only well-known environment names expand; anything else stays unresolved. */
|
|
1025
|
+
function envPathValue(name) {
|
|
1026
|
+
const key = String(name ?? '').toUpperCase()
|
|
1027
|
+
if (!EXPANDABLE_ENV_NAMES.has(key)) return undefined
|
|
1028
|
+
const value = process.env[key] ?? (key === 'HOME' ? homedir() : undefined)
|
|
1029
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* Quoted ranges inside one segment, so a `-Path`/write-API mention that only exists
|
|
1034
|
+
* inside a content string (`-Value "… -Path $x …"`) is never read as a real target.
|
|
1035
|
+
*/
|
|
1036
|
+
function quotedRanges(text) {
|
|
1037
|
+
const ranges = []
|
|
1038
|
+
let i = 0
|
|
1039
|
+
while (i < text.length) {
|
|
1040
|
+
const quote = text[i]
|
|
1041
|
+
if (quote !== '"' && quote !== "'") {
|
|
1042
|
+
i += 1
|
|
1043
|
+
continue
|
|
1044
|
+
}
|
|
1045
|
+
const start = i
|
|
1046
|
+
i += 1
|
|
1047
|
+
while (i < text.length) {
|
|
1048
|
+
if (text[i] === '`') {
|
|
1049
|
+
i += 2
|
|
1050
|
+
continue
|
|
1051
|
+
}
|
|
1052
|
+
if (quote === '"' && text[i] === '"' && text[i + 1] === '"') {
|
|
1053
|
+
i += 2
|
|
1054
|
+
continue
|
|
1055
|
+
}
|
|
1056
|
+
if (text[i] === quote) break
|
|
1057
|
+
i += 1
|
|
708
1058
|
}
|
|
1059
|
+
ranges.push([start, Math.min(i + 1, text.length)])
|
|
1060
|
+
i += 1
|
|
1061
|
+
}
|
|
1062
|
+
return ranges
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/** True when `index` falls inside one of the quoted ranges. */
|
|
1066
|
+
function indexInsideRanges(index, ranges) {
|
|
1067
|
+
for (const [start, end] of ranges) {
|
|
1068
|
+
if (index >= start && index < end) return true
|
|
1069
|
+
}
|
|
1070
|
+
return false
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Resolve one path expression to an absolute path. Returns undefined when the token is
|
|
1075
|
+
* not a path or still contains something the guard cannot resolve; such a token is left
|
|
1076
|
+
* to the old literal scan instead of being guessed.
|
|
1077
|
+
*/
|
|
1078
|
+
function resolveDynamicPathExpression(raw, symbols, platform) {
|
|
1079
|
+
let text = String(raw ?? '').trim()
|
|
1080
|
+
if (!text || text.length > 1024) return undefined
|
|
1081
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1)
|
|
1082
|
+
if (!text || /[\r\n`]/.test(text) || text.includes('$(')) return undefined
|
|
1083
|
+
// 1) variables assigned earlier in the same command text
|
|
1084
|
+
text = text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, braced, plain) => {
|
|
1085
|
+
const value = symbols.get(braced ?? plain)
|
|
1086
|
+
return value === undefined ? whole : value
|
|
1087
|
+
})
|
|
1088
|
+
// 2) well-known environment variables, `$HOME` and `~`
|
|
1089
|
+
text = text.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/gi, (whole, name) => envPathValue(name) ?? whole)
|
|
1090
|
+
text = text.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (whole, name) => envPathValue(name) ?? whole)
|
|
1091
|
+
text = text.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (whole, name) => envPathValue(name) ?? whole)
|
|
1092
|
+
if (/\$HOME\b/.test(text)) text = text.replace(/\$HOME\b/g, homedir())
|
|
1093
|
+
text = expandTildePath(text)
|
|
1094
|
+
if (!text || /[$%]/.test(text) || /[*?]/.test(text)) return undefined
|
|
1095
|
+
const absolute =
|
|
1096
|
+
platform === 'win32' ? /^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(text) : /^[A-Za-z]:[\\/]/.test(text) || /^\//.test(text)
|
|
1097
|
+
if (!absolute) return undefined
|
|
1098
|
+
try {
|
|
1099
|
+
return resolve(text)
|
|
1100
|
+
} catch {
|
|
709
1101
|
return undefined
|
|
710
1102
|
}
|
|
1103
|
+
}
|
|
711
1104
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
1105
|
+
/**
|
|
1106
|
+
* Record `$var = '<path>'` / `NAME=<path>` / `set VAR=<path>` for later statements.
|
|
1107
|
+
* Only a single-line value that already looks like an absolute path is kept, so content
|
|
1108
|
+
* strings, here-strings, command substitutions and relative paths never enter the map.
|
|
1109
|
+
*/
|
|
1110
|
+
function collectPathAssignment(segment, symbols, platform = process.platform) {
|
|
1111
|
+
if (symbols.size >= 500) return
|
|
1112
|
+
const match = SIMPLE_ASSIGNMENT.exec(String(segment ?? ''))
|
|
1113
|
+
if (!match) return
|
|
1114
|
+
const name = match[1] ?? match[2] ?? match[3]
|
|
1115
|
+
if (!name) return
|
|
1116
|
+
// `NAME=value` is an assignment only in POSIX shells; `set NAME=value` only in cmd.exe.
|
|
1117
|
+
// PowerShell (the Windows shell channel) has neither form, so do not poison the map.
|
|
1118
|
+
if (match[3] !== undefined && platform === 'win32') return
|
|
1119
|
+
if (match[2] !== undefined && platform !== 'win32') return
|
|
1120
|
+
let raw = String(match[4] ?? '').trim()
|
|
1121
|
+
// strip an optional trailing brace from `if (x) { $p = '…' }`
|
|
1122
|
+
if (raw.endsWith('}')) raw = raw.slice(0, -1).trim()
|
|
1123
|
+
let singleQuoted = false
|
|
1124
|
+
if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
|
|
1125
|
+
raw = raw.slice(1, -1)
|
|
1126
|
+
} else if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
|
|
1127
|
+
raw = raw.slice(1, -1)
|
|
1128
|
+
singleQuoted = true
|
|
1129
|
+
}
|
|
1130
|
+
if (!raw || raw.length > 1024) return
|
|
1131
|
+
if (/[\r\n`]/.test(raw) || raw.includes('$(')) return
|
|
1132
|
+
if (/[;,|]/.test(raw)) return
|
|
1133
|
+
if (/[*?]/.test(raw)) return
|
|
1134
|
+
if (singleQuoted && /[$%]/.test(raw)) return
|
|
1135
|
+
if (!PATH_VALUE_ANCHOR.test(raw) || !/[\\/]/.test(raw)) return
|
|
1136
|
+
symbols.set(name, raw)
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Index of the first write signal in a segment (`-1` when the segment only reads).
|
|
1141
|
+
* v0.11.0: a read-only `-Path` (e.g. `Test-Path -Path $p`) that appears *before* the
|
|
1142
|
+
* actual write command in the same segment must not be blamed as a write target.
|
|
1143
|
+
*/
|
|
1144
|
+
function firstWriteSignalIndex(segment) {
|
|
1145
|
+
let best = -1
|
|
1146
|
+
for (const pattern of [CREATE_VERB_PATTERN, WRITE_PROGRAM_PATTERN, DOWNLOAD_WRITE_PATTERN]) {
|
|
1147
|
+
const match = pattern.exec(segment)
|
|
1148
|
+
if (match && (best === -1 || match.index < best)) best = match.index
|
|
719
1149
|
}
|
|
720
|
-
return
|
|
1150
|
+
return best
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** Strip wrapping punctuation around an argument token (`$p)`, `{…}`, `"…"`). */
|
|
1154
|
+
function stripArgEdge(text) {
|
|
1155
|
+
return String(text ?? '')
|
|
1156
|
+
.trim()
|
|
1157
|
+
.replace(/^[([{]+/, '')
|
|
1158
|
+
.replace(/[)\]},]+$/, '')
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* v0.11.0: absolute paths that this segment creates/overwrites but expresses through a
|
|
1163
|
+
* variable, an environment variable or `~`. Only write *target* positions are resolved:
|
|
1164
|
+
* the first argument of a write API, explicit path parameters, the first positional
|
|
1165
|
+
* argument of path-first cmdlets, copy destinations, redirections and download/ffmpeg
|
|
1166
|
+
* outputs. Sources, content arguments and read-only parameters (a `-Path` in front of
|
|
1167
|
+
* the write command) are deliberately ignored.
|
|
1168
|
+
*/
|
|
1169
|
+
function dynamicWriteTargets(segment, symbols, options = {}) {
|
|
1170
|
+
const { platform = process.platform, dynamicRedirectTokens = [], quoteRanges = [], quoteOffset = 0 } = options
|
|
1171
|
+
const found = new Set()
|
|
1172
|
+
const firstWrite = firstWriteSignalIndex(segment)
|
|
1173
|
+
const copyLike = COPY_LIKE_VERB_PATTERN.test(segment)
|
|
1174
|
+
const depthAt = segment.includes('(') ? parenDepthMap(segment, quoteRanges, quoteOffset) : undefined
|
|
1175
|
+
/** Resolve a token only when it is dynamic AND not inside quoted content text. */
|
|
1176
|
+
const push = (raw) => {
|
|
1177
|
+
if (raw === undefined || raw === null) return
|
|
1178
|
+
const text = stripArgEdge(raw)
|
|
1179
|
+
if (!text || !isDynamicPathToken(text)) return // literals are handled by the old scan
|
|
1180
|
+
const abs = resolveDynamicPathExpression(text, symbols, platform)
|
|
1181
|
+
if (abs) found.add(abs)
|
|
1182
|
+
}
|
|
1183
|
+
const inTargetRegion = (index) =>
|
|
1184
|
+
firstWrite >= 0 && index >= firstWrite && !indexInsideRanges(quoteOffset + index, quoteRanges)
|
|
1185
|
+
// A) redirection targets (`> $log`, `4> $d\out.txt`)
|
|
1186
|
+
for (const raw of dynamicRedirectTokens) push(raw)
|
|
1187
|
+
// B) first argument of a .NET write API
|
|
1188
|
+
for (const match of segment.matchAll(WRITE_API_FIRST_ARG)) {
|
|
1189
|
+
if (inTargetRegion(match.index)) push(match[1])
|
|
1190
|
+
}
|
|
1191
|
+
// C) explicit write-target parameters (`-Path`, `-Destination`, `-OutFile`, …)
|
|
1192
|
+
for (const match of segment.matchAll(TARGET_PARAM_ARG)) {
|
|
1193
|
+
if (!inTargetRegion(match.index)) continue
|
|
1194
|
+
// `-Path` / `-LiteralPath` on a copy-like command is the source, never the destination.
|
|
1195
|
+
if (copyLike && /^(?:Path|LiteralPath)$/i.test(match[1])) continue
|
|
1196
|
+
// A read-only `-Path` inside an argument subexpression (`-Value (Get-Content -Path $x)`).
|
|
1197
|
+
if (depthAt && depthAt[match.index] > 0) continue
|
|
1198
|
+
push(match[2] ?? match[4])
|
|
1199
|
+
}
|
|
1200
|
+
// D) first positional argument of path-first cmdlets
|
|
1201
|
+
for (const match of segment.matchAll(FIRST_POSITIONAL_TARGET_ARG)) {
|
|
1202
|
+
if (inTargetRegion(match.index)) push(match[1] ?? match[3])
|
|
1203
|
+
}
|
|
1204
|
+
// E) `New-Item` positional form
|
|
1205
|
+
for (const match of segment.matchAll(NEW_ITEM_QUOTED_ARG)) {
|
|
1206
|
+
if (inTargetRegion(match.index)) push(match[1])
|
|
1207
|
+
}
|
|
1208
|
+
// F) curl / wget output flags
|
|
1209
|
+
for (const match of segment.matchAll(CURL_OUTPUT_ARG)) {
|
|
1210
|
+
if (inTargetRegion(match.index)) push(match[1] ?? match[3])
|
|
1211
|
+
}
|
|
1212
|
+
for (const match of segment.matchAll(WGET_OUTPUT_ARG)) {
|
|
1213
|
+
if (inTargetRegion(match.index)) push(match[1] ?? match[3])
|
|
1214
|
+
}
|
|
1215
|
+
// G) ffmpeg output = last argument of the ffmpeg invocation
|
|
1216
|
+
const ffmpeg = FFMPEG_TAIL.exec(segment)
|
|
1217
|
+
if (ffmpeg && inTargetRegion(ffmpeg.index)) {
|
|
1218
|
+
const args = ffmpeg[1].trim().match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? []
|
|
1219
|
+
const last = args.map(stripArgEdge).filter((token) => token && !/^[()[\]{}]+$/.test(token)).pop()
|
|
1220
|
+
push(last)
|
|
1221
|
+
}
|
|
1222
|
+
// H) positional destination of a copy-like command (`-Destination` is covered above)
|
|
1223
|
+
if (!DESTINATION_FLAG_PATTERN.test(segment)) {
|
|
1224
|
+
const copy = COPY_LIKE_VERB_PATTERN.exec(segment)
|
|
1225
|
+
if (copy && inTargetRegion(copy.index)) {
|
|
1226
|
+
const tail = segment.slice(copy.index)
|
|
1227
|
+
const args = tail.match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? []
|
|
1228
|
+
const last = [...args]
|
|
1229
|
+
.reverse()
|
|
1230
|
+
.map(stripArgEdge)
|
|
1231
|
+
.find((token) => token && !token.startsWith('-') && !/^[()[\]{}]+$/.test(token))
|
|
1232
|
+
push(last)
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
return [...found]
|
|
721
1236
|
}
|
|
722
1237
|
|
|
723
1238
|
// ── v0.7: write-channel resolution (capability based, not a fixed tool list) ──
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-session-tmpdir",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.1",
|
|
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": {
|