@skathio/somi 1.2.0 → 2.0.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/.claude/settings.json +9 -9
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +6 -1
- package/VERSION +1 -1
- package/commands/adopt.md +6 -4
- package/commands/code-loop.md +13 -13
- package/commands/plan-loop.md +10 -10
- package/commands/pr.md +1 -1
- package/commands/release-readiness.md +4 -4
- package/commands/review-panel.md +1 -1
- package/commands/review.md +3 -3
- package/commands/ship-loop.md +2 -2
- package/commands/somi.md +2 -2
- package/commands/upgrade.md +1 -1
- package/examples/sample-consumer/CLAUDE.md +5 -2
- package/examples/sample-consumer/README.md +20 -9
- 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 +2 -2
- package/rules/CLAUDE.md +6 -5
- 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 +21 -16
- package/skills/clean-code/SKILL.md +1 -1
- package/tests/hooks/cases/audit-log.json +21 -0
- package/tests/hooks/cases/block-dangerous-bash.json +90 -2
- package/tests/hooks/cases/block-secret-writes.json +1 -1
- package/tests/hooks/cases/detect-repo-instructions.json +84 -0
- package/tests/hooks/cases/gate-dep-install.json +6 -1
- package/tests/hooks/cases/guard-protected-paths.json +1 -1
- 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 +280 -15
- package/tests/scripts/goldens/somi-findings.json +336 -0
- package/tests/scripts/goldens/somi-loop.json +168 -0
- package/tests/scripts/run.sh +251 -30
- package/hooks/lib/common.sh +0 -133
- 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 -171
- package/hooks/pre-tool/block-secret-writes.sh +0 -83
- package/hooks/pre-tool/gate-dep-install.sh +0 -113
- package/hooks/pre-tool/guard-protected-paths.sh +0 -89
- package/hooks/session-start/detect-repo-instructions.sh +0 -73
- package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
- package/scripts/somi-check.sh +0 -135
- package/scripts/somi-findings.sh +0 -173
- package/scripts/somi-loop.sh +0 -225
|
@@ -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);
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// hooks/pre-tool/block-secret-writes.mjs — PreToolUse hook (matcher: Write|Edit) — block
|
|
3
|
+
// writes to secret-bearing paths.
|
|
4
|
+
//
|
|
5
|
+
// Node port of hooks/pre-tool/block-secret-writes.sh (node-runtime-port, phase 2,
|
|
6
|
+
// iteration 2.2). Imports the shared read/deny/context helpers from ../lib/common.mjs
|
|
7
|
+
// (2.1, reviewer-blessed) rather than reimplementing them.
|
|
8
|
+
//
|
|
9
|
+
// We block any attempt to write/edit files that are likely to hold real secrets. If the
|
|
10
|
+
// user genuinely needs to bootstrap a `.env`, they can do it themselves or explicitly add
|
|
11
|
+
// an override in their settings.local.json.
|
|
12
|
+
//
|
|
13
|
+
// SECRET_PATTERNS mirrors block-dangerous-bash.sh's SECRET_BASENAME set
|
|
14
|
+
// (block-dangerous-bash.sh:86) — "kept in sync by comment convention, not code sharing"
|
|
15
|
+
// today (context.md §2). Preserved as a deliberate duplication in this port; do not
|
|
16
|
+
// unify the two lists — that would be a scope-creeping refactor beyond this
|
|
17
|
+
// behavior-preserving port (flagged as a future-refactor target, same as today).
|
|
18
|
+
//
|
|
19
|
+
// ERE→RegExp translation note: every pattern below is basename-only, pure-ASCII, and
|
|
20
|
+
// uses only anchors, escaped literal dots, and `?`/`*` quantifiers (plus one bare `.`
|
|
21
|
+
// wildcard in the service-account pattern) — a mechanical, one-to-one translation, with
|
|
22
|
+
// no POSIX bracket-expression classes to convert. The `.`-semantics caveat that matters
|
|
23
|
+
// for block-dangerous-bash.sh's patterns (POSIX ERE `.` matches every byte but `\n`; JS
|
|
24
|
+
// `.` additionally refuses to match `\r`/U+2028/U+2029) is scoped to matching against
|
|
25
|
+
// raw COMMAND-STRING content — irrelevant here, since every pattern below matches a
|
|
26
|
+
// normalized file-path BASENAME extracted from the JSON payload, never raw content, and
|
|
27
|
+
// no realistic basename contains a line-terminator character for that divergence to bite.
|
|
28
|
+
// One platform sensitivity 2.3+ must inherit knowingly: path.basename() is posix-vs-win32
|
|
29
|
+
// separator-aware (on Windows, `C:\Users\me\.env` → `.env` → DENY, where bash basename on
|
|
30
|
+
// Linux treats `\` as a regular character → allow). For THIS hook the Windows behavior is
|
|
31
|
+
// strictly safer; for path-heavier hooks (guard-protected-paths) the same divergence could
|
|
32
|
+
// cut the unsafe way. The Linux fixture corpus validates only the posix axis.
|
|
33
|
+
|
|
34
|
+
import path from 'node:path';
|
|
35
|
+
import { readPayload, field, denyPretool, matchesAny, runHook } from '../lib/common.mjs';
|
|
36
|
+
|
|
37
|
+
const SECRET_PATTERNS = [
|
|
38
|
+
// env files (allow .env.example, .env.sample, .env.template explicitly)
|
|
39
|
+
/^\.env$/,
|
|
40
|
+
/^\.env\.local$/,
|
|
41
|
+
/^\.env\.production$/,
|
|
42
|
+
/^\.env\.prod$/,
|
|
43
|
+
/^\.env\.staging$/,
|
|
44
|
+
/^\.env\.secret$/,
|
|
45
|
+
|
|
46
|
+
// private keys and certs
|
|
47
|
+
/\.pem$/,
|
|
48
|
+
/\.key$/,
|
|
49
|
+
/\.p12$/,
|
|
50
|
+
/\.pfx$/,
|
|
51
|
+
/\.jks$/,
|
|
52
|
+
/^id_rsa$/,
|
|
53
|
+
/^id_ed25519$/,
|
|
54
|
+
/^id_ecdsa$/,
|
|
55
|
+
/^id_dsa$/,
|
|
56
|
+
|
|
57
|
+
// cloud credentials
|
|
58
|
+
/^credentials$/, // ~/.aws/credentials
|
|
59
|
+
/^config$/, // ~/.aws/config (usually contains profile refs but no secrets)
|
|
60
|
+
|
|
61
|
+
// service-account keys
|
|
62
|
+
/-key\.json$/,
|
|
63
|
+
/-credentials\.json$/,
|
|
64
|
+
/service-account.*\.json$/,
|
|
65
|
+
|
|
66
|
+
// shell rc files (may contain export STATEMENTS with secrets)
|
|
67
|
+
/\.netrc$/,
|
|
68
|
+
/\.pgpass$/,
|
|
69
|
+
|
|
70
|
+
// vault / secret tool files
|
|
71
|
+
/\.kdbx$/,
|
|
72
|
+
/secrets?\.ya?ml$/,
|
|
73
|
+
/secrets?\.json$/,
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
// Allow explicit example/template files.
|
|
77
|
+
const EXAMPLE_BASENAMES = ['.env.example', '.env.sample', '.env.template', '.env.dist'];
|
|
78
|
+
|
|
79
|
+
function main() {
|
|
80
|
+
const payload = readPayload();
|
|
81
|
+
const tool = field(payload, '.tool_name');
|
|
82
|
+
const pathInput = field(payload, '.tool_input.file_path');
|
|
83
|
+
if (!pathInput) return;
|
|
84
|
+
|
|
85
|
+
// Normalise to basename for pattern matching.
|
|
86
|
+
const basename = path.basename(pathInput);
|
|
87
|
+
|
|
88
|
+
if (EXAMPLE_BASENAMES.includes(basename)) return;
|
|
89
|
+
|
|
90
|
+
if (matchesAny(basename, SECRET_PATTERNS)) {
|
|
91
|
+
denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: this path is in the secret-bearing allowlist.
|
|
92
|
+
Bootstrap secret files by hand, or commit only \`.env.example\`-style templates.`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
runHook(main);
|