示例工程 52-ci-matrix-smoke

52-ci-matrix-smoke/app/shared/rules.ts

typescript · 5.7 KB

export type Severity = "high" | "medium";

export type Finding = {
  ruleId: string;
  severity: Severity;
  line: number;
  evidence: string;
  message: string;
  hint: string;
};

export type Flags = {
  oses: string[];
  xvfb: boolean;
  cache: boolean;
  frozen: boolean;
  artifact: boolean;
  timeout: boolean;
  permissions: boolean;
  nodePinned: boolean;
  pullRequestTarget: boolean;
  secretEcho: boolean;
};

export type Rule = {
  id: string;
  severity: Severity;
  label: string;
  hint: string;
};

export const RULES: Rule[] = [
  {
    id: "R01",
    severity: "medium",
    label: "矩阵未覆盖 macOS / Windows / Linux",
    hint: "至少列出三种 runner,否则平台差异不会被发现。",
  },
  {
    id: "R02",
    severity: "medium",
    label: "Linux 未使用 xvfb",
    hint: "无头 Linux 跑 E2E 需要 xvfb-run 或 xvfb action。",
  },
  {
    id: "R03",
    severity: "medium",
    label: "未配置 pnpm 缓存",
    hint: "setup-node 的 cache: pnpm 或 pnpm/action-setup。",
  },
  {
    id: "R04",
    severity: "medium",
    label: "安装未使用 frozen lockfile",
    hint: "CI 用 pnpm install --frozen-lockfile,避免依赖漂移。",
  },
  {
    id: "R05",
    severity: "high",
    label: "明文 echo secret",
    hint: "secret 只能注入 env,不能 echo 到日志。",
  },
  {
    id: "R06",
    severity: "medium",
    label: "未上传构建产物",
    hint: "用 actions/upload-artifact 保存安装包与报告。",
  },
  {
    id: "R07",
    severity: "medium",
    label: "job 未设置 timeout-minutes",
    hint: "超时能防止挂死的 job 占满额度。",
  },
  {
    id: "R08",
    severity: "medium",
    label: "未声明 permissions",
    hint: "默认权限过大,至少声明 contents: read。",
  },
  {
    id: "R09",
    severity: "medium",
    label: "Node 版本未固定",
    hint: "写具体版本或 node-version-file,不要用 latest。",
  },
  {
    id: "R10",
    severity: "high",
    label: "pull_request_target 检出 PR 代码",
    hint: "会把 secrets 暴露给 fork PR,改用 pull_request。",
  },
];

export function parseFlags(text: string): Flags {
  const oses = Array.from(
    new Set(
      text
        .split(/\r?\n/)
        .map((line) => /^\s*-\s+(macos|windows|ubuntu)-([\w.]+)/.exec(line))
        .filter((match): match is RegExpExecArray => match !== null)
        .map((match) => `${match[1]}-${match[2]}`),
    ),
  );
  const nodeMatch = /node-version:\s*(.+)/.exec(text);
  const nodeValue = nodeMatch?.[1]?.trim().replace(/["']/g, "") ?? "";
  return {
    oses,
    xvfb: /xvfb-run|xvfb-action/.test(text),
    cache: /cache:\s*pnpm/.test(text) || /pnpm\/action-setup/.test(text),
    frozen: /--frozen-lockfile/.test(text),
    artifact: /actions\/upload-artifact/.test(text),
    timeout: /timeout-minutes:/.test(text),
    permissions: /^permissions:/m.test(text),
    nodePinned: nodeValue !== "" && nodeValue !== "latest",
    pullRequestTarget: /pull_request_target/.test(text),
    secretEcho: /echo[^\n]*secrets\./.test(text),
  };
}

function lineOf(text: string, pattern: RegExp): number {
  const lines = text.split(/\r?\n/);
  const index = lines.findIndex((line) => pattern.test(line));
  return index >= 0 ? index + 1 : 1;
}

function evidenceAt(text: string, line: number): string {
  return (text.split(/\r?\n/)[line - 1] ?? "").trim().slice(0, 120);
}

const CHECKS: Array<{
  rule: Rule;
  line: (text: string, flags: Flags) => number;
  test: (text: string, flags: Flags) => boolean;
}> = [
  {
    rule: RULES[0]!,
    line: (text) => lineOf(text, /os:/),
    test: (_text, flags) => flags.oses.length >= 3,
  },
  {
    rule: RULES[1]!,
    line: (text) => lineOf(text, /runs-on:/),
    test: (_text, flags) =>
      !flags.oses.some((os) => os.startsWith("ubuntu")) || flags.xvfb,
  },
  {
    rule: RULES[2]!,
    line: (text) => lineOf(text, /setup-node|pnpm\/action-setup/),
    test: (_text, flags) => flags.cache,
  },
  {
    rule: RULES[3]!,
    line: (text) => lineOf(text, /pnpm install/),
    test: (_text, flags) => flags.frozen,
  },
  {
    rule: RULES[4]!,
    line: (text) => lineOf(text, /echo[^\n]*secrets\./),
    test: (_text, flags) => !flags.secretEcho,
  },
  {
    rule: RULES[5]!,
    line: () => 1,
    test: (_text, flags) => flags.artifact,
  },
  {
    rule: RULES[6]!,
    line: () => 1,
    test: (_text, flags) => flags.timeout,
  },
  {
    rule: RULES[7]!,
    line: () => 1,
    test: (_text, flags) => flags.permissions,
  },
  {
    rule: RULES[8]!,
    line: (text) => lineOf(text, /node-version:/),
    test: (_text, flags) => flags.nodePinned,
  },
  {
    rule: RULES[9]!,
    line: (text) => lineOf(text, /pull_request_target/),
    test: (text, flags) =>
      !flags.pullRequestTarget || !/actions\/checkout/.test(text),
  },
];

export function scanWorkflow(text: string): {
  findings: Finding[];
  flags: Flags;
} {
  const flags = parseFlags(text);
  const findings: Finding[] = [];
  for (const check of CHECKS) {
    if (check.test(text, flags)) continue;
    const line = check.line(text, flags);
    findings.push({
      ruleId: check.rule.id,
      severity: check.rule.severity,
      line,
      evidence: evidenceAt(text, line),
      message: check.rule.label,
      hint: check.rule.hint,
    });
  }
  return { findings, flags };
}

export function scoreFindings(findings: Finding[]): number {
  const penalty = findings.reduce(
    (sum, finding) => sum + (finding.severity === "high" ? 10 : 5),
    0,
  );
  return Math.max(0, 100 - penalty);
}

export function summarize(findings: Finding[]): {
  high: number;
  medium: number;
  total: number;
} {
  return {
    total: findings.length,
    high: findings.filter((row) => row.severity === "high").length,
    medium: findings.filter((row) => row.severity === "medium").length,
  };
}