dsh-vigil 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote rule-pack updates.
|
|
3
|
+
*
|
|
4
|
+
* Rule packs are data (`rules/*.yaml`), so an operator can host a newer pack
|
|
5
|
+
* outside the plugin and let dsh-vigil pick it up without a release. The
|
|
6
|
+
* manifest contract is deliberately tiny:
|
|
7
|
+
*
|
|
8
|
+
* {
|
|
9
|
+
* "version": "2026.11.21",
|
|
10
|
+
* "files": {
|
|
11
|
+
* "sentinel.yaml": "https://example.com/rules/sentinel.yaml",
|
|
12
|
+
* "audit.yaml": "https://example.com/rules/audit.yaml"
|
|
13
|
+
* }
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* Safety rules:
|
|
17
|
+
* - HTTPS only (loopback HTTP is allowed for tests);
|
|
18
|
+
* - bounded sizes, bounded file count, `.yaml`/`.yml` basenames only;
|
|
19
|
+
* - every downloaded file is validated by loading it through the rule-pack
|
|
20
|
+
* loader before it becomes active; a failure restores the previous files;
|
|
21
|
+
* - the hash lock is refreshed only for a successful update, so `vigil_rules
|
|
22
|
+
* verify` keeps describing what is actually loaded.
|
|
23
|
+
*
|
|
24
|
+
* @module rules/update
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
28
|
+
import { basename, dirname, join } from 'node:path'
|
|
29
|
+
import { parseYaml } from './yaml.js'
|
|
30
|
+
import { pinRulePack, reloadRulePack, verifyRulePack } from './pack.js'
|
|
31
|
+
|
|
32
|
+
/** Authenticated browser fetch path for rule-pack updates. */
|
|
33
|
+
export const RULES_UPDATE_PATH = '/api/dsh-vigil/rules-update'
|
|
34
|
+
|
|
35
|
+
const MAX_MANIFEST_BYTES = 256 * 1024
|
|
36
|
+
const MAX_PACK_BYTES = 512 * 1024
|
|
37
|
+
const MAX_PACK_FILES = 8
|
|
38
|
+
const FETCH_TIMEOUT_MS = 8000
|
|
39
|
+
|
|
40
|
+
const SOURCE_SCHEME = /^https:\/\//i
|
|
41
|
+
const LOOPBACK_HTTP = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//i
|
|
42
|
+
const PACK_NAME = /^[A-Za-z0-9._-]+\.ya?ml$/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} url
|
|
46
|
+
* @returns {{ ok: true } | { ok: false, error: string }}
|
|
47
|
+
*/
|
|
48
|
+
export function validateRulesSource(url) {
|
|
49
|
+
if (typeof url !== 'string' || url.trim() === '') return { ok: false, error: '规则库更新源为空' }
|
|
50
|
+
const value = url.trim()
|
|
51
|
+
if (SOURCE_SCHEME.test(value) || LOOPBACK_HTTP.test(value)) return { ok: true }
|
|
52
|
+
return { ok: false, error: '规则库更新源必须是 https:// 地址(测试可用 127.0.0.1 的 http)' }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {any} value
|
|
57
|
+
* @returns {{ ok: boolean, manifest?: { version: string, files: Record<string,string> }, error?: string }}
|
|
58
|
+
*/
|
|
59
|
+
export function parseManifest(value) {
|
|
60
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, error: '清单必须是 JSON 对象' }
|
|
61
|
+
const version = typeof value.version === 'string' ? value.version.trim() : ''
|
|
62
|
+
if (version === '' || version.length > 120) return { ok: false, error: '清单缺少合法的 version' }
|
|
63
|
+
const files = value.files
|
|
64
|
+
if (!files || typeof files !== 'object' || Array.isArray(files)) return { ok: false, error: '清单缺少 files 对象' }
|
|
65
|
+
const entries = Object.entries(files)
|
|
66
|
+
if (entries.length === 0 || entries.length > MAX_PACK_FILES) {
|
|
67
|
+
return { ok: false, error: `清单必须包含 1–${MAX_PACK_FILES} 个规则文件` }
|
|
68
|
+
}
|
|
69
|
+
/** @type {Record<string,string>} */
|
|
70
|
+
const clean = {}
|
|
71
|
+
for (const [name, url] of entries) {
|
|
72
|
+
if (!PACK_NAME.test(name)) return { ok: false, error: `规则文件名不合法:${name}` }
|
|
73
|
+
if (typeof url !== 'string') return { ok: false, error: `${name} 的地址不是字符串` }
|
|
74
|
+
const source = validateRulesSource(url)
|
|
75
|
+
if (!source.ok) return { ok: false, error: `${name}:${source.error}` }
|
|
76
|
+
clean[name] = url.trim()
|
|
77
|
+
}
|
|
78
|
+
return { ok: true, manifest: { version, files: clean } }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Fetch one URL with a byte cap, timeout and redirect policy.
|
|
83
|
+
* @param {string} url
|
|
84
|
+
* @param {{ maxBytes: number, fetchImpl?: typeof fetch, timeoutMs?: number }} options
|
|
85
|
+
* @returns {Promise<{ ok: true, text: string } | { ok: false, error: string }>}
|
|
86
|
+
*/
|
|
87
|
+
export async function fetchTextCapped(url, options) {
|
|
88
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch
|
|
89
|
+
if (typeof fetchImpl !== 'function') return { ok: false, error: '当前运行时没有 fetch' }
|
|
90
|
+
const controller = new AbortController()
|
|
91
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS)
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetchImpl(url, {
|
|
94
|
+
signal: controller.signal,
|
|
95
|
+
redirect: 'follow',
|
|
96
|
+
headers: { accept: 'application/json, text/yaml, text/plain, */*' },
|
|
97
|
+
})
|
|
98
|
+
if (!response.ok) return { ok: false, error: `${url} → HTTP ${response.status}` }
|
|
99
|
+
const length = Number(response.headers?.get?.('content-length'))
|
|
100
|
+
if (Number.isFinite(length) && length > options.maxBytes) {
|
|
101
|
+
return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
|
|
102
|
+
}
|
|
103
|
+
const text = await response.text()
|
|
104
|
+
if (Buffer.byteLength(text, 'utf8') > options.maxBytes) {
|
|
105
|
+
return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
|
|
106
|
+
}
|
|
107
|
+
return { ok: true, text }
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
110
|
+
return { ok: false, error: `${url} 请求失败:${reason}` }
|
|
111
|
+
} finally {
|
|
112
|
+
clearTimeout(timer)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @param {string} versionFile */
|
|
117
|
+
export function readRulesVersion(versionFile) {
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(readFileSync(versionFile, 'utf8'))
|
|
120
|
+
return parsed && typeof parsed === 'object' ? parsed : null
|
|
121
|
+
} catch {
|
|
122
|
+
return null
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @param {string} versionFile @param {any} value */
|
|
127
|
+
function writeRulesVersion(versionFile, value) {
|
|
128
|
+
mkdirSync(dirname(versionFile), { recursive: true })
|
|
129
|
+
const tmp = `${versionFile}.tmp`
|
|
130
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`)
|
|
131
|
+
renameSync(tmp, versionFile)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Rewrite a manifest file URL to the mirror matching the manifest source.
|
|
136
|
+
* The shipped manifest lists jsDelivr URLs; when the operator selects the
|
|
137
|
+
* GitHub raw manifest we must download the rule files from GitHub too,
|
|
138
|
+
* otherwise a CDN-cached stale file would be installed under a newer version.
|
|
139
|
+
* The reverse mapping keeps a custom jsDelivr manifest working when the
|
|
140
|
+
* manifest itself lists GitHub raw URLs.
|
|
141
|
+
*
|
|
142
|
+
* @param {string} fileUrl
|
|
143
|
+
* @param {string} sourceUrl
|
|
144
|
+
* @returns {string}
|
|
145
|
+
*/
|
|
146
|
+
export function resolveRuleFileUrl(fileUrl, sourceUrl) {
|
|
147
|
+
const githubRaw = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/.exec(fileUrl)
|
|
148
|
+
const jsdelivr = /^https:\/\/cdn\.jsdelivr\.net\/gh\/([^/@]+)\/([^@/]+)@([^/]+)\/(.+)$/.exec(fileUrl)
|
|
149
|
+
let host = ''
|
|
150
|
+
try {
|
|
151
|
+
host = new URL(sourceUrl).hostname
|
|
152
|
+
} catch {
|
|
153
|
+
return fileUrl
|
|
154
|
+
}
|
|
155
|
+
if (host === 'raw.githubusercontent.com' && jsdelivr) {
|
|
156
|
+
return `https://raw.githubusercontent.com/${jsdelivr[1]}/${jsdelivr[2]}/${jsdelivr[3]}/${jsdelivr[4]}`
|
|
157
|
+
}
|
|
158
|
+
if (host === 'cdn.jsdelivr.net' && githubRaw) {
|
|
159
|
+
return `https://cdn.jsdelivr.net/gh/${githubRaw[1]}/${githubRaw[2]}@${githubRaw[3]}/${githubRaw[4]}`
|
|
160
|
+
}
|
|
161
|
+
return fileUrl
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Download a manifest and compare it with the locally installed version.
|
|
166
|
+
* @param {{ source: string, versionFile: string, fetchImpl?: typeof fetch }} options
|
|
167
|
+
*/
|
|
168
|
+
export async function checkRulesUpdate(options) {
|
|
169
|
+
const source = validateRulesSource(options.source)
|
|
170
|
+
if (!source.ok) return { ok: false, error: source.error }
|
|
171
|
+
const manifestResult = await fetchTextCapped(options.source, {
|
|
172
|
+
maxBytes: MAX_MANIFEST_BYTES,
|
|
173
|
+
fetchImpl: options.fetchImpl,
|
|
174
|
+
})
|
|
175
|
+
if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
|
|
176
|
+
let parsed
|
|
177
|
+
try {
|
|
178
|
+
parsed = JSON.parse(manifestResult.text)
|
|
179
|
+
} catch {
|
|
180
|
+
return { ok: false, error: '清单不是合法 JSON' }
|
|
181
|
+
}
|
|
182
|
+
const manifest = parseManifest(parsed)
|
|
183
|
+
if (!manifest.ok) return { ok: false, error: manifest.error }
|
|
184
|
+
const current = readRulesVersion(options.versionFile)
|
|
185
|
+
const currentVersion = typeof current?.version === 'string' ? current.version : null
|
|
186
|
+
return {
|
|
187
|
+
ok: true,
|
|
188
|
+
currentVersion,
|
|
189
|
+
latestVersion: manifest.manifest.version,
|
|
190
|
+
available: currentVersion !== manifest.manifest.version,
|
|
191
|
+
files: Object.keys(manifest.manifest.files),
|
|
192
|
+
source: options.source,
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Download, validate and install the manifest's rule files.
|
|
198
|
+
*
|
|
199
|
+
* @param {{
|
|
200
|
+
* source: string,
|
|
201
|
+
* targetDir: string,
|
|
202
|
+
* versionFile: string,
|
|
203
|
+
* lockPath: string,
|
|
204
|
+
* fetchImpl?: typeof fetch,
|
|
205
|
+
* logger?: { warn?: (message: string) => void },
|
|
206
|
+
* }} options
|
|
207
|
+
* @returns {Promise<{ ok: boolean, version?: string, files?: string[], error?: string, warnings?: string[] }>}
|
|
208
|
+
*/
|
|
209
|
+
export async function applyRulesUpdate(options) {
|
|
210
|
+
const source = validateRulesSource(options.source)
|
|
211
|
+
if (!source.ok) return { ok: false, error: source.error }
|
|
212
|
+
const manifestResult = await fetchTextCapped(options.source, { maxBytes: MAX_MANIFEST_BYTES, fetchImpl: options.fetchImpl })
|
|
213
|
+
if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
|
|
214
|
+
let raw
|
|
215
|
+
try {
|
|
216
|
+
raw = JSON.parse(manifestResult.text)
|
|
217
|
+
} catch {
|
|
218
|
+
return { ok: false, error: '清单不是合法 JSON' }
|
|
219
|
+
}
|
|
220
|
+
const parsed = parseManifest(raw)
|
|
221
|
+
if (!parsed.ok) return { ok: false, error: parsed.error }
|
|
222
|
+
const { version, files } = parsed.manifest
|
|
223
|
+
|
|
224
|
+
// Download and validate everything before touching the live directory.
|
|
225
|
+
/** @type {Record<string,string>} */
|
|
226
|
+
const downloaded = {}
|
|
227
|
+
for (const [name, fileUrl] of Object.entries(files)) {
|
|
228
|
+
const result = await fetchTextCapped(resolveRuleFileUrl(fileUrl, options.source), { maxBytes: MAX_PACK_BYTES, fetchImpl: options.fetchImpl })
|
|
229
|
+
if (!result.ok) return { ok: false, error: result.error }
|
|
230
|
+
try {
|
|
231
|
+
const document = parseYaml(result.text)
|
|
232
|
+
if (!document || typeof document !== 'object' || Array.isArray(document)) {
|
|
233
|
+
return { ok: false, error: `${name} 不是 YAML 对象` }
|
|
234
|
+
}
|
|
235
|
+
downloaded[name] = result.text
|
|
236
|
+
} catch (error) {
|
|
237
|
+
return { ok: false, error: `${name} 解析失败:${error instanceof Error ? error.message : String(error)}` }
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
mkdirSync(options.targetDir, { recursive: true })
|
|
242
|
+
/** @type {Record<string, string|null>} */
|
|
243
|
+
const before = {}
|
|
244
|
+
for (const name of Object.keys(downloaded)) {
|
|
245
|
+
const file = join(options.targetDir, name)
|
|
246
|
+
try {
|
|
247
|
+
before[name] = readFileSync(file, 'utf8')
|
|
248
|
+
} catch {
|
|
249
|
+
before[name] = null
|
|
250
|
+
}
|
|
251
|
+
const tmp = `${file}.tmp`
|
|
252
|
+
writeFileSync(tmp, downloaded[name])
|
|
253
|
+
renameSync(tmp, file)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Load through the real loader *without* the lock first: the new files are
|
|
257
|
+
// expected to differ from the pinned hashes, and the lock check would reject
|
|
258
|
+
// them before parsing. A pack that fails to compile is rolled back below.
|
|
259
|
+
const loaded = reloadRulePack({ externalDir: options.targetDir, logger: options.logger })
|
|
260
|
+
const failed = loaded.warnings.filter(warning => Object.keys(downloaded).some(name => warning.includes(basename(name))))
|
|
261
|
+
if (failed.length > 0) {
|
|
262
|
+
for (const [name, content] of Object.entries(before)) {
|
|
263
|
+
const file = join(options.targetDir, name)
|
|
264
|
+
try {
|
|
265
|
+
if (content === null) writeFileSync(file, '')
|
|
266
|
+
else writeFileSync(file, content)
|
|
267
|
+
} catch {
|
|
268
|
+
// best effort restore
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
|
|
272
|
+
return { ok: false, error: `规则校验失败,已回滚:${failed[0]}`, warnings: failed }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const pinned = pinRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
|
|
276
|
+
if (!pinned.ok) return { ok: false, error: pinned.error ?? '无法更新规则锁' }
|
|
277
|
+
// Re-apply with the fresh lock so the loaded pack and the lock agree.
|
|
278
|
+
reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
|
|
279
|
+
writeRulesVersion(options.versionFile, {
|
|
280
|
+
source: options.source,
|
|
281
|
+
version,
|
|
282
|
+
updatedAt: new Date().toISOString(),
|
|
283
|
+
files: Object.keys(downloaded),
|
|
284
|
+
})
|
|
285
|
+
return { ok: true, version, files: Object.keys(downloaded) }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Compare the active files with the hash lock (used by the status route).
|
|
290
|
+
* @param {{ targetDir: string, lockPath: string }} options
|
|
291
|
+
*/
|
|
292
|
+
export function rulesDriftState(options) {
|
|
293
|
+
return verifyRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Ensure the target directory exists (updated packs are written there). */
|
|
297
|
+
export function ensureRulesTargetDir(dir) {
|
|
298
|
+
try {
|
|
299
|
+
if (existsSync(dir)) return
|
|
300
|
+
mkdirSync(dir, { recursive: true })
|
|
301
|
+
} catch {
|
|
302
|
+
// the update itself will report the failure
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Authenticated browser route for rule-pack updates.
|
|
308
|
+
*
|
|
309
|
+
* GET /api/dsh-vigil/rules-update last known state (no network)
|
|
310
|
+
* POST /api/dsh-vigil/rules-update { action: 'check' | 'update' }
|
|
311
|
+
*
|
|
312
|
+
* @param {{ getState: () => object, run: (options: { update?: boolean }) => Promise<any>, logger?: any }} deps
|
|
313
|
+
*/
|
|
314
|
+
export function createRulesUpdateRoute(deps) {
|
|
315
|
+
const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
|
|
316
|
+
status,
|
|
317
|
+
headers: {
|
|
318
|
+
'content-type': 'application/json; charset=utf-8',
|
|
319
|
+
'cache-control': 'no-store',
|
|
320
|
+
'x-content-type-options': 'nosniff',
|
|
321
|
+
},
|
|
322
|
+
})
|
|
323
|
+
return {
|
|
324
|
+
path: RULES_UPDATE_PATH,
|
|
325
|
+
methods: ['GET', 'POST'],
|
|
326
|
+
requestBody: 'buffered',
|
|
327
|
+
fetch: async request => {
|
|
328
|
+
const method = typeof request?.method === 'string' ? request.method.toUpperCase() : 'GET'
|
|
329
|
+
if (method !== 'POST') return json({ ok: true, state: deps.getState?.() ?? null })
|
|
330
|
+
let body
|
|
331
|
+
try {
|
|
332
|
+
body = typeof request.json === 'function' ? await request.json().catch(() => null) : null
|
|
333
|
+
} catch {
|
|
334
|
+
body = null
|
|
335
|
+
}
|
|
336
|
+
const action = body?.action === 'update' ? 'update' : 'check'
|
|
337
|
+
const result = await deps.run({ update: action === 'update' })
|
|
338
|
+
return json({ ok: result.ok !== false, action, ...result }, result.ok === false ? 500 : 200)
|
|
339
|
+
},
|
|
340
|
+
}
|
|
341
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal YAML subset parser for rule packs.
|
|
3
|
+
*
|
|
4
|
+
* Rule packs are data (strings, numbers, booleans, lists of maps). Supporting a
|
|
5
|
+
* full YAML implementation would add a dependency to a plugin that deliberately
|
|
6
|
+
* ships none, so this parser accepts exactly the shape the packs use:
|
|
7
|
+
*
|
|
8
|
+
* schema: 1
|
|
9
|
+
* rules:
|
|
10
|
+
* - id: VG-CRED-01
|
|
11
|
+
* severity: blocker
|
|
12
|
+
* patterns:
|
|
13
|
+
* - re: '\\bAKIA[0-9A-Z]{16}\\b'
|
|
14
|
+
* label: AWS Access Key
|
|
15
|
+
*
|
|
16
|
+
* Supported: nested mappings, block sequences, single/double quoted scalars,
|
|
17
|
+
* booleans, numbers, null, comments and `---` document markers. Not supported:
|
|
18
|
+
* flow collections (`[a, b]`, `{a: b}`), anchors, multi-line block scalars.
|
|
19
|
+
* Anything unsupported throws a `YamlParseError`, and the loader keeps the
|
|
20
|
+
* built-in defaults instead of silently loading a half-parsed pack.
|
|
21
|
+
*
|
|
22
|
+
* @module rules/yaml
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export class YamlParseError extends Error {}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} source
|
|
29
|
+
* @returns {any}
|
|
30
|
+
*/
|
|
31
|
+
export function parseYaml(source) {
|
|
32
|
+
const lines = []
|
|
33
|
+
const rawLines = String(source ?? '').split(/\r?\n/)
|
|
34
|
+
for (let index = 0; index < rawLines.length; index += 1) {
|
|
35
|
+
const raw = rawLines[index]
|
|
36
|
+
const trimmed = raw.trim()
|
|
37
|
+
if (trimmed === '' || trimmed.startsWith('#')) continue
|
|
38
|
+
if (trimmed === '---' || trimmed === '...') continue
|
|
39
|
+
const indent = raw.length - raw.trimStart().length
|
|
40
|
+
if (tabIndented(raw)) throw new YamlParseError(`第 ${index + 1} 行使用制表符缩进`)
|
|
41
|
+
lines.push({ indent, text: trimmed, line: index + 1 })
|
|
42
|
+
}
|
|
43
|
+
let cursor = 0
|
|
44
|
+
|
|
45
|
+
const peek = () => lines[cursor]
|
|
46
|
+
|
|
47
|
+
const parseBlock = indent => {
|
|
48
|
+
const first = peek()
|
|
49
|
+
if (!first || first.indent < indent) return null
|
|
50
|
+
return first.text.startsWith('-') ? parseSequence(first.indent) : parseMapping(first.indent)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const parseSequence = indent => {
|
|
54
|
+
/** @type {any[]} */
|
|
55
|
+
const out = []
|
|
56
|
+
while (cursor < lines.length) {
|
|
57
|
+
const line = lines[cursor]
|
|
58
|
+
if (line.indent !== indent || !line.text.startsWith('-')) break
|
|
59
|
+
if (line.text === '-' || line.text === '- ') {
|
|
60
|
+
cursor += 1
|
|
61
|
+
out.push(parseBlock(indent + 1))
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
const rest = line.text.slice(1).trim()
|
|
65
|
+
const key = keyOf(rest)
|
|
66
|
+
if (key === null) {
|
|
67
|
+
cursor += 1
|
|
68
|
+
out.push(parseScalar(rest, line.line))
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
// `- key: value` starts a mapping item; its remaining keys are indented.
|
|
72
|
+
const item = {}
|
|
73
|
+
const value = valueOf(rest)
|
|
74
|
+
cursor += 1
|
|
75
|
+
if (value === '') {
|
|
76
|
+
const child = parseBlock(indent + 2)
|
|
77
|
+
item[key] = child ?? null
|
|
78
|
+
} else {
|
|
79
|
+
item[key] = parseScalar(value, line.line)
|
|
80
|
+
}
|
|
81
|
+
while (cursor < lines.length && lines[cursor].indent > indent) {
|
|
82
|
+
const nested = lines[cursor]
|
|
83
|
+
if (nested.indent !== indent + 2) throw new YamlParseError(`第 ${nested.line} 行缩进不一致`)
|
|
84
|
+
mergeMappingEntry(item, nested, () => {
|
|
85
|
+
cursor += 1
|
|
86
|
+
}, () => parseBlock(indent + 2))
|
|
87
|
+
}
|
|
88
|
+
out.push(item)
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const parseMapping = indent => {
|
|
94
|
+
/** @type {Record<string, any>} */
|
|
95
|
+
const out = {}
|
|
96
|
+
while (cursor < lines.length && lines[cursor].indent === indent) {
|
|
97
|
+
const line = lines[cursor]
|
|
98
|
+
if (line.text.startsWith('-')) break
|
|
99
|
+
const key = keyOf(line.text)
|
|
100
|
+
if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
|
|
101
|
+
const value = valueOf(line.text)
|
|
102
|
+
cursor += 1
|
|
103
|
+
if (value === '') {
|
|
104
|
+
const child = parseBlock(indent + 1)
|
|
105
|
+
out[key] = child ?? null
|
|
106
|
+
} else {
|
|
107
|
+
out[key] = parseScalar(value, line.line)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const mergeMappingEntry = (target, line, advance, parseNested) => {
|
|
114
|
+
const key = keyOf(line.text)
|
|
115
|
+
if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
|
|
116
|
+
const value = valueOf(line.text)
|
|
117
|
+
if (value === '') {
|
|
118
|
+
advance()
|
|
119
|
+
target[key] = parseNested() ?? null
|
|
120
|
+
} else {
|
|
121
|
+
// Consume exactly this line. The previous version called a closure that
|
|
122
|
+
// also parsed the next block, which silently dropped the third and later
|
|
123
|
+
// keys of every sequence item (`source`/`flags` survived, `label` did not).
|
|
124
|
+
advance()
|
|
125
|
+
target[key] = parseScalar(value, line.line)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const result = parseBlock(0)
|
|
130
|
+
if (cursor < lines.length) throw new YamlParseError(`第 ${lines[cursor].line} 行无法解析`)
|
|
131
|
+
return result
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** @param {string} raw */
|
|
135
|
+
function tabIndented(raw) {
|
|
136
|
+
return /^\t/.test(raw) || /^ *\t/.test(raw)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} text
|
|
141
|
+
* @returns {string|null}
|
|
142
|
+
*/
|
|
143
|
+
function keyOf(text) {
|
|
144
|
+
const match = /^([A-Za-z0-9_.-]+)\s*:(?:\s|$)/.exec(text)
|
|
145
|
+
return match ? match[1] : null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @param {string} text
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
function valueOf(text) {
|
|
153
|
+
const index = text.indexOf(':')
|
|
154
|
+
if (index < 0) return ''
|
|
155
|
+
return text.slice(index + 1).trim()
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* @param {string} value
|
|
160
|
+
* @param {number} line
|
|
161
|
+
* @returns {any}
|
|
162
|
+
*/
|
|
163
|
+
function parseScalar(value, line) {
|
|
164
|
+
const text = value.trim()
|
|
165
|
+
if (text === '') return ''
|
|
166
|
+
if (text.startsWith('[') || text.startsWith('{')) {
|
|
167
|
+
throw new YamlParseError(`第 ${line} 行不支持流式集合,请用缩进列表`)
|
|
168
|
+
}
|
|
169
|
+
if (text.startsWith("'")) {
|
|
170
|
+
if (!text.endsWith("'") || text.length < 2) throw new YamlParseError(`第 ${line} 行单引号未闭合`)
|
|
171
|
+
return text.slice(1, -1).replace(/''/g, "'")
|
|
172
|
+
}
|
|
173
|
+
if (text.startsWith('"')) {
|
|
174
|
+
if (!text.endsWith('"') || text.length < 2) throw new YamlParseError(`第 ${line} 行双引号未闭合`)
|
|
175
|
+
try {
|
|
176
|
+
return JSON.parse(text)
|
|
177
|
+
} catch {
|
|
178
|
+
throw new YamlParseError(`第 ${line} 行双引号字符串转义无效`)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (text === 'true') return true
|
|
182
|
+
if (text === 'false') return false
|
|
183
|
+
if (text === 'null' || text === '~') return null
|
|
184
|
+
if (/^-?\d+(?:\.\d+)?$/.test(text)) return Number(text)
|
|
185
|
+
return text
|
|
186
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sage maintenance route (browser side).
|
|
3
|
+
*
|
|
4
|
+
* POST /api/dsh-vigil/sage-action { action: 'uninstall' }
|
|
5
|
+
*
|
|
6
|
+
* Only deletes the auto-provisioned engine tree; the settings page first turns
|
|
7
|
+
* `sage.enabled` / `autoUpdate` off so a rebuild cannot immediately re-download it. Installed versions and rule provenance stay in
|
|
8
|
+
* the audit log / provision receipt until the directory is gone.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-vigil/sage-action-route
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { removeProvisionedSage } from './sage-provision.js'
|
|
14
|
+
|
|
15
|
+
/** Authenticated browser fetch path for Sage maintenance. */
|
|
16
|
+
export const SAGE_ACTION_PATH = '/api/dsh-vigil/sage-action'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{ getRuntime: () => any, rebuild?: (reason: string) => Promise<void>|void }} deps
|
|
20
|
+
* @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
|
|
21
|
+
*/
|
|
22
|
+
export function createSageActionRoute(deps) {
|
|
23
|
+
return {
|
|
24
|
+
path: SAGE_ACTION_PATH,
|
|
25
|
+
methods: ['POST'],
|
|
26
|
+
requestBody: 'buffered',
|
|
27
|
+
fetch: async request => {
|
|
28
|
+
/** @type {{ ok: boolean, [key: string]: unknown }} */
|
|
29
|
+
let payload
|
|
30
|
+
let status = 200
|
|
31
|
+
try {
|
|
32
|
+
const body = typeof request.json === 'function' ? await request.json().catch(() => null) : null
|
|
33
|
+
if (body?.action !== 'uninstall') {
|
|
34
|
+
payload = { ok: false, error: '未知操作' }
|
|
35
|
+
status = 400
|
|
36
|
+
} else {
|
|
37
|
+
const runtime = deps.getRuntime()
|
|
38
|
+
const result = removeProvisionedSage(runtime?.config ?? {})
|
|
39
|
+
if (result.ok) {
|
|
40
|
+
try {
|
|
41
|
+
await deps.rebuild?.('sage-uninstalled')
|
|
42
|
+
} catch {
|
|
43
|
+
// the files are gone; a failed rebuild leaves the old generation in place
|
|
44
|
+
}
|
|
45
|
+
payload = { ok: true, action: 'uninstall', dir: result.dir, describe: runtime?.sage?.describe?.() ?? '' }
|
|
46
|
+
} else {
|
|
47
|
+
payload = { ok: false, action: 'uninstall', dir: result.dir, error: result.error }
|
|
48
|
+
status = 500
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
} catch (error) {
|
|
52
|
+
payload = { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
53
|
+
status = 500
|
|
54
|
+
}
|
|
55
|
+
const headers = {
|
|
56
|
+
'content-type': 'application/json; charset=utf-8',
|
|
57
|
+
'cache-control': 'no-store',
|
|
58
|
+
'x-content-type-options': 'nosniff',
|
|
59
|
+
}
|
|
60
|
+
return new Response(`${JSON.stringify(payload)}\n`, { status, headers })
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
}
|