@sshirkit/dsh-orchestrator 1.0.1 → 1.0.3

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.
@@ -1,333 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto'
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import { isPathWithinScope, validateWriteScopeInput } from './write-lease.js'
5
- import { normalizeScope, SCOPE_KIND } from './write-scope.js'
6
-
7
- const IGNORED_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', '__pycache__'])
8
- const MAX_ENTRIES = 30_000
9
- const MAX_FILE_BYTES = 64 * 1024 * 1024
10
- const MAX_SCAN_BYTES = 256 * 1024 * 1024
11
- const CHUNK_BYTES = 64 * 1024
12
- const MAX_REPORT_ROWS = 8
13
- const WINDOWS = process.platform === 'win32'
14
- const ISOLATION_NOTE = '当前宿主不提供逐子代理物理只读文件系统沙箱;这里只做工作区逻辑写后审计并告警。' +
15
- '不会阻止写入,不覆盖工作区外或忽略目录,也不能区分并发写入者或检测两次采样间已还原的改动。'
16
-
17
- const posixPath = (value) => value.split(path.sep).join('/')
18
- const pathKey = (value) => WINDOWS ? value.toLowerCase() : value
19
- const byPath = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
20
-
21
- function insideWorkspace(cwd, filename) {
22
- const relative = path.relative(cwd, filename)
23
- if (relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
24
- return null
25
- }
26
- return posixPath(relative)
27
- }
28
-
29
- function expectedPath(cwd, value) {
30
- if (typeof value !== 'string' || value.trim() === '' || value.includes('\0')) {
31
- throw new TypeError('预期目标必须是非空文件路径。')
32
- }
33
- const relative = insideWorkspace(cwd, path.resolve(cwd, value))
34
- if (relative === null) throw new TypeError(`预期目标必须位于工作区内:${JSON.stringify(value)}。`)
35
- return relative
36
- }
37
-
38
- function fingerprintEntries(cwd, expectedFingerprints) {
39
- if (expectedFingerprints == null) return []
40
- if (typeof expectedFingerprints !== 'object' || Array.isArray(expectedFingerprints)) {
41
- throw new TypeError('expectedFingerprints 必须是从文件路径到 SHA-256 的对象。')
42
- }
43
- const entries = new Map()
44
- for (const [filename, sha256] of Object.entries(expectedFingerprints)) {
45
- if (typeof sha256 !== 'string' || sha256 === '') {
46
- throw new TypeError(`预期指纹必须是非空字符串:${JSON.stringify(filename)}。`)
47
- }
48
- const relative = expectedPath(cwd, filename)
49
- const key = pathKey(relative)
50
- const expected = sha256.toLowerCase()
51
- if (entries.has(key) && entries.get(key).expected !== expected) {
52
- throw new TypeError(`同一文件声明了不同的预期指纹:${JSON.stringify(filename)}。`)
53
- }
54
- entries.set(key, Object.freeze({ path: relative, expected }))
55
- }
56
- return [...entries.values()].sort(byPath)
57
- }
58
-
59
- function targetPaths(cwd, expectedTargets) {
60
- if (expectedTargets == null) return []
61
- if (!Array.isArray(expectedTargets)) throw new TypeError('expectedTargets 必须是文件路径数组。')
62
- return expectedTargets.map((filename) => expectedPath(cwd, filename))
63
- }
64
-
65
- function scopeOf(writeScope, readOnly, cwd) {
66
- const validated = validateWriteScopeInput({ writeScope, readOnly })
67
- const normalized = validated.ok && !validated.readOnly
68
- ? normalizeScope(validated.entries, cwd)
69
- : validated
70
- if (!normalized.ok) {
71
- throw Object.assign(new TypeError(normalized.message), { code: normalized.code })
72
- }
73
- return normalized.entries
74
- }
75
-
76
- function sameObservation(left, right) {
77
- return left.dev === right.dev && left.ino === right.ino && left.size === right.size &&
78
- left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs
79
- }
80
-
81
- function fingerprint(filename, relative, stats, budget, chunk) {
82
- const hash = createHash('sha256')
83
- let bytes = 0
84
- let lines = 0
85
- let lastByte
86
- const consume = (data) => {
87
- bytes += data.length
88
- budget.bytes -= data.length
89
- hash.update(data)
90
- for (let offset = data.indexOf(10); offset !== -1; offset = data.indexOf(10, offset + 1)) {
91
- lines += 1
92
- }
93
- if (data.length > 0) lastByte = data[data.length - 1]
94
- }
95
-
96
- if (stats.isSymbolicLink()) {
97
- // Fingerprint the link itself, never its target (which may lie outside the workspace).
98
- const target = fs.readlinkSync(filename, { encoding: 'buffer' })
99
- if (target.length > budget.bytes) return { limited: true }
100
- consume(target)
101
- if (!sameObservation(stats, fs.lstatSync(filename))) return { unstable: true }
102
- } else {
103
- if (stats.size > MAX_FILE_BYTES || stats.size > budget.bytes) return { limited: true }
104
- const { O_RDONLY, O_NOFOLLOW = 0, O_NONBLOCK = 0 } = fs.constants
105
- const fd = fs.openSync(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
106
- try {
107
- const opened = fs.fstatSync(fd)
108
- if (!opened.isFile() || !sameObservation(stats, opened)) return { unstable: true }
109
- while (bytes < stats.size) {
110
- const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, stats.size - bytes), null)
111
- if (count === 0) break
112
- consume(chunk.subarray(0, count))
113
- }
114
- if (bytes !== stats.size || !sameObservation(stats, fs.lstatSync(filename))) {
115
- return { unstable: true }
116
- }
117
- } finally {
118
- fs.closeSync(fd)
119
- }
120
- }
121
- return {
122
- file: Object.freeze({
123
- path: relative,
124
- sha256: hash.digest('hex'),
125
- bytes,
126
- lines: lines + (lastByte === 10 ? 0 : 1),
127
- mtimeMs: stats.mtimeMs,
128
- size: stats.size,
129
- }),
130
- }
131
- }
132
-
133
- function snapshot(cwd) {
134
- const files = []
135
- const issues = []
136
- const budget = { entries: MAX_ENTRIES, bytes: MAX_SCAN_BYTES }
137
- const chunk = Buffer.allocUnsafe(CHUNK_BYTES)
138
- const pending = ['.']
139
- let truncated = false
140
- const recordIssue = (filename, reason, limited = false) => {
141
- issues.push(Object.freeze({ path: filename, reason }))
142
- if (limited) truncated = true
143
- }
144
- while (pending.length > 0) {
145
- const relativeDir = pending.pop()
146
- let dir
147
- try {
148
- const directory = path.join(cwd, relativeDir)
149
- if (relativeDir !== '.' && !fs.lstatSync(directory).isDirectory()) {
150
- recordIssue(relativeDir, '采样时目录发生变化')
151
- continue
152
- }
153
- dir = fs.opendirSync(directory)
154
- let entry
155
- while ((entry = dir.readSync()) !== null) {
156
- if (budget.entries === 0 || budget.bytes === 0) {
157
- recordIssue('.', '已达到扫描条目或总字节上限', true)
158
- return { files: files.sort(byPath), issues: issues.sort(byPath), truncated }
159
- }
160
- budget.entries -= 1
161
- if (pathKey(entry.name) === '.git' || (IGNORED_DIRS.has(pathKey(entry.name)) &&
162
- (entry.isDirectory() || entry.isSymbolicLink()))) continue
163
- const relative = relativeDir === '.' ? entry.name : `${relativeDir}/${entry.name}`
164
- const filename = path.join(cwd, relative)
165
- try {
166
- const stats = fs.lstatSync(filename)
167
- if (stats.isDirectory()) {
168
- pending.push(relative)
169
- } else if (stats.isFile() || stats.isSymbolicLink()) {
170
- const result = fingerprint(filename, relative, stats, budget, chunk)
171
- if (result.file) files.push(result.file)
172
- else if (result.limited) recordIssue(relative, '超过单文件或剩余扫描字节上限', true)
173
- else recordIssue(relative, '采样时文件发生变化')
174
- }
175
- } catch (error) {
176
- recordIssue(relative, `无法采样:${error.code ?? error.name}`)
177
- }
178
- }
179
- } catch (error) {
180
- recordIssue(relativeDir, `无法读取目录:${error.code ?? error.name}`)
181
- } finally {
182
- dir?.closeSync()
183
- }
184
- }
185
- return { files: files.sort(byPath), issues: issues.sort(byPath), truncated }
186
- }
187
-
188
- const fileMap = (files) => new Map(files.map((file) => [pathKey(file.path), file]))
189
-
190
- function coverageOf(issues) {
191
- const unknown = new Set(issues.map((issue) => pathKey(issue.path)))
192
- return (filename) => {
193
- if (unknown.has('.')) return false
194
- const pieces = pathKey(filename).split('/')
195
- let prefix = ''
196
- for (const [index, piece] of pieces.entries()) {
197
- if (piece === '.git' || (index < pieces.length - 1 && IGNORED_DIRS.has(piece))) return false
198
- prefix = prefix === '' ? piece : `${prefix}/${piece}`
199
- if (unknown.has(prefix)) return false
200
- }
201
- return true
202
- }
203
- }
204
-
205
- /** Freeze the full in-workspace observation before activation, including out-of-scope files. */
206
- export function captureBaseline({
207
- cwd,
208
- writeScope = [],
209
- readOnly = false,
210
- expectedFingerprints = null,
211
- expectedTargets = null,
212
- }) {
213
- if (typeof cwd !== 'string' || cwd.trim() === '') throw new TypeError('审计需要有效的 cwd。')
214
- const root = path.resolve(cwd)
215
- const entries = scopeOf(writeScope, readOnly, root)
216
- const expected = fingerprintEntries(root, expectedFingerprints)
217
- const targets = targetPaths(root, expectedTargets)
218
- const observed = snapshot(root)
219
- const original = fileMap(observed.files)
220
- for (const entry of entries) {
221
- if (entry.kind !== SCOPE_KIND.file) continue
222
- const relative = insideWorkspace(root, entry.path)
223
- const file = relative === null ? undefined : original.get(pathKey(relative))
224
- // A path named only in writeScope may be a planned creation, not a required deliverable.
225
- if (file !== undefined) targets.push(file.path)
226
- }
227
- return Object.freeze({
228
- baselineId: randomUUID(),
229
- cwd: root,
230
- writeScope: Object.freeze(typeof writeScope === 'string' ? [writeScope] : [...writeScope]),
231
- readOnly: readOnly === true,
232
- expectedFingerprints: Object.freeze(Object.fromEntries(expected.map((row) => [row.path, row.expected]))),
233
- expectedTargets: Object.freeze([...new Set(targets)].sort()),
234
- files: Object.freeze(observed.files),
235
- truncated: observed.truncated,
236
- scanIssues: Object.freeze(observed.issues),
237
- })
238
- }
239
-
240
- function compareFingerprints(expected, observed, covered, phase, violations) {
241
- for (const row of expected) {
242
- const actual = observed.get(pathKey(row.path))?.sha256
243
- if (actual === undefined && !covered(row.path)) {
244
- violations.push({ code: 'audit-incomplete', path: row.path, phase, reason: '无法核对预期指纹' })
245
- } else if (actual !== row.expected) {
246
- violations.push({ code: 'fingerprint-mismatch', path: row.path, expected: row.expected, actual: actual ?? null, phase })
247
- }
248
- }
249
- }
250
-
251
- /** Recompute current bytes. Capture expectations refer to the old bytes; settlement expectations to the final bytes. */
252
- export function auditBaseline(baseline, {
253
- cwd,
254
- writeScope,
255
- readOnly,
256
- expectedFingerprints,
257
- expectedTargets,
258
- } = {}) {
259
- const root = baseline.cwd
260
- if (cwd !== undefined && path.relative(root, path.resolve(cwd)) !== '') {
261
- throw new TypeError('审计结算必须使用冻结基线时的 cwd。')
262
- }
263
- const effectiveReadOnly = baseline.readOnly || readOnly === true
264
- const entries = scopeOf(baseline.writeScope, baseline.readOnly, root)
265
- const narrowed = writeScope === undefined ? entries : scopeOf(writeScope, effectiveReadOnly, root)
266
- const expected = fingerprintEntries(root, expectedFingerprints)
267
- const targets = new Map([...targetPaths(root, expectedTargets), ...baseline.expectedTargets]
268
- .map((filename) => [pathKey(filename), filename]))
269
- const current = snapshot(root)
270
- const before = fileMap(baseline.files)
271
- const after = fileMap(current.files)
272
- const coveredBefore = coverageOf(baseline.scanIssues)
273
- const coveredAfter = coverageOf(current.issues)
274
- const changedFiles = []
275
- const violations = [...baseline.scanIssues.map((issue) => ({ code: 'audit-incomplete', ...issue, phase: 'baseline' })),
276
- ...current.issues.map((issue) => ({ code: 'audit-incomplete', ...issue, phase: 'settlement' }))]
277
-
278
- for (const key of new Set([...before.keys(), ...after.keys()])) {
279
- const old = before.get(key)
280
- const now = after.get(key)
281
- if ((!old && !coveredBefore(now.path)) || (!now && !coveredAfter(old.path))) continue
282
- if (old && now && old.sha256 === now.sha256 && old.mtimeMs === now.mtimeMs && old.path === now.path) continue
283
- const filename = (now ?? old).path
284
- const changeType = !old ? 'added' : !now ? 'deleted' : 'modified'
285
- changedFiles.push({ path: filename, sha256: now?.sha256 ?? null, bytes: now?.bytes ?? 0, lines: now?.lines ?? 0, changeType })
286
- const absolute = path.join(root, filename)
287
- if (effectiveReadOnly || !isPathWithinScope(absolute, entries, { cwd: root }) ||
288
- (narrowed !== entries && !isPathWithinScope(absolute, narrowed, { cwd: root }))) {
289
- violations.push({ code: 'out-of-scope-write', path: filename, changeType })
290
- }
291
- }
292
-
293
- compareFingerprints(fingerprintEntries(root, baseline.expectedFingerprints), before, coveredBefore, 'baseline', violations)
294
- compareFingerprints(expected, after, coveredAfter, 'settlement', violations)
295
- for (const [key, filename] of targets) {
296
- if (after.has(key)) continue
297
- if (coveredAfter(filename)) violations.push({ code: 'target-missing', path: filename })
298
- else violations.push({ code: 'audit-incomplete', path: filename, phase: 'settlement', reason: '无法核对目标是否存在' })
299
- }
300
-
301
- const summary = {
302
- added: 0,
303
- modified: 0,
304
- deleted: 0,
305
- violations: violations.length,
306
- truncated: baseline.truncated || current.truncated,
307
- }
308
- for (const file of changedFiles) summary[file.changeType] += 1
309
- return {
310
- baselineId: baseline.baselineId,
311
- passed: violations.length === 0,
312
- readOnly: effectiveReadOnly,
313
- isolationLevel: 'logical-post-audit',
314
- isolationNote: ISOLATION_NOTE,
315
- changedFiles: changedFiles.sort(byPath),
316
- violations: violations.sort(byPath),
317
- summary,
318
- }
319
- }
320
-
321
- /** Produce a bounded Chinese notice; structured evidence remains in the result. */
322
- export function formatAuditReport(auditResult) {
323
- if (auditResult.passed) return ''
324
- const { baselineId, violations, summary } = auditResult
325
- const details = violations.slice(0, MAX_REPORT_ROWS).map(({ code, path: filename }) =>
326
- `- ${code}:${JSON.stringify(filename)}`)
327
- if (violations.length > details.length) details.push(`另有 ${violations.length - details.length} 项未列出。`)
328
- return [
329
- `写作用域审计未通过(基线 ${baselineId},${violations.length} 项${summary.truncated ? ',采样已截断' : ''}):`,
330
- ...details,
331
- auditResult.isolationNote,
332
- ].join('\n')
333
- }