Open History to see the last commit
1const FEEDBACK_TEXT_MAX_CHARS = 300;
2
3const REDACTED = "[redacted]";
4
5const escapeRegExp = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
6
7const TOKEN_PREFIX =
8 /\b(?:sk-|sk_live_|pk_live_|rk_live_|gh[pousr]_|github_pat_|glpat-|xox[abprs]-|xapp-|npm_|hf_|AIza|AKIA|ASIA)[A-Za-z0-9_-]{8,}/gu;
9const JWT = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/gu;
10const CREDENTIAL_URL = /\b[a-z][a-z0-9+.-]*:\/\/[^\s/@]+@\S+/giu;
11const EMAIL = /[A-Za-z0-9.!#$%&'*+=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/gu;
12// Where an absolute path starts: `/a/`, `~/`, `file://`, a drive, UNC, or a redacted known prefix.
13const pathStart = (outside: string) =>
14 String.raw`(?:/[^${outside}/]*/|~/|file://|[A-Za-z]:[\\/]|\\\\|\[redacted\][\\/])`;
15// A path inside quotes, spaces included, up to the quote that opened it.
16const QUOTED_PATH = new RegExp(
17 ['"', "'", "\\x60"]
18 .map((quote) => String.raw`${quote}${pathStart(`${quote}\n`)}[^${quote}\n]*${quote}`)
19 .join("|"),
20 "gu",
21);
22// Where an unquoted path starts: `/a/b`, `~/`, `file://`, a drive, `\\host\`, or a redacted known
23// prefix followed by a separator. URLs, `3/10`, `and/or` and one-segment `/compact` do not start one.
24// The first segment cannot hold a space, or `/mcp /compact` would read as a path.
25const PATH_START = [
26 String.raw`\[redacted\](?=://|[\\/])(?:://)?`,
27 String.raw`(?<![\w.:/~-])/[^\s/\\"'\x60<>(){},;:|]+/(?=\S)`,
28 String.raw`(?<![\w~-])~/`,
29 String.raw`\bfile://`,
30 String.raw`\b[A-Za-z]:[\\/]`,
31 String.raw`(?<![\w\\])\\\\[^\s\\/]+\\`,
32].join("|");
33// Where a path ends is unknowable (names hold spaces and `. `), so the rest of its line goes too.
34const PATH = new RegExp(String.raw`(?:${PATH_START})[^\n]*`, "gu");
35// Runs last: a long run that already holds a redaction goes whole, whatever is left of it.
36const LONG_RUN = /(?:[A-Za-z0-9_+=-]|\[redacted\])+/gu;
37
38const entropy = (value: string) => {
39 const counts = new Map<string, number>();
40 for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
41 let bits = 0;
42 for (const count of counts.values()) {
43 const probability = count / value.length;
44 bits -= probability * Math.log2(probability);
45 }
46 return bits;
47};
48
49// Long identifiers such as tool names have few digits; keys, hashes and ids have many.
50const looksRandom = (value: string) =>
51 (value.match(/\d/gu)?.length ?? 0) >= 2 && /[A-Za-z]/u.test(value) && entropy(value) >= 3.5;
52
53/** Replaces the union of what the patterns and values match, so overlaps redact whole. */
54const redactAll = (text: string, patterns: ReadonlyArray<RegExp>) => {
55 const spans = patterns
56 .flatMap((pattern) =>
57 Array.from(text.matchAll(pattern), (match) => [match.index, match.index + match[0].length]),
58 )
59 .sort(([a = 0], [b = 0]) => a - b);
60 let result = "";
61 let at = 0;
62 for (const [start = 0, end = 0] of spans) {
63 if (start < at) {
64 at = Math.max(at, end);
65 continue;
66 }
67 result += `${text.slice(at, start)}${REDACTED}`;
68 at = end;
69 }
70 return result + text.slice(at);
71};
72
73/**
74 * Removes anything shaped like a secret, email address, or URL with credentials,
75 * values the server knows are private to this caller, then file paths, and caps
76 * the result at `maxChars` characters. `cut` says whether any text was dropped
77 * to fit, by the scan window or the cap.
78 */
79export function scrubFeedbackText(
80 text: string,
81 sensitive: ReadonlyArray<string>,
82 maxChars = FEEDBACK_TEXT_MAX_CHARS,
83): { readonly text: string; readonly cut: boolean } {
84 // Bounds the scrubbing cost; the margin keeps a secret that crosses the cap whole.
85 const window = maxChars * 4;
86 let scrubbed = "";
87 let next: string | undefined;
88 let count = 0;
89 for (const char of text) {
90 if (count++ === window) {
91 next = char;
92 break;
93 }
94 scrubbed += char;
95 }
96 // Every pattern below stays within one line, so only a match in the line the window cut can
97 // reach past it. No pattern saw that line's rest, so none of the line is kept.
98 if (next !== undefined && next !== "\n") {
99 scrubbed = `${scrubbed.slice(0, scrubbed.lastIndexOf("\n") + 1)}${REDACTED}`;
100 }
101 // Values under three characters would redact ordinary words. A value that holds line breaks is
102 // matched line by line, every line however short, so no known value can match across lines.
103 const known = [
104 ...new Set(
105 sensitive
106 .map((value) => value.trim())
107 .filter((value) => value.length >= 3)
108 .flatMap((value) => value.split("\n").map((line) => line.trim()))
109 .filter((line) => line.length > 0),
110 ),
111 ].map((value) => new RegExp(`(?<![A-Za-z0-9_])${escapeRegExp(value)}(?![A-Za-z0-9_])`, "gu"));
112 // Secrets and known values on the original text, before either can break the other's match.
113 scrubbed = redactAll(scrubbed, [CREDENTIAL_URL, TOKEN_PREFIX, JWT, EMAIL, ...known])
114 .replaceAll(QUOTED_PATH, (quoted) => `${quoted[0]}${REDACTED}${quoted[0]}`)
115 .replaceAll(PATH, REDACTED)
116 .replaceAll(LONG_RUN, (run) =>
117 run.length >= 32 && (run.includes(REDACTED) || looksRandom(run)) ? REDACTED : run,
118 );
119 const chars = Array.from(scrubbed);
120 return {
121 text: chars.slice(0, maxChars).join(""),
122 cut: next !== undefined || chars.length > maxChars,
123 };
124}
125
126export const scrubFeedback = (
127 text: string,
128 sensitive: ReadonlyArray<string>,
129 maxChars = FEEDBACK_TEXT_MAX_CHARS,
130): string => scrubFeedbackText(text, sensitive, maxChars).text;