stopbar 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +180 -0
- package/README.md +165 -29
- package/SECURITY.md +115 -13
- package/dist/attest.js +28 -3
- package/dist/build-info.json +2 -2
- package/dist/classify.js +201 -25
- package/dist/cli.js +44 -8
- package/dist/commands.js +96 -22
- package/dist/config.js +7 -2
- package/dist/doctor.js +19 -9
- package/dist/hook.js +73 -36
- package/dist/integrations.js +14 -5
- package/dist/probe/index.js +247 -57
- package/dist/probe/init.js +217 -0
- package/dist/probe/sdk.js +242 -0
- package/dist/probe/stdio.js +207 -0
- package/dist/probe/wrapper.js +36 -7
- package/dist/repo.js +37 -11
- package/dist/store.js +1 -1
- package/package.json +17 -2
- package/skills/stopbar/SKILL.md +126 -0
- package/src/probe/sdk.ts +241 -0
package/SECURITY.md
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
# Security model
|
|
2
2
|
|
|
3
|
-
Stopbar
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Stopbar has two parts: a formally proven decision kernel (`src/kernel.ts`, proven by induction with gdp-wired and
|
|
4
|
+
checked again by `lake build` in Lean 4.34.0) and a tested wrapper around it: the hooks of Claude Code, Cursor, Codex
|
|
5
|
+
CLI, Gemini CLI and Antigravity CLI, and git hooks (`pre-commit`, `pre-push`) for any other tool. This file says what
|
|
6
|
+
is proven (section 1), what the wrapper enforces and how it is tested (section 2), and what Stopbar cannot give you
|
|
7
|
+
without an operating-system sandbox (section 3). Without an OS sandbox, Stopbar stops shortcuts and mistakes of an
|
|
8
|
+
agent; it is not a security boundary against a hostile agent.
|
|
6
9
|
|
|
7
10
|
## 1. What is proven
|
|
8
11
|
|
|
@@ -53,9 +56,24 @@ There is no proof for them.
|
|
|
53
56
|
- **Results from the event type.** Claude Code sends `PostToolUseFailure` for a failed command and `PostToolUse`
|
|
54
57
|
without an exit code for a successful one. A user interrupt (`is_interrupt`) does not count as a failure.
|
|
55
58
|
- **Tree changes from content.** A private git index in `.git/stopbar/` gives a content snapshot after every edit and
|
|
56
|
-
every shell call: edits, deletions and new files that are not ignored.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
+
every shell call: edits, deletions and new files that are not ignored. Without `config.baseRef`, a change to a test
|
|
60
|
+
file that exists in `HEAD`, or to any test-config file, is suspicious. With `config.baseRef`, the wrapper compares the
|
|
61
|
+
blob id of each changed test and test-config file with `baseRef` (one `git ls-tree`, only when such a file changed):
|
|
62
|
+
a test of `baseRef` with other content or deleted, and a test-config file whose content differs from `baseRef` (also
|
|
63
|
+
a new one), are suspicious; a file equal to `baseRef` is not. The file mode is ignored. A configured non-`HEAD`
|
|
64
|
+
`baseRef` that cannot be resolved fails closed. Every change still raises the tree revision, so the gates must run
|
|
65
|
+
again. The path patterns are in `config.json`.
|
|
66
|
+
- **Fresh state on a dirty tree.** `stopbar init --force` and `stopbar reset` classify the uncommitted changes against
|
|
67
|
+
`baseRef` (else `HEAD`) by the same rule. A suspicious change is one kernel step `EDIT_TEST` (`suspicious: true`,
|
|
68
|
+
`cost: 0`), logged with every kernel field: the session starts tainted until `approve-tests`.
|
|
69
|
+
- **`git cherry-pick` and `git rebase`.** They are ordinary shell commands: Stopbar does not block them before the gates
|
|
70
|
+
and does not treat them as a commit, although they write commits. They change the working tree, so the next hook
|
|
71
|
+
counts a new revision and the build and full test gates must pass again. With `--base-ref`, the blob-id comparison
|
|
72
|
+
finds every change of an existing test of `baseRef` and of test config against `baseRef`, whichever command made it;
|
|
73
|
+
tests taken over unchanged from `baseRef` do not taint. Without `--base-ref`, every change of an existing test taints.
|
|
74
|
+
`git commit`, `git push` (agent hooks and git hooks) and a green `stopbar attest` still need green gates and no
|
|
75
|
+
unapproved taint. A commit that `cherry-pick` or `rebase` writes itself does not pass through the commit gate (see
|
|
76
|
+
"Other commit paths" below); a later `git push` does.
|
|
59
77
|
- **Commits.** `git commit` and `git push` must be one command without operators, also with git global options before
|
|
60
78
|
the subcommand. The one allowed form of command substitution is the quoted heredoc that Claude Code writes:
|
|
61
79
|
`git commit ... -m "$(cat <<'EOF'` … `EOF` `)"`. The delimiter is in single quotes, so bash expands nothing in the
|
|
@@ -67,8 +85,23 @@ There is no proof for them.
|
|
|
67
85
|
`.cursor/hooks.json`, `.codex/hooks.json`, `.codex/config.toml`, `.gemini/*settings*.json`, `.gemini/**/hooks.json`,
|
|
68
86
|
`.agents/hooks.json`, at project and user level), or the Stopbar code that runs the hooks. A shell command may not
|
|
69
87
|
name a `.git`, `.claude`, `.cursor`, `.codex`, `.gemini` or `.agents` directory, write git config (`git config`
|
|
70
|
-
|
|
71
|
-
|
|
88
|
+
other than a read: `--get`, `--get-all`, `--get-regexp`, `--get-urlmatch`, `--list`, `-l`, or the subcommands `list`
|
|
89
|
+
and `get` right after `config`; a value such as `core.hooksPath list` is a write), define a one-off git alias
|
|
90
|
+
(`git -c alias.<name>=...`, `--config-env alias.*`, `GIT_CONFIG_KEY_<n>=alias.*`), name the Stopbar code, use a
|
|
91
|
+
`STOPBAR_*` variable, or run a human command (`approve-tests`, `approve-shell`, and `init`, `resume`, `reset`,
|
|
92
|
+
`upgrade`, `doctor --fix` right after the `stopbar` program word; `stopbar probe init` is allowed). Since 1.2.0
|
|
93
|
+
every text check runs on the command as written and as bash joins the quoted parts of a word, so `.e""nv`, `.g''it`,
|
|
94
|
+
`.cl''aude`, `'.cl'"aude"`, `.e"n"'v'` and `gi"t"` count as `.env`, `.git`, `.claude` and `git`. In Bash, the body
|
|
95
|
+
of one single-quoted heredoc that is stdin data (`agy -p - <<'EOF'` … `EOF`) is skipped by the human-only checks,
|
|
96
|
+
so a prompt may mention `approve-tests`; this does not apply when the command line pipes, redirects with `>`/`>>`,
|
|
97
|
+
expands a variable, or names a shell, an interpreter, `xargs`, `at`, `tee` or
|
|
98
|
+
`stopbar`. `.git`, the agent settings directories and the Stopbar code stay protected inside the body.
|
|
99
|
+
- **Halted sessions.** While halted, every tool is paused except the tools in `config.safeTools` (default: the local
|
|
100
|
+
task-list, turn and session-message tools of Claude Desktop), so the agent can still ask a human for `stopbar resume`.
|
|
101
|
+
These tools never take a kernel step, so they cannot change the state that laws L4.1 and L4.4 speak about. Edit,
|
|
102
|
+
Write, Read, Bash, WebFetch and every other MCP tool stay paused.
|
|
103
|
+
- **`requireRun`.** With `config.requireRun: true`, a build or full test run counts only through `stopbar run
|
|
104
|
+
build|test`; the same command from the agent's shell is recorded neither as a pass nor as a failure.
|
|
72
105
|
- **One kernel for every agent.** An adapter per client (Claude Code, Cursor, Codex CLI, Gemini CLI, Antigravity CLI)
|
|
73
106
|
translates the hook payload into one internal event and the decision into the client's output protocol. The
|
|
74
107
|
adapters are wrapper code: the E2E suite runs each with payloads in the client's published schema.
|
|
@@ -87,7 +120,9 @@ that tries to defeat it:
|
|
|
87
120
|
|
|
88
121
|
1. **Indirect execution.** A script written to a normal file and then run (`node x.js`, `bash x.sh`) can do anything:
|
|
89
122
|
delete `.git/stopbar`, edit `.claude/settings.local.json`, run `stopbar approve-tests`. The text checks do not see
|
|
90
|
-
inside the script. Obfuscation (`c=cu; ${c}rl`
|
|
123
|
+
inside the script. Obfuscation (`c=cu; ${c}rl`, `g=.g; d=$g"it"; rm -rf $d`), backslash escapes inside a word,
|
|
124
|
+
aliases and shell functions also pass the text checks. Only simple quote splicing (`.g""it`) is undone. The unit
|
|
125
|
+
test "known limits without an OS sandbox" keeps these cases visible.
|
|
91
126
|
2. **Gate commands run arbitrary code.** `buildCmd` and `fullTestCmd` run the repository's code. A new test file is
|
|
92
127
|
trusted. It can read secrets, use the network or weaken other checks at run time.
|
|
93
128
|
3. **Secrets by file name only.** Secrets in environment variables, in files with ordinary names, or found with Grep in
|
|
@@ -102,10 +137,17 @@ that tries to defeat it:
|
|
|
102
137
|
4. **Weak new tests and mutable `baseRef`.** A new test file is not suspicious. A mock of the system under test or an
|
|
103
138
|
empty assertion in a new file passes. Hard-coded answers in production code are an ordinary code edit. When
|
|
104
139
|
`config.baseRef` is a mutable local branch name (such as `main`) rather than a commit SHA, an agent with shell access
|
|
105
|
-
can move that branch ref; pass a commit hash (`--base-ref <sha>`) if you want an immutable baseline.
|
|
140
|
+
can move that branch ref; pass a commit hash (`--base-ref <sha>`) if you want an immutable baseline. Since 1.1.3 this
|
|
141
|
+
matters more: a test that equals `baseRef` does not taint, so an agent that moves the `baseRef` branch to a commit
|
|
142
|
+
with weakened tests (for example `git branch -f main <commit>` or `git update-ref`) and then checks it out is not
|
|
143
|
+
flagged. Stopbar does not watch the ref itself.
|
|
106
144
|
5. **Ignored files.** Files ignored by `.gitignore` are invisible to the snapshot (for example patches in
|
|
107
145
|
`node_modules`). A change to `.gitignore` itself is suspicious.
|
|
108
|
-
6. **Other commit paths.**
|
|
146
|
+
6. **Other commit paths.** Aliases from a git config file, `git commit-tree`, `git stash`, `git cherry-pick`,
|
|
147
|
+
`git rebase`, `gh pr create` and similar are not detected as commits by the agent hooks (a one-off
|
|
148
|
+
`git -c alias.*` is blocked). The git hooks, which `init --hooks <client>` writes by default since 1.2.0, close part
|
|
149
|
+
of this: `pre-commit` runs for every `git commit`, also through an alias, and `pre-push` gates every push of
|
|
150
|
+
commits made by `merge`, `cherry-pick`, `am` or `commit-tree`. `--no-verify` still skips them. The Stop hook
|
|
109
151
|
catches uncommitted work only. With `config.stopGate: "warn"` it does not even block that: the turn ends with a
|
|
110
152
|
`WARN (stopbar)` answer and a `stop:warn` entry in `events.jsonl`. This mode takes no kernel step at Stop and does not
|
|
111
153
|
weaken the commit gate: `git commit` and `git push` in the agent hooks and in the git hooks are judged by the kernel
|
|
@@ -138,6 +180,64 @@ For a hostile-agent threat model, run the agent in a container or VM: no network
|
|
|
138
180
|
read-write, `.git/stopbar` and `.claude` mounted read-only or owned by another user, and the human commands run outside
|
|
139
181
|
the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gives the boundary.
|
|
140
182
|
|
|
183
|
+
## 4. PROBE, `--cmd` and probe evidence
|
|
184
|
+
|
|
185
|
+
`stopbar probe` is a test tool run by a human or by CI. It is not a hook and it is not part of the proof.
|
|
186
|
+
|
|
187
|
+
- A probe target is code you trust. `--target <file>` imports the file into the worker processes, and
|
|
188
|
+
`--cmd "<command>"` runs the command in a shell, with the rights of the user who starts the probe. Do not probe
|
|
189
|
+
a file or a command from outside the session that no human has read. An agent may run a prober it wrote in the
|
|
190
|
+
current session (`skills/stopbar/SKILL.md`); a human reads it before its `probe:result` counts as evidence.
|
|
191
|
+
- `probe:result` in `events.jsonl` is evidence, not a gate. It has no `req`, it is not a kernel step and it does not
|
|
192
|
+
change `state.json`, so it can never allow a commit. It is appended under Stopbar's lock, like every other entry.
|
|
193
|
+
- `stopbar attest` shows the latest `probe:result` per target since the last `init` or `reset`, with the sha256 of the
|
|
194
|
+
target file (`targetSha256`), the command (`targetCmd`), the tree snapshot and `atCurrentSnapshot`. The entry says
|
|
195
|
+
what the prober saw on that tree. It does not prove the target file: an agent that can write to `events.jsonl` can
|
|
196
|
+
also write a false entry, as for every other log line (see section 3). Compare `targetSha256` with the file you
|
|
197
|
+
reviewed.
|
|
198
|
+
- For `--cmd`, `targetSha256` covers one file only: `--target-file`, else the first existing file after the
|
|
199
|
+
interpreter, else nothing (`null`). Imports, libraries and the interpreter are not hashed.
|
|
200
|
+
|
|
201
|
+
## Known limits of 1.2.0
|
|
202
|
+
|
|
203
|
+
- `safeTools` in `HALT`: a halted session still lets the tools in `config.safeTools` through. A human who adds a glob
|
|
204
|
+
there vouches that those tools are local; with a broad glob (for example `mcp__*`) a halted agent keeps those tools.
|
|
205
|
+
Edit, Write, Read, the shell and every tool outside the list stay paused.
|
|
206
|
+
- `--require-run` decides by the event's source (`stopbar run` or an agent hook), not by what ran. Without it, the
|
|
207
|
+
exact gate command from the agent's shell still counts, as before.
|
|
208
|
+
- Quote splicing: only quotes inside a word are undone (`.e""nv`, `.e"n"v`, `'.cl'"aude"`, `gi"t"`). A path built at
|
|
209
|
+
run time (`g=.g; d=$g"it"`), a backslash escape, a variable or a script (`node /tmp/x.js`) passes the text checks;
|
|
210
|
+
section 3 point 1. Only an OS sandbox closes this.
|
|
211
|
+
- The stdin heredoc exception trusts the command on the header line not to run its stdin. Stopbar knows the common
|
|
212
|
+
shells and interpreters (and `xargs`, `at`, `tee`, `stopbar`); another program that executes stdin passes. The
|
|
213
|
+
exception covers only `HUMAN_ONLY` and `STOPBAR_ADMIN`; every other check still reads the body.
|
|
214
|
+
- Git hooks by default: a foreign `pre-commit` or `pre-push` is kept with a `WARN` when the git hooks were added by
|
|
215
|
+
default; then that git action is not gated until a human runs `stopbar upgrade --hooks git --force-hooks`.
|
|
216
|
+
`stopbar doctor` reports `[WARN] hooks git` while one of the two Stopbar git hooks is missing.
|
|
217
|
+
- `stopbar doctor` checks the kernel link only where `gdp-wired` resolves from the running copy (`import.meta.resolve`).
|
|
218
|
+
A pinned runtime outside any `node_modules` tree reports `[WARN] kernel link`; run `stopbar prove` in the package.
|
|
219
|
+
- `--cmd`: the command runs through the system shell (`cmd.exe` on Windows, `/bin/sh` elsewhere), so quoting follows
|
|
220
|
+
that shell. A shell can hold stdout open after the program closed it; then only `--cmd-timeout` (default 300000 ms)
|
|
221
|
+
ends the wait.
|
|
222
|
+
- `--cmd`: answers are checked for their shape (`name`, `seed`, `actions`, `ok`, `steps`, `cov`, `mismatch.step`,
|
|
223
|
+
`mismatch.what`), not for meaning. A program that answers `ok: true` without running anything passes. Mutants
|
|
224
|
+
(`--check-mutants`) are the check that the model can fail.
|
|
225
|
+
- `--cmd`: Stopbar does not check that `generate` is deterministic. A reproduction replays the saved actions, so it
|
|
226
|
+
stays valid, but a new run of the same seed can differ if the program uses another source of randomness.
|
|
227
|
+
- `probe init --lang py` prints `python` on Windows and `python3` elsewhere; use the name your system has.
|
|
228
|
+
- `probe init --lang ts` writes a file that imports `stopbar/probe`: it runs only where that import resolves (Stopbar
|
|
229
|
+
installed in the project).
|
|
230
|
+
|
|
231
|
+
## Known limits of 1.1.3
|
|
232
|
+
|
|
233
|
+
- The blob-id comparison trusts `baseRef`: see point 4 of section 3 (a mutable branch name can be moved by the agent).
|
|
234
|
+
Use a commit SHA as `--base-ref` when the agent must not be able to move the baseline.
|
|
235
|
+
- `init --force` and `reset` count all suspicious uncommitted changes as one kernel step. A test file that changed in
|
|
236
|
+
a branch commit against `baseRef` counts too, even if a human approved it in an earlier session: after `reset` such
|
|
237
|
+
a branch starts tainted until `approve-tests`.
|
|
238
|
+
- `stopbar upgrade` re-pins the runtime from the package that runs the command. It does not check that the package is
|
|
239
|
+
newer, and it does not change `config.json`; new defaults (for example `safeTools`) are only named as a hint.
|
|
240
|
+
|
|
141
241
|
## Known limits of 1.1.2
|
|
142
242
|
|
|
143
243
|
- `stopGate: "warn"`: in Cursor, Codex CLI, Gemini CLI and Antigravity CLI the WARN text is not shown to the agent,
|
|
@@ -150,11 +250,13 @@ the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gi
|
|
|
150
250
|
- `buildCmd` and `fullTestCmd` that differ only in whitespace at the ends count as equal and are refused. Two different
|
|
151
251
|
commands that run the same script (for example `npm test` and `npm run test`) are not detected.
|
|
152
252
|
|
|
153
|
-
- Lean: the check needs Docker and a one-time image build with network access
|
|
253
|
+
- Lean: the check needs Docker and a one-time image build with network access, or (since 1.2.0, used in CI) Lean
|
|
254
|
+
4.34.0 on `PATH` with `node scripts/verify-lean.ts --local`. The base image is pinned by digest and
|
|
154
255
|
the Lean archive by sha256, both recorded at the first build (trust on first use). The Lean export is not
|
|
155
256
|
deterministic: each export is a different proof tree, and the gate checks the one it exports.
|
|
156
257
|
- Platforms: the unit tests, E2E, `stopbar probe` and `stopbar prove` pass on Windows 11 with Git for Windows and on
|
|
157
|
-
Linux (Debian 13, Node 24, git 2.47). A live Claude Code session ran on Windows. macOS
|
|
258
|
+
Linux (Debian 13, Node 24, git 2.47). A live Claude Code session ran on Windows. macOS runs only in CI (since
|
|
259
|
+
1.2.0, `.github/workflows/ci.yml`).
|
|
158
260
|
- Adapters: Cursor, Codex CLI, Gemini CLI and Antigravity CLI are spec-tested (see the README table); a client can
|
|
159
261
|
change its hook schema in a later version.
|
|
160
262
|
- Hook latency: Windows starts a process in 50–70 ms, so a hook with one git process takes about 120–200 ms in all.
|
package/dist/attest.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Built from src/attest.ts by scripts/build.ts. Do not edit.
|
|
2
2
|
// ATTEST: a deterministic attestation of the session from the current state and the event log. The same state and log
|
|
3
3
|
// give the same report byte for byte (no clock, no machine name). The sha256 of events.jsonl is the anchor for signing in
|
|
4
|
-
// a later version.
|
|
4
|
+
// a later version. Probe evidence: the latest `probe:result` per target, and whether its tree is the current one.
|
|
5
|
+
// Read-only for Stopbar state: it refreshes only the private snapshot index to see the working tree.
|
|
5
6
|
import {createHash} from 'node:crypto'
|
|
6
7
|
import {existsSync, readFileSync} from 'node:fs'
|
|
7
8
|
import {decode, initKernel, MACHINE, } from './engine.js'
|
|
@@ -38,7 +39,12 @@ export function attestation(repoDir ) {
|
|
|
38
39
|
|
|
39
40
|
// consistency: the state must be what the log says the last kernel step (or the last init/reset) left behind
|
|
40
41
|
const checks = []
|
|
41
|
-
|
|
42
|
+
// a loop from the end, not Math.max(...events): one argument per entry overflows the stack on a long log
|
|
43
|
+
let lastIdx = -1
|
|
44
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
45
|
+
const e = events[i].e
|
|
46
|
+
if (e.req || e.source === 'human:init' || e.source === 'human:reset') { lastIdx = i; break }
|
|
47
|
+
}
|
|
42
48
|
if (lastIdx < 0) checks.push({name: 'log matches state', ok: false, detail: 'no kernel step and no init in events.jsonl'})
|
|
43
49
|
else {
|
|
44
50
|
const last = events[lastIdx]
|
|
@@ -49,18 +55,33 @@ export function attestation(repoDir ) {
|
|
|
49
55
|
checks.push({name: 'config params = state params', ok: cfg.maxRetries === s.params.maxRetries && cfg.cap === s.params.cap, detail: `${JSON.stringify(s.params)}`})
|
|
50
56
|
checks.push({name: 'working tree counted', ok: now.id === s.snapshot, detail: now.id === s.snapshot ? 'no change the kernel has not seen' : 'uncounted change (counted at the next hook)'})
|
|
51
57
|
|
|
58
|
+
// probe evidence: the latest probe:result per target since the last init / reset (not kernel steps: no req)
|
|
59
|
+
let since = 0
|
|
60
|
+
events.forEach(({e}, i) => { if (e.source === 'human:init' || e.source === 'human:reset') since = i + 1 })
|
|
61
|
+
const latest = new Map ()
|
|
62
|
+
for (const x of events.slice(since)) if (x.e.source === 'probe:result' && typeof x.e.target === 'string') latest.set(x.e.target, x)
|
|
63
|
+
const probes = [...latest.keys()].sort().map((k) => {
|
|
64
|
+
const {line, e} = latest.get(k)
|
|
65
|
+
const m = e.mutants && typeof e.mutants === 'object' ? e.mutants : null
|
|
66
|
+
return {target: k, targetPath: e.targetPath ?? null, ...(typeof e.targetCmd === 'string' ? {targetCmd: e.targetCmd} : {}), targetSha256: e.targetSha256 ?? null, ok: e.ok === true, runs: e.runs ?? 0, regressions: e.regressions ?? 0,
|
|
67
|
+
passed: e.passed ?? 0, failed: e.failed ?? 0, steps: e.steps ?? 0,
|
|
68
|
+
mutants: m ? {killed: m.killed ?? 0, total: m.total ?? 0, survived: Array.isArray(m.survived) ? m.survived : []} : null,
|
|
69
|
+
treeSnapshot: e.treeSnapshot ?? null, atCurrentSnapshot: e.treeSnapshot === now.id, summarySha256: e.summarySha256 ?? null, line, ts: e.ts ?? null}
|
|
70
|
+
})
|
|
71
|
+
|
|
52
72
|
const commitNow = !v.halted && v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted
|
|
53
73
|
return {
|
|
54
74
|
stopbar: VERSION,
|
|
55
75
|
kernel: MACHINE,
|
|
56
76
|
repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
|
|
57
77
|
config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall, ...(cfg.baseRef ? {baseRef: cfg.baseRef} : {}),
|
|
58
|
-
stopGate: cfg.stopGate ?? 'block', ...(cfg.cliCmd ? {cliCmd: cfg.cliCmd} : {})},
|
|
78
|
+
stopGate: cfg.stopGate ?? 'block', ...(cfg.cliCmd ? {cliCmd: cfg.cliCmd} : {}), ...(cfg.requireRun ? {requireRun: true} : {})},
|
|
59
79
|
gates: {build: v.buildOkRev === v.treeRev, fullTests: v.testsOkRev === v.treeRev, tainted: v.testsTainted, secretRead: v.secretTainted,
|
|
60
80
|
...(v.secretTainted ? {secretReadBy: secretReason(repo)?.text ?? 'not in the event log'} : {}),
|
|
61
81
|
shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
|
|
62
82
|
budget: {spent: v.spent, cap: v.capNow}, failures: {tests: v.testFails, builds: v.buildFails}},
|
|
63
83
|
humanActions: approvals,
|
|
84
|
+
probes,
|
|
64
85
|
log: {file: 'events.jsonl', sha256: createHash('sha256').update(raw).digest('hex'), bytes: raw.length, entries: events.length, tornLines: torn,
|
|
65
86
|
kernelSteps: steps.length, blocks, commitsAllowed, decisions: Object.fromEntries(Object.entries(decisions).sort())},
|
|
66
87
|
consistent: checks.every((c) => c.ok || c.name === 'working tree counted'),
|
|
@@ -79,6 +100,7 @@ export function attestMarkdown(a ) {
|
|
|
79
100
|
`| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
|
|
80
101
|
...(a.config.baseRef ? [`| Base ref | \`${a.config.baseRef}\` |`] : []),
|
|
81
102
|
...(a.config.stopGate === 'warn' ? ['| Stop gate | warn (Stop does not block a turn; git commit and git push stay gated) |'] : []),
|
|
103
|
+
...(a.config.requireRun ? ['| requireRun | true (the build and full test gates count only through `stopbar run build` and `stopbar run test`) |'] : []),
|
|
82
104
|
`| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
|
|
83
105
|
`| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
|
|
84
106
|
`| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
|
|
@@ -88,6 +110,9 @@ export function attestMarkdown(a ) {
|
|
|
88
110
|
`| Kernel steps / blocks / commits allowed | ${a.log.kernelSteps} / ${a.log.blocks} / ${a.log.commitsAllowed} |`,
|
|
89
111
|
`| Consistent | ${yn(a.consistent)} |`, '',
|
|
90
112
|
`## Human actions`, '', ...(a.humanActions.length ? a.humanActions.map((h) => `- line ${h.line}, ${h.ts}: ${h.action}${'revision' in h ? ` revision ${h.revision}` : ''}${'extra' in h ? ` extra ${h.extra}` : ''}${h.decision ? ` -> ${h.decision}` : ''}`) : ['- none']), '',
|
|
113
|
+
`## Probe evidence`, '', ...(a.probes.length ? a.probes.map((p) => `- ${p.target}: ${p.ok ? 'PASS' : 'FAIL'}, ${p.runs} runs, ${p.steps} steps` +
|
|
114
|
+
`${p.mutants ? `, mutants ${p.mutants.killed}/${p.mutants.total} killed${p.mutants.survived.length ? ` (survived: ${p.mutants.survived.join(', ')})` : ''}` : ''}` +
|
|
115
|
+
`, at current snapshot: ${yn(p.atCurrentSnapshot)}${p.targetSha256 ? `, target sha256 \`${String(p.targetSha256).slice(0, 16)}\`` : ''} (line ${p.line})`) : ['- none']), '',
|
|
91
116
|
`## Checks`, '', ...a.checks.map((c) => `- [${c.ok ? 'x' : ' '}] ${c.name}: ${c.detail}`), '',
|
|
92
117
|
].join('\n')
|
|
93
118
|
}
|
package/dist/build-info.json
CHANGED
package/dist/classify.js
CHANGED
|
@@ -80,6 +80,39 @@ export function scanShell(cmd )
|
|
|
80
80
|
}
|
|
81
81
|
export const hasChain = (cmd ) => scanShell(cmd).chain
|
|
82
82
|
|
|
83
|
+
/** The command text as bash joins quoted parts of one word: `.e""nv`, `.g''it`, `.e"n"v` and `.cl''aude` become `.env`,
|
|
84
|
+
* `.git`, `.env` and `.claude`. For the text scans of secrets and self-protection only (never for gate matching):
|
|
85
|
+
* empty quote pairs are dropped, and so is a quote between two characters of a word. */
|
|
86
|
+
export function unsplice(cmd ) {
|
|
87
|
+
return cmd.replace(/""|''/g, '').replace(/(?<=[\w.\-/\\~])["'](?=[\w.\-/\\~])/g, '')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The command text with the quote pairs of every word removed, as bash joins the parts of a word: `'.cl'"aude"` is
|
|
91
|
+
* `.claude`, `.g"i"'t'` is `.git`, `gi"t"` is `git`. Separators (spaces, operators) and the spaces inside quotes stay as
|
|
92
|
+
* they are, so words are never joined across whitespace. Inside "..." the escapes \" \\ \$ \` work; inside '...' nothing.
|
|
93
|
+
* Outside quotes a backslash is kept as written (`g\it` is a known limit, SECURITY.md). An unterminated quote runs to the
|
|
94
|
+
* end. For the text scans (self-protection, secrets, the git subcommand) only; give it the command without the data
|
|
95
|
+
* bodies the caller skips (a plain `-m` message: commandForSelfProtect; a safe heredoc: its prefix). */
|
|
96
|
+
export function unquoteShellWords(cmd ) {
|
|
97
|
+
let out = ''
|
|
98
|
+
for (let i = 0; i < cmd.length; i++) {
|
|
99
|
+
const c = cmd[i]
|
|
100
|
+
if (c === "'") {
|
|
101
|
+
const j = cmd.indexOf("'", i + 1)
|
|
102
|
+
out += j < 0 ? cmd.slice(i + 1) : cmd.slice(i + 1, j)
|
|
103
|
+
i = j < 0 ? cmd.length : j
|
|
104
|
+
} else if (c === '"') {
|
|
105
|
+
let j = i + 1
|
|
106
|
+
for (; j < cmd.length && cmd[j] !== '"'; j++) {
|
|
107
|
+
if (cmd[j] === '\\' && j + 1 < cmd.length && '"\\$`'.includes(cmd[j + 1])) j++
|
|
108
|
+
out += cmd[j]
|
|
109
|
+
}
|
|
110
|
+
i = j
|
|
111
|
+
} else if (c === '\\' && i + 1 < cmd.length) { out += c + cmd[i + 1]; i++ } else out += c
|
|
112
|
+
}
|
|
113
|
+
return out
|
|
114
|
+
}
|
|
115
|
+
|
|
83
116
|
// ---------------------------------------------------------------- risky / outbound shell
|
|
84
117
|
const NET_TOOLS = /\b(curl|wget|nc|ncat|netcat|socat|ssh|scp|sftp|rsync|ftp|tftp|telnet)\b/i
|
|
85
118
|
const PS_NET = /Invoke-WebRequest|Invoke-RestMethod|\biwr\b|\birm\b|Start-BitsTransfer|Net\.WebClient|System\.Net\.|Net\.Sockets/i
|
|
@@ -95,18 +128,95 @@ export function isRiskyShell(cmd ) {
|
|
|
95
128
|
}
|
|
96
129
|
|
|
97
130
|
// ---------------------------------------------------------------- git commands
|
|
98
|
-
// git global options before the subcommand: -c k=v, -C dir, --git-dir=..., --work-tree ..., --no-pager, -p (values may be
|
|
99
|
-
|
|
131
|
+
// git global options before the subcommand: -c k=v, -C dir, --git-dir=..., --work-tree ..., --no-pager, -p (values may be
|
|
132
|
+
// quoted). With a separate value (git 2.56 `git --help` and git.c): --git-dir, --work-tree, --namespace, --config-env,
|
|
133
|
+
// --attr-source; --exec-path, --super-prefix (older git) and --list-cmds are listed too. Any other `--opt=value` is one word.
|
|
134
|
+
const GV = String.raw`(?:"[^"]*"|'[^']*'|\S+)`
|
|
135
|
+
const GIT_GLOBALS = String.raw`(?:\s+(?:-[cC]\s*${GV}|--(?:git-dir|work-tree|namespace|exec-path|config-env|attr-source|super-prefix|list-cmds)(?:=|\s+)${GV}|--[\w-]+=${GV}|--[\w-]+|-[A-Za-z]))*`
|
|
100
136
|
const gitSub = (sub , flags = 'i') => new RegExp(String.raw`\bgit(?:\.exe)?${GIT_GLOBALS}\s+(?:${sub})\b`, flags)
|
|
101
|
-
const COMMIT_RE = gitSub('commit|push'), PUSH_RE = gitSub('push'),
|
|
137
|
+
const COMMIT_RE = gitSub('commit|push'), PUSH_RE = gitSub('push'), CONFIG_RE_G = gitSub('config', 'gi')
|
|
102
138
|
const COMMIT_ONLY_RE = new RegExp(String.raw`^git(?:\.exe)?${GIT_GLOBALS}\s+commit\b`, 'i')
|
|
103
|
-
const CONFIG_READ = /\s(--get|--get-all|--get-regexp|--list|-l|--show-origin|--show-scope|get|list)(\s|=|$)/i
|
|
104
139
|
|
|
105
|
-
/** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data)
|
|
140
|
+
/** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data); as written
|
|
141
|
+
* and with the quotes of each word removed (`gi"t" commit` is `git commit`). */
|
|
106
142
|
const commandPart = (cmd ) => parseSafeHeredocCommit(cmd)?.prefix ?? cmd
|
|
107
|
-
|
|
108
|
-
export const
|
|
109
|
-
export const
|
|
143
|
+
const gitTexts = (part ) => [part, unquoteShellWords(part)]
|
|
144
|
+
export const isCommitCmd = (cmd ) => gitTexts(commandPart(cmd)).some((t) => COMMIT_RE.test(t))
|
|
145
|
+
export const isPushCmd = (cmd ) => gitTexts(commandPart(cmd)).some((t) => PUSH_RE.test(t))
|
|
146
|
+
|
|
147
|
+
// `git config` reads: only the tokens right after `config` decide, never a value at the end (`git config core.hooksPath
|
|
148
|
+
// list` is a write). A read is the subcommand `list` (no argument) or `get <name>` as the first positional word, or one
|
|
149
|
+
// of the options --get, --get-all, --get-regexp <name>, --get-urlmatch <name> <url>, --list / -l before the arguments;
|
|
150
|
+
// scope and format flags may stand around them. A write flag, an unknown flag, an expansion or any other argument count
|
|
151
|
+
// make it a write (fail closed).
|
|
152
|
+
const CFG_WRITE = new Set(['--add', '--unset', '--unset-all', '--replace-all', '--rename-section', '--remove-section', '--edit', '-e'])
|
|
153
|
+
const CFG_FLAG = new Set(['--local', '--global', '--system', '--worktree', '--includes', '--no-includes', '--show-origin', '--show-scope', '--null', '-z',
|
|
154
|
+
'--name-only', '--all', '--regexp', '--fixed-value', '--show-names', '--no-show-names', '--bool', '--int', '--bool-or-int', '--path', '--expiry-date', '--no-type'])
|
|
155
|
+
const CFG_FLAG_ARG = new Set(['--file', '-f', '--blob', '--default', '--type', '--value', '--url'])
|
|
156
|
+
const CFG_READ_OPT = new Map([['--get', 1], ['--get-all', 1], ['--get-regexp', 1], ['--get-urlmatch', 2], ['--list', 0], ['-l', 0]])
|
|
157
|
+
const CFG_READ_SUB = new Map([['list', 0], ['get', 1]])
|
|
158
|
+
|
|
159
|
+
/** The words of one simple command, quotes removed, up to the first operator outside quotes (`;`, `&`, `|`, `(`, `)`,
|
|
160
|
+
* a newline, a redirection; a file descriptor number right before `<` / `>` is dropped). Null for an expansion ($, `)
|
|
161
|
+
* outside single quotes: its value is unknown. */
|
|
162
|
+
function simpleWords(s ) {
|
|
163
|
+
const words = []
|
|
164
|
+
let w = '', inWord = false
|
|
165
|
+
for (let i = 0; i < s.length; i++) {
|
|
166
|
+
const c = s[i]
|
|
167
|
+
if (c === "'") { const j = s.indexOf("'", i + 1); w += j < 0 ? s.slice(i + 1) : s.slice(i + 1, j); inWord = true; i = j < 0 ? s.length : j; continue }
|
|
168
|
+
if (c === '"') {
|
|
169
|
+
let j = i + 1
|
|
170
|
+
for (; j < s.length && s[j] !== '"'; j++) {
|
|
171
|
+
if (s[j] === '\\' && j + 1 < s.length && '"\\$`'.includes(s[j + 1])) j++
|
|
172
|
+
else if (s[j] === '$' || s[j] === '`') return null
|
|
173
|
+
w += s[j]
|
|
174
|
+
}
|
|
175
|
+
inWord = true; i = j; continue
|
|
176
|
+
}
|
|
177
|
+
if (c === '$' || c === '`') return null
|
|
178
|
+
if (c === '\\') { w += s[i + 1] ?? ''; inWord = true; i++; continue }
|
|
179
|
+
if (c === ' ' || c === '\t') { if (inWord) words.push(w); w = ''; inWord = false; continue }
|
|
180
|
+
if (';&|()\r\n'.includes(c)) break
|
|
181
|
+
if (c === '<' || c === '>') { if (inWord && /^\d+$/.test(w)) inWord = false; break }
|
|
182
|
+
w += c; inWord = true
|
|
183
|
+
}
|
|
184
|
+
if (inWord) words.push(w)
|
|
185
|
+
return words
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function configIsRead(args ) {
|
|
189
|
+
let mode
|
|
190
|
+
const pos = []
|
|
191
|
+
for (let i = 0; i < args.length; i++) {
|
|
192
|
+
const a = args[i]
|
|
193
|
+
if (a.length > 1 && a.startsWith('-')) {
|
|
194
|
+
const eq = a.startsWith('--') ? a.indexOf('=') : -1, name = eq < 0 ? a : a.slice(0, eq)
|
|
195
|
+
if (CFG_WRITE.has(name)) return false
|
|
196
|
+
if (CFG_READ_OPT.has(name)) {
|
|
197
|
+
if (eq >= 0 || pos.length || mode !== undefined) return false
|
|
198
|
+
mode = CFG_READ_OPT.get(name); continue
|
|
199
|
+
}
|
|
200
|
+
if (CFG_FLAG_ARG.has(name)) { if (eq < 0 && ++i >= args.length) return false; continue }
|
|
201
|
+
if (CFG_FLAG.has(name) && eq < 0) continue
|
|
202
|
+
return false
|
|
203
|
+
}
|
|
204
|
+
if (!pos.length && mode === undefined && CFG_READ_SUB.has(a)) { mode = CFG_READ_SUB.get(a); continue }
|
|
205
|
+
pos.push(a)
|
|
206
|
+
}
|
|
207
|
+
return mode !== undefined && pos.length === mode
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Any `git config` in the text that is not a read (see above) is a write. */
|
|
211
|
+
export function isGitConfigWrite(cmd ) {
|
|
212
|
+
for (const m of cmd.matchAll(CONFIG_RE_G)) {
|
|
213
|
+
const rest = cmd.slice(m.index + m[0].length)
|
|
214
|
+
if (rest && !/^[\s;&|()<>]/.test(rest)) return true
|
|
215
|
+
const args = simpleWords(rest)
|
|
216
|
+
if (!args || !configIsRead(args)) return true
|
|
217
|
+
}
|
|
218
|
+
return false
|
|
219
|
+
}
|
|
110
220
|
|
|
111
221
|
// A runner counts only as a command word: `cat pytest.ini` or `vim jest.config.js` is not a test run (fuzzer find, seed 12).
|
|
112
222
|
const END = String.raw`(?![\w.\-/\\])`
|
|
@@ -128,7 +238,9 @@ const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
|
|
|
128
238
|
|
|
129
239
|
/** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched. */
|
|
130
240
|
export function secretInCommand(cmd , paths , exists = () => true) {
|
|
131
|
-
|
|
241
|
+
const words = (s ) => s.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)
|
|
242
|
+
// the words as written, then as bash joins them (`.e""nv` is `.env`)
|
|
243
|
+
for (const tok of new Set([...words(cmd), ...words(unsplice(cmd)), ...words(unquoteShellWords(cmd))])) {
|
|
132
244
|
const hits = paths.secrets.filter((g) => matchesSecretGlob(tok, g))
|
|
133
245
|
if (!hits.length) continue
|
|
134
246
|
const strong = hits.find((g) => !EXT_ONLY.test(g))
|
|
@@ -148,8 +260,8 @@ export const mentionsSecret = (cmd , paths , exists
|
|
|
148
260
|
/** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
|
|
149
261
|
export function classifyBash(cmd , cfg , shell = 'bash', exists ) {
|
|
150
262
|
const c = cmd.trim()
|
|
151
|
-
const scan
|
|
152
|
-
if (
|
|
263
|
+
const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
|
|
264
|
+
if (gitTexts(scan.heredoc ? commandPart(c) : c).some((t) => COMMIT_RE.test(t))) {
|
|
153
265
|
if (scan.chain) return {kind: 'commit-chained', reason: scan.reason ?? 'chain'}
|
|
154
266
|
return {kind: 'commit', heredoc: !!scan.heredoc, push: isPushCmd(c)}
|
|
155
267
|
}
|
|
@@ -163,15 +275,28 @@ export function classifyBash(cmd , cfg
|
|
|
163
275
|
return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
|
|
164
276
|
}
|
|
165
277
|
|
|
166
|
-
/** Kind of a tree change from a list of (status, path) and a test for "the path exists in
|
|
167
|
-
|
|
278
|
+
/** Kind of a tree change from a list of (status, path) and a test for "the path exists in the reference tree"
|
|
279
|
+
* (baseRef, else HEAD).
|
|
280
|
+
* `sameAsRef` (given with an explicit baseRef): "the file now has the same blob id as in baseRef, or is absent from
|
|
281
|
+
* both". Then a test-config file is suspicious only when its content differs from baseRef, and an existing test only
|
|
282
|
+
* when it differs from baseRef (changed or deleted), so tests taken over unchanged from baseRef (checkout, rebase,
|
|
283
|
+
* cherry-pick) do not taint. Without `sameAsRef` (no baseRef: HEAD, which the agent's own git commands can move),
|
|
284
|
+
* every change of test config and of an existing test is suspicious. */
|
|
285
|
+
export function classifyTreeChange(changes , inHead , paths , sameAsRef ) {
|
|
168
286
|
let anyTest = false, suspicious = false
|
|
169
287
|
const why = []
|
|
170
288
|
for (const {status, path} of changes) {
|
|
171
|
-
if (isTestConfigPath(path, paths)) {
|
|
289
|
+
if (isTestConfigPath(path, paths)) {
|
|
290
|
+
anyTest = true
|
|
291
|
+
if (sameAsRef?.(path)) why.push(`config ${status} ${path} (same as base ref)`)
|
|
292
|
+
else { suspicious = true; why.push(`config ${status} ${path}`) }
|
|
293
|
+
continue
|
|
294
|
+
}
|
|
172
295
|
if (isTestPath(path, paths)) {
|
|
173
296
|
anyTest = true
|
|
174
|
-
if (inHead(path))
|
|
297
|
+
if (!inHead(path)) why.push(`new test ${status} ${path}`)
|
|
298
|
+
else if (sameAsRef?.(path)) why.push(`existing test ${status} ${path} (same as base ref)`)
|
|
299
|
+
else { suspicious = true; why.push(`existing test ${status} ${path}`) }
|
|
175
300
|
}
|
|
176
301
|
}
|
|
177
302
|
return {op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE' , suspicious, why}
|
|
@@ -208,7 +333,9 @@ const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.repl
|
|
|
208
333
|
const DOT_GIT = SEG('.git')
|
|
209
334
|
const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
|
|
210
335
|
const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
|
|
211
|
-
|
|
336
|
+
// an admin subcommand right after the program word (`stopbar`, `stopbar.mjs`, `stopbar@1.2.0`, `.../stopbar/dist/cli.js`,
|
|
337
|
+
// quoted or not): `stopbar init` is human-only, `stopbar probe init` (a prober scaffold, SKILL.md) is the agent's
|
|
338
|
+
const STOPBAR_ADMIN = /stopbar[^\s"'|;&]*["']?\s+(?:init|resume|reset|upgrade|doctor\b[^\n;&|]*?\s--fix)\b/i
|
|
212
339
|
|
|
213
340
|
/** Command text inspected by self-protection. For a plain single-command `git commit` (chain-free, no substitution),
|
|
214
341
|
* strips the commit message (safe heredoc body or quoted `-m` / `--message` string) because git treats it as data. */
|
|
@@ -248,14 +375,63 @@ export function commandForSelfProtect(cmd , shell
|
|
|
248
375
|
return out
|
|
249
376
|
}
|
|
250
377
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
378
|
+
// `git -c alias.ci=commit ci` (also `-calias.`, `--config-env alias.`, GIT_CONFIG_KEY_n=alias.): a one-off alias hides
|
|
379
|
+
// the real git subcommand from the classification of commits and pushes in PreToolUse.
|
|
380
|
+
const GIT_ALIAS = new RegExp(String.raw`\bgit(?:\.exe)?${GIT_GLOBALS}\s+(?:-c\s*|--config-env(?:=|\s+))["']?\s*alias\.`, 'i')
|
|
381
|
+
const GIT_ALIAS_ENV = /\bGIT_CONFIG_(?:PARAMETERS\b|KEY_\d+\s*=\s*["']?alias\.)/i
|
|
382
|
+
|
|
383
|
+
// A single-quoted heredoc fed to a command as stdin, e.g. a prompt for another agent CLI: `agy -p - <<'EOF'` ... `EOF`.
|
|
384
|
+
// With the delimiter in quotes bash expands nothing in the body, so the body is data for the command, unless the command
|
|
385
|
+
// runs it as code (a shell or an interpreter, xargs, at), hands it to Stopbar, or stores it in a file (> / >>, tee).
|
|
386
|
+
const STDIN_HEREDOC = /<<-?[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'/g
|
|
387
|
+
const RUNS_STDIN = /^(?:sh|bash|zsh|dash|ksh|fish|pwsh|powershell|cmd|eval|source|\.|node|deno|bun|tsx|ts-node|python[0-9.]*|py|pypy[0-9.]*|perl|ruby|php|lua|osascript|xargs|parallel|at|batch|crontab|tee|dd|stopbar(?:\.mjs)?)$/i
|
|
388
|
+
|
|
389
|
+
/** The command without the body of its one single-quoted heredoc, when that body is plain stdin data (see above);
|
|
390
|
+
* else null. The lines before and after the heredoc stay: they are commands. */
|
|
391
|
+
export function withoutStdinHeredoc(cmd ) {
|
|
392
|
+
if (cmd.includes('\r') || cmd.includes('\0')) return null
|
|
393
|
+
const all = [...cmd.matchAll(STDIN_HEREDOC)]
|
|
394
|
+
if (all.length !== 1 || (cmd.match(/<</g) ?? []).length !== 1) return null
|
|
395
|
+
const m = all[0], at = m.index
|
|
396
|
+
const lineStart = cmd.lastIndexOf('\n', at) + 1
|
|
397
|
+
const nl = cmd.indexOf('\n', at)
|
|
398
|
+
if (nl < 0) return null
|
|
399
|
+
const header = cmd.slice(lineStart, at) + ' ' + cmd.slice(at + m[0].length, nl)
|
|
400
|
+
const lines = cmd.slice(nl + 1).split('\n')
|
|
401
|
+
const end = lines.indexOf(m[1])
|
|
402
|
+
if (end < 0) return null // no closing delimiter line: not a heredoc this function understands
|
|
403
|
+
// on the header line, outside quotes: a write redirection (fd duplication such as 2>&1 is fine) or a pipe; outside
|
|
404
|
+
// single quotes: an expansion ($X, $(...), `...`), which may name an interpreter (X=bash; $X <<'EOF')
|
|
405
|
+
if (/>(?!&\d)|&>|\|/.test(header.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, "''"))) return null
|
|
406
|
+
if (/[$`]/.test(header.replace(/'[^']*'/g, "''"))) return null
|
|
407
|
+
// a word anywhere before the body that runs or stores stdin (also in a function or alias defined on an earlier line)
|
|
408
|
+
for (const w of (cmd.slice(0, at) + ' ' + header).split(/[\s;&|(){}<>=]+/).filter(Boolean)) {
|
|
409
|
+
const base = w.replace(/^["']+|["']+$/g, '').replace(/\\/g, '/').split('/').pop() .replace(/\.exe$/i, '')
|
|
410
|
+
if (RUNS_STDIN.test(base)) return null
|
|
411
|
+
}
|
|
412
|
+
return [cmd.slice(0, nl), ...lines.slice(end)].join('\n')
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md.
|
|
416
|
+
* Every check runs on the text as written and as bash joins quoted parts of a word (`.g""it`, `'.cl'"aude"`, `gi"t"`:
|
|
417
|
+
* unsplice and unquoteShellWords). For bash, the body of
|
|
418
|
+
* one single-quoted heredoc that is plain stdin data (withoutStdinHeredoc) is skipped by the human-only checks only:
|
|
419
|
+
* .git, the agent settings directories and Stopbar code stay protected in it. */
|
|
420
|
+
export function protectedCommand(cmd , pr , shell = 'bash') {
|
|
421
|
+
const texts = [...new Set([cmd, unsplice(cmd), unquoteShellWords(cmd)])]
|
|
422
|
+
for (const t of texts) {
|
|
423
|
+
const c = norm(t).toLowerCase()
|
|
424
|
+
if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
|
|
425
|
+
for (const [re, d] of AGENT_DIRS) if (re.test(c)) return `the command names a ${d} directory (agent settings there hold the Stopbar hooks)`
|
|
426
|
+
}
|
|
427
|
+
for (const t of texts) {
|
|
428
|
+
const c = norm(t).toLowerCase()
|
|
429
|
+
if (isGitConfigWrite(t)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
|
|
430
|
+
if (GIT_ALIAS.test(t) || GIT_ALIAS_ENV.test(t)) return '`git -c alias.<name>=...` defines a one-off git alias, which hides the real git subcommand'
|
|
431
|
+
if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
|
|
432
|
+
for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
|
|
433
|
+
}
|
|
434
|
+
const admin = (shell === 'bash' ? withoutStdinHeredoc(cmd) : null) ?? cmd
|
|
435
|
+
for (const t of new Set([admin, unsplice(admin), unquoteShellWords(admin)])) if (HUMAN_ONLY.test(t) || STOPBAR_ADMIN.test(t)) return 'human-only Stopbar command or setting'
|
|
260
436
|
return null
|
|
261
437
|
}
|