@mossbear/eval-core 0.1.0-alpha.106 → 0.1.0-alpha.108

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.
@@ -1,1569 +1,97 @@
1
1
  /**
2
- * Secret redaction and length-capping for shell command text.
2
+ * Command evidence is an executable label, never arguments or shell source.
3
3
  *
4
- * Command text can embed secrets or whole file bodies (heredocs, inline env
5
- * vars). The CLI runs logged commands through this before creating an action
6
- * summary. Recognized credential syntax is removed; arbitrary shell/tool
7
- * programs remain an open language, so pattern scanning cannot prove that
8
- * every surviving argument is credential-free.
4
+ * Only literal, known executable names are admitted. An arbitrary first word
5
+ * can itself be a credential or file content, so unsupported syntax and custom
6
+ * executables produce a fixed withholding marker. Wrappers are not unwrapped:
7
+ * `sh -c ...` reports `sh`, and nothing inside its script is inspected.
9
8
  *
10
- * Lives in eval-core rather than the CLI because grading is what consumes the
11
- * result: this is the boundary that decides what a grader may ever see of a
12
- * command.
9
+ * The exported name is retained for callers that also print hook diagnostics.
13
10
  */
14
- import { COOKIE_HEADER_SOURCE, SENSITIVE_KEY_SOURCE, SENSITIVE_WORD_SOURCE, SHELL_WORD_SOURCE, } from './credential-patterns.js';
15
- import { PRIVATE_KEY_BLOCK_SOURCE, REDACTED } from './redaction.js';
16
- /**
17
- * Maximum characters of a single command string that survive redaction.
18
- * Short commands convey which tools the agent invoked — which is all a grader
19
- * needs; anything longer is bulk payload (heredocs, inline file writes) that
20
- * must not leave the machine.
21
- */
22
- const MAX_COMMAND_CHARS = 200;
23
- // SSHPASS, REDISCLI_AUTH, VALKEYCLI_AUTH and MYSQL_PWD are each tool's dedicated
24
- // environment credential, despite not containing the usual password/token spelling.
25
- const COMMAND_SENSITIVE_KEY_SOURCE = `(?:${SENSITIVE_KEY_SOURCE}|SSHPASS|REDISCLI_AUTH|VALKEYCLI_AUTH|MYSQL_PWD)`;
26
- const SENSITIVE_KEY = new RegExp(`^${COMMAND_SENSITIVE_KEY_SOURCE}$`, 'i');
27
- const SENSITIVE_CONTENT = new RegExp(SENSITIVE_WORD_SOURCE, 'i');
28
- // Only switches that consume no argument may precede an argument flag in
29
- // curl's short-option clusters. For example, -sx is proxy auth, while -osx
30
- // names an output file and must not be interpreted as a proxy option.
31
- const CURL_SHORT_SWITCHES = '[012346aBfgGiIjJklLMnNOpqRsSvVZ:#]*';
32
- const CURL_PAYLOAD_FLAG = new RegExp(`^(-${CURL_SHORT_SWITCHES}[dHF])(.+)?$|^(--(?:data|data-raw|data-binary|data-urlencode|json|form|form-string|header|proxy-header))(?:=(.*))?$`);
33
- const CURL_CONFIG_FLAG = new RegExp(`^(?:-${CURL_SHORT_SWITCHES}K|--config(?:=|$))`);
34
- const CURL_URL_OPTIONS = 'url|proxy|proxy1\\.0|preproxy|socks4|socks4a|socks5|socks5-hostname';
35
- const CURL_URL_FIELD = new RegExp(`^(?:${CURL_URL_OPTIONS})$`, 'i');
36
- // Tool families share one credential syntax, so each family is defined once and
37
- // every member inherits its password flags, URI handling and attached-value rules.
38
- // MySQL-family clients read a bare -p as a password prompt, so only the attached
39
- // -p<password> spelling carries a credential.
40
- const MYSQL_FAMILY = [
41
- 'mysql',
42
- 'mariadb',
43
- 'mysqldump',
44
- 'mysqladmin',
45
- 'mariadb-dump',
46
- 'mariadb-admin',
47
- ];
48
- // redis-cli and valkey-cli (a Redis fork) take the same password flags and URIs.
49
- const REDIS_FAMILY = ['redis-cli', 'valkey-cli'];
50
- const MYSQL_PASSWORD_FLAG = /^(-p)(.*)$/;
51
- const REDIS_PASSWORD_FLAG = /^(-a|--pass|--cluster-from-pass)(?:=(.*))?$/;
52
- // Both families accept redis:// and valkey:// URIs, with or without TLS (`s`).
53
- const REDIS_URI = /^(?:rediss?|valkeys?):\/\//i;
54
- /**
55
- * The tool a word invokes: its basename, lowercased, without a Windows
56
- * executable suffix. Windows resolves executable names case-insensitively.
57
- * Backticks are dropped, so a word a substitution begins or ends (`` `curl ``)
58
- * still names its tool when quoting hides the substitution from the parser.
59
- */
60
- function invokedTool(word) {
61
- return (word.replaceAll('`', '').split(/[\\/]/).at(-1) ?? word)
62
- .replace(/\.exe$/i, '')
63
- .toLowerCase();
64
- }
65
- const CREDENTIAL_TOOLS = [
66
- 'curl',
67
- 'http',
68
- 'https',
69
- 'httpie',
70
- 'openssl',
71
- 'sshpass',
72
- ...REDIS_FAMILY,
73
- ...MYSQL_FAMILY,
74
- ];
75
- // Password flags by tool. Each regex captures the flag name and, when the value
76
- // is attached, the value itself.
77
- const DIRECT_PASSWORD_FLAGS = new Map([
78
- [
79
- 'openssl',
80
- /^(-{1,2}(?:pass(?:in|out)?|password|srppass|pwri_password|secretkey|hmac|[kK]))(?:=(.*))?$/,
81
- ],
82
- ['sshpass', /^(-[46v]*p)(.*)$/],
83
- ...REDIS_FAMILY.map((tool) => [tool, REDIS_PASSWORD_FLAG]),
84
- ...MYSQL_FAMILY.map((tool) => [tool, MYSQL_PASSWORD_FLAG]),
85
- ]);
86
- // Valued wrapper options name users, files or scripts, never the child tool.
87
- const WRAPPER_VALUE_FLAGS = {
88
- sudo: /^-(?:[AbEHIKknPSVbveis]*[ughpDTRCrt])(.+)?$|^--(?:user|group|host|prompt|chdir|chroot|command-timeout|close-from|role|type)(?:=(.*))?$/,
89
- doas: /^-[uC](.+)?$/,
90
- env: /^-[uCSa](.+)?$|^--(?:unset|chdir|split-string|argv0)(?:=(.*))?$/,
91
- time: /^-[of](.+)?$|^--(?:output|format)(?:=(.*))?$/,
92
- xargs: /^-[adEILnPs](.+)?$|^--(?:arg-file|delimiter|eof|replace|max-lines|max-args|max-procs|max-chars)(?:=(.*))?$/,
93
- };
94
- // Wrapper options known to take no value. Any other option, unless its value is
95
- // attached with `=`, may have consumed the next word.
96
- const WRAPPER_SWITCHES = {
97
- sudo: /^-[AbEHIKklnPSsVvie]+$|^--(?:preserve-env|login|shell|set-home|non-interactive|background)$/,
98
- doas: /^-[nsL]+$/,
99
- env: /^-[i0v]+$|^-$|^--(?:ignore-environment|null|debug)$/,
100
- time: /^-[pvqa]+$|^--(?:portability|verbose|quiet|append)$/,
101
- xargs: /^-[0rtpxo]+$|^--(?:null|no-run-if-empty|verbose|interactive|exit|open-tty)$/,
102
- };
103
- // Programs that never run an argument as a command, so a credential tool's name
104
- // among their arguments is a file (`cat ./bin/curl`), not an invocation. Any
105
- // program not listed may dispatch (`timeout`, `watch`, `find -exec`, `ssh`), and
106
- // keeps treating every word as a possible invocation, so an unlisted program
107
- // errs toward over-redaction.
108
- const NON_DISPATCHING_TOOLS = new Set([
109
- 'basename',
11
+ const EXECUTABLES = new Set([
12
+ 'awk',
13
+ 'bash',
14
+ 'bun',
110
15
  'cat',
111
- 'chgrp',
16
+ 'cd',
112
17
  'chmod',
113
18
  'chown',
114
19
  'cmp',
115
20
  'cp',
21
+ 'curl',
22
+ 'cut',
23
+ 'date',
24
+ 'deno',
116
25
  'diff',
117
- 'dirname',
118
- 'du',
119
- 'file',
26
+ 'docker',
27
+ 'echo',
28
+ 'env',
29
+ 'find',
30
+ 'gh',
31
+ 'git',
32
+ 'go',
120
33
  'grep',
121
34
  'head',
122
- 'ln',
35
+ 'java',
36
+ 'jq',
37
+ 'less',
123
38
  'ls',
39
+ 'make',
124
40
  'mkdir',
41
+ 'mossbear',
125
42
  'mv',
126
- 'readlink',
127
- 'realpath',
43
+ 'mysql',
44
+ 'mysqladmin',
45
+ 'node',
46
+ 'npm',
47
+ 'npx',
48
+ 'openssl',
49
+ 'perl',
50
+ 'php',
51
+ 'pip',
52
+ 'pip3',
53
+ 'pnpm',
54
+ 'powershell',
55
+ 'printf',
56
+ 'ps',
57
+ 'psql',
58
+ 'pwsh',
59
+ 'python',
60
+ 'python3',
61
+ 'redis-cli',
62
+ 'rg',
128
63
  'rm',
129
- 'stat',
64
+ 'ruby',
65
+ 'rustc',
66
+ 'cargo',
67
+ 'sed',
68
+ 'sh',
69
+ 'sort',
70
+ 'ssh',
71
+ 'sudo',
130
72
  'tail',
73
+ 'tar',
74
+ 'tee',
75
+ 'test',
131
76
  'touch',
77
+ 'tr',
78
+ 'true',
79
+ 'tsc',
80
+ 'unzip',
81
+ 'uv',
82
+ 'vitest',
132
83
  'wc',
84
+ 'wget',
133
85
  'which',
86
+ 'xargs',
87
+ 'yarn',
88
+ 'zsh',
134
89
  ]);
135
- /**
136
- * Whether the command word starting at `index` of `text` runs a listed program:
137
- * bare, or from a system bin directory. A same-named local script
138
- * (`./tools/diff`) may run anything, and a redirection operand (`>file curl`)
139
- * names a file, not the command.
140
- */
141
- function isNonDispatching(text, index, word) {
142
- let before = index - 1;
143
- while (text[before] === ' ' || text[before] === '\t')
144
- before -= 1;
145
- // `>&file` and `>|file` redirect too.
146
- if (text[before] === '&' || text[before] === '|')
147
- before -= 1;
148
- if (text[before] === '<' || text[before] === '>')
149
- return false;
150
- // A backtick in the command word may start a substitution that runs anything.
151
- if (word.includes('`'))
152
- return false;
153
- return (NON_DISPATCHING_TOOLS.has(invokedTool(word)) &&
154
- /^(?:(?:\/usr)?\/bin\/)?[^\\/]+$/.test(word));
155
- }
156
- const CURL_AUTH_OPTIONS = `user|proxy-user|${CURL_URL_OPTIONS}|cookie|oauth2-bearer|cert|proxy-cert|pass|proxy-pass`;
157
- const CURL_AUTH_FLAG = new RegExp(`^(-${CURL_SHORT_SWITCHES}[uUbEx])(.+)?$|^(--(?:${CURL_AUTH_OPTIONS}))(?:=(.*))?$`);
158
- const CURL_EXPANSION = /\{\{([A-Za-z0-9_]+)(?::[^{}]*)?\}\}/g;
159
- const CURL_EXPAND_FLAG = new RegExp(`^--expand-(${CURL_AUTH_OPTIONS}|header|proxy-header|data|data-raw|data-binary|data-urlencode|json|form|form-string)(?:=(.*))?$`);
160
- function hasPrivateConfigVariables(body) {
161
- if (!/\b(?:expand-)?variable\s*[=: \t]/i.test(body))
162
- return false;
163
- if (/\bexpand-(?:user|proxy-user|oauth2-bearer|cookie|cert|proxy-cert|pass|proxy-pass|header|proxy-header|data(?:-raw|-binary|-urlencode)?|json|form(?:-string)?)\s*[=: \t]/i.test(body))
164
- return true;
165
- return (/\bexpand-(?:url|proxy|preproxy|socks[45](?:a|-hostname)?)\s*[=: \t]/i.test(body) &&
166
- (/[^/\s:@]+:[^@\s]*@/.test(body) ||
167
- new RegExp(`[?&#]${COMMAND_SENSITIVE_KEY_SOURCE}=`, 'i').test(body)));
168
- }
169
- function decodeShellWord(word) {
170
- return word.replace(/\$'((?:\\[\s\S]|[^'\\])*)'|'([^']*)'|"((?:\\.|[^"\\])*)"|\\([\s\S])|([^'"\\]+)/g, (_, ansi, single, double, escaped, plain) => {
171
- if (ansi !== undefined)
172
- return ansi.replace(/\\(?:x([\da-f]{1,2})|u([\da-f]{1,4})|U([\da-f]{1,8})|([0-7]{1,3})|([\s\S]))/gi, (escape, hex, unicode, wide, octal, character) => {
173
- if (hex || unicode || wide || octal) {
174
- const code = Number.parseInt(hex ?? unicode ?? wide ?? octal, octal ? 8 : 16);
175
- return code <= 0x10ffff ? String.fromCodePoint(code) : escape;
176
- }
177
- const controls = {
178
- a: '\x07',
179
- b: '\b',
180
- e: '\x1b',
181
- E: '\x1b',
182
- f: '\f',
183
- n: '\n',
184
- r: '\r',
185
- t: '\t',
186
- v: '\v',
187
- };
188
- return controls[character] ?? (/['"\\?]/.test(character) ? character : escape);
189
- });
190
- if (single !== undefined)
191
- return single;
192
- if (double !== undefined)
193
- return double.replace(/\\([$`"\\\n])/g, (_, character) => character === '\n' ? '' : character);
194
- return escaped ?? plain ?? '';
195
- });
196
- }
197
- /**
198
- * Undo the escapes a backtick substitution's body carries for `\\` and `\``,
199
- * and for `\"` when the substitution sits inside double quotes.
200
- * `\$` is left escaped: the word parser decodes it either way.
201
- */
202
- function unescapeBacktickBody(body, doubleQuoted = false) {
203
- return body.replace(doubleQuoted ? /\\([\\`"])/g : /\\([\\`])/g, '$1');
204
- }
205
- /** Spell a body back inside backticks, reversing `unescapeBacktickBody`. */
206
- function escapeBacktickBody(body, doubleQuoted = false) {
207
- return body.replace(doubleQuoted ? /\\(?=[\\`"]|$)|[`"]/g : /\\(?=[\\`]|$)|`/g, '\\$&');
208
- }
209
- /**
210
- * The command with each backtick substitution spelled `$(…)`. `(` separates
211
- * words for the tool parsers and a backtick does not, so tool-input discovery
212
- * reads this spelling to see the commands inside backticks.
213
- */
214
- function backticksAsSubshells(command, depth = 0) {
215
- if (depth > 8 || !command.includes('`'))
216
- return command;
217
- let quote = null;
218
- let out = '';
219
- for (let index = 0; index < command.length; index += 1) {
220
- const char = command[index];
221
- if (char === '\\' && quote !== "'") {
222
- out += command.slice(index, index + 2);
223
- index += 1;
224
- continue;
225
- }
226
- if (char === '`' && quote !== "'") {
227
- let end = index + 1;
228
- while (end < command.length && command[end] !== '`')
229
- end += command[end] === '\\' ? 2 : 1;
230
- const body = unescapeBacktickBody(command.slice(index + 1, end));
231
- out += `$(${backticksAsSubshells(body, depth + 1)})`;
232
- index = end;
233
- continue;
234
- }
235
- if (char === "'" && quote !== '"')
236
- quote = quote === "'" ? null : "'";
237
- else if (char === '"' && quote !== "'")
238
- quote = quote === '"' ? null : '"';
239
- out += char;
240
- }
241
- return out;
242
- }
243
- /**
244
- * Tool inputs read from the command as written and from its `$(…)` spelling.
245
- * The respelling separates a backtick body from its first word but also
246
- * splits a word that runs on past the substitution, so neither alone sees
247
- * every reference.
248
- */
249
- function backtickAwareInputs(command) {
250
- const inputs = getToolInputs(command);
251
- return command.includes('`')
252
- ? withInheritedInputs(getToolInputs(backticksAsSubshells(command)), inputs)
253
- : inputs;
254
- }
255
- function withInheritedInputs(inputs, inherited) {
256
- inputs.curlConfig ||= inherited?.curlConfig ?? false;
257
- for (const name of inherited?.curlVariables ?? [])
258
- inputs.curlVariables.add(name);
259
- for (const key of inherited?.env ?? [])
260
- inputs.env.add(key);
261
- for (const source of inherited?.passSources ?? [])
262
- inputs.passSources.add(source);
263
- return inputs;
264
- }
265
- /**
266
- * A program supplying a credential argument carries private produced content.
267
- * Any other backtick substitution runs a command of its own, which a backtick
268
- * does not separate from its first word the way `(` does, so its body is
269
- * redacted as a command in its own right. An escaped backtick is literal text;
270
- * `invokedTool` still reads the tool its word names.
271
- */
272
- /** Whether an unescaped double quote closes the one open at `from`. */
273
- function closesQuote(command, from) {
274
- for (let index = from; index < command.length; index += 1) {
275
- if (command[index] === '\\')
276
- index += 1;
277
- else if (command[index] === '"')
278
- return true;
279
- }
280
- return false;
281
- }
282
- function redactCommandSubstitutions(command, depth = 0, inheritedInputs, valuesFirst = true) {
283
- if (depth > 8)
284
- return REDACTED;
285
- const marker = '__SUBSTITUTION_BOUNDARY__';
286
- if (command.includes(marker))
287
- return REDACTED;
288
- let contextInputs;
289
- // A body also feeds, or consumes, the commands around it.
290
- const surroundingInputs = () => (contextInputs ??= withInheritedInputs(backtickAwareInputs(command), inheritedInputs));
291
- const isCredentialInput = (start, end) => {
292
- const probe = command.slice(0, start) + marker + command.slice(end + 1);
293
- const inputs = getToolInputs(probe);
294
- const redacted = redactCredentialAssignments(redactToolArguments(redactJsonArguments(probe), inputs), inputs);
295
- return !applyCommandRedactions(redacted).includes(marker);
296
- };
297
- const findEnd = (start, closing, depth) => {
298
- if (depth > 8)
299
- return command.length;
300
- // A backtick body ends at the first unescaped backtick, as bash reads it:
301
- // quotes inside it do not hide one, and `\` escapes even inside `'…'`.
302
- if (closing === '`') {
303
- for (let index = start; index < command.length; index += 1) {
304
- if (command[index] === '\\')
305
- index += 1;
306
- else if (command[index] === '`')
307
- return index;
308
- }
309
- return command.length;
310
- }
311
- let quote = null;
312
- let groups = 0;
313
- for (let index = start; index < command.length; index += 1) {
314
- const char = command[index];
315
- if (char === '\\' && quote !== "'") {
316
- index += 1;
317
- continue;
318
- }
319
- if (quote === "'") {
320
- if (char === "'")
321
- quote = null;
322
- continue;
323
- }
324
- if (char === '$' && command[index + 1] === '(') {
325
- index = findEnd(index + 2, ')', depth + 1);
326
- continue;
327
- }
328
- if (char === '`') {
329
- index = findEnd(index + 1, '`', depth + 1);
330
- continue;
331
- }
332
- if (char === "'" && quote === null)
333
- quote = "'";
334
- else if (char === '"')
335
- quote = quote === '"' ? null : '"';
336
- else if (quote === null && char === '(')
337
- groups += 1;
338
- else if (quote === null && char === ')') {
339
- if (groups === 0 && closing === ')')
340
- return index;
341
- groups -= 1;
342
- }
343
- }
344
- return command.length;
345
- };
346
- let quote = null;
347
- let out = '';
348
- let substitutions = 0;
349
- // Where in `out` the open double quote began.
350
- let quoteOpenedAt = 0;
351
- for (let index = 0; index < command.length; index += 1) {
352
- const char = command[index];
353
- if (char === '\\' && quote !== "'") {
354
- out += command.slice(index, index + 2);
355
- index += 1;
356
- continue;
357
- }
358
- if (quote !== "'" && (char === '`' || (char === '$' && command[index + 1] === '('))) {
359
- if (++substitutions > 64)
360
- return out + REDACTED;
361
- const start = index;
362
- const bodyStart = index + (char === '`' ? 1 : 2);
363
- index = findEnd(bodyStart, char === '`' ? '`' : ')', 0);
364
- const original = command.slice(start, index + 1);
365
- if (isCredentialInput(start, index))
366
- out += REDACTED;
367
- else if (char === '`') {
368
- // In the command as written, an unterminated backtick leaves the
369
- // body's extent unknown: fail closed. A nested pass sees words the
370
- // parser split at a backtick (`"a b"\``), so it parses the rest instead.
371
- const unterminated = command[index] !== '`';
372
- if (unterminated && depth === 0)
373
- return `${out}\`${REDACTED}`;
374
- const body = unescapeBacktickBody(command.slice(bodyStart, index), quote === '"');
375
- const redacted = redactShellSyntax(body, depth + 1, surroundingInputs(), valuesFirst);
376
- // Rewriting a body inside a double quote that never closes changes
377
- // how the rest of that quote splits into words, which can move a
378
- // credential argument's extent: fail closed, as for an unterminated
379
- // backtick.
380
- if (redacted !== body && quote === '"' && !closesQuote(command, index + 1))
381
- return `${out.slice(0, quoteOpenedAt)}${REDACTED}`;
382
- out +=
383
- redacted === body
384
- ? original
385
- : `\`${escapeBacktickBody(redacted, quote === '"')}${unterminated ? '' : '`'}`;
386
- }
387
- else if (original.includes('`')) {
388
- // `(` already exposes this body to the outer parse; only backticks
389
- // nested inside it need a pass of their own.
390
- const body = command.slice(bodyStart, index);
391
- out += `$(${redactCommandSubstitutions(body, depth + 1, surroundingInputs(), valuesFirst)}${command.slice(index, index + 1)}`;
392
- }
393
- else
394
- out += original;
395
- continue;
396
- }
397
- if (char === "'" && quote !== '"')
398
- quote = quote === "'" ? null : "'";
399
- else if (char === '"' && quote !== "'") {
400
- if (quote === null)
401
- quoteOpenedAt = out.length;
402
- quote = quote === '"' ? null : '"';
403
- }
404
- out += char;
405
- }
406
- return out;
407
- }
408
- function hasSensitiveContent(text) {
409
- // Even malformed JSON may spell a key with unicode escapes.
410
- return SENSITIVE_CONTENT.test(text.replace(/\\u([0-9a-f]{4})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))));
411
- }
412
- function redactJsonValue(value, depth = 0) {
413
- // Bound traversal independently of the later command-length cap. Deep
414
- // payloads are content, so dropping a subtree is the conservative answer.
415
- if (depth > 20)
416
- return REDACTED;
417
- if (typeof value === 'string' && /^\s*[[{]/.test(value)) {
418
- try {
419
- const parsed = JSON.parse(value);
420
- const redacted = JSON.stringify(redactJsonValue(parsed, depth + 1));
421
- return redacted === JSON.stringify(parsed) ? value : redacted;
422
- }
423
- catch {
424
- return hasSensitiveContent(value) ? REDACTED : value;
425
- }
426
- }
427
- if (Array.isArray(value))
428
- return value.map((item) => redactJsonValue(item, depth + 1));
429
- if (!value || typeof value !== 'object')
430
- return value;
431
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
432
- key,
433
- SENSITIVE_KEY.test(key) ? REDACTED : redactJsonValue(item, depth + 1),
434
- ]));
435
- }
436
- function redactJsonArguments(command) {
437
- const redactArgument = (argument) => {
438
- // Shell double quotes only consume escapes for these characters. JSON's
439
- // string decoder rejects valid shell escapes such as \$, so decode the
440
- // shell layer before parsing the request body.
441
- const raw = decodeShellWord(argument);
442
- if (!/^\s*[[{]/.test(raw))
443
- return argument;
444
- try {
445
- const parsed = JSON.parse(raw);
446
- const redacted = JSON.stringify(redactJsonValue(parsed));
447
- if (redacted === JSON.stringify(parsed))
448
- return argument;
449
- return argument.startsWith("'") ? `'${redacted}'` : JSON.stringify(redacted);
450
- }
451
- catch {
452
- // A JSON-like payload that cannot be decoded may still contain escaped
453
- // credential keys. Drop its contents rather than scan partial syntax.
454
- if (!hasSensitiveContent(raw))
455
- return argument;
456
- return argument.startsWith("'") ? `'${REDACTED}'` : `"${REDACTED}"`;
457
- }
458
- };
459
- // Dropping a word that a substitution closed onto a credential flag
460
- // (`[a]` then a backtick and `--token`) hides the flag from the
461
- // space-separated rule, so its value is followed here, as for every other
462
- // edit that rewrites a word.
463
- const next = textChainCursor(command);
464
- const chained = new Set();
465
- const ranges = [];
466
- for (const match of command.matchAll(new RegExp(SHELL_WORD_SOURCE, 'g'))) {
467
- const replaced = redactArgument(match[0]);
468
- if (replaced === match[0])
469
- continue;
470
- const end = match.index + match[0].length;
471
- ranges.push({ start: match.index, end, text: replaced });
472
- ranges.push(...followCredentialChain(match[0], end, next, chained, command));
473
- }
474
- return applyRanges(command, ranges);
475
- }
476
- /**
477
- * Credential values recognised by the name beside them (URL userinfo,
478
- * Authorization and Cookie headers, query keys) rather than by shell words.
479
- */
480
- const VALUE_REDACTIONS = [
481
- [/\b([a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:)[^@\s]+@/gi, `$1${REDACTED}@`],
482
- [/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+@/gi, `$1${REDACTED}@`],
483
- [/\b(authorization\s*:\s*)(?:(?:bearer|basic|token)\s+)?\S+/gi, `$1${REDACTED}`],
484
- [new RegExp(COOKIE_HEADER_SOURCE, 'gi'), `$1${REDACTED}`],
485
- [
486
- new RegExp(`([?&#]${COMMAND_SENSITIVE_KEY_SOURCE}=)[^&\\s"'<>]+`, 'gi'),
487
- `$1${REDACTED}`,
488
- ],
489
- ];
490
- /**
491
- * Space-separated credential flags have no assignment operator or token
492
- * prefix. Keep the flag for evidence, but never its value. The value is the
493
- * next shell word across any whitespace, newlines included: a word typed on
494
- * the line after `--password` is very likely the password, even though bash
495
- * would read it as a new command.
496
- *
497
- * That reach means the value can itself be a credential flag
498
- * (`--password --token <value>`). Taking it as the first flag's value must not
499
- * spare its own value, so the word after a swallowed credential flag is
500
- * redacted too, for as long as the chain runs. A chained word that spells a
501
- * credential key is left for the passes after this one to read (see
502
- * `isChainedValue`), and one with an attached value ends the chain. Every
503
- * match the rule makes on its own is still redacted: the chain only adds.
504
- */
505
- const CREDENTIAL_FLAG = new RegExp(`(^|[\\s;&|(\\x60])(--${COMMAND_SENSITIVE_KEY_SOURCE}\\s+)(${SHELL_WORD_SOURCE})`, 'gi');
506
- const NEXT_SHELL_WORD = new RegExp(`(\\s+)(${SHELL_WORD_SOURCE})`, 'y');
507
- const SHELL_WORDS = new RegExp(SHELL_WORD_SOURCE, 'g');
508
- // The words a credential key is spelled with. Keys are tested by scanning a
509
- // word's `[\w.-]` runs for one rather than by a regex with `[\w.-]*` on both
510
- // sides of the key, which backtracks quadratically on a long word.
511
- const CREDENTIAL_KEY_WORD = new RegExp(`${SENSITIVE_WORD_SOURCE}|SSHPASS|REDISCLI_AUTH|VALKEYCLI_AUTH|MYSQL_PWD`, 'i');
512
- const ASSIGNMENT_OPERATOR = /\s*[=:]/y;
513
- const LINE_CONTINUATION = /^\\\r?\n$/;
514
- const KEY_CHARACTER = /[\w.-]/;
515
- /** `SENSITIVE_KEY`'s test, without its backtracking on a long name. */
516
- function isCredentialKeyName(name) {
517
- return ((/^[\w.-]+$/.test(name) && SENSITIVE_CONTENT.test(name)) ||
518
- /^(?:SSHPASS|REDISCLI_AUTH|VALKEYCLI_AUTH|MYSQL_PWD)$/i.test(name));
519
- }
520
- function isBareCredentialFlag(word) {
521
- const flag = /^--([^=]+)$/.exec(decodeShellWord(word));
522
- return flag !== null && isCredentialKeyName(flag[1]);
523
- }
524
- /**
525
- * `--token=<value>` carries its own value, which the attached-flag and
526
- * assignment rules redact while keeping the flag's name readable to the
527
- * passes after them.
528
- */
529
- function isAttachedCredentialFlag(word) {
530
- const flag = /^--([^=]+)=/.exec(decodeShellWord(word));
531
- return flag !== null && isCredentialKeyName(flag[1]);
532
- }
533
- /**
534
- * Whether `text` spells a credential key where the other rules read one: a
535
- * `[\w.-]` run at the start, or after a shell boundary, quote or escape (where
536
- * a decoded word starts), that is a `--` flag or is followed by `=` or `:`.
537
- */
538
- function spellsCredentialKey(text) {
539
- for (const run of text.matchAll(/[\w.-]+/g)) {
540
- if (run.index > 0 && !/[\s;&|(\x60'"\\]/.test(text[run.index - 1]))
541
- continue;
542
- if (!CREDENTIAL_KEY_WORD.test(run[0]))
543
- continue;
544
- if (run[0].startsWith('--'))
545
- return true;
546
- ASSIGNMENT_OPERATOR.lastIndex = run.index + run[0].length;
547
- if (ASSIGNMENT_OPERATOR.test(text))
548
- return true;
549
- }
550
- return false;
551
- }
552
- /**
553
- * Whether `word` ends in a credential flag the space-separated rule reads on
554
- * its own: it reads boundaries in the raw text, so `\<tab>--token` (an escaped
555
- * tab) ends in one.
556
- */
557
- function endsInCredentialFlag(word) {
558
- let start = word.length;
559
- while (start > 0 && KEY_CHARACTER.test(word[start - 1]))
560
- start -= 1;
561
- if (!word.startsWith('--', start))
562
- return false;
563
- // A substitution a pass replaced with the redaction marker still ends where
564
- // its backtick did, so a flag after the marker starts a word as it did.
565
- if (start > 0 &&
566
- !/[\s;&|(\x60]/.test(word[start - 1]) &&
567
- !word.slice(0, start).endsWith(REDACTED))
568
- return false;
569
- return CREDENTIAL_KEY_WORD.test(word.slice(start + 2));
570
- }
571
- /**
572
- * Whether to redact a word the chain reached. The other rules read credential
573
- * keys in the raw text and, for nested commands, in decoded words, so a word
574
- * that spells one either way (a bare credential flag among them) is left whole
575
- * for them to read, exactly as it reads without the chain. So is a header that
576
- * a value pattern reads on into `after`, the word that follows it.
577
- */
578
- function isChainedValue(word, after) {
579
- return ![
580
- [word, after],
581
- [decodeShellWord(word), after === undefined ? undefined : decodeShellWord(after)],
582
- ].some(([text, next]) => spellsCredentialKey(text) || startsValueHeader(text, next));
583
- }
584
- // `VALUE_REDACTIONS` without the global flag, for testing a single word.
585
- const VALUE_PATTERNS = VALUE_REDACTIONS.map(([pattern]) => new RegExp(pattern.source, pattern.flags.replace('g', '')));
586
- /**
587
- * Whether `text` begins a match of a value pattern that runs on into the next
588
- * word, as a header name does (`Cookie: name=value`). Redacting that word
589
- * would hide the value from the pattern, so the chain leaves it whole. Where
590
- * no word follows (`next` is undefined: an operator or the end), no pattern
591
- * can read on, so the word is not left. The test is read off
592
- * `VALUE_REDACTIONS` itself, so a pattern added later is covered without a
593
- * list of header names here.
594
- */
595
- function startsValueHeader(text, next) {
596
- if (next === undefined)
597
- return false;
598
- return VALUE_PATTERNS.some((pattern) => [' name=value', ' value', ...(next ? [` ${next}`] : [])].some((following) => {
599
- const match = pattern.exec(text + following);
600
- return (match !== null &&
601
- match.index < text.length &&
602
- match.index + match[0].length > text.length);
603
- }));
604
- }
605
- /** Whether the word after `word` is a credential flag's value. */
606
- function continuesCredentialChain(word) {
607
- // Decoded too: quotes hide a flag glued after a substitution or the
608
- // redaction marker that replaced one (`[redacted]"--passwd"`).
609
- return (isBareCredentialFlag(word) ||
610
- endsInCredentialFlag(word) ||
611
- endsInCredentialFlag(decodeShellWord(word)));
612
- }
613
- /**
614
- * The words to redact after `value`, a word ending at `end` that a rule has
615
- * just taken as a credential's value. If `value` is itself a credential flag,
616
- * the redaction hides the flag the space-separated rule would read, so its
617
- * value, and the chain after it, are redacted here instead. This is the one
618
- * rule for every value edit: each rule that redacts a word as a value passes
619
- * the word here, whatever flag or tool took it. `seen` holds the ends a chain
620
- * has already left, so a run of flags stays linear.
621
- */
622
- function followCredentialChain(value, end, next, seen, text) {
623
- const ranges = [];
624
- for (let word = value; continuesCredentialChain(word);) {
625
- if (seen.has(end))
626
- break;
627
- seen.add(end);
628
- const following = next(end);
629
- if (!following)
630
- break;
631
- if (isAttachedCredentialFlag(following.word))
632
- break;
633
- if (isChainedValue(following.word, wordAfter(text, following.end, next)))
634
- ranges.push({ start: following.start, end: following.end, text: REDACTED });
635
- word = following.word;
636
- end = following.end;
637
- }
638
- return ranges;
639
- }
640
- /**
641
- * The word after position `end` for `startsValueHeader`: undefined where an
642
- * operator follows, so no pattern can read on, and empty at the end of the
643
- * text, which may be a nested word the enclosing command continues after.
644
- */
645
- function wordAfter(text, end, next) {
646
- const following = next(end);
647
- if (following)
648
- return following.word;
649
- return text.slice(end).trim() === '' ? '' : undefined;
650
- }
651
- /** Steps through `text` by shell word: a chain ends at an operator. */
652
- function textChainCursor(text) {
653
- return (end) => {
654
- NEXT_SHELL_WORD.lastIndex = end;
655
- let next = NEXT_SHELL_WORD.exec(text);
656
- // A line continuation left in a nested script is not a word.
657
- while (next && LINE_CONTINUATION.test(next[2]))
658
- next = NEXT_SHELL_WORD.exec(text);
659
- if (!next)
660
- return undefined;
661
- return {
662
- word: next[2],
663
- start: NEXT_SHELL_WORD.lastIndex - next[2].length,
664
- end: NEXT_SHELL_WORD.lastIndex,
665
- };
666
- };
667
- }
668
- /**
669
- * Replace each range of `text` with its text. Where ranges overlap, the
670
- * earlier one is written and the text under the later one is dropped, so an
671
- * overlap never puts back what either range removed.
672
- */
673
- function applyRanges(text, ranges) {
674
- ranges.sort((a, b) => a.start - b.start);
675
- let out = '';
676
- let cursor = 0;
677
- for (const range of ranges) {
678
- if (range.end <= cursor)
679
- continue;
680
- if (range.start >= cursor)
681
- out += text.slice(cursor, range.start) + range.text;
682
- cursor = range.end;
683
- }
684
- return out + text.slice(cursor);
685
- }
686
- /**
687
- * `text.replace(pattern, replace)` for a pattern whose last group is a value
688
- * the replacement may redact. A redacted value keeps its credential chain,
689
- * which may run on into `after`, the text that follows `text`; the words it
690
- * redacts there are returned as ranges of `after`.
691
- */
692
- function replaceValues(text, pattern, replace, after = '') {
693
- const next = textChainCursor(text + after);
694
- const seen = new Set();
695
- const ranges = [];
696
- const beyond = [];
697
- for (const match of text.matchAll(pattern)) {
698
- const end = match.index + match[0].length;
699
- const replaced = replace(match[0], ...match.slice(1).map((group) => group ?? ''));
700
- if (replaced === match[0])
701
- continue;
702
- ranges.push({ start: match.index, end, text: replaced });
703
- for (const range of followCredentialChain(match.at(-1) ?? '', end, next, seen, text + after)) {
704
- if (range.start < text.length)
705
- ranges.push(range);
706
- else
707
- beyond.push({
708
- start: range.start - text.length,
709
- end: range.end - text.length,
710
- text: range.text,
711
- });
712
- }
713
- }
714
- return { text: applyRanges(text, ranges), after: beyond };
715
- }
716
- function redactCredentialFlagValues(command) {
717
- const next = textChainCursor(command);
718
- const ranges = [];
719
- // A chain runs the same from any word it reaches, so one that reaches a word
720
- // another chain already left stops there, keeping a run of flags linear.
721
- const chained = new Set();
722
- for (const match of command.matchAll(CREDENTIAL_FLAG)) {
723
- const end = match.index + match[1].length + match[2].length + match[3].length;
724
- ranges.push({ start: end - match[3].length, end, text: REDACTED });
725
- ranges.push(...followCredentialChain(match[3], end, next, chained, command));
726
- }
727
- // A quote or escape in a flag (`'--token'`, `\--token`) hides it from the
728
- // pattern above, though the shell passes the tool the same flag. Read each
729
- // word as the shell decodes it, so the flag takes its value wherever it
730
- // stands, including where a command starts, which the per-tool walker
731
- // reads as the program's name.
732
- let wordEnd = 0;
733
- for (const word of command.matchAll(SHELL_WORDS)) {
734
- // A quote between words opens a string that never closes (a word would
735
- // have taken a closed one), and the shell reads the rest as its text.
736
- if (/['"]/.test(command.slice(wordEnd, word.index)))
737
- break;
738
- wordEnd = word.index + word[0].length;
739
- if (word.index > 0 && !/[\s;&|(]/.test(command[word.index - 1]))
740
- continue;
741
- // A substitution a pass replaced with the redaction marker ends where its
742
- // backtick did, so a flag glued after either starts a word.
743
- const flag = word[0].replace(/^(?:\x60|\[redacted\])+/, '');
744
- if (decodeShellWord(flag) === flag || !isBareCredentialFlag(flag))
745
- continue;
746
- const end = word.index + word[0].length;
747
- const value = next(end);
748
- // A value that spells a credential key or starts a header is left whole
749
- // for the rules that read one, as the chain leaves it; so is one that
750
- // opens a backtick substitution, which the substitution passes read.
751
- if (!value ||
752
- value.word.includes('\x60') ||
753
- !isChainedValue(value.word, wordAfter(command, value.end, next)))
754
- continue;
755
- ranges.push({ start: value.start, end: value.end, text: REDACTED });
756
- ranges.push(...followCredentialChain(value.word, value.end, next, chained, command));
757
- }
758
- return applyRanges(command, ranges);
759
- }
760
- function applyCommandRedactions(command) {
761
- let out = command;
762
- for (const redaction of COMMAND_REDACTIONS)
763
- out = typeof redaction === 'function' ? redaction(out) : out.replace(...redaction);
764
- return out;
765
- }
766
- /**
767
- * Redactions applied to command text, in order: heredoc bodies (bulk inline
768
- * file content), private-key blocks, URL userinfo credentials, Authorization
769
- * headers, sensitive key=value / key: value pairs (quoted values with spaces
770
- * included), then well-known bare token prefixes (OpenAI/Anthropic sk-,
771
- * GitHub ghp_/github_pat_, Slack xox*, AWS AKIA). Redaction is best-effort —
772
- * the length cap below is the backstop for anything these patterns miss.
773
- */
774
- const COMMAND_REDACTIONS = [
775
- [new RegExp(`(<<<\\s*)${SHELL_WORD_SOURCE}`, 'g'), `$1${REDACTED}`],
776
- // Heredoc: `cmd <<[-]['"]?WORD['"]? \n <body> \n WORD`. The body is inline
777
- // file content (secrets, source) that must never leave the machine — replace
778
- // it wholesale, keeping only the delimiters. Runs first so a heredoc'd
779
- // private key / token is gone before the narrower patterns below even scan.
780
- // Terminates on the closing delimiter line or end-of-input (unterminated
781
- // capture). Over-matching a rare `a << B` bit-shift only over-redacts, which
782
- // is the safe failure mode here.
783
- [
784
- /(<<-?\s*['"]?)([A-Za-z_]\w*)(['"]?)[\s\S]*?(\n[ \t]*\2\b|$)/g,
785
- `$1$2$3 ${REDACTED}$4`,
786
- ],
787
- [new RegExp(PRIVATE_KEY_BLOCK_SOURCE, 'g'), REDACTED],
788
- ...VALUE_REDACTIONS,
789
- redactCredentialFlagValues,
790
- // JSON bodies embedded in shell commands are still command text. Quoted
791
- // keys evade the shell-assignment scanner below, including escaped values.
792
- [
793
- new RegExp(`("${COMMAND_SENSITIVE_KEY_SOURCE}"\\s*:\\s*)"(?:\\\\.|[^"\\\\])*"`, 'gi'),
794
- `$1"${REDACTED}"`,
795
- ],
796
- // Sensitive assignment: an env-var-ish key (the sensitive word optionally
797
- // wrapped in `DB_…` / `…_FILE` segments, so `DB_PASSWORD`/`OPENAI_API_KEY`
798
- // match, not just a bare word) followed by `=`/`:` and a value that is a
799
- // double/single-quoted string (spaces and all) or an unquoted run up to the
800
- // next whitespace. Anchored at a shell-token boundary ($1, preserved) so it
801
- // never fires mid-word (a backtick opens a substitution's first word, as
802
- // `(` does); the whole value — quotes included — is redacted so
803
- // whitespace-containing passphrases can't slip through.
804
- [
805
- new RegExp(`(^|[\\s;&|(\\x60])(${COMMAND_SENSITIVE_KEY_SOURCE}\\s*[=:]\\s*)${SHELL_WORD_SOURCE}`, 'gi'),
806
- `$1$2${REDACTED}`,
807
- ],
808
- // Our own CLI token (`API_KEY_PREFIX`, the prefix the dashboard mints CLI
809
- // tokens under). Listed with the third-party prefixes because the documented
810
- // setup path — `mossbear sync --token mossbear_…` — is a *space-separated*
811
- // flag, so the `key=value` rule above never sees it: without this, the hook
812
- // logs that command and the next sync uploads a live dashboard credential in
813
- // an action summary. The product's own secret shape is the one most likely to
814
- // appear in a command a user runs. Any future re-mint under a new prefix has
815
- // to be added here in the same change — a token this rule does not match is
816
- // one the action log keeps in plaintext.
817
- [/\bmossbear_[A-Za-z0-9_-]{8,}/g, REDACTED],
818
- // The pre-rename prefix. Every key issued under it is deleted by migration
819
- // `0056-revoke_legacy_prefix_cli_tokens.ts`, so this matches nothing that can
820
- // still authenticate — it is kept because a CLI redacting on the user's
821
- // machine can be older or newer than the dashboard it syncs to, and the
822
- // window where one of these is still live is exactly the window where
823
- // dropping the rule would upload it in plaintext.
824
- [/\bauden_[A-Za-z0-9_-]{8,}/g, REDACTED],
825
- [/\bsk-[A-Za-z0-9_-]{8,}/g, REDACTED],
826
- [/\bgh[pousr]_[A-Za-z0-9]{8,}/g, REDACTED],
827
- [/\bgithub_pat_[A-Za-z0-9_]{8,}/g, REDACTED],
828
- [/\bxox[baprs]-[A-Za-z0-9-]{8,}/g, REDACTED],
829
- [/\bAKIA[0-9A-Z]{16}\b/g, REDACTED],
830
- ];
831
- /**
832
- * Proxy addresses take userinfo with or without a URL scheme, so the general
833
- * URL rule cannot see the scheme-less form. A bare `a:b@c` is not matched
834
- * everywhere because ordinary text has that shape too (`image:tag@sha256:…`);
835
- * only values in HTTP-client commands or proxy assignments are checked.
836
- */
837
- const PROXY_USERINFO = /^((?:[a-z][a-z\d+.-]*:\/\/)?[^/?#:@]*:)[^/?#]*@/i;
838
- /**
839
- * Redact the password from proxy environment assignments (`https_proxy=`,
840
- * `ALL_PROXY=`, …), which HTTP clients read at startup. Keeps the user and
841
- * host, matching the URL-userinfo rule, and leaves unauthenticated values as
842
- * they are. Other inline curl authentication fields lose their whole value.
843
- */
844
- function redactCredentialAssignments(command, inputs) {
845
- let assignments = command.replace(new RegExp(SHELL_WORD_SOURCE, 'g'), (word) => {
846
- // `env` accepts a quoted whole NAME=value argument. Decode the complete
847
- // word before identifying its key, just as for shell-encoded options.
848
- const assignment = /^([^=\0]+)=([\s\S]*)$/.exec(decodeShellWord(word));
849
- if (!assignment)
850
- return word;
851
- let key = assignment[1];
852
- let operator = '=';
853
- const proxy = assignment[2];
854
- if (key.endsWith('+') && !inputs.env.has(key)) {
855
- key = key.slice(0, -1);
856
- operator = '+=';
857
- }
858
- if (inputs.env.has(key))
859
- return `${key}${operator}${REDACTED}`;
860
- if (!/^(?:\w+_)?proxy$/i.test(key))
861
- return word;
862
- if (!PROXY_USERINFO.test(proxy))
863
- return word;
864
- const redacted = proxy.replace(PROXY_USERINFO, `$1${REDACTED}@`);
865
- return `${key}${operator}${redacted}`;
866
- });
867
- if (inputs.passSources.size || inputs.env.size)
868
- assignments = assignments.replace(new RegExp(`(<<<[ \\t]*)${SHELL_WORD_SOURCE}`, 'g'), `$1${REDACTED}`);
869
- // Config literals are produced by echo/printf before curl consumes -K.
870
- // Keep that channel separate from executable flags: sort -u and OpenSSL
871
- // passphrase source options must not become curl configuration by spelling.
872
- const words = [
873
- ...assignments.matchAll(new RegExp(`${SHELL_WORD_SOURCE}|[;&|()\\n]`, 'g')),
874
- ];
875
- if (!inputs.curlConfig && !inputs.passSources.size && !inputs.env.size)
876
- return assignments;
877
- const fields = new RegExp(`(^|[\\s'\"])(-{0,2}(?:(?:\\w+_)?proxy|${CURL_AUTH_OPTIONS})|-[uUbEx])([ \\t]*(?:=|:)[ \\t]*|[ \\t]+)(${SHELL_WORD_SOURCE})`, 'gi');
878
- const edits = [];
879
- let producerStart = null;
880
- let producerPrintf = false;
881
- const finishProducer = (end) => {
882
- if (producerStart === null)
883
- return;
884
- const body = assignments.slice(producerStart, end);
885
- const prefix = assignments.slice(0, producerStart);
886
- const producesPassphrase = (assignments[end] === '|' &&
887
- (inputs.passSources.has('stdin') ||
888
- [...inputs.passSources].some((source) => source.startsWith('fd:')))) ||
889
- ([...inputs.passSources].some((source) => /^(?:fd:|file:)/.test(source)) &&
890
- prefix.includes('<(')) ||
891
- [...inputs.passSources].some((source) => source.startsWith('file:') &&
892
- body.includes('>') &&
893
- body.includes(source.slice(5))) ||
894
- [...inputs.env].some((key) => prefix.includes(`${key}=`) && prefix.includes('('));
895
- if (producesPassphrase) {
896
- edits.push({ start: producerStart, end, text: ` ${REDACTED} ` });
897
- producerStart = null;
898
- return;
899
- }
900
- if (!inputs.curlConfig) {
901
- producerStart = null;
902
- return;
903
- }
904
- const decodedBody = [...body.matchAll(new RegExp(SHELL_WORD_SOURCE, 'g'))]
905
- .map((word) => decodeShellWord(word[0]))
906
- .join(' ');
907
- if (hasPrivateConfigVariables(decodedBody)) {
908
- edits.push({ start: producerStart, end, text: ` ${REDACTED} ` });
909
- producerStart = null;
910
- return;
911
- }
912
- const redactField = (match, prefix, key, separator, value) => {
913
- if (/^-[a-z]$/i.test(key) && !['-u', '-U', '-b', '-E', '-x'].includes(key))
914
- return match;
915
- const credential = decodeShellWord(value);
916
- const field = key.replace(/^-+/, '');
917
- if (producerPrintf && credential.includes('%'))
918
- return `${prefix}${key}${separator}${REDACTED}`;
919
- if (/^(?:proxy-)?(?:user|cert)$/i.test(field)) {
920
- if (!credential.includes(':'))
921
- return match;
922
- return `${prefix}${key}${separator}${credential.replace(/^([^:]*:)[\s\S]*$/, `$1${REDACTED}`)}`;
923
- }
924
- if (/^cookie$/i.test(field) && !credential.includes('='))
925
- return match;
926
- if (/^(?:(?:\w+_)?proxy|x)$/i.test(field) || CURL_URL_FIELD.test(field))
927
- return PROXY_USERINFO.test(credential)
928
- ? `${prefix}${key}${separator}${credential.replace(PROXY_USERINFO, `$1${REDACTED}@`)}`
929
- : match;
930
- return `${prefix}${key}${separator}${REDACTED}`;
931
- };
932
- // A producer's literals obey shell quoting before becoming config text.
933
- // Decode concatenated/escaped field names before matching them, while
934
- // retaining untouched words and also scanning unquoted multiword fields.
935
- let text = body.replace(new RegExp(SHELL_WORD_SOURCE, 'g'), (word) => {
936
- const decoded = decodeShellWord(word);
937
- const redacted = replaceValues(decoded, fields, redactField).text;
938
- return redacted === decoded ? word : JSON.stringify(redacted);
939
- });
940
- // The body ends at the producer's operator, but a field's credential
941
- // chain reaches on across a newline, as `redactCredentialFlagValues`
942
- // does, so the chain's words after the body are edited too.
943
- const fieldEdits = replaceValues(text, fields, redactField, assignments.slice(end));
944
- text = fieldEdits.text;
945
- for (const range of fieldEdits.after)
946
- edits.push({ start: end + range.start, end: end + range.end, text: range.text });
947
- // A printf template may take the credential from later arguments. Once
948
- // its format is private, drop the argument list rather than expose the
949
- // values substituted into it or attempt to interpret printf formatting.
950
- if (text !== body && producerPrintf && body.includes('%'))
951
- text = ` ${REDACTED} `;
952
- if (text !== body)
953
- edits.push({ start: producerStart, end, text });
954
- producerStart = null;
955
- };
956
- // Decided at each command's first word, so a file argument named echo under
957
- // a program that never runs its arguments is not mistaken for a producer.
958
- // Wrappers are not looked past here, which only errs toward redaction.
959
- let commandSeen = false;
960
- let argumentsInert = false;
961
- for (const word of words) {
962
- if (/^[;&|()\n]$/.test(word[0])) {
963
- finishProducer(word.index);
964
- commandSeen = false;
965
- argumentsInert = false;
966
- continue;
967
- }
968
- const decoded = decodeShellWord(word[0]);
969
- if (!commandSeen && !/^\w+\+?=/.test(decoded)) {
970
- commandSeen = true;
971
- argumentsInert = isNonDispatching(assignments, word.index, decoded);
972
- }
973
- const tool = invokedTool(decoded);
974
- // A backtick substitution runs its own command, whatever the outer one is.
975
- const inert = argumentsInert && !word[0].includes('`');
976
- if (producerStart === null && !inert && ['echo', 'printf'].includes(tool)) {
977
- producerStart = word.index + word[0].length;
978
- producerPrintf = tool === 'printf';
979
- }
980
- }
981
- finishProducer(assignments.length);
982
- return applyRanges(assignments, edits);
983
- }
984
- /** Redact known tool credential flags without matching unrelated short flags. */
985
- function redactToolArguments(command, inputs) {
986
- const words = [...command.matchAll(new RegExp(`${SHELL_WORD_SOURCE}|[;&|()\n]`, 'g'))];
987
- const edits = [];
988
- let client = null;
989
- let options = true;
990
- let opensslPasswd = false;
991
- let opensslSubcommandRead = false;
992
- // Set once a wrapper in the current command receives an option it does not
993
- // model, which may have taken the next word as its value.
994
- let wrapperOptionUnknown = false;
995
- // The current command is a program that never runs its arguments.
996
- let argumentsInert = false;
997
- const variables = new Map();
998
- const expansions = [];
999
- const resolveVariable = (contents, depth = 0) => {
1000
- if (depth > 20)
1001
- return 'private:@';
1002
- return contents.replace(CURL_EXPANSION, (_, name) => resolveVariable(variables.get(name)?.at(-1)?.contents ?? '', depth + 1));
1003
- };
1004
- const finishCurl = () => {
1005
- const privateNames = new Set(inputs?.curlVariables);
1006
- for (const expansion of expansions) {
1007
- if (CURL_URL_FIELD.test(expansion.field) &&
1008
- !PROXY_USERINFO.test(expansion.resolved) &&
1009
- !new RegExp(`[?&#]${COMMAND_SENSITIVE_KEY_SOURCE}=`, 'i').test(expansion.resolved))
1010
- continue;
1011
- for (const match of expansion.contents.matchAll(CURL_EXPANSION))
1012
- privateNames.add(match[1]);
1013
- }
1014
- // Expanded variable definitions can themselves refer to other definitions.
1015
- // Walk each name once, including all assignments, without evaluating shell code.
1016
- for (const name of privateNames) {
1017
- for (const variable of variables.get(name) ?? []) {
1018
- if (variable.env)
1019
- inputs?.env.add(name);
1020
- if (variable.contents === undefined)
1021
- continue;
1022
- for (const match of variable.contents.matchAll(CURL_EXPANSION))
1023
- privateNames.add(match[1]);
1024
- edits.push({
1025
- start: variable.start,
1026
- end: variable.end,
1027
- text: `${variable.prefix}${REDACTED}`,
1028
- });
1029
- }
1030
- }
1031
- for (const name of privateNames)
1032
- inputs?.curlVariables.add(name);
1033
- variables.clear();
1034
- expansions.length = 0;
1035
- };
1036
- for (let index = 0; index < words.length; index += 1) {
1037
- const word = words[index];
1038
- if (!word)
1039
- continue;
1040
- const raw = word[0];
1041
- if (/^[;&|()\n]$/.test(raw)) {
1042
- finishCurl();
1043
- client = null;
1044
- opensslPasswd = false;
1045
- opensslSubcommandRead = false;
1046
- wrapperOptionUnknown = false;
1047
- argumentsInert = false;
1048
- options = true;
1049
- continue;
1050
- }
1051
- const decoded = decodeShellWord(raw);
1052
- if (opensslPasswd) {
1053
- // passwd hashes each positional plaintext password. Its source and salt
1054
- // flags consume nonsecret references, which must not be mistaken for it.
1055
- const sourceFlag = /^-{1,2}(?:in|salt|rand|writerand|provider|provider-path|provparam|propquery)(?:=(.*))?$/.exec(decoded);
1056
- if (options && sourceFlag) {
1057
- if (inputs && /^-{1,2}in(?:=|$)/.test(decoded)) {
1058
- const source = sourceFlag[1] ?? words[index + 1]?.[0];
1059
- if (source)
1060
- inputs.passSources.add(`file:${decodeShellWord(source)}`);
1061
- }
1062
- if (sourceFlag[1] === undefined)
1063
- index += 1;
1064
- continue;
1065
- }
1066
- if (options && /^-{1,2}stdin$/.test(decoded))
1067
- inputs?.passSources.add('stdin');
1068
- if (!options || !decoded.startsWith('-')) {
1069
- edits.push({ start: word.index, end: word.index + raw.length, text: REDACTED });
1070
- continue;
1071
- }
1072
- }
1073
- if (client === 'sshpass') {
1074
- // sshpass dispatches a child after its own credential/source options.
1075
- // Consume source arguments so a filename named curl is not executable.
1076
- const source = /^-[fdP](.*)$/.exec(decoded);
1077
- if (options && source) {
1078
- if (!source[1])
1079
- index += 1;
1080
- continue;
1081
- }
1082
- if (options && /^-[evhV]+$/.test(decoded))
1083
- continue;
1084
- if (!options || !decoded.startsWith('-'))
1085
- client = null;
1086
- }
1087
- if (!CREDENTIAL_TOOLS.includes(client ?? '')) {
1088
- if (/^\w+\+?=/.test(decoded))
1089
- continue;
1090
- const wrapperValue = options
1091
- ? WRAPPER_VALUE_FLAGS[client ?? '']?.exec(decoded)
1092
- : null;
1093
- if (wrapperValue) {
1094
- if (wrapperValue[1] === undefined && wrapperValue[2] === undefined)
1095
- index += 1;
1096
- continue;
1097
- }
1098
- }
1099
- const executable = invokedTool(decoded);
1100
- // A backtick substitution runs its own command, whatever the outer one is.
1101
- const inert = argumentsInert && !raw.includes('`');
1102
- if (!inert &&
1103
- WRAPPER_VALUE_FLAGS[executable] &&
1104
- !CREDENTIAL_TOOLS.includes(client ?? '')) {
1105
- client = executable;
1106
- options = true;
1107
- continue;
1108
- }
1109
- // Dispatching tools may take their own options and positional arguments.
1110
- // Once a credential-consuming tool appears, its subsequent flags still carry
1111
- // credentials; a wrapper's -u or timeout must not hide that client.
1112
- if (!inert &&
1113
- CREDENTIAL_TOOLS.includes(executable) &&
1114
- !CREDENTIAL_TOOLS.includes(client ?? '')) {
1115
- client = executable;
1116
- opensslPasswd = false;
1117
- opensslSubcommandRead = false;
1118
- options = true;
1119
- continue;
1120
- }
1121
- // A wrapper's first operand (its modelled valued options were consumed
1122
- // above) is the program it runs, which decides whether later words can be
1123
- // invocations. After an option the table does not model, that operand may
1124
- // be the option's value instead, so the wrapper keeps dispatching.
1125
- if (client !== null && WRAPPER_VALUE_FLAGS[client]) {
1126
- if (options && decoded.startsWith('-')) {
1127
- if (decoded !== '--' &&
1128
- !decoded.includes('=') &&
1129
- !WRAPPER_SWITCHES[client]?.test(decoded))
1130
- wrapperOptionUnknown = true;
1131
- }
1132
- else if (!wrapperOptionUnknown) {
1133
- client = executable;
1134
- argumentsInert = isNonDispatching(command, word.index, decoded);
1135
- options = true;
1136
- continue;
1137
- }
1138
- }
1139
- if (client === null) {
1140
- if (/^[\w]+=.*/.test(decoded) ||
1141
- ['env', 'sudo', 'command', 'exec', 'nohup'].includes(decoded))
1142
- continue;
1143
- client = invokedTool(decoded);
1144
- argumentsInert = isNonDispatching(command, word.index, decoded);
1145
- continue;
1146
- }
1147
- if (client === 'openssl' && !opensslSubcommandRead && !decoded.startsWith('-')) {
1148
- opensslSubcommandRead = true;
1149
- opensslPasswd = decoded === 'passwd';
1150
- continue;
1151
- }
1152
- if (decoded === '--') {
1153
- options = false;
1154
- continue;
1155
- }
1156
- if (client === 'curl' && options) {
1157
- // Public source/output arguments cannot become config flags by spelling.
1158
- const publicSource = /^(-[oAw])(.+)?$|^(--(?:output|output-dir|write-out|user-agent|cacert|capath))(?:=(.*))?$/.exec(decoded);
1159
- if (publicSource) {
1160
- if (publicSource[2] === undefined && publicSource[4] === undefined)
1161
- index += 1;
1162
- continue;
1163
- }
1164
- if (CURL_CONFIG_FLAG.test(decoded) && inputs)
1165
- inputs.curlConfig = true;
1166
- const variableFlag = /^--(?:expand-)?variable(?:=(.*))?$/.exec(decoded);
1167
- const expandFlag = CURL_EXPAND_FLAG.exec(decoded);
1168
- if (variableFlag || expandFlag) {
1169
- const attached = variableFlag ? variableFlag[1] : expandFlag[2];
1170
- const value = attached === undefined ? words[index + 1] : word;
1171
- if (!value || /^[;&|()\n]$/.test(value[0]))
1172
- continue;
1173
- const contents = attached ?? decodeShellWord(value[0]);
1174
- if (variableFlag) {
1175
- const definition = /^(%?)([A-Za-z0-9_]+)(?:\[[^\]]*\])?(?:=([\s\S]*)|@[^\s]*|$)/.exec(contents);
1176
- if (definition) {
1177
- const name = definition[2];
1178
- const entries = variables.get(name) ?? [];
1179
- entries.push({
1180
- start: value.index,
1181
- end: value.index + value[0].length,
1182
- prefix: (attached === undefined ? '' : `${decoded.split('=')[0]}=`) +
1183
- contents.slice(0, contents.indexOf('=') + 1),
1184
- contents: definition[3],
1185
- env: definition[1] === '%',
1186
- });
1187
- variables.set(name, entries);
1188
- }
1189
- }
1190
- else
1191
- expansions.push({
1192
- field: expandFlag[1],
1193
- contents,
1194
- resolved: resolveVariable(contents),
1195
- });
1196
- if (attached === undefined)
1197
- index += 1;
1198
- continue;
1199
- }
1200
- }
1201
- if (client === 'openssl' && options && /^-{1,2}kfile(?:=|$)/.test(decoded)) {
1202
- const attached = decoded.includes('=')
1203
- ? decoded.slice(decoded.indexOf('=') + 1)
1204
- : undefined;
1205
- const source = attached ?? words[index + 1]?.[0];
1206
- if (source)
1207
- inputs?.passSources.add(`file:${decodeShellWord(source)}`);
1208
- if (attached === undefined)
1209
- index += 1;
1210
- continue;
1211
- }
1212
- // Curl also accepts URLs without a scheme and uses their userinfo as
1213
- // credentials. Restrict this shape to HTTP-client arguments so image
1214
- // digests and SSH paths in other commands retain their meaning. The Redis
1215
- // family reads a URI only with an explicit scheme; its other positional
1216
- // words are Redis command arguments, which must keep their meaning.
1217
- if (['curl', 'http', 'https', 'httpie', ...REDIS_FAMILY].includes(client) &&
1218
- (!REDIS_FAMILY.includes(client) || REDIS_URI.test(decoded)) &&
1219
- (!options || !decoded.startsWith('-')) &&
1220
- PROXY_USERINFO.test(decoded)) {
1221
- edits.push({
1222
- start: word.index,
1223
- end: word.index + raw.length,
1224
- text: decoded.replace(PROXY_USERINFO, `$1${REDACTED}@`),
1225
- });
1226
- continue;
1227
- }
1228
- if (!options)
1229
- continue;
1230
- // Decode option spellings before classifying them: shell quotes and
1231
- // escapes change syntax, never the credential the invoked tool receives.
1232
- const sensitiveFlag = /^--([^=]+)(?:=(.*))?$/.exec(decoded);
1233
- if (sensitiveFlag && SENSITIVE_KEY.test(sensitiveFlag[1])) {
1234
- const attached = sensitiveFlag[2];
1235
- const value = attached === undefined ? words[index + 1] : word;
1236
- if (value && !/^[;&|()\n]$/.test(value[0])) {
1237
- edits.push({
1238
- start: value.index,
1239
- end: value.index + value[0].length,
1240
- text: attached === undefined ? REDACTED : `--${sensitiveFlag[1]}=${REDACTED}`,
1241
- });
1242
- if (attached === undefined)
1243
- index += 1;
1244
- }
1245
- continue;
1246
- }
1247
- // Password flags are per tool: the spelling is what names the credential,
1248
- // so each tool's table entry is the only place its flags are defined.
1249
- const directPasswordFlag = DIRECT_PASSWORD_FLAGS.get(client ?? '')?.exec(decoded);
1250
- if (directPasswordFlag) {
1251
- const name = directPasswordFlag[1];
1252
- const mysqlFamily = MYSQL_FAMILY.includes(client ?? '');
1253
- const attached = client === 'sshpass' || mysqlFamily
1254
- ? directPasswordFlag[2] || undefined
1255
- : directPasswordFlag[2];
1256
- // MySQL reads a bare -p as a prompt, so the next word is the database, not
1257
- // a password. Only the attached -p<pw> spelling carries one.
1258
- if (mysqlFamily && attached === undefined)
1259
- continue;
1260
- const value = attached === undefined ? words[index + 1] : word;
1261
- if (!value || /^[;&|()\n]$/.test(value[0]))
1262
- continue;
1263
- const password = attached ?? decodeShellWord(value[0]);
1264
- if (client === 'openssl' && inputs) {
1265
- if (/^env:[^=\0]+$/.test(password))
1266
- inputs.env.add(password.slice(4));
1267
- else if (/^(?:stdin|(?:file|fd):)/.test(password))
1268
- inputs.passSources.add(password);
1269
- }
1270
- if (client !== 'openssl' ||
1271
- /^(?:k|srppass|pwri_password|secretkey|hmac)$/i.test(name.replace(/^-+/, '')) ||
1272
- password.startsWith('pass:')) {
1273
- edits.push({
1274
- start: value.index,
1275
- end: value.index + value[0].length,
1276
- text: attached === undefined
1277
- ? REDACTED
1278
- : `${name}${client === 'openssl' || name.startsWith('--') ? '=' : ''}${REDACTED}`,
1279
- });
1280
- }
1281
- if (attached === undefined)
1282
- index += 1;
1283
- continue;
1284
- }
1285
- if (!['curl', 'http', 'https', 'httpie'].includes(client))
1286
- continue;
1287
- const payloadFlag = client === 'curl' ? CURL_PAYLOAD_FLAG.exec(decoded) : null;
1288
- if (payloadFlag) {
1289
- const name = payloadFlag[1] ?? payloadFlag[3];
1290
- const attached = payloadFlag[2] ?? payloadFlag[4];
1291
- const value = attached === undefined ? words[index + 1] : word;
1292
- if (!value || /^[;&|()\n]$/.test(value[0]))
1293
- continue;
1294
- const payload = attached ?? decodeShellWord(value[0]);
1295
- const header = /^([^:]+):/.exec(payload);
1296
- const isHeader = ['--header', '--proxy-header'].includes(name) ||
1297
- (!name.startsWith('--') && name.endsWith('H'));
1298
- // JSON is handled structurally above. Form fields must also inspect
1299
- // percent-decoded names: passwords do not become public by encoding.
1300
- const formHasCredential = [...new URLSearchParams(payload).keys()].some((key) => SENSITIVE_KEY.test(key));
1301
- if (isHeader ? header && SENSITIVE_KEY.test(header[1].trim()) : formHasCredential) {
1302
- edits.push({
1303
- start: value.index,
1304
- end: value.index + value[0].length,
1305
- text: attached === undefined
1306
- ? REDACTED
1307
- : `${name}${name.startsWith('--') ? '=' : ''}${REDACTED}`,
1308
- });
1309
- }
1310
- if (attached === undefined)
1311
- index += 1;
1312
- continue;
1313
- }
1314
- const flag = client === 'curl'
1315
- ? CURL_AUTH_FLAG.exec(decoded)
1316
- : /^(-a)(.+)?$|^(--auth)(?:=(.*))?$/.exec(decoded);
1317
- if (!flag)
1318
- continue;
1319
- const name = flag[1] ?? flag[3];
1320
- const attached = flag[2] ?? flag[4];
1321
- const value = attached === undefined ? words[index + 1] : word;
1322
- if (!value || /^[;&|()\n]$/.test(value[0]))
1323
- continue;
1324
- let replacement = REDACTED;
1325
- if (CURL_URL_FIELD.test(name.replace(/^-+/, '')) ||
1326
- (!name.startsWith('--') && name.endsWith('x'))) {
1327
- const proxy = attached ?? decodeShellWord(value[0]);
1328
- if (!PROXY_USERINFO.test(proxy)) {
1329
- if (attached === undefined)
1330
- index += 1;
1331
- continue;
1332
- }
1333
- replacement = proxy.replace(PROXY_USERINFO, `$1${REDACTED}@`);
1334
- }
1335
- if (attached !== undefined) {
1336
- edits.push({
1337
- start: word.index,
1338
- end: word.index + raw.length,
1339
- text: `${name}${name?.startsWith('--') ? '=' : ''}${replacement}`,
1340
- });
1341
- }
1342
- else {
1343
- edits.push({
1344
- start: value.index,
1345
- end: value.index + value[0].length,
1346
- text: replacement,
1347
- });
1348
- index += 1;
1349
- }
1350
- }
1351
- finishCurl();
1352
- // Every edit above replaces a whole word, and a word an edit replaces is
1353
- // gone before `redactCredentialFlagValues` reads the text. Where that word
1354
- // was a credential flag, the flag's value would escape, so the chain is
1355
- // followed here for every edit, whichever tool or flag made it.
1356
- const wordAt = new Map(words.map((word, at) => [word.index, at]));
1357
- const wordEndingAt = new Map(words.map((word, at) => [word.index + word[0].length, at]));
1358
- const nextWord = (end) => {
1359
- let next = wordEndingAt.get(end);
1360
- if (next === undefined)
1361
- return undefined;
1362
- next += 1;
1363
- while (words[next] && /^(?:\n|\\\r?\n)$/.test(words[next][0]))
1364
- next += 1;
1365
- const following = words[next];
1366
- if (!following || /^[;&|()\n]$/.test(following[0]))
1367
- return undefined;
1368
- return {
1369
- word: following[0],
1370
- start: following.index,
1371
- end: following.index + following[0].length,
1372
- };
1373
- };
1374
- const chainedWords = new Set();
1375
- const chainEdits = edits.flatMap((edit) => {
1376
- const at = wordAt.get(edit.start);
1377
- const word = at === undefined ? undefined : words[at];
1378
- if (!word || edit.end !== word.index + word[0].length)
1379
- return [];
1380
- return followCredentialChain(word[0], edit.end, nextWord, chainedWords, command);
1381
- });
1382
- // A chain edit either matches an edit's word or misses it; on a match the
1383
- // whole-word redaction replaces it, so the chain only ever adds.
1384
- const editAt = new Map(edits.map((edit, at) => [edit.start, at]));
1385
- for (const chainEdit of chainEdits) {
1386
- const same = editAt.get(chainEdit.start);
1387
- if (same === undefined)
1388
- edits.push(chainEdit);
1389
- else
1390
- edits[same] = chainEdit;
1391
- }
1392
- edits.sort((a, b) => a.start - b.start);
1393
- for (const edit of edits.reverse())
1394
- command = command.slice(0, edit.start) + edit.text + command.slice(edit.end);
1395
- return command;
1396
- }
1397
- /** Find config consumers across shell wrappers before scanning their producers. */
1398
- function getToolInputs(command, depth = 0) {
1399
- const inputs = {
1400
- curlConfig: depth > 8,
1401
- env: new Set(),
1402
- passSources: new Set(),
1403
- curlVariables: new Set(),
1404
- };
1405
- if (depth > 8)
1406
- return inputs;
1407
- // Use the same invocation parser as redaction; an SSH -K is not curl config.
1408
- redactToolArguments(command, inputs);
1409
- const words = [...command.matchAll(new RegExp(SHELL_WORD_SOURCE, 'g'))];
1410
- for (const word of words) {
1411
- const decoded = decodeShellWord(word[0]);
1412
- if (decoded === word[0] || !/[\s;&|()]/.test(decoded))
1413
- continue;
1414
- const nested = getToolInputs(decoded, depth + 1);
1415
- inputs.curlConfig ||= nested.curlConfig;
1416
- for (const key of nested.env)
1417
- inputs.env.add(key);
1418
- for (const source of nested.passSources)
1419
- inputs.passSources.add(source);
1420
- for (const name of nested.curlVariables)
1421
- inputs.curlVariables.add(name);
1422
- }
1423
- if (inputs.curlConfig) {
1424
- for (const word of words) {
1425
- const body = decodeShellWord(word[0]);
1426
- if (!hasPrivateConfigVariables(body))
1427
- continue;
1428
- for (const match of body.matchAll(/\b(?:expand-)?variable\s*[=: \t]+["']?%+([A-Za-z0-9_]+)/g))
1429
- inputs.env.add(match[1]);
1430
- }
1431
- }
1432
- return inputs;
1433
- }
1434
- /** Apply the same boundary to scripts carried inside quoted shell words. */
1435
- /** The part of `before` that `after` replaced: what a redaction removed. */
1436
- function changedPart(before, after) {
1437
- let start = 0;
1438
- while (start < before.length && before[start] === after[start])
1439
- start += 1;
1440
- let end = 0;
1441
- while (end < before.length - start &&
1442
- before[before.length - 1 - end] === after[after.length - 1 - end])
1443
- end += 1;
1444
- return before.slice(start, before.length - end);
1445
- }
1446
- function redactShellSyntax(command, depth = 0, inheritedInputs, valuesFirst = true) {
1447
- // Nested shell/eval wrappers cannot create unbounded recursive scanning.
1448
- if (depth > 8)
1449
- return REDACTED;
1450
- // Redacting a backtick body can erase the reference (`{{VALUE}}`) that
1451
- // marks an outer assignment private, so read its inputs from the command
1452
- // as written too.
1453
- const writtenInputs = command.includes('`')
1454
- ? withInheritedInputs(backtickAwareInputs(command), inheritedInputs)
1455
- : inheritedInputs;
1456
- // Rewriting part of a backtick body can separate a header from its value, so
1457
- // the value patterns redact such a match before any body is rewritten. Only
1458
- // such a match: one whose value the later passes remove anyway is left to
1459
- // them, since the word-based rules see the rest of its word (`"Cookie: a"b`).
1460
- // Redacting one match early changes what the later passes see, so a value
1461
- // still in their output is redacted early too and the passes run again.
1462
- if (valuesFirst && command.includes('`') && !command.includes('\uE000')) {
1463
- const values = valueRedactionTargets(command);
1464
- if (values.length > 0) {
1465
- const withoutValuesFirst = redactShellSyntax(command, depth, inheritedInputs, false);
1466
- const early = new Set(values.filter((value) => withoutValuesFirst.includes(value)));
1467
- for (let round = 0;; round += 1) {
1468
- const out = redactAfterValues(redactValuesFirst(command, round < 3 ? early : new Set(values)), depth, writtenInputs);
1469
- const stranded = values.filter((value) => !early.has(value) && out.includes(value));
1470
- if (stranded.length === 0 || round === 3)
1471
- return out;
1472
- for (const value of stranded)
1473
- early.add(value);
1474
- }
1475
- }
1476
- }
1477
- return redactAfterValues(command, depth, writtenInputs, valuesFirst);
1478
- }
1479
- /** The values the `VALUE_REDACTIONS` would remove from text with no backtick in the match. */
1480
- function valueRedactionTargets(command) {
1481
- const values = [];
1482
- for (const [pattern, replacement] of VALUE_REDACTIONS) {
1483
- const single = new RegExp(pattern.source, pattern.flags.replace('g', ''));
1484
- for (const match of command.match(pattern) ?? []) {
1485
- if (/[`\uE000\uE001]/.test(match))
1486
- continue;
1487
- const value = changedPart(match, match.replace(single, replacement));
1488
- if (value !== '' && !values.includes(value))
1489
- values.push(value);
1490
- }
1491
- }
1492
- return values;
1493
- }
1494
- /**
1495
- * Apply the value patterns whose value is in `early`, holding every other
1496
- * match aside so no later pattern can match part of it. A match that spans a
1497
- * backtick is always held: the substitution pass owns that boundary, and an
1498
- * unterminated one must still fail closed. A reference this erases is still
1499
- * in the caller's `writtenInputs`.
1500
- */
1501
- function redactValuesFirst(command, early) {
1502
- const held = [];
1503
- let whole = command;
1504
- for (const [pattern, replacement] of VALUE_REDACTIONS) {
1505
- const single = new RegExp(pattern.source, pattern.flags.replace('g', ''));
1506
- whole = whole.replace(pattern, (match) => {
1507
- const redacted = match.replace(single, replacement);
1508
- if (!/[`\uE000\uE001]/.test(match) && early.has(changedPart(match, redacted)))
1509
- return redacted;
1510
- held.push(match);
1511
- return `\uE000${held.length - 1}\uE001`;
1512
- });
1513
- }
1514
- // A held match can contain an earlier one; each refers only to earlier ones.
1515
- while (whole.includes('\uE000'))
1516
- whole = whole.replace(/\uE000(\d+)\uE001/g, (_, index) => held[Number(index)]);
1517
- return whole;
1518
- }
1519
- function redactAfterValues(command, depth, writtenInputs, valuesFirst = true) {
1520
- command = redactCommandSubstitutions(command, depth, writtenInputs, valuesFirst);
1521
- // Nested scripts may be dispatched by any tool. Scan decoded compound
1522
- // words instead of maintaining another list of interpreter/wrapper flags.
1523
- // JSON and sensitive assignments already have structural/whole-word passes;
1524
- // treating their values as commands would lose evidence or word boundaries.
1525
- const inputs = withInheritedInputs(backtickAwareInputs(command), writtenInputs);
1526
- const sensitiveAssignment = new RegExp(`^(${COMMAND_SENSITIVE_KEY_SOURCE})(\\+?=)`, 'i');
1527
- // Resolve credential references before nested word redaction can erase the
1528
- // expansion marker while leaving its original variable definition behind.
1529
- let out = redactToolArguments(redactJsonArguments(command), inputs).replace(new RegExp(SHELL_WORD_SOURCE, 'g'), (word) => {
1530
- const decoded = decodeShellWord(word);
1531
- // A compound word beginning with a credential assignment may be either
1532
- // an env value or a whole script. Its entire value is private in both
1533
- // cases; dropping it avoids guessing which later spans belong to it.
1534
- const assignment = sensitiveAssignment.exec(decoded);
1535
- if (assignment)
1536
- return `${assignment[1]}${assignment[2]}${REDACTED}`;
1537
- if (decoded === word || !/[\s;&|()]/.test(decoded))
1538
- return word;
1539
- if (/^\s*[[{]/.test(decoded)) {
1540
- try {
1541
- JSON.parse(decoded);
1542
- return word;
1543
- }
1544
- catch {
1545
- // A shell group begins with '{' too; only valid JSON belongs to the
1546
- // structural JSON pass instead of the nested-command pass.
1547
- }
1548
- }
1549
- const redacted = redactShellSyntax(decoded, depth + 1, inputs, valuesFirst);
1550
- return redacted === decoded ? word : JSON.stringify(redacted);
1551
- });
1552
- return applyCommandRedactions(redactCredentialAssignments(out, inputs));
1553
- }
1554
- /**
1555
- * Redact common secret shapes from a shell command and cap its length so
1556
- * command text never carries credentials or bulk file content off-box.
1557
- *
1558
- * Pure function — no I/O.
1559
- */
90
+ const COMMAND_WITHHELD = '[command withheld]';
1560
91
  export function sanitizeCommand(command) {
1561
- // Shell continuations disappear before tokenization; otherwise a flag's
1562
- // value can be mistaken for the continuation itself and escape redaction.
1563
- let out = redactShellSyntax(command.replace(/\\\r?\n/g, ''));
1564
- if (out.length > MAX_COMMAND_CHARS) {
1565
- out = `${out.slice(0, MAX_COMMAND_CHARS)} [... truncated, ${out.length - MAX_COMMAND_CHARS} characters omitted]`;
1566
- }
1567
- return out;
92
+ // Inspect a bounded prefix only. Never decode quotes, substitutions, escaped
93
+ // words, paths or assignments, and never copy any unrecognized input back.
94
+ const first = /^[ \t\r\n]*([a-z][a-z0-9.+-]{0,31})(?=[ \t\r\n;|&<>]|$)/.exec(command.slice(0, 128))?.[1];
95
+ return first && EXECUTABLES.has(first) ? first : COMMAND_WITHHELD;
1568
96
  }
1569
97
  //# sourceMappingURL=sanitize-command.js.map