nofax 0.2.50 → 0.2.51

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.
package/src/protocol.mjs CHANGED
@@ -15,7 +15,9 @@ function normalizeSecretKeyName(key) {
15
15
 
16
16
  // Invisible format marks and blank fillers can split a credential field
17
17
  // name without changing its appearance. Ignore them only for classification.
18
- const comparisonKey = key.replace(/[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/gu, '');
18
+ const comparisonKey = key.normalize('NFKC')
19
+ .replace(/\x1b\[[0-9;]{0,16}m/gu, '')
20
+ .replace(/[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/gu, '');
19
21
 
20
22
  for (let index = 0; index < comparisonKey.length; index += 1) {
21
23
  const char = comparisonKey[index];
@@ -84,6 +86,69 @@ function normalizeUnicodeEscapedSecretKeys(text) {
84
86
  );
85
87
  }
86
88
 
89
+ function redactControlInterruptedSecretKeyText(text) {
90
+ // Inspect only bounded approval text; keep the original key spelling visible.
91
+ if (!/[\x00\x1b]|\\u00(?:00|1b)/i.test(text)) return text;
92
+ let plain = text;
93
+ let wrappers = 0;
94
+ while (wrappers < 3 && plain.startsWith('"') && plain.endsWith('"')) {
95
+ let decoded;
96
+ try { decoded = JSON.parse(plain); } catch { break; }
97
+ if (typeof decoded !== 'string') break;
98
+ plain = decoded;
99
+ wrappers += 1;
100
+ }
101
+
102
+ const hasControl = /[\x00\x1b]/u;
103
+ let changed = false;
104
+ const objectStart = plain.indexOf('{');
105
+ const arrayStart = /^\s*\[/u.test(plain) ? plain.indexOf('[') : -1;
106
+ const jsonStart = objectStart !== -1 ? objectStart : arrayStart;
107
+ const jsonEnd = jsonStart === -1 ? -1 : plain.lastIndexOf(jsonStart === arrayStart ? ']' : '}');
108
+ if (jsonEnd > jsonStart && jsonStart !== -1) {
109
+ let parsed;
110
+ try { parsed = JSON.parse(plain.slice(jsonStart, jsonEnd + 1)); } catch { /* Not a complete JSON segment. */ }
111
+ if (parsed && typeof parsed === 'object') {
112
+ const pending = [parsed];
113
+ while (pending.length > 0) {
114
+ const node = pending.pop();
115
+ for (const [key, child] of Object.entries(node)) {
116
+ if (hasControl.test(key) && isSecretKey(key)) {
117
+ node[key] = '[REDACTED]';
118
+ changed = true;
119
+ } else if (child && typeof child === 'object') {
120
+ pending.push(child);
121
+ }
122
+ }
123
+ }
124
+ if (changed) plain = `${plain.slice(0, jsonStart)}${JSON.stringify(parsed)}${plain.slice(jsonEnd + 1)}`;
125
+ }
126
+ }
127
+
128
+ if (!changed) {
129
+ plain = plain.replace(
130
+ /(?<![A-Za-z0-9_])(["']?)([A-Za-z](?:[A-Za-z0-9_.\/ -]|\x00|\x1b\[[0-9;]{0,16}m){0,96})\1([ \t]*[:=][ \t]*)(?:(["'])(?:\\.|(?!\4)[^\r\n])*\4|[^\s"'`,;&}\]]+)/gu,
131
+ (match, quote, key, separator) => {
132
+ if (!hasControl.test(key) || !isSecretKey(key)) return match;
133
+ changed = true;
134
+ return `${quote}${key}${quote}${separator}[REDACTED]`;
135
+ }
136
+ );
137
+ }
138
+ if (!changed) {
139
+ // A malformed embedded JSON segment cannot be parsed safely. Suppress the
140
+ // entire preview only when an encoded or raw control hides a secret key.
141
+ const unresolvedKeys = /([A-Za-z](?:[A-Za-z0-9_.\/ -]|\x00|\x1b\[[0-9;]{0,16}m|\\+u001b\[[0-9;]{0,16}m|\\+u0000){0,96})(?:\\*["'])?[ \t]*[:=]/giu;
142
+ for (const match of plain.matchAll(unresolvedKeys)) {
143
+ const decoded = match[1].replace(/\\+u001b\[[0-9;]{0,16}m|\\+u0000/giu, '');
144
+ if (decoded !== match[1] && isSecretKey(decoded)) return '[CONTROL_KEY_INPUT_REDACTED]';
145
+ }
146
+ }
147
+ if (!changed) return text;
148
+ for (let index = 0; index < wrappers; index += 1) plain = JSON.stringify(plain);
149
+ return plain;
150
+ }
151
+
87
152
  function redactInvisibleSecretKeyText(text) {
88
153
  const invisible = /[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/u;
89
154
  if (!invisible.test(text)) return text;
@@ -102,8 +167,653 @@ function redactInvisibleSecretKeyText(text) {
102
167
  );
103
168
  }
104
169
 
170
+ function redactCompatibilitySecretKeyText(text) {
171
+ if (!/[^\x00-\x7f]/u.test(text)) return text;
172
+ const isCompatibilitySecret = (key) => key.normalize('NFKC') !== key && isSecretKey(key);
173
+
174
+ // Keep the original suspicious spelling visible while redacting its value.
175
+ // Quoted keys/values may also be nested in once- or twice-serialized JSON.
176
+ // Unicode space separators can make an otherwise recognizable key look benign.
177
+ let redacted = text.replace(
178
+ /(?<![\p{L}\p{N}\p{Pc}])(\\*["'])([\p{L}\p{N}\p{Pc}_.\/ \-\p{Zs}]{1,64})\1([ \t]*[:=][ \t]*)(\\*["'])(?:\\.|(?!(?<!\\)\4)[^\r\n])*?(?<!\\)\4/gu,
179
+ (match, keyQuote, key, separator, valueQuote) => isCompatibilitySecret(key)
180
+ ? `${keyQuote}${key}${keyQuote}${separator}${valueQuote}[REDACTED]${valueQuote}`
181
+ : match
182
+ );
183
+ redacted = redacted.replace(
184
+ /(?<![\p{L}\p{N}\p{Pc}])([\p{L}\p{N}\p{Pc}_.\/ \-\p{Zs}]{1,64})([ \t]*[:=][ \t]*)(\\*["'])(?:\\.|(?!(?<!\\)\3)[^\r\n])*?(?<!\\)\3/gu,
185
+ (match, key, separator, valueQuote) => isCompatibilitySecret(key)
186
+ ? `${key}${separator}${valueQuote}[REDACTED]${valueQuote}`
187
+ : match
188
+ );
189
+ redacted = redacted.replace(
190
+ /(?<![\p{L}\p{N}\p{Pc}])(\\*["']?)([\p{L}\p{N}\p{Pc}_.\/ \-\p{Zs}]{1,64})\1([ \t]*[:=][ \t]*)(?!\\*["'])([^\s"'\x60,;&}\]]+)/gu,
191
+ (match, keyQuote, key, separator) => isCompatibilitySecret(key)
192
+ ? `${keyQuote}${key}${keyQuote}${separator}[REDACTED]`
193
+ : match
194
+ );
195
+ return redacted;
196
+ }
197
+
198
+ function redactYamlCredentialAliases(text) {
199
+ // Approval previews can contain YAML directly or inside nested JSON strings.
200
+ // Split only line separators, retaining their original escaping for display.
201
+ const parts = text.split(/(\r\n|\n|(?:\\{1,4}r)?\\{1,4}n)/g);
202
+ const credentialAnchors = new Set();
203
+ for (let index = 0; index < parts.length; index += 2) {
204
+ // A YAML flow mapping may put credential aliases after '{' or ',' on
205
+ // the same line; serialization can escape its optional key quotes.
206
+ for (const alias of parts[index].matchAll(/(?:^|[,{])\s*(?:-\s*)?((?:\\{0,4})["'])?([A-Za-z][A-Za-z0-9_. -]{0,63})\1\s*:\s*\*([A-Za-z0-9_-]{1,64})(?=\s|$|\\|["',}\]])/g)) {
207
+ if (isSecretKey(alias[2])) credentialAnchors.add(alias[3]);
208
+ }
209
+ }
210
+ if (credentialAnchors.size === 0) return text;
211
+
212
+ let blockIndent = null;
213
+ for (let index = 0; index < parts.length; index += 2) {
214
+ const line = parts[index];
215
+ const indent = line.match(/^[ \t]*/)[0].length;
216
+ if (blockIndent !== null && line.trim() && indent <= blockIndent) blockIndent = null;
217
+ if (blockIndent !== null && indent > blockIndent) {
218
+ if (line.trim()) parts[index] = `${line.slice(0, indent)}[REDACTED]`;
219
+ continue;
220
+ }
221
+
222
+ const anchors = /(^|[ \t:=])&([A-Za-z0-9_-]{1,64})(?=\s|$|\\|["'])/g;
223
+ for (const match of line.matchAll(anchors)) {
224
+ if (!credentialAnchors.has(match[2])) continue;
225
+ const end = match.index + match[0].length;
226
+ const tail = line.slice(end);
227
+ const isBlock = /^\s*(?:[|>][-+0-9]*)?\s*$/.test(tail);
228
+ parts[index] = `${line.slice(0, end)} [REDACTED]`;
229
+ if (isBlock) blockIndent = indent;
230
+ break;
231
+ }
232
+ }
233
+ return parts.join('');
234
+ }
235
+
236
+ function redactShellCredentialBlocks(text) {
237
+ // Decode only whole JSON-string wrappers, not arbitrary shell expressions.
238
+ let plain = text;
239
+ let wrappers = 0;
240
+ while (wrappers < 3 && plain.startsWith('"') && plain.endsWith('"')) {
241
+ let decoded;
242
+ try { decoded = JSON.parse(plain); } catch { break; }
243
+ if (typeof decoded !== 'string') break;
244
+ plain = decoded;
245
+ wrappers += 1;
246
+ }
247
+
248
+ const headers = /^([ \t]*(?:export[ \t]+)?(?:\$env:|\$)?)([A-Za-z][A-Za-z0-9_]{0,63})([ \t]*=[ \t]*)(?:\$\([ \t]*cat[ \t]+<<(-?)(['"]?)([A-Za-z_][A-Za-z0-9_]{0,31})\5[^\r\n]*|@(["']))(?=\r?$)/gm;
249
+ let output = '';
250
+ let cursor = 0;
251
+ let changed = false;
252
+ for (const match of plain.matchAll(headers)) {
253
+ if (match.index < cursor || !isSecretKey(match[2])) continue;
254
+ const headerEnd = match.index + match[0].length;
255
+ const firstBreak = plain.indexOf('\n', headerEnd);
256
+ if (firstBreak === -1) continue;
257
+
258
+ let nextStart = firstBreak + 1;
259
+ let blockEnd = plain.length;
260
+ while (nextStart <= plain.length) {
261
+ const lineEnd = plain.indexOf('\n', nextStart);
262
+ const afterLine = lineEnd === -1 ? plain.length : lineEnd + 1;
263
+ const line = plain.slice(nextStart, lineEnd === -1 ? undefined : lineEnd).replace(/\r$/, '');
264
+ const openingIndent = match[1].match(/^[ \t]*/)[0];
265
+ const psClosing = match[7] + '@';
266
+ const isTerminator = match[7]
267
+ ? line === psClosing || (openingIndent.length > 0 && line === openingIndent + psClosing)
268
+ : (match[4] === '-' ? line.replace(/^\t+/, '') : line) === match[6];
269
+ if (isTerminator) {
270
+ blockEnd = afterLine;
271
+ break;
272
+ }
273
+ if (lineEnd === -1) break;
274
+ nextStart = afterLine;
275
+ }
276
+
277
+ output += plain.slice(cursor, match.index);
278
+ // Quoting the placeholder keeps later assignment matchers from swallowing
279
+ // escaped newlines and the safe fields after a serialized credential block.
280
+ output += match[1] + match[2] + match[3] + '"[REDACTED]"';
281
+ if (blockEnd < plain.length) output += '\n';
282
+ changed = true;
283
+ cursor = blockEnd;
284
+ if (blockEnd === plain.length) break; // An unterminated secret has no safe boundary.
285
+ }
286
+ if (!changed) return text;
287
+ output += plain.slice(cursor);
288
+ for (let index = 0; index < wrappers; index += 1) output = JSON.stringify(output);
289
+ return output;
290
+ }
291
+
292
+ function redactMultilineCredentialAssignments(text) {
293
+ // Only standalone JSON-string wrappers are decoded, so quoted line breaks
294
+ // can be recognized without reinterpreting arbitrary command text.
295
+ let plain = text;
296
+ let wrappers = 0;
297
+ while (wrappers < 3 && plain.startsWith('"') && plain.endsWith('"')) {
298
+ let decoded;
299
+ try { decoded = JSON.parse(plain); } catch { break; }
300
+ if (typeof decoded !== 'string') break;
301
+ plain = decoded;
302
+ wrappers += 1;
303
+ }
304
+
305
+ const assignments = /^([ \t]*(?:export[ \t]+)?)([A-Za-z][A-Za-z0-9_. -]{0,63})([ \t]*=[ \t]*)("""|'''|"|')/gm;
306
+ let cursor = 0;
307
+ let output = '';
308
+ let changed = false;
309
+ for (const match of plain.matchAll(assignments)) {
310
+ if (match.index < cursor || !isSecretKey(match[2])) continue;
311
+ const quote = match[4];
312
+ const valueStart = match.index + match[0].length;
313
+ let closing = -1;
314
+ let searchFrom = valueStart;
315
+ while (searchFrom < plain.length) {
316
+ const candidate = plain.indexOf(quote, searchFrom);
317
+ if (candidate === -1) break;
318
+ let backslashes = 0;
319
+ if (quote[0] === '"') {
320
+ for (let index = candidate - 1; index >= valueStart && plain[index] === '\\'; index -= 1) backslashes += 1;
321
+ }
322
+ if (backslashes % 2 === 0) {
323
+ closing = candidate;
324
+ break;
325
+ }
326
+ searchFrom = candidate + 1;
327
+ }
328
+
329
+ const body = plain.slice(valueStart, closing === -1 ? undefined : closing);
330
+ if (!/[\r\n]/.test(body)) continue;
331
+ output += plain.slice(cursor, match.index);
332
+ output += `${match[1]}${match[2]}${match[3]}${quote}[REDACTED]${quote}`;
333
+ changed = true;
334
+ cursor = closing === -1 ? plain.length : closing + quote.length;
335
+ if (closing === -1) break; // An unterminated secret has no safe sibling boundary.
336
+ }
337
+ if (!changed) return text;
338
+ output += plain.slice(cursor);
339
+ for (let index = 0; index < wrappers; index += 1) output = JSON.stringify(output);
340
+ return output;
341
+ }
342
+
343
+ function redactShellExpressionCredentials(text) {
344
+ // Shell words can concatenate quotes and substitutions after an assignment.
345
+ // Mask the entire bounded word before simpler key=value redactors split it.
346
+ const assignments = /(^|[\s;])((?:export[ \t]+)?(?:\$env:|\$)?)([A-Za-z][A-Za-z0-9_]{0,63})([ \t]*=[ \t]*)/gm;
347
+ let output = '';
348
+ let cursor = 0;
349
+ for (const match of text.matchAll(assignments)) {
350
+ if (match.index < cursor || !isSecretKey(match[3])) continue;
351
+ const valueStart = match.index + match[0].length;
352
+ const frames = [];
353
+ let special = false;
354
+ let index = valueStart;
355
+
356
+ while (index < text.length) {
357
+ const char = text[index];
358
+ const frame = frames[frames.length - 1];
359
+ if (frame === 'single') {
360
+ if (char === "'") frames.pop();
361
+ index += 1;
362
+ continue;
363
+ }
364
+ if (char === '\\') {
365
+ if (!frame) special = true;
366
+ index = Math.min(text.length, index + 2);
367
+ continue;
368
+ }
369
+ if (frame === 'double') {
370
+ if (char === '"') frames.pop();
371
+ else if (char === '$' && text[index + 1] === '(') {
372
+ frames.push('sub');
373
+ index += 2;
374
+ special = true;
375
+ continue;
376
+ } else if (char === '`') frames.push('backtick');
377
+ index += 1;
378
+ continue;
379
+ }
380
+ if (frame === 'backtick' && char === '`') {
381
+ frames.pop();
382
+ index += 1;
383
+ continue;
384
+ }
385
+ if (frame === 'sub' && char === ')') {
386
+ frames.pop();
387
+ index += 1;
388
+ continue;
389
+ }
390
+ if (char === '$' && text[index + 1] === '(') {
391
+ frames.push('sub');
392
+ special = true;
393
+ index += 2;
394
+ continue;
395
+ }
396
+ if (char === "'" || char === '"' || char === '`') {
397
+ frames.push(char === "'" ? 'single' : char === '"' ? 'double' : 'backtick');
398
+ if (!frame && (index > valueStart || char === '`')) special = true;
399
+ index += 1;
400
+ continue;
401
+ }
402
+ if (frame === 'sub' && char === '(') {
403
+ frames.push('sub');
404
+ index += 1;
405
+ continue;
406
+ }
407
+ if (!frame && /[\s,;&|}\]]/.test(char)) break;
408
+ index += 1;
409
+ }
410
+
411
+ if (!special) continue;
412
+ // An unterminated expression has no trustworthy trailing-word boundary.
413
+ if (frames.length > 0) index = text.length;
414
+ output += text.slice(cursor, match.index) + match[0] + '[REDACTED]';
415
+ cursor = index;
416
+ }
417
+ return output + text.slice(cursor);
418
+ }
419
+
420
+ // Split only at unquoted, top-level delimiters. An incomplete quote or group
421
+ // deliberately consumes the remainder instead of guessing where a secret ends.
422
+ function splitPowerShellPreview(text, delimiter) {
423
+ const parts = [];
424
+ const groups = [];
425
+ let quote = '';
426
+ let hereQuote = '';
427
+ let start = 0;
428
+ for (let index = 0; index < text.length; index += 1) {
429
+ const char = text[index];
430
+ if (hereQuote) {
431
+ if (text[index - 1] === '\n' && char === hereQuote && text[index + 1] === '@') {
432
+ hereQuote = '';
433
+ index += 1;
434
+ }
435
+ continue;
436
+ }
437
+ if (char === '\x60' && quote !== "'") {
438
+ index += 1;
439
+ continue;
440
+ }
441
+ if (quote) {
442
+ if (char === quote) {
443
+ if (text[index + 1] === quote) index += 1;
444
+ else quote = '';
445
+ }
446
+ continue;
447
+ }
448
+ if (char === '@' && /["']/.test(text[index + 1] ?? '')
449
+ && (text[index + 2] === '\n' || text.slice(index + 2, index + 4) === '\r\n')) {
450
+ hereQuote = text[index + 1];
451
+ index += 1;
452
+ continue;
453
+ }
454
+ if (char === '"' || char === "'") {
455
+ quote = char;
456
+ continue;
457
+ }
458
+ if ('([{'.includes(char)) groups.push(char);
459
+ else if (')]}'.includes(char) && groups.at(-1) === '([{'.charAt(')]}'.indexOf(char))) groups.pop();
460
+ if (!groups.length && delimiter.test(char)) {
461
+ parts.push({ text: text.slice(start, index), delimiter: char });
462
+ start = index + 1;
463
+ }
464
+ }
465
+ parts.push({ text: text.slice(start), delimiter: '' });
466
+ return parts;
467
+ }
468
+
469
+ function powerShellLiteral(word) {
470
+ if (!word) return '';
471
+ const quote = word[0];
472
+ if ((quote === '"' || quote === "'") && word.endsWith(quote)) {
473
+ return word.slice(1, -1).replace(quote === "'" ? /''/g : /""/g, quote);
474
+ }
475
+ return word;
476
+ }
477
+
478
+ function redactPowerShellCredentialCommands(text, depth = 0) {
479
+ if (!/\b(?:Set-Item|New-Item|Set-Content|Set-Variable)\b/i.test(text)) return text;
480
+ // Inspect string lexemes in complete serialized containers without
481
+ // rebuilding objects (which could discard duplicate keys or context).
482
+ if (depth < 3 && /^\s*[\[{" ]/.test(text)) {
483
+ let parsed;
484
+ try { parsed = JSON.parse(text); } catch { /* Not a complete JSON value. */ }
485
+ if (typeof parsed === 'string') {
486
+ const masked = redactPowerShellCredentialCommands(parsed, depth + 1);
487
+ return masked === parsed ? text : JSON.stringify(masked);
488
+ }
489
+ if (parsed && typeof parsed === 'object') {
490
+ return text.replace(/"(?:\\.|[^"\\])*"/g, lexeme => {
491
+ const decoded = JSON.parse(lexeme);
492
+ const masked = redactPowerShellCredentialCommands(decoded, depth + 1);
493
+ return masked === decoded ? lexeme : JSON.stringify(masked);
494
+ });
495
+ }
496
+ }
497
+ return splitPowerShellPreview(text, /[;|\r\n&]/).map(({ text: segment, delimiter }) => {
498
+ const command = /^([ \t]*)((?:Microsoft\.PowerShell\.(?:Management|Utility)\\)?(Set-Item|New-Item|Set-Content|Set-Variable))(?=[ \t])/i.exec(segment);
499
+ if (!command) return segment + delimiter;
500
+ const variable = command[3].toLowerCase() === 'set-variable';
501
+ const args = splitPowerShellPreview(segment.slice(command[0].length), /[ \t]/)
502
+ .map(part => part.text).filter(Boolean);
503
+ const names = [];
504
+ const paths = [];
505
+ const positional = [];
506
+ let ambiguous = false;
507
+ const switches = /^(?:force|whatif|confirm|verbose|debug|passthru|nonewline|asbytestream)$/i;
508
+ const otherValues = /^(?:value|scope|option|description|erroraction|warningaction|informationaction|errorvariable|warningvariable|informationvariable|outvariable|outbuffer|pipelinevariable|credential|filter|include|exclude|encoding|stream|itemtype|type)$/i;
509
+ for (let index = 0; index < args.length; index += 1) {
510
+ const option = /^-([A-Za-z]+)(?::([\s\S]*))?$/.exec(args[index]);
511
+ if (!option) {
512
+ positional.push(args[index]);
513
+ continue;
514
+ }
515
+ const [, name, attached] = option;
516
+ if (switches.test(name)) continue;
517
+ const isName = /^name$/i.test(name);
518
+ const isPath = /^(?:path|literalpath)$/i.test(name);
519
+ if (!isName && !isPath && !otherValues.test(name)) {
520
+ ambiguous = true;
521
+ continue;
522
+ }
523
+ const arg = attached ?? args[++index];
524
+ if (!arg) ambiguous = true;
525
+ else if (isName) names.push(arg);
526
+ else if (isPath) paths.push(arg);
527
+ }
528
+ const targets = variable ? names : paths;
529
+ if (!targets.length && positional.length) targets.push(positional[0]);
530
+ const literalName = /^[\p{L}\p{N}_.:/\\-]+$/u;
531
+ const sensitiveName = word => {
532
+ const value = powerShellLiteral(word);
533
+ return !literalName.test(value) || isSecretKey(value);
534
+ };
535
+ const sensitivePath = word => {
536
+ const value = powerShellLiteral(word);
537
+ const provider = /^(?:(?:Microsoft\.PowerShell\.Core\\)?(?:environment|variable)::|(?:env|variable):)\\?([\s\S]*)$/i.exec(value);
538
+ if (!provider) {
539
+ // A composed provider expression has no trustworthy literal target.
540
+ return /(?:env|variable|environment):/i.test(value)
541
+ && /[()[\]{},$\x60]/.test(value);
542
+ }
543
+ return provider[1] ? sensitiveName(provider[1]) : names.some(sensitiveName);
544
+ };
545
+ const sensitive = variable
546
+ ? targets.some(sensitiveName)
547
+ : targets.some(sensitivePath);
548
+ // For unknown option layouts, avoid assuming that a credential-like
549
+ // positional argument is harmless. For recognized sensitive operations,
550
+ // omit the arguments rather than attempting to evaluate shell expressions.
551
+ const uncertain = ambiguous && args.some(word => {
552
+ const attached = /^-[A-Za-z]+:([\s\S]+)$/.exec(word)?.[1];
553
+ return variable
554
+ ? isSecretKey(powerShellLiteral(attached ?? word))
555
+ : sensitivePath(attached ?? word);
556
+ });
557
+ return sensitive || uncertain
558
+ ? command[1] + command[2] + ' [REDACTED: credential command arguments]' + delimiter
559
+ : segment + delimiter;
560
+ }).join('');
561
+ }
562
+
563
+ function isSetxExecutable(value) {
564
+ return typeof value === 'string' && /(?:^|[\\/])setx(?:\.exe)?$/i.test(value.replace(/^"|"$/g, ''));
565
+ }
566
+
567
+ function redactSetxArgv(argv) {
568
+ if (!isSetxExecutable(argv[0])) return argv;
569
+ if (argv.length === 1 || (argv.length === 2 && argv[1] === '/?')) return argv;
570
+
571
+ // Only the literal local variable/value form has an unambiguous value
572
+ // position. Omit all arguments for other layouts (including remote options).
573
+ const local = (argv.length === 3 || (argv.length === 4 && typeof argv[3] === 'string' && /^\/m$/i.test(argv[3])))
574
+ && typeof argv[1] === 'string' && /^[\p{L}_][\p{L}\p{N}_.-]*$/u.test(argv[1])
575
+ && typeof argv[2] === 'string';
576
+ if (!local) return [argv[0], '[REDACTED: credential command arguments]'];
577
+ return isSecretKey(argv[1]) ? [argv[0], argv[1], '[REDACTED]', ...argv.slice(3)] : argv;
578
+ }
579
+
580
+ function powerShellProviderCommand(value) {
581
+ if (typeof value !== 'string') return null;
582
+ return /^(?:Microsoft\.PowerShell\.(?:Management|Utility)\\)?(Set-Item|New-Item|Set-Content|Set-Variable)$/i.exec(powerShellLiteral(value))?.[1].toLowerCase() ?? null;
583
+ }
584
+
585
+ function redactPowerShellProviderArgv(argv) {
586
+ const command = powerShellProviderCommand(argv[0]);
587
+ if (!command || argv.length === 1) return argv;
588
+ const omitted = () => [argv[0], '[REDACTED: credential command arguments]'];
589
+ const variable = command === 'set-variable';
590
+ const names = [];
591
+ const paths = [];
592
+ const positional = [];
593
+ let hasValue = false;
594
+ const switches = /^(?:force|whatif|confirm|verbose|debug|passthru|nonewline|asbytestream)$/i;
595
+ const otherValues = /^(?:scope|option|description|erroraction|warningaction|informationaction|errorvariable|warningvariable|informationvariable|outvariable|outbuffer|pipelinevariable|filter|include|exclude|encoding|stream|itemtype|type)$/i;
596
+
597
+ // Inspect typed argument boundaries directly; joining them into shell text
598
+ // would reinterpret literal whitespace, punctuation and nested values.
599
+ for (let index = 1; index < argv.length; index += 1) {
600
+ const word = argv[index];
601
+ if (typeof word !== 'string') return omitted();
602
+ const option = /^-([A-Za-z]+)(?::([\s\S]*))?$/.exec(word);
603
+ if (!option) {
604
+ if (word.startsWith('-')) return omitted();
605
+ positional.push(word);
606
+ continue;
607
+ }
608
+ const [, flag, attached] = option;
609
+ if (switches.test(flag)) {
610
+ if (attached !== undefined && !/^\$(?:true|false)$/i.test(attached)) return omitted();
611
+ continue;
612
+ }
613
+ const isName = /^name$/i.test(flag);
614
+ const isPath = /^(?:path|literalpath)$/i.test(flag);
615
+ const isValue = /^value$/i.test(flag);
616
+ if (!isName && !isPath && !isValue && !otherValues.test(flag)) return omitted();
617
+ const arg = attached ?? argv[++index];
618
+ if (typeof arg !== 'string' || (attached === undefined && arg.startsWith('-'))) return omitted();
619
+ if (isName) names.push(arg);
620
+ else if (isPath) paths.push(arg);
621
+ else if (isValue) {
622
+ if (hasValue) return omitted();
623
+ hasValue = true;
624
+ }
625
+ }
626
+
627
+ const targets = variable ? names : paths;
628
+ if (variable && paths.length) return omitted();
629
+ if (!targets.length && positional.length) targets.push(positional.shift());
630
+ if (targets.length !== 1 || positional.length > (hasValue ? 0 : 1)) return omitted();
631
+ const literalName = /^[\p{L}\p{N}_.:/\\-]+$/u;
632
+ const sensitiveName = word => {
633
+ const name = powerShellLiteral(word);
634
+ return !literalName.test(name) || isSecretKey(name);
635
+ };
636
+ if (variable) return sensitiveName(targets[0]) ? omitted() : argv;
637
+
638
+ const path = powerShellLiteral(targets[0]);
639
+ const provider = /^(?:(?:Microsoft\.PowerShell\.Core\\)?(?:environment|variable)::|(?:env|variable):)\\?([\s\S]*)$/i.exec(path);
640
+ if (provider) {
641
+ if (!provider[1]) {
642
+ if (names.length !== 1 || sensitiveName(names[0])) return omitted();
643
+ } else if (names.length || sensitiveName(provider[1])) return omitted();
644
+ } else if (/[()[\]{},$\x60*?]/.test(path) || !path || names.length) {
645
+ // A composed or unresolved target cannot establish a benign provider.
646
+ return omitted();
647
+ }
648
+ return argv;
649
+ }
650
+
651
+ function interpreterArgvKind(value) {
652
+ if (typeof value !== 'string') return null;
653
+ const exe = value.replace(/^"|"$/g, '').split(/[\\/]/).pop();
654
+ if (/^(?:python(?:\d+(?:\.\d+)?)?w?|pyw?)(?:\.exe)?$/i.test(exe)) return 'python';
655
+ if (/^node(?:js)?(?:\.exe)?$/i.test(exe)) return 'node';
656
+ return null;
657
+ }
658
+
659
+ function interpreterCodeMayExposeCredentials(code, kind) {
660
+ if (code.length > MAX_REDACTION_INPUT) return true;
661
+ // Lexical classification only: never evaluate code or resolve runtime aliases.
662
+ // Keep literal benign targets, but omit ambiguous environment access.
663
+ const tokens = [];
664
+ const lexer = kind === 'python'
665
+ ? /#[^\r\n]*|(?:'''[\s\S]*?'''|"""[\s\S]*?"""|'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*")|\\\r?\n|[\p{L}_][\p{L}\p{N}_]*|[^\s]/gu
666
+ : /\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*"|\x60(?:\\[\s\S]|[^\x60\\])*\x60|[\p{L}_$][\p{L}\p{N}_$]*|[^\s]/gu;
667
+ for (const match of code.matchAll(lexer)) {
668
+ const token = match[0];
669
+ if (kind === 'python' ? token.startsWith('#') || /^\\\r?\n$/.test(token) : token.startsWith('//') || token.startsWith('/*')) continue;
670
+ tokens.push(token);
671
+ }
672
+ // A slash outside a recognized comment/string can begin a JS regex literal.
673
+ // Its contents can mimic a comment and conceal subsequent environment access.
674
+ if (kind === 'node' && tokens.includes('/') && /\b(?:process|env)\b/.test(code)) return true;
675
+ if (kind === 'node' && tokens.some(token => /^(?:require|import|globalThis)$/.test(token))
676
+ && tokens.some(token => token === 'env' || /^(['"])env\1$/.test(token))
677
+ && !tokens.includes('process')) return true;
678
+ const literal = token => {
679
+ if (!token || !/^(['"])[A-Za-z_][A-Za-z0-9_.-]*\1$/.test(token)) return null;
680
+ return token.slice(1, -1);
681
+ };
682
+ const benign = name => name !== null && !isSecretKey(name);
683
+ const bracketKey = index => tokens[index] === '[' && tokens[index + 2] === ']' && benign(literal(tokens[index + 1]));
684
+ const callKey = index => tokens[index] === '(' && [',', ')'].includes(tokens[index + 2]) && benign(literal(tokens[index + 1]));
685
+ for (let i = 0; i < tokens.length; i++) {
686
+ const token = tokens[i];
687
+ const previous = tokens[i - 1];
688
+ const next = tokens[i + 1];
689
+ // Interpolated strings and escaped identifiers are not plain literals.
690
+ if (kind === 'node' && token.startsWith('\x60') && token.includes('$' + '{') && /process|env|\\u/.test(token)) return true;
691
+ if (kind === 'python' && /^(?:f|fr|rf)$/i.test(previous ?? '') && /^['"]/.test(token) && token.includes('{') && /environ|putenv|getattr|os/.test(token)) return true;
692
+ if (token === '\\') return true;
693
+ if (kind === 'python') {
694
+ if (/^(?:environ|environb)$/.test(token)) {
695
+ if (previous !== '.') return true;
696
+ if (bracketKey(i + 1)) continue;
697
+ if (next === '.' && /^(?:get|setdefault|pop)$/.test(tokens[i + 2] ?? '') && callKey(i + 3)) continue;
698
+ return true;
699
+ }
700
+ if (/^(?:putenv|unsetenv|getenv|getenvb)$/.test(token)) {
701
+ if (previous === '.' && callKey(i + 1)) continue;
702
+ return true;
703
+ }
704
+ if (/^(?:getattr|setattr|__import__)$/.test(token) && tokens.includes('os')) return true;
705
+ if (/^(['"])(?:os|environ|environb|putenv)\1$/.test(token) && (previous === '[' || previous === ',' || previous === '(') && tokens.some(t => /^(?:getattr|setattr|__import__|import_module)$/.test(t))) return true;
706
+ } else {
707
+ if (/^(['"])(?:node:)?process\1$/.test(token) && (previous === '[' || previous === 'from' || previous === 'import' || (previous === '(' && tokens[i - 2] === 'require'))) return true;
708
+ if (token !== 'process') continue;
709
+ let end;
710
+ if (next === '.' && tokens[i + 2] === 'env') end = i + 3;
711
+ else if (next === '[' && literal(tokens[i + 2]) === 'env' && tokens[i + 3] === ']') end = i + 4;
712
+ else if (next === '.' && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 2] ?? '')) continue;
713
+ else return true;
714
+ if (bracketKey(end)) continue;
715
+ if (tokens[end] === '.' && /^[A-Za-z_$][\w$]*$/.test(tokens[end + 1] ?? '') && benign(tokens[end + 1])) continue;
716
+ return true;
717
+ }
718
+ }
719
+ return false;
720
+ }
721
+
722
+ function redactInterpreterArgv(argv) {
723
+ const kind = interpreterArgvKind(argv[0]);
724
+ if (!kind) return argv;
725
+ const omitted = () => [argv[0], '[REDACTED: credential command arguments]'];
726
+ for (let i = 1; i < argv.length; i++) {
727
+ const arg = argv[i];
728
+ if (typeof arg !== 'string') return omitted();
729
+ if (arg === '--' || !arg.startsWith('-')) break;
730
+ if (kind === 'python' && /^-[bBdEiIOPqRsSuvVx]*m/.test(arg)) break;
731
+ if (kind === 'node' && /^--run(?:=|$)/.test(arg)) break;
732
+ const optionWithValue = kind === 'python'
733
+ ? /^(?:-[bBdEiIOPqRsSuvVx]*[WX]|--check-hash-based-pycs)$/
734
+ : /^(?:-r|--require|--import|--loader|--experimental-loader|-C|--conditions|--input-type|--experimental-policy|--env-file|--env-file-if-exists|--icu-data-dir|--openssl-config|--title|--watch-path|--redirect-warnings|--diagnostic-dir|--report-directory|--report-filename|--snapshot-blob|--heapsnapshot-signal|--inspect-port)$/;
735
+ if (optionWithValue.test(arg)) {
736
+ if (typeof argv[++i] !== 'string') return omitted();
737
+ continue;
738
+ }
739
+ const match = (kind === 'python' ? /^-[bBdEiIOPqRsSuvVx]*c([\s\S]*)$/ : /^(?:-(?:pe|ep|ie|ip|e|p)([\s\S]*)|--(?:eval|print)(?:=([\s\S]*))?)$/).exec(arg);
740
+ if (!match) continue;
741
+ const attached = match[1] || match[2];
742
+ const code = attached || (arg.endsWith('=') ? '' : argv[++i]);
743
+ if (typeof code !== 'string' || interpreterCodeMayExposeCredentials(code, kind)) return omitted();
744
+ }
745
+ return argv;
746
+ }
747
+
748
+ function redactCommandArgv(argv) {
749
+ if (interpreterArgvKind(argv[0])) return redactInterpreterArgv(argv);
750
+ return isSetxExecutable(argv[0]) ? redactSetxArgv(argv) : redactPowerShellProviderArgv(argv);
751
+ }
752
+
753
+ function redactSerializedCommandArgv(text, depth = 0) {
754
+ if (!/^\s*[\[{" ]/.test(text) || !/setx|Set-Item|New-Item|Set-Content|Set-Variable|python|node|\bpyw?\b|\\u/i.test(text)) return text;
755
+ let parsed;
756
+ try { parsed = JSON.parse(text); } catch { return text; }
757
+ if (depth >= MAX_DEPTH) return '[REDACTED: nested command preview]';
758
+ if (typeof parsed === 'string') {
759
+ const masked = redactSerializedCommandArgv(parsed, depth + 1);
760
+ return masked === parsed ? text : JSON.stringify(masked);
761
+ }
762
+ if (!parsed || typeof parsed !== 'object') return text;
763
+
764
+ // Inspect complete array spans and nested string lexemes, not a rebuilt
765
+ // object: duplicate keys and unrelated review context must remain intact.
766
+ const arrays = [];
767
+ const replacements = [];
768
+ for (const match of text.matchAll(/"(?:\\.|[^"\\])*"|[\[\]]/g)) {
769
+ const token = match[0];
770
+ const start = match.index;
771
+ const end = start + token.length;
772
+ if (token === '[') {
773
+ arrays.push({ start, replacementIndex: replacements.length });
774
+ } else if (token === ']') {
775
+ const frame = arrays.pop();
776
+ const first = /^\s*("(?:\\.|[^"\\])*")/.exec(text.slice(frame.start + 1, start));
777
+ if (!first) continue;
778
+ const executable = JSON.parse(first[1]);
779
+ if (!isSetxExecutable(executable) && !powerShellProviderCommand(executable) && !interpreterArgvKind(executable)) continue;
780
+ const argv = JSON.parse(text.slice(frame.start, end));
781
+ const masked = redactCommandArgv(argv);
782
+ if (masked !== argv) {
783
+ replacements.length = frame.replacementIndex;
784
+ replacements.push({ start: frame.start, end, value: JSON.stringify(masked) });
785
+ }
786
+ } else if (!/^\s*:/.test(text.slice(end))) {
787
+ const decoded = JSON.parse(token);
788
+ const masked = redactSerializedCommandArgv(decoded, depth + 1);
789
+ if (masked !== decoded) replacements.push({ start, end, value: JSON.stringify(masked) });
790
+ }
791
+ }
792
+ let result = '';
793
+ let offset = 0;
794
+ for (const replacement of replacements) {
795
+ result += text.slice(offset, replacement.start) + replacement.value;
796
+ offset = replacement.end;
797
+ }
798
+ return result + text.slice(offset);
799
+ }
800
+
105
801
  function redactSecretText(value) {
106
- let redacted = redactInvisibleSecretKeyText(normalizeUnicodeEscapedSecretKeys(value));
802
+ // Whole JSON-string previews may encode line breaks as backslash-n. Decode
803
+ // only those complete wrappers so key-value matchers cannot eat a safe
804
+ // sibling across an escaped line boundary; preserve the original nesting.
805
+ let wrappers = 0;
806
+ while (wrappers < 3 && value.startsWith('"') && value.endsWith('"')) {
807
+ let decoded;
808
+ try { decoded = JSON.parse(value); } catch { break; }
809
+ if (typeof decoded !== 'string') break;
810
+ value = decoded;
811
+ wrappers += 1;
812
+ }
813
+ value = redactPowerShellCredentialCommands(redactSerializedCommandArgv(value));
814
+ let redacted = redactCompatibilitySecretKeyText(
815
+ redactInvisibleSecretKeyText(normalizeUnicodeEscapedSecretKeys(redactYamlCredentialAliases(redactShellExpressionCredentials(redactMultilineCredentialAssignments(redactShellCredentialBlocks(redactControlInterruptedSecretKeyText(value)))))))
816
+ );
107
817
 
108
818
  redacted = redacted.replace(
109
819
  /-----BEGIN ([A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?)-----[\s\S]*?(?:-----END \1-----|$)/g,
@@ -245,9 +955,17 @@ function redactSecretText(value) {
245
955
  }
246
956
  );
247
957
 
958
+ for (let index = 0; index < wrappers; index += 1) redacted = JSON.stringify(redacted);
248
959
  return redacted;
249
960
  }
250
961
 
962
+ export function redactDiagnosticSecrets(value) {
963
+ // Error strings can originate outside NoFax and reach captured stderr.
964
+ // Never show a prefix of oversized input that might contain a partial token.
965
+ if (value.length > MAX_REDACTION_INPUT) return '[OVERSIZED_INPUT_REDACTED]...[truncated]';
966
+ return redactSecretText(value);
967
+ }
968
+
251
969
  function randomBase64Url(bytes) {
252
970
  return randomBytes(bytes).toString('base64url');
253
971
  }
@@ -324,6 +1042,11 @@ export function redactAndBound(value, options = {}) {
324
1042
  seen.add(value);
325
1043
 
326
1044
  if (Array.isArray(value)) {
1045
+ const maskedArgv = redactCommandArgv(value);
1046
+ if (maskedArgv !== value) {
1047
+ seen.delete(value);
1048
+ return maskedArgv.map(boundString);
1049
+ }
327
1050
  if (value.length === 2 && typeof value[0] === 'string' && isSecretKey(value[0])) {
328
1051
  seen.delete(value);
329
1052
  return [boundString(value[0]), '[REDACTED]'];
@@ -344,11 +1067,11 @@ export function redactAndBound(value, options = {}) {
344
1067
  }
345
1068
 
346
1069
  const entries = Object.entries(value);
347
- const entryName = entries.find(([key, child]) => (
1070
+ const redactEntryValue = entries.some(([key, child]) => (
348
1071
  typeof child === 'string'
349
1072
  && (key.toLowerCase() === 'name' || key.toLowerCase() === 'key' || key.toLowerCase() === 'header')
350
- ))?.[1] ?? null;
351
- const redactEntryValue = entryName !== null && isSecretKey(entryName);
1073
+ && isSecretKey(child)
1074
+ ));
352
1075
 
353
1076
  const out = {};
354
1077
  for (const [key, child] of entries.slice(0, MAX_OBJECT_KEYS)) {