dsh-vigil 0.0.1
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 +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local quarantine for blocked deletions (FR-4).
|
|
3
|
+
*
|
|
4
|
+
* A blocked deletion is only recoverable if the files still exist. For an
|
|
5
|
+
* unambiguous, literal target (no glob, no unresolved variable) this module
|
|
6
|
+
* performs the "reversible delete" itself, inside the pre-execute hook, and then
|
|
7
|
+
* the original command is denied: the deletion effectively becomes a move into
|
|
8
|
+
* `<DSH_HOME>/vigil/quarantine/<id>/payload`, described by a `manifest.json`
|
|
9
|
+
* next to it.
|
|
10
|
+
*
|
|
11
|
+
* Deliberate limits (FR-4.4: never guess):
|
|
12
|
+
* - wildcard, variable and unparseable targets are never quarantined;
|
|
13
|
+
* - a directory move is one `rename`, so it is same-volume and cheap; a
|
|
14
|
+
* cross-volume directory is skipped (reported) rather than copied blindly;
|
|
15
|
+
* - critical roots are never quarantined: moving `~/.dsh` away would itself be
|
|
16
|
+
* a destructive act;
|
|
17
|
+
* - the store is capped by entry count and can expire entries.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-vigil/quarantine
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync } from 'node:fs'
|
|
23
|
+
import { basename, dirname, isAbsolute, join } from 'node:path'
|
|
24
|
+
import { atomicWriteJson, ensureDir, formatBytes, isWithin, nowIso, randomId, readJson, sha256 } from '../util.js'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Bound for the cross-volume fallback: a directory on another volume is copied
|
|
28
|
+
* (then removed) instead of renamed, but only when it is small enough that the
|
|
29
|
+
* synchronous copy cannot stall the harness or double the disk usage of a large
|
|
30
|
+
* tree. Larger targets are refused and reported, never copied silently.
|
|
31
|
+
*/
|
|
32
|
+
const CROSS_VOLUME_MAX_FILES = 5000
|
|
33
|
+
const CROSS_VOLUME_MAX_BYTES = 512 * 1024 * 1024
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Entry ids are directory names: they must never contain a separator, so a
|
|
37
|
+
* manifest cannot redirect `join(dir, id)` outside the quarantine.
|
|
38
|
+
*/
|
|
39
|
+
const ENTRY_ID_RE = /^q-[A-Za-z0-9._-]+$/
|
|
40
|
+
|
|
41
|
+
/** @typedef {'file'|'directory'} EntryKind */
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {object} QuarantineEntry
|
|
45
|
+
* @property {string} id
|
|
46
|
+
* @property {string} createdAt
|
|
47
|
+
* @property {string} originalPath
|
|
48
|
+
* @property {EntryKind} kind
|
|
49
|
+
* @property {number} bytes
|
|
50
|
+
* @property {string|null} sha256
|
|
51
|
+
* @property {string} reason
|
|
52
|
+
* @property {string|null} tool
|
|
53
|
+
* @property {string|null} session
|
|
54
|
+
* @property {string[]} ruleIds
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Create the quarantine store facade for one activation.
|
|
59
|
+
* @param {any} config resolved configuration
|
|
60
|
+
* @param {{ warn?: (message: string) => void }} [logger]
|
|
61
|
+
* @returns {QuarantineStore}
|
|
62
|
+
*/
|
|
63
|
+
export function createQuarantine(config, logger) {
|
|
64
|
+
const enabled = config?.quarantine?.enabled !== false
|
|
65
|
+
const dir = config?.paths?.quarantineDir ?? ''
|
|
66
|
+
const ttlDays = Math.max(1, Number(config?.quarantine?.ttlDays) || 7)
|
|
67
|
+
const maxEntries = Math.max(1, Number(config?.quarantine?.maxEntries) || 5000)
|
|
68
|
+
const ready = enabled ? ensureDir(dir) : false
|
|
69
|
+
if (enabled && !ready) logger?.warn?.(`[dsh-vigil] 无法创建隔离区目录:${dir}`)
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {object} target a classified delete target
|
|
73
|
+
* @param {{ tool?: string|null, session?: string|null, reason?: string, ruleIds?: string[] }} context
|
|
74
|
+
* @returns {{ ok: boolean, entry?: QuarantineEntry, error?: string }}
|
|
75
|
+
*/
|
|
76
|
+
function captureOne(target, context) {
|
|
77
|
+
if (!enabled || !ready) return { ok: false, error: '隔离区未启用' }
|
|
78
|
+
const source = target?.resolvedPath
|
|
79
|
+
if (typeof source !== 'string' || source === '') return { ok: false, error: '目标没有可解析路径' }
|
|
80
|
+
if (target.hasGlob) return { ok: false, error: '通配符目标不进入隔离区(FR-4.4)' }
|
|
81
|
+
if (target.rootLike) return { ok: false, error: '根目录/上级目录目标不进入隔离区' }
|
|
82
|
+
const currentCount = Number.isInteger(context?.entryCount) ? context.entryCount : entries().length
|
|
83
|
+
if (currentCount >= maxEntries) return { ok: false, error: `隔离区条目已达上限 ${maxEntries}` }
|
|
84
|
+
if (target.withinQuarantine) return { ok: false, error: '目标位于隔离区内部' }
|
|
85
|
+
|
|
86
|
+
let stat
|
|
87
|
+
try {
|
|
88
|
+
// Quarantining a symlink would move only the link while the manifest
|
|
89
|
+
// recorded the referent's kind/size/hash, and restoring it could recreate
|
|
90
|
+
// a link into a protected location. Refuse links outright.
|
|
91
|
+
stat = lstatSync(source)
|
|
92
|
+
if (stat.isSymbolicLink()) return { ok: false, error: '符号链接目标不进入隔离区' }
|
|
93
|
+
} catch {
|
|
94
|
+
return { ok: false, error: '目标不存在' }
|
|
95
|
+
}
|
|
96
|
+
const kind = /** @type {EntryKind} */ (stat.isDirectory() ? 'directory' : stat.isFile() ? 'file' : null)
|
|
97
|
+
if (kind === null) return { ok: false, error: '目标不是普通文件或目录' }
|
|
98
|
+
|
|
99
|
+
const id = randomId('q-')
|
|
100
|
+
const entryDir = join(dir, id)
|
|
101
|
+
const payloadDir = join(entryDir, 'payload')
|
|
102
|
+
try {
|
|
103
|
+
mkdirSync(payloadDir, { recursive: true })
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return { ok: false, error: `无法创建隔离区条目:${String(error)}` }
|
|
106
|
+
}
|
|
107
|
+
// Measure before moving: a directory's size is unreadable after the rename.
|
|
108
|
+
const bytes = kind === 'file' ? Number(stat.size) || 0 : measureTree(source).bytes
|
|
109
|
+
const destination = join(payloadDir, basename(source) || 'payload')
|
|
110
|
+
let sha = null
|
|
111
|
+
try {
|
|
112
|
+
if (kind === 'file') sha = sha256(readFileSync(source))
|
|
113
|
+
movePath(source, destination, kind)
|
|
114
|
+
} catch (error) {
|
|
115
|
+
removeEntryDir(entryDir)
|
|
116
|
+
return { ok: false, error: `移入隔离区失败:${error instanceof Error ? error.message : String(error)}` }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** @type {QuarantineEntry} */
|
|
120
|
+
const entry = {
|
|
121
|
+
id,
|
|
122
|
+
createdAt: nowIso(),
|
|
123
|
+
originalPath: source,
|
|
124
|
+
kind,
|
|
125
|
+
bytes,
|
|
126
|
+
sha256: sha,
|
|
127
|
+
reason: context?.reason ?? '',
|
|
128
|
+
tool: context?.tool ?? null,
|
|
129
|
+
session: context?.session ?? null,
|
|
130
|
+
ruleIds: Array.isArray(context?.ruleIds) ? context.ruleIds : [],
|
|
131
|
+
}
|
|
132
|
+
if (!atomicWriteJson(join(entryDir, config?.quarantine?.metadataFile || 'manifest.json'), entry)) {
|
|
133
|
+
// Metadata is what makes the entry restorable; restore the payload and fail.
|
|
134
|
+
try {
|
|
135
|
+
movePath(destination, source, kind)
|
|
136
|
+
} catch {
|
|
137
|
+
// the payload is still recoverable by hand from entryDir
|
|
138
|
+
}
|
|
139
|
+
removeEntryDir(entryDir)
|
|
140
|
+
return { ok: false, error: '无法写入隔离区清单,已回滚' }
|
|
141
|
+
}
|
|
142
|
+
return { ok: true, entry }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Quarantine a batch of classified targets. Returns what happened to each, so
|
|
147
|
+
* the deny reason can be honest.
|
|
148
|
+
* @param {object[]} targets
|
|
149
|
+
* @param {{ tool?: string|null, session?: string|null, reason?: string, ruleIds?: string[] }} [context]
|
|
150
|
+
* @returns {{ quarantined: Array<{ id: string, originalPath: string, kind: EntryKind, bytes: number }>, skipped: Array<{ originalPath: string, error: string }> }}
|
|
151
|
+
*/
|
|
152
|
+
function capture(targets, context = {}) {
|
|
153
|
+
/** @type {Array<{ id: string, originalPath: string, kind: EntryKind, bytes: number }>} */
|
|
154
|
+
const quarantined = []
|
|
155
|
+
/** @type {Array<{ originalPath: string, error: string }>} */
|
|
156
|
+
const skipped = []
|
|
157
|
+
// Read the manifest directory once per batch instead of once per target.
|
|
158
|
+
let entryCount = entries().length
|
|
159
|
+
for (const target of Array.isArray(targets) ? targets : []) {
|
|
160
|
+
const result = captureOne(target, { ...context, entryCount })
|
|
161
|
+
if (result.ok && result.entry) {
|
|
162
|
+
entryCount += 1
|
|
163
|
+
quarantined.push({
|
|
164
|
+
id: result.entry.id,
|
|
165
|
+
originalPath: result.entry.originalPath,
|
|
166
|
+
kind: result.entry.kind,
|
|
167
|
+
bytes: result.entry.bytes,
|
|
168
|
+
})
|
|
169
|
+
} else {
|
|
170
|
+
skipped.push({ originalPath: target?.resolvedPath ?? target?.raw ?? '?', error: result.error ?? '未知错误' })
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { quarantined, skipped }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** @returns {QuarantineEntry[]} */
|
|
177
|
+
function entries() {
|
|
178
|
+
if (!enabled || !ready) return []
|
|
179
|
+
/** @type {QuarantineEntry[]} */
|
|
180
|
+
const found = []
|
|
181
|
+
let names = []
|
|
182
|
+
try {
|
|
183
|
+
names = readdirSync(dir)
|
|
184
|
+
} catch {
|
|
185
|
+
return []
|
|
186
|
+
}
|
|
187
|
+
for (const name of names) {
|
|
188
|
+
if (!name.startsWith('q-') || !ENTRY_ID_RE.test(name)) continue
|
|
189
|
+
const manifestFile = join(dir, name, config?.quarantine?.metadataFile || 'manifest.json')
|
|
190
|
+
const manifest = readJson(manifestFile)
|
|
191
|
+
if (manifest && typeof manifest === 'object' && typeof manifest.id === 'string') {
|
|
192
|
+
// The directory name is authoritative: a manifest cannot point the
|
|
193
|
+
// entry id (and therefore the recursive delete on purge/restore) at
|
|
194
|
+
// another path such as `q-evil/../../victim`.
|
|
195
|
+
found.push(/** @type {QuarantineEntry} */ ({ ...manifest, id: name }))
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return found.sort((left, right) => String(left.createdAt).localeCompare(String(right.createdAt)))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Move one entry back to its original path.
|
|
203
|
+
* @param {string} id
|
|
204
|
+
* @param {{ force?: boolean }} [options]
|
|
205
|
+
* @returns {{ ok: boolean, restoredTo?: string, conflictPath?: string, error?: string }}
|
|
206
|
+
*/
|
|
207
|
+
function restore(id, options = {}) {
|
|
208
|
+
if (!enabled || !ready) return { ok: false, error: '隔离区未启用' }
|
|
209
|
+
if (!ENTRY_ID_RE.test(String(id ?? ''))) return { ok: false, error: `隔离区条目 id 不合法:${String(id)}` }
|
|
210
|
+
const entry = entries().find(item => item.id === id)
|
|
211
|
+
if (!entry) return { ok: false, error: `未找到隔离区条目 ${id}` }
|
|
212
|
+
const originalPath = typeof entry.originalPath === 'string' ? entry.originalPath : ''
|
|
213
|
+
if (!isAbsolute(originalPath)) return { ok: false, error: '清单缺少可用的原始路径' }
|
|
214
|
+
const payloadFile = join(dir, entry.id, 'payload', basename(originalPath) || 'payload')
|
|
215
|
+
if (!isWithin(dir, payloadFile)) return { ok: false, error: '清单的原始路径与条目不一致' }
|
|
216
|
+
if (isWithin(dir, originalPath)) return { ok: false, error: '原始路径位于隔离区内部,拒绝恢复' }
|
|
217
|
+
if (!existsSync(payloadFile)) return { ok: false, error: '隔离区载荷缺失,可能已被手动删除' }
|
|
218
|
+
try {
|
|
219
|
+
const payloadStat = lstatSync(payloadFile)
|
|
220
|
+
if (payloadStat.isSymbolicLink()) return { ok: false, error: '隔离区载荷是符号链接,拒绝恢复' }
|
|
221
|
+
if (entry.kind === 'file') {
|
|
222
|
+
if (Number.isInteger(entry.bytes) && payloadStat.size !== entry.bytes) {
|
|
223
|
+
return { ok: false, error: '载荷大小与清单不一致,拒绝恢复(可能已被篡改)' }
|
|
224
|
+
}
|
|
225
|
+
if (typeof entry.sha256 === 'string' && entry.sha256 !== '' && sha256(readFileSync(payloadFile)) !== entry.sha256) {
|
|
226
|
+
return { ok: false, error: '载荷 sha256 与清单不一致,拒绝恢复(可能已被篡改)' }
|
|
227
|
+
}
|
|
228
|
+
} else if (entry.kind === 'directory' && Number.isInteger(entry.bytes)) {
|
|
229
|
+
const measured = measureTree(payloadFile)
|
|
230
|
+
if (measured.bytes !== entry.bytes) {
|
|
231
|
+
return { ok: false, error: '目录载荷大小与清单不一致,拒绝恢复(可能已被篡改)' }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return { ok: false, error: `无法校验隔离区载荷:${String(error)}` }
|
|
236
|
+
}
|
|
237
|
+
/** @type {string|null} */
|
|
238
|
+
let conflictPath = null
|
|
239
|
+
if (existsSync(originalPath) && !options.force) {
|
|
240
|
+
return { ok: false, error: `原路径已被占用:${originalPath}(使用 force 覆盖)` }
|
|
241
|
+
}
|
|
242
|
+
if (existsSync(originalPath) && options.force) {
|
|
243
|
+
// Never destroy what is already there silently: move it aside first and
|
|
244
|
+
// report where it went, so it can be recovered.
|
|
245
|
+
conflictPath = `${originalPath}.vigil-conflict-${Date.now()}`
|
|
246
|
+
try {
|
|
247
|
+
renameSync(originalPath, conflictPath)
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return { ok: false, error: `无法让位原路径:${String(error)}` }
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
ensureDir(dirname(originalPath))
|
|
253
|
+
try {
|
|
254
|
+
movePath(payloadFile, originalPath, entry.kind)
|
|
255
|
+
} catch (error) {
|
|
256
|
+
return { ok: false, error: `恢复失败:${error instanceof Error ? error.message : String(error)}`, conflictPath: conflictPath ?? undefined }
|
|
257
|
+
}
|
|
258
|
+
removeEntryDir(join(dir, entry.id))
|
|
259
|
+
return { ok: true, restoredTo: originalPath, ...(conflictPath ? { conflictPath } : {}) }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Permanently delete one entry. `confirm` is required: the product never
|
|
264
|
+
* silently destroys the last copy (FR-4.3).
|
|
265
|
+
* @param {string} id
|
|
266
|
+
* @param {{ confirm?: boolean }} [options]
|
|
267
|
+
* @returns {{ ok: boolean, error?: string }}
|
|
268
|
+
*/
|
|
269
|
+
function purge(id, options = {}) {
|
|
270
|
+
if (!enabled || !ready) return { ok: false, error: '隔离区未启用' }
|
|
271
|
+
if (options.confirm !== true) return { ok: false, error: '永久删除需要二次确认:请传 confirm=true' }
|
|
272
|
+
if (!ENTRY_ID_RE.test(String(id ?? ''))) return { ok: false, error: `隔离区条目 id 不合法:${String(id)}` }
|
|
273
|
+
const entry = entries().find(item => item.id === id)
|
|
274
|
+
if (!entry) return { ok: false, error: `未找到隔离区条目 ${id}` }
|
|
275
|
+
const entryDir = join(dir, entry.id)
|
|
276
|
+
if (!isWithin(dir, entryDir)) return { ok: false, error: '隔离区条目路径异常' }
|
|
277
|
+
try {
|
|
278
|
+
rmSync(entryDir, { recursive: true, force: true })
|
|
279
|
+
return { ok: true }
|
|
280
|
+
} catch (error) {
|
|
281
|
+
return { ok: false, error: `永久删除失败:${String(error)}` }
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Remove entries past their TTL.
|
|
287
|
+
* @param {{ now?: number }} [options]
|
|
288
|
+
* @returns {{ expired: string[] }}
|
|
289
|
+
*/
|
|
290
|
+
function expire(options = {}) {
|
|
291
|
+
const now = options.now ?? Date.now()
|
|
292
|
+
const ttlMs = ttlDays * 24 * 60 * 60 * 1000
|
|
293
|
+
/** @type {string[]} */
|
|
294
|
+
const expired = []
|
|
295
|
+
for (const entry of entries()) {
|
|
296
|
+
const created = Date.parse(entry.createdAt)
|
|
297
|
+
if (!Number.isFinite(created)) continue
|
|
298
|
+
if (now - created < ttlMs) continue
|
|
299
|
+
try {
|
|
300
|
+
rmSync(join(dir, entry.id), { recursive: true, force: true })
|
|
301
|
+
expired.push(entry.id)
|
|
302
|
+
} catch {
|
|
303
|
+
// leave a locked entry for the next pass
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return { expired }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** @returns {{ enabled: boolean, dir: string, count: number, bytes: number, ttlDays: number, maxEntries: number }} */
|
|
310
|
+
function stats() {
|
|
311
|
+
const list = entries()
|
|
312
|
+
let bytes = 0
|
|
313
|
+
for (const entry of list) bytes += Number(entry.bytes) || 0
|
|
314
|
+
return { enabled, dir, count: list.length, bytes, ttlDays, maxEntries }
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Human readable summary used by `vigil_status`.
|
|
319
|
+
* @returns {string}
|
|
320
|
+
*/
|
|
321
|
+
function describe() {
|
|
322
|
+
const summary = stats()
|
|
323
|
+
if (!summary.enabled) return '隔离区:已禁用'
|
|
324
|
+
return `隔离区:${summary.count} 条,${formatBytes(summary.bytes)},保留 ${summary.ttlDays} 天,目录 ${summary.dir}`
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return { enabled, dir, capture, entries, restore, purge, expire, stats, describe }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** @typedef {ReturnType<typeof createQuarantine>} QuarantineStore */
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Move a file or directory into or out of the quarantine.
|
|
334
|
+
*
|
|
335
|
+
* A same-volume move is one `rename`. Cross-volume moves cannot be atomic: a
|
|
336
|
+
* file is copied and unlinked, and a *bounded* directory tree is copied and
|
|
337
|
+
* removed. The bound exists so a multi-gigabyte cross-volume tree is refused
|
|
338
|
+
* (and reported) rather than frozen or duplicated; the original command is
|
|
339
|
+
* already denied at that point, so refusing the copy does not lose data.
|
|
340
|
+
*
|
|
341
|
+
* @param {string} source
|
|
342
|
+
* @param {string} destination
|
|
343
|
+
* @param {EntryKind} kind
|
|
344
|
+
*/
|
|
345
|
+
function movePath(source, destination, kind) {
|
|
346
|
+
try {
|
|
347
|
+
renameSync(source, destination)
|
|
348
|
+
return
|
|
349
|
+
} catch (error) {
|
|
350
|
+
const code = /** @type {NodeJS.ErrnoException} */ (error).code
|
|
351
|
+
if (code !== 'EXDEV') throw error
|
|
352
|
+
}
|
|
353
|
+
if (kind === 'file') {
|
|
354
|
+
copyFileSync(source, destination)
|
|
355
|
+
unlinkSync(source)
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
const tree = measureTree(source)
|
|
359
|
+
if (tree.truncated) {
|
|
360
|
+
throw new Error(
|
|
361
|
+
`跨卷目录超过隔离区复制上限(${CROSS_VOLUME_MAX_FILES} 个文件 / ${formatBytes(CROSS_VOLUME_MAX_BYTES)}),未复制:${source}`,
|
|
362
|
+
)
|
|
363
|
+
}
|
|
364
|
+
cpSync(source, destination, { recursive: true, force: true })
|
|
365
|
+
rmSync(source, { recursive: true, force: true })
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Bounded tree measurement for the cross-volume fallback and entry metadata.
|
|
370
|
+
* @param {string} root
|
|
371
|
+
* @returns {{ files: number, bytes: number, truncated: boolean }}
|
|
372
|
+
*/
|
|
373
|
+
function measureTree(root) {
|
|
374
|
+
const result = { files: 0, bytes: 0, truncated: false }
|
|
375
|
+
/** @type {string[]} */
|
|
376
|
+
const stack = [root]
|
|
377
|
+
while (stack.length > 0) {
|
|
378
|
+
const current = /** @type {string} */ (stack.pop())
|
|
379
|
+
let entries
|
|
380
|
+
try {
|
|
381
|
+
entries = readdirSync(current, { withFileTypes: true })
|
|
382
|
+
} catch {
|
|
383
|
+
continue
|
|
384
|
+
}
|
|
385
|
+
for (const entry of entries) {
|
|
386
|
+
const full = join(current, entry.name)
|
|
387
|
+
if (entry.isSymbolicLink()) continue
|
|
388
|
+
if (entry.isDirectory()) {
|
|
389
|
+
stack.push(full)
|
|
390
|
+
continue
|
|
391
|
+
}
|
|
392
|
+
if (!entry.isFile()) continue
|
|
393
|
+
result.files += 1
|
|
394
|
+
try {
|
|
395
|
+
result.bytes += statSync(full).size
|
|
396
|
+
} catch {
|
|
397
|
+
// keep the file count but not a guessed size
|
|
398
|
+
}
|
|
399
|
+
if (result.files > CROSS_VOLUME_MAX_FILES || result.bytes > CROSS_VOLUME_MAX_BYTES) {
|
|
400
|
+
result.truncated = true
|
|
401
|
+
return result
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return result
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* @param {string} entryDir
|
|
410
|
+
*/
|
|
411
|
+
function removeEntryDir(entryDir) {
|
|
412
|
+
try {
|
|
413
|
+
rmSync(entryDir, { recursive: true, force: true })
|
|
414
|
+
} catch {
|
|
415
|
+
// best effort
|
|
416
|
+
}
|
|
417
|
+
}
|