cocheck 0.0.0-stage → 0.4.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.
Files changed (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/bin/cocheck.mjs +8 -0
  5. package/dist/agent-transcripts.js +541 -0
  6. package/dist/attribution/basis.js +31 -0
  7. package/dist/attribution/evidence.js +311 -0
  8. package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
  9. package/dist/attribution/hooks/sitecustomize.py +245 -0
  10. package/dist/attribution/names.js +163 -0
  11. package/dist/attribution/reconstruct.js +128 -0
  12. package/dist/attribution/tag.js +246 -0
  13. package/dist/attribution/write-scope-win.js +615 -0
  14. package/dist/attribution/write-scope.js +1668 -0
  15. package/dist/build-info.json +1 -0
  16. package/dist/cli-main.js +8 -0
  17. package/dist/cli.js +193 -0
  18. package/dist/codex-config.js +107 -0
  19. package/dist/connector/after-gap.js +56 -0
  20. package/dist/connector/after-snapshot.js +244 -0
  21. package/dist/connector/before-snapshot.js +168 -0
  22. package/dist/connector/builtins.js +93 -0
  23. package/dist/connector/changes-v1.js +276 -0
  24. package/dist/connector/claimed-state.js +40 -0
  25. package/dist/connector/claimed.js +86 -0
  26. package/dist/connector/conformance.js +458 -0
  27. package/dist/connector/diff-object.js +81 -0
  28. package/dist/connector/diff-samples.js +64 -0
  29. package/dist/connector/diff.js +273 -0
  30. package/dist/connector/doc-level.js +20 -0
  31. package/dist/connector/enabled-types.js +87 -0
  32. package/dist/connector/export-view.js +13 -0
  33. package/dist/connector/file-capture.js +265 -0
  34. package/dist/connector/frozen.js +213 -0
  35. package/dist/connector/installed-manifests.js +72 -0
  36. package/dist/connector/installed-match.js +161 -0
  37. package/dist/connector/local-process.js +119 -0
  38. package/dist/connector/nothing-changed-rule.js +23 -0
  39. package/dist/connector/old-rows.js +66 -0
  40. package/dist/connector/png-pixels.js +4 -0
  41. package/dist/connector/registry.js +78 -0
  42. package/dist/connector/requires.js +30 -0
  43. package/dist/connector/row-doc.js +54 -0
  44. package/dist/connector/run-argv.js +25 -0
  45. package/dist/connector/runner.js +325 -0
  46. package/dist/connector/schema.js +242 -0
  47. package/dist/connector/subject.js +8 -0
  48. package/dist/connector/subjects.js +113 -0
  49. package/dist/connector/validate.js +200 -0
  50. package/dist/connector-auth.js +101 -0
  51. package/dist/connector-create.js +55 -0
  52. package/dist/connector-doctor.js +167 -0
  53. package/dist/connector-test-cli.js +627 -0
  54. package/dist/connector-types-cli.js +43 -0
  55. package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
  56. package/dist/connectors/microsoft-excel/connector.mjs +11 -0
  57. package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
  58. package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
  59. package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
  60. package/dist/connectors/microsoft-word/connector.mjs +11 -0
  61. package/dist/copies.js +151 -0
  62. package/dist/copilot-helpers.js +246 -0
  63. package/dist/coverage.js +277 -0
  64. package/dist/credit-guard.js +330 -0
  65. package/dist/display.js +78 -0
  66. package/dist/file-lock.js +145 -0
  67. package/dist/fingerprint.js +25 -0
  68. package/dist/formats/files/align.js +84 -0
  69. package/dist/formats/files/csv.js +78 -0
  70. package/dist/formats/files/layer.js +274 -0
  71. package/dist/formats/files/scan.js +86 -0
  72. package/dist/formats/files/textlike.js +21 -0
  73. package/dist/formats/layer.js +48 -0
  74. package/dist/helpers/pdfpages +0 -0
  75. package/dist/home-page.js +173 -0
  76. package/dist/home-perms.js +59 -0
  77. package/dist/hook-adapter.js +3415 -0
  78. package/dist/hook-cli.js +505 -0
  79. package/dist/hook-journal.js +147 -0
  80. package/dist/hook.js +25 -0
  81. package/dist/hosts/claude.js +250 -0
  82. package/dist/hosts/codex-bin-macos.js +2 -0
  83. package/dist/hosts/codex-bin.js +35 -0
  84. package/dist/hosts/codex-trust-probe.js +52 -0
  85. package/dist/hosts/codex-trust.js +46 -0
  86. package/dist/hosts/codex.js +355 -0
  87. package/dist/hosts/copilot.js +236 -0
  88. package/dist/hosts/index.js +52 -0
  89. package/dist/hosts/session-titles.js +327 -0
  90. package/dist/hosts/shared.js +31 -0
  91. package/dist/hosts/types.js +26 -0
  92. package/dist/html.js +4 -0
  93. package/dist/install.js +676 -0
  94. package/dist/items.js +105 -0
  95. package/dist/ledger.js +2097 -0
  96. package/dist/narration.js +202 -0
  97. package/dist/normalize.js +82 -0
  98. package/dist/office/connector/apps.js +34 -0
  99. package/dist/office/connector/docx/layer.js +247 -0
  100. package/dist/office/connector/docx/reader.js +284 -0
  101. package/dist/office/connector/excel/align.js +284 -0
  102. package/dist/office/connector/excel/answer.js +352 -0
  103. package/dist/office/connector/excel/diff.js +1310 -0
  104. package/dist/office/connector/excel/errors.js +44 -0
  105. package/dist/office/connector/excel/look.js +121 -0
  106. package/dist/office/connector/excel/print-boxes.js +432 -0
  107. package/dist/office/connector/excel/print-grid-previous.js +206 -0
  108. package/dist/office/connector/excel/print-setup.js +168 -0
  109. package/dist/office/connector/excel/workbook.js +374 -0
  110. package/dist/office/connector/export-driver.js +9 -0
  111. package/dist/office/connector/helpers/cocheck-screen +0 -0
  112. package/dist/office/connector/issues.js +31 -0
  113. package/dist/office/connector/mac-guard.js +16 -0
  114. package/dist/office/connector/main.js +23 -0
  115. package/dist/office/connector/nothing-changed.js +18 -0
  116. package/dist/office/connector/office-job.js +416 -0
  117. package/dist/office/connector/office-macos.js +473 -0
  118. package/dist/office/connector/office-win-export.js +107 -0
  119. package/dist/office/connector/office-win-lifecycle.js +194 -0
  120. package/dist/office/connector/office-win.js +209 -0
  121. package/dist/office/connector/office-win.ps1 +451 -0
  122. package/dist/office/connector/open-watch.js +46 -0
  123. package/dist/office/connector/pictures.js +156 -0
  124. package/dist/office/connector/pptx/diff.js +589 -0
  125. package/dist/office/connector/pptx/frames.js +105 -0
  126. package/dist/office/connector/pptx/layer.js +148 -0
  127. package/dist/office/connector/pptx/links.js +59 -0
  128. package/dist/office/connector/pptx/reader.js +744 -0
  129. package/dist/office/connector/pptx/spans.js +70 -0
  130. package/dist/office/connector/pptx/tags.js +86 -0
  131. package/dist/office/connector/pptx/xml.js +96 -0
  132. package/dist/office/connector/pptx/zip.js +223 -0
  133. package/dist/office/connector/pptx-boxes.js +238 -0
  134. package/dist/office/connector/print-copy-cap.js +19 -0
  135. package/dist/office/connector/print-copy.js +13 -0
  136. package/dist/office/connector/program.js +291 -0
  137. package/dist/office/connector/reach.js +27 -0
  138. package/dist/office/connector/refusal.js +16 -0
  139. package/dist/office/connector/screen-macos.js +193 -0
  140. package/dist/office/connector/screen-windows.js +34 -0
  141. package/dist/office/connector/shared/chart-diff.js +376 -0
  142. package/dist/office/connector/shared/docprops-noise.js +13 -0
  143. package/dist/office/connector/shared/lock.js +107 -0
  144. package/dist/office/connector/shared/ooxml-names.js +347 -0
  145. package/dist/office/connector/shared/owner.js +57 -0
  146. package/dist/office/connector/shared/package-media.js +703 -0
  147. package/dist/office/connector/shared/preflight.js +226 -0
  148. package/dist/office/connector/shared/structure-check.js +623 -0
  149. package/dist/office/connector/word-boxes.js +364 -0
  150. package/dist/office/connector/word-print-copy.js +234 -0
  151. package/dist/office/connector/xlsx/diff.js +1038 -0
  152. package/dist/office/connector/xlsx/formula.js +410 -0
  153. package/dist/office/connector/xlsx/layer.js +621 -0
  154. package/dist/office/connector/xlsx/memo.js +39 -0
  155. package/dist/office/connector/xlsx/numbers.js +31 -0
  156. package/dist/office/connector/xlsx/numfmt.js +913 -0
  157. package/dist/office/connector/xlsx/parts.js +66 -0
  158. package/dist/office/connector/xlsx/reader.js +394 -0
  159. package/dist/office/connector/xlsx/types.js +20 -0
  160. package/dist/office/connector/xlsx/written.js +446 -0
  161. package/dist/open-pick.js +99 -0
  162. package/dist/patch-secrets.js +194 -0
  163. package/dist/paths.js +65 -0
  164. package/dist/platform/darwin.js +179 -0
  165. package/dist/platform/index.js +61 -0
  166. package/dist/platform/spawn.js +115 -0
  167. package/dist/platform/stub.js +21 -0
  168. package/dist/platform/task-folder.js +41 -0
  169. package/dist/platform/types.js +20 -0
  170. package/dist/platform/win32-docrender.js +7 -0
  171. package/dist/platform/win32.js +265 -0
  172. package/dist/preferences.js +49 -0
  173. package/dist/reason.js +103 -0
  174. package/dist/region-delivery.js +148 -0
  175. package/dist/registry.js +68 -0
  176. package/dist/reveal.js +45 -0
  177. package/dist/review-process.js +154 -0
  178. package/dist/review-refresh-process.js +17 -0
  179. package/dist/review-refresh.js +120 -0
  180. package/dist/review-server.js +2079 -0
  181. package/dist/review-view-server.js +106 -0
  182. package/dist/review.js +8 -0
  183. package/dist/seal.js +315 -0
  184. package/dist/secret-files.js +34 -0
  185. package/dist/secret-hashes.js +27 -0
  186. package/dist/secret-rules.generated.js +3519 -0
  187. package/dist/secret-scan.js +127 -0
  188. package/dist/session-context.js +18 -0
  189. package/dist/signoff.js +419 -0
  190. package/dist/skill.js +110 -0
  191. package/dist/states.js +192 -0
  192. package/dist/tasks.js +1001 -0
  193. package/dist/timeline/attribution.js +207 -0
  194. package/dist/timeline/broken.js +55 -0
  195. package/dist/timeline/describe.js +413 -0
  196. package/dist/timeline/generic.js +195 -0
  197. package/dist/timeline/load.js +464 -0
  198. package/dist/timeline/loading.js +49 -0
  199. package/dist/timeline/notes.js +208 -0
  200. package/dist/timeline/page.js +178 -0
  201. package/dist/timeline/picture.js +303 -0
  202. package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
  203. package/dist/timeline/rail/assets/files-view.js +198 -0
  204. package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
  205. package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
  206. package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
  207. package/dist/timeline/rail/assets/review.css +992 -0
  208. package/dist/timeline/rail/assets/review.js +3365 -0
  209. package/dist/timeline/rail/assets/view-table.js +683 -0
  210. package/dist/timeline/rail/failure-line.js +26 -0
  211. package/dist/timeline/rail/files-model.js +45 -0
  212. package/dist/timeline/rail/live.js +49 -0
  213. package/dist/timeline/rail/made-pictures.js +48 -0
  214. package/dist/timeline/rail/mcp-card.js +307 -0
  215. package/dist/timeline/rail/model.js +1317 -0
  216. package/dist/timeline/rail/page.js +167 -0
  217. package/dist/timeline/rail/passes.js +106 -0
  218. package/dist/timeline/rail/regions.js +26 -0
  219. package/dist/timeline/rail/send-back.js +154 -0
  220. package/dist/timeline/rail/stop-status.js +164 -0
  221. package/dist/timeline/read-signal.js +743 -0
  222. package/dist/timeline/render/claimed.js +13 -0
  223. package/dist/timeline/render/fallback.js +36 -0
  224. package/dist/timeline/render/pdf-helper.js +71 -0
  225. package/dist/timeline/render/pdf.js +410 -0
  226. package/dist/timeline/render/pixel-pages.js +168 -0
  227. package/dist/timeline/render/png-crop.js +281 -0
  228. package/dist/timeline/render/registry.js +7 -0
  229. package/dist/timeline/render/text.js +366 -0
  230. package/dist/timeline/render/types.js +1 -0
  231. package/dist/timeline/render/view-v1.js +148 -0
  232. package/dist/timeline/render/whole.js +6 -0
  233. package/dist/timeline/rollout-failures.js +40 -0
  234. package/dist/timeline/runs.js +836 -0
  235. package/dist/timeline/stored-image.js +34 -0
  236. package/dist/timeline/subject-display.js +44 -0
  237. package/dist/timeline/timeline.js +1114 -0
  238. package/dist/timeline/write-signal.js +403 -0
  239. package/dist/tool-label.js +201 -0
  240. package/dist/tracking.js +87 -0
  241. package/dist/vendor/pdfjs/LICENSE +177 -0
  242. package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
  243. package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
  244. package/package.json +66 -4
  245. package/public-kit/GUIDE.md +189 -0
  246. package/public-kit/README.md +10 -0
  247. package/public-kit/conformance/README.md +13 -0
  248. package/public-kit/conformance/cases/C1.json +12 -0
  249. package/public-kit/conformance/cases/C10.json +15 -0
  250. package/public-kit/conformance/cases/C11.json +16 -0
  251. package/public-kit/conformance/cases/C12.json +18 -0
  252. package/public-kit/conformance/cases/C13.json +23 -0
  253. package/public-kit/conformance/cases/C14.json +16 -0
  254. package/public-kit/conformance/cases/C16.json +15 -0
  255. package/public-kit/conformance/cases/C17.json +25 -0
  256. package/public-kit/conformance/cases/C2.json +13 -0
  257. package/public-kit/conformance/cases/C3.json +44 -0
  258. package/public-kit/conformance/cases/C4.json +13 -0
  259. package/public-kit/conformance/cases/C5.json +16 -0
  260. package/public-kit/conformance/cases/C6.json +58 -0
  261. package/public-kit/conformance/generate-large.mjs +15 -0
  262. package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
  263. package/public-kit/examples/toy-export/connector.mjs +28 -0
  264. package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
  265. package/public-kit/examples/toy-helpers/connector.mjs +69 -0
  266. package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
  267. package/public-kit/examples/toy-level-1/connector.mjs +61 -0
  268. package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
  269. package/public-kit/examples/toy-level-3/connector.mjs +82 -0
  270. package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
  271. package/public-kit/examples/toy-tracker/connector.mjs +46 -0
  272. package/public-kit/examples/toy-tracker/samples/history.json +10 -0
  273. package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
  274. package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
  275. package/public-kit/examples/toy-vendor/connector.mjs +62 -0
  276. package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
  277. package/public-kit/helpers/pdf-text-layout.mjs +602 -0
  278. package/public-kit/helpers/pdf-text.d.mts +56 -0
  279. package/public-kit/helpers/pdf-text.mjs +375 -0
  280. package/public-kit/helpers/pdf.d.mts +61 -0
  281. package/public-kit/helpers/pdf.mjs +251 -0
  282. package/public-kit/helpers/png.d.mts +15 -0
  283. package/public-kit/helpers/png.mjs +88 -0
  284. package/public-kit/helpers/spec.d.mts +4 -0
  285. package/public-kit/helpers/spec.mjs +2 -0
  286. package/public-kit/scaffold/README.md +23 -0
  287. package/public-kit/scaffold/template/README.md +13 -0
  288. package/public-kit/scaffold/template/cocheck-connector.json +10 -0
  289. package/public-kit/scaffold/template/connector.mjs +50 -0
  290. package/public-kit/spec/README.md +408 -0
  291. package/public-kit/spec/v1.md +598 -0
  292. package/public-kit/toy-product/README.md +7 -0
  293. package/public-kit/toy-product/notes-store.mjs +30 -0
  294. package/public-kit/toy-product/states/create.after.json +16 -0
  295. package/public-kit/toy-product/states/create.before.json +12 -0
  296. package/public-kit/toy-product/states/delete.after.json +8 -0
  297. package/public-kit/toy-product/states/delete.before.json +12 -0
  298. package/public-kit/toy-product/states/edit.after.json +12 -0
  299. package/public-kit/toy-product/states/edit.before.json +12 -0
  300. package/public-kit/toy-product/states/malformed.after.json +1 -0
  301. package/public-kit/toy-product/states/malformed.before.json +12 -0
  302. package/public-kit/toy-product/states/no-change.after.json +12 -0
  303. package/public-kit/toy-product/states/no-change.before.json +12 -0
  304. package/scripts/hook-launch.mjs +58 -0
  305. package/scripts/hook-launch.sh +52 -0
@@ -0,0 +1,1668 @@
1
+ // Which files a Bash call can write, read from its command alone, so that a call that provably cannot have written a file is not
2
+ // credited with it (`cannotHaveWritten`, behind the `creditWithEvidence` seam).
3
+ //
4
+ // The analyzer is deliberately small. It returns the exact set of paths a command can write or remove (`targets`), or UNKNOWN for anything it
5
+ // does not fully understand. What must not happen is a wrong single owner (a review refuted the "writes only outside the folder"
6
+ // rule on python -c with env paths, xlwings saves, tar -xP, variable paths and symlinks), so every doubt is UNKNOWN, and UNKNOWN never
7
+ // excludes. Understood, and nothing else:
8
+ // - curl with -o/--output FILE, or -O with a URL whose every value is known; read-only options from an allow-list. A curl config file
9
+ // (~/.curlrc and kin) can add outputs, so the live probe refuses curl while one exists.
10
+ // - rm, cp, mv, touch with literal operands; mkdir (creates directories, never changes a file); cd with a literal path.
11
+ // - readers that have no way to write a file (echo, cat, head, tail, wc, grep, ls, tr, cut, test, ...), printf without -v, date +FORMAT.
12
+ // - `for x in LIST`, `T=(...)` and `X=literal`, with `$x`, `${x}`, `${T[@]}` substitution; `{a,b}` brace expansion; `$(...)` whose
13
+ // command is itself understood (its value is unknown text, allowed only inside double quotes and never in a path).
14
+ // - redirects to /dev/null, fd duplication (2>&1), input from a file, here-strings, and heredocs feeding an understood command.
15
+ // - Python or Node children carrying the write hook (`observed`): the caller credits them as unable to write only when the call is
16
+ // tagged, its children logged no write and started no other program, and the hook's roots cover the file.
17
+ // - `python -I -c CODE` (or `python -I -` fed by a heredoc) whose code passes a strict read-only allow-list (`strictReadOnlyPython`).
18
+ // Any variable not bound by an understood literal assignment or loop, any other program, any other redirect, `eval`, `bash x.sh`, `xargs`,
19
+ // `find`, `sed`, `tee`, `dd`, `tar`, an env prefix (`X=1 cmd`), a glob or `~` in a path, a `..` component: UNKNOWN.
20
+ // Paths resolve against the call's cwd (and against each `cd`, keeping the old directory too when the cd may have failed). The probe
21
+ // rejects any target whose directories hold a symlink the user could have made (`fsProbe`).
22
+ import { lstatSync, readlinkSync, existsSync } from "node:fs";
23
+ import path from "node:path";
24
+ import { guardKit } from "../credit-guard.js";
25
+ import { PS_WRAPPERS, WinUnknown, psWrapperScript, readPowerShell } from "./write-scope-win.js";
26
+ class Unknown extends Error {
27
+ }
28
+ function no(why) {
29
+ throw new Unknown(why);
30
+ }
31
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
32
+ const RESERVED = new Set(["for", "in", "do", "done", "if", "then", "elif", "else", "fi", "while", "until", "case", "esac", "function", "select", "time", "coproc", "{", "}", "!", "[[", "]]"]);
33
+ /** The word's text when it is one unquoted literal, else undefined. */
34
+ const plainOf = (w) => (w.array === undefined && w.parts.length === 1 && w.parts[0].t === "lit" && !w.parts[0].q ? w.parts[0].s : undefined);
35
+ /** The word's text when every part is literal (quoted or not), else undefined. */
36
+ const literalOf = (w) => (w.array === undefined && w.parts.every((p) => p.t === "lit") ? w.parts.map((p) => p.s).join("") : undefined);
37
+ class Parser {
38
+ i = 0;
39
+ pending = [];
40
+ buf = [];
41
+ s;
42
+ constructor(s) {
43
+ this.s = s;
44
+ }
45
+ // ---- lexer ----
46
+ skipBlanks() {
47
+ for (;;) {
48
+ const c = this.s[this.i];
49
+ if (c === " " || c === "\t")
50
+ this.i++;
51
+ else if (c === "\\" && this.s[this.i + 1] === "\n")
52
+ this.i += 2;
53
+ else if (c === "#") {
54
+ while (this.i < this.s.length && this.s[this.i] !== "\n")
55
+ this.i++;
56
+ }
57
+ else
58
+ return;
59
+ }
60
+ }
61
+ peek() {
62
+ if (this.buf.length === 0)
63
+ this.buf.push(this.lex());
64
+ return this.buf[0];
65
+ }
66
+ next() {
67
+ const t = this.peek();
68
+ this.buf.shift();
69
+ return t;
70
+ }
71
+ lex() {
72
+ this.skipBlanks();
73
+ const s = this.s;
74
+ if (this.i >= s.length) {
75
+ if (this.pending.length > 0)
76
+ no("heredoc without its body");
77
+ return { k: "eof" };
78
+ }
79
+ const c = s[this.i];
80
+ const two = s.slice(this.i, this.i + 2);
81
+ if (c === "\n") {
82
+ this.i++;
83
+ this.readBodies();
84
+ return { k: "op", op: "\n" };
85
+ }
86
+ if (two === "&&" || two === "||" || two === "|&" || two === ";;") {
87
+ this.i += 2;
88
+ if (two === ";;")
89
+ no("case");
90
+ return { k: "op", op: two };
91
+ }
92
+ if (two === "&>")
93
+ return this.redir("");
94
+ if (c === ";" || c === "&" || c === "|" || c === ")") {
95
+ this.i++;
96
+ return { k: "op", op: c };
97
+ }
98
+ if (c === "(") {
99
+ if (s[this.i + 1] === "(")
100
+ no("arithmetic command");
101
+ this.i++;
102
+ return { k: "op", op: "(" };
103
+ }
104
+ if (c === "<" || c === ">")
105
+ return this.redir("");
106
+ // a word; digits right before a redirect are its fd
107
+ const m = /^\d+(?=[<>])/.exec(s.slice(this.i));
108
+ if (m) {
109
+ this.i += m[0].length;
110
+ return this.redir(m[0]);
111
+ }
112
+ return { k: "word", w: this.word(false) };
113
+ }
114
+ redir(fd) {
115
+ const s = this.s;
116
+ const ops = ["&>>", "<<<", "<<-", ">>", ">|", "<<", "<>", ">&", "<&", "&>", "<", ">"];
117
+ const op = ops.find((o) => s.startsWith(o, this.i));
118
+ this.i += op.length;
119
+ if ((op === "<" || op === ">") && s[this.i] === "(")
120
+ no("process substitution");
121
+ this.skipBlanks();
122
+ const w = this.word(true);
123
+ if (w.parts.length === 0)
124
+ no("redirect without a target");
125
+ const r = { op: fd + op, target: w };
126
+ if (op === "<<" || op === "<<-") {
127
+ const delim = literalOf(w);
128
+ if (delim === undefined || delim === "")
129
+ no("heredoc delimiter is not literal");
130
+ r.delim = delim;
131
+ r.quoted = w.parts.some((p) => p.t === "lit" && p.q);
132
+ r.strip = op === "<<-";
133
+ this.pending.push(r);
134
+ }
135
+ return { k: "redir", r };
136
+ }
137
+ /** Reads the bodies of the heredocs started on the line just ended. */
138
+ readBodies() {
139
+ for (const r of this.pending) {
140
+ const { delim, quoted, strip } = r;
141
+ const lines = [];
142
+ for (;;) {
143
+ if (this.i >= this.s.length)
144
+ no("heredoc never ends");
145
+ let end = this.s.indexOf("\n", this.i);
146
+ if (end < 0)
147
+ end = this.s.length;
148
+ let line = this.s.slice(this.i, end);
149
+ this.i = Math.min(end + 1, this.s.length);
150
+ if (strip)
151
+ line = line.replace(/^\t+/, "");
152
+ if (line === delim)
153
+ break;
154
+ lines.push(line);
155
+ }
156
+ const text = lines.length === 0 ? "" : lines.join("\n") + "\n";
157
+ r.body = quoted ? { parts: [{ t: "lit", s: text, q: true }] } : bodyWord(text);
158
+ }
159
+ this.pending = [];
160
+ }
161
+ /** One word. `redirTarget`: stop before another redirect operator. */
162
+ word(redirTarget) {
163
+ const s = this.s;
164
+ const parts = [];
165
+ const lit = (t, q) => {
166
+ const last = parts[parts.length - 1];
167
+ if (last && last.t === "lit" && last.q === q)
168
+ last.s += t;
169
+ else
170
+ parts.push({ t: "lit", s: t, q });
171
+ };
172
+ const start = this.i;
173
+ while (this.i < s.length) {
174
+ const c = s[this.i];
175
+ if (c === " " || c === "\t" || c === "\n" || c === ";" || c === "&" || c === "|" || c === "<" || c === ">" || c === ")")
176
+ break;
177
+ if (c === "(") {
178
+ // NAME=( ... ): an array
179
+ const sofar = parts.length === 1 && parts[0].t === "lit" && !parts[0].q ? parts[0].s : undefined;
180
+ if (!redirTarget && sofar !== undefined && /^[A-Za-z_][A-Za-z0-9_]*=$/.test(sofar) && this.i - start === sofar.length) {
181
+ this.i++;
182
+ const els = [];
183
+ for (;;) {
184
+ while (this.i < s.length && /[ \t\n]/.test(s[this.i]))
185
+ this.i++;
186
+ if (this.i >= s.length)
187
+ no("array never closes");
188
+ if (s[this.i] === ")") {
189
+ this.i++;
190
+ break;
191
+ }
192
+ if (s[this.i] === "#")
193
+ no("comment in an array");
194
+ const w = this.word(true);
195
+ if (w.parts.length === 0)
196
+ no("odd array element");
197
+ els.push(w);
198
+ }
199
+ return { parts, array: els };
200
+ }
201
+ no("parenthesis inside a word");
202
+ }
203
+ if (c === "\\") {
204
+ if (s[this.i + 1] === "\n") {
205
+ this.i += 2;
206
+ continue;
207
+ }
208
+ if (this.i + 1 >= s.length)
209
+ no("trailing backslash");
210
+ lit(s[this.i + 1], true);
211
+ this.i += 2;
212
+ continue;
213
+ }
214
+ if (c === "'") {
215
+ const end = s.indexOf("'", this.i + 1);
216
+ if (end < 0)
217
+ no("unclosed quote");
218
+ lit(s.slice(this.i + 1, end), true);
219
+ this.i = end + 1;
220
+ continue;
221
+ }
222
+ if (c === '"') {
223
+ this.i++;
224
+ lit("", true);
225
+ for (;;) {
226
+ if (this.i >= s.length)
227
+ no("unclosed quote");
228
+ const d = s[this.i];
229
+ if (d === '"') {
230
+ this.i++;
231
+ break;
232
+ }
233
+ if (d === "\\") {
234
+ const e = s[this.i + 1];
235
+ if (e === "$" || e === "`" || e === '"' || e === "\\") {
236
+ lit(e, true);
237
+ this.i += 2;
238
+ }
239
+ else if (e === "\n")
240
+ this.i += 2;
241
+ else {
242
+ lit("\\", true);
243
+ this.i++;
244
+ }
245
+ continue;
246
+ }
247
+ if (d === "$" || d === "`") {
248
+ const p = this.dollar(true);
249
+ if (p) {
250
+ parts.push(p);
251
+ continue;
252
+ }
253
+ }
254
+ lit(d, true);
255
+ this.i++;
256
+ }
257
+ continue;
258
+ }
259
+ if (c === "$" || c === "`") {
260
+ const p = this.dollar(false);
261
+ if (p) {
262
+ parts.push(p);
263
+ continue;
264
+ }
265
+ }
266
+ if (c === "~" && this.i === start) {
267
+ parts.push({ t: "special", q: false });
268
+ this.i++;
269
+ continue;
270
+ }
271
+ if (c === "=" && this.i === start && s[this.i + 1] !== undefined && !/[ \t\n;&|)]/.test(s[this.i + 1]))
272
+ no("zsh =command expansion");
273
+ lit(c, false);
274
+ this.i++;
275
+ }
276
+ return { parts };
277
+ }
278
+ /** `$name`, `${name}`, `${name[@]}`, `$?`-style specials, `$(...)` and backticks; null for a lone `$`. */
279
+ dollar(q) {
280
+ const s = this.s;
281
+ if (s[this.i] === "`") {
282
+ let j = this.i + 1;
283
+ let inner = "";
284
+ for (;;) {
285
+ if (j >= s.length)
286
+ no("unclosed backtick");
287
+ if (s[j] === "\\" && j + 1 < s.length) {
288
+ inner += s[j + 1];
289
+ j += 2;
290
+ continue;
291
+ }
292
+ if (s[j] === "`")
293
+ break;
294
+ inner += s[j];
295
+ j++;
296
+ }
297
+ this.i = j + 1;
298
+ return { t: "sub", list: parse(inner), q };
299
+ }
300
+ const n = s[this.i + 1];
301
+ if (n === "'" || n === '"')
302
+ no("$'...' or $\"...\" quoting");
303
+ if (n === "(") {
304
+ if (s[this.i + 2] === "(")
305
+ no("arithmetic expansion");
306
+ const end = matchParen(s, this.i + 1);
307
+ const inner = s.slice(this.i + 2, end);
308
+ this.i = end + 1;
309
+ return { t: "sub", list: parse(inner), q };
310
+ }
311
+ if (n === "{") {
312
+ const end = s.indexOf("}", this.i + 2);
313
+ if (end < 0)
314
+ no("unclosed ${");
315
+ const inner = s.slice(this.i + 2, end);
316
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)(\[[@*]\])?$/.exec(inner);
317
+ if (!m)
318
+ no(`parameter expansion \${${inner}}`);
319
+ this.i = end + 1;
320
+ return { t: "var", name: m[1], q };
321
+ }
322
+ if (n !== undefined && /[A-Za-z_]/.test(n)) {
323
+ const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(s.slice(this.i + 1));
324
+ this.i += 1 + m[0].length;
325
+ return { t: "var", name: m[0], q };
326
+ }
327
+ if (n !== undefined && /[0-9?$!#@*-]/.test(n)) {
328
+ this.i += 2;
329
+ return { t: "special", q };
330
+ }
331
+ return null;
332
+ }
333
+ // ---- grammar ----
334
+ parseList(stop) {
335
+ const items = [];
336
+ for (;;) {
337
+ let t = this.peek();
338
+ while (t.k === "op" && (t.op === "\n" || t.op === ";")) {
339
+ this.next();
340
+ t = this.peek();
341
+ }
342
+ if (t.k === "eof" || stop(t))
343
+ break;
344
+ const node = this.parsePipe();
345
+ const sep = this.peek();
346
+ if (sep.k === "op" && (sep.op === "&&" || sep.op === "||" || sep.op === ";" || sep.op === "&" || sep.op === "\n")) {
347
+ this.next();
348
+ items.push({ node, op: sep.op });
349
+ }
350
+ else {
351
+ items.push({ node, op: ";" });
352
+ if (!(sep.k === "eof" || stop(sep)))
353
+ no("unexpected token");
354
+ break;
355
+ }
356
+ }
357
+ return { k: "list", items };
358
+ }
359
+ parsePipe() {
360
+ const t = this.peek();
361
+ if (t.k === "word" && plainOf(t.w) === "!")
362
+ this.next();
363
+ const cmds = [this.parseCommand()];
364
+ for (;;) {
365
+ const p = this.peek();
366
+ if (p.k === "op" && (p.op === "|" || p.op === "|&")) {
367
+ this.next();
368
+ while (this.peek().k === "op" && this.peek().op === "\n")
369
+ this.next();
370
+ cmds.push(this.parseCommand());
371
+ }
372
+ else
373
+ break;
374
+ }
375
+ return cmds.length === 1 ? cmds[0] : { k: "pipe", cmds };
376
+ }
377
+ isWord(t, w) {
378
+ return t.k === "word" && plainOf(t.w) === w;
379
+ }
380
+ expectWord(w) {
381
+ const t = this.next();
382
+ if (!this.isWord(t, w))
383
+ no(`expected ${w}`);
384
+ }
385
+ redirs() {
386
+ const out = [];
387
+ while (this.peek().k === "redir")
388
+ out.push(this.next().r);
389
+ return out;
390
+ }
391
+ parseCommand() {
392
+ const t = this.peek();
393
+ if (t.k === "op" && t.op === "(") {
394
+ this.next();
395
+ const body = this.parseList((x) => x.k === "op" && x.op === ")");
396
+ if (!this.next().op)
397
+ no("unclosed subshell");
398
+ return { k: "sub", body, redirs: this.redirs() };
399
+ }
400
+ if (t.k === "word") {
401
+ const w = plainOf(t.w);
402
+ if (w === "{") {
403
+ this.next();
404
+ const body = this.parseList((x) => this.isWord(x, "}"));
405
+ this.expectWord("}");
406
+ return { k: "group", body, redirs: this.redirs() };
407
+ }
408
+ if (w === "for") {
409
+ this.next();
410
+ const nameTok = this.next();
411
+ const name = nameTok.k === "word" ? plainOf(nameTok.w) : undefined;
412
+ if (name === undefined || !NAME.test(name))
413
+ no("for without a plain name");
414
+ let n = this.peek();
415
+ while (n.k === "op" && n.op === "\n") {
416
+ this.next();
417
+ n = this.peek();
418
+ }
419
+ if (!this.isWord(n, "in"))
420
+ no("for without in");
421
+ this.next();
422
+ const words = [];
423
+ for (;;) {
424
+ const x = this.next();
425
+ if (x.k === "op" && (x.op === ";" || x.op === "\n"))
426
+ break;
427
+ if (x.k !== "word")
428
+ no("odd for list");
429
+ words.push(x.w);
430
+ }
431
+ let d = this.peek();
432
+ while (d.k === "op" && (d.op === "\n" || d.op === ";")) {
433
+ this.next();
434
+ d = this.peek();
435
+ }
436
+ this.expectWord("do");
437
+ const body = this.parseList((x) => this.isWord(x, "done"));
438
+ this.expectWord("done");
439
+ return { k: "for", name: name, words, body, redirs: this.redirs() };
440
+ }
441
+ if (w === "if") {
442
+ this.next();
443
+ const parts = [this.parseList((x) => this.isWord(x, "then"))];
444
+ this.expectWord("then");
445
+ for (;;) {
446
+ parts.push(this.parseList((x) => this.isWord(x, "elif") || this.isWord(x, "else") || this.isWord(x, "fi")));
447
+ const k = this.next();
448
+ if (this.isWord(k, "fi"))
449
+ break;
450
+ if (this.isWord(k, "else")) {
451
+ parts.push(this.parseList((x) => this.isWord(x, "fi")));
452
+ this.expectWord("fi");
453
+ break;
454
+ }
455
+ if (!this.isWord(k, "elif"))
456
+ no("odd if");
457
+ parts.push(this.parseList((x) => this.isWord(x, "then")));
458
+ this.expectWord("then");
459
+ }
460
+ return { k: "if", parts, redirs: this.redirs() };
461
+ }
462
+ if (w !== undefined && RESERVED.has(w))
463
+ no(`shell keyword ${w}`);
464
+ }
465
+ const words = [];
466
+ const redirs = [];
467
+ for (;;) {
468
+ const x = this.peek();
469
+ if (x.k === "word") {
470
+ if (words.length > 0 && x.w.array !== undefined)
471
+ no("array outside an assignment");
472
+ words.push(x.w);
473
+ this.next();
474
+ }
475
+ else if (x.k === "redir") {
476
+ redirs.push(x.r);
477
+ this.next();
478
+ }
479
+ else
480
+ break;
481
+ }
482
+ if (words.length === 0 && redirs.length === 0)
483
+ no("empty command");
484
+ return { k: "simple", words, redirs };
485
+ }
486
+ }
487
+ /** The index of the `)` closing the `(` at `open`, skipping quotes and nested parentheses. */
488
+ function matchParen(s, open) {
489
+ let depth = 0;
490
+ for (let j = open; j < s.length; j++) {
491
+ const c = s[j];
492
+ if (c === "\\") {
493
+ j++;
494
+ continue;
495
+ }
496
+ if (c === "'") {
497
+ const e = s.indexOf("'", j + 1);
498
+ if (e < 0)
499
+ no("unclosed quote");
500
+ j = e;
501
+ continue;
502
+ }
503
+ if (c === '"') {
504
+ let k = j + 1;
505
+ while (k < s.length && s[k] !== '"')
506
+ k += s[k] === "\\" ? 2 : 1;
507
+ if (k >= s.length)
508
+ no("unclosed quote");
509
+ j = k;
510
+ continue;
511
+ }
512
+ if (c === "#" || c === "<" && s[j + 1] === "<")
513
+ no("comment or heredoc inside $(...)");
514
+ if (c === "(")
515
+ depth++;
516
+ if (c === ")") {
517
+ depth--;
518
+ if (depth === 0)
519
+ return j;
520
+ }
521
+ }
522
+ return no("unclosed $(");
523
+ }
524
+ /** A heredoc body with an unquoted delimiter: variables are expanded, a command substitution would run (refused). */
525
+ function bodyWord(text) {
526
+ if (/`|\$\(/.test(text))
527
+ no("command substitution in a heredoc");
528
+ const parts = [];
529
+ let lit = "";
530
+ for (let i = 0; i < text.length; i++) {
531
+ const c = text[i];
532
+ if (c === "\\" && i + 1 < text.length && "$`\\\n".includes(text[i + 1])) {
533
+ if (text[i + 1] !== "\n")
534
+ lit += text[i + 1];
535
+ i++;
536
+ continue;
537
+ }
538
+ if (c === "$") {
539
+ const rest = text.slice(i + 1);
540
+ let m;
541
+ if ((m = /^\{([A-Za-z_][A-Za-z0-9_]*)(\[[@*]\])?\}/.exec(rest)) || (m = /^([A-Za-z_][A-Za-z0-9_]*)/.exec(rest))) {
542
+ parts.push({ t: "lit", s: lit, q: true }, { t: "var", name: m[1], q: true });
543
+ lit = "";
544
+ i += m[0].length;
545
+ continue;
546
+ }
547
+ if (rest.startsWith("{"))
548
+ no("parameter expansion in a heredoc");
549
+ if (/^[0-9?$!#@*-]/.test(rest)) {
550
+ parts.push({ t: "lit", s: lit, q: true }, { t: "special", q: true });
551
+ lit = "";
552
+ i++;
553
+ continue;
554
+ }
555
+ }
556
+ lit += c;
557
+ }
558
+ parts.push({ t: "lit", s: lit, q: true });
559
+ return { parts };
560
+ }
561
+ function parse(s) {
562
+ const p = new Parser(s);
563
+ const node = p.parseList(() => false);
564
+ if (p.peek().k !== "eof")
565
+ no("trailing tokens");
566
+ return node;
567
+ }
568
+ const CAP = 4096;
569
+ const uniq = (xs) => [...new Set(xs)];
570
+ function union(...ss) {
571
+ const cwds = ss.some((s) => s.cwds === null) ? null : uniq(ss.flatMap((s) => s.cwds));
572
+ const names = new Set(ss.flatMap((s) => [...s.vars.keys()]));
573
+ const vars = new Map();
574
+ for (const n of names) {
575
+ const bs = ss.map((s) => s.vars.get(n));
576
+ if (bs.some((b) => b === undefined || b === "taint"))
577
+ vars.set(n, "taint");
578
+ else {
579
+ const arr = bs[0].arr;
580
+ if (bs.some((b) => b.arr !== arr))
581
+ vars.set(n, "taint");
582
+ else {
583
+ const vals = uniq(bs.flatMap((b) => b.vals));
584
+ if (vals.length > CAP)
585
+ no("too many values");
586
+ vars.set(n, { vals, arr, count: Math.max(...bs.map((b) => b.count ?? b.vals.length)) });
587
+ }
588
+ }
589
+ }
590
+ return { cwds, vars, ...(ss.some((s) => s.win === true) ? { win: true } : {}) };
591
+ }
592
+ const same = (o) => o;
593
+ const both = (s) => ({ ok: s, fail: s });
594
+ const key = (s) => JSON.stringify([s.cwds?.slice().sort() ?? null, [...s.vars.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, v === "taint" ? v : [v.arr, v.vals.slice().sort()]])]);
595
+ /** Bash brace expansion of one word (`a{b,c}` gives `ab`, `ac`); throws on a sequence or past the cap. */
596
+ export function braceExpand(s) {
597
+ // the first `{` whose matching `}` holds a top-level comma
598
+ for (let i = 0; i < s.length; i++) {
599
+ if (s[i] !== "{")
600
+ continue;
601
+ let depth = 0;
602
+ const commas = [];
603
+ let j = i;
604
+ for (; j < s.length; j++) {
605
+ if (s[j] === "{")
606
+ depth++;
607
+ else if (s[j] === "}") {
608
+ depth--;
609
+ if (depth === 0)
610
+ break;
611
+ }
612
+ else if (s[j] === "," && depth === 1)
613
+ commas.push(j);
614
+ }
615
+ if (j >= s.length)
616
+ return [s];
617
+ const inner = s.slice(i + 1, j);
618
+ if (commas.length === 0) {
619
+ if (inner.includes(".."))
620
+ no("brace sequence");
621
+ continue;
622
+ }
623
+ const alts = [];
624
+ let from = i + 1;
625
+ for (const c of [...commas, j]) {
626
+ alts.push(s.slice(from, c));
627
+ from = c + 1;
628
+ }
629
+ const pre = s.slice(0, i);
630
+ const post = s.slice(j + 1);
631
+ const out = alts.flatMap((a) => braceExpand(pre + a + post));
632
+ if (out.length > CAP)
633
+ no("too many brace values");
634
+ return out;
635
+ }
636
+ return [s];
637
+ }
638
+ function expand(w, st, ctx) {
639
+ if (w.array !== undefined)
640
+ no("array word");
641
+ let unknown = false;
642
+ let unquotedUnknown = false;
643
+ let glob = false;
644
+ let prefix = "";
645
+ let prefixOpen = true;
646
+ // A variable has one value within a word: its values are enumerated once per word, not once per occurrence. Each variable's domain holds
647
+ // its values, an array's elements joined (zsh's "$T"), and the blank-split pieces of a scalar (bash's unquoted $x): a superset.
648
+ const domains = new Map();
649
+ for (const p of w.parts) {
650
+ if (prefixOpen && p.t === "lit")
651
+ prefix += p.s;
652
+ else
653
+ prefixOpen = false;
654
+ if (p.t === "sub") {
655
+ evalNode(p.list, st, ctx);
656
+ unknown = true;
657
+ if (!p.q)
658
+ unquotedUnknown = true;
659
+ }
660
+ else if (p.t === "special") {
661
+ unknown = true;
662
+ if (!p.q)
663
+ unquotedUnknown = true;
664
+ }
665
+ else if (p.t === "var") {
666
+ const b = st.vars.get(p.name);
667
+ if (b === undefined)
668
+ no(`$${p.name} is not bound in the command`);
669
+ if (b === "taint") {
670
+ unknown = true;
671
+ if (!p.q)
672
+ unquotedUnknown = true;
673
+ continue;
674
+ }
675
+ let vals = b.arr ? [...b.vals, b.vals.join(" ")] : b.vals;
676
+ vals = uniq(vals.flatMap((v) => (/\s/.test(v) ? [v, ...v.split(/\s+/).filter((x) => x !== "")] : [v])));
677
+ if (!p.q && vals.some((v) => /[*?[]/.test(v)))
678
+ glob = true;
679
+ domains.set(p.name, vals);
680
+ }
681
+ else if (!p.q && /[*?[]/.test(p.s))
682
+ glob = true;
683
+ }
684
+ if (unknown)
685
+ return { vals: [], unknown, unquotedUnknown, glob, prefix };
686
+ let combos = [new Map()];
687
+ for (const [name, vals] of domains) {
688
+ combos = combos.flatMap((c) => vals.map((v) => new Map(c).set(name, v)));
689
+ if (combos.length > CAP)
690
+ no("too many values");
691
+ }
692
+ const out = [];
693
+ for (const c of combos) {
694
+ let alts = [""];
695
+ for (const p of w.parts) {
696
+ const vals = p.t === "var" ? [c.get(p.name)] : p.t === "lit" ? (p.q || !p.s.includes("{") ? [p.s] : braceExpand(p.s)) : [""];
697
+ const next = [];
698
+ for (const x of alts)
699
+ for (const v of vals)
700
+ next.push(x + v);
701
+ alts = next;
702
+ if (alts.length > CAP)
703
+ no("too many values");
704
+ }
705
+ out.push(...alts);
706
+ if (out.length > CAP * 4)
707
+ no("too many values");
708
+ }
709
+ return { vals: uniq(out), unknown, unquotedUnknown, glob, prefix };
710
+ }
711
+ /** A word every value of which is known, as its values; UNKNOWN otherwise. */
712
+ function known(e, what) {
713
+ if (e.unknown || e.glob)
714
+ no(`${what} is not literal`);
715
+ return e.vals;
716
+ }
717
+ /**
718
+ * Fail-closed: on win32 a path is read only as `/<one drive letter>/seg/seg...` where every segment is a plain name. Anything that
719
+ * Windows or Git Bash may resolve to a file by another route (8.3 short names `PROGRA~1`, trailing dots or spaces, `:` streams, `%`, wildcards,
720
+ * device names, `/cygdrive`, msys mounts `/tmp` `/usr` `/home` `/dev` `/proc`, `//host`, any non-drive root) makes the command unknown.
721
+ */
722
+ const PLAIN_SEG = /^(?![ .]*$)[^\\~:%*?"<>|\0-\x1f]*[^\\~:%*?"<>|\0-\x1f. ]$/;
723
+ const DEVICE_SEG = /^(con|prn|aux|nul|conin\$|conout\$|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3])(\..*)?$/i;
724
+ export function plainDrivePath(p) {
725
+ const m = /^\/([A-Za-z])((?:\/[^/]+)*)\/?$/.exec(p);
726
+ if (m === null)
727
+ return false;
728
+ return m[2].split("/").slice(1).every((seg) => PLAIN_SEG.test(seg) && !DEVICE_SEG.test(seg));
729
+ }
730
+ function resolveIn(st, p) {
731
+ if (p === "")
732
+ no("empty path");
733
+ if (p.startsWith("~"))
734
+ no("~ path");
735
+ if (p.split("/").includes(".."))
736
+ no(".. in a path");
737
+ let out;
738
+ if (p.startsWith("/"))
739
+ out = [path.posix.normalize(p)]; // The analysis runs in POSIX shape; a win32 cwd and file are mapped to it first (`posixForm`)
740
+ else {
741
+ if (st.cwds === null)
742
+ no("relative path with an unknown working directory");
743
+ out = st.cwds.map((c) => path.posix.resolve(c, p));
744
+ }
745
+ if (st.win === true && !out.every(plainDrivePath))
746
+ no("win32 path that is not a plain drive form");
747
+ return out;
748
+ }
749
+ function addTargets(ctx, st, e, tree, what, removes = false) {
750
+ for (const v of known(e, what)) {
751
+ if (v.startsWith("-"))
752
+ no(`${what} looks like an option`);
753
+ for (const p of resolveIn(st, v))
754
+ ctx.targets.push({ path: p, tree, ...(removes ? { removes: true } : {}) });
755
+ }
756
+ }
757
+ /** Short-option clusters: each letter in `flags` stands alone, each in `withArg` takes the rest of the word or the next word. */
758
+ function options(args, flags, withArg, longs = {}) {
759
+ // GNU tools and curl take options after operands too, so every argument that may be an option is read as one
760
+ const opts = [];
761
+ const rest = [];
762
+ const lit = (x) => ({ vals: [x], unknown: false, unquotedUnknown: false, glob: false, prefix: x });
763
+ for (let i = 0; i < args.length; i++) {
764
+ const a = args[i];
765
+ if (a.unquotedUnknown)
766
+ no("unquoted unknown argument");
767
+ if (a.unknown) {
768
+ if (a.prefix === "" || a.prefix.startsWith("-"))
769
+ no("an argument that may be an option");
770
+ rest.push(a);
771
+ continue;
772
+ }
773
+ if (a.vals.length !== 1) {
774
+ if (a.vals.some((v) => v.startsWith("-")))
775
+ no("an option from an expansion");
776
+ rest.push(a);
777
+ continue;
778
+ }
779
+ const v = a.vals[0];
780
+ if (v === "--") {
781
+ rest.push(...args.slice(i + 1));
782
+ break;
783
+ }
784
+ if (!v.startsWith("-") || v === "-") {
785
+ rest.push(a);
786
+ continue;
787
+ }
788
+ if (v.startsWith("--")) {
789
+ const eq = v.indexOf("=");
790
+ const name = eq < 0 ? v : v.slice(0, eq);
791
+ const kind = longs[name];
792
+ if (kind === undefined)
793
+ no(`option ${name}`);
794
+ if (kind === "flag") {
795
+ if (eq >= 0)
796
+ no(`option ${name}=`);
797
+ opts.push({ o: name });
798
+ }
799
+ else if (eq >= 0)
800
+ opts.push({ o: name, v: lit(v.slice(eq + 1)) });
801
+ else {
802
+ const nv = args[++i];
803
+ if (nv === undefined)
804
+ no(`option ${name} without its value`);
805
+ opts.push({ o: name, v: nv });
806
+ }
807
+ continue;
808
+ }
809
+ for (let k = 1; k < v.length; k++) {
810
+ const c = v[k];
811
+ if (flags.includes(c)) {
812
+ opts.push({ o: "-" + c });
813
+ continue;
814
+ }
815
+ if (withArg.includes(c)) {
816
+ const restOf = v.slice(k + 1);
817
+ if (restOf !== "")
818
+ opts.push({ o: "-" + c, v: lit(restOf) });
819
+ else {
820
+ const nv = args[++i];
821
+ if (nv === undefined)
822
+ no(`option -${c} without its value`);
823
+ opts.push({ o: "-" + c, v: nv });
824
+ }
825
+ break;
826
+ }
827
+ no(`option -${c}`);
828
+ }
829
+ }
830
+ return { opts, rest };
831
+ }
832
+ /** Readers that have no way at all to write a file, whatever their arguments. */
833
+ /** Variables that change how the shell splits, finds programs or directories, or whether a child carries the write hook. */
834
+ const DANGEROUS_VARS = /^(IFS|PATH|CDPATH|HOME|BASH_ENV|ENV|ZDOTDIR|SHELLOPTS|BASHOPTS|GLOBIGNORE|POSIXLY_CORRECT|FPATH|CURL_HOME|XDG_CONFIG_HOME|TMPDIR|PYTHON\w*|NODE_\w*|LD_\w*|DYLD_\w*|COCHECK_\w*)$/;
835
+ /** Interpreters a program word may name: bare (found on PATH) or absolute under these system folders; `./python3`, a venv's or a user path is not one. */
836
+ const SYSTEM_BIN = /^\/(usr\/bin|bin|usr\/local\/bin|opt\/homebrew\/bin)\/[^/]+$/;
837
+ /** Where a hooked child's interpreter (its start record's path) may live to be trusted. */
838
+ const TRUSTED_INTERPRETER = /^\/(usr\/bin|bin|usr\/local\/(bin|Cellar|opt)|opt\/homebrew\/(bin|Cellar|opt)|Library\/Frameworks\/Python\.framework|Library\/Developer\/CommandLineTools|Applications\/Xcode\.app)\//;
839
+ const trustedInterpreter = (p) => TRUSTED_INTERPRETER.test(p) && !p.split("/").includes("..");
840
+ const READERS = new Set(["echo", "cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "ls", "true", "false", ":", "pwd", "sleep", "wait", "test", "[", "tr", "cut", "basename", "dirname", "break", "continue"]);
841
+ const PYTHON = /^python(\d+(\.\d+)*)?$/;
842
+ const CURL_LONG = {
843
+ "--silent": "flag", "--show-error": "flag", "--fail": "flag", "--fail-with-body": "flag", "--location": "flag", "--head": "flag", "--include": "flag",
844
+ "--insecure": "flag", "--globoff": "flag", "--compressed": "flag", "--verbose": "flag", "--get": "flag", "--http1.1": "flag", "--http2": "flag",
845
+ "--no-progress-meter": "flag", "--progress-bar": "flag", "--remote-name": "flag", "--create-dirs": "flag", "--raw": "flag",
846
+ "--user-agent": "arg", "--header": "arg", "--referer": "arg", "--max-time": "arg", "--connect-timeout": "arg", "--request": "arg", "--retry": "arg",
847
+ "--retry-delay": "arg", "--retry-max-time": "arg", "--range": "arg", "--proxy": "arg", "--data": "arg", "--data-raw": "arg", "--data-binary": "arg",
848
+ "--data-urlencode": "arg", "--cookie": "arg", "--write-out": "arg", "--max-filesize": "arg", "--url": "arg", "--output": "arg", "--user": "arg",
849
+ };
850
+ function curl(args, st, ctx) {
851
+ ctx.curl = true;
852
+ const { opts, rest } = options(args, "sSfLIikgvGNq#", "AHemXurxdbwo", CURL_LONG);
853
+ const urls = [...rest];
854
+ let remote = false;
855
+ let globoff = false;
856
+ for (const { o, v } of opts) {
857
+ if (o === "-o" || o === "--output") {
858
+ const vals = known(v, "curl output");
859
+ if (vals.some((x) => x.includes("#")))
860
+ no("curl output with #N");
861
+ const real = vals.filter((x) => x !== "-");
862
+ if (real.length > 0)
863
+ addTargets(ctx, st, { ...v, vals: real }, false, "curl output");
864
+ }
865
+ else if (o === "-O" || o === "--remote-name")
866
+ remote = true;
867
+ else if (o === "-g" || o === "--globoff")
868
+ globoff = true;
869
+ else if (o === "--url")
870
+ urls.push(v);
871
+ else if (o === "-w" || o === "--write-out") {
872
+ if (v.unknown || v.vals.some((x) => x.includes("%output{") || x.startsWith("@")))
873
+ no("curl --write-out to a file");
874
+ }
875
+ else if (v !== undefined && v.unquotedUnknown)
876
+ no("unquoted unknown curl option value");
877
+ }
878
+ for (const u of urls) {
879
+ if (u.unquotedUnknown)
880
+ no("unquoted unknown curl argument");
881
+ if (u.unknown ? u.prefix.startsWith("-") || u.prefix === "" : u.vals.some((x) => x.startsWith("-")))
882
+ no("curl argument that may be an option");
883
+ }
884
+ if (remote) {
885
+ for (const u of urls) {
886
+ for (const url of known(u, "curl -O URL")) {
887
+ if (!globoff && /[{}[\]]/.test(url))
888
+ no("curl URL glob with -O");
889
+ const base = url.replace(/[?#].*$/, "").replace(/^[a-z]+:\/\/[^/]*/i, "").split("/").pop() ?? "";
890
+ if (base === "" || base === "." || base === "..")
891
+ no("curl -O without a file name");
892
+ for (const p of resolveIn(st, base))
893
+ ctx.targets.push({ path: p, tree: false });
894
+ }
895
+ }
896
+ }
897
+ }
898
+ // ---- strict read-only Python (for `python -I`, which carries no write hook) ----
899
+ const PY_MODULES = new Set(["json", "sys", "datetime", "math", "re", "csv", "statistics"]);
900
+ const PY_BANNED = /\b(os|shutil|subprocess|pathlib|io|eval|exec|compile|globals|locals|vars|getattr|setattr|delattr|importlib|builtins|modules|breakpoint|help|write|writelines|writer|DictWriter|save|savefig|dump|to_csv|to_excel|to_json|to_pickle|truncate|remove|unlink|rename|replace|mkdir|makedirs|rmdir|system|popen|spawn|fork|kill|chmod|chown|symlink|link|open_code|file)\b/;
901
+ /** Skips a Python string literal starting at `i` (at its quote); returns the index after it. */
902
+ function skipPyString(code, i) {
903
+ const q = code[i];
904
+ const triple = code.startsWith(q.repeat(3), i);
905
+ let j = i + (triple ? 3 : 1);
906
+ for (; j < code.length; j++) {
907
+ if (code[j] === "\\") {
908
+ j++;
909
+ continue;
910
+ }
911
+ if (triple ? code.startsWith(q.repeat(3), j) : code[j] === q)
912
+ return j + (triple ? 3 : 1);
913
+ if (!triple && code[j] === "\n")
914
+ no("unclosed Python string");
915
+ }
916
+ return no("unclosed Python string");
917
+ }
918
+ /** The top-level arguments of the call whose `(` is at `open`. */
919
+ function pyArgs(code, open) {
920
+ const args = [];
921
+ let depth = 0;
922
+ let from = open + 1;
923
+ for (let j = open; j < code.length; j++) {
924
+ const c = code[j];
925
+ if (c === "'" || c === '"') {
926
+ j = skipPyString(code, j) - 1;
927
+ continue;
928
+ }
929
+ if (c === "(" || c === "[" || c === "{")
930
+ depth++;
931
+ else if (c === ")" || c === "]" || c === "}") {
932
+ depth--;
933
+ if (depth === 0) {
934
+ args.push(code.slice(from, j));
935
+ return args.map((a) => a.trim()).filter((a, k, all) => !(a === "" && k === all.length - 1));
936
+ }
937
+ }
938
+ else if (c === "," && depth === 1) {
939
+ args.push(code.slice(from, j));
940
+ from = j + 1;
941
+ }
942
+ }
943
+ return no("unclosed Python call");
944
+ }
945
+ /**
946
+ * Whether `code` (run with `python -I`, so neither the cwd nor PYTHON* variables reach sys.path) can only read: imports limited to
947
+ * json, sys, datetime, math, re, csv and statistics; every open() with one argument or an explicit read mode; no dunder, no non-ASCII
948
+ * (identifiers are NFKC-folded), and none of a list of names that reach files, programs or arbitrary objects (os, shutil, subprocess,
949
+ * pathlib, io, eval, exec, getattr, compile, globals, write, save, dump, sys.modules, ...). The text is scanned whole, strings included,
950
+ * so an f-string cannot hide a call; a false "no" only keeps a call a suspect.
951
+ */
952
+ export function strictReadOnlyPython(code) {
953
+ if (/[^\x00-\x7f]/.test(code) || code.includes("__"))
954
+ return false;
955
+ if (PY_BANNED.test(code))
956
+ return false;
957
+ if (/\bfile\s*=/.test(code))
958
+ return false;
959
+ // rebinding the standard streams turns print() into a file write
960
+ if (/\b(sys\s*\.\s*)?(stdout|stderr|stdin)\s*(=(?!=)|:=)/.test(code))
961
+ return false;
962
+ let rest = code.replace(/\bfrom\s+([A-Za-z_][\w.]*)\s+import\b/g, (_m, mod) => {
963
+ if (!PY_MODULES.has(mod.split(".")[0]))
964
+ throw new Unknown(`import from ${mod}`);
965
+ return " ";
966
+ });
967
+ for (const m of rest.matchAll(/\bimport\s+([^\n;]+)/g)) {
968
+ for (const item of m[1].split(",")) {
969
+ const mod = item.trim().split(/\s+as\s+/)[0].trim();
970
+ if (!/^[A-Za-z_][\w.]*$/.test(mod) || !PY_MODULES.has(mod.split(".")[0]))
971
+ return false;
972
+ }
973
+ }
974
+ if (/\bfrom\b/.test(rest.replace(/(['"]).*?\1/g, "")))
975
+ return false;
976
+ for (const m of code.matchAll(/\bopen\b/g)) {
977
+ const at = m.index;
978
+ if (/\.\s*$/.test(code.slice(0, at)))
979
+ return false;
980
+ const after = /^\s*\(/.exec(code.slice(at + 4));
981
+ if (!after)
982
+ return false;
983
+ const args = pyArgs(code, at + 4 + after[0].length - 1);
984
+ if (args.some((a) => a.startsWith("*")))
985
+ return false;
986
+ if (args.length === 1 && !args[0].includes("="))
987
+ continue;
988
+ if (args.length === 2 && /^(['"])(r|rb|rt|br|tr)\1$/.test(args[1]) && !args[0].includes("="))
989
+ continue;
990
+ return false;
991
+ }
992
+ rest = "";
993
+ return true;
994
+ }
995
+ function python(name, args, stdin, ctx) {
996
+ // flags up to the script: -I/-E/-S keep the write hook out (no PYTHONPATH, or no site), so such a run must pass the strict check
997
+ let isolated = false;
998
+ let iso = false;
999
+ let code;
1000
+ let script = "none";
1001
+ for (let i = 0; i < args.length; i++) {
1002
+ const a = args[i];
1003
+ if (a.unquotedUnknown)
1004
+ no("unquoted unknown python argument");
1005
+ if (a.unknown || a.vals.length !== 1) {
1006
+ if (a.vals.some((v) => v.startsWith("-")))
1007
+ no("a python option from an expansion");
1008
+ script = "file";
1009
+ break;
1010
+ }
1011
+ const v = a.vals[0];
1012
+ if (v === "-") {
1013
+ script = "stdin";
1014
+ break;
1015
+ }
1016
+ if (!v.startsWith("-")) {
1017
+ script = "file";
1018
+ break;
1019
+ }
1020
+ let done = false;
1021
+ for (let k = 1; k < v.length && !done; k++) {
1022
+ const c = v[k];
1023
+ if ("IES".includes(c)) {
1024
+ isolated = true;
1025
+ if (c === "I")
1026
+ iso = true;
1027
+ }
1028
+ else if ("suBOqbdv".includes(c))
1029
+ continue;
1030
+ else if (c === "W" || c === "X") {
1031
+ if (k === v.length - 1)
1032
+ i++;
1033
+ done = true;
1034
+ }
1035
+ else if (c === "c") {
1036
+ code = k === v.length - 1 ? args[++i] : { vals: [v.slice(k + 1)], unknown: false, unquotedUnknown: false, glob: false, prefix: "" };
1037
+ if (code === undefined)
1038
+ no("python -c without code");
1039
+ script = "none";
1040
+ done = true;
1041
+ i = args.length;
1042
+ }
1043
+ else if (c === "m") {
1044
+ script = "module";
1045
+ done = true;
1046
+ i = args.length;
1047
+ }
1048
+ else
1049
+ no(`python option -${c}`);
1050
+ }
1051
+ }
1052
+ if (!isolated) {
1053
+ // a hooked run must be one whose hook can be proven per process: plain python3/python only (python3.7 has no audit hook, a versioned
1054
+ // name may be another installation)
1055
+ if (name !== "python3" && name !== "python")
1056
+ no(`hooked interpreter ${name}: only python3 or python`);
1057
+ ctx.observed = true;
1058
+ ctx.kinds.add("python");
1059
+ countRun(ctx, "python");
1060
+ return;
1061
+ }
1062
+ if (!iso)
1063
+ no("python -E or -S without -I");
1064
+ const text = code ?? (script === "stdin" || script === "none" ? stdin : undefined);
1065
+ if (text === undefined || script === "file" || script === "module")
1066
+ no("python -I running a file, a module or piped code");
1067
+ if (text.unknown)
1068
+ no("python -I code is not literal");
1069
+ for (const c of text.vals)
1070
+ if (!strictReadOnlyPython(c))
1071
+ no("python -I code outside the read-only allow-list");
1072
+ }
1073
+ /** The plain readers (no option of theirs writes) that make a command read-only; echo, printf, test, pwd and date are only glue beside them. */
1074
+ const READ_ONLY_VERBS = new Set(["cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "ls"]);
1075
+ const GIT_READ_ONLY = new Set(["status", "diff", "log", "show"]);
1076
+ /**
1077
+ * `less`, `rg`, `stat`, `file` and `git status|diff|log|show` read and never write a file of the task, unless an option says otherwise
1078
+ * (less -o/-O/--log-file/+command, rg --pre/--hostname-bin, file -C, git --output/--ext-diff/--textconv). Every argument must be fully literal
1079
+ * (a variable could hold an option), and `git` takes no global option before its subcommand. Anything else is UNKNOWN.
1080
+ */
1081
+ function readOnlyProgram(base, args) {
1082
+ if (args.some((a) => a.unknown || a.unquotedUnknown))
1083
+ no(`${base} with an argument that is not literal`);
1084
+ const words = args.flatMap((a) => a.vals);
1085
+ const flags = words.filter((w) => w.startsWith("-") || w.startsWith("+"));
1086
+ const short = (w, letters) => /^-[^-]/.test(w) && [...w.slice(1)].some((c) => letters.includes(c));
1087
+ switch (base) {
1088
+ case "less":
1089
+ if (flags.some((w) => w.startsWith("+") || short(w, "oO") || /^--(log-file|LOG-FILE|lesskey|lesskey-file)/i.test(w)))
1090
+ no("less option that writes or runs");
1091
+ return;
1092
+ case "rg":
1093
+ if (flags.some((w) => /^--(pre|hostname-bin)/.test(w)))
1094
+ no("rg option that runs a program");
1095
+ return;
1096
+ case "file":
1097
+ if (flags.some((w) => short(w, "C") || w === "--compile"))
1098
+ no("file -C");
1099
+ return;
1100
+ case "git":
1101
+ if (words.length === 0 || !GIT_READ_ONLY.has(words[0]))
1102
+ no("git subcommand outside status, diff, log and show");
1103
+ if (flags.some((w) => /^--(output|ext-diff|textconv|open-files-in-pager|exec-path)/.test(w)))
1104
+ no("git option that writes or runs a program");
1105
+ return;
1106
+ }
1107
+ }
1108
+ /**
1109
+ * Whether `command` is made only of read-only forms (wc, cat, head, tail, less, grep, rg, ls, stat, file, git status|diff|log|show, with
1110
+ * echo, printf, test, pwd, date only as glue beside one of them) with no output redirection to a file, no pipe to a writer, no in-place flag. An output redirect to a file,
1111
+ * `tee`, `sed`, `xargs`, `find` and any program or construct the parser does not understand are UNKNOWN, so the answer is false. The bound:
1112
+ * the command's words are taken at face value (a shell alias or function that shadows `cat` is not seen).
1113
+ */
1114
+ export function isReadOnlyCommand(command) {
1115
+ if (command.trim() === "")
1116
+ return false;
1117
+ try {
1118
+ const st = { cwds: null, vars: new Map() };
1119
+ const ctx = { targets: [], observed: false, kinds: new Set(), runs: { python: 0, node: 0 }, mult: 1, counting: true, curl: false, pure: true, reader: false };
1120
+ evalNode(parse(command), st, ctx);
1121
+ return ctx.pure && ctx.reader && ctx.targets.length === 0 && !ctx.observed && !ctx.curl;
1122
+ }
1123
+ catch {
1124
+ return false;
1125
+ }
1126
+ }
1127
+ const MAX_RUNS = 256;
1128
+ function countRun(ctx, kind) {
1129
+ if (!ctx.counting)
1130
+ return;
1131
+ ctx.runs[kind] += ctx.mult;
1132
+ if (ctx.runs[kind] > MAX_RUNS)
1133
+ no("too many interpreter runs");
1134
+ }
1135
+ /** At most how many times a `for` runs its body: literal words brace-expanded, a lone variable its elements (or blank-split pieces). */
1136
+ function iterations(words, st, ctx) {
1137
+ let n = 0;
1138
+ for (const w of words) {
1139
+ const parts = w.parts.filter((p) => !(p.t === "lit" && p.s === ""));
1140
+ if (parts.length === 1 && parts[0].t === "var") {
1141
+ const v = parts[0];
1142
+ const b = st.vars.get(v.name);
1143
+ if (b === undefined || b === "taint")
1144
+ no("for list is not literal");
1145
+ const raw = b.count ?? b.vals.length;
1146
+ n += b.arr ? raw : v.q ? 1 : Math.max(raw, ...b.vals.map((x) => x.split(/\s+/).filter((y) => y !== "").length));
1147
+ continue;
1148
+ }
1149
+ n += Math.max(1, expand(w, st, ctx).vals.length);
1150
+ }
1151
+ return n;
1152
+ }
1153
+ function evalSimple(n, st, ctx) {
1154
+ let stdin;
1155
+ for (const r of n.redirs)
1156
+ stdin = checkRedir(r, st, ctx) ?? stdin;
1157
+ const assigns = [];
1158
+ let i = 0;
1159
+ for (; i < n.words.length; i++) {
1160
+ const w = n.words[i];
1161
+ const first = w.parts[0];
1162
+ if (first && first.t === "lit" && !first.q && /^[A-Za-z_][A-Za-z0-9_]*=/.test(first.s))
1163
+ assigns.push(w);
1164
+ else
1165
+ break;
1166
+ }
1167
+ const words = n.words.slice(i);
1168
+ if (words.length === 0) {
1169
+ const vars = new Map(st.vars);
1170
+ for (const w of assigns) {
1171
+ const first = w.parts[0];
1172
+ const name = first.s.slice(0, first.s.indexOf("="));
1173
+ if (DANGEROUS_VARS.test(name))
1174
+ no(`assignment to ${name}`);
1175
+ if (w.array !== undefined) {
1176
+ const exps = w.array.map((e) => expand(e, st, ctx));
1177
+ vars.set(name, exps.some((e) => e.unknown || e.glob) ? "taint" : { vals: uniq(exps.flatMap((e) => e.vals)), arr: true, count: exps.reduce((n, e) => n + Math.max(1, e.vals.length), 0) });
1178
+ continue;
1179
+ }
1180
+ const rest = { parts: [{ t: "lit", s: first.s.slice(name.length + 1), q: true }, ...w.parts.slice(1)] };
1181
+ const e = expand(rest, st, ctx);
1182
+ vars.set(name, e.unknown ? "taint" : { vals: e.vals, arr: false });
1183
+ }
1184
+ return both({ ...st, vars });
1185
+ }
1186
+ if (assigns.length > 0)
1187
+ no("environment prefix on a command");
1188
+ const prog = plainOf(words[0]);
1189
+ if (prog === undefined || (prog !== "[" && /[*?[{$]/.test(prog)))
1190
+ no("program name is not literal");
1191
+ const args = words.slice(1).map((w) => expand(w, st, ctx));
1192
+ const base = prog.includes("/") ? path.posix.basename(prog) : prog;
1193
+ const sys = !prog.includes("/") || /^\/(usr\/)?bin\/[^/]+$/.test(prog);
1194
+ if (PYTHON.test(base) || base === "node") {
1195
+ if (prog.includes("/") && !SYSTEM_BIN.test(prog))
1196
+ no(`interpreter ${prog} outside the system folders`);
1197
+ ctx.pure = false;
1198
+ if (base === "node") {
1199
+ if (args.some((a) => a.unquotedUnknown))
1200
+ no("unquoted unknown node argument");
1201
+ ctx.observed = true;
1202
+ ctx.kinds.add("node");
1203
+ countRun(ctx, "node");
1204
+ }
1205
+ else
1206
+ python(base, args, stdin, ctx);
1207
+ return both(st);
1208
+ }
1209
+ if (!sys)
1210
+ no(`program ${prog}`);
1211
+ if (READERS.has(base)) {
1212
+ if (READ_ONLY_VERBS.has(base))
1213
+ ctx.reader = true;
1214
+ return both(st);
1215
+ }
1216
+ switch (base) {
1217
+ case "printf":
1218
+ if (args[0] && (args[0].unquotedUnknown || args[0].vals.some((v) => v.startsWith("-v")) || (args[0].unknown && args[0].prefix.startsWith("-"))))
1219
+ no("printf -v");
1220
+ return both(st);
1221
+ case "date":
1222
+ for (const a of args)
1223
+ if (a.unknown || a.vals.some((v) => !(v.startsWith("+") || v === "-u")))
1224
+ no("date with an argument that may set the clock");
1225
+ return both(st);
1226
+ case "cd": {
1227
+ if (args.length !== 1)
1228
+ no("cd without one literal path");
1229
+ const dirs = known(args[0], "cd path");
1230
+ if (dirs.some((d) => d.startsWith("-")))
1231
+ no("cd option");
1232
+ // a bare relative cd may go through an inherited CDPATH: only an absolute path or ./ is read
1233
+ // POSIX-shaped analysis (a win32 Git Bash command's `/c/x` is absolute here)
1234
+ if (dirs.some((d) => !d.startsWith("/") && !d.startsWith("./")))
1235
+ no("cd to a relative path without ./");
1236
+ const next = uniq(dirs.flatMap((d) => resolveIn(st, d)));
1237
+ const ok = { ...st, cwds: next };
1238
+ // a cd into a directory that exists before the command runs (checked at the call's Pre) does not fail
1239
+ const cannotFail = ctx.pre !== undefined && next.every((d) => ctx.pre.dirExists(d));
1240
+ return { ok, fail: cannotFail ? ok : st };
1241
+ }
1242
+ case "mkdir": {
1243
+ ctx.pure = false;
1244
+ const { rest } = options(args, "pv", "m");
1245
+ for (const r of rest)
1246
+ known(r, "mkdir operand");
1247
+ return both(st);
1248
+ }
1249
+ case "rm": {
1250
+ ctx.pure = false;
1251
+ const { opts, rest } = options(args, "fFrRidvI", "");
1252
+ const tree = opts.some((o) => o.o === "-r" || o.o === "-R");
1253
+ for (const r of rest)
1254
+ addTargets(ctx, st, r, tree, "rm operand", true);
1255
+ return both(st);
1256
+ }
1257
+ case "touch": {
1258
+ ctx.pure = false;
1259
+ const { rest } = options(args, "acmhf", "tdr");
1260
+ for (const r of rest)
1261
+ addTargets(ctx, st, r, false, "touch operand");
1262
+ return both(st);
1263
+ }
1264
+ case "cp":
1265
+ case "mv": {
1266
+ ctx.pure = false;
1267
+ const { rest } = options(args, base === "cp" ? "fipvnX" : "fivn", "");
1268
+ if (rest.length < 2)
1269
+ no(`${base} without a source and a destination`);
1270
+ const dst = rest[rest.length - 1];
1271
+ const srcs = rest.slice(0, -1);
1272
+ const tree = base === "mv";
1273
+ addTargets(ctx, st, dst, tree, `${base} destination`);
1274
+ for (const s of srcs) {
1275
+ const vals = known(s, `${base} source`);
1276
+ if (vals.some((v) => v.startsWith("-")))
1277
+ no(`${base} source looks like an option`);
1278
+ if (tree)
1279
+ addTargets(ctx, st, s, true, "mv source", true);
1280
+ for (const d of known(dst, `${base} destination`)) {
1281
+ for (const v of vals) {
1282
+ const name = path.posix.basename(v);
1283
+ if (name === "" || name === "." || name === "..")
1284
+ no(`${base} source without a name`);
1285
+ for (const p of resolveIn(st, d)) {
1286
+ const to = path.posix.join(p, name);
1287
+ if (st.win === true && !plainDrivePath(to))
1288
+ no("win32 path that is not a plain drive form");
1289
+ ctx.targets.push({ path: to, tree });
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ return both(st);
1295
+ }
1296
+ case "curl":
1297
+ ctx.pure = false;
1298
+ curl(args, st, ctx);
1299
+ return both(st);
1300
+ // More read-only programs, each only without the options that make it write or run another program; any other option is UNKNOWN, as before
1301
+ case "less":
1302
+ case "rg":
1303
+ case "stat":
1304
+ case "file":
1305
+ case "git":
1306
+ readOnlyProgram(base, args);
1307
+ ctx.reader = true;
1308
+ return both(st);
1309
+ }
1310
+ return no(`program ${base}`);
1311
+ }
1312
+ /** Checks one redirect; returns the stdin a heredoc or here-string gives the command, if any. */
1313
+ function checkRedir(r, st, ctx) {
1314
+ const op = r.op.replace(/^\d+/, "");
1315
+ if (op === "<<" || op === "<<-")
1316
+ return expand(r.body, st, ctx);
1317
+ const t = expand(r.target, st, ctx);
1318
+ if (op === "<<<")
1319
+ return t;
1320
+ if (op === "<")
1321
+ return undefined;
1322
+ if (op === ">&" || op === "<&") {
1323
+ if (!t.unknown && t.vals.length === 1 && /^(\d+|-)$/.test(t.vals[0]))
1324
+ return undefined;
1325
+ return no("redirect to a file with >&");
1326
+ }
1327
+ if (op === ">" || op === ">>" || op === ">|" || op === "&>" || op === "&>>") {
1328
+ if (!t.unknown && !t.glob && t.vals.length === 1 && t.vals[0] === "/dev/null")
1329
+ return undefined;
1330
+ return no("output redirect to a file");
1331
+ }
1332
+ return no(`redirect ${r.op}`);
1333
+ }
1334
+ function withRedirs(redirs, st, ctx, run) {
1335
+ for (const r of redirs)
1336
+ checkRedir(r, st, ctx);
1337
+ return run();
1338
+ }
1339
+ function evalNode(n, st, ctx) {
1340
+ switch (n.k) {
1341
+ case "list": {
1342
+ let R = both(st);
1343
+ let prev = ";";
1344
+ for (const { node, op } of n.items) {
1345
+ if (prev === "&&") {
1346
+ const r = evalNode(node, R.ok, ctx);
1347
+ R = { ok: r.ok, fail: union(r.fail, R.fail) };
1348
+ }
1349
+ else if (prev === "||") {
1350
+ const r = evalNode(node, R.fail, ctx);
1351
+ R = { ok: union(r.ok, R.ok), fail: r.fail };
1352
+ }
1353
+ else
1354
+ R = evalNode(node, union(R.ok, R.fail), ctx);
1355
+ prev = op;
1356
+ }
1357
+ return R;
1358
+ }
1359
+ case "pipe": {
1360
+ const outs = n.cmds.map((c) => evalNode(c, st, ctx));
1361
+ return both(union(st, ...outs.flatMap((o) => [o.ok, o.fail])));
1362
+ }
1363
+ case "simple":
1364
+ return evalSimple(n, st, ctx);
1365
+ case "sub":
1366
+ return withRedirs(n.redirs, st, ctx, () => {
1367
+ const o = evalNode(n.body, st, ctx);
1368
+ return both(union(st, o.ok, o.fail));
1369
+ });
1370
+ case "group":
1371
+ return withRedirs(n.redirs, st, ctx, () => same(evalNode(n.body, st, ctx)));
1372
+ case "for":
1373
+ return withRedirs(n.redirs, st, ctx, () => {
1374
+ const vals = uniq(n.words.flatMap((w) => known(expand(w, st, ctx), "for list")));
1375
+ const bind = vals.length > 0 ? { vals, arr: false } : "taint";
1376
+ const set = (s) => ({ ...s, vars: new Map(s.vars).set(n.name, bind) });
1377
+ let cur = set(st);
1378
+ const mult = ctx.mult;
1379
+ const counting = ctx.counting;
1380
+ ctx.mult = mult * iterations(n.words, st, ctx);
1381
+ try {
1382
+ for (let k = 0;; k++) {
1383
+ if (k > 4)
1384
+ no("loop state does not settle");
1385
+ if (k > 0)
1386
+ ctx.counting = false;
1387
+ const o = evalNode(n.body, cur, ctx);
1388
+ const next = set(union(cur, o.ok, o.fail));
1389
+ if (key(next) === key(cur))
1390
+ break;
1391
+ cur = next;
1392
+ }
1393
+ }
1394
+ finally {
1395
+ ctx.mult = mult;
1396
+ ctx.counting = counting;
1397
+ }
1398
+ return both(cur);
1399
+ });
1400
+ case "if":
1401
+ return withRedirs(n.redirs, st, ctx, () => {
1402
+ let all = [st];
1403
+ let input = st;
1404
+ for (const p of n.parts) {
1405
+ const o = evalNode(p, input, ctx);
1406
+ all = [...all, o.ok, o.fail];
1407
+ input = union(...all);
1408
+ }
1409
+ return both(input);
1410
+ });
1411
+ }
1412
+ }
1413
+ /**
1414
+ * The paths `command` can write or remove, run from `cwd` (null when unknown: then any relative path is UNKNOWN), or UNKNOWN with why.
1415
+ * An empty command is UNKNOWN: a record that lost its command proves nothing.
1416
+ */
1417
+ export function writeScope(command, cwd, opts = {}) {
1418
+ if (command.trim() === "")
1419
+ return { known: false, why: "no command" };
1420
+ const kit = opts.kit ?? guardKit();
1421
+ try {
1422
+ // PowerShell is read only on win32, and only the bounded forms of write-scope-win.ts; elsewhere it is unknown, never excluded
1423
+ if (opts.shell === "powershell" && !isWin(kit))
1424
+ no("PowerShell command");
1425
+ // A Git Bash command that is one `powershell|pwsh -Command ...` call is read as the PowerShell it runs
1426
+ const wrapped = opts.shell === undefined && isWin(kit) ? gitBashPowerShell(command) : undefined;
1427
+ // Otherwise on win32 a Git Bash command is read in its own `/c/Users/...` form; a Windows-form path word (`C:\x`, `C:/x`) means the command
1428
+ // may be PowerShell or cmd run by a shell the host did not name: unknown, never excluded
1429
+ if (wrapped === undefined && opts.shell === undefined && isWin(kit) && /(^|[\s"'=(<>|;&])[A-Za-z]:[\\/]/.test(command))
1430
+ no("Windows-form path in the command");
1431
+ const pcwd = cwd === null ? null : posixForm(cwd, kit);
1432
+ if (isWin(kit) && pcwd !== null && !plainDrivePath(path.posix.normalize(pcwd)))
1433
+ no("win32 cwd that is not a plain drive form");
1434
+ const st = { cwds: pcwd !== null && pcwd.startsWith("/") && !pcwd.split("/").includes("..") ? [path.posix.normalize(pcwd)] : null, vars: new Map(), ...(isWin(kit) ? { win: true } : {}) };
1435
+ const ctx = { targets: [], observed: false, kinds: new Set(), runs: { python: 0, node: 0 }, mult: 1, counting: true, curl: false, pure: true, reader: false, ...(opts.pre ? { pre: opts.pre } : {}) };
1436
+ const win = {
1437
+ resolve: (p) => resolveIn(st, p),
1438
+ push: (t) => ctx.targets.push(t),
1439
+ fileAtPre: (p) => opts.pre !== undefined && opts.pre.exists(p) && !opts.pre.dirExists(p),
1440
+ };
1441
+ if (opts.shell === "powershell")
1442
+ readPowerShell(command, win);
1443
+ else if (wrapped !== undefined)
1444
+ readPowerShell(wrapped, win);
1445
+ else
1446
+ evalNode(parse(command), st, ctx);
1447
+ // at the Pre, before anything ran: every target's directories exist and hold no link the user could repoint, and no target is a link
1448
+ if (opts.pre)
1449
+ for (const t of ctx.targets)
1450
+ if (opts.pre.canonical(t.path) === undefined || !opts.pre.dirExists(path.posix.dirname(t.path)))
1451
+ no(`target ${t.path} is not where it reads at the Pre`);
1452
+ const seen = new Set();
1453
+ const targets = ctx.targets.filter((t) => {
1454
+ const k = `${t.tree ? 1 : 0}${t.removes ? 1 : 0}${t.path}`;
1455
+ if (seen.has(k))
1456
+ return false;
1457
+ seen.add(k);
1458
+ return true;
1459
+ });
1460
+ return { known: true, targets, observed: ctx.observed, ...(ctx.kinds.size > 0 ? { observedKinds: [...ctx.kinds].sort() } : {}), runs: { ...ctx.runs }, curl: ctx.curl };
1461
+ }
1462
+ catch (e) {
1463
+ if (e instanceof Unknown || e instanceof WinUnknown)
1464
+ return { known: false, why: e.message };
1465
+ return { known: false, why: "analyzer error" };
1466
+ }
1467
+ }
1468
+ /**
1469
+ * The PowerShell script of a Git Bash command that is exactly one `powershell(.exe)|pwsh(.exe) [options] -Command WORDS` call with
1470
+ * fully literal words and no redirect; undefined for any other command (read as Git Bash). A wrapper word that cannot be read is UNKNOWN.
1471
+ */
1472
+ function gitBashPowerShell(command) {
1473
+ let node;
1474
+ try {
1475
+ node = parse(command);
1476
+ }
1477
+ catch {
1478
+ return undefined;
1479
+ }
1480
+ if (node.k !== "list" || node.items.length !== 1)
1481
+ return undefined;
1482
+ const n = node.items[0].node;
1483
+ if (n.k !== "simple" || n.words.length === 0)
1484
+ return undefined;
1485
+ const prog = plainOf(n.words[0])?.toLowerCase();
1486
+ if (prog === undefined || !PS_WRAPPERS.has(prog))
1487
+ return undefined;
1488
+ if (n.redirs.length > 0)
1489
+ no("redirect on a powershell wrapper");
1490
+ const words = n.words.slice(1).map((w) => literalOf(w));
1491
+ if (words.some((w) => w === undefined))
1492
+ no("powershell wrapper word that is not literal");
1493
+ return psWrapperScript(words, true);
1494
+ }
1495
+ /**
1496
+ * Whether every hooked interpreter process the command starts provably carried the hook: per kind, as many start records from distinct
1497
+ * pids as the command can start (`scope.runs`), not counting a record whose parent is another hooked process of the call (a child it
1498
+ * started), each from an interpreter in a system folder, and none of that kind from anywhere else. A command with no hooked runs needs none.
1499
+ */
1500
+ export function hooksProven(scope, starts) {
1501
+ if (!scope.known)
1502
+ return false;
1503
+ const runs = scope.runs ?? { python: scope.observed ? Infinity : 0, node: scope.observed ? Infinity : 0 };
1504
+ const pids = new Set(starts.map((r) => r.pid));
1505
+ for (const kind of ["python", "node"]) {
1506
+ if (runs[kind] === 0)
1507
+ continue;
1508
+ const mine = starts.filter((r) => (kind === "node" ? path.posix.basename(r.path) === "node" : PYTHON.test(path.posix.basename(r.path))));
1509
+ if (!mine.every((r) => trustedInterpreter(r.path) && Number.isInteger(r.pid)))
1510
+ return false;
1511
+ const top = new Set(mine.filter((r) => r.ppid === undefined || !pids.has(r.ppid) || r.ppid === r.pid).map((r) => r.pid));
1512
+ if (top.size < runs[kind])
1513
+ return false;
1514
+ }
1515
+ return true;
1516
+ }
1517
+ /** For paths that cannot be looked at on this machine (a Windows path judged on another OS, as the tests do): every path as written, no curl config. */
1518
+ export const lexicalProbe = { canonical: (p) => path.posix.normalize(p), curlConfig: () => false, exists: () => true, dirExists: () => true };
1519
+ const MAX_HOPS = 16;
1520
+ /**
1521
+ * The live probe. A directory symlink is followed only when root owns it (/tmp -> /private/tmp on macOS): the user cannot repoint it. Any
1522
+ * other symlink on the way, a target that is itself a symlink, or a target file with more than one hard link is undefined. A path that
1523
+ * does not exist (yet, or any more) is taken as written from the first missing directory on.
1524
+ */
1525
+ export function fsProbe(env = process.env, kit = guardKit(), fsx = { lstat: lstatSync, readlink: readlinkSync, exists: existsSync }) {
1526
+ // On win32 the analyzer's paths are Git Bash's `/c/x`; every filesystem call takes the kit's native form (`C:\x`), and no symlink is followed
1527
+ // (Windows reports uid 0 for every file, so the root-owned test cannot tell a link the user made)
1528
+ const win = isWin(kit);
1529
+ const nat = (p) => (win ? kit.native(p) : p);
1530
+ const lstatSync = (p) => fsx.lstat(nat(p));
1531
+ const existsSync = (p) => fsx.exists(nat(p));
1532
+ return {
1533
+ canonical(p) {
1534
+ let parts = path.posix.normalize(p).split("/").filter((x) => x !== "");
1535
+ let hops = 0;
1536
+ let cur = "/";
1537
+ if (win) {
1538
+ // only a drive path (`/c/...`) is read; a UNC or other form is undefined
1539
+ if (!/^\/[A-Za-z](\/|$)/.test(path.posix.normalize(p)))
1540
+ return undefined;
1541
+ cur = `/${parts[0].toLowerCase()}`;
1542
+ parts = parts.slice(1);
1543
+ }
1544
+ for (let i = 0; i < parts.length; i++) {
1545
+ const next = path.posix.join(cur, parts[i]);
1546
+ const last = i === parts.length - 1;
1547
+ let st;
1548
+ try {
1549
+ st = lstatSync(next);
1550
+ }
1551
+ catch {
1552
+ // a missing file is taken as written; a missing directory is not (it existed at the Pre: something took it away, a link perhaps)
1553
+ return last ? next : undefined;
1554
+ }
1555
+ if (st.isSymbolicLink()) {
1556
+ if (last || win || st.uid !== 0 || ++hops > MAX_HOPS)
1557
+ return undefined;
1558
+ let to;
1559
+ try {
1560
+ to = fsx.readlink(next);
1561
+ }
1562
+ catch {
1563
+ return undefined;
1564
+ }
1565
+ // A real POSIX symlink read by lstat on the running OS (fsProbe never resolves on win32: unknown there)
1566
+ const abs = to.startsWith("/") ? to : path.posix.join(cur, to);
1567
+ parts = [...path.posix.normalize(abs).split("/").filter((x) => x !== ""), ...parts.slice(i + 1)];
1568
+ cur = "/";
1569
+ i = -1;
1570
+ continue;
1571
+ }
1572
+ if (last)
1573
+ return st.isFile() && st.nlink > 1 ? undefined : next;
1574
+ if (!st.isDirectory())
1575
+ return undefined;
1576
+ cur = next;
1577
+ }
1578
+ return cur;
1579
+ },
1580
+ exists(p) {
1581
+ try {
1582
+ lstatSync(p);
1583
+ return true;
1584
+ }
1585
+ catch {
1586
+ return false;
1587
+ }
1588
+ },
1589
+ dirExists(p) {
1590
+ // walked as a directory component (so root's /tmp link is followed), never as a final one
1591
+ const c = this.canonical(path.posix.join(p, ".cocheck-probe"));
1592
+ if (c === undefined)
1593
+ return false;
1594
+ try {
1595
+ return lstatSync(path.posix.dirname(c)).isDirectory();
1596
+ }
1597
+ catch {
1598
+ return false;
1599
+ }
1600
+ },
1601
+ curlConfig() {
1602
+ if (win) {
1603
+ const h = env.USERPROFILE ?? env.HOME ?? "";
1604
+ if (!h)
1605
+ return true;
1606
+ const w = [env.CURL_HOME && path.posix.join(env.CURL_HOME, ".curlrc"), env.CURL_HOME && path.posix.join(env.CURL_HOME, "_curlrc"), env.APPDATA && path.posix.join(env.APPDATA, "_curlrc"), path.posix.join(h, ".curlrc"), path.posix.join(h, "_curlrc"), path.posix.join(h, ".config", "curlrc")];
1607
+ return w.some((c) => typeof c === "string" && c !== "" && fsx.exists(isWin(kit) ? kit.native(c) : c));
1608
+ }
1609
+ const home = env.HOME ?? "";
1610
+ const cands = [env.CURL_HOME && path.join(env.CURL_HOME, ".curlrc"), env.XDG_CONFIG_HOME && path.join(env.XDG_CONFIG_HOME, "curlrc"), home && path.join(home, ".config", "curlrc"), home && path.join(home, ".curlrc")];
1611
+ if (!home)
1612
+ return true;
1613
+ return cands.some((c) => typeof c === "string" && c !== "" && existsSync(c));
1614
+ },
1615
+ };
1616
+ }
1617
+ const isWin = (kit) => kit.isAbs("C:/");
1618
+ /**
1619
+ * An absolute path in the one POSIX shape the analyzer reads. On win32 that is Git Bash's `/c/Users/x` (drive letter lower case); a
1620
+ * non-win32 path is unchanged. A relative path comes back as written.
1621
+ */
1622
+ function posixForm(p, kit) {
1623
+ if (!isWin(kit) || !kit.isAbs(p))
1624
+ return p;
1625
+ const c = kit.canon(p);
1626
+ return /^[A-Za-z]:/.test(c) ? `/${c[0].toLowerCase()}${c.slice(2)}` : c;
1627
+ }
1628
+ const fold = (p, kit) => kit.key(path.posix.normalize(posixForm(p, kit)).normalize("NFC"));
1629
+ /**
1630
+ * Whether a call with this write scope provably cannot have written or removed `file`: its scope is known, every Python or Node child it
1631
+ * relies on was observed writing nothing and starting nothing where the hook covers the file, no curl config can add an output, every
1632
+ * target is where it reads (`probe`), and none of them is the file or a tree holding it. Anything less is false: the call stays a suspect.
1633
+ */
1634
+ export function cannotHaveWritten(file, scope, facts, probe, kit = guardKit()) {
1635
+ if (!scope.known || !kit.isAbs(file))
1636
+ return false;
1637
+ // a command that writes nothing at all (readers only: `ls`, `echo`, `sleep`, `cat`) is never excluded: that is where a shell alias or
1638
+ // function from the user's snapshot would hide, and where a record's command may not be what ran. Only a command whose writes the analyzer
1639
+ // has read (its targets, or its hooked children) can be shown not to have written a file.
1640
+ if (scope.targets.length === 0 && !scope.observed)
1641
+ return false;
1642
+ if (scope.observed && !(facts !== undefined && facts.tagged && facts.wrote === 0 && !facts.spawned && facts.covered))
1643
+ return false;
1644
+ // "logged no write" proves nothing for a child whose hook never loaded: each kind of hooked child the command runs needs a start
1645
+ // record for this call, from an interpreter in a system folder, and every start record of that kind must be one
1646
+ if (scope.observed && !hooksProven(scope, facts?.starts ?? []))
1647
+ return false;
1648
+ if (scope.curl && probe.curlConfig())
1649
+ return false;
1650
+ const f = fold(file, kit);
1651
+ const removed = scope.targets.filter((t) => t.removes);
1652
+ for (const t of scope.targets) {
1653
+ const real = probe.canonical(t.path);
1654
+ if (real === undefined)
1655
+ return false;
1656
+ // gone at the sweep and removed by this very call: it may have been a link (or a hard link) to the file when it was written
1657
+ if (!probe.exists(t.path) && removed.some((r) => r.path === t.path || t.path.startsWith(r.path.replace(/\/$/, "") + "/"))) {
1658
+ if (scope.targets.some((w) => !w.removes && (w.path === t.path || w.path.startsWith(t.path + "/"))))
1659
+ return false;
1660
+ }
1661
+ for (const p of [t.path, real]) {
1662
+ const fp = fold(p, kit);
1663
+ if (fp === f || (t.tree && (f.startsWith(fp.endsWith("/") ? fp : fp + "/") || fp === "/")))
1664
+ return false;
1665
+ }
1666
+ }
1667
+ return true;
1668
+ }