@nightloom/isy 1.0.4 → 1.0.6-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +18 -2
  2. package/dist/agents/claude.js +3 -2
  3. package/dist/agents/claude.js.map +1 -1
  4. package/dist/agents/codex.js +14 -5
  5. package/dist/agents/codex.js.map +1 -1
  6. package/dist/agents/index.d.ts +14 -10
  7. package/dist/agents/index.js +65 -15
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/kimi.js +26 -8
  10. package/dist/agents/kimi.js.map +1 -1
  11. package/dist/agents/types.d.ts +12 -3
  12. package/dist/api.d.ts +1 -0
  13. package/dist/api.js +1 -1
  14. package/dist/api.js.map +1 -1
  15. package/dist/commands/commit.d.ts +6 -0
  16. package/dist/commands/commit.js +326 -16
  17. package/dist/commands/commit.js.map +1 -1
  18. package/dist/commands/health.js +1 -1
  19. package/dist/commands/health.js.map +1 -1
  20. package/dist/commands/init.js +40 -9
  21. package/dist/commands/init.js.map +1 -1
  22. package/dist/commands/status.d.ts +2 -0
  23. package/dist/commands/status.js +7 -4
  24. package/dist/commands/status.js.map +1 -1
  25. package/dist/commands/upload.d.ts +8 -1
  26. package/dist/commands/upload.js +65 -48
  27. package/dist/commands/upload.js.map +1 -1
  28. package/dist/detectors.d.ts +32 -0
  29. package/dist/detectors.js +279 -72
  30. package/dist/detectors.js.map +1 -1
  31. package/dist/git.d.ts +52 -0
  32. package/dist/git.js +166 -9
  33. package/dist/git.js.map +1 -1
  34. package/dist/githook.d.ts +18 -7
  35. package/dist/githook.js +147 -17
  36. package/dist/githook.js.map +1 -1
  37. package/dist/hook.d.ts +22 -2
  38. package/dist/hook.js +28 -3
  39. package/dist/hook.js.map +1 -1
  40. package/dist/index.js +23 -7
  41. package/dist/index.js.map +1 -1
  42. package/dist/mask-paths.d.ts +4 -3
  43. package/dist/mask-paths.js +4 -3
  44. package/dist/mask-paths.js.map +1 -1
  45. package/dist/parser.d.ts +58 -9
  46. package/dist/parser.js +337 -58
  47. package/dist/parser.js.map +1 -1
  48. package/dist/paths.d.ts +19 -1
  49. package/dist/paths.js +28 -3
  50. package/dist/paths.js.map +1 -1
  51. package/dist/redact.d.ts +2 -0
  52. package/dist/redact.js +987 -95
  53. package/dist/redact.js.map +1 -1
  54. package/dist/stage0.js +27 -8
  55. package/dist/stage0.js.map +1 -1
  56. package/dist/state.d.ts +15 -0
  57. package/dist/state.js +8 -0
  58. package/dist/state.js.map +1 -1
  59. package/dist/test/check.test.js +1 -1
  60. package/dist/test/check.test.js.map +1 -1
  61. package/dist/test/cli.test.js +11 -1
  62. package/dist/test/cli.test.js.map +1 -1
  63. package/dist/test/codex.test.js +27 -4
  64. package/dist/test/codex.test.js.map +1 -1
  65. package/dist/test/commit.test.js +1466 -6
  66. package/dist/test/commit.test.js.map +1 -1
  67. package/dist/test/e2e-harness.test.d.ts +1 -0
  68. package/dist/test/e2e-harness.test.js +53 -0
  69. package/dist/test/e2e-harness.test.js.map +1 -0
  70. package/dist/test/git.test.js +72 -2
  71. package/dist/test/git.test.js.map +1 -1
  72. package/dist/test/hook.test.js +138 -3
  73. package/dist/test/hook.test.js.map +1 -1
  74. package/dist/test/init.test.js +61 -2
  75. package/dist/test/init.test.js.map +1 -1
  76. package/dist/test/kimi-config.test.js +27 -5
  77. package/dist/test/kimi-config.test.js.map +1 -1
  78. package/dist/test/kimi-hook.test.js +1 -1
  79. package/dist/test/kimi-hook.test.js.map +1 -1
  80. package/dist/test/kimi-listing.test.js +42 -2
  81. package/dist/test/kimi-listing.test.js.map +1 -1
  82. package/dist/test/kimi.test.js +26 -2
  83. package/dist/test/kimi.test.js.map +1 -1
  84. package/dist/test/parser.test.js +527 -1
  85. package/dist/test/parser.test.js.map +1 -1
  86. package/dist/test/redact.test.js +2472 -14
  87. package/dist/test/redact.test.js.map +1 -1
  88. package/dist/test/stage0.test.js +617 -1
  89. package/dist/test/stage0.test.js.map +1 -1
  90. package/dist/test/sweep.test.js +110 -7
  91. package/dist/test/sweep.test.js.map +1 -1
  92. package/package.json +1 -1
  93. package/src/agents/claude.ts +3 -2
  94. package/src/agents/codex.ts +14 -5
  95. package/src/agents/index.ts +71 -16
  96. package/src/agents/kimi.ts +28 -8
  97. package/src/agents/types.ts +12 -3
  98. package/src/api.ts +4 -2
  99. package/src/commands/commit.ts +354 -18
  100. package/src/commands/health.ts +1 -1
  101. package/src/commands/init.ts +45 -10
  102. package/src/commands/status.ts +9 -4
  103. package/src/commands/upload.ts +73 -63
  104. package/src/detectors.ts +284 -75
  105. package/src/git.ts +175 -9
  106. package/src/githook.ts +151 -19
  107. package/src/hook.ts +30 -3
  108. package/src/index.ts +25 -7
  109. package/src/mask-paths.ts +5 -4
  110. package/src/parser.ts +355 -51
  111. package/src/paths.ts +30 -3
  112. package/src/redact.ts +991 -98
  113. package/src/stage0.ts +28 -8
  114. package/src/state.ts +18 -0
package/dist/redact.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { homedir } from "node:os";
2
- import { basename } from "node:path";
2
+ import { basename, resolve } from "node:path";
3
3
  import { fileLines } from "./lines.js";
4
- import { HEREDOC, commandSegments, withoutHeredocs } from "./parser.js";
5
- import { PATH_KEYS, REDACTION_MARKER, marker, maskPath, maskPaths, resolveRoots, rootOf, } from "./mask-paths.js";
4
+ import { HEREDOC, STRUCTURES, commandSegments, mayParse, shellEditWords, spend, withoutHeredocs } from "./parser.js";
5
+ import { PATH_KEYS, REDACTION_MARKER, looksAbsolute, marker, maskPath, maskPaths, resolveRoots, rootOf, } from "./mask-paths.js";
6
6
  // The marker vocabulary lives with the path rules, which cannot import this
7
7
  // module back without a cycle. Re-exported so every caller has one import.
8
8
  export { REDACTION_MARKER, marker };
