@lingda-ai/dsh-plugin-vault 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +117 -2
- package/bin/dsh-vault.mjs +189 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +7 -0
- package/index.js +84 -0
- package/lib/client.js +369 -0
- package/lib/route.js +70 -0
- package/lib/scope.js +125 -0
- package/lib/tool.js +60 -0
- package/lib/vault.js +268 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +83 -4
package/lib/client.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lingda-ai/dsh-plugin-vault —— Client 半(右侧栏「机库」tab)
|
|
3
|
+
*
|
|
4
|
+
* 契约同套件其它两件:classic script、一次 __ModuleLoader__.load()、
|
|
5
|
+
* sidebarRightTabs.register + slots.inject 两个座位。
|
|
6
|
+
*
|
|
7
|
+
* 这一屏只读:备份与回滚都在终端(dsh-vault),面板负责"让你看懂现在处于什么状态、
|
|
8
|
+
* 以及真要退回去时该敲哪一行"。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
window.__ModuleLoader__.load({
|
|
12
|
+
id: '@lingda-ai/dsh-plugin-vault',
|
|
13
|
+
factory(require) {
|
|
14
|
+
const React = require('react')
|
|
15
|
+
const h = React.createElement
|
|
16
|
+
const { useState, useEffect, useRef, useCallback } = React
|
|
17
|
+
|
|
18
|
+
const ID = '@lingda-ai/dsh-plugin-vault'
|
|
19
|
+
const KIND = 'vault.hangar'
|
|
20
|
+
const API = '/dsh-vault/api'
|
|
21
|
+
|
|
22
|
+
const C = {
|
|
23
|
+
t1: '#1f2733', t2: '#5a6472', t3: '#64707f', t4: '#8a93a0',
|
|
24
|
+
hair: '#eef1f5', card: '#fafbfd', green: '#2f7d64', amber: '#c98a12', red: '#b4453c', blue: '#2f6feb',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DICT = {
|
|
28
|
+
zh: {
|
|
29
|
+
title: '机库',
|
|
30
|
+
guideDesc: '备份与回滚:改坏了能退回去,且知道退到哪一份',
|
|
31
|
+
refresh: '刷新',
|
|
32
|
+
loading: '正在读机库…',
|
|
33
|
+
empty: '机库还是空的',
|
|
34
|
+
emptyBody: '先给现在这份能用的配置拍一张。终端执行一次即可,之后每次装插件前跑一次更稳妥。',
|
|
35
|
+
emptyCmd: 'dsh-vault create',
|
|
36
|
+
errTitle: '机库读不出来',
|
|
37
|
+
latest: '最近一份',
|
|
38
|
+
intact: '完整',
|
|
39
|
+
broken: '不一致',
|
|
40
|
+
changed: '已改',
|
|
41
|
+
missing: '缺失',
|
|
42
|
+
added: '新增',
|
|
43
|
+
none: '无',
|
|
44
|
+
diffTitle: '当前配置 vs 这一份',
|
|
45
|
+
history: '历史备份',
|
|
46
|
+
restore: '要退回去,在终端执行',
|
|
47
|
+
restoreNote: '回滚前会自动把当前状态再备一份,点错了也能退回',
|
|
48
|
+
notBackedUp: '不备份:凭据 / 会话 / 存储 / node_modules',
|
|
49
|
+
files: '{n} 个文件',
|
|
50
|
+
open: '查看',
|
|
51
|
+
},
|
|
52
|
+
en: {
|
|
53
|
+
title: 'Hangar',
|
|
54
|
+
guideDesc: 'Backups and rollback: if a change breaks things, you know which snapshot to return to',
|
|
55
|
+
refresh: 'Refresh',
|
|
56
|
+
loading: 'Reading hangar…',
|
|
57
|
+
empty: 'The hangar is empty',
|
|
58
|
+
emptyBody: 'Snapshot the config that works today. One command in the terminal; run it again before installing plugins.',
|
|
59
|
+
emptyCmd: 'dsh-vault create',
|
|
60
|
+
errTitle: 'Hangar unavailable',
|
|
61
|
+
latest: 'Latest',
|
|
62
|
+
intact: 'intact',
|
|
63
|
+
broken: 'mismatch',
|
|
64
|
+
changed: 'changed',
|
|
65
|
+
missing: 'missing',
|
|
66
|
+
added: 'added',
|
|
67
|
+
none: 'none',
|
|
68
|
+
diffTitle: 'Current config vs this snapshot',
|
|
69
|
+
history: 'History',
|
|
70
|
+
restore: 'To roll back, run',
|
|
71
|
+
restoreNote: 'A fresh snapshot of the current state is taken first, so a wrong click is recoverable',
|
|
72
|
+
notBackedUp: 'Never backed up: credentials / sessions / storages / node_modules',
|
|
73
|
+
files: '{n} files',
|
|
74
|
+
open: 'View',
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let T = DICT.zh
|
|
79
|
+
|
|
80
|
+
function getService(ctx, name) {
|
|
81
|
+
try {
|
|
82
|
+
if (ctx && typeof ctx.get === 'function') return ctx.get(name) ?? null
|
|
83
|
+
return (ctx && ctx[name]) ?? null
|
|
84
|
+
} catch {
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function detectLocale(ctx) {
|
|
90
|
+
const locale = getService(ctx, 'locale')
|
|
91
|
+
let id = ''
|
|
92
|
+
try {
|
|
93
|
+
const snapshot = typeof locale?.getLocale === 'function' ? locale.getLocale() : null
|
|
94
|
+
if (typeof snapshot === 'string') id = snapshot
|
|
95
|
+
else if (snapshot) id = String(snapshot.id || snapshot.locale || snapshot.language || '')
|
|
96
|
+
} catch {
|
|
97
|
+
id = ''
|
|
98
|
+
}
|
|
99
|
+
if (id.length === 0) {
|
|
100
|
+
try {
|
|
101
|
+
id = window.navigator.language || ''
|
|
102
|
+
} catch {
|
|
103
|
+
id = ''
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return /^en/i.test(id) ? 'en' : 'zh'
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function clockOf(at) {
|
|
110
|
+
if (!Number.isFinite(at)) return '—'
|
|
111
|
+
const d = new Date(at)
|
|
112
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
113
|
+
return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function kb(bytes) {
|
|
117
|
+
if (!Number.isFinite(bytes)) return '—'
|
|
118
|
+
if (bytes < 1024) return bytes + 'B'
|
|
119
|
+
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB'
|
|
120
|
+
return (bytes / 1024 / 1024).toFixed(1) + 'MB'
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function getJson(query, signal) {
|
|
124
|
+
const response = await fetch(API + '?' + query, { signal, headers: { accept: 'application/json' } })
|
|
125
|
+
if (!response.ok) throw new Error('HTTP ' + response.status)
|
|
126
|
+
const data = await response.json()
|
|
127
|
+
if (!data || data.ok !== true) throw new Error((data && data.error) || '查询失败')
|
|
128
|
+
return data
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function Code(props) {
|
|
132
|
+
return h('div', {
|
|
133
|
+
style: {
|
|
134
|
+
marginTop: 6, padding: '7px 9px', background: '#f5f7fa', borderRadius: 7,
|
|
135
|
+
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 10.5,
|
|
136
|
+
color: C.t1, wordBreak: 'break-all', lineHeight: 1.6,
|
|
137
|
+
},
|
|
138
|
+
}, props.text)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function Tag(props) {
|
|
142
|
+
const color = props.tone === 'ok' ? C.green : props.tone === 'warn' ? C.amber : props.tone === 'bad' ? C.red : C.t3
|
|
143
|
+
return h('span', {
|
|
144
|
+
style: {
|
|
145
|
+
fontSize: 10, padding: '1px 6px', borderRadius: 4, color,
|
|
146
|
+
background: props.tone === 'ok' ? '#edf6f1' : props.tone === 'warn' ? '#fdf7ec' : props.tone === 'bad' ? '#fbeeec' : '#f2f4f8',
|
|
147
|
+
},
|
|
148
|
+
}, props.text)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function Panel() {
|
|
152
|
+
const [data, setData] = useState(null)
|
|
153
|
+
const [verify, setVerify] = useState(null)
|
|
154
|
+
const [diff, setDiff] = useState(null)
|
|
155
|
+
const [error, setError] = useState(null)
|
|
156
|
+
const [loading, setLoading] = useState(true)
|
|
157
|
+
const [tick, setTick] = useState(0)
|
|
158
|
+
const [picked, setPicked] = useState(null)
|
|
159
|
+
const alive = useRef(true)
|
|
160
|
+
|
|
161
|
+
useEffect(() => () => { alive.current = false }, [])
|
|
162
|
+
|
|
163
|
+
useEffect(() => {
|
|
164
|
+
const controller = new AbortController()
|
|
165
|
+
setLoading(true)
|
|
166
|
+
getJson('list=1', controller.signal)
|
|
167
|
+
.then((payload) => {
|
|
168
|
+
if (!alive.current) return
|
|
169
|
+
setData(payload)
|
|
170
|
+
setError(null)
|
|
171
|
+
setLoading(false)
|
|
172
|
+
const first = (payload.backups || []).find((item) => !item.broken)
|
|
173
|
+
setPicked((current) => current ?? (first ? first.id : null))
|
|
174
|
+
})
|
|
175
|
+
.catch((cause) => {
|
|
176
|
+
if (cause && cause.name === 'AbortError') return
|
|
177
|
+
if (!alive.current) return
|
|
178
|
+
setError(cause.message || '读取失败')
|
|
179
|
+
setLoading(false)
|
|
180
|
+
})
|
|
181
|
+
return () => controller.abort()
|
|
182
|
+
}, [tick])
|
|
183
|
+
|
|
184
|
+
// 选中某个备份后再取校验与差异:两个请求都便宜,但只在需要时才发
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
if (!picked) {
|
|
187
|
+
setVerify(null)
|
|
188
|
+
setDiff(null)
|
|
189
|
+
return undefined
|
|
190
|
+
}
|
|
191
|
+
const controller = new AbortController()
|
|
192
|
+
getJson('verify=' + encodeURIComponent(picked), controller.signal)
|
|
193
|
+
.then((payload) => { if (alive.current) setVerify(payload) })
|
|
194
|
+
.catch(() => {})
|
|
195
|
+
getJson('diff=' + encodeURIComponent(picked), controller.signal)
|
|
196
|
+
.then((payload) => { if (alive.current) setDiff(payload) })
|
|
197
|
+
.catch(() => {})
|
|
198
|
+
return () => controller.abort()
|
|
199
|
+
}, [picked, tick])
|
|
200
|
+
|
|
201
|
+
const refresh = useCallback(() => setTick((n) => n + 1), [])
|
|
202
|
+
|
|
203
|
+
const head = h('div', {
|
|
204
|
+
style: {
|
|
205
|
+
display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px 8px',
|
|
206
|
+
borderBottom: '1px solid ' + C.hair,
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
h('span', { style: { fontSize: 13, fontWeight: 600, color: C.t1, whiteSpace: 'nowrap' } }, T.title),
|
|
210
|
+
data
|
|
211
|
+
? h('span', {
|
|
212
|
+
style: {
|
|
213
|
+
fontSize: 10.5, color: C.t3, border: '1px solid #e1e6ee', borderRadius: 999,
|
|
214
|
+
padding: '1px 7px', whiteSpace: 'nowrap',
|
|
215
|
+
},
|
|
216
|
+
}, T.files.replace('{n}', String((data.backups || []).length)))
|
|
217
|
+
: null,
|
|
218
|
+
h('button', {
|
|
219
|
+
type: 'button',
|
|
220
|
+
onClick: refresh,
|
|
221
|
+
style: {
|
|
222
|
+
marginLeft: 'auto', border: '1px solid #d8dee7', background: '#fff',
|
|
223
|
+
borderRadius: 7, padding: '3px 9px', fontSize: 11.5, color: C.t2, cursor: 'pointer',
|
|
224
|
+
},
|
|
225
|
+
}, T.refresh),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
let body
|
|
229
|
+
if (loading && !data) {
|
|
230
|
+
body = h('div', { style: { padding: '16px 14px', fontSize: 11.5, color: C.t3 } }, T.loading)
|
|
231
|
+
} else if (error) {
|
|
232
|
+
body = h('div', { style: { padding: '16px 14px' } },
|
|
233
|
+
h('div', { style: { fontSize: 13, fontWeight: 600, color: C.t1, marginBottom: 6 } }, T.errTitle),
|
|
234
|
+
h('div', { style: { fontSize: 11.5, color: C.t2, lineHeight: 1.7 } }, error))
|
|
235
|
+
} else if (data && (data.backups || []).length === 0) {
|
|
236
|
+
body = h('div', { style: { padding: '18px 14px 14px' } },
|
|
237
|
+
h('div', { style: { fontSize: 14, fontWeight: 600, color: C.t1, marginBottom: 6 } }, T.empty),
|
|
238
|
+
h('div', { style: { fontSize: 11.5, lineHeight: 1.7, color: C.t2 } }, T.emptyBody),
|
|
239
|
+
h(Code, { text: T.emptyCmd }))
|
|
240
|
+
} else if (data) {
|
|
241
|
+
const backups = data.backups || []
|
|
242
|
+
const current = backups.find((item) => item.id === picked) || backups[0]
|
|
243
|
+
const summary = verify ? verify.summary : null
|
|
244
|
+
const intact = summary ? summary.backupIntact === summary.total : null
|
|
245
|
+
|
|
246
|
+
body = h('div', null,
|
|
247
|
+
h('div', { style: { padding: '12px 14px 0' } },
|
|
248
|
+
h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 8 } },
|
|
249
|
+
h('span', { style: { fontSize: 11, color: C.t3 } }, T.latest),
|
|
250
|
+
h('span', {
|
|
251
|
+
style: { fontSize: 13, fontWeight: 600, color: C.t1, fontFamily: 'ui-monospace, monospace' },
|
|
252
|
+
}, current ? current.id : '—'),
|
|
253
|
+
intact === null ? null : h(Tag, { tone: intact ? 'ok' : 'bad', text: intact ? T.intact : T.broken }),
|
|
254
|
+
),
|
|
255
|
+
current
|
|
256
|
+
? h('div', { style: { marginTop: 4, fontSize: 10.5, color: C.t3 } },
|
|
257
|
+
clockOf(current.createdAt) + ' · ' + T.files.replace('{n}', String(current.files)) + ' · ' + kb(current.bytes))
|
|
258
|
+
: null,
|
|
259
|
+
),
|
|
260
|
+
|
|
261
|
+
diff
|
|
262
|
+
? h('div', { style: { padding: '10px 14px 0' } },
|
|
263
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.diffTitle),
|
|
264
|
+
[
|
|
265
|
+
[T.changed, diff.changed, diff.changed.length ? 'warn' : null],
|
|
266
|
+
[T.missing, diff.missing, diff.missing.length ? 'bad' : null],
|
|
267
|
+
[T.added, diff.added, null],
|
|
268
|
+
].map(([label, list, tone], index) => h('div', {
|
|
269
|
+
key: index,
|
|
270
|
+
style: { display: 'flex', gap: 8, padding: '4px 0', alignItems: 'baseline' },
|
|
271
|
+
},
|
|
272
|
+
h('span', { style: { width: 34, flex: 'none', fontSize: 11, color: C.t3 } }, label),
|
|
273
|
+
h('span', { style: { flex: 1, minWidth: 0, fontSize: 11, color: C.t2 } },
|
|
274
|
+
list.length === 0 ? T.none : list.slice(0, 4).join('、') + (list.length > 4 ? ` +${list.length - 4}` : '')),
|
|
275
|
+
tone ? h(Tag, { tone, text: String(list.length) }) : null,
|
|
276
|
+
)))
|
|
277
|
+
: null,
|
|
278
|
+
|
|
279
|
+
h('div', { style: { padding: '10px 14px 0' } },
|
|
280
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.history),
|
|
281
|
+
backups.slice(0, 6).map((item) => h('div', {
|
|
282
|
+
key: item.id,
|
|
283
|
+
onClick: () => setPicked(item.id),
|
|
284
|
+
style: {
|
|
285
|
+
display: 'flex', gap: 8, padding: '6px 0', alignItems: 'baseline', cursor: 'pointer',
|
|
286
|
+
opacity: picked === item.id ? 1 : 0.72,
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
h('span', {
|
|
290
|
+
style: {
|
|
291
|
+
width: 12, flex: 'none', fontSize: 10, color: picked === item.id ? C.blue : C.t4,
|
|
292
|
+
},
|
|
293
|
+
}, picked === item.id ? '●' : '○'),
|
|
294
|
+
h('span', { style: { flex: 1, minWidth: 0, fontSize: 11.5, color: C.t2, fontFamily: 'ui-monospace, monospace' } }, item.id),
|
|
295
|
+
h('span', { style: { fontSize: 10.5, color: C.t4 } }, kb(item.bytes)),
|
|
296
|
+
))),
|
|
297
|
+
|
|
298
|
+
h('div', { style: { padding: '10px 14px 4px' } },
|
|
299
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.restore),
|
|
300
|
+
h(Code, { text: picked ? 'dsh-vault restore ' + picked : 'dsh-vault list' }),
|
|
301
|
+
h('div', { style: { marginTop: 5, fontSize: 10.5, color: C.t4, lineHeight: 1.6 } }, T.restoreNote)))
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const foot = h('div', {
|
|
305
|
+
style: { padding: '10px 14px 12px', fontSize: 10.5, lineHeight: 1.65, color: C.t4 },
|
|
306
|
+
}, T.notBackedUp)
|
|
307
|
+
|
|
308
|
+
return h('div', { style: { display: 'flex', flexDirection: 'column', minHeight: 0 } }, head, body, foot)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function makeTitle() {
|
|
312
|
+
return function Title() {
|
|
313
|
+
return h('span', { style: { fontSize: 12, fontWeight: 600, color: C.t1 } }, T.title)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function apply(ctx) {
|
|
318
|
+
if (!ctx) return
|
|
319
|
+
T = DICT[detectLocale(ctx)] || DICT.zh
|
|
320
|
+
|
|
321
|
+
const tabs = getService(ctx, 'sidebarRightTabs')
|
|
322
|
+
const slots = getService(ctx, 'slots')
|
|
323
|
+
let disposers = []
|
|
324
|
+
|
|
325
|
+
if (tabs && typeof tabs.register === 'function') {
|
|
326
|
+
try {
|
|
327
|
+
disposers.push(tabs.register({
|
|
328
|
+
id: ID,
|
|
329
|
+
kind: KIND,
|
|
330
|
+
title: () => T.title,
|
|
331
|
+
priority: 'extension',
|
|
332
|
+
keepMounted: false,
|
|
333
|
+
guide: [{ id: 'vault.open', order: 60, title: () => T.title, description: () => T.guideDesc }],
|
|
334
|
+
}))
|
|
335
|
+
} catch (error) {
|
|
336
|
+
console.warn('[vault] 右栏 tab 登记失败:', error)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (slots && typeof slots.inject === 'function' && typeof slots.register === 'function') {
|
|
341
|
+
try {
|
|
342
|
+
disposers.push(slots.inject('sidebar.right.pane.tab', () =>
|
|
343
|
+
slots.register({ name: 'sidebar.right.pane.tab', key: ID }, Panel)))
|
|
344
|
+
disposers.push(slots.inject('sidebar.right.pane.tab.title', () =>
|
|
345
|
+
slots.register({ name: 'sidebar.right.pane.tab.title', key: ID }, makeTitle())))
|
|
346
|
+
} catch (error) {
|
|
347
|
+
console.warn('[vault] 面板挂载失败:', error)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const cleanup = () => {
|
|
352
|
+
for (const dispose of disposers) {
|
|
353
|
+
try {
|
|
354
|
+
dispose && dispose()
|
|
355
|
+
} catch {}
|
|
356
|
+
}
|
|
357
|
+
disposers = []
|
|
358
|
+
}
|
|
359
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
|
|
360
|
+
else if (typeof ctx.on === 'function') ctx.on('dispose', cleanup)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
inject: ['sidebarRightTabs'],
|
|
365
|
+
apply,
|
|
366
|
+
__test: { clockOf, kb, detectLocale, DICT, apply },
|
|
367
|
+
}
|
|
368
|
+
},
|
|
369
|
+
})
|
package/lib/route.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 机库的只读 HTTP 面。写操作(创建备份、回滚)**故意不开放 HTTP**:
|
|
3
|
+
* 回滚会覆盖用户文件,必须由人在终端里显式敲一次,才能在日志里留下"谁在什么时候动过"。
|
|
4
|
+
*/
|
|
5
|
+
export const API_PREFIX = '/dsh-vault/api'
|
|
6
|
+
|
|
7
|
+
export function createApi({ vault }) {
|
|
8
|
+
return {
|
|
9
|
+
list() {
|
|
10
|
+
const items = vault.list()
|
|
11
|
+
return {
|
|
12
|
+
ok: true,
|
|
13
|
+
vaultDir: vault.vaultDir,
|
|
14
|
+
home: vault.home,
|
|
15
|
+
backups: items,
|
|
16
|
+
policy: {
|
|
17
|
+
excludes: ['credentials', '*token*', '*secret*', '*.key', '.env', 'sessions', 'storages', 'node_modules'],
|
|
18
|
+
keeps: '默认保留最近 10 份',
|
|
19
|
+
},
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
verify(id) {
|
|
23
|
+
return vault.verify(id)
|
|
24
|
+
},
|
|
25
|
+
diff(id) {
|
|
26
|
+
return vault.diff(id)
|
|
27
|
+
},
|
|
28
|
+
manifest(id) {
|
|
29
|
+
const manifest = vault.readManifest(id)
|
|
30
|
+
if (manifest === null) return { ok: false, error: `找不到备份 ${id}` }
|
|
31
|
+
return { ok: true, manifest }
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function handleRequest(api, req, res) {
|
|
37
|
+
const send = (body) => {
|
|
38
|
+
const text = JSON.stringify(body)
|
|
39
|
+
res.writeHead(200, {
|
|
40
|
+
'content-type': 'application/json; charset=utf-8',
|
|
41
|
+
'cache-control': 'no-store',
|
|
42
|
+
'content-length': Buffer.byteLength(text),
|
|
43
|
+
})
|
|
44
|
+
res.end(text)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
48
|
+
send({ ok: false, error: '机库只提供只读查询;回滚请在终端执行 dsh-vault restore <id>' })
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let url
|
|
53
|
+
try {
|
|
54
|
+
url = new URL(req.url ?? '/', 'http://localhost')
|
|
55
|
+
} catch {
|
|
56
|
+
send({ ok: false, error: '请求地址不合法' })
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const id = url.searchParams.get('verify') ?? url.searchParams.get('diff') ?? url.searchParams.get('manifest')
|
|
61
|
+
try {
|
|
62
|
+
if (url.searchParams.has('list')) send(api.list())
|
|
63
|
+
else if (url.searchParams.has('verify')) send(id === null ? { ok: false, error: '缺少备份 id' } : api.verify(id))
|
|
64
|
+
else if (url.searchParams.has('diff')) send(id === null ? { ok: false, error: '缺少备份 id' } : api.diff(id))
|
|
65
|
+
else if (url.searchParams.has('manifest')) send(id === null ? { ok: false, error: '缺少备份 id' } : api.manifest(id))
|
|
66
|
+
else send({ ok: false, error: '未知查询:用 list / verify / diff / manifest' })
|
|
67
|
+
} catch (error) {
|
|
68
|
+
send({ ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
69
|
+
}
|
|
70
|
+
}
|
package/lib/scope.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 备什么、不备什么:这是一条**安全边界**,不是配置项。
|
|
3
|
+
*
|
|
4
|
+
* 默认只备"改坏了会让人开不了工、但又不含密钥"的东西:
|
|
5
|
+
* - 每个 profile 的 package.json(装了哪些插件、bundle 顺序)
|
|
6
|
+
* - 每个 profile 的 cordis 补丁层(*.yml / *.yaml)
|
|
7
|
+
* - 根目录的 settings.json / app-patches
|
|
8
|
+
*
|
|
9
|
+
* 明确**不备**:
|
|
10
|
+
* - .credentials.yaml、任何 *token* / *secret* / *.key / .env —— 备份目录是普通文件,
|
|
11
|
+
* 把密钥复制进去等于多造一份泄漏面;
|
|
12
|
+
* - sessions/、storages/、node_modules/ —— 体积大、无配置价值。
|
|
13
|
+
*
|
|
14
|
+
* 用户可以加 include,但"不备密钥"这条不可通过配置打开。
|
|
15
|
+
*/
|
|
16
|
+
import { readdirSync, statSync } from 'node:fs'
|
|
17
|
+
import { join, relative, sep } from 'node:path'
|
|
18
|
+
import { homedir } from 'node:os'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* DSH_HOME 指向的就是 `~/.dsh` 本身(profiles 就在它下面),
|
|
22
|
+
* 所以"家"是 `~/.dsh`,不是 `~`。这条搞错的话,备份会一个文件都匹配不到。
|
|
23
|
+
*/
|
|
24
|
+
export function dshHomeOf(env = process.env) {
|
|
25
|
+
return env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function defaultVaultDir(home = dshHomeOf()) {
|
|
29
|
+
return join(home, 'ops', 'vault')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const DEFAULT_INCLUDE = Object.freeze([
|
|
33
|
+
'profiles/*/package.json',
|
|
34
|
+
'profiles/*/*.yml',
|
|
35
|
+
'profiles/*/*.yaml',
|
|
36
|
+
'settings.json',
|
|
37
|
+
'app-patches',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
/** 永远不备份:命中即跳过,且**不能**被 include 覆盖。 */
|
|
41
|
+
export const ALWAYS_EXCLUDE_NAMES = Object.freeze([
|
|
42
|
+
'.credentials.yaml', '.credentials.yml', '.env', '.netrc',
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
export const ALWAYS_EXCLUDE_DIRS = Object.freeze(['node_modules', '.git', 'sessions', 'storages'])
|
|
46
|
+
|
|
47
|
+
export function isSecretName(name) {
|
|
48
|
+
const lower = name.toLowerCase()
|
|
49
|
+
if (ALWAYS_EXCLUDE_NAMES.includes(lower)) return true
|
|
50
|
+
if (lower.endsWith('.key') || lower.endsWith('.pem') || lower.endsWith('.p12')) return true
|
|
51
|
+
return /(^|[._-])(token|secret|password|credential|credentials)([._-]|$)/.test(lower)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 极简通配:只支持 `*`(单段)与 `**`(任意段),够用且好解释。 */
|
|
55
|
+
export function matchGlob(pattern, path) {
|
|
56
|
+
const escaped = pattern
|
|
57
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
58
|
+
.replace(/\*\*\//g, '\u0000')
|
|
59
|
+
.replace(/\*/g, '[^/]*')
|
|
60
|
+
.replace(/\u0000/g, '(?:.*/)?')
|
|
61
|
+
return new RegExp('^' + escaped + '$').test(path)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function walk(root, dir, out, depth) {
|
|
65
|
+
if (depth > 6) return
|
|
66
|
+
let entries
|
|
67
|
+
try {
|
|
68
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
69
|
+
} catch {
|
|
70
|
+
return
|
|
71
|
+
}
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
const full = join(dir, entry.name)
|
|
74
|
+
if (entry.isDirectory()) {
|
|
75
|
+
if (ALWAYS_EXCLUDE_DIRS.includes(entry.name)) continue
|
|
76
|
+
walk(root, full, out, depth + 1)
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
if (!entry.isFile()) continue
|
|
80
|
+
if (isSecretName(entry.name)) continue
|
|
81
|
+
out.push(relative(root, full).split(sep).join('/'))
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 列出"应当备份"的相对路径(相对 DSH_HOME)。
|
|
87
|
+
* @param {{home?: string, include?: string[], exclude?: string[]}} options
|
|
88
|
+
*/
|
|
89
|
+
export function selectFiles(options = {}) {
|
|
90
|
+
const home = options.home ?? dshHomeOf()
|
|
91
|
+
const include = options.include ?? DEFAULT_INCLUDE
|
|
92
|
+
const exclude = options.exclude ?? []
|
|
93
|
+
|
|
94
|
+
const all = []
|
|
95
|
+
// 只走顶层与 profiles:不递归整棵 ~/.dsh(那里有 sessions/storages)
|
|
96
|
+
try {
|
|
97
|
+
for (const entry of readdirSync(home, { withFileTypes: true })) {
|
|
98
|
+
if (entry.isDirectory()) {
|
|
99
|
+
if (ALWAYS_EXCLUDE_DIRS.includes(entry.name)) continue
|
|
100
|
+
if (entry.name === 'profiles' || entry.name === 'app-patches') walk(home, join(home, entry.name), all, 0)
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
if (isSecretName(entry.name)) continue
|
|
104
|
+
all.push(entry.name)
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
return []
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const selected = all.filter((path) => {
|
|
111
|
+
if (isSecretName(path.split('/').pop() ?? '')) return false
|
|
112
|
+
if (exclude.some((pattern) => matchGlob(pattern, path))) return false
|
|
113
|
+
return include.some((pattern) => matchGlob(pattern, path) || path === pattern || path.startsWith(pattern + '/'))
|
|
114
|
+
})
|
|
115
|
+
return selected.sort()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 文件大小(不读内容)。 */
|
|
119
|
+
export function sizeOf(home, relativePath) {
|
|
120
|
+
try {
|
|
121
|
+
return statSync(join(home, relativePath)).size
|
|
122
|
+
} catch {
|
|
123
|
+
return null
|
|
124
|
+
}
|
|
125
|
+
}
|
package/lib/tool.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vault_query:让 Agent 知道"有没有备份、能不能退回去"。
|
|
3
|
+
*
|
|
4
|
+
* 刻意**不**提供 create/restore:一次误回滚会覆盖用户正在用的配置。
|
|
5
|
+
* Agent 可以查、可以建议,动手必须是人。
|
|
6
|
+
*/
|
|
7
|
+
export function createVaultTool({ vault }) {
|
|
8
|
+
return {
|
|
9
|
+
name: 'vault_query',
|
|
10
|
+
description:
|
|
11
|
+
'查询机库备份:有哪些备份、某个备份是否完整、它与当前配置差在哪里。'
|
|
12
|
+
+ '只读——创建备份与回滚需要用户在终端执行 dsh-vault,Agent 不能代替。',
|
|
13
|
+
parameters: {
|
|
14
|
+
type: 'object',
|
|
15
|
+
additionalProperties: false,
|
|
16
|
+
properties: {
|
|
17
|
+
op: { type: 'string', enum: ['list', 'verify', 'diff'], description: '默认 list' },
|
|
18
|
+
id: { type: 'string', description: '备份 id(verify / diff 需要)' },
|
|
19
|
+
},
|
|
20
|
+
required: [],
|
|
21
|
+
},
|
|
22
|
+
output: {
|
|
23
|
+
schema: { type: 'string' },
|
|
24
|
+
render(_args, value) {
|
|
25
|
+
return [{ type: 'text', text: String(value) }]
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
async execute(args) {
|
|
29
|
+
const op = args?.op ?? 'list'
|
|
30
|
+
if (op === 'list') {
|
|
31
|
+
const items = vault.list()
|
|
32
|
+
if (items.length === 0) return `机库还是空的(${vault.vaultDir})。终端执行 dsh-vault create 建第一份。`
|
|
33
|
+
const lines = [`共 ${items.length} 份备份:`]
|
|
34
|
+
for (const item of items.slice(0, 10)) {
|
|
35
|
+
lines.push(`- ${item.id} · ${item.files} 个文件 · ${Math.round((item.bytes ?? 0) / 1024)}KB${item.note ? ' · ' + item.note : ''}`)
|
|
36
|
+
}
|
|
37
|
+
return lines.join('\n')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const id = args?.id
|
|
41
|
+
if (typeof id !== 'string' || id.length === 0) return `op=${op} 需要 id。先 op=list 看有哪些。`
|
|
42
|
+
|
|
43
|
+
if (op === 'verify') {
|
|
44
|
+
const result = vault.verify(id)
|
|
45
|
+
if (!result.ok) return result.error
|
|
46
|
+
const s = result.summary
|
|
47
|
+
return `备份 ${id}(${s.total} 个文件):完整 ${s.backupIntact}/${s.total};`
|
|
48
|
+
+ `当前状态 相同 ${s.currentSame} · 已改 ${s.currentChanged} · 缺失 ${s.currentMissing}`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const result = vault.diff(id)
|
|
52
|
+
if (!result.ok) return result.error
|
|
53
|
+
const lines = [`当前 vs 备份 ${id}:`]
|
|
54
|
+
lines.push(`- 已改 ${result.changed.length}${result.changed.length ? ':' + result.changed.slice(0, 5).join(', ') : ''}`)
|
|
55
|
+
lines.push(`- 缺失 ${result.missing.length}${result.missing.length ? ':' + result.missing.slice(0, 5).join(', ') : ''}`)
|
|
56
|
+
lines.push(`- 新增 ${result.added.length}${result.added.length ? ':' + result.added.slice(0, 5).join(', ') : ''}`)
|
|
57
|
+
return lines.join('\n')
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
}
|