@sshirkit/dsh-orchestrator 0.9.2 → 1.0.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.
@@ -0,0 +1,383 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { isPathWithinScope, validateWriteScopeInput } from './write-lease.js'
6
+ import { normalizeScope, SCOPE_KIND } from './write-scope.js'
7
+ import { WORKTREE_POOL_DIRNAME } from './worktree.js'
8
+
9
+ const WINDOWS = process.platform === 'win32'
10
+ const MAX_FILE_BYTES = 64 * 1024 * 1024
11
+ const CHUNK_BYTES = 64 * 1024
12
+ const MAX_REPORT_ROWS = 8
13
+ const ISOLATION_NOTE = '子代理在独立 Git 工作树中执行;审计覆盖 Git 可见净变更,不是操作系统写权限沙箱。' +
14
+ '不会识别普通忽略文件、已还原的未提交改动,也不会将主仓污点归因给该子代理。'
15
+ const posix = (value) => value.split(path.sep).join('/')
16
+ const pathKey = (value) => WINDOWS ? value.toLowerCase() : value
17
+ const byPath = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
18
+ const missing = (error) => error.code === 'ENOENT' || error.code === 'ENOTDIR'
19
+ const gitError = (error) => String(error.stderr || error.message).trim()
20
+
21
+ function git(cwd, ...args) {
22
+ const bytes = execFileSync('git', ['--no-optional-locks', '--literal-pathspecs', ...args], {
23
+ cwd,
24
+ windowsHide: true,
25
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
26
+ maxBuffer: 16 * 1024 * 1024,
27
+ timeout: 30000,
28
+ stdio: ['ignore', 'pipe', 'pipe'],
29
+ })
30
+ // A lossy decode could conflate two filenames; fail closed instead.
31
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
32
+ }
33
+
34
+ function relativeInside(root, filename) {
35
+ const relative = path.relative(root, filename)
36
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return null
37
+ return posix(relative)
38
+ }
39
+
40
+ function expectedPath(cwd, value) {
41
+ if (typeof value !== 'string' || !value.trim() || value.includes('\0')) {
42
+ throw new TypeError('预期目标必须是非空文件路径。')
43
+ }
44
+ const relative = relativeInside(cwd, path.resolve(cwd, value))
45
+ if (!relative) throw new TypeError(`预期目标必须位于工作区内:${JSON.stringify(value)}。`)
46
+ return relative
47
+ }
48
+
49
+ function fingerprintEntries(cwd, expectedFingerprints) {
50
+ if (expectedFingerprints == null) return []
51
+ if (typeof expectedFingerprints !== 'object' || Array.isArray(expectedFingerprints)) {
52
+ throw new TypeError('expectedFingerprints 必须是从文件路径到 SHA-256 的对象。')
53
+ }
54
+ const entries = new Map()
55
+ for (const [filename, sha256] of Object.entries(expectedFingerprints)) {
56
+ if (typeof sha256 !== 'string' || sha256 === '') {
57
+ throw new TypeError(`预期指纹必须是非空字符串:${JSON.stringify(filename)}。`)
58
+ }
59
+ const relative = expectedPath(cwd, filename)
60
+ const key = pathKey(relative)
61
+ const expected = sha256.toLowerCase()
62
+ if (entries.has(key) && entries.get(key).expected !== expected) {
63
+ throw new TypeError(`同一文件声明了不同的预期指纹:${JSON.stringify(filename)}。`)
64
+ }
65
+ entries.set(key, { path: relative, expected })
66
+ }
67
+ return [...entries.values()].sort(byPath)
68
+ }
69
+
70
+ function targetPaths(cwd, expectedTargets) {
71
+ if (expectedTargets == null) return []
72
+ if (!Array.isArray(expectedTargets)) throw new TypeError('expectedTargets 必须是文件路径数组。')
73
+ return expectedTargets.map((filename) => expectedPath(cwd, filename))
74
+ }
75
+
76
+ function scopeOf(cwd, writeScope, readOnly) {
77
+ const validated = validateWriteScopeInput({ writeScope, readOnly })
78
+ const normalized = validated.ok && !validated.readOnly ? normalizeScope(validated.entries, cwd) : validated
79
+ if (!normalized.ok) throw Object.assign(new TypeError(normalized.message), { code: normalized.code })
80
+ return normalized.entries
81
+ }
82
+
83
+ function observationMatches(left, right) {
84
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size &&
85
+ left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs
86
+ }
87
+
88
+ function fileObservation(root, realRoot, relative, fingerprint = true) {
89
+ try {
90
+ const filename = path.resolve(root, relative)
91
+ if (!relativeInside(root, filename) || relative.split('/').some((part) => pathKey(part) === '.git')) {
92
+ return { exists: null, reason: '目标超出文件审计边界' }
93
+ }
94
+ // Never follow a symlink/junction in the parent chain out of the checkout.
95
+ const realParent = fs.realpathSync.native(path.dirname(filename))
96
+ if (relativeInside(realRoot, realParent) === null) return { exists: null, reason: '目标父目录指向工作树外部' }
97
+ const stats = fs.lstatSync(filename)
98
+ if (!stats.isFile() && !stats.isSymbolicLink()) {
99
+ return fingerprint ? { exists: false, reason: '目标不是普通文件或符号链接' } : { exists: false }
100
+ }
101
+ if (!fingerprint) return { exists: true }
102
+ if (stats.isFile() && stats.size > MAX_FILE_BYTES) return { exists: true, reason: '超过单文件采样上限' }
103
+
104
+ const hash = createHash('sha256')
105
+ let bytes = 0
106
+ let lines = 0
107
+ let lastByte
108
+ const consume = (data) => {
109
+ hash.update(data)
110
+ bytes += data.length
111
+ for (let offset = data.indexOf(10); offset !== -1; offset = data.indexOf(10, offset + 1)) lines += 1
112
+ if (data.length > 0) lastByte = data[data.length - 1]
113
+ }
114
+ if (stats.isSymbolicLink()) {
115
+ consume(fs.readlinkSync(filename, { encoding: 'buffer' }))
116
+ } else {
117
+ const { O_RDONLY, O_NOFOLLOW = 0, O_NONBLOCK = 0 } = fs.constants
118
+ const fd = fs.openSync(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
119
+ try {
120
+ const opened = fs.fstatSync(fd)
121
+ if (!opened.isFile() || !observationMatches(stats, opened)) return { exists: true, reason: '采样时文件发生变化' }
122
+ const chunk = Buffer.allocUnsafe(Math.min(CHUNK_BYTES, stats.size))
123
+ while (bytes < stats.size) {
124
+ const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, stats.size - bytes), null)
125
+ if (count === 0) break
126
+ consume(chunk.subarray(0, count))
127
+ }
128
+ if (bytes !== stats.size) return { exists: true, reason: '采样时文件发生变化' }
129
+ } finally {
130
+ fs.closeSync(fd)
131
+ }
132
+ }
133
+ if (!observationMatches(stats, fs.lstatSync(filename))) return { exists: true, reason: '采样时文件发生变化' }
134
+ return { exists: true, sha256: hash.digest('hex'), bytes, lines: lines + (lastByte === 10 ? 0 : 1) }
135
+ } catch (error) {
136
+ return missing(error) ? { exists: false } : { exists: null, reason: `无法采样:${error.code ?? error.name}` }
137
+ }
138
+ }
139
+
140
+ function readStatus(root) {
141
+ const dirty = []
142
+ const untracked = []
143
+ const args = ['status', '--porcelain=v1', '-z', '--no-renames', '--ignore-submodules=none', '--untracked-files=all']
144
+ for (const row of git(root, ...args).split('\0').filter(Boolean)) {
145
+ const filename = row.slice(3)
146
+ dirty.push(filename)
147
+ if (row.startsWith('??')) untracked.push(filename)
148
+ }
149
+ return { dirty, untracked }
150
+ }
151
+
152
+ function diffRows(root, ...revisions) {
153
+ const tokens = git(root, 'diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules=none',
154
+ '--no-renames', '--name-status', '-z', ...revisions, '--').split('\0')
155
+ const files = new Map()
156
+ for (let index = 0; index < tokens.length - 1; index += 2) {
157
+ const type = tokens[index]
158
+ const filename = tokens[index + 1]
159
+ if (!filename) throw new Error('Git name-status 没有返回有效路径。')
160
+ files.set(filename, type === 'A' ? 'added' : type === 'D' ? 'deleted' : 'modified')
161
+ }
162
+ return files
163
+ }
164
+
165
+ function checkoutRoot(cwd) {
166
+ return fs.realpathSync.native(git(cwd, 'rev-parse', '--show-toplevel').replace(/\r?\n$/, ''))
167
+ }
168
+
169
+ function assertCheckout(worktreePath) {
170
+ if (!fs.lstatSync(worktreePath).isDirectory() ||
171
+ path.relative(checkoutRoot(worktreePath), fs.realpathSync.native(worktreePath)) !== '') {
172
+ throw new TypeError('目录不是冻结的 Git 工作树根目录。')
173
+ }
174
+ }
175
+
176
+ export function captureGitBaseline({ worktree, cwd = null, repoRoot = null, writeScope = [], readOnly = false,
177
+ expectedFingerprints = null, expectedTargets = null }) {
178
+ if (!worktree || typeof worktree.worktreePath !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i.test(worktree.baseCommit)) {
179
+ throw new TypeError('Git 审计需要工作树路径和有效的冻结基线提交。')
180
+ }
181
+ const worktreePath = path.resolve(worktree.worktreePath)
182
+ const execCwd = path.resolve(cwd ?? worktree.execCwd ?? worktreePath)
183
+ const sourceRoot = path.resolve(repoRoot ?? worktree.repoRoot)
184
+ assertCheckout(worktreePath)
185
+ const realRoot = fs.realpathSync.native(worktreePath)
186
+ if (relativeInside(worktreePath, execCwd) === null || relativeInside(realRoot, fs.realpathSync.native(execCwd)) === null) {
187
+ throw new TypeError('Git 审计的执行目录必须位于冻结的工作树内。')
188
+ }
189
+ const entries = scopeOf(execCwd, writeScope, readOnly)
190
+ const fingerprints = fingerprintEntries(execCwd, expectedFingerprints)
191
+ const fingerprintKeys = new Set(fingerprints.map((row) => pathKey(row.path)))
192
+ const explicitTargets = targetPaths(execCwd, expectedTargets)
193
+ const targets = new Map(explicitTargets.map((filename) => [pathKey(filename), filename]))
194
+ const selected = new Map([...explicitTargets, ...fingerprints.map((row) => row.path)]
195
+ .map((filename) => [pathKey(filename), filename]))
196
+ const declaredFiles = new Map()
197
+ for (const entry of entries) {
198
+ if (entry.kind !== SCOPE_KIND.file) continue
199
+ const filename = relativeInside(execCwd, entry.path)
200
+ if (!filename) continue
201
+ const key = pathKey(filename)
202
+ declaredFiles.set(key, filename)
203
+ if (!selected.has(key)) selected.set(key, filename)
204
+ }
205
+ const targetSnapshots = []
206
+ const baselineIssues = []
207
+ for (const [key, filename] of selected) {
208
+ const entry = fileObservation(worktreePath, realRoot, posix(path.relative(worktreePath, path.resolve(execCwd, filename))))
209
+ targetSnapshots.push(Object.freeze({ path: filename, ...entry }))
210
+ if (declaredFiles.has(key) && entry.exists) targets.set(key, filename)
211
+ if (entry.exists === null && declaredFiles.has(key) && !fingerprintKeys.has(key)) {
212
+ baselineIssues.push(Object.freeze({ code: 'audit-incomplete', path: filename, phase: 'baseline', reason: entry.reason }))
213
+ }
214
+ }
215
+ return Object.freeze({
216
+ baselineId: randomUUID(), kind: 'git-worktree', worktreeId: worktree.id, worktreePath, execCwd, cwd: execCwd,
217
+ repoRoot: sourceRoot, branch: worktree.branch, baseCommit: worktree.baseCommit,
218
+ writeScope: Object.freeze(typeof writeScope === 'string' ? [writeScope] : [...writeScope]), readOnly: readOnly === true,
219
+ expectedFingerprints: Object.freeze(Object.fromEntries(fingerprints.map((row) => [row.path, row.expected]))),
220
+ expectedTargets: Object.freeze([...targets.values()].sort()), capturedAt: Date.now(),
221
+ targetSnapshots: Object.freeze(targetSnapshots.sort(byPath)), baselineIssues: Object.freeze(baselineIssues),
222
+ mainBeforeDirty: Object.freeze(readStatus(sourceRoot).dirty),
223
+ })
224
+ }
225
+
226
+ function listCommits(root, baseCommit) {
227
+ return git(root, 'log', '--format=%H%x1f%h%x1f%s', `${baseCommit}..HEAD`, '--')
228
+ .split('\n').filter(Boolean).map((row) => {
229
+ const [hash, shortHash, ...subject] = row.split('\x1f')
230
+ return { hash, shortHash, subject: subject.join('\x1f') }
231
+ })
232
+ }
233
+
234
+ function compareFingerprint(row, observation, phase, violations) {
235
+ const actual = observation?.sha256
236
+ if (actual == null && (phase === 'baseline' || observation?.exists !== false)) {
237
+ violations.push({ code: 'audit-incomplete', path: row.path, phase, reason: observation?.reason ?? '无法核对预期指纹' })
238
+ } else if (actual !== row.expected) {
239
+ violations.push({ code: 'fingerprint-mismatch', path: row.path, phase, expected: row.expected, actual: actual ?? null })
240
+ }
241
+ }
242
+
243
+ // An index deletion can make a recreated file appear both deleted and untracked.
244
+ // Compare the recreated object (after Git's normal clean conversion) with the base tree.
245
+ function replacesBaseFile(root, baseCommit, filename, observation) {
246
+ const entry = git(root, 'ls-tree', '-z', baseCommit, '--', filename)
247
+ const match = /^(100(?:644|755)|120000) blob ([a-f0-9]+)\t/.exec(entry)
248
+ if (!match || !observation.exists) return true
249
+ const absolute = path.resolve(root, filename)
250
+ const stats = fs.lstatSync(absolute)
251
+ const symlink = stats.isSymbolicLink()
252
+ if ((match[1] === '120000') !== symlink) return true
253
+ if (!symlink && !WINDOWS && (match[1] === '100755') !== Boolean(stats.mode & 0o100)) return true
254
+ if (symlink) {
255
+ const data = fs.readlinkSync(absolute, { encoding: 'buffer' })
256
+ const algo = match[2].length === 64 ? 'sha256' : 'sha1'
257
+ return createHash(algo).update(`blob ${data.length}\0`).update(data).digest('hex') !== match[2]
258
+ }
259
+ return git(root, 'hash-object', `--path=${filename}`, '--', absolute).trim() !== match[2]
260
+ }
261
+
262
+ export function auditGitBaseline(baseline, overrides = {}) {
263
+ const { execCwd, worktreePath, repoRoot, baseCommit } = baseline
264
+ const { cwd, writeScope, readOnly, expectedFingerprints, expectedTargets } = overrides
265
+ if (cwd !== undefined && path.relative(execCwd, path.resolve(cwd)) !== '') {
266
+ throw new TypeError('审计结算必须使用冻结基线时的 cwd。')
267
+ }
268
+ const effectiveReadOnly = baseline.readOnly || readOnly === true
269
+ const entries = scopeOf(execCwd, baseline.writeScope, baseline.readOnly)
270
+ const narrowed = writeScope === undefined ? entries : scopeOf(execCwd, writeScope, effectiveReadOnly)
271
+ const expected = fingerprintEntries(execCwd, expectedFingerprints)
272
+ const targets = new Map([...targetPaths(execCwd, expectedTargets), ...baseline.expectedTargets]
273
+ .map((filename) => [pathKey(filename), filename]))
274
+ const before = new Map(baseline.targetSnapshots.map((row) => [pathKey(row.path), row]))
275
+ const violations = [...baseline.baselineIssues]
276
+ const changedFiles = []
277
+ let commits = []
278
+ let headCommit = null
279
+ let dirtyFiles = []
280
+ let mainWorkspaceTaint = []
281
+ let isolationNote = ISOLATION_NOTE
282
+ const incomplete = (filename, reason) => violations.push({ code: 'audit-incomplete', path: filename, phase: 'settlement', reason })
283
+
284
+ for (const row of fingerprintEntries(execCwd, baseline.expectedFingerprints)) {
285
+ compareFingerprint(row, before.get(pathKey(row.path)), 'baseline', violations)
286
+ }
287
+ try {
288
+ assertCheckout(worktreePath)
289
+ const realRoot = fs.realpathSync.native(worktreePath)
290
+ headCommit = git(worktreePath, 'rev-parse', 'HEAD').trim()
291
+ commits = listCommits(worktreePath, baseCommit)
292
+ const committed = diffRows(worktreePath, `${baseCommit}..HEAD`)
293
+ const staged = diffRows(worktreePath, '--cached')
294
+ const unstaged = diffRows(worktreePath)
295
+ const current = readStatus(worktreePath)
296
+ dirtyFiles = [...new Set([...staged.keys(), ...unstaged.keys(), ...current.dirty])]
297
+ const net = diffRows(worktreePath, baseCommit)
298
+ const untracked = new Set(current.untracked)
299
+ const post = new Map()
300
+ const observe = (repoRelative, fingerprint = true) => {
301
+ const key = `${fingerprint}:${repoRelative}`
302
+ if (!post.has(key)) post.set(key, fileObservation(worktreePath, realRoot, repoRelative, fingerprint))
303
+ return post.get(key)
304
+ }
305
+ // Restrict byte observations to the effective change set, not every historical path.
306
+ for (const filename of new Set([...committed.keys(), ...staged.keys(), ...unstaged.keys(), ...net.keys(), ...untracked])) {
307
+ let changeType = net.get(filename)
308
+ let observation
309
+ if (untracked.has(filename)) {
310
+ observation = observe(filename)
311
+ if (changeType === 'deleted') {
312
+ if (observation.sha256 && !replacesBaseFile(worktreePath, baseCommit, filename, observation)) continue
313
+ changeType = 'modified'
314
+ } else changeType ??= 'added'
315
+ }
316
+ if (!changeType) continue
317
+ const absolute = path.resolve(worktreePath, filename)
318
+ const relative = posix(path.relative(execCwd, absolute))
319
+ const inExecCwd = Boolean(relativeInside(execCwd, absolute))
320
+ if (changeType !== 'deleted') {
321
+ observation ??= observe(filename)
322
+ if (observation.exists === false && !observation.reason) {
323
+ if (changeType === 'added') continue
324
+ changeType = 'deleted'
325
+ } else if (!observation.sha256) incomplete(relative, observation.reason ?? '无法计算变更文件指纹')
326
+ }
327
+ changedFiles.push({ path: relative, changeType,
328
+ sha256: changeType === 'deleted' ? null : observation.sha256 ?? null,
329
+ bytes: changeType === 'deleted' ? 0 : observation.bytes ?? 0,
330
+ lines: changeType === 'deleted' ? 0 : observation.lines ?? 0,
331
+ })
332
+ if (effectiveReadOnly) violations.push({ code: 'readonly-write', path: relative, changeType })
333
+ else if (!inExecCwd || !isPathWithinScope(absolute, entries, { cwd: execCwd }) ||
334
+ (narrowed !== entries && !isPathWithinScope(absolute, narrowed, { cwd: execCwd }))) {
335
+ violations.push({ code: 'out-of-scope-write', path: relative, changeType })
336
+ }
337
+ }
338
+
339
+ const toRepoPath = (filename) => posix(path.relative(worktreePath, path.resolve(execCwd, filename)))
340
+ for (const row of expected) compareFingerprint(row, observe(toRepoPath(row.path)), 'settlement', violations)
341
+ for (const filename of targets.values()) {
342
+ const observation = observe(toRepoPath(filename), false)
343
+ if (observation.exists === false) violations.push({ code: 'target-missing', path: filename })
344
+ else if (observation.exists === null) incomplete(filename, observation.reason ?? '无法核对目标是否存在')
345
+ }
346
+ } catch (error) {
347
+ incomplete('.', `无法完成 Git 工作树采样:${gitError(error)}`)
348
+ }
349
+
350
+ try {
351
+ const previous = new Set(baseline.mainBeforeDirty.map(pathKey))
352
+ const pool = pathKey(WORKTREE_POOL_DIRNAME)
353
+ mainWorkspaceTaint = readStatus(repoRoot).dirty
354
+ .filter((filename) => !previous.has(pathKey(filename)) && pathKey(filename) !== pool &&
355
+ !pathKey(filename).startsWith(`${pool}/`)).sort()
356
+ } catch (error) {
357
+ isolationNote += `无法观测主仓污点:${gitError(error)}`
358
+ }
359
+
360
+ const summary = { added: 0, modified: 0, deleted: 0, violations: violations.length, truncated: false,
361
+ commits: commits.length, dirty: dirtyFiles.length > 0 }
362
+ for (const file of changedFiles) summary[file.changeType] += 1
363
+ return {
364
+ baselineId: baseline.baselineId, passed: violations.length === 0, readOnly: effectiveReadOnly,
365
+ isolationLevel: 'git-worktree', isolationNote,
366
+ changedFiles: changedFiles.sort(byPath), violations: violations.sort(byPath), summary,
367
+ git: { worktreeId: baseline.worktreeId, worktreePath, branch: baseline.branch, baseCommit, headCommit,
368
+ commits, dirtyFiles: dirtyFiles.sort(), mainWorkspaceTaint },
369
+ }
370
+ }
371
+
372
+ export function formatGitAuditReport(auditResult) {
373
+ const { baselineId, passed, violations, summary, git: evidence } = auditResult
374
+ const details = violations.slice(0, MAX_REPORT_ROWS).map(({ code, path: filename }) =>
375
+ `- ${code}:${JSON.stringify(filename)}`)
376
+ if (violations.length > details.length) details.push(`另有 ${violations.length - details.length} 项未列出。`)
377
+ return [
378
+ `写作用域审计${passed ? '通过' : '未通过'}(git-worktree;基线 ${baselineId};分支 ${evidence.branch};${summary.commits} 个提交)。`,
379
+ ...(summary.dirty ? [`工作树有 ${evidence.dirtyFiles.length} 项未提交改动。`] : []),
380
+ ...(evidence.mainWorkspaceTaint.length ? [`主仓出现 ${evidence.mainWorkspaceTaint.length} 项新增污点(仅观测)。`] : []),
381
+ ...details,
382
+ ].join('\n')
383
+ }