示例工程 48-project-security-auditor
48-project-security-auditor/demo-02-rule-score/score.ts
type Severity = "high" | "medium";
type Finding = {
ruleId: string;
severity: Severity;
file: string;
};
function scoreFindings(findings: Finding[]): number {
const penalty = findings.reduce(
(sum, finding) => sum + (finding.severity === "high" ? 8 : 4),
0,
);
return Math.max(0, 100 - penalty);
}
function groupByRule(findings: Finding[]): Map<string, number> {
const map = new Map<string, number>();
for (const finding of findings) {
map.set(finding.ruleId, (map.get(finding.ruleId) ?? 0) + 1);
}
return map;
}
type Gate = {
pass: boolean;
reason: string;
};
function gate(findings: Finding[], minimumScore = 80): Gate {
const high = findings.filter((finding) => finding.severity === "high").length;
if (high > 0) {
return { pass: false, reason: `HIGH_FINDINGS:${high}` };
}
const score = scoreFindings(findings);
if (score < minimumScore) {
return { pass: false, reason: `SCORE_BELOW:${score}` };
}
return { pass: true, reason: `PASS:${score}` };
}
const findings: Finding[] = [
{ ruleId: "R01", severity: "high", file: "a.ts" },
{ ruleId: "R01", severity: "high", file: "b.ts" },
{ ruleId: "R05", severity: "medium", file: "a.ts" },
];
const empty: Finding[] = [];
const mediumOnly: Finding[] = [
{ ruleId: "R05", severity: "medium", file: "a.ts" },
{ ruleId: "R09", severity: "medium", file: "index.html" },
];
const score = scoreFindings(findings);
const grouped = groupByRule(findings);
const blocked = gate(findings);
const pass = gate(empty);
const mediumGate = gate(mediumOnly);
const strict = gate(mediumOnly, 95);
const ok =
score === 80 &&
grouped.get("R01") === 2 &&
grouped.get("R05") === 1 &&
!blocked.pass &&
blocked.reason === "HIGH_FINDINGS:2" &&
pass.pass &&
pass.reason === "PASS:100" &&
mediumGate.pass &&
!strict.pass &&
strict.reason === "SCORE_BELOW:92";
console.log(
JSON.stringify({
evt: "smoke",
ok,
score,
blocked,
pass,
mediumGate,
strict,
grouped: [...grouped.entries()],
}),
);