示例工程 31-notifications-taskbar

31-notifications-taskbar/app/shared/redact.ts

typescript · 1.6 KB

export type Redaction = {
  title: string;
  body: string;
  hits: string[];
};

function apply(
  text: string,
  pattern: RegExp,
  replacement: string | ((...args: unknown[]) => string),
  label: string,
  hits: Set<string>,
): string {
  return text.replace(pattern, (...args: unknown[]) => {
    hits.add(label);
    return typeof replacement === "function"
      ? replacement(...args)
      : replacement;
  });
}

export function redactText(input: string): {
  text: string;
  hits: string[];
} {
  const hits = new Set<string>();
  let text = input;

  text = apply(
    text,
    /\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b/g,
    "<email>",
    "邮箱",
    hits,
  );
  text = apply(
    text,
    /(\/Users\/|\/home\/|C:\\Users\\)[^\\/\s]+/g,
    (_match: unknown, prefix: unknown) => `${String(prefix)}<user>`,
    "用户路径",
    hits,
  );
  text = apply(text, /\bsk-[A-Za-z0-9_-]{8,}\b/g, "sk-***", "API Key", hits);
  text = apply(
    text,
    /\bBearer\s+[A-Za-z0-9._-]{8,}/gi,
    "Bearer ***",
    "Bearer Token",
    hits,
  );
  text = apply(
    text,
    /([?&](?:token|key|secret|password)=)[^&\s]+/gi,
    (_match: unknown, prefix: unknown) => `${String(prefix)}***`,
    "查询参数密钥",
    hits,
  );
  text = apply(
    text,
    /\b[a-f0-9]{32,}\b/gi,
    "<hex-token>",
    "长十六进制串",
    hits,
  );

  return { text, hits: [...hits] };
}

export function redactPayload(title: string, body: string): Redaction {
  const titleResult = redactText(title);
  const bodyResult = redactText(body);
  return {
    title: titleResult.text,
    body: bodyResult.text,
    hits: [...new Set([...titleResult.hits, ...bodyResult.hits])],
  };
}