dsh-chief 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * safety/index.js
3
+ *
4
+ * Unified entry point for the DSH Chief Safety Kernel (`pkg/safety/`).
5
+ */
6
+
7
+ export {
8
+ SECRET_REDACT_PATTERN,
9
+ redactAuditText,
10
+ auditJsonlPath,
11
+ normalizeAuditRecord,
12
+ appendAuditJsonlRecord,
13
+ readRecentAuditJsonl,
14
+ } from './audit-log.js'
15
+
16
+ export {
17
+ decodeEncodedPowerShell,
18
+ normalizeCommandForSecurity,
19
+ splitCompoundCommand,
20
+ extractInlineScriptPayloads,
21
+ analyzeCommand,
22
+ } from './command-analyzer.js'
23
+
24
+ export {
25
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
26
+ safeRealpath,
27
+ isPathInsideWorkspace,
28
+ hasWindowsReservedDeviceName,
29
+ hasForbiddenNtfsAds,
30
+ isSensitiveCredentialPath,
31
+ validateWorkspacePath,
32
+ verifyBoundsWriteAuth,
33
+ } from './path-guard.js'
34
+
35
+ export {
36
+ HARD_GUARD_RULE_IDS,
37
+ isDestructiveShellCommand,
38
+ commandTouchesSensitiveCredential,
39
+ checkForbiddenBounds,
40
+ evaluateSafetyGuardHardRules,
41
+ } from './invariant-guards.js'
42
+
43
+ export {
44
+ FORBIDDEN_WEAKENING_KEYS,
45
+ validatePolicyPlugin,
46
+ validatePolicyPluginList,
47
+ evaluatePolicyPlugins,
48
+ } from './policy-plugin.js'
49
+
50
+ export {
51
+ CHIEF_PERMISSION_MODES,
52
+ DEFAULT_CHIEF_PERMISSION_MODE,
53
+ CHIEF_PERMISSION_META,
54
+ normalizePermissionMode,
55
+ permissionRank,
56
+ getToolOpClass,
57
+ resolveRoleCapabilities,
58
+ buildCapabilityScope,
59
+ verifyCapabilityScope,
60
+ } from './policy-engine.js'
61
+
62
+ export {
63
+ evaluateChiefPermissionGate,
64
+ evaluateUnifiedToolGate,
65
+ } from './tool-gate.js'
66
+
67
+ export {
68
+ GUARD_WALL_RULE_TYPES,
69
+ GUARD_WALL_SCOPES,
70
+ guardWallsFilePath,
71
+ validateGuardWallInput,
72
+ normalizeGuardWall,
73
+ isGuardWallActiveForCwd,
74
+ listGuardWalls,
75
+ mutateGuardWalls,
76
+ evaluateGuardWalls,
77
+ evaluatePreExecuteDefense,
78
+ } from './guard-walls.js'
@@ -0,0 +1,280 @@
1
+ /**
2
+ * safety/invariant-guards.js
3
+ *
4
+ * Non-overridable Hard Guards: destructive shell command prevention,
5
+ * credential touch blocking, workspace boundary containment, and user
6
+ * `bounds.forbidden` enforcement across compound commands and inline scripts.
7
+ */
8
+
9
+ import path from 'node:path'
10
+ import { analyzeCommand, normalizeCommandForSecurity } from './command-analyzer.js'
11
+ import { validateWorkspacePath } from './path-guard.js'
12
+
13
+ export const HARD_GUARD_RULE_IDS = Object.freeze([
14
+ 'sensitive_credential',
15
+ 'sensitive_credential_cmd',
16
+ 'inline_script_credential',
17
+ 'windows_reserved_device',
18
+ 'ntfs_ads_stream',
19
+ 'workspace_escape',
20
+ 'destructive_command',
21
+ 'forbidden_bound',
22
+ ])
23
+
24
+ const DESTRUCTIVE_COMMAND_PATTERNS = [
25
+ /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
26
+ /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
27
+ /\b(?:format|diskpart|cipher\s+\/w|bcdedit)\b/i,
28
+ /\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
29
+ /\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
30
+ /\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,
31
+ /\breg(?:\.exe)?\s+delete\s+(?:hklm|hkcr|hkcu\\software\\microsoft)\b/i,
32
+ /\bdrop\s+(?:database|schema)\b/i,
33
+ ]
34
+
35
+ const CREDENTIAL_TOUCH_RE = /(?:^|[\s"'=/\\:;>|&(\[,])(?:\.+\\*env(?:\.[a-z0-9_-]+)?|\.+\\*credentials(?:\.[a-z0-9_-]+)?|\.\\*(?:git-credentials|npmrc|pypirc|netrc)|id_rsa|id_ed25519|id_ecdsa|id_dsa|[a-z0-9_.-]+\.(?:pem|p12|pfx))(?:$|[\s"';&|><)\],\r\n])/i
36
+
37
+ function stripQuotedBackslashSplits(text) {
38
+ return String(text || '')
39
+ .replace(/\\+(["'`])/g, '$1')
40
+ .replace(/(["'`])\\+(?=[a-zA-Z0-9_.-])/g, '$1')
41
+ .replace(/["'`]/g, '')
42
+ }
43
+
44
+ function clamp(text, maxLen = 200) {
45
+ const s = String(text || '').trim()
46
+ return s.length > maxLen ? s.slice(0, maxLen) + '...' : s
47
+ }
48
+
49
+ function expandEnvPlaceholdersForCheck(text) {
50
+ return String(text || '')
51
+ .replace(/%[A-Za-z0-9_]+%/g, '/')
52
+ .replace(/\$env:[A-Za-z0-9_]+/gi, '/')
53
+ .replace(/\$\{[A-Za-z0-9_]+\}/g, '/')
54
+ }
55
+
56
+ export function isDestructiveShellCommand(command) {
57
+ const raw = String(command || '').trim()
58
+ if (!raw) return false
59
+ const analysis = analyzeCommand(raw)
60
+ const probes = [raw, analysis.normalized, ...analysis.segments, ...analysis.inlinePayloads]
61
+ return probes.some(p => p && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(p)))
62
+ }
63
+
64
+ export function commandTouchesSensitiveCredential(command) {
65
+ const raw = String(command || '')
66
+ if (!raw.trim()) return { touched: false, viaInline: false }
67
+ const analysis = analyzeCommand(raw)
68
+
69
+ for (const payload of analysis.inlinePayloads) {
70
+ const normPayload = normalizeCommandForSecurity(payload)
71
+ const expPayload = expandEnvPlaceholdersForCheck(normPayload)
72
+ const strippedPayload = stripQuotedBackslashSplits(payload)
73
+ if (
74
+ CREDENTIAL_TOUCH_RE.test(payload)
75
+ || CREDENTIAL_TOUCH_RE.test(strippedPayload)
76
+ || CREDENTIAL_TOUCH_RE.test(normPayload)
77
+ || CREDENTIAL_TOUCH_RE.test(expPayload)
78
+ ) {
79
+ return { touched: true, viaInline: true }
80
+ }
81
+ }
82
+
83
+ const probes = [
84
+ raw,
85
+ stripQuotedBackslashSplits(raw),
86
+ analysis.normalized,
87
+ stripQuotedBackslashSplits(analysis.normalized),
88
+ expandEnvPlaceholdersForCheck(analysis.normalized),
89
+ ...analysis.segments,
90
+ ...analysis.segments.map(seg => stripQuotedBackslashSplits(seg)),
91
+ ...analysis.segments.map(seg => expandEnvPlaceholdersForCheck(normalizeCommandForSecurity(seg))),
92
+ ]
93
+ for (const probe of probes) {
94
+ if (probe && CREDENTIAL_TOUCH_RE.test(probe)) {
95
+ return { touched: true, viaInline: false }
96
+ }
97
+ }
98
+ return { touched: false, viaInline: false }
99
+ }
100
+
101
+ /**
102
+ * 无论当前处于何种权限级别(包括 chief),都坚决守住用户在看板中设定的禁止红线。
103
+ */
104
+ export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '', extraContent = '') {
105
+ const forbidden = [
106
+ ...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
107
+ ...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
108
+ ]
109
+ if (!forbidden.length) return { blocked: false }
110
+ const primary = String(commandOrPath || '')
111
+ const analysis = analyzeCommand(primary)
112
+ const normCmd = analysis.normalized
113
+ const contentSample = String(extraContent || '').slice(0, 8192).normalize('NFKC')
114
+ const extraSegments = [
115
+ ...analysis.segments,
116
+ ...analysis.inlinePayloads,
117
+ ].join(' \n ')
118
+ const haystack = [
119
+ String(actionDesc || ''),
120
+ primary,
121
+ primary.replace(/\\/g, '/'),
122
+ normCmd,
123
+ normCmd.replace(/\\/g, '/'),
124
+ extraSegments,
125
+ extraSegments.replace(/\\/g, '/'),
126
+ contentSample,
127
+ contentSample.replace(/\\/g, '/'),
128
+ ].join(' \n ').toLowerCase()
129
+
130
+ for (const rule of forbidden) {
131
+ const rText = String(rule || '').trim()
132
+ if (!rText) continue
133
+ const ruleNorm = rText.replace(/\\/g, '/')
134
+ const ruleLower = ruleNorm.toLowerCase()
135
+
136
+ // 1. 提取反引号或引号内的受禁命令或路径字面量
137
+ const quoted = [
138
+ ...[...ruleNorm.matchAll(/`([^`]{2,80})`/g)].map(m => m[1]),
139
+ ...[...ruleNorm.matchAll(/["'「『]([^"'」』]{2,80})["'」』]/g)].map(m => m[1]),
140
+ ].map(s => s.trim().toLowerCase())
141
+ for (const token of quoted) {
142
+ if (token && haystack.includes(token)) {
143
+ return { blocked: true, matchedRule: rText, trigger: token }
144
+ }
145
+ }
146
+
147
+ // 2. 提取不带反引号的文件名、路径片段、点文件或扩展名
148
+ const pathTokens = [...ruleLower.matchAll(/(?:[a-z0-9_.-]+\/[a-z0-9_.\-\/]+|\.[a-z0-9_-]{2,16}|[a-z0-9_-]{2,40}\.[a-z0-9]{1,10})/g)]
149
+ .map(m => m[0].trim())
150
+ for (const tok of pathTokens) {
151
+ if (tok && tok.length >= 3 && haystack.includes(tok)) {
152
+ return { blocked: true, matchedRule: rText, trigger: tok }
153
+ }
154
+ }
155
+
156
+ // 3. 匹配常见高危动词组合
157
+ const dangerousCmds = [
158
+ 'git push',
159
+ 'npm publish',
160
+ 'git reset --hard',
161
+ 'rm -rf',
162
+ 'del /f',
163
+ 'format ',
164
+ 'drop table',
165
+ 'drop database',
166
+ ]
167
+ for (const cmdTok of dangerousCmds) {
168
+ if (ruleLower.includes(cmdTok) && haystack.includes(cmdTok)) {
169
+ return { blocked: true, matchedRule: rText, trigger: cmdTok }
170
+ }
171
+ }
172
+
173
+ // 4. 若用户直接写了极短裸禁止词(去前缀后 >= 4 字符的命令行或目录标记)
174
+ const stripped = ruleLower
175
+ .replace(/^(?:严禁|禁止|不得|切勿|不要|不能|不可|不允许|勿|do\s+not|never|forbid)\s*/i, '')
176
+ .replace(/^(?:改动|修改|编辑|写入|删除|覆盖|执行|运行|推送|发布|触碰)\s*/i, '')
177
+ .trim()
178
+ if (stripped.length >= 4 && /^[a-z0-9_.\-\/:\s]{4,64}$/.test(stripped) && haystack.includes(stripped)) {
179
+ return { blocked: true, matchedRule: rText, trigger: stripped }
180
+ }
181
+ }
182
+ return { blocked: false }
183
+ }
184
+
185
+ const WORKSPACE_SCOPED_FS_TOOLS = new Set(['read_file', 'write_file', 'edit_file', 'list_dir', 'search_files'])
186
+
187
+ /** 安全卫兵硬性规则:优先于四级权限判定与策略插件,L3 与逐项放行均不可绕过。 */
188
+ export function evaluateSafetyGuardHardRules({
189
+ tool = '',
190
+ opClass = '',
191
+ targetPath = '',
192
+ command = '',
193
+ content = '',
194
+ target = '',
195
+ replacement = '',
196
+ extraContent = '',
197
+ args = null,
198
+ cwd = '',
199
+ board = null,
200
+ } = {}) {
201
+ const argObj = args && typeof args === 'object' ? args : {}
202
+ const resolvedPath = targetPath || (typeof argObj.path === 'string' ? argObj.path : '')
203
+ const resolvedCommand = command || (typeof argObj.command === 'string' ? argObj.command : (typeof argObj.cmd === 'string' ? argObj.cmd : ''))
204
+
205
+ if (resolvedPath) {
206
+ const enforceRoot = WORKSPACE_SCOPED_FS_TOOLS.has(String(tool || '').trim()) ? cwd : ''
207
+ const pathCheck = validateWorkspacePath(enforceRoot, resolvedPath, { mode: opClass === 'read' ? 'read' : 'write' })
208
+ if (pathCheck.blocked) {
209
+ return pathCheck
210
+ }
211
+ }
212
+
213
+ if (tool === 'run_command' && cwd && typeof argObj.cwd === 'string' && argObj.cwd.trim()) {
214
+ const runCwdCheck = validateWorkspacePath(cwd, path.resolve(cwd, argObj.cwd.trim()), { mode: 'write' })
215
+ if (runCwdCheck.blocked) {
216
+ return {
217
+ ...runCwdCheck,
218
+ reason: runCwdCheck.rule === 'workspace_escape'
219
+ ? `安全卫兵拦截工作区外命令执行目录 (cwd):${argObj.cwd}`
220
+ : runCwdCheck.reason,
221
+ }
222
+ }
223
+ }
224
+
225
+ if (resolvedCommand) {
226
+ const credTouch = commandTouchesSensitiveCredential(resolvedCommand)
227
+ if (credTouch.touched) {
228
+ return {
229
+ blocked: true,
230
+ stage: 'safety_guard',
231
+ rule: credTouch.viaInline ? 'inline_script_credential' : 'sensitive_credential_cmd',
232
+ reason: credTouch.viaInline
233
+ ? '安全卫兵拦截内联脚本(node -e / python -c / pwsh)触及敏感凭据文件(.env / .credentials / 私钥)'
234
+ : '安全卫兵拦截触及敏感凭据路径(.env / .credentials / 私钥证书)的终端命令',
235
+ badge: '🛡️ 卫兵拦凭据命令',
236
+ }
237
+ }
238
+ if (isDestructiveShellCommand(resolvedCommand)) {
239
+ return {
240
+ blocked: true,
241
+ stage: 'safety_guard',
242
+ rule: 'destructive_command',
243
+ reason: `安全卫兵拦截高危毁灭性系统命令:${clamp(resolvedCommand, 80)}`,
244
+ badge: '🛡️ 卫兵拦高危命令',
245
+ }
246
+ }
247
+ }
248
+
249
+ if (opClass !== 'read' && opClass !== 'elevation_request') {
250
+ const checkInput = resolvedPath || resolvedCommand
251
+ const payloadParts = [
252
+ content,
253
+ target,
254
+ replacement,
255
+ extraContent,
256
+ argObj.content,
257
+ argObj.target,
258
+ argObj.replacement,
259
+ argObj.prompt,
260
+ argObj.message,
261
+ argObj.text,
262
+ argObj.body,
263
+ ]
264
+ .filter(v => v !== undefined && v !== null && String(v).trim())
265
+ .map(v => String(v).slice(0, 8192))
266
+ const mergedExtra = payloadParts.join('\n').slice(0, 12_288)
267
+ const boundCheck = checkForbiddenBounds(board, tool, checkInput, mergedExtra)
268
+ if (boundCheck.blocked) {
269
+ return {
270
+ blocked: true,
271
+ stage: 'safety_guard',
272
+ rule: 'forbidden_bound',
273
+ matchedRule: boundCheck.matchedRule,
274
+ reason: `安全卫兵命中禁止红线【${boundCheck.matchedRule}】,坚决拦截:${clamp(checkInput || tool, 80)}`,
275
+ badge: '🛡️ 卫兵拦红线',
276
+ }
277
+ }
278
+ }
279
+ return { blocked: false }
280
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * safety/path-guard.js
3
+ *
4
+ * Workspace containment, symlink/junction escape detection, Windows reserved
5
+ * device & NTFS ADS checks, sensitive credential path matching, and bounds.*
6
+ * human confirmation guard.
7
+ */
8
+
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+
12
+ export const HUMAN_BOUNDS_CONFIRM_TOKEN = Symbol.for('dsh-chief.humanBoundsConfirm')
13
+
14
+ const SENSITIVE_CREDENTIAL_BASENAMES = /^(?:\.+env(?:\.[a-z0-9_-]+)?|\.credentials(?:\.[a-z0-9_-]+)?|\.(?:git-credentials|npmrc|pypirc|netrc))$/i
15
+ const SENSITIVE_CREDENTIAL_FULLPATH = /(?:id_rsa|id_ed25519|id_ecdsa|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/i
16
+ const WINDOWS_RESERVED_DEVICE_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.[^.]*)?$/i
17
+
18
+ export function safeRealpath(targetPath) {
19
+ try {
20
+ return fs.realpathSync.native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath)
21
+ } catch {
22
+ return path.resolve(targetPath)
23
+ }
24
+ }
25
+
26
+ function resolveDeepestExistingPath(absPath) {
27
+ if (fs.existsSync(absPath)) {
28
+ return safeRealpath(absPath)
29
+ }
30
+ const missingTail = []
31
+ let probe = absPath
32
+ while (probe && !fs.existsSync(probe)) {
33
+ const parent = path.dirname(probe)
34
+ if (parent === probe) break
35
+ missingTail.unshift(path.basename(probe))
36
+ probe = parent
37
+ }
38
+ const realBase = fs.existsSync(probe) ? safeRealpath(probe) : path.resolve(probe)
39
+ return missingTail.length ? path.join(realBase, ...missingTail) : realBase
40
+ }
41
+
42
+ export function isPathInsideWorkspace(workspaceRoot, targetPath) {
43
+ if (!workspaceRoot || !targetPath) return false
44
+ const rootAbs = safeRealpath(workspaceRoot)
45
+ const resolvedCandidate = path.resolve(rootAbs, String(targetPath))
46
+ const realTarget = resolveDeepestExistingPath(resolvedCandidate)
47
+ const cmpRoot = process.platform === 'win32' ? rootAbs.toLowerCase() : rootAbs
48
+ const cmpTarget = process.platform === 'win32' ? realTarget.toLowerCase() : realTarget
49
+ const rel = path.relative(cmpRoot, cmpTarget)
50
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
51
+ }
52
+
53
+ export function hasWindowsReservedDeviceName(filePath) {
54
+ const raw = String(filePath || '').trim()
55
+ if (!raw) return false
56
+ const withoutDrive = raw.replace(/^[a-zA-Z]:(?=[\\/]|$)/, '')
57
+ const parts = withoutDrive.split(/[\\/]+/).filter(Boolean)
58
+ return parts.some(seg => WINDOWS_RESERVED_DEVICE_RE.test(seg))
59
+ }
60
+
61
+ export function hasForbiddenNtfsAds(filePath) {
62
+ const raw = String(filePath || '').trim()
63
+ if (!raw) return false
64
+ const withoutDrive = raw.replace(/^[a-zA-Z]:(?=[\\/]|$)/, '')
65
+ return withoutDrive.includes(':')
66
+ }
67
+
68
+ function isSensitiveNameOrStream(candidate) {
69
+ const s = String(candidate || '').trim()
70
+ if (!s || s === '$DATA') return false
71
+ const slashNorm = s.replace(/\\/g, '/').toLowerCase()
72
+ const base = path.basename(slashNorm)
73
+ if (SENSITIVE_CREDENTIAL_BASENAMES.test(base)) return true
74
+ if (SENSITIVE_CREDENTIAL_FULLPATH.test(slashNorm)) return true
75
+ return false
76
+ }
77
+
78
+ function resolveWithSymlinkTarget(filePath) {
79
+ const out = []
80
+ const raw = String(filePath || '').trim()
81
+ if (!raw) return out
82
+ out.push(raw)
83
+ try {
84
+ const abs = path.resolve(raw)
85
+ out.push(abs)
86
+ try {
87
+ const lst = fs.lstatSync(abs)
88
+ if (lst.isSymbolicLink()) {
89
+ const linkTarget = fs.readlinkSync(abs)
90
+ out.push(linkTarget)
91
+ out.push(path.resolve(path.dirname(abs), linkTarget))
92
+ }
93
+ } catch {}
94
+ out.push(safeRealpath(abs))
95
+ const parent = path.dirname(abs)
96
+ if (fs.existsSync(parent)) {
97
+ out.push(path.join(safeRealpath(parent), path.basename(abs)))
98
+ }
99
+ } catch {}
100
+ return out
101
+ }
102
+
103
+ export function isSensitiveCredentialPath(filePath) {
104
+ const candidates = resolveWithSymlinkTarget(filePath)
105
+ for (const cand of candidates) {
106
+ if (isSensitiveNameOrStream(cand)) return true
107
+ // Strip Windows drive letter `C:` then inspect any NTFS Alternate Data Streams (`file.txt:.env:$DATA`)
108
+ const withoutDrive = String(cand || '').replace(/^[a-zA-Z]:(?=[\\/]|$)/, '')
109
+ if (withoutDrive.includes(':')) {
110
+ for (const streamPart of withoutDrive.split(':')) {
111
+ if (isSensitiveNameOrStream(streamPart)) return true
112
+ }
113
+ }
114
+ }
115
+ return false
116
+ }
117
+
118
+ export function validateWorkspacePath(workspaceRoot, targetPath, { mode = 'write', allowedSubPrefixes = null } = {}) {
119
+ const raw = String(targetPath || '').trim()
120
+ if (!raw) return { blocked: false, resolvedPath: '' }
121
+
122
+ if (hasWindowsReservedDeviceName(raw)) {
123
+ return {
124
+ blocked: true,
125
+ stage: 'safety_guard',
126
+ rule: 'windows_reserved_device',
127
+ reason: `安全卫兵拦截 Windows 保留设备名路径:${path.basename(raw)}`,
128
+ badge: '🛡️ 卫兵拦保留设备名',
129
+ }
130
+ }
131
+
132
+ if (hasForbiddenNtfsAds(raw)) {
133
+ return {
134
+ blocked: true,
135
+ stage: 'safety_guard',
136
+ rule: 'ntfs_ads_stream',
137
+ reason: `安全卫兵拦截 NTFS 交替数据流 (ADS) 路径:${path.basename(raw)}`,
138
+ badge: '🛡️ 卫兵拦ADS流',
139
+ }
140
+ }
141
+
142
+ if (isSensitiveCredentialPath(raw)) {
143
+ return {
144
+ blocked: true,
145
+ stage: 'safety_guard',
146
+ rule: 'sensitive_credential',
147
+ reason: `安全卫兵拦截访问敏感凭据文件:${path.basename(raw)}`,
148
+ badge: '🛡️ 卫兵拦凭据',
149
+ }
150
+ }
151
+
152
+ if (workspaceRoot && !isPathInsideWorkspace(workspaceRoot, raw)) {
153
+ return {
154
+ blocked: true,
155
+ stage: 'safety_guard',
156
+ rule: 'workspace_escape',
157
+ reason: `安全卫兵拦截工作区越界路径:${raw}`,
158
+ badge: '🛡️ 卫兵拦越界路径',
159
+ }
160
+ }
161
+
162
+ const resolvedAbs = workspaceRoot ? path.resolve(safeRealpath(workspaceRoot), raw) : path.resolve(raw)
163
+ if (mode === 'write' && Array.isArray(allowedSubPrefixes) && allowedSubPrefixes.length > 0 && !allowedSubPrefixes.includes('*') && workspaceRoot) {
164
+ const rootAbs = safeRealpath(workspaceRoot)
165
+ const rel = path.relative(rootAbs, resolveDeepestExistingPath(resolvedAbs)).replace(/\\/g, '/').toLowerCase()
166
+ const matched = allowedSubPrefixes.some(pref => {
167
+ const clean = String(pref || '').replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '').toLowerCase()
168
+ if (!clean) return false
169
+ return rel === clean || rel.startsWith(clean + '/')
170
+ })
171
+ if (!matched) {
172
+ return {
173
+ blocked: true,
174
+ stage: 'permission_gate',
175
+ rule: 'capability_prefix_denied',
176
+ reason: `当前授权写前缀未覆盖目标路径:${rel || '.'}`,
177
+ badge: '🔒 路径前缀未授权',
178
+ }
179
+ }
180
+ }
181
+
182
+ return { blocked: false, resolvedPath: resolvedAbs }
183
+ }
184
+
185
+ const BOUNDS_WRITE_ACTIONS = new Set([
186
+ 'bounds.set',
187
+ 'bounds.add',
188
+ 'bounds.pin',
189
+ 'bounds.remove',
190
+ 'bounds.edit',
191
+ 'bounds.consolidate',
192
+ ])
193
+
194
+ export function verifyBoundsWriteAuth({
195
+ action = '',
196
+ field = '',
197
+ callerOrigin = '',
198
+ humanConfirmToken = null,
199
+ } = {}) {
200
+ const act = String(action || '').trim()
201
+ if (!BOUNDS_WRITE_ACTIONS.has(act)) return { ok: true }
202
+ if (humanConfirmToken === HUMAN_BOUNDS_CONFIRM_TOKEN) return { ok: true }
203
+
204
+ const origin = String(callerOrigin || '').trim()
205
+ if (origin === 'human_ui' || origin === 'human_approval') return { ok: true }
206
+
207
+ if (origin === 'model_tool') {
208
+ return {
209
+ ok: false,
210
+ rule: 'bounds_human_only',
211
+ error: '安全卫兵拦截:模型工具禁止直接改动或覆写工作边界(bounds.*),请改用 action="bounds.propose" 提交参谋长由用户拍板。',
212
+ }
213
+ }
214
+
215
+ if (origin === 'chief_llm') {
216
+ const normField = String(field || '').trim().toLowerCase()
217
+ if (act === 'bounds.remove' || (act === 'bounds.set' && (!normField || normField === 'forbidden'))) {
218
+ return {
219
+ ok: false,
220
+ rule: 'bounds_forbidden_protected',
221
+ error: '安全卫兵拦截:禁止红线(forbidden)受人类确认保护,参谋不可未经用户拍板直接移除或覆写。',
222
+ }
223
+ }
224
+ }
225
+
226
+ return { ok: true }
227
+ }