dsh-recycle-center 0.4.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/lib/bin.js ADDED
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Windows 回收站桥接。
3
+ *
4
+ * Node 没有「移动到回收站」的内置 API,SHFileOperation 也不在标准库里,
5
+ * 所以这里只做一件事:把一段**固定的** PowerShell 脚本用 -EncodedCommand 交给
6
+ * powershell.exe 执行,请求参数走环境变量(base64 里套 UTF-8 JSON)。
7
+ *
8
+ * 安全要点:
9
+ * · 脚本本身是常量,任何来自请求的字符串都不会被拼进脚本文本;
10
+ * · execFile 不经过 shell,不存在命令行注入;
11
+ * · 参数走环境变量而不是标准输入,避免控制台代码页把中文路径读坏;
12
+ * · 回包是 `DSB:<base64>`,Node 侧只认这一行,脚本的其它输出不会污染结果。
13
+ */
14
+
15
+ import { execFile } from 'node:child_process'
16
+ import { existsSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+
19
+ /**
20
+ * 用绝对路径调 PowerShell,而不是让它走 PATH 解析。
21
+ *
22
+ * `powershell.exe` 如果只写文件名,理论上会被 PATH 里靠前的同名程序劫持
23
+ * (比如用户在某个项目目录里放了一个假的 powershell.exe)。这里直接钉死系统路径,
24
+ * 取不到才退回裸名字。
25
+ */
26
+ function powershellPath() {
27
+ const root = typeof process.env.SystemRoot === 'string' && process.env.SystemRoot.trim() !== ''
28
+ ? process.env.SystemRoot.trim()
29
+ : 'C:\\Windows'
30
+ return join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
31
+ }
32
+
33
+ const POWERSHELL = existsSync(powershellPath()) ? powershellPath() : 'powershell.exe'
34
+
35
+ const SCRIPT = String.raw`
36
+ $ErrorActionPreference = 'Stop'
37
+
38
+ function Reply($obj) {
39
+ $json = $obj | ConvertTo-Json -Compress -Depth 8
40
+ $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
41
+ [Console]::Out.Write('DSB:' + $b64)
42
+ exit 0
43
+ }
44
+
45
+ try {
46
+ $raw = $env:DSH_BIN_REQ
47
+ $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($raw))
48
+ $req = $json | ConvertFrom-Json
49
+ } catch {
50
+ Reply @{ ok = $false; code = 'BAD_REQUEST'; error = $($_.Exception.Message) }
51
+ }
52
+
53
+ $op = [string]$req.op
54
+
55
+ # ── probe:判断某个路径能不能安全地放进回收站 ──────────────────────────
56
+ if ($op -eq 'probe') {
57
+ $p = [string]$req.path
58
+ if (-not (Test-Path -LiteralPath $p)) { Reply @{ ok = $false; code = 'NOT_FOUND' } }
59
+
60
+ $item = Get-Item -LiteralPath $p -Force
61
+ $isDir = [bool]$item.PSIsContainer
62
+ $bytes = [int64]0
63
+ if ($isDir) {
64
+ $files = @(Get-ChildItem -LiteralPath $p -Recurse -Force -File -ErrorAction SilentlyContinue)
65
+ if ($files.Count -gt 0) { $bytes = [int64](($files | Measure-Object -Property Length -Sum).Sum) }
66
+ } else {
67
+ $bytes = [int64]$item.Length
68
+ }
69
+
70
+ $full = (Resolve-Path -LiteralPath $p).Path
71
+ $root = [System.IO.Path]::GetPathRoot($full)
72
+ $letter = $root.Substring(0, 1)
73
+
74
+ $vol = $null
75
+ try { $vol = Get-Volume -DriveLetter $letter -ErrorAction Stop } catch { $vol = $null }
76
+ if ($null -eq $vol) {
77
+ try { $vol = Get-CimInstance Win32_Volume -Filter "DriveLetter='$root'" -ErrorAction Stop } catch { $vol = $null }
78
+ }
79
+ $fs = ''
80
+ $uid = ''
81
+ if ($null -ne $vol) {
82
+ $fs = [string]$vol.FileSystem
83
+ $uid = [string]$vol.UniqueId
84
+ if (-not $uid) { $uid = [string]$vol.DeviceID }
85
+ }
86
+
87
+ $key = ''
88
+ if ($uid -match '(\{[0-9a-fA-F\-]+\})') { $key = $matches[1].ToLower() }
89
+
90
+ $capMB = 0
91
+ $nuke = 0
92
+ $known = $false
93
+ $bases = @()
94
+ if ($key -ne '') { $bases += ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\BitBucket\Volume\' + $key) }
95
+ $bases += 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\BitBucket'
96
+ foreach ($base in $bases) {
97
+ if (-not (Test-Path $base)) { continue }
98
+ $props = Get-ItemProperty -Path $base -ErrorAction SilentlyContinue
99
+ if ($null -eq $props) { continue }
100
+ $names = @($props.PSObject.Properties.Name)
101
+ if ($names -contains 'NukeOnDelete') { $nuke = [int]$props.NukeOnDelete }
102
+ if ($names -contains 'MaxCapacity') { $capMB = [int]$props.MaxCapacity; $known = $true; break }
103
+ }
104
+
105
+ Reply @{
106
+ ok = $true
107
+ isDir = $isDir
108
+ bytes = $bytes
109
+ volume = $letter
110
+ fs = $fs
111
+ capacityMB = $capMB
112
+ nukeOnDelete = $nuke
113
+ quotaKnown = $known
114
+ }
115
+ }
116
+
117
+ # ── recycle:把给定的路径放进回收站 ────────────────────────────────────
118
+ if ($op -eq 'recycle') {
119
+ Add-Type -AssemblyName Microsoft.VisualBasic
120
+ $results = @()
121
+ foreach ($rawPath in @($req.paths)) {
122
+ $p = [string]$rawPath
123
+ try {
124
+ if (-not (Test-Path -LiteralPath $p)) {
125
+ $results += @{ path = $p; ok = $false; code = 'NOT_FOUND' }
126
+ continue
127
+ }
128
+ $it = Get-Item -LiteralPath $p -Force
129
+ if ($it.PSIsContainer) {
130
+ [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($p, 'OnlyErrorDialogs', 'SendToRecycleBin')
131
+ } else {
132
+ [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($p, 'OnlyErrorDialogs', 'SendToRecycleBin')
133
+ }
134
+ $gone = -not (Test-Path -LiteralPath $p)
135
+ $results += @{ path = $p; ok = $gone }
136
+ } catch {
137
+ $results += @{ path = $p; ok = $false; error = $($_.Exception.Message) }
138
+ }
139
+ }
140
+ Reply @{ ok = $true; results = @($results) }
141
+ }
142
+
143
+ # ── restore:把回收站里的某项还原回原位置 ──────────────────────────────
144
+ if ($op -eq 'restore') {
145
+ $shell = New-Object -ComObject Shell.Application
146
+ $bin = $shell.Namespace(10)
147
+ if ($null -eq $bin) { Reply @{ ok = $false; code = 'BIN_UNAVAILABLE' } }
148
+
149
+ $name = [string]$req.name
150
+ $location = [string]$req.location
151
+ $items = $bin.Items()
152
+ $hit = $null
153
+ $nameMatches = @()
154
+
155
+ for ($i = 0; $i -lt $items.Count; $i++) {
156
+ $it = $items.Item($i)
157
+ if ([string]$it.Name -ne $name) { continue }
158
+ $nameMatches += $it
159
+ $orig = [string]$bin.GetDetailsOf($it, 1)
160
+ if ($orig -eq $location) { $hit = $it; break }
161
+ }
162
+ if ($null -eq $hit -and $nameMatches.Count -eq 1) { $hit = $nameMatches[0] }
163
+ if ($null -eq $hit) { Reply @{ ok = $false; code = 'NOT_IN_BIN' } }
164
+
165
+ $verbs = $hit.Verbs()
166
+ $done = $false
167
+ for ($j = 0; $j -lt $verbs.Count; $j++) {
168
+ $label = ([string]$verbs.Item($j).Name) -replace '&', ''
169
+ if ($label -match '(还原|復元|Restore|복원)') {
170
+ $verbs.Item($j).DoIt()
171
+ $done = $true
172
+ break
173
+ }
174
+ }
175
+ Start-Sleep -Milliseconds 400
176
+ Reply @{ ok = $done; code = $(if ($done) { 'OK' } else { 'NO_RESTORE_VERB' }) }
177
+ }
178
+
179
+ # ── open:在资源管理器里打开一个目录 ──────────────────────────────────
180
+ # 只发一个 Explore 就回 ok 是不可靠的:窗口没起来也会报成功。
181
+ # 这里做完之后**真的去数窗口**,确认确实有一个资源管理器窗口停在这个目录上,
182
+ # 才回 ok;否则回 NO_WINDOW,让界面如实显示失败。
183
+ function Test-FolderWindow([string]$target) {
184
+ try {
185
+ $shell = New-Object -ComObject Shell.Application
186
+ foreach ($w in @($shell.Windows())) {
187
+ try {
188
+ if ([string]$w.Document.Folder.Self.Path -eq $target) { return $true }
189
+ } catch { }
190
+ }
191
+ } catch { }
192
+ return $false
193
+ }
194
+
195
+ if ($op -eq 'open') {
196
+ $p = [string]$req.path
197
+ if (-not (Test-Path -LiteralPath $p)) { Reply @{ ok = $false; code = 'NOT_FOUND' } }
198
+
199
+ $opened = $false
200
+ try {
201
+ $shell = New-Object -ComObject Shell.Application
202
+ $shell.Explore($p)
203
+ } catch { }
204
+
205
+ for ($i = 0; $i -lt 10; $i++) {
206
+ Start-Sleep -Milliseconds 200
207
+ if (Test-FolderWindow $p) { $opened = $true; break }
208
+ }
209
+ if (-not $opened) {
210
+ try { Start-Process -FilePath 'explorer.exe' -ArgumentList $p | Out-Null } catch { }
211
+ for ($i = 0; $i -lt 6; $i++) {
212
+ Start-Sleep -Milliseconds 200
213
+ if (Test-FolderWindow $p) { $opened = $true; break }
214
+ }
215
+ }
216
+ Reply @{ ok = $opened; code = $(if ($opened) { 'OK' } else { 'NO_WINDOW' }) }
217
+ }
218
+
219
+ Reply @{ ok = $false; code = 'UNKNOWN_OP'; op = $op }
220
+ `
221
+
222
+ /** UTF-16LE base64,powershell.exe 的 -EncodedCommand 只接受这种编码。 */
223
+ const ENCODED_SCRIPT = Buffer.from(SCRIPT, 'utf16le').toString('base64')
224
+
225
+ /**
226
+ * 一次调用最多搬多少个路径。
227
+ *
228
+ * 请求 JSON 要经过环境变量传给子进程,而 Windows 单个环境变量有长度上限
229
+ * (约 32 KB)。一个会话带几百个附件时会超,所以分批。
230
+ */
231
+ const MAX_PATHS_PER_CALL = 40
232
+
233
+ /**
234
+ * 调用一次回收站操作。
235
+ * @param {'probe'|'recycle'|'restore'} op
236
+ * @param {Record<string, unknown>} payload 会被 JSON 序列化后交给脚本
237
+ * @param {{ timeoutMs?: number }} [options]
238
+ * @returns {Promise<Record<string, any>>} 永远是对象;失败时带 ok:false
239
+ */
240
+ export async function callBin(op, payload = {}, options = {}) {
241
+ // 路径太多就分批,逐批执行后合并结果。
242
+ const paths = payload.paths
243
+ if (op === 'recycle' && Array.isArray(paths) && paths.length > MAX_PATHS_PER_CALL) {
244
+ const merged = []
245
+ for (let i = 0; i < paths.length; i += MAX_PATHS_PER_CALL) {
246
+ const batch = paths.slice(i, i + MAX_PATHS_PER_CALL)
247
+ const result = await callBin(op, { ...payload, paths: batch }, options)
248
+ if (!result || result.ok !== true) return result
249
+ if (Array.isArray(result.results)) merged.push(...result.results)
250
+ }
251
+ return { ok: true, results: merged }
252
+ }
253
+
254
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 60000
255
+ const request = Buffer.from(JSON.stringify({ op, ...payload }), 'utf8').toString('base64')
256
+
257
+ return new Promise((resolve) => {
258
+ execFile(
259
+ POWERSHELL,
260
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', ENCODED_SCRIPT],
261
+ {
262
+ timeout: timeoutMs,
263
+ windowsHide: true,
264
+ maxBuffer: 8 * 1024 * 1024,
265
+ env: { ...process.env, DSH_BIN_REQ: request },
266
+ },
267
+ (error, stdout, stderr) => {
268
+ if (error) {
269
+ resolve({
270
+ ok: false,
271
+ code: 'PS_FAILED',
272
+ error: String((error && error.message) || error),
273
+ stderr: String(stderr || '').slice(0, 400),
274
+ })
275
+ return
276
+ }
277
+ const line = String(stdout || '')
278
+ .split(/\r?\n/)
279
+ .map((row) => row.trim())
280
+ .filter((row) => row.startsWith('DSB:'))
281
+ .pop()
282
+ if (!line) {
283
+ resolve({ ok: false, code: 'NO_REPLY', raw: String(stdout || '').slice(0, 300) })
284
+ return
285
+ }
286
+ try {
287
+ const text = Buffer.from(line.slice(4), 'base64').toString('utf8')
288
+ resolve(JSON.parse(text))
289
+ } catch (error2) {
290
+ resolve({ ok: false, code: 'BAD_REPLY', error: String((error2 && error2.message) || error2) })
291
+ }
292
+ },
293
+ )
294
+ })
295
+ }
package/lib/logtext.js ADDED
@@ -0,0 +1,210 @@
1
+ /**
2
+ * 读取 DSH 的会话日志(多帧 zstd),并从中取出**结构化**的附件引用。
3
+ *
4
+ * 会话日志不是单个 zstd 流,而是一帧一帧追加的。分段依据是 zstd 帧魔数
5
+ * 0x28B52FFD;每段独立解压后拼起来。任何一帧解不开,返回的 complete 就是
6
+ * false —— 调用方据此判断「这次扫描不可信」,从而放弃按引用计数做清理。
7
+ *
8
+ * ── 关于附件引用(2026-12 修正) ──────────────────────────────────────
9
+ * 旧实现用正则在整个日志文本里找 `"attachmentId":"…"`。这是错的:
10
+ * 任何把这段 JSON 打印出来的工具输出,在文本层面和真实引用完全一样,
11
+ * 于是「提到过」被当成「引用着」,导致删除时把独占附件误判为共享。
12
+ *
13
+ * 现在只认**结构**:事件 `data` 里形如
14
+ * { type: 'image' | 'file', attachment: { attachmentId: '…' } }
15
+ * 的对象才算引用;字符串(无论内容多像 JSON)一律不看。
16
+ *
17
+ * 不要按事件类型跳过 `tool/result`:DSH 允许工具结果携带图片内容块,
18
+ * 跳过它会把「真共享」误判成「独占」,那是会删掉别人还在用的数据。
19
+ */
20
+
21
+ import { readFile } from 'node:fs/promises'
22
+ import { zstdDecompressSync } from 'node:zlib'
23
+
24
+ const FRAME_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
25
+ const MAX_LOG_BYTES = 64 * 1024 * 1024
26
+
27
+ /** 单帧解压输出上限:一帧日志文本不该有 128 MB。 */
28
+ const MAX_FRAME_OUTPUT = 128 * 1024 * 1024
29
+
30
+ /** 一次扫描的累计解压上限,防压缩炸弹把内存打满。 */
31
+ const MAX_TOTAL_OUTPUT = 256 * 1024 * 1024
32
+
33
+ /** 承载附件的结构化内容块类型。 */
34
+ const ATTACHMENT_BLOCK_TYPES = new Set(['image', 'file'])
35
+
36
+ /** DSH 的附件摘要是 sha256,固定 64 位小写十六进制。 */
37
+ const ATTACHMENT_ID = /^[0-9a-f]{64}$/
38
+
39
+ /** 单个事件里最多走多少个对象节点,防病态结构拖死进程。 */
40
+ const MAX_NODES_PER_EVENT = 200_000
41
+
42
+ /**
43
+ * 解压多帧 zstd 日志。
44
+ *
45
+ * 两道上限:单帧解压输出不超过 MAX_FRAME_OUTPUT,累计不超过 MAX_TOTAL_OUTPUT。
46
+ * 目的不是性能,而是防止「压缩炸弹」——一段几十 KB 的 zstd 可以解出几个 GB,
47
+ * 直接把宿主进程的内存打满。超限按「解不开」处理,调用方会因此拒绝删除。
48
+ *
49
+ * @param {Buffer} buffer 原始日志字节
50
+ * @returns {{ text: string, frames: number, decoded: number, complete: boolean }}
51
+ */
52
+ export function decodeLog(buffer) {
53
+ const starts = []
54
+ let cursor = 0
55
+ for (;;) {
56
+ const at = buffer.indexOf(FRAME_MAGIC, cursor)
57
+ if (at < 0) break
58
+ starts.push(at)
59
+ cursor = at + FRAME_MAGIC.length
60
+ }
61
+ if (starts.length === 0) return { text: '', frames: 0, decoded: 0, complete: false }
62
+
63
+ const parts = []
64
+ let decoded = 0
65
+ let total = 0
66
+ for (let i = 0; i < starts.length; i += 1) {
67
+ const begin = starts[i]
68
+ const end = i + 1 < starts.length ? starts[i + 1] : buffer.length
69
+ try {
70
+ const out = zstdDecompressSync(buffer.subarray(begin, end), { maxOutputLength: MAX_FRAME_OUTPUT })
71
+ total += out.length
72
+ if (total > MAX_TOTAL_OUTPUT) {
73
+ return { text: Buffer.concat(parts).toString('utf8'), frames: starts.length, decoded, complete: false }
74
+ }
75
+ parts.push(out)
76
+ decoded += 1
77
+ } catch {
78
+ // 解不开就停在这里;complete=false 会让调用方放弃这次判断。
79
+ return { text: Buffer.concat(parts).toString('utf8'), frames: starts.length, decoded, complete: false }
80
+ }
81
+ }
82
+ return { text: Buffer.concat(parts).toString('utf8'), frames: starts.length, decoded, complete: true }
83
+ }
84
+
85
+ /**
86
+ * 读一个会话目录里的日志文件。
87
+ * @param {string} file 日志绝对路径
88
+ * @returns {Promise<{ text: string, complete: boolean } | null>} 读不了返回 null
89
+ */
90
+ export async function readLogFile(file) {
91
+ let buffer
92
+ try {
93
+ buffer = await readFile(file)
94
+ } catch {
95
+ return null
96
+ }
97
+ if (!buffer || buffer.length === 0 || buffer.length > MAX_LOG_BYTES) return null
98
+ const result = decodeLog(buffer)
99
+ return { text: result.text, complete: result.complete }
100
+ }
101
+
102
+ /**
103
+ * 把日志文本拆成事件对象。坏行跳过,不影响其余事件。
104
+ * @param {string} text 解压后的日志全文
105
+ * @returns {Array<Record<string, any>>}
106
+ */
107
+ export function parseLogEvents(text) {
108
+ if (typeof text !== 'string' || text === '') return []
109
+ const events = []
110
+ for (const line of text.split('\n')) {
111
+ const trimmed = line.trim()
112
+ if (trimmed === '') continue
113
+ try {
114
+ const parsed = JSON.parse(trimmed)
115
+ if (parsed !== null && typeof parsed === 'object') events.push(parsed)
116
+ } catch {
117
+ // 半行 / 坏帧产出的残行:跳过
118
+ }
119
+ }
120
+ return events
121
+ }
122
+
123
+ /**
124
+ * 规范化一个附件 id:去掉 `sha256:` 之类前缀,校验必须是 64 位十六进制。
125
+ * @param {unknown} raw
126
+ * @returns {string | null}
127
+ */
128
+ export function normalizeAttachmentId(raw) {
129
+ if (typeof raw !== 'string') return null
130
+ const tail = raw.includes(':') ? raw.slice(raw.lastIndexOf(':') + 1) : raw
131
+ const id = tail.trim().toLowerCase()
132
+ return ATTACHMENT_ID.test(id) ? id : null
133
+ }
134
+
135
+ /**
136
+ * 从一个值里递归收集附件引用。
137
+ *
138
+ * 只认 `{ type: 'image' | 'file', attachment: { attachmentId } }` 这种结构;
139
+ * 字符串不参与匹配,所以「把 JSON 打印出来」不会造成误判。
140
+ *
141
+ * @param {unknown} value 事件 data(或它的子结构)
142
+ * @param {Set<string>} into 收集结果
143
+ * @param {{ nodes: number }} budget 节点预算,防止病态结构
144
+ * @returns {boolean} 是否因超预算而提前中止
145
+ */
146
+ function collectFromValue(value, into, budget) {
147
+ if (value === null || typeof value !== 'object') return false
148
+ budget.nodes += 1
149
+ if (budget.nodes > MAX_NODES_PER_EVENT) return true
150
+
151
+ if (Array.isArray(value)) {
152
+ for (const item of value) {
153
+ if (collectFromValue(item, into, budget)) return true
154
+ }
155
+ return false
156
+ }
157
+
158
+ // 先判断这个对象本身是不是一个附件内容块。
159
+ const type = value.type
160
+ if (typeof type === 'string' && ATTACHMENT_BLOCK_TYPES.has(type)) {
161
+ const attachment = value.attachment
162
+ if (attachment !== null && typeof attachment === 'object') {
163
+ const id = normalizeAttachmentId(attachment.attachmentId)
164
+ if (id !== null) {
165
+ into.add(id)
166
+ // 内容块内部不再往下走:它的其余字段不承载引用
167
+ return false
168
+ }
169
+ }
170
+ }
171
+
172
+ for (const child of Object.values(value)) {
173
+ if (collectFromValue(child, into, budget)) return true
174
+ }
175
+ return false
176
+ }
177
+
178
+ /**
179
+ * 一个事件里引用的附件 id。
180
+ * @param {Record<string, any>} event
181
+ * @returns {{ ids: Set<string>, truncated: boolean }}
182
+ */
183
+ export function attachmentIdsOfEvent(event) {
184
+ const ids = new Set()
185
+ if (event === null || typeof event !== 'object') return { ids, truncated: false }
186
+ const data = event.data
187
+ if (data === null || typeof data !== 'object') return { ids, truncated: false }
188
+ const truncated = collectFromValue(data, ids, { nodes: 0 })
189
+ return { ids, truncated }
190
+ }
191
+
192
+ /**
193
+ * 一组事件里引用的全部附件 id。
194
+ *
195
+ * 收集端(判断本会话引用了什么)和共享判定端(判断别的会话引用了什么)
196
+ * **必须共用这一个函数**,否则两边的口径会再次分裂。
197
+ *
198
+ * @param {Array<Record<string, any>>} events
199
+ * @returns {{ ids: Set<string>, truncated: boolean }}
200
+ */
201
+ export function attachmentIdsOfEvents(events) {
202
+ const ids = new Set()
203
+ if (!Array.isArray(events)) return { ids, truncated: false }
204
+ for (const event of events) {
205
+ const result = attachmentIdsOfEvent(event)
206
+ if (result.truncated) return { ids, truncated: true }
207
+ for (const id of result.ids) ids.add(id)
208
+ }
209
+ return { ids, truncated: false }
210
+ }
package/lib/safety.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 纯函数:会话 id 的形状校验与路径围栏。
3
+ *
4
+ * 这里没有任何 I/O,方便单独用 node --test 验证。之所以单独放一个文件,
5
+ * 是因为「请求里的字符串会不会被拼进路径」是这类插件唯一真正危险的地方,
6
+ * 它应该能被一眼读完。
7
+ */
8
+
9
+ import { isAbsolute, resolve, sep } from 'node:path'
10
+
11
+ /**
12
+ * 会话 id 只允许单个路径段。
13
+ * DSH 现在的 id 长这样:`session-<uuid>`;也见过裸 `<uuid>`。
14
+ * 允许的字符集刻意收紧到字母数字和 `._-`,并且首字符必须是字母或数字,
15
+ * 因此 `..`、`/`、`\`、`:` 都进不来。
16
+ */
17
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,150}$/
18
+
19
+ /**
20
+ * 判断一个值能否安全地当作会话 id 使用。
21
+ * @param {unknown} value 请求里取到的原始值
22
+ * @returns {value is string}
23
+ */
24
+ export function isSafeSessionId(value) {
25
+ return typeof value === 'string' && SESSION_ID.test(value) && value !== '.' && value !== '..'
26
+ }
27
+
28
+ /**
29
+ * target 是否落在 base 内部(含 base 自身)。
30
+ * 先 resolve 再按分隔符比较,避免 `C:\a\bc` 被判定成 `C:\a\b` 的子路径。
31
+ * @param {string} base 围栏根
32
+ * @param {string} target 待检查的路径
33
+ * @returns {boolean}
34
+ */
35
+ export function isInside(base, target) {
36
+ const b = resolve(base)
37
+ const t = resolve(target)
38
+ if (t === b) return true
39
+ return t.startsWith(b.endsWith(sep) ? b : b + sep)
40
+ }
41
+
42
+ /**
43
+ * 把一个已经通过形状校验的会话 id 拼进根目录,并再次确认没有越界。
44
+ * 两道检查里任何一道失败都返回 null,调用方必须把 null 当成「拒绝」。
45
+ * @param {string} root 会话存储根(<DSH_HOME>/sessions)
46
+ * @param {string} projectDir 一级项目目录名
47
+ * @param {string} sid 会话 id
48
+ * @returns {string | null}
49
+ */
50
+ export function sessionDirUnder(root, projectDir, sid) {
51
+ if (!isSafeSessionId(sid)) return null
52
+ if (typeof projectDir !== 'string' || projectDir === '' || isAbsolute(projectDir)) return null
53
+ if (projectDir.includes('/') || projectDir.includes('\\') || projectDir === '.' || projectDir === '..') return null
54
+ const dir = resolve(root, projectDir, sid)
55
+ return isInside(root, dir) ? dir : null
56
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "dsh-recycle-center",
3
+ "version": "0.4.0",
4
+ "type": "module",
5
+ "description": "把 DSH 会话删进 Windows 回收站,7 天内可在 DSH 内恢复",
6
+ "license": "MIT",
7
+ "author": "M1ser1es (https://github.com/M1ser1es)",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/M1ser1es/dsh-recyclebin.git"
11
+ },
12
+ "homepage": "https://github.com/M1ser1es/dsh-recyclebin#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/M1ser1es/dsh-recyclebin/issues"
15
+ },
16
+ "keywords": [
17
+ "dsh",
18
+ "deepseek-harness",
19
+ "plugin",
20
+ "session",
21
+ "recycle-bin",
22
+ "windows"
23
+ ],
24
+ "main": "index.js",
25
+ "exports": {
26
+ ".": "./index.js",
27
+ "./client": "./client.js"
28
+ },
29
+ "files": [
30
+ "index.js",
31
+ "lib",
32
+ "client.js",
33
+ "cordis.patch.yml",
34
+ "README.md",
35
+ "CHANGELOG.md",
36
+ "SECURITY.md",
37
+ "docs"
38
+ ],
39
+ "engines": {
40
+ "node": ">=22.19.0"
41
+ },
42
+ "os": [
43
+ "win32"
44
+ ],
45
+ "dsh": {
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web"
51
+ }
52
+ }
53
+ }