@@ -10,30 +10,208 @@ export { REDACTION_MARKER, marker };
10
10
  function anyCase(source) {
11
11
  return source.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`);
12
12
  }
13
- const SECRET_WORD = anyCase("(?:password|passwd|secret|token|api[-_]?key|private[-_]?key|access[-_]?key)");
13
+ /**
14
+ * `pass` and `pwd` count only as a word of their own, as `compass`, `bypass`, and the
15
+ * shell's `PWD` and `OLDPWD` are all over a transcript: `DB_PASS`, `db-pass`, `dbPass`,
16
+ * `DB_PWD`, `jdbc.pwd`, `Uid=sa;Pwd=…`, and `Pwd=…` as only a connection string spells it.
17
+ */
18
+ const SECRET_WORD = [
19
+ anyCase("pass(?:word|wd|phrase)|secret|token|(?:api|private|access|account)[-_]?key|credentials?|auth(?:orization)?|cookie"),
20
+ `(?:(?<![A-Za-z0-9])|(?<=[a-z0-9])(?<![bB][yY])(?=[A-Z]))${anyCase("pass")}`,
21
+ `(?:(?<=[;_]|[A-Za-z0-9][.-])|(?<=[a-z0-9])(?=[A-Z]))${anyCase("pwd")}`,
22
+ "(?<![A-Za-z0-9])Pwd",
23
+ ].join("|");
24
+ /** What is still the secret itself: its value, and the environment it is for. */
25
+ const SAME_SECRET = "value|prod(?:uction)?|dev|stag(?:e|ing)|test|live|old|new|local";
26
+ const KEY_OR_BASE = "(?:[-_]?key)?(?:[-_]?base)?";
27
+ /** Its version too, short of a year: `token_2022` names a chain's program and holds nothing. */
28
+ const VERSION = "[0-9]{1,3}";
29
+ /** `TOKEN_PROD`, `secret-old`, `API_KEY_2`. */
30
+ const PLAIN_TAIL = anyCase(`${KEY_OR_BASE}(?:[-_](?:${SAME_SECRET}))?(?:[-_]${VERSION})?`);
31
+ /** `tokenValue`, `apiKeyProd`, and `accessToken2`, as `token0` and `oauth2` are no secrets. The cap keeps a run of `token1` linear. */
32
+ const HUMP_TAIL = anyCase(`${KEY_OR_BASE}(?:[-_]?(?:${SAME_SECRET}))?`) + `(?:(?:[-_]|(?<=[a-z0-9][A-Z][A-Za-z0-9]{0,64}))${VERSION})?`;
14
33
  /**
15
34
  * A name that holds a secret: one of the words, wherever it sits in an
16
35
  * identifier — `PGPASSWORD`, `STRIPE_SECRET_KEY`, `aws_secret_access_key`,
17
- * `x-api-key` — and followed by nothing but `KEY` and `BASE` (`SECRET_KEY_BASE`).
18
- * That tail is the line between the secret and what is said about it:
19
- * `tokenHash`, `max_tokens`, `TOKENS_PER_ANALYSIS` and `PASSWORD_FILE` turn up
20
- * in a real corpus as often as the secrets do, and none of them is one.
36
+ * `x-api-key` — and followed by nothing but `KEY` and `BASE` (`SECRET_KEY_BASE`)
37
+ * and what is still the secret. That tail is the line between the secret and what
38
+ * is said about it: `tokenHash`, `max_tokens`, `TOKENS_PER_ANALYSIS` and
39
+ * `PASSWORD_FILE` turn up in a real corpus as often as the secrets do, and none of
40
+ * them is one.
21
41
  */
22
- function secretName(atWord = "") {
23
- return String.raw `[A-Za-z0-9_.-]*?${atWord}${SECRET_WORD}${anyCase("(?:[-_]?key)?(?:[-_]?base)?")}(?![A-Za-z0-9_.-])`;
42
+ function secretName(atWord = "", tail = HUMP_TAIL) {
43
+ // From the front this runs at every character of a word, so the letters the words start with go first.
44
+ return String.raw `[A-Za-z0-9_.-]*?(?=[aAcCpPsStT])${atWord}(?:${SECRET_WORD})${tail}(?![A-Za-z0-9_.-])`;
24
45
  }
46
+ /** `adminPassword`, `_authToken`, `tokenValue`: as often a variable in code as a key in a file, and told by a hump. */
47
+ const CAMEL_NAME = secretName() + "(?<=[a-z0-9][A-Z][A-Za-z0-9_.-]*)";
48
+ /** `accessToken: …`, which a value in no quotes leaves to be a type as often as data. */
49
+ const CAMEL_ENDING = String.raw `[A-Za-z0-9_.-]*?(?<=[a-z0-9])(?:Token|Secret|Password)`;
50
+ /**
51
+ * `First pass: everything compiles`, `--- PASS: TestParser`, `auth: requireAuth`,
52
+ * `const cookie = parseCookie(req)`: alone, these words are all over prose, code and
53
+ * test output, so alone and spaced from a value with no digit and no quote they name
54
+ * nothing. A secret has a name in front (`SMTP_PASS: …`), a quote or a digit, or
55
+ * takes its `=` with no space.
56
+ */
57
+ const NOT_SAID_IN_PASSING = String.raw `(?!PASS:[ \t]|(?:${anyCase("pass|auth|credentials?|cookie")})["']?\s*[=:]\s+(?!["'])[^\d\s]*(?:\s|$))`;
25
58
  /** The word glued to what came before, but not as a camelCase hump. */
26
- const PLAIN_NAME = secretName("(?!(?<=[a-z0-9])[A-Z])");
27
- /** `adminPassword`, `_authToken`: as often a variable in code as a key in a file. */
28
- const CAMEL_NAME = secretName("(?<=[a-z0-9])(?=[A-Z])");
59
+ const PLAIN_NAME = NOT_SAID_IN_PASSING + secretName("(?!(?<=[a-z0-9])[A-Z])", PLAIN_TAIL);
60
+ const VALUE_CHAR = String.raw `[^\s"'{}()[\]<>$]`;
61
+ /**
62
+ * `hash(input)`, `foo.bar(baz).qux(),`, `f(g(x))`: a call, which in quotes is a password
63
+ * with a bracket in it, and so is `abc(def)ghi1` anywhere, as code puts nothing like that
64
+ * after a closing bracket.
65
+ */
66
+ const CALL = String.raw `(?<!["'])[A-Za-z_][\w.]*\((?![^\s"'{}[\]<>]{0,256}\)[\w$#@~\\])`;
29
67
  /**
30
68
  * What an assigned secret looks like: long enough to be one, and not code. A
31
69
  * bare number under a quoted name is JSON's own (`"token": 1234567890`), where a
32
70
  * secret would be a string; anywhere else a number is a password like any other
33
71
  * — `DB_PASSWORD=1234567890123`, `MYSQL_ROOT_PASSWORD: 12345678`. The digit is
34
72
  * looked for first so the lookbehind runs only where a number starts.
73
+ *
74
+ * A `$` or a bracket inside belongs to the value (`abc$REST123`, `abc(def)ghi1`), as
75
+ * a password takes any character. They end it only where they start something
76
+ * else: `$PASSWORD` and `$(cat f)` at the front, `prefix${X}`, and a call, of which
77
+ * only a name long enough to be a value goes.
78
+ *
79
+ * How much more a value takes goes by what is around it. In quotes it runs to the
80
+ * closing one, the other quote and `{}[]<>` included, though what opens with a
81
+ * bracket is a placeholder; `$` at the front is literal in single quotes, and in
82
+ * double ones where no shell would expand it: a hash, or anything with a digit in it
83
+ * that no all-caps name spells. With no space after an `=` it takes `{}[]<>` too,
84
+ * short of one closing around the assignment. Spaced from its name and unquoted it is
85
+ * code as often as not (`token = tokens[index]`), so the limits above hold there.
86
+ *
87
+ * A token's rule runs before the rules that go by a name and ends at the token's shape, so a
88
+ * value with a token in it (`api_key=glpat-…,…`, `secret: "ghp_…&…"`) reaches them as markers
89
+ * with the rest of the value around them, and nothing else has a name for that rest. It is the
90
+ * value still, whatever its length, as long as some of it follows a marker: a value that ends
91
+ * on a marker was cut whole. RUNS_ON reads a value so too.
92
+ */
93
+ const MARKED_VALUE = String.raw `(?:${VALUE_CHAR}*\[ISY_REDACTED:\w+\])+${VALUE_CHAR}+`;
94
+ const INNER_DOLLAR_OR_PAREN = String.raw `[$()](?=[^\s"'{}[\]<>])`;
95
+ const LITERAL_DOLLAR = String.raw `\$(?=[^\s"]{0,256}\d)(?![{(])(?![A-Z_][A-Z0-9_]*\b)`;
96
+ const SECRET_VALUE = String.raw `(?:${MARKED_VALUE}|(?!\[ISY_REDACTED)(?!(?=-?\d)(?<=["']\s*:\s*)-?\d[\d.,eE+-]*(?![^\s"'{}()[\]<>$]))(?:(?<=")(?:${VALUE_CHAR}|${LITERAL_DOLLAR})(?:[^\s"$()]|${INNER_DOLLAR_OR_PAREN}){7,}|(?<=')(?:${VALUE_CHAR}|\$)(?:[^\s'$()]|${INNER_DOLLAR_OR_PAREN}){7,}|(?<=[\w.-]=)(?!=|${CALL})${VALUE_CHAR}(?:${VALUE_CHAR}|${INNER_DOLLAR_OR_PAREN}|[{}[\]<>](?=[^\s"'])){7,}|(?!${CALL})${VALUE_CHAR}(?:${VALUE_CHAR}|${INNER_DOLLAR_OR_PAREN}){7,}|${VALUE_CHAR}{8,}))`;
97
+ /**
98
+ * A value read to a space or a quote can end on the name of the next one: `Set-Cookie:
99
+ * session_token="…"`, `DB_PASS=DB_PASSWORD="…"`, `auth-cookie: api_key= …`. That name is then
100
+ * inside the match, where no rule after it looks, so the match goes on through the name's
101
+ * separator and over what it holds, as the name's own would have, closing quote and all, and
102
+ * again where that ends on a name. The rules after the plain assignment find such a name cut
103
+ * already, by its own match there, so only that rule goes on, with those ahead of it that can take a
104
+ * name (the authorization header's, a bearer token's, which takes a separator doubled (`secret==`) too,
105
+ * and a token's, with the rest of a name glued on to it) and the camelCase one after it, whose name the
106
+ * plain rule does not read (`apiKey: 'accessToken": '…'`).
107
+ * A quote right after a separator opens what the name holds rather than closing the step before:
108
+ * taken as the close, it left the next step nothing to start from (`password=api_token: "…,api_key="…"`).
109
+ *
110
+ * ponytail: the name is told by the word it ends with, as a copy of secretName() in both would
111
+ * take the patterns past the size a commit compiles in time (the size test in redact.test.ts),
112
+ * so what a name ending otherwise holds (`DB_PASS`, `TOKEN_PROD`) stays. Telling the name
113
+ * outside the pattern, once a match is found, is the way up.
114
+ */
115
+ const NAME_END = anyCase("(?:passw(?:or)?d|secret|token|key|base)");
116
+ const RUNS_ON = String.raw `(?:(?<=${NAME_END}["']?[=:]*)(?:(?<=[=:])|["']?\s*[=:])\s*(?<q>["']?)(?:${MARKED_VALUE}|${VALUE_CHAR}{8,})(?:(?<![=:])\k<q>)?)*`;
117
+ /**
118
+ * The rest of a name glued on to a token whose shape stops inside it (`ghp_…2api-key==…`), so that
119
+ * the token's match reaches the name's end and goes on over what the name holds. Only with that
120
+ * value: a name taken with no value after it is one the assignment rule no longer sees. Any name, not
121
+ * only one RUNS_ON reads: the shape takes the name it is glued to whatever the name ends with
122
+ * (`glpat-…2auth=…`, `xapp-…TOKEN_PROD:=…`), so a value left after it had nothing to cut it.
123
+ * The value stops short of `Bearer` and a space, which a token's rule, ahead of the bearer
124
+ * token's, would otherwise take from it (`…-accessToken:…&Proxy-Authorization=Bearer …`).
125
+ */
126
+ const NAME_TAIL = String.raw `(?:[\w.-]*["']?\s*[=:]\s*["']?(?:(?!${anyCase("bearer")}\s)${VALUE_CHAR}){8,})?${RUNS_ON}`;
127
+ /**
128
+ * A separator with a name before it, looked for from the separator back: from the front,
129
+ * a name costs a look at every letter of every word.
130
+ */
131
+ const afterName = (name, between, separator) => String.raw `${separator}(?<=(?<![A-Za-z0-9_.-])${name}${between}${separator})`;
132
+ /** The space or quote a name may have before its separator. */
133
+ const CLOSED = String.raw `["']?\s*`;
134
+ /**
135
+ * `=>`, `:=`, a comparison and a subscript's `"] =`: what is code as often as data
136
+ * (`password => password.trim()`), unless what follows is in quotes. A run of `=` is
137
+ * looked back from only where it starts, as no name stands right before the rest of it.
138
+ */
139
+ const beforeQuoted = (name) => afterName(name, String.raw `["']?\]?\s*`, "(?:=>|:=|(?<!=)={1,3}|!={1,2})") + String.raw `\s*["']`;
140
+ /** What nobody types by hand: twelve letters and digits in a row, both among them, as `documentation` and `202410201230` are not. */
141
+ const GENERATED_RUN = String.raw `(?=[A-Za-z]{0,11}\d)(?=\d{0,11}[A-Za-z])[A-Za-z0-9]{12}`;
142
+ const GENERATED = new RegExp(GENERATED_RUN);
143
+ /** `STRIPE_KEY`, `HMAC_KEY`: as often a sort order as a secret (`SORT_KEY=created_at`), so what it holds has to look generated too. */
144
+ const KEY_NAME = String.raw `(?:[A-Z][A-Z0-9_]{0,64}_)?KEY`;
145
+ const KEY_FIELD = new RegExp(`^${KEY_NAME}$`);
146
+ const KEY_END = String.raw `KEY(?<=(?<![A-Za-z0-9_])${KEY_NAME})`;
147
+ /**
148
+ * `curl -u admin:…`, its flag alone or last among others (`-fsSLu`). A walk to the flag
149
+ * stops at the next `curl`, which finds the same from there, so the walks of a line come
150
+ * to about its length however often it says `curl`. The cap says how far a flag is still
151
+ * this client's.
152
+ */
153
+ const CURL_USER_FLAG = String.raw `curl\b(?:(?!\bcurl\b)[^\n;|]){0,200}?\s(?:-[a-zA-Z]{0,16}[uU]\s*|--(?:proxy-)?user[=\s]\s*)`;
154
+ /** A name may be a marker already: an address is one by now. */
155
+ const CURL_USER = String.raw `(?:\[ISY_REDACTED:\w+\]|(?!\[ISY_REDACTED)[^\s:"']+):`;
156
+ /**
157
+ * A client, whatever comes between, and its flag: stopped and capped as above, at a start
158
+ * as `PASSWORD_FLAG` has it.
159
+ *
160
+ * ponytail: the walks come to a line's length for each client it names, so a line naming
161
+ * every one of them in turn costs ten times a plain one. Finding each client's flags once,
162
+ * outside the pattern, is the way up if a stranger's session makes that matter.
163
+ */
164
+ const onClient = (client, flag) => String.raw `(?:${client})\b(?:(?!\b(?<![.-])(?:${client})\b)[^\n;|]){0,200}?\s${flag}`;
165
+ /** The next word looks generated, for where what stands in front of it says too little. */
166
+ const GENERATED_WORD = String.raw `(?=["']?[^\s"'/]{0,256}?${GENERATED_RUN})`;
167
+ /**
168
+ * Where a client takes a password, which says nothing anywhere else: `-p` is a port to
169
+ * `ssh`, a directory's parents to `mkdir`, and to `mysql` with a space after it only a
170
+ * prompt. A name after `.` or `-` is a file's or another tool's (`wget a.zip -P out`),
171
+ * and `--name mongo -p 27017:27017` is a container, so to that family `-p` counts
172
+ * behind `-u`. What a here-string feeds is anyone's, so that word has to look generated.
173
+ *
174
+ * A walk that a text can start again and again stops where the next one starts, which
175
+ * finds the same from there: a text of `mongo -u a ` is otherwise thousands of steps for
176
+ * each word in it, and a text of `<` hundreds for each character. A `-u` with `-p` for its
177
+ * name finds nothing from there, so that one is walked through.
178
+ *
179
+ * ponytail: the clients people use. Another tool's own flag stays, as it does anywhere,
180
+ * unless a project's own script (`./x`) gets something generated on one of these flags.
35
181
  */
36
- const SECRET_VALUE = String.raw `(?!\[ISY_REDACTED)(?!(?=-?\d)(?<=["']\s*:\s*)-?\d[\d.,eE+-]*(?![^\s"'{}()[\]<>$]))[^\s"'{}()[\]<>$]{8,}`;
182
+ const USER_FIRST = "mongosh|mongo|mongodump|mongorestore|mongoexport|mongoimport|cqlsh";
183
+ const USER_FLAG = String.raw `\s(?:-u|--username)[=\s]`;
184
+ const PASSWORD_FLAG = String.raw `(?:\b(?<![.-])(?:${[
185
+ onClient("sshpass", String.raw `-p\s*`),
186
+ onClient(String.raw `(?:docker|podman)\s+login|helm\s+registry\s+login|az\s+login|twine\s+upload`, String.raw `-p\s+`),
187
+ String.raw `(?:${USER_FIRST})\b(?:(?!\b(?<![.-])(?:${USER_FIRST})\b)[^\n;|]){0,200}?${USER_FLAG}\s*\S+(?!\S)(?:(?!${USER_FLAG}(?!\s*-p\s))[^\n;|]){0,200}?\s-p\s+(?!\d+:\d)`,
188
+ onClient("redis-cli", String.raw `-a\s+`),
189
+ onClient("mysql|mariadb|mysqldump|mysqladmin|7z|7za|7zz", String.raw `-p(?=[^\s=])`),
190
+ onClient("sqlcmd|bcp|zip|unzip", String.raw `-P\s*`),
191
+ onClient("plink|pscp|psftp", String.raw `-pw\s+`),
192
+ onClient("ssh-keygen", String.raw `-N\s+`),
193
+ onClient("lftp", String.raw `-u\s+["']?[^\s,"']+,`),
194
+ onClient("smbclient", String.raw `-U\s+["']?[^\s%"']+%`),
195
+ onClient(String.raw `(?:https?|xh)(?=\s)`, String.raw `(?:-a|--auth)[=\s]\s*["']?[^\s:"']+:`),
196
+ onClient("curl", String.raw `(?:-[a-zA-Z]{0,16}b|--cookie)[=\s]\s*(?=["']?[^\s"'=]{1,256}=)`),
197
+ onClient("rabbitmqctl", String.raw `(?:add_user|change_password)\s+\S+\s+`),
198
+ onClient(String.raw `gh\s+secret\s+set`, String.raw `(?:-b|--body)[=\s]\s*`),
199
+ onClient(String.raw `doctl\s+auth\s+init`, String.raw `(?:-t|--access-token)[=\s]\s*`),
200
+ onClient(String.raw `security\s+add-\w+-password`, String.raw `-w\s+`),
201
+ String.raw `htpasswd\s+(?=-[a-zA-Z]*b)(?:-[a-zA-Z]*n[a-zA-Z]*\s+\S+\s+|-[a-zA-Z]+\s+\S+\s+\S+\s+)`,
202
+ String.raw `sqlplus\s+(?:-\S+\s+)*[^\s/@"'-][^\s/@"']*\/`,
203
+ // Not a second `smbclient`, which is the next command's: `apt install smbclient && smbclient -U a%b`.
204
+ String.raw `smbclient\s+[^\s-]\S*\s+(?!smbclient\b)`,
205
+ String.raw `net\s+use\s+(?:\S+\s+){1,2}\/user:\S+\s+`,
206
+ String.raw `vault\s+login\s+${GENERATED_WORD}`,
207
+ String.raw `ngrok\s+(?:config\s+add-)?authtoken\s+`,
208
+ String.raw `(?:poetry|composer)\s+config\s+(?:--\S+\s+)*(?:http-basic\.\S+\s+\S+|pypi-token\.\S+)\s+`,
209
+ String.raw `(?:aws\s+configure\s+set|(?:npm|yarn|wp)\s+config\s+set|setx|setenv|set\s+-[a-z]*x[a-z]*)\s+(?:\S*[/:])?${secretName()}\s+`,
210
+ String.raw `SetEnvironmentVariable\(\s*["']${secretName()}["']\s*,\s*`,
211
+ String.raw `echo\s+(?:-n\s+)?(?=["']?[^\s"']{1,400}["']?\s*\|[^\n;|]{0,200}?--(?:password-stdin|with-token)\b)`,
212
+ ].join("|")})|-(?<=\s-)(?:(?:src|dest)?(?:store|key)pass\s+|Dsonar\.login=)|<<<\s*(?=["']?(?:(?!<<<)[^\s"'/]){0,256}?${GENERATED_RUN})|\.\/[\w.-](?:(?!\.\/[\w.-])[^\n;|]){0,263}?\s(?:-p|--key|--pwd)\s+${GENERATED_WORD})`;
213
+ /** To a closing quote named by the backreference `quote`, spaces and the other quote included. */
214
+ const quotedTo = (quote) => String.raw `(?!\[ISY_REDACTED|\$)(?:(?!${quote})[^\n]){1,400}(?=${quote})`;
37
215
  export const BUILTIN_RULES = [
38
216
  {
39
217
  type: "private_key",
@@ -57,8 +235,10 @@ export const BUILTIN_RULES = [
57
235
  replacement: marker("openai_key"),
58
236
  },
59
237
  {
238
+ // Open at the end for a refresh token's length, so it also takes a name glued on
239
+ // (`ghp_…passwd=…`): the rest of that name goes too, and what it holds (NAME_TAIL).
60
240
  type: "github_token",
61
- pattern: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b/g,
241
+ pattern: new RegExp(String.raw `\b(?:ghp|gho|ghs|ghu|ghr)_[A-Za-z0-9]{36,}\b` + NAME_TAIL, "g"),
62
242
  replacement: marker("github_token"),
63
243
  },
64
244
  {
@@ -92,20 +272,56 @@ export const BUILTIN_RULES = [
92
272
  pattern: /\bnpm_[A-Za-z0-9]{36}\b/g,
93
273
  replacement: marker("npm_token"),
94
274
  },
275
+ {
276
+ // One pass for all of them, as a rule each is one more scan of every string: GitLab, Slack,
277
+ // Discord, Groq, xAI, Google's OAuth, Stripe's webhooks, SendGrid, Mailgun, Twilio, Shopify,
278
+ // DigitalOcean, Hugging Face, PyPI, RubyGems, Docker, Supabase, Vercel, Atlassian, Linear,
279
+ // Notion, Figma, Replicate, ElevenLabs, age. A fal.ai key, and a Telegram or a Discord bot
280
+ // token, open with an id that is public and whose shape would be read at every word of
281
+ // every string, so they are found from what comes after it and the id stays. A shape open at
282
+ // its end also takes a name glued on (`glpat-…-apikey=`), so the rest of it goes too (NAME_TAIL).
283
+ type: "service_token",
284
+ pattern: new RegExp(String.raw `(?:\b(?:gl(?:pat|dt)-[\w-]{20,}|xapp-\d-[A-Za-z0-9-]{20,}|hooks\.slack\.com\/\w+\/[\w/]{20,}|discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w-]{40,}` +
285
+ String.raw `|gsk_[A-Za-z0-9]{40,}|xai-[A-Za-z0-9]{40,}|ya29\.[\w-]{40,}|1\/\/0[\w-]{40,}|whsec_[A-Za-z0-9+/]{24,}|SG\.[\w-]{16,}\.[\w-]{16,}` +
286
+ String.raw `|key-[0-9a-f]{32}\b|SK[0-9a-f]{32}\b|shp(?:at|ss|ca|pa)_[0-9a-fA-F]{32}\b|do[pors]_v1_[0-9a-f]{64}\b|hf_[A-Za-z0-9]{30,}|pypi-[\w-]{50,}` +
287
+ String.raw `|rubygems_[0-9a-f]{48}\b|dckr_pat_[\w-]{20,}|sbp_[0-9a-f]{40}\b|vercel_[A-Za-z0-9]{20,}|ATATT[\w-]{50,}|lin_api_[A-Za-z0-9]{30,}` +
288
+ String.raw `|ntn_[A-Za-z0-9]{40,}|secret_[A-Za-z0-9]{40,}|figd_[\w-]{30,}|r8_[A-Za-z0-9]{30,}|sk_[0-9a-f]{48}\b|AGE-SECRET-KEY-1[A-Z0-9]{50,})` +
289
+ String.raw `|:(?<=\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:)[0-9a-f]{32}\b|:(?<=\b\d{8,12}:)AA[\w-]{30,}` +
290
+ String.raw `|\.(?<=[\w-]{24}\.)[\w-]{6}\.(?=[\w-]{0,26}?${GENERATED_RUN})[\w-]{27,})${NAME_TAIL}`, "g"),
291
+ replacement: marker("service_token"),
292
+ },
95
293
  {
96
294
  // After every shape a bearer token can have, so a JWT or a GitHub token
97
- // keeps its own label and its marker is not marked again.
295
+ // keeps its own label and its marker is not marked again. Twenty characters
296
+ // for a word alone, or eight with a digit: `Bearer authentication` is prose.
297
+ // Eight with a digit also take a name glued on or on the next line
298
+ // (`Bearer x1_password="…"`, `TOKEN_TYPE=Bearer` over `AWS_S3_SECRET=…`), so the
299
+ // token goes on over what that name holds.
98
300
  type: "bearer_token",
99
- pattern: /\b(Bearer\s+)(?!\[ISY_REDACTED)[A-Za-z0-9._~+/-]{20,}=*/gi,
301
+ pattern: new RegExp(/\b(Bearer\s+)(?!\[ISY_REDACTED)(?:(?=[A-Za-z._~+/-]*\d)[A-Za-z0-9._~+/-]{8,}|[A-Za-z0-9._~+/-]{20,})=*/.source + RUNS_ON, "gi"),
100
302
  replacement: `$1${marker("bearer_token")}`,
101
303
  },
304
+ {
305
+ // Whatever the scheme (`Basic`, `Token`, `Digest`): the header says what the
306
+ // word after it is, so it needs no shape. Before the assignment rule, which
307
+ // would stop at the scheme. A variable or a placeholder is left as it is. A
308
+ // backtick right after a separator opens a value (Basic secret=:credentials=`…`):
309
+ // stopped there, the credential was the names and left the value. That value
310
+ // runs on as an assigned one does, over backticks too (`…,auth=`…``), and where
311
+ // it ends on a name, before or after the name's separator (`Pwd="…"`), over what
312
+ // the name holds, as no rule after this one sees the name inside it.
313
+ type: "authorization",
314
+ pattern: new RegExp(/\b(authorization["'`]?[ \t]*[:=][ \t]*["'`]?[A-Za-z][A-Za-z0-9-]*[ \t]+)(?!\[ISY_REDACTED)[^\s"'`$<>{}()[\]]{8,}(?:(?<=[=:])`[^\s"'{}()[\]<>$]+(?:(?:(?<=[=:])|["']?\s*[=:])\s*["']?[^\s"'{}()[\]<>$]{8,})?)?/.source + RUNS_ON, "gi"),
315
+ replacement: `$1${marker("authorization")}`,
316
+ },
102
317
  {
103
318
  // Any scheme: a password in a URL is one whatever speaks it — rediss,
104
319
  // amqps, https to a bare IP. The scheme is capped because `\b` lets a match
105
320
  // start inside a dotted or dashed run: unbounded, every start rescans the
106
- // rest of the run, and a long one costs minutes.
321
+ // rest of the run, and a long one costs minutes. The user may be empty, as
322
+ // Redis URLs usually write it: `redis://:password@host`.
107
323
  type: "connection_string",
108
- pattern: /\b([A-Za-z][A-Za-z0-9+.-]{0,31}):\/\/([^\s:/@]+):([^\s/@]+)@/g,
324
+ pattern: /\b([A-Za-z][A-Za-z0-9+.-]{0,31}):\/\/([^\s:/@]*):([^\s/@]+)@/g,
109
325
  replacement: `$1://$2:${marker("connection_string")}@`,
110
326
  },
111
327
  {
@@ -120,16 +336,85 @@ export const BUILTIN_RULES = [
120
336
  {
121
337
  // The name may close a quote of its own: `"password": "…"`.
122
338
  type: "assignment",
123
- pattern: new RegExp(String.raw `(?<![A-Za-z0-9_.-])(${PLAIN_NAME})(["']?\s*[=:]\s*)(["']?)${SECRET_VALUE}`, "g"),
339
+ pattern: new RegExp(String.raw `(${afterName(PLAIN_NAME, CLOSED, "[=:]")}\s*["']?|${beforeQuoted(PLAIN_NAME)})${SECRET_VALUE}${RUNS_ON}`, "g"),
340
+ replacement: `$1${marker("assignment")}`,
341
+ },
342
+ {
343
+ // A camelCase name counts where it is plainly data — with a quoted value
344
+ // (`accessToken: "…"`), as `name=value` with no space, as `.npmrc` writes
345
+ // `_authToken=`, or as a log prints one when what it holds looks generated
346
+ // (`accessToken: aB3…`) — and not in `adminPassword = someVariable`. One look for
347
+ // `=` and `:`, as a commit compiles every copy of a name in here again.
348
+ type: "assignment",
349
+ pattern: new RegExp(String.raw `(${afterName(CAMEL_NAME, String.raw `(?:(?=[=])|${CLOSED}(?=:))`, "[=:]")}(?:(?<==)|\s*["'])|${beforeQuoted(CAMEL_NAME)}|${afterName(CAMEL_ENDING, "", ":")}[ \t]+(?=[^\s"']{0,256}?${GENERATED_RUN}))${SECRET_VALUE}${RUNS_ON}`, "g"),
350
+ replacement: `$1${marker("assignment")}`,
351
+ },
352
+ {
353
+ // What SQL, `.netrc` and XML have for a separator. `password '…'` only in single quotes,
354
+ // as SQL writes it, since `grep password "src/auth"` names none; a tag only with its
355
+ // close, since `bot<token>/getUpdates` is a placeholder.
356
+ type: "assignment",
357
+ pattern: new RegExp(String.raw `(\b${anyCase("password")}\s+(?:${anyCase("for")}\s+\S{1,256}\s*=\s*)?'|\b${anyCase("identified")}\s+(?:${anyCase("with")}\s+\S{1,64}\s+)?${anyCase("by")}\s+["']|\bmachine\s+\S{1,256}\s+login\s+\S{1,256}\s+password\s+["']?)${SECRET_VALUE}` +
358
+ String.raw `|(<${secretName()}>)${SECRET_VALUE}(?=<\/)`, "g"),
359
+ replacement: `$1$2${marker("assignment")}`,
360
+ },
361
+ {
362
+ // What signs a URL, up to its next parameter.
363
+ type: "assignment",
364
+ pattern: new RegExp(String.raw `([?&](?:[xX]-(?:${anyCase("amz")}|${anyCase("goog")})-)?${anyCase("sig")}(?:${anyCase("nature")})?=)(?!\[ISY_REDACTED|\$)[^\s&"'#]{8,}`, "g"),
365
+ replacement: `$1${marker("assignment")}`,
366
+ },
367
+ {
368
+ // `--password hunter2000`, `--api-key "…"`: a name like any other, with a
369
+ // space where `=` goes. `--password-file /x` has a tail no secret's name has,
370
+ // and what starts with a dash is the next flag.
371
+ type: "assignment",
372
+ pattern: new RegExp(String.raw `(?<![A-Za-z0-9_.-])(-${secretName()})([ \t]+)(["']?)(?!-)${SECRET_VALUE}`, "g"),
124
373
  replacement: `$1$2$3${marker("assignment")}`,
125
374
  },
126
375
  {
127
- // A camelCase name counts where it is plainly data — a quoted key with a
128
- // quoted value (`{"accessToken":"…"}`) or `name=value` with no space, as
129
- // `.npmrc` writes `_authToken=` — and not in `adminPassword = someVariable`.
376
+ // From the word back to the name, as the name from its front is a scan at every capital.
377
+ // The word is looked through as far as the next such name, which looks on from there.
378
+ type: "assignment",
379
+ pattern: new RegExp(String.raw `${KEY_END}(["']?\]?\s*[=:]\s*["']?)(?=(?:(?!${KEY_END}\]?[=:])[^\s"']){0,256}?${GENERATED_RUN})${SECRET_VALUE}`, "g"),
380
+ replacement: `KEY$1${marker("assignment")}`,
381
+ },
382
+ {
383
+ // A cookie header's value runs to the end of the line, spaces and `;` included, or to a quote.
384
+ // It opens with a name and `=`, which `cookie == null` and `cookie = jar.get()` do not.
385
+ //
386
+ // After every rule that goes by a name, as this one takes whatever stands in its way:
387
+ // ahead of them, `--cookie=k=v --password='…'` lost the name and kept what it named. So a
388
+ // marker may stand for its first pair, or for that pair's name, and the rest still goes where
389
+ // it is a pair. A flag, a URL or the next command is none (`--cookie=cookies.txt -u "bob:…"`),
390
+ // and is left to the rules after this one.
391
+ type: "cookie",
392
+ pattern: /\b(cookie["'`]?[ \t]*[:=][ \t]*["'`]?)(?:(?!\[ISY_REDACTED)(?=[^\s"'`=;,$<{]{1,256}=[^=])|(?=\[ISY_REDACTED:\w+\](?:=[^=]|[ \t;]*(?!-)[^\s"'`=;,$<{\/:?]{1,256}=[^=])))[^"'`\r\n]{8,}/gi,
393
+ replacement: `$1${marker("cookie")}`,
394
+ },
395
+ {
396
+ // The quote opens before the name or after its colon, and only one of the two
397
+ // groups takes part, so together they are that one quote.
130
398
  type: "assignment",
131
- pattern: new RegExp(String.raw `(?<=["'])(${CAMEL_NAME})(["']\s*:\s*["'])${SECRET_VALUE}|(?<![A-Za-z0-9_.-])(${CAMEL_NAME})(=)${SECRET_VALUE}`, "g"),
132
- replacement: `$1$2$3$4${marker("assignment")}`,
399
+ pattern: new RegExp(String.raw `\b(${CURL_USER_FLAG}(?:(["'])${CURL_USER}|${CURL_USER}(["'])))${quotedTo(String.raw `\2\3`)}`, "g"),
400
+ replacement: `$1${marker("assignment")}`,
401
+ },
402
+ {
403
+ type: "assignment",
404
+ pattern: new RegExp(String.raw `\b(${CURL_USER_FLAG}["']?${CURL_USER})(?!\[ISY_REDACTED)[^\s"'$][^\s"']*`, "g"),
405
+ replacement: `$1${marker("assignment")}`,
406
+ },
407
+ {
408
+ // One pass for both spellings, as each is a scan of every word for every client.
409
+ //
410
+ // ponytail: one pass over the text, as a second doubles what any text with a password
411
+ // costs and goes over all it grew by. So a flag's second use stays (`curl -b k=a -b j=b`),
412
+ // and so does a flag a match of another kind took the way to: `ssh-keygen -t rsa && curl
413
+ // -N https://x -b k=b` loses `curl` to `-N`, `plink a mysql plink -pw b` loses `-pw` to
414
+ // `-p`. Tracking each client's flags outside the pattern is the way up.
415
+ type: "assignment",
416
+ pattern: new RegExp(String.raw `(${PASSWORD_FLAG})(?:(["'])${quotedTo(String.raw `\2`)}|(["']?)(?!\[ISY_REDACTED|(?<=\s)-)[^\s"'$][^\s"']*)`, "g"),
417
+ replacement: `$1$2$3${marker("assignment")}`,
133
418
  },
134
419
  ];
135
420
  /** A JSON key is data, never code, so any spelling of a secret's name counts. */
@@ -165,36 +450,352 @@ export function applyRules(text, rules, onMatch) {
165
450
  }
166
451
  return result;
167
452
  }
453
+ /** `NAME=value` as a dotenv file or a shell write spells it; code puts spaces round its `=`. */
454
+ const DOTENV_PAIR = /(?<![\w.$-])([A-Za-z_][A-Za-z0-9_]*)=("[^"\n]*"|'[^'\n]*'|[^\s"']+)/g;
455
+ /** A line that is one value and nothing else: `cut -d= -f2 .env`, `node -p process.env.X`. */
456
+ const BARE_VALUE = /^[^\s"'{}[\]<>=]+=*$/;
457
+ /** A word or a number: `password`, `changeme`, `production` and `12345678` are all through normal text. */
458
+ const PLAIN_WORD = /^(?:[A-Z]?[a-z]+|[A-Z]+|\d+)$/;
459
+ const MIN_LEARNED_VALUE = 12;
460
+ /** ponytail: a session names far fewer. The first ones win. */
461
+ const MAX_LEARNED_VALUES = 500;
462
+ /**
463
+ * A value worth cutting wherever it turns up. Under a secret's name it only has to
464
+ * be no plain word. Under any other, it has to be long and not plainly public:
465
+ * `BASE_URL=http://localhost:3000`, `APP_DIR=/srv/app`, `HOST=docs.example.com`, a name:
466
+ * `MODEL=whisper-large-v3`, `APP_NAME=MyCoolApplication`, a list: `METHODS=GET,POST,PUT`,
467
+ * or words and spaces: `START_CMD="npm run build"`, whose going would blind whatever
468
+ * reads the commands. A generated value gives itself away with a sign none of those
469
+ * has, or twelve letters and digits in a row, both among them.
470
+ *
471
+ * ponytail: a passphrase in words, or generated in short groups (`ABCD1-EFGH2-IJKL3`),
472
+ * under a name nothing knows stays where it is quoted outside the read itself; telling
473
+ * it from a command or a name takes more than its shape.
474
+ */
475
+ function worthLearning(name, value) {
476
+ if (value.length < MIN_SENSITIVE_VALUE || value.startsWith("$"))
477
+ return false;
478
+ if (value.includes(REDACTION_MARKER) || PLAIN_WORD.test(value))
479
+ return false;
480
+ if (name !== undefined && SENSITIVE_KEY.test(name))
481
+ return true;
482
+ if (value.length < MIN_LEARNED_VALUE || /\s/.test(value))
483
+ return false;
484
+ if (/^[~.]{0,2}\/[\w./-]*$/.test(value))
485
+ return false;
486
+ return !/^[\w.:/,=-]*$/.test(value) || GENERATED.test(value);
487
+ }
488
+ /**
489
+ * What a dotenv file holds is a secret by where it sits, whatever it looks like
490
+ * and whatever it is called, so the rules cannot be asked to know it: `MAILER_PHRASE`
491
+ * names nothing they know, and the value quoted in a later sentence has no name
492
+ * at all. What a dotenv call read or wrote is searched for values here, and they go
493
+ * from the whole session at the end (`cutLearnedValues`). Only names written the way
494
+ * such files write them count, so that a test run under `--env-file` does not teach
495
+ * its log's `id=…`.
496
+ *
497
+ * ponytail: only what the session showed. A value printed by a script that read
498
+ * the file itself, or typed in a prompt, is known to nothing here; so is one under
499
+ * the floors above, which keep short values from shredding the text.
500
+ */
501
+ function learnValues(value, context) {
502
+ // A loop and not a call per level: what a dotenv read returned goes whatever it holds,
503
+ // and a result nested deeper than the stack must not take the session with it.
504
+ const pending = [value];
505
+ while (pending.length > 0) {
506
+ const item = pending.pop();
507
+ if (Array.isArray(item))
508
+ for (const inner of item)
509
+ pending.push(inner);
510
+ else if (isObject(item))
511
+ for (const inner of Object.values(item))
512
+ pending.push(inner);
513
+ else if (typeof item === "string")
514
+ learnText(item, context);
515
+ }
516
+ }
517
+ function learnText(value, context) {
518
+ // `printf 'A=1\nB=2\n' > .env` holds its lines as written, and `echo K=\"v\" > .env` a quoted value.
519
+ const text = value.replace(/\\n/g, "\n").replace(/\\(["'])/g, "$1");
520
+ const learn = (name, found) => {
521
+ if (context.learned.size < MAX_LEARNED_VALUES && worthLearning(name, found))
522
+ context.learned.add(found);
523
+ };
524
+ for (const [, name, written] of text.matchAll(DOTENV_PAIR)) {
525
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name) && !SENSITIVE_KEY.test(name))
526
+ continue;
527
+ if (/^["']/.test(written)) {
528
+ learn(name, written.slice(1, -1));
529
+ continue;
530
+ }
531
+ // A shell ends a word at an operator the value does not hold: `VALUE=x; echo "K=$VALUE"`,
532
+ // `echo K=x>.env`. A dotenv file may hold one in its value, so the whole goes as well.
533
+ const whole = written.replace(/;$/, "");
534
+ learn(name, whole);
535
+ const end = whole.search(/[;|&<>)\\]/);
536
+ if (end > 0)
537
+ learn(name, whole.slice(0, end));
538
+ }
539
+ for (const line of text.split("\n")) {
540
+ const bare = line.trim();
541
+ if (BARE_VALUE.test(bare) && /[A-Za-z]/.test(bare) && /\d/.test(bare))
542
+ learn(undefined, bare);
543
+ }
544
+ }
545
+ /** What says what a record is, not what anybody said: the parse reads these, and they stay. */
546
+ const NOT_SAID = new Set([
547
+ ...PATH_KEYS,
548
+ "type",
549
+ "role",
550
+ "uuid",
551
+ "parentUuid",
552
+ "sessionId",
553
+ "id",
554
+ "tool_use_id",
555
+ "name",
556
+ "model",
557
+ "timestamp",
558
+ "version",
559
+ "gitBranch",
560
+ ]);
561
+ /**
562
+ * What may be walked along values that then are not there, over a text of some length:
563
+ * one of 100 KB of a letter took a minute over 200 KB of that letter. Past this the text
564
+ * goes whole, since what could not be looked through may hold one.
565
+ *
566
+ * ponytail: a text held up against a value that keeps almost matching, like thousands of
567
+ * zeros against one that starts with dozens, is lost with it. Failure links if a real one is.
568
+ */
569
+ const walksOver = (length) => ({ left: 4096 + 8 * length });
570
+ /** Two bits up per character, so that one falls off the top after `MIN_SENSITIVE_VALUE`, which no value is shorter than. */
571
+ const hashedOn = (hash, code) => ((hash << 2) ^ code) & 0xffff;
572
+ /** Of values in sorted order, so that what the first and the last share, all do. */
573
+ function branchOf(values, depth) {
574
+ const first = values[0];
575
+ const last = values.at(-1);
576
+ let end = depth;
577
+ while (end < first.length && first[end] === last[end])
578
+ end += 1;
579
+ const groups = new Map();
580
+ for (const value of values) {
581
+ if (value.length > end)
582
+ groups.set(value.charCodeAt(end), [...(groups.get(value.charCodeAt(end)) ?? []), value]);
583
+ }
584
+ const parts = new Map();
585
+ for (const [code, group] of groups)
586
+ parts.set(code, branchOf(group, end + 1));
587
+ return { common: first.slice(depth, end), value: first.length === end ? first : undefined, parts };
588
+ }
589
+ /**
590
+ * Finds the next of some values, the longest of those that start together, in one pass
591
+ * over the text whatever their number. A loop over them costs that number times the
592
+ * session's size; one alternation of them is slower than that below a few hundred, and
593
+ * does not compile when they are long.
594
+ */
595
+ function valueFinder(values) {
596
+ const seen = new Uint8Array(1 << 16);
597
+ for (const value of values) {
598
+ let hash = 0;
599
+ for (let i = 0; i < MIN_SENSITIVE_VALUE; i += 1)
600
+ hash = hashedOn(hash, value.charCodeAt(i));
601
+ seen[hash] = 1;
602
+ }
603
+ const root = branchOf([...values].sort(), 0);
604
+ return (text, from, walks) => {
605
+ let hash = 0;
606
+ for (let end = from; end < text.length; end += 1) {
607
+ hash = hashedOn(hash, text.charCodeAt(end));
608
+ if (seen[hash] === 0 || end - from < MIN_SENSITIVE_VALUE - 1)
609
+ continue;
610
+ const at = end - MIN_SENSITIVE_VALUE + 1;
611
+ let found;
612
+ let next = at;
613
+ for (let branch = root; branch !== undefined; next += 1) {
614
+ const { common } = branch;
615
+ let same = 0;
616
+ while (same < common.length && text.charCodeAt(next + same) === common.charCodeAt(same))
617
+ same += 1;
618
+ next += same;
619
+ if (same < common.length)
620
+ break;
621
+ found = branch.value ?? found;
622
+ branch = branch.parts.get(text.charCodeAt(next));
623
+ }
624
+ walks.left -= next - at - (found?.length ?? 0);
625
+ if (walks.left < 0)
626
+ return undefined;
627
+ if (found !== undefined)
628
+ return [at, found];
629
+ }
630
+ return undefined;
631
+ };
632
+ }
633
+ /**
634
+ * What a session may cut before a text holding a learned value goes whole, as one too
635
+ * dear to look through does. Each cut makes the text longer and holds a string of its
636
+ * own until the text is done, and finding one spends no walks, so that a value repeated
637
+ * through a few gzipped kilobytes is what the heap has to hold. The most in a real
638
+ * session is 5271.
639
+ *
640
+ * ponytail: one count for a session, so that past it a text with a single hit is lost
641
+ * with the rest. Per-text limits if a real session ever comes near.
642
+ */
643
+ const MOST_CUTS = 1_000_000;
644
+ function withoutValues(value, find, context, key) {
645
+ if (typeof value === "string") {
646
+ if (key !== undefined && NOT_SAID.has(key))
647
+ return value;
648
+ let text = "";
649
+ let from = 0;
650
+ const walks = walksOver(value.length);
651
+ for (let hit = find(value, 0, walks); hit !== undefined; hit = find(value, from, walks)) {
652
+ if ((context.counts.dotenv ?? 0) >= MOST_CUTS) {
653
+ count(context, "oversized", 1);
654
+ return marker("oversized");
655
+ }
656
+ text += value.slice(from, hit[0]) + marker("dotenv");
657
+ from = hit[0] + hit[1].length;
658
+ count(context, "dotenv", 1);
659
+ }
660
+ if (walks.left < 0) {
661
+ count(context, "oversized", 1);
662
+ return marker("oversized");
663
+ }
664
+ return text + value.slice(from);
665
+ }
666
+ if (Array.isArray(value))
667
+ return value.map((item) => withoutValues(item, find, context));
668
+ if (!isObject(value))
669
+ return value;
670
+ const result = {};
671
+ for (const [entryKey, entry] of Object.entries(value))
672
+ result[entryKey] = withoutValues(entry, find, context, entryKey);
673
+ return result;
674
+ }
675
+ /**
676
+ * After the whole session, because a value can be quoted long before the read that
677
+ * shows what it is. A line is parsed only if it holds one, and the cut is made on
678
+ * its strings, as one made in the JSON could land across an escape.
679
+ */
680
+ function cutLearnedValues(lines, context) {
681
+ if (context.learned.size === 0)
682
+ return lines;
683
+ // Longest first: a value inside another must not leave the rest of that one.
684
+ const values = [...context.learned].sort((a, b) => b.length - a.length);
685
+ const inText = valueFinder(values);
686
+ const inLine = valueFinder(values.map((value) => JSON.stringify(value).slice(1, -1)));
687
+ return lines.map((line) => {
688
+ const walks = walksOver(line.length);
689
+ if (inLine(line, 0, walks) === undefined && walks.left >= 0)
690
+ return line;
691
+ try {
692
+ return JSON.stringify(withoutValues(JSON.parse(line), inText, context));
693
+ }
694
+ catch {
695
+ return withoutValues(line, inText, context);
696
+ }
697
+ });
698
+ }
699
+ /**
700
+ * How code reaches the environment, which reads like a file called `process.env`.
701
+ *
702
+ * ponytail: the objects it is usually read from. Any other's `.env` in a one-liner
703
+ * costs that one command's result.
704
+ */
705
+ const CODE_ENV = /(?:^|\.)(?:process|meta|this|self|globalThis|window|Deno|Bun|ctx|c|os|context|event|req|request)\.env$/;
706
+ /** `.env`, `.env.local`, and the other way of naming one: `prod.env`, `.x.env`, `$STAGE.env`. */
168
707
  function isDotenvPath(filePath) {
169
- return typeof filePath === "string" && basename(filePath).startsWith(".env");
708
+ if (typeof filePath !== "string")
709
+ return false;
710
+ const name = basename(filePath);
711
+ return name.startsWith(".env") || (/^[\w.*?${}-]*\.env$/.test(name) && !CODE_ENV.test(name));
170
712
  }
171
- /** Commands that print a file they are given, or load it into the shell. */
172
- const SHELL_READER = /^\s*(?:sudo\s+)?(?:cat|head|tail|less|more|bat|nl|grep|egrep|fgrep|rg|sed|awk|jq|xxd|od|diff|source|\.|git\s+(?:show|diff|log|blame)|get-content|gc|type)(?:\s|$)/i;
173
713
  /**
174
- * `cat .env`, `grep KEY config/.env.local`, `source .env`: a shell call that
175
- * reads a dotenv file is as much a read of it as `Read {file_path}` is, and
176
- * its output is the file. The command itself stays — it names the file, not
177
- * what is in it.
714
+ * Commands that can name a dotenv file without printing any of it. The list runs
715
+ * this way round because the other one has no end: `cut`, `node -e`, `python -c`,
716
+ * `docker exec … cat`, anything behind `ssh` or `timeout`.
717
+ */
718
+ const SHELL_NO_READ = /^\s*(?:(?:sudo|if|then|elif|else|while|until|do)\s+|[!{(]\s*)*(?:ls|ll|stat|file|wc|test|test-path|\[\[?|echo|printf|touch|chmod|chown|mkdir|rm|mv|cp|ln|cd|git\s+(?:add|rm|mv|status|commit|check-ignore|ls-files))(?:\s|$)/i;
719
+ /** Where a shell line, or the code it hands an interpreter, ends one word and starts the next. */
720
+ const WORD_BREAK = /[\s"'`(){}=,;|&<>]+/;
721
+ /**
722
+ * `cat .env`, `cut -d= -f2 config/.env.local`, `node -e "…readFileSync('.env')…"`,
723
+ * `source .env`: a shell call that names a dotenv file is as much a read of it as
724
+ * `Read {file_path}` is, and what it prints may be any of the file. The command
725
+ * itself stays — it names the file, not what is in it. A revision goes with its
726
+ * word: `git show origin/main:.env`.
727
+ *
728
+ * ponytail: by the name in the command. `node scripts/x.js` opening the file
729
+ * itself, or `load_dotenv()` with no path, still goes up; scrubbing the file's
730
+ * values at upload is the way up.
178
731
  */
179
732
  function readsDotenv(command) {
180
733
  if (typeof command !== "string" || !command.includes(".env"))
181
734
  return false;
182
- return commandSegments(withoutHeredocs(command)).some((segment) => SHELL_READER.test(segment) &&
183
- segment.trim().split(/\s+/).slice(1).some((word) => isDotenvPath(word.replace(/["'`]/g, "").replace(/^\w*:/, ""))));
735
+ const names = (text) => text.split(WORD_BREAK).some((word) => isDotenvPath(word.replace(/^.*:/, "")));
736
+ const text = withoutHeredocs(command);
737
+ // What a substitution or `xargs` turns up goes to whatever takes it: `cat $(ls .env*)`.
738
+ if ((text.match(/\$\([^()]*\)/g) ?? []).some(names) || (/\|\s*xargs\b/.test(text) && names(text)))
739
+ return true;
740
+ // A backtick or a `$(` left in a segment still runs what it holds.
741
+ return commandSegments(text).some((segment) => (!SHELL_NO_READ.test(segment) || /`|\$\(/.test(segment)) && names(segment));
184
742
  }
185
- /** Commands that write the file they are given: `tee` and PowerShell's own. */
186
- const SHELL_WRITER = /^\s*(?:sudo\s+)?(?:tee|set-content|sc|add-content|ac|out-file)(?:\s|$)/i;
187
- const unquoted = (word) => word.replace(/["'`]/g, "");
188
- /** The dotenv file a statement redirects or tees into, if it writes one. */
743
+ /** Commands that write the file they are given: `tee`, PowerShell's own, `dd of=`, and `cp` from stdin. */
744
+ const SHELL_WRITER = /^\s*(?:sudo\s+)?(?:tee|set-content|sc|add-content|ac|out-file|new-item|dd|(?:cp|install)(?=\s.*\/dev\/stdin))(?:\s|$)/i;
745
+ /** `tee` behind whatever runs it — `sudo -u app`, `doas`, `ssh host 'tee …'`, `/usr/bin/` — still writes. */
746
+ const TEE = /(?:^|[\s/"'])(?:tee|tee-object)(?=\s|$)/i;
747
+ /** A word as the shell hands it over: quotes gone, `\ ` a plain space; a Windows `\` stays. */
748
+ const unquoted = (word) => word.replace(/\\( )|["'`]/g, "$1");
749
+ /** A quoted or escaped word keeps its spaces: `> "My Projects/.env"`. */
750
+ const REDIRECT = String.raw `>\s*((?:"[^"]*"|'[^']*'|\\.|[^\s;&|<>"'\\])+)`;
751
+ const ANY_REDIRECT = new RegExp(REDIRECT, "g");
752
+ /**
753
+ * Quotes go first and run to the end if they never close, so nothing is scanned twice;
754
+ * ahead of them what a backslash escapes, which opens nothing: `echo don\'t > .env`.
755
+ */
756
+ const REDIRECT_PAST_QUOTES = new RegExp(String.raw `\\.|'[^']*(?:'|$)|"(?:[^"\\]|\\[\s\S]?)*(?:"|$)|${REDIRECT}`, "g");
757
+ /**
758
+ * Commands whose quoted arguments are only text: `git commit -m "x > .env"` writes
759
+ * nothing. What runs its argument is not here, as `sh -c`, `ssh` and `sudo` hold a
760
+ * real write in those quotes.
761
+ */
762
+ const TEXT_ARGUMENTS = /^\s*(?:echo|printf|grep|egrep|fgrep|rg|git\s+(?:commit|tag|log|grep)|gh)(?:\s|$)/i;
763
+ /** `git commit -m "$(cat <<'EOF'`: what such a heredoc holds is a message. */
764
+ const TAKES_MESSAGE = /^\s*(?:git\s+(?:commit|tag)|gh)\s/;
765
+ /** A path as a call's first argument, in quotes a shell may have had to escape. */
766
+ const PATH_ARGUMENT = String.raw `\(\s{0,8}\\?["'\`]([^"'\`\\\n]{1,256})\\?["'\`]`;
767
+ /**
768
+ * What a one-liner calls to write a file it names: `fs.writeFileSync('.env', …)`,
769
+ * `Path('.env').write_text(…)`, and `open('.env', 'w')`, as `open` alone only reads.
770
+ *
771
+ * ponytail: a literal path, in the usual calls. A path in the script's own variable,
772
+ * or a call not listed, leaves the one-liner as it was; parsing each language is the
773
+ * way up.
774
+ */
775
+ const WRITE_CALL = new RegExp(String.raw `\b(?:(?:write|append)File(?:Sync)?|createWriteStream|file_put_contents|(?:File|IO)\.write)${PATH_ARGUMENT}` +
776
+ String.raw `|\bf?open${PATH_ARGUMENT}\s{0,8},\s{0,8}(?:mode\s{0,8}=\s{0,8})?\\?["'][a-z]{0,2}[wax+]` +
777
+ String.raw `|\bPath${PATH_ARGUMENT}\s{0,8}\)\.write_`, "g");
778
+ /** The dotenv file a statement redirects, tees or opens to write, if it writes one. */
189
779
  function dotenvTarget(statement) {
190
- for (const segment of commandSegments(statement)) {
191
- for (const redirect of segment.matchAll(/>\|?\s*([^\s;&|<>]+)/g)) {
192
- if (isDotenvPath(unquoted(redirect[1])))
780
+ // `>|` overrides `noclobber` and is no pipe.
781
+ for (const segment of commandSegments(statement.replace(/>\|/g, ">"))) {
782
+ const text = TEXT_ARGUMENTS.test(segment);
783
+ for (const redirect of segment.matchAll(text ? REDIRECT_PAST_QUOTES : ANY_REDIRECT)) {
784
+ if (redirect[1] !== undefined && isDotenvPath(unquoted(redirect[1])))
193
785
  return unquoted(redirect[1]);
194
786
  }
195
- if (!SHELL_WRITER.test(segment))
787
+ if (text)
788
+ continue;
789
+ for (const call of segment.matchAll(WRITE_CALL)) {
790
+ const path = call[1] ?? call[2] ?? call[3];
791
+ if (isDotenvPath(path))
792
+ return path;
793
+ }
794
+ const writer = SHELL_WRITER.exec(segment) ?? TEE.exec(segment);
795
+ if (!writer)
196
796
  continue;
197
- const named = segment.trim().split(/\s+/).slice(1).map(unquoted).find(isDotenvPath);
797
+ const after = segment.slice(writer.index + writer[0].length);
798
+ const named = after.trim().split(/\s+/).map((word) => unquoted(word).replace(/^of=/, "")).find(isDotenvPath);
198
799
  if (named)
199
800
  return named;
200
801
  }
@@ -210,8 +811,11 @@ function statements(line) {
210
811
  let quote;
211
812
  for (let i = 0; i < line.length; i += 1) {
212
813
  const char = line[i];
213
- if (quote !== undefined) {
214
- if (char === quote && (quote === "'" || line[i - 1] !== "\\"))
814
+ if (char === "\\" && quote !== "'") {
815
+ i += 1;
816
+ }
817
+ else if (quote !== undefined) {
818
+ if (char === quote)
215
819
  quote = undefined;
216
820
  }
217
821
  else if (char === '"' || char === "'" || char === "`") {
@@ -227,8 +831,64 @@ function statements(line) {
227
831
  parts.push(line.slice(start));
228
832
  return { parts, open: quote !== undefined };
229
833
  }
230
- /** A write that closes a group or a substitution: `{ …; } > .env`, `(…) | tee .env`. */
231
- const GROUP_WRITE = /[})]\s*(?:\d?>|&>|\|)/;
834
+ /** `VALUE=x`, then `echo "K=$VALUE" > .env`: the value sits where the write only names it. */
835
+ function expandsAssigned(statement, assigned) {
836
+ for (const match of statement.matchAll(/\$\{?([A-Za-z_]\w*)/g))
837
+ if (assigned.has(match[1]))
838
+ return true;
839
+ return false;
840
+ }
841
+ /** A write that closes a group or a substitution: `{ …; } > .env`, `(…) | tee .env`, `done > .env`. */
842
+ const GROUP_WRITE = /(?:[})]|\b(?:done|fi|esac))\s*(?:\d?>|&>|\|)/;
843
+ /** A write whose values come later or from around it: `exec 3>.env; echo K=v >&3`, `export K=v; envsubst < t > .env`. */
844
+ const WRITES_FROM_AROUND = /^\s*exec\b|\benvsubst\b/;
845
+ /**
846
+ * `F=.env`, and a loop over a list: both say what `$F` is, and that `F` was set. A quote
847
+ * right behind the `=` makes the value one word, one anywhere else closes something.
848
+ */
849
+ const ASSIGNMENT = /(?<![\w$])([A-Za-z_]\w*)=("[^"]*"|'[^']*'|[^\s;&|]*)/g;
850
+ const FOR_LOOP = /\bfor\s+([A-Za-z_]\w*)\s+in\s([^\n;]{0,2000})/g;
851
+ const VARIABLE = /\$\{?([A-Za-z_]\w*)\}?/g;
852
+ /** `${F:-.env}`, `${F:=.env}`: nothing else in the command says what `F` is. */
853
+ const VARIABLE_DEFAULT = /\$\{\w+:?[-=]([^{}]*)\}/g;
854
+ /** What says only where a path starts or how it is named: `$HOME/.env`, `$STAGE.env`. */
855
+ const VARIABLE_DIR = /\$\{?\w+\}?(?:\/|(?=\.env\b))/g;
856
+ /** `F="$(pwd)/.env"`: what a substitution turns up says as little. */
857
+ const SUBSTITUTED_DIR = /\$\([^()]*\)\/?/g;
858
+ /** What sed's `a`, `i` and `c` open with, right against the text: `$aK=v`, `1iK=v`, `/^K=/cK=v`. */
859
+ const SED_TEXT_COMMAND = /(?<=^|['"\s])(?:\$|\d{1,12}|\/[^/\n]{0,256}\/)[ \t]{0,8}[aic]\\?[ \t]{0,8}/g;
860
+ /**
861
+ * An in-place editor wherever a statement runs it: behind `time`, `/usr/bin/`,
862
+ * `docker exec app`, in the quotes of `ssh host "…"`. Only where to read from, as the
863
+ * parse says whether it edits and what.
864
+ *
865
+ * ponytail: up to 16 flags ahead of its script, as any run of them is tried again from each
866
+ * word in it, and the usual editors. `time sed 's/a/b/' -i .env` or `sh -c "ex .env"` keeps
867
+ * its script, as a command nothing recognises does.
868
+ */
869
+ const EDITOR_CALL = /(?<![\w.-])(?:g?sed|g?awk|perl|ruby)(?:\s+-\S+){0,16}?\s+(?:-[a-zA-Z0-9]*[iI]|--in-place|--include)/;
870
+ /** What hands an editor its files from in front of it: `find … -exec sed -i`, `… | xargs sed -i`. */
871
+ const FEEDS_FILES = /\s-(?:exec|ok)(?:dir)?\s|\bxargs\s/;
872
+ /**
873
+ * The text of an edit's script: `s|a|b|` and `s#a#b#` split where `s/a/b/` does, and
874
+ * `sub("a","b")`, whose values have no name to go by, at its quotes.
875
+ */
876
+ function learnEdit(statement, context) {
877
+ const script = statement.replace(SED_TEXT_COMMAND, "\n");
878
+ const lines = script.replaceAll(/(?<![\w-])s([^\w\s\\])/.exec(script)?.[1] ?? "/", "\n");
879
+ learnValues(lines, context);
880
+ learnValues(lines.replace(/["']/g, "\n"), context);
881
+ }
882
+ /**
883
+ * What a session's commands naming a dotenv file may come to, past which one goes
884
+ * whole. Each statement of them is held up to a dozen patterns, several times what a
885
+ * byte of any other text costs, on the thread that serves requests. The most in a real
886
+ * session is 3.1 MB, out of 552 MB, and in any other 67 KB.
887
+ *
888
+ * ponytail: what goes whole reads as no write to the parse, and teaches nothing of what
889
+ * it held. Raise it if sessions come near, or take redaction off that thread.
890
+ */
891
+ const DOTENV_COMMAND_CHARS = 4 * 1024 * 1024;
232
892
  /**
233
893
  * `cat > .env << 'EOF'`, `echo "KEY=…" >> .env.local`, `… | tee .env`: a shell
234
894
  * call that writes a dotenv file holds what it writes, so unlike a read the
@@ -237,63 +897,222 @@ const GROUP_WRITE = /[})]\s*(?:\d?>|&>|\|)/;
237
897
  * itself (`python - <<PY` opening `.env`) — and the statement keeps its target,
238
898
  * so `sed -i` beside it is still an edit and the parse still sees a write.
239
899
  */
240
- function cutDotenvWrites(command) {
900
+ function cutDotenvWrites(command, context) {
241
901
  if (!command.includes(".env"))
242
902
  return command;
903
+ if (!spend(context.dotenvCommands, command.length)) {
904
+ count(context, "oversized", 1);
905
+ return marker("oversized");
906
+ }
907
+ // Once, as a statement asking for itself would rescan the command for each one.
908
+ const assigned = new Set();
909
+ const files = new Map();
910
+ // ponytail: one budget for the command, as a long name used in every statement otherwise
911
+ // grows it past what memory holds. A write past the budget reads as no write, as one
912
+ // through a variable nothing knows does; a real command spends a few hundred bytes of it.
913
+ let room = 1 << 16;
914
+ const resolved = (text) => text.replace(VARIABLE_DEFAULT, "$1").replace(VARIABLE, (whole, name) => {
915
+ const file = files.get(name);
916
+ if (file === undefined || file.length > room)
917
+ return whole;
918
+ room -= file.length;
919
+ return file;
920
+ });
921
+ // ponytail: a substitution inside one, the deepest a path is usually built.
922
+ const unsubstituted = command.replace(SUBSTITUTED_DIR, "").replace(SUBSTITUTED_DIR, "");
923
+ // In the order they run, for `A=.env; B=$A`.
924
+ for (const [, name, list] of [...unsubstituted.matchAll(ASSIGNMENT), ...command.matchAll(FOR_LOOP)]) {
925
+ assigned.add(name);
926
+ const file = resolved(list).split(/\s+/).map(unquoted).find(isDotenvPath);
927
+ // A glob in the list is that file as far as a write goes.
928
+ if (file !== undefined)
929
+ files.set(name, file.replace(/[*?]/g, ""));
930
+ }
931
+ const parsedEdit = (text) => shellEditWords(resolved(text).replace(VARIABLE_DIR, "").replace(/\\\n/g, " ")).find(isDotenvPath);
932
+ const editedFile = (text) => {
933
+ const call = EDITOR_CALL.exec(text);
934
+ const before = text.slice(0, call?.index ?? 0);
935
+ // `git commit -m "sed -i …"` only speaks of one.
936
+ if (call === null || TEXT_ARGUMENTS.test(before.slice(before.lastIndexOf("|") + 1)))
937
+ return parsedEdit(text);
938
+ return parsedEdit(text.slice(call.index)) ?? (FEEDS_FILES.test(before) ? resolved(before).split(WORD_BREAK).find(isDotenvPath) : undefined);
939
+ };
243
940
  const lines = command.split("\n");
244
941
  const kept = [];
245
942
  let written;
246
943
  let spread = false;
247
944
  for (let i = 0; i < lines.length; i += 1) {
248
945
  let writes = false;
249
- const { parts, open } = statements(lines[i]);
250
- if (open)
946
+ // A backslash joins them, to the shell and so here.
947
+ const first = i;
948
+ while (lines[i].endsWith("\\") && i + 1 < lines.length)
949
+ i += 1;
950
+ const line = lines.slice(first, i + 1).join("\n");
951
+ const { parts, open } = statements(line);
952
+ // A line that goes on in the next (a trailing pipe, an open quote) is one
953
+ // statement with it, and the values may sit on either.
954
+ if (open || /[\\|]\s*$/.test(line))
251
955
  spread = true;
252
956
  kept.push(parts
253
957
  .map((part) => {
254
- const target = dotenvTarget(part);
255
- if (target === undefined)
958
+ // Once per statement of what can be a few hundred thousand, so no check for one that names no file.
959
+ if (!part.includes(".env") && (files.size === 0 || !part.includes("$")))
256
960
  return part;
961
+ const indent = /^\s*/.exec(part)[0];
962
+ const target = dotenvTarget(resolved(part));
963
+ if (target === undefined) {
964
+ // The script holds the value, and the parse needs only to see an edit.
965
+ const edited = editedFile(part);
966
+ if (edited === undefined)
967
+ return part;
968
+ writes = true;
969
+ learnEdit(part, context);
970
+ const edit = `sed -i ${marker("dotenv")} ${edited}`;
971
+ if (expandsAssigned(part, assigned)) {
972
+ spread = true;
973
+ written ??= edit;
974
+ }
975
+ return `${indent}${edit}${part.slice(part.trimEnd().length)}`;
976
+ }
977
+ const write = `${marker("dotenv")} > ${target}`;
257
978
  writes = true;
258
- written ??= target;
259
- if (GROUP_WRITE.test(part))
979
+ written ??= write;
980
+ learnValues(part, context);
981
+ if (GROUP_WRITE.test(part) || WRITES_FROM_AROUND.test(part) || expandsAssigned(part, assigned))
260
982
  spread = true;
261
- return `${/^\s*/.exec(part)[0]}${marker("dotenv")} > ${target}`;
983
+ return `${indent}${write}`;
262
984
  })
263
985
  .join(""));
264
- const terminator = HEREDOC.exec(lines[i])?.[2];
986
+ const terminator = HEREDOC.exec(line)?.[2];
265
987
  if (terminator === undefined)
266
988
  continue;
267
- let end = lines.findIndex((line, j) => j > i && line.trim() === terminator);
268
- if (end === -1)
269
- end = lines.length;
989
+ let end = i + 1;
990
+ while (end < lines.length && lines[end].trim() !== terminator)
991
+ end += 1;
270
992
  const body = lines.slice(i + 1, end);
271
993
  if (writes) {
994
+ learnValues(body.join("\n"), context);
995
+ if (expandsAssigned(body.join("\n"), assigned))
996
+ spread = true;
272
997
  i = end;
273
998
  continue;
274
999
  }
275
- const namesDotenv = body.some((line) => line.split(/[\s"'`()=,;|&<>]+/).some(isDotenvPath));
276
- kept.push(...(namesDotenv ? [marker("dotenv")] : body), ...lines.slice(end, end + 1));
1000
+ const message = commandSegments(parts.find((part) => HEREDOC.test(part))).every((segment) => TAKES_MESSAGE.test(segment));
1001
+ // A shell or an interpreter fed a script that writes the file: what the script
1002
+ // holds is written as surely as what `cat > .env` is fed.
1003
+ let bodyWrites;
1004
+ for (const line of message ? [] : body) {
1005
+ const edited = editedFile(line);
1006
+ if (edited !== undefined)
1007
+ learnEdit(line, context);
1008
+ bodyWrites ??= dotenvTarget(resolved(line)) ?? edited;
1009
+ }
1010
+ if (bodyWrites !== undefined) {
1011
+ learnValues(body.join("\n"), context);
1012
+ if (expandsAssigned(body.join("\n"), assigned)) {
1013
+ spread = true;
1014
+ written ??= `${marker("dotenv")} > ${bodyWrites}`;
1015
+ }
1016
+ }
1017
+ // A body is code as often as not, where `cfg.env` is a property and not a file.
1018
+ const namesDotenv = bodyWrites !== undefined || (!message && body.some((line) => line.split(WORD_BREAK).some((word) => basename(word).startsWith(".env"))));
1019
+ // One at a time: spread, a body of a few hundred thousand lines overflows the stack.
1020
+ for (const line of namesDotenv ? [marker("dotenv")] : body)
1021
+ kept.push(line);
1022
+ if (end < lines.length)
1023
+ kept.push(lines[end]);
277
1024
  i = end;
278
1025
  }
1026
+ // A quoted script over several lines is an edit that no one of them shows.
1027
+ const editAcross = written === undefined && spread ? parsedEdit(command) : undefined;
1028
+ if (editAcross !== undefined) {
1029
+ learnEdit(command, context);
1030
+ written = `sed -i ${marker("dotenv")} ${editAcross}`;
1031
+ }
279
1032
  // A group or a quoted string over several lines holds the values outside the
280
1033
  // statement that names the file (`{ echo A=1; echo B=2; } > .env`), so the
281
1034
  // whole command goes, and only the write is left for the parse to see.
282
- if (written !== undefined && spread)
283
- return `${marker("dotenv")} > ${written}`;
1035
+ if (written !== undefined && spread) {
1036
+ learnValues(command, context);
1037
+ return written;
1038
+ }
284
1039
  return kept.join("\n");
285
1040
  }
1041
+ /** A multi-edit keeps its steps: each is one edit to the parse, and only their strings go. */
286
1042
  function cutDotenvInput(input, context) {
287
1043
  for (const field of EDIT_INPUT_FIELDS) {
288
1044
  if (typeof input[field] === "string") {
1045
+ learnValues(input[field], context);
289
1046
  input[field] = marker("dotenv");
290
1047
  count(context, "dotenv", 1);
291
1048
  }
292
1049
  }
1050
+ if (!Array.isArray(input.edits))
1051
+ return;
1052
+ for (const edit of input.edits)
1053
+ if (isObject(edit))
1054
+ cutDotenvInput(edit, context);
1055
+ }
1056
+ const FILE_ARGUMENT = /^(?:file_?path|filePath|notebook_path|(?:relative_)?path|paths|file|files|filename|target_file)$/;
1057
+ /**
1058
+ * Whether a call that is no shell works on a dotenv file, by the argument that
1059
+ * says what it works on: `Read {file_path}`, `Grep {path}`, a filesystem
1060
+ * server's `read_file {path}`. A glob reads a gitignored file as well as a named
1061
+ * one, however it is spelled (`{.env,.env.local}`, `*.env`), so any mention
1062
+ * counts, and the worst of that is one search's result on `*.envelope.ts`. Code
1063
+ * a tool runs (`REPL {code}`, `exec {script}`) is read as a shell line is.
1064
+ *
1065
+ * ponytail: by what the call names. A search that names no file (`Grep
1066
+ * {pattern}`, `grep -r KEY .`) still goes up when `.env` is not ignored; reading
1067
+ * its result's lines for a dotenv path is the way up.
1068
+ */
1069
+ function callNamesDotenv(name, input) {
1070
+ if (typeof input.glob === "string" && input.glob.includes(".env"))
1071
+ return true;
1072
+ // A workflow's script hands out prompts: it reads nothing by itself.
1073
+ if (readsDotenv(input.code) || readsDotenv(input.cmd) || (name !== "Workflow" && readsDotenv(input.script)))
1074
+ return true;
1075
+ return Object.entries(input).some(([key, value]) => FILE_ARGUMENT.test(key) && [value].flat().some(isDotenvPath));
1076
+ }
1077
+ /**
1078
+ * `! cat .env` typed in Claude Code is no tool call: the command comes as one
1079
+ * user turn, `<bash-input>…</bash-input>`, and what it printed as the next,
1080
+ * `<bash-stdout>…`. The cuts of a shell call apply across the pair.
1081
+ */
1082
+ function scanBashMode(message, content, context) {
1083
+ const input = /^\s*<bash-input>([\s\S]*)<\/bash-input>\s*$/.exec(content)?.[1];
1084
+ if (input !== undefined) {
1085
+ const cut = cutDotenvWrites(input, context);
1086
+ context.bashInputTouchedDotenv = cut !== input || readsDotenv(input);
1087
+ if (cut !== input) {
1088
+ message.content = `<bash-input>${cut}</bash-input>`;
1089
+ count(context, "dotenv", 1);
1090
+ }
1091
+ return;
1092
+ }
1093
+ if (!context.bashInputTouchedDotenv || !content.trimStart().startsWith("<bash-stdout>"))
1094
+ return;
1095
+ context.bashInputTouchedDotenv = false;
1096
+ learnValues(content.replace(/<\/?bash-std(?:out|err)>/g, "\n"), context);
1097
+ message.content = marker("dotenv");
1098
+ count(context, "dotenv", 1);
1099
+ }
1100
+ /** Where a background command's output also lands: `tail -f …/tasks/<id>.output`, `Read {file_path}`. */
1101
+ const TASK_OUTPUT = /(?<![\w-])([\w-]+)\.output\b/g;
1102
+ /** Whether a call goes on with a cut background command, by stopping it or reading what it printed. */
1103
+ function followsCutTask(input, context) {
1104
+ const tasks = [input.task_id, input.shell_id, input.bash_id];
1105
+ for (const text of [input.file_path, input.command]) {
1106
+ if (typeof text === "string")
1107
+ tasks.push(...[...text.matchAll(TASK_OUTPUT)].map((match) => match[1]));
1108
+ }
1109
+ return tasks.some((task) => typeof task === "string" && context.envToolUseIds.has(task));
293
1110
  }
294
1111
  function scanDotenv(record, context) {
295
1112
  const message = record.message;
296
1113
  const content = isObject(message) ? message.content : undefined;
1114
+ if (isObject(message) && typeof content === "string")
1115
+ return scanBashMode(message, content, context);
297
1116
  if (!Array.isArray(content))
298
1117
  return;
299
1118
  for (const block of content) {
@@ -303,51 +1122,103 @@ function scanDotenv(record, context) {
303
1122
  const input = isObject(block.input) ? block.input : undefined;
304
1123
  if (!input)
305
1124
  continue;
306
- if (block.name === "Bash" || block.name === "PowerShell") {
307
- const command = input.command;
308
- const cut = typeof command === "string" ? cutDotenvWrites(command) : command;
309
- if (cut === command && !readsDotenv(command))
310
- continue;
311
- if (typeof block.id === "string")
312
- context.envToolUseIds.add(block.id);
313
- if (cut !== command) {
314
- input.command = cut;
315
- count(context, "dotenv", 1);
316
- }
317
- continue;
1125
+ const command = input.command;
1126
+ const cut = typeof command === "string" ? cutDotenvWrites(command, context) : command;
1127
+ if (cut !== command) {
1128
+ input.command = cut;
1129
+ count(context, "dotenv", 1);
318
1130
  }
319
- if (!isDotenvPath(input.file_path) && !isDotenvPath(input.notebook_path))
320
- continue;
321
- if (typeof block.id === "string")
1131
+ const named = callNamesDotenv(block.name, input);
1132
+ if (named)
1133
+ cutDotenvInput(input, context);
1134
+ if ((named || cut !== command || readsDotenv(command) || followsCutTask(input, context)) && typeof block.id === "string") {
322
1135
  context.envToolUseIds.add(block.id);
323
- cutDotenvInput(input, context);
1136
+ }
324
1137
  }
325
1138
  if (block.type === "tool_result") {
326
1139
  const id = block.tool_use_id;
327
1140
  if (typeof id !== "string" || !context.envToolUseIds.has(id))
328
1141
  continue;
1142
+ // A command sent to the background goes on as a task: stopping that repeats
1143
+ // the command, and reading it prints what the command printed.
1144
+ const task = isObject(record.toolUseResult) ? record.toolUseResult.backgroundTaskId : undefined;
1145
+ if (typeof task === "string")
1146
+ context.envToolUseIds.add(task);
1147
+ learnValues(block.content, context);
1148
+ // A tool can say "done" in its text and return the file as data.
1149
+ learnValues(record.mcpMeta, context);
329
1150
  block.content = marker("dotenv");
330
1151
  count(context, "dotenv", 1);
331
1152
  if (record.toolUseResult !== undefined) {
1153
+ learnValues(record.toolUseResult, context);
332
1154
  record.toolUseResult = marker("dotenv");
333
1155
  count(context, "dotenv", 1);
334
1156
  }
335
1157
  }
336
1158
  }
337
1159
  }
1160
+ /**
1161
+ * Codex and Kimi pass a tool the name the agent typed, relative to where the
1162
+ * session stood. Read from a root above that it would be another file, so it is
1163
+ * made whole here and masking spells it from the root like any other.
1164
+ */
1165
+ function fromBase(value, base) {
1166
+ if (base === undefined || value.length === 0)
1167
+ return value;
1168
+ if (looksAbsolute(value) || value.startsWith("~") || value.includes("://"))
1169
+ return value;
1170
+ return resolve(base, value);
1171
+ }
1172
+ /**
1173
+ * What redaction may add to a session, in characters, net of what it takes off. A marker
1174
+ * is longer than a short value, so `7z -pa ` comes to four times its length, and an upload
1175
+ * of 400 KB outgrew the heap, on the cut itself as well as on all it kept.
1176
+ *
1177
+ * ponytail: one count for a session, so past it any text with a hit goes whole, however
1178
+ * little it holds. A limit per text if a real session ever comes near.
1179
+ */
1180
+ const ADDED_CHARS = 16 * 1024 * 1024;
1181
+ /** One, as millions of short texts past the limit would each pay for a stack trace. */
1182
+ const ADDS_TOO_MUCH = new RangeError("adds more than is left");
1183
+ /**
1184
+ * The rules, then the paths. A pattern that runs out of backtrack stack on a run of
1185
+ * millions of characters reports it as a RangeError, and then nothing says how much of
1186
+ * the text is a secret: all of it goes, as the session around it can still go out. The
1187
+ * same goes for a text that would take the session past `ADDED_CHARS`.
1188
+ */
1189
+ function scrubbed(text, context, key) {
1190
+ try {
1191
+ const secretsGone = applyRules(text, context.rules, (type, amount) => {
1192
+ count(context, type, amount);
1193
+ // Ahead of the cut, whose result is what the heap runs out on. A match adds at most its marker.
1194
+ if (amount * marker(type).length > context.added.left)
1195
+ throw ADDS_TOO_MUCH;
1196
+ });
1197
+ // Paths last: a secret already replaced by its marker must not then be read
1198
+ // as a directory, and `[ISY_REDACTED:…]` carries no slash to be read as one.
1199
+ const onMask = (amount) => count(context, "path", amount);
1200
+ const clean = key && PATH_KEYS.has(key)
1201
+ ? maskPath(fromBase(secretsGone, context.base), context.roots, onMask)
1202
+ : maskPaths(secretsGone, context.roots, onMask);
1203
+ if (spend(context.added, clean.length - text.length))
1204
+ return clean;
1205
+ }
1206
+ catch (error) {
1207
+ if (!(error instanceof RangeError))
1208
+ throw error;
1209
+ }
1210
+ count(context, "oversized", 1);
1211
+ return marker("oversized");
1212
+ }
338
1213
  function redactValue(value, context, key) {
339
1214
  if (typeof value === "string") {
340
- if (key && SENSITIVE_KEY.test(key) && value.length >= MIN_SENSITIVE_VALUE) {
1215
+ if (key && value.length >= MIN_SENSITIVE_VALUE && (SENSITIVE_KEY.test(key) || (KEY_FIELD.test(key) && GENERATED.test(value)))) {
341
1216
  if (value.startsWith(`[${REDACTION_MARKER}`))
342
1217
  return value;
343
1218
  count(context, "assignment", 1);
344
1219
  return marker("assignment");
345
1220
  }
346
- const secretsGone = applyRules(value, context.rules, (type, amount) => count(context, type, amount));
347
- // Paths last: a secret already replaced by its marker must not then be read
348
- // as a directory, and `[ISY_REDACTED:…]` carries no slash to be read as one.
349
- const mask = key && PATH_KEYS.has(key) ? maskPath : maskPaths;
350
- return mask(secretsGone, context.roots, (amount) => count(context, "path", amount));
1221
+ return scrubbed(value, context, key);
351
1222
  }
352
1223
  if (Array.isArray(value))
353
1224
  return value.map((item) => redactValue(item, context));
@@ -435,7 +1306,8 @@ function stripAttachment(record, context) {
435
1306
  * `serverClassifierRequest` and `serverClassifierContext` are what a permission
436
1307
  * classifier was shown, the working tree's git state included;
437
1308
  * `wireIngestContext` and `permissionDecision` say where a call ran and what
438
- * allowed it.
1309
+ * allowed it; `mcpMeta` repeats what an MCP tool returned, as out of reach of the
1310
+ * cut as `wireToolInputs` is.
439
1311
  */
440
1312
  const HARNESS_FIELDS = [
441
1313
  "wireToolInputs",
@@ -443,6 +1315,7 @@ const HARNESS_FIELDS = [
443
1315
  "serverClassifierContext",
444
1316
  "wireIngestContext",
445
1317
  "permissionDecision",
1318
+ "mcpMeta",
446
1319
  ];
447
1320
  function stripHarnessFields(record, context) {
448
1321
  let stripped = false;
@@ -482,10 +1355,16 @@ function createContext(options, invalid) {
482
1355
  rules: [...BUILTIN_RULES, ...compileExtraRules(options.extraPatterns, invalid)],
483
1356
  counts: {},
484
1357
  envToolUseIds: new Set(),
1358
+ bashInputTouchedDotenv: false,
1359
+ learned: new Set(),
1360
+ structures: { left: STRUCTURES },
1361
+ dotenvCommands: { left: DOTENV_COMMAND_CHARS },
1362
+ added: { left: ADDED_CHARS },
485
1363
  // The home directory is this machine's and is never in the transcript's
486
1364
  // gift, so it is read here rather than passed by every caller.
487
1365
  roots: resolveRoots({ cwd: options.cwd, home: options.home ?? homedir() }),
488
1366
  rootGiven: Boolean(options.cwd),
1367
+ base: options.base,
489
1368
  };
490
1369
  }
491
1370
  function summarize(context, lines, unparsedLines, invalidExtraPatterns) {
@@ -496,16 +1375,17 @@ function redactOneLine(line, context) {
496
1375
  const trimmed = line.trim();
497
1376
  if (trimmed.length === 0)
498
1377
  return { line: trimmed, unparsed: false };
1378
+ // Parsing and copying it would hold twice what the parser allows itself to keep.
1379
+ if (!mayParse(trimmed, context.structures)) {
1380
+ count(context, "oversized", 1);
1381
+ return { line: marker("oversized"), unparsed: true };
1382
+ }
499
1383
  let parsed;
500
1384
  try {
501
1385
  parsed = JSON.parse(trimmed);
502
1386
  }
503
1387
  catch {
504
- const secretsGone = applyRules(trimmed, context.rules, (type, amount) => count(context, type, amount));
505
- return {
506
- line: maskPaths(secretsGone, context.roots, (amount) => count(context, "path", amount)),
507
- unparsed: true,
508
- };
1388
+ return { line: scrubbed(trimmed, context), unparsed: true };
509
1389
  }
510
1390
  if (!isObject(parsed)) {
511
1391
  return {
@@ -515,6 +1395,16 @@ function redactOneLine(line, context) {
515
1395
  }
516
1396
  return { line: JSON.stringify(redactRecord(parsed, context)), unparsed: false };
517
1397
  }
1398
+ function chargedLine(line, context) {
1399
+ const left = context.added.left;
1400
+ const result = redactOneLine(line, context);
1401
+ // What its texts did not pay for: a cut by key name, and a marker past the limit, which
1402
+ // is more than a text shorter than it, so that a line of such texts still grew threefold.
1403
+ if (spend(context.added, result.line.length - line.length - (left - context.added.left)))
1404
+ return result;
1405
+ count(context, "oversized", 1);
1406
+ return { line: marker("oversized"), unparsed: true };
1407
+ }
518
1408
  /**
519
1409
  * A transcript's lines, redacted. With no `cwd`, paths are rooted at the first
520
1410
  * record that names one; with no `home`, at the home that directory implies,
@@ -530,14 +1420,15 @@ export function redactLines(lines, options = {}) {
530
1420
  let unparsed = 0;
531
1421
  for (const line of lines) {
532
1422
  total += 1;
533
- const result = redactOneLine(line, context);
1423
+ const result = chargedLine(line, context);
534
1424
  if (result.line.length === 0)
535
1425
  continue;
536
1426
  if (result.unparsed)
537
1427
  unparsed += 1;
538
1428
  output.push(result.line);
539
1429
  }
540
- return { lines: output, summary: summarize(context, total, unparsed, invalid) };
1430
+ const clean = cutLearnedValues(output, context);
1431
+ return { lines: clean, summary: summarize(context, total, unparsed, invalid) };
541
1432
  }
542
1433
  /**
543
1434
  * `redactLines` for lines that arrive one at a time — a file read as it streams,
@@ -553,14 +1444,15 @@ export async function redactLineStream(lines, options = {}) {
553
1444
  let unparsed = 0;
554
1445
  for await (const line of lines) {
555
1446
  total += 1;
556
- const result = redactOneLine(line, context);
1447
+ const result = chargedLine(line, context);
557
1448
  if (result.line.length === 0)
558
1449
  continue;
559
1450
  if (result.unparsed)
560
1451
  unparsed += 1;
561
1452
  output.push(result.line);
562
1453
  }
563
- return { lines: output, summary: summarize(context, total, unparsed, invalid) };
1454
+ const clean = cutLearnedValues(output, context);
1455
+ return { lines: clean, summary: summarize(context, total, unparsed, invalid) };
564
1456
  }
565
1457
  export function redactTranscriptFile(filePath, options = {}) {
566
1458
  return redactLineStream(fileLines(filePath), options);