@cratis/pi 7.131.6 → 7.132.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/package/corpus/harnesses/pi/extensions/cratis-hooks/index.ts +4 -2
- package/package/corpus/hooks/README.md +87 -8
- package/package/corpus/hooks/scripts/cratis-check-pr.mjs +34 -2
- package/package/corpus/hooks/scripts/cratis-guard-pr-body.sh +1 -1
- package/package/corpus/hooks/scripts/cratis-guard-secrets.sh +6 -2
- package/package/corpus/hooks/scripts/cratis-guard-shell-writes.sh +236 -0
- package/package/corpus/hooks/scripts/cratis-guard-writes.sh +172 -75
- package/package/corpus/hooks/settings.template.json +4 -0
- package/package.json +1 -1
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* Claude PreToolUse (Write|Edit) → Pi `tool_call` → cratis-guard-writes.sh (exit 2 = block)
|
|
10
10
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-store-mutations.sh (exit 2 = block)
|
|
11
11
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-secrets.sh (exit 2 = block)
|
|
12
|
+
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-shell-writes.sh (exit 2 = block)
|
|
12
13
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-pr-body.sh (exit 2 = block)
|
|
13
14
|
* Claude PostToolUse (Write|Edit) → Pi `tool_result` → cratis-pattern-scan.sh (advisory context)
|
|
14
15
|
* Claude PostToolUse (Bash) → Pi `tool_result` → cratis-cleanup-worktrees.sh --hook (removes delivered worktrees/branches)
|
|
@@ -31,7 +32,7 @@
|
|
|
31
32
|
* CRATIS_HOOKS_SKIP_GATE, …) still works because the scripts are executed unchanged, in the environment
|
|
32
33
|
* Pi was started from.
|
|
33
34
|
*
|
|
34
|
-
* Only Pi's `bash` tool is bridged to the store-mutation and
|
|
35
|
+
* Only Pi's `bash` tool is bridged to the store-mutation, secrets and shell-write guards. A command the user types directly (`!cmd`,
|
|
35
36
|
* the `user_bash` event) is the person's own action and is deliberately not guarded.
|
|
36
37
|
*/
|
|
37
38
|
|
|
@@ -201,6 +202,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
201
202
|
const guardWrites = path.join(scriptsDir, "cratis-guard-writes.sh");
|
|
202
203
|
const guardStoreMutations = path.join(scriptsDir, "cratis-guard-store-mutations.sh");
|
|
203
204
|
const guardSecrets = path.join(scriptsDir, "cratis-guard-secrets.sh");
|
|
205
|
+
const guardShellWrites = path.join(scriptsDir, "cratis-guard-shell-writes.sh");
|
|
204
206
|
const guardPrBody = path.join(scriptsDir, "cratis-guard-pr-body.sh");
|
|
205
207
|
const patternScan = path.join(scriptsDir, "cratis-pattern-scan.sh");
|
|
206
208
|
const qualityGate = path.join(scriptsDir, "cratis-quality-gate.sh");
|
|
@@ -229,7 +231,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
229
231
|
const command = (event as any).input?.command;
|
|
230
232
|
if (typeof command !== "string" || !command.trim()) return;
|
|
231
233
|
const payload = { cwd: ctx.cwd, tool_name: "Bash", tool_input: { command } };
|
|
232
|
-
const blocked = await runCommandGuards([[guardStoreMutations, "cratis-guard-store-mutations"], [guardSecrets, "cratis-guard-secrets"]], payload, ctx);
|
|
234
|
+
const blocked = await runCommandGuards([[guardStoreMutations, "cratis-guard-store-mutations"], [guardSecrets, "cratis-guard-secrets"], [guardShellWrites, "cratis-guard-shell-writes"]], payload, ctx);
|
|
233
235
|
if (blocked) return blocked;
|
|
234
236
|
if (isInstalled(guardPrBody)) {
|
|
235
237
|
const run = await runScript(guardPrBody, JSON.stringify(payload), ctx.cwd, ctx.signal);
|
|
@@ -10,8 +10,9 @@ Three layers:
|
|
|
10
10
|
|---|---|---|---|---|
|
|
11
11
|
| Pattern pass | `PostToolUse` on a write | `scripts/cratis-pattern-scan.sh` | zero tokens until a match | appends a one-line reminder to context, never blocks |
|
|
12
12
|
| Hard block | `PreToolUse` on a write | `scripts/cratis-guard-writes.sh` | zero | exits **2** — the write does not happen |
|
|
13
|
+
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-shell-writes.sh` | zero tokens; one batch Write/Edit classification | exits **2** — a protected reference requires read-only syntax throughout the command; best-effort, not a sandbox |
|
|
13
14
|
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-store-mutations.sh` | zero; parses only commands that mention `cratis` | exits **2** — the store-changing `cratis chronicle` command does not run |
|
|
14
|
-
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-secrets.sh` | zero; parses only commands that mention a credential-bearing tool or file | exits **2** — the guard is a **best-effort, defense-in-depth text filter, NOT a sandbox**: it refuses some harmless commands rather than model the whole shell. Real protection requires **OS-level sandboxing or file permissions**. A command is *tainted* when a protected file-name stem appears in any token, including option values, in any letter case, after quotes, backslashes and line continuations are removed. Only search regex text is exempt: `-e`/`--regexp` values, or the first operand when neither `-e` nor `-f` is present. `-f`/`--file` values and all other operands are paths, not exempt patterns. The stems are `.env`, `.pem`, `.p12`, `.pfx`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `id_dsa`, `.netrc`, `.npmrc`, `.pgpass`, `.pypirc`, `.git-credentials`, `.kube/`, `kubeconfig`, `credentials`, `.docker/`, `/environ` and `run/secrets`. Stars, question marks, bracket expressions and grouped pathname patterns count as the characters they can match when the pattern retains at least two literal stem characters. A command is also tainted when an assignment value or any expanded word can contain a stem. A tainted command runs only when it is a single simple command with every word literal: `cat`, `head`, `tail`, `less`, `more`, `wc`, `grep`, `egrep`, `fgrep` or `rg` of paths that are not protected (such as `cat .env.example`); `test` of literal paths; or `cp SOURCE DEST` with no options and a source that is not protected (
|
|
15
|
+
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-secrets.sh` | zero; parses only commands that mention a credential-bearing tool or file | exits **2** — the guard is a **best-effort, defense-in-depth text filter, NOT a sandbox**: it refuses some harmless commands rather than model the whole shell. Real protection requires **OS-level sandboxing or file permissions**. A command is *tainted* when a protected file-name stem appears in any token, including option values, in any letter case, after quotes, backslashes and line continuations are removed. Only search regex text is exempt: `-e`/`--regexp` values, or the first operand when neither `-e` nor `-f` is present. `-f`/`--file` values and all other operands are paths, not exempt patterns. The stems are `.env`, `.pem`, `.p12`, `.pfx`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `id_dsa`, `.netrc`, `.npmrc`, `.pgpass`, `.pypirc`, `.git-credentials`, `.kube/`, `kubeconfig`, `credentials`, `.docker/`, `/environ` and `run/secrets`. Stars, question marks, bracket expressions and grouped pathname patterns count as the characters they can match when the pattern retains at least two literal stem characters. A command is also tainted when an assignment value or any expanded word can contain a stem. A tainted command runs only when it is a single simple command with every word literal: `cat`, `head`, `tail`, `less`, `more`, `wc`, `grep`, `egrep`, `fgrep` or `rg` of paths that are not protected (such as `cat .env.example`); `test` of literal paths; or `cp SOURCE DEST` with no options and a source that is not protected (for example, `cp .env.example example.txt`; the shell-write guard separately refuses `.env` destinations). A single simple `ls` or `stat` may also take glob operands, but not variables, substitutions, wrappers or other shell structure. Tainted searches cannot recurse, search a directory with `rg`, omit `rg` path operands, or use value-taking options other than `-e`/`--regexp`. Every other tainted command is refused, including variables, command substitution, globs for content readers, loops, conditionals, pipes, redirections, here-strings, here-documents, wrappers, `bash -c`, `eval` and transfer tools. Shell-option changes are checked even without a protected stem: modifying `shopt`, `setopt`, `unsetopt` and `emulate` are refused. `extglob` is refused as an option, not merely as text. Shell invocation `-o`/`-O` options, including clustered flags, must name a supported option. Expanded `set` arguments are refused. Only `set` flags `e`, `u`, `x`, `f`, `v`, `E`, `T` and named options `errexit`, `nounset`, `pipefail`, `xtrace`, `verbose`, `noglob`, `errtrace`, `functrace` (including their `+` forms) are supported. The message names the stem: run the read on its own with literal paths, or put long text that mentions the name in a file. Commands without a stem keep the full analysis. In that analysis a variable can hold any value the command assigns to it anywhere, a positional parameter or an unquoted expansion with glob or space characters is unknown, and an unknown file operand is refused. Residual classes include **shell glob grammar across bash and zsh, option toggles, option arity and quote concatenation**, as well as runtime-generated names, inherited state, filesystem indirection, user-defined commands, external programs and scripts, and searches without a named protected path. These classes are not modeled exhaustively. Use OS-level sandboxing or file permissions, harness isolation and least privilege as the primary boundary. Token files and key-extension globs (`*.key`, `*.jks`) are refused only through the listed reader, input, `dd` and transfer commands; see [`secrets.md`](../rules/secrets.md) |
|
|
15
16
|
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-pr-body.sh` | fetches shared rules only for `gh pr create/edit` | exits **2** for inline bodies, invalid notes or conflicting release labels; warns and allows when offline with no cache |
|
|
16
17
|
| Cleanup of delivered work | `PostToolUse` on `Bash` (`gh pr merge`, `git pull/merge/worktree`) and `SessionStart` (Pi: `tool_result` and `session_start`) | `scripts/cratis-cleanup-worktrees.sh --hook` | zero when the command is unrelated | never blocks; removes delivered worktrees and branches, reports what it kept |
|
|
17
18
|
| Quality gate (Claude) | `Stop` | `scripts/cratis-quality-gate.sh` | one build/test run, only when relevant files changed | exits **2** — the turn does not end |
|
|
@@ -39,7 +40,7 @@ they describe what a hook should do for tools that have no wiring yet.
|
|
|
39
40
|
|
|
40
41
|
> Hooks use native wiring rather than a shared folder adapter: Claude Code reads `.claude/settings.json`;
|
|
41
42
|
> Codex has a shell-only adapter described below. The Pi harness bridges the same scripts to its own events through the `cratis-hooks`
|
|
42
|
-
> extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation and PR-body guards, its
|
|
43
|
+
> extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation, secrets, shell-write and PR-body guards, its
|
|
43
44
|
> `write` and `edit` tools the write guard); Copilot would read `.github/hooks/*.json`, and no
|
|
44
45
|
> Copilot wiring ships yet.
|
|
45
46
|
>
|
|
@@ -80,7 +81,7 @@ alone. **Consumer activation through `cratis ai install/update` is not delivered
|
|
|
80
81
|
adapter**: the CLI's Codex installation plan needs a separate change. Authoring setup
|
|
81
82
|
and isolated fixtures are not evidence of installed or end-to-end Codex runtime coverage.
|
|
82
83
|
|
|
83
|
-
The bridge runs the
|
|
84
|
+
The bridge runs the store-mutation, secrets, PR-body and shell-write guards through
|
|
84
85
|
Bash, using the payload's working directory and inherited environment. It never executes
|
|
85
86
|
the pending command. A denial is final; the later guard cannot override it. Malformed
|
|
86
87
|
input, a missing managed guard, spawn failure, signal, unexpected nonzero exit, malformed
|
|
@@ -158,7 +159,7 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
|
|
|
158
159
|
|
|
159
160
|
- Editing a file whose header marks it as Cratis-generated output — rule 15 `[contract]`
|
|
160
161
|
- Writing content that opens with such a header (hand-authoring a "generated" proxy)
|
|
161
|
-
- `Directory.Packages.props`, `global.json`, `NuGet.config` (also `NuGet.Config` and `nuget.config`),
|
|
162
|
+
- `package.json`, `Directory.Packages.props`, `global.json`, `NuGet.config` (also `NuGet.Config` and `nuget.config`),
|
|
162
163
|
`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `packages.lock.json` — unless the
|
|
163
164
|
repository's dependency-manifest policy allows them (see below)
|
|
164
165
|
- `.env`, `.env.*`, `*.env` — secrets
|
|
@@ -171,9 +172,81 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
|
|
|
171
172
|
|
|
172
173
|
For agent controls, report the intended change rather than rewriting permissions or hooks.
|
|
173
174
|
A person edits settings; `cratis ai update` replaces managed files using the CLI's filesystem
|
|
174
|
-
operations, not agent Write/Edit calls.
|
|
175
|
-
|
|
176
|
-
|
|
175
|
+
operations, not agent Write/Edit calls. The shell-write guard scans the **whole command text**
|
|
176
|
+
for protected references, including nested strings, heredoc bodies and option values. It
|
|
177
|
+
removes simple quoting/escapes, checks case-insensitive spellings, and asks the write guard's
|
|
178
|
+
`--references` batch mode to classify candidate paths relative to the hook cwd. Original
|
|
179
|
+
spellings are retained too so existing generated headers can be checked on case-sensitive
|
|
180
|
+
filesystems. Glob/bracket patterns are checked against that same policy; brace patterns
|
|
181
|
+
are conservative. A directory containing owned controls/managed paths also counts, such as
|
|
182
|
+
`.claude`, `.pi/extensions` or installed `.cratis/ai`; no second tree list lives in the shell
|
|
183
|
+
guard. Other trees, including `.github/workflows`, count only if the write policy protects them.
|
|
184
|
+
Dependency manifests, including `package.json`, retain their origin/opt-in allowances.
|
|
185
|
+
|
|
186
|
+
**No protected reference: allow.** For example, `npm test`, `dotnet build`, `bash --version`,
|
|
187
|
+
`bash --help` and `cd src && echo ok > out.txt` are unaffected. If any reference exists,
|
|
188
|
+
**every simple command must be on this read-only allowlist**:
|
|
189
|
+
|
|
190
|
+
Only the following **exact options** are exempt, because they select/present reads rather
|
|
191
|
+
than create files or invoke helpers. Any other option denies, including long-option
|
|
192
|
+
abbreviations and unlisted `--option=value` forms. `--` ends option checking; remaining
|
|
193
|
+
arguments are operands. A lone `-` is a stdin operand. Value-free short flags may combine
|
|
194
|
+
(e.g. `grep -ni`); value-taking forms must use the explicitly listed spelling.
|
|
195
|
+
|
|
196
|
+
| Command | Permitted options |
|
|
197
|
+
| --- | --- |
|
|
198
|
+
| `cat` | `-n -A -v -e -t -s -b` |
|
|
199
|
+
| `head`, `tail` | `-n N`, `-nN`, `-c N`, `-N` (numeric counts); no `-f` |
|
|
200
|
+
| `wc` | `-l -w -c -m` |
|
|
201
|
+
| `ls` | `-l -a -A -1 -h -d -R -t -r -F` |
|
|
202
|
+
| `grep`, `egrep`, `fgrep` | `-n -i -r -R -l -L -c -v -w -x -F -E -H -h -o -q -s`; `-e PATTERN`, `-A N`, `-B N`, `-C N`; no long options |
|
|
203
|
+
| `echo` | `-n -e -E` |
|
|
204
|
+
| `printf`, `test`, `[`, `true`, `false`, `pwd` | None (in particular, no `printf -v`) |
|
|
205
|
+
| `git status` | `-s -b --short --porcelain` |
|
|
206
|
+
| `git diff` | `--stat --name-only --name-status --cached --staged --check -p -U<N> --no-color` |
|
|
207
|
+
| `git log` | `--oneline --stat --name-only -n N -nN -<N> -p --no-color --format=<fmt> --pretty=<fmt> --follow` |
|
|
208
|
+
| `git show` | `--stat --name-only -p --no-color --format=<fmt>` |
|
|
209
|
+
| `git add` | `-A -u -p` |
|
|
210
|
+
| `git commit` | `-m MSG`, `-mMSG`, `-a`, `-q`; `-F FILE` only for a literal non-protected file; no `--no-verify` |
|
|
211
|
+
| `git blame`, `ls-files`, `rev-parse`, `check-ignore`, `grep` | None |
|
|
212
|
+
|
|
213
|
+
No global git options are exempt (`-C`, `-c`, `--no-pager` etc. deny before the subcommand).
|
|
214
|
+
Git format values containing `%(` are not accepted. Index/commit operations are deliberate
|
|
215
|
+
allowances, not general shell execution permission. Output-to-file options such as
|
|
216
|
+
`git diff --output=...` are never exempt, even with a non-protected destination on a line
|
|
217
|
+
that references a protected file.
|
|
218
|
+
|
|
219
|
+
`gh` (all subcommands), `rg`, `ag`, `sort`, `uniq`, `cut`, `jq`, `yq`, `less`, `more`, `stat`,
|
|
220
|
+
`file`, `diff`, `cmp`, checksum tools, `realpath`, `dirname`, `basename`, `which` and `type`
|
|
221
|
+
are not on this list: their option surfaces are deliberately not analysed here.
|
|
222
|
+
|
|
223
|
+
Assignment prefixes and assignment-only commands are not allowlisted. Neither are wrappers,
|
|
224
|
+
evaluators, shells or writer verbs. `cd`, `pushd` and `popd` are **not** allowlisted when a
|
|
225
|
+
protected reference exists: `cd .claude && echo x > settings.json` refuses without tracking
|
|
226
|
+
cwd or inferring destinations. Shells refuse regardless of stdin descriptor, lone `-`, or
|
|
227
|
+
`-c` option spelling. Unparsed complex syntax, including substitutions and heredocs, refuses
|
|
228
|
+
once a protected reference exists; no shell bodies are interpreted.
|
|
229
|
+
|
|
230
|
+
Even an allowlisted command may not redirect output to a protected or non-literal target
|
|
231
|
+
(`$`, backticks or pathname patterns). Literal ordinary output is permitted, for example
|
|
232
|
+
`grep -n version package.json > /tmp/v.txt`; descriptor duplication such as `2>&1` is fine.
|
|
233
|
+
`cat package.json`, `git diff -- package.json`, `git commit -m "Update package.json"` and
|
|
234
|
+
`ls -la .env.example` are allowed reads/explicit index operations. `head -n 20 .env.example`
|
|
235
|
+
is allowed too: the write policy protects that file, but reading is not writing (the secrets
|
|
236
|
+
guard independently governs reads). `cp .env.example .env` refuses. Use the edit/write tools, or report
|
|
237
|
+
the intended change; those tools retain their own protection and are not a bypass.
|
|
238
|
+
|
|
239
|
+
Parser/classifier failures and bounded work limits fail closed (128 KiB command text,
|
|
240
|
+
256 distinct candidates, 256 words per simple command, 64 simple commands, 64 existing glob
|
|
241
|
+
matches and a bounded glob-intersection state space). Pattern and tree references can make
|
|
242
|
+
this deliberately over-conservative.
|
|
243
|
+
|
|
244
|
+
This is **best-effort, not a sandbox**. Runtime names assembled from variables without a
|
|
245
|
+
protected name appearing literally are out of scope, as are aliases/functions, external
|
|
246
|
+
scripts, tool configuration/hooks and symlinks created during execution. Existing generated
|
|
247
|
+
headers are classified; content that would create a new generated header is not inspected by
|
|
248
|
+
the shell filter. OS permissions/sandboxing remain the primary boundary. Do not use another
|
|
249
|
+
route to work around a refusal.
|
|
177
250
|
|
|
178
251
|
The generated-file check is anchored: the marker must be a comment opener at the start of one of
|
|
179
252
|
the first five lines. A rule file or a document that merely *mentions* the marker is not blocked.
|
|
@@ -705,7 +778,7 @@ Each is an explicit, auditable opt-out — none of them is a default.
|
|
|
705
778
|
|
|
706
779
|
| Variable | Effect |
|
|
707
780
|
|---|---|
|
|
708
|
-
| `CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1` | bypasses
|
|
781
|
+
| `CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1` | bypasses both Write/Edit and shell-write guards, including generated files, `.env`, agent controls and installed trees, while set in the harness environment; use only for an explicitly requested protected write. Repository-scoped manifest allowance uses `.cratis/ai.json` instead and never bypasses those protections |
|
|
709
782
|
| `CRATIS_HOOKS_SKIP_SCAN=1` | disables the pattern pass |
|
|
710
783
|
| `CRATIS_HOOKS_SKIP_GATE=1` | disables the quality gate |
|
|
711
784
|
| `CRATIS_HOOKS_GATE_DRYRUN=1` | prints which gates would run, and why, then exits 0 |
|
|
@@ -763,6 +836,12 @@ jq -nc '{session_id:"t", cwd:"'"$PWD"'", tool_name:"Edit",
|
|
|
763
836
|
tool_input:{file_path:"'"$PWD"'/Directory.Packages.props", new_string:"x"}}' \
|
|
764
837
|
| bash .cratis/ai/hooks/scripts/cratis-guard-writes.sh; echo "exit=$?"
|
|
765
838
|
|
|
839
|
+
# Shell-write guard: expect exit 2, then exit 0 for an ordinary destination
|
|
840
|
+
jq -nc '{cwd:"'"$PWD"'", tool_name:"Bash", tool_input:{command:"echo x > .env"}}' \
|
|
841
|
+
| bash .cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh; echo "exit=$?"
|
|
842
|
+
jq -nc '{cwd:"'"$PWD"'", tool_name:"Bash", tool_input:{command:"echo x > notes.md"}}' \
|
|
843
|
+
| bash .cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh; echo "exit=$?"
|
|
844
|
+
|
|
766
845
|
# Store-mutation guard, both directions: expect exit 2, then exit 0 for the read-only neighbor
|
|
767
846
|
jq -nc '{tool_name:"Bash", tool_input:{command:"cratis chronicle observers replay my-observer --yes"}}' \
|
|
768
847
|
| bash .cratis/ai/hooks/scripts/cratis-guard-store-mutations.sh; echo "exit=$?"
|
|
@@ -337,6 +337,32 @@ function executableWords(words) {
|
|
|
337
337
|
return { words: result, environmentRepository };
|
|
338
338
|
}
|
|
339
339
|
|
|
340
|
+
function isPrMutation(words, index) {
|
|
341
|
+
return words[index] === 'pr' && ['create', 'edit'].includes(words[index + 1]);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function normalizeGlobalOptions(words) {
|
|
345
|
+
if (words[0] !== 'gh') return words;
|
|
346
|
+
const options = [];
|
|
347
|
+
let index = 1;
|
|
348
|
+
while (words[index]?.startsWith('-')) {
|
|
349
|
+
const option = words[index++];
|
|
350
|
+
if (['-R', '--repo'].includes(option)) {
|
|
351
|
+
options.push(option, words[index++]);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (/^(?:-R.|--repo=)/.test(option)) {
|
|
355
|
+
options.push(option);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
// The caller refuses this only where the release-note checks apply.
|
|
359
|
+
if (words.slice(index).some((_, offset) => isPrMutation(words, index + offset))) return null;
|
|
360
|
+
return words;
|
|
361
|
+
}
|
|
362
|
+
if (!isPrMutation(words, index)) return words;
|
|
363
|
+
return ['gh', words[index], words[index + 1], ...options, ...words.slice(index + 2)];
|
|
364
|
+
}
|
|
365
|
+
|
|
340
366
|
function effectiveRepository(words, cwd, environmentRepository) {
|
|
341
367
|
// gh selects an edit's PR URL before --repo, then GH_REPO, then the checkout origin.
|
|
342
368
|
let repository, target;
|
|
@@ -375,7 +401,7 @@ function hook() {
|
|
|
375
401
|
try { payload = JSON.parse(readFileSync(0, 'utf8')); } catch { return 0; }
|
|
376
402
|
claudeHook = payload?.hook_event_name === 'PreToolUse';
|
|
377
403
|
const text = payload?.tool_input?.command;
|
|
378
|
-
if (typeof text !== 'string' || !/\bgh
|
|
404
|
+
if (typeof text !== 'string' || !/\bgh(?:\s+\S+)*\s+pr\s+(create|edit)\b/.test(text.replace(/\\\r?\n/g, ''))) return 0;
|
|
379
405
|
// Match each simple command, never the same text inside an echo/grep argument.
|
|
380
406
|
let cwd = payload.cwd || process.cwd();
|
|
381
407
|
invocation = { 'hook payload directory': payload.cwd || '(none)' };
|
|
@@ -384,7 +410,13 @@ function hook() {
|
|
|
384
410
|
try { parsed = commands(text); } catch (error) { if (!optedIn(cwd)) return 0; throw error; }
|
|
385
411
|
const written = new Set();
|
|
386
412
|
for (const command of parsed) {
|
|
387
|
-
const
|
|
413
|
+
const executable = executableWords(command.words);
|
|
414
|
+
const words = normalizeGlobalOptions(executable.words);
|
|
415
|
+
if (!words) {
|
|
416
|
+
if (!optedIn(cwd)) continue;
|
|
417
|
+
throw new Error('Put options after gh pr create/edit; only -R/--repo is supported before the subcommand.');
|
|
418
|
+
}
|
|
419
|
+
const { environmentRepository } = executable;
|
|
388
420
|
const writes = [...command.writes];
|
|
389
421
|
if (words[0] === 'tee') writes.push(...words.slice(1).filter(word => !word.startsWith('-')));
|
|
390
422
|
if (knownDirectory) for (const file of writes) written.add(resolve(cwd, file));
|
|
@@ -14,7 +14,7 @@ command_text=${payload//\\n/ }
|
|
|
14
14
|
command_text=${command_text//\\t/ }
|
|
15
15
|
command_text=${command_text//\\r/ }
|
|
16
16
|
command_text=${command_text//\\/}
|
|
17
|
-
if [[ ! "$command_text" =~ gh[[:space:]]+pr[[:space:]]+(create|edit) ]]; then
|
|
17
|
+
if [[ ! "$command_text" =~ gh([[:space:]]+[^[:space:]]+)*[[:space:]]+pr[[:space:]]+(create|edit) ]]; then
|
|
18
18
|
exit 0
|
|
19
19
|
fi
|
|
20
20
|
if ! command -v node >/dev/null 2>&1; then
|
|
@@ -900,7 +900,11 @@ function allowed_option(option) { return option ~ /^(errexit|nounset|pipefail|xt
|
|
|
900
900
|
function shell_invocation(A, s, n, k, j, flags, c, script) {
|
|
901
901
|
for (k = s + 1; k <= n; k++) {
|
|
902
902
|
if (A[k] == "--" || A[k] !~ /^[-+]/) break
|
|
903
|
-
if (A[k] ~ /^--/)
|
|
903
|
+
if (A[k] ~ /^--/) {
|
|
904
|
+
# Only startup switches that preserve the checked shell syntax are safe.
|
|
905
|
+
if (A[k] !~ /^--(norc|noprofile|noediting|verbose|login|version|help)$/) config_report()
|
|
906
|
+
continue
|
|
907
|
+
}
|
|
904
908
|
flags = substr(A[k], 2); script = index(flags, "c")
|
|
905
909
|
for (j = 1; j <= length(flags); j++) {
|
|
906
910
|
c = substr(flags, j, 1)
|
|
@@ -1271,7 +1275,7 @@ BEGIN {
|
|
|
1271
1275
|
if (pass == 1 && bindings > 0) continue
|
|
1272
1276
|
if (TAINT != "" && (complex || queued != 1 || commands != 1 || !simple_ok)) {
|
|
1273
1277
|
other_reports = reports; reports = ""
|
|
1274
|
-
report("the command names a protected file (" TAINT ") and is not a single literal read", "run the read on its own with literal paths, e.g. cat .env.example
|
|
1278
|
+
report("the command names a protected file (" TAINT ") and is not a single literal read", "run the read on its own with literal paths, e.g. cat .env.example; split compound commands into separate calls; do not build the name with variables, globs, loops, pipes, redirections or nested shells; for a commit message or PR body that mentions the name, write the text to a file with the file tool and pass the file")
|
|
1275
1279
|
reports = reports other_reports
|
|
1276
1280
|
}
|
|
1277
1281
|
printf "%s", reports
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Whole-command reference filter, not a shell interpreter or sandbox.
|
|
3
|
+
# The Write/Edit guard is the only protected-path policy. With any protected reference,
|
|
4
|
+
# accept only the small read-only command language below; never infer write destinations.
|
|
5
|
+
set -euo pipefail
|
|
6
|
+
export LC_ALL=C
|
|
7
|
+
script_directory="${BASH_SOURCE[0]%/*}"
|
|
8
|
+
[ "$script_directory" != "${BASH_SOURCE[0]}" ] || script_directory=.
|
|
9
|
+
# shellcheck source=SCRIPTDIR/hook-lib.sh
|
|
10
|
+
. "$script_directory/hook-lib.sh"
|
|
11
|
+
[ "${CRATIS_HOOKS_ALLOW_PROTECTED_WRITES:-0}" = 1 ] && exit 0
|
|
12
|
+
input=""
|
|
13
|
+
IFS= read -r -d '' input || true
|
|
14
|
+
[ -n "$input" ] || exit 0
|
|
15
|
+
hook_require_jq cratis-guard-shell-writes CRATIS_HOOKS_ALLOW_PROTECTED_WRITES
|
|
16
|
+
parser_failed() {
|
|
17
|
+
printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: parser failed; cannot check this tool call.' >&2
|
|
18
|
+
exit 2
|
|
19
|
+
}
|
|
20
|
+
cwd="" command_text="" parser_status=""
|
|
21
|
+
{
|
|
22
|
+
IFS= read -r -d '' cwd
|
|
23
|
+
IFS= read -r -d '' command_text
|
|
24
|
+
IFS= read -r -d '' parser_status
|
|
25
|
+
} < <(jq -j -s '
|
|
26
|
+
def field(path): ([try (path // empty) catch empty] | first // "")
|
|
27
|
+
| if type == "string" then . else tojson end | gsub("\u0000"; "");
|
|
28
|
+
if length == 1 then .[0] else error("expected one JSON document") end
|
|
29
|
+
| [field(.cwd), field(.tool_input.command)] | .[] | ., "\u0000"
|
|
30
|
+
' <<<"$input" 2>/dev/null && printf 'ok\0') || parser_failed
|
|
31
|
+
[ "$parser_status" = ok ] || parser_failed
|
|
32
|
+
[ -n "$command_text" ] || exit 0
|
|
33
|
+
cwd="${cwd:-$PWD}"
|
|
34
|
+
[ "${#command_text}" -le 131072 ] || parser_failed
|
|
35
|
+
|
|
36
|
+
IFS= read -r -d '' program <<'AWK' || true
|
|
37
|
+
function candidate(s) {
|
|
38
|
+
if (s == "" || s ~ /[\n\r\t]/ || (s in seen)) return
|
|
39
|
+
if (++candidates > 256 || length(s) > 4096) exit 2
|
|
40
|
+
seen[s] = 1; print s
|
|
41
|
+
if (s != tolower(s)) candidate(tolower(s))
|
|
42
|
+
# A generic attached option prefix must not hide a path spelling (-t.pi/...).
|
|
43
|
+
if (s ~ /^-/ && match(s, /[.\/]/) && RSTART > 1) candidate(substr(s, RSTART))
|
|
44
|
+
}
|
|
45
|
+
function scan(s, n, i, c, word) {
|
|
46
|
+
n = length(s)
|
|
47
|
+
for (i = 1; i <= n; i++) {
|
|
48
|
+
c = substr(s, i, 1)
|
|
49
|
+
if (c ~ /[ \t\n\r;|&<>()\047"`$=\\]/) { candidate(word); word = "" }
|
|
50
|
+
else word = word c
|
|
51
|
+
}
|
|
52
|
+
candidate(word)
|
|
53
|
+
# Braces have a second boundary view; retain the original pattern above too.
|
|
54
|
+
if (s ~ /[{}]/) { gsub(/[{}]/, " ", s); scan(s) }
|
|
55
|
+
}
|
|
56
|
+
# Reuse ANSI-C decoding for reference spellings, not for interpreting shell code.
|
|
57
|
+
function ansi(s, i, c, c2, v, k, limit, d, digits) {
|
|
58
|
+
ansi_word = ""
|
|
59
|
+
while (i <= length(s)) {
|
|
60
|
+
c = substr(s, i++, 1)
|
|
61
|
+
if (c == "\047") return i
|
|
62
|
+
if (c != "\\") { ansi_word = ansi_word c; continue }
|
|
63
|
+
c2 = substr(s, i++, 1); v = -1
|
|
64
|
+
if (c2 in ESC) v = ESC[c2]
|
|
65
|
+
else if (c2 ~ /^[0-7]$/) {
|
|
66
|
+
v = c2 + 0
|
|
67
|
+
for (k = 0; k < 2 && substr(s, i, 1) ~ /^[0-7]$/; k++) { v = v * 8 + substr(s, i++, 1) }
|
|
68
|
+
v = v % 256
|
|
69
|
+
} else if (c2 == "x" || c2 == "u" || c2 == "U") {
|
|
70
|
+
limit = c2 == "x" ? 2 : c2 == "u" ? 4 : 8; v = digits = 0
|
|
71
|
+
while (digits < limit && (d = tolower(substr(s, i, 1))) != "" && (d in HEX)) { v = v * 16 + HEX[d]; i++; digits++ }
|
|
72
|
+
if (!digits || v > 255) v = -1
|
|
73
|
+
}
|
|
74
|
+
if (v > 0) ansi_word = ansi_word sprintf("%c", v)
|
|
75
|
+
else if (v < 0) ansi_word = ansi_word c2
|
|
76
|
+
}
|
|
77
|
+
return i
|
|
78
|
+
}
|
|
79
|
+
function unquote(s, i, c, c2, q, out, quoted) {
|
|
80
|
+
for (i = 1; i <= length(s); i++) {
|
|
81
|
+
c = substr(s, i, 1); c2 = substr(s, i + 1, 1)
|
|
82
|
+
if (c == "$" && c2 == "\047" && q != "\047") { i = ansi(s, i + 2) - 1; out = out ansi_word; continue }
|
|
83
|
+
if (c == "\\" && q != "\047") { if (c2 != "\n") { out = out c2; quoted = quoted c2 }; i++; continue }
|
|
84
|
+
if ((c == "\047" || c == "\"") && (q == "" || q == c)) {
|
|
85
|
+
if (q == c) { candidate(quoted); quoted = ""; q = "" } else q = c
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
out = out c; if (q != "") quoted = quoted c
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
function protected(s) { return s in protected_paths }
|
|
93
|
+
function endword() {
|
|
94
|
+
if (!inword) return
|
|
95
|
+
if (redirect) {
|
|
96
|
+
if (!(redirect == 2 && word ~ /^([0-9]+|-)$/) && (word ~ /[$`*?\[{]/ || protected(word))) bad = 1
|
|
97
|
+
redirect = 0
|
|
98
|
+
} else {
|
|
99
|
+
if (++argc > 256) bad = 1
|
|
100
|
+
W[argc] = word
|
|
101
|
+
}
|
|
102
|
+
word = ""; inword = 0
|
|
103
|
+
}
|
|
104
|
+
# Each exemption permits only the reviewed read/presentation options below. No unknown
|
|
105
|
+
# options, long-option abbreviations or implicit value-taking short clusters are accepted.
|
|
106
|
+
# Every table entry has a sibling ALLOW test and rejected-option neighbors.
|
|
107
|
+
function policy(verb, flags, longs, words, n, k) {
|
|
108
|
+
verbs[verb] = 1; short_options[verb] = flags
|
|
109
|
+
n = split(longs, words, " ")
|
|
110
|
+
for (k = 1; k <= n; k++) long_options[verb, words[k]] = 1
|
|
111
|
+
}
|
|
112
|
+
function short_flags(w, flags, k) {
|
|
113
|
+
if (w !~ /^-[^-]/) return 0
|
|
114
|
+
for (k = 2; k <= length(w); k++) if (!index(flags, substr(w, k, 1))) return 0
|
|
115
|
+
return 1
|
|
116
|
+
}
|
|
117
|
+
function number(s) { return s ~ /^[+-]?[0-9]+$/ }
|
|
118
|
+
function options_allowed(verb, first, i, w) {
|
|
119
|
+
for (i = first; i <= argc; i++) {
|
|
120
|
+
w = W[i]
|
|
121
|
+
if (w == "--") return 1
|
|
122
|
+
if (w !~ /^-/ || w == "-") continue
|
|
123
|
+
if ((verb, w) in long_options) continue
|
|
124
|
+
if (verb == "head" || verb == "tail" || verb == "git log") {
|
|
125
|
+
if (w == "-n" || (verb != "git log" && w == "-c")) {
|
|
126
|
+
if (++i > argc || !number(W[i])) return 0
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
if (w ~ /^-n[+-]?[0-9]+$/ || w ~ /^-[0-9]+$/) continue
|
|
130
|
+
}
|
|
131
|
+
if (verb == "grep" || verb == "egrep" || verb == "fgrep") {
|
|
132
|
+
if (w == "-e") { if (++i > argc) return 0; continue }
|
|
133
|
+
if (w == "-A" || w == "-B" || w == "-C") {
|
|
134
|
+
if (++i > argc || !number(W[i])) return 0
|
|
135
|
+
continue
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (verb == "git diff" && w ~ /^-U[0-9]+$/) continue
|
|
139
|
+
if ((verb == "git log" && w ~ /^--(format|pretty)=/) || (verb == "git show" && w ~ /^--format=/)) {
|
|
140
|
+
if (index(w, "%(")) return 0
|
|
141
|
+
continue
|
|
142
|
+
}
|
|
143
|
+
if (verb == "git commit") {
|
|
144
|
+
if (w == "-m") { if (++i > argc) return 0; continue }
|
|
145
|
+
if (w ~ /^-m./) continue
|
|
146
|
+
if (w == "-F") {
|
|
147
|
+
if (++i > argc || W[i] ~ /[$`*?\[{]/ || protected(W[i])) return 0
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (!short_flags(w, short_options[verb])) return 0
|
|
152
|
+
}
|
|
153
|
+
return 1
|
|
154
|
+
}
|
|
155
|
+
function allow_command( verb, first) {
|
|
156
|
+
if (!argc) return
|
|
157
|
+
if (++commands > 64) { bad = 1; return }
|
|
158
|
+
verb = W[1]; first = 2
|
|
159
|
+
# No global git option is exempt, including -C, -c and --no-pager.
|
|
160
|
+
if (verb == "git") { verb = verb " " W[2]; first = 3 }
|
|
161
|
+
if (!(verb in verbs) || !options_allowed(verb, first)) bad = 1
|
|
162
|
+
}
|
|
163
|
+
function command_end() { endword(); allow_command(); delete W; argc = 0 }
|
|
164
|
+
function readonly(s, i, c, c2, sq, dq) {
|
|
165
|
+
for (i = 1; i <= length(s); i++) {
|
|
166
|
+
c = substr(s, i, 1); c2 = substr(s, i + 1, 1)
|
|
167
|
+
if (sq) { if (c == "\047") sq = 0; else word = word c; continue }
|
|
168
|
+
if (c == "\\") { if (c2 != "\n") { word = word c2; inword = 1 }; i++; continue }
|
|
169
|
+
if (c == "\047" && !dq) { sq = inword = 1; continue }
|
|
170
|
+
if (c == "\"") { dq = !dq; inword = 1; continue }
|
|
171
|
+
# Expansions and globs can supply option words the per-verb tables never see.
|
|
172
|
+
if (c == "`" || c == "$") bad = 1
|
|
173
|
+
if (dq) { word = word c; continue }
|
|
174
|
+
# A glob that starts a word, or follows a leading dash, may expand to an option word.
|
|
175
|
+
if ((c == "*" || c == "?" || c == "[") && (word == "" ? !(c == "[" && c2 ~ /[ \t]/) : substr(word, 1, 1) == "-")) bad = 1
|
|
176
|
+
if (c == "#" && !inword) { while (i <= length(s) && substr(s, i, 1) != "\n") i++; c = "\n" }
|
|
177
|
+
if (c == "(" || c == ")" || c == "{" || c == "}") bad = 1
|
|
178
|
+
if (c == ">" || c == "<" || (c == "&" && c2 == ">")) {
|
|
179
|
+
if (inword && word ~ /^[0-9]+$/) { word = ""; inword = 0 } else endword()
|
|
180
|
+
if (redirect) bad = 1
|
|
181
|
+
if (c == "<" && (c2 == "<" || c2 == "(")) bad = 1
|
|
182
|
+
redirect = c == ">" || c == "&" || (c == "<" && c2 == ">")
|
|
183
|
+
if (c == ">" && c2 == "&") redirect = 2
|
|
184
|
+
if (c2 ~ /[><&|]/) { i++; if (substr(s, i + 1, 1) == ">") i++ }
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
if (c ~ /[;|&\n]/) { command_end(); if (redirect) bad = 1; continue }
|
|
188
|
+
if (c ~ /[ \t\r]/) { endword(); continue }
|
|
189
|
+
word = word c; inword = 1
|
|
190
|
+
}
|
|
191
|
+
command_end()
|
|
192
|
+
if (sq || dq || redirect) bad = 1
|
|
193
|
+
return !bad
|
|
194
|
+
}
|
|
195
|
+
BEGIN {
|
|
196
|
+
policy("cat", "nAvetsb", "")
|
|
197
|
+
policy("head", "", ""); policy("tail", "", "")
|
|
198
|
+
policy("wc", "lwcm", ""); policy("ls", "laA1hdRtrF", "")
|
|
199
|
+
policy("grep", "nirRlLcvwxFEHhoqs", "")
|
|
200
|
+
policy("egrep", "nirRlLcvwxFEHhoqs", ""); policy("fgrep", "nirRlLcvwxFEHhoqs", "")
|
|
201
|
+
policy("echo", "neE", "")
|
|
202
|
+
policy("printf", "", ""); policy("test", "", ""); policy("[", "", "")
|
|
203
|
+
policy("true", "", ""); policy("false", "", ""); policy("pwd", "", "")
|
|
204
|
+
policy("git status", "sb", "--short --porcelain")
|
|
205
|
+
policy("git diff", "p", "--stat --name-only --name-status --cached --staged --check --no-color")
|
|
206
|
+
policy("git log", "p", "--oneline --stat --name-only --no-color --follow")
|
|
207
|
+
policy("git show", "p", "--stat --name-only --no-color")
|
|
208
|
+
policy("git add", "Aup", ""); policy("git commit", "aq", "")
|
|
209
|
+
policy("git blame", "", ""); policy("git ls-files", "", "")
|
|
210
|
+
policy("git rev-parse", "", ""); policy("git check-ignore", "", ""); policy("git grep", "", "")
|
|
211
|
+
for (i = 0; i < 16; i++) HEX[substr("0123456789abcdef", i + 1, 1)] = i
|
|
212
|
+
ESC["n"] = 10; ESC["r"] = 13; ESC["t"] = 9; ESC["\\"] = 92; ESC["\047"] = 39; ESC["\""] = 34
|
|
213
|
+
text = ENVIRON["GSW_COMMAND"]
|
|
214
|
+
if (ENVIRON["GSW_MODE"] == "references") { scan(text); scan(unquote(text)); exit 0 }
|
|
215
|
+
n = split(ENVIRON["GSW_PROTECTED"], a, "\n"); for (i = 1; i <= n; i++) protected_paths[a[i]] = 1
|
|
216
|
+
exit readonly(text) ? 0 : 1
|
|
217
|
+
}
|
|
218
|
+
AWK
|
|
219
|
+
candidates_text="$(GSW_COMMAND="$command_text" GSW_MODE=references LC_ALL=C awk "$program" </dev/null)" || parser_failed
|
|
220
|
+
[ -n "$candidates_text" ] || exit 0
|
|
221
|
+
candidates=()
|
|
222
|
+
while IFS= read -r candidate; do candidates[${#candidates[@]}]="$candidate"; done <<<"$candidates_text"
|
|
223
|
+
classifier="$script_directory/cratis-guard-writes.sh"
|
|
224
|
+
[ -f "$classifier" ] || {
|
|
225
|
+
printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: could not check references (write guard is missing).' >&2
|
|
226
|
+
exit 2
|
|
227
|
+
}
|
|
228
|
+
classifier_input="$(jq -nc --arg cwd "$cwd" --args '{cwd:$cwd,tool_input:{file_paths:$ARGS.positional}}' -- "${candidates[@]}")" || parser_failed
|
|
229
|
+
references="$("$BASH" "$classifier" --references <<<"$classifier_input")" || {
|
|
230
|
+
printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: could not check references (write guard failed).' >&2
|
|
231
|
+
exit 2
|
|
232
|
+
}
|
|
233
|
+
[ -n "$references" ] || exit 0
|
|
234
|
+
if GSW_COMMAND="$command_text" GSW_MODE=readonly GSW_PROTECTED="$references" LC_ALL=C awk "$program" </dev/null; then exit 0; fi
|
|
235
|
+
printf "BLOCKED by cratis-guard-shell-writes: protected reference '%s' (cratis-guard-writes). Use the edit/write tools, or report the intended change.\n" "${references%%$'\n'*}" >&2
|
|
236
|
+
exit 2
|
|
@@ -44,13 +44,16 @@ parser_failed() {
|
|
|
44
44
|
# as a command substitution would drop them); a missing, null or false path is empty.
|
|
45
45
|
# The process substitution's exit status does not reach the reading group, and Bash 3.2 (macOS /bin/bash)
|
|
46
46
|
# cannot wait on its PID, so a sentinel field is written only after jq succeeds.
|
|
47
|
-
|
|
47
|
+
reference_mode=0
|
|
48
|
+
[ "${1:-}" != --references ] || reference_mode=1
|
|
49
|
+
cwd="" file="" notebook="" new_content="" new_string="" references="" parser_status=""
|
|
48
50
|
{
|
|
49
51
|
IFS= read -r -d '' cwd
|
|
50
52
|
IFS= read -r -d '' file
|
|
51
53
|
IFS= read -r -d '' notebook
|
|
52
54
|
IFS= read -r -d '' new_content
|
|
53
55
|
IFS= read -r -d '' new_string
|
|
56
|
+
IFS= read -r -d '' references
|
|
54
57
|
IFS= read -r -d '' parser_status
|
|
55
58
|
} < <(jq -j -s '
|
|
56
59
|
def field(path): ([try (path // empty) catch empty] | first // "")
|
|
@@ -60,7 +63,7 @@ cwd="" file="" notebook="" new_content="" new_string="" parser_status=""
|
|
|
60
63
|
# so no field from a later document can stand in for the sentinel.
|
|
61
64
|
if length == 1 then .[0] else error("expected one JSON document") end
|
|
62
65
|
| [field(.cwd), field(.tool_input.file_path), field(.tool_input.notebook_path),
|
|
63
|
-
field(.tool_input.content), field(.tool_input.new_string)]
|
|
66
|
+
field(.tool_input.content), field(.tool_input.new_string), (field(.tool_input.file_paths) | if . == "" then "[]" else . end)]
|
|
64
67
|
| .[] | ., "\u0000"
|
|
65
68
|
' <<<"$input" 2>/dev/null && printf 'ok\0') || parser_failed
|
|
66
69
|
[ "$parser_status" = "ok" ] || parser_failed
|
|
@@ -71,7 +74,7 @@ done
|
|
|
71
74
|
|
|
72
75
|
[ -n "$cwd" ] || cwd="$(hook_repo_root)"
|
|
73
76
|
[ -n "$file" ] || file="$notebook"
|
|
74
|
-
[ -n "$file" ] || exit 0
|
|
77
|
+
[ -n "$file" ] || [ "$reference_mode" = 1 ] || exit 0
|
|
75
78
|
|
|
76
79
|
# dir_of / base_of / relative_to mirror dirname, basename and hook_relpath for the absolute,
|
|
77
80
|
# normalized paths used here. abspath mirrors hook_abspath. All return through REPLY.
|
|
@@ -120,12 +123,6 @@ normalize_target_path() {
|
|
|
120
123
|
REPLY="${normalized:-/}"
|
|
121
124
|
}
|
|
122
125
|
|
|
123
|
-
abspath "$file" "$cwd"
|
|
124
|
-
normalize_target_path "$REPLY"
|
|
125
|
-
file="$REPLY"
|
|
126
|
-
base_of "$file"
|
|
127
|
-
base="$REPLY"
|
|
128
|
-
|
|
129
126
|
block() {
|
|
130
127
|
# Pi can run the bundled script in a consumer checkout; this root is only for diagnostics,
|
|
131
128
|
# so it is looked up only when a write is actually refused.
|
|
@@ -189,9 +186,92 @@ origin_matches() {
|
|
|
189
186
|
return "$matched"
|
|
190
187
|
}
|
|
191
188
|
|
|
189
|
+
# One policy vocabulary for normal Write/Edit and whole-command reference checks.
|
|
190
|
+
manifest_patterns=(package.json Directory.Packages.props global.json NuGet.config yarn.lock package-lock.json pnpm-lock.yaml packages.lock.json)
|
|
191
|
+
environment_patterns=('.env' '.env.*' '*.env')
|
|
192
|
+
control_patterns=('.claude/settings.json' '.claude/settings.local.json' '.mcp.json' '.pi/settings.json' '.pi/extensions/*')
|
|
193
|
+
|
|
194
|
+
# Glob-language intersection, not expansion/eval. A star has an epsilon transition and
|
|
195
|
+
# a character loop. The product automaton accepts iff the two patterns share a spelling.
|
|
196
|
+
# Braces conservatively become a star; bracket classes retain their ordinary meaning.
|
|
197
|
+
IFS= read -r -d '' glob_program <<'AWK' || true
|
|
198
|
+
function tokens(s, side, i, c, j, t, n) {
|
|
199
|
+
s = tolower(s)
|
|
200
|
+
for (i = 1; i <= length(s); i++) {
|
|
201
|
+
c = substr(s, i, 1); t = c
|
|
202
|
+
if (c == "{") { j = index(substr(s, i), "}"); if (j) i += j - 1; t = "*" }
|
|
203
|
+
else if (c == "[") {
|
|
204
|
+
j = index(substr(s, i + 1), "]")
|
|
205
|
+
if (j) { t = substr(s, i, j + 1); i += j; sub(/^\[!/, "[^", t) }
|
|
206
|
+
}
|
|
207
|
+
N[side]++; A[side, N[side]] = t
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function push(i, j, key) { key = i SUBSEP j; if (!(key in seen)) { seen[key] = 1; L[++last] = i; R[last] = j } }
|
|
211
|
+
function accepts(t, c, side) {
|
|
212
|
+
if (side == 1 && c == "/" && (t == "*" || t == "?" || length(t) > 1)) return 0
|
|
213
|
+
return t == "*" || t == "?" || (length(t) > 1 && substr(t, 1, 1) == "[" ? c ~ ("^" t "$") : t == c)
|
|
214
|
+
}
|
|
215
|
+
function compatible(a, b, k, c) {
|
|
216
|
+
if (length(a) == 1 && a != "*" && a != "?") return accepts(b, a, 2)
|
|
217
|
+
if (length(b) == 1 && b != "*" && b != "?") return accepts(a, b, 1)
|
|
218
|
+
for (k = 1; k < 256; k++) { c = sprintf("%c", k); if (accepts(a, c, 1) && accepts(b, c, 2)) return 1 }
|
|
219
|
+
return 0
|
|
220
|
+
}
|
|
221
|
+
BEGIN {
|
|
222
|
+
tokens(ENVIRON["REF_LEFT"], 1); tokens(ENVIRON["REF_RIGHT"], 2); push(1, 1)
|
|
223
|
+
while (next_state < last) {
|
|
224
|
+
if (last > 65536) exit 2
|
|
225
|
+
i = L[++next_state]; j = R[next_state]
|
|
226
|
+
if (i > N[1] && j > N[2]) exit 0
|
|
227
|
+
a = A[1, i]; b = A[2, j]
|
|
228
|
+
if (a == "*") push(i + 1, j)
|
|
229
|
+
if (b == "*") push(i, j + 1)
|
|
230
|
+
if (i <= N[1] && j <= N[2] && compatible(a, b)) push(i + (a != "*"), j + (b != "*"))
|
|
231
|
+
}
|
|
232
|
+
exit 1
|
|
233
|
+
}
|
|
234
|
+
AWK
|
|
235
|
+
|
|
236
|
+
names_match() {
|
|
237
|
+
local value="$1" pattern status LC_ALL=C
|
|
238
|
+
shift
|
|
239
|
+
for pattern in "$@"; do
|
|
240
|
+
if [ "$reference_pattern" = 1 ]; then
|
|
241
|
+
if REF_LEFT="$value" REF_RIGHT="$pattern" LC_ALL=C awk "$glob_program" </dev/null; then return 0
|
|
242
|
+
else status=$?; [ "$status" = 1 ] || parser_failed; fi
|
|
243
|
+
else
|
|
244
|
+
shopt -s nocasematch
|
|
245
|
+
# Intentional policy glob matching, not literal filename equality.
|
|
246
|
+
# shellcheck disable=SC2053
|
|
247
|
+
if [[ "$value" == $pattern ]]; then shopt -u nocasematch; return 0; fi
|
|
248
|
+
shopt -u nocasematch
|
|
249
|
+
fi
|
|
250
|
+
done
|
|
251
|
+
return 1
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
# Directory references include owned descendants, without classifying every ordinary
|
|
255
|
+
# directory as a possible environment file. Normal Write/Edit classification is unchanged.
|
|
256
|
+
control_match() {
|
|
257
|
+
local value="$1" reference_pattern="$reference_pattern" pattern LC_ALL=C
|
|
258
|
+
shift
|
|
259
|
+
if names_match "$value" "$@"; then return 0; fi
|
|
260
|
+
[ "$reference_mode" = 1 ] || return 1
|
|
261
|
+
if [ "$reference_pattern" = 0 ]; then
|
|
262
|
+
shopt -s nocasematch
|
|
263
|
+
for pattern in "$@"; do
|
|
264
|
+
if [[ "$pattern" == "${value%/}/"* ]]; then shopt -u nocasematch; return 0; fi
|
|
265
|
+
done
|
|
266
|
+
shopt -u nocasematch
|
|
267
|
+
return 1
|
|
268
|
+
fi
|
|
269
|
+
names_match "${value%/}/*" "$@"
|
|
270
|
+
}
|
|
271
|
+
|
|
192
272
|
# ── 4. Agent controls and installed managed trees ─────────────────────────────
|
|
193
273
|
agent_control_target() {
|
|
194
|
-
local target="$1" directory policy_root target_rel managed
|
|
274
|
+
local target="$1" directory policy_root target_rel managed pattern
|
|
195
275
|
dir_of "$target"
|
|
196
276
|
directory="$REPLY"
|
|
197
277
|
# Keep the addressed spelling here, even when an adapter directory is a symlink.
|
|
@@ -205,23 +285,21 @@ agent_control_target() {
|
|
|
205
285
|
relative_to "$target" "$policy_root"
|
|
206
286
|
target_rel="$REPLY"
|
|
207
287
|
if [ -f "$policy_root/.cratis/ai.manifest.json" ]; then
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
;;
|
|
224
|
-
esac
|
|
288
|
+
if control_match "$target_rel" '.cratis/ai/*'; then return 0; fi
|
|
289
|
+
if control_match "$target_rel" '.claude/*' '.pi/*'; then
|
|
290
|
+
# Integration paths, not corpus Files, establish adapter ownership.
|
|
291
|
+
managed="$(jq -r '
|
|
292
|
+
(.Integrations // []) | if type != "array" then empty else
|
|
293
|
+
.[] | select(type == "object") | select(.Path | type == "string")
|
|
294
|
+
| if (.Path | explode | any(.[]; . == 0 or . == 9 or . == 10 or . == 13)) then error("invalid integration path") else
|
|
295
|
+
.Path, (if .IsDirectory == true then .Path + "/*" else empty end) end
|
|
296
|
+
end
|
|
297
|
+
' "$policy_root/.cratis/ai.manifest.json" 2>/dev/null)" || parser_failed
|
|
298
|
+
while IFS= read -r pattern; do
|
|
299
|
+
[ -n "$pattern" ] || continue
|
|
300
|
+
if control_match "$target_rel" "$pattern"; then return 0; fi
|
|
301
|
+
done <<<"$managed"
|
|
302
|
+
fi
|
|
225
303
|
else
|
|
226
304
|
# The corpus is authored source in Cratis/AI, not a managed installation.
|
|
227
305
|
repository_origin "$policy_root"
|
|
@@ -229,20 +307,9 @@ agent_control_target() {
|
|
|
229
307
|
return 1
|
|
230
308
|
fi
|
|
231
309
|
fi
|
|
232
|
-
|
|
233
|
-
.claude/settings.json | .claude/settings.local.json | .mcp.json \
|
|
234
|
-
| .pi/settings.json | .pi/extensions/*) return 0 ;;
|
|
235
|
-
esac
|
|
236
|
-
return 1
|
|
310
|
+
control_match "$target_rel" "${control_patterns[@]}"
|
|
237
311
|
}
|
|
238
312
|
|
|
239
|
-
physical_target_path "$file" || physical_file=""
|
|
240
|
-
if agent_control_target "$file" || { [ -n "$physical_file" ] && agent_control_target "$physical_file"; }; then
|
|
241
|
-
block \
|
|
242
|
-
"This target controls the agent's permissions or extensions, or belongs to an installed managed corpus/adapter tree. Agent Write/Edit calls may not alter their own controls or managed instructions." \
|
|
243
|
-
"Instead: report the intended change. Use 'cratis ai update' for managed files, or let a person change settings. An explicitly authorized protected write requires CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 in the harness environment. Do not retry through a shell write."
|
|
244
|
-
fi
|
|
245
|
-
|
|
246
313
|
# ── 1. Generated files ────────────────────────────────────────────────────────
|
|
247
314
|
# The marker must be a real header: a comment opener at the start of one of the first few lines.
|
|
248
315
|
# Merely *mentioning* the string — documentation, a rule file, this corpus — is not a match.
|
|
@@ -259,24 +326,6 @@ first_lines_carry_marker() {
|
|
|
259
326
|
return 1
|
|
260
327
|
}
|
|
261
328
|
|
|
262
|
-
# The cheap in-shell header test runs first; grep -I then confirms the file is text, as before.
|
|
263
|
-
if [ -f "$file" ] \
|
|
264
|
-
&& first_lines_carry_marker 2>/dev/null <"$file" \
|
|
265
|
-
&& LC_ALL=C grep -Iq . "$file" 2>/dev/null; then
|
|
266
|
-
block \
|
|
267
|
-
"This file is generated output (its header marks it as generated by Cratis). Rule 15 [contract] in .cratis/ai/rules/general.md: never edit a generated file — the next build overwrites it." \
|
|
268
|
-
"Instead: change the C# source it is generated from (the [Command] / [ReadModel] record) and rebuild with 'dotnet build -c Debug' to regenerate the proxy."
|
|
269
|
-
fi
|
|
270
|
-
|
|
271
|
-
# The same guard for authoring a *new* file that pretends to be generated output.
|
|
272
|
-
[ -n "$new_content" ] || new_content="$new_string"
|
|
273
|
-
if [ -n "$new_content" ] \
|
|
274
|
-
&& first_lines_carry_marker <<<"$new_content"; then
|
|
275
|
-
block \
|
|
276
|
-
"The content being written opens with a Cratis generated-file header. Proxies are produced by the Cratis proxy generator, never hand-written." \
|
|
277
|
-
"Instead: write the C# source and run 'dotnet build -c Debug' to generate the proxy."
|
|
278
|
-
fi
|
|
279
|
-
|
|
280
329
|
# ── 2. Dependency manifests, lockfiles, SDK and NuGet configuration ───────────
|
|
281
330
|
manifest_writes_allowed() {
|
|
282
331
|
local setting="" directory policy_root start="$PWD"
|
|
@@ -307,23 +356,71 @@ manifest_writes_allowed() {
|
|
|
307
356
|
origin_matches '^(https://github\.com/|git@github\.com:|ssh://git@github\.com(:[0-9]+)?/)cratis/[a-z0-9_.-]+/?$'
|
|
308
357
|
}
|
|
309
358
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
359
|
+
# Return the category, leaving normal Write/Edit diagnostics unchanged below.
|
|
360
|
+
classify_file() {
|
|
361
|
+
local reference_pattern="${2:-0}"
|
|
362
|
+
abspath "$1" "$cwd"; normalize_target_path "$REPLY"; file="$REPLY"
|
|
363
|
+
base_of "$file"; base="$REPLY"
|
|
364
|
+
physical_target_path "$file" || physical_file=""
|
|
365
|
+
if agent_control_target "$file" || { [ -n "$physical_file" ] && agent_control_target "$physical_file"; }; then
|
|
366
|
+
classification=controls; return 0
|
|
367
|
+
fi
|
|
368
|
+
if [ -f "$file" ] && first_lines_carry_marker 2>/dev/null <"$file" && LC_ALL=C grep -Iq . "$file" 2>/dev/null; then
|
|
369
|
+
classification=generated; return 0
|
|
370
|
+
fi
|
|
371
|
+
if [ -n "$new_content" ] && first_lines_carry_marker <<<"$new_content"; then classification=content; return 0; fi
|
|
372
|
+
if names_match "$base" "${manifest_patterns[@]}"; then
|
|
373
|
+
if manifest_writes_allowed; then return 1; fi
|
|
374
|
+
classification=manifest; return 0
|
|
375
|
+
fi
|
|
376
|
+
if names_match "$base" "${environment_patterns[@]}"; then classification=environment; return 0; fi
|
|
377
|
+
return 1
|
|
378
|
+
}
|
|
319
379
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
380
|
+
if [ "$reference_mode" = 1 ]; then
|
|
381
|
+
candidates=() parser_status=""
|
|
382
|
+
while IFS= read -r -d '' candidate; do candidates[${#candidates[@]}]="$candidate"; done < <(
|
|
383
|
+
jq -j 'if type == "array" and length <= 256 and all(.[]; type == "string" and (explode | all(.[]; . != 0 and . != 9 and . != 10 and . != 13)))
|
|
384
|
+
then .[], "ok" else error("invalid reference candidates") end | ., "\u0000"' <<<"$references" 2>/dev/null
|
|
385
|
+
)
|
|
386
|
+
[ "${#candidates[@]}" -gt 0 ] || parser_failed
|
|
387
|
+
last=$((${#candidates[@]} - 1))
|
|
388
|
+
[ "${candidates[$last]}" = ok ] || parser_failed
|
|
389
|
+
[ "$last" -gt 0 ] || exit 0
|
|
390
|
+
unset 'candidates[last]'
|
|
391
|
+
new_content=""
|
|
392
|
+
for candidate in "${candidates[@]}"; do
|
|
393
|
+
reference_pattern=0
|
|
394
|
+
case "$candidate" in *'*'* | *'?'* | *'['* | *'{'*) reference_pattern=1 ;; esac
|
|
395
|
+
if classify_file "$candidate" "$reference_pattern"; then printf '%s\n' "$candidate"; continue; fi
|
|
396
|
+
# Existing generated files can have arbitrary names; inspect actual glob matches too.
|
|
397
|
+
if [ "$reference_pattern" = 1 ]; then
|
|
398
|
+
count=0
|
|
399
|
+
while IFS= read -r expanded; do
|
|
400
|
+
count=$((count + 1)); [ "$count" -le 64 ] || parser_failed
|
|
401
|
+
if classify_file "$expanded"; then printf '%s\n' "$candidate"; break; fi
|
|
402
|
+
done < <(abspath "$candidate" "$cwd"; compgen -G "$REPLY" || true)
|
|
403
|
+
fi
|
|
404
|
+
done
|
|
405
|
+
exit 0
|
|
406
|
+
fi
|
|
328
407
|
|
|
329
|
-
|
|
408
|
+
[ -n "$new_content" ] || new_content="$new_string"
|
|
409
|
+
if ! classify_file "$file"; then exit 0; fi
|
|
410
|
+
case "$classification" in
|
|
411
|
+
controls) block \
|
|
412
|
+
"This target controls the agent's permissions or extensions, or belongs to an installed managed corpus/adapter tree. Agent Write/Edit calls may not alter their own controls or managed instructions." \
|
|
413
|
+
"Instead: report the intended change. Use 'cratis ai update' for managed files, or let a person change settings. An explicitly authorized protected write requires CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 in the harness environment. Do not retry through a shell write." ;;
|
|
414
|
+
generated) block \
|
|
415
|
+
"This file is generated output (its header marks it as generated by Cratis). Rule 15 [contract] in .cratis/ai/rules/general.md: never edit a generated file — the next build overwrites it." \
|
|
416
|
+
"Instead: change the C# source it is generated from (the [Command] / [ReadModel] record) and rebuild with 'dotnet build -c Debug' to regenerate the proxy." ;;
|
|
417
|
+
content) block \
|
|
418
|
+
"The content being written opens with a Cratis generated-file header. Proxies are produced by the Cratis proxy generator, never hand-written." \
|
|
419
|
+
"Instead: write the C# source and run 'dotnet build -c Debug' to generate the proxy." ;;
|
|
420
|
+
manifest) block \
|
|
421
|
+
"'$base' is a dependency manifest / lockfile / SDK or NuGet configuration file. .cratis/ai/rules/general.md (Source-of-Truth Discipline): don't change these unless explicitly asked." \
|
|
422
|
+
"To allow dependency updates for this repository, set allowDependencyManifestWrites to true in .cratis/ai.json. If the user explicitly asked for this change, re-run the tool call with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported. Otherwise take the dependency as given and solve the problem in source." ;;
|
|
423
|
+
environment) block \
|
|
424
|
+
"'$base' is an environment file and normally holds secrets. Hooks block writing it so credentials are never authored, rewritten, or echoed by an agent." \
|
|
425
|
+
"Instead: tell the user exactly which variable to set and let them edit the file. If they explicitly asked you to write it, re-run with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported." ;;
|
|
426
|
+
esac
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"type": "command",
|
|
23
23
|
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-secrets.sh"
|
|
24
24
|
},
|
|
25
|
+
{
|
|
26
|
+
"type": "command",
|
|
27
|
+
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh"
|
|
28
|
+
},
|
|
25
29
|
{
|
|
26
30
|
"type": "command",
|
|
27
31
|
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-pr-body.sh"
|