@twinsearth/dsh-fang 3.1.0 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/client.js +1511 -1
  2. package/cordis.patch.yml +9 -0
  3. package/package.json +7 -3
  4. package/src/compose.mjs +4 -1
  5. package/src/kernel/paths.mjs +9 -1
  6. package/src/kernel/role.mjs +1 -0
  7. package/src/kernel/types.mjs +5 -1
  8. package/src/lib/ai-secret-store.mjs +202 -0
  9. package/src/lib/boot-guard.mjs +182 -0
  10. package/src/lib/business-producers.mjs +109 -0
  11. package/src/lib/compat.mjs +1 -1
  12. package/src/lib/composer-journal.mjs +8 -0
  13. package/src/lib/decision-events.mjs +129 -0
  14. package/src/lib/decision-ingest-client.mjs +41 -0
  15. package/src/lib/decision-outbox.mjs +129 -0
  16. package/src/lib/desktop-launch.mjs +138 -0
  17. package/src/lib/fork-supervision-settings.mjs +58 -0
  18. package/src/lib/mirror-official-source.mjs +93 -0
  19. package/src/lib/mirror.mjs +10 -3
  20. package/src/lib/producer-contract.mjs +162 -0
  21. package/src/lib/restart-contract.mjs +650 -0
  22. package/src/lib/rule-registry.mjs +69 -0
  23. package/src/lib/ssrf-guard.mjs +170 -0
  24. package/src/lib/umbrella.mjs +143 -18
  25. package/src/plugins/adapter.mjs +31 -2
  26. package/src/plugins/approver.mjs +423 -40
  27. package/src/plugins/decision-center.mjs +2255 -0
  28. package/src/plugins/forker.mjs +20 -1
  29. package/src/plugins/healer.mjs +53 -20
  30. package/src/plugins/imports.mjs +48 -0
  31. package/src/plugins/orchestrator.mjs +844 -46
  32. package/src/plugins/restart-guard.mjs +645 -52
  33. package/src/plugins/scorer.mjs +227 -15
  34. package/src/plugins/umbrella.mjs +18 -14
  35. package/tools/boot-guard.mjs +95 -0
  36. package/tools/decision-ingest.mjs +53 -0
  37. package/tools/desktop-launch.mjs +71 -0
  38. package/tools/fangctl.mjs +229 -1
@@ -777,6 +777,23 @@ export function createRuleRegistry(builtinRules = DEFAULT_ACTION_RULES, options
777
777
  lockViolation = true
778
778
  continue
779
779
  }
780
+ if (entry.tags !== undefined) {
781
+ const requiredTags = (base.tags ?? []).filter((tag) => NON_NEGOTIABLE_TAGS.includes(tag))
782
+ const missingTags = requiredTags.filter((tag) => !Array.isArray(entry.tags) || !entry.tags.includes(tag))
783
+ if (missingTags.length > 0) {
784
+ layerErrors.push(`rule "${entry.id}" is non-negotiable; locked tags cannot be removed: ${missingTags.join(',')}`)
785
+ lockViolation = true
786
+ continue
787
+ }
788
+ }
789
+ if (entry.priority !== undefined) {
790
+ const currentPriority = priorities[base.id] ?? defaultPriorities[base.id] ?? 500
791
+ if (entry.priority > currentPriority) {
792
+ layerErrors.push(`rule "${entry.id}" is non-negotiable; priority cannot move later than ${currentPriority}`)
793
+ lockViolation = true
794
+ continue
795
+ }
796
+ }
780
797
  }
781
798
 
