dsh-project-flow 0.9.2 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -0
- package/README.md +25 -0
- package/checks/assertion.mjs +104 -0
- package/checks/command.mjs +416 -0
- package/checks/requirement.mjs +91 -0
- package/commands/slash.mjs +754 -0
- package/commands/steer.mjs +43 -0
- package/config/settings.mjs +217 -0
- package/docs/DETAIL.md +2 -0
- package/docs/FEATURES.md +9 -6
- package/docs/anchors/file-whitelist.md +1 -1
- package/http/routes.mjs +252 -0
- package/index.js +173 -8538
- package/issues/issue.mjs +322 -0
- package/package.json +16 -1
- package/persistence/lock.mjs +67 -0
- package/persistence/log.mjs +43 -0
- package/persistence/recovery.mjs +118 -0
- package/persistence/state.mjs +202 -0
- package/pricing/estimate.mjs +72 -0
- package/prompts/rules.mjs +192 -0
- package/rollback/ledger.mjs +237 -0
- package/runner/pipeline.mjs +1190 -0
- package/runner/stage.mjs +370 -0
- package/runner/tools/context.mjs +64 -0
- package/runner/tools/decorate-cost.mjs +49 -0
- package/runner/tools/doctor.mjs +59 -0
- package/runner/tools/estimate.mjs +63 -0
- package/runner/tools/execute-run.mjs +255 -0
- package/runner/tools/models.mjs +55 -0
- package/runner/tools/resume.mjs +136 -0
- package/runner/tools/rollback.mjs +291 -0
- package/runner/tools/run.mjs +262 -0
- package/runner/tools/set.mjs +65 -0
- package/runner/tools/snapshots.mjs +83 -0
- package/runner/tools/status.mjs +70 -0
- package/runner/tools.mjs +94 -0
- package/shared/constants.mjs +273 -0
- package/shared/tool.mjs +32 -0
- package/shared/util.mjs +231 -0
- package/snapshot/repo.mjs +452 -0
- package/state/registry.mjs +40 -0
- package/tests/aesthetic.test.mjs +20 -12
- package/tests/apply-wiring.test.mjs +172 -0
- package/tests/assertions-e2e.mjs +2 -1
- package/tests/atomic-write.test.mjs +129 -0
- package/tests/client-bundle.test.mjs +3 -3
- package/tests/command-whitelist.test.mjs +135 -0
- package/tests/contract.test.mjs +2 -2
- package/tests/desktop.test.mjs +2 -2
- package/tests/domains.test.mjs +10 -7
- package/tests/e2e.mjs +2 -1
- package/tests/extra-phase.test.mjs +2 -2
- package/tests/feedback.test.mjs +2 -1
- package/tests/flow-gate.test.mjs +16 -56
- package/tests/issues-e2e.mjs +2 -1
- package/tests/panel-independence.test.mjs +2 -2
- package/tests/panel-report.test.mjs +2 -2
- package/tests/paths.mjs +70 -1
- package/tests/preview-path.test.mjs +2 -1
- package/tests/qa-assertions.test.mjs +10 -3
- package/tests/run-all.mjs +6 -0
- package/tests/snapshot-core.test.mjs +234 -0
- package/tests/stage-model.test.mjs +2 -2
- package/tests/steer-command.test.mjs +151 -0
- package/tests/stop-resume.test.mjs +7 -2
- package/tests/watch-root.test.mjs +2 -1
- package/ui/prompt.mjs +101 -0
- package/workspace/models.mjs +111 -0
- package/workspace/panel.mjs +359 -0
- package/workspace/paths.mjs +393 -0
- package/workspace/resume.mjs +107 -0
package/CHANGELOG.md
CHANGED
|
Binary file
|
package/README.md
CHANGED
|
@@ -59,6 +59,8 @@ dsh plugin --profile <你的 profile> add dsh-project-flow
|
|
|
59
59
|
|
|
60
60
|
默认 `off`:在哪个目录都能开工作模式,装完就能用,不用先建目录再切工作区。
|
|
61
61
|
|
|
62
|
+
`flowGate` 和 `intentGate` 默认都是 `off`,这是**低门槛优先**的取舍:装完就能用,不拿门控挡路。它们管的是「会不会在你不想动的目录、没问清的意图上动手」,**不是安全隔离**——不做身份校验,也不当权限边界,白名单和 `.project-flow` 下的产物都不是。想硬一点就往 `strict` / `enforce` 调,但那仍然只是多一道确认;真正的安全边界要靠宿主自己的权限设置。
|
|
63
|
+
|
|
62
64
|
想让目录边界硬一点就设 `flowGate: strict`——那时只认「工作流」目录,不在那儿会拒绝并告诉你去哪。也可以用 `flowRoot` 填绝对路径把工作流固定到一个地方;`flowRoot` 只影响「该去哪」,不拦别处。
|
|
63
65
|
|
|
64
66
|
| `flowGate` | 行为 |
|
|
@@ -203,6 +205,29 @@ PF_LIVE_DIR=D:\path\to\installed\dsh-project-flow node tests/run-all.mjs
|
|
|
203
205
|
|
|
204
206
|
## 改代码时怎么验
|
|
205
207
|
|
|
208
|
+
源码是分模块的,`index.js` 只剩装配(210 行);工具、流水、快照、回滚各在
|
|
209
|
+
自己的目录里,改动落在哪个目录就去验那个目录。
|
|
210
|
+
|
|
211
|
+
```
|
|
212
|
+
shared/ 常量、小工具、工具定义装配
|
|
213
|
+
state/ 跨模块共享的活对象与服务句柄
|
|
214
|
+
config/ 配置解析(patch 值 + JSON 覆盖文件)
|
|
215
|
+
persistence/ state.json、四份产物、日志、锁、自愈
|
|
216
|
+
snapshot/ 快照仓(独立 git 树)
|
|
217
|
+
rollback/ 补丁台账与按台账回滚
|
|
218
|
+
checks/ 判据执行、断言判定
|
|
219
|
+
issues/ 问题闭环
|
|
220
|
+
runner/ 单阶执行、三段流水;runner/tools/ 下每个工具一个文件
|
|
221
|
+
prompts/ 三个子会话看到的提示词
|
|
222
|
+
workspace/ 路径门控、状态栏数据、续跑、模型目录
|
|
223
|
+
pricing/ 估价
|
|
224
|
+
http/ 给状态栏的只读路由
|
|
225
|
+
commands/ 斜杠命令、把指令送到模型
|
|
226
|
+
ui/ 注入给模型的系统提示
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
分层规则:下层不 import 上层。`shared` 谁都能用,`ui` / `http` / `commands` 在最上面。
|
|
230
|
+
|
|
206
231
|
开发仓库里另有一份 `run-all.mjs`(35 套),多出来的就是上面那 5 套。它在仓库根,不进包。
|
|
207
232
|
|
|
208
233
|
改判定逻辑之后 `npm run bench` 应该告诉你哪条语料变了——那是这套东西存在的理由。
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 断言判定:退出码说了算;判不了不等于判过了。
|
|
3
|
+
*/
|
|
4
|
+
import { issueLines } from '../issues/issue.mjs'
|
|
5
|
+
import { quoteScalar } from '../shared/util.mjs'
|
|
6
|
+
|
|
7
|
+
export function criteriaInPlay(assertions) {
|
|
8
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
9
|
+
return list.some(item => item.status !== 'unverified')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function gateAssertions(assertions, requirementCount) {
|
|
13
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
14
|
+
const failed = list.filter(item => item.status === 'fail' || item.status === 'denied')
|
|
15
|
+
const unverified = list.filter(item => item.status === 'unverified')
|
|
16
|
+
const passed = list.filter(item => item.status === 'pass')
|
|
17
|
+
const covered = new Set(list.map(item => item.req))
|
|
18
|
+
const total = Number.isInteger(requirementCount) && requirementCount > 0 ? requirementCount : covered.size
|
|
19
|
+
const uncovered = []
|
|
20
|
+
for (let index = 1; index <= total; index += 1) if (!covered.has(index)) uncovered.push(index)
|
|
21
|
+
const verdict = failed.length > 0 ? 'FAIL' : (unverified.length > 0 || uncovered.length > 0) ? 'UNVERIFIED' : 'PASS'
|
|
22
|
+
return {
|
|
23
|
+
verdict,
|
|
24
|
+
failed,
|
|
25
|
+
unverified,
|
|
26
|
+
passed,
|
|
27
|
+
uncovered,
|
|
28
|
+
total,
|
|
29
|
+
checked: list.length,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function describeAssertions(gate) {
|
|
34
|
+
if (gate === undefined || gate === null) return ''
|
|
35
|
+
const lines = [
|
|
36
|
+
'## 插件自己跑过的断言(这部分不是模型判断,是命令的退出码)',
|
|
37
|
+
'',
|
|
38
|
+
`结论:${gate.verdict}|共 ${gate.total} 条要求,有判据 ${gate.checked} 条,过 ${gate.passed.length} 条,`
|
|
39
|
+
+ `未过 ${gate.failed.length} 条,判不了 ${gate.unverified.length + gate.uncovered.length} 条`,
|
|
40
|
+
]
|
|
41
|
+
if (gate.checked === 0) {
|
|
42
|
+
lines.push('', '这次一条 check 都没有:所有要求都是 unverified,按规矩不能算 PASS。')
|
|
43
|
+
return lines.join('\n')
|
|
44
|
+
}
|
|
45
|
+
for (const item of gate.failed) {
|
|
46
|
+
lines.push('', `- 第 ${item.req} 条:${item.cmd}`, ` 退出码 ${item.exit ?? '?'},用时 ${item.durationMs}ms`)
|
|
47
|
+
if (item.timeout === true) lines.push(' 超时被收掉(timeout: true)')
|
|
48
|
+
const tail = String(item.stdoutTail ?? '').trim()
|
|
49
|
+
if (tail !== '') lines.push(' 输出的尾巴:', ' ```', ...tail.split(/\r?\n/u).slice(-15).map(line => ` ${line}`), ' ```')
|
|
50
|
+
}
|
|
51
|
+
for (const item of gate.unverified) {
|
|
52
|
+
lines.push('', `- 第 ${item.req} 条:没有 check,判不了(unverified)`)
|
|
53
|
+
}
|
|
54
|
+
return lines.join('\n')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function renderAssertionsBlock(assertions, meta = {}) {
|
|
58
|
+
const lines = ['---']
|
|
59
|
+
if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
|
|
60
|
+
if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
|
|
61
|
+
lines.push(...assertionFrontLines(assertions))
|
|
62
|
+
lines.push('---')
|
|
63
|
+
return lines.join('\n')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function assertionFrontLines(assertions) {
|
|
67
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
68
|
+
if (list.length === 0) return ['assertions: []']
|
|
69
|
+
const lines = ['assertions:']
|
|
70
|
+
for (const item of list) {
|
|
71
|
+
lines.push(` - req: ${Number.isInteger(item.req) ? item.req : 0}`)
|
|
72
|
+
lines.push(` cmd: ${!item.cmd && item.cmd !== 0 ? "''" : quoteScalar(String(item.cmd))}`)
|
|
73
|
+
lines.push(` exit: ${typeof item.exit === 'number' ? item.exit : 'null'}`)
|
|
74
|
+
lines.push(` durationMs: ${Number.isInteger(item.durationMs) ? item.durationMs : 0}`)
|
|
75
|
+
lines.push(` status: ${item.status ?? 'unknown'}`)
|
|
76
|
+
if (item.timeout === true) lines.push(' timeout: true')
|
|
77
|
+
if (item.denied === true) lines.push(' denied: true')
|
|
78
|
+
const tail = String(item.stdoutTail ?? '')
|
|
79
|
+
if (tail === '') {
|
|
80
|
+
lines.push(" stdoutTail: ''")
|
|
81
|
+
} else {
|
|
82
|
+
lines.push(' stdoutTail: |')
|
|
83
|
+
for (const line of tail.split(/\r?\n/u)) lines.push(` ${line}`)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return lines
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function renderQaFrontMatter(meta = {}) {
|
|
90
|
+
const lines = ['---']
|
|
91
|
+
if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
|
|
92
|
+
if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
|
|
93
|
+
const issues = Array.isArray(meta.issues) ? meta.issues : []
|
|
94
|
+
if (issues.length === 0) {
|
|
95
|
+
lines.push('issues: []')
|
|
96
|
+
} else {
|
|
97
|
+
lines.push('issues:')
|
|
98
|
+
for (const issue of issues) lines.push(...issueLines(issue))
|
|
99
|
+
}
|
|
100
|
+
lines.push(...assertionFrontLines(meta.assertions))
|
|
101
|
+
lines.push('---')
|
|
102
|
+
return lines.join('\n')
|
|
103
|
+
}
|
|
104
|
+
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 判据执行器:白名单、命令解析、Windows 上的 .cmd 走法、超时、输出只留尾巴。
|
|
3
|
+
*/
|
|
4
|
+
import { basename, join, isAbsolute, delimiter, dirname, relative, resolve } from 'node:path'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { writeFileSync, rmSync, existsSync, realpathSync } from 'node:fs'
|
|
7
|
+
import { execFile } from 'node:child_process'
|
|
8
|
+
import { CHECK_MISSING_BINARY_LIMIT, CODE_ESCAPE_FLAGS, DEFAULT_ALLOWED_COMMANDS, DEFAULT_CHECK_TAIL_CHARS, DEFAULT_CHECK_TIMEOUT_MS, GIT_DANGEROUS_CONFIG, PACKAGE_RUNNERS, STRICT_ONLY_FLAGS } from '../shared/constants.mjs'
|
|
9
|
+
import { messageOf, tailOf } from '../shared/util.mjs'
|
|
10
|
+
|
|
11
|
+
export function commandNameOf(token) {
|
|
12
|
+
const base = basename(String(token ?? '').trim()).toLowerCase()
|
|
13
|
+
return base.replace(/\.(exe|cmd|bat|ps1)$/u, '')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function checkCodeEscape(name, args, strictEval = false) {
|
|
17
|
+
const direct = CODE_ESCAPE_FLAGS[name]
|
|
18
|
+
if (Array.isArray(direct) && direct.length > 0) {
|
|
19
|
+
// 严格模式下才管 eval 类开关;包运行器不受这个开关影响。
|
|
20
|
+
const enforced = strictEval || !STRICT_ONLY_FLAGS.has(name)
|
|
21
|
+
if (enforced) {
|
|
22
|
+
for (const arg of args) {
|
|
23
|
+
// `--eval=code` 这样的写法也要认
|
|
24
|
+
const head = arg.split('=')[0]
|
|
25
|
+
if (direct.includes(arg) || direct.includes(head)) {
|
|
26
|
+
return {
|
|
27
|
+
escaped: true,
|
|
28
|
+
reason: strictEval
|
|
29
|
+
? `${name} ${head} 等于直接执行一段代码(checkStrictEval 已开启,这类调用一律拒)`
|
|
30
|
+
: `${name} ${head} 会再起一个解释器,等于绕过白名单`,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// git -c key=value:只有那几个能把命令挂上去的键才拦。
|
|
37
|
+
if (name === 'git') {
|
|
38
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
39
|
+
if (args[i] !== '-c') continue
|
|
40
|
+
const assignment = args[i + 1] ?? ''
|
|
41
|
+
const key = assignment.split('=')[0].trim()
|
|
42
|
+
if (GIT_DANGEROUS_CONFIG.test(key)) {
|
|
43
|
+
return { escaped: true, reason: `git -c ${key} 会把任意命令挂到 git 上执行,换成不带这条配置的写法` }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// 包运行器:npm exec / pnpm dlx 后面跟的其实是另一条命令,递归看一眼。
|
|
48
|
+
if (PACKAGE_RUNNERS.has(name) && args.length > 0) {
|
|
49
|
+
const sub = args.find(arg => !arg.startsWith('-'))
|
|
50
|
+
if (sub !== undefined) {
|
|
51
|
+
const subName = commandNameOf(sub)
|
|
52
|
+
if (PACKAGE_RUNNERS.has(subName) || (CODE_ESCAPE_FLAGS[subName] ?? []).length > 0) {
|
|
53
|
+
return { escaped: true, reason: `${name} ${sub} 会再起一个解释器,等于绕过白名单` }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { escaped: false }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function allowedCommandsOf(settings) {
|
|
61
|
+
const extra = typeof settings?.checkAllowedCommands === 'string' ? settings.checkAllowedCommands : ''
|
|
62
|
+
const names = [...DEFAULT_ALLOWED_COMMANDS, ...extra.split(/[,\s]+/u)]
|
|
63
|
+
.map(commandNameOf)
|
|
64
|
+
.filter(name => name !== '')
|
|
65
|
+
return [...new Set(names)]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function tokenizeCommand(cmd) {
|
|
69
|
+
const text = typeof cmd === 'string' ? cmd : ''
|
|
70
|
+
const tokens = []
|
|
71
|
+
let current = ''
|
|
72
|
+
let quote = ''
|
|
73
|
+
let started = false
|
|
74
|
+
for (const ch of text) {
|
|
75
|
+
if (quote !== '') {
|
|
76
|
+
if (ch === quote) {
|
|
77
|
+
quote = ''
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
current += ch
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
if (ch === '"' || ch === "'") {
|
|
84
|
+
quote = ch
|
|
85
|
+
started = true
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
if (/\s/u.test(ch)) {
|
|
89
|
+
if (started) {
|
|
90
|
+
tokens.push(current)
|
|
91
|
+
current = ''
|
|
92
|
+
started = false
|
|
93
|
+
}
|
|
94
|
+
continue
|
|
95
|
+
}
|
|
96
|
+
current += ch
|
|
97
|
+
started = true
|
|
98
|
+
}
|
|
99
|
+
if (started) tokens.push(current)
|
|
100
|
+
return tokens
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** target 是否落在 dir 里面(含相等)。跨盘符时 relative 会给出绝对路径,也算不在里面。 */
|
|
104
|
+
function isInside(dir, target) {
|
|
105
|
+
const rel = relative(dir, target)
|
|
106
|
+
if (rel === '' || rel === '.') return true
|
|
107
|
+
return !rel.startsWith('..') && !isAbsolute(rel) && !/^[a-zA-Z]:/u.test(rel)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** PATH 里的目录,去掉首尾引号与空项,逐个解析成绝对路径。 */
|
|
111
|
+
function pathDirs() {
|
|
112
|
+
const dirs = []
|
|
113
|
+
for (const raw of (process.env.PATH ?? '').split(delimiter)) {
|
|
114
|
+
let entry = raw.trim()
|
|
115
|
+
if (entry.length >= 2 && entry.startsWith('"') && entry.endsWith('"')) entry = entry.slice(1, -1).trim()
|
|
116
|
+
if (entry === '') continue
|
|
117
|
+
try {
|
|
118
|
+
dirs.push(resolve(entry))
|
|
119
|
+
} catch {
|
|
120
|
+
// 这条写坏了就跳过,不影响别的
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// node 自己所在目录永远算数:本机经常没有 node 在 PATH 里,
|
|
124
|
+
// 而 Requirement 的判据就是拿 process.execPath 跑的那条命令。
|
|
125
|
+
dirs.push(dirname(process.execPath))
|
|
126
|
+
return dirs
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 这个 token 算不算「带路径」的写法。
|
|
131
|
+
*
|
|
132
|
+
* 只看有没有分隔符是不够的:`C:node.exe` 是盘符相对写法,一个分隔符都没有,
|
|
133
|
+
* 跑起来却是 C 盘当前目录下的同名二进制——按名字放行等于白名单被绕开。
|
|
134
|
+
* 所以盘符前缀(含 `C:` 后面不跟反斜杠的那种)一律当路径处理。
|
|
135
|
+
*/
|
|
136
|
+
function isPathLike(token) {
|
|
137
|
+
const text = String(token ?? '')
|
|
138
|
+
return /[\\/]/u.test(text) || /^[A-Za-z]:/u.test(text)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 带路径的命令单独判一次。
|
|
143
|
+
*
|
|
144
|
+
* 白名单按「命令名」放行,而 `D:\evil\node.exe` 的名字也叫 node——光看名字
|
|
145
|
+
* 等于任何同名二进制都能跑。所以命令里带路径时,只认真实路径落在 PATH
|
|
146
|
+
* 目录(或 node 所在目录)里的那些;解析不到的(不存在、没权限)直接拒,
|
|
147
|
+
* 绝不退回「按名字放行」。
|
|
148
|
+
*
|
|
149
|
+
* 返回 '' 表示放行,否则返回拒的理由。
|
|
150
|
+
*/
|
|
151
|
+
function pathVerdict(rawFile) {
|
|
152
|
+
let real
|
|
153
|
+
try {
|
|
154
|
+
// 盘符相对写法(`C:node.exe`)交给 resolve 时会被当成 C 盘根下的同名文件,
|
|
155
|
+
// 与 cmd 的语义(C 盘当前目录)不完全一样;这里取保守方向——解析不到就拒。
|
|
156
|
+
real = realpathSync(resolve(rawFile))
|
|
157
|
+
} catch {
|
|
158
|
+
return `命令带了路径,但找不到这个文件,没法确认它在 PATH 里:${rawFile}`
|
|
159
|
+
}
|
|
160
|
+
const win = process.platform === 'win32'
|
|
161
|
+
const target = win ? real.toLowerCase().replace(/[\\/]+$/u, '') : real
|
|
162
|
+
for (const dir of pathDirs()) {
|
|
163
|
+
const probe = win ? dir.toLowerCase().replace(/[\\/]+$/u, '') : dir
|
|
164
|
+
if (probe === '' || target === '') continue
|
|
165
|
+
if (isInside(probe, target)) return ''
|
|
166
|
+
}
|
|
167
|
+
return `命令带了路径,且不在 PATH 或 node 所在目录内:${rawFile}`
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function checkDenial(cmd, allowed, options = {}) {
|
|
171
|
+
const list = Array.isArray(allowed) ? allowed : DEFAULT_ALLOWED_COMMANDS
|
|
172
|
+
if (typeof cmd !== 'string' || cmd.trim() === '') return { denied: true, reason: 'check 是空的' }
|
|
173
|
+
const tokens = tokenizeCommand(cmd)
|
|
174
|
+
const name = commandNameOf(tokens[0] ?? '')
|
|
175
|
+
if (name === '') return { denied: true, reason: '认不出命令名' }
|
|
176
|
+
if (!list.includes(name)) {
|
|
177
|
+
return { denied: true, reason: `命令 ${name} 不在白名单里(只放行 ${list.join(' / ')})` }
|
|
178
|
+
}
|
|
179
|
+
const args = tokens.slice(1)
|
|
180
|
+
// 名字在白名单里还有几种绕过路子(npm exec / pnpm dlx / git -c 挂命令)。
|
|
181
|
+
// eval 类开关默认放行——那是写轻量判据的正常写法,见 CODE_ESCAPE_FLAGS 的说明。
|
|
182
|
+
const escape = checkCodeEscape(name, args, options.strictEval === true)
|
|
183
|
+
if (escape.escaped) return { denied: true, reason: escape.reason }
|
|
184
|
+
// 带路径的写法要单独查:名字对不代表跑的就是那个程序。
|
|
185
|
+
// `C:node.exe` 这类盘符相对写法也算路径,不然它绕开这条一路按名字放行。
|
|
186
|
+
const rawFile = tokens[0] ?? ''
|
|
187
|
+
if (isPathLike(rawFile)) {
|
|
188
|
+
const verdict = pathVerdict(rawFile)
|
|
189
|
+
if (verdict !== '') return { denied: true, reason: verdict }
|
|
190
|
+
}
|
|
191
|
+
return { denied: false, name, file: tokens[0], args }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 把一条参数转成能原样交回给程序的批处理写法。
|
|
196
|
+
*
|
|
197
|
+
* 两层规则叠加,顺序不能反:
|
|
198
|
+
* 1. 批处理先做变量展开,`%` 会被吃掉(`100%` 变 `100`,`%PATH%` 变成路径),
|
|
199
|
+
* 所以先 `%` → `%%`。这一步只看百分号,不参与下面的反斜杠计算。
|
|
200
|
+
* 2. 目标程序按 CommandLineToArgvW / CRT 的规则解析命令行:连续反斜杠只有
|
|
201
|
+
* 在双引号前、或位于参数末尾时才翻倍,双引号本身写成 \"。
|
|
202
|
+
* 以前只把 `"` 换成 `""`,那是给 cmd 内建命令用的写法,交给程序解析时是坏的。
|
|
203
|
+
*/
|
|
204
|
+
export function quoteForCmd(arg) {
|
|
205
|
+
const text = String(arg ?? '')
|
|
206
|
+
if (text === '') return '""'
|
|
207
|
+
const escaped = text.replace(/%/gu, '%%')
|
|
208
|
+
let out = '"'
|
|
209
|
+
let slashes = 0
|
|
210
|
+
for (const ch of escaped) {
|
|
211
|
+
if (ch === '\\') {
|
|
212
|
+
slashes += 1
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
if (ch === '"') {
|
|
216
|
+
out += `${'\\'.repeat(slashes * 2 + 1)}"`
|
|
217
|
+
slashes = 0
|
|
218
|
+
continue
|
|
219
|
+
}
|
|
220
|
+
out += '\\'.repeat(slashes) + ch
|
|
221
|
+
slashes = 0
|
|
222
|
+
}
|
|
223
|
+
out += '\\'.repeat(slashes * 2) + '"'
|
|
224
|
+
return out
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function resolveWindowsCommand(file, args) {
|
|
228
|
+
const list = Array.isArray(args) ? args : []
|
|
229
|
+
if (process.platform !== 'win32') return { file, args: list, viaCmd: false, resolved: file }
|
|
230
|
+
|
|
231
|
+
const lower = String(file).toLowerCase()
|
|
232
|
+
const isBatch = lower.endsWith('.cmd') || lower.endsWith('.bat')
|
|
233
|
+
|
|
234
|
+
let resolved = file
|
|
235
|
+
if (!isBatch) {
|
|
236
|
+
const found = whichSync(file)
|
|
237
|
+
if (found === undefined) return { file, args: list, viaCmd: false, resolved: file }
|
|
238
|
+
resolved = found
|
|
239
|
+
const foundLower = found.toLowerCase()
|
|
240
|
+
if (!foundLower.endsWith('.cmd') && !foundLower.endsWith('.bat')) {
|
|
241
|
+
// 找到的是 .exe,直接跑,不用过 cmd
|
|
242
|
+
return { file: found, args: list, viaCmd: false, resolved: found }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// 写一个临时 bat:把路径和参数原样写进去。
|
|
247
|
+
//
|
|
248
|
+
// 编码是个坑:cmd.exe 默认按系统 ANSI 代码页(简中 Windows 是 GBK/936)读
|
|
249
|
+
// 批处理,写 UTF-8 会让中文路径变成乱码,写 ascii 会丢字。这里用
|
|
250
|
+
// `chcp 65001` 把控制台切到 UTF-8,再以 UTF-8 写文件——这样中文、emoji
|
|
251
|
+
// 路径都不受系统代码页影响。切代码页只影响这个 bat 自己的进程,不外溢。
|
|
252
|
+
let batPath
|
|
253
|
+
try {
|
|
254
|
+
batPath = join(tmpdir(), `pf-run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.bat`)
|
|
255
|
+
const quotedArgs = list.map(part => quoteForCmd(part)).join(' ')
|
|
256
|
+
const body = [
|
|
257
|
+
'@echo off',
|
|
258
|
+
// 延迟展开关掉,否则参数里的 `!` 会被当成变量吃掉。
|
|
259
|
+
'setlocal DisableDelayedExpansion',
|
|
260
|
+
'chcp 65001 >nul 2>&1',
|
|
261
|
+
`"${resolved}"${quotedArgs === '' ? '' : ` ${quotedArgs}`}`,
|
|
262
|
+
// 这一行是常量,单独拼,不能进 quoteForCmd 的 % 处理。
|
|
263
|
+
'exit /b %ERRORLEVEL%',
|
|
264
|
+
].join('\r\n')
|
|
265
|
+
writeFileSync(batPath, `${body}\r\n`, 'utf8')
|
|
266
|
+
} catch {
|
|
267
|
+
// 写不出临时文件就退回直连,至少 exe 类命令不受影响
|
|
268
|
+
return { file: resolved, args: list, viaCmd: false, resolved }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
file: process.env.ComSpec ?? 'cmd.exe',
|
|
273
|
+
args: ['/d', '/s', '/c', batPath],
|
|
274
|
+
viaCmd: true,
|
|
275
|
+
resolved,
|
|
276
|
+
cleanup: () => {
|
|
277
|
+
try { rmSync(batPath, { force: true }) } catch { /* 删不掉就算了,在系统临时目录里 */ }
|
|
278
|
+
},
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function whichSync(name) {
|
|
283
|
+
if (typeof name !== 'string' || name === '') return undefined
|
|
284
|
+
if (isAbsolute(name)) return existsSync(name) ? name : undefined
|
|
285
|
+
|
|
286
|
+
const exts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(e => e !== '')
|
|
287
|
+
// 名字本身已经带扩展名就只试那一个
|
|
288
|
+
const hasExt = exts.some(ext => name.toLowerCase().endsWith(ext.toLowerCase()))
|
|
289
|
+
const candidates = hasExt ? [name] : exts.map(ext => `${name}${ext.toLowerCase()}`)
|
|
290
|
+
|
|
291
|
+
const dirs = [process.cwd(), ...(process.env.PATH ?? '').split(';').filter(d => d !== '')]
|
|
292
|
+
for (const dir of dirs) {
|
|
293
|
+
for (const candidate of candidates) {
|
|
294
|
+
const full = join(dir, candidate)
|
|
295
|
+
try {
|
|
296
|
+
if (existsSync(full)) return full
|
|
297
|
+
} catch {
|
|
298
|
+
// 这个目录不可访问,试下一个
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return undefined
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
|
|
306
|
+
const resolved = resolveWindowsCommand(file, args)
|
|
307
|
+
return new Promise(resolve => {
|
|
308
|
+
execFile(resolved.file, resolved.args, {
|
|
309
|
+
cwd,
|
|
310
|
+
timeout: timeoutMs,
|
|
311
|
+
killSignal: 'SIGKILL',
|
|
312
|
+
windowsHide: true,
|
|
313
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
314
|
+
...(env === undefined ? {} : { env }),
|
|
315
|
+
}, (error, stdout, stderr) => {
|
|
316
|
+
// 临时 bat 用完就删,别在系统临时目录里攒
|
|
317
|
+
if (typeof resolved.cleanup === 'function') resolved.cleanup()
|
|
318
|
+
const output = `${stdout ?? ''}${stderr ?? ''}`
|
|
319
|
+
if (error === null || error === undefined) {
|
|
320
|
+
resolve({ exit: 0, output })
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
if (error.code === 'ENOENT') {
|
|
324
|
+
// 说清「找的是哪个文件」:Windows 上常见的坑是 npm 装成了 npm.cmd,
|
|
325
|
+
// 只报一句「命令不存在」会让人去重装,实际是路径没解析到。
|
|
326
|
+
resolve({
|
|
327
|
+
exit: 127,
|
|
328
|
+
output: `${output}${error.message}`,
|
|
329
|
+
missing: true,
|
|
330
|
+
...(resolved.resolved !== file ? { triedPath: resolved.resolved } : {}),
|
|
331
|
+
})
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
const timedOut = error.killed === true || (error.signal !== undefined && error.signal !== null)
|
|
335
|
+
// 超时一律记 124(和 shell timeout 命令一致),不用内核信号码。
|
|
336
|
+
if (timedOut) {
|
|
337
|
+
resolve({ exit: 124, output, timedOut: true })
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
if (typeof error.code === 'number') {
|
|
341
|
+
resolve({ exit: error.code, output })
|
|
342
|
+
return
|
|
343
|
+
}
|
|
344
|
+
resolve({ exit: 1, output: `${output}${error.message}` })
|
|
345
|
+
})
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export async function runRequirementChecks(options) {
|
|
350
|
+
const {
|
|
351
|
+
entries = [],
|
|
352
|
+
cwd,
|
|
353
|
+
allowed = DEFAULT_ALLOWED_COMMANDS,
|
|
354
|
+
strictEval = false,
|
|
355
|
+
timeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
|
|
356
|
+
tailChars = DEFAULT_CHECK_TAIL_CHARS,
|
|
357
|
+
env,
|
|
358
|
+
spawnCheck = defaultSpawnCheck,
|
|
359
|
+
} = options ?? {}
|
|
360
|
+
const assertions = []
|
|
361
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
362
|
+
const req = Number.isInteger(entry?.req) ? entry.req : assertions.length + 1
|
|
363
|
+
const cmd = typeof entry?.cmd === 'string' ? entry.cmd.trim() : ''
|
|
364
|
+
if (cmd === '') {
|
|
365
|
+
assertions.push({ req, cmd: null, exit: null, durationMs: 0, stdoutTail: '', status: 'unverified' })
|
|
366
|
+
continue
|
|
367
|
+
}
|
|
368
|
+
const denial = checkDenial(cmd, allowed, { strictEval })
|
|
369
|
+
if (denial.denied === true) {
|
|
370
|
+
assertions.push({
|
|
371
|
+
req,
|
|
372
|
+
cmd,
|
|
373
|
+
exit: 126,
|
|
374
|
+
durationMs: 0,
|
|
375
|
+
stdoutTail: `白名单拒绝:${denial.reason}`,
|
|
376
|
+
status: 'denied',
|
|
377
|
+
denied: true,
|
|
378
|
+
})
|
|
379
|
+
continue
|
|
380
|
+
}
|
|
381
|
+
const startedAt = Date.now()
|
|
382
|
+
let run
|
|
383
|
+
try {
|
|
384
|
+
run = await spawnCheck({ file: denial.file, args: denial.args, cwd, timeoutMs, env })
|
|
385
|
+
} catch (error) {
|
|
386
|
+
run = { exit: 1, output: messageOf(error) }
|
|
387
|
+
}
|
|
388
|
+
const durationMs = Date.now() - startedAt
|
|
389
|
+
const expectExit = Number.isInteger(entry?.expectExit) ? entry.expectExit : 0
|
|
390
|
+
const status = run.timedOut === true
|
|
391
|
+
? 'fail'
|
|
392
|
+
: run.missing === true
|
|
393
|
+
? 'missing'
|
|
394
|
+
: run.exit === expectExit ? 'pass' : 'fail'
|
|
395
|
+
assertions.push({
|
|
396
|
+
req,
|
|
397
|
+
cmd,
|
|
398
|
+
exit: run.exit ?? null,
|
|
399
|
+
durationMs,
|
|
400
|
+
stdoutTail: tailOf(run.output ?? '', tailChars),
|
|
401
|
+
status,
|
|
402
|
+
...(run.timedOut === true ? { timeout: true } : {}),
|
|
403
|
+
...(expectExit === 0 ? {} : { expectExit }),
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
const missing = assertions.filter(item => item.status === 'missing')
|
|
407
|
+
const degrade = missing.length > CHECK_MISSING_BINARY_LIMIT
|
|
408
|
+
for (const item of assertions) {
|
|
409
|
+
if (item.status !== 'missing') continue
|
|
410
|
+
// 环境里没有这条命令:少数几条按 FAIL 记(应该是这次实现要用的工具),
|
|
411
|
+
// 成片缺失按 unverified 记(更像是这台机器没装)。
|
|
412
|
+
item.status = degrade ? 'unverified' : 'fail'
|
|
413
|
+
}
|
|
414
|
+
return assertions
|
|
415
|
+
}
|
|
416
|
+
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 要求里的判据:从 Requirement.md 读出来、写回去、算指纹。
|
|
3
|
+
*/
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { quoteScalar, splitFrontMatter, unquoteScalar } from '../shared/util.mjs'
|
|
6
|
+
|
|
7
|
+
export function parseRequirementChecks(text) {
|
|
8
|
+
const { front } = splitFrontMatter(text)
|
|
9
|
+
if (front === '') return []
|
|
10
|
+
const entries = []
|
|
11
|
+
let inChecks = false
|
|
12
|
+
let current
|
|
13
|
+
for (const rawLine of front.split(/\r?\n/u)) {
|
|
14
|
+
const line = rawLine.replace(/\s+$/u, '')
|
|
15
|
+
if (/^checks\s*:\s*$/u.test(line)) {
|
|
16
|
+
inChecks = true
|
|
17
|
+
continue
|
|
18
|
+
}
|
|
19
|
+
// 顶格的非空行意味着 checks 这一段结束了。
|
|
20
|
+
if (inChecks && /^\S/u.test(line)) {
|
|
21
|
+
inChecks = false
|
|
22
|
+
current = undefined
|
|
23
|
+
}
|
|
24
|
+
if (!inChecks) continue
|
|
25
|
+
const reqMatch = /^\s*-\s*req\s*:\s*(\d+)\s*$/u.exec(line)
|
|
26
|
+
if (reqMatch !== null) {
|
|
27
|
+
current = { req: Number(reqMatch[1]), cmd: '', expectExit: 0 }
|
|
28
|
+
entries.push(current)
|
|
29
|
+
continue
|
|
30
|
+
}
|
|
31
|
+
if (current === undefined) continue
|
|
32
|
+
const cmdMatch = /^\s+cmd\s*:\s*(.*)$/u.exec(line)
|
|
33
|
+
if (cmdMatch !== null) {
|
|
34
|
+
current.cmd = unquoteScalar(cmdMatch[1])
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
const exitMatch = /^\s+exit\s*:\s*(-?\d+)\s*$/u.exec(line)
|
|
38
|
+
if (exitMatch !== null) current.expectExit = Number(exitMatch[1])
|
|
39
|
+
}
|
|
40
|
+
return entries
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function renderRequirementChecks(entries) {
|
|
44
|
+
if (!Array.isArray(entries) || entries.length === 0) return ''
|
|
45
|
+
const lines = ['---', 'checks:']
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
lines.push(` - req: ${entry.req}`)
|
|
48
|
+
lines.push(` cmd: ${quoteScalar(entry.cmd ?? '')}`)
|
|
49
|
+
lines.push(` exit: ${Number.isInteger(entry.expectExit) ? entry.expectExit : 0}`)
|
|
50
|
+
}
|
|
51
|
+
lines.push('---')
|
|
52
|
+
return lines.join('\n')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function requirementFingerprint(entries) {
|
|
56
|
+
const list = Array.isArray(entries) ? entries : []
|
|
57
|
+
const canonical = JSON.stringify(
|
|
58
|
+
list.map(entry => ({
|
|
59
|
+
req: Number.isInteger(entry.req) ? entry.req : 0,
|
|
60
|
+
cmd: typeof entry.cmd === 'string' ? entry.cmd : '',
|
|
61
|
+
expectedExit: Number.isInteger(entry.expectExit) ? entry.expectExit : 0,
|
|
62
|
+
})),
|
|
63
|
+
)
|
|
64
|
+
return createHash('sha256').update(canonical, 'utf8').digest('hex')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function buildCheckEntries(requirements, checks) {
|
|
68
|
+
const list = Array.isArray(requirements) ? requirements : []
|
|
69
|
+
const extra = Array.isArray(checks) ? checks : []
|
|
70
|
+
return list.map((line, index) => {
|
|
71
|
+
const text = typeof line === 'string' ? line : String(line ?? '')
|
|
72
|
+
const inline = /(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*([\s\S]+)$/u.exec(text)
|
|
73
|
+
const fromList = extra.find(item => item !== null && typeof item === 'object' && Number(item.req) === index + 1)
|
|
74
|
+
const listed = fromList !== undefined && typeof fromList.check === 'string' && fromList.check.trim() !== ''
|
|
75
|
+
? fromList.check.trim()
|
|
76
|
+
: ''
|
|
77
|
+
const cmd = listed !== '' ? listed : inline === null ? '' : inline[1].trim()
|
|
78
|
+
// checks 列表中 exit 等价于 checkExit:两个字段都接收,checkExit 优先,缺省均为 0
|
|
79
|
+
const rawExit = fromList !== undefined
|
|
80
|
+
? (Number.isInteger(Number(fromList.checkExit)) ? fromList.checkExit : (Number.isInteger(Number(fromList.exit)) ? fromList.exit : undefined))
|
|
81
|
+
: undefined
|
|
82
|
+
const expectExit = Number.isInteger(Number(rawExit)) ? Number(rawExit) : 0
|
|
83
|
+
return { req: index + 1, cmd, expectExit }
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function stripInlineCheck(line) {
|
|
88
|
+
const text = typeof line === 'string' ? line : String(line ?? '')
|
|
89
|
+
return text.replace(/(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*[\s\S]+$/u, '').trim()
|
|
90
|
+
}
|
|
91
|
+
|