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
package/src/integrity.js
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-integrity checks (FR-5.1 – FR-5.4).
|
|
3
|
+
*
|
|
4
|
+
* dsh-vigil cannot stop a privileged attacker from replacing its files — it can
|
|
5
|
+
* only make that replacement *visible*. This module keeps four cheap signals:
|
|
6
|
+
*
|
|
7
|
+
* 1. a content baseline: SHA-256 per shipped file, per plugin version;
|
|
8
|
+
* 2. an optional Ed25519 signature over `baseline.json`;
|
|
9
|
+
* 3. a heartbeat: every hook/guard wrapper is tagged with a module-private
|
|
10
|
+
* symbol, and a periodic check notices when the tag or the registration has
|
|
11
|
+
* been stripped;
|
|
12
|
+
* 4. a canary file under the Harness home whose hash is in the baseline. If the
|
|
13
|
+
* canary is rewritten or deleted, the plugin files are not what they were
|
|
14
|
+
* when this installation last verified itself.
|
|
15
|
+
*
|
|
16
|
+
* All of it is advisory: results appear in `vigil_status`, in the audit log, and
|
|
17
|
+
* as warnings from the `vigil_integrity` tool. Nothing here is a security
|
|
18
|
+
* boundary, and the README says so.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-vigil/integrity
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createPublicKey, randomBytes, verify as cryptoVerify } from 'node:crypto'
|
|
24
|
+
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
25
|
+
import { dirname, extname, join } from 'node:path'
|
|
26
|
+
import { fileURLToPath } from 'node:url'
|
|
27
|
+
import { atomicWriteJson, ensureDir, getHomeDir, nowIso, readJson, sha256, toPosixRelative } from './util.js'
|
|
28
|
+
|
|
29
|
+
const HEARTBEAT = Symbol('dsh-vigil.integrity.heartbeat')
|
|
30
|
+
|
|
31
|
+
/** Directory containing this module (`<packageRoot>/src`). */
|
|
32
|
+
const SELF_DIR = dirname(fileURLToPath(import.meta.url))
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Files included in the content baseline: the code that actually runs, plus the
|
|
36
|
+
* manifest and the patch that mounts it. Documentation, locale text and the icon
|
|
37
|
+
* are deliberately excluded so editing them does not raise a tamper alert.
|
|
38
|
+
*/
|
|
39
|
+
const BASELINE_EXTENSIONS = new Set(['.js'])
|
|
40
|
+
/** Rule packs are data, but they decide what is detected: hash them too. */
|
|
41
|
+
const BASELINE_RULE_EXTENSIONS = new Set(['.yaml', '.yml', '.json'])
|
|
42
|
+
const BASELINE_ROOT_FILES = ['package.json', 'cordis.patch.yml', 'client.js']
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @typedef {object} IntegrityState
|
|
46
|
+
* @property {{ state: 'absent'|'match'|'drift'|'error', changed: string[], added: string[], missing: string[], version: string|null, checkedAt: string|null }} baseline
|
|
47
|
+
* @property {{ state: 'absent'|'ok'|'tampered'|'error', reason: string|null }} canary
|
|
48
|
+
* @property {{ state: 'disabled'|'unverified'|'verified'|'failed', reason: string|null }} signature
|
|
49
|
+
* @property {{ state: 'ok'|'broken'|'unchecked', reason: string|null }} heartbeat
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {any} config
|
|
54
|
+
* @param {{ logger?: { warn?: (message: string) => void }, pluginDir?: string, record?: (event: { kind: string, event: string, reason: string, ruleIds?: string[] }) => void }} [options]
|
|
55
|
+
* @returns {IntegrityMonitor}
|
|
56
|
+
*/
|
|
57
|
+
export function createIntegrity(config, options = {}) {
|
|
58
|
+
const pluginDir = options.pluginDir ?? resolvePluginDir()
|
|
59
|
+
const enabled = config?.integrity?.enabled !== false
|
|
60
|
+
const baselineDir = config?.paths?.integrityDir ?? ''
|
|
61
|
+
const baselineFile = config?.paths?.baselineFile ?? ''
|
|
62
|
+
const canaryFile = config?.paths?.canaryFile ?? ''
|
|
63
|
+
const canaryEnabled = enabled && config?.integrity?.canary !== false
|
|
64
|
+
const baselineEnabled = enabled && config?.integrity?.baseline !== false
|
|
65
|
+
|
|
66
|
+
/** @type {IntegrityState} */
|
|
67
|
+
const state = {
|
|
68
|
+
baseline: { state: 'absent', changed: [], added: [], missing: [], version: null, checkedAt: null },
|
|
69
|
+
canary: { state: 'absent', reason: null },
|
|
70
|
+
signature: { state: 'disabled', reason: null },
|
|
71
|
+
heartbeat: { state: 'unchecked', reason: null },
|
|
72
|
+
}
|
|
73
|
+
/** @type {string[]} */
|
|
74
|
+
const alerts = []
|
|
75
|
+
/** @type {Function[]} */
|
|
76
|
+
const heartbeats = []
|
|
77
|
+
let lastCheck = 0
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @param {string} message
|
|
81
|
+
* @param {string} [ruleId]
|
|
82
|
+
*/
|
|
83
|
+
function alert(message, ruleId = 'VG-INT-00') {
|
|
84
|
+
const text = `[integrity] ${message}`
|
|
85
|
+
if (!alerts.includes(text)) alerts.push(text)
|
|
86
|
+
options.record?.({ kind: 'integrity', event: 'alert', reason: text, ruleIds: [ruleId] })
|
|
87
|
+
options.logger?.warn?.(`[dsh-vigil] ${text}`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** @returns {string} plugin package root */
|
|
91
|
+
function resolvePluginDir() {
|
|
92
|
+
// This module lives in `<packageRoot>/src`; the package root is one level up.
|
|
93
|
+
return dirname(SELF_DIR)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Enumerate the shipped *runtime* files relative to the package root: every
|
|
98
|
+
* `.js` under `src/`, plus the manifest and the bundle patch. Documentation,
|
|
99
|
+
* locale text, tests, scripts and the icon are not part of the integrity
|
|
100
|
+
* baseline: they cannot execute, and alerting on a README edit is noise.
|
|
101
|
+
* @returns {Record<string, string>} relative path → sha256
|
|
102
|
+
*/
|
|
103
|
+
function hashShippedFiles() {
|
|
104
|
+
/** @type {Record<string, string>} */
|
|
105
|
+
const files = {}
|
|
106
|
+
const walk = (dir, depth, extensions) => {
|
|
107
|
+
if (depth > 6) return
|
|
108
|
+
let entries
|
|
109
|
+
try {
|
|
110
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
111
|
+
} catch {
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
for (const entry of entries) {
|
|
115
|
+
const full = join(dir, entry.name)
|
|
116
|
+
if (entry.isDirectory()) {
|
|
117
|
+
if (entry.name === 'node_modules' || entry.name === '.git') continue
|
|
118
|
+
walk(full, depth + 1, extensions)
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
if (!entry.isFile()) continue
|
|
122
|
+
if (!extensions.has(extname(entry.name).toLowerCase())) continue
|
|
123
|
+
try {
|
|
124
|
+
if (statSync(full).size > 2 * 1024 * 1024) continue
|
|
125
|
+
files[toPosixRelative(pluginDir, full)] = sha256(readFileSync(full))
|
|
126
|
+
} catch {
|
|
127
|
+
// inaccessible file: skip, the next check reports a missing entry
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
walk(join(pluginDir, 'src'), 0, BASELINE_EXTENSIONS)
|
|
132
|
+
walk(join(pluginDir, 'rules'), 0, BASELINE_RULE_EXTENSIONS)
|
|
133
|
+
for (const name of BASELINE_ROOT_FILES) {
|
|
134
|
+
const full = join(pluginDir, name)
|
|
135
|
+
try {
|
|
136
|
+
if (!statSync(full).isFile()) continue
|
|
137
|
+
files[name] = sha256(readFileSync(full))
|
|
138
|
+
} catch {
|
|
139
|
+
// absent manifest/patch: the report will show the reduced baseline
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return files
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @returns {string} installed plugin version from package.json */
|
|
146
|
+
function packageVersion() {
|
|
147
|
+
const manifest = readJson(join(pluginDir, 'package.json'))
|
|
148
|
+
return typeof manifest?.version === 'string' ? manifest.version : '0.0.0'
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Write a new baseline (also used by the `rebaseline` action after a trusted
|
|
153
|
+
* upgrade).
|
|
154
|
+
* @returns {{ ok: boolean, version: string, files: number, error?: string }}
|
|
155
|
+
*/
|
|
156
|
+
function writeBaseline(previous = null) {
|
|
157
|
+
if (!baselineEnabled) return { ok: false, version: packageVersion(), files: 0, error: '完整性基线已禁用' }
|
|
158
|
+
try {
|
|
159
|
+
ensureDir(baselineDir)
|
|
160
|
+
/** @type {Record<string, unknown>} */
|
|
161
|
+
const document = {
|
|
162
|
+
schema: 1,
|
|
163
|
+
createdAt: nowIso(),
|
|
164
|
+
version: packageVersion(),
|
|
165
|
+
root: pluginDir,
|
|
166
|
+
files: hashShippedFiles(),
|
|
167
|
+
}
|
|
168
|
+
if (canaryEnabled) {
|
|
169
|
+
const previousCanary = previous && typeof previous === 'object' && previous.canary && typeof previous.canary === 'object'
|
|
170
|
+
? previous.canary
|
|
171
|
+
: undefined
|
|
172
|
+
document.canary = considerCanary(previousCanary)
|
|
173
|
+
}
|
|
174
|
+
if (!atomicWriteJson(baselineFile, document)) {
|
|
175
|
+
return { ok: false, version: packageVersion(), files: 0, error: '无法写入基线文件' }
|
|
176
|
+
}
|
|
177
|
+
state.baseline = {
|
|
178
|
+
state: 'match',
|
|
179
|
+
changed: [],
|
|
180
|
+
added: [],
|
|
181
|
+
missing: [],
|
|
182
|
+
version: packageVersion(),
|
|
183
|
+
checkedAt: nowIso(),
|
|
184
|
+
}
|
|
185
|
+
verifySignature()
|
|
186
|
+
return { ok: true, version: packageVersion(), files: Object.keys(/** @type {Record<string, string>} */ (document.files)).length }
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { ok: false, version: packageVersion(), files: 0, error: error instanceof Error ? error.message : String(error) }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Ensure the canary exists; returns its fingerprint for the baseline.
|
|
194
|
+
* @param {unknown} existingBaselineCanary
|
|
195
|
+
* @returns {{ sha256: string, path: string, createdAt: string }}
|
|
196
|
+
*/
|
|
197
|
+
function considerCanary(existingBaselineCanary) {
|
|
198
|
+
const existing = existingBaselineCanary && typeof existingBaselineCanary === 'object'
|
|
199
|
+
? /** @type {{ sha256?: string, createdAt?: string }} */ (existingBaselineCanary)
|
|
200
|
+
: undefined
|
|
201
|
+
if (existsSync(canaryFile)) {
|
|
202
|
+
try {
|
|
203
|
+
const content = readFileSync(canaryFile, 'utf8')
|
|
204
|
+
const digest = sha256(content)
|
|
205
|
+
if (existing?.sha256 && existing.sha256 !== digest) {
|
|
206
|
+
alert('金丝雀文件内容与基线不一致:Harness 主目录可能被改动', 'VG-INT-03')
|
|
207
|
+
}
|
|
208
|
+
return { sha256: digest, path: canaryFile, createdAt: existing?.createdAt ?? nowIso() }
|
|
209
|
+
} catch (error) {
|
|
210
|
+
alert(`无法读取金丝雀文件:${String(error)}`, 'VG-INT-03')
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const content = `dsh-vigil canary\nnonce=${randomBytes(16).toString('hex')}\ncreated=${nowIso()}\n`
|
|
214
|
+
try {
|
|
215
|
+
ensureDir(dirname(canaryFile))
|
|
216
|
+
writeFileSync(canaryFile, content, { encoding: 'utf8', flag: 'wx' })
|
|
217
|
+
const digest = sha256(content)
|
|
218
|
+
state.canary = { state: 'ok', reason: null }
|
|
219
|
+
return { sha256: digest, path: canaryFile, createdAt: nowIso() }
|
|
220
|
+
} catch (error) {
|
|
221
|
+
alert(`无法创建金丝雀文件:${String(error)}`, 'VG-INT-03')
|
|
222
|
+
return { sha256: '', path: canaryFile, createdAt: nowIso() }
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Compare current files with the stored baseline.
|
|
228
|
+
* @returns {void}
|
|
229
|
+
*/
|
|
230
|
+
function checkBaseline() {
|
|
231
|
+
if (!baselineEnabled) {
|
|
232
|
+
state.baseline.state = 'absent'
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
const stored = readJson(baselineFile)
|
|
236
|
+
if (!stored || typeof stored !== 'object') {
|
|
237
|
+
state.baseline.state = 'absent'
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
try {
|
|
241
|
+
const expected = /** @type {Record<string, string>} */ (stored.files ?? {})
|
|
242
|
+
const current = hashShippedFiles()
|
|
243
|
+
const changed = []
|
|
244
|
+
const added = []
|
|
245
|
+
const missing = []
|
|
246
|
+
for (const [file, digest] of Object.entries(expected)) {
|
|
247
|
+
if (!(file in current)) missing.push(file)
|
|
248
|
+
else if (current[file] !== digest) changed.push(file)
|
|
249
|
+
}
|
|
250
|
+
for (const file of Object.keys(current)) {
|
|
251
|
+
if (!(file in expected)) added.push(file)
|
|
252
|
+
}
|
|
253
|
+
state.baseline = {
|
|
254
|
+
state: changed.length + added.length + missing.length === 0 ? 'match' : 'drift',
|
|
255
|
+
changed,
|
|
256
|
+
added,
|
|
257
|
+
missing,
|
|
258
|
+
version: typeof stored.version === 'string' ? stored.version : null,
|
|
259
|
+
checkedAt: nowIso(),
|
|
260
|
+
}
|
|
261
|
+
if (state.baseline.state === 'drift') {
|
|
262
|
+
const parts = []
|
|
263
|
+
if (changed.length > 0) parts.push(`改动 ${changed.length} 个文件(${changed.slice(0, 3).join('、')})`)
|
|
264
|
+
if (added.length > 0) parts.push(`新增 ${added.length} 个(${added.slice(0, 3).join('、')})`)
|
|
265
|
+
if (missing.length > 0) parts.push(`缺失 ${missing.length} 个(${missing.slice(0, 3).join('、')})`)
|
|
266
|
+
alert(`插件文件与基线不一致:${parts.join(';')}。可能被篡改,也可能是本地修改后未重建基线`, 'VG-INT-01')
|
|
267
|
+
}
|
|
268
|
+
} catch (error) {
|
|
269
|
+
state.baseline.state = 'error'
|
|
270
|
+
alert(`基线校验失败:${error instanceof Error ? error.message : String(error)}`, 'VG-INT-01')
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Check the canary file against the baseline fingerprint.
|
|
276
|
+
* @returns {void}
|
|
277
|
+
*/
|
|
278
|
+
function checkCanary() {
|
|
279
|
+
if (!canaryEnabled) {
|
|
280
|
+
state.canary = { state: 'absent', reason: '金丝雀已禁用' }
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
const stored = readJson(baselineFile)
|
|
284
|
+
const fingerprint = typeof stored?.canary?.sha256 === 'string' ? stored.canary.sha256 : ''
|
|
285
|
+
if (fingerprint === '') {
|
|
286
|
+
state.canary = { state: 'absent', reason: '基线中没有金丝雀指纹(下次激活会写入)' }
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
if (!existsSync(canaryFile)) {
|
|
290
|
+
state.canary = { state: 'tampered', reason: '金丝雀文件缺失' }
|
|
291
|
+
alert('金丝雀文件缺失:Harness 主目录可能被批量删除', 'VG-INT-03')
|
|
292
|
+
return
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const digest = sha256(readFileSync(canaryFile, 'utf8'))
|
|
296
|
+
if (digest !== fingerprint) {
|
|
297
|
+
state.canary = { state: 'tampered', reason: '金丝雀内容被改写' }
|
|
298
|
+
alert('金丝雀文件内容被改写:本插件保护的状态目录可能被篡改', 'VG-INT-03')
|
|
299
|
+
} else {
|
|
300
|
+
state.canary = { state: 'ok', reason: null }
|
|
301
|
+
}
|
|
302
|
+
} catch (error) {
|
|
303
|
+
state.canary = { state: 'error', reason: error instanceof Error ? error.message : String(error) }
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** @returns {void} */
|
|
308
|
+
function verifySignature() {
|
|
309
|
+
if (!config?.integrity?.signatureEnabled) {
|
|
310
|
+
state.signature = { state: 'disabled', reason: null }
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
const keyInput = typeof config?.integrity?.publicKeyPem === 'string' ? config.integrity.publicKeyPem.trim() : ''
|
|
314
|
+
if (keyInput === '') {
|
|
315
|
+
state.signature = { state: 'unverified', reason: '未配置公钥' }
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
let publicKeyPem = keyInput
|
|
319
|
+
if (!keyInput.includes('BEGIN PUBLIC KEY') && existsSync(keyInput)) {
|
|
320
|
+
try {
|
|
321
|
+
publicKeyPem = readFileSync(keyInput, 'utf8')
|
|
322
|
+
} catch (error) {
|
|
323
|
+
state.signature = { state: 'failed', reason: `无法读取公钥:${String(error)}` }
|
|
324
|
+
return
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const signaturePath = typeof config?.integrity?.signatureFile === 'string' && config.integrity.signatureFile.trim() !== ''
|
|
328
|
+
? (config.integrity.signatureFile.startsWith('/') || /^[A-Za-z]:[\\/]/.test(config.integrity.signatureFile)
|
|
329
|
+
? config.integrity.signatureFile
|
|
330
|
+
: join(pluginDir, config.integrity.signatureFile))
|
|
331
|
+
: join(pluginDir, 'baseline.sig')
|
|
332
|
+
if (!existsSync(signaturePath)) {
|
|
333
|
+
state.signature = { state: 'failed', reason: `签名文件不存在:${signaturePath}` }
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
if (!existsSync(baselineFile)) {
|
|
337
|
+
state.signature = { state: 'unverified', reason: '基线文件不存在' }
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
const data = readFileSync(baselineFile)
|
|
342
|
+
const signature = readFileSync(signaturePath)
|
|
343
|
+
const key = createPublicKey(publicKeyPem)
|
|
344
|
+
const ok = cryptoVerify(null, data, key, signature)
|
|
345
|
+
state.signature = ok
|
|
346
|
+
? { state: 'verified', reason: null }
|
|
347
|
+
: { state: 'failed', reason: '签名校验失败:基线文件不是由持有私钥的一方签发的' }
|
|
348
|
+
if (!ok) alert('基线签名校验失败:插件可能被替换', 'VG-INT-02')
|
|
349
|
+
} catch (error) {
|
|
350
|
+
state.signature = { state: 'failed', reason: `签名校验异常:${error instanceof Error ? error.message : String(error)}` }
|
|
351
|
+
alert(`基线签名校验异常:${String(error)}`, 'VG-INT-02')
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** @returns {void} */
|
|
356
|
+
function verifyHeartbeat() {
|
|
357
|
+
if (heartbeats.length === 0) {
|
|
358
|
+
state.heartbeat = { state: 'unchecked', reason: '尚未注册心跳目标' }
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
const broken = heartbeats.filter(target => target?.[HEARTBEAT] !== true)
|
|
362
|
+
if (broken.length > 0) {
|
|
363
|
+
state.heartbeat = { state: 'broken', reason: `${broken.length} 个钩子标记丢失` }
|
|
364
|
+
alert('钩子心跳标记丢失:本插件的 pre-execute/guard 包装器可能被剥离', 'VG-INT-04')
|
|
365
|
+
} else {
|
|
366
|
+
state.heartbeat = { state: 'ok', reason: null }
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Tag a wrapper function so the heartbeat can notice its replacement, and
|
|
372
|
+
* remember it for periodic checks.
|
|
373
|
+
* @template {Function} T
|
|
374
|
+
* @param {T} fn
|
|
375
|
+
* @returns {T}
|
|
376
|
+
*/
|
|
377
|
+
function markHeartbeat(fn) {
|
|
378
|
+
try {
|
|
379
|
+
Object.defineProperty(fn, HEARTBEAT, { value: true, enumerable: false, configurable: false })
|
|
380
|
+
} catch {
|
|
381
|
+
// frozen function: verification will report the missing tag
|
|
382
|
+
}
|
|
383
|
+
heartbeats.push(fn)
|
|
384
|
+
return fn
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Run the periodic checks, throttled so a hook call cannot pay for them.
|
|
389
|
+
* @param {{ force?: boolean, minIntervalMs?: number }} [options]
|
|
390
|
+
* @returns {void}
|
|
391
|
+
*/
|
|
392
|
+
function check(options = {}) {
|
|
393
|
+
if (!enabled) return
|
|
394
|
+
const now = Date.now()
|
|
395
|
+
const minimum = Math.max(1000, Number(options.minIntervalMs ?? 60000))
|
|
396
|
+
if (!options.force && now - lastCheck < minimum) return
|
|
397
|
+
lastCheck = now
|
|
398
|
+
checkBaseline()
|
|
399
|
+
checkCanary()
|
|
400
|
+
verifyHeartbeat()
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** @returns {string} */
|
|
404
|
+
function describe() {
|
|
405
|
+
if (!enabled) return '完整性:已禁用'
|
|
406
|
+
const parts = []
|
|
407
|
+
parts.push(state.baseline.state === 'match'
|
|
408
|
+
? `基线一致(v${state.baseline.version ?? '?'})`
|
|
409
|
+
: state.baseline.state === 'absent'
|
|
410
|
+
? '基线未建立'
|
|
411
|
+
: state.baseline.state === 'drift'
|
|
412
|
+
? `文件漂移 ${state.baseline.changed.length + state.baseline.added.length + state.baseline.missing.length} 项`
|
|
413
|
+
: '基线校验异常')
|
|
414
|
+
parts.push(state.canary.state === 'ok' ? '金丝雀正常' : `金丝雀 ${state.canary.state}${state.canary.reason ? `(${state.canary.reason})` : ''}`)
|
|
415
|
+
if (state.signature.state !== 'disabled') {
|
|
416
|
+
parts.push(`签名 ${state.signature.state}${state.signature.reason ? `(${state.signature.reason})` : ''}`)
|
|
417
|
+
}
|
|
418
|
+
parts.push(state.heartbeat.state === 'ok' ? '心跳正常' : `心跳 ${state.heartbeat.state}`)
|
|
419
|
+
return `完整性:${parts.join(';')}`
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Start the periodic timer. Returns a dispose function; the timer is unref'd so
|
|
424
|
+
* it never keeps a host process alive by itself.
|
|
425
|
+
* @param {number} intervalMs
|
|
426
|
+
* @returns {() => void}
|
|
427
|
+
*/
|
|
428
|
+
function startTimer(intervalMs) {
|
|
429
|
+
if (!enabled) return () => {}
|
|
430
|
+
const timer = setInterval(() => {
|
|
431
|
+
try {
|
|
432
|
+
check({ force: true })
|
|
433
|
+
} catch {
|
|
434
|
+
// a monitoring failure must never crash the host
|
|
435
|
+
}
|
|
436
|
+
}, Math.max(60000, Number(intervalMs) || 1800000))
|
|
437
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
438
|
+
return () => clearInterval(timer)
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// First activation writes the baseline; later activations compare against it.
|
|
442
|
+
if (baselineEnabled) {
|
|
443
|
+
const stored = readJson(baselineFile)
|
|
444
|
+
const recordRebaseline = reason => {
|
|
445
|
+
try {
|
|
446
|
+
options.record?.({
|
|
447
|
+
kind: 'event',
|
|
448
|
+
event: 'rebaseline',
|
|
449
|
+
tool: 'vigil_integrity',
|
|
450
|
+
decision: 'none',
|
|
451
|
+
ruleIds: ['VG-INT-00'],
|
|
452
|
+
reason,
|
|
453
|
+
})
|
|
454
|
+
} catch {
|
|
455
|
+
// an audit failure must not block the baseline repair
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (!stored || typeof stored !== 'object') {
|
|
459
|
+
writeBaseline()
|
|
460
|
+
checkCanary()
|
|
461
|
+
} else if (typeof stored.version !== 'string' || stored.version !== packageVersion()) {
|
|
462
|
+
// A version change is a deployment act (upgrade), not tampering: rebuild
|
|
463
|
+
// it, but leave an audit trail so "edit files + bump version" is visible.
|
|
464
|
+
recordRebaseline(`版本变化(${stored.version} → ${packageVersion()}),自动重建完整性基线`)
|
|
465
|
+
writeBaseline(stored)
|
|
466
|
+
checkCanary()
|
|
467
|
+
} else if (typeof stored.root !== 'string' || stored.root !== pluginDir) {
|
|
468
|
+
// The package was installed from a different path: the old baseline
|
|
469
|
+
// describes another directory and would report every file as missing.
|
|
470
|
+
recordRebaseline(`安装路径变化(${stored.root} → ${pluginDir}),自动重建完整性基线`)
|
|
471
|
+
writeBaseline(stored)
|
|
472
|
+
checkCanary()
|
|
473
|
+
} else {
|
|
474
|
+
checkBaseline()
|
|
475
|
+
checkCanary()
|
|
476
|
+
verifySignature()
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return {
|
|
481
|
+
enabled,
|
|
482
|
+
pluginDir,
|
|
483
|
+
state,
|
|
484
|
+
get alerts() {
|
|
485
|
+
return [...alerts]
|
|
486
|
+
},
|
|
487
|
+
check,
|
|
488
|
+
markHeartbeat,
|
|
489
|
+
verifyHeartbeat,
|
|
490
|
+
writeBaseline,
|
|
491
|
+
startTimer,
|
|
492
|
+
describe,
|
|
493
|
+
/** @returns {{ ok: boolean, version: string, files: number, error?: string }} */
|
|
494
|
+
rebaseline() {
|
|
495
|
+
const result = writeBaseline()
|
|
496
|
+
checkBaseline()
|
|
497
|
+
checkCanary()
|
|
498
|
+
verifySignature()
|
|
499
|
+
return result
|
|
500
|
+
},
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** @typedef {ReturnType<typeof createIntegrity>} IntegrityMonitor */
|
|
505
|
+
|
|
506
|
+
/** @returns {string} current user's home (exposed for status output) */
|
|
507
|
+
export function integrityHome() {
|
|
508
|
+
return getHomeDir()
|
|
509
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live-configuration helpers.
|
|
3
|
+
*
|
|
4
|
+
* With the declarative `Config` schema, `apply(ctx, config)` receives a tree in
|
|
5
|
+
* which volatile leaves are {@link import('@deepseek-ai/cosmokit').Volatile}
|
|
6
|
+
* references (`{ get(): value }`) rather than plain values. dsh-vigil needs:
|
|
7
|
+
*
|
|
8
|
+
* - a plain snapshot for its own validation/defaulting (`resolveConfig`), and
|
|
9
|
+
* - a cheap fingerprint to notice that a Settings save changed something, so
|
|
10
|
+
* the runtime can be rebuilt without a plugin restart.
|
|
11
|
+
*
|
|
12
|
+
* Both are duck-typed here instead of importing `cosmokit`: a volatile reference
|
|
13
|
+
* is exactly "an object whose `get` is a function", and no legitimate plugin
|
|
14
|
+
* option in this package is such an object. Keeping the check local means the
|
|
15
|
+
* module stays importable from unit tests and the package keeps one fewer
|
|
16
|
+
* runtime dependency.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-vigil/live-config
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Whether a value is a volatile configuration reference.
|
|
23
|
+
* @param {unknown} value
|
|
24
|
+
* @returns {boolean}
|
|
25
|
+
*/
|
|
26
|
+
export function isVolatileRef(value) {
|
|
27
|
+
return typeof value === 'object'
|
|
28
|
+
&& value !== null
|
|
29
|
+
&& !Array.isArray(value)
|
|
30
|
+
&& typeof (/** @type {{ get?: unknown }} */ (value).get) === 'function'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Deep-copy a live Config tree into plain JSON-shaped values.
|
|
35
|
+
* Volatile references are resolved through `get()`; arrays and plain objects are
|
|
36
|
+
* walked; everything else is returned as-is.
|
|
37
|
+
* @param {unknown} value
|
|
38
|
+
* @returns {any}
|
|
39
|
+
*/
|
|
40
|
+
export function snapshotConfig(value) {
|
|
41
|
+
if (isVolatileRef(value)) {
|
|
42
|
+
try {
|
|
43
|
+
return snapshotConfig(/** @type {{ get: () => unknown }} */ (value).get())
|
|
44
|
+
} catch {
|
|
45
|
+
// A reference that throws while reading is treated as absent; the caller's
|
|
46
|
+
// validation then restores the documented default instead of crashing.
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (Array.isArray(value)) return value.map(item => snapshotConfig(item))
|
|
51
|
+
if (value !== null && typeof value === 'object') {
|
|
52
|
+
const prototype = Object.getPrototypeOf(value)
|
|
53
|
+
if (prototype !== Object.prototype && prototype !== null) return value
|
|
54
|
+
/** @type {Record<string, unknown>} */
|
|
55
|
+
const out = {}
|
|
56
|
+
for (const [key, child] of Object.entries(value)) {
|
|
57
|
+
const snapshot = snapshotConfig(child)
|
|
58
|
+
if (snapshot !== undefined) out[key] = snapshot
|
|
59
|
+
}
|
|
60
|
+
return out
|
|
61
|
+
}
|
|
62
|
+
return value
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Stable string used to detect a changed effective configuration.
|
|
67
|
+
* The snapshot is JSON-shaped by construction, so `JSON.stringify` order is
|
|
68
|
+
* stable for the shapes this plugin declares.
|
|
69
|
+
* @param {unknown} snapshot
|
|
70
|
+
* @returns {string}
|
|
71
|
+
*/
|
|
72
|
+
export function configFingerprint(snapshot) {
|
|
73
|
+
try {
|
|
74
|
+
return JSON.stringify(snapshot ?? {})
|
|
75
|
+
} catch {
|
|
76
|
+
return ''
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Whether a runtime rebuild is required for a new snapshot.
|
|
82
|
+
* @param {string} previous fingerprint of the running runtime
|
|
83
|
+
* @param {unknown} nextSnapshot fresh snapshot
|
|
84
|
+
* @returns {boolean}
|
|
85
|
+
*/
|
|
86
|
+
export function configChanged(previous, nextSnapshot) {
|
|
87
|
+
return previous !== configFingerprint(nextSnapshot)
|
|
88
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authenticated endpoint for the two quarantine housekeeping actions the audit
|
|
3
|
+
* dialog offers:
|
|
4
|
+
*
|
|
5
|
+
* POST /api/dsh-vigil/quarantine { action: 'expire' }
|
|
6
|
+
* POST /api/dsh-vigil/quarantine { action: 'purge-all', confirm: true }
|
|
7
|
+
*
|
|
8
|
+
* `purge-all` destroys the backup copies, so it requires an explicit
|
|
9
|
+
* `confirm: true` from the page's two-step button. Both answers include a fresh
|
|
10
|
+
* `quarantineView()` so the UI can show the new size immediately.
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-vigil/quarantine-route
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { quarantineView } from './quarantine-view.js'
|
|
16
|
+
|
|
17
|
+
/** Authenticated browser Fetch path for quarantine housekeeping. */
|
|
18
|
+
export const QUARANTINE_ROUTE_PATH = '/api/dsh-vigil/quarantine'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {{ getQuarantine: () => any }} deps
|
|
22
|
+
* @returns {{ path: string, methods: Array<'POST'>, requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
|
|
23
|
+
*/
|
|
24
|
+
export function createQuarantineRoute(deps) {
|
|
25
|
+
const headers = {
|
|
26
|
+
'content-type': 'application/json; charset=utf-8',
|
|
27
|
+
'cache-control': 'no-store',
|
|
28
|
+
'x-content-type-options': 'nosniff',
|
|
29
|
+
}
|
|
30
|
+
const reply = (status, payload) => new Response(JSON.stringify(payload), { status, headers })
|
|
31
|
+
return {
|
|
32
|
+
path: QUARANTINE_ROUTE_PATH,
|
|
33
|
+
methods: ['POST'],
|
|
34
|
+
requestBody: 'buffered',
|
|
35
|
+
fetch: async request => {
|
|
36
|
+
let body
|
|
37
|
+
try {
|
|
38
|
+
body = await request.json()
|
|
39
|
+
} catch {
|
|
40
|
+
return reply(400, { ok: false, error: 'invalid-json' })
|
|
41
|
+
}
|
|
42
|
+
const quarantine = deps.getQuarantine?.()
|
|
43
|
+
if (!quarantine) return reply(503, { ok: false, error: 'unavailable' })
|
|
44
|
+
const action = typeof body?.action === 'string' ? body.action : ''
|
|
45
|
+
if (action === 'expire') {
|
|
46
|
+
let expired = 0
|
|
47
|
+
try {
|
|
48
|
+
const result = typeof quarantine.expire === 'function' ? quarantine.expire() : { expired: [] }
|
|
49
|
+
expired = Array.isArray(result?.expired) ? result.expired.length : 0
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return reply(500, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
52
|
+
}
|
|
53
|
+
return reply(200, { ok: true, action, expired, quarantine: quarantineView(quarantine) })
|
|
54
|
+
}
|
|
55
|
+
if (action === 'purge-all') {
|
|
56
|
+
if (body?.confirm !== true) return reply(400, { ok: false, error: 'confirm-required' })
|
|
57
|
+
const entries = typeof quarantine.entries === 'function' ? quarantine.entries() : []
|
|
58
|
+
let removed = 0
|
|
59
|
+
let failed = 0
|
|
60
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
61
|
+
try {
|
|
62
|
+
const result = quarantine.purge(entry.id, { confirm: true })
|
|
63
|
+
if (result?.ok) removed += 1
|
|
64
|
+
else failed += 1
|
|
65
|
+
} catch {
|
|
66
|
+
failed += 1
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return reply(200, { ok: true, action, removed, failed, quarantine: quarantineView(quarantine) })
|
|
70
|
+
}
|
|
71
|
+
return reply(400, { ok: false, error: 'invalid-action' })
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
}
|