nofax 0.2.48 → 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/CHANGELOG.md +13 -0
- package/PRIVACY.md +25 -0
- package/README.md +99 -3
- package/docs/desktop-extension.md +18 -0
- package/docs/remote-mcp.md +55 -0
- package/manifest.json +81 -0
- package/package.json +5 -2
- package/src/adapters/claude.mjs +2 -2
- package/src/adapters/codex.mjs +2 -2
- package/src/adapters/gemini.mjs +3 -3
- package/src/cli.mjs +197 -26
- package/src/config.mjs +174 -15
- package/src/mcp-server.mjs +6 -2
- package/src/mcp-tools.mjs +41 -40
- package/src/ntfy.mjs +387 -53
- package/src/protocol.mjs +852 -24
- package/src/requests.mjs +122 -38
package/src/protocol.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
|
|
3
|
-
const SECRET_KEY = /(?:^|[_-])(token|password|passwd|secret|api[_-]?key|authorization|cookie|credential|private[_-]?key)(?:$|[_-])/i;
|
|
3
|
+
const SECRET_KEY = /(?:^|[_-])(token|password|passwd|secret|api[_-]?key|authorization|cookie|session[_-]?(?:id|key)|credential|private[_-]?key)(?:$|[_-])/i;
|
|
4
4
|
const MAX_STRING = 500;
|
|
5
|
+
const MAX_REDACTION_INPUT = 16 * 1024;
|
|
5
6
|
const MAX_DEPTH = 5;
|
|
6
7
|
const MAX_ARRAY = 20;
|
|
7
8
|
const MAX_OBJECT_KEYS = 30;
|
|
@@ -12,8 +13,14 @@ const TRUNCATION_MARKER = '…[truncated]';
|
|
|
12
13
|
function normalizeSecretKeyName(key) {
|
|
13
14
|
let normalized = '';
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
// Invisible format marks and blank fillers can split a credential field
|
|
17
|
+
// name without changing its appearance. Ignore them only for classification.
|
|
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, '');
|
|
21
|
+
|
|
22
|
+
for (let index = 0; index < comparisonKey.length; index += 1) {
|
|
23
|
+
const char = comparisonKey[index];
|
|
17
24
|
const code = char.charCodeAt(0);
|
|
18
25
|
const isUpper = code >= 65 && code <= 90;
|
|
19
26
|
const isLower = code >= 97 && code <= 122;
|
|
@@ -24,8 +31,8 @@ function normalizeSecretKeyName(key) {
|
|
|
24
31
|
continue;
|
|
25
32
|
}
|
|
26
33
|
|
|
27
|
-
const previousCode = index > 0 ?
|
|
28
|
-
const nextCode = index + 1 <
|
|
34
|
+
const previousCode = index > 0 ? comparisonKey.charCodeAt(index - 1) : -1;
|
|
35
|
+
const nextCode = index + 1 < comparisonKey.length ? comparisonKey.charCodeAt(index + 1) : -1;
|
|
29
36
|
const previousIsUpper = previousCode >= 65 && previousCode <= 90;
|
|
30
37
|
const previousIsLower = previousCode >= 97 && previousCode <= 122;
|
|
31
38
|
const previousIsDigit = previousCode >= 48 && previousCode <= 57;
|
|
@@ -58,12 +65,755 @@ function isSecretKey(key) {
|
|
|
58
65
|
|| lower === 'pass_phrase'
|
|
59
66
|
|| lower.endsWith('_passphrase')
|
|
60
67
|
|| lower.endsWith('_pass_phrase');
|
|
61
|
-
const isSignedUrlSignature = lower === 'x_amz_signature' || lower === 'x_goog_signature';
|
|
62
|
-
|
|
68
|
+
const isSignedUrlSignature = lower === 'sig' || lower === 'x_amz_signature' || lower === 'x_goog_signature';
|
|
69
|
+
// Hosted Git PAT fields are credentials even when the key omits "token".
|
|
70
|
+
const isHostedPat = /(?:^|_)(?:github|gitlab|gh)_pat$/.test(lower);
|
|
71
|
+
return lower === 'auth' || isSignedUrlSignature || isAuthHeader || isAuthHeaderValue || isPassphrase || isHostedPat || SECRET_KEY.test(normalized);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function normalizeUnicodeEscapedSecretKeys(text) {
|
|
75
|
+
// Serialized agent commands can conceal credential field names with JSON
|
|
76
|
+
// Unicode escapes (including extra escaping when JSON is serialized again).
|
|
77
|
+
// Normalize only secret-key names, so the existing quoted-value redaction
|
|
78
|
+
// handles them without decoding or exposing unrelated command content.
|
|
79
|
+
return text.replace(
|
|
80
|
+
/(?<!\\)(\\*["'])((?:[A-Za-z0-9_./ \\-]|\\+u[0-9a-fA-F]{4}){1,64})\1(?=\s*[:=])/g,
|
|
81
|
+
(match, quote, key) => {
|
|
82
|
+
if (!key.includes('\\u')) return match;
|
|
83
|
+
const decoded = key.replace(/\\+u([0-9a-fA-F]{4})/g, (_escape, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
84
|
+
return isSecretKey(decoded) ? `${quote}${decoded}${quote}` : match;
|
|
85
|
+
}
|
|
86
|
+
);
|
|
87
|
+
}
|
|
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
|
+
|
|
152
|
+
function redactInvisibleSecretKeyText(text) {
|
|
153
|
+
const invisible = /[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/u;
|
|
154
|
+
if (!invisible.test(text)) return text;
|
|
155
|
+
|
|
156
|
+
// Classify the original key before escaping its invisible marks for display.
|
|
157
|
+
// Preserve that evidence while hiding the value in quoted and plain assignments.
|
|
158
|
+
return text.replace(
|
|
159
|
+
/(["']?)([A-Za-z][A-Za-z0-9_.\/ \-\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]{0,63})\1([ \t]*[:=][ \t]*)(?:(?:bearer|basic)[ \t]+(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s`,;&}\]]+)|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s`,;&}\]]+)/giu,
|
|
160
|
+
(match, keyQuote, key, separator) => {
|
|
161
|
+
if (!invisible.test(key) || !isSecretKey(key)) return match;
|
|
162
|
+
const prefix = `${keyQuote}${key}${keyQuote}${separator}`;
|
|
163
|
+
const value = match.slice(prefix.length);
|
|
164
|
+
const valueQuote = value[0] === '"' || value[0] === "'" ? value[0] : '';
|
|
165
|
+
return `${prefix}${valueQuote}[REDACTED]${valueQuote}`;
|
|
166
|
+
}
|
|
167
|
+
);
|
|
168
|
+
}
|
|
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);
|
|
63
799
|
}
|
|
64
800
|
|
|
65
801
|
function redactSecretText(value) {
|
|
66
|
-
|
|
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
|
+
);
|
|
67
817
|
|
|
68
818
|
redacted = redacted.replace(
|
|
69
819
|
/-----BEGIN ([A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?)-----[\s\S]*?(?:-----END \1-----|$)/g,
|
|
@@ -71,8 +821,30 @@ function redactSecretText(value) {
|
|
|
71
821
|
);
|
|
72
822
|
|
|
73
823
|
redacted = redacted.replace(
|
|
74
|
-
/\b([A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/)([^\s
|
|
75
|
-
|
|
824
|
+
/\b([A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/)([^\s\/?#"'`<>]+)/g,
|
|
825
|
+
(match, scheme, authority) => {
|
|
826
|
+
const finalAt = authority.lastIndexOf('@');
|
|
827
|
+
if (finalAt === -1) return match;
|
|
828
|
+
|
|
829
|
+
const userinfo = authority.slice(0, finalAt);
|
|
830
|
+
const host = authority.slice(finalAt + 1);
|
|
831
|
+
const passwordAt = userinfo.indexOf(':');
|
|
832
|
+
// Keep established username:password output, but never expose token-only
|
|
833
|
+
// or ambiguous multi-@ userinfo in approval previews.
|
|
834
|
+
if (passwordAt !== -1 && !userinfo.includes('@')) {
|
|
835
|
+
return `${scheme}${userinfo.slice(0, passwordAt)}:[REDACTED]@${host}`;
|
|
836
|
+
}
|
|
837
|
+
return `${scheme}[REDACTED]@${host}`;
|
|
838
|
+
}
|
|
839
|
+
);
|
|
840
|
+
|
|
841
|
+
// Commands may embed a JSON string containing another serialized JSON object,
|
|
842
|
+
// such as \"api_key\":\"value\". Redact escaped credential fields too.
|
|
843
|
+
redacted = redacted.replace(
|
|
844
|
+
/(?<!\\)(\\+")([A-Za-z][A-Za-z0-9_./ \\-\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]{0,63})\1(\s*[:=]\s*)\1[\s\S]*?(?<!\\)\1/g,
|
|
845
|
+
(match, quote, key, separator) => isSecretKey(key)
|
|
846
|
+
? quote + key + quote + separator + quote + '[REDACTED]' + quote
|
|
847
|
+
: match
|
|
76
848
|
);
|
|
77
849
|
|
|
78
850
|
redacted = redacted.replace(
|
|
@@ -111,28 +883,41 @@ function redactSecretText(value) {
|
|
|
111
883
|
);
|
|
112
884
|
|
|
113
885
|
redacted = redacted.replace(
|
|
114
|
-
/([?&#])([A-Za-z][A-Za-z0-9._-]{0,63})=([^&\s"'`,;]+)/g,
|
|
115
|
-
(match, prefix, key) =>
|
|
116
|
-
|
|
117
|
-
|
|
886
|
+
/([?&#])((?:[A-Za-z]|%[0-9a-fA-F]{2})(?:[A-Za-z0-9._+-]|%[0-9a-fA-F]{2}){0,63})=([^&\s"'`,;]+)/g,
|
|
887
|
+
(match, prefix, key) => {
|
|
888
|
+
let decodedKey;
|
|
889
|
+
// Form-encoded query keys interpret '+' as a space (e.g. api+key).
|
|
890
|
+
try { decodedKey = decodeURIComponent(key.replace(/\+/g, ' ')); } catch { return match; }
|
|
891
|
+
return isSecretKey(decodedKey) || decodedKey.toLowerCase() === 'signature'
|
|
892
|
+
? `${prefix}${key}=[REDACTED]`
|
|
893
|
+
: match;
|
|
894
|
+
}
|
|
118
895
|
);
|
|
119
896
|
|
|
120
897
|
redacted = redacted.replace(
|
|
121
|
-
/(["'])([A-Za-z][A-Za-z0-9_
|
|
898
|
+
/(["'])([A-Za-z][A-Za-z0-9_./ \\-]{0,63})\1(\s*[:=]\s*)(["'])(?:\\.|(?!\4)[^\r\n])*\4/g,
|
|
122
899
|
(match, keyQuote, key, separator, valueQuote) => isSecretKey(key)
|
|
123
900
|
? `${keyQuote}${key}${keyQuote}${separator}${valueQuote}[REDACTED]${valueQuote}`
|
|
124
901
|
: match
|
|
125
902
|
);
|
|
126
903
|
|
|
127
904
|
redacted = redacted.replace(
|
|
128
|
-
/([A-Za-z][A-Za-z0-9_-]{0,63})(\s*[:=]\s*)(["'])(.*?)\3/g,
|
|
905
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)(\s*[:=]\s*)(["'])(.*?)\3/g,
|
|
129
906
|
(match, key, separator, valueQuote) => isSecretKey(key)
|
|
130
907
|
? `${key}${separator}${valueQuote}[REDACTED]${valueQuote}`
|
|
131
908
|
: match
|
|
132
909
|
);
|
|
133
910
|
|
|
911
|
+
// Preserve the displayed auth scheme, but never leave its credential behind.
|
|
912
|
+
redacted = redacted.replace(
|
|
913
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)([ \t]*[:=][ \t]*)(bearer|basic)([ \t]+)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s"'`,;&]+)/gi,
|
|
914
|
+
(match, key, separator, scheme, gap) => isSecretKey(key)
|
|
915
|
+
? `${key}${separator}${scheme}${gap}[REDACTED]`
|
|
916
|
+
: match
|
|
917
|
+
);
|
|
918
|
+
|
|
134
919
|
redacted = redacted.replace(
|
|
135
|
-
/([A-Za-z][A-Za-z0-9_-]{0,63})(\s*[:=]\s*)([^\s"'`,;&]+)/g,
|
|
920
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)(\s*[:=]\s*)([^\s"'`,;&]+)/g,
|
|
136
921
|
(match, key, separator, rawValue) => {
|
|
137
922
|
if (!isSecretKey(key)) return match;
|
|
138
923
|
if (/^\[REDACTED\][}\])]*$/.test(rawValue)) return match;
|
|
@@ -156,7 +941,7 @@ function redactSecretText(value) {
|
|
|
156
941
|
);
|
|
157
942
|
|
|
158
943
|
redacted = redacted.replace(
|
|
159
|
-
/--([A-Za-z][A-Za-z0-9_
|
|
944
|
+
/--([A-Za-z][A-Za-z0-9_./-]{0,63})(\s+)(["'](?:.*?)["']|[^\s"'`,;&]+)/g,
|
|
160
945
|
(match, key, separator) => isSecretKey(key)
|
|
161
946
|
? `--${key}${separator}[REDACTED]`
|
|
162
947
|
: match
|
|
@@ -170,9 +955,17 @@ function redactSecretText(value) {
|
|
|
170
955
|
}
|
|
171
956
|
);
|
|
172
957
|
|
|
958
|
+
for (let index = 0; index < wrappers; index += 1) redacted = JSON.stringify(redacted);
|
|
173
959
|
return redacted;
|
|
174
960
|
}
|
|
175
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
|
+
|
|
176
969
|
function randomBase64Url(bytes) {
|
|
177
970
|
return randomBytes(bytes).toString('base64url');
|
|
178
971
|
}
|
|
@@ -182,6 +975,26 @@ function safeSliceEnd(text, end) {
|
|
|
182
975
|
return previous >= 0xD800 && previous <= 0xDBFF ? end - 1 : end;
|
|
183
976
|
}
|
|
184
977
|
|
|
978
|
+
function escapeDisplayControls(text) {
|
|
979
|
+
// Human-facing summaries must reveal hidden direction and zero-width marks,
|
|
980
|
+
// while retaining ordinary line breaks and emoji joiners.
|
|
981
|
+
const characters = [...text];
|
|
982
|
+
return characters.map((character, index) => {
|
|
983
|
+
if (character === '\u200c' || character === '\u200d') {
|
|
984
|
+
let before = index - 1;
|
|
985
|
+
while (before >= 0 && /[\ufe0e\ufe0f\p{Emoji_Modifier}]/u.test(characters[before])) before--;
|
|
986
|
+
if (character === '\u200d' &&
|
|
987
|
+
/\p{Extended_Pictographic}/u.test(characters[before] ?? '') &&
|
|
988
|
+
/\p{Extended_Pictographic}/u.test(characters[index + 1] ?? '')) {
|
|
989
|
+
return character;
|
|
990
|
+
}
|
|
991
|
+
return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
|
|
992
|
+
}
|
|
993
|
+
return character.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b\u200e-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\u2800\u3164\uffa0\ufeff]/gu,
|
|
994
|
+
(control) => `\\u${control.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
995
|
+
}).join('');
|
|
996
|
+
}
|
|
997
|
+
|
|
185
998
|
function boundResponseText(value) {
|
|
186
999
|
if (value.length <= MAX_RESPONSE_TEXT) return value;
|
|
187
1000
|
const end = safeSliceEnd(value, MAX_RESPONSE_TEXT - TRUNCATION_MARKER.length);
|
|
@@ -201,7 +1014,10 @@ export function createPhoneTopic() {
|
|
|
201
1014
|
}
|
|
202
1015
|
|
|
203
1016
|
function boundString(value) {
|
|
204
|
-
|
|
1017
|
+
// Do not run complex credential-redaction patterns on arbitrarily large
|
|
1018
|
+
// untrusted commands. Showing a prefix could disclose a partial secret.
|
|
1019
|
+
if (value.length > MAX_REDACTION_INPUT) return '[OVERSIZED_INPUT_REDACTED]';
|
|
1020
|
+
const redacted = escapeDisplayControls(redactSecretText(value));
|
|
205
1021
|
const truncated = value.length > MAX_STRING || redacted.length > MAX_STRING;
|
|
206
1022
|
const bounded = redacted.length <= MAX_STRING
|
|
207
1023
|
? redacted
|
|
@@ -222,10 +1038,17 @@ export function redactAndBound(value, options = {}) {
|
|
|
222
1038
|
if (typeof value !== 'object') return boundString(String(value));
|
|
223
1039
|
|
|
224
1040
|
if (seen.has(value)) return '[CIRCULAR]';
|
|
1041
|
+
// Track only the active recursion path; shared sibling references are not cycles.
|
|
225
1042
|
seen.add(value);
|
|
226
1043
|
|
|
227
1044
|
if (Array.isArray(value)) {
|
|
1045
|
+
const maskedArgv = redactCommandArgv(value);
|
|
1046
|
+
if (maskedArgv !== value) {
|
|
1047
|
+
seen.delete(value);
|
|
1048
|
+
return maskedArgv.map(boundString);
|
|
1049
|
+
}
|
|
228
1050
|
if (value.length === 2 && typeof value[0] === 'string' && isSecretKey(value[0])) {
|
|
1051
|
+
seen.delete(value);
|
|
229
1052
|
return [boundString(value[0]), '[REDACTED]'];
|
|
230
1053
|
}
|
|
231
1054
|
const bounded = value.slice(0, MAX_ARRAY);
|
|
@@ -239,28 +1062,32 @@ export function redactAndBound(value, options = {}) {
|
|
|
239
1062
|
: redactAndBound(item, { seen, depth: depth + 1 })
|
|
240
1063
|
));
|
|
241
1064
|
if (value.length > MAX_ARRAY) out.push(TRUNCATION_MARKER);
|
|
1065
|
+
seen.delete(value);
|
|
242
1066
|
return out;
|
|
243
1067
|
}
|
|
244
1068
|
|
|
245
1069
|
const entries = Object.entries(value);
|
|
246
|
-
const
|
|
1070
|
+
const redactEntryValue = entries.some(([key, child]) => (
|
|
247
1071
|
typeof child === 'string'
|
|
248
1072
|
&& (key.toLowerCase() === 'name' || key.toLowerCase() === 'key' || key.toLowerCase() === 'header')
|
|
249
|
-
|
|
250
|
-
|
|
1073
|
+
&& isSecretKey(child)
|
|
1074
|
+
));
|
|
251
1075
|
|
|
252
1076
|
const out = {};
|
|
253
1077
|
for (const [key, child] of entries.slice(0, MAX_OBJECT_KEYS)) {
|
|
254
1078
|
const normalizedKey = key.toLowerCase();
|
|
255
|
-
|
|
1079
|
+
const bounded = isSecretKey(key) || (redactEntryValue && (normalizedKey === 'value' || normalizedKey === 'values'))
|
|
256
1080
|
? '[REDACTED]'
|
|
257
1081
|
: redactAndBound(child, { seen, depth: depth + 1 });
|
|
1082
|
+
// Assignment to '__proto__' changes the prototype instead of retaining approval context.
|
|
1083
|
+
Object.defineProperty(out, key, { value: bounded, enumerable: true, writable: true, configurable: true });
|
|
258
1084
|
}
|
|
259
1085
|
if (entries.length > MAX_OBJECT_KEYS) {
|
|
260
1086
|
let markerKey = TRUNCATION_MARKER;
|
|
261
1087
|
while (Object.hasOwn(out, markerKey)) markerKey += '*';
|
|
262
1088
|
out[markerKey] = true;
|
|
263
1089
|
}
|
|
1090
|
+
seen.delete(value);
|
|
264
1091
|
return out;
|
|
265
1092
|
}
|
|
266
1093
|
|
|
@@ -307,7 +1134,8 @@ export function parseResponseMessage(message, { requestId, allowed, kind }) {
|
|
|
307
1134
|
if (kind === 'choice') return { decision: 'refine' };
|
|
308
1135
|
if (typeof parsed.text !== 'string') return null;
|
|
309
1136
|
const text = parsed.text.trim();
|
|
310
|
-
|
|
1137
|
+
// JSON permits escaped lone surrogates; never silently rewrite a human refinement.
|
|
1138
|
+
if (!text || !text.isWellFormed()) return null;
|
|
311
1139
|
return { decision: 'refine', text: boundResponseText(text) };
|
|
312
1140
|
}
|
|
313
1141
|
|