@leiyi-works/dsh-session-tmpdir 0.11.0 → 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.
Files changed (3) hide show
  1. package/README.md +9 -1
  2. package/index.js +47 -73
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -342,8 +342,16 @@ 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`)的**内容**在分段前被屏蔽(视为数据;起始行的 `@"`/`@'` 两个字符也会被抹掉,避免留下未闭合引号把后续语句吞进字符串;结束行允许 `"@; 后续代码` 并保留后续代码参与判定;未闭合按“其余都是数据”处理,语法错误的命令本来也跑不起来);行注释与 `<# … #>` 块注释在判定前剥掉;语句分段改为**引号感知**(`-Value "a; Set-Content …"` 保持一段),所以生成 `.ps1`/`.cmd`/`.sh` 时内容里的路径、注释里的命令都不会被误当成写目标。
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 条**(含历史回放的代表性写法)。
package/index.js CHANGED
@@ -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 && isDynamicPathToken(cleaned) && !indexInsideRanges(match.index, quoteRanges)
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
- for (const abs of dynamicWriteTargets(segment, symbols, { platform, dynamicRedirectTokens, quoteRanges })) {
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, { platform, dynamicRedirectTokens, quoteRanges })) {
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), comments are not statements, and
793
- // splitting is quote-aware so quoted content keeps its `;`/`|` characters intact.
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 segments = splitCommandSegments(commandText)
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 segment of segments) {
799
- const reason = judgeSegment(segment, symbols)
809
+ for (const entry of splitSegmentsWithOffsets(commandText)) {
810
+ const reason = judgeSegment(entry.text, symbols, entry.start, quoteRanges)
800
811
  if (reason) return reason
801
- collectPathAssignment(segment, symbols, platform)
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 a command into statement segments on newline / `;` / `&&` / `||` / `|`
964
- * **outside quotes**. The old splitter cut quoted content open, so a generated script
965
- * passed through `-Value "a; Set-Content …"` looked like two real statements.
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 splitCommandSegments(command) {
980
+ function splitSegmentsWithOffsets(command) {
968
981
  const text = String(command ?? '')
969
982
  const segments = []
970
- let start = 0
971
- let quote = ''
972
- let i = 0
973
- const push = (end) => {
974
- const part = text.slice(start, end).trim()
975
- if (part) segments.push(part)
976
- }
977
- while (i < text.length) {
978
- const ch = text[i]
979
- if (quote) {
980
- if (quote === '"' && ch === '`') {
981
- i += 2
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 = quotedRanges(segment) } = options
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) => firstWrite >= 0 && index >= firstWrite && !indexInsideRanges(index, quoteRanges)
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.11.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": {