@skathio/somi 1.1.1 → 2.0.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/.claude/settings.json +8 -8
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +11 -2
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +21 -4
- package/VERSION +1 -1
- package/agents/coder.md +8 -3
- package/agents/designer.md +22 -7
- package/agents/discovery-analyst.md +11 -0
- package/agents/planner.md +69 -9
- package/agents/refactorer.md +3 -1
- package/agents/reviewer.md +4 -0
- package/commands/adopt.md +77 -0
- package/commands/atlas.md +83 -0
- package/commands/code-loop.md +70 -44
- package/commands/code-parallel.md +3 -1
- package/commands/code.md +8 -2
- package/commands/debug.md +136 -0
- package/commands/design.md +17 -7
- package/commands/discover.md +23 -18
- package/commands/impact.md +74 -0
- package/commands/incident.md +83 -0
- package/commands/plan-loop.md +44 -19
- package/commands/plan.md +38 -26
- package/commands/pr.md +82 -0
- package/commands/release-readiness.md +70 -0
- package/commands/review-panel.md +5 -0
- package/commands/review.md +19 -0
- package/commands/ship-loop.md +18 -10
- package/commands/ship.md +4 -2
- package/commands/somi.md +85 -0
- package/commands/upgrade.md +81 -0
- package/hooks/hooks.json +8 -8
- package/hooks/lib/common.mjs +328 -0
- package/hooks/post-tool/audit-log.mjs +93 -0
- package/hooks/post-tool/lint-changed-files.mjs +212 -0
- package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
- package/hooks/pre-tool/block-secret-writes.mjs +96 -0
- package/hooks/pre-tool/gate-dep-install.mjs +229 -0
- package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
- package/hooks/session-start/detect-repo-instructions.mjs +264 -0
- package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
- package/package.json +6 -1
- package/rules/50-collaboration.md +4 -1
- package/scripts/somi-check.mjs +243 -0
- package/scripts/somi-findings.mjs +307 -0
- package/scripts/somi-loop.mjs +354 -0
- package/scripts/validate.sh +120 -0
- package/skills/clean-code/SKILL.md +1 -1
- package/templates/ATLAS.md.tmpl +75 -0
- package/templates/BRIEF.md.tmpl +20 -4
- package/templates/DOD.md.tmpl +2 -2
- package/templates/PHASE.md.tmpl +1 -1
- package/templates/RCA.md.tmpl +53 -0
- package/templates/RD-README.md.tmpl +2 -2
- package/templates/SDD.md.tmpl +4 -4
- package/templates/SOMI-README.md.tmpl +20 -3
- package/templates/SRS.md.tmpl +1 -1
- package/templates/TDD.md.tmpl +5 -5
- package/tests/hooks/cases/audit-log.json +21 -0
- package/tests/hooks/cases/block-dangerous-bash.json +166 -0
- package/tests/hooks/cases/block-secret-writes.json +22 -0
- package/tests/hooks/cases/detect-repo-instructions.json +84 -0
- package/tests/hooks/cases/gate-dep-install.json +42 -0
- package/tests/hooks/cases/guard-protected-paths.json +30 -0
- package/tests/hooks/cases/inject-workflow-context.json +126 -0
- package/tests/hooks/cases/lint-changed-files.json +120 -0
- package/tests/hooks/run.sh +362 -0
- package/tests/scripts/goldens/somi-findings.json +336 -0
- package/tests/scripts/goldens/somi-loop.json +168 -0
- package/tests/scripts/run.sh +389 -0
- package/hooks/lib/common.sh +0 -120
- package/hooks/post-tool/audit-log.sh +0 -40
- package/hooks/post-tool/lint-changed-files.sh +0 -80
- package/hooks/pre-tool/block-dangerous-bash.sh +0 -83
- package/hooks/pre-tool/block-secret-writes.sh +0 -83
- package/hooks/pre-tool/gate-dep-install.sh +0 -72
- package/hooks/pre-tool/guard-protected-paths.sh +0 -74
- package/hooks/session-start/detect-repo-instructions.sh +0 -73
- package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// hooks/post-tool/lint-changed-files.mjs — PostToolUse hook (matcher: Write|Edit) —
|
|
3
|
+
// best-effort lint of just-changed files.
|
|
4
|
+
//
|
|
5
|
+
// Node port of hooks/post-tool/lint-changed-files.sh (node-runtime-port, phase 2,
|
|
6
|
+
// iteration 2.5). Imports the shared read/context/projectRoot helpers from
|
|
7
|
+
// ../lib/common.mjs (2.1, reviewer-blessed) rather than reimplementing them.
|
|
8
|
+
//
|
|
9
|
+
// Runs the project's configured linter on the touched file, if one is available,
|
|
10
|
+
// keyed off file extension + presence of a config file. Result is informational —
|
|
11
|
+
// this hook NEVER blocks (PostToolUse: the file is already written by the time it
|
|
12
|
+
// runs). Every failure mode — missing linter, missing config, linter crash, linter
|
|
13
|
+
// non-zero exit, output truncated by maxBuffer — degrades to "no context emitted",
|
|
14
|
+
// never a deny, never a non-zero hook exit. Preserve that contract exactly; a
|
|
15
|
+
// future edit must not let any of these become a thrown, uncaught error.
|
|
16
|
+
//
|
|
17
|
+
// --- PROJECT_ROOT resolution: guarded projectRoot(), not bash's raw pattern ------
|
|
18
|
+
// bash: `PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"` — no `${...}`-unexpanded-
|
|
19
|
+
// literal guard on THIS specific line (unlike most other ported hooks' PROJECT_ROOT
|
|
20
|
+
// lines, context.md §2). Using common.mjs's projectRoot() here anyway (which DOES
|
|
21
|
+
// carry the guard) is a deliberate, safe-direction improvement, not a silent
|
|
22
|
+
// behavior change: if a host ever fails to expand `${CLAUDE_PROJECT_DIR}` before
|
|
23
|
+
// setting it, bash's un-guarded line would set PROJECT_ROOT to that literal
|
|
24
|
+
// garbage string, and the .ts/.go/.rs branches' `cd "$PROJECT_ROOT" &&` would then
|
|
25
|
+
// FAIL (nonexistent directory) — which, under this script's `set -euo pipefail`,
|
|
26
|
+
// aborts the ENTIRE hook script non-gracefully (a crash, not the intended
|
|
27
|
+
// best-effort no-op). The guarded projectRoot() falls back to `process.cwd()` in
|
|
28
|
+
// that same scenario instead, so this port degrades to "no lint delegate ran" for
|
|
29
|
+
// the broken-host case rather than crashing — strictly safer, and consistent with
|
|
30
|
+
// 2.1's centralization intent (every port imports the one guarded helper rather
|
|
31
|
+
// than re-duplicating bash's un-guarded line).
|
|
32
|
+
//
|
|
33
|
+
// --- run_if_present() -> runIfPresent(), combined with the `command -v` gate ----
|
|
34
|
+
// bash checks presence first (`command -v "$cmd"`), then, only if found, execs it
|
|
35
|
+
// with `2>&1 || true` (swallow a non-zero exit AND merge stdout+stderr). Node's
|
|
36
|
+
// spawnSync already reports "executable not found on PATH" as
|
|
37
|
+
// `result.error.code === 'ENOENT'` (Node does the PATH search itself, including
|
|
38
|
+
// PATHEXT on Windows) — a single spawnSync call reproduces BOTH steps (presence
|
|
39
|
+
// check + conditional exec) without a separate hand-rolled PATH-search helper, and
|
|
40
|
+
// without the check-then-exec TOCTOU race the bash original technically has
|
|
41
|
+
// (immaterial for a best-effort hook either way, but a strictly safer property of
|
|
42
|
+
// this shape, not a behavior change). `result.error` covers every reason the
|
|
43
|
+
// subprocess output couldn't be captured (not found, EACCES, exceeded maxBuffer,
|
|
44
|
+
// ...) — all of them collapse to "no lint output," matching bash's blanket `|| true`
|
|
45
|
+
// swallow.
|
|
46
|
+
//
|
|
47
|
+
// stdout/stderr are captured as SEPARATE buffers by spawnSync and concatenated
|
|
48
|
+
// (`stdout + stderr`) rather than truly interleaved the way a shell's `2>&1`
|
|
49
|
+
// fd-level merge would produce — Node has no direct equivalent without opening a
|
|
50
|
+
// real on-disk fd shared by both streams, which would be needless complexity for
|
|
51
|
+
// output that is purely informational and never programmatically parsed
|
|
52
|
+
// downstream. This is an intentional, named divergence: the acceptance criteria
|
|
53
|
+
// for this port pin SHAPE (does the wrapped "Lint output for the file just
|
|
54
|
+
// changed:" envelope appear, non-empty, when a real delegate run produces
|
|
55
|
+
// anything), not exact interleaved text — verified per fixture case that every
|
|
56
|
+
// scenario this port is actually tested against produces output on only ONE of
|
|
57
|
+
// the two streams, so concatenation order is moot for what's tested.
|
|
58
|
+
//
|
|
59
|
+
// --- maxBuffer -------------------------------------------------------------------
|
|
60
|
+
// LINT_MAX_BUFFER below is set explicitly on every output-capturing spawnSync call.
|
|
61
|
+
// This is the first hook port that shells out to capture an ARBITRARY THIRD-PARTY
|
|
62
|
+
// TOOL's own output (prior ports only capture `git`'s output for decision logic,
|
|
63
|
+
// not a linter's free-form diagnostic text) — Node's child_process default
|
|
64
|
+
// maxBuffer is 1 MB, and a verbose linter run (e.g. `cargo clippy` across a whole
|
|
65
|
+
// crate, or `eslint` with a large ruleset) could plausibly exceed that. 10 MB is a
|
|
66
|
+
// generous ceiling: enough to never truncate a realistic single-file lint run,
|
|
67
|
+
// small enough to bound worst-case memory use from a hook that's supposed to be a
|
|
68
|
+
// cheap, best-effort side note. If a real run exceeds it, spawnSync sets
|
|
69
|
+
// `result.error`, which `runIfPresent`'s swallow-everything contract already
|
|
70
|
+
// treats as "nothing to report" — an over-the-cap linter run degrades to silence,
|
|
71
|
+
// not a crash. This establishes the explicit-maxBuffer convention 1.1's review
|
|
72
|
+
// asked Phase 2's first output-capturing hook to set
|
|
73
|
+
// (`.somi/reviews/node-runtime-port/2026-07-06-1.1-pass1-approve.md`); later hook
|
|
74
|
+
// ports that capture subprocess output should follow this precedent.
|
|
75
|
+
//
|
|
76
|
+
// --- command-substitution trailing-newline stripping -----------------------------
|
|
77
|
+
// bash builds LINT_OUTPUT via `"$(...)"` command substitution, which
|
|
78
|
+
// UNCONDITIONALLY strips ALL trailing newlines from the captured text (a bash
|
|
79
|
+
// `$(...)` primitive, not specific to this hook). Node's spawnSync does not do
|
|
80
|
+
// this — reproduced explicitly via stripTrailingNewlines() below, applied to every
|
|
81
|
+
// branch's captured output, not just the `cargo clippy | head -50` branch that
|
|
82
|
+
// visibly pipes through another command.
|
|
83
|
+
//
|
|
84
|
+
// --- extension dispatch + config gating -------------------------------------------
|
|
85
|
+
// Ported 1:1 from the bash `case "$PATH_INPUT" in ... esac` arms, same order,
|
|
86
|
+
// same per-linter config-file gate, same cd-vs-no-cd behavior per branch (verified
|
|
87
|
+
// line-by-line against the bash original: ts/go/rust branches `cd "$PROJECT_ROOT"`
|
|
88
|
+
// before running their delegate; py/sh branches do not).
|
|
89
|
+
//
|
|
90
|
+
// --- cargo clippy path unreachable in the authoring/CI sandbox -------------------
|
|
91
|
+
// No rust toolchain exists in either environment (confirmed absent both places) —
|
|
92
|
+
// headLines()'s "head -50" translation is a faithful, readable-output-preserving
|
|
93
|
+
// port (not byte-exact POSIX `head` semantics, which don't matter here since bash's
|
|
94
|
+
// own `$(...)` strips trailing newlines from the piped result anyway), but is
|
|
95
|
+
// UNVERIFIED against a real `cargo clippy` invocation. Flagged, not silently
|
|
96
|
+
// assumed correct.
|
|
97
|
+
import fs from 'node:fs';
|
|
98
|
+
import path from 'node:path';
|
|
99
|
+
import { spawnSync } from 'node:child_process';
|
|
100
|
+
import { readPayload, field, contextOutput, projectRoot, runHook } from '../lib/common.mjs';
|
|
101
|
+
|
|
102
|
+
const LINT_MAX_BUFFER = 10 * 1024 * 1024; // 10 MB — see header comment.
|
|
103
|
+
const MAX_LINT_FILE_BYTES = 500000; // bash: SIZE_BYTES > 500000 skip (likely generated).
|
|
104
|
+
|
|
105
|
+
function isFile(p) {
|
|
106
|
+
try {
|
|
107
|
+
return fs.statSync(p).isFile();
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function stripTrailingNewlines(text) {
|
|
114
|
+
return text.replace(/\n+$/, '');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// See the header comment's "run_if_present() -> runIfPresent()" section.
|
|
118
|
+
function runIfPresent(cmd, args, cwd) {
|
|
119
|
+
const result = spawnSync(cmd, args, { cwd, encoding: 'utf8', maxBuffer: LINT_MAX_BUFFER });
|
|
120
|
+
if (result.error) return '';
|
|
121
|
+
return stripTrailingNewlines((result.stdout || '') + (result.stderr || ''));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// head -N equivalent for the clippy branch. Bash's own `$(...)` strips trailing
|
|
125
|
+
// newlines from the piped-through result regardless, so byte-exact `head`
|
|
126
|
+
// semantics around a missing/present final newline don't matter here — see the
|
|
127
|
+
// header comment.
|
|
128
|
+
function headLines(text, n) {
|
|
129
|
+
const lines = text.split('\n');
|
|
130
|
+
if (lines.length <= n) return text;
|
|
131
|
+
return lines.slice(0, n).join('\n');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// bash: nullglob loop over "$PROJECT_ROOT"/.eslintrc* filtered to `-f` (regular
|
|
135
|
+
// files only), OR eslint.config.js, OR eslint.config.mjs.
|
|
136
|
+
function hasEslintConfig(root) {
|
|
137
|
+
let entries;
|
|
138
|
+
try {
|
|
139
|
+
entries = fs.readdirSync(root);
|
|
140
|
+
} catch {
|
|
141
|
+
entries = [];
|
|
142
|
+
}
|
|
143
|
+
const hasRcVariant = entries.some(
|
|
144
|
+
(name) => name.startsWith('.eslintrc') && isFile(path.join(root, name)),
|
|
145
|
+
);
|
|
146
|
+
if (hasRcVariant) return true;
|
|
147
|
+
return isFile(path.join(root, 'eslint.config.js')) || isFile(path.join(root, 'eslint.config.mjs'));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// bash: "./$(dirname "${PATH_INPUT#$PROJECT_ROOT/}")/..." — strip the
|
|
151
|
+
// PROJECT_ROOT/ prefix (a no-op if PATH_INPUT doesn't actually start with it,
|
|
152
|
+
// matching bash's `#`-prefix-removal no-op-on-no-match behavior), take the
|
|
153
|
+
// directory component, wrap as a `go vet` package pattern. Uses platform-default
|
|
154
|
+
// path.dirname (posix on Linux/macOS) — same Windows-backslash caveat 2.2/2.3
|
|
155
|
+
// already flagged and deferred (F-32-class divergence, not fixed here either).
|
|
156
|
+
function goVetPackageArg(pathInput, root) {
|
|
157
|
+
const prefix = root.endsWith(path.sep) ? root : root + path.sep;
|
|
158
|
+
const rel = pathInput.startsWith(prefix) ? pathInput.slice(prefix.length) : pathInput;
|
|
159
|
+
return `./${path.dirname(rel)}/...`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function main() {
|
|
163
|
+
const payload = readPayload();
|
|
164
|
+
const pathInput = field(payload, '.tool_input.file_path');
|
|
165
|
+
if (!pathInput) return;
|
|
166
|
+
if (!isFile(pathInput)) return;
|
|
167
|
+
|
|
168
|
+
// Skip oversized files (likely generated). bash: `wc -c < "$PATH_INPUT" 2>/dev/null
|
|
169
|
+
// || echo 0` — a stat race after the isFile() check above falls back to 0 (treated
|
|
170
|
+
// as "not oversized," matching bash's fallback exactly).
|
|
171
|
+
let sizeBytes = 0;
|
|
172
|
+
try {
|
|
173
|
+
sizeBytes = fs.statSync(pathInput).size;
|
|
174
|
+
} catch {
|
|
175
|
+
sizeBytes = 0;
|
|
176
|
+
}
|
|
177
|
+
if (sizeBytes > MAX_LINT_FILE_BYTES) return;
|
|
178
|
+
|
|
179
|
+
const root = projectRoot();
|
|
180
|
+
let lintOutput = '';
|
|
181
|
+
|
|
182
|
+
if (pathInput.endsWith('.py')) {
|
|
183
|
+
if (isFile(path.join(root, 'pyproject.toml')) || isFile(path.join(root, '.ruff.toml'))) {
|
|
184
|
+
lintOutput = runIfPresent('ruff', ['check', '--quiet', pathInput], undefined);
|
|
185
|
+
}
|
|
186
|
+
} else if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].some((ext) => pathInput.endsWith(ext))) {
|
|
187
|
+
if (hasEslintConfig(root)) {
|
|
188
|
+
lintOutput = runIfPresent('npx', ['--no-install', 'eslint', '--no-color', pathInput], root);
|
|
189
|
+
}
|
|
190
|
+
} else if (pathInput.endsWith('.go')) {
|
|
191
|
+
if (isFile(path.join(root, 'go.mod'))) {
|
|
192
|
+
lintOutput = runIfPresent('go', ['vet', goVetPackageArg(pathInput, root)], root);
|
|
193
|
+
}
|
|
194
|
+
} else if (pathInput.endsWith('.rs')) {
|
|
195
|
+
if (isFile(path.join(root, 'Cargo.toml'))) {
|
|
196
|
+
lintOutput = headLines(
|
|
197
|
+
runIfPresent('cargo', ['clippy', '--quiet', '--message-format=short'], root),
|
|
198
|
+
50,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
} else if (pathInput.endsWith('.sh')) {
|
|
202
|
+
lintOutput = runIfPresent('shellcheck', [pathInput], undefined);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (lintOutput) {
|
|
206
|
+
// PostToolUse additionalContext must live under hookSpecificOutput per the
|
|
207
|
+
// Claude Code hook schema (same note the bash original carried).
|
|
208
|
+
contextOutput('PostToolUse', `Lint output for the file just changed:\n${lintOutput}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
runHook(main);
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// hooks/pre-tool/block-dangerous-bash.mjs — PreToolUse hook (matcher: Bash) — block clearly
|
|
3
|
+
// dangerous shell commands.
|
|
4
|
+
//
|
|
5
|
+
// Node port of hooks/pre-tool/block-dangerous-bash.sh (node-runtime-port, phase 2,
|
|
6
|
+
// iteration 2.9 — the work item's named highest-risk file, brief.md §3/§8). Imports the
|
|
7
|
+
// shared read/deny/matching helpers from ../lib/common.mjs (2.1, reviewer-blessed)
|
|
8
|
+
// rather than reimplementing them.
|
|
9
|
+
//
|
|
10
|
+
// This is a deterministic guardrail, not a policy debate. It catches the
|
|
11
|
+
// common-and-catastrophic class of mistakes; nuanced cases are the human's call. Block
|
|
12
|
+
// list focuses on irreversible / system-destructive / supply-chain shapes, plus
|
|
13
|
+
// shell-level writes to secret-bearing paths — the Bash-side complement of
|
|
14
|
+
// block-secret-writes.mjs (2.2), whose Write|Edit matcher a redirect / tee / sed -i /
|
|
15
|
+
// cp / mv would otherwise bypass entirely. Intentionally conservative — false positives
|
|
16
|
+
// cost less than false negatives here.
|
|
17
|
+
//
|
|
18
|
+
// COUNT CORRECTION (verified by direct read — `awk` over the array literal, not
|
|
19
|
+
// inherited from the phase file's/brief's stated "19"): the bash original's
|
|
20
|
+
// DANGEROUS_PATTERNS array holds 23 case-sensitive patterns, not 19 — same class of
|
|
21
|
+
// miscount 2.4 found and corrected for DEP_ADD_PATTERNS (18→19), just larger here. All
|
|
22
|
+
// 23 are ported below, plus the 5 case-insensitive SQL patterns (that count IS
|
|
23
|
+
// accurate) and the 4 secret-write patterns. "Port ALL of the patterns" wins over an
|
|
24
|
+
// inherited miscount, per 2.4's precedent; phases/02-hooks-port.md's iteration-2.9 scope
|
|
25
|
+
// line is corrected alongside this port (see the diary entry for this pass).
|
|
26
|
+
//
|
|
27
|
+
// ERE→RegExp translation rules applied uniformly (verified pattern-by-pattern, not by a
|
|
28
|
+
// blanket find-and-replace across the whole set — every one of the 23+5+4 patterns
|
|
29
|
+
// below was hand-translated and carries its own bash line reference):
|
|
30
|
+
// [[:space:]] → \s POSIX space class → JS \s, POSITIVE (non-negated) form
|
|
31
|
+
// ONLY — see the negated-form entry below, which is NOT the
|
|
32
|
+
// same argument. POSIX [[:space:]] is exactly the 6 ASCII
|
|
33
|
+
// whitespace bytes (space/tab/LF/CR/FF/VT); JS \s is a
|
|
34
|
+
// strict SUPERSET (adds Unicode whitespace: NBSP,
|
|
35
|
+
// U+2028/U+2029, U+FEFF, other Zs). A wider POSITIVE \s can
|
|
36
|
+
// only make this hook MATCH (and therefore block) a
|
|
37
|
+
// broader set of verb/argument separators than bash would —
|
|
38
|
+
// over-gating, never under-gating. Same argument 2.4 made
|
|
39
|
+
// for gate-dep-install, and it is sound for this direction.
|
|
40
|
+
// [^[:space:]] → [^ \t\n\r\f\v] NOT [^\s] (F-40, Major, fixed at 2.9 pass 2 after
|
|
41
|
+
// the security review caught it — a prior version of this
|
|
42
|
+
// file used [^\s] here and was WRONG). Negation INVERTS the
|
|
43
|
+
// superset relationship above: \s ⊋ [[:space:]] means
|
|
44
|
+
// [^\s] ⊊ [^[:space:]] — the negated JS class matches FEWER
|
|
45
|
+
// characters than bash's negated POSIX class, so a pattern
|
|
46
|
+
// built from [^\s] stops (and fails to reach a required
|
|
47
|
+
// literal further on) at a byte bash's [^[:space:]] would
|
|
48
|
+
// happily consume — an UNDER-gate, the unsafe direction for
|
|
49
|
+
// a security guard. Concrete, re-derived case: NBSP
|
|
50
|
+
// (U+00A0) IS in JS's \s (so it's EXCLUDED from [^\s]) but
|
|
51
|
+
// is NOT one of POSIX [[:space:]]'s 6 ASCII bytes (so it's
|
|
52
|
+
// INCLUDED in bash's [^[:space:]]) — verified live both
|
|
53
|
+
// directions: bash's `service-account[^[:space:]]*\.json`
|
|
54
|
+
// matches THROUGH a literal NBSP byte onto `.json`
|
|
55
|
+
// (BASH_REMATCH confirms the full path); the buggy
|
|
56
|
+
// `service-account[^\s]*\.json` stopped before the NBSP and
|
|
57
|
+
// never reached `.json`, so the whole pattern failed to
|
|
58
|
+
// match — a real deny→allow gap on a crafted filename.
|
|
59
|
+
// Every negated occurrence below now uses the explicit
|
|
60
|
+
// POSIX-C byte class [^ \t\n\r\f\v] (the literal 6 ASCII
|
|
61
|
+
// whitespace bytes, negated, with zero Unicode awareness to
|
|
62
|
+
// accidentally invert) instead of \s's Unicode-aware
|
|
63
|
+
// negation.
|
|
64
|
+
// \+ → \+ ERE escaped '+' (LITERAL plus character, used in the
|
|
65
|
+
// +refspec force-push patterns, e.g. `git push origin
|
|
66
|
+
// +main`) → JS escaped '+' (also a literal). Both engines
|
|
67
|
+
// treat a bare, unescaped '+' as the one-or-more
|
|
68
|
+
// quantifier and require the backslash to mean "the
|
|
69
|
+
// character +" — identical escaping convention, so this is
|
|
70
|
+
// a direct 1:1 port, not a translation.
|
|
71
|
+
// + → + ERE one-or-more quantifier → JS one-or-more quantifier,
|
|
72
|
+
// unescaped in both. (The two '+' meanings above — literal
|
|
73
|
+
// vs quantifier — are what this file's scope note flags as
|
|
74
|
+
// needing care; verified per-occurrence below, not
|
|
75
|
+
// conflated.)
|
|
76
|
+
// \* \$ \. → \* \$ \. ERE escaped literal metacharacters → identical JS
|
|
77
|
+
// escapes; both require the backslash for "the literal
|
|
78
|
+
// character", not "zero-or-more of the preceding" / "end
|
|
79
|
+
// of string" / "any character".
|
|
80
|
+
// (a|b) {1,2} → identical Byte-identical alternation and interval-quantifier
|
|
81
|
+
// syntax in both engines.
|
|
82
|
+
//
|
|
83
|
+
// DOT-SEMANTICS CAVEAT — LIVE HERE (unlike block-secret-writes.mjs/gate-dep-install.mjs,
|
|
84
|
+
// where the same caveat was checked and found inert because those files only ever
|
|
85
|
+
// match basenames or already-tokenized argument text, never raw command-string content).
|
|
86
|
+
//
|
|
87
|
+
// RE-DERIVED AT 2.9 PASS 2 (F-39, Blocker) — the paragraph that used to sit here claimed
|
|
88
|
+
// "POSIX ERE '.' matches every byte except '\n'" and translated '.*' to '[^\n]*'. That
|
|
89
|
+
// claim is WRONG for what this file actually needs: it is grep/awk-with-REG_NEWLINE
|
|
90
|
+
// semantics, not bash `[[ =~ ]]` semantics, and the security review caught the gap it
|
|
91
|
+
// produced. Re-derived from first principles, not restated:
|
|
92
|
+
//
|
|
93
|
+
// bash's `[[ "$c" =~ $pattern ]]` calls glibc `regexec()` WITHOUT the `REG_NEWLINE`
|
|
94
|
+
// flag. REG_NEWLINE is what makes '.' refuse a newline (and makes '^'/'$' match at
|
|
95
|
+
// internal line boundaries) in POSIX regex — WITHOUT it, '.' matches ANY single byte at
|
|
96
|
+
// all, '\n' included. Verified live, not assumed: `[[ $'a\nb' =~ ^a.b$ ]]` MATCHES in a
|
|
97
|
+
// real bash 5.2 shell. So every bare '.'/'.*' in bash's DANGEROUS_PATTERNS spans
|
|
98
|
+
// embedded newlines freely — the opposite of what the old comment here claimed.
|
|
99
|
+
//
|
|
100
|
+
// The correct translation is "match every character, no exclusions at all" — JS `[^]`
|
|
101
|
+
// (a negated character class with an EMPTY exclusion set is a well-known idiom meaning
|
|
102
|
+
// "matches anything", equivalent to `[\s\S]`), NOT `[^\n]`. Every bare '.'/'.*' in the
|
|
103
|
+
// bash source (patterns #7, #13, #14, #21, #22, #23 below) is translated to `[^]`/`[^]*`.
|
|
104
|
+
// The wrong `[^\n]*` translation made node's matched set a strict SUBSET of bash's — an
|
|
105
|
+
// UNDER-gate, confirmed exploitable: `git commit -m "fix\n\nbody" --no-verify` is DENIED
|
|
106
|
+
// by bash's `git commit .*--no-verify` (the `.*` crosses the embedded newline to reach
|
|
107
|
+
// `--no-verify`) but was silently ALLOWED by `[^\n]*` (which cannot cross the newline) —
|
|
108
|
+
// `--no-verify` disables somi's own commit/push safety hooks, and multi-line commit
|
|
109
|
+
// messages are completely routine, so this was a live gap, not a theoretical one. A CR
|
|
110
|
+
// (not LF) embedded in the same position happens to still be excluded by `[^\n]` too
|
|
111
|
+
// (CR isn't `\n`), which is why the pass-1 CR-embedded regression probes passed and gave
|
|
112
|
+
// false confidence — LF was the actual break, and pass 1 had no LF fixture.
|
|
113
|
+
//
|
|
114
|
+
// Every other '.' in this file is an ESCAPED '\.' (a literal dot character, e.g.
|
|
115
|
+
// `mkfs\.`), unaffected by this caveat in either engine — checked by hand per
|
|
116
|
+
// occurrence, not assumed.
|
|
117
|
+
//
|
|
118
|
+
// Patterns are built via `new RegExp(String.raw\`...\`)` rather than `/.../ ` literals:
|
|
119
|
+
// most of this file's patterns contain a bare `/` (filesystem paths, `/dev/...`,
|
|
120
|
+
// `origin/`), and String.raw's un-escaped backslash handling reads far more directly
|
|
121
|
+
// against the bash ERE source strings than a literal would once every `/` is escaped
|
|
122
|
+
// to `\/`. No pattern here uses a backtick or `${`, so String.raw is safe throughout.
|
|
123
|
+
//
|
|
124
|
+
// SECRET_WRITE_PATTERNS mirrors block-secret-writes.mjs's SECRET_PATTERNS set
|
|
125
|
+
// (block-secret-writes.mjs's SECRET_PATTERNS / block-dangerous-bash.sh:86) — "kept in
|
|
126
|
+
// sync by comment convention, not code sharing" today (context.md §2). Preserved as a
|
|
127
|
+
// deliberate duplication in this port; do not unify the two lists — that would be a
|
|
128
|
+
// scope-creeping refactor beyond this behavior-preserving port (same convention 2.2
|
|
129
|
+
// already flagged as a future-refactor target).
|
|
130
|
+
//
|
|
131
|
+
// check_secret_writes' capture-before-internal-test discipline is preserved exactly
|
|
132
|
+
// (see checkSecretWrites below): the matched substring is read into a local `matched`
|
|
133
|
+
// BEFORE the exception regex is tested against it, mirroring bash's own comment at
|
|
134
|
+
// block-dangerous-bash.sh:121-122 ("Capture the match first: the exception's own =~
|
|
135
|
+
// resets BASH_REMATCH") — the analogous JS hazard (a shared/global match result) does
|
|
136
|
+
// not exist here since every match lives in its own local variable, but the ordering
|
|
137
|
+
// discipline is kept anyway, verbatim, so a future edit to this file can't reintroduce
|
|
138
|
+
// bash's exact failure shape by reordering the two statements.
|
|
139
|
+
//
|
|
140
|
+
// The bare-force-push check (checkBareForcePush) is NOT a regex port — it is bash's
|
|
141
|
+
// own small procedural token-walk (block-dangerous-bash.sh:139-164), ported as an
|
|
142
|
+
// algorithm: split the command tail on whitespace, count non-flag tokens, detect a
|
|
143
|
+
// bare HEAD as the 2nd non-flag token. See its own comment below for the full mapping.
|
|
144
|
+
//
|
|
145
|
+
// Deny-message interpolation: bash's `${BASH_REMATCH[0]}` → this port's `m[0]`/`matched`
|
|
146
|
+
// (the RegExpExecArray's full-match element, returned by common.mjs's matchesAny /
|
|
147
|
+
// matchesAnyNocase, or from a direct `.exec()` call in checkSecretWrites).
|
|
148
|
+
|
|
149
|
+
import {
|
|
150
|
+
readPayload,
|
|
151
|
+
field,
|
|
152
|
+
denyPretool,
|
|
153
|
+
matchesAny,
|
|
154
|
+
matchesAnyNocase,
|
|
155
|
+
runHook,
|
|
156
|
+
} from '../lib/common.mjs';
|
|
157
|
+
|
|
158
|
+
// Case-sensitive patterns (block-dangerous-bash.sh:36-73, 23 entries — see the
|
|
159
|
+
// COUNT CORRECTION note above).
|
|
160
|
+
const DANGEROUS_PATTERNS = [
|
|
161
|
+
// filesystem nukes (bash:38-42)
|
|
162
|
+
new RegExp(String.raw`rm\s+-rf?\s+/(\s|$)`), // #1
|
|
163
|
+
new RegExp(String.raw`rm\s+-rf?\s+~(\s|/|$)`), // #2
|
|
164
|
+
new RegExp(String.raw`rm\s+-rf?\s+\*`), // #3
|
|
165
|
+
new RegExp(String.raw`rm\s+-rf?\s+\$HOME`), // #4
|
|
166
|
+
new RegExp(String.raw`:\(\)\{\s*:\|:&\s*\};:`), // #5 fork bomb
|
|
167
|
+
|
|
168
|
+
// device / partition writes (bash:45-47)
|
|
169
|
+
new RegExp(String.raw`>\s*/dev/(sd[a-z]|nvme|hd[a-z]|disk)`), // #6
|
|
170
|
+
new RegExp(String.raw`dd\s+if=[^]*\s+of=/dev/(sd[a-z]|nvme|hd[a-z]|disk)`), // #7 dot-semantics: .*→[^]* (F-39)
|
|
171
|
+
new RegExp(String.raw`mkfs(\.|\s)`), // #8
|
|
172
|
+
|
|
173
|
+
// supply-chain / remote-exec one-liners (bash:50-53)
|
|
174
|
+
new RegExp(String.raw`curl\s+[^|]*\|\s*(sudo\s+)?(ba)?sh`), // #9
|
|
175
|
+
new RegExp(String.raw`wget\s+[^|]*\|\s*(sudo\s+)?(ba)?sh`), // #10
|
|
176
|
+
new RegExp(String.raw`curl\s+[^|]*\|\s*python[0-9]*`), // #11
|
|
177
|
+
new RegExp(String.raw`wget\s+[^|]*\|\s*python[0-9]*`), // #12
|
|
178
|
+
|
|
179
|
+
// destructive git ops on protected branches (bash:57-64). Covers --force, -f,
|
|
180
|
+
// --force-with-lease (with or without =value), and refspec form (origin HEAD:main).
|
|
181
|
+
new RegExp(String.raw`git\s+push\s+(-{1,2}force|-f)([\s=]|$)[^]*[\s:](main|master|trunk|release)(\s|$)`), // #13 dot-semantics (F-39)
|
|
182
|
+
new RegExp(String.raw`git\s+push\s+--force-with-lease([\s=][^ \t\n\r\f\v]*)?\s[^]*[\s:](main|master|trunk|release)(\s|$)`), // #14 dot-semantics + negated-class (F-39, F-40)
|
|
183
|
+
// force-push via +refspec — no --force flag involved (`git push origin +main`, `+HEAD:main`)
|
|
184
|
+
new RegExp(String.raw`git\s+push\s+[^;&|]*\s\+(main|master|trunk|release)([\s:]|$)`), // #15
|
|
185
|
+
new RegExp(String.raw`git\s+push\s+[^;&|]*\s\+[^ \t\n\r\f\v]*:(main|master|trunk|release)(\s|$)`), // #16 negated-class (F-40)
|
|
186
|
+
new RegExp(String.raw`git\s+branch\s+-D\s+(main|master|trunk)`), // #17
|
|
187
|
+
new RegExp(String.raw`git\s+reset\s+--hard\s+(origin/)?(main|master|trunk)`), // #18
|
|
188
|
+
new RegExp(String.raw`git\s+clean\s+-[fdx]+\s`), // #19
|
|
189
|
+
|
|
190
|
+
// process / permission ops (bash:67-68)
|
|
191
|
+
new RegExp(String.raw`chmod\s+-R\s+777\s+/`), // #20
|
|
192
|
+
new RegExp(String.raw`chown\s+-R\s+[^]*\s+/`), // #21 dot-semantics: .*→[^]* (F-39)
|
|
193
|
+
|
|
194
|
+
// skipping safety checks (only block when used in commit/push context) (bash:71-72)
|
|
195
|
+
new RegExp(String.raw`git\s+commit\s+[^]*--no-verify`), // #22 dot-semantics (F-39)
|
|
196
|
+
new RegExp(String.raw`git\s+push\s+[^]*--no-verify`), // #23 dot-semantics (F-39)
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
// Case-insensitive patterns (bash:76-82, 5 entries — SQL keywords arrive lowercase
|
|
200
|
+
// from ORM logs, mixed case from REPLs). No /i here: matchesAnyNocase (common.mjs)
|
|
201
|
+
// owns the case-insensitivity flag, per its documented contract — mirrors bash's own
|
|
202
|
+
// mechanism, where `shopt -s nocasematch` is an ambient property of the match
|
|
203
|
+
// operation, not a per-pattern annotation.
|
|
204
|
+
// DISCOVERED DIVERGENCE, found and fixed, not shipped as a known gap (empirical, not
|
|
205
|
+
// theoretical — reproduced with the real bash binary before concluding anything):
|
|
206
|
+
// POSIX ERE ([[ =~ ]]) uses LEFTMOST-LONGEST matching for alternation; JS regex uses
|
|
207
|
+
// leftmost-first-successful-alternative (ordered backtracking), which are the SAME
|
|
208
|
+
// semantics only when nothing after the group forces a shorter alternative to fail and
|
|
209
|
+
// backtrack into a longer one. bash's own source lists this group as
|
|
210
|
+
// `(public|prod|production)`, and NOTHING follows the group in the pattern — so for
|
|
211
|
+
// input "...production", bash's leftmost-longest picks the full "production" (11
|
|
212
|
+
// chars: verified live — `DROP SCHEMA production` under `shopt -s nocasematch` yields
|
|
213
|
+
// BASH_REMATCH[0] = "DROP SCHEMA production"), while JS's first-alternative-wins
|
|
214
|
+
// backtracking would try "public" (fails), then "prod" (succeeds, 4 chars) and STOP
|
|
215
|
+
// there without ever trying "production" — verified live with the untranslated order:
|
|
216
|
+
// `/DROP\s+SCHEMA\s+(public|prod|production)/i.exec("DROP SCHEMA production")[0]` →
|
|
217
|
+
// `"DROP SCHEMA prod"`, a genuinely shorter, wrong deny-message substring, same
|
|
218
|
+
// allow/deny decision either way but a corrupted `permissionDecisionReason`. Fixed by
|
|
219
|
+
// reordering the alternation LONGEST-FIRST (`production` before `prod`; `public` has
|
|
220
|
+
// no prefix relationship with either, so its position doesn't matter) — this changes
|
|
221
|
+
// nothing about WHICH inputs match, only WHICH substring an ambiguous input's match
|
|
222
|
+
// reports, restoring exact parity with bash's leftmost-longest result. Audited every
|
|
223
|
+
// other alternation group in this file for the same prefix-collision shape (see the
|
|
224
|
+
// diary for the full audit): `(main|master|trunk|release)`,
|
|
225
|
+
// `(sd[a-z]|nvme|hd[a-z]|disk)`, `(rsa|ed25519|ecdsa|dsa)`,
|
|
226
|
+
// `(local|production|prod|staging|secret)` (already longest-first in bash's own
|
|
227
|
+
// source), `(-{1,2}force|-f)` (protected by a mandatory boundary character after the
|
|
228
|
+
// group, which forces backtracking into the correct longer alternative regardless of
|
|
229
|
+
// try-order) — none of these has an unprotected prefix collision; this SQL pattern is
|
|
230
|
+
// the only one that needed a fix.
|
|
231
|
+
const DANGEROUS_PATTERNS_NOCASE = [
|
|
232
|
+
new RegExp(String.raw`DROP\s+DATABASE`),
|
|
233
|
+
new RegExp(String.raw`DROP\s+SCHEMA\s+(production|public|prod)`),
|
|
234
|
+
new RegExp(String.raw`DROP\s+TABLE\s+[a-zA-Z_]+`),
|
|
235
|
+
new RegExp(String.raw`TRUNCATE\s+(TABLE\s+)?[a-zA-Z_]+`),
|
|
236
|
+
new RegExp(String.raw`DELETE\s+FROM\s+[a-zA-Z_]+\s*;`),
|
|
237
|
+
];
|
|
238
|
+
|
|
239
|
+
// Secret-bearing basename alternation (bash:86). A regex-source FRAGMENT, not a
|
|
240
|
+
// standalone pattern — interpolated into each of the 4 SECRET_WRITE_PATTERNS below,
|
|
241
|
+
// exactly as bash interpolates `${SECRET_BASENAME}` into 4 array entries.
|
|
242
|
+
const SECRET_BASENAME = String.raw`(\.env(\.(local|production|prod|staging|secret))?|id_(rsa|ed25519|ecdsa|dsa)|[^ \t\n\r\f\v]*\.(pem|key|p12|pfx|jks)|[^ \t\n\r\f\v]*(-key|-credentials)\.json|service-account[^ \t\n\r\f\v]*\.json|\.netrc|\.pgpass|[^ \t\n\r\f\v]*secrets?\.(ya?ml|json))`; // negated-class fixed (F-40)
|
|
243
|
+
|
|
244
|
+
// Shell-level writes to secret paths (bash:90-95): redirection, tee, in-place sed,
|
|
245
|
+
// cp/mv onto the target. Matched against the quote-stripped command, same as bash.
|
|
246
|
+
const SECRET_WRITE_PATTERNS = [
|
|
247
|
+
new RegExp(String.raw`(>|>>)\s*([^ \t\n\r\f\v]*/)?${SECRET_BASENAME}(\s|$)`),
|
|
248
|
+
new RegExp(String.raw`(^|[\s|;&])tee\s+(-[a-zA-Z]+\s+)*([^ \t\n\r\f\v]*/)?${SECRET_BASENAME}(\s|$)`),
|
|
249
|
+
new RegExp(String.raw`(^|[\s|;&])sed\s+[^|;&]*-i[^|;&]*\s([^ \t\n\r\f\v]*/)?${SECRET_BASENAME}(\s|$)`),
|
|
250
|
+
new RegExp(String.raw`(^|[\s|;&])(cp|mv)\s+[^|;&]*\s([^ \t\n\r\f\v]*/)?${SECRET_BASENAME}(\s|$)`),
|
|
251
|
+
]; // negated-class prefix groups fixed (F-40)
|
|
252
|
+
|
|
253
|
+
// Explicit example/template files are fine — same exception as block-secret-writes.mjs.
|
|
254
|
+
const EXAMPLE_ENV_RE = /\.env\.(example|sample|template|dist)/;
|
|
255
|
+
|
|
256
|
+
function checkDangerous(payload, c) {
|
|
257
|
+
const m = matchesAny(c, DANGEROUS_PATTERNS);
|
|
258
|
+
if (m) {
|
|
259
|
+
denyPretool(
|
|
260
|
+
payload,
|
|
261
|
+
`somi refused this command: it matches a dangerous-shell pattern (\`${m[0]}\`).
|
|
262
|
+
If this is genuinely intended, stop and ask the human to run it themselves — never work around this hook silently.`,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const mNocase = matchesAnyNocase(c, DANGEROUS_PATTERNS_NOCASE);
|
|
267
|
+
if (mNocase) {
|
|
268
|
+
denyPretool(
|
|
269
|
+
payload,
|
|
270
|
+
`somi refused this command: it matches a destructive-SQL pattern (\`${mNocase[0]}\`).
|
|
271
|
+
If this is genuinely intended, stop and ask the human to run it themselves — never work around this hook silently.`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Iterates SECRET_WRITE_PATTERNS directly (not via common.mjs's matchesAny) because
|
|
277
|
+
// bash's own loop does something matchesAny's "return the first match" contract can't
|
|
278
|
+
// express: on an EXCEPTION match (an explicit .env.example-style path), it `continue`s
|
|
279
|
+
// to the NEXT pattern rather than stopping — so a later pattern in the array can still
|
|
280
|
+
// deny on the same command (e.g. `sed -i s/x/y/ .env.example && cp .env.backup .env`:
|
|
281
|
+
// the sed pattern matches but hits the exception and is skipped; the cp/mv pattern
|
|
282
|
+
// then matches the real secret write and denies). Reproduced as a manual loop to keep
|
|
283
|
+
// that skip-and-continue behavior exact.
|
|
284
|
+
function checkSecretWrites(payload, c) {
|
|
285
|
+
for (const pattern of SECRET_WRITE_PATTERNS) {
|
|
286
|
+
const m = pattern.exec(c);
|
|
287
|
+
if (!m) continue;
|
|
288
|
+
const matched = m[0]; // captured before the exception's own test — see header note
|
|
289
|
+
if (EXAMPLE_ENV_RE.test(matched)) continue;
|
|
290
|
+
denyPretool(
|
|
291
|
+
payload,
|
|
292
|
+
`somi refused this command: it writes to a secret-bearing path via the shell (\`${matched}\`).
|
|
293
|
+
Bootstrap secret files by hand, or commit only \`.env.example\`-style templates. This is the
|
|
294
|
+
Bash-side twin of the Write/Edit secret guard — do not work around either silently.`,
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Force-push without a verifiable target (block-dangerous-bash.sh:133-164). The
|
|
300
|
+
// protected-branch patterns above only fire when the branch is named in the command —
|
|
301
|
+
// but `git push -f`, `git push -f origin`, and `git push -f origin HEAD` push the
|
|
302
|
+
// *current* branch, which this hook cannot resolve (it may well be main). Deny force
|
|
303
|
+
// pushes that don't name an explicit target branch; naming it is what makes the
|
|
304
|
+
// protected-branch check meaningful.
|
|
305
|
+
//
|
|
306
|
+
// Gate regex (bash:141) — unchanged translation rules from DANGEROUS_PATTERNS above,
|
|
307
|
+
// no dot-semantics concern (no '.'/'.*' in this one):
|
|
308
|
+
const BARE_FORCE_PUSH_GATE_RE = new RegExp(
|
|
309
|
+
String.raw`git\s+push(\s+[^;&|]*)?\s(-f|--force(-with-lease(=[^ \t\n\r\f\v]*)?)?)(\s|$)`, // negated-class fixed (F-40)
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
// This is NOT a regex port — bash:144-156 is a small procedural parser (word-split the
|
|
313
|
+
// command tail, count non-flag tokens, flag a bare HEAD as the 2nd one). Ported as an
|
|
314
|
+
// algorithm, one statement at a time against its bash counterpart:
|
|
315
|
+
//
|
|
316
|
+
// bash: after_push="${c#*push}"
|
|
317
|
+
// here: slice everything after the FIRST literal occurrence of "push" in c — `#*push`
|
|
318
|
+
// is bash's SHORTEST-prefix-removal for the glob `*push`, which is exactly
|
|
319
|
+
// "up to and including the first occurrence of the literal substring `push`".
|
|
320
|
+
//
|
|
321
|
+
// bash: for tok in $after_push (IFS word-splitting; bash ALSO performs unquoted
|
|
322
|
+
// pathname/glob expansion here, deliberately NOT reproduced — same judgment
|
|
323
|
+
// call gate-dep-install.mjs's tokensAfterVerb() made (2.4): glob expansion
|
|
324
|
+
// would make the gate's outcome depend on the hook process's cwd/filesystem
|
|
325
|
+
// state, a strictly worse property for a security control, and no realistic
|
|
326
|
+
// git-push argument or fixture exercises it).
|
|
327
|
+
// here: afterPush.split(/\s+/).filter(Boolean) — whitespace-run splitting only.
|
|
328
|
+
//
|
|
329
|
+
// bash: case "$tok" in ';'|'&&'|'||'|'|') break ;; -*) continue ;; esac
|
|
330
|
+
// here: exact-string boundary check, then a leading-'-' check, in the same order.
|
|
331
|
+
//
|
|
332
|
+
// bash: nonflag_count++; if 2nd non-flag token is literally "HEAD", set the flag.
|
|
333
|
+
// here: same counters, same 2nd-token check.
|
|
334
|
+
//
|
|
335
|
+
// bash: deny if nonflag_count < 2 OR names_bare_head — i.e. fewer than a
|
|
336
|
+
// remote+branch pair was named, or the named "branch" is the ambiguous bare HEAD.
|
|
337
|
+
function checkBareForcePush(payload, c) {
|
|
338
|
+
if (!BARE_FORCE_PUSH_GATE_RE.test(c)) return;
|
|
339
|
+
|
|
340
|
+
const pushIdx = c.indexOf('push');
|
|
341
|
+
const afterPush = pushIdx === -1 ? '' : c.slice(pushIdx + 'push'.length);
|
|
342
|
+
const tokens = afterPush.split(/\s+/).filter(Boolean);
|
|
343
|
+
|
|
344
|
+
let nonFlagCount = 0;
|
|
345
|
+
let namesBareHead = false;
|
|
346
|
+
for (const tok of tokens) {
|
|
347
|
+
if (tok === ';' || tok === '&&' || tok === '||' || tok === '|') break;
|
|
348
|
+
if (tok.startsWith('-')) continue;
|
|
349
|
+
nonFlagCount += 1;
|
|
350
|
+
if (nonFlagCount === 2 && tok === 'HEAD') namesBareHead = true;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (nonFlagCount < 2 || namesBareHead) {
|
|
354
|
+
denyPretool(
|
|
355
|
+
payload,
|
|
356
|
+
`somi refused this command: force-push without an explicit target branch (the current branch cannot be verified and may be protected).
|
|
357
|
+
Name the remote and branch explicitly — e.g. \`git push --force-with-lease origin feature-x\`.
|
|
358
|
+
Force pushes naming main/master/trunk/release are always refused; if this is genuinely
|
|
359
|
+
intended, stop and ask the human to run it themselves.`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function main() {
|
|
365
|
+
const payload = readPayload();
|
|
366
|
+
const cmd = field(payload, '.tool_input.command');
|
|
367
|
+
if (!cmd) return;
|
|
368
|
+
|
|
369
|
+
// Quote-stripped copy. `bash -c "rm -rf /"` hides the dangerous string inside quotes
|
|
370
|
+
// where the patterns' trailing boundary classes ([\s]|$) don't match. Stripping
|
|
371
|
+
// quote characters never removes dangerous content — it only widens matching — so
|
|
372
|
+
// every check runs against both the raw and the stripped form. False positives are
|
|
373
|
+
// tolerated here by design (bash:27-33).
|
|
374
|
+
const cmdStripped = cmd.replace(/"/g, '').replace(/'/g, '');
|
|
375
|
+
|
|
376
|
+
checkDangerous(payload, cmd);
|
|
377
|
+
checkDangerous(payload, cmdStripped);
|
|
378
|
+
checkSecretWrites(payload, cmdStripped);
|
|
379
|
+
checkBareForcePush(payload, cmdStripped);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
runHook(main);
|