stopbar 1.1.3 → 1.2.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 +184 -0
- package/README.md +225 -31
- package/SECURITY.md +129 -39
- package/bin/stopbar.mjs +0 -0
- package/dist/adapters/antigravity.js +6 -6
- package/dist/adapters/claude.js +1 -1
- package/dist/adapters/codex.js +7 -7
- package/dist/adapters/cursor.js +6 -6
- package/dist/adapters/gemini.js +7 -7
- package/dist/adapters/index.js +4 -3
- package/dist/adapters/types.js +7 -4
- package/dist/attest.js +28 -3
- package/dist/build-info.json +2 -2
- package/dist/classify.js +356 -29
- package/dist/cli.js +39 -7
- package/dist/commands.js +36 -13
- package/dist/config.js +7 -2
- package/dist/doctor.js +63 -28
- package/dist/hook.js +59 -32
- package/dist/integrations.js +50 -6
- package/dist/probe/index.js +261 -62
- package/dist/probe/init.js +217 -0
- package/dist/probe/sdk.js +242 -0
- package/dist/probe/stdio.js +219 -0
- package/dist/probe/wrapper.js +1 -1
- package/dist/store.js +1 -1
- package/dist/verify.js +34 -26
- package/package.json +17 -2
- package/skills/stopbar/SKILL.md +126 -0
- package/src/probe/sdk.ts +241 -0
package/dist/classify.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Deterministic classification rules of the wrapper: file paths and the text of a shell command. No AST.
|
|
3
3
|
// Everything here is enforced by the wrapper, not by the proof (see SECURITY.md).
|
|
4
4
|
|
|
5
|
+
import {posix} from 'node:path'
|
|
5
6
|
import {matchAny, matchAnySuffix} from './glob.js'
|
|
6
7
|
|
|
7
8
|
const norm = (p ) => p.replace(/\\/g, '/')
|
|
@@ -80,6 +81,39 @@ export function scanShell(cmd )
|
|
|
80
81
|
}
|
|
81
82
|
export const hasChain = (cmd ) => scanShell(cmd).chain
|
|
82
83
|
|
|
84
|
+
/** The command text as bash joins quoted parts of one word: `.e""nv`, `.g''it`, `.e"n"v` and `.cl''aude` become `.env`,
|
|
85
|
+
* `.git`, `.env` and `.claude`. For the text scans of secrets and self-protection only (never for gate matching):
|
|
86
|
+
* empty quote pairs are dropped, and so is a quote between two characters of a word. */
|
|
87
|
+
export function unsplice(cmd ) {
|
|
88
|
+
return cmd.replace(/""|''/g, '').replace(/(?<=[\w.\-/\\~])["'](?=[\w.\-/\\~])/g, '')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The command text with the quote pairs of every word removed, as bash joins the parts of a word: `'.cl'"aude"` is
|
|
92
|
+
* `.claude`, `.g"i"'t'` is `.git`, `gi"t"` is `git`. Separators (spaces, operators) and the spaces inside quotes stay as
|
|
93
|
+
* they are, so words are never joined across whitespace. Inside "..." the escapes \" \\ \$ \` work; inside '...' nothing.
|
|
94
|
+
* Outside quotes a backslash is kept as written (`g\it` is a known limit, SECURITY.md). An unterminated quote runs to the
|
|
95
|
+
* end. For the text scans (self-protection, secrets, the git subcommand) only; give it the command without the data
|
|
96
|
+
* bodies the caller skips (a plain `-m` message: commandForSelfProtect; a safe heredoc: its prefix). */
|
|
97
|
+
export function unquoteShellWords(cmd ) {
|
|
98
|
+
let out = ''
|
|
99
|
+
for (let i = 0; i < cmd.length; i++) {
|
|
100
|
+
const c = cmd[i]
|
|
101
|
+
if (c === "'") {
|
|
102
|
+
const j = cmd.indexOf("'", i + 1)
|
|
103
|
+
out += j < 0 ? cmd.slice(i + 1) : cmd.slice(i + 1, j)
|
|
104
|
+
i = j < 0 ? cmd.length : j
|
|
105
|
+
} else if (c === '"') {
|
|
106
|
+
let j = i + 1
|
|
107
|
+
for (; j < cmd.length && cmd[j] !== '"'; j++) {
|
|
108
|
+
if (cmd[j] === '\\' && j + 1 < cmd.length && '"\\$`'.includes(cmd[j + 1])) j++
|
|
109
|
+
out += cmd[j]
|
|
110
|
+
}
|
|
111
|
+
i = j
|
|
112
|
+
} else if (c === '\\' && i + 1 < cmd.length) { out += c + cmd[i + 1]; i++ } else out += c
|
|
113
|
+
}
|
|
114
|
+
return out
|
|
115
|
+
}
|
|
116
|
+
|
|
83
117
|
// ---------------------------------------------------------------- risky / outbound shell
|
|
84
118
|
const NET_TOOLS = /\b(curl|wget|nc|ncat|netcat|socat|ssh|scp|sftp|rsync|ftp|tftp|telnet)\b/i
|
|
85
119
|
const PS_NET = /Invoke-WebRequest|Invoke-RestMethod|\biwr\b|\birm\b|Start-BitsTransfer|Net\.WebClient|System\.Net\.|Net\.Sockets/i
|
|
@@ -95,18 +129,95 @@ export function isRiskyShell(cmd ) {
|
|
|
95
129
|
}
|
|
96
130
|
|
|
97
131
|
// ---------------------------------------------------------------- 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
|
-
|
|
132
|
+
// git global options before the subcommand: -c k=v, -C dir, --git-dir=..., --work-tree ..., --no-pager, -p (values may be
|
|
133
|
+
// quoted). With a separate value (git 2.56 `git --help` and git.c): --git-dir, --work-tree, --namespace, --config-env,
|
|
134
|
+
// --attr-source; --exec-path, --super-prefix (older git) and --list-cmds are listed too. Any other `--opt=value` is one word.
|
|
135
|
+
const GV = String.raw`(?:"[^"]*"|'[^']*'|\S+)`
|
|
136
|
+
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
137
|
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'),
|
|
138
|
+
const COMMIT_RE = gitSub('commit|push'), PUSH_RE = gitSub('push'), CONFIG_RE_G = gitSub('config', 'gi')
|
|
102
139
|
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
140
|
|
|
105
|
-
/** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data)
|
|
141
|
+
/** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data); as written
|
|
142
|
+
* and with the quotes of each word removed (`gi"t" commit` is `git commit`). */
|
|
106
143
|
const commandPart = (cmd ) => parseSafeHeredocCommit(cmd)?.prefix ?? cmd
|
|
107
|
-
|
|
108
|
-
export const
|
|
109
|
-
export const
|
|
144
|
+
const gitTexts = (part ) => [part, unquoteShellWords(part)]
|
|
145
|
+
export const isCommitCmd = (cmd ) => gitTexts(commandPart(cmd)).some((t) => COMMIT_RE.test(t))
|
|
146
|
+
export const isPushCmd = (cmd ) => gitTexts(commandPart(cmd)).some((t) => PUSH_RE.test(t))
|
|
147
|
+
|
|
148
|
+
// `git config` reads: only the tokens right after `config` decide, never a value at the end (`git config core.hooksPath
|
|
149
|
+
// list` is a write). A read is the subcommand `list` (no argument) or `get <name>` as the first positional word, or one
|
|
150
|
+
// of the options --get, --get-all, --get-regexp <name>, --get-urlmatch <name> <url>, --list / -l before the arguments;
|
|
151
|
+
// scope and format flags may stand around them. A write flag, an unknown flag, an expansion or any other argument count
|
|
152
|
+
// make it a write (fail closed).
|
|
153
|
+
const CFG_WRITE = new Set(['--add', '--unset', '--unset-all', '--replace-all', '--rename-section', '--remove-section', '--edit', '-e'])
|
|
154
|
+
const CFG_FLAG = new Set(['--local', '--global', '--system', '--worktree', '--includes', '--no-includes', '--show-origin', '--show-scope', '--null', '-z',
|
|
155
|
+
'--name-only', '--all', '--regexp', '--fixed-value', '--show-names', '--no-show-names', '--bool', '--int', '--bool-or-int', '--path', '--expiry-date', '--no-type'])
|
|
156
|
+
const CFG_FLAG_ARG = new Set(['--file', '-f', '--blob', '--default', '--type', '--value', '--url'])
|
|
157
|
+
const CFG_READ_OPT = new Map([['--get', 1], ['--get-all', 1], ['--get-regexp', 1], ['--get-urlmatch', 2], ['--list', 0], ['-l', 0]])
|
|
158
|
+
const CFG_READ_SUB = new Map([['list', 0], ['get', 1]])
|
|
159
|
+
|
|
160
|
+
/** The words of one simple command, quotes removed, up to the first operator outside quotes (`;`, `&`, `|`, `(`, `)`,
|
|
161
|
+
* a newline, a redirection; a file descriptor number right before `<` / `>` is dropped). Null for an expansion ($, `)
|
|
162
|
+
* outside single quotes: its value is unknown. */
|
|
163
|
+
function simpleWords(s ) {
|
|
164
|
+
const words = []
|
|
165
|
+
let w = '', inWord = false
|
|
166
|
+
for (let i = 0; i < s.length; i++) {
|
|
167
|
+
const c = s[i]
|
|
168
|
+
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 }
|
|
169
|
+
if (c === '"') {
|
|
170
|
+
let j = i + 1
|
|
171
|
+
for (; j < s.length && s[j] !== '"'; j++) {
|
|
172
|
+
if (s[j] === '\\' && j + 1 < s.length && '"\\$`'.includes(s[j + 1])) j++
|
|
173
|
+
else if (s[j] === '$' || s[j] === '`') return null
|
|
174
|
+
w += s[j]
|
|
175
|
+
}
|
|
176
|
+
inWord = true; i = j; continue
|
|
177
|
+
}
|
|
178
|
+
if (c === '$' || c === '`') return null
|
|
179
|
+
if (c === '\\') { w += s[i + 1] ?? ''; inWord = true; i++; continue }
|
|
180
|
+
if (c === ' ' || c === '\t') { if (inWord) words.push(w); w = ''; inWord = false; continue }
|
|
181
|
+
if (';&|()\r\n'.includes(c)) break
|
|
182
|
+
if (c === '<' || c === '>') { if (inWord && /^\d+$/.test(w)) inWord = false; break }
|
|
183
|
+
w += c; inWord = true
|
|
184
|
+
}
|
|
185
|
+
if (inWord) words.push(w)
|
|
186
|
+
return words
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function configIsRead(args ) {
|
|
190
|
+
let mode
|
|
191
|
+
const pos = []
|
|
192
|
+
for (let i = 0; i < args.length; i++) {
|
|
193
|
+
const a = args[i]
|
|
194
|
+
if (a.length > 1 && a.startsWith('-')) {
|
|
195
|
+
const eq = a.startsWith('--') ? a.indexOf('=') : -1, name = eq < 0 ? a : a.slice(0, eq)
|
|
196
|
+
if (CFG_WRITE.has(name)) return false
|
|
197
|
+
if (CFG_READ_OPT.has(name)) {
|
|
198
|
+
if (eq >= 0 || pos.length || mode !== undefined) return false
|
|
199
|
+
mode = CFG_READ_OPT.get(name); continue
|
|
200
|
+
}
|
|
201
|
+
if (CFG_FLAG_ARG.has(name)) { if (eq < 0 && ++i >= args.length) return false; continue }
|
|
202
|
+
if (CFG_FLAG.has(name) && eq < 0) continue
|
|
203
|
+
return false
|
|
204
|
+
}
|
|
205
|
+
if (!pos.length && mode === undefined && CFG_READ_SUB.has(a)) { mode = CFG_READ_SUB.get(a); continue }
|
|
206
|
+
pos.push(a)
|
|
207
|
+
}
|
|
208
|
+
return mode !== undefined && pos.length === mode
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Any `git config` in the text that is not a read (see above) is a write. */
|
|
212
|
+
export function isGitConfigWrite(cmd ) {
|
|
213
|
+
for (const m of cmd.matchAll(CONFIG_RE_G)) {
|
|
214
|
+
const rest = cmd.slice(m.index + m[0].length)
|
|
215
|
+
if (rest && !/^[\s;&|()<>]/.test(rest)) return true
|
|
216
|
+
const args = simpleWords(rest)
|
|
217
|
+
if (!args || !configIsRead(args)) return true
|
|
218
|
+
}
|
|
219
|
+
return false
|
|
220
|
+
}
|
|
110
221
|
|
|
111
222
|
// 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
223
|
const END = String.raw`(?![\w.\-/\\])`
|
|
@@ -126,17 +237,113 @@ export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
|
|
|
126
237
|
const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
|
|
127
238
|
|
|
128
239
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
240
|
+
// Commands that print the whole environment (tokens, keys) count as a secret read, as a file would. `env VAR=1 cmd` and a
|
|
241
|
+
// bare `set` do not count: the first runs a command, the second is too common in scripts (a known limit, SECURITY.md).
|
|
242
|
+
const ENV_DUMP = [
|
|
243
|
+
[/(?:^|[\s;&|(`])printenv(?![\w.\-])/i, 'env:printenv'],
|
|
244
|
+
[/(?:^|[\s;&|(`])(?:Get-ChildItem|gci|dir|ls|Get-Item|gi|Get-Content|gc|cat|type)\s+(?:-(?:Path|LiteralPath)\s+)?Env:/i, 'env:Get-ChildItem Env:'],
|
|
245
|
+
[/(?:^|[;&|(`\n])\s*env\s*(?:-0\s*)?(?=$|[;&|>)\n])/i, 'env:env'],
|
|
246
|
+
[/\/proc\/(?:self|\d+|\$\$)\/environ\b/i, 'env:/proc/environ'],
|
|
247
|
+
]
|
|
248
|
+
const HAS_GLOB = /[*?[{]/
|
|
249
|
+
|
|
250
|
+
/** One path segment of a shell glob (`*`, `?`, `[...]`, `{a,b}`) as a RegExp (case-insensitive: Windows, and wider is
|
|
251
|
+
* safer here), or null when it cannot be read. */
|
|
252
|
+
export function globSegment(seg ) {
|
|
253
|
+
let re = '', depth = 0
|
|
254
|
+
for (let i = 0; i < seg.length; i++) {
|
|
255
|
+
const c = seg[i]
|
|
256
|
+
if (c === '*') re += '.*'
|
|
257
|
+
else if (c === '?') re += '.'
|
|
258
|
+
else if (c === '[') {
|
|
259
|
+
const j = seg.indexOf(']', i + 2)
|
|
260
|
+
if (j < 0) { re += '\\['; continue }
|
|
261
|
+
const body = seg.slice(i + 1, j).replace(/\\/g, '\\\\')
|
|
262
|
+
re += `[${body[0] === '!' ? '^' + body.slice(1) : body}]`
|
|
263
|
+
i = j
|
|
264
|
+
} else if (c === '{') { re += '(?:'; depth++ }
|
|
265
|
+
else if (c === ',' && depth) re += '|'
|
|
266
|
+
else if (c === '}' && depth) { re += ')'; depth-- }
|
|
267
|
+
else re += c.replace(/[.+^$()|\\/\]]/g, '\\$&')
|
|
268
|
+
}
|
|
269
|
+
if (depth) return null
|
|
270
|
+
try { return new RegExp(`^${re}$`, 'i') } catch { return null }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Names a wildcard may reach: the literal secret patterns and the `<prefix>*` ones (`.env*` gives .env and .env.local). */
|
|
274
|
+
function secretSamples(paths ) {
|
|
275
|
+
const out = []
|
|
276
|
+
for (const g of paths.secrets) {
|
|
277
|
+
const last = g.split('/').pop() ?? ''
|
|
278
|
+
if (!/^[^*?[{]+\*?$/.test(last)) continue
|
|
279
|
+
const base = last.replace(/\*$/, '')
|
|
280
|
+
out.push(base, ...(last.endsWith('*') ? [`${base}.local`] : []))
|
|
281
|
+
}
|
|
282
|
+
return out
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched.
|
|
286
|
+
* Also: a command that prints the environment (printenv, Get-ChildItem Env:), `..` segments (`src/../.env`), and a
|
|
287
|
+
* wildcard that reaches a secret name (`.en*`, `.en?`, `src/../.e*`). */
|
|
288
|
+
export function secretInCommand(cmd , paths , exists = () => true, shell = 'bash') {
|
|
289
|
+
const words = (s ) => s.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)
|
|
290
|
+
const texts = [cmd, unsplice(cmd), unquoteShellWords(cmd)]
|
|
291
|
+
if (paths.secrets.length) {
|
|
292
|
+
for (const t of texts) for (const [re, pattern] of ENV_DUMP) {
|
|
293
|
+
const m = re.exec(t)
|
|
294
|
+
if (m) return {token: m[0].replace(/^[\s;&|(`]+/, '').trim(), pattern}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// the words as written, then as bash joins them (`.e""nv` is `.env`); each also with its `..` segments resolved
|
|
298
|
+
for (const tok of new Set(texts.flatMap(words))) {
|
|
299
|
+
const n = posix.normalize(norm(tok))
|
|
300
|
+
for (const cand of n === tok ? [tok] : [tok, n]) {
|
|
301
|
+
const hits = paths.secrets.filter((g) => matchesSecretGlob(cand, g))
|
|
302
|
+
if (!hits.length) continue
|
|
303
|
+
const strong = hits.find((g) => !EXT_ONLY.test(g))
|
|
304
|
+
if (strong) return {token: tok, pattern: strong}
|
|
305
|
+
if (/[\\/]/.test(cand) || exists(cand)) return {token: tok, pattern: hits[0]}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// wildcards that expand: bash expands none inside quotes or after a backslash; PowerShell -Path expands them quoted too
|
|
309
|
+
const samples = secretSamples(paths)
|
|
310
|
+
for (const tok of new Set(words(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd)))) {
|
|
311
|
+
// the last segment: dot-leading (bash matches dotfiles only so), or after a literal prefix of 2+ chars
|
|
312
|
+
const last = posix.normalize(norm(tok)).split('/').pop() ?? ''
|
|
313
|
+
const at = last.search(HAS_GLOB)
|
|
314
|
+
if (at < 0 || !(last.startsWith('.') || at >= 2)) continue
|
|
315
|
+
const re = globSegment(last)
|
|
316
|
+
if (!re) continue
|
|
317
|
+
for (const s of samples) {
|
|
318
|
+
const pattern = re.test(s) ? secretPattern(s, paths) : null
|
|
319
|
+
if (pattern) return {token: tok, pattern}
|
|
320
|
+
}
|
|
137
321
|
}
|
|
138
322
|
return null
|
|
139
323
|
}
|
|
324
|
+
|
|
325
|
+
/** The command as bash joins its words, with the glob characters that do not expand (inside quotes, after a backslash)
|
|
326
|
+
* replaced by \x01, so only live wildcards are left. */
|
|
327
|
+
function globView(cmd ) {
|
|
328
|
+
let out = ''
|
|
329
|
+
const mask = (s ) => s.replace(/[*?[\]{}]/g, '\x01')
|
|
330
|
+
for (let i = 0; i < cmd.length; i++) {
|
|
331
|
+
const c = cmd[i]
|
|
332
|
+
if (c === "'") {
|
|
333
|
+
const j = cmd.indexOf("'", i + 1)
|
|
334
|
+
out += mask(j < 0 ? cmd.slice(i + 1) : cmd.slice(i + 1, j))
|
|
335
|
+
i = j < 0 ? cmd.length : j
|
|
336
|
+
} else if (c === '"') {
|
|
337
|
+
let j = i + 1
|
|
338
|
+
for (; j < cmd.length && cmd[j] !== '"'; j++) {
|
|
339
|
+
if (cmd[j] === '\\' && j + 1 < cmd.length && '"\\$`'.includes(cmd[j + 1])) j++
|
|
340
|
+
out += mask(cmd[j])
|
|
341
|
+
}
|
|
342
|
+
i = j
|
|
343
|
+
} else if (c === '\\' && i + 1 < cmd.length) { out += mask(cmd[i + 1]); i++ } else out += c
|
|
344
|
+
}
|
|
345
|
+
return out
|
|
346
|
+
}
|
|
140
347
|
export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
|
|
141
348
|
|
|
142
349
|
|
|
@@ -148,8 +355,8 @@ export const mentionsSecret = (cmd , paths , exists
|
|
|
148
355
|
/** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
|
|
149
356
|
export function classifyBash(cmd , cfg , shell = 'bash', exists ) {
|
|
150
357
|
const c = cmd.trim()
|
|
151
|
-
const scan
|
|
152
|
-
if (
|
|
358
|
+
const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
|
|
359
|
+
if (gitTexts(scan.heredoc ? commandPart(c) : c).some((t) => COMMIT_RE.test(t))) {
|
|
153
360
|
if (scan.chain) return {kind: 'commit-chained', reason: scan.reason ?? 'chain'}
|
|
154
361
|
return {kind: 'commit', heredoc: !!scan.heredoc, push: isPushCmd(c)}
|
|
155
362
|
}
|
|
@@ -160,7 +367,7 @@ export function classifyBash(cmd , cfg
|
|
|
160
367
|
if (c === cfg.buildCmd.trim()) return {kind: 'build'}
|
|
161
368
|
if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
|
|
162
369
|
}
|
|
163
|
-
return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
|
|
370
|
+
return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists, shell)}
|
|
164
371
|
}
|
|
165
372
|
|
|
166
373
|
/** Kind of a tree change from a list of (status, path) and a test for "the path exists in the reference tree"
|
|
@@ -221,7 +428,9 @@ const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.repl
|
|
|
221
428
|
const DOT_GIT = SEG('.git')
|
|
222
429
|
const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
|
|
223
430
|
const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
|
|
224
|
-
|
|
431
|
+
// an admin subcommand right after the program word (`stopbar`, `stopbar.mjs`, `stopbar@1.2.0`, `.../stopbar/dist/cli.js`,
|
|
432
|
+
// quoted or not): `stopbar init` is human-only, `stopbar probe init` (a prober scaffold, SKILL.md) is the agent's
|
|
433
|
+
const STOPBAR_ADMIN = /stopbar[^\s"'|;&]*["']?\s+(?:init|resume|reset|upgrade|doctor\b[^\n;&|]*?\s--fix)\b/i
|
|
225
434
|
|
|
226
435
|
/** Command text inspected by self-protection. For a plain single-command `git commit` (chain-free, no substitution),
|
|
227
436
|
* strips the commit message (safe heredoc body or quoted `-m` / `--message` string) because git treats it as data. */
|
|
@@ -261,14 +470,132 @@ export function commandForSelfProtect(cmd , shell
|
|
|
261
470
|
return out
|
|
262
471
|
}
|
|
263
472
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
473
|
+
// `git -c alias.ci=commit ci` (also `-calias.`, `--config-env alias.`, GIT_CONFIG_KEY_n=alias.): a one-off alias hides
|
|
474
|
+
// the real git subcommand from the classification of commits and pushes in PreToolUse.
|
|
475
|
+
const GIT_ALIAS = new RegExp(String.raw`\bgit(?:\.exe)?${GIT_GLOBALS}\s+(?:-c\s*|--config-env(?:=|\s+))["']?\s*alias\.`, 'i')
|
|
476
|
+
const GIT_ALIAS_ENV = /\bGIT_CONFIG_(?:PARAMETERS\b|KEY_\d+\s*=\s*["']?alias\.)/i
|
|
477
|
+
|
|
478
|
+
// A single-quoted heredoc fed to a command as stdin, e.g. a prompt for another agent CLI: `agy -p - <<'EOF'` ... `EOF`.
|
|
479
|
+
// With the delimiter in quotes bash expands nothing in the body, so the body is data for the command, unless the command
|
|
480
|
+
// runs it as code (a shell or an interpreter, xargs, at), hands it to Stopbar, or stores it in a file (> / >>, tee).
|
|
481
|
+
const STDIN_HEREDOC = /<<-?[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'/g
|
|
482
|
+
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
|
|
483
|
+
|
|
484
|
+
/** The command without the body of its one single-quoted heredoc, when that body is plain stdin data (see above);
|
|
485
|
+
* else null. The lines before and after the heredoc stay: they are commands. */
|
|
486
|
+
export function withoutStdinHeredoc(cmd ) {
|
|
487
|
+
if (cmd.includes('\r') || cmd.includes('\0')) return null
|
|
488
|
+
const all = [...cmd.matchAll(STDIN_HEREDOC)]
|
|
489
|
+
if (all.length !== 1 || (cmd.match(/<</g) ?? []).length !== 1) return null
|
|
490
|
+
const m = all[0], at = m.index
|
|
491
|
+
const lineStart = cmd.lastIndexOf('\n', at) + 1
|
|
492
|
+
const nl = cmd.indexOf('\n', at)
|
|
493
|
+
if (nl < 0) return null
|
|
494
|
+
const header = cmd.slice(lineStart, at) + ' ' + cmd.slice(at + m[0].length, nl)
|
|
495
|
+
const lines = cmd.slice(nl + 1).split('\n')
|
|
496
|
+
const end = lines.indexOf(m[1])
|
|
497
|
+
if (end < 0) return null // no closing delimiter line: not a heredoc this function understands
|
|
498
|
+
// on the header line, outside quotes: a write redirection (fd duplication such as 2>&1 is fine) or a pipe; outside
|
|
499
|
+
// single quotes: an expansion ($X, $(...), `...`), which may name an interpreter (X=bash; $X <<'EOF')
|
|
500
|
+
if (/>(?!&\d)|&>|\|/.test(header.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, "''"))) return null
|
|
501
|
+
if (/[$`]/.test(header.replace(/'[^']*'/g, "''"))) return null
|
|
502
|
+
// a word anywhere before the body that runs or stores stdin (also in a function or alias defined on an earlier line)
|
|
503
|
+
for (const w of (cmd.slice(0, at) + ' ' + header).split(/[\s;&|(){}<>=]+/).filter(Boolean)) {
|
|
504
|
+
const base = w.replace(/^["']+|["']+$/g, '').replace(/\\/g, '/').split('/').pop() .replace(/\.exe$/i, '')
|
|
505
|
+
if (RUNS_STDIN.test(base)) return null
|
|
506
|
+
}
|
|
507
|
+
return [cmd.slice(0, nl), ...lines.slice(end)].join('\n')
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// A wildcard that reaches .git or an agent settings directory (`rm -rf .g*`, `mv .cl* x`, `Remove-Item .g*`): blocked
|
|
511
|
+
// for the commands that delete or move, and for any command when the wildcard is followed by a path inside such a
|
|
512
|
+
// directory (`cp x .g*/hooks/pre-commit`). Other wildcards (`rm *.log`, a `.*` in a grep pattern) stay allowed.
|
|
513
|
+
const GUARDED = ['.git', '.claude', '.cursor', '.codex', '.gemini', '.agents']
|
|
514
|
+
const DESTRUCTIVE = /^(?:rm|rmdir|unlink|shred|mv|del|erase|rd|move|remove-item|ri|move-item|mi)$/i
|
|
515
|
+
const INSIDE = /^(?:hooks|config|stopbar|info|refs|head|index|objects|settings[\w.-]*\.json|hooks\.json)$/i
|
|
516
|
+
const globDir = (seg ) => (HAS_GLOB.test(seg) && /^[.?[]/.test(seg) ? GUARDED.find((d) => globSegment(seg)?.test(d)) ?? null : null)
|
|
517
|
+
/** `t`: the command with only live wildcards left (globView for bash). */
|
|
518
|
+
function wildcardGuardedDir(t ) {
|
|
519
|
+
for (const part of norm(t).split(/[;&|\n()`]+/)) {
|
|
520
|
+
const ws = part.split(/[\s<>='"]+/).filter(Boolean)
|
|
521
|
+
let k = 0
|
|
522
|
+
while (k < ws.length && (/^\w+=/.test(ws[k]) || /^(?:sudo|command|exec|nice|time)$/i.test(ws[k]))) k++
|
|
523
|
+
const destructive = DESTRUCTIVE.test((ws[k] ?? '').split('/').pop() .replace(/\.exe$/i, ''))
|
|
524
|
+
for (const w of ws.slice(k + 1)) {
|
|
525
|
+
const segs = w.split('/')
|
|
526
|
+
for (let i = 0; i < segs.length; i++) {
|
|
527
|
+
const d = globDir(segs[i])
|
|
528
|
+
if (d && (destructive || (i + 1 < segs.length && INSIDE.test(segs[i + 1])))) return d
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return null
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Shell words with their quotes kept; the operators ; & | ( ) and newline are words of their own. */
|
|
536
|
+
function shellWords(cmd ) {
|
|
537
|
+
const out = []
|
|
538
|
+
let w = ''
|
|
539
|
+
const flush = () => { if (w) out.push(w); w = '' }
|
|
540
|
+
for (let i = 0; i < cmd.length; i++) {
|
|
541
|
+
const c = cmd[i]
|
|
542
|
+
if (c === ' ' || c === '\t' || c === '\r') { flush(); continue }
|
|
543
|
+
if (';&|()\n'.includes(c)) { flush(); out.push(c); continue }
|
|
544
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
545
|
+
let j = i + 1
|
|
546
|
+
for (; j < cmd.length && cmd[j] !== c; j++) if (c !== "'" && cmd[j] === '\\') j++
|
|
547
|
+
w += cmd.slice(i, j + 1); i = j; continue
|
|
548
|
+
}
|
|
549
|
+
if (c === '$' && cmd[i + 1] === '(') {
|
|
550
|
+
let j = i + 2, depth = 1
|
|
551
|
+
for (; j < cmd.length && depth; j++) depth += cmd[j] === '(' ? 1 : cmd[j] === ')' ? -1 : 0
|
|
552
|
+
w += cmd.slice(i, j); i = j - 1; continue
|
|
553
|
+
}
|
|
554
|
+
if (c === '\\' && i + 1 < cmd.length) { w += cmd.slice(i, i + 2); i++; continue }
|
|
555
|
+
w += c
|
|
556
|
+
}
|
|
557
|
+
flush()
|
|
558
|
+
return out
|
|
559
|
+
}
|
|
560
|
+
// `git $f -m x`, `p=push; git $p`, `git "${cmd}"`, git `echo push`: the subcommand comes from an expansion, so the commit
|
|
561
|
+
// and push gates cannot see it. A `git` inside a quoted string is one word with its quotes, so it is no command here.
|
|
562
|
+
const GIT_OPT_ARG = /^(?:-[cC]|--(?:git-dir|work-tree|namespace|exec-path|config-env|attr-source|super-prefix))$/
|
|
563
|
+
export function dynamicGitSubcommand(cmd ) {
|
|
564
|
+
const ws = shellWords(cmd)
|
|
565
|
+
for (let i = 0; i < ws.length; i++) {
|
|
566
|
+
if (!/^git(?:\.exe)?$/i.test(unquoteShellWords(ws[i]).replace(/\\/g, '/').split('/').pop() )) continue
|
|
567
|
+
let j = i + 1
|
|
568
|
+
while (j < ws.length && ws[j].length > 1 && ws[j].startsWith('-')) j += GIT_OPT_ARG.test(ws[j]) ? 2 : 1
|
|
569
|
+
const sub = ws[j]
|
|
570
|
+
if (sub && /^(?:"?\$|"?`)/.test(sub)) return sub
|
|
571
|
+
}
|
|
572
|
+
return null
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md.
|
|
576
|
+
* Every check runs on the text as written and as bash joins quoted parts of a word (`.g""it`, `'.cl'"aude"`, `gi"t"`:
|
|
577
|
+
* unsplice and unquoteShellWords). For bash, the body of
|
|
578
|
+
* one single-quoted heredoc that is plain stdin data (withoutStdinHeredoc) is skipped by the human-only checks only:
|
|
579
|
+
* .git, the agent settings directories and Stopbar code stay protected in it. */
|
|
580
|
+
export function protectedCommand(cmd , pr , shell = 'bash') {
|
|
581
|
+
const texts = [...new Set([cmd, unsplice(cmd), unquoteShellWords(cmd)])]
|
|
582
|
+
for (const t of texts) {
|
|
583
|
+
const c = norm(t).toLowerCase()
|
|
584
|
+
if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
|
|
585
|
+
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)`
|
|
586
|
+
}
|
|
587
|
+
const g = wildcardGuardedDir(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd))
|
|
588
|
+
if (g) return `the command has a wildcard that reaches the ${g} directory (${g === '.git' ? 'Stopbar state, git hooks, git config live there' : 'agent settings there hold the Stopbar hooks'})`
|
|
589
|
+
const dyn = dynamicGitSubcommand(cmd)
|
|
590
|
+
if (dyn) return `the git subcommand comes from an expansion (${dyn}), which hides it from the commit and push gates; write the subcommand out`
|
|
591
|
+
for (const t of texts) {
|
|
592
|
+
const c = norm(t).toLowerCase()
|
|
593
|
+
if (isGitConfigWrite(t)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
|
|
594
|
+
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'
|
|
595
|
+
if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
|
|
596
|
+
for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
|
|
597
|
+
}
|
|
598
|
+
const admin = (shell === 'bash' ? withoutStdinHeredoc(cmd) : null) ?? cmd
|
|
599
|
+
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'
|
|
273
600
|
return null
|
|
274
601
|
}
|
package/dist/cli.js
CHANGED
|
@@ -11,9 +11,12 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
|
|
|
11
11
|
|
|
12
12
|
stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--base-ref <ref>] [--max-retries 3] [--cap 500]
|
|
13
13
|
[--cost 1] [--hooks claude,claude-project,cursor,codex,gemini,antigravity,git] [--no-pin] [--force] [--force-hooks] [--repo <dir>]
|
|
14
|
-
[--cli "<cmd>"] [--stop-gate block|warn]
|
|
14
|
+
[--cli "<cmd>"] [--stop-gate block|warn] [--require-run] [--no-git-hooks]
|
|
15
|
+
--hooks <clients> adds the git hooks (pre-commit, pre-push) unless --no-git-hooks;
|
|
16
|
+
a foreign git hook is kept with a warning (replace it: --hooks git --force-hooks)
|
|
15
17
|
--cli: command that starts Stopbar in hints (default: npx --no-install stopbar)
|
|
16
18
|
--stop-gate warn: Stop only warns; git commit and git push stay blocked until the gates pass
|
|
19
|
+
--require-run: build and full test gates count only through stopbar run build|test
|
|
17
20
|
stopbar upgrade [--hooks <targets>] [--force-hooks] [--repo <dir>]
|
|
18
21
|
a human re-pins the hook runtime from this package (and rewrites hooks with --hooks);
|
|
19
22
|
state, gates, taint and budget stay as they are
|
|
@@ -31,10 +34,25 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
|
|
|
31
34
|
Four pillars:
|
|
32
35
|
PROVE stopbar prove [--out f.json] [--lean f.lean] inductive proof of the kernel and the 10 mutants
|
|
33
36
|
(npm run verify:lean checks the Lean export with lake build in Docker)
|
|
34
|
-
PROBE stopbar probe [--target wrapper
|
|
35
|
-
|
|
37
|
+
PROBE stopbar probe [--target wrapper|<file> | --cmd "<command>" [--target-file <path>] [--cmd-timeout 300000]]
|
|
38
|
+
[--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir] [--regressions dir]
|
|
39
|
+
[--regressions-only] [--check-mutants] [--mutant-runs 50] [--no-record]
|
|
40
|
+
stateful probing: --target wrapper (default) checks the hooks against the proven kernel on real git
|
|
41
|
+
repositories; --target <file.ts|.mts|.js|.mjs> runs a model of any TS/JS project (defineModel from
|
|
42
|
+
'stopbar/probe', export default or export target). A failure is shrunk to repro-<seed>.json in --out.
|
|
43
|
+
--cmd: a program in any language (Python, Go, Rust, ...), one process per job, NDJSON on stdin/stdout:
|
|
44
|
+
{"op":"info"} -> {"name","description","mutants"?} {"op":"generate","seed":N} -> {"seed":N,"actions":[...]}
|
|
45
|
+
{"op":"execute","run":{...},"dir":"...","mutant"?} -> {"ok":true,"steps","cov"} | {"ok":false,"mismatch":{...}}
|
|
46
|
+
--target-file: the file hashed as targetSha256 (default: the first existing file in the command)
|
|
47
|
+
--cmd-timeout: ms to wait for one answer (0 = no limit); a crash or bad answer exits 1 with its stderr
|
|
48
|
+
--check-mutants: every mutant of the target must fail within --mutant-runs seeds (exit 0 only if all do)
|
|
49
|
+
--no-record: do not append probe:result to events.jsonl (else recorded when Stopbar is initialised)
|
|
50
|
+
stopbar probe init [--lang ts|py] [--name sample] [--out probes] [--force] [--repo <dir>]
|
|
51
|
+
writes a starter target (<name>.probe.ts or <name>_probe.py, 2 mutants) and
|
|
52
|
+
prints the command that runs it
|
|
36
53
|
GATE init, upgrade, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
|
|
37
|
-
ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256
|
|
54
|
+
ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256,
|
|
55
|
+
probe evidence (the latest probe:result per target, and whether it was taken at the current snapshot)
|
|
38
56
|
All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
|
|
39
57
|
|
|
40
58
|
function opts(a ) {
|
|
@@ -76,11 +94,25 @@ async function main() {
|
|
|
76
94
|
}
|
|
77
95
|
if (cmd === 'probe') {
|
|
78
96
|
const P = await import('./probe/index.js')
|
|
97
|
+
// a worker share: --worker-file <path> (the runner), or --worker <json> (older runners)
|
|
98
|
+
if (o.has('worker-file')) { await P.worker(JSON.parse(readFileSync(o.get('worker-file') , 'utf8'))); return {code: 0} }
|
|
79
99
|
if (o.has('worker')) { await P.worker(JSON.parse(o.get('worker') )); return {code: 0} }
|
|
80
100
|
const num = (n ) => (o.get(n) === undefined ? undefined : o.int(n, 0))
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
101
|
+
try {
|
|
102
|
+
if (argv[1] === 'init') {
|
|
103
|
+
const io = opts(argv.slice(2))
|
|
104
|
+
const r = (await import('./probe/init.js')).initProbe({lang: io.get('lang'), name: io.get('name'), out: io.get('out'), force: io.has('force'), repo: io.get('repo')})
|
|
105
|
+
return {code: 0, msg: r.message}
|
|
106
|
+
}
|
|
107
|
+
for (const f of ['target', 'cmd', 'target-file']) if (o.has(f) && o.get(f) === undefined) throw new P.ProbeError(`--${f} needs a value`)
|
|
108
|
+
const r = await P.probe({target: o.get('target'), cmd: o.get('cmd'), targetFile: o.get('target-file'), cmdTimeoutMs: num('cmd-timeout'), runs: num('runs'), seed: num('seed'), jobs: num('jobs'), work: o.get('work'), out: o.get('out'),
|
|
109
|
+
regressions: o.get('regressions'), regressionsOnly: o.has('regressions-only'), checkMutants: o.has('check-mutants'), mutantRuns: num('mutant-runs'),
|
|
110
|
+
repo: o.get('repo'), record: !o.has('no-record')})
|
|
111
|
+
return {code: r.ok ? 0 : 1}
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e instanceof P.ProbeError) return {code: 1, msg: `stopbar probe: ${e.message}`}
|
|
114
|
+
throw e
|
|
115
|
+
}
|
|
84
116
|
}
|
|
85
117
|
if (cmd === 'attest') return (await import('./attest.js')).attest({repo: o.get('repo'), format: o.get('format')})
|
|
86
118
|
return {code: 1, msg: `unknown command ${cmd}\n\n${HELP}`}
|