@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.57

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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
@@ -0,0 +1,2564 @@
1
+ // The scrubber's rules (secret-cut.ts scrub): what a shared transcript is cut of, each rule anchored on something a reader
2
+ // can name: a known format, a value the server holds, a whole dump (env output, a .env file, ~/.ssh, a credentials file),
3
+ // a label typed beside a value, or a personal detail. No rule reads randomness alone. Each rule's kind is what anchors
4
+ // its match, never the file its pattern comes from: a value that names its own format (a prefix, a checksum, secretlint's
5
+ // finds) is "format"; one found by what stands beside it (a variable's name, a flag, a header, a URL's userinfo or
6
+ // parameter, a scheme word) is "label". The kind alone says whether a preview may put the text back (RESTORABLE).
7
+ //
8
+ // Every rule reads each of a text's views (viewsOf): the raw text, and the text decoded as a JSON string once, twice and
9
+ // three times, an escape a boundary in each; the engine takes the union of what every view finds. Every pattern is a
10
+ // named module-level constant (RULE_PATTERNS) and every run it reads is bounded, so each rule reads a text in time linear
11
+ // in its length (secret-scrub.test.mjs walks them).
12
+ import { heldNeedles, MIN_SECRET } from "./learn/secrets.js";
13
+ import { cutSpans, SECRET_SHAPES, shapeSpans } from "./redact/match.js";
14
+ /** Whether a cut of each kind may be put back by a preview: fixed per kind, never per rule or per cut. */
15
+ export const RESTORABLE = Object.freeze({ format: false, held: false, dump: false, label: true, personal: true, jev: true });
16
+ /** The index of the last of `places` (sorted) before `at`, or -1. */
17
+ function placeBefore(places, at) {
18
+ let low = 0;
19
+ let high = places.length;
20
+ while (low < high) {
21
+ const mid = (low + high) >> 1;
22
+ if (places[mid] < at)
23
+ low = mid + 1;
24
+ else
25
+ high = mid;
26
+ }
27
+ return low - 1;
28
+ }
29
+ /** A text's strings: its quotes (sorted, none an escape's) paired the way JSON reads them, an opening quote then the
30
+ * next as its closing one, where `source` (the text the quotes stand in as written) holds no line break between them.
31
+ * A line break inside resets: the quote before it opened nothing, and the next quote opens (rulings XXXIX, XLVI). Each
32
+ * pair is the indices of its two quotes. */
33
+ function pairQuotes(source, quotes) {
34
+ const pairs = [];
35
+ let open = -1;
36
+ // The first line break at or after the open quote, looked for once and again only after an open quote passes it
37
+ // (ruling LXIII): the quotes rise, so the search is linear in the text, never once per pair.
38
+ let newline = -1;
39
+ for (let i = 0; i < quotes.length; i++) {
40
+ if (open < 0) {
41
+ open = i;
42
+ continue;
43
+ }
44
+ if (newline < quotes[open]) {
45
+ const at = source.indexOf("\n", quotes[open]);
46
+ newline = at < 0 ? Number.POSITIVE_INFINITY : at;
47
+ }
48
+ if (newline < quotes[i]) {
49
+ open = i;
50
+ continue;
51
+ }
52
+ pairs.push([open, i]);
53
+ open = -1;
54
+ }
55
+ return pairs;
56
+ }
57
+ /** `text`'s line bounds. Inside a string (one of `strings`, sorted and disjoint per list: the strings the view was
58
+ * decoded from, and its own), a line starts after the string's opening quote and ends at its closing quote, or at a
59
+ * line break in between. A position outside every string is bounded by line breaks alone (ruling XLVI): a value that
60
+ * starts outside every string never ends at a string's start (`os.environ["X"]`). */
61
+ export function lineBounds(text, ...lists) {
62
+ const indexed = lists.map((spans) => ({ spans, opens: spans.map(([open]) => open) }));
63
+ // Each list's string holding `at` (after its opening quote, up to and with its closing one).
64
+ const holding = (at) => indexed.flatMap(({ spans, opens }) => {
65
+ const i = placeBefore(opens, at);
66
+ return i >= 0 && spans[i][1] >= at ? [spans[i]] : [];
67
+ });
68
+ // The text's line breaks, found once on first ask and searched by halves (ruling LXIX): a scan from `at` to the
69
+ // nearest break is a scan to the text's start or end on one long line, once per match, quadratic in the line.
70
+ let breaks;
71
+ const lineBreaks = () => {
72
+ if (breaks === undefined) {
73
+ breaks = [];
74
+ for (let at = text.indexOf("\n"); at >= 0; at = text.indexOf("\n", at + 1))
75
+ breaks.push(at);
76
+ }
77
+ return breaks;
78
+ };
79
+ return {
80
+ start: (at) => {
81
+ const all = lineBreaks();
82
+ const before = placeBefore(all, at);
83
+ return Math.max(before >= 0 ? all[before] + 1 : 0, ...holding(at).map(([open]) => open + 1));
84
+ },
85
+ end: (at) => {
86
+ const all = lineBreaks();
87
+ const next = placeBefore(all, at) + 1;
88
+ return Math.min(next < all.length ? all[next] : text.length, ...holding(at).map(([, close]) => close));
89
+ },
90
+ };
91
+ }
92
+ const linesOfContext = (text, ctx) => ctx?.lines ?? lineBounds(text);
93
+ const rule = (id, kind, find, extra = {}) => Object.freeze({ id, kind, restorable: RESTORABLE[kind], find, ...extra });
94
+ // ---------- the views (ruling A): the raw text and each JSON decoding of it, up to three, each mapped to the input
95
+ /** A JSON string's escape: \n \t \r \b \f \" \\ \/ or \uXXXX. Read left to right, so `\\n` is an escaped backslash
96
+ * and a letter. */
97
+ const ESCAPE = /\\(?:(["\\/bfnrt])|u([0-9A-Fa-f]{4}))/g;
98
+ const CONTROLS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
99
+ /** A Windows path from its drive, written as typed (one backslash a separator, never `C:\\`: that is a path a JSON
100
+ * string holds, its backslashes escapes the next view decodes), through every character a path holds. */
101
+ const DRIVE_PATH = /(?<![A-Za-z0-9])[A-Za-z]:\\(?!\\)[^\s"'\x60<>|]{0,4096}/g;
102
+ const DECODED = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
103
+ /** `text` decoded once as a JSON string's body: each escape read as the character it stands for (no exception: a
104
+ * backslash in a Windows path is a JSON escape here like any other, and the raw view reads the path as written). An
105
+ * escape JSON does not have (`\U`, `\d`) is left as written. `escapes` are the decoded escapes' spans in `text`; `at`
106
+ * maps an offset in the decoded text back to `text`'s, an offset at an escape's character to that escape's start. */
107
+ function decodeOnce(text) {
108
+ const escapes = [];
109
+ if (!text.includes("\\"))
110
+ return { out: text, escapes, at: (offset) => offset, delimiters: [] };
111
+ const parts = [];
112
+ const viewAt = [];
113
+ let from = 0;
114
+ let length = 0;
115
+ for (const m of text.matchAll(ESCAPE)) {
116
+ parts.push(text.slice(from, m.index));
117
+ length += m.index - from;
118
+ viewAt.push(length);
119
+ escapes.push([m.index, m.index + m[0].length]);
120
+ parts.push(m[1] !== undefined ? DECODED[m[1]] : String.fromCharCode(Number.parseInt(m[2], 16)));
121
+ length += 1;
122
+ from = m.index + m[0].length;
123
+ }
124
+ parts.push(text.slice(from));
125
+ const out = parts.join("");
126
+ // The quotes `text` holds as written (no escape's): its JSON strings' delimiters, structure to the decoded text.
127
+ const delimiters = [];
128
+ for (let at = out.indexOf('"'), escape = 0; at >= 0; at = out.indexOf('"', at + 1)) {
129
+ while (escape < viewAt.length && viewAt[escape] < at)
130
+ escape++;
131
+ if (viewAt[escape] !== at)
132
+ delimiters.push(at);
133
+ }
134
+ const at = (offset) => {
135
+ // The last escape read at or before `offset`.
136
+ let low = 0;
137
+ let high = viewAt.length - 1;
138
+ let found = -1;
139
+ while (low <= high) {
140
+ const mid = (low + high) >> 1;
141
+ if (viewAt[mid] <= offset)
142
+ (found = mid), (low = mid + 1);
143
+ else
144
+ high = mid - 1;
145
+ }
146
+ if (found < 0)
147
+ return offset;
148
+ if (viewAt[found] === offset)
149
+ return escapes[found][0];
150
+ return escapes[found][1] + (offset - viewAt[found] - 1);
151
+ };
152
+ return { out, escapes, at, delimiters };
153
+ }
154
+ /** `text` as the rules read it: each of `delimiters` blanked (the quotes the text it was decoded from held as written:
155
+ * that text's JSON strings' delimiters, which would otherwise close a quoted value that was never one), each escape in
156
+ * it blanked (a blank for each of its characters, so offsets hold), but one
157
+ * that stands whole inside a Windows path (`C:\Users\nina`: there a backslash is the path's separator, read as
158
+ * written: the next view decodes it), and each control character a blank. So no value starts on an escape's letter
159
+ * (`\tgit@...` reads a blank and `git@...`) and none runs through one. */
160
+ function blanked(text, escapes, delimiters = []) {
161
+ let plain = text.replace(CONTROLS, " ");
162
+ if (delimiters.length) {
163
+ const chars = plain.split("");
164
+ for (const at of delimiters)
165
+ chars[at] = " ";
166
+ plain = chars.join("");
167
+ }
168
+ if (!escapes.length)
169
+ return { text: plain, escapes: [] };
170
+ const drives = [...text.matchAll(DRIVE_PATH)].map((m) => [m.index, m.index + m[0].length]);
171
+ const parts = [];
172
+ const cut = [];
173
+ let from = 0;
174
+ let drive = 0;
175
+ for (const [start, end] of escapes) {
176
+ while (drive < drives.length && drives[drive][1] < end)
177
+ drive++;
178
+ if (drive < drives.length && drives[drive][0] < start)
179
+ continue;
180
+ parts.push(plain.slice(from, start), " ".repeat(end - start));
181
+ cut.push([start, end]);
182
+ from = end;
183
+ }
184
+ parts.push(plain.slice(from));
185
+ return { text: parts.join(""), escapes: cut };
186
+ }
187
+ /** The most times a text is decoded: a JSON string inside a JSON string inside one (a tool's output kept in a record). */
188
+ export const VIEW_DEPTH = 3;
189
+ /** The quotes `source` holds that no escape writes (no odd run of backslashes before one): its JSON strings' bounds
190
+ * as it stands (ruling XXXIX: a view with no escape left has strings too). */
191
+ function quotesOf(source) {
192
+ const out = [];
193
+ for (let at = source.indexOf('"'); at >= 0; at = source.indexOf('"', at + 1)) {
194
+ let run = 0;
195
+ while (at - run - 1 >= 0 && source.charCodeAt(at - run - 1) === 92)
196
+ run++;
197
+ if (run % 2 === 0)
198
+ out.push(at);
199
+ }
200
+ return out;
201
+ }
202
+ /** `text`'s views: the raw text, then each JSON decoding of it up to VIEW_DEPTH times, while a decoding changes it. */
203
+ export function viewsOf(text) {
204
+ const views = [];
205
+ let source = text;
206
+ let at = (offset) => offset;
207
+ let delimiters = [];
208
+ let decodedStrings = [];
209
+ for (let depth = 0; depth <= VIEW_DEPTH; depth++) {
210
+ const next = decodeOnce(source);
211
+ const read = blanked(source, next.escapes, delimiters);
212
+ const inherited = new Set(delimiters);
213
+ const quotes = quotesOf(source).filter((quote) => !inherited.has(quote));
214
+ const strings = pairQuotes(source, quotes).map(([open, close]) => [quotes[open], quotes[close]]);
215
+ views.push({ text: read.text, source, depth, escapes: read.escapes, at, delimiters, decodedStrings, strings });
216
+ if (!next.escapes.length || depth === VIEW_DEPTH)
217
+ break;
218
+ const outer = at;
219
+ at = (offset) => outer(next.at(offset));
220
+ source = next.out;
221
+ delimiters = next.delimiters;
222
+ // Each level's strings, to the decoded text's offsets: a quote as written stands in both (next.delimiters).
223
+ const toNext = new Map(next.delimiters.map((quote) => [next.at(quote), quote]));
224
+ decodedStrings = [...decodedStrings, strings].map((list) => list.flatMap(([open, close]) => {
225
+ const [from, to] = [toNext.get(open), toNext.get(close)];
226
+ return from === undefined || to === undefined ? [] : [[from, to]];
227
+ }));
228
+ }
229
+ return views;
230
+ }
231
+ /** Each view's escape starts, in order (its escapes are disjoint, in order), for inputSpan's search by halves. */
232
+ const escapeStarts = new WeakMap();
233
+ /** A view's span widened to hold each escape it starts or ends inside, mapped to the input: a cut never splits an
234
+ * escape, so a cut JSON string stays one. The escape holding each end is found by halves (ruling LXXXIII): a walk
235
+ * from the first escape is one per hit, quadratic in a JSON text holding many hits. */
236
+ export function inputSpan(view, start, end) {
237
+ let starts = escapeStarts.get(view);
238
+ if (starts === undefined) {
239
+ starts = view.escapes.map(([a]) => a);
240
+ escapeStarts.set(view, starts);
241
+ }
242
+ let from = start;
243
+ let to = end;
244
+ const holdingFrom = view.escapes[placeBefore(starts, from)];
245
+ if (holdingFrom !== undefined && from < holdingFrom[1])
246
+ from = holdingFrom[0];
247
+ const holdingTo = view.escapes[placeBefore(starts, to)];
248
+ if (holdingTo !== undefined && to < holdingTo[1])
249
+ to = holdingTo[1];
250
+ return [view.at(from), view.at(to)];
251
+ }
252
+ /** `text` decoded `times` times (a cut's text as the view that found it reads it: its shape and its line count). */
253
+ export function decodedTimes(text, times) {
254
+ let out = text;
255
+ for (let i = 0; i < times; i++)
256
+ out = decodeOnce(out).out;
257
+ return out;
258
+ }
259
+ // ---------- shapes
260
+ /** Public prefixes a format's shape may name: each a fixed literal of a published format, never read from the value. */
261
+ const PREFIXES = ["pypi-AgEIcHlwaS5vcmc", "github_pat_", "-----BEGIN", "AGE-SECRET-KEY-", "dop_v1_", "doo_v1_", "dor_v1_", "sk-ant-", "sk-proj-", "glpat-", "whsec_", "ar_key_", "xoxb-", "xoxp-", "xoxa-", "xoxo-", "xoxs-", "xoxr-", "xoxe-", "xapp-", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "npm_", "hf_", "sk-", "SG.", "AKIA", "ASIA", "AIza", "eyJ"];
262
+ const NOT_DIGIT = /[^0-9]/;
263
+ const NOT_HEX = /[^0-9a-f]/i;
264
+ const NOT_ALNUM = /[^A-Za-z0-9]/;
265
+ const NOT_BASE64 = /[^A-Za-z0-9+/_=-]/;
266
+ const classOf = (value) => !NOT_DIGIT.test(value) ? "digits" : !NOT_HEX.test(value) ? "hex" : !NOT_ALNUM.test(value) ? "alnum" : !NOT_BASE64.test(value) ? "base64" : "text";
267
+ /** A cut's shape: a dump's line count, a personal rule's class, or a public prefix (else a character class), and the
268
+ * cut's length in characters. */
269
+ export function shapeOf(of, value) {
270
+ if (of.kind === "dump")
271
+ return `lines:${lineCount(value)}[${value.length}]`;
272
+ if (of.shapeClass)
273
+ return `${of.shapeClass}[${value.length}]`;
274
+ const prefix = PREFIXES.find((each) => value.startsWith(each) && value.length > each.length);
275
+ return prefix ? `${prefix}…[${value.length}]` : `${classOf(value)}[${value.length}]`;
276
+ }
277
+ export const lineCount = (value) => value.split("\n").length;
278
+ // ---------- placeholders (ruling D): a marker for a value, never one, by its whole shape
279
+ /** A value's text in a typed command: inside escaped double quotes (a JSON string's), double or single quotes, or bare
280
+ * to the next blank, quote or shell operator. Four groups, one defined; the cut is the group alone, the quotes kept.
281
+ * Each group reads at most 1024 characters: a quoted one is taken whole (a lookahead's capture, never backtracked
282
+ * into) and then closes, or stands at the bound with the value going on, and valueHit reads the rest to the value's
283
+ * end (ruling LXXXVIII). */
284
+ const VALUE = String.raw `(?:\\"(?=(?<vj>(?:[^"\\\n]|\\[^"\n]){1,1024}))\k<vj>(?:\\"|(?=[^"\\\n]|\\[^"\n]))|"(?=(?<vd>[^"\n]{1,1024}))\k<vd>(?:"|(?=[^"\n]))|'(?=(?<vs>[^'\n]{1,1024}))\k<vs>(?:'|(?=[^'\n]))|([^\s'"\x60;&|()<>]{1,1024}))`;
285
+ /** The whole-value shapes of a marker: a variable ($VAR, ${VAR}, ${{ expr }}, %VAR%), a <slot>, a {{template}}, YOUR_...
286
+ * (your-..., your_...), the upper-case markers REPLACE_ME, CHANGEME, CHANGE_ME and TODO, x-runs (xxx, XXXX-XXXX), ***
287
+ * and a cut already made ([redacted...]). The markers are upper case only: lower-case `changeme` is a weak password
288
+ * many images ship as their live default, and a literal test password beside a label is cut (GRAY.md item 4,
289
+ * amendment 2). */
290
+ const PLACEHOLDER = new RegExp(`^(?:${[
291
+ String.raw `\$[A-Za-z_][A-Za-z0-9_]{0,127}`,
292
+ String.raw `\$\{[^}\n]{1,256}\}{1,2}`,
293
+ String.raw `\$\{\{[^\n]{0,256}`,
294
+ String.raw `%[A-Za-z_][A-Za-z0-9_]{0,127}%`,
295
+ String.raw `<[^<>\n]{1,256}>`,
296
+ String.raw `\{\{[^{}\n]{1,256}\}\}`,
297
+ String.raw `(?:YOUR|[Yy]our)[-_][A-Za-z0-9_-]{1,128}`,
298
+ String.raw `REPLACE_ME|CHANGEME|CHANGE_ME|TODO`,
299
+ String.raw `[xX]{3,64}(?:-[xX]{3,64}){0,16}`,
300
+ String.raw `\*{3,64}`,
301
+ String.raw `\[(?:redacted|REDACTED)[^\]\n]{0,128}\]`,
302
+ ].join("|")})$`);
303
+ /** A value cut short for display: a trailing ... or …, stripped before the rest is judged. */
304
+ const ELLIPSIS = /(?:\.\.\.|…)$/;
305
+ /** The fewest characters a value shown cut short must keep, a public prefix aside, to still be one: `abc...`,
306
+ * `sk-proj-...` and `<token>…` are markers; a whole value with an ellipsis after it is still that value. */
307
+ const SHOWN_MIN = 8;
308
+ /** A type's name where a value would stand: an annotation (`token: string`, `password: str`, `api_key: SecretStr`), a
309
+ * literal no secret is (null, None, true), or a generic (`Optional[str]`, `Array<string>`). */
310
+ const TYPE_WORD = /^(?:string|String|str|int|Int|integer|bool|boolean|Boolean|number|Number|float|double|bytes|any|unknown|object|Object|void|null|NULL|nil|None|undefined|true|false|True|False|required|optional)$/;
311
+ const GENERIC = /^[A-Za-z_][A-Za-z0-9_.]{0,63}(?:\[[^\]\n]{1,128}\]|<[^>\n]{1,128}>)$/;
312
+ const PASCAL_TYPE = /^(?:[A-Z][a-z]{1,32}){2,8}$/;
313
+ /** An all-capitals metavar a help text writes where its flag's value goes (`--token TOKEN`, `--api-key KEY`). */
314
+ const METAVAR = /^[A-Z][A-Z0-9_]{0,63}$/;
315
+ const NAME_PARTS = /[-_]{1,8}/;
316
+ const LEADING_DASHES = /^-{1,2}/;
317
+ /** Code where a value would stand (only when bare, never quoted): a call or an index (`getAuthHeader()`,
318
+ * `os.environ[...]`), a member chain with no digit (`process.env.TOKEN`, `config.secret`), or an identifier in a
319
+ * code's casing with no digit (`authHeader`, `hf_token`, `GITHUB_TOKEN`). */
320
+ const CODE_CALL = /^[A-Za-z_$][\w$]{0,127}(?:\.[A-Za-z_$][\w$]{0,127}){0,16}[([]/;
321
+ const IDENT_CHAIN = /^[A-Za-z_$][\w$]{0,127}(?:\.[A-Za-z_$][\w$]{0,127}){0,16}$/;
322
+ const MEMBER_CHAIN = /^[A-Za-z_$][A-Za-z_$]{0,127}(?:\.[A-Za-z_$][A-Za-z_$]{0,127}){1,16}$/;
323
+ const CODE_CASE = /^[A-Za-z_$]{1,128}$/;
324
+ const CAMEL_OR_SNAKE = /[a-z][A-Z]|[A-Za-z]_[A-Za-z]/;
325
+ const CALL_AFTER = /^[ \t]{0,3}[([]/;
326
+ /** A reference to a value, never one (ruling II): a shell expansion opening it (`$(...)`, `${...}`, `$NAME`, a
327
+ * backtick; escaped too, `\$NAME`, ruling XXXVIII), a secret manager's address (`op://`, `vault:`, `${{ secrets.X }}`, an AWS Secrets Manager ARN, a GCP
328
+ * secret's resource name), a template's slot (`{self.password}`, `{password}`) standing whole, or a member chain rooted
329
+ * at the environment (`process.env.`, `import.meta.env.`, `os.environ[`/`.get(`, `ENV[`, `System.getenv(`, ruling
330
+ * XLVII), in every slot. */
331
+ const REFERENCE = /^(?:\\?\$[({A-Za-z_]|\x60|process\.env\.|import\.meta\.env\.|os\.environ(?:\[|\.get\()|ENV\[|System\.getenv\(|op:\/\/|vault:|arn:aws:secretsmanager:|projects\/[^/\s]{1,128}\/secrets\/|\{[^{}\n]{1,256}\}$)/;
332
+ /** A value elided for display anywhere in it (ruling II): a <slot>, a bullet, ***, a cut already made, or an ellipsis
333
+ * inside it (a trailing one is ELLIPSIS's: the rest is judged). */
334
+ const ELIDED = /<[^<>\n]{1,256}>|•|\*\*\*|\[redacted|…(?!$)/i;
335
+ /** Punctuation a value's end may carry from the sentence or the syntax around it, stripped before it is judged. */
336
+ const TRAILING_PUNCTUATION = /[,;:!?)\]}'"]{1,8}$/;
337
+ const SENTENCE_END = /\.$/;
338
+ /** A bare value opens with a letter, a digit or `_` (ruling II): `,`, `-`, `(` or `/` after a label is a list, a flag,
339
+ * a call or a path, never a password; a quoted value is a literal however it opens. In a slot code does not fill
340
+ * (ruling XII) a value opens with anything but a blank, a quote or `$` (a reference, read before). */
341
+ const BARE_START = /^[A-Za-z0-9_]/;
342
+ const LITERAL_START = /^[^\s'"$]/;
343
+ /** YAML's own nodes where a value would stand (ruling XII): a tag (`!Ref`, `!Sub`, `!vault`, `!!binary`: letters, no
344
+ * digit), an alias (`*db_pw`), an anchor (`&db_pw`), a block indicator (`|`, `>-`), `~`. */
345
+ const YAML_NODE = /^(?:!{1,2}[A-Za-z][A-Za-z_.:/-]{0,63}|[*&][A-Za-z0-9_.-]{1,64}|[|>][+-]?[1-9]?|~)$/;
346
+ /** The fewest characters a bare value holds (ruling II): `-p and`, `--api-key and kin` are prose. */
347
+ const BARE_MIN = 4;
348
+ const EDGE_BLANK = /^\s|\s$/;
349
+ /** Blank-edged quoted contents whose first or last blank-separated token is punctuation alone (no letter, digit or `_`):
350
+ * the quotes are one string's close and the next one's open, an operator between (`" + pw + "`, `" . $pw . "`,
351
+ * `", pw, "`, `" || pw || "`), no value's bound (ruling LVII). Read on the trimmed contents; an edge token that mixes
352
+ * punctuation with word characters (`" !Copper8 "`) is a value's. Bounded at 64 (ruling B). */
353
+ const EDGE_TOKEN_PUNCT = /^[^\w\s]{1,64}(?:\s|$)|\s[^\w\s]{1,64}$/;
354
+ /** The fewest characters quoted contents hold once trimmed (valueHit's least, ruling LVII). */
355
+ const INNER_MIN = 3;
356
+ /** A value that runs straight into an angle-bracket placeholder (`wk_live_<redacted>`) is a kept prefix, the rest
357
+ * elided; read in the 8 characters after the value. */
358
+ const ELIDED_AFTER = /^<[A-Za-z][\w -]{0,6}(?:>|$)/;
359
+ /** Whether a label rule's value is a marker for one, never one, by its whole shape (no guess at randomness). The engine
360
+ * (secret-cut.ts) drops every label rule's hit whose value this holds, so no label rule can skip it. */
361
+ /** A name or a value as XIX compares them: lower case, no separator (`SESSION_TOKEN` and "session-token" are one). */
362
+ const nameKey = (name) => name.toLowerCase().replace(NAME_KEY_OFF, "");
363
+ const NAME_KEY_OFF = /[-_. ]/g;
364
+ const IDENTIFIER = /^[A-Za-z_$][\w$]{0,127}$/;
365
+ /** A value that ends with, or is followed by, what ends an argument or an entry in code: `,`, `)`, `}`. */
366
+ const ENDS_ENTRY = /[,)}]$/;
367
+ const ENTRY_END_AFTER = /^[ \t]{0,3}[,)}]/;
368
+ /** A type's name in a YAML key's slot, which a Python annotation shares (ruling XVI): PascalCase with a type's suffix, or
369
+ * a subscript, a union, a default or a call after it. Any other PascalCase word there is a value. */
370
+ const TYPE_SUFFIX = /(?:Str|String|Bytes|Int|Float|Bool|Dict|List|Type|Field|Model|Settings|Config|Optional|Any|Token)$/;
371
+ const TYPE_AFTER = /^[ \t]{0,3}[[|=(]/;
372
+ const typeName = (whole, after) => PASCAL_TYPE.test(whole) && (TYPE_SUFFIX.test(whole) || TYPE_AFTER.test(after));
373
+ export function isPlaceholder(value, slot = {}) {
374
+ // Inside quotes the quotes are the bound (rulings LV, LVII): the inner value is judged without its edge blanks, and a
375
+ // cut takes the whole quoted contents. Only an unquoted value with an edge blank is no value.
376
+ if (slot.bare === false && EDGE_BLANK.test(value)) {
377
+ const inner = value.trim();
378
+ return inner.length < INNER_MIN || EDGE_TOKEN_PUNCT.test(inner) || isPlaceholder(inner, slot);
379
+ }
380
+ if (EDGE_BLANK.test(value))
381
+ return true;
382
+ if (REFERENCE.test(value) || ELIDED.test(value) || PLACEHOLDER.test(value))
383
+ return true;
384
+ const trimmed = value.replace(TRAILING_PUNCTUATION, "");
385
+ if (trimmed === "" || REFERENCE.test(trimmed))
386
+ return true;
387
+ if (ELLIPSIS.test(trimmed)) {
388
+ const rest = trimmed.replace(ELLIPSIS, "");
389
+ if (rest === "" || isPlaceholder(rest, { ...slot, after: "" }))
390
+ return true;
391
+ const prefix = PREFIXES.find((each) => rest.startsWith(each)) ?? "";
392
+ return rest.length - prefix.length < SHOWN_MIN;
393
+ }
394
+ const whole = trimmed.replace(SENTENCE_END, "");
395
+ if (whole === "" || PLACEHOLDER.test(whole) || TYPE_WORD.test(whole) || GENERIC.test(whole))
396
+ return true;
397
+ if (slot.name !== undefined && METAVAR.test(whole)) {
398
+ const parts = slot.name.replace(LEADING_DASHES, "").toUpperCase().split(NAME_PARTS);
399
+ if (parts.includes(whole) || parts.join("_") === whole)
400
+ return true;
401
+ }
402
+ if (ELIDED_AFTER.test(slot.after ?? ""))
403
+ return true;
404
+ // In code a value equal to its own name is a name (an enum's member, a constant naming its key; ruling XIX).
405
+ if (slot.code !== false && slot.name !== undefined && nameKey(whole) !== "" && nameKey(whole) === nameKey(slot.name))
406
+ return true;
407
+ if (slot.bare === false)
408
+ return false;
409
+ // The code shapes are no value in code alone (ruling XII): a call's opening after the value makes any slot code's.
410
+ if (slot.code === false && !CALL_AFTER.test(slot.after ?? "")) {
411
+ return !LITERAL_START.test(whole) || whole.length < BARE_MIN || YAML_NODE.test(whole) || (slot.typed === true && typeName(whole, slot.after ?? ""));
412
+ }
413
+ // In code an unquoted identifier that ends an argument, an element or an object's entry is a variable (ruling XXI).
414
+ if (IDENTIFIER.test(whole) && (ENDS_ENTRY.test(value) || ENTRY_END_AFTER.test(slot.after ?? "")))
415
+ return true;
416
+ if (!BARE_START.test(whole) || whole.length < BARE_MIN)
417
+ return true;
418
+ if (PASCAL_TYPE.test(whole) || CODE_CALL.test(whole))
419
+ return true;
420
+ if (IDENT_CHAIN.test(whole) && CALL_AFTER.test(slot.after ?? ""))
421
+ return true;
422
+ return MEMBER_CHAIN.test(whole) || (CODE_CASE.test(whole) && CAMEL_OR_SNAKE.test(whole));
423
+ }
424
+ /** The end of the value VALUE's group `kind` (0 escaped-quoted, 1 double-, 2 single-quoted, 3 bare) stopped at `end`
425
+ * (ruling LXXXVIII, Greptile's P1 on 55b0239695: a 1500-character token was cut to its first 1024, the rest shown). A
426
+ * value that ended there ends there; one VALUE's bound stopped runs on to its closing quote, its line's end or, bare,
427
+ * to the next blank, quote or shell operator. The run last read is kept, so a value that stops inside it is answered
428
+ * without reading it again: linear in the text. */
429
+ let valueRun;
430
+ const BARE_STOP = /[\s'"\x60;&|()<>]/;
431
+ function valueEnd(text, kind, end) {
432
+ const c = text.charAt(end);
433
+ if (c === "" || c === "\n")
434
+ return end;
435
+ if (kind === 0 ? c === "\\" && text.charAt(end + 1) === '"' : kind === 1 ? c === '"' : kind === 2 ? c === "'" : BARE_STOP.test(c))
436
+ return end;
437
+ const run = valueRun;
438
+ if (run !== undefined && run.kind === kind && run.from <= end && end <= run.to && run.text === text)
439
+ return run.to;
440
+ let at = end;
441
+ if (kind === 0) {
442
+ while (at < text.length) {
443
+ const d = text.charAt(at);
444
+ if (d === '"' || d === "\n")
445
+ break;
446
+ if (d === "\\") {
447
+ const e = text.charAt(at + 1);
448
+ if (e === "" || e === '"' || e === "\n")
449
+ break;
450
+ at += 2;
451
+ }
452
+ else
453
+ at++;
454
+ }
455
+ }
456
+ else if (kind === 3) {
457
+ while (at < text.length && !BARE_STOP.test(text.charAt(at)))
458
+ at++;
459
+ }
460
+ else {
461
+ const quote = kind === 1 ? '"' : "'";
462
+ while (at < text.length && text.charAt(at) !== quote && text.charAt(at) !== "\n")
463
+ at++;
464
+ }
465
+ valueRun = { text, kind, from: end, to: at };
466
+ return at;
467
+ }
468
+ /** The defined one of VALUE's four groups at `first`, as a hit, when at least `min` characters long, to the value's
469
+ * end (valueEnd). */
470
+ function valueHit(m, first, min = 3, name) {
471
+ for (let group = first; group < first + 4; group++) {
472
+ const value = m[group];
473
+ if (value === undefined)
474
+ continue;
475
+ if (value.length < min)
476
+ return undefined;
477
+ const [start, matched] = m.indices[group];
478
+ const end = valueEnd(m.input, group - first, matched);
479
+ return name === undefined ? { start, end } : { start, end, name };
480
+ }
481
+ return undefined;
482
+ }
483
+ /** Each match of `pattern` (flags g and d) in `text`, mapped to a hit or none. A match mapped to none is read again
484
+ * from where `resume` says, when it says (a rejected `content : password: x` leaves `password: x`). */
485
+ function each(text, pattern, hit, resume) {
486
+ const re = new RegExp(pattern.source, pattern.flags.includes("d") ? pattern.flags : `${pattern.flags}d`);
487
+ const out = [];
488
+ for (let m = re.exec(text); m; m = re.exec(text)) {
489
+ const found = hit(m);
490
+ if (found)
491
+ out.push(found);
492
+ else {
493
+ const at = resume?.(m);
494
+ if (at !== undefined)
495
+ re.lastIndex = Math.max(m.index + 1, at);
496
+ }
497
+ if (m[0] === "")
498
+ re.lastIndex = Math.max(re.lastIndex, m.index + 1);
499
+ }
500
+ return out;
501
+ }
502
+ /** Every place `form` stands in `text`, overlapping places included. */
503
+ function placesOf(text, form) {
504
+ const out = [];
505
+ if (!form)
506
+ return out;
507
+ for (let at = text.indexOf(form); at >= 0; at = text.indexOf(form, at + 1))
508
+ out.push({ start: at, end: at + form.length });
509
+ return out;
510
+ }
511
+ /** How far a command is read past its name: SHELL_LINE_MAX, and CURL_MAX for curl's continuation lines. */
512
+ const SHELL_LINE_MAX = 1024;
513
+ const CURL_MAX = 4096;
514
+ /** How far a substitution's closer is looked for: one that does not close within it ends the command where it opens. */
515
+ const SUBSTITUTION_MAX = 256;
516
+ /** Where a substitution opened at `at` ends, past its closer, before its line's end, `limit` and SUBSTITUTION_MAX, or
517
+ * -1: a backtick's at the next one, a `$(`'s at its matching `)`, parentheses counted and a quoted part read whole. */
518
+ function substitutionEnd(text, at, limit) {
519
+ const tick = text.charAt(at) === "\x60";
520
+ const stop = Math.min(limit, at + SUBSTITUTION_MAX);
521
+ let depth = 0;
522
+ for (let i = at + 1; i < stop; i++) {
523
+ const c = text.charAt(i);
524
+ if (c === "\n")
525
+ return -1;
526
+ if (c === "\\")
527
+ i++;
528
+ else if (tick) {
529
+ if (c === "\x60")
530
+ return i + 1;
531
+ }
532
+ else if (c === "(")
533
+ depth++;
534
+ else if (c === ")") {
535
+ if (--depth === 0)
536
+ return i + 1;
537
+ }
538
+ else if (c === "'" || c === '"') {
539
+ let close = i + 1;
540
+ while (close < stop && text.charAt(close) !== c && text.charAt(close) !== "\n")
541
+ close += c === '"' && text.charAt(close) === "\\" ? 2 : 1;
542
+ if (close >= stop || text.charAt(close) !== c)
543
+ return -1;
544
+ i = close;
545
+ }
546
+ }
547
+ return -1;
548
+ }
549
+ /** Where the quoted part opened at `at` closes, before its line's end and `limit`, or -1 (a quote left open is a
550
+ * character). A double-quoted part's backslash escapes the next character; for curl its substitutions are read whole
551
+ * and added to `subs`, and one that never closes leaves the quote open. A quote inside a span an earlier search of its
552
+ * kind read without a closer reads on from where that one stopped (the same characters, paired the same), so each
553
+ * character is searched once per kind: linear. */
554
+ function quoteEnd(text, at, limit, curl, misses, subs) {
555
+ const quote = text.charAt(at);
556
+ const found = [];
557
+ let i = at + 1;
558
+ const miss = misses[quote];
559
+ if (miss && miss.from < at && at < miss.to) {
560
+ if (miss.final || miss.to >= limit)
561
+ return -1;
562
+ i = miss.to;
563
+ for (const sub of miss.subs)
564
+ if (sub[0] > at)
565
+ found.push(sub);
566
+ }
567
+ let final = false;
568
+ for (; i < limit; i++) {
569
+ const c = text.charAt(i);
570
+ if (c === quote) {
571
+ subs.push(...found);
572
+ return i;
573
+ }
574
+ if (c === "\n") {
575
+ final = true;
576
+ break;
577
+ }
578
+ if (quote !== '"')
579
+ continue;
580
+ if (curl && (c === "\x60" || (c === "$" && text.charAt(i + 1) === "("))) {
581
+ const end = substitutionEnd(text, i, limit);
582
+ if (end < 0) {
583
+ // The command's own read reaches this `$(` next and ends there: it asks misses["$"], not substitutionEnd again.
584
+ misses.$ = { from: i, to: i, final: true, subs: [] };
585
+ final = true;
586
+ break;
587
+ }
588
+ found.push([i, end]);
589
+ i = end - 1;
590
+ }
591
+ else if (c === "\\" && text.charAt(i + 1) !== "\n")
592
+ i++;
593
+ }
594
+ misses[quote] = { from: at, to: i, final, subs: found };
595
+ return -1;
596
+ }
597
+ /** Where a shell command whose name ends at `from` ends, and the substitutions it holds (Greptile P1 on 683391d4fd:
598
+ * `redis-cli -a 'Copper&lumen9'` stopped at its quoted `&`, and its password stayed): its line's end, or a shell
599
+ * operator outside quotes (`;`, `|`, `&`). A quoted part is read whole to its closing quote on its line. curl (ruling
600
+ * XXIV) runs on over a backslash's line break and a lone `&`, and ends at `&&`; a substitution (`$(…)`, a backtick
601
+ * pair), bare or in double quotes, is read whole and the command read on past it (Greptile's P2 and P1 on 4cacd50606
602
+ * and 3e8ed77da8: its contents are no part of curl's arguments, and a `-u` after it is), and one that never closes
603
+ * ends the command where it opens. At most SHELL_LINE_MAX characters (CURL_MAX) are read. `misses` carries failed
604
+ * quote searches from one command to the next (quoteEnd), and a substitution's search is bounded and ends its command
605
+ * when it fails: linear in the text. */
606
+ function commandEnd(text, from, curl, misses) {
607
+ const limit = Math.min(text.length, from + (curl ? CURL_MAX : SHELL_LINE_MAX));
608
+ const subs = [];
609
+ let at = from;
610
+ while (at < limit) {
611
+ const c = text.charAt(at);
612
+ if (c === "\n" || c === ";" || c === "|")
613
+ return { end: at, subs };
614
+ if (c === "&") {
615
+ if (!curl || text.charAt(at + 1) === "&")
616
+ return { end: at, subs };
617
+ }
618
+ else if (curl && (c === "\x60" || (c === "$" && text.charAt(at + 1) === "("))) {
619
+ const end = misses.$?.from === at ? -1 : substitutionEnd(text, at, limit);
620
+ if (end < 0)
621
+ return { end: at, subs };
622
+ subs.push([at, end]);
623
+ at = end;
624
+ continue;
625
+ }
626
+ else if (curl && c === "\\") {
627
+ const e = text.charAt(at + 1);
628
+ at += e === "\r" && text.charAt(at + 2) === "\n" ? 3 : e === "" ? 1 : 2;
629
+ continue;
630
+ }
631
+ else if (c === "'" || c === '"') {
632
+ const close = quoteEnd(text, at, limit, curl, misses, subs);
633
+ if (close >= 0)
634
+ at = close;
635
+ }
636
+ at++;
637
+ }
638
+ return { end: Math.min(at, limit), subs };
639
+ }
640
+ /** How deep a command inside a substitution of the same command is read on its own (`curl -H "$(curl -u a:pw …)"`). */
641
+ const SUBSTITUTION_DEPTH = 4;
642
+ /** The hits `pattern` finds inside each command `command` names (read whole first, to commandEnd), mapped to the text.
643
+ * A hit starting inside one of the command's substitutions is not the command's; the substitution's contents are read
644
+ * as a text of their own. The next command is looked for past this one's end. */
645
+ function inside(text, command, pattern, hit, curl = false, depth = 0) {
646
+ const out = [];
647
+ const re = new RegExp(command.source, command.flags);
648
+ const misses = {};
649
+ for (let m = re.exec(text); m; m = re.exec(text)) {
650
+ const { end, subs } = commandEnd(text, m.index + m[0].length, curl, misses);
651
+ for (const found of each(text.slice(m.index, end), pattern, hit)) {
652
+ const start = m.index + found.start;
653
+ if (!subs.some(([from, to]) => from <= start && start < to))
654
+ out.push({ ...found, start, end: m.index + found.end });
655
+ }
656
+ if (depth < SUBSTITUTION_DEPTH) {
657
+ for (const [from, to] of subs) {
658
+ const body = from + (text.charAt(from) === "$" ? 2 : 1);
659
+ for (const found of inside(text.slice(body, to - 1), command, pattern, hit, curl, depth + 1))
660
+ out.push({ ...found, start: body + found.start, end: body + found.end });
661
+ }
662
+ }
663
+ re.lastIndex = Math.max(end, m.index + 1);
664
+ }
665
+ return out;
666
+ }
667
+ // ---------- format: redact/match.ts SECRET_SHAPES, the PEM block whole, secretlint
668
+ const SHAPE_IDS = new Map([
669
+ ["AWS access key id", "aws-access-key"],
670
+ ["Google API key", "google-api-key"],
671
+ ["private key block", "private-key-block"],
672
+ ["GitHub token", "github-token"],
673
+ ["sk- key", "sk-key"],
674
+ ["AgentRun API key", "agentrun-api-key"],
675
+ ["Slack token", "slack-token"],
676
+ ["JWT", "jwt"],
677
+ ["webhook signing secret", "webhook-secret"],
678
+ ["URL with a password", "url-password"],
679
+ ["bearer token", "bearer-token"],
680
+ ["URL parameter named like a credential", "url-credential"],
681
+ ]);
682
+ /** The shapes found by what stands beside the value, not by the value itself: a URL's `user:` before its `@`, a
683
+ * parameter's name, the `Bearer` scheme. Every other shape names its own format (a prefix, a checksum). */
684
+ const SHAPE_LABELS = new Set(["url-password", "url-credential", "bearer-token"]);
685
+ const SLUG_OFF = /[^a-z0-9]{1,64}/g;
686
+ const SLUG_ENDS = /^-|-$/g;
687
+ const slug = (name) => name.toLowerCase().replace(SLUG_OFF, "-").replace(SLUG_ENDS, "");
688
+ /** A PEM block's end, and the characters a block holds between its header and its end (base64, its own headers, line
689
+ * breaks as written or as a JSON string escapes them). */
690
+ const PEM_END = /-----END[ A-Z0-9]{0,40}PRIVATE KEY[ A-Z0-9]{0,40}-----/g;
691
+ /** A BEGIN line read where a private-key span starts, as SECRET_SHAPES' header (at most 64 characters each side of
692
+ * "PRIVATE KEY"). pemBlocks takes a header's end from this, not from the span: a shape may span the whole block. */
693
+ const PEM_BEGIN = /-----BEGIN[ A-Z0-9]{0,64}PRIVATE KEY[ A-Z0-9]{0,64}-----/y;
694
+ const PEM_OFF = /[^A-Za-z0-9+/=:,. \t\r\n\\-]/g;
695
+ const PEM_GAP = 16384;
696
+ /** The fewest base64 characters a block's body holds to be a key (ruling V): a BEGIN line alone, or one a few
697
+ * characters on (a header in code, a string repeated), is none. */
698
+ const PEM_BODY_MIN = 64;
699
+ const BASE64_CHARS = /[A-Za-z0-9+/=]/g;
700
+ /** A block's base64 run when no end is found (a key cut short): base64 words of 16 characters or more (or a padded
701
+ * last one), blanks or escaped line breaks between, so it stops at the next header and before a line of prose. */
702
+ const PEM_TAIL = /(?:(?:[ \t\r\n]|\\[nr]){1,16}(?:[A-Za-z0-9+/]{16,4096}={0,2}|[A-Za-z0-9+/]{1,15}={1,2})){0,1024}/y;
703
+ /** `run` without its trailing blanks and escaped line breaks (`\n`, `\r` as a JSON string writes them). */
704
+ function trimmedTail(run) {
705
+ let end = run.length;
706
+ for (;;) {
707
+ if (end > 0 && " \t\r\n".includes(run.charAt(end - 1)))
708
+ end--;
709
+ else if (end > 1 && run.charAt(end - 2) === "\\" && "nr".includes(run.charAt(end - 1)))
710
+ end -= 2;
711
+ else
712
+ return run.slice(0, end);
713
+ }
714
+ }
715
+ /** The private-key spans SECRET_SHAPES finds, each read from its BEGIN line's end to its block's end: the next END line,
716
+ * when only a block's characters stand between; else the base64 run after it. A span is its header alone or its whole
717
+ * block (either shape of redact/match.ts), so the header's end is read at the span's start; with no BEGIN line there
718
+ * this rule reads, the span's end stands. A header inside a block already cut is skipped, so a text of repeated
719
+ * headers is read once. Exported for its test. */
720
+ export function pemBlocks(text, spans, lines) {
721
+ const ends = [...text.matchAll(PEM_END)].map((m) => [m.index, m.index + m[0].length]);
722
+ const out = [];
723
+ let next = 0;
724
+ let last = -1;
725
+ // The first character no block holds at or after the header's end, kept while headers come before it: each found once.
726
+ let off = -1;
727
+ for (const [start, spanEnd] of spans) {
728
+ if (start < last)
729
+ continue;
730
+ PEM_BEGIN.lastIndex = start;
731
+ const headerEnd = start + (PEM_BEGIN.exec(text)?.[0].length ?? spanEnd - start);
732
+ while (next < ends.length && ends[next][0] < headerEnd)
733
+ next++;
734
+ const end = ends[next];
735
+ let stop;
736
+ if (end && end[0] - headerEnd <= PEM_GAP) {
737
+ if (off < headerEnd) {
738
+ PEM_OFF.lastIndex = headerEnd;
739
+ off = PEM_OFF.exec(text)?.index ?? text.length;
740
+ }
741
+ if (off >= end[0])
742
+ stop = end[1];
743
+ }
744
+ let body;
745
+ if (stop === undefined) {
746
+ PEM_TAIL.lastIndex = headerEnd;
747
+ body = trimmedTail(PEM_TAIL.exec(text)[0]);
748
+ stop = headerEnd + body.length;
749
+ }
750
+ else
751
+ body = text.slice(headerEnd, end[0]);
752
+ // Escaped line breaks (`\n` in a JSON string's raw text) are no body.
753
+ if ((body.replaceAll("\\n", "").replaceAll("\\r", "").match(BASE64_CHARS)?.length ?? 0) < PEM_BODY_MIN) {
754
+ // Else a block read line by line (ruling XXV): each line under the BEGIN line's own prefix (a Read tool's
755
+ // ` 2→`, `cat -n`, `grep -n`, a diff's `+`), one base64 line at least, to its END or its body's end.
756
+ const lineStop = pemLines(text, start, headerEnd, lines);
757
+ if (lineStop === undefined)
758
+ continue;
759
+ stop = lineStop;
760
+ }
761
+ out.push({ start, end: stop });
762
+ last = stop;
763
+ }
764
+ return out;
765
+ }
766
+ /** A body line of a key read line by line: base64 alone, at least 16 characters (a line cut short counts); its last
767
+ * line may be shorter, when its END line follows (ruling XXXIII). */
768
+ const PEM_BODY_LINE = /^[A-Za-z0-9+/=]{16,4096}$/;
769
+ const PEM_LAST_LINE = /^[A-Za-z0-9+/]{1,15}={0,2}$/;
770
+ const PEM_END_LINE = /^-----END[ A-Z0-9]{0,40}PRIVATE KEY[ A-Z0-9]{0,40}-----/;
771
+ /** A line lead's tokens: a run of digits (any line number), a run of blanks (a number's padding narrows as it grows),
772
+ * grep -n's `:` or `-` (a match line's or a context line's), else the character itself. */
773
+ const LEAD_TOKEN = /\d{1,7}|[ \t]{1,256}|[:-]|[^]/gu;
774
+ const DIGIT_START = /^\d/;
775
+ const leadToken = (token) => (DIGIT_START.test(token) ? "\uE000" : token.trim() === "" ? "\uE001" : token === ":" || token === "-" ? "\uE002" : token);
776
+ const leadTokens = (text) => [...text.matchAll(LEAD_TOKEN)].map(([token]) => leadToken(token));
777
+ const PEM_LEAD_MAX = 128;
778
+ /** The longest run of `prefix` (a BEGIN line's text before its header, as tokens) that each of `heads` (the first
779
+ * two lines after the BEGIN line, or the one there is) opens with, token for token (rulings XXVIII, XLI): a Read
780
+ * tool's ` 1→`, cat -n's, grep -n's `path:41:`, a diff's `-`, or nothing. Its end when the BEGIN line has more
781
+ * before its lead (a decoded string's field), its start when the BEGIN line has more after it
782
+ * (` 1→key = """-----BEGIN`), any run of it in general. Two lines must hold it, and it never ends on a token a
783
+ * body opens with (ruling XLI): a base64 character, or a digit run a base64 character follows. One line's chance
784
+ * match (a body opening with the prefix's last character, one in 64) would eat a body character. */
785
+ function sharedLead(prefix, heads) {
786
+ const tokens = heads.map((line) => leadTokens(line.slice(0, PEM_LEAD_MAX * 2)).slice(0, prefix.length));
787
+ let best = [];
788
+ for (let from = 0; from < prefix.length; from++) {
789
+ let k = 0;
790
+ while (from + k < prefix.length && tokens.every((head) => k < head.length && prefix[from + k] === head[k]))
791
+ k++;
792
+ while (k > best.length && !leadEnds(prefix.slice(from, from + k), heads))
793
+ k--;
794
+ if (k > best.length)
795
+ best = prefix.slice(from, from + k);
796
+ }
797
+ return best;
798
+ }
799
+ const BASE64_CHAR = /^[A-Za-z0-9+/=]$/;
800
+ /** Whether a lead may end where `lead` does on each of `heads` (ruling XLI): not on a base64 character, and on a
801
+ * digit run only when no base64 character follows it (a separator: `→`, a tab, `:`). */
802
+ function leadEnds(lead, heads) {
803
+ const last = lead[lead.length - 1];
804
+ if (last === "\uE000")
805
+ return heads.every((line) => !BASE64_CHAR.test(line.charAt(leadLength(lead, line) ?? 0)));
806
+ return !BASE64_CHAR.test(last);
807
+ }
808
+ /** The length of `lead` (tokens) at the start of `line`, or undefined when `line` does not open with it. */
809
+ function leadLength(lead, line) {
810
+ if (lead.length === 0)
811
+ return 0;
812
+ const re = new RegExp(LEAD_TOKEN.source, "gu");
813
+ for (const token of lead) {
814
+ const at = re.lastIndex;
815
+ const m = re.exec(line);
816
+ if (!m || m.index !== at)
817
+ return undefined;
818
+ if (leadToken(m[0]) !== token)
819
+ return undefined;
820
+ }
821
+ return re.lastIndex;
822
+ }
823
+ /** The end of a key read line by line from its BEGIN line at `start` (rulings XXV, XXVIII), or undefined when no base64
824
+ * line follows it. A line starts after a line break or where its decoded string starts (`lines`), so a JSON string's
825
+ * first line has its own lead; the lead is the longest run of the BEGIN line's prefix the next two lines open with, and
826
+ * every line after opens with it too. Then its PEM headers (Proc-Type, DEK-Info) and a blank after them, base64 lines,
827
+ * and its END line or the last base64 line (output cut short, `head`). */
828
+ function pemLines(text, start, headerEnd, lines) {
829
+ const prefix = leadTokens(text.slice(Math.max(lines.start(start), start - PEM_LEAD_MAX), start));
830
+ let eol = lines.end(headerEnd);
831
+ if (text.charAt(eol) !== "\n" || text.slice(headerEnd, eol).trim() !== "")
832
+ return undefined;
833
+ // The lead holds on the first two lines after the BEGIN line (a body line and the next, or its END), ruling XLI.
834
+ const firstEnd = lines.end(eol + 1);
835
+ const heads = [text.slice(eol + 1, firstEnd)];
836
+ if (text.charAt(firstEnd) === "\n")
837
+ heads.push(text.slice(firstEnd + 1, lines.end(firstEnd + 1)));
838
+ const lead = sharedLead(prefix, heads);
839
+ let stop;
840
+ let short;
841
+ let headed = false;
842
+ for (let at = eol + 1; at < text.length && at - headerEnd <= PEM_GAP; at = eol + 1) {
843
+ eol = lines.end(at);
844
+ const line = text.slice(at, eol);
845
+ const length = leadLength(lead, line);
846
+ if (length === undefined)
847
+ break;
848
+ const rest = line.slice(length).trimEnd();
849
+ const endLine = PEM_END_LINE.exec(rest);
850
+ if (endLine)
851
+ return stop === undefined ? undefined : at + length + endLine[0].length;
852
+ if (short !== undefined)
853
+ break;
854
+ if (PEM_BODY_LINE.test(rest))
855
+ stop = at + length + rest.length;
856
+ else if (stop !== undefined && PEM_LAST_LINE.test(rest))
857
+ short = at + length + rest.length;
858
+ else if (stop === undefined && PEM_HEADER_LINE.test(rest))
859
+ headed = true;
860
+ else if (!(stop === undefined && headed && rest === ""))
861
+ break;
862
+ if (text.charAt(eol) !== "\n")
863
+ break;
864
+ }
865
+ return stop;
866
+ }
867
+ /** A URL's password as a URL holds one (ruling XXIX), which SECRET_SHAPES' URL shape (a user first, no `/` in the password)
868
+ * misses: a scheme, `://`, a user (none: `redis://:pw@`), `:`, then the password to the last `@` before a blank or a
869
+ * quote that a host follows (a name or a bracketed IPv6 address, then a port, a path, a query or the URL's end). `/`,
870
+ * `+`, `=` and `@` are a password's characters; a user is never bracketed or braced (`http://[::1]:8080/a@b`, a
871
+ * template's `{user}:{password}@`). */
872
+ const URL_USERINFO = /(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\/[A-Za-z0-9._~%!$&*+,;=-]{0,256}:([^\s"'\x60]{1,1024})@(?:[A-Za-z0-9][A-Za-z0-9-]{0,62}(?:\.[A-Za-z0-9-]{1,63}){0,16}|\[[0-9A-Fa-f:.]{2,45}\])(?=[:/?#\s"'\x60),;>\]]|$)/dg;
873
+ /** A "password" that is a port (ruling XLII): `\d{1,5}` then a `/`, after a host-shaped "user" (`localhost`, an IPv4
874
+ * address, a dotted name; a bracketed IPv6 address is never read as a user). A Vite path (`localhost:5173/@vite`), an
875
+ * npm `pkg@ver` path, docker's `@sha256` and `ws://host:3000/x@v2` put an `@` after a host's port. Digits alone before
876
+ * the `@` (`root:1234@`), or after a user that names no host (`bob:12/25/1990@`, a dotless compose service's
877
+ * `api:8080/@vite` too), are a password. */
878
+ const PORT_PASSWORD = /^\d{1,5}\//;
879
+ const HOST_SHAPED = /^(?:localhost|[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){1,16})$/i;
880
+ /** The URL userinfos URL_USERINFO reads, ports none: each its password's span, and the userinfo it stands in, from after
881
+ * `://` to the `@` the match accepted. url-password cuts the passwords; the email rule reads no address inside a
882
+ * userinfo (ruling XLIII). */
883
+ function urlUserinfos(text) {
884
+ const out = [];
885
+ URL_USERINFO.lastIndex = 0;
886
+ for (let m = URL_USERINFO.exec(text); m; m = URL_USERINFO.exec(text)) {
887
+ const [from, to] = m.indices[1];
888
+ const userinfo = text.indexOf("://", m.index) + 3;
889
+ if (PORT_PASSWORD.test(m[1]) && HOST_SHAPED.test(text.slice(userinfo, from - 1)))
890
+ continue;
891
+ out.push({ password: [from, to], userinfo: [userinfo, to] });
892
+ }
893
+ return out;
894
+ }
895
+ /** A URL's password alone, of SECRET_SHAPES' `://user:password@` match: the user and the host stay. */
896
+ function urlPassword(text, [start, end]) {
897
+ // `scheme://[::1]:8443;x@host`: a bracketed IPv6 host, never a user (ruling XXXV).
898
+ if (text.charAt(start + 3) === "[")
899
+ return undefined;
900
+ const colon = text.indexOf(":", start + 3);
901
+ const from = colon + 1;
902
+ const to = end - 1;
903
+ return to > from ? { start: from, end: to, quoted: true } : undefined;
904
+ }
905
+ /** secretlint's messages that name a URL with its password (a connection string, basic auth in a URL): url-password
906
+ * cuts the password alone of each, the user and the host kept. A second reading only: URL_USERINFO is what reads a
907
+ * password holding `/`, `+` or `@` (secretlint's rules do not, ruling XXIX). Every other message is a format's
908
+ * (secretlint rule, ruling C). */
909
+ const LINT_URLS = new Set(["BasicAuth", "MongoDBConnection", "MySQLConnection", "PostgreSQLConnection"]);
910
+ /** A URL secretlint names, to its password: scheme, `://`, a user, `:`, the password (to the last `@`), the host. */
911
+ const LINT_URL = /^[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\/[^:@/\s]{0,256}:([^\s]{1,1024})@[^@\s]{1,512}$/d;
912
+ async function lintUrlPasswords(text, ctx) {
913
+ const out = [];
914
+ for (const find of await ctx.lint()) {
915
+ if (!LINT_URLS.has(find.id))
916
+ continue;
917
+ const m = LINT_URL.exec(find.value);
918
+ if (!m)
919
+ continue;
920
+ const [from, to] = m.indices[1];
921
+ for (const place of placesOf(text, find.value))
922
+ out.push({ start: place.start + from, end: place.start + to, name: "url", quoted: true });
923
+ }
924
+ return out;
925
+ }
926
+ /** The shapes that open with a public prefix, each with the characters of the run (a blob) its prefix could sit inside
927
+ * (ruling X). A prefix holding `-` or `_` (sk-, ghp_, github_pat_, xoxb-, whsec_) and a JWT can only sit inside a
928
+ * base64url run, so `/`, `+`, `.`, `:` and `=` stand outside one: a key in a URL's or a file's path is a key. AKIA and
929
+ * AIza sit inside standard base64 too: `+` is of the run, `/` is a path's separator (s3://bucket/AKIA...), and a run
930
+ * ends on `=`'s padding. */
931
+ const URL_SAFE_RUN = /[A-Za-z0-9_-]/;
932
+ const BASE64_RUN_BEFORE = /[A-Za-z0-9+_-]/;
933
+ const BASE64_RUN_AFTER = /[A-Za-z0-9+=_-]/;
934
+ const URL_SAFE = { before: URL_SAFE_RUN, after: URL_SAFE_RUN };
935
+ const BASE64 = { before: BASE64_RUN_BEFORE, after: BASE64_RUN_AFTER };
936
+ const RUNS = {
937
+ "aws-access-key": BASE64,
938
+ "google-api-key": BASE64,
939
+ "github-token": URL_SAFE,
940
+ "sk-key": URL_SAFE,
941
+ "slack-token": URL_SAFE,
942
+ "webhook-secret": URL_SAFE,
943
+ jwt: URL_SAFE,
944
+ };
945
+ // An AgentRun API key (ar_key_) has no entry: its shape reads its own run to the end and asks a capital or a digit of
946
+ // it, so a match is a key wherever it stands, inside a longer run too. The server holds no value of one to find it by.
947
+ const LETTER_OR_DIGIT = /[A-Za-z0-9]/;
948
+ /** An environment variable's name and its separator glued before a key (`SLACK_xoxb-...`): a name, not a blob. */
949
+ const ENV_NAME_RUN = /^[A-Z][A-Z0-9]{0,31}(?:_[A-Z0-9]{1,32}){0,8}_$/;
950
+ /** How far back a run before a prefix is read: a longer one is a blob's. */
951
+ const RUN_LOOKBACK = 256;
952
+ /** How far a key's run is read past its shape's match (ruling XI): a longer run fails the scrub closed. Below
953
+ * SCRUB_OVERLAP, so a chunk's overlap still holds every cut whole. */
954
+ export const KEY_RUN_MAX = 65_536;
955
+ /** Whether a prefix's match at `start` opens a key (ruling X): the run of its blob's characters right before it is
956
+ * empty, holds no letter or digit (`"+AKIA...`, `-sk-...`), or is an environment variable's name and its `_`. */
957
+ function opensKey(text, start, before) {
958
+ let from = start;
959
+ while (from > 0 && start - from < RUN_LOOKBACK && before.test(text.charAt(from - 1)))
960
+ from--;
961
+ if (from === start)
962
+ return true;
963
+ if (start - from >= RUN_LOOKBACK)
964
+ return false;
965
+ const run = text.slice(from, start);
966
+ return !LETTER_OR_DIGIT.test(run) || ENV_NAME_RUN.test(run);
967
+ }
968
+ /** A key's end (ruling XI): a match that opens a key runs on through its blob's characters past the shape's own bound,
969
+ * so a longer run is cut whole, never skipped nor cut short; a run longer than KEY_RUN_MAX from its start throws (fails closed). */
970
+ function keyEnd(text, start, end, after) {
971
+ let to = end;
972
+ const limit = Math.min(text.length, start + KEY_RUN_MAX);
973
+ while (to < limit && after.test(text.charAt(to)))
974
+ to++;
975
+ if (to === start + KEY_RUN_MAX && after.test(text.charAt(to)))
976
+ throw new Error("scrub: a key's run is past the scan's bound");
977
+ return to;
978
+ }
979
+ /** A view's text with each escape's letter a level further down blanked too (ruling XXXIII): a JSON string nested past
980
+ * the views' depth leaves `\\n` before a key, its `\\` blanked and its `n` a letter a shape's own lookbehind and
981
+ * opensKey would glue onto the key. Same length, so a hit's offsets hold. */
982
+ const BACKSLASH_RUN = /\\{2,64}/g;
983
+ let nestedMemo;
984
+ function nestedBlanked(text, source) {
985
+ if (source === undefined || source.length !== text.length)
986
+ return text;
987
+ if (nestedMemo?.text === text && nestedMemo.source === source)
988
+ return nestedMemo.out;
989
+ let out = "";
990
+ let from = 0;
991
+ for (const m of source.matchAll(BACKSLASH_RUN)) {
992
+ const at = m.index + m[0].length;
993
+ const letter = nestedEscape(source, at);
994
+ if (letter === 0 || text.slice(m.index, at).trim() !== "")
995
+ continue;
996
+ out += text.slice(from, at) + " ".repeat(letter);
997
+ from = at + letter;
998
+ }
999
+ out = from === 0 ? text : out + text.slice(from);
1000
+ nestedMemo = { text, source, out };
1001
+ return out;
1002
+ }
1003
+ /** SECRET_SHAPES by kind, in their order: a kind two shapes find (GitHub's classic and fine-grained tokens) is one rule. */
1004
+ const SHAPE_KINDS = [
1005
+ ...SECRET_SHAPES.reduce((kinds, shape) => kinds.set(shape.kind, [...(kinds.get(shape.kind) ?? []), shape]), new Map()),
1006
+ ];
1007
+ /** Every match of one kind's shapes in `text`, each on its own, in order. */
1008
+ const kindSpans = (text, shapes) => shapes.length === 1 ? shapeSpans(text, shapes[0]) : shapes.flatMap((shape) => shapeSpans(text, shape)).sort((a, b) => a[0] - b[0]);
1009
+ const SHAPE_RULES = SHAPE_KINDS.map(([name, shapes]) => {
1010
+ const id = SHAPE_IDS.get(name) ?? slug(name);
1011
+ const kind = SHAPE_LABELS.has(id) ? "label" : "format";
1012
+ if (id === "private-key-block")
1013
+ return rule(id, kind, (text, ctx) => pemBlocks(text, kindSpans(text, shapes), linesOfContext(text, ctx)));
1014
+ if (id === "url-password") {
1015
+ return rule(id, kind, async (text, ctx) => [
1016
+ ...kindSpans(text, shapes).flatMap((span) => urlPassword(text, span) ?? []),
1017
+ ...urlUserinfos(text).map(({ password: [start, end] }) => ({ start, end, name: "url", quoted: true })),
1018
+ ...(await lintUrlPasswords(text, ctx)),
1019
+ ]);
1020
+ }
1021
+ const quoted = id === "url-credential";
1022
+ const run = RUNS[id];
1023
+ if (run) {
1024
+ return rule(id, kind, (text, ctx) => {
1025
+ const read = nestedBlanked(text, ctx?.source);
1026
+ return kindSpans(read, shapes).flatMap(([start, end]) => (opensKey(read, start, run.before) ? [{ start, end: keyEnd(read, start, end, run.after) }] : []));
1027
+ });
1028
+ }
1029
+ return rule(id, kind, (text) => kindSpans(text, shapes).map(([start, end]) => ({ start, end, ...(quoted ? { quoted } : {}) })));
1030
+ });
1031
+ /** Vendor keys with a public prefix the learning guard's SECRET_SHAPES do not hold (ruling L), the scrubber's alone: each a
1032
+ * format, bounded like X's prefixes (a prefix holding `_`, `-` or `.` sits only inside a base64url run). Hugging
1033
+ * Face `hf_`, DigitalOcean `dop_v1_`/`doo_v1_`/`dor_v1_` (64 hex), PyPI's `pypi-` macaroon (its fixed
1034
+ * `AgEIcHlwaS5vcmc` header: "pypi.org"), SendGrid `SG.<22>.<43>`. */
1035
+ const HF_TOKEN = /hf_[A-Za-z0-9]{30,64}/g;
1036
+ const DIGITALOCEAN_TOKEN = /do[opr]_v1_[a-f0-9]{64}/g;
1037
+ const PYPI_TOKEN = /pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{32,4096}/g;
1038
+ const SENDGRID_KEY = /SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g;
1039
+ const VENDOR_RULES = [
1040
+ ["huggingface-token", HF_TOKEN],
1041
+ ["digitalocean-token", DIGITALOCEAN_TOKEN],
1042
+ ["pypi-token", PYPI_TOKEN],
1043
+ ["sendgrid-key", SENDGRID_KEY],
1044
+ ].map(([id, pattern]) => rule(id, "format", (text, ctx) => {
1045
+ const read = nestedBlanked(text, ctx?.source);
1046
+ return [...read.matchAll(pattern)].flatMap((m) => (opensKey(read, m.index, URL_SAFE_RUN) ? [{ start: m.index, end: keyEnd(read, m.index, m.index + m[0].length, URL_SAFE_RUN) }] : []));
1047
+ }));
1048
+ /** A PEM block stored base64'd (rulings LXII a, LXXIV): a k8s Secret's `tls.key`, a kubeconfig's `client-key-data`,
1049
+ * `base64 key.pem`'s output. The anchor is `-----BEGIN ` as base64 writes it at any byte offset of the encoded text
1050
+ * (a BOM, a line break, a blank, a pkcs12 `Bag Attributes` preamble before the block): at an offset 0, 1 or 2 (mod 3)
1051
+ * it encodes to one of three fixed runs, which start 0, 2 or 3 characters (mod 4) into a 4-character group
1052
+ * (BASE64_PEM_ALIGN). The encoding starts at the run's start: a run whose start puts the anchor off its alignment is
1053
+ * another run's middle, no PEM's (`QQLS0t...`), unless what stands before the aligned start holds no letter or digit
1054
+ * (a diff's `+`, ruling X's reading). A format, never restorable: the run whole, its preamble too, and the lines a
1055
+ * wrap carries it on (a line of a wrap's width, 60 to 80 and a multiple of 4: each next line under the first line's
1056
+ * own lead (a Read tool's ` 2→`, `cat -n`, grep's `file:`, a diff's `+`, as pemLines reads leads) or indented, a
1057
+ * run no longer than the first, ending its line or its string (a decoded view blanks the string's quote before a `}`,
1058
+ * `]` or `,`), the first shorter one its last). A certificate's (`client-certificate-data`) is cut too: public, but an
1059
+ * over-cut fails closed (the lead, 13:37Z). */
1060
+ const BASE64_PEM = /LS0tLS1CRUdJTi|0tLS0tQkVHSU4g|tLS0tLUJFR0lOI/g;
1061
+ const BASE64_PEM_ALIGN = { LS0tLS1CRUdJTi: 0, "0tLS0tQkVHSU4g": 2, tLS0tLUJFR0lOI: 3 };
1062
+ /** The fewest base64 characters after the anchor: a BEGIN line's encoding alone is no block. */
1063
+ const BASE64_PEM_BODY_MIN = 40;
1064
+ const BASE64_STD_BEFORE = /[A-Za-z0-9+/]/;
1065
+ const BASE64_STD_AFTER = /[A-Za-z0-9+/=]/;
1066
+ const BASE64_WRAP_BREAK = /[ \t]{0,8}\r?\n/y;
1067
+ const BASE64_WRAP_INDENT = /[ \t]{0,32}/y;
1068
+ const BASE64_WRAP_RUN = /[A-Za-z0-9+/]{1,80}={0,2}(?=[ \t]{0,8}(?:\r?\n|$|["',}\]]))/y;
1069
+ const BASE64_WRAP_LINES = 4096;
1070
+ /** The anchor alone, for a window across a line break (LXXIX), and the most of it one side of the break holds. */
1071
+ const BASE64_PEM_SPAN = /LS0tLS1CRUdJTi|0tLS0tQkVHSU4g|tLS0tLUJFR0lOI/;
1072
+ const BASE64_PEM_SPLIT = 13;
1073
+ /** What stands between a wrap line's run and its line feed: blanks, then a carriage return (BASE64_WRAP_BREAK's). */
1074
+ const BASE64_BREAK_BEFORE = /[ \t]{0,8}\r?\n$/;
1075
+ /** Whether a character code is standard base64's (no `=`): A-Z, a-z, 0-9, `+`, `/`. */
1076
+ const base64Code = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || code === 43 || code === 47;
1077
+ /** A wrap line's run after the line break at `at`: under `lead` (the first line's, as tokens) or indented, whichever
1078
+ * gives a run of the wrap's `width` (a full line), else the first that gives a shorter run (the last line). */
1079
+ function base64WrapLine(text, at, lead, width) {
1080
+ const starts = [];
1081
+ if (lead.length) {
1082
+ const led = leadLength(lead, text.slice(at, at + PEM_LEAD_MAX * 2));
1083
+ if (led !== undefined)
1084
+ starts.push(at + led);
1085
+ }
1086
+ BASE64_WRAP_INDENT.lastIndex = at;
1087
+ BASE64_WRAP_INDENT.exec(text);
1088
+ starts.push(BASE64_WRAP_INDENT.lastIndex);
1089
+ let last;
1090
+ for (const start of starts) {
1091
+ BASE64_WRAP_RUN.lastIndex = start;
1092
+ const run = BASE64_WRAP_RUN.exec(text);
1093
+ if (!run || run[0].length > width)
1094
+ continue;
1095
+ const line = { end: start + run[0].length, length: run[0].length };
1096
+ if (line.length === width)
1097
+ return line;
1098
+ last ??= line;
1099
+ }
1100
+ return last;
1101
+ }
1102
+ function base64Pems(text, lines) {
1103
+ const out = [];
1104
+ // The base64 run holding each anchor, found by one walk forward (linear: never a walk back per anchor), and every
1105
+ // anchor inside a block already cut skipped (ruling LXXIII: a wrap's lines are read once).
1106
+ let scanned = 0;
1107
+ let runStart = 0;
1108
+ BASE64_PEM.lastIndex = 0;
1109
+ for (let m = BASE64_PEM.exec(text); m; m = BASE64_PEM.exec(text)) {
1110
+ const anchor = m.index;
1111
+ for (; scanned < anchor; scanned++)
1112
+ if (!base64Code(text.charCodeAt(scanned)))
1113
+ runStart = scanned + 1;
1114
+ // The group the anchor's first fixed character sits in starts at `group`; the encoding starts a whole number of
1115
+ // groups before it, at the run's start or after what stands glued before it.
1116
+ const group = anchor - BASE64_PEM_ALIGN[m[0]];
1117
+ if (group < runStart)
1118
+ continue;
1119
+ const start = runStart + ((group - runStart) % 4);
1120
+ if (start > runStart && LETTER_OR_DIGIT.test(text.slice(runStart, start)))
1121
+ continue;
1122
+ if (anchor - start > KEY_RUN_MAX)
1123
+ throw new Error("scrub: a base64 run before a PEM's anchor is past the scan's bound");
1124
+ const anchorEnd = anchor + m[0].length;
1125
+ const lineEnd = keyEnd(text, start, anchorEnd, BASE64_STD_AFTER);
1126
+ const wrap = base64Wrap(text, start, lineEnd, lines);
1127
+ if (lineEnd - anchorEnd + wrap.length < BASE64_PEM_BODY_MIN)
1128
+ continue;
1129
+ out.push({ start, end: wrap.end });
1130
+ BASE64_PEM.lastIndex = Math.max(BASE64_PEM.lastIndex, wrap.end);
1131
+ }
1132
+ return [...out, ...straddlingPems(text, lines, out)];
1133
+ }
1134
+ /** The end of the wrap a base64 line from `start` to `end` opens (a line of a wrap's width, 60 to 80 and a multiple of
1135
+ * 4), and the base64 characters its next lines carry: each under the first line's lead or indented, the first shorter
1136
+ * line its last. */
1137
+ function base64Wrap(text, start, end, lines) {
1138
+ const width = end - start;
1139
+ let length = 0;
1140
+ if (width < 60 || width > 80 || width % 4 !== 0)
1141
+ return { end, length };
1142
+ const lead = leadTokens(text.slice(Math.max(lines.start(start), start - PEM_LEAD_MAX), start));
1143
+ for (let n = 0; n < BASE64_WRAP_LINES; n++) {
1144
+ BASE64_WRAP_BREAK.lastIndex = end;
1145
+ if (!BASE64_WRAP_BREAK.exec(text))
1146
+ break;
1147
+ const line = base64WrapLine(text, BASE64_WRAP_BREAK.lastIndex, lead, width);
1148
+ if (!line)
1149
+ break;
1150
+ end = line.end;
1151
+ length += line.length;
1152
+ if (line.length < width)
1153
+ break;
1154
+ }
1155
+ return { end, length };
1156
+ }
1157
+ /** The base64 PEMs whose anchor straddles a wrap's line break (ruling LXXIX: a preamble's length, `openssl pkcs12
1158
+ * -nodes | base64`'s Bag Attributes, puts it there at about one length in six). Each line break after a wrap line (a
1159
+ * run of a wrap's width ending its line, what stands glued before it no letter or digit, as LXXIV reads a diff's `+`)
1160
+ * is read once: the line's last 13 characters joined to the next line's first 13 (under the first line's lead or
1161
+ * indented) hold the anchor across the break, on its alignment counted from the line's start. The block runs from that
1162
+ * line's start through its wrap. Line breaks inside a block `found` already cut, or one cut here, are not read again
1163
+ * (linear, ruling LXXIII). */
1164
+ function straddlingPems(text, lines, found) {
1165
+ const out = [];
1166
+ const half = BASE64_PEM_SPLIT;
1167
+ let next = 0;
1168
+ for (let at = text.indexOf("\n"); at >= 0; at = text.indexOf("\n", at + 1)) {
1169
+ while (next < found.length && found[next].end <= at)
1170
+ next++;
1171
+ if (next < found.length && found[next].start <= at) {
1172
+ at = found[next].end - 1;
1173
+ continue;
1174
+ }
1175
+ const brk = BASE64_BREAK_BEFORE.exec(text.slice(Math.max(0, at - 9), at + 1));
1176
+ const runEnd = brk ? at + 1 - brk[0].length : at;
1177
+ let runStart = runEnd;
1178
+ while (runStart > runEnd - 81 && runStart > 0 && base64Code(text.charCodeAt(runStart - 1)))
1179
+ runStart--;
1180
+ if (runStart > 0 && base64Code(text.charCodeAt(runStart - 1)))
1181
+ continue;
1182
+ const width = (runEnd - runStart) - ((runEnd - runStart) % 4);
1183
+ const start = runEnd - width;
1184
+ if (width < 60 || width > 80 || LETTER_OR_DIGIT.test(text.slice(runStart, start)))
1185
+ continue;
1186
+ BASE64_WRAP_BREAK.lastIndex = runEnd;
1187
+ if (!BASE64_WRAP_BREAK.exec(text))
1188
+ continue;
1189
+ const lead = leadTokens(text.slice(Math.max(lines.start(start), start - PEM_LEAD_MAX), start));
1190
+ const following = base64WrapLine(text, BASE64_WRAP_BREAK.lastIndex, lead, width);
1191
+ if (!following)
1192
+ continue;
1193
+ const head = following.end - following.length;
1194
+ const m = BASE64_PEM_SPAN.exec(text.slice(runEnd - half, runEnd) + text.slice(head, head + Math.min(half, following.length)));
1195
+ if (!m)
1196
+ continue;
1197
+ const anchor = runEnd - half + m.index;
1198
+ if ((anchor - BASE64_PEM_ALIGN[m[0]] - start) % 4 !== 0)
1199
+ continue;
1200
+ const wrap = base64Wrap(text, start, runEnd, lines);
1201
+ // The anchor's characters on the next line are counted in the wrap's: what is after the anchor is the rest.
1202
+ if (runEnd - anchor - m[0].length + wrap.length < BASE64_PEM_BODY_MIN)
1203
+ continue;
1204
+ out.push({ start, end: wrap.end });
1205
+ at = wrap.end - 1;
1206
+ }
1207
+ return out;
1208
+ }
1209
+ /** secretlint's recommended rules (secret-cut.ts lintFinds), each key it names found where it stands: kind format all
1210
+ * (ruling C), an AWS secret access key after its name too, so no keep restores one. */
1211
+ const SECRETLINT = rule("secretlint", "format", async (text, ctx) => (await ctx.lint()).filter((find) => !LINT_URLS.has(find.id)).flatMap((find) => placesOf(text, find.value)));
1212
+ // ---------- held
1213
+ /** Every place a held value stands in `text`: each form, hex and folded identifier redact/match.ts cuts in place
1214
+ * (cutSpans over learn/secrets.ts heldNeedles), and each form split by one run of blanks (blankSplitPlaces). A form found
1215
+ * nowhere as it stands (partly encoded, split twice) is still seen by valueMatcher over what is left. */
1216
+ function heldSpans(text, values) {
1217
+ const needles = heldNeedles(values);
1218
+ return [...cutSpans(text, needles, []), ...blankSplitPlaces(text, needles.forms)];
1219
+ }
1220
+ const isBlankCode = (code) => code === 32 || (code >= 9 && code <= 13) || code === 0xa0 || code === 0x1680 || (code >= 0x2000 && code <= 0x200a) || code === 0x2028 || code === 0x2029 || code === 0x202f || code === 0x205f || code === 0x3000 || code === 0xfeff;
1221
+ /** How many runs of blanks stand in `text` from `start` to `last`. */
1222
+ function blankRuns(text, start, last) {
1223
+ let runs = 0;
1224
+ for (let at = start + 1; at <= last; at++)
1225
+ if (isBlankCode(text.charCodeAt(at)) && !isBlankCode(text.charCodeAt(at - 1)))
1226
+ runs++;
1227
+ return runs;
1228
+ }
1229
+ /** Every place a form (one MIN_SECRET long or more, with no blank of its own) stands in `text` split by one run of
1230
+ * blanks (a line wrapped, a space typed into it; ruling XXXII: two runs are words, `alpha beta gamma`): the span from
1231
+ * its first character to its last, the blanks between included, so a cut over it takes the form whole (ruling XIV).
1232
+ * Each blank's offset is kept, not a copy of the text's: an offset in the text with its blanks taken out maps back by a
1233
+ * search over them. */
1234
+ function blankSplitPlaces(text, forms) {
1235
+ const blanks = [];
1236
+ const kept = [];
1237
+ let from = 0;
1238
+ for (let at = 0; at < text.length; at++) {
1239
+ if (!isBlankCode(text.charCodeAt(at)))
1240
+ continue;
1241
+ if (at > from)
1242
+ kept.push(text.slice(from, at));
1243
+ blanks.push(at);
1244
+ from = at + 1;
1245
+ }
1246
+ if (!blanks.length)
1247
+ return [];
1248
+ kept.push(text.slice(from));
1249
+ const squeezed = kept.join("");
1250
+ // The text's offset of the squeezed text's `k`th character: k plus the blanks before it (blank i has blanks[i] - i
1251
+ // characters before it).
1252
+ const offsetOf = (k) => {
1253
+ let low = 0;
1254
+ let high = blanks.length;
1255
+ while (low < high) {
1256
+ const mid = (low + high) >> 1;
1257
+ if (blanks[mid] - mid <= k)
1258
+ low = mid + 1;
1259
+ else
1260
+ high = mid;
1261
+ }
1262
+ return k + low;
1263
+ };
1264
+ const out = [];
1265
+ for (const form of forms) {
1266
+ if (form.length < MIN_SECRET || [...form].some((c) => isBlankCode(c.charCodeAt(0))))
1267
+ continue;
1268
+ for (const { start: at, end } of placesOf(squeezed, form)) {
1269
+ const start = offsetOf(at);
1270
+ const last = offsetOf(end - 1);
1271
+ if (last - start + 1 > form.length && blankRuns(text, start, last) === 1)
1272
+ out.push([start, last + 1]);
1273
+ }
1274
+ }
1275
+ return out;
1276
+ }
1277
+ /** Held values are read in the view's text before its escapes were blanked: a held value may hold a backslash. */
1278
+ const HELD = rule("held-value", "held", (_text, ctx) => (ctx.held.length ? heldSpans(ctx.source, ctx.held).map(([start, end]) => ({ start, end })) : []));
1279
+ // ---------- label
1280
+ /** The scrubber's own name test (ruling I), apart from secret-name.ts keyShaped (the run environment's cut, which reads
1281
+ * any segment): a name labels a secret when its LAST segment (`_`, `-`, `.` or a camel hump apart, a trailing number
1282
+ * aside) is a credential word, or is KEY after a qualifier that makes it one (`API_KEY`, `SECRET_KEY`; never `cache_key`,
1283
+ * `foreign_key`, `GIT_CONFIG_KEY_0`, `KEY`), or the name is one of PASSWORD_NAMES. So a name about a secret
1284
+ * (`token_type`, `PASSWORD_FILE`, `SECRET_NAME`, `KEY_PREFIX`) is none. */
1285
+ const CREDENTIAL_WORDS = new Set(["TOKEN", "SECRET", "PASSWORD", "PASSWD", "PASS", "PAT", "CREDENTIAL", "CREDENTIALS", "DSN", "APIKEY", "PASSPHRASE"]);
1286
+ const KEY_QUALIFIERS = new Set(["API", "SECRET", "ACCESS", "PRIVATE", "AUTH", "SIGNING", "MASTER", "ENCRYPTION"]);
1287
+ /** Credential words that name a credential only after another segment: `DB_PASS`, `AWS_CREDENTIALS`, `MYSQL_PWD`, `GH_PAT`. */
1288
+ const QUALIFIED_WORDS = new Set(["PASS", "CREDENTIAL", "CREDENTIALS", "PWD", "PAT"]);
1289
+ /** Names whose value is a password though no segment says so. */
1290
+ const PASSWORD_NAMES = new Set(["PGPASSWORD", "SSHPASS", "REDISCLI_AUTH", "MYSQL_PWD"]);
1291
+ const CAMEL_HUMP = /([a-z0-9])([A-Z])/g;
1292
+ const NAME_SEPARATORS = /[-_.]{1,8}/;
1293
+ const DIGITS_ONLY = /^\d{1,8}$/;
1294
+ /** `camel`: a camel hump separates segments too (`apiKey`, `clientSecret`); labelsSecret says when (ruling LXXII). */
1295
+ const secretName = (name, camel = false) => {
1296
+ const segments = (camel ? name.replace(CAMEL_HUMP, "$1_$2") : name).toUpperCase().split(NAME_SEPARATORS).filter(Boolean);
1297
+ if (PASSWORD_NAMES.has(segments.join("_")))
1298
+ return true;
1299
+ while (segments.length > 1 && DIGITS_ONLY.test(segments.at(-1)))
1300
+ segments.pop();
1301
+ const last = segments.at(-1) ?? "";
1302
+ // Bare PASS (a verdict), CREDENTIALS (fetch's option), PWD (a directory) and PAT (a pattern) need a segment before
1303
+ // them (XX, XXII, XXXVII): DB_PASS, GITHUB_PAT.
1304
+ if (QUALIFIED_WORDS.has(last))
1305
+ return segments.length > 1;
1306
+ if (CREDENTIAL_WORDS.has(last))
1307
+ return true;
1308
+ return last === "KEY" && segments.length > 1 && KEY_QUALIFIERS.has(segments.at(-2));
1309
+ };
1310
+ /** A resource's name (DNS-1123: lower-case words joined by `-` or `.`): a k8s object's, which Helm's camelCase keys
1311
+ * reference (`existingSecret: app-credentials`). */
1312
+ const RESOURCE_NAME = /^[a-z0-9]{1,63}(?:[-.][a-z0-9]{1,63}){1,8}$/;
1313
+ /** A camelCase name that refers to a Secret object, or a key inside one, by name (ruling LXXX): Helm's existingSecret
1314
+ * family at a segment boundary, last or before an upper-case segment: `existingSecret`, `metricsExistingSecret`,
1315
+ * Bitnami's `existingSecretKey`, `existingSecretPasswordKey`. `secretName`, `secretRef` and `existingSecretName` end in
1316
+ * no credential word, so they label no secret to begin with. */
1317
+ const SECRET_OBJECT_NAME = /(?:(?:^|[^A-Za-z0-9])e|[a-z0-9]E)xistingSecret(?:$|[A-Z])/;
1318
+ /** Whether `name` labels a secret for its value (`bare`: the unquoted value, undefined when it is quoted), ruling LXXII:
1319
+ * a camel hump separates segments whatever the value (`dbPassword: v`, `clientSecret: v`, `authToken=v`), code's
1320
+ * readings decided by code's evidence and the placeholder check as for any name. A bare resource's name under a name
1321
+ * of the existingSecret family is a reference to a Secret object, no value (ruling LXXX: under any other camelCase
1322
+ * credential name a resource-shaped value, a UUID, a passphrase `tidal-oxide-lantern`, `abc123.def456`, is one). */
1323
+ const labelsSecret = (name, bare) => {
1324
+ if (secretName(name))
1325
+ return true;
1326
+ return secretName(name, true) && (bare === undefined || !SECRET_OBJECT_NAME.test(name) || !RESOURCE_NAME.test(bare));
1327
+ };
1328
+ const UPPER_NAME = /^[A-Z_][A-Z0-9_]{0,63}$/;
1329
+ /** A line's lead a tool or a diff puts before what it shows (ruling XXVII): a Read tool's ` 12→`, `cat -n`'s
1330
+ * ` 12\t`, grep -n's `path:12:` (`path-12-` on a context line) or `12:`, a diff's `+` or `-` (its ` ` is indentation).
1331
+ * One grammar for every rule anchored at a line's start: the config slot, pemLines, a dump's lines. */
1332
+ const NUMBER_LEAD = String.raw `[ \t]{0,8}\d{1,7}(?:\t|→)|(?=[^\s:=]{0,255}[./])[^\s:=]{1,256}[:-]\d{1,7}[:-]`;
1333
+ const LINE_LEAD = String.raw `(?:${NUMBER_LEAD}|\d{1,7}:|[+-])`;
1334
+ const LEAD_AT_START = new RegExp(`^${LINE_LEAD}`);
1335
+ /** What may stand between a line's start and a config key: a lead, indentation, a YAML list's `- `, an `export `, a
1336
+ * quote. */
1337
+ const LINE_PREFIX = new RegExp(String.raw `^${LINE_LEAD}?[ \t]{0,32}(?:-[ \t]{1,3}|export[ \t]{1,3})?["']?$`);
1338
+ /** What may follow a bare value to its line's end: blanks, a comment. */
1339
+ const LINE_REST = /^[ \t\r]{0,64}(?:[ \t]#[^\n]{0,1024})?$/;
1340
+ const lineStartAt = (text, at, lines) => {
1341
+ const from = lines.start(at);
1342
+ return at - from <= 320 && LINE_PREFIX.test(text.slice(from, at));
1343
+ };
1344
+ const lineEndAt = (text, at, lines) => {
1345
+ const to = lines.end(at);
1346
+ return to - at <= 1100 && LINE_REST.test(text.slice(at, to));
1347
+ };
1348
+ /** Code's evidence for a config-shaped slot (ruling XXVII; without it the slot is config's): a `{` or `(` left open
1349
+ * before the name on its line, a declaration's keyword or `self.`/`this.` before it, an entry's `,` after the value,
1350
+ * or a lower-case name, a spaced `=` and a code expression for its value. */
1351
+ const CODE_KEYWORD = /(?:^|[\s;{(])(?:const|let|var|def)[ \t][^\n]{0,256}$|(?:self|this)\.$/;
1352
+ const CODE_EXPRESSION = /^[A-Za-z_$][\w$]{0,127}(?:\.[A-Za-z_$][\w$]{0,127}){1,16}$/;
1353
+ const OPENERS = /[{(]/g;
1354
+ const CLOSERS = /[})]/g;
1355
+ function codeEvidence(before, name, value, spaced) {
1356
+ if (ENDS_ENTRY.test(value))
1357
+ return true; // ruling XLV: `,`, `)`, `}`
1358
+ if ((before.match(OPENERS)?.length ?? 0) > (before.match(CLOSERS)?.length ?? 0))
1359
+ return true;
1360
+ if (CODE_KEYWORD.test(before))
1361
+ return true;
1362
+ return spaced && !UPPER_NAME.test(name) && CODE_EXPRESSION.test(value);
1363
+ }
1364
+ /** An INI or TOML section's header, and a line a section holds (a key and its value, a comment, a blank). */
1365
+ const INI_HEADER = /^[ \t]{0,8}\[[A-Za-z0-9_. :"'-]{1,64}\][ \t\r]{0,8}$/;
1366
+ const INI_LINE = /^[ \t]{0,8}(?:[;#][^\n]{0,1024}|[A-Za-z0-9_.-]{1,64}[ \t]{0,3}[=:][^\n]{0,1024})?[ \t\r]{0,8}$/;
1367
+ /** Whether the line starting at `from` sits in an INI section (ruling XXX): above it only a section's lines, up to its
1368
+ * `[section]` header, at most 64 lines up. */
1369
+ function iniSection(text, from) {
1370
+ let end = from;
1371
+ for (let n = 0; n < 64 && end > 0 && from - end <= 16_384; n++) {
1372
+ const start = text.lastIndexOf("\n", end - 2) + 1;
1373
+ const line = text.slice(start, end - 1).replace(LEAD_AT_START, "");
1374
+ if (INI_HEADER.test(line))
1375
+ return true;
1376
+ if (!INI_LINE.test(line))
1377
+ return false;
1378
+ end = start;
1379
+ }
1380
+ return false;
1381
+ }
1382
+ /** npm's registry credentials in an .npmrc: `//registry/:_authToken=`, `:_password=`, `:_auth=`, and a bare `_auth=`
1383
+ * (ruling XXX). npm's underscore keys are credentials by name, so the key is its own anchor (ruling LVIII, after LII's
1384
+ * line leads): anything but a letter or a digit before it opens it, anywhere on its line (`//registry/:`, a Read
1385
+ * tool's `12→`, grep's `path:12:`, a diff's `+`, `foo 12:`, a blank, a quote). Not after `_` (`foo_authToken`,
1386
+ * `a__auth`: a longer name's tail, secret-assign's), `$` or `.` (`this._auth=`: a member's). The key's separator is
1387
+ * any npm writes or reads (ruling LXXVI): `=` with blanks around it or none (ini allows them: `_authToken = tok`), or a
1388
+ * quoted key's `:` (`"//registry/:_authToken": "tok"`, a JSON or YAML map of npm's config). npm config list's own
1389
+ * mask, `= (protected)`, is no value VALUE reads. */
1390
+ const NPMRC_AUTH = new RegExp(String.raw `(?<![\w$.])(_authToken|_password|_auth)(?:[ \t]{0,3}=(?!=)|["'][ \t]{0,3}:)[ \t]{0,3}${VALUE}`, "gd");
1391
+ /** npm's (pnpm's, yarn's) `config set` or `set`, read to its end (commandEnd): there a key and its value are two words
1392
+ * (`npm config set //registry/:_authToken tok`), ruling LXXVI. */
1393
+ const NPM_SET_COMMAND = /\b(?:npm|pnpm|yarn)[ \t]{1,3}(?:config[ \t]{1,3})?set(?=[ \t])/g;
1394
+ const NPM_SET_AUTH = new RegExp(String.raw `(?<![\w$.])(_authToken|_password|_auth)[ \t]{1,3}${VALUE}`, "gd");
1395
+ /** An npm key's value: a slot code does not fill (ruling XII). */
1396
+ const npmAuth = (m) => flagValue(valueHit(m, 2, 3, m[1]));
1397
+ /** NAME=value, as a shell or .env writes it: a key-shaped name or one of PASSWORD_NAMES. An upper-case name (an
1398
+ * environment variable's) is cut whatever its value; any other (a keyword argument, `token=tok`) when its value is a
1399
+ * quoted literal, or as its line's whole (`.properties`, `my.cnf`, ruling XXX). Never after `?` or `&` (a URL's parameter: url-credential reads those) or `-` (a flag). */
1400
+ const ASSIGN = new RegExp(String.raw `(?<![A-Za-z0-9_$?&])([A-Za-z_][A-Za-z0-9_]{0,63})=(?!=)${VALUE}`, "gd");
1401
+ /** name = value, name: value, "name": "value" (TOML, INI, YAML, JSON, an object literal): the name may be quoted and
1402
+ * hold a `-`. A quoted value is cut wherever it stands; a bare one runs to its line's end, and its slot is config's
1403
+ * unless code's evidence stands (ruling XXVII). */
1404
+ const ASSIGN_SPACED = new RegExp(String.raw `(?<![A-Za-z0-9_$?&])([A-Za-z_][A-Za-z0-9_]{0,63})(?:[ \t]{1,3}=(?!=)[ \t]{0,3}|=[ \t]{1,3})${VALUE}`, "gd");
1405
+ const ASSIGN_COLON = new RegExp(String.raw `(?<![A-Za-z0-9_$.])(["']?)([A-Za-z_][A-Za-z0-9_-]{0,63})\1[ \t]{0,3}:(?![:=/])[ \t]{0,3}${VALUE}`, "gd");
1406
+ /** A bare value in code's casing with no digit: a name (`password`, `secret_key`, `apiToken`) or a member chain
1407
+ * (`cfg.apiToken`), an entry's `,`, `)` or `}` after it dropped. Where the left side is code's beyond doubt (ruling
1408
+ * LIII: an environment write, a member write) it is a variable's, never a value; a quoted literal still is one. */
1409
+ const CODE_END = /[,)}]{1,4}$/;
1410
+ const codeName = (value) => {
1411
+ const name = value.replace(CODE_END, "");
1412
+ return CODE_CASE.test(name) || MEMBER_CHAIN.test(name);
1413
+ };
1414
+ /** An object's member chain right before a name (`self.`, `this.`, `settings.`, `app.config.`): a member write's. */
1415
+ const MEMBER_OBJECT_BEFORE = /(?:^|[^\w$.])([A-Za-z_$][\w$]{0,127}(?:\.[A-Za-z_$][\w$]{0,127}){0,16}\.)$/;
1416
+ /** A member write's root that is code's beyond doubt: a language's own (`self.`, `this.`, `cls.`) or the environment's
1417
+ * (`process.env.`, `import.meta.env.`, XLVII/LI). */
1418
+ const CODE_ROOT_BEFORE = /(?:^|[^\w$.])(?:self|this|cls|process\.env|import\.meta\.env)\.$/;
1419
+ /** A statement's `;` right after a value, on its line. */
1420
+ const STATEMENT_END_AFTER = /^[ \t]{0,3};/;
1421
+ /** Whether the name at `at`, its value ending at `end`, is written as an object's member beyond doubt (rulings LIII,
1422
+ * LIX): after a language's root (`self.`, `this.`, `cls.`) or the environment's always; after any other object only when a `;` ends the
1423
+ * statement. A dotted name alone (`service.DB_PASSWORD=`, `spring.datasource.password=`) is a `.properties` or INI
1424
+ * key's as much as an object's: undecidable, so config's, cut. */
1425
+ const memberWrite = (text, at, end, lines) => {
1426
+ const before = text.slice(Math.max(0, at - 320), at);
1427
+ if (CODE_ROOT_BEFORE.test(before))
1428
+ return true;
1429
+ if (!MEMBER_OBJECT_BEFORE.test(before))
1430
+ return false;
1431
+ return STATEMENT_END_AFTER.test(text.slice(end, Math.min(end + 8, lines.end(end))));
1432
+ };
1433
+ /** A bare value that is an identifier with `[`, `(` or `.` and a name right after it (the character after the value
1434
+ * included: VALUE stops at a quote or `(`): an index, a call or a member read starts there (`config["password"]`,
1435
+ * `get_secret("db")`, `settings.db.password`), a reference where the left side is code's (ruling LX). */
1436
+ const REFERENCE_START = /^[A-Za-z_$][\w$]{0,127}(?:[[(]|\.[A-Za-z_$])/;
1437
+ const referenceStart = (text, value, end) => REFERENCE_START.test(value + text.slice(end, end + 2));
1438
+ /** A write to the environment under a credential's name (ruling LI, XLVII's write side): `os.environ["X"] = v`,
1439
+ * `ENV["X"]=v`, `process.env.X = v`, `import.meta.env.X = v`. The value is a label's. */
1440
+ const ENV_ASSIGN = new RegExp(String.raw `(?<![A-Za-z0-9_$.])(?:os\.environ|ENV|process\.env|import\.meta\.env)(?:\[(["'])([A-Za-z_][A-Za-z0-9_]{0,63})\1\]|\.([A-Za-z_][A-Za-z0-9_]{0,63}))[ \t]{0,3}=(?!=)[ \t]{0,3}${VALUE}`, "gd");
1441
+ const envAssign = (m) => {
1442
+ const name = m[2] ?? m[3];
1443
+ if (!secretName(name, m[7] === undefined))
1444
+ return undefined;
1445
+ // Ruling LIII: a bare name is a variable's (`os.environ["PGPASSWORD"] = password`). Any other value is the
1446
+ // environment's, as NAME=value's is (code: false): the code-shape guesses are read here, never after the value (a
1447
+ // JSON string's end and its object's `}` after it read as an entry's end).
1448
+ if (m[7] !== undefined && (codeName(m[7]) || referenceStart(m.input, m[7], m.indices[7][1])))
1449
+ return undefined; // rulings LIII, LX
1450
+ const hit = valueHit(m, 4, 3, name);
1451
+ return hit && { ...hit, code: false };
1452
+ };
1453
+ /** Whether the `-` before a name at `at` makes it a flag's (`--db-password=`, `-Dkey=`, `cmd -PGPASSWORD=`): it does
1454
+ * unless a line start or a digit stands before the `-` (ruling XL): a diff's `-` line and grep -C's `path-N-` lead
1455
+ * open a line. A line start is `lines`', so a decoded string's start counts where its quote is blanked. */
1456
+ const flagDash = (text, at, lines) => {
1457
+ if (text.charAt(at - 1) !== "-")
1458
+ return false;
1459
+ const dash = at - 1;
1460
+ if (lines.start(dash) === dash)
1461
+ return false;
1462
+ const before = text.charCodeAt(dash - 1);
1463
+ return !(before >= 48 && before <= 57);
1464
+ };
1465
+ /** A name's match, unless a flag's `-` stands before it. */
1466
+ const notFlag = (text, lines, read) => (m) => flagDash(text, m.index, lines) ? undefined : read(m);
1467
+ /** Where a rejected `name: value` is read again: at its value, when a blank or a quote stands before the value (the
1468
+ * value may be the next key: `content : password: x` in a decoded JSON string, or a quoted value that is a line,
1469
+ * `"stdout":"password: x"`, ruling XXXIX), never inside a glued chain (an ARN's `:secret:`). */
1470
+ const afterBlank = (m) => {
1471
+ const start = m.indices.slice(3).find((span) => span !== undefined)?.[0];
1472
+ if (start === undefined)
1473
+ return undefined;
1474
+ const before = m.input.charAt(start - 1);
1475
+ return before === " " || before === "\t" || before === '"' || before === "'" ? start : undefined;
1476
+ };
1477
+ /** Whether a bare value sits between escaped quotes (`\"value\"` in a JSON string's raw view, whose escapes are
1478
+ * blanked): it is a quoted value, read as one in the view that decodes the string, never bare. */
1479
+ const ESCAPED_QUOTE_BEFORE = /\\["']$/;
1480
+ const ESCAPED_QUOTE_AFTER = /^\\["']/;
1481
+ const escapeQuoted = (source, m, group) => {
1482
+ const span = m.indices[group];
1483
+ return source !== undefined && span !== undefined && ESCAPED_QUOTE_BEFORE.test(source.slice(Math.max(0, span[0] - 2), span[0])) && ESCAPED_QUOTE_AFTER.test(source.slice(span[1], span[1] + 2));
1484
+ };
1485
+ /** A `.properties` key's segments before its last (`spring.datasource.` of `spring.datasource.password=`). */
1486
+ const DOTTED_KEY_BEFORE = /(?:[A-Za-z0-9_-]{1,64}\.){1,8}$/;
1487
+ const assign = (text, lines, source) => (m) => {
1488
+ const name = m[1];
1489
+ const bare = m[5] !== undefined && !escapeQuoted(source, m, 5); // group 5: the bare value
1490
+ if (!labelsSecret(name, bare ? m[5] : undefined))
1491
+ return undefined;
1492
+ const hit = valueHit(m, 2, 3, name);
1493
+ if (!hit)
1494
+ return undefined;
1495
+ // A bare value ending with `,`, `)` or `}` ends an argument or an entry: code's evidence (ruling XLV), so the code
1496
+ // checks (XIX name==value, XXI identifier, a member chain) read it, the ending stripped.
1497
+ const entry = bare && ENDS_ENTRY.test(m[5]);
1498
+ const end = m.indices[5]?.[1] ?? hit.end;
1499
+ if (bare && (codeName(m[5]) || referenceStart(text, m[5], end)) && memberWrite(text, m.index, end, lines))
1500
+ return undefined; // rulings LIII, LIX, LX
1501
+ // NAME=value with an upper-case name is the environment's slot, quoted or not (rulings XII, XIX).
1502
+ if (UPPER_NAME.test(name))
1503
+ return entry ? hit : { ...hit, code: false };
1504
+ if (!bare)
1505
+ return hit;
1506
+ // A lower-case name=value is a config's line (.properties, my.cnf) when it is its line's whole (ruling XXX); else
1507
+ // it is a keyword argument's, never cut bare.
1508
+ const key = m.index - (DOTTED_KEY_BEFORE.exec(text.slice(Math.max(0, m.index - 320), m.index))?.[0].length ?? 0);
1509
+ if (CODE_KEYWORD.test(text.slice(key, m.index)))
1510
+ return undefined; // `self.token=token`: an attribute's, code's
1511
+ // Before a command on its line (`db_password=x ./run.sh`), a lower-case name=value is that command's environment, as
1512
+ // an upper-case one is (ruling LXI c).
1513
+ // After a `;` alone (code's statement as much as a shell's) code's shapes stay no value (ruling LXX).
1514
+ const env = key === m.index ? commandEnv(text, m.index, end, lines) : undefined;
1515
+ if (env === "statement")
1516
+ return hit;
1517
+ if (env === "command")
1518
+ return entry ? hit : { ...hit, code: false };
1519
+ if (!keyStartAt(text, key, m.index, lines) || !lineEndAt(text, hit.end, lines))
1520
+ return undefined;
1521
+ return entry ? hit : { ...hit, code: false };
1522
+ };
1523
+ /** A shell's prompt (ruling LXX): a virtualenv's `(name) ` maybe, a `user@host` and its `:path` or a bracketed
1524
+ * `[user@host dir]` maybe, then `$`, `#`, `%`, `>` or `❯` and a blank (`bob@h:~/app$ `, `root@h:~# `, `# `). */
1525
+ const PROMPT = String.raw `(?:\([^()\n]{1,64}\)[ \t]{1,3})?(?:[A-Za-z0-9_.-]{1,64}@[A-Za-z0-9_.-]{1,64}(?::[^\s$#]{0,256})?|\[[^\]\n]{1,256}\])?[$#%>❯][ \t]{1,3}`;
1526
+ /** A command word's options (ruling LXXXII): a flag, its `=argument` or its next word as an argument maybe (a word
1527
+ * with no `=` that is no flag: `-u app`, `--user=app`, `-E`), each before a blank. Which flag takes an argument is
1528
+ * the command's own; reading a next word as one is the read that leaves the assignment after it. */
1529
+ const COMMAND_OPTIONS = String.raw `(?:-{1,2}[A-Za-z][A-Za-z0-9-]{0,63}(?:=[^\s;&|]{0,1024}|[ \t]{1,3}[^\s=;&|-][^\s=;&|]{0,1024})?[ \t]{1,3}){0,8}`;
1530
+ /** What stands before a command's environment (rulings LXI c, LXX): its line's start (a lead, indentation, a prompt:
1531
+ * group 1) or a shell's `;`, `&&`, `||` or `|`, then `env`, `sudo` or `export` maybe (group 2) and its options
1532
+ * (ruling LXXXII), then any other NAME=value before it. */
1533
+ const ENV_PREFIX_BEFORE = new RegExp(String.raw `(?:^${LINE_LEAD}?[ \t]{0,32}(${PROMPT})?|(?:;|&&|\|\|?)[ \t]{1,8})(?:(env|sudo|export)[ \t]{1,3}${COMMAND_OPTIONS})?(?:[A-Za-z_][A-Za-z0-9_]{0,63}=[^\s;&|]{0,1024}[ \t]{1,8}){0,8}$`);
1534
+ /** What follows it: any other NAME=value, then a blank and a command's word (no `=` in it). */
1535
+ const ENV_PREFIX_AFTER = /^(?:[ \t]{1,8}[A-Za-z_][A-Za-z0-9_]{0,63}=[^\s;&|]{0,1024}){0,8}[ \t]{1,8}[A-Za-z0-9_./~][^\s=;&|]{0,1024}(?=[\s;&|]|$)/;
1536
+ /** Or a shell's `&&` or `||` (ruling LXX): the line goes on as a shell's, never code's. */
1537
+ const ENV_PREFIX_CHAIN = /^(?:[ \t]{1,8}[A-Za-z_][A-Za-z0-9_]{0,63}=[^\s;&|]{0,1024}){0,8}[ \t]{0,8}(?:&&|\|\|)/;
1538
+ /** Or a `;`: a statement's end in code as much as in a shell (ruling LXX). */
1539
+ const ENV_PREFIX_STATEMENT = /^(?:[ \t]{1,8}[A-Za-z_][A-Za-z0-9_]{0,63}=[^\s;&|]{0,1024}){0,8}[ \t]{0,8};/;
1540
+ /** Whether the name=value at [at, end) is a shell's environment on its line (rulings LXI c, LXX): "command" when it
1541
+ * prefixes a command or a shell's `&&`/`||` follows it, or a `;` does after a prompt, `env`, `sudo` or `export` (a
1542
+ * slot code does not fill); "statement" when a `;` follows it with no such mark (code's or a shell's: code's shapes
1543
+ * stay no value there); else undefined. */
1544
+ const commandEnv = (text, at, end, lines) => {
1545
+ const from = lines.start(at);
1546
+ const to = lines.end(end);
1547
+ if (at - from > 320 || to - end > 2048)
1548
+ return undefined;
1549
+ const before = ENV_PREFIX_BEFORE.exec(text.slice(from, at));
1550
+ if (!before)
1551
+ return undefined;
1552
+ const after = text.slice(end, to);
1553
+ if (ENV_PREFIX_AFTER.test(after) || ENV_PREFIX_CHAIN.test(after))
1554
+ return "command";
1555
+ if (!ENV_PREFIX_STATEMENT.test(after))
1556
+ return undefined;
1557
+ return before[1] !== undefined || before[2] !== undefined ? "command" : "statement";
1558
+ };
1559
+ /** A flag whose value is itself NAME=value (ruling LXX): `docker run -e NAME=v`, `--env NAME=v`, `--env=NAME=v`,
1560
+ * `kubectl create secret generic x --from-literal=NAME=v`, a quote maybe before the name (group 1). The name may be
1561
+ * dotted, a value's path (ruling LXXXI: `helm install --set auth.postgresPassword=v`, `--from-literal=db.password=v`):
1562
+ * its last segment decides, as secretName reads any name. Each segment may be dashed, as a Helm path's (ruling LXXXVI:
1563
+ * `--from-literal=postgres-password=v`, Bitnami's keys, read as `--set postgres-password=v` is). The value is a
1564
+ * flag's, a slot code does not fill. */
1565
+ const ENV_FLAG = new RegExp(String.raw `(?<![\w-])-{1,2}[A-Za-z][A-Za-z0-9-]{0,63}(?:=|[ \t]{1,3})(["']?)([A-Za-z_][A-Za-z0-9_-]{0,63}(?:\.[A-Za-z_][A-Za-z0-9_-]{0,63}){0,8})=(?!=)${VALUE}`, "gd");
1566
+ const envFlag = (m) => {
1567
+ if (HELM_LIST_FLAG.test(m[0]))
1568
+ return undefined; // helmSetLists reads the whole list
1569
+ if (!labelsSecret(m[2], m[6]))
1570
+ return undefined;
1571
+ const hit = valueHit(m, 3, 3, m[2]);
1572
+ return hit && { ...hit, code: false };
1573
+ };
1574
+ /** Helm's list flags (ruling LXXXI): `--set`, `--set-string` and `--set-file` take a comma-separated list of name=value
1575
+ * (`--set db.user=u,db.password=x`), a `\,` an escaped comma inside a value; `--set-literal` takes one name=value,
1576
+ * commas and all, and ENV_FLAG reads it. A quote maybe opens the list (group 1). */
1577
+ const HELM_LIST_FLAG = /^--set(?:-string|-file)?(?:=|[ \t])/;
1578
+ const HELM_SET = /(?<![\w-])--set(?:-string|-file)?(?:=|[ \t]{1,3})(["']?)/g;
1579
+ /** A list item's name (a Helm path: dots, `[0]` indices, `\.` escaped dots, `/` in annotation keys) and its `=`. */
1580
+ const HELM_NAME = /[A-Za-z_][A-Za-z0-9_.[\]\/\\-]{0,255}=(?!=)/y;
1581
+ /** How many items of one list helmSetLists reads. A value runs to its end, however long (ruling LXXXVIII): each list is
1582
+ * read once, so the reading stays linear without a bound on it. */
1583
+ const HELM_PAIRS = 64;
1584
+ /** Each credential's value in each Helm list (ruling LXXXI): every item's name decides its own value, which runs to the
1585
+ * next unescaped `,`, a blank (the list's quote when one opened it) or the line's end. A flag's slot: code does not
1586
+ * fill it. */
1587
+ function helmSetLists(text) {
1588
+ const hits = [];
1589
+ // Where the last list read ended: a `--set` inside it is a value's text, read already, and read again from each
1590
+ // such `--set` a list of them was read up to 64 x 1024 over (ruling LXXXV).
1591
+ let scanned = 0;
1592
+ for (const m of text.matchAll(HELM_SET)) {
1593
+ if (m.index < scanned)
1594
+ continue;
1595
+ const quote = m[1];
1596
+ let at = m.index + m[0].length;
1597
+ for (let pairs = 0; pairs < HELM_PAIRS; pairs++) {
1598
+ HELM_NAME.lastIndex = at;
1599
+ const name = HELM_NAME.exec(text);
1600
+ if (name === null)
1601
+ break;
1602
+ const start = at + name[0].length;
1603
+ const limit = text.length;
1604
+ let end = start;
1605
+ while (end < limit) {
1606
+ const c = text.charAt(end);
1607
+ if (c === "\\" && end + 1 < limit) {
1608
+ end += 2;
1609
+ continue;
1610
+ }
1611
+ if (c === "," || c === "\n" || (quote ? c === quote : c === " " || c === "\t"))
1612
+ break;
1613
+ end++;
1614
+ }
1615
+ const key = name[0].slice(0, -1);
1616
+ if (end - start >= 3 && labelsSecret(key, text.slice(start, end)))
1617
+ hits.push({ start, end, name: key, code: false });
1618
+ scanned = end;
1619
+ if (text.charAt(end) !== ",")
1620
+ break;
1621
+ at = end + 1;
1622
+ }
1623
+ }
1624
+ return hits;
1625
+ }
1626
+ /** Whether a dotted key in [key, name) starts its line. The key's grammar takes a `-` (`max-pool-size`), so a grep -C
1627
+ * lead (`app.yml-41-`) reads as its first segments: the line may start at any of the key's `.` or `-` (ruling XL). */
1628
+ const keyStartAt = (text, key, name, lines) => {
1629
+ for (let at = key; at <= name; at++) {
1630
+ if (at > key && text.charAt(at - 1) !== "." && text.charAt(at - 1) !== "-")
1631
+ continue;
1632
+ if (lineStartAt(text, at, lines))
1633
+ return true;
1634
+ }
1635
+ return false;
1636
+ };
1637
+ /** A bare word that is itself a `name=value` (`dbname=widgets`, `next=1`), not base64's `=` padding at its end. */
1638
+ const NEXT_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}=(?!=)[^\s=]/;
1639
+ /** An assignment right before a name on its line, a blank between (`host=db `, `A=1 `): its line separates assignments
1640
+ * by blanks (ruling LXVII). */
1641
+ const ASSIGNMENT_BEFORE = /(?:^|[\s"';])[A-Za-z_][A-Za-z0-9_.-]{0,63}=\S{0,1024}[ \t]{1,8}$/;
1642
+ /** Whether the context decides that the blank after the name's `=` at [at, end) ends an empty value (ruling LXVII): an
1643
+ * assignment stands right before it on its line, or it prefixes a command (commandEnv). */
1644
+ const emptyByContext = (text, at, end, lines) => {
1645
+ const from = lines.start(at);
1646
+ return (at - from <= 320 && ASSIGNMENT_BEFORE.test(text.slice(from, at))) || commandEnv(text, at, end, lines) !== undefined;
1647
+ };
1648
+ const configAssign = (text, nameGroup, lines, source) => (m) => {
1649
+ const name = m[nameGroup];
1650
+ const value = escapeQuoted(source, m, nameGroup + 4) ? undefined : m[nameGroup + 4];
1651
+ // `name= next=v`: `=` right after the name, then a blank, then a word that is itself an assignment. Where blanks
1652
+ // separate assignments that blank ends an empty value: another assignment right before it on its line (libpq's
1653
+ // `host=db password= dbname=x`, a shell's `A=1 B= c=2`) or a command it prefixes (`TOKEN= OTHER=1 ./run.sh`). Nothing
1654
+ // else decides it: a .env's or a .properties' `DB_PASSWORD= realm=x` may hold the password `realm=x`, so the next
1655
+ // word is the value, cut (ruling LXVII, narrowing LXI's empty-value negative).
1656
+ if (value !== undefined && text[m.index + name.length] === "=" && NEXT_ASSIGNMENT.test(value) && emptyByContext(text, m.index, m.index + name.length + 1, lines))
1657
+ return undefined;
1658
+ if (!labelsSecret(name, value))
1659
+ return undefined;
1660
+ const hit = valueHit(m, nameGroup + 1, 3, name);
1661
+ if (!hit || value === undefined)
1662
+ return hit;
1663
+ // A bare value is its line's whole value (a flow map, `{password: x}`, is beta 2's backlog: it reads as code's).
1664
+ if (!lineEndAt(text, hit.end, lines))
1665
+ return undefined;
1666
+ if (nameGroup === 1 && (codeName(value) || referenceStart(text, value, hit.end)) && memberWrite(text, m.indices[1][0], hit.end, lines))
1667
+ return undefined; // rulings LIII, LIX, LX
1668
+ // The slot is config's unless code's evidence stands (ruling XXVII: what can't be decided is config's, cut); a
1669
+ // section's lines are config's whatever their value's shape (ruling XXX). A YAML key's slot (the name unquoted)
1670
+ // is one a type annotation fills too (`typed`, ruling XVI).
1671
+ const nameStart = m.indices[nameGroup][0] - (nameGroup === 2 ? m[1].length : 0);
1672
+ const from = lines.start(nameStart);
1673
+ const before = nameStart - from <= 320 ? text.slice(from, nameStart) : "";
1674
+ const spaced = nameGroup === 1;
1675
+ const lineFrom = text.lastIndexOf("\n", nameStart - 1) + 1;
1676
+ if (codeEvidence(before, name, value, spaced) && !(spaced && lineStartAt(text, nameStart, lines) && !CODE_KEYWORD.test(before) && iniSection(text, lineFrom)))
1677
+ return hit;
1678
+ return { ...hit, code: false, ...(nameGroup === 2 && m[1] === "" ? { typed: true } : {}) };
1679
+ };
1680
+ /** A connection string's password (ruling LXI a): libpq's `k=v k=v` (`psql "host=db password=..."`), ADO's `k=v;k=v;`
1681
+ * and ODBC's (`PWD={...};`). The key, any case, opens the text or follows `;`, a blank or a quote; blanks may stand
1682
+ * around its `=` (groups 2, 3: libpq and ADO allow them, ruling LXVIII); its value ends at `;`, a blank, a quote or the
1683
+ * end, or is ODBC's braced value (group 4: `}}` an escaped brace inside it, `{` any character but its first, so a
1684
+ * template's `{{...}}` is no braced value). */
1685
+ const CONNECTION_PASSWORD = new RegExp(String.raw `(?<![^\s;"'])(password|passwd|pwd)([ \t]{0,3})=([ \t]{0,3})(?:\{(?!\{)((?:[^}\n]|\}\}){1,1024})\}|${VALUE})`, "dgi");
1686
+ /** An ADO pair beside a key's (rulings LXVIII, LXXXIII): a key (ADO's hold blanks, `User Id`), blanks maybe around its
1687
+ * `=` (`Server = db`) and a value, read from the `;` or quote before it. Code's `x = 1;` reads the same: the slot's
1688
+ * code shapes decide there, as for any connection string's value. The value may be empty (ruling LXXXIV:
1689
+ * `Application Name=;`, its `;` or the read's end right after the `=`); code's `==` is no pair. */
1690
+ const ADO_PAIR = /^[ \t]{0,8}[A-Za-z](?:[A-Za-z0-9 _.-]{0,62}[A-Za-z0-9_.-])?([ \t]{0,3})=([ \t]{0,3})(?:[^\s=]|$)/;
1691
+ const adoPair = (slice) => {
1692
+ const pair = ADO_PAIR.exec(slice);
1693
+ return pair === null ? undefined : pair[1] === "" && pair[2] === "" ? "plain" : "spaced";
1694
+ };
1695
+ /** Blanks only (none too). */
1696
+ const BLANKS = /^[ \t]{0,8}$/;
1697
+ /** A libpq pair right after a value (ruling LXXXIII: `password = x host=db`): a blank, a key, `=` and a value. */
1698
+ const LIBPQ_PAIR_AFTER = /^[ \t]{1,8}[A-Za-z_][A-Za-z0-9_.-]{0,63}=(?!=)[^\s=]/;
1699
+ /** The pairs before a key the connection-string reads, at most this far back on its line. */
1700
+ const CONNECTION_BEFORE = 1024;
1701
+ /** A braced value that is a format string's field, never ODBC's value: a name with no digit (`{password}`,
1702
+ * `{cfg.pw}`), a position (`{0}`), or none, a conversion or a format spec after it (`{pw!r}`, `{pw:>8}`). ODBC braces
1703
+ * exist to escape a `;` or `}` in a value, so braces holding only an identifier are a template's field far more often
1704
+ * than a password (lead 11-23); a braced value with a digit or other punctuation (`{Hunter2xyz}`) stays cut. */
1705
+ const FORMAT_FIELD = /^(?:[A-Za-z_][A-Za-z_.]{0,127}|\d{1,3})?(?:![rsa])?(?::[^{}\n]{0,32})?$/;
1706
+ /** `pwd`'s value as a path: the shell's working directory (`PWD=/srv/app`), never a password. */
1707
+ const PWD_PATH = /^(?:[/~.]|[A-Za-z]:[\\/]|%2F)/i;
1708
+ /** Whether the key at `at` (its line from `from`) follows ADO's `;` that closes another pair (ruling LXVIII): blanks,
1709
+ * the `;`, and back to the `;` or quote before it, ADO_PAIR. */
1710
+ const adoKey = (text, at, from) => {
1711
+ let semi = at;
1712
+ while (semi > from && (text.charAt(semi - 1) === " " || text.charAt(semi - 1) === "\t"))
1713
+ semi--;
1714
+ if (semi <= from || text.charAt(semi - 1) !== ";")
1715
+ return undefined;
1716
+ let open = semi - 1;
1717
+ const limit = Math.max(from, semi - 1 - CONNECTION_BEFORE);
1718
+ while (open > limit && !";\"'".includes(text.charAt(open - 1)))
1719
+ open--;
1720
+ return adoPair(text.slice(open, semi - 1));
1721
+ };
1722
+ /** A pair whose key is a connection string's own (ruling LXXXIII): its server, database, user, port, driver, provider
1723
+ * or security keys, ADO's, ODBC's and libpq's, blanks maybe around its `=`. Code names its variables otherwise. */
1724
+ const CONNECTION_KEY_PAIR = /^[ \t]{0,8}(?:server|data[ \t]{1,3}source|host|address|addr|network[ \t]{1,3}address|database|initial[ \t]{1,3}catalog|user[ \t]{1,3}id|uid|user|port|driver|provider|dsn|integrated[ \t]{1,3}security|encrypt|trustservercertificate)[ \t]{0,3}=[ \t]{0,3}[^\s;=]/i;
1725
+ /** How many pairs on each side of a key connectionKeyBeside reads. */
1726
+ const CONNECTION_PAIRS = 16;
1727
+ /** Whether a connection string's own key stands among the `;`-separated pairs before the key at `at` or after its
1728
+ * value's `;` at `stop` (ruling LXXXIII): positive evidence of a connection string, so its slot is config's whatever
1729
+ * the value's shape. Read in the source to the line's start or end or a quote as written, at most CONNECTION_PAIRS
1730
+ * pairs and CONNECTION_BEFORE characters each way. */
1731
+ const connectionKeyBeside = (source, at, stop, from, to) => {
1732
+ let semi = at;
1733
+ while (semi > from && (source.charAt(semi - 1) === " " || source.charAt(semi - 1) === "\t"))
1734
+ semi--;
1735
+ const back = Math.max(from, semi - CONNECTION_BEFORE);
1736
+ for (let pairs = 0; pairs < CONNECTION_PAIRS && semi > back && source.charAt(semi - 1) === ";"; pairs++) {
1737
+ let open = semi - 1;
1738
+ while (open > back && !";\"'".includes(source.charAt(open - 1)))
1739
+ open--;
1740
+ if (CONNECTION_KEY_PAIR.test(source.slice(open, semi - 1)))
1741
+ return true;
1742
+ semi = open;
1743
+ }
1744
+ const on = Math.min(to, stop + CONNECTION_BEFORE);
1745
+ for (let pairs = 0, at2 = stop; pairs < CONNECTION_PAIRS && at2 < on && source.charAt(at2) === ";"; pairs++) {
1746
+ let close = at2 + 1;
1747
+ while (close < on && !";\"'".includes(source.charAt(close)))
1748
+ close++;
1749
+ if (CONNECTION_KEY_PAIR.test(source.slice(at2 + 1, close)))
1750
+ return true;
1751
+ at2 = close;
1752
+ }
1753
+ return false;
1754
+ };
1755
+ /** The ADO pair after the `;` at `semi` (ruling LXXXIII: `Password = x; Server=db`, the key first). */
1756
+ const adoPairAfter = (text, semi) => (text.charAt(semi) === ";" ? adoPair(text.slice(semi + 1, semi + 1 + 160)) : undefined);
1757
+ /** An ADO value's run over blanks (ruling LXXXIII): from a value's end, the offset of its stop, its `;`, a line break
1758
+ * or its line's end, at most CONNECTION_BEFORE on. A tab is the value's when its `;` follows on the line
1759
+ * (`Pwd=Copper\tlumen x;`, ruling LXXXVII); with none in reach the first tab stops it (a tab-separated column after
1760
+ * it). A view blanks each escape it decodes (`\n`, `\t`, `\"`, whatever the encodings around it put), so where the
1761
+ * view's character is not the source's an escape stands, and the run stops at it: the decoded view holds the line
1762
+ * break, tab or quote there, and reads it as above. The text's next stop, and the tabs before it, are read forward
1763
+ * once and kept while the values asked about stand before it: linear in the text. */
1764
+ const adoRun = (text, source, lines) => {
1765
+ let from = Infinity;
1766
+ let next = -1;
1767
+ let tabs = [];
1768
+ return (end) => {
1769
+ if (end < from || end > next) {
1770
+ from = end;
1771
+ next = end;
1772
+ tabs = [];
1773
+ for (; next < text.length; next++) {
1774
+ const c = text.charAt(next);
1775
+ if (c === "\t" && source.charAt(next) === "\t") {
1776
+ tabs.push(next);
1777
+ continue;
1778
+ }
1779
+ if (c === ";" || c === "\r" || c === "\n" || c !== source.charAt(next))
1780
+ break;
1781
+ }
1782
+ }
1783
+ const bound = Math.min(lines.end(end), end + CONNECTION_BEFORE);
1784
+ if (next <= bound && text.charAt(next) === ";")
1785
+ return next;
1786
+ // No `;` in reach: the first tab at or after the value's end stops it.
1787
+ let lo = 0;
1788
+ let hi = tabs.length;
1789
+ while (lo < hi) {
1790
+ const mid = (lo + hi) >> 1;
1791
+ if (tabs[mid] < end)
1792
+ lo = mid + 1;
1793
+ else
1794
+ hi = mid;
1795
+ }
1796
+ return Math.min(lo < tabs.length ? tabs[lo] : next, bound);
1797
+ };
1798
+ };
1799
+ const connectionPassword = (text, lines, source = text) => {
1800
+ const runTo = adoRun(text, source, lines);
1801
+ return (m) => {
1802
+ const key = m[1];
1803
+ const spaced = m[2] !== "" || m[3] !== "";
1804
+ // A view blanks the escapes it decodes: blanks around `=` are a connection string's only as written (`Password=\"`
1805
+ // in a JSON string is a quote's, ruling LXXXIII), and the pairs before the key are read to the quote as written.
1806
+ if (spaced && !BLANKS.test(source.slice(m.indices[2][0], m.indices[3][1]).replace("=", "")))
1807
+ return undefined;
1808
+ const from = lines.start(m.index);
1809
+ const before0 = adoKey(source, m.index, from);
1810
+ // The value's end as matched, and where an ADO run over blanks from it would stop (ruling LXXXIII).
1811
+ const matched = m.indices[0][1];
1812
+ const blankAfter = text.charAt(matched) === " " || text.charAt(matched) === "\t";
1813
+ const stop = blankAfter ? runTo(matched) : matched;
1814
+ // An ADO string's: a pair before the key's `;`, or one after the value's `;` (the key first, ruling LXXXIII).
1815
+ const after0 = adoPairAfter(text, stop);
1816
+ const ado = before0 !== undefined || after0 !== undefined;
1817
+ // A blank around `=` is code's spacing as often as a connection string's: it is one only beside another pair, ADO's
1818
+ // `;` closing one, or libpq's pair and a blank right before the key or right after the value (rulings LXVIII, LXXXIII).
1819
+ const libpq = (m.index - from <= 320 && ASSIGNMENT_BEFORE.test(text.slice(from, m.index))) || LIBPQ_PAIR_AFTER.test(text.slice(matched, matched + 72));
1820
+ if (spaced && !ado && !libpq)
1821
+ return undefined;
1822
+ // A spaced key beside spaced pairs only (`a = 1; password = x;`) reads as code's statements as well: its slot is one
1823
+ // code fills, code's shapes decide (an identifier in code's casing stays). A plain pair beside it, or a connection
1824
+ // string's own key among its pairs (`Server = db; Password = x;`), is a connection string's: config's slot (ruling
1825
+ // LXXXIII).
1826
+ const codeSlot = spaced && !libpq && before0 !== "plain" && after0 !== "plain" && !connectionKeyBeside(source, m.index, stop, from, lines.end(stop));
1827
+ if (m[4] !== undefined) {
1828
+ if (FORMAT_FIELD.test(m[4]))
1829
+ return undefined;
1830
+ const [start, end] = m.indices[4];
1831
+ return { start, end, name: key, quoted: true };
1832
+ }
1833
+ const hit = valueHit(m, 5, 1, key);
1834
+ const value = m[8]; // the bare value
1835
+ if (!hit || value === undefined)
1836
+ return hit;
1837
+ // libpq's `password= dbname=x`: the blank after `=` ends an empty value, the next pair stands after it (LXVII).
1838
+ if (m[3] !== "" && NEXT_ASSIGNMENT.test(value))
1839
+ return undefined;
1840
+ if (key.toLowerCase() === "pwd" && PWD_PATH.test(value))
1841
+ return undefined;
1842
+ // ADO runs an unquoted value over its blanks to its `;`, a tab or its line's end, an escaped one too
1843
+ // (`Password=Copper lumen x;`), its trailing blanks left out: read on when a blank follows the bare value (rulings
1844
+ // LXVIII, LXXXIII).
1845
+ let end = hit.end;
1846
+ if (ado && blankAfter && end === matched)
1847
+ end += text.slice(end, stop).trimEnd().length;
1848
+ // A connection string is config's, unless code's evidence stands (a keyword argument: `connect(password=pw)`).
1849
+ const before = m.index - from <= 320 ? text.slice(from, m.index) : "";
1850
+ const out = { ...hit, end };
1851
+ return codeSlot || codeEvidence(before, key, text.slice(hit.start, end), spaced) ? out : { ...out, code: false };
1852
+ };
1853
+ };
1854
+ /** A query string's or a form body's password (rulings LXI b, LXXI): after `?` or `&`, any length (url-credential's
1855
+ * 16-character least holds for its other names). The key's last name is password, passwd or pwd, after other name
1856
+ * segments maybe (`new_password`, `current_password`) or before `_confirmation` (Rails'); a form's nested key holds it
1857
+ * bracketed, as typed or percent-encoded (`user[password]`, `user%5Bpassword%5D`), and opens anywhere a word does (the
1858
+ * text's start, a blank, a quote: `curl -d "user[password]=..."`). The value (group 2) runs to a blank or the next `&`;
1859
+ * queryPassword ends it where its argument ends, and reads one QUERY_VALUE_MAX stopped on to its run's end. */
1860
+ const QUERY_VALUE_MAX = 1024;
1861
+ const QUERY_VALUE_STOP = /[\s&]/;
1862
+ const QUERY_PASSWORD = new RegExp(String.raw `(?:(?<=[?&])|(?<![^\s"'])(?=[A-Za-z0-9_-]{1,64}(?:\[|%5B)))(?:[A-Za-z0-9_-]{1,64}(?:\[|%5B)(?:[A-Za-z0-9_-]{1,64}(?:\]|%5D)(?:\[|%5B)){0,4})?((?:[A-Za-z0-9]{1,32}[_-]){0,4}(?:password|passwd|pwd)(?:[_-]confirmation)?)(?:\]|%5D)?=([^\s&]{1,${QUERY_VALUE_MAX}})`, "dgi");
1863
+ /** The characters that open an argument's part, each with the one that closes it. */
1864
+ const ARGUMENT_CLOSERS = { '"': '"', "'": "'", "\x60": "\x60", "(": ")", "[": "]", "<": ">", "{": "}" };
1865
+ /** How far back from a key its argument's start is read (ruling LXXI): a longer argument's opener is missed, its value
1866
+ * read to the next blank, an over-cut a string's end still bounds (ruling XLIX). */
1867
+ const ARGUMENT_BACK = 512;
1868
+ const ARGUMENT_DEPTH = 64;
1869
+ /** The closers of the parts left open at each key of a text, innermost last, read left to right once (ruling LXXI): from
1870
+ * the argument's start (the last blank before the first key, at most ARGUMENT_BACK back; every blank after starts
1871
+ * another), each quote opening or closing its own kind, each bracket opening its kind and each closer closing the
1872
+ * innermost part it closes. Keys are asked in rising order; one asked before the last restarts the read. */
1873
+ function argumentClosers(text) {
1874
+ let pos = -1;
1875
+ let open = [];
1876
+ return (at) => {
1877
+ if (pos < 0 || at < pos) {
1878
+ pos = at;
1879
+ while (pos > 0 && at - pos < ARGUMENT_BACK && text.charCodeAt(pos - 1) > 32)
1880
+ pos--;
1881
+ open = [];
1882
+ }
1883
+ for (; pos < at; pos++) {
1884
+ const c = text.charAt(pos);
1885
+ if (text.charCodeAt(pos) <= 32)
1886
+ open = [];
1887
+ else if (open.at(-1) === c)
1888
+ open.pop();
1889
+ else if (ARGUMENT_CLOSERS[c] !== undefined && open.length < ARGUMENT_DEPTH)
1890
+ open.push(ARGUMENT_CLOSERS[c]);
1891
+ }
1892
+ return open.slice();
1893
+ };
1894
+ }
1895
+ const QUOTE_CLOSERS = new Set(['"', "'", "\x60"]);
1896
+ /** What may follow a bracket that ends its argument, to the value's blank or `&` (ruling LXXVIII): more closers, then a
1897
+ * sentence's punctuation maybe (`(see …?password=x).`). A bracket followed by more of the word is the URL's own. */
1898
+ const ARGUMENT_TAIL = /^[)\]}>"'\x60]{1,8}[.,;:!?]{0,3}$/;
1899
+ /** Where a value an argument holds ends (ruling LXXVIII), as an offset in it, or -1 (to its blank or `&`). Inside a
1900
+ * quote the innermost quote decides: a bracket opened in it may be the string's own (a URL's `(`), and its quote cannot
1901
+ * stand in it unescaped; a `)` before that quote is cut with the value, since it may be the value's last character.
1902
+ * With no quote open a bracket's closer ends the value only where it ends the argument too (ARGUMENT_TAIL); else the
1903
+ * next bracket out is asked, and with none the value runs on: an undecided end is cut. */
1904
+ function argumentEnd(value, open) {
1905
+ for (let at = open.length - 1; at >= 0; at--) {
1906
+ if (QUOTE_CLOSERS.has(open[at]))
1907
+ return value.indexOf(open[at]);
1908
+ }
1909
+ for (let at = open.length - 1; at >= 0; at--) {
1910
+ const cut = value.indexOf(open[at]);
1911
+ if (cut >= 0 && ARGUMENT_TAIL.test(value.slice(cut)))
1912
+ return cut;
1913
+ }
1914
+ return -1;
1915
+ }
1916
+ /** A query's or form's password (rulings LXXI, LXXVIII): its value to a blank, the next `&` or where the part its
1917
+ * argument left open before the key ends (argumentEnd), never at a character a value holds (`'`, `\`, `[`, `#`, `<`
1918
+ * with no part open). After `?` or `&` it is a URL's or a form's literal; a bracketed key opening a word elsewhere
1919
+ * reads code's shapes as code's (`form[password]=newPassword`). */
1920
+ const queryPassword = (text) => {
1921
+ const closers = argumentClosers(text);
1922
+ // The end of the run a value stopped at QUERY_VALUE_MAX was last read on to (Greptile P1 on 683391d4fd: a 1500-character
1923
+ // `new_password` kept its last 476). A value starting inside that run (a `?password=` the run itself holds) is read to
1924
+ // the bound only, as before, so each run is read on once: linear in the text.
1925
+ let read = -1;
1926
+ return (m) => {
1927
+ const start = m.indices[2][0];
1928
+ let valueEnd = m.indices[2][1];
1929
+ if (m[2].length === QUERY_VALUE_MAX && m.index >= read) {
1930
+ while (valueEnd < text.length && !QUERY_VALUE_STOP.test(text.charAt(valueEnd)))
1931
+ valueEnd++;
1932
+ read = valueEnd;
1933
+ }
1934
+ const cut = argumentEnd(text.slice(start, valueEnd), closers(m.index));
1935
+ const end = cut < 0 ? valueEnd : start + cut;
1936
+ if (end <= start)
1937
+ return undefined;
1938
+ if (m[1].toLowerCase().endsWith("pwd") && PWD_PATH.test(text.slice(start, end)))
1939
+ return undefined;
1940
+ const query = m.index > 0 && "?&".includes(text.charAt(m.index - 1));
1941
+ return query ? { start, end, name: m[1], quoted: true } : { start, end, name: m[1] };
1942
+ };
1943
+ };
1944
+ /** A k8s Secret's values (ruling LXII b): each key's under its `data:` (base64) or `stringData:` map, the key any name a
1945
+ * Secret takes (`tls.key`, `.dockerconfigjson`, `db-url`), in a YAML document whose `kind:` is Secret (between `---`
1946
+ * lines), or a JSON one (`"kind": "Secret"` in the text, `kubectl get secret -o json`). A block scalar's (`key: |`)
1947
+ * lines are each cut. */
1948
+ const K8S_SECRET_KIND = /^[ \t]{0,8}kind:[ \t]{1,3}(["']?)Secret\1[ \t]{0,8}(?:#[^\n]{0,1024})?$/;
1949
+ const YAML_DOC_START = /^(?:---|\.\.\.)(?:[ \t]|$)/;
1950
+ const K8S_DATA = /^([ \t]{0,32})(?:data|stringData):[ \t]{0,8}(?:#[^\n]{0,1024})?$/;
1951
+ const K8S_ENTRY = /^([ \t]{1,64})(["']?)([A-Za-z0-9._-]{1,253})\2:(?:[ \t]{1,8}([^\n]{0,65536}))?$/d;
1952
+ const BLOCK_SCALAR = /^[|>][+-]?[1-9]?[ \t]{0,8}(?:#[^\n]{0,1024})?$/;
1953
+ const QUOTED_WHOLE = /^(["'])([^\n]{0,65536})\1$/;
1954
+ const K8S_SECRET_JSON = /"kind"[ \t]{0,8}:[ \t]{0,8}"Secret"/;
1955
+ const K8S_DATA_JSON = /"(?:data|stringData)"[ \t\r\n]{0,64}:[ \t\r\n]{0,64}\{/g;
1956
+ const K8S_ENTRY_JSON = /[ \t\r\n]{0,64}"([^"\\\n]{1,253})"[ \t\r\n]{0,64}:[ \t\r\n]{0,64}"((?:[^"\\\n]|\\[^\n]){0,65536})"[ \t\r\n]{0,64},?/dy;
1957
+ const indentOf = (body) => body.length - body.trimStart().length;
1958
+ /** A line's body's start in the text (linesOf drops a numbered lead from the body). */
1959
+ const bodyAt = (line) => line.end - line.body.length;
1960
+ /** A unified diff's evidence in a text (ruling LXXV): a hunk's header, or a line a `+` opens (YAML opens none with it). */
1961
+ const DIFF_EVIDENCE = /^(?:@@ -\d{1,9}|\+)/;
1962
+ /** A diff line's `+` or `-` marker, never a file's header (`--- a/x`, `+++ b/x`) nor a YAML document's `---`. */
1963
+ const DIFF_MARKER = /^[+-](?!(?:--|\+\+)(?:[ \t]|$))/;
1964
+ /** A diff's file header: another file's lines start after it. */
1965
+ const DIFF_FILE_HEADER = /^(?:diff --git|\+\+\+)[ \t]/;
1966
+ /** `text`'s lines as the k8s reader reads them: in a diff (ruling LXXV), each line's marker column (` ` a context line's,
1967
+ * `+`, `-`) read as a blank, so a hunk's lines keep the indentation they have in the file whichever marker each has;
1968
+ * a document starts at a file's header or at a `---` under any marker. */
1969
+ function k8sLines(text) {
1970
+ const read = linesOf(text);
1971
+ if (!read.some((line) => DIFF_EVIDENCE.test(line.body)))
1972
+ return { lines: read, docStart: (row) => YAML_DOC_START.test(read[row].body) };
1973
+ const lines = read.map((line) => (DIFF_MARKER.test(line.body) ? { ...line, body: ` ${line.body.slice(1)}` } : line));
1974
+ const docStart = (row) => {
1975
+ const body = lines[row].body;
1976
+ return YAML_DOC_START.test(read[row].body) || DIFF_FILE_HEADER.test(read[row].body) || (body.charAt(0) === " " && YAML_DOC_START.test(body.slice(1)));
1977
+ };
1978
+ return { lines, docStart };
1979
+ }
1980
+ function k8sSecretValues(text) {
1981
+ const out = [];
1982
+ const { lines, docStart } = k8sLines(text);
1983
+ for (let doc = 0; doc < lines.length;) {
1984
+ let next = doc + 1;
1985
+ while (next < lines.length && !docStart(next))
1986
+ next++;
1987
+ if (lines.slice(doc, next).some((line) => K8S_SECRET_KIND.test(line.body))) {
1988
+ for (let at = doc; at < next; at++) {
1989
+ const data = K8S_DATA.exec(lines[at].body);
1990
+ if (!data)
1991
+ continue;
1992
+ const base = data[1].length;
1993
+ let child;
1994
+ for (let row = at + 1; row < next; row++) {
1995
+ const line = lines[row];
1996
+ if (blank(line))
1997
+ continue;
1998
+ const indent = indentOf(line.body);
1999
+ if (indent <= base)
2000
+ break;
2001
+ const entry = K8S_ENTRY.exec(line.body);
2002
+ if (!entry || (child !== undefined && indent !== child))
2003
+ continue;
2004
+ child = indent;
2005
+ const name = entry[3];
2006
+ const value = entry[4]?.trimEnd() ?? "";
2007
+ if (BLOCK_SCALAR.test(value)) {
2008
+ for (; row + 1 < next && (blank(lines[row + 1]) || indentOf(lines[row + 1].body) > indent); row++) {
2009
+ const inner = lines[row + 1];
2010
+ if (!blank(inner))
2011
+ out.push({ start: bodyAt(inner) + indentOf(inner.body), end: inner.end, name, quoted: true });
2012
+ }
2013
+ continue;
2014
+ }
2015
+ if (value === "")
2016
+ continue;
2017
+ const start = bodyAt(line) + entry.indices[4][0];
2018
+ const quoted = QUOTED_WHOLE.exec(value);
2019
+ out.push(quoted ? { start: start + 1, end: start + 1 + quoted[2].length, name, quoted: true } : { start, end: start + value.length, name, quoted: true });
2020
+ }
2021
+ }
2022
+ }
2023
+ doc = next;
2024
+ }
2025
+ if (K8S_SECRET_JSON.test(text)) {
2026
+ for (const data of text.matchAll(K8S_DATA_JSON)) {
2027
+ K8S_ENTRY_JSON.lastIndex = data.index + data[0].length;
2028
+ for (let entry = K8S_ENTRY_JSON.exec(text); entry; entry = K8S_ENTRY_JSON.exec(text)) {
2029
+ const [start, end] = entry.indices[2];
2030
+ if (end > start)
2031
+ out.push({ start, end, name: entry[1], quoted: true });
2032
+ }
2033
+ }
2034
+ }
2035
+ return out;
2036
+ }
2037
+ /** A kubeconfig's key data (ruling LXII b): `client-key-data:` and any other `*-key-data` key, YAML or JSON. Its `token:`
2038
+ * and `password:` are secret-assign's names already. */
2039
+ const KUBE_KEY_DATA = new RegExp(String.raw `(?<![\w.-])(["']?)([A-Za-z0-9-]{0,64}key-data)\1[ \t]{0,3}:[ \t]{0,3}${VALUE}`, "dg");
2040
+ /** A docker config's registry credentials (ruling LXII c): `"auth"` (base64 of user:password), `"identitytoken"` and
2041
+ * `"registrytoken"`, under an `"auths"` map before them in the text, or in a read of a `config.json` (the call's path
2042
+ * or a path its command names). */
2043
+ const DOCKER_AUTH = /"(auth|identitytoken|registrytoken)"[ \t]{0,8}:[ \t]{0,8}"([^"\\\n]{1,4096})"/dg;
2044
+ const DOCKER_AUTHS = '"auths"';
2045
+ const DOCKER_CONFIG = /(?:^|[\\/])config\.json$/;
2046
+ const DOCKER_AUTHS_BEFORE = 65_536;
2047
+ /** Each `"auths"` in the text and whether the call read a config.json are found once a text (ruling LXXIII), never
2048
+ * once a match: a text of many `"auth"` keys is read in linear time. */
2049
+ const dockerAuth = (text, ctx) => {
2050
+ const read = [ctx.path, ...commandPaths(ctx.command)].some((path) => path !== undefined && DOCKER_CONFIG.test(path));
2051
+ const auths = [];
2052
+ if (!read)
2053
+ for (let at = text.indexOf(DOCKER_AUTHS); at >= 0; at = text.indexOf(DOCKER_AUTHS, at + 1))
2054
+ auths.push(at);
2055
+ return (m) => {
2056
+ if (!read) {
2057
+ // The last `"auths"` at or before the match.
2058
+ const before = placeBefore(auths, m.index + 1);
2059
+ if (before < 0 || m.index - auths[before] > DOCKER_AUTHS_BEFORE)
2060
+ return undefined;
2061
+ }
2062
+ const [start, end] = m.indices[2];
2063
+ return { start, end, name: m[1], quoted: true };
2064
+ };
2065
+ };
2066
+ const SSHPASS = new RegExp(String.raw `\bsshpass[ \t]{1,3}-p[ \t]{0,3}${VALUE}`, "gd");
2067
+ /** A mysql-family command, read to its end (commandEnd); its `-p<pw>` read inside (no blank after
2068
+ * `-p`: `-p word` prompts for the password and names a database, ruling D). */
2069
+ const MYSQL_COMMAND = /\b(?:mysql|mysqldump|mysqladmin|mysqlimport|mysqlshow|mysqlcheck|mysqlsh|mariadb|mariadb-dump|mariadb-admin)(?=[ \t])/g;
2070
+ const MYSQL_P = new RegExp(String.raw `(?<=[ \t])-p${VALUE}`, "gd");
2071
+ /** --password=<pw> or --password <pw>, and the same of --*-password, --passwd, --token, --api-key and kin. */
2072
+ const PASSWORD_FLAG = new RegExp(String.raw `(?<![A-Za-z0-9-])(--(?:[a-z0-9]{1,20}-){0,3}(?:password|passwd|pass|token|api-key|apikey|auth-token|secret-key|access-key))(?:=|[ \t]{1,3}(?!-))${VALUE}`, "gdi");
2073
+ /** A registry login (`docker login -p <pw>`), redis-cli's `-a <pw>`: each command read to its end (commandEnd), its
2074
+ * short password flag inside. */
2075
+ const LOGIN_COMMAND = /\b(?:docker|podman|nerdctl|buildah|skopeo)[ \t]{1,3}login\b/g;
2076
+ const LOGIN_P = new RegExp(String.raw `(?<=[ \t])(-p)(?:=|[ \t]{1,3})${VALUE}`, "gd");
2077
+ const REDIS_COMMAND = /\bredis-cli\b/g;
2078
+ const REDIS_A = new RegExp(String.raw `(?<=[ \t])(-a)[ \t]{1,3}${VALUE}`, "gd");
2079
+ /** openssl's `-passin pass:<pw>` (and -passout, -pass, -k pass:): the password after `pass:`. */
2080
+ const OPENSSL_PASS = /(?<![A-Za-z0-9-])(-(?:passin|passout|pass|k))[ \t]{1,3}(["']?)pass:([^\s"']{1,1024})\2/dg;
2081
+ /** A .netrc line: `machine <host>` (or `default`), maybe `login`/`account`, then `password <pw>`. */
2082
+ const NETRC = /(?:\bmachine[ \t]{1,3}[^\s]{1,256}|\bdefault)(?:[ \t]{1,3}(?:login|account)[ \t]{1,3}[^\s]{1,256}){0,2}[ \t]{1,3}(password)[ \t]{1,3}([^\s]{1,1024})/dg;
2083
+ /** A flag's value: a slot code does not fill (ruling XII). */
2084
+ const flagValue = (hit) => (hit ? { ...hit, code: false } : undefined);
2085
+ function passwordFlags(text) {
2086
+ return [
2087
+ ...each(text, PASSWORD_FLAG, (m) => flagValue(valueHit(m, 2, 3, m[1]))),
2088
+ ...inside(text, LOGIN_COMMAND, LOGIN_P, (m) => flagValue(valueHit(m, 2, 1, m[1]))),
2089
+ ...inside(text, REDIS_COMMAND, REDIS_A, (m) => flagValue(valueHit(m, 2, 1, m[1]))),
2090
+ ...each(text, OPENSSL_PASS, (m) => ({ start: m.indices[3][0], end: m.indices[3][1], name: m[1], quoted: true })),
2091
+ ...each(text, NETRC, (m) => ({ start: m.indices[2][0], end: m.indices[2][1], name: m[1], quoted: true })),
2092
+ ];
2093
+ }
2094
+ /** The schemes a credential header names before its credential: a scheme alone (`Authorization: Bearer` and nothing
2095
+ * after it) is a header named, no value. */
2096
+ const SCHEMES = String.raw `(?:Bearer|Basic|Token|Bot|ApiKey|Digest|Negotiate|NTLM|AWS4-HMAC-SHA256)`;
2097
+ /** A credential header's value (curl -H, a request dump, a JSON headers object): the scheme kept, the credential cut.
2098
+ * The value is the scheme's credential, or with no scheme a token's characters (ruling D): never a type annotation,
2099
+ * a call, a word of prose. */
2100
+ const AUTH_HEADER = new RegExp(String.raw `(?<![A-Za-z0-9-])((?:Proxy-)?Authorization|X-Api-Key|Api-Key|X-Auth-[A-Za-z0-9-]{1,32}|X-Access-Token|Private-Token|X-Goog-Api-Key)(["']?)[ \t]{0,3}:[ \t]{0,3}(["'\x60]?)(?:(${SCHEMES})[ \t]{1,3})?(?!${SCHEMES}(?![^\s"'\x60\\,]))([A-Za-z0-9._~+/=:-][^\s"'\x60\\,;(){}<>[\]]{0,4095})`, "gdi");
2101
+ const TOKEN_RUN = /^[A-Za-z0-9._~+/=:-]{8,4096}$/;
2102
+ /** What before a header's name makes it a code object's key or a call's argument (ruling III): `{`, `,` or `(`, an
2103
+ * opening quote maybe between. */
2104
+ const CODE_KEY_BEFORE = /[{,(][ \t]{0,4}["']?$/;
2105
+ /** Whether a header name stands as a code key (quoted and followed by its colon, `"Authorization":`, or after `{`, `,`,
2106
+ * `(`) with no string literal after it: then its value is an expression, never cut (ruling III). */
2107
+ const codeKeyWithoutLiteral = (text, m, nameQuote, valueQuote) => !valueQuote && (nameQuote !== "" || CODE_KEY_BEFORE.test(text.slice(Math.max(0, m.index - 8), m.index)));
2108
+ const authHeader = (text) => (m) => {
2109
+ const value = m[5];
2110
+ if (codeKeyWithoutLiteral(text, m, m[2], m[3]))
2111
+ return undefined;
2112
+ if (m[4] !== undefined ? value.length < 4 : !TOKEN_RUN.test(value))
2113
+ return undefined;
2114
+ const [start, end] = m.indices[5];
2115
+ return { start, end, name: m[1] };
2116
+ };
2117
+ /** A Cookie or Set-Cookie header's value whole (its name=value pairs, a Set-Cookie's attributes), to the quote or the
2118
+ * line's end: it needs a `=` to be one. */
2119
+ const COOKIE_HEADER = /(?<![A-Za-z0-9-])((?:Set-)?Cookie)(["']?)[ \t]{0,3}:[ \t]{0,3}(["']?)([^\r\n"'\x60\\]{8,4096})/dgi;
2120
+ const COOKIE_PAIR = /[A-Za-z0-9_.-]=[^\s;]/;
2121
+ /** A Set-Cookie's attributes: no cookie's value. */
2122
+ const COOKIE_ATTRIBUTES = new Set(["path", "domain", "expires", "max-age", "samesite", "secure", "httponly", "priority", "partitioned"]);
2123
+ const COOKIE_SPLIT = /;[ \t]{0,8}/;
2124
+ /** Whether every cookie's value in a header is an expansion or a placeholder (`sid=$SID; csrf=${CSRF}`; ruling XXIII). */
2125
+ const cookiesUnset = (value) => value
2126
+ .split(COOKIE_SPLIT)
2127
+ .map((pair) => [pair.slice(0, pair.indexOf("=")).trim().toLowerCase(), pair.slice(pair.indexOf("=") + 1)])
2128
+ .filter(([name]) => name !== "" && !COOKIE_ATTRIBUTES.has(name))
2129
+ .every(([, each]) => isPlaceholder(each.trim(), { bare: false }));
2130
+ const cookieHeader = (text) => (m) => {
2131
+ const value = m[4].trimEnd();
2132
+ if (codeKeyWithoutLiteral(text, m, m[2], m[3]))
2133
+ return undefined;
2134
+ if (value.length < 8 || !COOKIE_PAIR.test(value) || cookiesUnset(value))
2135
+ return undefined;
2136
+ const start = m.indices[4][0];
2137
+ return { start, end: start + value.length, name: m[1] };
2138
+ };
2139
+ /** A curl command, its continuation lines included, to the shell's end of it (commandEnd with curl: `;`, `|`, `&&`,
2140
+ * `||`, `$(`, a backtick, a line's end, none of them quoted; ruling XXIV); its `-u user:pass` / `--user user:pass`
2141
+ * password read inside. */
2142
+ const CURL_COMMAND = /\bcurl\b/g;
2143
+ const CURL_USER = /(?<=\s)(?:-u[ \t]{0,3}|--user(?:=|[ \t]{1,3}))(?:(["'])[^\s:"']{0,256}:([^"'\n]{1,512})\1|[^\s:"']{0,256}:([^\s"']{1,512}))/gd;
2144
+ const curlUser = (m) => {
2145
+ const [start, end] = m.indices[m[2] !== undefined ? 2 : 3];
2146
+ return { start, end, name: "user", quoted: true };
2147
+ };
2148
+ /** A line-numbered read's prefix (cat -n, a Read tool's " 12→", grep -n's `path:12:`: LINE_LEAD's numbered leads,
2149
+ * ruling XXVII; a diff's `+`/`-` is not dropped, a PEM line opens with `-`), dropped before a line's shape is read. A JSON
2150
+ * string's quotes are not of its lines either (a text kept as one JSON string reads `"$ env` on its first line and
2151
+ * `$ ls"` on its last): linesOf leaves the quotes of a text that opens and closes with one out of its lines, so a dump
2152
+ * never takes them. */
2153
+ const NUMBERED = new RegExp(`^(?:${NUMBER_LEAD})`);
2154
+ /** A JSON object's field opening a line (`{"stdout":"$ env`: a record decoded whole, its string's escaped line breaks
2155
+ * read as lines): up to the last `":"` of a line that opens with `{`, `[` or `,` (its quotes blanks where a decoded view
2156
+ * blanked its string's delimiters), not of the line's own text. */
2157
+ const JSON_FIELD_OPEN = /^[ \t]{0,8}[{[,][^\n]{0,4096}[" \t]{1,4}:[" \t]{1,4}/;
2158
+ let linesCache;
2159
+ /** `text`'s lines, each with its span (no line break, no quote opening or closing the text) and its body (a numbered
2160
+ * prefix and a CR dropped too). */
2161
+ function linesOf(text) {
2162
+ if (linesCache?.text === text)
2163
+ return linesCache.lines;
2164
+ const lines = [];
2165
+ // A text that opens and closes with a quote is read as one JSON string: its quotes are not of its first and last line.
2166
+ const quoted = text.length >= 2 && text.charAt(0) === '"' && text.charAt(text.length - 1) === '"' ? 1 : 0;
2167
+ for (let start = 0; start <= text.length;) {
2168
+ const at = text.indexOf("\n", start);
2169
+ const stop = at < 0 ? text.length : at;
2170
+ let end = stop;
2171
+ // A line's span ends at its last character that is not a blank or a CR: a dump never takes the blank a decoded
2172
+ // view reads in place of its string's closing quote.
2173
+ while (end > start && " \t\r".includes(text.charAt(end - 1)))
2174
+ end--;
2175
+ let from = start;
2176
+ if (from === 0)
2177
+ from += quoted;
2178
+ if (stop === text.length)
2179
+ end = Math.max(from, end - quoted);
2180
+ const field = JSON_FIELD_OPEN.exec(text.slice(from, end));
2181
+ if (field)
2182
+ from += field[0].length;
2183
+ lines.push({ start: from, end: Math.max(from, end), body: text.slice(from, end).replace(NUMBERED, "") });
2184
+ start = stop + 1;
2185
+ }
2186
+ linesCache = { text, lines };
2187
+ return lines;
2188
+ }
2189
+ const blank = (line) => line.body.trim() === "";
2190
+ const block = (lines, from, to) => ({ start: lines[from].start, end: lines[to].end });
2191
+ /** The lines after `at` while `fits` holds, trailing blank lines left out; undefined when none is left. */
2192
+ function after(lines, at, fits) {
2193
+ let to = at;
2194
+ while (to + 1 < lines.length && fits(lines[to + 1].body))
2195
+ to++;
2196
+ while (to > at && blank(lines[to]))
2197
+ to--;
2198
+ return to > at ? block(lines, at + 1, to) : undefined;
2199
+ }
2200
+ /** A shell's prompt opening a line: the next command, where a file's printed contents end. */
2201
+ const PROMPT_LINE = /^\s{0,8}(?:[$#%❯]|>>?)\s{1,3}\S/;
2202
+ const notPrompt = (body) => !PROMPT_LINE.test(body);
2203
+ /** A line that is a dump's cut already made: no file's content (ruling VIII: a cut text read again is cut no more). */
2204
+ const DUMP_MARKER_LINE = /^\s{0,8}\[redacted:[a-z0-9-]{1,64}(?: \d{1,9} lines)?\]\s{0,8}$/;
2205
+ const notMarker = (body) => !DUMP_MARKER_LINE.test(body);
2206
+ /** A line of env, printenv, set or export -p output: NAME=value, maybe after `declare -x ` or `export `. */
2207
+ const ENV_LINE = /^(declare -x |export )?([A-Za-z_][A-Za-z0-9_]{0,127})=/;
2208
+ /** The command that prints one, alone on its line (a prompt before it, a pipe after it). */
2209
+ const ENV_COMMAND = /^\s{0,8}(?:(?:[$#%>❯]|[A-Za-z]:\\[^>\n]{0,256}>)\s{0,3})?(?:sudo\s{1,3})?(?:env|printenv|set|export\s{1,3}-p|declare\s{1,3}-p?x|compgen\s{1,3}-v)(?:\s{0,3}\|[^\n]{0,200})?\s{0,8}$/;
2210
+ /** printenv of named variables, or an echo of one key-shaped variable: the lines after it are their values. */
2211
+ const PRINTENV_NAMES = /^\s{0,8}(?:[$#%>❯]\s{0,3})?(?:sudo\s{1,3})?printenv((?:[ \t]{1,3}[A-Za-z_][A-Za-z0-9_]{0,127}){1,16})\s{0,8}$/;
2212
+ const ECHO_VARIABLE = /^\s{0,8}(?:[$#%>❯]\s{0,3})?echo[ \t]{1,3}(["']?)\$\{?([A-Za-z_][A-Za-z0-9_]{0,127})\}?\1\s{0,8}$/;
2213
+ const NAME_RUN = /[A-Za-z_][A-Za-z0-9_]{0,127}/g;
2214
+ /** Names every login environment has: two among a block of eight lines or more (not `export` lines, which a script
2215
+ * writes) make it a dump with no command before it (ruling G). */
2216
+ const ENV_NAMES = new Set(["PATH", "HOME", "SHELL", "USER", "PWD", "LANG"]);
2217
+ const ENV_UNCOMMANDED_LINES = 8;
2218
+ /** NAME=value lines in a row printed by an env command on the line before (a blank between allowed), any number of
2219
+ * them; eight or more holding two login names; or all `declare -x` lines (export -p's own output, its command's mark).
2220
+ * And the values printenv NAME... or echo $KEY prints, one line a name. */
2221
+ function envDumps(text) {
2222
+ const lines = linesOf(text);
2223
+ const out = [];
2224
+ for (let at = 0; at < lines.length;) {
2225
+ const body = lines[at].body;
2226
+ const named = PRINTENV_NAMES.exec(body);
2227
+ const echoed = ECHO_VARIABLE.exec(body);
2228
+ if (named || (echoed && secretName(echoed[2]))) {
2229
+ const count = named ? named[1].match(NAME_RUN).length : 1;
2230
+ let to = at;
2231
+ while (to + 1 < lines.length && to - at < count && !blank(lines[to + 1]) && notPrompt(lines[to + 1].body) && notMarker(lines[to + 1].body))
2232
+ to++;
2233
+ if (to > at)
2234
+ out.push(block(lines, at + 1, to));
2235
+ at = to + 1;
2236
+ continue;
2237
+ }
2238
+ if (!ENV_LINE.test(body)) {
2239
+ at++;
2240
+ continue;
2241
+ }
2242
+ let to = at;
2243
+ while (to + 1 < lines.length && ENV_LINE.test(lines[to + 1].body))
2244
+ to++;
2245
+ const shapes = lines.slice(at, to + 1).map((line) => ENV_LINE.exec(line.body));
2246
+ const before = at > 1 && blank(lines[at - 1]) ? lines[at - 2] : lines[at - 1];
2247
+ const commanded = before !== undefined && ENV_COMMAND.test(before.body);
2248
+ const login = to - at + 1 >= ENV_UNCOMMANDED_LINES && new Set(shapes.filter((m) => m[1] !== "export ").map((m) => m[2]).filter((name) => ENV_NAMES.has(name))).size >= 2;
2249
+ const declared = to - at + 1 >= 3 && shapes.every((m) => m[1] === "declare -x ");
2250
+ if (commanded || login || declared)
2251
+ out.push(block(lines, at, to));
2252
+ at = to + 1;
2253
+ }
2254
+ return out;
2255
+ }
2256
+ /** A command (or a Read tool's line) that prints one file, alone on its line: the path is group 2 (group 1 of the tool). */
2257
+ const READ_COMMAND = /^\s{0,8}(?:[$#%>❯]\s{0,3})?(?:sudo\s{1,3})?(?:cat|less|more|head|tail|bat|batcat|nl|type|Get-Content|gc)(?:\s{1,3}-{1,2}[A-Za-z0-9=-]{1,24}(?:\s{1,3}\d{1,6})?){0,4}\s{1,3}(["']?)([^\s"']{1,512})\1\s{0,8}$/;
2258
+ const READ_TOOL = /^\s{0,8}(?:⏺\s{0,2})?Read\(([^()\s]{1,512})\)\s{0,8}$/;
2259
+ const readPath = (body) => READ_COMMAND.exec(body)?.[2] ?? READ_TOOL.exec(body)?.[1];
2260
+ /** The file a command prints whole, when it is one read alone (`cat ~/.pgpass`): its output is that file's content
2261
+ * (ruling LVI). */
2262
+ export const commandReadPath = (command) => (command === undefined ? undefined : readPath(command));
2263
+ /** envDumps with `command` as the line before the text (ruling LVI): the output of `env`, `printenv NAME` or
2264
+ * `echo $KEY`, given apart from its command, is cut as it is when the command stands in the text. */
2265
+ function commandDumps(text, command) {
2266
+ if (command === undefined || command.trim() === "")
2267
+ return [];
2268
+ const shift = command.length + 1;
2269
+ return envDumps(`${command}\n${text}`).filter((hit) => hit.end > shift).map((hit) => ({ ...hit, start: Math.max(hit.start - shift, 0), end: hit.end - shift }));
2270
+ }
2271
+ const PATH_SEPARATOR = /[\\/]/;
2272
+ const ENV_FILE_NAME = /^(?:\.env(?:rc)?|\.env\.[A-Za-z0-9_.-]{1,64}|[A-Za-z0-9_.-]{1,64}\.env)$/;
2273
+ const ENV_TEMPLATE = /\.(?:example|sample|template|tmpl|dist|defaults?|schema)$/i;
2274
+ /** A .env file's path: .env, .envrc, .env.<name>, <name>.env; never a template (.env.example, .sample, ...). */
2275
+ export const envFilePath = (path) => {
2276
+ const base = path.split(PATH_SEPARATOR).pop() ?? "";
2277
+ return ENV_FILE_NAME.test(base) && !ENV_TEMPLATE.test(base);
2278
+ };
2279
+ const SSH_FILE = /(?:^|[\\/])\.ssh[\\/][^\\/]{1,512}$/;
2280
+ /** A path under a .ssh folder. */
2281
+ export const sshFilePath = (path) => SSH_FILE.test(path);
2282
+ /** A file of credentials, path-anchored like ~/.ssh's: .netrc (_netrc), .pgpass (pgpass.conf on Windows, under
2283
+ * %APPDATA%\postgresql), .git-credentials, .pypirc, .npmrc, .my.cnf, .vault-token, ~/.aws/credentials, a docker config
2284
+ * (~/.docker/config.json), a kubeconfig (~/.kube/config, kubeconfig, *.kubeconfig). Ruling LXXVII added pgpass.conf
2285
+ * and the four after .pypirc, the lead's list, no more. */
2286
+ const CREDENTIAL_FILE = /(?:^|[\\/])(?:[._]netrc|\.pgpass|pgpass\.conf|\.git-credentials|\.pypirc|\.npmrc|\.my\.cnf|\.vault-token|\.aws[\\/]credentials|\.docker[\\/]config\.json|\.kube[\\/]config|[A-Za-z0-9_.-]{0,64}kubeconfig(?:\.ya?ml)?)$/i;
2287
+ /** A variable that names a credential file by that file's own name (ruling LXXVII): `$PGPASSFILE`, `${PGPASSFILE}`
2288
+ * (libpq's override of ~/.pgpass), `$NETRC_FILE`. Its name less a trailing `FILE` or `_FILE`, as a dotted base name,
2289
+ * is one CREDENTIAL_FILE names. */
2290
+ const FILE_VARIABLE = /^\$\{?([A-Za-z_][A-Za-z0-9_]{0,63}?)_?FILE\}?$/i;
2291
+ export const credentialFilePath = (path) => {
2292
+ if (CREDENTIAL_FILE.test(path))
2293
+ return true;
2294
+ const variable = FILE_VARIABLE.exec(path);
2295
+ return variable !== null && CREDENTIAL_FILE.test(`/.${variable[1].toLowerCase()}`);
2296
+ };
2297
+ /** A .env file's line: blank, a comment, or NAME=value (maybe after `export `). */
2298
+ const ENV_FILE_LINE = /^\s{0,8}(?:#.*|(?:export\s{1,3})?[A-Za-z_][A-Za-z0-9_.-]{0,127}\s{0,3}=.*|)$/;
2299
+ /** A key line of authorized_keys, known_hosts or a .pub file: up to two fields before (options, host names), the key
2300
+ * type, its base64 (group 1), a comment. */
2301
+ const KEY_LINE = /^(?:\S{1,1024}[ \t]{1,3}){0,2}(?:ssh-(?:rsa|dss|ed25519)|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)(?:-cert-v01@openssh\.com)?[ \t]{1,3}(AAAA[A-Za-z0-9+/]{1,16384}={0,3})(?:[ \t].{0,1024})?$/;
2302
+ const SSH_CONFIG = /^\s{0,8}(?:Host|Match|HostName|User|Port|IdentityFile|IdentitiesOnly|IdentityAgent|ProxyCommand|ProxyJump|ForwardAgent|AddKeysToAgent|UseKeychain|StrictHostKeyChecking|UserKnownHostsFile|GlobalKnownHostsFile|ServerAliveInterval|ServerAliveCountMax|LocalForward|RemoteForward|DynamicForward|Include|PreferredAuthentications|PubkeyAuthentication|PasswordAuthentication|LogLevel|ControlMaster|ControlPath|ControlPersist|Compression|HostKeyAlias|HostKeyAlgorithms|SendEnv|SetEnv|CertificateFile|KexAlgorithms|Ciphers|MACs|ConnectTimeout|RequestTTY|RemoteCommand|CanonicalizeHostname|VisualHostKey|HashKnownHosts|ExitOnForwardFailure|BatchMode|TCPKeepAlive)(?:\s|=)/i;
2303
+ const COMMENT_LINE = /^\s{0,8}#/;
2304
+ const PEM_LINE = /^-----(?:BEGIN|END) [A-Z0-9 ]{1,48}-----\s{0,8}$/;
2305
+ const BASE64_LINE = /^[A-Za-z0-9+/=]{1,128}\s{0,8}$/;
2306
+ const PEM_HEADER_LINE = /^(?:Proc-Type|DEK-Info|Comment):/;
2307
+ const sshLine = (body) => body.trim() === "" || COMMENT_LINE.test(body) || SSH_CONFIG.test(body) || (body.length <= 20_000 && KEY_LINE.test(body)) || PEM_LINE.test(body) || BASE64_LINE.test(body) || PEM_HEADER_LINE.test(body);
2308
+ /** The text whole, its trailing blanks left out, when the caller says it is the content of a file `fits` names. */
2309
+ /** The words of a call's command that may name a file: split at blanks and shell operators, an option's `--name=` and
2310
+ * a word's quotes dropped, wherever they stand in it as the shell removes them (`grep app ~/.pgpass`,
2311
+ * `jq . "$HOME/.docker/config.json"`, `--env-file=.env`, `cat ~/'.pgpass'`, ruling LXXVII). */
2312
+ const COMMAND_WORD_SPLIT = /[\s|;&<>()]{1,64}/;
2313
+ const OPTION_NAME = /^-{1,2}[A-Za-z0-9-]{1,64}=/;
2314
+ const WORD_QUOTES = /["']/g;
2315
+ const COMMAND_MAX = 65_536;
2316
+ export const commandPaths = (command) => command === undefined ? [] : command.slice(0, COMMAND_MAX).split(COMMAND_WORD_SPLIT).map((word) => word.replace(OPTION_NAME, "").replace(WORD_QUOTES, "")).filter(Boolean);
2317
+ /** The text whole, its trailing blanks left out, when the caller says it is the content of a file `fits` names: the call
2318
+ * read that file (`ctx.path`), or its command names one anywhere (ruling LXII d: `grep app ~/.pgpass`, `jq . ~/.docker/
2319
+ * config.json`, `grep -v ^# .env`; an over-cut, `ls ~/.ssh/known_hosts`'s, fails closed). */
2320
+ const wholeText = (text, ctx, fits) => {
2321
+ if (!((ctx.path !== undefined && fits(ctx.path)) || commandPaths(ctx.command).some(fits)) || DUMP_MARKER_LINE.test(text))
2322
+ return [];
2323
+ const end = text.trimEnd().length;
2324
+ return end > 0 ? [{ start: 0, end }] : [];
2325
+ };
2326
+ /** What a read of a file `fits` names printed after it, while each line `line` holds. */
2327
+ function fileReads(text, fits, line) {
2328
+ const lines = linesOf(text);
2329
+ const out = [];
2330
+ for (let at = 0; at < lines.length; at++) {
2331
+ const path = readPath(lines[at].body);
2332
+ if (path === undefined || !fits(path))
2333
+ continue;
2334
+ const hit = after(lines, at, line);
2335
+ if (hit)
2336
+ out.push(hit);
2337
+ }
2338
+ return out;
2339
+ }
2340
+ // ---------- personal
2341
+ /** A home folder's user (ruling VII): the user segment alone of /home/<user>, /Users/<user> and <drive>:\\Users\\<user>,
2342
+ * for every user (the default cloud user and the CI runner's too), is cut, and a cut writes `<user>` in its place, so
2343
+ * a path keeps its shape (only the user segment changes). /root names no one and is never cut. /home/<user> is cut only with a
2344
+ * further path segment after the user or when it is a home the caller holds (ruling E): an app's route
2345
+ * (`/home/settings`, `navigate("/home/feed")`) names no user. Bare /home and /home/ name no user; the folders every
2346
+ * user shares (macOS's /Users/Shared, Windows' Public and Default) are no one's home. A Claude project's folder name
2347
+ * (`-home-<user>-proj`, `-Users-<user>-proj`) holds a home too: its user is cut when the caller holds that home or the
2348
+ * name stands under `.claude/projects/`. */
2349
+ const HOME_UNIX = /(?<![A-Za-z0-9._~-])\/(home|Users)\/([^\s/\\"'`:;,()<>[\]{}|*?$&=%]{1,64})(?=[/\\\s"'`:;,()<>[\]{}|]|$)/dg;
2350
+ const HOME_WINDOWS = /\b[A-Za-z]:(?:\\\\|\\|\/)Users(?:\\\\|\\|\/)([^\s/\\"'`:;,()<>[\]{}|*?$&=%]{1,64})(?=[/\\\s"'`:;,()<>[\]{}|]|$)/dgi;
2351
+ /** A path segment after a folder: a separator, then a character a segment holds. */
2352
+ const SEGMENT_AFTER = /^(?:\/|\\\\?)[^\s/\\"'`:;,()<>[\]{}|]/;
2353
+ const SHARED_HOMES = new Set(["Users/Shared", "win/public", "win/default", "win/all users", "win/default user"]);
2354
+ const TRAILING_SLASHES = /[\\/]{1,64}$/;
2355
+ /** A home's user, of a home the caller holds: /home/<user>, /Users/<user>, <drive>:\\Users\\<user>. */
2356
+ const HOME_USER = /^(?:\/(?:home|Users)|[A-Za-z]:[\\/]{1,2}Users)[\\/]{1,2}([^\\/]{1,64})$/;
2357
+ /** A Claude project's folder name holding a home: `-home-` or `-Users-` opening a path segment, then the rest of it. */
2358
+ const CLAUDE_SLUG = /(?<![A-Za-z0-9._-])-(home|Users)-([A-Za-z0-9._-]{1,256})/dg;
2359
+ const CLAUDE_PROJECTS_BEFORE = /\.claude[\\/]{1,2}projects[\\/]{1,2}$/;
2360
+ const SLUG_OFF_CHARS = /[^A-Za-z0-9-]/g;
2361
+ const SLUG_USER = /^[A-Za-z0-9._]{1,64}/;
2362
+ const userHit = (m, group) => {
2363
+ const [start, end] = m.indices[group];
2364
+ return { start, end };
2365
+ };
2366
+ const homeUnix = (text, homes) => (m) => {
2367
+ if (SHARED_HOMES.has(`${m[1]}/${m[2]}`))
2368
+ return undefined;
2369
+ const end = m.index + m[0].length;
2370
+ if (m[1] !== "Users" && !SEGMENT_AFTER.test(text.slice(end, end + 3)) && !homes.has(m[0]))
2371
+ return undefined;
2372
+ return userHit(m, 2);
2373
+ };
2374
+ const homeWindows = (m) => (SHARED_HOMES.has(`win/${m[1].toLowerCase()}`) ? undefined : userHit(m, 1));
2375
+ const claudeSlug = (text, users) => (m) => {
2376
+ const rest = m[2];
2377
+ let user = users.find((each) => rest === each || rest.startsWith(`${each}-`));
2378
+ if (user === undefined && CLAUDE_PROJECTS_BEFORE.test(text.slice(Math.max(0, m.index - 24), m.index)))
2379
+ user = SLUG_USER.exec(rest)?.[0];
2380
+ if (!user)
2381
+ return undefined;
2382
+ const start = m.indices[2][0];
2383
+ return { start, end: start + user.length };
2384
+ };
2385
+ const homeFolders = (text, ctx) => {
2386
+ const homes = new Set(ctx.homes.map((home) => home.replace(TRAILING_SLASHES, "")));
2387
+ // Each held home's user as a Claude project's folder name writes it (every character but a letter, a digit or `-` a
2388
+ // `-`), the longest first.
2389
+ const users = [...homes].flatMap((home) => HOME_USER.exec(home)?.[1] ?? []).map((user) => user.replace(SLUG_OFF_CHARS, "-")).sort((a, b) => b.length - a.length);
2390
+ return [...each(text, HOME_UNIX, homeUnix(text, homes)), ...each(text, HOME_WINDOWS, homeWindows), ...each(text, CLAUDE_SLUG, claudeSlug(text, users))];
2391
+ };
2392
+ /** An address: a local part, then one to eight labels and a letter TLD. */
2393
+ const EMAIL = /(?<![A-Za-z0-9._%+-])([A-Za-z0-9._%+-]{1,64})@((?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.){1,8}([A-Za-z]{2,24}))(?![A-Za-z0-9-]|\.[A-Za-z0-9])/g;
2394
+ /** TLDs that are a file's extension in practice (logo@2x.png, a scoped import's file). */
2395
+ const FILE_TLDS = new Set(["png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "bmp", "avif", "js", "mjs", "cjs", "ts", "mts", "cts", "tsx", "jsx", "css", "scss", "less", "json", "md", "mdx", "txt", "py", "rb", "go", "rs", "html", "htm", "xml", "yml", "yaml", "toml", "lock", "map", "wasm", "zip", "gz", "tgz", "tar", "pdf", "mp4", "mov", "mp3", "wav", "sh", "ps1", "exe", "dll", "so", "java", "kt", "swift", "vue", "svelte"]);
2396
+ /** The names reserved for examples and tests (RFC 2606, RFC 6761) alone: .local and .internal are names people's own
2397
+ * machines and companies use (item 1). */
2398
+ const RESERVED_TLDS = new Set(["example", "test", "invalid", "localhost"]);
2399
+ const EXAMPLE_DOMAIN = /(?:^|\.)example\.(?:com|org|net)$/;
2400
+ const NO_REPLY_LOCAL = /^(?:no-?reply|do-?not-?reply|donotreply|mailer-daemon|postmaster)$/;
2401
+ const NO_REPLY_DOMAIN = /(?:^|\.)noreply\./;
2402
+ const FORGE_NO_REPLY = /^users\.noreply\./;
2403
+ /** A URL's user with no password (`ssh://deploy@build-01.corp.io`): `://` right before the address. URL_USERINFO reads a
2404
+ * user and a password; a user alone is no address either. */
2405
+ const USER_ONLY_BEFORE = /:\/\/$/;
2406
+ /** A commit trailer's line naming a bot identity before the address (ruling VI): `Signed-off-by: lintbot[bot] <...>`. */
2407
+ const BOT_TRAILER = /(?:^|[\s"'{,])[A-Za-z][A-Za-z-]{1,40}:[ \t][^\n]{0,512}\[bot\]/;
2408
+ /** A local part's grammar (ruling XVII): it starts and ends with a letter or a digit (`+@router.post`, `4021-@pytest`,
2409
+ * `%@domain` are none). Leading punctuation is dropped before it is read, so `<-jane@...` still finds jane. */
2410
+ const LOCAL_LEAD = /^[._%+-]{1,64}/;
2411
+ const LOCAL_END = /[A-Za-z0-9]$/;
2412
+ /** systemd unit types: `getty@tty1.service`, `user@1001.service` name a unit's instance, not an address. */
2413
+ const UNIT_TYPES = new Set(["service", "socket", "timer", "target", "mount", "path", "slice", "device", "scope"]);
2414
+ /** The letter of an escape one level down that a blanked `\\` leaves right before an address (`\\tgit@` read raw: the
2415
+ * `t` is the escape's): its length, 0 when none (ruling XVIII). */
2416
+ const NESTED_ESCAPE = /^(?:[bfnrt/]|u[0-9A-Fa-f]{4})/;
2417
+ function nestedEscape(source, at) {
2418
+ let run = 0;
2419
+ while (run < 64 && at - run - 1 >= 0 && source.charCodeAt(at - run - 1) === 92)
2420
+ run++;
2421
+ if (run < 2 || run % 2)
2422
+ return 0;
2423
+ return NESTED_ESCAPE.exec(source.slice(at, at + 5))?.[0].length ?? 0;
2424
+ }
2425
+ /** The address rule: `userinfos` (from urlUserinfos, sorted) are the URL userinfos url-password reads; an address that
2426
+ * starts inside one is a user's or a password's tail (ruling XLIII), and is none. */
2427
+ const email = (text, source, userinfos) => {
2428
+ const froms = userinfos.map(({ userinfo }) => userinfo[0]);
2429
+ return (m) => emailAt(text, source, m, froms, userinfos);
2430
+ };
2431
+ function emailAt(text, source, m, froms, userinfos) {
2432
+ const skip = nestedEscape(source, m.index);
2433
+ const raw = m[1].slice(skip);
2434
+ const lead = LOCAL_LEAD.exec(raw)?.[0].length ?? 0;
2435
+ const local = raw.slice(lead).toLowerCase();
2436
+ const domain = m[2].toLowerCase();
2437
+ const tld = m[3].toLowerCase();
2438
+ if (local === "" || !LOCAL_END.test(local))
2439
+ return undefined;
2440
+ // A domain a `(` follows is a call's callee (`@pytest.mark.parametrize(`); a unit type's TLD names a systemd unit.
2441
+ if (text.charAt(m.index + m[0].length) === "(" || UNIT_TYPES.has(tld))
2442
+ return undefined;
2443
+ if (local === "git" || local === "hg")
2444
+ return undefined; // an SSH remote's user (git@github.com:org/repo)
2445
+ if (NO_REPLY_LOCAL.test(local))
2446
+ return undefined;
2447
+ // A forge's no-reply address for a person (`12345+login@users.noreply.github.com`) names that person's account, so it
2448
+ // is personal (amendment 2); a bot's (`...+dependabot[bot]@...`) holds a bracket no address here reads, and stays.
2449
+ // Every other no-reply domain is a service's own.
2450
+ if (NO_REPLY_DOMAIN.test(domain) && !FORGE_NO_REPLY.test(domain))
2451
+ return undefined;
2452
+ if (FILE_TLDS.has(tld) || RESERVED_TLDS.has(tld) || EXAMPLE_DOMAIN.test(domain))
2453
+ return undefined;
2454
+ const inside = placeBefore(froms, m.index + 1);
2455
+ if (inside >= 0 && m.index < userinfos[inside].userinfo[1])
2456
+ return undefined;
2457
+ if (USER_ONLY_BEFORE.test(text.slice(Math.max(0, m.index - 3), m.index)))
2458
+ return undefined;
2459
+ // The line before the address (its last 600 characters): a bot's trailer keeps its address.
2460
+ const before = text.slice(Math.max(0, m.index - 600), m.index);
2461
+ if (BOT_TRAILER.test(before.slice(before.lastIndexOf("\n") + 1)))
2462
+ return undefined;
2463
+ return { start: m.index + skip + lead, end: m.index + m[0].length };
2464
+ }
2465
+ const IPV4 = /(?<![\w.])(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?!\w|\.\d)/g;
2466
+ /** What before an address makes it a version: v, version, release, a pin's operator. */
2467
+ const VERSION_BEFORE = /(?:\bv|\bversion|\bver|\brelease|\brev|@|==|>=|<=|~=|\^|~)\s{0,2}[:=]?\s{0,2}$/i;
2468
+ const PRE_RELEASE_AFTER = /^-(?:alpha|beta|rc|dev|pre|snapshot)/i;
2469
+ const BUILD_AFTER = /^\+[0-9A-Za-z]/;
2470
+ const RANGE_AFTER = /^\/\d/;
2471
+ const privateV4 = (a, b) => a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
2472
+ function ipv4(text, m) {
2473
+ const octets = [1, 2, 3, 4].map((group) => Number(m[group]));
2474
+ if (octets.some((octet) => octet > 255) || !privateV4(octets[0], octets[1]))
2475
+ return undefined;
2476
+ const end = m.index + m[0].length;
2477
+ if (VERSION_BEFORE.test(text.slice(Math.max(0, m.index - 24), m.index)))
2478
+ return undefined;
2479
+ const rest = text.slice(end, end + 12);
2480
+ if (PRE_RELEASE_AFTER.test(rest) || BUILD_AFTER.test(rest))
2481
+ return undefined;
2482
+ if (octets[3] === 0 && RANGE_AFTER.test(rest))
2483
+ return undefined; // a range (10.0.0.0/8), no host
2484
+ return { start: m.index, end };
2485
+ }
2486
+ /** fc00::/7 (unique local) and fe80::/10 (link local), a zone after it allowed. */
2487
+ const IPV6 = /(?<![0-9A-Fa-f:.])(?:f[cd][0-9a-f]{2}|fe[89ab][0-9a-f]):[0-9a-f:]{1,39}(?:%[A-Za-z0-9._-]{1,16})?(?![0-9a-f:])/gi;
2488
+ const IPV6_GROUPS = /::?/;
2489
+ function ipv6(text, m) {
2490
+ const address = m[0].split("%")[0];
2491
+ const doubles = address.split("::").length - 1;
2492
+ const groups = address.split(IPV6_GROUPS).filter(Boolean);
2493
+ if (doubles > 1 || groups.length > 8 || groups.some((group) => group.length > 4))
2494
+ return undefined;
2495
+ if (doubles === 0 && groups.length !== 8)
2496
+ return undefined;
2497
+ if (address.endsWith(":") && !address.endsWith("::"))
2498
+ return undefined;
2499
+ const end = m.index + m[0].length;
2500
+ if (address.endsWith("::") && text.charAt(end) === "/")
2501
+ return undefined; // a range (fe80::/10)
2502
+ return { start: m.index, end };
2503
+ }
2504
+ // ---------- the table
2505
+ export const SCRUB_RULES = Object.freeze([
2506
+ ...SHAPE_RULES,
2507
+ ...VENDOR_RULES,
2508
+ rule("base64-pem", "format", (text, ctx) => base64Pems(nestedBlanked(text, ctx?.source), linesOfContext(text, ctx))),
2509
+ SECRETLINT,
2510
+ HELD,
2511
+ rule("env-dump", "dump", (text, ctx) => [...envDumps(text), ...commandDumps(text, ctx.command)]),
2512
+ rule("env-file", "dump", (text, ctx) => [...wholeText(text, ctx, envFilePath), ...fileReads(text, envFilePath, (body) => ENV_FILE_LINE.test(body))]),
2513
+ rule("credential-file", "dump", (text, ctx) => [...wholeText(text, ctx, credentialFilePath), ...fileReads(text, credentialFilePath, (body) => notPrompt(body) && notMarker(body))]),
2514
+ // A key file read (authorized_keys, known_hosts, a key) or a config read is a dump; key lines printed with no read
2515
+ // naming their file (ssh-keyscan's public host keys) are not cut (ruling G).
2516
+ rule("ssh-file", "dump", (text, ctx) => [...wholeText(text, ctx, sshFilePath), ...fileReads(text, sshFilePath, sshLine)]),
2517
+ rule("sshpass", "label", (text) => each(text, SSHPASS, (m) => flagValue(valueHit(m, 1, 1, "sshpass -p")))),
2518
+ rule("mysql-password", "label", (text) => inside(text, MYSQL_COMMAND, MYSQL_P, (m) => flagValue(valueHit(m, 1, 1, "-p")))),
2519
+ rule("password-flag", "label", passwordFlags),
2520
+ rule("auth-header", "label", (text) => [...each(text, AUTH_HEADER, authHeader(text)), ...each(text, COOKIE_HEADER, cookieHeader(text))]),
2521
+ rule("curl-user", "label", (text) => inside(text, CURL_COMMAND, CURL_USER, curlUser, true)),
2522
+ // The generic label comes after the labels a command or a header names, so where both read one value (a header
2523
+ // in a string, ruling XXXIX), the cut is named for the narrower label.
2524
+ rule("secret-assign", "label", (text, ctx) => {
2525
+ const lines = linesOfContext(text, ctx);
2526
+ return [
2527
+ ...each(text, ASSIGN, notFlag(text, lines, assign(text, lines, ctx?.source))),
2528
+ ...each(text, ASSIGN_SPACED, notFlag(text, lines, configAssign(text, 1, lines, ctx?.source))),
2529
+ ...each(text, ASSIGN_COLON, notFlag(text, lines, configAssign(text, 2, lines, ctx?.source)), afterBlank),
2530
+ ...each(text, ENV_ASSIGN, envAssign),
2531
+ ...each(text, ENV_FLAG, envFlag),
2532
+ ...helmSetLists(text),
2533
+ ...each(text, NPMRC_AUTH, npmAuth),
2534
+ ...inside(text, NPM_SET_COMMAND, NPM_SET_AUTH, npmAuth),
2535
+ ];
2536
+ }),
2537
+ rule("k8s-secret", "label", (text) => [
2538
+ ...k8sSecretValues(text),
2539
+ ...each(text, KUBE_KEY_DATA, (m) => {
2540
+ const hit = valueHit(m, 3, 3, m[2]);
2541
+ return hit && { ...hit, code: false };
2542
+ }),
2543
+ ]),
2544
+ rule("docker-auth", "label", (text, ctx) => each(text, DOCKER_AUTH, dockerAuth(text, ctx))),
2545
+ rule("connection-string", "label", (text, ctx) => each(text, CONNECTION_PASSWORD, connectionPassword(text, linesOfContext(text, ctx), ctx?.source))),
2546
+ rule("query-password", "label", (text) => each(text, QUERY_PASSWORD, queryPassword(text))),
2547
+ rule("home-path", "personal", homeFolders, { shapeClass: "home", replacement: "<user>" }),
2548
+ rule("email", "personal", (text, ctx) => each(text, EMAIL, email(text, ctx.source, urlUserinfos(text))), { shapeClass: "email" }),
2549
+ rule("private-ip", "personal", (text) => [...each(text, IPV4, (m) => ipv4(text, m)), ...each(text, IPV6, (m) => ipv6(text, m))], { shapeClass: "ip" }),
2550
+ ]);
2551
+ /** Every module-level pattern the rules read, by name: secret-scrub.test.mjs walks each (redact/match.ts SECRET_SHAPES are scanners, linear by construction)
2552
+ * and fails on an unbounded quantifier outside its allowlist, and fails on a module-level pattern missing here. */
2553
+ export const RULE_PATTERNS = Object.freeze({
2554
+ ESCAPE, CONTROLS, DRIVE_PATH, NOT_DIGIT, NOT_HEX, NOT_ALNUM, NOT_BASE64, PLACEHOLDER, ELLIPSIS, TYPE_WORD, GENERIC, PASCAL_TYPE, METAVAR, NAME_PARTS, LEADING_DASHES,
2555
+ CODE_CALL, IDENT_CHAIN, MEMBER_CHAIN, CODE_CASE, CAMEL_OR_SNAKE, CALL_AFTER, LITERAL_START, YAML_NODE, ELIDED_AFTER, REFERENCE, ELIDED, TRAILING_PUNCTUATION, SENTENCE_END, BARE_START, EDGE_BLANK, EDGE_TOKEN_PUNCT, SLUG_OFF, SLUG_ENDS, PEM_END, PEM_BEGIN, PEM_OFF, PEM_TAIL, PEM_BODY_LINE, PEM_LAST_LINE, PEM_END_LINE, LEAD_TOKEN, DIGIT_START, BASE64_CHAR, BACKSLASH_RUN, BARE_STOP, URL_USERINFO, NAME_KEY_OFF, IDENTIFIER, ENDS_ENTRY, ENTRY_END_AFTER, TYPE_SUFFIX, TYPE_AFTER, LOCAL_LEAD, LOCAL_END, NESTED_ESCAPE, COOKIE_SPLIT, LINT_URL, CAMEL_HUMP, NAME_SEPARATORS, DIGITS_ONLY,
2556
+ UPPER_NAME, LEAD_AT_START, LINE_PREFIX, LINE_REST, CODE_KEYWORD, CODE_EXPRESSION, OPENERS, CLOSERS, INI_HEADER, INI_LINE, NPMRC_AUTH, NPM_SET_COMMAND, NPM_SET_AUTH, ESCAPED_QUOTE_BEFORE, ESCAPED_QUOTE_AFTER, DOTTED_KEY_BEFORE, CODE_END, MEMBER_OBJECT_BEFORE, CODE_ROOT_BEFORE, STATEMENT_END_AFTER, REFERENCE_START, ENV_ASSIGN, HF_TOKEN, DIGITALOCEAN_TOKEN, PYPI_TOKEN, SENDGRID_KEY, ASSIGN, ASSIGN_SPACED, ASSIGN_COLON, SSHPASS, MYSQL_COMMAND, MYSQL_P, PASSWORD_FLAG, LOGIN_COMMAND, LOGIN_P,
2557
+ REDIS_COMMAND, REDIS_A, OPENSSL_PASS, NETRC, AUTH_HEADER, TOKEN_RUN, CODE_KEY_BEFORE, URL_SAFE_RUN, BASE64_RUN_BEFORE, BASE64_RUN_AFTER, LETTER_OR_DIGIT, ENV_NAME_RUN, BASE64_CHARS, COOKIE_HEADER, COOKIE_PAIR, CURL_COMMAND, CURL_USER, NUMBERED, JSON_FIELD_OPEN, PROMPT_LINE,
2558
+ ENV_LINE, ENV_COMMAND, PRINTENV_NAMES, ECHO_VARIABLE, NAME_RUN, READ_COMMAND, READ_TOOL, PATH_SEPARATOR, ENV_FILE_NAME, ENV_TEMPLATE, SSH_FILE,
2559
+ CREDENTIAL_FILE, FILE_VARIABLE, ENV_FILE_LINE, KEY_LINE, SSH_CONFIG, COMMENT_LINE, PEM_LINE, BASE64_LINE, PEM_HEADER_LINE, HOME_UNIX, HOME_WINDOWS, SEGMENT_AFTER,
2560
+ TRAILING_SLASHES, HOME_USER, CLAUDE_SLUG, CLAUDE_PROJECTS_BEFORE, SLUG_OFF_CHARS, SLUG_USER, BOT_TRAILER, DUMP_MARKER_LINE, EMAIL, EXAMPLE_DOMAIN, NO_REPLY_LOCAL, NO_REPLY_DOMAIN, FORGE_NO_REPLY, USER_ONLY_BEFORE, PORT_PASSWORD, HOST_SHAPED, IPV4, VERSION_BEFORE, PRE_RELEASE_AFTER,
2561
+ BUILD_AFTER, RANGE_AFTER, IPV6, IPV6_GROUPS, ENV_PREFIX_BEFORE, ENV_PREFIX_AFTER, ENV_PREFIX_CHAIN, ENV_PREFIX_STATEMENT, ENV_FLAG, HELM_LIST_FLAG, HELM_SET, HELM_NAME, RESOURCE_NAME, SECRET_OBJECT_NAME, CONNECTION_PASSWORD, ADO_PAIR, CONNECTION_KEY_PAIR, BLANKS, LIBPQ_PAIR_AFTER, FORMAT_FIELD, PWD_PATH, QUERY_VALUE_STOP, QUERY_PASSWORD, ARGUMENT_TAIL, NEXT_ASSIGNMENT, ASSIGNMENT_BEFORE,
2562
+ BASE64_PEM, BASE64_STD_BEFORE, BASE64_STD_AFTER, BASE64_WRAP_BREAK, BASE64_WRAP_INDENT, BASE64_WRAP_RUN, BASE64_PEM_SPAN, BASE64_BREAK_BEFORE, K8S_SECRET_KIND, YAML_DOC_START, K8S_DATA, K8S_ENTRY, BLOCK_SCALAR, QUOTED_WHOLE, K8S_SECRET_JSON, K8S_DATA_JSON, K8S_ENTRY_JSON, DIFF_EVIDENCE, DIFF_MARKER, DIFF_FILE_HEADER,
2563
+ KUBE_KEY_DATA, DOCKER_AUTH, DOCKER_CONFIG, COMMAND_WORD_SPLIT, OPTION_NAME, WORD_QUOTES,
2564
+ });