@capybara-hq/kernel 0.1.0-rc.30 → 0.1.0-rc.32

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.
Files changed (85) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplace-fetch.d.ts +5 -2
  3. package/dist/catalog/marketplace-fetch.js +4 -1
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/requests.service.d.ts +6 -5
  6. package/dist/catalog/requests.service.js +7 -6
  7. package/dist/config/load.d.ts +6 -0
  8. package/dist/config/load.js +26 -0
  9. package/dist/config/schema.js +5 -5
  10. package/dist/conversations/events.d.ts +10 -0
  11. package/dist/conversations/events.js +23 -1
  12. package/dist/ctx/create-ctx.d.ts +26 -4
  13. package/dist/ctx/create-ctx.js +54 -34
  14. package/dist/devices/devices.controller.js +3 -2
  15. package/dist/devices/devices.service.d.ts +17 -5
  16. package/dist/devices/devices.service.js +24 -13
  17. package/dist/devices/dto.d.ts +7 -6
  18. package/dist/devices/dto.js +6 -5
  19. package/dist/errors.d.ts +6 -1
  20. package/dist/errors.js +6 -1
  21. package/dist/evals/reconstruct.js +18 -8
  22. package/dist/extensions/bootstrap.d.ts +1 -1
  23. package/dist/extensions/bootstrap.js +7 -1
  24. package/dist/extensions/installs.js +4 -1
  25. package/dist/extensions/permission-set.d.ts +7 -6
  26. package/dist/extensions/permission-set.js +9 -6
  27. package/dist/extensions/permission-view.d.ts +4 -4
  28. package/dist/extensions/permission-view.js +10 -5
  29. package/dist/http/app.d.ts +8 -2
  30. package/dist/http/app.js +12 -2
  31. package/dist/http/plugin-dispatch.d.ts +55 -18
  32. package/dist/http/plugin-dispatch.js +124 -29
  33. package/dist/http/plugin-route-access.d.ts +56 -0
  34. package/dist/http/plugin-route-access.js +192 -0
  35. package/dist/identity/auth.guard.d.ts +26 -12
  36. package/dist/identity/auth.guard.js +62 -33
  37. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  38. package/dist/infra/throttler/named-throttlers.js +16 -0
  39. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  40. package/dist/infra/throttler/throttler.guard.js +2 -1
  41. package/dist/kernel.module.js +3 -0
  42. package/dist/lifecycle/kernel-lifecycle.js +1 -3
  43. package/dist/net/public-address.d.ts +14 -4
  44. package/dist/net/public-address.js +22 -12
  45. package/dist/net/safe-fetch.d.ts +2 -1
  46. package/dist/net/safe-fetch.js +16 -4
  47. package/dist/overrides.d.ts +3 -0
  48. package/dist/overrides.js +2 -0
  49. package/dist/packages/npm.d.ts +28 -9
  50. package/dist/packages/npm.js +30 -19
  51. package/dist/packages/provenance.d.ts +3 -1
  52. package/dist/packages/provenance.js +7 -3
  53. package/dist/platform/ops/devices.ops.js +1 -1
  54. package/dist/platform/ops/platform.ops.d.ts +3 -1
  55. package/dist/platform/ops/platform.ops.js +11 -13
  56. package/dist/runtime/context/build.d.ts +10 -1
  57. package/dist/runtime/context/build.js +44 -10
  58. package/dist/runtime/context/compaction.d.ts +27 -8
  59. package/dist/runtime/context/compaction.js +133 -58
  60. package/dist/runtime/context/fit.d.ts +54 -22
  61. package/dist/runtime/context/fit.js +116 -40
  62. package/dist/runtime/model-call.d.ts +0 -8
  63. package/dist/runtime/model-call.js +185 -83
  64. package/dist/sandbox/review/classifier.d.ts +2 -0
  65. package/dist/sandbox/review/classifier.js +12 -1
  66. package/dist/sandbox/review/index.d.ts +3 -3
  67. package/dist/sandbox/review/index.js +3 -3
  68. package/dist/sandbox/review/review.service.d.ts +12 -4
  69. package/dist/sandbox/review/review.service.js +88 -19
  70. package/dist/sandbox/review/rules.d.ts +6 -0
  71. package/dist/sandbox/review/rules.js +1013 -95
  72. package/dist/sandbox/review/types.d.ts +21 -4
  73. package/dist/sandbox/review/types.js +41 -5
  74. package/dist/sandbox/sandbox.service.d.ts +8 -7
  75. package/dist/sandbox/sandbox.service.js +16 -16
  76. package/dist/setup/kernel-checks.js +3 -2
  77. package/dist/setup/oauth-token-probe.d.ts +1 -8
  78. package/dist/setup/oauth-token-probe.js +0 -16
  79. package/dist/tools/builtins/sandbox/common.d.ts +1 -1
  80. package/dist/tools/builtins/sandbox/common.js +1 -1
  81. package/dist/tools/builtins/tool-search.js +4 -3
  82. package/dist/tools/oauth/discovery.d.ts +38 -16
  83. package/dist/tools/oauth/discovery.js +59 -33
  84. package/dist/tools/pipeline.js +17 -13
  85. package/package.json +3 -3
