openfeel 1.5.11 → 1.5.13

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
@@ -2002,19 +2106,61 @@ function coversWholeTree(token) {
2002
2106
  * 整树写(`reset --hard`/`--merge`、`stash`(含 `push`)、`clean`、`commit`、
2003
2107
  * `checkout/switch 分支`、`merge/rebase/pull/…`)需要特定相位:
2004
2108
  * - 默认要求 `exec_running`(否则「非 exec 相位用 git 还原/丢弃源码」绕过一切文件门禁);
2005
- * - `commit` 额外允许 `archiving`(op-005 / P1-4:发版提交发生在 archiving);
2109
+ * - `commit` 额外允许 `review_passed` / `test_passed` / `archiving`(op-005 / P1-4:
2110
+ * 发版提交发生在 archiving;v1.5.13 / stage-128:审完即可提交、测完即可提交);
2111
+ * 只放宽 `commit` 的 `phases`,写侧相位门槛(`decideForTargets`)仍只认 `exec_running`;
2006
2112
  * - 进入整树写前还有一道 `.openfeel/**` 无差异检查(op-005 / P1-2),见 `openfeelTreeDirty`。
2007
2113
  * @param {string[]} tokens
2008
2114
  * @param {number} start
2009
2115
  * @param {string} baseDir
2010
- * @returns {{ kind: 'readonly' } | { kind: 'targets', targets: string[] } | { kind: 'whole-tree', detail: string, phases?: string[] } | { kind: 'undecidable', detail: string }}
2116
+ * @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
2117
  */
2012
2118
  function classifyGitCommand(tokens, start, baseDir) {
2013
2119
  let index = start + 1;
2014
2120
  let subcommand;
2121
+ // v1.5.12 / stage-127 C.4:git 全局选项解析。
2122
+ // **大小写敏感**:`-c`(config)与 `-C`(repo)是不同选项,必须先判 `-C` 再判 `-c`,
2123
+ // 否则 `-C/path` 会被 `-c` 前缀吞掉。分离值形式吞值 `+2`,附着形式(`-cV` / `-c=V`
2124
+ // / `--config-env=V` / `-C=…`)值已在本 token 内,只能 `+1`(再 `+2` 会把 `commit`
2125
+ // 当值吞掉 → 判成 `kind:'none'` 任意相位放行)。
2126
+ let repoOverride = false;
2127
+ /** 是否出现 `-c` / `--config-env`(v1.5.12 / stage-127 op-004 / P1-1)。 */
2128
+ let gitConfig = false;
2015
2129
  while (index < tokens.length && tokens[index] !== '|') {
2016
2130
  const token = tokens[index];
2017
- if (token === '-C' || token === '--git-dir' || token === '--work-tree') { index += 2; continue; }
2131
+ // 仓库改写:`-C` / `--git-dir` / `--work-tree`(精确与附着两种形式)。
2132
+ if (token === '-C' || token === '--git-dir' || token === '--work-tree') {
2133
+ repoOverride = true;
2134
+ index += 2;
2135
+ continue;
2136
+ }
2137
+ if (
2138
+ token.startsWith('-C=')
2139
+ || (token.startsWith('-C') && token.length > 2)
2140
+ || token.startsWith('--git-dir=')
2141
+ || token.startsWith('--work-tree=')
2142
+ ) {
2143
+ repoOverride = true;
2144
+ index += 1;
2145
+ continue;
2146
+ }
2147
+ // config 类:吞值后继续;记录出现过 `-c`(书账分支要求没有),并把
2148
+ // **安全键白名单之外**的键判为外部执行面(op-006:黑名单永远补不完)。
2149
+ if (token === '-c' || token === '--config-env') {
2150
+ gitConfig = true;
2151
+ const unsafe = gitUnsafeConfigDetail(tokens[index + 1]);
2152
+ if (unsafe !== null) return { kind: 'unsafe', detail: unsafe };
2153
+ index += 2;
2154
+ continue;
2155
+ }
2156
+ if (token.startsWith('-c=') || (token.startsWith('-c') && token.length > 2) || token.startsWith('--config-env=')) {
2157
+ gitConfig = true;
2158
+ const value = token.startsWith('--config-env=') ? token.slice('--config-env='.length) : token.slice(2);
2159
+ const unsafe = gitUnsafeConfigDetail(value);
2160
+ if (unsafe !== null) return { kind: 'unsafe', detail: unsafe };
2161
+ index += 1;
2162
+ continue;
2163
+ }
2018
2164
  if (token.startsWith('-')) { index += 1; continue; }
2019
2165
  subcommand = token.toLowerCase();
2020
2166
  break;
@@ -2086,11 +2232,20 @@ function classifyGitCommand(tokens, start, baseDir) {
2086
2232
  // `commit` **不覆盖工作区**(它是把当前状态记进版本库),所以 P1-2 的
2087
2233
  // 「`.openfeel/**` 必须干净」不能套在它身上 —— 否则「先提交 .openfeel」
2088
2234
  // 的修复动作本身会被拒(死锁)。
2235
+ // v1.5.12 / stage-127 C.1/C.4:`gitSubcommand` 与 `repoOverride` 供
2236
+ // 「无阶段纯书账」分支判定(字段白名单必须两处一并透传,见
2237
+ // `analyzeShellStatement` / `classifyShellCommand`)。
2238
+ // v1.5.13 / stage-128:审完即可提交(`review_passed`)/ 测完即可提交(`test_passed`),
2239
+ // `done` 仍拒(工作已收口,落地走归档提交)。**只放宽 commit**:写侧相位
2240
+ // (`decideForTargets`)与 `checkout`/`reset --hard`/`stash`/`clean` 一律不动。
2089
2241
  return {
2090
2242
  kind: 'whole-tree',
2091
2243
  detail: 'git commit',
2092
- phases: ['exec_running', 'archiving'],
2244
+ phases: ['exec_running', 'review_passed', 'test_passed', 'archiving'],
2093
2245
  preservesWorktree: true,
2246
+ gitSubcommand: 'commit',
2247
+ repoOverride,
2248
+ gitConfig,
2094
2249
  };
2095
2250
  case 'merge':
2096
2251
  case 'rebase':
@@ -2104,9 +2259,29 @@ function classifyGitCommand(tokens, start, baseDir) {
2104
2259
  return positionals.length > 0
2105
2260
  ? { kind: 'targets', targets: positionals }
2106
2261
  : { kind: 'undecidable', detail: `git ${subcommand}` };
2107
- default:
2108
- // `status|log|diff|show|branch|fetch|remote|rev-parse|…` 与其它非工作区写命令
2262
+ case 'config': {
2263
+ // v1.5.12 / stage-127 op-006:持久化配置与 `-c` 是同一类外部执行面
2264
+ // (`diff.external` / `core.pager` / `alias.*` / `include.path` …)。只读用法
2265
+ // (`--get*` / `--list` / `git config <key>` 单参数读值)照旧放行;
2266
+ // **安全键白名单之外**的键写入硬拒(`--unset*` / `--remove-section`
2267
+ // 只会减少攻击面,直接放行)。
2268
+ const readOnly = rest.some((token) => [
2269
+ '--get', '--get-all', '--get-regexp', '--get-urlmatch', '--list', '-l', '--show-origin',
2270
+ '--show-scope', '--name-only', '--null', '-z', '--help', '-h', '--type', '--bool', '--int',
2271
+ ].includes(token));
2272
+ const removing = rest.some((token) => token === '--unset' || token === '--unset-all' || token === '--remove-section');
2273
+ const writing = positionals.length >= 2
2274
+ || rest.some((token) => ['--add', '--replace-all', '--edit', '-e', '--rename-section'].includes(token));
2275
+ const unsafe = readOnly || removing || !writing ? null : gitUnsafeConfigDetail(positionals[0]);
2276
+ if (unsafe !== null) return { kind: 'unsafe', detail: `git config:${unsafe}` };
2109
2277
  return { kind: 'readonly' };
2278
+ }
2279
+ default:
2280
+ // v1.5.12 / stage-127 op-004 / P1-3:**未知子命令不再当只读** ——
2281
+ // `git -c 'alias.zz=…' zz` / 未来新增写子命令都曾因此「任意相位放行」。
2282
+ // 正面白名单之外一律落第 4 类(默认告警 + strict 拒)。
2283
+ if (GIT_READONLY_SUBCOMMANDS.has(subcommand)) return { kind: 'readonly' };
2284
+ return { kind: 'undecidable', detail: `git ${subcommand} 不在只读白名单(写入意图无法判定)` };
2110
2285
  }
2111
2286
  }
2112
2287
 
@@ -2120,7 +2295,7 @@ function classifyGitCommand(tokens, start, baseDir) {
2120
2295
  * @param {string} statement
2121
2296
  * @param {'bash'|'pwsh'} shell
2122
2297
  * @param {string} baseDir
2123
- * @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], undecidable: boolean, detail: string }}
2298
+ * @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], wholeTreeGitSubcommand?: string, wholeTreeRepoOverride?: boolean, wholeTreeGitConfig?: boolean, blockedGit?: string, undecidable: boolean, detail: string }}
2124
2299
  */
