@cratis/pi 7.170.3 → 7.170.4
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.
|
@@ -290,7 +290,34 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
|
|
|
290
290
|
|
|
291
291
|
For agent controls, report the intended change rather than rewriting permissions or hooks.
|
|
292
292
|
A person edits settings; `cratis ai update` replaces managed files using the CLI's filesystem
|
|
293
|
-
operations, not agent Write/Edit calls.
|
|
293
|
+
operations, not agent Write/Edit calls. Before reference classification, the shell guard admits
|
|
294
|
+
only these standalone install/repair operations (Node must be available):
|
|
295
|
+
|
|
296
|
+
- Literal `cratis ai init`, `cratis ai update` or `cratis ai restore`, optionally followed only by
|
|
297
|
+
`--force` or `--dry-run`. Other arguments receive no exception. This invokes the CLI rather than
|
|
298
|
+
granting file-content writes.
|
|
299
|
+
- `ln -s`, `ln -sf` or `ln -sfn` with exactly a target and a link. The link must be below `.pi/`,
|
|
300
|
+
`.claude/`, `.cursor/`, `.opencode/` or `.github/` in the current repository. Resolve the target
|
|
301
|
+
relative to the link's directory: both its lexical path and its physical path (existing ancestors
|
|
302
|
+
resolved, including symlinks) must stay inside that repository's `.cratis/ai/`. The link's parent
|
|
303
|
+
must physically stay in its managed folder. A present `.cratis/ai.manifest.json` must contain an
|
|
304
|
+
exact `Integrations` link entry (`Path` and a string `Target`); missing/invalid entries or invalid
|
|
305
|
+
JSON refuse the repair. A missing manifest also refuses every link repair, even if the corpus
|
|
306
|
+
tree already exists; use the standalone installer commands instead. Both addressed and physical
|
|
307
|
+
link names are checked against the write guard's own `control_patterns`, read without executing
|
|
308
|
+
that guard. Hook, agent, guard, extension and workflow trees cannot be repaired with `ln`, even
|
|
309
|
+
when a manifest lists the link. Recognized repairs that fail validation are blocked outright,
|
|
310
|
+
rather than falling back to an uninstalled repository's more permissive reference policy.
|
|
311
|
+
Only links whose lexical or physical target lands in the corpus enter these repair checks.
|
|
312
|
+
Ordinary non-corpus links and calls outside Git retain the original reference policy; a
|
|
313
|
+
symlinked link parent or target alias cannot disguise a physical corpus target.
|
|
314
|
+
- These exceptions accept simple whole-word quoting, but no `cd` prefix, chaining, pipes,
|
|
315
|
+
redirects, substitutions, expansions, escapes, comments, globs or multiline shell constructs.
|
|
316
|
+
Existing directories cannot be replaced; an existing symlink to a directory requires `-sfn`
|
|
317
|
+
so `ln` cannot follow it and write into its target. File Write/Edit calls, including writes
|
|
318
|
+
through repaired links, remain protected as before.
|
|
319
|
+
|
|
320
|
+
All other commands retain the existing policy. The shell-write guard scans the **whole command text**
|
|
294
321
|
for protected references, including nested strings, heredoc bodies and option values. It
|
|
295
322
|
removes simple quoting/escapes, checks case-insensitive spellings, and asks the write guard's
|
|
296
323
|
`--references` batch mode to classify candidate paths relative to the hook cwd. Original
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
// Non-applicable commands fall back to reference checks; recognized invalid repairs fail closed.
|
|
5
|
+
import assert from 'node:assert/strict';
|
|
6
|
+
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs';
|
|
8
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
9
|
+
|
|
10
|
+
const managedFolders = ['.pi', '.claude', '.cursor', '.opencode', '.github'];
|
|
11
|
+
|
|
12
|
+
function literalWords(command) {
|
|
13
|
+
// No shell operators, expansions, escapes, comments, globs or multiline constructs, even in quotes.
|
|
14
|
+
if (/[\x00-\x1f\x7f$`\\;|&<>(){}*?!#~\[\]]/.test(command)) return [];
|
|
15
|
+
// Require whitespace between whole words: do not interpret concatenated quote fragments.
|
|
16
|
+
if (!/^ *(?:(?:'[^']*'|"[^"]*"|[^\s'"]+)(?: +|$))*$/.test(command)) return [];
|
|
17
|
+
return command.match(/'[^']*'|"[^"]*"|[^\s'"]+/g) ?? [];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function unquote(word) {
|
|
21
|
+
return /^["']/.test(word) ? word.slice(1, -1) : word;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function inside(path, directory) {
|
|
25
|
+
const suffix = relative(directory, path);
|
|
26
|
+
if (isAbsolute(suffix)) return false;
|
|
27
|
+
return !['', '..'].includes(suffix.split(sep)[0]);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function addressedTarget(link, target) {
|
|
31
|
+
return isAbsolute(target) ? target : `${dirname(link)}/${target}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function physicalPath(path, depth = 0) {
|
|
35
|
+
if (depth >= 40) throw new Error('Symlink resolution limit');
|
|
36
|
+
// Follow each symlink before '..', even when its destination does not exist yet.
|
|
37
|
+
let physical = sep;
|
|
38
|
+
for (const component of path.split(sep).filter(Boolean)) {
|
|
39
|
+
const candidate = resolve(physical, component);
|
|
40
|
+
physical = lstatIfPresent(candidate)?.isSymbolicLink()
|
|
41
|
+
? physicalPath(addressedTarget(candidate, readlinkSync(candidate)), depth + 1)
|
|
42
|
+
: candidate;
|
|
43
|
+
}
|
|
44
|
+
return physical;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function lstatIfPresent(path) {
|
|
48
|
+
try { return lstatSync(path); }
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error.code === 'ENOENT') return undefined;
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function controlPatterns() {
|
|
56
|
+
// Read the write guard's literal policy, never execute/source it or maintain a second copy.
|
|
57
|
+
const source = readFileSync(new URL('./cratis-guard-writes.sh', import.meta.url), 'utf8');
|
|
58
|
+
const definition = source.match(/^control_patterns=\((.*)\)$/m)?.[1] ?? '';
|
|
59
|
+
const words = definition.match(/'[a-z0-9_./*-]+'/g) ?? [];
|
|
60
|
+
if (!words.length || words.join(' ') !== definition) throw new Error('Unsupported control policy');
|
|
61
|
+
return words.map(unquote);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function matchesControl(name, pattern) {
|
|
65
|
+
const expression = pattern.split('*').map(part => part.replaceAll('.', '\\.')).join('.*');
|
|
66
|
+
return new RegExp(`^${expression}(?:/.*)?$`).test(name) || pattern.startsWith(`${name}/`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function controlLink(root, link) {
|
|
70
|
+
const names = [link, physicalPath(link)].map(path => relative(root, path).toLowerCase());
|
|
71
|
+
const patterns = controlPatterns();
|
|
72
|
+
// Repairs are also forbidden in executable/agent-definition trees, even if a manifest lists them.
|
|
73
|
+
const executableTree = /(?:^|\/)(?:hooks|agents|guards|extensions|workflows)(?:\/|$)/;
|
|
74
|
+
return names.some(name => executableTree.test(name) || patterns.some(pattern => matchesControl(name, pattern)));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function managedEntry(root, link) {
|
|
78
|
+
const manifest = resolve(root, '.cratis/ai.manifest.json');
|
|
79
|
+
if (!existsSync(manifest)) return false;
|
|
80
|
+
const { Integrations } = JSON.parse(readFileSync(manifest, 'utf8'));
|
|
81
|
+
return Array.isArray(Integrations) && Integrations.some(entry =>
|
|
82
|
+
entry?.Path === relative(root, link) && typeof entry.Target === 'string');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function linkOperands(words) {
|
|
86
|
+
if (words.length !== 4) return undefined;
|
|
87
|
+
if (!/^ln -(?:s|sf|sfn)$/.test(words.slice(0, 2).join(' '))) return undefined;
|
|
88
|
+
const [target, name] = words.slice(2).map(unquote);
|
|
89
|
+
if ([target, name].some(operand => !operand || operand.startsWith('-'))) return undefined;
|
|
90
|
+
if (unsafeLinkName(name)) return undefined;
|
|
91
|
+
return { target, name, flag: words[1] };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function unsafeLinkName(name) {
|
|
95
|
+
// A trailing slash or '/.' forces directory traversal even with ln -n.
|
|
96
|
+
return name.endsWith('/') || basename(name) === '.' || name.split('/').includes('..');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parentInFolder(root, link, folder) {
|
|
100
|
+
const parent = physicalPath(dirname(link));
|
|
101
|
+
const managedFolder = resolve(realpathSync(root), folder);
|
|
102
|
+
return parent === managedFolder || inside(parent, managedFolder);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function atOrInside(path, directory) {
|
|
106
|
+
return path === directory || inside(path, directory);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function corpusRepair(root, link, target) {
|
|
110
|
+
const addressed = addressedTarget(link, target);
|
|
111
|
+
const corpus = resolve(root, '.cratis/ai');
|
|
112
|
+
return atOrInside(resolve(addressed), corpus) || atOrInside(physicalPath(addressed), corpus);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function corpusTarget(root, link, target) {
|
|
116
|
+
const addressed = addressedTarget(link, target);
|
|
117
|
+
if (!inside(resolve(addressed), resolve(root, '.cratis/ai'))) return false;
|
|
118
|
+
return inside(physicalPath(addressed), resolve(root, '.cratis/ai'));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function replaceableDestination(link, flag) {
|
|
122
|
+
const existing = lstatIfPresent(link);
|
|
123
|
+
if (existing?.isDirectory()) return false;
|
|
124
|
+
if (!existing?.isSymbolicLink()) return true;
|
|
125
|
+
if (!existsSync(link)) return true;
|
|
126
|
+
// Without -n, ln follows a destination symlink to a directory and writes inside its target.
|
|
127
|
+
return !statSync(link).isDirectory() || flag === '-sfn';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function repositoryRoot(cwd) {
|
|
131
|
+
try {
|
|
132
|
+
const repository = execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
133
|
+
return realpathSync(repository);
|
|
134
|
+
} catch { return undefined; }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function validateRepair(root, link, folder, { target, flag }) {
|
|
138
|
+
try {
|
|
139
|
+
assert(!controlLink(root, link), 'Agent control link');
|
|
140
|
+
assert(managedEntry(root, link), 'Unmanaged link');
|
|
141
|
+
assert(parentInFolder(root, link, folder), 'Redirected link parent');
|
|
142
|
+
assert(corpusTarget(root, link, target), 'Non-corpus target');
|
|
143
|
+
assert(replaceableDestination(link, flag), 'Directory destination');
|
|
144
|
+
} catch {
|
|
145
|
+
// Once identified as a corpus repair, unreadable/invalid policy or paths must not permit fallback.
|
|
146
|
+
assert.fail('Corpus repair validation failed');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function repairLink(cwd, words) {
|
|
151
|
+
const operands = linkOperands(words);
|
|
152
|
+
if (!operands) return false;
|
|
153
|
+
const root = repositoryRoot(cwd);
|
|
154
|
+
if (!root) return false;
|
|
155
|
+
// Git reports the physical root on macOS; align the cwd alias without resolving the link itself.
|
|
156
|
+
const link = resolve(realpathSync(cwd), operands.name);
|
|
157
|
+
const folder = managedFolders.find(folder => inside(link, resolve(root, folder)));
|
|
158
|
+
if (!folder) return false;
|
|
159
|
+
if (!corpusRepair(root, link, operands.target)) return false;
|
|
160
|
+
validateRepair(root, link, folder, operands);
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function admitted(cwd, command) {
|
|
165
|
+
const words = literalWords(command);
|
|
166
|
+
if (['cratis ai init', 'cratis ai update', 'cratis ai restore'].includes(words.slice(0, 3).join(' '))) {
|
|
167
|
+
assert(words.slice(3).every(word => ['--force', '--dry-run'].includes(word)), 'Unsupported installer arguments');
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
return repairLink(cwd, words);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
try { process.exitCode = admitted(process.argv[2], process.argv[3]) ? 0 : 1; }
|
|
174
|
+
catch (error) { process.exitCode = error instanceof assert.AssertionError ? 2 : 1; }
|
|
@@ -33,6 +33,21 @@ cwd="" command_text="" parser_status=""
|
|
|
33
33
|
cwd="${cwd:-$PWD}"
|
|
34
34
|
[ "${#command_text}" -le 131072 ] || parser_failed
|
|
35
35
|
|
|
36
|
+
# Only standalone corpus installer/repair invocations may bypass reference classification.
|
|
37
|
+
# The helper accepts a deliberately smaller language than the shell, never shell evaluation.
|
|
38
|
+
if [[ "$command_text" =~ ^[[:space:]]*(cratis|ln)[[:space:]] ]] && command -v node >/dev/null 2>&1; then
|
|
39
|
+
repair_status=0
|
|
40
|
+
node "$script_directory/cratis-guard-shell-writes-repair.mjs" "$cwd" "$command_text" || repair_status=$?
|
|
41
|
+
case "$repair_status" in
|
|
42
|
+
0) exit 0 ;;
|
|
43
|
+
1) ;; # Not an installer/repair exception: preserve the ordinary reference policy.
|
|
44
|
+
*)
|
|
45
|
+
printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: managed link repair was refused; use the installer or report the intended change.' >&2
|
|
46
|
+
exit 2
|
|
47
|
+
;;
|
|
48
|
+
esac
|
|
49
|
+
fi
|
|
50
|
+
|
|
36
51
|
IFS= read -r -d '' program <<'AWK' || true
|
|
37
52
|
function candidate(s) {
|
|
38
53
|
if (checking_marker) return
|