782
799
  if (entry.enabled === false) {
@@ -975,6 +992,58 @@ export function loadRuleConfigFile(file) {
975
992
  return { config: validated.config, errors: validated.errors, found: true }
976
993
  }
977
994
 
995
+ export function watchRuleConfigFiles(files, onChange = () => {}, options = {}) {
996
+ const debounceMs = Number(options.debounceMs) > 0 ? Number(options.debounceMs) : 200
997
+ const logger = options.logger ?? null
998
+ const list = [...new Set((Array.isArray(files) ? files : [files])
999
+ .filter((file) => typeof file === 'string' && file.length > 0))]
1000
+ const watchers = []
1001
+ let timer = null
1002
+ let stopped = false
1003
+
1004
+ const schedule = () => {
1005
+ if (stopped) return
1006
+ if (timer !== null) clearTimeout(timer)
1007
+ timer = setTimeout(() => {
1008
+ timer = null
1009
+ if (stopped) return
1010
+ try { onChange() } catch (error) {
1011
+ try { logger?.warn?.(`[umbrella-rules] reload callback failed: ${error?.message ?? error}`) } catch { /* ignore */ }
1012
+ }
1013
+ }, debounceMs)
1014
+ }
1015
+
1016
+ for (const file of list) {
1017
+ try {
1018
+ watchers.push(fs.watch(file, schedule))
1019
+ continue
1020
+ } catch { /* missing file: watch its directory */ }
1021
+ try {
1022
+ const dir = path.dirname(file)
1023
+ const base = path.basename(file)
1024
+ watchers.push(fs.watch(dir, (_event, name) => {
1025
+ if (!name || String(name) === base) schedule()
1026
+ }))
1027
+ } catch (error) {
1028
+ try { logger?.warn?.(`[umbrella-rules] cannot watch ${file}: ${error?.message ?? error}`) } catch { /* ignore */ }
1029
+ }
1030
+ }
1031
+
1032
+ return {
1033
+ files: list,
1034
+ reload: schedule,
1035
+ stop() {
1036
+ stopped = true
1037
+ if (timer !== null) clearTimeout(timer)
1038
+ timer = null
1039
+ for (const watcher of watchers) {
1040
+ try { watcher.close() } catch { /* ignore */ }
1041
+ }
1042
+ watchers.length = 0
1043
+ },
1044
+ }
1045
+ }
1046
+
978
1047
  /**
979
1048
  * 热加载:文件变化 → 防抖 → 重新读取 → 应用。失败保留旧规则。
980
1049
  * @returns {{ stop: () => void }}
@@ -0,0 +1,170 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // ssrf-guard — AI / 出站端点的最小 SSRF 防护:
5
+ // * 字面量私网 IP:默认拒绝,除非显式 allowlist
6
+ // * 云元数据地址/主机名:永远拒绝(allowlist 也不能放行)
7
+ // * hostname:配置时只做语法检查;请求前做一次 DNS 解析,
8
+ // 解析到私网/元数据则拒绝(防“公网域名解析到内网”的常见 SSRF)
9
+ //
10
+ // 诚实边界:DNS 预检与 fetch 的真实解析之间仍有 TOCTOU 窗口(DNS rebinding),
11
+ // Node fetch 没有 pinned-lookup 接口;因此这里只做“高置信拦截”,不宣称完备。
12
+ import net from 'node:net'
13
+ import dns from 'node:dns/promises'
14
+
15
+ const METADATA_HOSTS = new Set([
16
+ 'metadata.google.internal',
17
+ 'metadata.goog',
18
+ 'instance-data',
19
+ ])
20
+
21
+ const METADATA_ADDRESSES = new Set([
22
+ '169.254.169.254', // AWS / GCP / Azure IMDS
23
+ '100.100.100.200', // Alibaba Cloud
24
+ '192.0.0.192', // Oracle Cloud
25
+ 'fd00:ec2::254', // AWS IPv6 IMDS
26
+ ])
27
+
28
+ export function normalizeHost(value) {
29
+ let host = String(value ?? '').trim().toLowerCase()
30
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1)
31
+ return host.replace(/\.$/, '')
32
+ }
33
+
34
+ export function isMetadataAddress(value) {
35
+ return METADATA_ADDRESSES.has(normalizeHost(value))
36
+ }
37
+
38
+ export function isMetadataHost(value) {
39
+ return METADATA_HOSTS.has(normalizeHost(value))
40
+ }
41
+
42
+ const inV4Range = (parts, base, bits) => {
43
+ if (!Array.isArray(parts) || parts.length !== 4) return false
44
+ let value = 0
45
+ for (const part of parts) value = (value << 8) | part
46
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0
47
+ return (value & mask) === (base & mask)
48
+ }
49
+
50
+ function ipv4Parts(ip) {
51
+ const parts = ip.split('.').map(Number)
52
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null
53
+ return parts
54
+ }
55
+
56
+ function ipv4ToInt(parts) {
57
+ return (((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3]) >>> 0
58
+ }
59
+
60
+ export function isPrivateIpv4(ip) {
61
+ const parts = ipv4Parts(ip)
62
+ if (!parts) return false
63
+ const value = ipv4ToInt(parts)
64
+ // RFC1918
65
+ if (inV4Range(parts, ipv4ToInt([10, 0, 0, 0]), 8)) return true
66
+ if (inV4Range(parts, ipv4ToInt([172, 16, 0, 0]), 12)) return true
67
+ if (inV4Range(parts, ipv4ToInt([192, 168, 0, 0]), 16)) return true
68
+ // loopback / link-local / unspecified
69
+ if (inV4Range(parts, ipv4ToInt([127, 0, 0, 0]), 8)) return true
70
+ if (inV4Range(parts, ipv4ToInt([169, 254, 0, 0]), 16)) return true
71
+ if (inV4Range(parts, ipv4ToInt([0, 0, 0, 0]), 8)) return true
72
+ // CGNAT / benchmark / multicast / reserved
73
+ if (inV4Range(parts, ipv4ToInt([100, 64, 0, 0]), 10)) return true
74
+ if (inV4Range(parts, ipv4ToInt([198, 18, 0, 0]), 15)) return true
75
+ if (inV4Range(parts, ipv4ToInt([198, 51, 100, 0]), 24)) return true
76
+ if (inV4Range(parts, ipv4ToInt([203, 0, 113, 0]), 24)) return true
77
+ if (((value & 0xF0000000) >>> 0) === 0xE0000000) return true // multicast
78
+ if (((value & 0xF0000000) >>> 0) === 0xF0000000) return true // reserved
79
+ return false
80
+ }
81
+
82
+ function ipv6Groups(ip) {
83
+ const raw = normalizeHost(ip)
84
+ if (!raw.includes(':')) return null
85
+ const [head, tail] = raw.split('::')
86
+ const parse = (segment) => segment.length === 0 ? [] : segment.split(':')
87
+ let groups = []
88
+ if (raw.includes('::')) groups = [...parse(head), ...Array(8 - parse(head).length - parse(tail ?? '').length).fill('0'), ...parse(tail ?? '')]
89
+ else groups = raw.split(':')
90
+ if (groups.length !== 8) return null
91
+ return groups.map((group) => parseInt(group || '0', 16)).filter((part) => Number.isInteger(part))
92
+ }
93
+
94
+ export function isPrivateIpv6(ip) {
95
+ const raw = normalizeHost(ip)
96
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(raw)
97
+ if (mapped) return isPrivateIpv4(mapped[1])
98
+ const groups = ipv6Groups(raw)
99
+ if (!groups) return false
100
+ if (groups.every((group, index) => (index < 7 ? group === 0 : group === 1))) return true // ::1
101
+ if (groups.every((group) => group === 0)) return true // ::
102
+ if ((groups[0] & 0xFE00) === 0xFC00) return true // fc00::/7
103
+ if ((groups[0] & 0xFFC0) === 0xFE80) return true // fe80::/10
104
+ if ((groups[0] & 0xFF00) === 0xFF00) return true // multicast
105
+ // IPv4-mapped ::ffff:a.b.c.d
106
+ if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xFFFF) {
107
+ const v4 = `${groups[6] >> 8}.${groups[6] & 0xFF}.${groups[7] >> 8}.${groups[7] & 0xFF}`
108
+ return isPrivateIpv4(v4)
109
+ }
110
+ return false
111
+ }
112
+
113
+ export function isPrivateAddress(ip) {
114
+ const host = normalizeHost(ip)
115
+ const family = net.isIP(host)
116
+ if (family === 4) return isPrivateIpv4(host)
117
+ if (family === 6) return isPrivateIpv6(host)
118
+ return false
119
+ }
120
+
121
+ /** 同步分类:仅处理字面量 IP 与元数据主机名;DNS 主机名留给请求前预检。 */
122
+ export function classifyEndpointHost(hostname, { allowHosts = [] } = {}) {
123
+ const host = normalizeHost(hostname)
124
+ const allowed = new Set((Array.isArray(allowHosts) ? allowHosts : []).map(normalizeHost))
125
+ if (isMetadataHost(host)) return { ok: false, reason: 'metadata-address-blocked', kind: 'metadata' }
126
+ const family = net.isIP(host)
127
+ if (family === 0) {
128
+ if (host === 'localhost') return { ok: true, kind: 'loopback' }
129
+ return { ok: true, kind: 'hostname' }
130
+ }
131
+ if (isMetadataAddress(host)) return { ok: false, reason: 'metadata-address-blocked', kind: 'metadata' }
132
+ if (family === 4 && inV4Range(ipv4Parts(host) ?? [], ipv4ToInt([127, 0, 0, 0]), 8)) return { ok: true, kind: 'loopback' }
133
+ if (family === 6) {
134
+ const groups = ipv6Groups(host)
135
+ if (groups && groups.every((group, index) => (index < 7 ? group === 0 : group === 1))) return { ok: true, kind: 'loopback' }
136
+ }
137
+ if ((family === 4 && isPrivateIpv4(host)) || (family === 6 && isPrivateIpv6(host))) {
138
+ if (allowed.has(host)) return { ok: true, kind: 'private-allowlisted' }
139
+ return { ok: false, reason: 'private-address-blocked', kind: 'private' }
140
+ }
141
+ return { ok: true, kind: family === 4 ? 'public-ipv4' : 'public-ipv6' }
142
+ }
143
+
144
+ /** 请求前 DNS 预检;解析失败视为 NXDOMAIN(交给 fetch 失败,不视为 SSRF)。 */
145
+ export async function assertEndpointSafe(hostname, { allowHosts = [], resolve = dns.lookup, timeoutMs = 1500 } = {}) {
146
+ const sync = classifyEndpointHost(hostname, { allowHosts })
147
+ if (!sync.ok) return sync
148
+ if (sync.kind !== 'hostname') return sync
149
+ const host = normalizeHost(hostname)
150
+ const allowed = new Set((Array.isArray(allowHosts) ? allowHosts : []).map(normalizeHost))
151
+ // 明确的 metadata 主机名已在 sync 拦截;其余做一次解析。
152
+ let addresses = []
153
+ try {
154
+ const result = await Promise.race([
155
+ resolve(host, { all: true, verbatim: true }),
156
+ new Promise((_, reject) => setTimeout(() => reject(new Error('dns-timeout')), timeoutMs).unref?.()),
157
+ ])
158
+ addresses = Array.isArray(result) ? result : (result?.address ? [result] : [])
159
+ } catch (error) {
160
+ return { ok: true, kind: 'hostname-unresolved', detail: String(error?.message ?? error) }
161
+ }
162
+ for (const entry of addresses) {
163
+ const address = normalizeHost(entry?.address ?? entry)
164
+ if (isMetadataAddress(address)) return { ok: false, reason: 'metadata-address-blocked', kind: 'metadata', address }
165
+ if (isPrivateAddress(address) && !allowed.has(host)) {
166
+ return { ok: false, reason: 'private-address-blocked', kind: 'private', address }
167
+ }
168
+ }
169
+ return { ok: true, kind: 'hostname-public', addresses: addresses.map((entry) => normalizeHost(entry?.address ?? entry)) }
170
+ }
@@ -171,10 +171,28 @@ function compilePatterns(patterns) {
171
171
  }
172
172
 
173
173
  /** 指针:`[/\\]` 已覆盖两种分隔符,`resolve` 之后这里只做大小写与包含判断。 */
174
+ /** Resolve a path through the nearest existing ancestor so symlinked parents are real. */
175
+ function realPathWithMissing(value) {
176
+ let current = path.resolve(String(value))
177
+ const suffix = []
178
+ for (;;) {
179
+ try {
180
+ const real = fs.realpathSync(current)
181
+ return suffix.length === 0 ? real : path.join(real, ...suffix)
182
+ } catch {
183
+ const parent = path.dirname(current)
184
+ if (parent === current) return path.resolve(String(value))
185
+ suffix.unshift(path.basename(current))
186
+ current = parent
187
+ }
188
+ }
189
+ }
190
+
191
+ /** 路径 containment:realpath 后再比较,避免 symlink/junction 逃出 root。 */
174
192
  function withinPath(child, parent) {
175
193
  if (!child || !parent) return false
176
- const c = process.platform === 'win32' ? child.toLowerCase() : child
177
- const p = process.platform === 'win32' ? parent.toLowerCase() : parent
194
+ const c = process.platform === 'win32' ? realPathWithMissing(child).toLowerCase() : realPathWithMissing(child)
195
+ const p = process.platform === 'win32' ? realPathWithMissing(parent).toLowerCase() : realPathWithMissing(parent)
178
196
  if (c === p) return true
179
197
  const withSep = p.endsWith(path.sep) ? p : p + path.sep
180
198
  return c.startsWith(withSep)
@@ -351,22 +369,41 @@ export function isReadOnly(evidence = {}) {
351
369
 
352
370
  function networkAllowed(hostText, policy) {
353
371
  if (!hostText) return false
372
+ const rawText = String(hostText)
354
373
  let host = ''
355
374
  let hostPort = ''
375
+ let parsedUrl = null
356
376
  try {
357
- const url = new URL(hostText)
358
- host = url.hostname.toLowerCase()
359
- hostPort = `${url.hostname}:${url.port || (url.protocol === 'https:' ? '443' : '80')}`.toLowerCase()
377
+ parsedUrl = new URL(rawText)
378
+ host = parsedUrl.hostname.toLowerCase()
379
+ hostPort = `${parsedUrl.hostname}:${parsedUrl.port || (parsedUrl.protocol === 'https:' ? '443' : '80')}`.toLowerCase()
360
380
  } catch {
361
- host = hostText.toLowerCase()
381
+ host = rawText.toLowerCase()
362
382
  hostPort = host
363
383
  }
364
384
  for (const raw of asStringList(policy.networkAllowlist)) {
365
- const entry = raw.trim().toLowerCase()
385
+ const rawEntry = raw.trim()
386
+ const entry = rawEntry.toLowerCase()
366
387
  if (!entry) continue
388
+ // URL-prefix entries must match an origin/path boundary; startsWith on the raw URL
389
+ // lets https://example.com allowlist https://example.com.evil.
390
+ if (rawEntry.includes('://')) {
391
+ let allow = null
392
+ try { allow = new URL(rawEntry) } catch { continue }
393
+ if (parsedUrl === null) continue
394
+ if (allow.protocol !== parsedUrl.protocol || allow.hostname.toLowerCase() !== host) continue
395
+ const allowPort = allow.port || (allow.protocol === 'https:' ? '443' : '80')
396
+ const targetPort = parsedUrl.port || (parsedUrl.protocol === 'https:' ? '443' : '80')
397
+ if (allowPort !== targetPort) continue
398
+ const allowPath = allow.pathname || '/'
399
+ const targetPath = parsedUrl.pathname || '/'
400
+ if (allowPath === '/' || targetPath === allowPath) return true
401
+ if (targetPath.startsWith(allowPath)
402
+ && (allowPath.endsWith('/') || ['/', '?', '#'].includes(targetPath[allowPath.length]))) return true
403
+ continue
404
+ }
367
405
  if (entry === host || entry === hostPort) return true
368
406
  if (entry.startsWith('*.') && host.endsWith(entry.slice(1))) return true
369
- if (hostText.toLowerCase().startsWith(entry)) return true
370
407
  }
371
408
  return false
372
409
  }
@@ -387,6 +424,12 @@ function execLooksReadOnly(evidence, policy) {
387
424
  const text = target.kind === 'command' ? target.value : String(evidence?.args?.command ?? '')
388
425
  if (!text) return false
389
426
  if (WRITE_REDIRECT_RE.test(text)) return false
427
+ // A read-only prefix only applies to a single simple command. Any command separator,
428
+ // pipeline, substitution or backtick can smuggle a side-effect into "cat x; rm ...".
429
+ const lex = tokenizeShell(text)
430
+ if (lex.errors.length > 0) return false
431
+ if (lex.tokens.some((token) => token.type === 'op' && SHELL_SEPARATORS.has(token.value))) return false
432
+ if (text.includes('`') || /\$\(/.test(text)) return false
390
433
  return matchesAny(compilePatterns(policy.readOnlyExecPatterns), text)
391
434
  }
392
435
 
@@ -804,6 +847,7 @@ export function buildActionContext(evidence = {}, policyInput = {}) {
804
847
  parseError: redirects.parseError,
805
848
  heredocs: redirects.heredocs,
806
849
  warnings: redirects.warnings,
850
+ trusted: evidence?.trusted === true,
807
851
  policy,
808
852
  }
809
853
  }
@@ -1146,6 +1190,7 @@ export function baseLight(evidence = {}, policyInput = {}, ruleSet = DEFAULT_RUL
1146
1190
  tags: [...(rule.tags ?? [])],
1147
1191
  lifecycle: rule.id === 'dsh-lifecycle',
1148
1192
  credential: rule.id === 'credential-access',
1193
+ trusted: ctx.trusted === true,
1149
1194
  target: ctx.target ?? NO_TARGET,
1150
1195
  path: ctx.targetPath ?? (detail.targets?.[0] ?? null),
1151
1196
  reason: rule.reason,
@@ -1215,8 +1260,11 @@ function mtimeOf(file) {
1215
1260
  }
1216
1261
 
1217
1262
  function pluginKeyOf(input) {
1218
- if (typeof input.pluginId === 'string' && input.pluginId.length > 0) return `id:${input.pluginId}`
1219
- if (typeof input.dir === 'string' && input.dir.length > 0) return `dir:${path.resolve(input.dir)}`
1263
+ const id = typeof input.pluginId === 'string' && input.pluginId.length > 0 ? input.pluginId : ''
1264
+ const dir = typeof input.dir === 'string' && input.dir.length > 0 ? path.resolve(input.dir) : ''
1265
+ if (id && dir) return `id:${id}|dir:${dir}`
1266
+ if (id) return `id:${id}`
1267
+ if (dir) return `dir:${dir}`
1220
1268
  if (typeof input.source === 'string') return `src:${sha1(input.source)}`
1221
1269
  return null
1222
1270
  }
@@ -1240,7 +1288,7 @@ export function createUmbrella(options = {}) {
1240
1288
  floorTable = DEFAULT_FLOOR_TABLE,
1241
1289
  cacheSize = 200,
1242
1290
  now = () => Date.now(),
1243
- audit = null,
1291
+ decisionCenter = null, audit = null,
1244
1292
  onPluginScored = null,
1245
1293
  rules: initialRules = null,
1246
1294
  registry = null,
@@ -1274,8 +1322,19 @@ export function createUmbrella(options = {}) {
1274
1322
  const stats = { hits: 0, misses: 0, evictions: 0, invalidations: 0, pluginScans: 0 }
1275
1323
 
1276
1324
  function auditRecord(record) {
1277
- if (typeof audit !== 'function') return
1278
- try { audit(record) } catch { /* 审计失败不得影响评分 */ }
1325
+ if (typeof audit !== 'function') return { ok: true, skipped: true }
1326
+ try {
1327
+ const result = audit(record)
1328
+ if (result && result.ok === false) {
1329
+ record.auditDegraded = true
1330
+ return result
1331
+ }
1332
+ return { ok: true }
1333
+ } catch (error) {
1334
+ record.auditDegraded = true
1335
+ record.auditError = String(error?.message ?? error)
1336
+ return { ok: false, error: record.auditError }
1337
+ }
1279
1338
  }
1280
1339
 
1281
1340
  function emitPluginScored(assessment) {
@@ -1315,7 +1374,11 @@ export function createUmbrella(options = {}) {
1315
1374
  if (entry.entryFile) {
1316
1375
  const current = mtimeOf(entry.entryFile)
1317
1376
  if (current === null) return true
1318
- return current !== entry.fingerprint
1377
+ if (current !== entry.fingerprint) return true
1378
+ }
1379
+ if (entry.packageFile) {
1380
+ const currentPackage = mtimeOf(entry.packageFile)
1381
+ if (currentPackage !== entry.packageFingerprint) return true
1319
1382
  }
1320
1383
  return false
1321
1384
  }
@@ -1358,7 +1421,9 @@ export function createUmbrella(options = {}) {
1358
1421
  stats.pluginScans += 1
1359
1422
  const scored = runScorer(input)
1360
1423
  const entryFile = scored?.dir && scored?.entry ? path.join(scored.dir, scored.entry) : null
1424
+ const packageFile = scored?.dir ? path.join(scored.dir, 'package.json') : null
1361
1425
  const fingerprint = entryFile ? mtimeOf(entryFile) : sha1(String(input.source ?? ''))
1426
+ const packageFingerprint = packageFile ? mtimeOf(packageFile) : null
1362
1427
  const grade = normalizeGrade(scored?.grade)
1363
1428
  const assessment = {
1364
1429
  pluginId: String(input.pluginId ?? (input.dir ? path.basename(path.resolve(input.dir)) : 'inline')),
@@ -1379,7 +1444,7 @@ export function createUmbrella(options = {}) {
1379
1444
  fromCache: false,
1380
1445
  }
1381
1446
  rememberGrade(assessment)
1382
- store(key, { assessment, entryFile, fingerprint })
1447
+ store(key, { assessment, entryFile, fingerprint, packageFile, packageFingerprint })
1383
1448
  emitPluginScored(assessment)
1384
1449
  return assessment
1385
1450
  }
@@ -1420,6 +1485,7 @@ export function createUmbrella(options = {}) {
1420
1485
  tags: base.tags,
1421
1486
  lifecycle: base.lifecycle,
1422
1487
  credential: base.credential,
1488
+ trusted: base.trusted === true,
1423
1489
  reason: base.reason,
1424
1490
  evidence: base.evidence,
1425
1491
  tool: String(evidence?.tool ?? ''),
@@ -1447,13 +1513,69 @@ export function createUmbrella(options = {}) {
1447
1513
  light: assessment.light,
1448
1514
  matchedRule: assessment.matchedRule,
1449
1515
  category: assessment.category,
1516
+ trusted: assessment.trusted === true,
1450
1517
  evidence: assessment.evidence,
1451
1518
  decision: decision.decision,
1452
1519
  severity: decision.severity,
1453
1520
  durationMs: Math.max(0, now() - started),
1454
1521
  }
1455
- auditRecord(record)
1456
- return { ...assessment, decision: decision.decision, severity: decision.severity, decisionRecord: record }
1522
+ const auditState = auditRecord(record)
1523
+ let decisionTicketId = null
1524
+ let decisionTicketPromise = null
1525
+ // Umbrella's ASK is exactly the yellow/red attention event the decision center
1526
+ // exists for. Keep it best-effort: a missing decision center must never change
1527
+ // the umbrella decision itself.
1528
+ if (decision.decision === 'ask') {
1529
+ try {
1530
+ const center = typeof decisionCenter === 'function' ? decisionCenter() : decisionCenter
1531
+ if (center && typeof center.submit === 'function') {
1532
+ const level = assessment.light === 'red' || decision.severity === 'critical' ? 'red' : 'yellow'
1533
+ const submitted = center.submit({
1534
+ level,
1535
+ title: `保护伞请求确认:${assessment.matchedRule ?? 'unknown-action'}`,
1536
+ description: `${assessment.tool || 'tool'} → ${assessment.target?.kind || 'none'}:${String(assessment.target?.value || '').slice(0, 500)}`,
1537
+ source: 'System',
1538
+ // 同一 action 的重复 ASK 在决策中心 pending 期内合并,避免重复开票。
1539
+ dedupeKey: `umbrella:${assessment.tool ?? ''}:${assessment.target?.kind ?? ''}:${String(assessment.target?.value ?? '').slice(0, 120)}:${assessment.matchedRule ?? ''}`.slice(0, 200),
1540
+ actions: [
1541
+ { id: 'ack', label: '知悉', type: 'default' },
1542
+ { id: 'ignore', label: '忽略', type: 'default' },
1543
+ ],
1544
+ metadata: {
1545
+ tool: assessment.tool || null,
1546
+ target: assessment.target ?? null,
1547
+ light: assessment.light,
1548
+ matchedRule: assessment.matchedRule ?? null,
1549
+ category: assessment.category ?? null,
1550
+ },
1551
+ })
1552
+ const link = (result) => {
1553
+ if (result?.ok === true && result.ticket?.id) {
1554
+ decisionTicketId = result.ticket.id
1555
+ record.decisionTicketId = decisionTicketId
1556
+ }
1557
+ return result ?? null
1558
+ }
1559
+ // fork 代理的 submit 是异步(outbox/HTTP);不能丢 Promise,否则 fork 里
1560
+ // decisionTicketId 永远为 null 且可能出现 unhandled rejection。
1561
+ if (submitted && typeof submitted.then === 'function') {
1562
+ decisionTicketPromise = Promise.resolve(submitted).then(link).catch(() => null)
1563
+ } else {
1564
+ link(submitted)
1565
+ }
1566
+ }
1567
+ } catch { /* decision-center is optional */ }
1568
+ }
1569
+ record.decisionTicketId = decisionTicketId
1570
+ return {
1571
+ ...assessment,
1572
+ decision: decision.decision,
1573
+ severity: decision.severity,
1574
+ decisionTicketId,
1575
+ decisionTicketPromise,
1576
+ decisionRecord: record,
1577
+ auditDegraded: auditState?.ok === false || record.auditDegraded === true,
1578
+ }
1457
1579
  }
1458
1580
 
1459
1581
  function cacheStats() {
@@ -1464,7 +1586,10 @@ export function createUmbrella(options = {}) {
1464
1586
  const text = String(keyOrPluginId ?? '')
1465
1587
  let removed = 0
1466
1588
  for (const key of [...cache.keys()]) {
1467
- if (key === text || key.endsWith(`:${text}`)) {
1589
+ if (key === text
1590
+ || key.endsWith(`:${text}`)
1591
+ || key.startsWith(`id:${text}|`)
1592
+ || key === `id:${text}`) {
1468
1593
  cache.delete(key)
1469
1594
  removed += 1
1470
1595
  }
@@ -444,6 +444,23 @@ export function apply(ctx, config) {
444
444
  }
445
445
  }
446
446
 
447
+ const orphanedApprovalItems = () => {
448
+ const approver = safeGet(SERVICE.approver)
449
+ if (!approver || typeof approver.orphaned !== 'function') return []
450
+ try {
451
+ const items = approver.orphaned()
452
+ return Array.isArray(items) ? items : []
453
+ } catch {
454
+ return []
455
+ }
456
+ }
457
+
458
+ const approvalItemsWithOrphans = () => {
459
+ const pending = approvalItems()
460
+ if (pending === null) return null
461
+ return [...pending, ...orphanedApprovalItems()]
462
+ }
463
+
447
464
  const auditHead = () => {
448
465
  const auditor = safeGet(SERVICE.auditor)
449
466
  if (!auditor || typeof auditor.read !== 'function') {
@@ -663,7 +680,7 @@ export function apply(ctx, config) {
663
680
  }
664
681
 
665
682
  const approvals = () => {
666
- const items = approvalItems()
683
+ const items = approvalItemsWithOrphans()
667
684
  if (items === null) return { ok: false, code: 'service-unavailable', error: 'service-unavailable', items: [] }
668
685
  return { ok: true, items }
669
686
  }
@@ -771,6 +788,18 @@ export function apply(ctx, config) {
771
788
  }
772
789
  }],
773
790
 
791
+ [ADAPTER_OP.DECISION_INGEST, async (payload) => {
792
+ const center = safeGet(SERVICE.decisionCenter)
793
+ if (!center || typeof center.submit !== 'function') return unavailable()
794
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return badRequest('payload-required')
795
+ try {
796
+ const out = await center.submit({ producer: 'adapter', ...payload })
797
+ return out && typeof out === 'object' ? out : { ok: true }
798
+ } catch (e) {
799
+ return { ok: false, code: 'handler-threw', error: `decision-ingest-failed:${msgOf(e)}` }
800
+ }
801
+ }],
802
+
774
803
  [ADAPTER_OP.READ_PLUGIN, (payload) => readPlugin(payload)],
775
804
 
776
805
  [ADAPTER_OP.ROUTE_CONFIRM, async (payload) => {
@@ -781,7 +810,7 @@ export function apply(ctx, config) {
781
810
  }],
782
811
 
783
812
  [ADAPTER_OP.APPROVALS, () => {
784
- const items = approvalItems()
813
+ const items = approvalItemsWithOrphans()
785
814
  if (items === null) return unavailable()
786
815
  return { items }
787
816
  }],