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

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 +8 -0
  2. package/index.js +112 -55
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -213,3 +213,11 @@ 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`/重定向/管道写文件仍照旧判定;已存在文件仍按"改写放行"。
222
+
223
+ v0.9.5 变更(2026-11-16):**复制/移动类命令不再判源路径**。`Copy-Item`、`Move-Item`、`cp`、`mv`、`rsync`、`scp`、`robocopy`、`xcopy`、`Expand-Archive`、`Compress-Archive` 的源参数是"读",只有目标才是写落点:有 `-Destination`/`-DestinationPath`/`-Dest`/`-Target` 时只判该目标,否则位置参数形式下判**最后一个路径**(目标),其余按源跳过。这样"源文件缺失 + 检查/写入已存在目标"的命令不会再被误拦;目标新建未审批仍照常拦截。
package/index.js CHANGED
@@ -129,7 +129,23 @@ 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|;|&&|\|\||\|)+/
141
+ /**
142
+ * v0.9.5: copy-like commands read their source arguments — only the destination is a
143
+ * write target. A missing source must never make the guard blame the destination check.
144
+ */
145
+ const COPY_LIKE_VERB_PATTERN =
146
+ /\b(?:Copy-Item|Move-Item|cp|mv|rsync|scp|robocopy|xcopy|Expand-Archive|Compress-Archive)\b/i
147
+ /** Explicit destination flag of a copy-like command (`-Destination`, `-DestinationPath`, …). */
148
+ const DESTINATION_FLAG_PATTERN = /-(?:Destination|Dest|DestinationPath|Target)\b\s+(?:"([^"]+)"|'([^']+)'|([^\s;|&]+))/i
133
149
  /**
134
150
  * v0.9: programs/APIs that write files but never match CREATE_VERB_PATTERN.
135
151
  * Without this list a command like `ffmpeg … D:\out.mp4` skipped the path scan
@@ -485,25 +501,9 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
485
501
  // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
486
502
  // parsed as one token instead of leaving a second `>` behind. Quoted text such as
487
503
  // `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
504
  const base = resolve(workspaceRoot)
500
505
  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
506
  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
507
  const classifyOptions = {
508
508
  rootDirName,
509
509
  allowRootPatterns,
@@ -515,52 +515,109 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
515
515
  requireApprovalOutsideTmp,
516
516
  guardOutsideWorkspace,
517
517
  }
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
518
+
519
+ /** Judge one statement segment (`;` / `&&` / `||` / `|` / newline separated). */
520
+ function judgeSegment(segment) {
521
+ // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
522
+ // parsed as one token instead of leaving a second `>` behind. Quoted text such as
523
+ // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
524
+ const redirectTokens = new Set()
525
+ for (const match of segment.matchAll(REDIRECT_ALL_PATTERN)) {
526
+ const token = match[1] ?? match[2] ?? match[3]
527
+ if (!token) continue
528
+ const cleaned = token.replace(/["'`]+$/, '')
529
+ if (!cleaned || /^>+$/.test(cleaned)) continue
530
+ if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
531
+ redirectTokens.add(token)
527
532
  }
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') {
532
- try {
533
- options.onTarget(abs)
534
- } catch {
535
- // a reporting callback never changes the verdict
533
+ const hasRedirect = redirectTokens.size > 0
534
+ if (
535
+ !hasRedirect &&
536
+ !CREATE_VERB_PATTERN.test(segment) &&
537
+ !WRITE_PROGRAM_PATTERN.test(segment) &&
538
+ !DOWNLOAD_WRITE_PATTERN.test(segment)
539
+ ) {
540
+ // v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged.
541
+ return undefined
542
+ }
543
+ // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
544
+ // Windows drive-path pattern would otherwise treat as a directory.
545
+ const scanText = segment.replace(URL_PATTERN, ' ')
546
+ const ordered = []
547
+ for (const match of scanText.matchAll(pathPattern)) ordered.push(match[1])
548
+ const tokens = new Set([...redirectTokens, ...ordered])
549
+ // v0.9.5: copy/move/archive sources are reads, not write targets.
550
+ const skipSources = new Set()
551
+ if (COPY_LIKE_VERB_PATTERN.test(segment)) {
552
+ const destMatch = DESTINATION_FLAG_PATTERN.exec(segment)
553
+ if (destMatch) {
554
+ const destValue = destMatch[1] ?? destMatch[2] ?? destMatch[3]
555
+ for (const item of ordered) {
556
+ if (String(item).replace(/["'`]+$/, '') !== destValue) skipSources.add(item)
557
+ }
558
+ } else if (ordered.length >= 2) {
559
+ // Positional form: the last path token is the destination, the rest are sources.
560
+ const destination = ordered[ordered.length - 1]
561
+ for (const item of ordered) if (item !== destination) skipSources.add(item)
536
562
  }
537
563
  }
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}`)
564
+ for (const raw of tokens) {
565
+ if (!raw) continue
566
+ if (skipSources.has(raw) && !redirectTokens.has(raw)) continue
567
+ const cleaned = String(raw).replace(/["'`]+$/, '')
568
+ let abs
569
+ try {
570
+ const expanded = expandTildePath(cleaned)
571
+ abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
572
+ } catch {
546
573
  continue
547
574
  }
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)) {
575
+ if (isDevicePath(abs)) continue
576
+ // v0.8 claim-on-write: report every resolved target so the caller can attribute
577
+ // unmarked `<rootDirName>/<dir>/` folders to the acting session.
578
+ if (typeof options.onTarget === 'function') {
579
+ try {
580
+ options.onTarget(abs)
581
+ } catch {
582
+ // a reporting callback never changes the verdict
583
+ }
584
+ }
585
+ const verdict = classifyWriteTarget(abs, base, classifyOptions)
586
+ if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
587
+ // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
588
+ if (allowOverwrite && pathExists(abs)) continue
589
+ if (verdict.kind === 'outside') {
590
+ if (guardOutsideWorkspace === 'warn') {
591
+ console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
592
+ continue
593
+ }
594
+ return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
595
+ }
596
+ // inside the workspace but not approved / not scratch
597
+ if (skipInside) continue
598
+ const first = firstSegmentUnder(base, abs)
599
+ if (samePath(dirname(abs), base)) {
600
+ return (
601
+ `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
602
+ `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
603
+ )
604
+ }
554
605
  return (
555
- `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
556
- `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
606
+ `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
607
+ `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
608
+ `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
557
609
  )
558
610
  }
559
- return (
560
- `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
561
- `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
562
- `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
563
- )
611
+ return undefined
612
+ }
613
+
614
+ const segments = String(command)
615
+ .split(COMMAND_SEGMENT_SPLIT)
616
+ .map((part) => part.trim())
617
+ .filter(Boolean)
618
+ for (const segment of segments) {
619
+ const reason = judgeSegment(segment)
620
+ if (reason) return reason
564
621
  }
565
622
  return undefined
566
623
  }
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.5",
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": {