Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions plugins/github-watcher/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,21 @@ copy shared with stewards and linear; edit all three or none):
A `gh` that is not signed in is reported in `error`, not thrown.
- `sourceAdoptable`: every open pull request in the repositories, oldest
first, up to the limit.
- `sourceSetInterest`: the repositories and entities stewards wants to hear
about. Only stewards may call it. Kept in kv, leased on bb-gate-hooks
beside the watches (`repo` leases for repositories, `issue` leases for
entities), and every doorbell for one of them is debounced and rung over
to stewards as `stewardsRing` (`ringStewards`, quiet when stewards is not
installed). A refused lease is logged.
- `sourceDependabotAlerts`: a repository's Dependabot alerts, read with the
token from `GET /repos/{owner}/{repo}/dependabot/alerts` and named the way
the shared contract wants them. Reading alerts needs the token's alert
access (the `security_events` scope, or Dependabot alerts read), more than
read access to the repository; a repo the token cannot read is named in
`errors` and the rest are still returned.
- `sourceSetInterest`: the repositories, entities and Dependabot
repositories stewards wants to hear about. Only stewards may call it. Kept
in kv, leased on bb-gate-hooks beside the watches (`repo` leases for
repositories, `issue` leases for entities, `dependabot_repo` leases for
Dependabot repositories; a `repo` lease does not receive alert doorbells),
and every doorbell for one of them is debounced and rung over to stewards
as `stewardsRing` (`ringStewards`, quiet when stewards is not installed).
A refused lease is logged; a refused `dependabot_repo` is a skip, since a
login that cannot read alerts simply does not get those doorbells.

