openfeel 1.5.11 → 1.5.12

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/dsh/lib/guard.js CHANGED
@@ -1987,6 +1987,110 @@ function classifyBuildTool(name, args) {
1987
1987
  /** git 里表示「整个工作树」的路径参数(`.` / `:/` / `*` 等)。 */
1988
1988
  const WHOLE_TREE_GIT_TARGETS = new Set(['.', './', './*', ':/', ':(top)', '*', '**', '.\\']);
1989
1989
 
1990
+ /**
1991
+ * 确认只读(不写工作区)的 git 子命令(v1.5.12 / stage-127 op-004 / P1-3)。
1992
+ *
1993
+ * 旧实现把所有未命中写分支的子命令都当 `readonly` —— `git -c 'alias.zz=commit -a -m pwn' zz`
1994
+ * 因此得到 `kind:'none'`,任意相位放行(真展开成 commit 提交了源码)。未知子命令现在
1995
+ * 落第 4 类(`undecidable`,默认告警 + strict 拒),只保留下面这张正面白名单。
1996
+ * 注意:`bisect` / `submodule` / `worktree` / `lfs` / `add` / `push` / `init` / `clone`
1997
+ * 都会改工作区或仓库状态,**不在**白名单里。
1998
+ */
1999
+ const GIT_READONLY_SUBCOMMANDS = new Set([
2000
+ // 查询类
2001
+ 'status', 'log', 'diff', 'show', 'branch', 'fetch', 'remote', 'rev-parse', 'rev-list',
2002
+ 'ls-files', 'ls-tree', 'ls-remote', 'cat-file', 'hash-object', 'grep', 'blame', 'describe',
2003
+ 'shortlog', 'tag', 'show-ref', 'for-each-ref', 'merge-base', 'name-rev', 'reflog',
2004
+ 'symbolic-ref', 'whatchanged', 'count-objects', 'fsck', 'help', 'version', 'var',
2005
+ 'diff-tree', 'diff-index', 'diff-files', 'check-ignore', 'check-attr', 'cherry', 'notes',
2006
+ 'verify-commit', 'verify-tag', 'range-diff',
2007
+ // 只动 index / refs / 对象库,**不覆盖工作区**(沿用旧行为,避免严格档误杀日常流程)
2008
+ 'add', 'update-index', 'read-tree', 'write-tree', 'commit-tree', 'update-ref', 'pack-refs',
2009
+ 'gc', 'prune', 'maintenance', 'repack', 'rerere', 'replace', 'push',
2010
+ ]);
2011
+
2012
+ /**
2013
+ * `-c` / `--config-env` / `git config` 的**安全键白名单**(v1.5.12 / stage-127 op-006)。
2014
+ *
2015
+ * 旧实现是黑名单(只拦 alias.* / core.hooksPath / core.fsmonitor),于是
2016
+ * `git -c diff.external="sh run-me.sh" diff` / `core.pager` / `core.editor` /
2017
+ * `gpg.program` / `include.path` 这类「外部执行面」全漏。黑名单永远补不完 ——
2018
+ * 改成白名单:只放行确定不会执行外部程序、也不改写仓库归属的键,**其余(含未来新增)
2019
+ * 一律第 1 类硬拒**。
2020
+ *
2021
+ * 精确键:`user.name` / `user.email` / `core.quotepath` / `core.autocrlf` / `core.safecrlf`
2022
+ * 前缀键:`color.*` / `i18n.*`
2023
+ */
2024
+ const SAFE_GIT_CONFIG_KEYS = new Set([
2025
+ 'user.name', 'user.email', 'core.quotepath', 'core.autocrlf', 'core.safecrlf',
2026
+ ]);
2027
+ const SAFE_GIT_CONFIG_PREFIXES = ['color.', 'i18n.'];
2028
+
2029
+ /**
2030
+ * 允许出现在命令位置的 `GIT_*` 环境变量(v1.5.12 / stage-127 op-006)。
2031
+ *
2032
+ * 只允许「身份/时间戳」类:写进提交对象的作者/提交者信息,不触发外部程序、不改仓库。
2033
+ * `GIT_DIR` / `GIT_WORK_TREE` / `GIT_INDEX_FILE`(仓库归属)、`GIT_EXTERNAL_DIFF`、
2034
+ * `GIT_CONFIG_GLOBAL`、`GIT_PAGER`、`GIT_SSH_COMMAND`、`GIT_ASKPASS` … **一律不放行**。
2035
+ */
2036
+ const SAFE_GIT_ENV_VARS = new Set([
2037
+ 'GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL', 'GIT_AUTHOR_DATE',
2038
+ 'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL', 'GIT_COMMITTER_DATE',
2039
+ ]);
2040
+
2041
+ /**
2042
+ * 该 git 配置键是否在安全白名单内(大小写不敏感)。
2043
+ * @param {string} key
2044
+ * @returns {boolean}
2045
+ */
2046
+ function isSafeGitConfigKey(key) {
2047
+ const k = String(key).trim().toLowerCase();
2048
+ if (k === '') return false;
2049
+ if (SAFE_GIT_CONFIG_KEYS.has(k)) return true;
2050
+ return SAFE_GIT_CONFIG_PREFIXES.some((prefix) => k.startsWith(prefix));
2051
+ }
2052
+
2053
+ /**
2054
+ * `-c` / `--config-env` / `git config <key>` 的键安全判定(v1.5.12 / stage-127 op-006)。
2055
+ *
2056
+ * 白名单之外一律返回拒绝理由:未列入安全白名单的配置键**可触发外部程序执行**
2057
+ * (`diff.external` / `core.pager` / `core.editor` / `gpg.program` / `include.path`
2058
+ * / `alias.*` …),静态无法判定。
2059
+ * @param {string} value `-c` 的值(`key=value` / `key`),或 `git config` 的第一个位置参数
2060
+ * @returns {string | null}
2061
+ */
2062
+ function gitUnsafeConfigDetail(value) {
2063
+ if (typeof value !== 'string') return 'git 配置缺少键名';
2064
+ const key = value.replace(/^=/, '').split('=')[0].trim();
2065
+ if (key === '') return 'git 配置缺少键名';
2066
+ if (isSafeGitConfigKey(key)) return null;
2067
+ return `git 配置键 ${key.toLowerCase()} 不在安全白名单(未列入白名单的配置键可触发外部程序执行或改写仓库)`;
2068
+ }
2069
+
2070
+ /**
2071
+ * 扫命令位置的 `VAR=value` 前缀里的非白名单 `GIT_*`(v1.5.12 / stage-127 op-006)。
2072
+ *
2073
+ * 非白名单 `GIT_*` 与 `-c` 是同一类外部执行面(`GIT_EXTERNAL_DIFF` / `GIT_CONFIG_GLOBAL`
2074
+ * / `GIT_PAGER` / `GIT_SSH_COMMAND` / `GIT_ASKPASS` …),一律第 1 类硬拒;
2075
+ * `GIT_DIR` / `GIT_WORK_TREE` / `GIT_INDEX_FILE` 额外说明「无法校验仓库归属」。
2076
+ * @param {string[]} prefixTokens 命令位置上的赋值前缀 token
2077
+ * @returns {string | null}
2078
+ */
2079
+ function findUnsafeGitEnv(prefixTokens) {
2080
+ for (const token of prefixTokens) {
2081
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(String(token));
2082
+ if (match === null) continue;
2083
+ const name = match[1].toUpperCase();
2084
+ if (!name.startsWith('GIT_')) continue;
2085
+ if (SAFE_GIT_ENV_VARS.has(name)) continue;
2086
+ if (name === 'GIT_DIR' || name === 'GIT_WORK_TREE' || name === 'GIT_INDEX_FILE') {
2087
+ return `${name} 改写 git 仓库归属,无法校验仓库归属,一律拒绝`;
2088
+ }
2089
+ return `${name} 不在安全白名单(git 环境变量可触发外部程序执行)`;
2090
+ }
2091
+ return null;
2092
+ }
2093
+
1990
2094
  /**
1991
2095
  * 该 git 路径参数是否覆盖整个工作树(op-005 / P1-2)。
1992
2096
  * @param {string} token
@@ -2007,14 +2111,54 @@ function coversWholeTree(token) {
2007
2111
  * @param {string[]} tokens
2008
2112
  * @param {number} start
2009
2113
  * @param {string} baseDir
2010
- * @returns {{ kind: 'readonly' } | { kind: 'targets', targets: string[] } | { kind: 'whole-tree', detail: string, phases?: string[] } | { kind: 'undecidable', detail: string }}
2114
+ * @returns {{ kind: 'readonly' } | { kind: 'targets', targets: string[] } | { kind: 'whole-tree', detail: string, phases?: string[], gitSubcommand?: string, repoOverride?: boolean, gitConfig?: boolean } | { kind: 'unsafe', detail: string } | { kind: 'undecidable', detail: string }}
2011
2115
  */
2012
2116
  function classifyGitCommand(tokens, start, baseDir) {
2013
2117
  let index = start + 1;
2014
2118
  let subcommand;
2119
+ // v1.5.12 / stage-127 C.4:git 全局选项解析。
2120
+ // **大小写敏感**:`-c`(config)与 `-C`(repo)是不同选项,必须先判 `-C` 再判 `-c`,
2121
+ // 否则 `-C/path` 会被 `-c` 前缀吞掉。分离值形式吞值 `+2`,附着形式(`-cV` / `-c=V`
2122
+ // / `--config-env=V` / `-C=…`)值已在本 token 内,只能 `+1`(再 `+2` 会把 `commit`
2123
+ // 当值吞掉 → 判成 `kind:'none'` 任意相位放行)。
2124
+ let repoOverride = false;
2125
+ /** 是否出现 `-c` / `--config-env`(v1.5.12 / stage-127 op-004 / P1-1)。 */
2126
+ let gitConfig = false;
2015
2127
  while (index < tokens.length && tokens[index] !== '|') {
2016
2128
  const token = tokens[index];
2017
- if (token === '-C' || token === '--git-dir' || token === '--work-tree') { index += 2; continue; }
2129
+ // 仓库改写:`-C` / `--git-dir` / `--work-tree`(精确与附着两种形式)。
2130
+ if (token === '-C' || token === '--git-dir' || token === '--work-tree') {
2131
+ repoOverride = true;
2132
+ index += 2;
2133
+ continue;
2134
+ }
2135
+ if (
2136
+ token.startsWith('-C=')
2137
+ || (token.startsWith('-C') && token.length > 2)
2138
+ || token.startsWith('--git-dir=')
2139
+ || token.startsWith('--work-tree=')
2140
+ ) {
2141
+ repoOverride = true;
2142
+ index += 1;
2143
+ continue;
2144
+ }
2145
+ // config 类:吞值后继续;记录出现过 `-c`(书账分支要求没有),并把
2146
+ // **安全键白名单之外**的键判为外部执行面(op-006:黑名单永远补不完)。
2147
+ if (token === '-c' || token === '--config-env') {
2148
+ gitConfig = true;
2149
+ const unsafe = gitUnsafeConfigDetail(tokens[index + 1]);
2150
+ if (unsafe !== null) return { kind: 'unsafe', detail: unsafe };
2151
+ index += 2;
2152
+ continue;
2153
+ }
2154
+ if (token.startsWith('-c=') || (token.startsWith('-c') && token.length > 2) || token.startsWith('--config-env=')) {
2155
+ gitConfig = true;
2156
+ const value = token.startsWith('--config-env=') ? token.slice('--config-env='.length) : token.slice(2);
2157
+ const unsafe = gitUnsafeConfigDetail(value);
2158
+ if (unsafe !== null) return { kind: 'unsafe', detail: unsafe };
2159
+ index += 1;
2160
+ continue;
2161
+ }
2018
2162
  if (token.startsWith('-')) { index += 1; continue; }
2019
2163
  subcommand = token.toLowerCase();
2020
2164
  break;
@@ -2086,11 +2230,17 @@ function classifyGitCommand(tokens, start, baseDir) {
2086
2230
  // `commit` **不覆盖工作区**(它是把当前状态记进版本库),所以 P1-2 的
2087
2231
  // 「`.openfeel/**` 必须干净」不能套在它身上 —— 否则「先提交 .openfeel」
2088
2232
  // 的修复动作本身会被拒(死锁)。
2233
+ // v1.5.12 / stage-127 C.1/C.4:`gitSubcommand` 与 `repoOverride` 供
2234
+ // 「无阶段纯书账」分支判定(字段白名单必须两处一并透传,见
2235
+ // `analyzeShellStatement` / `classifyShellCommand`)。
2089
2236
  return {
2090
2237
  kind: 'whole-tree',
2091
2238
  detail: 'git commit',
2092
2239
  phases: ['exec_running', 'archiving'],
2093
2240
  preservesWorktree: true,
2241
+ gitSubcommand: 'commit',
2242
+ repoOverride,
2243
+ gitConfig,
2094
2244
  };
2095
2245
  case 'merge':
2096
2246
  case 'rebase':
@@ -2104,9 +2254,29 @@ function classifyGitCommand(tokens, start, baseDir) {
2104
2254
  return positionals.length > 0
2105
2255
  ? { kind: 'targets', targets: positionals }
2106
2256
  : { kind: 'undecidable', detail: `git ${subcommand}` };
2107
- default:
2108
- // `status|log|diff|show|branch|fetch|remote|rev-parse|…` 与其它非工作区写命令
2257
+ case 'config': {
2258
+ // v1.5.12 / stage-127 op-006:持久化配置与 `-c` 是同一类外部执行面
2259
+ // (`diff.external` / `core.pager` / `alias.*` / `include.path` …)。只读用法
2260
+ // (`--get*` / `--list` / `git config <key>` 单参数读值)照旧放行;
2261
+ // **安全键白名单之外**的键写入硬拒(`--unset*` / `--remove-section`
2262
+ // 只会减少攻击面,直接放行)。
2263
+ const readOnly = rest.some((token) => [
2264
+ '--get', '--get-all', '--get-regexp', '--get-urlmatch', '--list', '-l', '--show-origin',
2265
+ '--show-scope', '--name-only', '--null', '-z', '--help', '-h', '--type', '--bool', '--int',
2266
+ ].includes(token));
2267
+ const removing = rest.some((token) => token === '--unset' || token === '--unset-all' || token === '--remove-section');
2268
+ const writing = positionals.length >= 2
2269
+ || rest.some((token) => ['--add', '--replace-all', '--edit', '-e', '--rename-section'].includes(token));
2270
+ const unsafe = readOnly || removing || !writing ? null : gitUnsafeConfigDetail(positionals[0]);
2271
+ if (unsafe !== null) return { kind: 'unsafe', detail: `git config:${unsafe}` };
2109
2272
  return { kind: 'readonly' };
2273
+ }
2274
+ default:
2275
+ // v1.5.12 / stage-127 op-004 / P1-3:**未知子命令不再当只读** ——
2276
+ // `git -c 'alias.zz=…' zz` / 未来新增写子命令都曾因此「任意相位放行」。
2277
+ // 正面白名单之外一律落第 4 类(默认告警 + strict 拒)。
2278
+ if (GIT_READONLY_SUBCOMMANDS.has(subcommand)) return { kind: 'readonly' };
2279
+ return { kind: 'undecidable', detail: `git ${subcommand} 不在只读白名单(写入意图无法判定)` };
2110
2280
  }
2111
2281
  }
2112
2282
 
@@ -2120,7 +2290,7 @@ function classifyGitCommand(tokens, start, baseDir) {
2120
2290
  * @param {string} statement
2121
2291
  * @param {'bash'|'pwsh'} shell
2122
2292
  * @param {string} baseDir
2123
- * @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], undecidable: boolean, detail: string }}
2293
+ * @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], wholeTreeGitSubcommand?: string, wholeTreeRepoOverride?: boolean, wholeTreeGitConfig?: boolean, blockedGit?: string, undecidable: boolean, detail: string }}
2124
2294
  */
