feedbackPrivacy.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /** 仅用于用户反馈的排障材料;不得应用到模型请求或认证载荷。 */
  2. const REDACTED = "[REDACTED]";
  3. const sensitiveKey =
  4. /(?:password|passwd|passphrase|secret|token|apikey|accesskey|privatekey|authorization|cookie|credential)/i;
  5. const diagnosticBodyKey =
  6. /^(?:content|messages?|prompt|systemprompt|request|response|body|payload|input|output|toolinput|tooloutput|arguments|args|env|environment|headers|text|completion|result|stdout|stderr|data|params)$/i;
  7. function normalizeKey(key: string): string {
  8. return key.replace(/[^a-z0-9]/gi, "");
  9. }
  10. function shouldRedactKey(key: string, diagnostic: boolean): boolean {
  11. const normalized = normalizeKey(key);
  12. return sensitiveKey.test(normalized) || (diagnostic && diagnosticBodyKey.test(normalized));
  13. }
  14. // 与 JSON 对象共用键名判定;带引号、转义和分隔符的字段不能走另一份精简名单。
  15. function fieldKeys(text: string): Array<{ key: string; quoted: boolean; end: number }> {
  16. const fields = [];
  17. const pattern = /(?:"((?:\\.|[^"\\])*)"|'([^']*)'|([\w.-]+))\s*[:=]\s*/g;
  18. for (const match of text.matchAll(pattern)) {
  19. let key = match[1] ?? match[2] ?? match[3] ?? "";
  20. if (match[1] !== undefined) {
  21. try {
  22. key = JSON.parse(`"${key}"`) as string;
  23. } catch {
  24. // 无法解码时仍按字面键名检查。
  25. }
  26. }
  27. fields.push({ key, quoted: match[3] === undefined, end: match.index + match[0].length });
  28. }
  29. return fields;
  30. }
  31. function shouldRedactUrlPath(url: URL, diagnostic: boolean): boolean {
  32. if (diagnostic || url.username || url.password || url.hostname === "hooks.slack.com") return true;
  33. // 签名下载的对象路径也可能是凭据;必须在删除 query 前判定。
  34. if (
  35. [...url.searchParams.keys()].some(
  36. (key) => shouldRedactKey(key, false) || /^(?:.*signature|sig|code)$/i.test(normalizeKey(key)),
  37. )
  38. )
  39. return true;
  40. try {
  41. return decodeURIComponent(url.pathname)
  42. .split("/")
  43. .some((segment) => {
  44. const normalized = normalizeKey(segment);
  45. return (
  46. sensitiveKey.test(normalized) ||
  47. /^(?:webhook\w*|(?:password)?reset(?:password)?|invites?|invitations?|callback|downloads?|signed|verify|verification|activate|magiclink)$/.test(
  48. normalized.toLowerCase(),
  49. )
  50. );
  51. });
  52. } catch {
  53. // 无法解码的路径不能证明安全,避免编码形式绕过识别。
  54. return true;
  55. }
  56. }
  57. function redactValues(text: string, diagnostic: boolean): string {
  58. let result = text
  59. .replace(/\b((?:Proxy-)?Authorization|Cookie|Set-Cookie)\s*:\s*[^\r\n]+/gi, `$1: ${REDACTED}`)
  60. .replace(
  61. /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g,
  62. REDACTED,
  63. )
  64. .replace(/\bBearer\s+[^\s"'\\,;]+/gi, `Bearer ${REDACTED}`)
  65. .replace(
  66. /([\w.-]+)(\s*[=:]\s*)(?:"(?:\\.|[^"\\])*"|'[^']*'|[^\s,;"'<>]+)/g,
  67. (match, key: string, separator: string) =>
  68. shouldRedactKey(key, false) ? `${key}${separator}${REDACTED}` : match,
  69. )
  70. .replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>\\]+/gi, (raw) => {
  71. try {
  72. const url = new URL(raw);
  73. // URL 凭据并不只在 userinfo/query 中,webhook 和重置链接常将秘密放在路径里。
  74. if (shouldRedactUrlPath(url, diagnostic) && url.pathname && url.pathname !== "/") {
  75. url.pathname = `/${REDACTED}`;
  76. }
  77. url.username = "";
  78. url.password = "";
  79. url.search = "";
  80. url.hash = "";
  81. return url.toString();
  82. } catch {
  83. return REDACTED;
  84. }
  85. })
  86. .replace(/(?:\/(?:Users|home)\/|[a-z]:\\Users\\)[^\s"'<>]+/gi, "[USER_PATH]");
  87. if (diagnostic) {
  88. result = result.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[EMAIL]");
  89. }
  90. return result;
  91. }
  92. function scrubValue(value: unknown, diagnostic: boolean, depth = 0): unknown {
  93. if (depth > 32) return REDACTED;
  94. if (typeof value === "string") {
  95. // 字符串也可能包含日志前缀或多个 JSON 片段,必须走同一条完整脱敏路径。
  96. return redactText(value, diagnostic, depth + 1);
  97. }
  98. if (Array.isArray(value)) return value.map((item) => scrubValue(item, diagnostic, depth + 1));
  99. if (value && typeof value === "object") {
  100. return Object.fromEntries(
  101. Object.entries(value).map(([key, item]) => [
  102. key,
  103. shouldRedactKey(key, diagnostic) ? REDACTED : scrubValue(item, diagnostic, depth + 1),
  104. ]),
  105. );
  106. }
  107. return value;
  108. }
  109. function redactPlainText(text: string, diagnostic: boolean): string {
  110. return redactValues(text, diagnostic)
  111. .split(/\r?\n/)
  112. .map((line) => {
  113. // 非结构化正文的长度和换行边界不可靠;已知敏感字段无法安全解析时舍弃该行。
  114. const unsafe = fieldKeys(line).some(
  115. ({ key, quoted, end }) =>
  116. shouldRedactKey(key, diagnostic) &&
  117. (quoted || diagnostic || !line.slice(end).startsWith(REDACTED)),
  118. );
  119. return unsafe ? REDACTED : line;
  120. })
  121. .join("\n");
  122. }
  123. function jsonFragmentEnd(text: string, start: number): number {
  124. let nesting = 0;
  125. let quoted = false;
  126. let escaped = false;
  127. for (let index = start; index < text.length; index += 1) {
  128. const character = text[index];
  129. if (quoted) {
  130. if (escaped) escaped = false;
  131. else if (character === "\\") escaped = true;
  132. else if (character === '"') quoted = false;
  133. } else if (character === '"') quoted = true;
  134. else if (character === "{" || character === "[") nesting += 1;
  135. else if ((character === "}" || character === "]") && --nesting === 0) return index + 1;
  136. }
  137. return text.length;
  138. }
  139. function redactText(text: string, diagnostic: boolean, depth: number): string {
  140. if (depth > 32) return REDACTED;
  141. try {
  142. const parsed: unknown = JSON.parse(text);
  143. if (parsed && typeof parsed === "object") {
  144. return JSON.stringify(scrubValue(parsed, diagnostic, depth + 1));
  145. }
  146. } catch {
  147. // 混合日志继续逐片段处理,不能只清洗可解析的最后一个 JSON。
  148. }
  149. // 私钥和普通凭据可能跨行或含括号,先按整体清洗,避免片段切分后残留值的后半段。
  150. const source = redactValues(text, diagnostic);
  151. const chunks: string[] = [];
  152. let cursor = 0;
  153. for (let index = 0; index < source.length; index += 1) {
  154. if (source.startsWith(REDACTED, index)) {
  155. index += REDACTED.length - 1;
  156. continue;
  157. }
  158. if (source[index] !== "{" && source[index] !== "[") continue;
  159. const prefix = source.slice(cursor, index);
  160. let end = jsonFragmentEnd(source, index);
  161. const linePrefix = prefix.slice(prefix.lastIndexOf("\n") + 1);
  162. const sensitiveValue = fieldKeys(linePrefix).some(({ key }) =>
  163. shouldRedactKey(key, diagnostic),
  164. );
  165. if (sensitiveValue) {
  166. // 普通字段值可能由文本和对象混合组成;不能只删对象而留下同行尾部。
  167. const lineEnd = source.indexOf("\n", end);
  168. end = lineEnd < 0 ? source.length : lineEnd;
  169. }
  170. const fragment = source.slice(index, end);
  171. chunks.push(redactPlainText(prefix, diagnostic));
  172. try {
  173. chunks.push(
  174. sensitiveValue
  175. ? REDACTED
  176. : JSON.stringify(scrubValue(JSON.parse(fragment), diagnostic, depth + 1)),
  177. );
  178. } catch {
  179. // 多行或截断对象不能只丢弃键名所在行,否则下一行的值仍会泄露。
  180. chunks.push(
  181. sensitiveValue || fieldKeys(fragment).some(({ key }) => shouldRedactKey(key, diagnostic))
  182. ? REDACTED
  183. : redactPlainText(fragment, diagnostic),
  184. );
  185. }
  186. cursor = end;
  187. index = end - 1;
  188. }
  189. chunks.push(redactPlainText(source.slice(cursor), diagnostic));
  190. return chunks.join("");
  191. }
  192. export function redactFeedbackText(text: string, options: { diagnostic?: boolean } = {}): string {
  193. return redactText(text, options.diagnostic === true, 0);
  194. }