@jalaxy33/pi-permission 0.4.0 → 0.5.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/src/tokenize.ts CHANGED
@@ -2,9 +2,14 @@
2
2
  * Quote-aware command splitter.
3
3
  *
4
4
  * Turns a raw bash command string into simple commands (argv lists) and
5
- * throws away text that is not a command: quoted words stay inside argv,
6
- * heredoc bodies and comments are skipped, and command substitutions are
7
- * tokenized as their own commands.
5
+ * throws away text that is not a command: heredoc bodies and comments are
6
+ * skipped, and command and process substitutions are tokenized as their own
7
+ * commands. Text the splitter cannot resolve (an unterminated quote, `$(` or
8
+ * heredoc) is reported as a hazard, so the gate can refuse to guess.
9
+ *
10
+ * Every word carries what it lost on the way here: an expansion, a quote, an
11
+ * escape or a glob. A program name that came from one of those is not a name,
12
+ * and the gate treats it as unreadable rather than matching on a guess.
8
13
  */
9
14
 
10
15
  export interface Redirect {
@@ -12,9 +17,33 @@ export interface Redirect {
12
17
  target: string;
13
18
  }
14
19
 
20
+ /** What a word went through before it became text. */
21
+ export interface WordMeta {
22
+ /** `$(...)`, backticks, process substitution, `$VAR`, `$((...))`, `$'...'`. */
23
+ expansion: boolean;
24
+ quote: boolean;
25
+ escape: boolean;
26
+ /** Unquoted `*`, `?` or `[`. */
27
+ glob: boolean;
28
+ }
29
+
15
30
  export interface SimpleCommand {
16
31
  argv: string[];
32
+ /** Parallel to `argv`. */
33
+ words: WordMeta[];
17
34
  redirects: Redirect[];
35
+ /** Body of the first heredoc this command reads (`bash <<EOF`). */
36
+ heredoc?: string;
37
+ /** Text fed on stdin by a here string (`bash <<< "..."`). */
38
+ stdinText?: string;
39
+ /** Stdin comes from a pipe, so it is not visible in the command text. */
40
+ stdinPiped?: boolean;
41
+ }
42
+
43
+ export interface Tokenized {
44
+ commands: SimpleCommand[];
45
+ /** Parts of the command text the splitter could not resolve. */
46
+ hazards: string[];
18
47
  }
19
48
 
20
49
  const BLANK = /\s/;
@@ -23,78 +52,209 @@ function isSeparator(ch: string): boolean {
23
52
  return ch === ";" || ch === "&" || ch === "|" || ch === "\n";
24
53
  }
25
54
 
26
- /** Reads a quoted string starting at `start`; double quotes honour backslash escapes. */
27
- function readQuoted(input: string, start: number): { text: string; next: number } {
28
- const quote = input[start];
55
+ function blankMeta(): WordMeta {
56
+ return { expansion: false, quote: false, escape: false, glob: false };
57
+ }
58
+
59
+ interface Scanned {
60
+ inner: string;
61
+ next: number;
62
+ }
63
+
64
+ /** Reads `(...)` open at `open`; nested parentheses are balanced. */
65
+ function scanParen(input: string, open: number): Scanned | undefined {
66
+ let depth = 1;
67
+ let i = open + 1;
68
+ while (i < input.length) {
69
+ const ch = input[i] as string;
70
+ if (ch === "\\") {
71
+ i += 2;
72
+ continue;
73
+ }
74
+ if (ch === "(") depth++;
75
+ else if (ch === ")") {
76
+ depth--;
77
+ if (depth === 0) return { inner: input.slice(open + 1, i), next: i + 1 };
78
+ }
79
+ i++;
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ /** Reads a backtick pair open at `open`. */
85
+ function scanBacktick(input: string, open: number): Scanned | undefined {
86
+ let i = open + 1;
87
+ while (i < input.length) {
88
+ const ch = input[i] as string;
89
+ if (ch === "\\") {
90
+ i += 2;
91
+ continue;
92
+ }
93
+ if (ch === "`") return { inner: input.slice(open + 1, i), next: i + 1 };
94
+ i++;
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ interface Quoted {
100
+ text: string;
101
+ next: number;
102
+ /** Substitutions the shell still runs inside the quotes. */
103
+ subs: string[];
104
+ /** The quoted text holds an expansion, so its value is not literal. */
105
+ expansion: boolean;
106
+ unterminated: boolean;
107
+ }
108
+
109
+ /**
110
+ * Reads a quoted string starting at `start`. Double quotes honour backslash
111
+ * escapes and keep running `$(...)` and `` `...` ``; single quotes keep
112
+ * everything literally, the way the shell does.
113
+ */
114
+ function readQuoted(input: string, start: number): Quoted {
115
+ const quote = input[start] as string;
116
+ const subs: string[] = [];
117
+ let expansion = false;
29
118
  let text = "";
30
119
  let i = start + 1;
120
+
31
121
  while (i < input.length && input[i] !== quote) {
32
- if (quote === '"' && input[i] === "\\") {
33
- text += input[i + 1] ?? "";
34
- i += 2;
35
- continue;
122
+ const ch = input[i] as string;
123
+ if (quote === '"') {
124
+ if (ch === "\\") {
125
+ // Inside double quotes bash only removes the backslash before these.
126
+ // Everywhere else it stays, which is what keeps `"C:\\repo"` intact.
127
+ const next = input[i + 1];
128
+ if (next !== undefined && "$`\"\\\n".includes(next)) {
129
+ text += next;
130
+ i += 2;
131
+ continue;
132
+ }
133
+ text += ch;
134
+ i++;
135
+ continue;
136
+ }
137
+ if (ch === "`") {
138
+ const found = scanBacktick(input, i);
139
+ if (!found) return { text, next: input.length, subs, expansion: true, unterminated: true };
140
+ subs.push(found.inner);
141
+ expansion = true;
142
+ i = found.next;
143
+ continue;
144
+ }
145
+ if (ch === "$" && input[i + 1] === "(") {
146
+ const found = scanParen(input, i + 1);
147
+ if (!found) return { text, next: input.length, subs, expansion: true, unterminated: true };
148
+ subs.push(found.inner);
149
+ expansion = true;
150
+ i = found.next;
151
+ continue;
152
+ }
153
+ if (ch === "$") expansion = true;
36
154
  }
37
- text += input[i];
155
+ text += ch;
38
156
  i++;
39
157
  }
40
- return { text, next: i + 1 };
158
+
159
+ if (i >= input.length) return { text, next: input.length, subs, expansion: true, unterminated: true };
160
+ return { text, next: i + 1, subs, expansion, unterminated: false };
41
161
  }
42
162
 
43
- export function tokenize(input: string): SimpleCommand[] {
163
+ /**
164
+ * Index after the closing `))` of an arithmetic expansion. `open` points at the
165
+ * first of the two opening parentheses.
166
+ */
167
+ function scanArithmetic(input: string, open: number): number | undefined {
168
+ let depth = 2;
169
+ let i = open + 2;
170
+ while (i < input.length) {
171
+ const ch = input[i] as string;
172
+ if (ch === "(") depth++;
173
+ else if (ch === ")") {
174
+ depth--;
175
+ if (depth === 0) return i + 1;
176
+ }
177
+ i++;
178
+ }
179
+ return undefined;
180
+ }
181
+
182
+ export function tokenizeDetailed(input: string): Tokenized {
44
183
  const commands: SimpleCommand[] = [];
184
+ const hazards: string[] = [];
45
185
  const subs: string[] = [];
46
186
  let argv: string[] = [];
187
+ let words: WordMeta[] = [];
47
188
  let redirects: Redirect[] = [];
48
189
  let word = "";
190
+ let meta = blankMeta();
49
191
  let inWord = false;
192
+ let piped = false;
193
+ let pendingStdin: string | undefined;
50
194
  let heredocs: string[] = [];
51
195
 
52
196
  const flushWord = () => {
53
197
  if (inWord) {
54
198
  argv.push(word);
199
+ words.push(meta);
55
200
  word = "";
201
+ meta = blankMeta();
56
202
  inWord = false;
57
203
  }
58
204
  };
59
205
 
60
206
  const endCommand = () => {
61
207
  flushWord();
62
- if (argv.length > 0) commands.push({ argv, redirects });
208
+ if (argv.length > 0) {
209
+ const command: SimpleCommand = { argv, words, redirects };
210
+ if (piped) command.stdinPiped = true;
211
+ if (pendingStdin !== undefined) command.stdinText = pendingStdin;
212
+ pendingStdin = undefined;
213
+ commands.push(command);
214
+ piped = false;
215
+ }
63
216
  argv = [];
217
+ words = [];
64
218
  redirects = [];
65
219
  };
66
220
 
67
- // Skip to the end of a pending heredoc body; returns the index after it.
68
- const skipHeredoc = (from: number, delimiter: string): number => {
221
+ // Skip to the end of a pending heredoc body, keeping the body text.
222
+ const skipHeredoc = (from: number, delimiter: string): { next: number; found: boolean; body: string } => {
69
223
  let i = from;
70
224
  while (i < input.length) {
71
225
  const nl = input.indexOf("\n", i);
72
226
  const lineEnd = nl === -1 ? input.length : nl;
73
227
  if (input.slice(i, lineEnd).replace(/^\t+/, "").trimEnd() === delimiter) {
74
- return nl === -1 ? input.length : nl + 1;
228
+ return {
229
+ next: nl === -1 ? input.length : nl + 1,
230
+ found: true,
231
+ body: input.slice(from, i),
232
+ };
75
233
  }
76
- if (nl === -1) return input.length;
234
+ if (nl === -1) return { next: input.length, found: false, body: input.slice(from) };
77
235
  i = nl + 1;
78
236
  }
79
- return input.length;
237
+ return { next: input.length, found: false, body: input.slice(from) };
80
238
  };
81
239
 
82
- const readRedirTarget = (from: number): { target: string; next: number } => {
240
+ const readRedirTarget = (from: number): { target: string; next: number; subs: string[] } => {
83
241
  let i = from;
84
242
  while (i < input.length && (input[i] === " " || input[i] === "\t")) i++;
85
243
  let target = "";
244
+ const found: string[] = [];
86
245
  while (i < input.length && !BLANK.test(input[i] as string) && !isSeparator(input[i] as string)) {
87
246
  const ch = input[i] as string;
88
247
  if (ch === "'" || ch === '"') {
89
248
  const quoted = readQuoted(input, i);
90
249
  target += quoted.text;
250
+ found.push(...quoted.subs);
91
251
  i = quoted.next;
92
252
  continue;
93
253
  }
94
254
  target += ch;
95
255
  i++;
96
256
  }
97
- return { target, next: i };
257
+ return { target, next: i, subs: found };
98
258
  };
99
259
 
100
260
  let i = 0;
@@ -103,6 +263,7 @@ export function tokenize(input: string): SimpleCommand[] {
103
263
 
104
264
  if (ch === "\\") {
105
265
  word += input[i + 1] ?? "";
266
+ meta.escape = true;
106
267
  inWord = true;
107
268
  i += 2;
108
269
  continue;
@@ -110,36 +271,87 @@ export function tokenize(input: string): SimpleCommand[] {
110
271
 
111
272
  if (ch === "'" || ch === '"') {
112
273
  const quoted = readQuoted(input, i);
274
+ if (quoted.unterminated) hazards.push("unterminated quote");
275
+ subs.push(...quoted.subs);
113
276
  word += quoted.text;
277
+ meta.quote = true;
278
+ if (quoted.expansion) meta.expansion = true;
114
279
  inWord = true;
115
280
  i = quoted.next;
116
281
  continue;
117
282
  }
118
283
 
119
284
  if (ch === "`") {
120
- const close = input.indexOf("`", i + 1);
121
- const stop = close === -1 ? input.length : close;
122
- subs.push(input.slice(i + 1, stop));
123
- i = stop + 1;
285
+ const found = scanBacktick(input, i);
286
+ if (!found) {
287
+ hazards.push("unterminated backtick");
288
+ i = input.length;
289
+ continue;
290
+ }
291
+ subs.push(found.inner);
292
+ meta.expansion = true;
293
+ i = found.next;
124
294
  continue;
125
295
  }
126
296
 
127
297
  if (ch === "$" && input[i + 1] === "(") {
128
- let depth = 1;
129
- let j = i + 2;
130
- while (j < input.length && depth > 0) {
131
- const c = input[j] as string;
132
- if (c === "(") depth++;
133
- else if (c === ")") depth--;
134
- if (depth === 0) break;
135
- j++;
298
+ // `$((...))` is arithmetic: a value, not a command.
299
+ if (input[i + 2] === "(") {
300
+ const next = scanArithmetic(input, i + 1);
301
+ if (next === undefined) {
302
+ hazards.push("unterminated arithmetic expansion");
303
+ i = input.length;
304
+ continue;
305
+ }
306
+ meta.expansion = true;
307
+ i = next;
308
+ continue;
136
309
  }
137
- subs.push(input.slice(i + 2, j));
138
- i = j + 1;
310
+ const found = scanParen(input, i + 1);
311
+ if (!found) {
312
+ hazards.push("unterminated command substitution");
313
+ i = input.length;
314
+ continue;
315
+ }
316
+ subs.push(found.inner);
317
+ meta.expansion = true;
318
+ i = found.next;
319
+ continue;
320
+ }
321
+
322
+ // `<(cmd)` and `>(cmd)` run a command, so their text is checked too.
323
+ if ((ch === "<" || ch === ">") && input[i + 1] === "(") {
324
+ const found = scanParen(input, i + 1);
325
+ if (!found) {
326
+ hazards.push("unterminated process substitution");
327
+ i = input.length;
328
+ continue;
329
+ }
330
+ subs.push(found.inner);
331
+ meta.expansion = true;
332
+ i = found.next;
333
+ continue;
334
+ }
335
+
336
+ if (ch === "$") {
337
+ // `$VAR`, `${VAR}` and `$'...'`: the word's value is decided at runtime.
338
+ if (/[A-Za-z_{@*#?$!'-]/.test(input[i + 1] ?? "")) meta.expansion = true;
339
+ word += ch;
340
+ inWord = true;
341
+ i++;
139
342
  continue;
140
343
  }
141
344
 
142
345
  if (ch === "<" && input[i + 1] === "<") {
346
+ // `<<<word` feeds `word` on stdin. It is not an operand, so it is read
347
+ // here and attached to the command as data.
348
+ if (input[i + 2] === "<") {
349
+ const redir = readRedirTarget(i + 3);
350
+ subs.push(...redir.subs);
351
+ pendingStdin = redir.target;
352
+ i = redir.next;
353
+ continue;
354
+ }
143
355
  let j = i + 2;
144
356
  if (input[j] === "-") j++;
145
357
  while (input[j] === " " || input[j] === "\t") j++;
@@ -164,6 +376,7 @@ export function tokenize(input: string): SimpleCommand[] {
164
376
  const append = input[i + 2] === ">";
165
377
  flushWord();
166
378
  const redir = readRedirTarget(i + (append ? 3 : 2));
379
+ subs.push(...redir.subs);
167
380
  redirects.push({ op: append ? ">>" : ">", target: redir.target });
168
381
  i = redir.next;
169
382
  continue;
@@ -175,6 +388,7 @@ export function tokenize(input: string): SimpleCommand[] {
175
388
  const clobber = input[i + 1] === "|";
176
389
  flushWord();
177
390
  const redir = readRedirTarget(i + (append || clobber ? 2 : 1));
391
+ subs.push(...redir.subs);
178
392
  redirects.push({ op: append ? ">>" : ">", target: redir.target });
179
393
  i = redir.next;
180
394
  continue;
@@ -183,16 +397,29 @@ export function tokenize(input: string): SimpleCommand[] {
183
397
  if (ch === "<") {
184
398
  flushWord();
185
399
  const redir = readRedirTarget(i + 1);
400
+ subs.push(...redir.subs);
186
401
  redirects.push({ op: "<", target: redir.target });
187
402
  i = redir.next;
188
403
  continue;
189
404
  }
190
405
 
191
406
  if (isSeparator(ch)) {
407
+ const pushedTo = commands.length;
192
408
  endCommand();
409
+ if (ch === "|") {
410
+ // `||` is logical or; only a single `|` feeds the next command.
411
+ if (input[i + 1] === "|") i += 1;
412
+ else if (commands.length >= pushedTo) piped = true;
413
+ }
193
414
  i++;
194
415
  if (ch === "\n") {
195
- for (const delimiter of heredocs) i = skipHeredoc(i, delimiter);
416
+ for (const delimiter of heredocs) {
417
+ const skipped = skipHeredoc(i, delimiter);
418
+ if (!skipped.found) hazards.push("unterminated heredoc");
419
+ const owner = commands[commands.length - 1];
420
+ if (owner && owner.heredoc === undefined) owner.heredoc = skipped.body;
421
+ i = skipped.next;
422
+ }
196
423
  heredocs = [];
197
424
  }
198
425
  continue;
@@ -210,13 +437,24 @@ export function tokenize(input: string): SimpleCommand[] {
210
437
  continue;
211
438
  }
212
439
 
440
+ if (ch === "*" || ch === "?" || ch === "[") meta.glob = true;
213
441
  word += ch;
214
442
  inWord = true;
215
443
  i++;
216
444
  }
217
445
 
218
446
  endCommand();
447
+ if (heredocs.length > 0) hazards.push("unterminated heredoc");
219
448
 
220
- for (const sub of subs) commands.push(...tokenize(sub));
221
- return commands;
449
+ for (const sub of subs) {
450
+ const inner = tokenizeDetailed(sub);
451
+ commands.push(...inner.commands);
452
+ hazards.push(...inner.hazards);
453
+ }
454
+
455
+ return { commands, hazards };
456
+ }
457
+
458
+ export function tokenize(input: string): SimpleCommand[] {
459
+ return tokenizeDetailed(input).commands;
222
460
  }
package/src/unlayer.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Peels the layers between a command string and the program that runs.
3
+ *
4
+ * Two things hide a program from the rule matcher:
5
+ *
6
+ * - shell keywords, which the splitter leaves in front of the command
7
+ * (`if true; then rm -rf x; fi` puts `then` where the program should be);
8
+ * - wrapper programs whose own argv carries the real command.
9
+ *
10
+ * Only wrappers with a closed option table are peeled here. `env -S`, `xargs`,
11
+ * `find -exec`, `busybox`, `eval` and `source` build or hide their command at
12
+ * runtime, so they stay whole and remain a reason to ask.
13
+ */
14
+
15
+ import { stripPrefixes } from "./prefixes";
16
+
17
+ /** Segments that never carry a command of their own. */
18
+ const SKIP_WORDS = new Set(["for", "in", "case", "fi", "done", "esac", "}"]);
19
+
20
+ /** Keywords that precede a command; the command follows them. */
21
+ const PREFIX_WORDS = new Set(["then", "do", "else", "elif", "if", "while", "until", "!", "{"]);
22
+
23
+ /**
24
+ * The innermost command of one simple command, or undefined when the segment
25
+ * holds no command at all. Word-exact, position zero only: `cp a in` keeps `in`
26
+ * as an operand.
27
+ */
28
+ export function unlayer(argv: string[]): string[] | undefined {
29
+ let current = argv;
30
+
31
+ for (let step = 0; step < 4; step += 1) {
32
+ const head = current[0];
33
+ if (head === undefined) return current;
34
+ if (SKIP_WORDS.has(head)) return undefined;
35
+ if (PREFIX_WORDS.has(head)) {
36
+ current = current.slice(1);
37
+ continue;
38
+ }
39
+ const stripped = stripPrefixes(current);
40
+ if (stripped !== current && stripped.length > 0) {
41
+ current = stripped;
42
+ continue;
43
+ }
44
+ return current;
45
+ }
46
+
47
+ return current;
48
+ }