@@ -774,7 +774,12 @@ function homeOf(workspace) {
774
774
  function resolveFacts(facts) {
775
775
  const workspace = normalizePath(facts.workspace);
776
776
  const cwd = facts.cwd === undefined ? workspace : normalizePath(facts.cwd);
777
- return { workspace, cwd, home: homeOf(workspace) };
777
+ return {
778
+ workspace,
779
+ cwd,
780
+ home: homeOf(workspace),
781
+ written: new Set((facts.written ?? []).map((p) => p.endsWith("/**") ? `${normalizePath(p.slice(0, -3))}/**` : normalizePath(p))),
782
+ };
778
783
  }
779
784
  function normalizePath(path) {
780
785
  const absolute = path.startsWith("/");
@@ -886,6 +891,20 @@ const SECRET_HOME_PATHS = [
886
891
  "~/.netrc",
887
892
  "~/.git-credentials",
888
893
  "~/.config/gh/hosts.yml",
894
+ "~/.npmrc",
895
+ "~/.pypirc",
896
+ "~/.vault-token",
897
+ "~/.terraform.d/credentials.tfrc.json",
898
+ "~/.config/op",
899
+ "~/.bash_history",
900
+ "~/.zsh_history",
901
+ "~/.sh_history",
902
+ "~/.history",
903
+ "~/.python_history",
904
+ "~/.node_repl_history",
905
+ "~/.psql_history",
906
+ "~/.mysql_history",
907
+ "~/.local/share/fish/fish_history",
889
908
  ];
890
909
  /**
891
910
  * Home directories that hold credential material. A shell pattern that can expand inside one is a
@@ -1383,6 +1402,8 @@ const READ_PROGRAMS = new Set([
1383
1402
  ]);
1384
1403
  const DEV_PROGRAMS = new Set([
1385
1404
  "node",
1405
+ "tsx",
1406
+ "ts-node",
1386
1407
  "nodejs",
1387
1408
  "deno",
1388
1409
  "bun",
@@ -1481,6 +1502,279 @@ const DEV_PROGRAMS = new Set([
1481
1502
  "seq",
1482
1503
  ]);
1483
1504
  const SHELL_PROGRAMS = new Set(["bash", "sh", "zsh", "dash", "ksh", "fish"]);
1505
+ /**
1506
+ * Interpreters and the options that make them run code written on the command line (hardening
1507
+ * spec R1): `python3 -c`, `node -e`, `perl -e` … run whatever the line says, which no rule can read,
1508
+ * so they are not development commands. A short option counts when its cluster carries the letter
1509
+ * (`python3 -Ic`, `perl -ne`).
1510
+ */
1511
+ const INLINE_CODE_OPTIONS = {
1512
+ python: ["-c"],
1513
+ python2: ["-c"],
1514
+ python3: ["-c"],
1515
+ pypy: ["-c"],
1516
+ pypy3: ["-c"],
1517
+ node: ["-e", "--eval", "-p", "--print"],
1518
+ nodejs: ["-e", "--eval", "-p", "--print"],
1519
+ bun: ["-e", "--eval", "-p", "--print"],
1520
+ tsx: ["-e", "--eval", "-p", "--print"],
1521
+ "ts-node": ["-e", "--eval", "-p", "--print"],
1522
+ ruby: ["-e"],
1523
+ perl: ["-e", "-E"],
1524
+ php: ["-r"],
1525
+ lua: ["-e"],
1526
+ Rscript: ["-e"],
1527
+ julia: ["-e", "-E", "--eval"],
1528
+ elixir: ["-e", "--eval"],
1529
+ osascript: ["-e"],
1530
+ swift: ["-e"],
1531
+ scala: ["-e"],
1532
+ };
1533
+ /** Programs that run a script file named as their first operand (or read one from stdin). */
1534
+ const SCRIPT_RUNNERS = new Set([
1535
+ ...Object.keys(INLINE_CODE_OPTIONS),
1536
+ "deno",
1537
+ "source",
1538
+ ".",
1539
+ ...SHELL_PROGRAMS,
1540
+ ]);
1541
+ /** The script-runner families whose option tables {@link RUNNER_OPTIONS} keys by. */
1542
+ function runnerFamily(program) {
1543
+ if (/^(python[0-9.]*|pypy3?)$/.test(program))
1544
+ return "python";
1545
+ if (["node", "nodejs", "bun", "tsx", "ts-node"].includes(program))
1546
+ return "node";
1547
+ if (SHELL_PROGRAMS.has(program))
1548
+ return "shell";
1549
+ return program;
1550
+ }
1551
+ /**
1552
+ * Per family: the options that take the next word as their value (so it is not the script), and
1553
+ * the ones whose value is itself code the runner loads first (`node -r ./x.js`, `ruby -r`).
1554
+ */
1555
+ const RUNNER_OPTIONS = {
1556
+ python: { value: ["-W", "-X", "--check-hash-based-pycs"], preload: [] },
1557
+ node: {
1558
+ value: [
1559
+ "-r",
1560
+ "--require",
1561
+ "--import",
1562
+ "--loader",
1563
+ "--experimental-loader",
1564
+ "--env-file",
1565
+ "--conditions",
1566
+ "-C",
1567
+ "--title",
1568
+ "--tsconfig",
1569
+ "-P",
1570
+ "--project",
1571
+ "-O",
1572
+ "--compiler-options",
1573
+ "--cwd",
1574
+ "--config",
1575
+ "--preload",
1576
+ ],
1577
+ preload: ["-r", "--require", "--import", "--loader", "--experimental-loader", "--preload"],
1578
+ },
1579
+ deno: {
1580
+ value: [
1581
+ "--config",
1582
+ "-c",
1583
+ "--import-map",
1584
+ "--lock",
1585
+ "--cert",
1586
+ "--location",
1587
+ "--seed",
1588
+ "--env-file",
1589
+ ],
1590
+ preload: [],
1591
+ },
1592
+ shell: { value: ["-o", "+o", "-O", "+O", "--rcfile", "--init-file"], preload: [] },
1593
+ ruby: { value: ["-r", "-I", "-C"], preload: ["-r"] },
1594
+ perl: { value: ["-I", "-M"], preload: [] },
1595
+ php: { value: ["-c", "-d", "-f"], preload: [] },
1596
+ lua: { value: ["-l"], preload: [] },
1597
+ };
1598
+ const NO_OPTIONS = {
1599
+ value: [],
1600
+ preload: [],
1601
+ };
1602
+ /** The subcommands of a script runner that run no script file (`tsx watch` runs the next one). */
1603
+ const RUNNER_SUBCOMMANDS = {
1604
+ tsx: ["watch"],
1605
+ };
1606
+ /**
1607
+ * Packages a package runner may fetch and run as development tools without the review reading
1608
+ * them: the development programs this table already allows, plus the usual locally installed
1609
+ * project tools. Matched by exact bare name only (no scope, no `npm:` alias, no tag other than a
1610
+ * version), so `npx @evil/tsc` or `npx tsc@npm:evil` is not this list.
1611
+ */
1612
+ const RUNNER_TOOLS = new Set([
1613
+ "playwright",
1614
+ "prisma",
1615
+ "turbo",
1616
+ "changeset",
1617
+ "husky",
1618
+ "lint-staged",
1619
+ "tailwindcss",
1620
+ "nx",
1621
+ "wrangler",
1622
+ "drizzle-kit",
1623
+ "astro",
1624
+ "storybook",
1625
+ "rollup",
1626
+ "webpack",
1627
+ "esbuild",
1628
+ "nodemon",
1629
+ "concurrently",
1630
+ "typescript",
1631
+ "vite-node",
1632
+ ]);
1633
+ /** Scoped packages matched exactly by {@link RUNNER_TOOLS}' rule. */
1634
+ const RUNNER_SCOPED_TOOLS = new Set([
1635
+ "@biomejs/biome",
1636
+ "@playwright/test",
1637
+ "@changesets/cli",
1638
+ ]);
1639
+ /** Options of a package manager or runner that take the next word as their value. */
1640
+ const PM_VALUE_OPTIONS = new Set([
1641
+ "--dir",
1642
+ "-C",
1643
+ "--filter",
1644
+ "-F",
1645
+ "--workspace",
1646
+ "-w",
1647
+ "--prefix",
1648
+ "--cwd",
1649
+ "--registry",
1650
+ "--userconfig",
1651
+ "--reporter",
1652
+ "--loglevel",
1653
+ "--python",
1654
+ "-p",
1655
+ "--with",
1656
+ "--from",
1657
+ "--project",
1658
+ "--directory",
1659
+ "--env-file",
1660
+ "--index-url",
1661
+ "--extra-index-url",
1662
+ "-n",
1663
+ "--name",
1664
+ ]);
1665
+ /** The first operand of `args` (skipping options and their values) and what follows it. */
1666
+ function subcommandOf(args) {
1667
+ const options = [];
1668
+ for (let i = 0; i < args.length; i += 1) {
1669
+ const a = args[i];
1670
+ if (a === "--")
1671
+ return { sub: args[i + 1], rest: args.slice(i + 2), options };
1672
+ if (a.startsWith("-")) {
1673
+ options.push(a);
1674
+ if (!a.includes("=") && PM_VALUE_OPTIONS.has(a)) {
1675
+ options.push(args[i + 1] ?? "");
1676
+ i += 1;
1677
+ }
1678
+ continue;
1679
+ }
1680
+ return { sub: a, rest: args.slice(i + 1), options };
1681
+ }
1682
+ return { sub: undefined, rest: [], options };
1683
+ }
1684
+ /**
1685
+ * Package runners: they fetch a package and run it (`npx rimraf`, `pnpm dlx`, `uvx`, `deno x`).
1686
+ * `name` is the package (null when an option chooses or relocates what is fetched, which the review
1687
+ * cannot vouch for: `--package`, `--registry`, `--from`, `--with`), `rest` its arguments.
1688
+ */
1689
+ function runnerPackage(inv) {
1690
+ const { program, args } = inv;
1691
+ let rest = null;
1692
+ let options = [];
1693
+ if (["npx", "pnpx", "bunx", "uvx"].includes(program))
1694
+ rest = args;
1695
+ else if (["pnpm", "yarn", "npm", "bun", "pipx", "uv", "deno"].includes(program)) {
1696
+ const top = subcommandOf(args);
1697
+ options = top.options;
1698
+ if ((program === "pnpm" || program === "yarn") && top.sub === "dlx")
1699
+ rest = top.rest;
1700
+ else if (program === "npm" && (top.sub === "exec" || top.sub === "x"))
1701
+ rest = top.rest;
1702
+ else if (program === "bun" && top.sub === "x")
1703
+ rest = top.rest;
1704
+ else if (program === "pipx" && top.sub === "run")
1705
+ rest = top.rest;
1706
+ else if (program === "uv" && top.sub === "tool" && top.rest[0] === "run")
1707
+ rest = top.rest.slice(1);
1708
+ else if (program === "deno" && (top.sub === "x" || top.sub === "install"))
1709
+ rest = top.rest;
1710
+ }
1711
+ if (rest === null)
1712
+ return undefined;
1713
+ const relocated = (a) => /^(--package|--registry|--userconfig|--from|--with|--index-url|--extra-index-url)(=|$)/.test(a) ||
1714
+ a === "-p" ||
1715
+ a === "-c" ||
1716
+ a === "--call";
1717
+ if (options.some(relocated))
1718
+ return { name: null, rest: [] };
1719
+ const inner = subcommandOf(rest);
1720
+ if (inner.options.some(relocated))
1721
+ return { name: null, rest: [] };
1722
+ return { name: inner.sub ?? null, rest: inner.rest };
1723
+ }
1724
+ /**
1725
+ * The tool a runner package spec names when it is a known development tool: a bare name (or one
1726
+ * of {@link RUNNER_SCOPED_TOOLS}) with at most a version, never an alias (`npm:`, `jsr:`, a URL, a
1727
+ * git or file spec); otherwise null.
1728
+ */
1729
+ function knownRunnerTool(spec) {
1730
+ const scoped = /^(@[a-z0-9-]+\/[a-z0-9._-]+)(?:@[0-9][0-9A-Za-z.+-]*)?$/.exec(spec);
1731
+ if (scoped !== null)
1732
+ return RUNNER_SCOPED_TOOLS.has(scoped[1]) ? scoped[1] : null;
1733
+ const bare = /^([a-z0-9][a-z0-9._-]*)(?:@[0-9][0-9A-Za-z.+-]*)?$/.exec(spec);
1734
+ if (bare === null)
1735
+ return null;
1736
+ const name = bare[1];
1737
+ return DEV_PROGRAMS.has(name) || RUNNER_TOOLS.has(name) ? name : null;
1738
+ }
1739
+ /**
1740
+ * Launchers that run another program in a project environment (`uv run`, `poetry run`, `pnpm
1741
+ * exec`, `yarn node`, `bundle exec`, `bun run`): the program they launch, judged as if it ran
1742
+ * directly; undefined when `inv` launches nothing.
1743
+ */
1744
+ function launchedInvocation(inv) {
1745
+ const { program, args } = inv;
1746
+ const top = subcommandOf(args);
1747
+ const after = (rest) => {
1748
+ const inner = subcommandOf(rest);
1749
+ return inner.sub === undefined ? [] : [inner.sub, ...inner.rest];
1750
+ };
1751
+ let launched;
1752
+ if (ENV_LAUNCHERS.has(program) && top.sub === "run")
1753
+ launched = after(top.rest);
1754
+ else if (program === "bundle" && top.sub === "exec")
1755
+ launched = top.rest;
1756
+ else if (program === "pnpm" || program === "yarn" || program === "bun") {
1757
+ if (top.sub === "exec" || (program === "bun" && top.sub === "run"))
1758
+ launched = after(top.rest);
1759
+ else if (top.sub !== undefined && (top.sub in INLINE_CODE_OPTIONS || /[/.]/.test(top.sub))) {
1760
+ launched = [top.sub, ...top.rest];
1761
+ }
1762
+ }
1763
+ if (launched === undefined || launched.length === 0)
1764
+ return undefined;
1765
+ const raw = launched[0];
1766
+ return { program: baseName(raw), raw, args: launched.slice(1), argv: launched };
1767
+ }
1768
+ /** Project-environment launchers whose `run` subcommand runs another program. */
1769
+ const ENV_LAUNCHERS = new Set([
1770
+ "uv",
1771
+ "poetry",
1772
+ "pipenv",
1773
+ "pdm",
1774
+ "hatch",
1775
+ "rye",
1776
+ "conda",
1777
+ ]);
1484
1778
  const SAFE_SERVE_PROGRAMS = new Set([
1485
1779
  "open",
1486
1780
  "xdg-open",
@@ -1731,12 +2025,73 @@ function gitPushKind(args) {
1731
2025
  }
1732
2026
  return forced ? "force" : null;
1733
2027
  }
2028
+ /**
2029
+ * What a `gh api` call does: `read` for a GET or HEAD without fields, `destroy` for a DELETE,
2030
+ * `write` for anything else (another method, or `-f` / `-F` / `--input`, which make it a POST).
2031
+ */
2032
+ function ghApiMethod(args) {
2033
+ let method = null;
2034
+ let fields = false;
2035
+ for (let i = 0; i < args.length; i += 1) {
2036
+ const a = args[i];
2037
+ if (a === "-X" || a === "--method")
2038
+ method = (args[i + 1] ?? "").toUpperCase();
2039
+ else if (a.startsWith("--method="))
2040
+ method = a.slice("--method=".length).toUpperCase();
2041
+ else if (/^-X./.test(a))
2042
+ method = a.slice(2).toUpperCase();
2043
+ else if (["-f", "-F", "--field", "--raw-field", "--input"].includes(a) ||
2044
+ /^-[fF]./.test(a) ||
2045
+ /^--(raw-)?field=/.test(a) ||
2046
+ a.startsWith("--input="))
2047
+ fields = true;
2048
+ }
2049
+ if (method === "DELETE")
2050
+ return "destroy";
2051
+ // a GraphQL query is a read even though it is sent as a POST; a mutation is a write
2052
+ // `args` starts with the `api` subcommand; the endpoint is the first operand after it
2053
+ const endpoint = args.find((a, i) => i > 0 && !a.startsWith("-") && !isOptionValue(args, i));
2054
+ if (endpoint === "graphql" && (method === null || method === "POST")) {
2055
+ // a body from a file (`--input`, `-F query=@q.graphql`) may hold a mutation the review cannot see
2056
+ const fromFile = args.some((a, i) => a === "--input" || a.startsWith("--input=") || (/=@/.test(a) && i > 0));
2057
+ return fromFile || args.some((a) => /\bmutation\b/.test(a)) ? "write" : "read";
2058
+ }
2059
+ if (method !== null && method !== "GET" && method !== "HEAD")
2060
+ return "write";
2061
+ return fields && method === null ? "write" : "read";
2062
+ }
2063
+ /** Whether `args[i]` is the value of the option before it (`-X GET`, `-f key=value`). */
2064
+ function isOptionValue(args, i) {
2065
+ const before = args[i - 1];
2066
+ return (before !== undefined &&
2067
+ [
2068
+ "-X",
2069
+ "--method",
2070
+ "-f",
2071
+ "-F",
2072
+ "--field",
2073
+ "--raw-field",
2074
+ "--input",
2075
+ "-H",
2076
+ "--header",
2077
+ "--jq",
2078
+ "-q",
2079
+ "--template",
2080
+ "-t",
2081
+ "--hostname",
2082
+ "--cache",
2083
+ "-p",
2084
+ "--preview",
2085
+ ].includes(before));
2086
+ }
1734
2087
  function ghIsSafe(args) {
1735
2088
  const cleaned = args.filter((a) => !a.startsWith("-"));
1736
2089
  const sub = cleaned[0];
1737
2090
  const action = cleaned[1];
1738
- if (sub === undefined || sub === "api" || sub === "search")
2091
+ if (sub === undefined || sub === "search")
1739
2092
  return true;
2093
+ if (sub === "api")
2094
+ return ghApiMethod(args) === "read";
1740
2095
  if (sub === "auth")
1741
2096
  return ["login", "logout", "status", "switch", "setup-git", "token"].includes(action ?? "");
1742
2097
  if (sub === "pr") {
@@ -2015,6 +2370,30 @@ const TAR_VALUE_LETTERS = new Set([
2015
2370
  "V",
2016
2371
  "X",
2017
2372
  ]);
2373
+ /** The files a `tar` command names (its operands other than the archive `-f` names). */
2374
+ function tarMembers(args) {
2375
+ const index = args.findIndex((a) => a === "-f" || a === "--file" || /^-[A-Za-z]*f$/.test(a));
2376
+ const archive = index >= 0 ? args[index + 1] : undefined;
2377
+ return operands(args).filter((op) => op !== archive);
2378
+ }
2379
+ /** git subcommands that rewrite files in the work tree they run in. */
2380
+ const GIT_WORKTREE_WRITERS = new Set([
2381
+ "clean",
2382
+ "checkout",
2383
+ "restore",
2384
+ "reset",
2385
+ "rm",
2386
+ "mv",
2387
+ "stash",
2388
+ "switch",
2389
+ "pull",
2390
+ "merge",
2391
+ "rebase",
2392
+ "am",
2393
+ "apply",
2394
+ "cherry-pick",
2395
+ "revert",
2396
+ ]);
2018
2397
  function writeTargetsOf(inv) {
2019
2398
  const { program, args } = inv;
2020
2399
  const positional = nonOptionArgs(args);
@@ -2089,12 +2468,17 @@ function writeTargetsOf(inv) {
2089
2468
  case "rsync": {
2090
2469
  const last = positional[positional.length - 1];
2091
2470
  // `host:path` and `rsync://...` are remote: the command writes there, not here.
2092
- return last !== undefined && !isRemoteSpec(last) ? [last] : [];
2471
+ const out = last !== undefined && !isRemoteSpec(last) ? [last] : [];
2472
+ // `--remove-source-files` deletes the local sources it sent
2473
+ if (program === "rsync" && args.includes("--remove-source-files")) {
2474
+ out.push(...positional.slice(0, -1).filter((op) => !isRemoteSpec(op)));
2475
+ }
2476
+ return out;
2093
2477
  }
2094
2478
  case "tar": {
2095
2479
  // `-C DIR` extracts into DIR; `-cf ARCHIVE` writes ARCHIVE. `-C` on create only selects
2096
- // the files read, so it is not a write target there.
2097
- const targets = [];
2480
+ // the files read, so it is not a write target there. `--remove-files` deletes its members.
2481
+ const targets = args.includes("--remove-files") ? tarMembers(args) : [];
2098
2482
  let directory = null;
2099
2483
  let extract = false;
2100
2484
  let create = false;
@@ -2200,6 +2584,11 @@ function writeTargetsOf(inv) {
2200
2584
  return dirs.length > 0 ? dirs : ["."];
2201
2585
  }
2202
2586
  case "git": {
2587
+ // a subcommand that rewrites the work tree writes where it runs (`git -C ~/x checkout -- .`)
2588
+ if (GIT_WORKTREE_WRITERS.has(args[0] ?? "")) {
2589
+ const paths = args[0] === "clean" ? operands(args.slice(1)) : [];
2590
+ return [inv.dir ?? ".", ...paths];
2591
+ }
2203
2592
  if (args[0] !== "clone")
2204
2593
  return [];
2205
2594
  // `git clone [opts] <url> [dest]`: option values are skipped, so `--depth 1` does not shift
@@ -2260,6 +2649,234 @@ function writeTargets(command) {
2260
2649
  }
2261
2650
  return out;
2262
2651
  }
2652
+ /** Whether `command` reads the output of an earlier command of the same pipeline (`a | b`). */
2653
+ function pipedInto(command, commands) {
2654
+ const index = commands.indexOf(command);
2655
+ return commands
2656
+ .slice(0, Math.max(index, 0))
2657
+ .some((c) => c.pipeline === command.pipeline && c.block === command.block);
2658
+ }
2659
+ /** The option table of a script runner. */
2660
+ const optionsOf = (program) => RUNNER_OPTIONS[runnerFamily(program)] ?? NO_OPTIONS;
2661
+ /** Whether a short or long option of `inv` makes its interpreter run code given inline. */
2662
+ function inlineCodeOption(inv) {
2663
+ if (inv.program === "deno")
2664
+ return inv.args[0] === "eval";
2665
+ const options = INLINE_CODE_OPTIONS[inv.program];
2666
+ if (options === undefined)
2667
+ return false;
2668
+ const values = optionsOf(inv.program).value;
2669
+ const letters = options.filter((o) => /^-[A-Za-z]$/.test(o)).map((o) => o.slice(1));
2670
+ const longs = options.filter((o) => o.startsWith("--"));
2671
+ for (let i = 0; i < inv.args.length; i += 1) {
2672
+ const a = inv.args[i];
2673
+ if (a === "--")
2674
+ return false;
2675
+ if (longs.some((l) => a === l || a.startsWith(`${l}=`)))
2676
+ return true;
2677
+ if (/^-[A-Za-z]+$/.test(a)) {
2678
+ if ([...a.slice(1)].some((letter) => letters.includes(letter)))
2679
+ return true;
2680
+ // `python -m module`: what follows is the module's own arguments
2681
+ if (a === "-m")
2682
+ return false;
2683
+ if (values.includes(a))
2684
+ i += 1;
2685
+ continue;
2686
+ }
2687
+ if (a.startsWith("-") || a.startsWith("+")) {
2688
+ if (values.includes(a))
2689
+ i += 1;
2690
+ continue;
2691
+ }
2692
+ // the first operand is the script; what follows is the script's own arguments
2693
+ return false;
2694
+ }
2695
+ return false;
2696
+ }
2697
+ /** The file extensions of scripts: a word with one names a file a runner or launcher would run. */
2698
+ const SCRIPT_FILE = /\.(py|pyw|js|mjs|cjs|ts|mts|cts|tsx|jsx|sh|bash|zsh|fish|rb|pl|php|lua|[rR]|jl|exs?|swift|scala|go)$/;
2699
+ /**
2700
+ * The runner's operands after its options: the first is the script (or `-` for stdin); null when
2701
+ * there is none (it reads stdin or starts a REPL), undefined when the runner runs something else
2702
+ * (`python -m pytest`, `deno test`, `bun install`).
2703
+ */
2704
+ function scriptOperand(inv) {
2705
+ let args = inv.args;
2706
+ const subcommands = RUNNER_SUBCOMMANDS[inv.program] ?? [];
2707
+ if (inv.program === "deno") {
2708
+ if (args[0] === "run" || args[0] === "serve")
2709
+ args = args.slice(1);
2710
+ else {
2711
+ const first = subcommandOf(args).sub;
2712
+ if (first === undefined || !(first.includes("/") || SCRIPT_FILE.test(first)))
2713
+ return undefined;
2714
+ }
2715
+ }
2716
+ const values = optionsOf(inv.program).value;
2717
+ for (let i = 0; i < args.length; i += 1) {
2718
+ const a = args[i];
2719
+ if (a === "--")
2720
+ return args[i + 1] ?? null;
2721
+ if (a === "-")
2722
+ return "-";
2723
+ if (a === "-m")
2724
+ return undefined;
2725
+ if (a.startsWith("-") || (a.startsWith("+") && runnerFamily(inv.program) === "shell")) {
2726
+ if (!a.includes("=") && values.includes(a))
2727
+ i += 1;
2728
+ continue;
2729
+ }
2730
+ if (subcommands.includes(a))
2731
+ continue;
2732
+ // `bun install`, `bun test`: a bun subcommand or package script, not a file
2733
+ if (inv.program === "bun" && !a.includes("/") && !SCRIPT_FILE.test(a))
2734
+ return undefined;
2735
+ return a;
2736
+ }
2737
+ return null;
2738
+ }
2739
+ /** The module `python -m <module>` runs, as the files it may load (`a.b` → `a/b.py`, `a/b/__main__.py`). */
2740
+ function moduleFiles(inv) {
2741
+ if (runnerFamily(inv.program) !== "python")
2742
+ return [];
2743
+ const index = inv.args.indexOf("-m");
2744
+ const module = index < 0 ? undefined : inv.args[index + 1];
2745
+ if (module === undefined || !/^[A-Za-z_][\w.]*$/.test(module))
2746
+ return [];
2747
+ const path = module.replaceAll(".", "/");
2748
+ return [`${path}.py`, `${path}/__main__.py`, `${path}/__init__.py`];
2749
+ }
2750
+ /** The values of a runner's preload options (`node -r ./x.js`, `--import`, `ruby -r`). */
2751
+ function preloadValues(inv) {
2752
+ const preload = optionsOf(inv.program).preload;
2753
+ const out = [];
2754
+ for (let i = 0; i < inv.args.length; i += 1) {
2755
+ const a = inv.args[i];
2756
+ const eq = a.indexOf("=");
2757
+ if (eq > 0 && preload.includes(a.slice(0, eq)))
2758
+ out.push(a.slice(eq + 1));
2759
+ else if (preload.includes(a) && inv.args[i + 1] !== undefined)
2760
+ out.push(inv.args[i + 1]);
2761
+ }
2762
+ return out;
2763
+ }
2764
+ /** A shell glob as an anchored regular expression over a full path. */
2765
+ function globRegex(pattern) {
2766
+ let source = "";
2767
+ for (const ch of pattern) {
2768
+ if (ch === "*")
2769
+ source += "[^/]*";
2770
+ else if (ch === "?")
2771
+ source += "[^/]";
2772
+ else
2773
+ source += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
2774
+ }
2775
+ return new RegExp(`^${source}$`, "i");
2776
+ }
2777
+ /**
2778
+ * Whether a path word names something this conversation (or an earlier command of the line)
2779
+ * wrote: compared without case (macOS file systems ignore it), a glob matched against every
2780
+ * written path, and a cloned directory counting for everything under it.
2781
+ */
2782
+ function writtenMatcher(command, ctx) {
2783
+ const written = [...ctx.facts.written, ...(ctx.writtenBefore.get(command) ?? [])].map((p) => p.toLowerCase());
2784
+ const cwd = cwdOf(command, ctx.facts);
2785
+ return (word) => {
2786
+ const resolved = expandPath(word, ctx.facts, cwd, command.vars);
2787
+ if (resolved === null)
2788
+ return false;
2789
+ const path = resolved.toLowerCase();
2790
+ if (SHELL_PATTERN.test(word)) {
2791
+ const re = globRegex(path);
2792
+ return written.some((w) => re.test(w.endsWith("/**") ? w.slice(0, -3) : w));
2793
+ }
2794
+ return written.some((w) => (w.endsWith("/**") ? path.startsWith(w.slice(0, -2)) : w === path));
2795
+ };
2796
+ }
2797
+ const RISK_INLINE = "Runs code written inline for an interpreter; the review cannot read it.";
2798
+ const RISK_FETCHED = "Runs a package or module it fetches; the review cannot read its code.";
2799
+ const RISK_STDIN = "Feeds code to an interpreter on its standard input; the review cannot read it.";
2800
+ const RISK_URL = "Runs code from a URL or package registry; the review cannot read it.";
2801
+ const RISK_WROTE = "Runs a file this conversation wrote; the review cannot vouch for its code.";
2802
+ /**
2803
+ * Why running `inv` is code the review cannot read (hardening spec R1), or null when it is an
2804
+ * ordinary development command: inline code (also through a launcher such as `uv run` or `pnpm
2805
+ * exec`), a fetched package or module, code fed on stdin or from a URL, a program whose own
2806
+ * script language runs commands (`awk` `system()`, `sed` `e`), or a file this conversation (or an
2807
+ * earlier command of the line) wrote — run directly, as a script, a preload or a module.
2808
+ */
2809
+ function interpreterRisk(inv, command, ctx) {
2810
+ const launched = launchedInvocation(inv);
2811
+ if (launched !== undefined)
2812
+ return interpreterRisk(launched, command, ctx);
2813
+ const written = writtenMatcher(command, ctx);
2814
+ const cwd = cwdOf(command, ctx.facts);
2815
+ const pkg = runnerPackage(inv);
2816
+ if (pkg !== undefined) {
2817
+ const tool = pkg.name === null ? null : knownRunnerTool(pkg.name);
2818
+ if (tool === null)
2819
+ return RISK_FETCHED;
2820
+ // a local bin the conversation replaced is not the tool any more
2821
+ if (written(`${cwd}/node_modules/.bin/${baseName(tool)}`))
2822
+ return RISK_WROTE;
2823
+ return SCRIPT_RUNNERS.has(tool)
2824
+ ? interpreterRisk({ ...inv, program: tool, raw: tool, args: pkg.rest }, command, ctx)
2825
+ : null;
2826
+ }
2827
+ if (inv.program === "go" && inv.args[0] === "run") {
2828
+ const target = subcommandOf(inv.args.slice(1)).sub;
2829
+ if (target === undefined)
2830
+ return null;
2831
+ if (target.includes("@") || /^[a-z0-9-]+(\.[a-z0-9-]+)+\//i.test(target))
2832
+ return RISK_FETCHED;
2833
+ return written(target) ? RISK_WROTE : null;
2834
+ }
2835
+ if (inv.program === "make" || inv.program === "gmake") {
2836
+ const file = inv.args.find((_, i) => ["-f", "--file", "--makefile"].includes(inv.args[i - 1] ?? ""));
2837
+ if (file === "-" || file === "/dev/stdin")
2838
+ return RISK_STDIN;
2839
+ return written(file ?? "Makefile") ? RISK_WROTE : null;
2840
+ }
2841
+ if (["awk", "gawk", "mawk", "nawk"].includes(inv.program)) {
2842
+ const program = inv.args.find((a) => !a.startsWith("-"));
2843
+ if (program !== undefined && /\bsystem\s*\(|\|\s*getline|print[^;]*\|\s*"/.test(program)) {
2844
+ return RISK_INLINE;
2845
+ }
2846
+ return null;
2847
+ }
2848
+ if (inv.program === "sed") {
2849
+ const scripts = inv.args.filter((a, i) => !a.startsWith("-") || inv.args[i - 1] === "-e");
2850
+ if (scripts.some((sc) => /(^|[;\n])\s*e(\s|$)|\/[gpiImMw0-9]*e[gpiImMw0-9]*\s*$/.test(sc))) {
2851
+ return RISK_INLINE;
2852
+ }
2853
+ return null;
2854
+ }
2855
+ if (!SCRIPT_RUNNERS.has(inv.program)) {
2856
+ // a program run by its path (`./x.sh`, `bin/tool`) or by its script name
2857
+ return (inv.raw.includes("/") || SCRIPT_FILE.test(inv.raw)) && written(inv.raw)
2858
+ ? RISK_WROTE
2859
+ : null;
2860
+ }
2861
+ if (inlineCodeOption(inv))
2862
+ return RISK_INLINE;
2863
+ if (SHELL_PROGRAMS.has(inv.program) && wrapperScript(inv) !== null)
2864
+ return null;
2865
+ if (preloadValues(inv).some((value) => written(value)))
2866
+ return RISK_WROTE;
2867
+ if (moduleFiles(inv).some((file) => written(file)))
2868
+ return RISK_WROTE;
2869
+ const script = scriptOperand(inv);
2870
+ if (script === undefined)
2871
+ return null;
2872
+ if (script === null || script === "-") {
2873
+ const fed = command.redirects.some((r) => r.op === "<") || pipedInto(command, ctx.commands);
2874
+ return fed ? RISK_STDIN : null;
2875
+ }
2876
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(script) || /^(npm|jsr):/.test(script))
2877
+ return RISK_URL;
2878
+ return written(script) ? RISK_WROTE : null;
2879
+ }
2263
2880
  /** Every command an invocation of which satisfies `visit`; used to mark commands as covered. */
2264
2881
  function eachInvocation(commands, visit) {
2265
2882
  const matched = [];
@@ -3034,6 +3651,14 @@ function gitConfigIsDangerous(key, value) {
3034
3651
  }
3035
3652
  if (k === "core.askpass" || k === "diff.external" || /^http\..*\.cmd$/.test(k))
3036
3653
  return true;
3654
+ // hooks, the file system monitor and filter / diff / merge drivers run programs too
3655
+ if (k === "core.hookspath" || k === "core.gitproxy")
3656
+ return true;
3657
+ if (k === "core.fsmonitor")
3658
+ return !/^(true|false|0|1|yes|no|on|off)$/i.test(value.trim());
3659
+ if (/^(filter\..*\.(clean|smudge|process)|diff\..*\.(textconv|command)|merge\..*\.driver)$/.test(k)) {
3660
+ return true;
3661
+ }
3037
3662
  return false;
3038
3663
  }
3039
3664
  /**
@@ -3256,23 +3881,6 @@ function writesOutside(inv, command, ctx) {
3256
3881
  }
3257
3882
  return false;
3258
3883
  }
3259
- function rmIsRecursiveForce(args) {
3260
- let recursive = false;
3261
- let force = false;
3262
- for (const a of args) {
3263
- if (a === "--recursive")
3264
- recursive = true;
3265
- else if (a === "--force")
3266
- force = true;
3267
- else if (/^-[A-Za-z]+$/.test(a)) {
3268
- if (a.includes("r") || a.includes("R"))
3269
- recursive = true;
3270
- if (a.includes("f"))
3271
- force = true;
3272
- }
3273
- }
3274
- return recursive && force;
3275
- }
3276
3884
  /** The part of a path before its first glob segment: `rm -rf /home/*` deletes `/home`. */
3277
3885
  function globBase(path) {
3278
3886
  const parts = path.split("/");
@@ -3281,12 +3889,78 @@ function globBase(path) {
3281
3889
  return path;
3282
3890
  return parts.slice(0, index).join("/") || "/";
3283
3891
  }
3892
+ /**
3893
+ * The paths an invocation destroys rather than writes into (hardening spec R2): what `rm`, `rmdir`,
3894
+ * `unlink`, `shred` and `truncate` name, the sources `mv` moves away, the targets of a recursive
3895
+ * `chmod` / `chown` / `chgrp`, where `find … -delete` starts, and the destination `rsync --delete`
3896
+ * prunes. A directory that `cp` or `ln` writes into is not destroyed.
3897
+ */
3898
+ function destroyTargetsOf(inv) {
3899
+ const { program, args } = inv;
3900
+ switch (program) {
3901
+ case "rm":
3902
+ case "rmdir":
3903
+ case "unlink":
3904
+ case "shred":
3905
+ case "truncate":
3906
+ return operands(args);
3907
+ case "mv": {
3908
+ const ops = operands(args);
3909
+ return targetDirectory(args) !== null ? ops : ops.slice(0, -1);
3910
+ }
3911
+ case "chmod":
3912
+ case "chown":
3913
+ case "chgrp":
3914
+ return args.some((a) => a === "--recursive" || /^-[A-Za-z]*R/.test(a))
3915
+ ? operands(args).slice(1)
3916
+ : [];
3917
+ case "find": {
3918
+ if (!args.includes("-delete"))
3919
+ return [];
3920
+ const starts = [];
3921
+ for (let i = 0; i < args.length; i += 1) {
3922
+ const a = args[i];
3923
+ // the symlink and optimisation options come before the start paths
3924
+ if (["-H", "-L", "-P"].includes(a) || /^-O[0-9]$/.test(a))
3925
+ continue;
3926
+ if (a === "-D") {
3927
+ i += 1;
3928
+ continue;
3929
+ }
3930
+ if (a.startsWith("-") || a === "(" || a === "!")
3931
+ break;
3932
+ starts.push(a);
3933
+ }
3934
+ return starts.length > 0 ? starts : ["."];
3935
+ }
3936
+ case "rsync": {
3937
+ const ops = operands(args).filter((op) => !isRemoteSpec(op));
3938
+ const out = [];
3939
+ if (args.includes("--remove-source-files"))
3940
+ out.push(...ops.slice(0, -1));
3941
+ if (args.some((a) => a.startsWith("--delete"))) {
3942
+ const last = operands(args).at(-1);
3943
+ if (last !== undefined && !isRemoteSpec(last))
3944
+ out.push(last);
3945
+ }
3946
+ return out;
3947
+ }
3948
+ case "tar":
3949
+ return args.includes("--remove-files") ? tarMembers(args) : [];
3950
+ case "git":
3951
+ // `git clean <path>`: what it names; without a path it cleans untracked files, not the tree
3952
+ return args[0] === "clean" ? operands(args.slice(1)) : [];
3953
+ default:
3954
+ return [];
3955
+ }
3956
+ }
3284
3957
  function isDangerousDelete(resolved, ctx) {
3285
3958
  const base = globBase(resolved);
3286
3959
  const t = tildeForm(base, ctx.facts);
3287
3960
  if (t === "/" || t === "~" || t === "~/")
3288
3961
  return true;
3289
- return isAncestor(base, ctx.facts.workspace);
3962
+ // the workspace root itself and every directory above it (hardening spec R2)
3963
+ return base === ctx.facts.workspace || isAncestor(base, ctx.facts.workspace);
3290
3964
  }
3291
3965
  function modifiesDevice(command, ctx) {
3292
3966
  // Only a write redirect that really lands on a device path counts (`2>/dev/null`, a listing to
@@ -3322,6 +3996,129 @@ function modifiesDevice(command, ctx) {
3322
3996
  "ed",
3323
3997
  ].includes(inv.program)).length > 0);
3324
3998
  }
3999
+ const CONFIG_REASONS = {
4000
+ "ask.shell-config": "Changes a shell rc file or the global git configuration; this needs approval.",
4001
+ "ask.persistence": "Installs something that runs later (crontab, a launch agent, a systemd unit or a git hook); this needs approval.",
4002
+ "ask.ssh": "Changes or prints SSH keys or configuration; this needs approval.",
4003
+ "ask.secret-file": "Prints, copies or changes a credential file; this needs approval each time.",
4004
+ };
4005
+ /** The grant class of a secret or persistence path. */
4006
+ function configClassOf(path, facts) {
4007
+ const t = tildeForm(path, facts);
4008
+ if (t === "~/.ssh" || t.startsWith("~/.ssh/"))
4009
+ return "ask.ssh";
4010
+ if (isGitHook(path) ||
4011
+ /^(~|)\/Library\/Launch(Agents|Daemons)/.test(t) ||
4012
+ t === "/etc/crontab" ||
4013
+ t.startsWith("/var/spool/cron") ||
4014
+ t.startsWith("/etc/cron.") ||
4015
+ t.startsWith("~/.config/systemd")) {
4016
+ return "ask.persistence";
4017
+ }
4018
+ return isPersistencePath(path, facts) ? "ask.shell-config" : "ask.secret-file";
4019
+ }
4020
+ /**
4021
+ * What each config class matched in the line: the programs that change those locations
4022
+ * themselves (crontab, launchctl, ssh-keygen, `git config --global`, a keychain dump), unresolved
4023
+ * words that may name a credential, and every secret or persistence path a command touches other
4024
+ * than as its own tool's credential.
4025
+ */
4026
+ function configMatches(ctx) {
4027
+ const found = new Map();
4028
+ const add = (cls, command, why) => {
4029
+ const entry = found.get(cls);
4030
+ if (entry === undefined)
4031
+ found.set(cls, { why: why ?? CONFIG_REASONS[cls], commands: [command] });
4032
+ else if (!entry.commands.includes(command))
4033
+ entry.commands.push(command);
4034
+ };
4035
+ for (const command of ctx.commands) {
4036
+ for (const inv of invocationsOf(command)) {
4037
+ if (inv.program === "crontab" &&
4038
+ (!inv.args.includes("-l") || nonOptionArgs(inv.args).length > 0)) {
4039
+ add("ask.persistence", command, "Changes crontab; this needs approval.");
4040
+ }
4041
+ if (inv.program === "launchctl") {
4042
+ const action = nonOptionArgs(inv.args)[0];
4043
+ if (action !== undefined && LAUNCHCTL_CHANGES.includes(action)) {
4044
+ add("ask.persistence", command, "Changes a launch agent; this needs approval.");
4045
+ }
4046
+ }
4047
+ if (inv.program === "ssh-keygen")
4048
+ add("ask.ssh", command, "Changes ~/.ssh; this needs approval.");
4049
+ if (inv.program === "git" &&
4050
+ inv.args[0] === "config" &&
4051
+ hasArg(inv.args.slice(1), "--global", "--system")) {
4052
+ add("ask.shell-config", command, "Changes ~/.gitconfig; this needs approval.");
4053
+ }
4054
+ if (inv.program === "security" && inv.args.some((a) => KEYCHAIN_DUMP.test(a))) {
4055
+ add("ask.secret-file", command, "Prints a macOS keychain item; this needs approval.");
4056
+ }
4057
+ }
4058
+ if (commandHasUnresolvedSecret(command, ctx))
4059
+ add("ask.secret-file", command);
4060
+ const touched = [...persistenceTokens(command, ctx.facts), ...secretTokens(command, ctx.facts)];
4061
+ if (touched.length === 0)
4062
+ continue;
4063
+ const ownersOnly = eachInvocation([command], (inv) => isSecretOwner(inv.program, touched, ctx.facts)).length > 0;
4064
+ const credentials = credentialSecretTokens(command, ctx);
4065
+ if (ownersOnly || touched.every((path) => credentials.has(path)))
4066
+ continue;
4067
+ for (const path of touched) {
4068
+ if (!credentials.has(path))
4069
+ add(configClassOf(path, ctx.facts), command);
4070
+ }
4071
+ }
4072
+ return found;
4073
+ }
4074
+ function configRule(id) {
4075
+ return {
4076
+ id,
4077
+ outcome: "ask",
4078
+ check: (ctx) => {
4079
+ const match = configMatches(ctx).get(id);
4080
+ return match === undefined ? null : { reason: match.why, commands: match.commands };
4081
+ },
4082
+ };
4083
+ }
4084
+ /** The paths an `ln` links to (its sources), resolved against the command's directory. */
4085
+ function linkSources(inv, command, ctx) {
4086
+ const cpLink = inv.program === "cp" &&
4087
+ inv.args.some((a) => ["--symbolic-link", "--link"].includes(a) || /^-[A-Za-z]*[sl]/.test(a));
4088
+ if (inv.program !== "ln" && !cpLink)
4089
+ return [];
4090
+ const ops = operands(inv.args);
4091
+ const directory = targetDirectory(inv.args);
4092
+ const sources = directory !== null || ops.length < 2 ? ops : ops.slice(0, -1);
4093
+ const symbolic = cpLink || inv.args.some((a) => a === "--symbolic" || /^-[A-Za-z]*s/.test(a));
4094
+ const cwd = cwdOf(command, ctx.facts);
4095
+ // a relative symbolic link points from the link's own directory, not from where ln ran
4096
+ const linkDir = directory ?? (ops.length >= 2 ? ops.at(-1).replace(/\/[^/]*$/, "") || "." : ".");
4097
+ const base = symbolic ? (expandPath(linkDir, ctx.facts, cwd, command.vars) ?? cwd) : cwd;
4098
+ const out = [];
4099
+ for (const source of sources) {
4100
+ const resolved = expandPath(source, ctx.facts, source.startsWith("/") ? cwd : base, command.vars);
4101
+ if (resolved !== null)
4102
+ out.push(resolved);
4103
+ }
4104
+ return out;
4105
+ }
4106
+ /**
4107
+ * What a link would expose (hardening spec R3): a credential, SSH, persistence or device path, or
4108
+ * the home directory or `/` itself (a link to them reaches every secret under them) is
4109
+ * `sensitive`; anything else outside the workspace and temporary files is `outside`.
4110
+ */
4111
+ function linkClass(path, ctx) {
4112
+ if (inside(path, ctx.facts.workspace) || tmpRootOf(path))
4113
+ return null;
4114
+ if (isSecretPath(path, ctx.facts) ||
4115
+ isPersistencePath(path, ctx.facts) ||
4116
+ isDevicePath(path, ctx.facts) ||
4117
+ isDangerousDelete(path, ctx)) {
4118
+ return "sensitive";
4119
+ }
4120
+ return "outside";
4121
+ }
3325
4122
  const RULES = [
3326
4123
  {
3327
4124
  id: "allow.read",
@@ -3385,9 +4182,12 @@ const RULES = [
3385
4182
  id: "allow.dev",
3386
4183
  outcome: "allow",
3387
4184
  check: (ctx) => {
3388
- const matched = eachInvocation(ctx.commands, (inv) => {
4185
+ const matched = eachInvocation(ctx.commands, (inv, command) => {
3389
4186
  if (credentialProducer(inv))
3390
4187
  return false;
4188
+ // code the review cannot read is not a development command (`unsure.interpreter`)
4189
+ if (interpreterRisk(inv, command, ctx) !== null)
4190
+ return false;
3391
4191
  if (globalInstallOf(inv.program, inv.args, ctx.venv || venvBinary(inv.raw)))
3392
4192
  return false;
3393
4193
  const local = inv.raw.startsWith("./") || inv.raw.startsWith("../");
@@ -3408,6 +4208,21 @@ const RULES = [
3408
4208
  : null;
3409
4209
  },
3410
4210
  },
4211
+ {
4212
+ id: "unsure.interpreter",
4213
+ outcome: "unsure",
4214
+ check: (ctx) => {
4215
+ let why = null;
4216
+ const matched = eachInvocation(ctx.commands, (inv, command) => {
4217
+ const risk = interpreterRisk(inv, command, ctx);
4218
+ if (risk === null)
4219
+ return false;
4220
+ why ??= risk;
4221
+ return true;
4222
+ });
4223
+ return why === null ? null : { reason: why, commands: matched };
4224
+ },
4225
+ },
3411
4226
  {
3412
4227
  id: "allow.git",
3413
4228
  outcome: "allow",
@@ -3601,8 +4416,6 @@ const RULES = [
3601
4416
  isPersistencePath(resolved, ctx.facts) ||
3602
4417
  isDevicePath(resolved, ctx.facts)))
3603
4418
  continue;
3604
- if (resolved !== null && isDangerousDelete(resolved, ctx))
3605
- continue;
3606
4419
  matched.push(command);
3607
4420
  why ??=
3608
4421
  resolved === null
@@ -3662,68 +4475,56 @@ const RULES = [
3662
4475
  why ??= "Deletes a GitHub release; this needs approval.";
3663
4476
  return true;
3664
4477
  }
4478
+ if (inv.program === "gh" && inv.args[0] === "api" && ghApiMethod(inv.args) === "destroy") {
4479
+ why ??= "Deletes something on GitHub through the API; this needs approval.";
4480
+ return true;
4481
+ }
3665
4482
  return false;
3666
4483
  });
3667
4484
  return why === null ? null : { reason: why, commands: matched };
3668
4485
  },
3669
4486
  },
3670
4487
  {
3671
- id: "ask.rc-files",
4488
+ id: "ask.remote-write",
3672
4489
  outcome: "ask",
3673
4490
  check: (ctx) => {
3674
- let why = null;
3675
- const matched = eachInvocation(ctx.commands, (inv) => {
3676
- if (inv.program === "crontab" &&
3677
- (!inv.args.includes("-l") || nonOptionArgs(inv.args).length > 0)) {
3678
- why ??= "Changes crontab; this needs approval.";
3679
- return true;
3680
- }
3681
- if (inv.program === "launchctl") {
3682
- const action = nonOptionArgs(inv.args)[0];
3683
- if (action !== undefined && LAUNCHCTL_CHANGES.includes(action)) {
3684
- why ??= "Changes a launch agent; this needs approval.";
3685
- return true;
3686
- }
3687
- }
3688
- if (inv.program === "ssh-keygen") {
3689
- why ??= "Changes ~/.ssh; this needs approval.";
3690
- return true;
3691
- }
3692
- if (inv.program === "git" &&
3693
- inv.args[0] === "config" &&
3694
- hasArg(inv.args.slice(1), "--global", "--system")) {
3695
- why ??= "Changes ~/.gitconfig; this needs approval.";
3696
- return true;
4491
+ const matched = eachInvocation(ctx.commands, (inv) => inv.program === "gh" && inv.args[0] === "api" && ghApiMethod(inv.args) === "write");
4492
+ return matched.length > 0
4493
+ ? {
4494
+ reason: "Changes something on GitHub through the API; this needs approval.",
4495
+ commands: matched,
3697
4496
  }
3698
- return false;
3699
- });
3700
- for (const command of ctx.commands) {
3701
- if (commandHasUnresolvedSecret(command, ctx)) {
3702
- matched.push(command);
3703
- why ??=
3704
- "Changes or prints a shell rc file, SSH configuration or another secret/persistence location; this needs approval.";
4497
+ : null;
4498
+ },
4499
+ },
4500
+ configRule("ask.shell-config"),
4501
+ configRule("ask.persistence"),
4502
+ configRule("ask.ssh"),
4503
+ configRule("ask.secret-file"),
4504
+ {
4505
+ id: "ask.outside-link",
4506
+ outcome: "ask",
4507
+ check: (ctx) => {
4508
+ const matched = eachInvocation(ctx.commands, (inv, command) => linkSources(inv, command, ctx).some((path) => linkClass(path, ctx) === "outside"));
4509
+ return matched.length > 0
4510
+ ? {
4511
+ reason: "Links to a path outside the workspace and temporary files; this needs approval.",
4512
+ commands: matched,
3705
4513
  }
3706
- const touched = [
3707
- ...persistenceTokens(command, ctx.facts),
3708
- ...secretTokens(command, ctx.facts),
3709
- ];
3710
- if (touched.length === 0)
3711
- continue;
3712
- const ownersOnly = eachInvocation([command], (inv) => isSecretOwner(inv.program, touched, ctx.facts))
3713
- .length > 0;
3714
- const credentials = credentialSecretTokens(command, ctx);
3715
- if (!ownersOnly && !touched.every((path) => credentials.has(path))) {
3716
- matched.push(command);
3717
- why ??=
3718
- "Changes or prints a shell rc file, SSH configuration or another secret/persistence location; this needs approval.";
4514
+ : null;
4515
+ },
4516
+ },
4517
+ {
4518
+ id: "ask.credential-link",
4519
+ outcome: "ask",
4520
+ check: (ctx) => {
4521
+ const matched = eachInvocation(ctx.commands, (inv, command) => linkSources(inv, command, ctx).some((path) => linkClass(path, ctx) === "sensitive"));
4522
+ return matched.length > 0
4523
+ ? {
4524
+ reason: "Links to a credential, SSH or startup file, or to the home directory itself; this needs approval each time.",
4525
+ commands: matched,
3719
4526
  }
3720
- }
3721
- const keychain = eachInvocation(ctx.commands, (inv) => inv.program === "security" && inv.args.some((a) => KEYCHAIN_DUMP.test(a)));
3722
- if (keychain.length > 0) {
3723
- matched.push(...keychain);
3724
- why ??= "Prints a macOS keychain item; this needs approval.";
3725
- }
3726
- return why === null ? null : { reason: why, commands: matched };
4527
+ : null;
3727
4528
  },
3728
4529
  },
3729
4530
  {
@@ -3877,22 +4678,26 @@ const RULES = [
3877
4678
  },
3878
4679
  },
3879
4680
  {
3880
- id: "deny.root-delete",
4681
+ id: "deny.root-destroy",
3881
4682
  outcome: "deny",
3882
4683
  check: (ctx) => {
3883
4684
  const matched = eachInvocation(ctx.commands, (inv, command) => {
3884
- if (inv.program !== "rm" || !rmIsRecursiveForce(inv.args))
3885
- return false;
3886
- for (const target of nonOptionArgs(inv.args)) {
4685
+ // `find` and `git clean` remove what they select below a start path, so the workspace
4686
+ // as their start is ordinary cleanup; `/`, `~` and the workspace's parents still count
4687
+ const selects = inv.program === "find" || inv.program === "git";
4688
+ for (const target of destroyTargetsOf(inv)) {
3887
4689
  const resolved = expandPath(target, ctx.facts, cwdOf(command, ctx.facts), command.vars);
3888
- if (resolved !== null && isDangerousDelete(resolved, ctx))
3889
- return true;
4690
+ if (resolved === null || !isDangerousDelete(resolved, ctx))
4691
+ continue;
4692
+ if (selects && globBase(resolved) === ctx.facts.workspace)
4693
+ continue;
4694
+ return true;
3890
4695
  }
3891
4696
  return false;
3892
4697
  });
3893
4698
  return matched.length > 0
3894
4699
  ? {
3895
- reason: "Deletes /, the home directory or a parent of the workspace with rm -rf.",
4700
+ reason: "Deletes, moves away or recursively changes /, the home directory or a parent of the workspace.",
3896
4701
  commands: matched,
3897
4702
  }
3898
4703
  : null;
@@ -4137,6 +4942,122 @@ function strictest(hits) {
4137
4942
  outcome = hit.outcome;
4138
4943
  return outcome;
4139
4944
  }
4945
+ /** The last path segment of a URL's path (`https://h/a/x.sh?q` → `x.sh`), or null. */
4946
+ function urlBaseName(url) {
4947
+ const match = /^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/[^?#]*)/i.exec(url);
4948
+ const name = match?.[1]?.split("/").pop();
4949
+ return name === undefined || name === "" ? null : name;
4950
+ }
4951
+ /**
4952
+ * What a command writes beyond its write targets, for the record of what the conversation wrote:
4953
+ * a file copied into a directory (`cp a.py sub/` writes `sub/a.py`), a download saved under the
4954
+ * URL's name (`curl -O`, `wget URL`) or by an option cluster (`curl -sSLo x.sh`), and a cloned
4955
+ * repository (everything under its directory, as `<dir>/**`).
4956
+ */
4957
+ function extraWrites(inv) {
4958
+ const { program, args } = inv;
4959
+ const ops = operands(args);
4960
+ switch (program) {
4961
+ case "cp":
4962
+ case "mv":
4963
+ case "install":
4964
+ case "ln": {
4965
+ const directory = targetDirectory(args);
4966
+ const dest = directory ?? ops.at(-1);
4967
+ const sources = directory !== null ? ops : ops.slice(0, -1);
4968
+ return dest === undefined ? [] : sources.map((src) => `${dest}/${baseName(src)}`);
4969
+ }
4970
+ case "curl": {
4971
+ const out = [];
4972
+ const urls = args.filter((a) => /^[a-z][a-z0-9+.-]*:\/\//i.test(a));
4973
+ for (let i = 0; i < args.length; i += 1) {
4974
+ const a = args[i];
4975
+ if (/^-[A-Za-z]*o$/.test(a) && args[i + 1] !== undefined)
4976
+ out.push(args[i + 1]);
4977
+ if (/^-[A-Za-z]*O[A-Za-z]*$/.test(a) ||
4978
+ a === "--remote-name" ||
4979
+ a === "--remote-name-all") {
4980
+ for (const url of urls) {
4981
+ const name = urlBaseName(url);
4982
+ if (name !== null)
4983
+ out.push(name);
4984
+ }
4985
+ }
4986
+ }
4987
+ return out;
4988
+ }
4989
+ case "wget": {
4990
+ const named = args.findIndex((a) => /^-[A-Za-z]*O$/.test(a) || a === "--output-document");
4991
+ if (named >= 0)
4992
+ return args[named + 1] === undefined || args[named + 1] === "-"
4993
+ ? []
4994
+ : [args[named + 1]];
4995
+ if (args.some((a) => a.startsWith("--output-document=")))
4996
+ return [];
4997
+ const index = args.findIndex((a) => a === "-P" || a === "--directory-prefix");
4998
+ const dir = index >= 0 ? args[index + 1] : undefined;
4999
+ return args
5000
+ .filter((a) => /^[a-z][a-z0-9+.-]*:\/\//i.test(a))
5001
+ .map((url) => urlBaseName(url) ?? "index.html")
5002
+ .map((name) => (dir === undefined ? name : `${dir}/${name}`));
5003
+ }
5004
+ case "git": {
5005
+ if (args[0] !== "clone")
5006
+ return [];
5007
+ const cloneOps = operands(args.slice(1));
5008
+ const url = cloneOps[0];
5009
+ if (url === undefined)
5010
+ return [];
5011
+ const dir = cloneOps[1] ?? repoName(url);
5012
+ return dir === undefined ? [] : [`${dir}/**`];
5013
+ }
5014
+ default:
5015
+ return [];
5016
+ }
5017
+ }
5018
+ /** The absolute paths `command` writes (its write targets and output redirections). */
5019
+ function writtenBy(command, facts) {
5020
+ const out = [];
5021
+ const cwd = cwdOf(command, facts);
5022
+ const targets = [
5023
+ ...writeTargets(command),
5024
+ ...invocationsOf(command).flatMap((inv) => extraWrites(inv)),
5025
+ ];
5026
+ for (const target of targets) {
5027
+ const glob = target.endsWith("/**");
5028
+ const resolved = expandPath(glob ? target.slice(0, -3) : target, facts, cwd, command.vars);
5029
+ if (resolved !== null)
5030
+ out.push(glob ? `${resolved}/**` : resolved);
5031
+ }
5032
+ return out;
5033
+ }
5034
+ /** For each command, what the commands before it in the line wrote. */
5035
+ function writtenBeforeEach(commands, facts) {
5036
+ const before = new Map();
5037
+ const seen = new Set();
5038
+ for (const command of commands) {
5039
+ before.set(command, new Set(seen));
5040
+ for (const path of writtenBy(command, facts))
5041
+ seen.add(path);
5042
+ }
5043
+ return before;
5044
+ }
5045
+ /**
5046
+ * The absolute paths a command line writes, for the review's record of what a conversation wrote
5047
+ * (hardening spec R1: running one of them later is not a development command). An unparseable line
5048
+ * writes nothing the review can name.
5049
+ */
5050
+ export function writtenPaths(command, facts) {
5051
+ const resolved = resolveFacts(facts);
5052
+ const parsed = parseDetailed(command);
5053
+ if (!parsed.ok)
5054
+ return [];
5055
+ const withCwds = assignCwds(parsed.value, resolved);
5056
+ if (!withCwds.ok)
5057
+ return [];
5058
+ assignVariables(withCwds.value, resolved);
5059
+ return [...new Set(withCwds.value.flatMap((c) => writtenBy(c, resolved)))];
5060
+ }
4140
5061
  /**
4141
5062
  * The rule table over a command line: the strictest outcome and every hit, in rule order. A parse
4142
5063
  * the tokenizer cannot make confidently yields only `unsure.unparsed`; a command no rule covers
@@ -4161,6 +5082,7 @@ export function reviewRules(command, facts) {
4161
5082
  commands,
4162
5083
  unsure,
4163
5084
  venv: commandLineActivatesVenv(commands),
5085
+ writtenBefore: writtenBeforeEach(commands, resolved),
4164
5086
  };
4165
5087
  const hits = [];
4166
5088
  const covered = new Set();
@@ -4225,7 +5147,11 @@ export function reviewWrite(path, facts) {
4225
5147
  return {
4226
5148
  outcome: "ask",
4227
5149
  hits: [
4228
- { id: "ask.rc-files", outcome: "ask", reason: "Changes a git hook; this needs approval." },
5150
+ {
5151
+ id: "ask.persistence",
5152
+ outcome: "ask",
5153
+ reason: "Changes a git hook; this needs approval.",
5154
+ },
4229
5155
  ],
4230
5156
  };
4231
5157
  }
@@ -4254,16 +5180,8 @@ export function reviewWrite(path, facts) {
4254
5180
  };
4255
5181
  }
4256
5182
  if (isPersistencePath(absolute, resolved) || isSecretPath(absolute, resolved)) {
4257
- return {
4258
- outcome: "ask",
4259
- hits: [
4260
- {
4261
- id: "ask.rc-files",
4262
- outcome: "ask",
4263
- reason: "Changes a shell rc file, SSH configuration or another secret/persistence location; this needs approval.",
4264
- },
4265
- ],
4266
- };
5183
+ const id = configClassOf(absolute, resolved);
5184
+ return { outcome: "ask", hits: [{ id, outcome: "ask", reason: CONFIG_REASONS[id] }] };
4267
5185
  }
4268
5186
  return {
4269
5187
  outcome: "ask",