2125
2295
  function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2126
2296
  const redirections = scanShellRedirections(statement);
@@ -2138,8 +2308,16 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2138
2308
  // 命令替换(`echo $(touch x)` / 反引号)的内层命令不进入解析器 → 第 4 类。
2139
2309
  // 叠加在正常分析之上(不提前返回):`git commit -m "…$(…)"` 仍按整树写判。
2140
2310
  // 反引号用掩码文本判断,避免提交信息里的反引号被误当命令替换。
2141
- if (/\$\(/.test(statement) || maskQuoted(statement).includes('`')) {
2142
- noteUnknown('命令替换($() / 反引号)的内层命令无法解析');
2311
+ // v1.5.12 / stage-127 op-004(P0):**进程替换** `<(...)` / `>(...)` 同样会真执行内层
2312
+ // 命令(`git commit -m x < <(rm -rf src)`),而且不进 tokenizer → 也记第 4 类。
2313
+ // 引号内是字面量(bash 不展开),所以用掩码文本判,避免提交信息被误杀。
2314
+ const maskedForSubstitution = maskQuoted(statement);
2315
+ if (
2316
+ /\$\(/.test(statement)
2317
+ || maskedForSubstitution.includes('`')
2318
+ || /<\(|>\(/.test(maskedForSubstitution)
2319
+ ) {
2320
+ noteUnknown('命令替换 / 进程替换($() / 反引号 / <() / >())的内层命令无法解析');
2143
2321
  }
2144
2322
 
2145
2323
  for (let index = 0; index < tokens.length; index += 1) {
@@ -2149,11 +2327,17 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2149
2327
  const isCommandStart = index === 0 || tokens[index - 1] === '|' || tokens[index - 1] === '&';
2150
2328
  if (!isCommandStart) continue;
2151
2329
  let cursor = index;
2330
+ // v1.5.12 / stage-127 op-004(P1-4):命令位置的 `VAR=value` 环境赋值前缀。
2331
+ // 不剥离的话 `GIT_DIR=../other/.git GIT_WORK_TREE=../other git commit` 会把
2332
+ // `GIT_DIR=…` 当成「未识别命令」→ 第 4 类默认 warn 放行(真把提交写进别的仓库)。
2333
+ while (cursor < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[cursor])) cursor += 1;
2152
2334
  while (cursor < tokens.length && SHELL_WRAPPER_COMMANDS.has(commandNameOf(tokens[cursor]))) {
2153
2335
  cursor += 1;
2154
2336
  while (cursor < tokens.length && (tokens[cursor].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[cursor]))) cursor += 1;
2155
2337
  }
2156
2338
  if (cursor >= tokens.length || tokens[cursor] === '|') continue;
2339
+ /** 命令位置的赋值前缀(`VAR=value`,含 wrapper 之后的),op-006 用它判 `GIT_*` 白名单。 */
2340
+ const prefixTokens = tokens.slice(index, cursor);
2157
2341
  let name = commandNameOf(tokens[cursor]);
2158
2342
  // `&` / `.` 调用运算符(op-005 / P0-1):被调用者是字面量就按它判,
2159
2343
  // 是**同命令内一次字面量赋值**(`$c='Set-Content'; & $c …`)→ 解析成该程序再判
@@ -2177,7 +2361,15 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2177
2361
  for (let rest = cursor + 1; rest < tokens.length && tokens[rest] !== '|'; rest += 1) args.push(tokens[rest]);
2178
2362
 
2179
2363
  if (name === 'git') {
2364
+ // v1.5.12 / stage-127 op-006:**先判执行面,再判子命令** —— 非白名单 `GIT_*`
2365
+ // 环境前缀(GIT_EXTERNAL_DIFF / GIT_CONFIG_GLOBAL / GIT_PAGER / GIT_SSH_COMMAND /
2366
+ // GIT_ASKPASS / GIT_DIR …)可触发外部程序或改写仓库归属,一律第 1 类硬拒。
2367
+ const unsafeEnv = findUnsafeGitEnv(prefixTokens);
2368
+ if (unsafeEnv !== null) return { targets, blockedGit: unsafeEnv, undecidable, detail };
2180
2369
  const git = classifyGitCommand(tokens, cursor, baseDir);
2370
+ // v1.5.12 / stage-127 op-004/op-006:`-c` / `--config-env` 的键不在安全白名单
2371
+ // 即外部执行面(内容不可见)→ 交回第 1 类硬拒(只读子命令也先过这一关)。
2372
+ if (git.kind === 'unsafe') return { targets, blockedGit: git.detail, undecidable, detail };
2181
2373
  if (git.kind === 'whole-tree') {
2182
2374
  return {
2183
2375
  targets,
@@ -2186,6 +2378,12 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2186
2378
  wholeTreePreservesWorktree: git.preservesWorktree,
2187
2379
  wholeTreeDestroysUntracked: git.destroysUntracked === true,
2188
2380
  wholeTreePurgesIgnored: git.purgesIgnored === true,
2381
+ // v1.5.12 / stage-127 C.1:**新增字段必须同时改这两处白名单**
2382
+ // (这里 + `classifyShellCommand` 的 whole-tree 重建),否则字段丢失
2383
+ // 会让「无阶段纯书账」放行条件恒不成立。
2384
+ wholeTreeGitSubcommand: git.gitSubcommand,
2385
+ wholeTreeRepoOverride: git.repoOverride === true,
2386
+ wholeTreeGitConfig: git.gitConfig === true,
2189
2387
  undecidable,
2190
2388
  detail,
2191
2389
  };
@@ -2291,7 +2489,7 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2291
2489
  * 内层可判定按内层判;内层为空/不可判定 → 第 4 类(`undecidable`)。
2292
2490
  *
2293
2491
  * @param {{ command: string, baseDir: string, shell: 'bash'|'pwsh', depth?: number }} input
2294
- * @returns {{ kind: 'indirect'|'openfeel-write'|'whole-tree'|'targets'|'undecidable'|'none'|'readonly-interpreter', detail: string, targets: string[], undecidable: boolean, phases?: string[] }}
2492
+ * @returns {{ kind: 'indirect'|'openfeel-write'|'whole-tree'|'targets'|'undecidable'|'none'|'readonly-interpreter', detail: string, targets: string[], undecidable: boolean, phases?: string[], gitSubcommand?: string, repoOverride?: boolean, gitConfig?: boolean }}
2295
2493
  */
2296
2494
  export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2297
2495
  const statements = splitShellStatements(command);
@@ -2374,6 +2572,11 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2374
2572
  // 命令替换 / 反引号的内层命令在 `analyzeShellStatement` 里**叠加**判定为第 4 类
2375
2573
  // (不和 git 整树写等更强结论二选一)。
2376
2574
  const analysis = analyzeShellStatement(statement, shell, baseDir, vars);
2575
+ // v1.5.12 / stage-127 op-004(P1-1/P1-3):git 危险配置(`-c alias.*` /
2576
+ // `core.fsmonitor` / `core.hooksPath`)内容不可见 → 第 1 类硬拒。
2577
+ if (analysis.blockedGit !== undefined) {
2578
+ return { kind: 'indirect', detail: analysis.blockedGit, targets: [], undecidable: false };
2579
+ }
2377
2580
  if (analysis.wholeTree !== undefined) {
2378
2581
  return {
2379
2582
  kind: 'whole-tree',
@@ -2382,8 +2585,18 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2382
2585
  preservesWorktree: analysis.wholeTreePreservesWorktree === true,
2383
2586
  destroysUntracked: analysis.wholeTreeDestroysUntracked === true,
2384
2587
  purgesIgnored: analysis.wholeTreePurgesIgnored === true,
2588
+ // v1.5.12 / stage-127 C.1:与 `analyzeShellStatement` 的 whole-tree 返回
2589
+ // **必须同时改**(字段白名单重建会丢字段 → 放行条件恒不成立)。
2590
+ gitSubcommand: analysis.wholeTreeGitSubcommand,
2591
+ repoOverride: analysis.wholeTreeRepoOverride === true,
2592
+ gitConfig: analysis.wholeTreeGitConfig === true,
2385
2593
  targets: [],
2386
- undecidable: false,
2594
+ // v1.5.12 / stage-127 C.1(v4-P0①):这里**原先写死 false**,让
2595
+ // 「undecidable !== true」在 whole-tree 分支成为死条件 ——
2596
+ // 实测 `git commit -m "$(rm -rf src)"` 得到 undecidable:false。
2597
+ // 必须保留 analyzeShellStatement 算出的 `$(` / 反引号 / wrapper 不可判结论。
2598
+ // **不得改回 false**(测试钉死:classifyShellCommand('git commit -m "$(x)").undecidable === true)。
2599
+ undecidable: analysis.undecidable === true,
2387
2600
  };
2388
2601
  }
2389
2602
  for (const raw of analysis.targets) pushTarget(raw);
@@ -2749,6 +2962,160 @@ function openfeelTreeDirty(resolvedCwd, options = {}) {
2749
2962
  return false;
2750
2963
  }
2751
2964
 
2965
+ /**
2966
+ * 「单条纯书账 commit」的**命令文本**硬条件(v1.5.12 / stage-127 C.2)。
2967
+ *
2968
+ * **必须对原始 command 判定,不得先 `maskQuoted`**:
2969
+ * - 单语句(`;` / `&&` / `||` / 换行都被 `splitShellStatements` 切开);
2970
+ * - 无重定向(`git commit -m x > src/x.ts` 会真写源码);
2971
+ * - 原始字符串不含 `$(` 与反引号 —— 双引号内的 `$()` 在 bash 里是**真替换、会真执行**,
2972
+ * 不能因为它在引号里就放过。**已知代价**:单引号内的 `$(` / 反引号也会被误拒
2973
+ * (`git commit -m 'fix $(x)'`)—— 接受,改用双引号或去掉即可;绝不为了少误拒
2974
+ * 而漏检真执行形态。
2975
+ * - 裸 `;` / `|` / `&`:在**掩码后**的文本上判(引号内的 `"a; b"` 不拆语句,属正向边界)。
2976
+ * - v1.5.12 / stage-127 op-004(P0):**进程替换** `<(...)` / `>(...)` 会真执行内层命令
2977
+ * (`git commit -m x < <(rm -rf src)` 七条件全过且真建了文件);输入重定向 `< file`
2978
+ * 同样不是纯书账需要的东西,只放行 `< /dev/null`。两者都按掩码文本判(引号内是字面量)。
2979
+ * @param {string} command
2980
+ * @returns {boolean}
2981
+ */
2982
+ function isSingleSimpleCommit(command) {
2983
+ const text = String(command);
2984
+ if (splitShellStatements(text).length !== 1) return false;
2985
+ if (scanShellRedirections(text).targets.length !== 0) return false;
2986
+ if (/\$\(/.test(text)) return false;
2987
+ if (text.includes('`')) return false;
2988
+ const masked = maskQuoted(text);
2989
+ if (/[;|&]/.test(masked)) return false;
2990
+ if (hasUnsafeInputRedirect(masked)) return false;
2991
+ return true;
2992
+ }
2993
+
2994
+ /**
2995
+ * 掩码文本里是否有「进程替换 / 非 `/dev/null` 输入重定向」(v1.5.12 / stage-127 op-004 P0)。
2996
+ *
2997
+ * 覆盖:`<(...)` / `>(...)`、`<<` 与 `<<<`(heredoc / herestring)、`< file`、`0<file`、
2998
+ * `2< file`。只放行 `</dev/null`(Git Bash 下的空设备)。掩码已把引号内容变成空格,
2999
+ * 所以 `git commit -m "a < b"` 不会被误拒。
3000
+ * @param {string} masked
3001
+ * @returns {boolean}
3002
+ */
3003
+ function hasUnsafeInputRedirect(masked) {
3004
+ for (let index = 0; index < masked.length; index += 1) {
3005
+ if (masked[index] !== '<') continue;
3006
+ const next = masked[index + 1];
3007
+ if (next === '(' || next === '<') return true; // 进程替换 / heredoc-herestring
3008
+ let cursor = index + 1;
3009
+ while (cursor < masked.length && /\s/.test(masked[cursor])) cursor += 1;
3010
+ let target = '';
3011
+ while (cursor < masked.length && !/[\s;&|<>]/.test(masked[cursor])) {
3012
+ target += masked[cursor];
3013
+ cursor += 1;
3014
+ }
3015
+ if (target === '') return true; // `<&3` / 悬空重定向
3016
+ if (target.toLowerCase() !== '/dev/null') return true;
3017
+ index = cursor - 1;
3018
+ }
3019
+ return false;
3020
+ }
3021
+
3022
+ /**
3023
+ * 是否为**直接** git 调用(v1.5.12 / stage-127 C.2 / v4-P0③)。
3024
+ *
3025
+ * 以 `git` 开头(`/^git(\s|$)/`)且没有 `bash -c` / `pwsh -Command` 之类外层 wrapper。
3026
+ * **凡来自 nested wrapper 的分类结果一律不放行**:内层语句分隔 / 替换藏在 wrapper
3027
+ * 字符串里,无法用同一条 `isSingleSimpleCommit` 判定。
3028
+ * @param {string} command
3029
+ * @returns {boolean}
3030
+ */
3031
+ function isDirectGitInvocation(command) {
3032
+ const text = String(command).trim();
3033
+ if (!/^git(\s|$)/.test(text)) return false;
3034
+ return extractWrapperPayload(text) === null;
3035
+ }
3036
+
3037
+ /**
3038
+ * 「纯书账」待提交路径集(v1.5.12 / stage-127 C.3)。
3039
+ *
3040
+ * 用 `git status --porcelain=v1 -z --untracked-files=all` 而不是 `git diff HEAD`:
3041
+ * - porcelain 的 `X` 位能看见 **staged-only**(`git add src/x.ts` 后
3042
+ * `git restore -W -s HEAD src/x.ts` 可让 worktree 干净、`diff HEAD` 看不到);
3043
+ * - `??` 覆盖未跟踪;`X`/`Y` 两个位置全覆盖。
3044
+ * `-z` 关闭引号 + `core.quotePath=false` 双保险。
3045
+ *
3046
+ * v1.5.12 / stage-127 op-004(P1-2 / P2-1):
3047
+ * - `R`/`C` 条目的**新旧路径都参与** offender 判定。只取新路径时
3048
+ * `git mv src/a.ts .openfeel/a.ts` 会被判纯书账放行,而 HEAD 里 `src/a.ts` 被删。
3049
+ * - 判定必须对**实际生效仓库**做:`workdir` 可能指向被外层 `.gitignore` 忽略的嵌套
3050
+ * 仓库(外层判干净、实际提交进 nested)。生效仓库根 ≠ 项目工作区 → 拒绝。
3051
+ *
3052
+ * @param {string} resolvedCwd 会话工作区(项目根)
3053
+ * @param {string} baseDir shell 的相对路径基准(`resolvedCwd + workdir`)
3054
+ * @returns {{ ok: true, offenders: string[] } | { ok: false, offenders: string[], repoMismatch?: boolean, repoRoot?: string } | null}
3055
+ * `null` = 无法判定(非仓库 / 无 HEAD / status 失败)→ 调用方拒绝。
3056
+ */
3057
+ function inspectCommitBookkeeping(resolvedCwd, baseDir = resolvedCwd) {
3058
+ const run = (args, capture = false) => {
3059
+ try {
3060
+ const stdout = execFileSync('git', args, {
3061
+ cwd: resolvedCwd,
3062
+ stdio: capture ? ['ignore', 'pipe', 'ignore'] : 'ignore',
3063
+ encoding: 'utf8',
3064
+ timeout: 5000,
3065
+ windowsHide: true,
3066
+ });
3067
+ return { status: 0, stdout: typeof stdout === 'string' ? stdout : '' };
3068
+ } catch (error) {
3069
+ const status = error !== null && typeof error === 'object' && Number.isInteger(error.status)
3070
+ ? error.status
3071
+ : null;
3072
+ return { status, stdout: '' };
3073
+ }
3074
+ };
3075
+ /** 某个目录实际生效的仓库根(跟随 workdir / 嵌套仓库)。 */
3076
+ const toplevelOf = (dir) => {
3077
+ const result = run(['-C', dir, 'rev-parse', '--show-toplevel'], true);
3078
+ if (result.status !== 0) return null;
3079
+ const text = result.stdout.trim();
3080
+ if (text === '') return null;
3081
+ return normalizeTarget(dir, text);
3082
+ };
3083
+ const repoRoot = toplevelOf(baseDir);
3084
+ if (repoRoot === null) return null;
3085
+ const projectRoot = normalizeTarget(resolvedCwd, '.');
3086
+ if (repoRoot !== projectRoot) {
3087
+ // workdir 落在另一个仓库(常见:被外层 .gitignore 忽略的嵌套仓库)→ 不书账。
3088
+ return { ok: false, offenders: [], repoMismatch: true, repoRoot };
3089
+ }
3090
+ // 非仓库目录里 `git status` 会失败(不同于 `git diff` 退化成 --no-index)→ null。
3091
+ if (run(['rev-parse', '--git-dir']).status !== 0) return null;
3092
+ if (run(['rev-parse', '--verify', '--quiet', 'HEAD']).status !== 0) return null;
3093
+ const status = run(['-c', 'core.quotePath=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all'], true);
3094
+ if (status.status !== 0) return null;
3095
+
3096
+ const entries = status.stdout.split('\0');
3097
+ const paths = [];
3098
+ for (let index = 0; index < entries.length; index += 1) {
3099
+ const entry = entries[index];
3100
+ if (entry === '') continue;
3101
+ // `XY <path>`:`-z` 下没有引号,但格式异常一律按「不可判定」拒绝。
3102
+ if (entry.length < 4) return null;
3103
+ const xy = entry.slice(0, 2);
3104
+ const path = entry.slice(3);
3105
+ if (path === '') return null;
3106
+ // `R`/`C`:下一项是**原路径**;新旧路径**都算**(旧路径可能正是被搬走的源码)。
3107
+ if (xy[0] === 'R' || xy[0] === 'C') {
3108
+ const original = entries[index + 1];
3109
+ index += 1;
3110
+ if (typeof original === 'string' && original !== '') paths.push(original);
3111
+ }
3112
+ paths.push(path);
3113
+ }
3114
+ // 空集合 = 交给 git 报 nothing to commit(不是放行写源码的理由)。
3115
+ const offenders = paths.filter((path) => path !== OPENFEEL_DIR && !path.startsWith(`${OPENFEEL_DIR}/`));
3116
+ return { ok: offenders.length === 0, offenders };
3117
+ }
3118
+
2752
3119
  /**
2753
3120
  * 生成守卫。
2754
3121
  *
@@ -2966,10 +3333,58 @@ export function createOpenFeelGuard(options = {}) {
2966
3333
  // 第 2 类:git 整树工作区写(需要相位 + `.openfeel/**` 无差异,见 P1-2 / P1-4)
2967
3334
  if (classification.kind === 'whole-tree') {
2968
3335
  if (!allowsWholeTreeWrite(resolvedCwd, enforce, classification.phases)) {
2969
- return denyDecidable('shell-git-whole-tree', t(
3336
+ // v1.5.12 / stage-127 §3-C(C.5/C.6)+ op-004 复审修正:无 `exec_running` /
3337
+ // `archiving` 阶段时,只给「单条、直接、纯 `.openfeel/**` 书账」的
3338
+ // `git commit` 开一道窄口。**条件缺一不可**(漏一条即变后门,见 plan R8):
3339
+ // ① 无 exec_running/archiving 阶段 —— 上面 `allowsWholeTreeWrite` 已保证;
3340
+ // ② 是项目工作区且 flow.json 可读(fail-closed:非项目 / flow 读不出
3341
+ // 不等于「无阶段」,不能一律当书账);
3342
+ // ③ 单条简单 commit(对**原始命令**判:无多语句/重定向/`$(`/反引号/进程替换);
3343
+ // ④ 直接 git 调用(无 `bash -c` / `pwsh -Command` 等 wrapper payload);
3344
+ // ⑤ 分类结果可判定(`undecidable !== true`,C.1 修好后才是真条件);
3345
+ // ⑥ 待提交路径(含 R/C 旧路径)全部落在 `.openfeel/` 下,且实际生效仓库
3346
+ // 就是项目工作区自身(workdir 嵌套仓库不放行);
3347
+ // ⑦ 无 `-C` / `--git-dir` / `--work-tree` / `GIT_DIR` 等仓库改写;
3348
+ // ⑧ 无 `-c` / `--config-env`(hooks / fsmonitor / alias 是外部执行面)。
3349
+ const flow = readFlow(resolvedCwd);
3350
+ const canBeBookkeeping = classification.gitSubcommand === 'commit'
3351
+ && classification.repoOverride !== true
3352
+ && classification.gitConfig !== true
3353
+ && classification.undecidable !== true
3354
+ && isSingleSimpleCommit(command)
3355
+ && isDirectGitInvocation(command)
3356
+ && isProjectWorkspace(resolvedCwd) === true
3357
+ && flow.ok === true;
3358
+ const scope = canBeBookkeeping ? inspectCommitBookkeeping(resolvedCwd, baseDir) : null;
3359
+ if (scope !== null && scope.ok === true) return allowShell('git-commit-bookkeeping', []);
3360
+ let denyMessage = t(
2970
3361
  `OpenFeel 写入门禁:禁止在没有 exec_running 阶段时用 shell 做 git 工作区写(${classification.detail})—— 它会整树覆盖/丢弃源码或把状态直接写进仓库,等同绕过文件门禁。请先 feel_flow action=advance 推进到 exec_running;只读查询(git status / log / diff)不受影响。`,
2971
3362
  `OpenFeel write guard: git worktree writes via the shell (${classification.detail}) are blocked without an exec_running stage — they overwrite/discard sources across the whole tree or write repo state, bypassing the file gate. Advance to exec_running with feel_flow action=advance; read-only git status / log / diff are unaffected.`,
2972
- ), []);
3363
+ );
3364
+ if (scope !== null && scope.repoMismatch === true) {
3365
+ denyMessage += `\n${t(
3366
+ `待提交仓库根(${scope.repoRoot})不是项目工作区(${normalizeTarget(resolvedCwd, '.')}):workdir 指向了另一个仓库(常见于被外层 .gitignore 忽略的嵌套仓库),纯书账只对项目自身的仓库生效。`,
3367
+ `The repository root for this commit (${scope.repoRoot}) is not the project workspace (${normalizeTarget(resolvedCwd, '.')}): the workdir points at another repository (often a nested repo ignored by the outer .gitignore). Bookkeeping commits only apply to the project's own repository.`,
3368
+ )}`;
3369
+ } else if (scope !== null && scope.ok === false) {
3370
+ // 安全阀文案(追加行):点名前 5 条外部路径。
3371
+ const shown = scope.offenders.slice(0, 5).join(', ');
3372
+ denyMessage += `\n${t(
3373
+ `本次待提交路径含 .openfeel/ 之外的条目:${shown};该命令仅在提交纯书账时放行。`,
3374
+ `Pending paths include entries outside .openfeel/: ${shown}; this command is only allowed for pure bookkeeping commits.`,
3375
+ )}`;
3376
+ } else if (classification.gitSubcommand === 'commit' && classification.repoOverride === true) {
3377
+ denyMessage += `\n${t(
3378
+ '该 commit 带 -C / --git-dir / --work-tree(或 GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE),无法校验仓库归属,一律拒绝。',
3379
+ 'This commit carries -C / --git-dir / --work-tree (or GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE), so the repository it targets cannot be verified; it is refused.',
3380
+ )}`;
3381
+ } else if (classification.gitSubcommand === 'commit' && classification.gitConfig === true) {
3382
+ denyMessage += `\n${t(
3383
+ '该 commit 带 -c / --config-env(可改写 hooks / fsmonitor / 别名),无法证明只提交书账,一律拒绝。',
3384
+ 'This commit carries -c / --config-env (which can redirect hooks, fsmonitor or aliases), so a pure bookkeeping commit cannot be proven; it is refused.',
3385
+ )}`;
3386
+ }
3387
+ return denyDecidable('shell-git-whole-tree', denyMessage, []);
2973
3388
  }
2974
3389
  // op-005 / P1-2:整树写会覆盖受保护路径所在的 `.openfeel/**`(flow.json /
2975
3390
  // chore.json / guard-audit…),「受保护路径任意相位硬拒」在主相位会被它绕过。
package/dsh/lib/index.js CHANGED
@@ -29,7 +29,7 @@ import { fileURLToPath } from 'node:url';
29
29
  import { FeelCli } from './adapters/cli.js';
30
30
  import { resolveWorkspace } from './adapters/workspace.js';
31
31
  import { writeHostMarker } from './adapters/host-state.js';
32
- import { writeGuardState } from './adapters/guard-state.js';
32
+ import { setGuardRuntimeIdentity, writeGuardState } from './adapters/guard-state.js';
33
33
  import { touchSession } from './adapters/session-cwd-registry.js';
34
34
  import { createOpenFeelGuard, resolveShellGate } from './guard.js';
35
35
  import { createFeelCommandHandler } from './surface/command.js';
@@ -144,6 +144,14 @@ export function apply(ctx, rawConfig) {
144
144
  } catch {
145
145
  /* 标记写入失败 → CLI check 会提示 restart-required,可操作,不阻塞 */
146
146
  }
147
+ // v1.5.12 / stage-127 D1:登记**当前进程**的运行时身份(pid / marker 的 started_at+loaded_hash)。
148
+ // guard-state 写入时用它在 seed 之后覆盖旧身份;旧工作区文件的身份一律剥离,
149
+ // 因此重启后首条判定即可自证可信(不再因旧 hostStartedAt 恒 stale)。
150
+ setGuardRuntimeIdentity({
151
+ pid: process.pid,
152
+ hostStartedAt: hostMarker?.started_at ?? new Date().toISOString(),
153
+ loaded_hash: hostMarker?.loaded_hash ?? '',
154
+ });
147
155
  const log = typeof ctx.logger === 'function'
148
156
  ? ctx.logger('openfeel-dsh')
149
157
  : {