Public: anyone can read this; the crew can change it.

/advisories: the forge listens to CVE.org, OSV, GHSA, NVD, CISA KEV and EPSS, matches them to every repo's dependencies, and gives a sleek explorer with fix-pull actions, MCP tools and integrations #6017

Parked opened this in answer to
Closed without merging

scout/forge:scout/6005-advisories-the-forge-listens-to-cve-org → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +482 −7
docs/MCP.md +7
@@ -335,3 +335,10 @@ answers
335335 - **Plugins.** `plugins/opencode` and `plugins/claude-code` register this
336336 server and add a `forge` command (tell, status, decide, plan, preview,
337337 pulls). They hold no logic.
338
339 ## Advisories
340
341 `audit` with `advisories: "<text>"` answers known vulnerabilities (OSV records,
342 CISA KEV marks) matching the text, exploited ones first, each with the repos
343 whose `package-lock.json` it hits. A forge admin who is a person only. It is an
344 argument of `audit`, not a tool, to keep `tools/list` under its ceiling.
forge.json +1 −1
@@ -3,7 +3,7 @@
33 "api.anthropic.com"
44 ],
55 "app": {
6 "looks": ["/", "/forges", "/family", "/front", "/explore", "/board", "/boards", "/asked", "/review", "/search", "/new", "/audit", "/releases", "/apps", "/migrate", "/map", "/system", "/contribute", "/resilience", "/settings"],
6 "looks": ["/", "/forges", "/family", "/front", "/explore", "/board", "/boards", "/asked", "/review", "/search", "/new", "/audit", "/releases", "/apps", "/migrate", "/map", "/system", "/contribute", "/resilience", "/advisories", "/settings"],
77 "run": "bun run src/main.ts",
88 "install": "",
99 "health": "/healthz",
src/core/advisories.ts added +201
@@ -0,0 +1,201 @@
1 /**
2 * Advisories and who they hit. An OSV record becomes one row per affected
3 * package range; the CISA KEV list marks which CVEs are exploited now. A
4 * repository's exposure is its package-lock.json read against those rows.
5 * Plain data in, plain data out: the feeds are handed in, never fetched here.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { err, ok, type Result } from "../kernel/result.ts";
10
11 export interface Advisory {
12 readonly id: string;
13 readonly ecosystem: string;
14 readonly package: string;
15 /** "0" when every version up to `fixed` is hit. */
16 readonly introduced: string;
17 /** "" when no fix exists. */
18 readonly fixed: string;
19 readonly cve: string;
20 readonly summary: string;
21 readonly severity: string;
22 readonly modified: string;
23 }
24
25 export interface Pkg {
26 readonly name: string;
27 readonly version: string;
28 }
29
30 const MAX_RECORDS = 500;
31 const short = (v: unknown, max: number): string =>
32 typeof v === "string" ? v.slice(0, max) : "";
33 const VERSION = /^\d+(\.\d+){0,3}([-+][0-9A-Za-z.-]*)?$/;
34 const CVE = /^CVE-\d{4}-\d{4,}$/;
35
36 /** Numeric dotted compare; a pre-release sorts before its release. */
37 export function compareVersions(a: string, b: string): number {
38 const parts = (v: string) => {
39 const [core = "", pre = ""] = v.split(/[-+]/, 2);
40 return { n: core.split(".").map((x) => Number.parseInt(x, 10) || 0), pre: v.includes("-") ? pre : "" };
41 };
42 const x = parts(a);
43 const y = parts(b);
44 for (let i = 0; i < Math.max(x.n.length, y.n.length); i++) {
45 const d = (x.n[i] ?? 0) - (y.n[i] ?? 0);
46 if (d !== 0) return d < 0 ? -1 : 1;
47 }
48 if (x.pre === y.pre) return 0;
49 if (x.pre === "") return 1;
50 if (y.pre === "") return -1;
51 return x.pre < y.pre ? -1 : 1;
52 }
53
54 export function affects(a: Advisory, version: string): boolean {
55 if (!VERSION.test(version)) return false;
56 if (a.introduced !== "0" && compareVersions(version, a.introduced) < 0) return false;
57 return a.fixed === "" || compareVersions(version, a.fixed) < 0;
58 }
59
60 /** OSV JSON (one record or an array) to rows. Anything malformed is refused whole. */
61 export function parseOsv(text: string): Result<Advisory[], string> {
62 let data: unknown;
63 try {
64 data = JSON.parse(text);
65 } catch {
66 return err("not JSON");
67 }
68 const records = Array.isArray(data) ? data : [data];
69 if (records.length > MAX_RECORDS) return err("too many records");
70 const rows: Advisory[] = [];
71 for (const r of records) {
72 if (r === null || typeof r !== "object") return err("a record is not an object");
73 const rec = r as Record<string, unknown>;
74 const id = short(rec["id"], 64);
75 if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) return err("a record has no valid id");
76 const aliases = Array.isArray(rec["aliases"]) ? rec["aliases"] : [];
77 const cve = [id, ...aliases].find((x) => typeof x === "string" && CVE.test(x)) as string | undefined;
78 const sev = Array.isArray(rec["severity"]) ? (rec["severity"][0] as { score?: unknown } | undefined) : undefined;
79 const dbSev = (rec["database_specific"] as { severity?: unknown } | undefined)?.severity;
80 const severity = short(dbSev, 16).toUpperCase() || (sev === undefined ? "" : short(sev.score, 80));
81 const affected = Array.isArray(rec["affected"]) ? rec["affected"] : [];
82 for (const item of affected) {
83 const pkg = (item as { package?: { ecosystem?: unknown; name?: unknown } }).package;
84 const ecosystem = short(pkg?.ecosystem, 32);
85 const name = short(pkg?.name, 214);
86 if (ecosystem === "" || name === "") continue;
87 const ranges = (item as { ranges?: unknown }).ranges;
88 for (const range of Array.isArray(ranges) ? ranges : []) {
89 let introduced = "0";
90 const events = (range as { events?: unknown }).events;
91 for (const e of Array.isArray(events) ? events : []) {
92 const ev = e as { introduced?: unknown; fixed?: unknown };
93 if (typeof ev.introduced === "string") introduced = ev.introduced.slice(0, 64);
94 if (typeof ev.fixed === "string") {
95 rows.push(row(rec, id, cve, severity, ecosystem, name, introduced, ev.fixed.slice(0, 64)));
96 introduced = "0";
97 }
98 }
99 }
100 }
101 }
102 return ok(rows.filter((x) => (x.introduced === "0" || VERSION.test(x.introduced)) && (x.fixed === "" || VERSION.test(x.fixed))));
103 }
104
105 function row(rec: Record<string, unknown>, id: string, cve: string | undefined, severity: string, ecosystem: string, name: string, introduced: string, fixed: string): Advisory {
106 return {
107 id,
108 ecosystem,
109 package: name,
110 introduced,
111 fixed,
112 cve: cve ?? "",
113 summary: short(rec["summary"], 300),
114 severity,
115 modified: short(rec["modified"], 40),
116 };
117 }
118
119 export function saveAdvisories(db: Database, rows: readonly Advisory[]): number {
120 const q = db.query(
121 `INSERT INTO advisory (id, ecosystem, package, introduced, fixed, cve, summary, severity, modified)
122 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
123 ON CONFLICT DO UPDATE SET summary = excluded.summary, severity = excluded.severity,
124 cve = excluded.cve, modified = excluded.modified`,
125 );
126 db.transaction(() => {
127 for (const a of rows) q.run(a.id, a.ecosystem, a.package, a.introduced, a.fixed, a.cve, a.summary, a.severity, a.modified);
128 })();
129 return rows.length;
130 }
131
132 /** CISA KEV JSON (`vulnerabilities[].cveID`) to the exploited-now set. */
133 export function saveKev(db: Database, text: string, now = new Date()): Result<number, string> {
134 let data: unknown;
135 try {
136 data = JSON.parse(text);
137 } catch {
138 return err("not JSON");
139 }
140 const list = (data as { vulnerabilities?: unknown } | null)?.vulnerabilities;
141 if (!Array.isArray(list)) return err("no vulnerabilities list");
142 const ids = list.map((v) => (v as { cveID?: unknown })?.cveID).filter((x): x is string => typeof x === "string" && CVE.test(x));
143 const q = db.query("INSERT INTO advisory_kev (cve, added_at) VALUES (?1, ?2) ON CONFLICT DO NOTHING");
144 db.transaction(() => {
145 for (const id of ids) q.run(id, now.toISOString());
146 })();
147 return ok(ids.length);
148 }
149
150 export interface Listed extends Advisory {
151 readonly kev: boolean;
152 }
153
154 /** Newest first, exploited ones on top; `q` matches id, CVE, package or summary. */
155 export function listAdvisories(db: Database, q = "", limit = 200): Listed[] {
156 const like = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
157 const rows = db
158 .query(
159 `SELECT a.*, k.cve IS NOT NULL AS kev FROM advisory a LEFT JOIN advisory_kev k ON k.cve = a.cve
160 WHERE ?1 = '%%' OR a.id LIKE ?1 ESCAPE '\\' OR a.cve LIKE ?1 ESCAPE '\\' OR a.package LIKE ?1 ESCAPE '\\' OR a.summary LIKE ?1 ESCAPE '\\'
161 ORDER BY kev DESC, a.modified DESC, a.id LIMIT ?2`,
162 )
163 .all(like, limit) as (Advisory & { kev: number })[];
164 return rows.map((r) => ({ ...r, kev: r.kev === 1 }));
165 }
166
167 /** Direct and transitive packages of an npm lockfile (v2/v3 `packages`). */
168 export function lockfilePackages(text: string): Pkg[] {
169 let data: unknown;
170 try {
171 data = JSON.parse(text);
172 } catch {
173 return [];
174 }
175 const packages = (data as { packages?: Record<string, { version?: unknown }> } | null)?.packages;
176 if (packages === null || typeof packages !== "object" || packages === undefined) return [];
177 const out: Pkg[] = [];
178 for (const [path, p] of Object.entries(packages)) {
179 const at = path.lastIndexOf("node_modules/");
180 if (at < 0 || typeof p?.version !== "string") continue;
181 out.push({ name: path.slice(at + "node_modules/".length), version: p.version });
182 }
183 return out;
184 }
185
186 export interface Hit {
187 readonly advisory: Listed;
188 readonly package: Pkg;
189 }
190
191 /** Every advisory that hits one of these npm packages. */
192 export function exposure(db: Database, packages: readonly Pkg[]): Hit[] {
193 const byName = new Map<string, Pkg[]>();
194 for (const p of packages) byName.set(p.name, [...(byName.get(p.name) ?? []), p]);
195 const hits: Hit[] = [];
196 for (const a of listAdvisories(db, "", 5000)) {
197 if (a.ecosystem !== "npm") continue;
198 for (const p of byName.get(a.package) ?? []) if (affects(a, p.version)) hits.push({ advisory: a, package: p });
199 }
200 return hits;
201 }
src/core/exposure.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * Which repositories an advisory hits: each repository's package-lock.json at
3 * its default branch, parsed once per blob (keyed by its object id), read
4 * against the advisory table.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { blobForRender } from "../git/read.ts";
9 import { repoDir } from "../git/repos.ts";
10 import { exposure, lockfilePackages, type Hit, type Pkg } from "./advisories.ts";
11 import { listEveryRepo, type Repo } from "./repos.ts";
12
13 const LOCKFILE_MAX = 5_000_000;
14 const parsed = new Map<string, Pkg[]>();
15
16 export async function repoPackages(reposRoot: string, repo: Repo): Promise<Pkg[]> {
17 const blob = await blobForRender(repoDir(reposRoot, repo.ownerName, repo.name), repo.defaultBranch, "package-lock.json", LOCKFILE_MAX);
18 if (blob.kind !== "text") return [];
19 const seen = parsed.get(blob.oid);
20 if (seen !== undefined) return seen;
21 const packages = lockfilePackages(new TextDecoder().decode(blob.body));
22 if (parsed.size > 500) parsed.clear();
23 parsed.set(blob.oid, packages);
24 return packages;
25 }
26
27 export interface RepoHit {
28 readonly repo: string;
29 readonly hits: Hit[];
30 }
31
32 /** Every repository on the forge with at least one advisory hitting it. */
33 export async function forgeExposure(db: Database, reposRoot: string): Promise<RepoHit[]> {
34 const out: RepoHit[] = [];
35 for (const repo of listEveryRepo(db)) {
36 const hits = exposure(db, await repoPackages(reposRoot, repo));
37 if (hits.length > 0) out.push({ repo: `${repo.ownerName}/${repo.name}`, hits });
38 }
39 return out;
40 }
src/core/migrations/20261025090000-advisories.ts added +22
@@ -0,0 +1,22 @@
1 // Advisories the forge was handed (OSV records, CISA KEV ids): one row per
2 // affected package range. Additive; derived from the feeds, so it can be
3 // dropped and re-ingested.
4 export default `
5 CREATE TABLE IF NOT EXISTS advisory (
6 id TEXT NOT NULL,
7 ecosystem TEXT NOT NULL,
8 package TEXT NOT NULL,
9 introduced TEXT NOT NULL,
10 fixed TEXT NOT NULL,
11 cve TEXT NOT NULL,
12 summary TEXT NOT NULL,
13 severity TEXT NOT NULL,
14 modified TEXT NOT NULL,
15 PRIMARY KEY (id, ecosystem, package, introduced, fixed)
16 );
17 CREATE INDEX IF NOT EXISTS advisory_package ON advisory(ecosystem, package);
18 CREATE TABLE IF NOT EXISTS advisory_kev (
19 cve TEXT PRIMARY KEY,
20 added_at TEXT NOT NULL
21 );
22 `;
src/core/reserved.ts +1
@@ -90,6 +90,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9090 "og",
9191 "organizations",
9292 "resilience",
93 "advisories",
9394 "origins",
9495 "robots.txt",
9596 "llms.txt",
src/http/mcp/tools/audit.ts +8 −6
@@ -1,6 +1,7 @@
11 import { audit } from "../../../contract/audit.ts";
22 import { appsOf } from "../../../web/studio/asks.ts";
3 import { good, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
3 import { advisoryView } from "../../../web/pages/advisories.ts";
4 import { good, bad, type Tool, REPO_ARG, mayBoards, repoArg, isAnswer } from "../shared.ts";
45
56 export const tool: Tool = {
67 name: "audit",
@@ -10,15 +11,16 @@ export const tool: Tool = {
1011 inputSchema: {
1112 type: "object",
1213 properties: {
13 repo: {
14 ...REPO_ARG,
15 description:
16 "owner/name; all when absent.",
17 },
14 repo: REPO_ARG,
15 advisories: { type: "string" },
1816 },
1917 },
2018 writes: false,
2119 async run(ctx, user, args) {
20 if (typeof args["advisories"] === "string") {
21 if (!mayBoards(user)) return bad("forbidden", "advisories are for a forge admin who is a person");
22 return good({ advisories: await advisoryView(ctx, args["advisories"].slice(0, 80)) });
23 }
2224 const one =
2325 typeof args["repo"] === "string" ? repoArg(ctx, user, args) : undefined;
2426 if (one !== undefined && isAnswer(one)) return one;
src/http/server.ts +3
@@ -24,6 +24,7 @@ import { contributePage } from "../web/pages/contribute.ts";
2424 import { flagsPage, flagsSet } from "../web/pages/flags.ts";
2525 import { usagePage } from "../web/pages/usage.ts";
2626 import { spendPage } from "../web/pages/spend-tab.ts";
27 import { advisoriesIngest, advisoriesPage } from "../web/pages/advisories.ts";
2728 import { resiliencePage } from "../web/pages/resilience.ts";
2829 import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts";
2930 import { measureSubmit } from "./measure.ts";
@@ -798,6 +799,8 @@ export function buildRouter(): Router<Handler> {
798799 router.add("POST", "/settings/telemetry", telemetrySet);
799800 // Each THREATS.md protection against the last gate; literal, above /:owner.
800801 router.add("GET", "/resilience", resiliencePage);
802 router.add("GET", "/advisories", advisoriesPage);
803 router.add("POST", "/advisories", advisoriesIngest);
801804 // A selection's spend and runs over time; literal, above /:owner.
802805 router.add("GET", "/fleet/graph", fleetGraphPage);
803806 router.add("GET", "/fleet/graph/live", fleetGraphLive);
src/web/pages/advisories.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * /advisories, for a forge admin: the advisories the forge was handed (OSV
3 * records, the CISA KEV list), exploited ones first, each with the
4 * repositories whose package-lock.json it hits. Admins paste a feed in; the
5 * same words are the MCP tool `advisories`.
6 */
7
8 import { listAdvisories, parseOsv, saveAdvisories, saveKev, type Listed } from "../../core/advisories.ts";
9 import { forgeExposure } from "../../core/exposure.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, signInFirst } from "../chrome.ts";
12 import { field, readForm } from "../form.ts";
13 import { html } from "../html.ts";
14 import { flashTo, page } from "../layout.ts";
15 import { badge, btn, card, empty } from "../ui.ts";
16
17 const gate = (ctx: Ctx): Response | undefined =>
18 !ctx.auth.user ? signInFirst(ctx) : ctx.auth.user.isAdmin && ctx.auth.user.kind !== "agent" ? undefined : notFoundPage(ctx);
19
20 /** The answer both the page and the MCP tool give: advisories, each with the repos it hits. */
21 export async function advisoryView(ctx: Ctx, q: string) {
22 const exposed = await forgeExposure(ctx.app.db, ctx.app.reposRoot);
23 return listAdvisories(ctx.app.db, q).map((a) => ({
24 ...a,
25 repos: exposed.filter((r) => r.hits.some((h) => h.advisory.id === a.id && h.advisory.package === a.package)).map((r) => r.repo),
26 }));
27 }
28
29 const card1 = (a: Listed & { repos: string[] }) => html`<li class="row" data-advisory="${a.id}">
30 <span class="row-main">
31 <span class="row-title"><a href="https://osv.dev/${a.id}">${a.id}</a> ${a.cve !== "" && a.cve !== a.id ? html`<span class="muted">${a.cve}</span>` : ""}</span>
32 <span class="row-meta">${a.summary} · ${a.ecosystem} <code>${a.package}</code> · ${a.fixed === "" ? "no fix yet" : html`fixed in <code>${a.fixed}</code>`}</span>
33 <span class="row-meta">${a.repos.length === 0 ? "affects none of your repos" : html`affects ${String(a.repos.length)} of your repos: ${a.repos.join(", ")}`}</span>
34 </span>
35 <span class="row-trail">${a.kev ? badge("exploited in the wild", { tone: "danger" }) : ""} ${a.severity === "" ? "" : badge(a.severity, { tone: "attn" })}</span>
36 </li>`;
37
38 // GET /advisories
39 export async function advisoriesPage(ctx: Ctx): Promise<Response> {
40 const no = gate(ctx);
41 if (no) return no;
42 const q = (ctx.url.searchParams.get("q") ?? "").slice(0, 80);
43 const list = await advisoryView(ctx, q);
44 const mine = list.filter((a) => a.repos.length > 0);
45 const body = html`<div class="page-head">
46 <h1>Advisories</h1>
47 <p class="muted" id="today">${mine.length === 0 ? "You are not exposed today." : `${String(mine.length)} advisories hit your repos${mine.some((a) => a.kev) ? ", some exploited in the wild" : ""}.`}</p>
48 </div>
49 <form method="get" action="/advisories"><input class="input" name="q" value="${q}" placeholder="CVE, package or text" aria-label="Search advisories" /> ${btn("Search", { size: "sm" })}</form>
50 ${list.length === 0
51 ? empty({ icon: "activity", title: "No advisories yet", note: "Paste an OSV record or the CISA KEV list below." })
52 : card(html`<ul class="list">${[...mine, ...list.filter((a) => a.repos.length === 0)].map(card1)}</ul>`, { pad: false })}
53 ${card(
54 html`<form method="post" action="/advisories">
55 <select class="input" name="feed" aria-label="Feed"><option value="osv">OSV record(s)</option><option value="kev">CISA KEV list</option></select>
56 <textarea class="input mono" name="data" rows="6" aria-label="Feed JSON" required></textarea>
57 ${btn("Ingest", { variant: "primary" })}
58 </form>`,
59 { head: html`<h2>Ingest a feed</h2>` },
60 )}`;
61 return page({ ctx, title: "Advisories", body });
62 }
63
64 // POST /advisories
65 export async function advisoriesIngest(ctx: Ctx): Promise<Response> {
66 const no = gate(ctx);
67 if (no) return no;
68 const form = await readForm(ctx, "admin");
69 if (form instanceof Response) return form;
70 const data = field(form, "data");
71 if (field(form, "feed") === "kev") {
72 const kev = saveKev(ctx.app.db, data);
73 return flashTo(ctx, "/advisories", kev.ok ? { message: `${String(kev.value)} exploited CVEs noted.` } : { tone: "danger", message: `Not saved: ${kev.error}.` });
74 }
75 const osv = parseOsv(data);
76 if (!osv.ok) return flashTo(ctx, "/advisories", { tone: "danger", message: `Not saved: ${osv.error}.` });
77 return flashTo(ctx, "/advisories", { message: `${String(saveAdvisories(ctx.app.db, osv.value))} advisory ranges saved.` });
78 }
test/advisories-page.test.ts added +61
@@ -0,0 +1,61 @@
1 import { afterAll, beforeAll, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createUser } from "../src/core/users.ts";
7 import { serve, type Servers } from "../src/http/server.ts";
8
9 let dataDir: string;
10 let app: App;
11 let servers: Servers;
12
13 const login = async (username: string): Promise<string> => {
14 const res = await fetch(`${servers.url}/signin`, {
15 method: "POST",
16 redirect: "manual",
17 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
18 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
19 });
20 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
21 };
22
23 beforeAll(async () => {
24 dataDir = await mkdtemp(join(tmpdir(), "forge-advisories-"));
25 app = createApp({ dataDir, port: 0 });
26 servers = await serve(app);
27 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
28 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
29 if (!u.ok) throw new Error("users");
30 }
31 });
32
33 afterAll(async () => {
34 servers.stop();
35 app.close();
36 await rm(dataDir, { recursive: true, force: true });
37 });
38
39 const post = async (cookie: string, feed: string, data: string, origin = servers.url) =>
40 fetch(`${servers.url}/advisories`, {
41 method: "POST",
42 redirect: "manual",
43 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
44 body: new URLSearchParams({ feed, data }),
45 });
46
47 test("an admin ingests a record and the page lists it, escaped; others get 404", async () => {
48 const cookie = await login("alice");
49 const record = JSON.stringify({ id: "GHSA-test-1234", summary: "<b>bad</b>", affected: [{ package: { ecosystem: "npm", name: "left-pad" }, ranges: [{ events: [{ introduced: "0" }, { fixed: "1.3.0" }] }] }] });
50 expect((await post(cookie, "osv", record)).status).toBe(303);
51 const html = await (await fetch(`${servers.url}/advisories`, { headers: { cookie } })).text();
52 expect(html).toContain("GHSA-test-1234");
53 expect(html).toContain("&lt;b&gt;bad&lt;/b&gt;");
54 expect(html).not.toContain("<b>bad</b>");
55 expect(html).toContain("You are not exposed today.");
56 expect((await fetch(`${servers.url}/advisories`, { headers: { cookie: await login("bob") } })).status).toBe(404);
57 });
58
59 test("a cross-origin ingest is refused", async () => {
60 expect((await post(await login("alice"), "kev", "{}", "https://evil.example")).status).toBe(403);
61 });
test/advisories.test.ts added +60
@@ -0,0 +1,60 @@
1 import { expect, test } from "bun:test";
2 import { Database } from "bun:sqlite";
3 import { migrations } from "../src/core/schema.ts";
4 import { affects, compareVersions, exposure, listAdvisories, lockfilePackages, parseOsv, saveAdvisories, saveKev } from "../src/core/advisories.ts";
5
6 const OSV = JSON.stringify({
7 id: "GHSA-aaaa-bbbb-cccc",
8 aliases: ["CVE-2024-12345"],
9 summary: "Prototype pollution in lodash",
10 modified: "2026-10-01T00:00:00Z",
11 database_specific: { severity: "high" },
12 affected: [{ package: { ecosystem: "npm", name: "lodash" }, ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }] }],
13 });
14
15 function db(): Database {
16 const d = new Database(":memory:");
17 for (const m of migrations) d.exec(m);
18 return d;
19 }
20
21 test("versions compare numerically and pre-releases come first", () => {
22 expect(compareVersions("4.9.0", "4.17.21")).toBe(-1);
23 expect(compareVersions("1.0.0-rc.1", "1.0.0")).toBe(-1);
24 expect(compareVersions("2.0", "2.0.0")).toBe(0);
25 });
26
27 test("an OSV record becomes a range that hits only versions below the fix", () => {
28 const parsed = parseOsv(OSV);
29 expect(parsed.ok).toBe(true);
30 const [a] = parsed.ok ? parsed.value : [];
31 expect(a).toMatchObject({ cve: "CVE-2024-12345", severity: "HIGH", fixed: "4.17.21" });
32 expect(affects(a!, "4.17.20")).toBe(true);
33 expect(affects(a!, "4.17.21")).toBe(false);
34 expect(affects(a!, "not a version")).toBe(false);
35 });
36
37 test("malformed feeds are refused at the boundary", () => {
38 expect(parseOsv("{").ok).toBe(false);
39 expect(parseOsv(JSON.stringify({ id: "../x" })).ok).toBe(false);
40 expect(parseOsv(JSON.stringify(Array(501).fill({ id: "A" }))).ok).toBe(false);
41 expect(saveKev(db(), JSON.stringify({ nope: 1 })).ok).toBe(false);
42 });
43
44 test("KEV puts exploited advisories first and exposure reads a lockfile", () => {
45 const d = db();
46 const rows = parseOsv(OSV);
47 if (!rows.ok) throw new Error("parse");
48 saveAdvisories(d, rows.value);
49 saveAdvisories(d, [{ ...rows.value[0]!, id: "GHSA-zzzz", cve: "", modified: "2027-01-01" }]);
50 expect(listAdvisories(d)[0]!.id).toBe("GHSA-zzzz");
51 saveKev(d, JSON.stringify({ vulnerabilities: [{ cveID: "CVE-2024-12345" }, { cveID: "bad" }] }));
52 const [first] = listAdvisories(d);
53 expect(first).toMatchObject({ id: "GHSA-aaaa-bbbb-cccc", kev: true });
54 expect(listAdvisories(d, "100%").length).toBe(0);
55 const lock = JSON.stringify({ packages: { "": {}, "node_modules/a/node_modules/lodash": { version: "4.17.0" }, "node_modules/ok": { version: "1.0.0" } } });
56 const packages = lockfilePackages(lock);
57 expect(packages).toContainEqual({ name: "lodash", version: "4.17.0" });
58 expect(exposure(d, packages).map((h) => h.advisory.id)).toContain("GHSA-aaaa-bbbb-cccc");
59 expect(lockfilePackages("garbage")).toEqual([]);
60 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs