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.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,716 @@
1
+ /**
2
+ * Sage engine provisioning and auto-upgrade.
3
+ *
4
+ * Turning on `sage.enabled` must not force the operator to hand-install an npm
5
+ * package and point at a rule directory, and keeping Sage current must not wait
6
+ * for a dsh-vigil release. This module owns both:
7
+ *
8
+ * - a plugin-owned install root `<DSH_HOME>/vigil/sage` with its own pinned
9
+ * `package.json` (never the profile's, never this package's);
10
+ * - `@gendigital/sage-core` — the detection engine that is imported in-process;
11
+ * - `@gendigital/sage-omp` — used **only** as the rules vehicle: it has no
12
+ * runtime dependencies and ships the upstream `resources/threats/*.yaml` and
13
+ * `resources/trusted-domains` set. Its code is never imported.
14
+ *
15
+ * Version policy: on first enable the newest stable pair published on npm is
16
+ * installed. When `sage.autoUpdate` is on, a periodic check (default once a day,
17
+ * tracked in the install receipt) upgrades to a newer stable pair. Every
18
+ * download is verified by loading the engine and the rule set before the running
19
+ * runtime swaps onto it; a release that fails verification is rolled back to the
20
+ * previously installed version when there is one.
21
+ *
22
+ * Supply-chain posture:
23
+ * - versions are exact (never ranges), install runs with `ignore-scripts` and
24
+ * optional native dependencies disabled;
25
+ * - install/update commands are composed from fixed arguments, never from
26
+ * config;
27
+ * - the registry can be pointed at a mirror through `npm_config_registry` (the
28
+ * same variable the package manager honors) or `DSH_VIGIL_SAGE_REGISTRY`.
29
+ *
30
+ * @module dsh-vigil/sage-provision
31
+ */
32
+
33
+ import { spawn } from 'node:child_process'
34
+ import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
35
+ import { get as httpGet } from 'node:http'
36
+ import { get as httpsGet } from 'node:https'
37
+ import { join } from 'node:path'
38
+ import { atomicWriteJson, ensureDir, nowIso, truncate } from './util.js'
39
+ import { verifySageModule } from './sentinel/sage-load.js'
40
+
41
+ /** Version used when the registry cannot be reached for the very first install. */
42
+ export const SAGE_DEFAULT_VERSION = '0.15.0'
43
+
44
+ /** Both upstream packages release in lockstep. */
45
+ export const SAGE_PACKAGES = Object.freeze(['@gendigital/sage-core', '@gendigital/sage-omp'])
46
+
47
+ /** Default time budget for one download. */
48
+ export const SAGE_INSTALL_TIMEOUT_MS = 240000
49
+
50
+ /** Default interval between automatic version checks (24 hours). */
51
+ export const SAGE_DEFAULT_UPDATE_INTERVAL_MS = 24 * 60 * 60 * 1000
52
+
53
+ const MANIFEST_FILE = 'provision.json'
54
+
55
+ /** One in-flight install per directory. */
56
+ const inFlight = new Map()
57
+
58
+ /**
59
+ * Plugin-owned Sage install root.
60
+ * @param {any} config resolved configuration
61
+ * @returns {string}
62
+ */
63
+ export function sageInstallDir(config) {
64
+ const stateDir = config?.paths?.stateDir
65
+ if (typeof stateDir !== 'string' || stateDir === '') throw new Error('未解析出状态目录,无法安装 Sage')
66
+ return join(stateDir, 'sage')
67
+ }
68
+
69
+ /* -------------------------------------------------------------------------- */
70
+ /* Versions */
71
+ /* -------------------------------------------------------------------------- */
72
+
73
+ /**
74
+ * Parse a semver string; prerelease/build metadata is ignored for ordering.
75
+ * @param {unknown} value
76
+ * @returns {{ major: number, minor: number, patch: number, prerelease: string|null }|null}
77
+ */
78
+ export function parseVersion(value) {
79
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(value ?? ''))
80
+ if (!match) return null
81
+ return {
82
+ major: Number(match[1]),
83
+ minor: Number(match[2]),
84
+ patch: Number(match[3]),
85
+ prerelease: match[4] ?? null,
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Compare two version strings. Prereleases sort below their release.
91
+ * @param {unknown} a
92
+ * @param {unknown} b
93
+ * @returns {number} negative when a < b, positive when a > b, 0 when equal
94
+ */
95
+ export function compareVersions(a, b) {
96
+ const left = parseVersion(a)
97
+ const right = parseVersion(b)
98
+ if (!left && !right) return 0
99
+ if (!left) return -1
100
+ if (!right) return 1
101
+ for (const key of ['major', 'minor', 'patch']) {
102
+ if (left[key] !== right[key]) return left[key] - right[key]
103
+ }
104
+ if (left.prerelease === right.prerelease) return 0
105
+ if (left.prerelease === null) return 1
106
+ if (right.prerelease === null) return -1
107
+ return left.prerelease < right.prerelease ? -1 : 1
108
+ }
109
+
110
+ /**
111
+ * Whether `target` is a newer stable release than `installed`.
112
+ * @param {unknown} installed
113
+ * @param {unknown} target
114
+ * @returns {boolean}
115
+ */
116
+ export function needsUpdate(installed, target) {
117
+ const parsedTarget = parseVersion(target)
118
+ if (!parsedTarget || parsedTarget.prerelease !== null) return false
119
+ if (!parseVersion(installed)) return true
120
+ return compareVersions(target, installed) > 0
121
+ }
122
+
123
+ /**
124
+ * Whether the receipt is old enough for another registry check.
125
+ * @param {{ lastCheckedAt?: string }|undefined} receipt
126
+ * @param {number} intervalMs
127
+ * @param {number} [now]
128
+ * @returns {boolean}
129
+ */
130
+ export function shouldCheckForUpdate(receipt, intervalMs, now = Date.now()) {
131
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) return false
132
+ const checkedAt = Date.parse(receipt?.lastCheckedAt ?? '')
133
+ if (!Number.isFinite(checkedAt)) return true
134
+ return now - checkedAt >= intervalMs
135
+ }
136
+
137
+ /* -------------------------------------------------------------------------- */
138
+ /* Registry */
139
+ /* -------------------------------------------------------------------------- */
140
+
141
+ /**
142
+ * Configured npm registry base URL (trailing slash removed).
143
+ * @returns {string}
144
+ */
145
+ export function registryBase() {
146
+ const configured = process.env.DSH_VIGIL_SAGE_REGISTRY
147
+ || process.env.npm_config_registry
148
+ || 'https://registry.npmjs.org'
149
+ return String(configured).replace(/\/+$/, '')
150
+ }
151
+
152
+ /**
153
+ * Minimal JSON GET with a timeout and a hard response-size bound.
154
+ * Uses the built-in HTTP client so it works in every Electron/Node host without
155
+ * relying on global `fetch`.
156
+ * @param {string} url
157
+ * @param {{ timeoutMs?: number, maxBytes?: number }} [options]
158
+ * @returns {Promise<any>}
159
+ */
160
+ export function fetchJson(url, options = {}) {
161
+ const timeoutMs = Math.max(1000, options.timeoutMs ?? 8000)
162
+ const maxBytes = Math.max(64 * 1024, options.maxBytes ?? 2 * 1024 * 1024)
163
+ return new Promise((resolve, reject) => {
164
+ let settled = false
165
+ const settle = (error, value) => {
166
+ if (settled) return
167
+ settled = true
168
+ clearTimeout(timer)
169
+ if (error) reject(error)
170
+ else resolve(value)
171
+ }
172
+ const timer = setTimeout(() => {
173
+ try {
174
+ request?.destroy()
175
+ } catch {
176
+ // ignore
177
+ }
178
+ settle(new Error(`请求超时(>${Math.round(timeoutMs / 1000)} 秒):${url}`))
179
+ }, timeoutMs)
180
+ /** @type {import('node:http').ClientRequest|undefined} */
181
+ let request
182
+ try {
183
+ const client = url.startsWith('https:') ? httpsGet : httpGet
184
+ request = client(url, { headers: { accept: 'application/json', 'user-agent': 'dsh-vigil' } }, response => {
185
+ if (response.statusCode === 301 || response.statusCode === 302) {
186
+ response.resume()
187
+ const location = response.headers.location
188
+ if (typeof location === 'string') {
189
+ fetchJson(location, options).then(value => settle(null, value), error => settle(error))
190
+ return
191
+ }
192
+ settle(new Error(`重定向缺少 location:${url}`))
193
+ return
194
+ }
195
+ if (response.statusCode !== undefined && response.statusCode >= 400) {
196
+ response.resume()
197
+ settle(new Error(`HTTP ${String(response.statusCode)}:${url}`))
198
+ return
199
+ }
200
+ /** @type {Buffer[]} */
201
+ const chunks = []
202
+ let size = 0
203
+ response.on('data', chunk => {
204
+ size += chunk.length
205
+ if (size > maxBytes) {
206
+ response.destroy()
207
+ settle(new Error(`响应超过 ${maxBytes} 字节:${url}`))
208
+ return
209
+ }
210
+ chunks.push(chunk)
211
+ })
212
+ response.on('error', error => settle(error))
213
+ response.on('end', () => {
214
+ try {
215
+ settle(null, JSON.parse(Buffer.concat(chunks).toString('utf8')))
216
+ } catch (error) {
217
+ settle(new Error(`响应不是 JSON:${url}(${error instanceof Error ? error.message : String(error)})`))
218
+ }
219
+ })
220
+ })
221
+ request.on('error', error => settle(error))
222
+ } catch (error) {
223
+ settle(error instanceof Error ? error : new Error(String(error)))
224
+ }
225
+ })
226
+ }
227
+
228
+ /**
229
+ * Read one package's `dist-tags.latest` from the registry.
230
+ * @param {string} name package name
231
+ * @param {{ registry?: string, timeoutMs?: number, fetchJson?: typeof fetchJson }} [options]
232
+ * @returns {Promise<string>}
233
+ */
234
+ export async function resolveLatestVersion(name, options = {}) {
235
+ const base = (options.registry ?? registryBase()).replace(/\/+$/, '')
236
+ const request = options.fetchJson ?? fetchJson
237
+ const document = await request(`${base}/${encodeURIComponent(name)}/latest`, { timeoutMs: options.timeoutMs })
238
+ const version = typeof document?.version === 'string' ? document.version : null
239
+ if (!version) throw new Error(`registry 未返回 ${name} 的版本`)
240
+ return version
241
+ }
242
+
243
+ /**
244
+ * Resolve the newest stable version available for both packages.
245
+ * @param {{ registry?: string, timeoutMs?: number, logger?: { warn?: (message: string) => void }, fetchJson?: typeof fetchJson }} [options]
246
+ * @returns {Promise<{ ok: boolean, version: string|null, latest: Record<string,string|null>, error: string|null }>}
247
+ */
248
+ export async function resolveSageTarget(options = {}) {
249
+ /** @type {Record<string, string|null>} */
250
+ const latest = {}
251
+ try {
252
+ for (const name of SAGE_PACKAGES) latest[name] = await resolveLatestVersion(name, options)
253
+ } catch (error) {
254
+ return { ok: false, version: null, latest, error: error instanceof Error ? error.message : String(error) }
255
+ }
256
+ const candidates = SAGE_PACKAGES.map(name => latest[name]).filter(version => typeof version === 'string')
257
+ // Both projects release in lockstep; using the lower of the two guarantees the
258
+ // engine/rules pair exists on the registry.
259
+ const version = candidates.reduce((lowest, current) => (compareVersions(current, lowest) < 0 ? current : lowest), /** @type {string} */ (candidates[0]))
260
+ return { ok: true, version, latest, error: null }
261
+ }
262
+
263
+ /* -------------------------------------------------------------------------- */
264
+ /* Local install */
265
+ /* -------------------------------------------------------------------------- */
266
+
267
+ /**
268
+ * Locate an installed Sage engine and rule set.
269
+ * @param {string} dir install root
270
+ * @returns {{ available: boolean, dir: string, modulePath: string|null, threatsDir: string|null, trustedDomainsDir: string|null, rules: number, version: string|null, reason: string|null }}
271
+ */
272
+ export function locateSage(dir) {
273
+ const result = {
274
+ available: false,
275
+ dir,
276
+ modulePath: null,
277
+ threatsDir: null,
278
+ trustedDomainsDir: null,
279
+ rules: 0,
280
+ version: null,
281
+ reason: null,
282
+ }
283
+ if (typeof dir !== 'string' || dir === '') {
284
+ result.reason = '没有安装目录'
285
+ return result
286
+ }
287
+ const modulePath = join(dir, 'node_modules', '@gendigital', 'sage-core', 'dist', 'index.js')
288
+ const threatsDir = join(dir, 'node_modules', '@gendigital', 'sage-omp', 'resources', 'threats')
289
+ const trustedDomainsDir = join(dir, 'node_modules', '@gendigital', 'sage-omp', 'resources', 'trusted-domains')
290
+ if (!existsSync(modulePath)) {
291
+ result.reason = `未安装 Sage 引擎(${modulePath} 不存在)`
292
+ return result
293
+ }
294
+ result.modulePath = modulePath
295
+ try {
296
+ const manifest = JSON.parse(readFileSync(join(dir, 'node_modules', '@gendigital', 'sage-core', 'package.json'), 'utf8'))
297
+ result.version = typeof manifest.version === 'string' ? manifest.version : null
298
+ } catch {
299
+ result.version = null
300
+ }
301
+ if (!existsSync(threatsDir)) {
302
+ result.reason = `未找到 Sage 规则目录(${threatsDir} 不存在)`
303
+ return result
304
+ }
305
+ try {
306
+ result.rules = readdirSync(threatsDir).filter(name => /\.ya?ml$/i.test(name)).length
307
+ } catch {
308
+ result.rules = 0
309
+ }
310
+ if (result.rules === 0) {
311
+ result.reason = `Sage 规则目录为空(${threatsDir})`
312
+ return result
313
+ }
314
+ result.threatsDir = threatsDir
315
+ result.trustedDomainsDir = existsSync(trustedDomainsDir) ? trustedDomainsDir : null
316
+ result.available = true
317
+ return result
318
+ }
319
+
320
+ /**
321
+ * Read the provisioning receipt written by a successful install.
322
+ * @param {string} dir install root
323
+ * @returns {any|undefined}
324
+ */
325
+ export function readProvisionReceipt(dir) {
326
+ try {
327
+ return JSON.parse(readFileSync(join(dir, MANIFEST_FILE), 'utf8'))
328
+ } catch {
329
+ return undefined
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Persist the provisioning receipt.
335
+ * @param {string} dir
336
+ * @param {any} receipt
337
+ * @returns {boolean}
338
+ */
339
+ export function writeProvisionReceipt(dir, receipt) {
340
+ try {
341
+ return atomicWriteJson(join(dir, MANIFEST_FILE), receipt)
342
+ } catch {
343
+ return false
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Write the plugin-owned package manifest and an `.npmrc` that disables install
349
+ * scripts and optional native dependencies for this tree only.
350
+ * @param {string} dir
351
+ * @param {Record<string, string>} [versions] versions by package name
352
+ */
353
+ export function writeInstallManifest(dir, versions = { ['@gendigital/sage-core']: SAGE_DEFAULT_VERSION, ['@gendigital/sage-omp']: SAGE_DEFAULT_VERSION }) {
354
+ ensureDir(dir)
355
+ atomicWriteJson(join(dir, 'package.json'), {
356
+ name: 'dsh-vigil-sage',
357
+ version: '1.0.0',
358
+ private: true,
359
+ type: 'module',
360
+ description: 'Sage engine and rule set provisioned by dsh-vigil; not a package to publish',
361
+ dependencies: { ...versions },
362
+ })
363
+ writeFileSync(join(dir, '.npmrc'), [
364
+ 'ignore-scripts=true',
365
+ 'optional=false',
366
+ 'audit=false',
367
+ 'fund=false',
368
+ 'package-lock=false',
369
+ '',
370
+ ].join('\n'))
371
+ }
372
+
373
+ /**
374
+ * Compose the package-manager invocations to try, in order.
375
+ * @param {{ command: string, args: readonly string[], env: Record<string, string> }|undefined} packageManager
376
+ * @returns {Array<{ kind: string, command: string, args: string[], shell: boolean, env: Record<string, string> }>}
377
+ */
378
+ export function installCandidates(packageManager) {
379
+ /** @type {Array<{ kind: string, command: string, args: string[], shell: boolean, env: Record<string, string> }>} */
380
+ const candidates = []
381
+ const baseEnv = { ...process.env, npm_config_ignore_scripts: 'true', npm_config_optional: 'false' }
382
+ if (packageManager && typeof packageManager.command === 'string' && packageManager.command !== '') {
383
+ candidates.push({
384
+ kind: 'profile-package-manager',
385
+ command: packageManager.command,
386
+ args: [
387
+ ...(Array.isArray(packageManager.args) ? packageManager.args.map(String) : []),
388
+ 'install',
389
+ '--prod',
390
+ '--ignore-scripts',
391
+ '--config.optional=false',
392
+ ],
393
+ shell: false,
394
+ env: { ...baseEnv, ...(packageManager.env ?? {}) },
395
+ })
396
+ }
397
+ const isWindows = process.platform === 'win32'
398
+ const winArgs = ['--omit=optional', '--ignore-scripts', '--no-audit', '--no-fund', '--no-package-lock', 'install']
399
+ if (isWindows) {
400
+ const comspec = process.env.ComSpec || 'cmd.exe'
401
+ candidates.push({ kind: 'npm', command: comspec, args: ['/d', '/s', '/c', 'npm.cmd', ...winArgs], shell: false, env: baseEnv })
402
+ candidates.push({ kind: 'pnpm', command: comspec, args: ['/d', '/s', '/c', 'pnpm.cmd', 'install', '--prod', '--ignore-scripts', '--config.optional=false'], shell: false, env: baseEnv })
403
+ } else {
404
+ candidates.push({ kind: 'npm', command: 'npm', args: winArgs, shell: false, env: baseEnv })
405
+ candidates.push({ kind: 'pnpm', command: 'pnpm', args: ['install', '--prod', '--ignore-scripts', '--config.optional=false'], shell: false, env: baseEnv })
406
+ }
407
+ return candidates
408
+ }
409
+
410
+ /**
411
+ * Run one command to completion with a bounded output tail and timeout.
412
+ * @param {{ command: string, args: string[], shell: boolean, env: Record<string, string> }} spec
413
+ * @param {{ cwd: string, timeoutMs: number }} options
414
+ * @returns {Promise<{ ok: boolean, exitCode: number|null, output: string, error: string|null }>}
415
+ */
416
+ export function runInstallCommand(spec, options) {
417
+ return new Promise(resolve => {
418
+ const controller = new AbortController()
419
+ const timer = setTimeout(() => controller.abort(), Math.max(1000, options.timeoutMs))
420
+ /** @type {string[]} */
421
+ const chunks = []
422
+ let settled = false
423
+ const settle = result => {
424
+ if (settled) return
425
+ settled = true
426
+ clearTimeout(timer)
427
+ resolve(result)
428
+ }
429
+ let child
430
+ try {
431
+ child = spawn(spec.command, spec.args, {
432
+ cwd: options.cwd,
433
+ env: spec.env,
434
+ shell: spec.shell,
435
+ windowsHide: true,
436
+ stdio: ['ignore', 'pipe', 'pipe'],
437
+ signal: controller.signal,
438
+ })
439
+ } catch (error) {
440
+ settle({ ok: false, exitCode: null, output: '', error: error instanceof Error ? error.message : String(error) })
441
+ return
442
+ }
443
+ const collect = data => {
444
+ chunks.push(String(data))
445
+ if (chunks.length > 400) chunks.splice(0, chunks.length - 400)
446
+ }
447
+ child.stdout?.on('data', collect)
448
+ child.stderr?.on('data', collect)
449
+ child.on('error', error => {
450
+ settle({ ok: false, exitCode: null, output: truncate(chunks.join(''), 8000), error: error instanceof Error ? error.message : String(error) })
451
+ })
452
+ child.on('close', code => {
453
+ const output = truncate(chunks.join(''), 8000)
454
+ if (controller.signal.aborted) {
455
+ settle({ ok: false, exitCode: code, output, error: `安装超时(>${Math.round(options.timeoutMs / 1000)} 秒)` })
456
+ return
457
+ }
458
+ settle({ ok: code === 0, exitCode: code, output, error: code === 0 ? null : `安装命令退出码 ${String(code)}` })
459
+ })
460
+ })
461
+ }
462
+
463
+ /**
464
+ * Run one install pass with the available package managers.
465
+ * @param {object} options
466
+ * @returns {Promise<{ ok: boolean, attempts: Array<{ kind: string, ok: boolean, error: string|null }>, outputs: string[], location: any, verified: any }>}
467
+ */
468
+ async function installVersions(options) {
469
+ const { dir, versions, packageManager, logger, run, timeoutMs, verify } = options
470
+ writeInstallManifest(dir, versions)
471
+ /** @type {Array<{ kind: string, ok: boolean, error: string|null }>} */
472
+ const attempts = []
473
+ /** @type {string[]} */
474
+ const outputs = []
475
+ for (const candidate of installCandidates(packageManager)) {
476
+ const result = await run(candidate, { cwd: dir, timeoutMs })
477
+ outputs.push(`[${candidate.kind}] ${result.output}`)
478
+ let entry = { kind: candidate.kind, ok: result.ok, error: result.error }
479
+ if (result.ok) {
480
+ const location = locateSage(dir)
481
+ const expected = versions['@gendigital/sage-core']
482
+ if (!location.available) {
483
+ entry = { ...entry, ok: false, error: location.reason ?? '安装完成但未见 Sage 文件' }
484
+ } else if (expected && location.version && compareVersions(location.version, expected) !== 0) {
485
+ entry = { ...entry, ok: false, error: `安装后版本不匹配:期望 ${expected},实际 ${location.version}` }
486
+ } else {
487
+ const verified = await verify(location)
488
+ if (!verified.ok) {
489
+ entry = { ...entry, ok: false, error: `安装后验证失败:${verified.error ?? '未知原因'}` }
490
+ } else {
491
+ attempts.push(entry)
492
+ return { ok: true, attempts, outputs, location, verified }
493
+ }
494
+ }
495
+ }
496
+ attempts.push(entry)
497
+ logger?.warn?.(`[dsh-vigil] Sage 安装尝试失败(${candidate.kind}):${entry.error ?? '未知原因'}`)
498
+ }
499
+ return { ok: false, attempts, outputs, location: locateSage(dir), verified: { ok: false, rules: 0 } }
500
+ }
501
+
502
+ /**
503
+ * Download, upgrade, or repair the pinned Sage packages in `dir`.
504
+ *
505
+ * @param {object} options
506
+ * @param {any} options.config resolved configuration
507
+ * @param {string} [options.dir] install root (defaults to the plugin state dir)
508
+ * @param {{ command: string, args: readonly string[], env: Record<string, string> }|undefined} [options.packageManager]
509
+ * @param {{ info?: (message: string) => void, warn?: (message: string) => void }} [options.logger]
510
+ * @param {number} [options.timeoutMs]
511
+ * @param {(spec: any, runOptions: any) => Promise<any>} [options.run]
512
+ * @param {(location: any) => Promise<{ ok: boolean, rules: number, error: string|null }>} [options.verify]
513
+ * @param {string} [options.targetVersion] explicit version (skip registry resolution)
514
+ * @param {boolean} [options.resolveVersion] resolve the newest pair from the registry (default true)
515
+ * @param {string} [options.registry] registry base override
516
+ * @param {typeof fetchJson} [options.fetchJson] injectable registry reader
517
+ * @param {'install'|'update'|'repair'} [options.reason]
518
+ * @returns {Promise<any>}
519
+ */
520
+ export async function provisionSage(options) {
521
+ const dir = options.dir ?? sageInstallDir(options.config)
522
+ const existing = inFlight.get(dir)
523
+ if (existing) return existing
524
+ const attempt = (async () => {
525
+ const logger = options.logger
526
+ const run = options.run ?? runInstallCommand
527
+ const verify = options.verify ?? verifySageModule
528
+ const timeoutMs = Math.max(10000, options.timeoutMs ?? SAGE_INSTALL_TIMEOUT_MS)
529
+ const previous = readProvisionReceipt(dir)
530
+ const previousVersion = previous?.version ?? locateSage(dir).version ?? null
531
+ /** @type {Array<{ kind: string, ok: boolean, error: string|null }>} */
532
+ const attempts = []
533
+ /** @type {string[]} */
534
+ const outputs = []
535
+ try {
536
+ writeInstallManifest(dir)
537
+ // Resolve the target version: explicit > registry > pinned fallback.
538
+ let targetVersion = options.targetVersion ?? null
539
+ if (!targetVersion && options.resolveVersion !== false) {
540
+ const target = await resolveSageTarget({
541
+ registry: options.registry,
542
+ timeoutMs: Math.min(timeoutMs, 8000),
543
+ logger,
544
+ fetchJson: options.fetchJson,
545
+ })
546
+ if (target.ok) {
547
+ targetVersion = target.version
548
+ } else {
549
+ logger?.warn?.(`[dsh-vigil] 无法从 registry 解析 Sage 最新版本,回退到内置版本:${target.error ?? '未知原因'}`)
550
+ }
551
+ }
552
+ if (!targetVersion) targetVersion = SAGE_DEFAULT_VERSION
553
+ /** @type {Record<string, string>} */
554
+ const versions = { '@gendigital/sage-core': targetVersion, '@gendigital/sage-omp': targetVersion }
555
+ logger?.info?.(`[dsh-vigil] 正在${previousVersion ? '更新' : '下载'} Sage(${targetVersion})到 ${dir}`)
556
+ // A version change needs a clean tree: a package manager may otherwise keep
557
+ // the already-installed tree and leave a different version behind.
558
+ if (previousVersion) {
559
+ try {
560
+ rmSync(join(dir, 'node_modules'), { recursive: true, force: true })
561
+ } catch {
562
+ // a locked tree fails the version check below and is reported
563
+ }
564
+ try {
565
+ rmSync(join(dir, 'package-lock.json'), { force: true })
566
+ } catch {
567
+ // absent or locked: ignore
568
+ }
569
+ }
570
+ let pass = await installVersions({ dir, versions, packageManager: options.packageManager, logger, run, timeoutMs, verify })
571
+ attempts.push(...pass.attempts)
572
+ outputs.push(...pass.outputs)
573
+
574
+ // Verification failed after a successful download: roll back to the last
575
+ // known-good pair when this was an update.
576
+ let rolledBack = false
577
+ if (!pass.ok && previousVersion && compareVersions(targetVersion, previousVersion) > 0) {
578
+ rolledBack = true
579
+ logger?.warn?.(`[dsh-vigil] Sage ${targetVersion} 验证失败,回滚到 ${previousVersion}`)
580
+ const rollbackVersions = { '@gendigital/sage-core': previousVersion, '@gendigital/sage-omp': previousVersion }
581
+ const rollback = await installVersions({ dir, versions: rollbackVersions, packageManager: options.packageManager, logger, run, timeoutMs, verify })
582
+ attempts.push(...rollback.attempts)
583
+ outputs.push(...rollback.outputs)
584
+ if (!rollback.ok) {
585
+ return {
586
+ ok: false,
587
+ dir,
588
+ location: rollback.location,
589
+ attempts,
590
+ output: truncate(outputs.join('\n'), 8000),
591
+ error: `Sage ${targetVersion} 安装/验证失败,回滚到 ${previousVersion} 也失败`,
592
+ rolledBack,
593
+ targetVersion,
594
+ }
595
+ }
596
+ const location = rollback.location
597
+ writeProvisionReceipt(dir, {
598
+ schema: 2,
599
+ installedAt: previous?.installedAt ?? nowIso(),
600
+ version: location.version,
601
+ rules: rollback.verified.rules,
602
+ previousVersion: previous?.previousVersion ?? null,
603
+ lastCheckedAt: previous?.lastCheckedAt ?? null,
604
+ dependencies: { ...rollbackVersions },
605
+ manager: attempts.filter(item => item.ok).map(item => item.kind).pop() ?? null,
606
+ lastFailure: { at: nowIso(), version: targetVersion, error: '安装后验证失败,已回滚' },
607
+ })
608
+ return {
609
+ ok: false,
610
+ dir,
611
+ location,
612
+ attempts,
613
+ output: truncate(outputs.join('\n'), 8000),
614
+ error: `Sage ${targetVersion} 安装/验证失败,已回滚到 ${location.version ?? previousVersion}`,
615
+ rolledBack: true,
616
+ targetVersion,
617
+ }
618
+ }
619
+ if (!pass.ok) {
620
+ return {
621
+ ok: false,
622
+ dir,
623
+ location: pass.location,
624
+ attempts,
625
+ output: truncate(outputs.join('\n'), 8000),
626
+ error: attempts.length > 0 ? (attempts[attempts.length - 1].error ?? '所有安装方式均失败') : '找不到可用的包管理器(npm / pnpm)',
627
+ rolledBack,
628
+ targetVersion,
629
+ }
630
+ }
631
+ const location = pass.location
632
+ writeProvisionReceipt(dir, {
633
+ schema: 2,
634
+ installedAt: nowIso(),
635
+ version: location.version,
636
+ rules: pass.verified.rules,
637
+ previousVersion: previousVersion && previousVersion !== location.version ? previousVersion : (previous?.previousVersion ?? null),
638
+ lastCheckedAt: nowIso(),
639
+ dependencies: { ...versions },
640
+ manager: attempts.filter(item => item.ok).map(item => item.kind).pop() ?? null,
641
+ })
642
+ logger?.info?.(`[dsh-vigil] Sage ${location.version ?? targetVersion} 已就绪:${pass.verified.rules} 条规则`)
643
+ return {
644
+ ok: true,
645
+ dir,
646
+ location,
647
+ attempts,
648
+ output: truncate(outputs.join('\n'), 8000),
649
+ error: null,
650
+ rolledBack: false,
651
+ targetVersion,
652
+ updated: Boolean(previousVersion && location.version && compareVersions(location.version, previousVersion) > 0),
653
+ }
654
+ } catch (error) {
655
+ return {
656
+ ok: false,
657
+ dir,
658
+ location: locateSage(dir),
659
+ attempts,
660
+ output: truncate(outputs.join('\n'), 8000),
661
+ error: error instanceof Error ? error.message : String(error),
662
+ rolledBack: false,
663
+ }
664
+ } finally {
665
+ inFlight.delete(dir)
666
+ }
667
+ })()
668
+ inFlight.set(dir, attempt)
669
+ return attempt
670
+ }
671
+
672
+ /**
673
+ * Check the registry for a newer pair without installing anything.
674
+ * @param {object} options
675
+ * @param {string} options.installedVersion
676
+ * @param {{ lastCheckedAt?: string }|undefined} options.receipt
677
+ * @param {number} [options.intervalMs]
678
+ * @param {boolean} [options.force]
679
+ * @param {string} [options.registry]
680
+ * @param {{ warn?: (message: string) => void }} [options.logger]
681
+ * @param {typeof fetchJson} [options.fetchJson]
682
+ * @param {number} [options.now]
683
+ * @returns {Promise<{ checked: boolean, ok: boolean, latestVersion: string|null, updateAvailable: boolean, error: string|null, reason?: string }>}
684
+ */
685
+ export async function checkSageUpdate(options) {
686
+ const intervalMs = options.intervalMs ?? SAGE_DEFAULT_UPDATE_INTERVAL_MS
687
+ if (!options.force && !shouldCheckForUpdate(options.receipt, intervalMs, options.now)) {
688
+ return { checked: false, ok: true, latestVersion: null, updateAvailable: false, error: null, reason: 'interval' }
689
+ }
690
+ const target = await resolveSageTarget({ registry: options.registry, logger: options.logger, fetchJson: options.fetchJson })
691
+ if (!target.ok) {
692
+ return { checked: true, ok: false, latestVersion: null, updateAvailable: false, error: target.error }
693
+ }
694
+ return {
695
+ checked: true,
696
+ ok: true,
697
+ latestVersion: target.version,
698
+ updateAvailable: needsUpdate(options.installedVersion, target.version),
699
+ error: null,
700
+ }
701
+ }
702
+
703
+ /**
704
+ * Best-effort removal of the provisioned tree.
705
+ * @param {any} config
706
+ * @returns {{ ok: boolean, dir: string, error?: string }}
707
+ */
708
+ export function removeProvisionedSage(config) {
709
+ const dir = sageInstallDir(config)
710
+ try {
711
+ rmSync(dir, { recursive: true, force: true })
712
+ return { ok: true, dir }
713
+ } catch (error) {
714
+ return { ok: false, dir, error: error instanceof Error ? error.message : String(error) }
715
+ }
716
+ }