@ziptie-soft/orca-local-decider 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,586 @@
1
+ /**
2
+ * A small, quote-aware shell splitter for the deterministic guard. It is not a shell parser: it
3
+ * only needs to find command words and their arguments reliably enough to match a short list of
4
+ * clearly destructive patterns without tripping on quoted text. Every pass is linear in the input.
5
+ */
6
+
7
+ export interface Segment {
8
+ readonly words: readonly string[];
9
+ /** True when this segment reads the previous one's stdout (`a | b`). */
10
+ readonly piped: boolean;
11
+ /** Bodies of the heredocs this segment's command reads (joined by newlines); `''` when none. */
12
+ readonly heredoc: string;
13
+ /** The bodies among those whose delimiter was unquoted: `$(…)` and backticks in them run. */
14
+ readonly expanded: string;
15
+ }
16
+
17
+ export interface ShellParse {
18
+ readonly segments: readonly Segment[];
19
+ /** The text with every quoted span (and heredoc body) removed. */
20
+ readonly bare: string;
21
+ /** The text with single-quoted (and `$'…'`) spans removed; double quotes stay. */
22
+ readonly noSingle: string;
23
+ }
24
+
25
+ type Quote = '' | "'" | '"' | "$'";
26
+
27
+ interface Pending {
28
+ readonly delim: string;
29
+ readonly strip: boolean;
30
+ readonly quoted: boolean;
31
+ readonly seg: number;
32
+ }
33
+
34
+ interface SplitState {
35
+ segments: Segment[];
36
+ words: string[];
37
+ word: string;
38
+ inWord: boolean;
39
+ quote: Quote;
40
+ piped: boolean;
41
+ pending: Pending[];
42
+ /** Depth of `((` arithmetic, where `<<` is a shift and not a heredoc. */
43
+ arith: number;
44
+ lineEnd: boolean;
45
+ /** Set once a heredoc has no terminator: later ones are left as commands (no repeated scans). */
46
+ heredocsOff: boolean;
47
+ /** `[start, end)` index pairs of `text` kept in the masked copies (merged when adjacent). */
48
+ bare: number[];
49
+ noSingle: number[];
50
+ }
51
+
52
+ /** Queued heredoc delimiters beyond this are not stripped (bodies stay visible as commands). */
53
+ const MAX_HEREDOCS = 8;
54
+ const SEPARATORS = new Set([';', '&', '|', '\n', '(', ')', '`']);
55
+ const NAME_CHAR = /[\w]/;
56
+ type Handler = (s: SplitState, text: string, i: number) => number;
57
+
58
+ function endWord(s: SplitState): void {
59
+ if (s.inWord) {
60
+ s.words.push(s.word);
61
+ }
62
+ s.word = '';
63
+ s.inWord = false;
64
+ }
65
+
66
+ function endSegment(s: SplitState, next: string, prev: string): void {
67
+ endWord(s);
68
+ if (s.words.length > 0) {
69
+ s.segments.push({ words: s.words, piped: s.piped, heredoc: '', expanded: '' });
70
+ }
71
+ s.words = [];
72
+ // `a | b` pipes; `a || b` does not.
73
+ s.piped = next === '|' && prev !== '|';
74
+ }
75
+
76
+ function addChars(s: SplitState, chars: string): void {
77
+ s.word += chars;
78
+ s.inWord = true;
79
+ }
80
+
81
+ const plain: Handler = (s, text, i) => {
82
+ addChars(s, text[i] ?? '');
83
+ return i;
84
+ };
85
+
86
+ const space: Handler = (s, _text, i) => {
87
+ endWord(s);
88
+ return i;
89
+ };
90
+
91
+ const openQuote: Handler = (s, text, i) => {
92
+ s.quote = text[i] === "'" ? "'" : '"';
93
+ s.inWord = true;
94
+ return i;
95
+ };
96
+
97
+ const separator: Handler = (s, text, i) => {
98
+ const ch = text[i] ?? '';
99
+ endSegment(s, text[i + 1] === '|' ? '' : ch, text[i - 1] ?? '');
100
+ s.lineEnd = ch === '\n';
101
+ return i;
102
+ };
103
+
104
+ /** `((` opens and `))` closes arithmetic, where `<<` is a shift. */
105
+ const paren: Handler = (s, text, i) => {
106
+ if (text[i] === '(' && text[i - 1] === '(') {
107
+ s.arith++;
108
+ } else if (text[i] === ')' && text[i - 1] === ')' && s.arith > 0) {
109
+ s.arith--;
110
+ }
111
+ return separator(s, text, i);
112
+ };
113
+
114
+ /** Backslash outside quotes: backslash-newline vanishes, anything else is taken literally. */
115
+ const escape: Handler = (s, text, i) => {
116
+ const next = text[i + 1];
117
+ if (next === undefined) {
118
+ addChars(s, '\\');
119
+ return i;
120
+ }
121
+ if (next !== '\n') {
122
+ addChars(s, next);
123
+ }
124
+ return i + 1;
125
+ };
126
+
127
+ /** `$'…'` quoting, `$"…"` (the `$` is dropped), `$IFS` and `${IFS}` (a word break). */
128
+ const dollar: Handler = (s, text, i) => {
129
+ const next = text[i + 1];
130
+ if (next === "'") {
131
+ s.quote = "$'";
132
+ s.inWord = true;
133
+ return i + 1;
134
+ }
135
+ if (next === '"') {
136
+ return i;
137
+ }
138
+ if (text.startsWith('${IFS}', i)) {
139
+ endWord(s);
140
+ return i + 5;
141
+ }
142
+ if (text.startsWith('$IFS', i) && !NAME_CHAR.test(text[i + 4] ?? '')) {
143
+ endWord(s);
144
+ return i + 3;
145
+ }
146
+ return plain(s, text, i);
147
+ };
148
+
149
+ /** The delimiter word at `from` (quotes and backslashes stripped) and the index after it. */
150
+ function readDelimiter(
151
+ text: string,
152
+ from: number,
153
+ ): { delim: string; end: number; quoted: boolean } {
154
+ let end = from;
155
+ while (end < text.length) {
156
+ const c = text[end] ?? '';
157
+ if (c === ' ' || c === '\t' || c === '\r' || c === '<' || c === '>' || SEPARATORS.has(c)) {
158
+ break;
159
+ }
160
+ end++;
161
+ }
162
+ const raw = text.slice(from, end);
163
+ return { delim: raw.replace(/['"\\]/g, ''), end, quoted: /['"\\]/.test(raw) };
164
+ }
165
+
166
+ /** `<<` / `<<-` `WORD` queues a heredoc; `<<<` and arithmetic shifts are ordinary text. */
167
+ const angle: Handler = (s, text, i) => {
168
+ if (text[i + 1] !== '<') {
169
+ return plain(s, text, i);
170
+ }
171
+ if (text[i + 2] === '<') {
172
+ addChars(s, '<<<');
173
+ return i + 2;
174
+ }
175
+ const strip = text[i + 2] === '-';
176
+ let from = i + (strip ? 3 : 2);
177
+ while (text[from] === ' ' || text[from] === '\t') {
178
+ from++;
179
+ }
180
+ const { delim, end, quoted: wasQuoted } = readDelimiter(text, from);
181
+ if (delim === '' || s.arith > 0 || s.heredocsOff || s.pending.length >= MAX_HEREDOCS) {
182
+ addChars(s, '<<');
183
+ return i + 1;
184
+ }
185
+ endWord(s);
186
+ s.pending.push({ delim, strip, quoted: wasQuoted, seg: s.segments.length });
187
+ return end - 1;
188
+ };
189
+
190
+ const UNQUOTED = new Map<string, Handler>([
191
+ ["'", openQuote],
192
+ ['"', openQuote],
193
+ ['\\', escape],
194
+ ['$', dollar],
195
+ ['<', angle],
196
+ ['(', paren],
197
+ [')', paren],
198
+ [' ', space],
199
+ ['\t', space],
200
+ ['\r', space],
201
+ ...[';', '&', '|', '\n', '`'].map((c): [string, Handler] => [c, separator]),
202
+ ]);
203
+
204
+ const DQ_ESCAPES = new Set(['"', '\\', '$', '`']);
205
+
206
+ /** Backslash inside quotes; `escapes` lists what it may escape (else the backslash stays). */
207
+ function quotedEscape(
208
+ s: SplitState,
209
+ text: string,
210
+ i: number,
211
+ escapes: ReadonlySet<string>,
212
+ ): number {
213
+ const next = text[i + 1];
214
+ if (next === undefined || !escapes.has(next)) {
215
+ s.word += '\\';
216
+ return i;
217
+ }
218
+ s.word += next;
219
+ return i + 1;
220
+ }
221
+
222
+ const SINGLE_ESCAPES = new Set(["'", '\\']);
223
+
224
+ function quoted(s: SplitState, text: string, i: number): number {
225
+ const ch = text[i] ?? '';
226
+ if (ch === (s.quote === '"' ? '"' : "'")) {
227
+ s.quote = '';
228
+ } else if (ch === '\\' && s.quote === '"') {
229
+ return dqEscape(s, text, i);
230
+ } else if (ch === '\\' && s.quote === "$'") {
231
+ return quotedEscape(s, text, i, SINGLE_ESCAPES);
232
+ } else {
233
+ s.word += ch;
234
+ }
235
+ return i;
236
+ }
237
+
238
+ function dqEscape(s: SplitState, text: string, i: number): number {
239
+ if (text[i + 1] === '\n') {
240
+ return i + 1;
241
+ }
242
+ return quotedEscape(s, text, i, DQ_ESCAPES);
243
+ }
244
+
245
+ /** Delimiter line at `line`: `{body end, next}` of the heredoc body starting at `pos`, or null. */
246
+ function findTerminator(
247
+ text: string,
248
+ pos: number,
249
+ p: Pending,
250
+ ): { body: string; next: number } | null {
251
+ let line = pos;
252
+ for (;;) {
253
+ const found = text.indexOf('\n', line);
254
+ const end = found === -1 ? text.length : found;
255
+ const content = text.slice(line, end);
256
+ if ((p.strip ? content.replace(/^\t+/, '') : content) === p.delim) {
257
+ return { body: text.slice(pos, line), next: Math.min(end + 1, text.length) };
258
+ }
259
+ if (found === -1) {
260
+ return null;
261
+ }
262
+ line = found + 1;
263
+ }
264
+ }
265
+
266
+ function attachBody(s: SplitState, p: Pending, body: string): void {
267
+ const seg = s.segments[p.seg];
268
+ if (seg !== undefined) {
269
+ const join = (a: string): string => (a === '' ? body : `${a}\n${body}`);
270
+ s.segments[p.seg] = {
271
+ ...seg,
272
+ heredoc: join(seg.heredoc),
273
+ expanded: p.quoted ? seg.expanded : join(seg.expanded),
274
+ };
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Consume the queued heredoc bodies that start at `pos` (after a newline) into their segments.
280
+ * An unterminated heredoc is left in place so its text is still checked as commands.
281
+ */
282
+ function consumeHeredocs(s: SplitState, text: string, start: number): number {
283
+ let pos = start;
284
+ for (const p of s.pending) {
285
+ const found = findTerminator(text, pos, p);
286
+ if (found === null) {
287
+ s.heredocsOff = true;
288
+ break;
289
+ }
290
+ attachBody(s, p, found.body);
291
+ pos = found.next;
292
+ }
293
+ s.pending = [];
294
+ return pos;
295
+ }
296
+
297
+ const isSingle = (q: Quote): boolean => q === "'" || q === "$'";
298
+
299
+ function keep(spans: number[], start: number, end: number): void {
300
+ if (spans.at(-1) === start) {
301
+ spans[spans.length - 1] = end;
302
+ } else {
303
+ spans.push(start, end);
304
+ }
305
+ }
306
+
307
+ /** Record `text[start, end)` in the masked copies it belongs to (a backslash-newline in neither). */
308
+ function mask(s: SplitState, text: string, before: Quote, start: number, end: number): void {
309
+ if (end - start === 2 && text[start] === '\\' && text[start + 1] === '\n') {
310
+ return;
311
+ }
312
+ if (before === '' && s.quote === '') {
313
+ keep(s.bare, start, end);
314
+ }
315
+ if (!isSingle(before) && !isSingle(s.quote)) {
316
+ keep(s.noSingle, start, end);
317
+ }
318
+ }
319
+
320
+ function spanText(text: string, spans: readonly number[]): string {
321
+ const parts: string[] = [];
322
+ for (let k = 0; k < spans.length; k += 2) {
323
+ parts.push(text.slice(spans[k], spans[k + 1]));
324
+ }
325
+ return parts.join('');
326
+ }
327
+
328
+ /** Runs of characters no handler treats specially, per quote state. */
329
+ const RUNS: Readonly<Record<Quote, RegExp>> = {
330
+ '': /[^'"\\$<()\t\r\n ;&|`#]+/y,
331
+ "'": /[^']+/y,
332
+ '"': /[^"\\]+/y,
333
+ "$'": /[^'\\]+/y,
334
+ };
335
+
336
+ /** Consume a plain run at `i` in one step; returns its end, or `i` when there is none. */
337
+ function takeRun(s: SplitState, text: string, i: number): number {
338
+ const re = RUNS[s.quote];
339
+ re.lastIndex = i;
340
+ if (!re.test(text)) {
341
+ return i;
342
+ }
343
+ const chunk = text.slice(i, re.lastIndex);
344
+ s.word += chunk;
345
+ s.inWord = true;
346
+ mask(s, text, s.quote, i, re.lastIndex);
347
+ return re.lastIndex;
348
+ }
349
+
350
+ /** A `#` at a word boundary outside quotes starts a comment: its end (the newline), else `i`. */
351
+ function commentEnd(s: SplitState, text: string, i: number): number {
352
+ if (s.quote !== '' || text[i] !== '#' || s.inWord) {
353
+ return i;
354
+ }
355
+ const nl = text.indexOf('\n', i);
356
+ return nl === -1 ? text.length : nl;
357
+ }
358
+
359
+ /** Split a command line into segments and masked copies, linear in its length. */
360
+ export function parseShell(text: string): ShellParse {
361
+ const s: SplitState = {
362
+ segments: [],
363
+ words: [],
364
+ word: '',
365
+ inWord: false,
366
+ quote: '',
367
+ piped: false,
368
+ pending: [],
369
+ arith: 0,
370
+ lineEnd: false,
371
+ heredocsOff: false,
372
+ bare: [],
373
+ noSingle: [],
374
+ };
375
+ let i = 0;
376
+ while (i < text.length) {
377
+ const run = takeRun(s, text, i);
378
+ if (run > i) {
379
+ i = run;
380
+ continue;
381
+ }
382
+ const comment = commentEnd(s, text, i);
383
+ if (comment > i) {
384
+ i = comment;
385
+ continue;
386
+ }
387
+ const before = s.quote;
388
+ const start = i;
389
+ i = before === '' ? (UNQUOTED.get(text[i] ?? '') ?? plain)(s, text, i) : quoted(s, text, i);
390
+ mask(s, text, before, start, i + 1);
391
+ i++;
392
+ if (s.lineEnd) {
393
+ s.lineEnd = false;
394
+ i = s.pending.length > 0 ? consumeHeredocs(s, text, i) : i;
395
+ }
396
+ }
397
+ endSegment(s, '', '');
398
+ return {
399
+ segments: s.segments,
400
+ bare: spanText(text, s.bare),
401
+ noSingle: spanText(text, s.noSingle),
402
+ };
403
+ }
404
+
405
+ /** Split a command line into segments of words, honouring quotes and backslash escapes. */
406
+ export function splitShell(text: string): readonly Segment[] {
407
+ return parseShell(text).segments;
408
+ }
409
+
410
+ const PREFIXES = new Set([
411
+ 'sudo',
412
+ 'doas',
413
+ 'env',
414
+ 'command',
415
+ 'nohup',
416
+ 'time',
417
+ 'exec',
418
+ 'nice',
419
+ 'timeout',
420
+ 'xargs',
421
+ 'busybox',
422
+ 'setsid',
423
+ 'stdbuf',
424
+ 'ionice',
425
+ ]);
426
+ /** Shell keywords that begin a command: `then rm …`, `do rm …`, `{ rm …`, `! rm …`. */
427
+ const KEYWORDS = new Set([
428
+ 'if',
429
+ 'then',
430
+ 'elif',
431
+ 'else',
432
+ 'fi',
433
+ 'while',
434
+ 'until',
435
+ 'do',
436
+ 'done',
437
+ 'for',
438
+ 'case',
439
+ 'esac',
440
+ '{',
441
+ '}',
442
+ '!',
443
+ ]);
444
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
445
+
446
+ /** Prefix flags whose value is the next word: `sudo -u root rm …`, `nice -n 10 rm …`. */
447
+ const VALUE_FLAGS: Readonly<Record<string, ReadonlySet<string>>> = {
448
+ sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U']),
449
+ doas: new Set(['-u', '-C']),
450
+ env: new Set(['-u', '-C']),
451
+ nice: new Set(['-n']),
452
+ ionice: new Set(['-c', '-n', '-p', '-t']),
453
+ timeout: new Set(['-s', '-k']),
454
+ xargs: new Set(['-I', '-n', '-P', '-L', '-d', '-s', '-E', '-a']),
455
+ stdbuf: new Set(['-i', '-o', '-e']),
456
+ };
457
+
458
+ /** Words a prefix's flag at `i` spans (1, or 2 when its value is the next word); 0 if none. */
459
+ function prefixFlagSpan(prefix: string, words: readonly string[], i: number): number {
460
+ const w = words[i] ?? '';
461
+ if (prefix === '' || !w.startsWith('-')) {
462
+ return 0;
463
+ }
464
+ return VALUE_FLAGS[prefix]?.has(w) === true && i + 1 < words.length ? 2 : 1;
465
+ }
466
+
467
+ /** Drop `sudo`, `env`, `timeout 5`, `VAR=value` and similar prefixes so `words[0]` is the command. */
468
+ export function commandWords(words: readonly string[]): readonly string[] {
469
+ let i = 0;
470
+ let prefix = '';
471
+ let durationDue = false;
472
+ while (i < words.length) {
473
+ const w = words[i] ?? '';
474
+ const span = prefixFlagSpan(prefix, words, i);
475
+ if (span > 0) {
476
+ i += span;
477
+ } else if (durationDue && !ASSIGNMENT.test(w)) {
478
+ durationDue = false;
479
+ i++;
480
+ } else if (prefix === '' && KEYWORDS.has(w)) {
481
+ i++;
482
+ } else if (PREFIXES.has(w) || ASSIGNMENT.test(w)) {
483
+ if (PREFIXES.has(w)) {
484
+ prefix = w;
485
+ durationDue = w === 'timeout';
486
+ }
487
+ i++;
488
+ } else {
489
+ break;
490
+ }
491
+ }
492
+ return words.slice(i);
493
+ }
494
+
495
+ /** The basename of a command word: `/usr/bin/rm` → `rm`. */
496
+ export function baseName(word: string): string {
497
+ const slash = word.lastIndexOf('/');
498
+ return slash === -1 ? word : word.slice(slash + 1);
499
+ }
500
+
501
+ /** Scanner contexts inside a substitution: `$(` ('S'), a bare `(` ('P') and a `"` ('D'). */
502
+ interface Scan {
503
+ readonly text: string;
504
+ readonly stack: string[];
505
+ readonly out: string[];
506
+ start: number;
507
+ }
508
+
509
+ /** A backtick substitution at `i`: its body runs to the next unescaped backtick. */
510
+ function backtick(sc: Scan, i: number): number {
511
+ let j = i + 1;
512
+ while (j < sc.text.length && sc.text[j] !== '`') {
513
+ j += sc.text[j] === '\\' ? 2 : 1;
514
+ }
515
+ sc.out.push(sc.text.slice(i + 1, j));
516
+ return j + 1;
517
+ }
518
+
519
+ function open(sc: Scan, kind: string, at: number, next: number): number {
520
+ if (sc.stack.length === 0) {
521
+ sc.start = next;
522
+ }
523
+ sc.stack.push(kind);
524
+ return at;
525
+ }
526
+
527
+ function baseStep(sc: Scan, i: number): number {
528
+ const c = sc.text[i];
529
+ if (c === '\\') {
530
+ return i + 2;
531
+ }
532
+ if (c === '$' && sc.text[i + 1] === '(') {
533
+ return open(sc, 'S', i + 2, i + 2);
534
+ }
535
+ return c === '`' ? backtick(sc, i) : i + 1;
536
+ }
537
+
538
+ function innerStep(sc: Scan, i: number, top: string): number {
539
+ const c = sc.text[i];
540
+ if (c === '\\') {
541
+ return i + 2;
542
+ }
543
+ if (c === '$' && sc.text[i + 1] === '(') {
544
+ return open(sc, 'S', i + 2, i + 2);
545
+ }
546
+ return top === 'D' ? dqStep(sc, c, i) : codeStep(sc, c, i);
547
+ }
548
+
549
+ function dqStep(sc: Scan, c: string | undefined, i: number): number {
550
+ if (c === '"') {
551
+ sc.stack.pop();
552
+ }
553
+ return i + 1;
554
+ }
555
+
556
+ function codeStep(sc: Scan, c: string | undefined, i: number): number {
557
+ if (c === "'") {
558
+ const j = sc.text.indexOf("'", i + 1);
559
+ return j === -1 ? i + 1 : j + 1;
560
+ }
561
+ if (c === '"' || c === '(') {
562
+ return open(sc, c === '"' ? 'D' : 'P', i + 1, i + 1);
563
+ }
564
+ if (c === ')') {
565
+ sc.stack.pop();
566
+ if (sc.stack.length === 0) {
567
+ sc.out.push(sc.text.slice(sc.start, i));
568
+ }
569
+ }
570
+ return i + 1;
571
+ }
572
+
573
+ /**
574
+ * The scripts of the outermost `$(…)` and backtick substitutions in `text`, and the text of an
575
+ * unterminated `$(` (`tail`, to the end), found in one forward pass so repeated openers cost nothing extra. Nested ones
576
+ * are the caller's recursion.
577
+ */
578
+ export function substitutions(text: string): { scripts: readonly string[]; tail: string } {
579
+ const sc: Scan = { text, stack: [], out: [], start: 0 };
580
+ let i = 0;
581
+ while (i < text.length) {
582
+ const top = sc.stack.at(-1);
583
+ i = top === undefined ? baseStep(sc, i) : innerStep(sc, i, top);
584
+ }
585
+ return { scripts: sc.out, tail: sc.stack.length > 0 ? text.slice(sc.start) : '' };
586
+ }