pi-odd-worktree 3.2.0 → 3.3.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/extensions/odd-worktree-tools.ts +33 -3
- package/lib/bash-activity.js +405 -32
- package/lib/bash-inline-script.js +314 -0
- package/lib/skill-read-guard.js +397 -0
- package/package.json +1 -1
- package/tools/bash-activity.test.js +400 -35
- package/tools/package-surface.test.js +15 -1
- package/tools/skill-read-guard.test.js +316 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The activity an INLINE script names: the program an interpreter is handed on its command
|
|
3
|
+
// line (`python3 -c '…'`, `node -e '…'`, `python3 - <<'PY' … PY`), read from its own text.
|
|
4
|
+
//
|
|
5
|
+
// A script is code, and code can do anything, so this reader answers only what the text
|
|
6
|
+
// itself proves and refuses everything else:
|
|
7
|
+
// * `destructive` — the text calls a deleting function (`os.remove`, `shutil.rmtree`,
|
|
8
|
+
// `fs.rmSync`, `.unlink(`). The call provably deletes whatever else it does.
|
|
9
|
+
// * `preparing` — the text writes, creates, renames or copies a file; the same
|
|
10
|
+
// build-up a `cat > file` already names.
|
|
11
|
+
// * `exploring` — the text imports only modules from a short list of read-only
|
|
12
|
+
// standard libraries, writes nothing and runs nothing.
|
|
13
|
+
// * `undefined` — anything else: a module outside the list (it runs code of its own),
|
|
14
|
+
// a shell-out, a network call, `eval`, a dynamic import, a flag this reader does not
|
|
15
|
+
// know. The card stays generic, as it always did.
|
|
16
|
+
//
|
|
17
|
+
// Pure: no filesystem, no process, no Pi. It reads a list of words and a string.
|
|
18
|
+
|
|
19
|
+
const PYTHON_PROGRAM = /^python(3(\.\d+)?)?$/;
|
|
20
|
+
const NODE_PROGRAM = /^nodejs?$/;
|
|
21
|
+
|
|
22
|
+
// Interpreter flags that change nothing about which code runs. A flag outside these lists
|
|
23
|
+
// ends the reading: `-m` runs a module, `-r`/`--import` load code first.
|
|
24
|
+
const PYTHON_PLAIN_FLAGS = new Set(['-I', '-B', '-u', '-E', '-S', '-s', '-O', '-OO', '-q', '-b', '-bb', '-d', '-v']);
|
|
25
|
+
const NODE_PLAIN_FLAGS = new Set([
|
|
26
|
+
'--no-warnings', '--no-deprecation', '--experimental-strip-types', '--experimental-vm-modules',
|
|
27
|
+
'--experimental-default-type=module', '--input-type=module', '--input-type=commonjs', '--enable-source-maps',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
// Standard-library modules that only read: parsing, text, hashing, dates and path math. A
|
|
31
|
+
// module outside the list may run any code on import, so a script that needs one stays
|
|
32
|
+
// generic.
|
|
33
|
+
const PYTHON_MODULES = new Set([
|
|
34
|
+
'json', 'sys', 're', 'os', 'pathlib', 'tomllib', 'collections', 'itertools', 'functools', 'textwrap',
|
|
35
|
+
'datetime', 'time', 'math', 'hashlib', 'base64', 'csv', 'glob', 'fnmatch', 'io', 'string', 'typing',
|
|
36
|
+
'operator', 'statistics', 'difflib', 'unicodedata', 'copy', 'enum', 'dataclasses', 'argparse',
|
|
37
|
+
'configparser', 'plistlib', 'struct', 'binascii', 'html', 'shlex', 'pprint', 'posixpath', 'uuid', 'yaml', 'toml', 'PIL',
|
|
38
|
+
]);
|
|
39
|
+
const NODE_MODULES = new Set([
|
|
40
|
+
'fs', 'fs/promises', 'path', 'os', 'util', 'url', 'assert', 'assert/strict', 'crypto', 'readline',
|
|
41
|
+
'stream', 'zlib', 'events', 'buffer', 'string_decoder', 'querystring', 'perf_hooks', 'timers',
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
// What a script may not contain whatever it imports: running another program, evaluating
|
|
45
|
+
// text as code, loading code by name, talking to the network or a process, or hiding a name
|
|
46
|
+
// behind an alias. Read on the whole text, strings included: a script that merely MENTIONS one
|
|
47
|
+
// of these stays generic, which is the safe side.
|
|
48
|
+
const PYTHON_UNREADABLE = /\b(os\.(system|popen|exec\w*|spawn\w*|fork|forkpty|kill|killpg|putenv|startfile)|eval|exec|compile|__import__|importlib|getattr|setattr|globals|locals|breakpoint|signal|webbrowser|pty)\b|\bsubprocess\b|\bsocket\b|\bimport\s+\*|\bimport\s+(os|shutil)\s+as\b|,\s*(os|shutil)\s+as\b/;
|
|
49
|
+
const NODE_UNREADABLE = /\b(eval|Function|fetch|XMLHttpRequest|WebSocket|process\.(kill|binding|dlopen|chdir))\b|\.constructor\s*\(/;
|
|
50
|
+
|
|
51
|
+
// What the CODE of a script calls, read with every string literal and comment emptied, so a
|
|
52
|
+
// script that only prints the word is not a script that does it.
|
|
53
|
+
// A bare name counts only when it is called; a property access (`os.remove`, `fs.rmSync`) counts
|
|
54
|
+
// as written, because it may be aliased and called later.
|
|
55
|
+
const PYTHON_DELETES = /\bos\.(remove|unlink|rmdir|removedirs)\b|\bshutil\.rmtree\b|\b(rmtree|unlink|removedirs)\s*\(|\.(unlink|rmdir)\s*\(/;
|
|
56
|
+
const NODE_DELETES = /\.(rmSync|rmdirSync|unlinkSync)\b|\b(rmSync|rmdirSync|unlinkSync|rimraf)\s*\(|\.(rm|rmdir|unlink)\s*\(/;
|
|
57
|
+
|
|
58
|
+
const PYTHON_WRITES = /\.(write|writelines|write_text|write_bytes|touch|mkdir|rename|chmod|chown|symlink_to|hardlink_to|save|to_csv|to_json)\s*\(|\b(makedirs|os\.(rename|replace|mkdir|chmod|chown|symlink|link|truncate|utime)|shutil\.\w+)\b|\b(json|pickle|yaml|toml|plistlib)\.dump\s*\(/;
|
|
59
|
+
const NODE_WRITES = /\b(writeFile\w*|appendFile\w*|createWriteStream|mkdir\w*|copyFile\w*|cp\w*|rename\w*|chmod\w*|chown\w*|symlink\w*|link\w*|truncate\w*|utimes\w*|writeSync|write\w*)\s*\(|\.write\s*\(|\bWriteStream\b/;
|
|
60
|
+
|
|
61
|
+
// Names a script may take out of the filesystem module by destructuring: reads only.
|
|
62
|
+
const NODE_FS_READ_NAMES = new Set([
|
|
63
|
+
'readFileSync', 'readFile', 'readdirSync', 'readdir', 'existsSync', 'statSync', 'stat', 'lstatSync', 'lstat',
|
|
64
|
+
'readlinkSync', 'realpathSync', 'access', 'accessSync', 'promises',
|
|
65
|
+
]);
|
|
66
|
+
const PYTHON_OS_READ_NAMES = new Set(['path', 'environ', 'getcwd', 'listdir', 'walk', 'scandir', 'stat', 'sep', 'linesep', 'name']);
|
|
67
|
+
|
|
68
|
+
// A print is not a write: the two standard streams are what a read-only script talks to.
|
|
69
|
+
const PRINTING = /\bsys\.(stdout|stderr)\.write\s*\(|\bprocess\.(stdout|stderr)\.write\s*\(/g;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The text with the content of every string literal and comment emptied. An f-string and a
|
|
73
|
+
* template literal keep theirs: what sits inside their braces is code.
|
|
74
|
+
*/
|
|
75
|
+
function codeOf(language, text, keepModes = false) {
|
|
76
|
+
let out = '';
|
|
77
|
+
let index = 0;
|
|
78
|
+
while (index < text.length) {
|
|
79
|
+
const char = text[index];
|
|
80
|
+
if (language === 'python' && char === '#') {
|
|
81
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (language === 'node' && char === '/' && text[index + 1] === '/') {
|
|
85
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (language === 'node' && char === '/' && text[index + 1] === '*') {
|
|
89
|
+
const end = text.indexOf('*/', index + 2);
|
|
90
|
+
index = end < 0 ? text.length : end + 2;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
94
|
+
const triple = language === 'python' && text.startsWith(char.repeat(3), index);
|
|
95
|
+
const quote = triple ? char.repeat(3) : char;
|
|
96
|
+
let end = index + quote.length;
|
|
97
|
+
while (end < text.length && !text.startsWith(quote, end)) end += text[end] === '\\' ? 2 : 1;
|
|
98
|
+
const body = text.slice(index + quote.length, end);
|
|
99
|
+
// A short mode-shaped string (`'w'`, `'r+'`) is kept on request: it is what `open` reads.
|
|
100
|
+
const keep = char === '`' || (language === 'python' && /(^|[^a-z0-9_])(rf|fr|f)$/i.test(out.slice(-3))) || (keepModes && /^[rwxabt+U]{1,4}$/.test(body));
|
|
101
|
+
out += quote + (keep ? body : '') + quote;
|
|
102
|
+
index = end + quote.length;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
out += char;
|
|
106
|
+
index += 1;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The index of the parenthesis that closes the call whose opening one is at `open`. */
|
|
112
|
+
function callEnd(text, open) {
|
|
113
|
+
let depth = 0;
|
|
114
|
+
let quote;
|
|
115
|
+
for (let index = open; index < text.length; index += 1) {
|
|
116
|
+
const char = text[index];
|
|
117
|
+
if (quote !== undefined) {
|
|
118
|
+
if (char === '\\') index += 1;
|
|
119
|
+
else if (char === quote) quote = undefined;
|
|
120
|
+
} else if (char === '"' || char === "'") quote = char;
|
|
121
|
+
else if (char === '(') depth += 1;
|
|
122
|
+
else if (char === ')' && (depth -= 1) === 0) return index;
|
|
123
|
+
}
|
|
124
|
+
return text.length;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The top-level, comma-separated arguments of the call whose opening parenthesis is at `open`. */
|
|
128
|
+
function callArguments(text, open) {
|
|
129
|
+
const end = callEnd(text, open);
|
|
130
|
+
const args = [];
|
|
131
|
+
let depth = 0;
|
|
132
|
+
let quote;
|
|
133
|
+
let current = '';
|
|
134
|
+
for (let index = open + 1; index < end; index += 1) {
|
|
135
|
+
const char = text[index];
|
|
136
|
+
if (quote !== undefined) {
|
|
137
|
+
current += char;
|
|
138
|
+
if (char === '\\') {
|
|
139
|
+
current += text[index + 1] === undefined ? '' : text[index + 1];
|
|
140
|
+
index += 1;
|
|
141
|
+
} else if (char === quote) quote = undefined;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === '"' || char === "'") quote = char;
|
|
145
|
+
if (char === '(' || char === '[' || char === '{') depth += 1;
|
|
146
|
+
if (char === ')' || char === ']' || char === '}') depth -= 1;
|
|
147
|
+
if (char === ',' && depth === 0) {
|
|
148
|
+
args.push(current.trim());
|
|
149
|
+
current = '';
|
|
150
|
+
} else current += char;
|
|
151
|
+
}
|
|
152
|
+
if (current.trim() !== '') args.push(current.trim());
|
|
153
|
+
return args;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A string literal's text, or undefined when the argument is anything else. */
|
|
157
|
+
function literal(arg) {
|
|
158
|
+
const found = /^[a-zA-Z]{0,2}(['"])([\s\S]*)\1$/.exec(arg === undefined ? '' : arg);
|
|
159
|
+
return found === null ? undefined : found[2];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Whether the text opens a file for writing: a mode that creates, truncates, appends or
|
|
164
|
+
* updates, or a mode this reader cannot see. Nested calls in the path (`open(Path('a'), 'w')`)
|
|
165
|
+
* and `mode=` are read as arguments, not as a pattern.
|
|
166
|
+
*/
|
|
167
|
+
function pythonOpensForWrite(text) {
|
|
168
|
+
for (const found of text.matchAll(/(\.?)\bopen\s*\(/g)) {
|
|
169
|
+
const args = callArguments(text, found.index + found[0].length - 1);
|
|
170
|
+
if (found[1] === '.') {
|
|
171
|
+
// A method such as `Path.open('w')` or `Path.open(mode='w')`: a mode-shaped first
|
|
172
|
+
// argument, or `mode=`, is the mode.
|
|
173
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
174
|
+
const mode = literal(keyword === undefined ? args[0] : keyword.replace(/^mode\s*=\s*/, ''));
|
|
175
|
+
if (mode !== undefined && /^[rwxabt+U]+$/.test(mode) && /[wax+]/.test(mode)) return true;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
179
|
+
const modeArg = keyword === undefined ? args[1] : keyword.replace(/^mode\s*=\s*/, '');
|
|
180
|
+
if (modeArg === undefined) continue;
|
|
181
|
+
const mode = literal(modeArg);
|
|
182
|
+
if (mode === undefined || /[wax+]/.test(mode)) return true;
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The same for `fs.openSync(path, flags)`: a flag that writes, or one this reader cannot see. */
|
|
188
|
+
function nodeOpensForWrite(text) {
|
|
189
|
+
for (const found of text.matchAll(/\bopen(?:Sync)?\s*\(/g)) {
|
|
190
|
+
const flags = callArguments(text, found.index + found[0].length - 1)[1];
|
|
191
|
+
if (flags === undefined) continue;
|
|
192
|
+
const mode = literal(flags);
|
|
193
|
+
if (mode === undefined || /[wa+]/.test(mode)) return true;
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The family the script text proves, or `undefined`.
|
|
200
|
+
* @param {'python'|'node'} language
|
|
201
|
+
* @param {string} source
|
|
202
|
+
*/
|
|
203
|
+
function readScript(language, source) {
|
|
204
|
+
if (typeof source !== 'string' || source.trim() === '') return undefined;
|
|
205
|
+
const text = source.replace(PRINTING, '');
|
|
206
|
+
if (language === 'python') return readPython(text);
|
|
207
|
+
if (language === 'node') return readNode(text);
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function pythonImportsAreReadable(text) {
|
|
212
|
+
const pairs = [...text.matchAll(/(?:^|;)[ \t]*(?:import[ \t]+([^\n#;]+)|from[ \t]+(\S+)[ \t]+import[ \t]+([^\n#;]+))/gm)];
|
|
213
|
+
for (const found of pairs) {
|
|
214
|
+
const names = found[2] === undefined ? found[1].split(',').map((part) => part.trim().split(/\s+/)[0]) : [found[2]];
|
|
215
|
+
for (const name of names) {
|
|
216
|
+
const root = name === undefined ? '' : name.split('.')[0];
|
|
217
|
+
if (root === '' || !PYTHON_MODULES.has(root)) return false;
|
|
218
|
+
}
|
|
219
|
+
// Names pulled out of `os` may be the deleting ones, so only the reading ones pass.
|
|
220
|
+
if (found[2] === 'os') {
|
|
221
|
+
for (const name of found[3].split(',').map((part) => part.trim().split(/\s+/)[0])) {
|
|
222
|
+
if (!PYTHON_OS_READ_NAMES.has(name)) return false;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function readPython(text) {
|
|
230
|
+
const code = codeOf('python', text);
|
|
231
|
+
// A deletion the code calls is proven whatever else the script does or imports.
|
|
232
|
+
if (PYTHON_DELETES.test(code)) return 'destructive';
|
|
233
|
+
if (PYTHON_UNREADABLE.test(text)) return undefined;
|
|
234
|
+
if (!pythonImportsAreReadable(text)) return undefined;
|
|
235
|
+
if (PYTHON_WRITES.test(code) || pythonOpensForWrite(codeOf('python', text, true))) return 'preparing';
|
|
236
|
+
return 'exploring';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function readNode(text) {
|
|
240
|
+
const code = codeOf('node', text);
|
|
241
|
+
if (NODE_DELETES.test(code)) return 'destructive';
|
|
242
|
+
if (NODE_UNREADABLE.test(text)) return undefined;
|
|
243
|
+
// Every module the script loads, by `require`, a static `import` or a dynamic one: a
|
|
244
|
+
// builtin from the list, or a JSON file. Anything else — a path, a package, an
|
|
245
|
+
// expression — is code this reader has not seen.
|
|
246
|
+
const specifiers = [];
|
|
247
|
+
for (const found of text.matchAll(/\b(?:require|import)\s*\(\s*(['"])([^'"]*)\1\s*\)/g)) specifiers.push(found[2]);
|
|
248
|
+
for (const found of text.matchAll(/\bimport\s+(?:[\w*${},\s]+\s+from\s+)?(['"])([^'"]+)\1/g)) specifiers.push(found[2]);
|
|
249
|
+
const calls = [...text.matchAll(/\b(?:require|import)\s*\(/g)].length;
|
|
250
|
+
const literals = [...text.matchAll(/\b(?:require|import)\s*\(\s*(['"])[^'"]*\1\s*\)/g)].length;
|
|
251
|
+
if (calls !== literals) return undefined;
|
|
252
|
+
for (const specifier of specifiers) {
|
|
253
|
+
const name = specifier.startsWith('node:') ? specifier.slice(5) : specifier;
|
|
254
|
+
if (/\.json$/.test(name) && !name.startsWith('http')) continue;
|
|
255
|
+
if (!NODE_MODULES.has(name)) return undefined;
|
|
256
|
+
}
|
|
257
|
+
// Names destructured out of the filesystem module may be the deleting or writing ones.
|
|
258
|
+
const destructured = /(?:\{([^}]*)\}\s*=\s*require\s*\(\s*['"](?:node:)?fs(?:\/promises)?['"]\s*\)|import\s*\{([^}]*)\}\s*from\s*['"](?:node:)?fs(?:\/promises)?['"])/g;
|
|
259
|
+
for (const found of text.matchAll(destructured)) {
|
|
260
|
+
for (const part of (found[1] === undefined ? found[2] : found[1]).split(',')) {
|
|
261
|
+
const name = part.trim().split(/\s*:\s*|\s+as\s+/)[0];
|
|
262
|
+
if (name !== '' && !NODE_FS_READ_NAMES.has(name)) return undefined;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (NODE_WRITES.test(code) || nodeOpensForWrite(codeOf('node', text, true))) return 'preparing';
|
|
266
|
+
return 'exploring';
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The inline script a command's words hand an interpreter, or `undefined` when they hand it
|
|
271
|
+
* anything else (a file to run, a module, a flag this reader does not know).
|
|
272
|
+
* @param {string[]} words The words of ONE simple command, quotes folded.
|
|
273
|
+
* @param {string|undefined} body The text of the first heredoc the segment opens, if any.
|
|
274
|
+
*/
|
|
275
|
+
function inlineScript(words, body) {
|
|
276
|
+
// A node option that loads code before the script runs, wherever it stands.
|
|
277
|
+
if (words.some((word) => /^(-r|--require|--import|--loader|--experimental-loader|--env-file)(=|$)/.test(word))) return undefined;
|
|
278
|
+
const program = (words[0] === undefined ? '' : words[0]).split('/').pop();
|
|
279
|
+
const python = PYTHON_PROGRAM.test(program);
|
|
280
|
+
const node = NODE_PROGRAM.test(program) || program === 'node';
|
|
281
|
+
if (!python && !node) return undefined;
|
|
282
|
+
const plain = python ? PYTHON_PLAIN_FLAGS : NODE_PLAIN_FLAGS;
|
|
283
|
+
const payload = python ? new Set(['-c']) : new Set(['-e', '--eval', '-p', '--print']);
|
|
284
|
+
for (let index = 1; index < words.length; index += 1) {
|
|
285
|
+
const word = words[index] === undefined ? '' : words[index];
|
|
286
|
+
if (payload.has(word)) {
|
|
287
|
+
const script = words[index + 1];
|
|
288
|
+
return script === undefined ? undefined : { language: python ? 'python' : 'node', source: script };
|
|
289
|
+
}
|
|
290
|
+
if (word === '-') return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
291
|
+
if (plain.has(word)) continue;
|
|
292
|
+
if (python && /^-[IBuESsOqbd]+$/.test(word)) continue;
|
|
293
|
+
// Anything else is a script path, a module, or a flag this reader cannot vouch for.
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
// No script argument: the interpreter reads its program from the heredoc on stdin.
|
|
297
|
+
return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The family an inline script names, or `undefined`.
|
|
302
|
+
* @param {string[]} words
|
|
303
|
+
* @param {string|undefined} body
|
|
304
|
+
*/
|
|
305
|
+
function inlineScriptActivity(words, body) {
|
|
306
|
+
try {
|
|
307
|
+
const script = inlineScript(words, body);
|
|
308
|
+
return script === undefined ? undefined : readScript(script.language, script.source);
|
|
309
|
+
} catch {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
module.exports = { inlineScriptActivity, readScript };
|