@alexwkleung/reika 0.8.0 → 0.10.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.
@@ -3,7 +3,7 @@ import { homedir, tmpdir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { execFileSync, spawnSync } from 'node:child_process';
5
5
  import { expandingHeredocBodies, stripHeredocs } from './_heredoc.js';
6
- import { dropCarriers, hasExecutableSubstitution, hasRawSubstitution, maskQuoted, splitSegments, words, INSPECTION_COMMANDS, } from './_readonly.js';
6
+ import { WORD_RE, dropCarriers, hasExecutableSubstitution, hasRawSubstitution, maskQuoted, splitSegments, words, INSPECTION_COMMANDS, } from './_readonly.js';
7
7
  // Kernel-enforced confinement for model-chosen shell commands (#163). Seatbelt (`sandbox-exec`)
8
8
  // only: bubblewrap has no port-level network filtering, so a sandboxed process gets its own
9
9
  // loopback and cannot reach the host's model server — the one thing bash needs localhost for. The
@@ -220,8 +220,9 @@ const GIT_GLOBAL_VALUE_FLAGS = new Set([
220
220
  ]);
221
221
  // Subcommand options that run a program the model wrote. `--template` plants hooks that run at
222
222
  // checkout and clone's `--config` is `-c` again, so both belong here although neither is spelled
223
- // as a command. Long names apply to every subcommand: none has a harmless option abbreviated by
224
- // these, and `push --exec`/`archive --exec` mean the same as `rebase --exec`.
223
+ // as a command. Long names apply to every subcommand: `push --exec`/`archive --exec` mean the same
224
+ // as `rebase --exec`, and an abbreviation of one of these is refused on any subcommand — a false
225
+ // deny where that subcommand's own `--e`/`--t`/`--u` means something else, never a hole.
225
226
  const GIT_PROGRAM_LONG_FLAGS = [
226
227
  'upload-pack',
227
228
  'receive-pack',
@@ -240,21 +241,98 @@ const GIT_PROGRAM_SHORT_FLAGS = {
240
241
  rebase: { run: 'x', value: 'sXxC' },
241
242
  difftool: { run: 'x', value: 'tx' },
242
243
  };
243
- // Whole subcommands (or a subcommand's first operand) whose job is running a command.
244
- const GIT_PROGRAM_SUBCOMMANDS = new Set(['filter-branch', 'submodule foreach', 'bisect run']);
244
+ // The subcommands a `git` segment may keep the network with — an ALLOWLIST since #910, the polarity
245
+ // `gh` and `hf` already have, because the blocklist it replaced (`filter-branch`, `submodule
246
+ // foreach`, `bisect run`, `send-email`) left every subcommand nobody had listed open: `git
247
+ // remote-ext`, `git submodule--helper foreach` and `git merge-index ./x.sh -a` each ran a program
248
+ // with the network. A missed subcommand is now a false deny. Only the first group needs the network;
249
+ // the second is here so a read or a branch switch beside a fetch (`git fetch && git log ..@{u}`,
250
+ // `git checkout main && git pull`) does not cost the fetch its allow, and each was checked for an
251
+ // option that names a program on the command line (`merge -s` looks a strategy up on PATH only, so
252
+ // `-s ./x` is refused by git itself). `send-email`, `filter-branch`, `bisect`, `worktree add`, `help`
253
+ // (`-w` starts a browser) and every plumbing command not named are out.
254
+ const GIT_NETWORK_SUBCOMMANDS = new Set(['fetch', 'pull', 'clone', 'ls-remote', 'push', 'remote']);
255
+ const GIT_LOCAL_SUBCOMMANDS = new Set([
256
+ 'add',
257
+ 'apply',
258
+ 'blame',
259
+ 'branch',
260
+ 'cat-file',
261
+ 'check-ignore',
262
+ 'checkout',
263
+ 'cherry',
264
+ 'cherry-pick',
265
+ 'commit',
266
+ 'config',
267
+ 'count-objects',
268
+ 'describe',
269
+ 'diff',
270
+ 'for-each-ref',
271
+ 'grep',
272
+ 'hash-object',
273
+ 'log',
274
+ 'ls-files',
275
+ 'ls-tree',
276
+ 'merge',
277
+ 'merge-base',
278
+ 'merge-tree',
279
+ 'mv',
280
+ 'name-rev',
281
+ 'range-diff',
282
+ 'rebase',
283
+ 'reflog',
284
+ 'reset',
285
+ 'restore',
286
+ 'rev-list',
287
+ 'rev-parse',
288
+ 'revert',
289
+ 'rm',
290
+ 'shortlog',
291
+ 'show',
292
+ 'show-ref',
293
+ 'stash',
294
+ 'status',
295
+ 'stripspace',
296
+ 'switch',
297
+ 'symbolic-ref',
298
+ 'tag',
299
+ 'version',
300
+ 'whatchanged',
301
+ ]);
302
+ // Subcommands allowed only with one of these as their first operand: `submodule foreach` and `lfs`'s
303
+ // own verbs that push or install hooks are the rest of those namespaces.
304
+ const GIT_SUBCOMMAND_OPERANDS = {
305
+ submodule: new Set(['update', 'init', 'sync', 'status', 'summary', 'deinit', 'absorbgitdirs']),
306
+ lfs: new Set(['fetch', 'pull', 'ls-files', 'status', 'env', 'version']),
307
+ worktree: new Set(['list', 'prune', 'remove']),
308
+ };
245
309
  function gitSubcommandRunsProgram(sub, args) {
246
- if (GIT_PROGRAM_SUBCOMMANDS.has(sub))
247
- return true;
248
- const first = args.find(a => !a.startsWith('-'));
249
- if (first && GIT_PROGRAM_SUBCOMMANDS.has(`${sub} ${first}`))
310
+ const operands = GIT_SUBCOMMAND_OPERANDS[sub];
311
+ if (operands) {
312
+ const first = args.find(a => !a.startsWith('-'));
313
+ if (!first || !operands.has(first))
314
+ return true;
315
+ }
316
+ else if (!GIT_NETWORK_SUBCOMMANDS.has(sub) && !GIT_LOCAL_SUBCOMMANDS.has(sub)) {
250
317
  return true;
318
+ }
251
319
  const short = GIT_PROGRAM_SHORT_FLAGS[sub];
252
- for (const a of args) {
253
- if (a === '--')
254
- return false;
320
+ for (let i = 0; i < args.length; i++) {
321
+ const a = args[i];
322
+ // `--` ends the options only when it is not the VALUE of the option before it: in `git
323
+ // ls-remote -o -- --upload-pack=./x.sh .` it is `-o`'s value and git read the next word as an
324
+ // option (measured, #910). Which options take a value is per subcommand and not worth a table,
325
+ // so any bare option before it (one carrying no `=value`) keeps the scan going.
326
+ if (a === '--') {
327
+ const prev = args[i - 1];
328
+ if (prev === undefined || !prev.startsWith('-') || prev.includes('='))
329
+ return false;
330
+ continue;
331
+ }
255
332
  if (a.startsWith('--')) {
256
333
  const name = a.slice(2).split('=')[0];
257
- if (name.length >= 2 && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
334
+ // Any prefix, down to one letter (`--u=cmd` ran); `--=x` has an empty name, which is none.
335
+ if (name && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
258
336
  return true;
259
337
  }
260
338
  else if (short && a.startsWith('-')) {
@@ -268,6 +346,46 @@ function gitSubcommandRunsProgram(sub, args) {
268
346
  }
269
347
  return false;
270
348
  }
349
+ // Whether a raw (still-quoted) word holds something the shell expands before git sees it, so the
350
+ // classifier cannot read the option git will get (#910): a parameter (`"$f"` from a `for` loop), a
351
+ // backtick, a glob (`--up*` matches a file of that name) or a brace expansion (`{--u=./x.sh,.}`,
352
+ // `git {send-email,p}`). Single quotes and backslashes make each of these literal. A brace counts only
353
+ // with a `,` or `..` before its `}`, since `HEAD@{1}` and `@{u}` are not expansions.
354
+ function shellExpandsWord(raw) {
355
+ let quote = null;
356
+ for (let i = 0; i < raw.length; i++) {
357
+ const c = raw[i];
358
+ if (c === '\\') {
359
+ i++;
360
+ }
361
+ else if (quote === '"') {
362
+ if (c === '"')
363
+ quote = null;
364
+ else if (c === '$' || c === '`')
365
+ return true;
366
+ }
367
+ else if (c === "'") {
368
+ const end = raw.indexOf("'", i + 1);
369
+ i = end < 0 ? raw.length : end;
370
+ }
371
+ else if (c === '$' && (raw[i + 1] === "'" || raw[i + 1] === '"')) {
372
+ // `$'…'` and `$"…"` are quoting, not a parameter; the quote itself is read next.
373
+ }
374
+ else if (c === '"') {
375
+ quote = '"';
376
+ }
377
+ else if (c === '$' || c === '`' || c === '*' || c === '?' || c === '[') {
378
+ return true;
379
+ }
380
+ else if (c === '{') {
381
+ const close = raw.indexOf('}', i + 1);
382
+ const inner = close < 0 ? '' : raw.slice(i + 1, close);
383
+ if (inner.includes(',') || inner.includes('..'))
384
+ return true;
385
+ }
386
+ }
387
+ return false;
388
+ }
271
389
  // Called with the git segment's OWN words (verb, `timeout`/`xargs` carrier and xargs flags already
272
390
  // dropped), so a carrier's data cannot pose as the verb's arguments: `xargs -I git git -c k=v
273
391
  // fetch` would otherwise find the `-I` placeholder where it looks for `git`.
@@ -386,7 +504,8 @@ function effectiveWords(segment) {
386
504
  // `timeout` and `xargs` each name the command they run rather than being it, so both are skipped to
387
505
  // reach it — a carrier inside the command xargs runs included.
388
506
  let ws = dropCarriers(words(segment.trim().replace(VERB_PREFIX_RE, '')));
389
- if (ws[0] === 'xargs') {
507
+ const viaXargs = ws[0] === 'xargs';
508
+ if (viaXargs) {
390
509
  let i = 1;
391
510
  while (i < ws.length && ws[i].startsWith('-')) {
392
511
  if (XARGS_VALUE_FLAGS.has(ws[i]))
@@ -395,7 +514,7 @@ function effectiveWords(segment) {
395
514
  }
396
515
  ws = dropCarriers(ws.slice(i));
397
516
  }
398
- return ws;
517
+ return { ws, viaXargs };
399
518
  }
400
519
  /**
401
520
  * Whether `command` may run sandboxed WITH network: every segment is a `NET_VERBS` command or one
@@ -435,7 +554,7 @@ export function networkDecision(command) {
435
554
  let net = false;
436
555
  let blockedBy;
437
556
  for (const seg of segments) {
438
- const ws = effectiveWords(seg);
557
+ const { ws, viaXargs } = effectiveWords(seg);
439
558
  const verb = ws[0];
440
559
  if (!verb)
441
560
  return { allowed: false };
@@ -443,8 +562,16 @@ export function networkDecision(command) {
443
562
  if (NET_VERBS.has(verb)) {
444
563
  if (!envPrefixHarmless(seg))
445
564
  return { allowed: false };
446
- if (verb === 'git' && gitArgsRunProgram(args))
447
- return { allowed: false };
565
+ if (verb === 'git') {
566
+ // What `xargs` appends comes from stdin and what the shell expands is decided at run time, so
567
+ // neither is an argument this reader has seen (#910): `echo --upload-pack=./x.sh . | xargs
568
+ // git ls-remote` ran the program. `gh`/`hf` keep both shapes, which their verb tables bound.
569
+ if (viaXargs || (seg.match(WORD_RE) ?? []).some(shellExpandsWord)) {
570
+ return { allowed: false };
571
+ }
572
+ if (gitArgsRunProgram(args))
573
+ return { allowed: false };
574
+ }
448
575
  net = true;
449
576
  }
450
577
  else if (!NET_PIPE_COMMANDS.has(verb)) {