There are no write tools: a steward comments and reviews with `gh` like
any thread, and signs what it posts as the skill asks, which is how
Expand Down
48 changes: 47 additions & 1 deletion plugins/github-watcher/github.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js";
import { parseDependabotAlerts, parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js";
import { entitySnapshotSchema, SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS } from "./source-contract.js";

describe("refs", () => {
Expand Down Expand Up @@ -262,3 +262,49 @@ describe("repositories", () => {
expect(parseOpenPulls({ data: { viewer: { login: "dev" }, repository: null }, errors: [{ type: "NOT_FOUND", message: "Could not resolve" }] })).toBeNull();
});
});

describe("Dependabot alerts", () => {
const node = (over: Record<string, unknown> = {}) => ({
number: 4,
state: "open",
dependency: { package: { ecosystem: "npm", name: "lodash" }, manifest_path: "package-lock.json" },
security_advisory: { ghsa_id: "GHSA-xxxx-yyyy-zzzz", severity: "high", summary: "Prototype pollution" },
security_vulnerability: { severity: "high", first_patched_version: { identifier: "4.17.21" } },
html_url: "https://github.com/Acme/Widgets/security/dependabot/4",
url: "https://api.github.com/repos/Acme/Widgets/dependabot/alerts/4",
created_at: "2026-10-01T00:00:00Z",
updated_at: "2026-10-02T00:00:00Z",
...over,
});

it("reads a page as the shared contract wants it, with the alert's own number", () => {
expect(parseDependabotAlerts([node()], "Acme/Widgets")).toEqual([
{
id: "Acme/Widgets#4",
repo: "Acme/Widgets",
number: 4,
severity: "high",
package: "lodash",
ecosystem: "npm",
manifestPath: "package-lock.json",
state: "open",
ghsaId: "GHSA-xxxx-yyyy-zzzz",
fixedVersion: "4.17.21",
summary: "Prototype pollution",
url: "https://github.com/Acme/Widgets/security/dependabot/4",
createdAt: "2026-10-01T00:00:00Z",
updatedAt: "2026-10-02T00:00:00Z",
},
]);
});

it("falls back to the vulnerability's severity, and to low for anything unexpected, and tolerates a bare alert", () => {
const bare = parseDependabotAlerts([node({ dependency: null, security_advisory: null, security_vulnerability: { severity: "medium", first_patched_version: null } })], "Acme/Widgets")[0]!;
expect(bare).toMatchObject({ severity: "medium", package: "(unknown)", ecosystem: "unknown", ghsaId: null, fixedVersion: null });
expect(parseDependabotAlerts([node({ security_advisory: { severity: "banana" } })], "Acme/Widgets")[0]!.severity).toBe("low");
});

it("throws on anything that is not an alert list", () => {
expect(() => parseDependabotAlerts({ message: "Not Found" }, "Acme/Widgets")).toThrow(/Dependabot alert list/u);
});
});
58 changes: 57 additions & 1 deletion plugins/github-watcher/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
// function that talks to the network takes its fetch as an argument, and no
// token appears in anything this module returns or throws.
import { z } from "zod";
import { SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS, signedBy, type AdoptableEntity, type EntitySnapshot } from "./source-contract.js";
import { DEPENDABOT_SEVERITIES, SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS, signedBy, type AdoptableEntity, type DependabotAlert, type DependabotSeverity, type EntitySnapshot } from "./source-contract.js";

export const GITHUB_URL = "https://github.com";
export const GITHUB_API_URL = "https://api.github.com";
export const GRAPHQL_PATH = "/graphql";

/** The Dependabot alerts REST path for one repository, and one alert's. */
export const dependabotAlertsPath = (repo: string, state: string, perPage = 100): string => `/repos/${repo}/dependabot/alerts?state=${encodeURIComponent(state)}&per_page=${perPage}`;
export const dependabotAlertPath = (repo: string, number: number): string => `/repos/${repo}/dependabot/alerts/${number}`;

export class GitHubRequestError extends Error {
constructor(
message: string,
Expand Down Expand Up @@ -486,3 +490,55 @@ export function parseOpenPulls(payload: unknown): { viewer: string | null; entit

/** "pull request" or "issue", for prose. */
export const kindName = (kind: Target["kind"]): string => (kind === "pull" ? "pull request" : "issue");

// ---- Dependabot alerts -------------------------------------------------------------

const dependabotAlertNode = z.object({
number: z.number(),
state: z.string(),
dependency: z
.object({
package: z.object({ ecosystem: z.string(), name: z.string() }),
manifest_path: z.string().nullish(),
})
.nullish(),
security_advisory: z.object({ ghsa_id: z.string().nullish(), severity: z.string().nullish(), summary: z.string().nullish() }).nullish(),
security_vulnerability: z.object({ severity: z.string().nullish(), first_patched_version: z.object({ identifier: z.string() }).nullish() }).nullish(),
html_url: z.string().nullish(),
url: z.string().nullish(),
created_at: z.string().nullish(),
updated_at: z.string().nullish(),
});

/** GitHub's severity is one of the four; anything unexpected is read as low rather than thrown away. */
const severityOf = (value: string | null | undefined): DependabotSeverity => {
const s = (value ?? "").toLowerCase();
return (DEPENDABOT_SEVERITIES as readonly string[]).includes(s) ? (s as DependabotSeverity) : "low";
};

/**
* One page of `GET /repos/{owner}/{repo}/dependabot/alerts`, as the shared
* contract wants it. `repo` is the name the caller asked with; GitHub's
* answer does not repeat it. The alert number is the repository's own alert
* numbering, which is what the entity id and fingerprint use.
*/
export function parseDependabotAlerts(payload: unknown, repo: string): DependabotAlert[] {
const parsed = z.array(dependabotAlertNode).safeParse(payload);
if (!parsed.success) throw new Error("GitHub answered with something that is not a Dependabot alert list");
return parsed.data.map((a) => ({
id: `${repo}#${a.number}`,
repo,
number: a.number,
severity: severityOf(a.security_advisory?.severity ?? a.security_vulnerability?.severity),
package: a.dependency?.package.name ?? "(unknown)",
ecosystem: a.dependency?.package.ecosystem ?? "unknown",
manifestPath: a.dependency?.manifest_path ?? null,
state: a.state,
ghsaId: a.security_advisory?.ghsa_id ?? null,
fixedVersion: a.security_vulnerability?.first_patched_version?.identifier ?? null,
summary: a.security_advisory?.summary ?? null,
url: a.html_url ?? null,
createdAt: a.created_at ?? null,
updatedAt: a.updated_at ?? null,
}));
}
12 changes: 8 additions & 4 deletions plugins/github-watcher/hooks-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ describe("the loop", () => {
const logs: string[] = [];
const sweeps: string[] = [];
const doorbells: string[] = [];
const doorbellKinds: string[] = [];
const units: Array<string | null> = [];
const rejected: Rejection[][] = [];
let token = "tok-1";
Expand All @@ -179,7 +180,8 @@ describe("the loop", () => {
return token;
},
watchIds: over.watchIds ?? (() => [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }]),
onDoorbell: (id, unit) => {
onDoorbell: (kind, id, unit) => {
doorbellKinds.push(kind);
doorbells.push(id);
units.push(unit);
},
Expand All @@ -193,7 +195,7 @@ describe("the loop", () => {
});
const controller = new AbortController();
const done = loop.run(controller.signal);
return { loop, logs, sweeps, doorbells, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
return { loop, logs, sweeps, doorbells, doorbellKinds, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
}

it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => {
Expand All @@ -211,13 +213,15 @@ describe("the loop", () => {

hooks.last().send(hooks.doorbell("i-1"));
hooks.last().send(hooks.doorbell("acme/widgets", { kind: "repo" }));
hooks.last().send(hooks.doorbell("acme/widgets#4", { kind: "dependabot_alert" }));
hooks.last().send(hooks.doorbell("i-9", { source: "linear" }));
hooks.last().send("event: doorbell\ndata: not json\n\n");
hooks.last().send(hooks.doorbell("i-2", { action: "remove", unit: "" }));
await tick();
expect(s.doorbells).toEqual(["i-1", "i-2"]);
expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "i-2"]);
expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "issue"]);
// The unit comes along when the service names one.
expect(s.units).toEqual(["acme/widgets", null]);
expect(s.units).toEqual(["acme/widgets", "acme/widgets", null]);
expect(s.logs.join("\n")).not.toContain("tok-1");

s.controller.abort();
Expand Down
20 changes: 14 additions & 6 deletions plugins/github-watcher/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@ export const SUBSCRIBE_BATCH = 100;
/**
* What a lease hangs off. `issue` is one issue or pull request,
* "owner/repo#12"; `repo` is a whole repository, "owner/repo", and receives
* every doorbell whose unit it is. Doorbells themselves are always `issue`.
* every issue doorbell whose unit it is; `dependabot_repo` is a whole
* repository and receives every `dependabot_alert` doorbell in it. Doorbells
* are always `issue` or `dependabot_alert`; the unit lease kinds are
* separate because reading a repository does not entitle a token to its
* alerts (bb-gate/docs/hooks.md).
*/
export type LeaseKind = "issue" | "repo";
export type LeaseKind = "issue" | "repo" | "dependabot_repo";
export type Lease = { kind: LeaseKind; id: string };

// ---- server-sent events ----------------------------------------------------
Expand Down Expand Up @@ -212,8 +216,12 @@ export interface HooksLoopDeps {
refreshToken: () => Promise<string>;
/** Every lease to hold, right now: watched issues, and whatever stewards asked for. */
watchIds: () => Lease[];
/** A doorbell for an issue, with the unit (the repository) it fell in when the service named one: look at it again. */
onDoorbell: (issueId: string, unit: string | null) => void;
/**
* A doorbell: the kind (`issue` or `dependabot_alert`), the entity id, and
* the unit (the repository) when the service named one. The caller decides
* what to look at.
*/
onDoorbell: (kind: string, id: string, unit: string | null) => void;
/** Leases the service refused. The caller decides what that means for each watch. */
onRejected: (rejected: Rejection[]) => Promise<void>;
/** Check every watch against its cursor. */
Expand Down Expand Up @@ -418,10 +426,10 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
// `action` and `at` are for the service's logs; the reaction to any
// doorbell is the same check. The unit is passed on so a repository
// lease can tell which of its doorbells it was rung for.
if (doorbell.success && doorbell.data.source === SOURCE && doorbell.data.kind === "issue") {
if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert")) {
doorbells.push();
const unit = doorbell.data.unit?.trim() ?? "";
deps.onDoorbell(doorbell.data.id, unit === "" ? null : unit);
deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit);
}
}
}
Expand Down
Loading
Loading