@leiyi-works/dsh-session-tmpdir 0.9.2 → 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.
- package/README.md +12 -0
- package/client.js +164 -22
- package/index.js +134 -55
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -207,3 +207,15 @@ v0.9.0 变更(2026-11-16):**中间产物/长期产物划分(方案 3)+
|
|
|
207
207
|
v0.9.1 变更(2026-11-16):左侧菜单「临时目录」图标从彩色 emoji 换成**单色线框文件夹 SVG**(`currentColor` 描边、24 viewBox、无填充),与「云端同步」「隐私模式」等菜单的图标风格一致;尺寸跟随 `sidebar.panellist` 传入的 `size`(默认 18)。功能无变化。
|
|
208
208
|
|
|
209
209
|
v0.9.2 变更(2026-11-16):图标再改为**沙漏**(单色线框),因为文件夹线框和「AI视频」「会话相关」等收纳夹图标撞形;沙漏表达“临时/到期清理”的语义,18px 下两笔可辨,与左栏现有图标形状都不重复。功能无变化。
|
|
210
|
+
|
|
211
|
+
v0.9.3 变更(2026-11-16):面板体验与条目回收。
|
|
212
|
+
|
|
213
|
+
1. **左侧菜单改为打开右侧边栏标签页**(与「常驻钥则」一致):点击「临时目录」行时先回到会话、再打开原生右侧标签页;右侧栏不可用时自动回退全页面板。
|
|
214
|
+
2. **5 秒自动刷新**:仅面板页面可见时轮询 `GET /state`(静默刷新、不闪 loading);页面隐藏时暂停,切回来立即刷新一次;保留「刷新」按钮。
|
|
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/client.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-session-tmpdir — Client half(v0.9).
|
|
2
|
+
* dsh-session-tmpdir — Client half(v0.9.3).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* 左侧菜单「临时目录」入口:点击时切到**右侧边栏标签页**(和「常驻钥则」一致);
|
|
5
|
+
* 侧边栏不可用时回退到全页面板。
|
|
6
6
|
*
|
|
7
|
-
*
|
|
7
|
+
* 面板内容:长期落点白名单(文件级/目录级),5 秒自动刷新(仅页面可见时),
|
|
8
|
+
* 支持「移除」一条;目标已不存在的条目由宿主侧自动回收。
|
|
9
|
+
*
|
|
10
|
+
* 宿主接口:
|
|
8
11
|
* GET /__dsh-session-tmpdir/state 白名单清单 + 配置
|
|
9
12
|
* POST /__dsh-session-tmpdir/revoke { id } 移除一条
|
|
10
13
|
*/
|
|
@@ -14,23 +17,25 @@ window.__ModuleLoader__.load({
|
|
|
14
17
|
const React = require('react')
|
|
15
18
|
const h = React.createElement
|
|
16
19
|
const PANEL_ID = 'session-tmpdir'
|
|
20
|
+
const TAB_ID = 'session-tmpdir-tab'
|
|
17
21
|
const API = '/__dsh-session-tmpdir'
|
|
22
|
+
const REFRESH_MS = 5000
|
|
18
23
|
|
|
19
24
|
const styles = {
|
|
20
25
|
root: {
|
|
21
26
|
height: '100%',
|
|
22
27
|
overflow: 'auto',
|
|
23
28
|
boxSizing: 'border-box',
|
|
24
|
-
padding: '
|
|
29
|
+
padding: '10px 12px 20px',
|
|
25
30
|
color: 'var(--dsw-alias-label-primary)',
|
|
26
31
|
fontSize: 13,
|
|
27
32
|
lineHeight: 1.55,
|
|
28
33
|
},
|
|
29
|
-
inner: {
|
|
30
|
-
title: { margin: 0, fontSize:
|
|
34
|
+
inner: { display: 'flex', flexDirection: 'column', gap: 10 },
|
|
35
|
+
title: { margin: 0, fontSize: 15, fontWeight: 600 },
|
|
31
36
|
hint: { margin: 0, color: 'var(--dsw-alias-label-secondary)', fontSize: 12 },
|
|
32
37
|
meta: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)' },
|
|
33
|
-
bar: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'
|
|
38
|
+
bar: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
|
|
34
39
|
btn: {
|
|
35
40
|
appearance: 'none',
|
|
36
41
|
cursor: 'pointer',
|
|
@@ -54,18 +59,18 @@ window.__ModuleLoader__.load({
|
|
|
54
59
|
color: 'var(--dsw-alias-state-error-primary, #d14a4a)',
|
|
55
60
|
whiteSpace: 'nowrap',
|
|
56
61
|
},
|
|
57
|
-
table: { display: 'flex', flexDirection: 'column', gap: 6
|
|
62
|
+
table: { display: 'flex', flexDirection: 'column', gap: 6 },
|
|
58
63
|
row: {
|
|
59
64
|
display: 'flex',
|
|
60
65
|
alignItems: 'center',
|
|
61
|
-
gap:
|
|
66
|
+
gap: 8,
|
|
62
67
|
border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.22))',
|
|
63
68
|
borderRadius: 8,
|
|
64
69
|
padding: '8px 10px',
|
|
65
70
|
},
|
|
66
71
|
rowMain: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 },
|
|
67
72
|
path: { fontFamily: 'ui-monospace, Consolas, monospace', fontSize: 12, wordBreak: 'break-all' },
|
|
68
|
-
rowMeta: { display: 'flex', alignItems: 'center', gap:
|
|
73
|
+
rowMeta: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
|
|
69
74
|
tag: {
|
|
70
75
|
fontSize: 10,
|
|
71
76
|
lineHeight: '16px',
|
|
@@ -73,6 +78,16 @@ window.__ModuleLoader__.load({
|
|
|
73
78
|
borderRadius: 6,
|
|
74
79
|
background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,.08))',
|
|
75
80
|
color: 'var(--dsw-alias-label-secondary)',
|
|
81
|
+
whiteSpace: 'nowrap',
|
|
82
|
+
},
|
|
83
|
+
tagWarn: {
|
|
84
|
+
fontSize: 10,
|
|
85
|
+
lineHeight: '16px',
|
|
86
|
+
padding: '0 6px',
|
|
87
|
+
borderRadius: 6,
|
|
88
|
+
background: 'rgba(210,120,0,.14)',
|
|
89
|
+
color: 'var(--dsw-alias-state-warning-primary, #c27c00)',
|
|
90
|
+
whiteSpace: 'nowrap',
|
|
76
91
|
},
|
|
77
92
|
empty: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', margin: '8px 0 0' },
|
|
78
93
|
err: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #d14a4a)', margin: 0 },
|
|
@@ -97,21 +112,37 @@ window.__ModuleLoader__.load({
|
|
|
97
112
|
function WhitelistPanel() {
|
|
98
113
|
const [state, setState] = React.useState({ loading: true, error: '', data: null })
|
|
99
114
|
const [busy, setBusy] = React.useState('')
|
|
115
|
+
const aliveRef = React.useRef(true)
|
|
100
116
|
|
|
101
|
-
|
|
102
|
-
|
|
117
|
+
React.useEffect(() => () => { aliveRef.current = false }, [])
|
|
118
|
+
|
|
119
|
+
const load = React.useCallback(async (quiet = false) => {
|
|
120
|
+
if (!quiet) setState((prev) => ({ ...prev, loading: true, error: '' }))
|
|
103
121
|
try {
|
|
104
122
|
const res = await fetch(`${API}/state`, { cache: 'no-store' })
|
|
105
123
|
const data = await res.json()
|
|
106
124
|
if (!data || data.ok !== true) throw new Error(data?.error || '读取失败')
|
|
107
|
-
setState({ loading: false, error: '', data })
|
|
125
|
+
if (aliveRef.current) setState({ loading: false, error: '', data })
|
|
108
126
|
} catch (error) {
|
|
109
|
-
setState({ loading: false, error: String(error?.message ?? error)
|
|
127
|
+
if (aliveRef.current) setState((prev) => ({ ...prev, loading: false, error: String(error?.message ?? error) }))
|
|
110
128
|
}
|
|
111
129
|
}, [])
|
|
112
130
|
|
|
131
|
+
// 首次加载 + 页面可见时每 5 秒静默刷新
|
|
113
132
|
React.useEffect(() => {
|
|
114
|
-
void load()
|
|
133
|
+
void load(false)
|
|
134
|
+
const timer = setInterval(() => {
|
|
135
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
|
|
136
|
+
void load(true)
|
|
137
|
+
}, REFRESH_MS)
|
|
138
|
+
const onVisible = () => {
|
|
139
|
+
if (typeof document === 'undefined' || document.visibilityState !== 'hidden') void load(true)
|
|
140
|
+
}
|
|
141
|
+
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)
|
|
142
|
+
return () => {
|
|
143
|
+
clearInterval(timer)
|
|
144
|
+
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)
|
|
145
|
+
}
|
|
115
146
|
}, [load])
|
|
116
147
|
|
|
117
148
|
const remove = async (id) => {
|
|
@@ -124,7 +155,7 @@ window.__ModuleLoader__.load({
|
|
|
124
155
|
})
|
|
125
156
|
const data = await res.json()
|
|
126
157
|
if (!data || data.ok !== true) throw new Error(data?.error || '移除失败')
|
|
127
|
-
await load()
|
|
158
|
+
await load(true)
|
|
128
159
|
} catch (error) {
|
|
129
160
|
setState((prev) => ({ ...prev, error: String(error?.message ?? error) }))
|
|
130
161
|
} finally {
|
|
@@ -145,13 +176,13 @@ window.__ModuleLoader__.load({
|
|
|
145
176
|
h(
|
|
146
177
|
'p',
|
|
147
178
|
{ style: styles.hint },
|
|
148
|
-
'
|
|
179
|
+
'长期落点白名单:在临时目录外**新建**产物要先经过你同意,同意后才会出现在这里;**改写已存在文件**按规则直接放行,不弹窗。目标被删除后条目会自动消失。',
|
|
149
180
|
),
|
|
150
181
|
data
|
|
151
182
|
? h(
|
|
152
183
|
'p',
|
|
153
184
|
{ style: styles.meta },
|
|
154
|
-
|
|
185
|
+
`改写放行:${data.allowOverwrite ? '是' : '否'} · 临时根:${data.rootDirName || '_tmp'}/ · ${data.approvalsFile || ''}`,
|
|
155
186
|
)
|
|
156
187
|
: null,
|
|
157
188
|
h(
|
|
@@ -159,7 +190,7 @@ window.__ModuleLoader__.load({
|
|
|
159
190
|
{ style: styles.bar },
|
|
160
191
|
h(
|
|
161
192
|
'button',
|
|
162
|
-
{ style: styles.btn, onClick: () => void load(), disabled: state.loading || Boolean(busy) },
|
|
193
|
+
{ style: styles.btn, onClick: () => void load(false), disabled: state.loading || Boolean(busy) },
|
|
163
194
|
state.loading ? '读取中…' : '刷新',
|
|
164
195
|
),
|
|
165
196
|
),
|
|
@@ -181,6 +212,7 @@ window.__ModuleLoader__.load({
|
|
|
181
212
|
'div',
|
|
182
213
|
{ style: styles.rowMeta },
|
|
183
214
|
h('span', { style: styles.tag }, row.kind === 'dir' ? '目录' : '文件'),
|
|
215
|
+
row.exists === false ? h('span', { style: styles.tagWarn }, '目标不存在') : null,
|
|
184
216
|
h('span', { style: styles.meta }, `同意于 ${fmtTime(row.approvedAt) || '未知时间'}`),
|
|
185
217
|
row.sessionId
|
|
186
218
|
? h(
|
|
@@ -228,12 +260,83 @@ window.__ModuleLoader__.load({
|
|
|
228
260
|
|
|
229
261
|
return {
|
|
230
262
|
name: '@leiyi-works/dsh-session-tmpdir',
|
|
231
|
-
inject: ['slots'],
|
|
263
|
+
inject: ['slots', 'layout'],
|
|
232
264
|
apply(ctx) {
|
|
265
|
+
let nativeOpen = null
|
|
266
|
+
let redirecting = false
|
|
267
|
+
|
|
268
|
+
const openTab = () => {
|
|
269
|
+
if (nativeOpen === null) return false
|
|
270
|
+
try {
|
|
271
|
+
nativeOpen()
|
|
272
|
+
return true
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.warn('[dsh-session-tmpdir] native right-sidebar openTab failed:', error)
|
|
275
|
+
return false
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// 右侧边栏标签页(与「常驻钥则」同款原生通道)
|
|
280
|
+
const mountTab = (inner) => {
|
|
281
|
+
let registry
|
|
282
|
+
let slots
|
|
283
|
+
let sidebarRight
|
|
284
|
+
try {
|
|
285
|
+
registry = inner.sidebarRightTabs ?? inner.get?.('sidebarRightTabs')
|
|
286
|
+
slots = inner.slots
|
|
287
|
+
sidebarRight = inner.sidebarRight ?? inner.get?.('sidebarRight')
|
|
288
|
+
} catch {
|
|
289
|
+
return undefined
|
|
290
|
+
}
|
|
291
|
+
if (registry === undefined || typeof registry.register !== 'function' || slots === undefined) return undefined
|
|
292
|
+
const disposers = []
|
|
293
|
+
try {
|
|
294
|
+
const disposeType = registry.register({
|
|
295
|
+
id: TAB_ID,
|
|
296
|
+
kind: TAB_ID,
|
|
297
|
+
title: () => '临时目录',
|
|
298
|
+
})
|
|
299
|
+
if (typeof disposeType === 'function') disposers.push(disposeType)
|
|
300
|
+
const disposeBody = slots.inject('sidebar.right.pane.tab', () =>
|
|
301
|
+
slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, (props) => h(WhitelistPanel, props)),
|
|
302
|
+
)
|
|
303
|
+
if (typeof disposeBody === 'function') disposers.push(disposeBody)
|
|
304
|
+
if (sidebarRight !== undefined && typeof sidebarRight.openTab === 'function') {
|
|
305
|
+
nativeOpen = () => sidebarRight.openTab(TAB_ID)
|
|
306
|
+
}
|
|
307
|
+
} catch (error) {
|
|
308
|
+
for (const dispose of disposers.reverse()) {
|
|
309
|
+
try {
|
|
310
|
+
dispose()
|
|
311
|
+
} catch {
|
|
312
|
+
/* ignore */
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return undefined
|
|
316
|
+
}
|
|
317
|
+
return () => {
|
|
318
|
+
for (const dispose of disposers.reverse()) {
|
|
319
|
+
try {
|
|
320
|
+
dispose()
|
|
321
|
+
} catch {
|
|
322
|
+
/* ignore */
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
ctx.inject(['sidebarRightTabs', 'sidebarRight', 'slots'], mountTab)
|
|
329
|
+
} catch {
|
|
330
|
+
mountTab(ctx)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// 兜底:右侧边栏不可用时仍可用全页面板。
|
|
233
334
|
ctx.effect(
|
|
234
335
|
() => ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, WhitelistPanel)),
|
|
235
|
-
'session-task-tmpdir: whitelist page',
|
|
336
|
+
'session-task-tmpdir: whitelist page (fallback)',
|
|
236
337
|
)
|
|
338
|
+
|
|
339
|
+
// 左侧菜单入口。
|
|
237
340
|
ctx.effect(
|
|
238
341
|
() =>
|
|
239
342
|
ctx.slots.inject('sidebar.panellist', () =>
|
|
@@ -241,6 +344,45 @@ window.__ModuleLoader__.load({
|
|
|
241
344
|
),
|
|
242
345
|
'session-task-tmpdir: sidebar entry',
|
|
243
346
|
)
|
|
347
|
+
|
|
348
|
+
// 点左侧行时保持会话:先回到会话,再打开右侧标签页;打不开才退回全页面板。
|
|
349
|
+
ctx.effect(() => {
|
|
350
|
+
const layout = ctx.layout
|
|
351
|
+
if (!layout || !layout.panelInfo) return undefined
|
|
352
|
+
const openAfterReturn = () => {
|
|
353
|
+
const opened = openTab()
|
|
354
|
+
if (!opened) {
|
|
355
|
+
try {
|
|
356
|
+
layout.selectPanel(PANEL_ID)
|
|
357
|
+
} catch (error) {
|
|
358
|
+
console.warn('[dsh-session-tmpdir] full-page fallback failed:', error)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
redirecting = false
|
|
362
|
+
}
|
|
363
|
+
const check = () => {
|
|
364
|
+
if (redirecting) return
|
|
365
|
+
let active
|
|
366
|
+
try {
|
|
367
|
+
active = layout.panelInfo.getSnapshot().activePanelId
|
|
368
|
+
} catch {
|
|
369
|
+
return
|
|
370
|
+
}
|
|
371
|
+
if (active !== PANEL_ID) return
|
|
372
|
+
redirecting = true
|
|
373
|
+
try {
|
|
374
|
+
layout.selectPanel(null)
|
|
375
|
+
} catch (error) {
|
|
376
|
+
redirecting = false
|
|
377
|
+
console.warn('[dsh-session-tmpdir] returning to the conversation failed:', error)
|
|
378
|
+
return
|
|
379
|
+
}
|
|
380
|
+
if (typeof queueMicrotask === 'function') queueMicrotask(openAfterReturn)
|
|
381
|
+
else setTimeout(openAfterReturn, 0)
|
|
382
|
+
}
|
|
383
|
+
check()
|
|
384
|
+
return layout.panelInfo.subscribe(check)
|
|
385
|
+
}, 'session-tmpdir: row opens the native right-sidebar tab')
|
|
244
386
|
},
|
|
245
387
|
}
|
|
246
388
|
},
|
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|
|
|
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
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
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
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
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
|
-
|
|
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
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
-
|
|
556
|
-
|
|
581
|
+
`命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
|
|
582
|
+
`若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
|
|
583
|
+
`临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
|
|
557
584
|
)
|
|
558
585
|
}
|
|
559
|
-
return
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
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
|
}
|
|
@@ -1546,9 +1578,54 @@ export function apply(ctx, config) {
|
|
|
1546
1578
|
reason: entry.reason ?? '',
|
|
1547
1579
|
basis: entry.basis ?? '',
|
|
1548
1580
|
approvedAt: entry.approvedAt ?? 0,
|
|
1581
|
+
exists: (() => {
|
|
1582
|
+
try {
|
|
1583
|
+
return existsSync(entry.path)
|
|
1584
|
+
} catch {
|
|
1585
|
+
return false
|
|
1586
|
+
}
|
|
1587
|
+
})(),
|
|
1549
1588
|
}))
|
|
1550
1589
|
}
|
|
1551
1590
|
|
|
1591
|
+
/**
|
|
1592
|
+
* v0.9.3:目标已不存在的白名单条目自动回收。
|
|
1593
|
+
* 保护:刚批准、还没写入的条目(从未见过存在,且批准不到 30 分钟)不删,避免误删;
|
|
1594
|
+
* 一旦见过目标存在(lastSeenAt>0),之后目标消失 → 下次刷新即删。
|
|
1595
|
+
*/
|
|
1596
|
+
function pruneMissingApprovals() {
|
|
1597
|
+
const now = Date.now()
|
|
1598
|
+
const keep = []
|
|
1599
|
+
let changed = false
|
|
1600
|
+
for (const entry of approvalState.entries) {
|
|
1601
|
+
let exists = false
|
|
1602
|
+
try {
|
|
1603
|
+
exists = existsSync(entry.path)
|
|
1604
|
+
} catch {
|
|
1605
|
+
exists = false
|
|
1606
|
+
}
|
|
1607
|
+
if (exists) {
|
|
1608
|
+
if (!entry.lastSeenAt || now - entry.lastSeenAt > 60_000) {
|
|
1609
|
+
entry.lastSeenAt = now
|
|
1610
|
+
changed = true
|
|
1611
|
+
}
|
|
1612
|
+
keep.push(entry)
|
|
1613
|
+
continue
|
|
1614
|
+
}
|
|
1615
|
+
const approvedAt = Number(entry.approvedAt) || 0
|
|
1616
|
+
const seen = Number(entry.lastSeenAt) || 0
|
|
1617
|
+
if (seen > 0 || (approvedAt > 0 && now - approvedAt > 30 * 60_000)) {
|
|
1618
|
+
changed = true
|
|
1619
|
+
continue
|
|
1620
|
+
}
|
|
1621
|
+
keep.push(entry)
|
|
1622
|
+
}
|
|
1623
|
+
if (changed) {
|
|
1624
|
+
approvalState.entries = keep
|
|
1625
|
+
saveApprovalsNow()
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1552
1629
|
function registerApproval(session, targetPath, { reason, basis, kind = 'file' } = {}) {
|
|
1553
1630
|
const id = sessionKey(session)
|
|
1554
1631
|
if (!id) throw new Error('longterm_approve: session is unavailable')
|
|
@@ -2148,6 +2225,8 @@ export function apply(ctx, config) {
|
|
|
2148
2225
|
}
|
|
2149
2226
|
})()
|
|
2150
2227
|
if (pathname.endsWith('/state') && req.method === 'GET') {
|
|
2228
|
+
// v0.9.3:目标已不存在的条目自动回收(新建→批准→写入的窗口期受保护)
|
|
2229
|
+
pruneMissingApprovals()
|
|
2151
2230
|
const approvals = approvalEntriesForPanel().map((entry) => ({
|
|
2152
2231
|
...entry,
|
|
2153
2232
|
current: Boolean(sessionId && entry.sessionId === sessionId),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-session-tmpdir",
|
|
3
|
-
"version": "0.9.
|
|
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": {
|