@leiyi-works/dsh-session-tmpdir 0.9.3 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -0
  2. package/index.js +87 -55
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -213,3 +213,9 @@ v0.9.3 变更(2026-11-16):面板体验与条目回收。
213
213
  1. **左侧菜单改为打开右侧边栏标签页**(与「常驻钥则」一致):点击「临时目录」行时先回到会话、再打开原生右侧标签页;右侧栏不可用时自动回退全页面板。
214
214
  2. **5 秒自动刷新**:仅面板页面可见时轮询 `GET /state`(静默刷新、不闪 loading);页面隐藏时暂停,切回来立即刷新一次;保留「刷新」按钮。
215
215
  3. **目标不存在的条目自动回收**:`GET /state` 时检查每条路径,文件/目录已删除 → 条目自动删除并落盘。保护:刚批准但还没写入的条目(从未见过存在且批准不到 30 分钟)不会被误删;一旦见过目标存在,之后消失即删。面板同时显示「目标不存在」状态(回收前的短暂窗口)。
216
+
217
+ v0.9.4 变更(2026-11-16):**命令守卫减少误拦**(不影响正常任务)。
218
+
219
+ 1. **按语句分段判定**:`pwsh`/`bash` 命令先按 `;`、`&&`、`||`、`|`、换行拆段,只检查"这一段里真的有写动作"的绝对路径。此前整条命令共用一个判定:同一条命令里既有写动作、又有只读检查(例如 `Invoke-RestMethod …; Test-Path C:\不存在的路径`),只读路径会被误当成新建产物而拦截。
220
+ 2. **下载类命令只在带输出参数时才算写**:`Invoke-WebRequest`/`Invoke-RestMethod` 需带 `-OutFile`/`-OutFileList`,`curl` 需带 `-o`/`--output`/`-O`,`wget` 需带 `-O`/`--output-document`;不带输出参数时按只读处理,不再扫描路径。
221
+ 3. 行为回归:`ffmpeg`/`pandoc`/`Export-*`/`[IO.File]::WriteAllText` 等程序级写盘、`New-Item`/`Set-Content`/重定向/管道写文件仍照旧判定;已存在文件仍按"改写放行"。
package/index.js CHANGED
@@ -129,7 +129,15 @@ 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|Invoke-WebRequest|Invoke-RestMethod|curl|wget|robocopy|git\s+clone|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)|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
+ /**
134
+ * v0.9.4: download commands only write files when they name an output target.
135
+ * `Invoke-RestMethod …` / `curl https://…` without `-OutFile`/`-o` are pure reads.
136
+ */
137
+ const DOWNLOAD_WRITE_PATTERN =
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/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|;|&&|\|\||\|)+/
133
141
  /**
134
142
  * v0.9: programs/APIs that write files but never match CREATE_VERB_PATTERN.
135
143
  * Without this list a command like `ffmpeg … D:\out.mp4` skipped the path scan
@@ -485,25 +493,9 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
485
493
  // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
486
494
  // parsed as one token instead of leaving a second `>` behind. Quoted text such as
487
495
  // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
488
- const redirectTokens = new Set()
489
- for (const match of command.matchAll(REDIRECT_ALL_PATTERN)) {
490
- const token = match[1] ?? match[2] ?? match[3]
491
- if (!token) continue
492
- const cleaned = token.replace(/["'`]+$/, '')
493
- if (!cleaned || /^>+$/.test(cleaned)) continue
494
- if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
495
- redirectTokens.add(token)
496
- }
497
- const hasRedirect = redirectTokens.size > 0
498
- if (!hasRedirect && !CREATE_VERB_PATTERN.test(command) && !WRITE_PROGRAM_PATTERN.test(command)) return undefined
499
496
  const base = resolve(workspaceRoot)
500
497
  const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
501
- // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
502
- // Windows drive-path pattern would otherwise treat as a directory.
503
- const scanText = command.replace(URL_PATTERN, ' ')
504
498
  const pathPattern = platform === 'win32' ? WIN_ABS_PATH_PATTERN : POSIX_ABS_PATH_PATTERN
505
- const tokens = new Set([...redirectTokens])
506
- for (const match of scanText.matchAll(pathPattern)) tokens.add(match[1])
507
499
  const classifyOptions = {
508
500
  rootDirName,
509
501
  allowRootPatterns,
@@ -515,52 +507,92 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
515
507
  requireApprovalOutsideTmp,
516
508
  guardOutsideWorkspace,
517
509
  }
518
- for (const raw of tokens) {
519
- if (!raw) continue
520
- const cleaned = String(raw).replace(/["'`]+$/, '')
521
- let abs
522
- try {
523
- const expanded = expandTildePath(cleaned)
524
- abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
525
- } catch {
526
- continue
510
+
511
+ /** Judge one statement segment (`;` / `&&` / `||` / `|` / newline separated). */
512
+ function judgeSegment(segment) {
513
+ // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
514
+ // parsed as one token instead of leaving a second `>` behind. Quoted text such as
515
+ // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
516
+ const redirectTokens = new Set()
517
+ for (const match of segment.matchAll(REDIRECT_ALL_PATTERN)) {
518
+ const token = match[1] ?? match[2] ?? match[3]
519
+ if (!token) continue
520
+ const cleaned = token.replace(/["'`]+$/, '')
521
+ if (!cleaned || /^>+$/.test(cleaned)) continue
522
+ if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
523
+ redirectTokens.add(token)
527
524
  }
528
- if (isDevicePath(abs)) continue
529
- // v0.8 claim-on-write: report every resolved target so the caller can attribute
530
- // unmarked `<rootDirName>/<dir>/` folders to the acting session.
531
- if (typeof options.onTarget === 'function') {
525
+ const hasRedirect = redirectTokens.size > 0
526
+ if (
527
+ !hasRedirect &&
528
+ !CREATE_VERB_PATTERN.test(segment) &&
529
+ !WRITE_PROGRAM_PATTERN.test(segment) &&
530
+ !DOWNLOAD_WRITE_PATTERN.test(segment)
531
+ ) {
532
+ // v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged.
533
+ return undefined
534
+ }
535
+ // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
536
+ // Windows drive-path pattern would otherwise treat as a directory.
537
+ const scanText = segment.replace(URL_PATTERN, ' ')
538
+ const tokens = new Set([...redirectTokens])
539
+ for (const match of scanText.matchAll(pathPattern)) tokens.add(match[1])
540
+ for (const raw of tokens) {
541
+ if (!raw) continue
542
+ const cleaned = String(raw).replace(/["'`]+$/, '')
543
+ let abs
532
544
  try {
533
- options.onTarget(abs)
545
+ const expanded = expandTildePath(cleaned)
546
+ abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
534
547
  } catch {
535
- // a reporting callback never changes the verdict
536
- }
537
- }
538
- const isRedirectTarget = redirectTokens.has(raw)
539
- const verdict = classifyWriteTarget(abs, base, classifyOptions)
540
- if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
541
- // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
542
- if (allowOverwrite && pathExists(abs)) continue
543
- if (verdict.kind === 'outside') {
544
- if (guardOutsideWorkspace === 'warn') {
545
- console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
546
548
  continue
547
549
  }
548
- return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
549
- }
550
- // inside the workspace but not approved / not scratch
551
- if (skipInside) continue
552
- const first = firstSegmentUnder(base, abs)
553
- if (samePath(dirname(abs), base)) {
550
+ if (isDevicePath(abs)) continue
551
+ // v0.8 claim-on-write: report every resolved target so the caller can attribute
552
+ // unmarked `<rootDirName>/<dir>/` folders to the acting session.
553
+ if (typeof options.onTarget === 'function') {
554
+ try {
555
+ options.onTarget(abs)
556
+ } catch {
557
+ // a reporting callback never changes the verdict
558
+ }
559
+ }
560
+ const verdict = classifyWriteTarget(abs, base, classifyOptions)
561
+ if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
562
+ // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
563
+ if (allowOverwrite && pathExists(abs)) continue
564
+ if (verdict.kind === 'outside') {
565
+ if (guardOutsideWorkspace === 'warn') {
566
+ console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
567
+ continue
568
+ }
569
+ return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
570
+ }
571
+ // inside the workspace but not approved / not scratch
572
+ if (skipInside) continue
573
+ const first = firstSegmentUnder(base, abs)
574
+ if (samePath(dirname(abs), base)) {
575
+ return (
576
+ `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
577
+ `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
578
+ )
579
+ }
554
580
  return (
555
- `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
556
- `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
581
+ `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
582
+ `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
583
+ `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
557
584
  )
558
585
  }
559
- return (
560
- `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
561
- `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
562
- `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
563
- )
586
+ return undefined
587
+ }
588
+
589
+ const segments = String(command)
590
+ .split(COMMAND_SEGMENT_SPLIT)
591
+ .map((part) => part.trim())
592
+ .filter(Boolean)
593
+ for (const segment of segments) {
594
+ const reason = judgeSegment(segment)
595
+ if (reason) return reason
564
596
  }
565
597
  return undefined
566
598
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.9.3",
3
+ "version": "0.9.4",
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": {