2125
2300
  function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2126
2301
  const redirections = scanShellRedirections(statement);
@@ -2138,8 +2313,16 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2138
2313
  // 命令替换(`echo $(touch x)` / 反引号)的内层命令不进入解析器 → 第 4 类。
2139
2314
  // 叠加在正常分析之上(不提前返回):`git commit -m "…$(…)"` 仍按整树写判。
2140
2315
  // 反引号用掩码文本判断,避免提交信息里的反引号被误当命令替换。
2141
- if (/\$\(/.test(statement) || maskQuoted(statement).includes('`')) {
2142
- noteUnknown('命令替换($() / 反引号)的内层命令无法解析');
2316
+ // v1.5.12 / stage-127 op-004(P0):**进程替换** `<(...)` / `>(...)` 同样会真执行内层
2317
+ // 命令(`git commit -m x < <(rm -rf src)`),而且不进 tokenizer → 也记第 4 类。
2318
+ // 引号内是字面量(bash 不展开),所以用掩码文本判,避免提交信息被误杀。
2319
+ const maskedForSubstitution = maskQuoted(statement);
2320
+ if (
2321
+ /\$\(/.test(statement)
2322
+ || maskedForSubstitution.includes('`')
2323
+ || /<\(|>\(/.test(maskedForSubstitution)
2324
+ ) {
2325
+ noteUnknown('命令替换 / 进程替换($() / 反引号 / <() / >())的内层命令无法解析');
2143
2326
  }
2144
2327
 
2145
2328
  for (let index = 0; index < tokens.length; index += 1) {
@@ -2149,11 +2332,17 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2149
2332
  const isCommandStart = index === 0 || tokens[index - 1] === '|' || tokens[index - 1] === '&';
2150
2333
  if (!isCommandStart) continue;
2151
2334
  let cursor = index;
2335
+ // v1.5.12 / stage-127 op-004(P1-4):命令位置的 `VAR=value` 环境赋值前缀。
2336
+ // 不剥离的话 `GIT_DIR=../other/.git GIT_WORK_TREE=../other git commit` 会把
2337
+ // `GIT_DIR=…` 当成「未识别命令」→ 第 4 类默认 warn 放行(真把提交写进别的仓库)。
2338
+ while (cursor < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[cursor])) cursor += 1;
2152
2339
  while (cursor < tokens.length && SHELL_WRAPPER_COMMANDS.has(commandNameOf(tokens[cursor]))) {
2153
2340
  cursor += 1;
2154
2341
  while (cursor < tokens.length && (tokens[cursor].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[cursor]))) cursor += 1;
2155
2342
  }
2156
2343
  if (cursor >= tokens.length || tokens[cursor] === '|') continue;
2344
+ /** 命令位置的赋值前缀(`VAR=value`,含 wrapper 之后的),op-006 用它判 `GIT_*` 白名单。 */
2345
+ const prefixTokens = tokens.slice(index, cursor);
2157
2346
  let name = commandNameOf(tokens[cursor]);
2158
2347
  // `&` / `.` 调用运算符(op-005 / P0-1):被调用者是字面量就按它判,
2159
2348
  // 是**同命令内一次字面量赋值**(`$c='Set-Content'; & $c …`)→ 解析成该程序再判
@@ -2177,7 +2366,15 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2177
2366
  for (let rest = cursor + 1; rest < tokens.length && tokens[rest] !== '|'; rest += 1) args.push(tokens[rest]);
2178
2367
 
2179
2368
  if (name === 'git') {
2369
+ // v1.5.12 / stage-127 op-006:**先判执行面,再判子命令** —— 非白名单 `GIT_*`
2370
+ // 环境前缀(GIT_EXTERNAL_DIFF / GIT_CONFIG_GLOBAL / GIT_PAGER / GIT_SSH_COMMAND /
2371
+ // GIT_ASKPASS / GIT_DIR …)可触发外部程序或改写仓库归属,一律第 1 类硬拒。
2372
+ const unsafeEnv = findUnsafeGitEnv(prefixTokens);
2373
+ if (unsafeEnv !== null) return { targets, blockedGit: unsafeEnv, undecidable, detail };
2180
2374
  const git = classifyGitCommand(tokens, cursor, baseDir);
2375
+ // v1.5.12 / stage-127 op-004/op-006:`-c` / `--config-env` 的键不在安全白名单
2376
+ // 即外部执行面(内容不可见)→ 交回第 1 类硬拒(只读子命令也先过这一关)。
2377
+ if (git.kind === 'unsafe') return { targets, blockedGit: git.detail, undecidable, detail };
2181
2378
  if (git.kind === 'whole-tree') {
2182
2379
  return {
2183
2380
  targets,
@@ -2186,6 +2383,12 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2186
2383
  wholeTreePreservesWorktree: git.preservesWorktree,
2187
2384
  wholeTreeDestroysUntracked: git.destroysUntracked === true,
2188
2385
  wholeTreePurgesIgnored: git.purgesIgnored === true,
2386
+ // v1.5.12 / stage-127 C.1:**新增字段必须同时改这两处白名单**
2387
+ // (这里 + `classifyShellCommand` 的 whole-tree 重建),否则字段丢失
2388
+ // 会让「无阶段纯书账」放行条件恒不成立。
2389
+ wholeTreeGitSubcommand: git.gitSubcommand,
2390
+ wholeTreeRepoOverride: git.repoOverride === true,
2391
+ wholeTreeGitConfig: git.gitConfig === true,
2189
2392
  undecidable,
2190
2393
  detail,
2191
2394
  };
@@ -2291,7 +2494,7 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2291
2494
  * 内层可判定按内层判;内层为空/不可判定 → 第 4 类(`undecidable`)。
2292
2495
  *
2293
2496
  * @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[] }}
2497
+ * @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
2498
  */
2296
2499
  export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2297
2500
  const statements = splitShellStatements(command);
@@ -2374,6 +2577,11 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2374
2577
  // 命令替换 / 反引号的内层命令在 `analyzeShellStatement` 里**叠加**判定为第 4 类
2375
2578
  // (不和 git 整树写等更强结论二选一)。
2376
2579
  const analysis = analyzeShellStatement(statement, shell, baseDir, vars);
2580
+ // v1.5.12 / stage-127 op-004(P1-1/P1-3):git 危险配置(`-c alias.*` /
2581
+ // `core.fsmonitor` / `core.hooksPath`)内容不可见 → 第 1 类硬拒。
2582
+ if (analysis.blockedGit !== undefined) {
2583
+ return { kind: 'indirect', detail: analysis.blockedGit, targets: [], undecidable: false };
2584
+ }
2377
2585
  if (analysis.wholeTree !== undefined) {
2378
2586
  return {
2379
2587
  kind: 'whole-tree',
@@ -2382,8 +2590,18 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2382
2590
  preservesWorktree: analysis.wholeTreePreservesWorktree === true,
2383
2591
  destroysUntracked: analysis.wholeTreeDestroysUntracked === true,
2384
2592
  purgesIgnored: analysis.wholeTreePurgesIgnored === true,
2593
+ // v1.5.12 / stage-127 C.1:与 `analyzeShellStatement` 的 whole-tree 返回
2594
+ // **必须同时改**(字段白名单重建会丢字段 → 放行条件恒不成立)。
2595
+ gitSubcommand: analysis.wholeTreeGitSubcommand,
2596
+ repoOverride: analysis.wholeTreeRepoOverride === true,
2597
+ gitConfig: analysis.wholeTreeGitConfig === true,
2385
2598
  targets: [],
2386
- undecidable: false,
2599
+ // v1.5.12 / stage-127 C.1(v4-P0①):这里**原先写死 false**,让
2600
+ // 「undecidable !== true」在 whole-tree 分支成为死条件 ——
2601
+ // 实测 `git commit -m "$(rm -rf src)"` 得到 undecidable:false。
2602
+ // 必须保留 analyzeShellStatement 算出的 `$(` / 反引号 / wrapper 不可判结论。
2603
+ // **不得改回 false**(测试钉死:classifyShellCommand('git commit -m "$(x)").undecidable === true)。
2604
+ undecidable: analysis.undecidable === true,
2387
2605
  };
2388
2606
  }
2389
2607
  for (const raw of analysis.targets) pushTarget(raw);
@@ -2670,7 +2888,8 @@ function decideForTargets(context, request) {
2670
2888
  * 未初始化工作区沿用 `enforce` 语义(`always` 下 fail-closed)。
2671
2889
  * @param {string} resolvedCwd
2672
2890
  * @param {'off'|'project'|'always'} enforce
2673
- * @param {string[]} [phases] 放行的相位(缺省 `['exec_running']`;`git commit` 额外允许 `archiving`)
2891
+ * @param {string[]} [phases] 放行的相位(缺省 `['exec_running']`;`git commit` 额外允许
2892
+ * `review_passed` / `test_passed` / `archiving`)
2674
2893
  * @returns {boolean}
2675
2894
  */
2676
2895
  function allowsWholeTreeWrite(resolvedCwd, enforce, phases = ['exec_running']) {
@@ -2749,6 +2968,160 @@ function openfeelTreeDirty(resolvedCwd, options = {}) {
2749
2968
  return false;
2750
2969
  }
2751
2970
 
2971
+ /**
2972
+ * 「单条纯书账 commit」的**命令文本**硬条件(v1.5.12 / stage-127 C.2)。
2973
+ *
2974
+ * **必须对原始 command 判定,不得先 `maskQuoted`**:
2975
+ * - 单语句(`;` / `&&` / `||` / 换行都被 `splitShellStatements` 切开);
2976
+ * - 无重定向(`git commit -m x > src/x.ts` 会真写源码);
2977
+ * - 原始字符串不含 `$(` 与反引号 —— 双引号内的 `$()` 在 bash 里是**真替换、会真执行**,
2978
+ * 不能因为它在引号里就放过。**已知代价**:单引号内的 `$(` / 反引号也会被误拒
2979
+ * (`git commit -m 'fix $(x)'`)—— 接受,改用双引号或去掉即可;绝不为了少误拒
2980
+ * 而漏检真执行形态。
2981
+ * - 裸 `;` / `|` / `&`:在**掩码后**的文本上判(引号内的 `"a; b"` 不拆语句,属正向边界)。
2982
+ * - v1.5.12 / stage-127 op-004(P0):**进程替换** `<(...)` / `>(...)` 会真执行内层命令
2983
+ * (`git commit -m x < <(rm -rf src)` 七条件全过且真建了文件);输入重定向 `< file`
2984
+ * 同样不是纯书账需要的东西,只放行 `< /dev/null`。两者都按掩码文本判(引号内是字面量)。
2985
+ * @param {string} command
2986
+ * @returns {boolean}
2987
+ */
2988
+ function isSingleSimpleCommit(command) {
2989
+ const text = String(command);
2990
+ if (splitShellStatements(text).length !== 1) return false;
2991
+ if (scanShellRedirections(text).targets.length !== 0) return false;
2992
+ if (/\$\(/.test(text)) return false;
2993
+ if (text.includes('`')) return false;
2994
+ const masked = maskQuoted(text);
2995
+ if (/[;|&]/.test(masked)) return false;
2996
+ if (hasUnsafeInputRedirect(masked)) return false;
2997
+ return true;
2998
+ }
2999
+
3000
+ /**
3001
+ * 掩码文本里是否有「进程替换 / 非 `/dev/null` 输入重定向」(v1.5.12 / stage-127 op-004 P0)。
3002
+ *
3003
+ * 覆盖:`<(...)` / `>(...)`、`<<` 与 `<<<`(heredoc / herestring)、`< file`、`0<file`、
3004
+ * `2< file`。只放行 `</dev/null`(Git Bash 下的空设备)。掩码已把引号内容变成空格,
3005
+ * 所以 `git commit -m "a < b"` 不会被误拒。
3006
+ * @param {string} masked
3007
+ * @returns {boolean}
3008
+ */
3009
+ function hasUnsafeInputRedirect(masked) {
3010
+ for (let index = 0; index < masked.length; index += 1) {
3011
+ if (masked[index] !== '<') continue;
3012
+ const next = masked[index + 1];
3013
+ if (next === '(' || next === '<') return true; // 进程替换 / heredoc-herestring
3014
+ let cursor = index + 1;
3015
+ while (cursor < masked.length && /\s/.test(masked[cursor])) cursor += 1;
3016
+ let target = '';
3017
+ while (cursor < masked.length && !/[\s;&|<>]/.test(masked[cursor])) {
3018
+ target += masked[cursor];
3019
+ cursor += 1;
3020
+ }
3021
+ if (target === '') return true; // `<&3` / 悬空重定向
3022
+ if (target.toLowerCase() !== '/dev/null') return true;
3023
+ index = cursor - 1;
3024
+ }
3025
+ return false;
3026
+ }
3027
+
3028
+ /**
3029
+ * 是否为**直接** git 调用(v1.5.12 / stage-127 C.2 / v4-P0③)。
3030
+ *
3031
+ * 以 `git` 开头(`/^git(\s|$)/`)且没有 `bash -c` / `pwsh -Command` 之类外层 wrapper。
3032
+ * **凡来自 nested wrapper 的分类结果一律不放行**:内层语句分隔 / 替换藏在 wrapper
3033
+ * 字符串里,无法用同一条 `isSingleSimpleCommit` 判定。
3034
+ * @param {string} command
3035
+ * @returns {boolean}
3036
+ */
3037
+ function isDirectGitInvocation(command) {
3038
+ const text = String(command).trim();
3039
+ if (!/^git(\s|$)/.test(text)) return false;
3040
+ return extractWrapperPayload(text) === null;
3041
+ }
3042
+
3043
+ /**
3044
+ * 「纯书账」待提交路径集(v1.5.12 / stage-127 C.3)。
3045
+ *
3046
+ * 用 `git status --porcelain=v1 -z --untracked-files=all` 而不是 `git diff HEAD`:
3047
+ * - porcelain 的 `X` 位能看见 **staged-only**(`git add src/x.ts` 后
3048
+ * `git restore -W -s HEAD src/x.ts` 可让 worktree 干净、`diff HEAD` 看不到);
3049
+ * - `??` 覆盖未跟踪;`X`/`Y` 两个位置全覆盖。
3050
+ * `-z` 关闭引号 + `core.quotePath=false` 双保险。
3051
+ *
3052
+ * v1.5.12 / stage-127 op-004(P1-2 / P2-1):
3053
+ * - `R`/`C` 条目的**新旧路径都参与** offender 判定。只取新路径时
3054
+ * `git mv src/a.ts .openfeel/a.ts` 会被判纯书账放行,而 HEAD 里 `src/a.ts` 被删。
3055
+ * - 判定必须对**实际生效仓库**做:`workdir` 可能指向被外层 `.gitignore` 忽略的嵌套
3056
+ * 仓库(外层判干净、实际提交进 nested)。生效仓库根 ≠ 项目工作区 → 拒绝。
3057
+ *
3058
+ * @param {string} resolvedCwd 会话工作区(项目根)
3059
+ * @param {string} baseDir shell 的相对路径基准(`resolvedCwd + workdir`)
3060
+ * @returns {{ ok: true, offenders: string[] } | { ok: false, offenders: string[], repoMismatch?: boolean, repoRoot?: string } | null}
3061
+ * `null` = 无法判定(非仓库 / 无 HEAD / status 失败)→ 调用方拒绝。
3062
+ */
3063
+ function inspectCommitBookkeeping(resolvedCwd, baseDir = resolvedCwd) {
3064
+ const run = (args, capture = false) => {
3065
+ try {
3066
+ const stdout = execFileSync('git', args, {
3067
+ cwd: resolvedCwd,
3068
+ stdio: capture ? ['ignore', 'pipe', 'ignore'] : 'ignore',
3069
+ encoding: 'utf8',
3070
+ timeout: 5000,
3071
+ windowsHide: true,
3072
+ });
3073
+ return { status: 0, stdout: typeof stdout === 'string' ? stdout : '' };
3074
+ } catch (error) {
3075
+ const status = error !== null && typeof error === 'object' && Number.isInteger(error.status)
3076
+ ? error.status
3077
+ : null;
3078
+ return { status, stdout: '' };
3079
+ }
3080
+ };
3081
+ /** 某个目录实际生效的仓库根(跟随 workdir / 嵌套仓库)。 */
3082
+ const toplevelOf = (dir) => {
3083
+ const result = run(['-C', dir, 'rev-parse', '--show-toplevel'], true);
3084
+ if (result.status !== 0) return null;
3085
+ const text = result.stdout.trim();
3086
+ if (text === '') return null;
3087
+ return normalizeTarget(dir, text);
3088
+ };
3089
+ const repoRoot = toplevelOf(baseDir);
3090
+ if (repoRoot === null) return null;
3091
+ const projectRoot = normalizeTarget(resolvedCwd, '.');
3092
+ if (repoRoot !== projectRoot) {
3093
+ // workdir 落在另一个仓库(常见:被外层 .gitignore 忽略的嵌套仓库)→ 不书账。
3094
+ return { ok: false, offenders: [], repoMismatch: true, repoRoot };
3095
+ }
3096
+ // 非仓库目录里 `git status` 会失败(不同于 `git diff` 退化成 --no-index)→ null。
3097
+ if (run(['rev-parse', '--git-dir']).status !== 0) return null;
3098
+ if (run(['rev-parse', '--verify', '--quiet', 'HEAD']).status !== 0) return null;
3099
+ const status = run(['-c', 'core.quotePath=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all'], true);
3100
+ if (status.status !== 0) return null;
3101
+
3102
+ const entries = status.stdout.split('\0');
3103
+ const paths = [];
3104
+ for (let index = 0; index < entries.length; index += 1) {
3105
+ const entry = entries[index];
3106
+ if (entry === '') continue;
3107
+ // `XY <path>`:`-z` 下没有引号,但格式异常一律按「不可判定」拒绝。
3108
+ if (entry.length < 4) return null;
3109
+ const xy = entry.slice(0, 2);
3110
+ const path = entry.slice(3);
3111
+ if (path === '') return null;
3112
+ // `R`/`C`:下一项是**原路径**;新旧路径**都算**(旧路径可能正是被搬走的源码)。
3113
+ if (xy[0] === 'R' || xy[0] === 'C') {
3114
+ const original = entries[index + 1];
3115
+ index += 1;
3116
+ if (typeof original === 'string' && original !== '') paths.push(original);
3117
+ }
3118
+ paths.push(path);
3119
+ }
3120
+ // 空集合 = 交给 git 报 nothing to commit(不是放行写源码的理由)。
3121
+ const offenders = paths.filter((path) => path !== OPENFEEL_DIR && !path.startsWith(`${OPENFEEL_DIR}/`));
3122
+ return { ok: offenders.length === 0, offenders };
3123
+ }
3124
+
2752
3125
  /**
2753
3126
  * 生成守卫。
2754
3127
  *
@@ -2966,10 +3339,71 @@ export function createOpenFeelGuard(options = {}) {
2966
3339
  // 第 2 类:git 整树工作区写(需要相位 + `.openfeel/**` 无差异,见 P1-2 / P1-4)
2967
3340
  if (classification.kind === 'whole-tree') {
2968
3341
  if (!allowsWholeTreeWrite(resolvedCwd, enforce, classification.phases)) {
2969
- return denyDecidable('shell-git-whole-tree', t(
2970
- `OpenFeel 写入门禁:禁止在没有 exec_running 阶段时用 shell 做 git 工作区写(${classification.detail})—— 它会整树覆盖/丢弃源码或把状态直接写进仓库,等同绕过文件门禁。请先 feel_flow action=advance 推进到 exec_running;只读查询(git status / log / diff)不受影响。`,
2971
- `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
- ), []);
3342
+ // v1.5.12 / stage-127 §3-C(C.5/C.6)+ op-004 复审修正:无 `exec_running` /
3343
+ // `review_passed` / `test_passed` / `archiving` 阶段时,只给「单条、直接、纯
3344
+ // `.openfeel/**` 书账」的 `git commit` 开一道窄口。**条件缺一不可**(漏一条即变后门,见 plan R8):
3345
+ // ① 无上述四相位阶段 —— 上面 `allowsWholeTreeWrite` 已保证(v1.5.13 / stage-128
3346
+ // 把 `review_passed` / `test_passed` 并入白名单后,二者不再走这道窄口,窄口只剩
3347
+ // `plan_*` / `scheme_*` / `review_pending` / `review_failed` / `test_pending` /
3348
+ // `test_failed` / `done` 七类);
3349
+ // ② 是项目工作区且 flow.json 可读(fail-closed:非项目 / flow 读不出
3350
+ // 不等于「无阶段」,不能一律当书账);
3351
+ // ③ 单条简单 commit(对**原始命令**判:无多语句/重定向/`$(`/反引号/进程替换);
3352
+ // ④ 直接 git 调用(无 `bash -c` / `pwsh -Command` 等 wrapper payload);
3353
+ // ⑤ 分类结果可判定(`undecidable !== true`,C.1 修好后才是真条件);
3354
+ // ⑥ 待提交路径(含 R/C 旧路径)全部落在 `.openfeel/` 下,且实际生效仓库
3355
+ // 就是项目工作区自身(workdir 嵌套仓库不放行);
3356
+ // ⑦ 无 `-C` / `--git-dir` / `--work-tree` / `GIT_DIR` 等仓库改写;
3357
+ // ⑧ 无 `-c` / `--config-env`(hooks / fsmonitor / alias 是外部执行面)。
3358
+ const flow = readFlow(resolvedCwd);
3359
+ const canBeBookkeeping = classification.gitSubcommand === 'commit'
3360
+ && classification.repoOverride !== true
3361
+ && classification.gitConfig !== true
3362
+ && classification.undecidable !== true
3363
+ && isSingleSimpleCommit(command)
3364
+ && isDirectGitInvocation(command)
3365
+ && isProjectWorkspace(resolvedCwd) === true
3366
+ && flow.ok === true;
3367
+ const scope = canBeBookkeeping ? inspectCommitBookkeeping(resolvedCwd, baseDir) : null;
3368
+ if (scope !== null && scope.ok === true) return allowShell('git-commit-bookkeeping', []);
3369
+ // v1.5.13 / stage-128:文案按子命令分叉,相位串从 `classification.phases`
3370
+ // 派生(单一真值,防数组与文案两处漂移)。**必须保留**「git 工作区写」字样
3371
+ // (既有断言 `/git 工作区写/`),非 commit 的通用文案逐字保留(stash/clean/
3372
+ // reset --hard 仍在文案里提示 advance 到 exec_running,不能谎报四相位可用)。
3373
+ const allowedPhaseList = (classification.phases ?? ['exec_running']).join(' / ');
3374
+ let denyMessage = classification.gitSubcommand === 'commit'
3375
+ ? t(
3376
+ `OpenFeel 写入门禁:禁止在当前阶段用 shell 做 git 工作区写(${classification.detail})—— git commit 只允许活跃阶段处于 ${allowedPhaseList} 之一;plan_* / scheme_* / review_pending / review_failed / test_pending / test_failed / done 一律拒绝(done 表示工作已收口,请走归档提交)。只读查询(git status / log / diff)不受影响。`,
3377
+ `OpenFeel write guard: git worktree writes via the shell (${classification.detail}) are blocked in this phase — git commit is only allowed when an active stage is in ${allowedPhaseList}; plan_* / scheme_* / review_pending / review_failed / test_pending / test_failed / done are always refused (done means the work is closed — commit through the archive flow). Read-only git status / log / diff are unaffected.`,
3378
+ )
3379
+ : t(
3380
+ `OpenFeel 写入门禁:禁止在没有 exec_running 阶段时用 shell 做 git 工作区写(${classification.detail})—— 它会整树覆盖/丢弃源码或把状态直接写进仓库,等同绕过文件门禁。请先 feel_flow action=advance 推进到 exec_running;只读查询(git status / log / diff)不受影响。`,
3381
+ `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.`,
3382
+ );
3383
+ if (scope !== null && scope.repoMismatch === true) {
3384
+ denyMessage += `\n${t(
3385
+ `待提交仓库根(${scope.repoRoot})不是项目工作区(${normalizeTarget(resolvedCwd, '.')}):workdir 指向了另一个仓库(常见于被外层 .gitignore 忽略的嵌套仓库),纯书账只对项目自身的仓库生效。`,
3386
+ `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.`,
3387
+ )}`;
3388
+ } else if (scope !== null && scope.ok === false) {
3389
+ // 安全阀文案(追加行):点名前 5 条外部路径。
3390
+ const shown = scope.offenders.slice(0, 5).join(', ');
3391
+ denyMessage += `\n${t(
3392
+ `本次待提交路径含 .openfeel/ 之外的条目:${shown};该命令仅在提交纯书账时放行。`,
3393
+ `Pending paths include entries outside .openfeel/: ${shown}; this command is only allowed for pure bookkeeping commits.`,
3394
+ )}`;
3395
+ } else if (classification.gitSubcommand === 'commit' && classification.repoOverride === true) {
3396
+ denyMessage += `\n${t(
3397
+ '该 commit 带 -C / --git-dir / --work-tree(或 GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE),无法校验仓库归属,一律拒绝。',
3398
+ '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.',
3399
+ )}`;
3400
+ } else if (classification.gitSubcommand === 'commit' && classification.gitConfig === true) {
3401
+ denyMessage += `\n${t(
3402
+ '该 commit 带 -c / --config-env(可改写 hooks / fsmonitor / 别名),无法证明只提交书账,一律拒绝。',
3403
+ 'This commit carries -c / --config-env (which can redirect hooks, fsmonitor or aliases), so a pure bookkeeping commit cannot be proven; it is refused.',
3404
+ )}`;
3405
+ }
3406
+ return denyDecidable('shell-git-whole-tree', denyMessage, []);
2973
3407
  }
2974
3408
  // op-005 / P1-2:整树写会覆盖受保护路径所在的 `.openfeel/**`(flow.json /
2975
3409
  // 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
  : {