From ee4b4794925d56c1fa211b08afffa8536c838b88 Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 00:03:31 +0000 Subject: [PATCH 1/6] Use a GUID for GitHub App webhook delivery IDs App webhook deliveries used Date.now() as X-GitHub-Delivery, so two deliveries in the same millisecond shared an ID. Receivers that deduplicate by delivery ID, as GitHub recommends, then dropped the second event. GitHub sends a GUID; the emulator now does too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../__tests__/webhook-installation.test.ts | 38 +++++++++++++++++++ packages/@emulators/github/src/index.ts | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/@emulators/github/src/__tests__/webhook-installation.test.ts b/packages/@emulators/github/src/__tests__/webhook-installation.test.ts index cbfb36b9e..8bd8c90f7 100644 --- a/packages/@emulators/github/src/__tests__/webhook-installation.test.ts +++ b/packages/@emulators/github/src/__tests__/webhook-installation.test.ts @@ -1014,6 +1014,44 @@ describe("app webhook_url delivery", () => { expect(body.installation.id).toBe(55); }); + it("gives each app webhook delivery its own GUID, even within the same millisecond", async () => { + vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000); + try { + const { app } = createTestApp({ + users: [{ login: "octocat" }], + repos: [{ owner: "octocat", name: "hello-world" }], + apps: [ + { + app_id: 550, + slug: "delivery-app", + name: "Delivery App", + private_key: "fake-key", + events: ["issues"], + webhook_url: "https://delivery.example/webhook", + installations: [{ installation_id: 57, account: "octocat", repository_selection: "all" }], + }, + ], + }); + + for (const title of ["First delivery", "Second delivery"]) { + await app.request(`${base}/repos/octocat/hello-world/issues`, { + method: "POST", + headers: { ...authHeaders(), "Content-Type": "application/json" }, + body: JSON.stringify({ title }), + }); + } + + const ids = mockFetch.mock.calls + .filter((c) => c[0] === "https://delivery.example/webhook") + .map((c) => ((c[1] as RequestInit).headers as Record)["X-GitHub-Delivery"]); + expect(ids).toHaveLength(2); + for (const id of ids) expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); + expect(new Set(ids).size).toBe(2); + } finally { + vi.restoreAllMocks(); + } + }); + it("signs app webhook delivery with webhook_secret", async () => { const secret = "app-webhook-secret"; const { app } = createTestApp({ diff --git a/packages/@emulators/github/src/index.ts b/packages/@emulators/github/src/index.ts index 61630f9aa..31df2151a 100644 --- a/packages/@emulators/github/src/index.ts +++ b/packages/@emulators/github/src/index.ts @@ -631,7 +631,7 @@ async function deliverToAppWebhookUrls( const headers: Record = { "Content-Type": "application/json", "X-GitHub-Event": event, - "X-GitHub-Delivery": String(Date.now()), + "X-GitHub-Delivery": crypto.randomUUID(), }; if (ghApp.webhook_secret) { const hmac = createHmac("sha256", ghApp.webhook_secret).update(body).digest("hex"); From 5f3fef45b3057e8b3c68ca0dcdade3b6c9a4d34f Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 00:08:43 +0000 Subject: [PATCH 2/6] feat(github): organization issue types - Seeded organizations get GitHub's default Task, Bug and Feature types unless their seed lists issue_types ([] seeds none). - GET /orgs/{org}/issue-types for organization members and installations on the organization; GET /repos/{owner}/{repo}/issue-types lists the owning organization's types (none for personal repositories). - Issue create and update accept `type`: an enabled type name (matched without regard to case) or null to clear; unknown, disabled or personal-repository types return 422 before any write. - Issue objects carry `type`. The typed/untyped issue webhooks are not included yet. Closes #4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../github/src/__tests__/issue-types.test.ts | 128 ++++++++++++++++++ packages/@emulators/github/src/entities.ts | 12 ++ packages/@emulators/github/src/helpers.ts | 8 ++ packages/@emulators/github/src/index.ts | 6 + packages/@emulators/github/src/issue-types.ts | 71 ++++++++++ .../github/src/routes/issue-types.ts | 31 +++++ .../@emulators/github/src/routes/issues.ts | 6 + packages/@emulators/github/src/store.ts | 3 + packages/github-emulator/README.md | 2 + 9 files changed, 267 insertions(+) create mode 100644 packages/@emulators/github/src/__tests__/issue-types.test.ts create mode 100644 packages/@emulators/github/src/issue-types.ts create mode 100644 packages/@emulators/github/src/routes/issue-types.ts diff --git a/packages/@emulators/github/src/__tests__/issue-types.test.ts b/packages/@emulators/github/src/__tests__/issue-types.test.ts new file mode 100644 index 000000000..785f4442a --- /dev/null +++ b/packages/@emulators/github/src/__tests__/issue-types.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + Hono, + Store, + WebhookDispatcher, + authMiddleware, + createApiErrorHandler, + createErrorHandler, + type TokenMap, +} from "@emulators/core"; +import { githubPlugin, seedFromConfig } from "../index.js"; + +const base = "http://localhost:4000"; + +type IssueType = { id: number; name: string; is_enabled: boolean; description: string | null }; +type Issue = { number: number; type: IssueType | null }; + +function createTestApp() { + const store = new Store(); + const tokenMap: TokenMap = new Map([ + ["admin-token", { login: "admin", id: 1, scopes: ["repo", "user", "read:org"] }], + ["outsider-token", { login: "outsider", id: 2, scopes: ["repo", "user", "read:org"] }], + ]); + const app = new Hono(); + app.onError(createApiErrorHandler()); + app.use("*", createErrorHandler()); + app.use("*", authMiddleware(tokenMap)); + githubPlugin.register(app as any, store, new WebhookDispatcher(), base, tokenMap); + githubPlugin.seed?.(store, base); + seedFromConfig(store, base, { + users: [{ login: "admin" }, { login: "outsider" }], + orgs: [ + { login: "acme", members: [{ login: "admin", role: "admin" }] }, + { + login: "custom", + members: [{ login: "admin", role: "admin" }], + issue_types: [ + { name: "Epic", description: "A large body of work" }, + { name: "Chore", is_enabled: false }, + ], + }, + { login: "untyped", members: [{ login: "admin", role: "admin" }], issue_types: [] }, + ], + repos: [ + { owner: "acme", name: "widget" }, + { owner: "custom", name: "tool" }, + { owner: "admin", name: "personal" }, + ], + }); + return app; +} + +describe("GitHub issue types", () => { + let app: Hono; + const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => { + const headers: Record = {}; + const token = init.token === undefined ? "admin-token" : init.token; + if (token) headers.Authorization = `Bearer ${token}`; + if (init.body !== undefined) headers["Content-Type"] = "application/json"; + return app.request(`${base}${path}`, { + method: init.method ?? "GET", + headers, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }); + }; + const names = async (res: Response) => ((await res.json()) as IssueType[]).map((type) => type.name); + + beforeEach(() => { + app = createTestApp(); + }); + + it("seeds GitHub's default types, custom types or none per organization", async () => { + expect(await names(await call("/orgs/acme/issue-types"))).toEqual(["Task", "Bug", "Feature"]); + const custom = (await (await call("/orgs/custom/issue-types")).json()) as IssueType[]; + expect(custom.map((type) => [type.name, type.is_enabled, type.description])).toEqual([ + ["Epic", true, "A large body of work"], + ["Chore", false, null], + ]); + expect(await names(await call("/orgs/untyped/issue-types"))).toEqual([]); + }); + + it("lists a repository's types from its organization, and none for a personal repository", async () => { + expect(await names(await call("/repos/acme/widget/issue-types"))).toEqual(["Task", "Bug", "Feature"]); + expect(await names(await call("/repos/admin/personal/issue-types"))).toEqual([]); + }); + + it("hides an organization's types from non-members", async () => { + expect((await call("/orgs/acme/issue-types", { token: "outsider-token" })).status).toBe(404); + expect((await call("/orgs/acme/issue-types", { token: null })).status).toBe(404); + expect((await call("/orgs/missing/issue-types")).status).toBe(404); + }); + + it("sets, changes and clears an issue's type by name", async () => { + const created = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed", type: "bug" } }); + expect(created.status).toBe(201); + const issue = (await created.json()) as Issue; + expect(issue.type?.name).toBe("Bug"); + + const changed = await call(`/repos/acme/widget/issues/${issue.number}`, { + method: "PATCH", + body: { type: "Feature" }, + }); + expect(((await changed.json()) as Issue).type?.name).toBe("Feature"); + const untouched = await call(`/repos/acme/widget/issues/${issue.number}`, { + method: "PATCH", + body: { title: "Renamed" }, + }); + expect(((await untouched.json()) as Issue).type?.name).toBe("Feature"); + const cleared = await call(`/repos/acme/widget/issues/${issue.number}`, { method: "PATCH", body: { type: null } }); + expect(((await cleared.json()) as Issue).type).toBeNull(); + + const plain = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Untyped" } }); + expect(((await plain.json()) as Issue).type).toBeNull(); + }); + + it("rejects an unknown, disabled or personal-repository type with 422 and writes nothing", async () => { + const before = ((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length; + for (const type of ["Bug", "Chore", ""]) { + const res = await call("/repos/custom/tool/issues", { method: "POST", body: { title: "Rejected", type } }); + expect(res.status, type).toBe(422); + } + expect(((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length).toBe(before); + expect( + (await call("/repos/admin/personal/issues", { method: "POST", body: { title: "Personal", type: "Task" } })) + .status, + ).toBe(422); + }); +}); diff --git a/packages/@emulators/github/src/entities.ts b/packages/@emulators/github/src/entities.ts index dc5d091b7..7d760f08c 100644 --- a/packages/@emulators/github/src/entities.ts +++ b/packages/@emulators/github/src/entities.ts @@ -131,6 +131,8 @@ export interface GitHubIssue extends Entity { closed_at: string | null; closed_by_id: number | null; is_pull_request: boolean; + /** Organization issue type; absent on rows written before issue types existed. */ + type_id?: number | null; } export interface GitHubPullRequest extends Entity { @@ -237,6 +239,16 @@ export interface GitHubIssueEvent extends Entity { rename: { from: string; to: string } | null; } +/** An organization's issue type (Task, Bug, Feature by default). */ +export interface GitHubIssueType extends Entity { + node_id: string; + org_id: number; + name: string; + description: string | null; + color: string | null; + is_enabled: boolean; +} + /** A directed "blocked by" edge: `blocked_issue_id` cannot proceed until `blocking_issue_id` is done. */ export interface GitHubIssueDependency extends Entity { blocked_issue_id: number; diff --git a/packages/@emulators/github/src/helpers.ts b/packages/@emulators/github/src/helpers.ts index 352f2e6d7..cd2189df8 100644 --- a/packages/@emulators/github/src/helpers.ts +++ b/packages/@emulators/github/src/helpers.ts @@ -374,6 +374,7 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str assignee: assignees[0] ?? null, assignees, milestone: milestone ? formatMilestone(milestone, repo, store, baseUrl) : null, + type: issueTypeJson(issue, store), comments: issue.comments, created_at: issue.created_at, updated_at: issue.updated_at, @@ -388,6 +389,13 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str }; } +function issueTypeJson(issue: GitHubIssue, store: GitHubStore) { + const type = issue.type_id ? store.issueTypes.get(issue.type_id) : undefined; + if (!type) return null; + const { id, node_id, name, description, color, created_at, updated_at, is_enabled } = type; + return { id, node_id, name, description, color, created_at, updated_at, is_enabled }; +} + /** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */ function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) { const blockers = store.issueDependencies diff --git a/packages/@emulators/github/src/index.ts b/packages/@emulators/github/src/index.ts index 31df2151a..ce7322ed5 100644 --- a/packages/@emulators/github/src/index.ts +++ b/packages/@emulators/github/src/index.ts @@ -19,6 +19,8 @@ import { usersRoutes } from "./routes/users.js"; import { reposRoutes } from "./routes/repos.js"; import { issuesRoutes } from "./routes/issues.js"; import { issueDependenciesRoutes } from "./routes/issue-dependencies.js"; +import { issueTypesRoutes } from "./routes/issue-types.js"; +import { seedIssueTypes, type IssueTypeSeed } from "./issue-types.js"; import { pullsRoutes } from "./routes/pulls.js"; import { commentsRoutes } from "./routes/comments.js"; import { reviewsRoutes } from "./routes/reviews.js"; @@ -67,6 +69,8 @@ export interface GitHubSeedConfig { login: string; role?: "member" | "admin"; }>; + /** Defaults to GitHub's Task, Bug and Feature; an empty list seeds none. */ + issue_types?: IssueTypeSeed[]; }>; tokens?: Record; repos?: Array<{ @@ -359,6 +363,7 @@ export function seedFromConfig(store: Store, baseUrl: string, config: GitHubSeed billing_email: null, }); gh.orgs.update(org.id, { node_id: generateNodeId("Org", org.id) }); + seedIssueTypes(gh, gh.orgs.get(org.id)!, o.issue_types); } } @@ -702,6 +707,7 @@ export const githubPlugin: ServicePlugin = { reposRoutes(ctx); issuesRoutes(ctx); issueDependenciesRoutes(ctx); + issueTypesRoutes(ctx); pullsRoutes(ctx); commentsRoutes(ctx); reviewsRoutes(ctx); diff --git a/packages/@emulators/github/src/issue-types.ts b/packages/@emulators/github/src/issue-types.ts new file mode 100644 index 000000000..6c647b114 --- /dev/null +++ b/packages/@emulators/github/src/issue-types.ts @@ -0,0 +1,71 @@ +import { ApiError } from "@emulators/core"; +import type { GitHubIssueType, GitHubOrg, GitHubRepo } from "./entities.js"; +import type { GitHubStore } from "./store.js"; +import { generateNodeId } from "./helpers.js"; + +export interface IssueTypeSeed { + name: string; + description?: string | null; + color?: string | null; + is_enabled?: boolean; +} + +/** The issue types GitHub creates for a new organization. */ +export const DEFAULT_ISSUE_TYPES: IssueTypeSeed[] = [ + { name: "Task", description: "A specific piece of work", color: "yellow" }, + { name: "Bug", description: "An unexpected problem or behavior", color: "red" }, + { name: "Feature", description: "A request, idea, or new functionality", color: "blue" }, +]; + +export function seedIssueTypes(gh: GitHubStore, org: GitHubOrg, types: IssueTypeSeed[] = DEFAULT_ISSUE_TYPES): void { + for (const type of types) { + if (!type.name?.trim()) throw new Error(`Issue type for ${org.login} needs a name`); + if (orgIssueTypes(gh, org.id).some((existing) => existing.name.toLowerCase() === type.name.toLowerCase())) continue; + const row = gh.issueTypes.insert({ + node_id: "", + org_id: org.id, + name: type.name.trim(), + description: type.description ?? null, + color: type.color ?? null, + is_enabled: type.is_enabled ?? true, + } as Omit); + gh.issueTypes.update(row.id, { node_id: generateNodeId("IssueType", row.id) }); + } +} + +export function orgIssueTypes(gh: GitHubStore, orgId: number): GitHubIssueType[] { + return gh.issueTypes.findBy("org_id", orgId); +} + +/** Issue types belong to organizations; a personal repository has none. */ +export function repoIssueTypes(gh: GitHubStore, repo: GitHubRepo): GitHubIssueType[] { + return repo.owner_type === "Organization" ? orgIssueTypes(gh, repo.owner_id) : []; +} + +export function formatIssueType(type: GitHubIssueType) { + return { + id: type.id, + node_id: type.node_id, + name: type.name, + description: type.description, + color: type.color, + created_at: type.created_at, + updated_at: type.updated_at, + is_enabled: type.is_enabled, + }; +} + +/** + * Resolves the `type` field of an issue write. `undefined` leaves the type unchanged, `null` clears it, + * and a name selects an enabled type of the repository's organization, matched without regard to case. + */ +export function resolveIssueTypeId(gh: GitHubStore, repo: GitHubRepo, raw: unknown): number | null | undefined { + if (raw === undefined) return undefined; + if (raw === null) return null; + if (typeof raw !== "string" || !raw.trim()) throw new ApiError(422, "Validation failed"); + const type = repoIssueTypes(gh, repo).find( + (candidate) => candidate.is_enabled && candidate.name.toLowerCase() === raw.trim().toLowerCase(), + ); + if (!type) throw new ApiError(422, "Validation failed"); + return type.id; +} diff --git a/packages/@emulators/github/src/routes/issue-types.ts b/packages/@emulators/github/src/routes/issue-types.ts new file mode 100644 index 000000000..848bc9813 --- /dev/null +++ b/packages/@emulators/github/src/routes/issue-types.ts @@ -0,0 +1,31 @@ +import type { RouteContext } from "@emulators/core"; +import { getGitHubStore } from "../store.js"; +import { assertRepoPermission, getActorUser, isOrgMember, notFoundResponse } from "../route-helpers.js"; +import { lookupRepo } from "../helpers.js"; +import { formatIssueType, orgIssueTypes, repoIssueTypes } from "../issue-types.js"; + +export function issueTypesRoutes({ app, store }: RouteContext): void { + const gh = getGitHubStore(store); + + // Organization members and installations on the organization may read its issue types. + app.get("/orgs/:org/issue-types", (c) => { + const login = c.req.param("org")!.toLowerCase(); + const org = gh.orgs.all().find((candidate) => candidate.login.toLowerCase() === login); + if (!org) throw notFoundResponse(); + const authUser = c.get("authUser"); + const installation = authUser?.installation; + const user = authUser && !installation ? getActorUser(gh, authUser) : undefined; + const allowed = installation + ? installation.accountType === "Organization" && installation.accountId === org.id + : !!user && isOrgMember(gh, user.id, org.id); + if (!allowed) throw notFoundResponse(); + return c.json(orgIssueTypes(gh, org.id).map(formatIssueType)); + }); + + app.get("/repos/:owner/:repo/issue-types", (c) => { + const repo = lookupRepo(gh, c.req.param("owner")!, c.req.param("repo")!); + if (!repo) throw notFoundResponse(); + assertRepoPermission(gh, c.get("authUser"), repo, ["issues", "metadata"]); + return c.json(repoIssueTypes(gh, repo).map(formatIssueType)); + }); +} diff --git a/packages/@emulators/github/src/routes/issues.ts b/packages/@emulators/github/src/routes/issues.ts index 21e94f842..335630ce4 100644 --- a/packages/@emulators/github/src/routes/issues.ts +++ b/packages/@emulators/github/src/routes/issues.ts @@ -2,6 +2,7 @@ import type { Context } from "@emulators/core"; import type { RouteContext } from "@emulators/core"; import { ApiError, parseJsonBody, parsePagination, setLinkHeader } from "@emulators/core"; import { getGitHubStore } from "../store.js"; +import { resolveIssueTypeId } from "../issue-types.js"; import { assertIssueWrite, assertRepoPermission, notFoundResponse, ownerLoginOf } from "../route-helpers.js"; import type { GitHubStore } from "../store.js"; import type { GitHubIssue, GitHubIssueEvent, GitHubLabel, GitHubRepo, GitHubUser } from "../entities.js"; @@ -311,6 +312,8 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v milestoneId = ms.id; } + const typeId = resolveIssueTypeId(gh, repo, body.type) ?? null; + const num = getNextIssueNumber(gh, repo.id); const row = gh.issues.insert({ node_id: "", @@ -330,6 +333,7 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v closed_at: null, closed_by_id: null, is_pull_request: false, + type_id: typeId, } as Omit); gh.issues.update(row.id, { node_id: generateNodeId("Issue", row.id) }); const issue = gh.issues.get(row.id)!; @@ -438,6 +442,8 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v } } + if ("type" in body) patch.type_id = resolveIssueTypeId(gh, repo, body.type) ?? null; + const prevLabelIds = new Set(issue.label_ids); const prevAssigneeIds = new Set(issue.assignee_ids); const prevMilestoneId = issue.milestone_id; diff --git a/packages/@emulators/github/src/store.ts b/packages/@emulators/github/src/store.ts index fbbcd43df..844fd8a63 100644 --- a/packages/@emulators/github/src/store.ts +++ b/packages/@emulators/github/src/store.ts @@ -15,6 +15,7 @@ import type { GitHubReview, GitHubIssueEvent, GitHubIssueDependency, + GitHubIssueType, GitHubBranch, GitHubBranchProtection, GitHubRef, @@ -55,6 +56,7 @@ export interface GitHubStore { reviews: Collection; issueEvents: Collection; issueDependencies: Collection; + issueTypes: Collection; branches: Collection; branchProtections: Collection; refs: Collection; @@ -99,6 +101,7 @@ export function getGitHubStore(store: Store): GitHubStore { "blocked_issue_id", "blocking_issue_id", ]), + issueTypes: store.collection("github.issue_types", ["org_id"]), branches: store.collection("github.branches", ["repo_id"]), branchProtections: store.collection("github.branch_protections", ["repo_id"]), refs: store.collection("github.refs", ["repo_id"]), diff --git a/packages/github-emulator/README.md b/packages/github-emulator/README.md index 86f535f42..e499bb9aa 100644 --- a/packages/github-emulator/README.md +++ b/packages/github-emulator/README.md @@ -22,6 +22,8 @@ Tokens are checked as GitHub checks them: a bearer token that the seed did not c Issue dependencies follow GitHub's REST API: `GET`/`POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by`, `DELETE .../dependencies/blocked_by/{issue_id}` and `GET .../dependencies/blocking`, across repositories, with GitHub's 50-relationship limit. Issue objects carry `issue_dependencies_summary`. +Organizations have issue types: GitHub's Task, Bug and Feature unless a seed org lists `issue_types` (`[]` for none). `GET /orgs/{org}/issue-types` and `GET /repos/{owner}/{repo}/issue-types` list them, issue writes accept `type` (an enabled type's name, or `null` to clear), and issue objects carry `type`. + The default seed is synthetic. Configure `seed` and `tokens` for your tests. The instance provides `url`, `generatedSecrets`, `reset()`, and `close()`; tokens are resolved to seeded user IDs. Reset clears dynamic credentials and replays fixture state while preserving generated App keys. After installing the tarball, `npx github-emulator --help` lists CLI options. It listens on loopback port 4200 by default and accepts `--port`, `--host`, `--base-url`, and `--config` for JSON configuration. From 2ca62e2b2e68e8513b8cf5f81cd49e51cbdc802f Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 00:36:15 +0000 Subject: [PATCH 3/6] fix(github): review fixes for dependencies, delivery IDs and issue types Dependencies (#12): - issue_dependencies_summary counts only related issues every reader of the issue can see (same repository or public), so the shared issue payload no longer reveals blockers in private repositories. - DELETE needs write on the blocked issue only, so an edge whose far end became unreadable can still be removed; a malformed id returns 400. - One findIssueForRepo helper for issue and dependency routes. Delivery IDs (#13): import randomUUID by name. Issue types (#14): formatIssueType lives in helpers.ts beside the issue serializer; a null issue_types seed means the defaults; the type resolver returns number | null. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../src/__tests__/issue-dependencies.test.ts | 14 ++++++++ packages/@emulators/github/src/helpers.ts | 35 +++++++++++++++---- packages/@emulators/github/src/index.ts | 4 +-- packages/@emulators/github/src/issue-types.ts | 27 ++++---------- .../github/src/routes/issue-dependencies.ts | 14 +++++--- .../@emulators/github/src/routes/issues.ts | 9 ++--- 6 files changed, 64 insertions(+), 39 deletions(-) diff --git a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts index a647c21e4..7067fac66 100644 --- a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts +++ b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts @@ -158,6 +158,20 @@ describe("GitHub issue dependencies", () => { token: "hubot-token", }); expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]); + // The shared issue payload never counts a blocker some readers of this issue cannot see. + const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue) + .issue_dependencies_summary; + expect(summary).toEqual({ blocked_by: 0, blocking: 0, total_blocked_by: 0, total_blocking: 0 }); + }); + + it("removes an edge whose far end the caller can no longer read, and rejects a malformed id", async () => { + const blocked = await createIssue("octocat/alpha"); + const hidden = await createIssue("hubot/secret", "hubot-token"); + getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id }); + const path = `/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`; + expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(400); + expect((await call(`${path}/${hidden.id}`, { method: "DELETE" })).status).toBe(200); + expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toEqual([]); }); it("requires authentication to add an edge", async () => { diff --git a/packages/@emulators/github/src/helpers.ts b/packages/@emulators/github/src/helpers.ts index cd2189df8..b6adb19d6 100644 --- a/packages/@emulators/github/src/helpers.ts +++ b/packages/@emulators/github/src/helpers.ts @@ -4,6 +4,7 @@ import type { GitHubOrg, GitHubRepo, GitHubIssue, + GitHubIssueType, GitHubPullRequest, GitHubLabel, GitHubMilestone, @@ -389,23 +390,45 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str }; } +export function formatIssueType(type: GitHubIssueType) { + return { + id: type.id, + node_id: type.node_id, + name: type.name, + description: type.description, + color: type.color, + created_at: type.created_at, + updated_at: type.updated_at, + is_enabled: type.is_enabled, + }; +} + function issueTypeJson(issue: GitHubIssue, store: GitHubStore) { const type = issue.type_id ? store.issueTypes.get(issue.type_id) : undefined; - if (!type) return null; - const { id, node_id, name, description, color, created_at, updated_at, is_enabled } = type; - return { id, node_id, name, description, color, created_at, updated_at, is_enabled }; + return type ? formatIssueType(type) : null; +} + +export function findIssueForRepo(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined { + return gh.issues.findBy("repo_id", repoId).find((i) => i.number === issueNumber && !i.is_pull_request); } -/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */ +/** + * Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. + * The issue payload is shared by every reader, so only related issues every reader of this issue can + * see are counted: those in the same repository or in a public one. The dependency list endpoints, + * which know the caller, return the rest to callers who may see them. + */ function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) { + const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue => + !!other && (other.repo_id === issue.repo_id || store.repos.get(other.repo_id)?.visibility === "public"); const blockers = store.issueDependencies .findBy("blocked_issue_id", issue.id) .map((edge) => store.issues.get(edge.blocking_issue_id)) - .filter((other): other is GitHubIssue => !!other); + .filter(visibleToAllReaders); const blocked = store.issueDependencies .findBy("blocking_issue_id", issue.id) .map((edge) => store.issues.get(edge.blocked_issue_id)) - .filter((other): other is GitHubIssue => !!other); + .filter(visibleToAllReaders); return { blocked_by: blockers.filter((other) => other.state === "open").length, blocking: blocked.filter((other) => other.state === "open").length, diff --git a/packages/@emulators/github/src/index.ts b/packages/@emulators/github/src/index.ts index ce7322ed5..f4e4a049a 100644 --- a/packages/@emulators/github/src/index.ts +++ b/packages/@emulators/github/src/index.ts @@ -1,4 +1,4 @@ -import { createHmac, generateKeyPair } from "crypto"; +import { createHmac, generateKeyPair, randomUUID } from "crypto"; import { constantTimeSecretEqual } from "@emulators/core"; import type { Context, Hono } from "@emulators/core"; import type { @@ -636,7 +636,7 @@ async function deliverToAppWebhookUrls( const headers: Record = { "Content-Type": "application/json", "X-GitHub-Event": event, - "X-GitHub-Delivery": crypto.randomUUID(), + "X-GitHub-Delivery": randomUUID(), }; if (ghApp.webhook_secret) { const hmac = createHmac("sha256", ghApp.webhook_secret).update(body).digest("hex"); diff --git a/packages/@emulators/github/src/issue-types.ts b/packages/@emulators/github/src/issue-types.ts index 6c647b114..f22fc0bb5 100644 --- a/packages/@emulators/github/src/issue-types.ts +++ b/packages/@emulators/github/src/issue-types.ts @@ -2,6 +2,7 @@ import { ApiError } from "@emulators/core"; import type { GitHubIssueType, GitHubOrg, GitHubRepo } from "./entities.js"; import type { GitHubStore } from "./store.js"; import { generateNodeId } from "./helpers.js"; +export { formatIssueType } from "./helpers.js"; export interface IssueTypeSeed { name: string; @@ -17,8 +18,8 @@ export const DEFAULT_ISSUE_TYPES: IssueTypeSeed[] = [ { name: "Feature", description: "A request, idea, or new functionality", color: "blue" }, ]; -export function seedIssueTypes(gh: GitHubStore, org: GitHubOrg, types: IssueTypeSeed[] = DEFAULT_ISSUE_TYPES): void { - for (const type of types) { +export function seedIssueTypes(gh: GitHubStore, org: GitHubOrg, types?: IssueTypeSeed[] | null): void { + for (const type of types ?? DEFAULT_ISSUE_TYPES) { if (!type.name?.trim()) throw new Error(`Issue type for ${org.login} needs a name`); if (orgIssueTypes(gh, org.id).some((existing) => existing.name.toLowerCase() === type.name.toLowerCase())) continue; const row = gh.issueTypes.insert({ @@ -42,26 +43,12 @@ export function repoIssueTypes(gh: GitHubStore, repo: GitHubRepo): GitHubIssueTy return repo.owner_type === "Organization" ? orgIssueTypes(gh, repo.owner_id) : []; } -export function formatIssueType(type: GitHubIssueType) { - return { - id: type.id, - node_id: type.node_id, - name: type.name, - description: type.description, - color: type.color, - created_at: type.created_at, - updated_at: type.updated_at, - is_enabled: type.is_enabled, - }; -} - /** - * Resolves the `type` field of an issue write. `undefined` leaves the type unchanged, `null` clears it, - * and a name selects an enabled type of the repository's organization, matched without regard to case. + * Resolves the `type` field of an issue write: `null` or an absent field clears it, and a name selects an + * enabled type of the repository's organization, matched without regard to case. */ -export function resolveIssueTypeId(gh: GitHubStore, repo: GitHubRepo, raw: unknown): number | null | undefined { - if (raw === undefined) return undefined; - if (raw === null) return null; +export function resolveIssueTypeId(gh: GitHubStore, repo: GitHubRepo, raw: unknown): number | null { + if (raw === undefined || raw === null) return null; if (typeof raw !== "string" || !raw.trim()) throw new ApiError(422, "Validation failed"); const type = repoIssueTypes(gh, repo).find( (candidate) => candidate.is_enabled && candidate.name.toLowerCase() === raw.trim().toLowerCase(), diff --git a/packages/@emulators/github/src/routes/issue-dependencies.ts b/packages/@emulators/github/src/routes/issue-dependencies.ts index b41a9eff8..39865b7be 100644 --- a/packages/@emulators/github/src/routes/issue-dependencies.ts +++ b/packages/@emulators/github/src/routes/issue-dependencies.ts @@ -5,7 +5,7 @@ import { getGitHubStore } from "../store.js"; import type { GitHubStore } from "../store.js"; import type { GitHubIssue, GitHubRepo } from "../entities.js"; import { assertIssueWrite, assertRepoPermission, notFoundResponse } from "../route-helpers.js"; -import { formatIssue, lookupRepo } from "../helpers.js"; +import { findIssueForRepo, formatIssue, lookupRepo } from "../helpers.js"; /** GitHub limits each issue to 50 relationships of each kind. */ export const MAX_ISSUE_DEPENDENCIES = 50; @@ -30,7 +30,7 @@ function pathIssue(gh: GitHubStore, c: Context, required: "read" | "write"): { r if (!repo.has_issues) throw notFoundResponse(); const issueNumber = Number(c.req.param("issue_number")); if (!Number.isInteger(issueNumber)) throw notFoundResponse(); - const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request); + const issue = findIssueForRepo(gh, repo.id, issueNumber); if (!issue) throw notFoundResponse(); return { repo, issue }; } @@ -90,12 +90,16 @@ export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): }); app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => { + // Removing an edge needs write on the blocked issue only: the far end may have become unreadable since. const { issue } = pathIssue(gh, c, "write"); - const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id")); + const raw = c.req.param("issue_id")!; + if (!/^\d+$/.test(raw)) throw new ApiError(400, "Problems parsing issue_id"); + const blockingId = Number(raw); const edge = gh.issueDependencies .findBy("blocked_issue_id", issue.id) - .find((candidate) => candidate.blocking_issue_id === blocking.id); - if (!edge) throw notFoundResponse(); + .find((candidate) => candidate.blocking_issue_id === blockingId); + const blocking = edge ? gh.issues.get(blockingId) : undefined; + if (!edge || !blocking) throw notFoundResponse(); gh.issueDependencies.delete(edge.id); return c.json(formatIssue(blocking, gh, baseUrl)); }); diff --git a/packages/@emulators/github/src/routes/issues.ts b/packages/@emulators/github/src/routes/issues.ts index 335630ce4..cee0302ef 100644 --- a/packages/@emulators/github/src/routes/issues.ts +++ b/packages/@emulators/github/src/routes/issues.ts @@ -7,6 +7,7 @@ import { assertIssueWrite, assertRepoPermission, notFoundResponse, ownerLoginOf import type { GitHubStore } from "../store.js"; import type { GitHubIssue, GitHubIssueEvent, GitHubLabel, GitHubRepo, GitHubUser } from "../entities.js"; import { + findIssueForRepo, formatIssue, formatRepo, formatUser, @@ -16,10 +17,6 @@ import { timestamp, } from "../helpers.js"; -function findIssueForRepo(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined { - return gh.issues.findBy("repo_id", repoId).find((i) => i.number === issueNumber && !i.is_pull_request); -} - function adjustRepoOpenIssues(gh: GitHubStore, repoId: number, delta: number) { const repo = gh.repos.get(repoId); if (!repo) return; @@ -312,7 +309,7 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v milestoneId = ms.id; } - const typeId = resolveIssueTypeId(gh, repo, body.type) ?? null; + const typeId = resolveIssueTypeId(gh, repo, body.type); const num = getNextIssueNumber(gh, repo.id); const row = gh.issues.insert({ @@ -442,7 +439,7 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v } } - if ("type" in body) patch.type_id = resolveIssueTypeId(gh, repo, body.type) ?? null; + if ("type" in body) patch.type_id = resolveIssueTypeId(gh, repo, body.type); const prevLabelIds = new Set(issue.label_ids); const prevAssigneeIds = new Set(issue.assignee_ids); From eb588e1fd80174faa88c41625e5ee4982da0ada3 Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 08:20:54 +0000 Subject: [PATCH 4/6] fix(github): hide unreadable far end on dependency DELETE; align id errors - DELETE blocked_by returns 204 when the caller cannot read the removed blocker, instead of serializing a private issue. - A malformed issue_id now answers 422 Validation failed, like POST. - The org issue-types route uses the exact login lookup the other org routes use. - Routes import formatIssueType from helpers directly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../github/src/__tests__/issue-dependencies.test.ts | 7 +++++-- packages/@emulators/github/src/issue-types.ts | 1 - .../@emulators/github/src/routes/issue-dependencies.ts | 5 ++++- packages/@emulators/github/src/routes/issue-types.ts | 7 +++---- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts index 7067fac66..0354b88cf 100644 --- a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts +++ b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts @@ -169,8 +169,11 @@ describe("GitHub issue dependencies", () => { const hidden = await createIssue("hubot/secret", "hubot-token"); getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id }); const path = `/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`; - expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(400); - expect((await call(`${path}/${hidden.id}`, { method: "DELETE" })).status).toBe(200); + expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(422); + // The private far end is not serialized back to a caller who cannot read it. + const removed = await call(`${path}/${hidden.id}`, { method: "DELETE" }); + expect(removed.status).toBe(204); + expect(await removed.text()).toBe(""); expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toEqual([]); }); diff --git a/packages/@emulators/github/src/issue-types.ts b/packages/@emulators/github/src/issue-types.ts index f22fc0bb5..fbeac781a 100644 --- a/packages/@emulators/github/src/issue-types.ts +++ b/packages/@emulators/github/src/issue-types.ts @@ -2,7 +2,6 @@ import { ApiError } from "@emulators/core"; import type { GitHubIssueType, GitHubOrg, GitHubRepo } from "./entities.js"; import type { GitHubStore } from "./store.js"; import { generateNodeId } from "./helpers.js"; -export { formatIssueType } from "./helpers.js"; export interface IssueTypeSeed { name: string; diff --git a/packages/@emulators/github/src/routes/issue-dependencies.ts b/packages/@emulators/github/src/routes/issue-dependencies.ts index 39865b7be..bf428135a 100644 --- a/packages/@emulators/github/src/routes/issue-dependencies.ts +++ b/packages/@emulators/github/src/routes/issue-dependencies.ts @@ -93,7 +93,7 @@ export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): // Removing an edge needs write on the blocked issue only: the far end may have become unreadable since. const { issue } = pathIssue(gh, c, "write"); const raw = c.req.param("issue_id")!; - if (!/^\d+$/.test(raw)) throw new ApiError(400, "Problems parsing issue_id"); + if (!/^\d+$/.test(raw)) throw new ApiError(422, "Validation failed"); const blockingId = Number(raw); const edge = gh.issueDependencies .findBy("blocked_issue_id", issue.id) @@ -101,6 +101,9 @@ export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): const blocking = edge ? gh.issues.get(blockingId) : undefined; if (!edge || !blocking) throw notFoundResponse(); gh.issueDependencies.delete(edge.id); + // Never serialize a far end the caller cannot read; the edge is still removed. + const blockingRepo = gh.repos.get(blocking.repo_id); + if (!blockingRepo || !canRead(gh, c.get("authUser"), blockingRepo)) return c.body(null, 204); return c.json(formatIssue(blocking, gh, baseUrl)); }); } diff --git a/packages/@emulators/github/src/routes/issue-types.ts b/packages/@emulators/github/src/routes/issue-types.ts index 848bc9813..77c550ef5 100644 --- a/packages/@emulators/github/src/routes/issue-types.ts +++ b/packages/@emulators/github/src/routes/issue-types.ts @@ -1,16 +1,15 @@ import type { RouteContext } from "@emulators/core"; import { getGitHubStore } from "../store.js"; import { assertRepoPermission, getActorUser, isOrgMember, notFoundResponse } from "../route-helpers.js"; -import { lookupRepo } from "../helpers.js"; -import { formatIssueType, orgIssueTypes, repoIssueTypes } from "../issue-types.js"; +import { formatIssueType, lookupRepo } from "../helpers.js"; +import { orgIssueTypes, repoIssueTypes } from "../issue-types.js"; export function issueTypesRoutes({ app, store }: RouteContext): void { const gh = getGitHubStore(store); // Organization members and installations on the organization may read its issue types. app.get("/orgs/:org/issue-types", (c) => { - const login = c.req.param("org")!.toLowerCase(); - const org = gh.orgs.all().find((candidate) => candidate.login.toLowerCase() === login); + const org = gh.orgs.findOneBy("login", c.req.param("org")!); if (!org) throw notFoundResponse(); const authUser = c.get("authUser"); const installation = authUser?.installation; From e1a44ce0ee281c6a001d1d4270f8de0cef512bc6 Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 10:55:28 +0000 Subject: [PATCH 5/6] build(github-emulator): clear stale .types; document strict tokens in root README - The wrapper's tsup onSuccess removes .types before tsc writes declarations, so declarations of deleted sources never reach dist/index.d.ts (the root build calls tsup directly, so a package script alone would not run). - Add a clean script matching the sibling packages. - The root README states the strict token default and private-repo 404s. Review of PR 11 (findings 7 and 10). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- README.md | 2 +- packages/github-emulator/package.json | 1 + packages/github-emulator/tsup.config.ts | 4 +++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a83cd1e06..b2cef4bb8 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ try { } ``` -Options are `port`, `hostname`, `baseUrl`, `seed`, and `tokens`. The instance exposes `url`, `generatedSecrets`, `reset()`, and `close()`. Seeding uses the retained [upstream GitHub config](packages/@emulators/github/README.md). Tokens resolve to actual seeded user IDs. Omitted GitHub App keys are generated and returned through `generatedSecrets` in the programmatic API; the CLI does not print private keys. +Options are `port`, `hostname`, `baseUrl`, `seed`, and `tokens`. Unlike upstream, tokens are checked strictly by default: a bearer token the seed did not configure and the emulator did not issue (for example one issued before `reset()`) gets `401 Bad credentials` (set `strict_scopes: false` in the seed for upstream's default-user fallback), and private repositories answer `404` to callers who cannot see them. The instance exposes `url`, `generatedSecrets`, `reset()`, and `close()`. Seeding uses the retained [upstream GitHub config](packages/@emulators/github/README.md). Tokens resolve to actual seeded user IDs. Omitted GitHub App keys are generated and returned through `generatedSecrets` in the programmatic API; the CLI does not print private keys. Each instance has independent in-memory state. Reset replays its seed and clears dynamic OAuth and installation tokens while retaining generated App keys. Closing an instance releases its HTTP listener. The baseline retains upstream's in-memory backend; SQLite is planned as a later consistency improvement. In-flight webhook cancellation across reset is not guaranteed by this baseline. diff --git a/packages/github-emulator/package.json b/packages/github-emulator/package.json index b1cd15c0b..f77503b60 100644 --- a/packages/github-emulator/package.json +++ b/packages/github-emulator/package.json @@ -32,6 +32,7 @@ }, "scripts": { "build": "tsup --clean", + "clean": "rm -rf dist .types .turbo", "test": "vitest run", "type-check": "tsc-ts --noEmit", "type-check:tsc": "tsc --noEmit", diff --git a/packages/github-emulator/tsup.config.ts b/packages/github-emulator/tsup.config.ts index 3f9102689..2da5c3270 100644 --- a/packages/github-emulator/tsup.config.ts +++ b/packages/github-emulator/tsup.config.ts @@ -1,5 +1,5 @@ import { defineConfig } from "tsup"; -import { cpSync } from "node:fs"; +import { cpSync, rmSync } from "node:fs"; import { emitTypes } from "../../scripts/emit-types.mjs"; export default defineConfig({ @@ -12,6 +12,8 @@ export default defineConfig({ noExternal: [/^@emulators\//], onSuccess: async () => { cpSync("../@emulators/core/src/fonts", "dist/fonts", { recursive: true }); + // Declarations from deleted sources must not reach the bundled dist/index.d.ts. + rmSync(".types", { recursive: true, force: true }); emitTypes(__dirname, { bundle: true }); }, }); From af644727653f2fd65a813ebcfaf9cf980f877651 Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Tue, 17 Nov 2026 12:45:07 +0000 Subject: [PATCH 6/6] fix(github): close #13 review findings on dependencies and issue types - DELETE .../dependencies/blocked_by/{issue_id} resolves the far end with issueById, so an issue the caller cannot read is a 404 like a missing edge and the edge stays; no status difference reveals hidden blockers, and id validation lives in one place. - GET /orgs/{org}/issue-types requires an installation on the org to hold issues or metadata read, as the repository endpoint does. - PATCH type changes record issue_type_added/changed/removed timeline events and send issues typed / untyped webhooks. - README documents that issue_dependencies_summary counts only same-repo or public related issues for every reader. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../src/__tests__/issue-dependencies.test.ts | 11 ++- .../github/src/__tests__/issue-types.test.ts | 69 +++++++++++++++++-- .../@emulators/github/src/route-helpers.ts | 6 +- .../github/src/routes/issue-dependencies.ts | 14 ++-- .../github/src/routes/issue-types.ts | 15 +++- .../@emulators/github/src/routes/issues.ts | 26 +++++++ packages/github-emulator/README.md | 4 +- 7 files changed, 119 insertions(+), 26 deletions(-) diff --git a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts index 0354b88cf..b4e51ea7a 100644 --- a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts +++ b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts @@ -164,17 +164,16 @@ describe("GitHub issue dependencies", () => { expect(summary).toEqual({ blocked_by: 0, blocking: 0, total_blocked_by: 0, total_blocking: 0 }); }); - it("removes an edge whose far end the caller can no longer read, and rejects a malformed id", async () => { + it("treats an edge to an issue the caller cannot read as not found, and rejects a malformed id", async () => { const blocked = await createIssue("octocat/alpha"); const hidden = await createIssue("hubot/secret", "hubot-token"); getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id }); const path = `/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`; expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(422); - // The private far end is not serialized back to a caller who cannot read it. - const removed = await call(`${path}/${hidden.id}`, { method: "DELETE" }); - expect(removed.status).toBe(204); - expect(await removed.text()).toBe(""); - expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toEqual([]); + // Same status as an id with no edge at all, so a writer cannot probe for hidden blockers. + expect((await call(`${path}/${hidden.id}`, { method: "DELETE" })).status).toBe(404); + expect((await call(`${path}/999999`, { method: "DELETE" })).status).toBe(404); + expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toHaveLength(1); }); it("requires authentication to add an edge", async () => { diff --git a/packages/@emulators/github/src/__tests__/issue-types.test.ts b/packages/@emulators/github/src/__tests__/issue-types.test.ts index 785f4442a..52c54ae9d 100644 --- a/packages/@emulators/github/src/__tests__/issue-types.test.ts +++ b/packages/@emulators/github/src/__tests__/issue-types.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { Hono, Store, @@ -9,6 +9,7 @@ import { type TokenMap, } from "@emulators/core"; import { githubPlugin, seedFromConfig } from "../index.js"; +import { getGitHubStore } from "../store.js"; const base = "http://localhost:4000"; @@ -21,11 +22,12 @@ function createTestApp() { ["admin-token", { login: "admin", id: 1, scopes: ["repo", "user", "read:org"] }], ["outsider-token", { login: "outsider", id: 2, scopes: ["repo", "user", "read:org"] }], ]); + const webhooks = new WebhookDispatcher(); const app = new Hono(); app.onError(createApiErrorHandler()); app.use("*", createErrorHandler()); app.use("*", authMiddleware(tokenMap)); - githubPlugin.register(app as any, store, new WebhookDispatcher(), base, tokenMap); + githubPlugin.register(app as any, store, webhooks, base, tokenMap); githubPlugin.seed?.(store, base); seedFromConfig(store, base, { users: [{ login: "admin" }, { login: "outsider" }], @@ -47,11 +49,33 @@ function createTestApp() { { owner: "admin", name: "personal" }, ], }); - return app; + // Installations on acme: one granted nothing, one granted issues read. + const acmeId = getGitHubStore(store).orgs.findOneBy("login", "acme")!.id; + for (const [token, permissions] of [ + ["bare-installation-token", {}], + ["issues-installation-token", { issues: "read" }], + ] as const) { + tokenMap.set(token, { + login: "acme-app[bot]", + id: 9000, + scopes: [], + installation: { + installationId: 1, + appId: 1, + accountId: acmeId, + accountType: "Organization", + permissions, + repositoryIds: [], + repositorySelection: "all", + }, + }); + } + return { app, webhooks }; } describe("GitHub issue types", () => { let app: Hono; + let webhooks: WebhookDispatcher; const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => { const headers: Record = {}; const token = init.token === undefined ? "admin-token" : init.token; @@ -66,7 +90,7 @@ describe("GitHub issue types", () => { const names = async (res: Response) => ((await res.json()) as IssueType[]).map((type) => type.name); beforeEach(() => { - app = createTestApp(); + ({ app, webhooks } = createTestApp()); }); it("seeds GitHub's default types, custom types or none per organization", async () => { @@ -90,6 +114,43 @@ describe("GitHub issue types", () => { expect((await call("/orgs/missing/issue-types")).status).toBe(404); }); + it("lets an installation on the organization list its types only with issues or metadata read", async () => { + expect((await call("/orgs/acme/issue-types", { token: "bare-installation-token" })).status).toBe(403); + const granted = await call("/orgs/acme/issue-types", { token: "issues-installation-token" }); + expect(await names(granted)).toEqual(["Task", "Bug", "Feature"]); + expect((await call("/orgs/custom/issue-types", { token: "issues-installation-token" })).status).toBe(404); + }); + + it("records a timeline event and sends issues typed or untyped when the type changes", async () => { + const dispatch = vi.spyOn(webhooks, "dispatch"); + const issue = (await ( + await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed" } }) + ).json()) as Issue; + const patch = (body: unknown) => + call(`/repos/acme/widget/issues/${issue.number}`, { method: "PATCH", body: body as Record }); + await patch({ type: "Bug" }); + await patch({ type: "Feature" }); + await patch({ type: "Feature" }); + await patch({ type: null }); + + const typeHooks = dispatch.mock.calls + .filter(([event, action]) => event === "issues" && (action === "typed" || action === "untyped")) + .map(([, action, payload]) => [action, (payload as { type: IssueType | null }).type?.name]); + expect(typeHooks).toEqual([ + ["typed", "Bug"], + ["typed", "Feature"], + ["untyped", "Feature"], + ]); + const events = (await (await call(`/repos/acme/widget/issues/${issue.number}/events`)).json()) as { + event: string; + }[]; + expect(events.map((e) => e.event).filter((e) => e.startsWith("issue_type"))).toEqual([ + "issue_type_added", + "issue_type_changed", + "issue_type_removed", + ]); + }); + it("sets, changes and clears an issue's type by name", async () => { const created = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed", type: "bug" } }); expect(created.status).toBe(201); diff --git a/packages/@emulators/github/src/route-helpers.ts b/packages/@emulators/github/src/route-helpers.ts index ade5cea44..cd6c93636 100644 --- a/packages/@emulators/github/src/route-helpers.ts +++ b/packages/@emulators/github/src/route-helpers.ts @@ -84,7 +84,11 @@ export function assertRepoRead(gh: GitHubStore, authUser: AuthUser | undefined, throw notFound(); } -function hasInstallationPermission(authUser: AuthUser, permissions: string[], required: "read" | "write"): boolean { +export function hasInstallationPermission( + authUser: AuthUser, + permissions: string[], + required: "read" | "write", +): boolean { const requiredRank = required === "write" ? 2 : 1; return permissions.some((name) => { const granted = authUser.installation?.permissions[name]; diff --git a/packages/@emulators/github/src/routes/issue-dependencies.ts b/packages/@emulators/github/src/routes/issue-dependencies.ts index bf428135a..95fd6a3a0 100644 --- a/packages/@emulators/github/src/routes/issue-dependencies.ts +++ b/packages/@emulators/github/src/routes/issue-dependencies.ts @@ -90,20 +90,14 @@ export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): }); app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => { - // Removing an edge needs write on the blocked issue only: the far end may have become unreadable since. const { issue } = pathIssue(gh, c, "write"); - const raw = c.req.param("issue_id")!; - if (!/^\d+$/.test(raw)) throw new ApiError(422, "Validation failed"); - const blockingId = Number(raw); + // A far end the caller cannot read is not found, as in the lists: its status must not reveal the edge. + const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id")); const edge = gh.issueDependencies .findBy("blocked_issue_id", issue.id) - .find((candidate) => candidate.blocking_issue_id === blockingId); - const blocking = edge ? gh.issues.get(blockingId) : undefined; - if (!edge || !blocking) throw notFoundResponse(); + .find((candidate) => candidate.blocking_issue_id === blocking.id); + if (!edge) throw notFoundResponse(); gh.issueDependencies.delete(edge.id); - // Never serialize a far end the caller cannot read; the edge is still removed. - const blockingRepo = gh.repos.get(blocking.repo_id); - if (!blockingRepo || !canRead(gh, c.get("authUser"), blockingRepo)) return c.body(null, 204); return c.json(formatIssue(blocking, gh, baseUrl)); }); } diff --git a/packages/@emulators/github/src/routes/issue-types.ts b/packages/@emulators/github/src/routes/issue-types.ts index 77c550ef5..4806b869d 100644 --- a/packages/@emulators/github/src/routes/issue-types.ts +++ b/packages/@emulators/github/src/routes/issue-types.ts @@ -1,13 +1,19 @@ -import type { RouteContext } from "@emulators/core"; +import { forbidden, type RouteContext } from "@emulators/core"; import { getGitHubStore } from "../store.js"; -import { assertRepoPermission, getActorUser, isOrgMember, notFoundResponse } from "../route-helpers.js"; +import { + assertRepoPermission, + getActorUser, + hasInstallationPermission, + isOrgMember, + notFoundResponse, +} from "../route-helpers.js"; import { formatIssueType, lookupRepo } from "../helpers.js"; import { orgIssueTypes, repoIssueTypes } from "../issue-types.js"; export function issueTypesRoutes({ app, store }: RouteContext): void { const gh = getGitHubStore(store); - // Organization members and installations on the organization may read its issue types. + // Organization members, and installations on the organization granted issues or metadata read, may read its issue types. app.get("/orgs/:org/issue-types", (c) => { const org = gh.orgs.findOneBy("login", c.req.param("org")!); if (!org) throw notFoundResponse(); @@ -18,6 +24,9 @@ export function issueTypesRoutes({ app, store }: RouteContext): void { ? installation.accountType === "Organization" && installation.accountId === org.id : !!user && isOrgMember(gh, user.id, org.id); if (!allowed) throw notFoundResponse(); + if (installation && !hasInstallationPermission(authUser!, ["issues", "metadata"], "read")) { + throw forbidden(); + } return c.json(orgIssueTypes(gh, org.id).map(formatIssueType)); }); diff --git a/packages/@emulators/github/src/routes/issues.ts b/packages/@emulators/github/src/routes/issues.ts index cee0302ef..4f6607994 100644 --- a/packages/@emulators/github/src/routes/issues.ts +++ b/packages/@emulators/github/src/routes/issues.ts @@ -9,6 +9,7 @@ import type { GitHubIssue, GitHubIssueEvent, GitHubLabel, GitHubRepo, GitHubUser import { findIssueForRepo, formatIssue, + formatIssueType, formatRepo, formatUser, generateNodeId, @@ -444,6 +445,7 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v const prevLabelIds = new Set(issue.label_ids); const prevAssigneeIds = new Set(issue.assignee_ids); const prevMilestoneId = issue.milestone_id; + const prevTypeId = issue.type_id ?? null; const updated = gh.issues.update(issue.id, patch); if (!updated) throw notFoundResponse(); @@ -637,6 +639,30 @@ export function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): v } } + // GitHub reports a type change as issues/typed (a type set or replaced) or issues/untyped (cleared). + const newTypeId = issue.type_id ?? null; + if ("type" in body && prevTypeId !== newTypeId) { + const event = + newTypeId === null ? "issue_type_removed" : prevTypeId === null ? "issue_type_added" : "issue_type_changed"; + insertIssueEvent(gh, repo, issue.number, event, actor.id); + const action = newTypeId === null ? "untyped" : "typed"; + const typeId = newTypeId ?? prevTypeId; + const type = typeId ? gh.issueTypes.get(typeId) : undefined; + webhooks.dispatch( + "issues", + action, + { + action, + issue: formatIssue(issue, gh, baseUrl)!, + type: type ? formatIssueType(type) : null, + repository: formatRepo(repo, gh, baseUrl), + sender: formatUser(actor, baseUrl), + }, + ownerLogin, + repo.name, + ); + } + const titleEdited = typeof body.title === "string" && body.title !== beforePatch.title; const bodyEdited = "body" in body && diff --git a/packages/github-emulator/README.md b/packages/github-emulator/README.md index e499bb9aa..411531e90 100644 --- a/packages/github-emulator/README.md +++ b/packages/github-emulator/README.md @@ -20,9 +20,9 @@ try { Tokens are checked as GitHub checks them: a bearer token that the seed did not configure and the emulator did not issue (for example one issued before `reset()`) gets `401 Bad credentials`. Upstream emulate treats such a token as the default user; set `strict_scopes: false` in the seed to restore that. Private repositories answer `404` to callers who cannot see them. -Issue dependencies follow GitHub's REST API: `GET`/`POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by`, `DELETE .../dependencies/blocked_by/{issue_id}` and `GET .../dependencies/blocking`, across repositories, with GitHub's 50-relationship limit. Issue objects carry `issue_dependencies_summary`. +Issue dependencies follow GitHub's REST API: `GET`/`POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by`, `DELETE .../dependencies/blocked_by/{issue_id}` and `GET .../dependencies/blocking`, across repositories, with GitHub's 50-relationship limit. Issue objects carry `issue_dependencies_summary`; because one issue payload serves every reader, unlike GitHub's, it counts only related issues in the same repository or a public one, even for a caller who can read more. The dependency lists return every edge the caller can read, and a far end the caller cannot read is a 404 on `DELETE`. -Organizations have issue types: GitHub's Task, Bug and Feature unless a seed org lists `issue_types` (`[]` for none). `GET /orgs/{org}/issue-types` and `GET /repos/{owner}/{repo}/issue-types` list them, issue writes accept `type` (an enabled type's name, or `null` to clear), and issue objects carry `type`. +Organizations have issue types: GitHub's Task, Bug and Feature unless a seed org lists `issue_types` (`[]` for none). `GET /orgs/{org}/issue-types` and `GET /repos/{owner}/{repo}/issue-types` list them, issue writes accept `type` (an enabled type's name, or `null` to clear), and issue objects carry `type`. Changing a type records a timeline event and sends `issues` `typed` or `untyped`. An installation on the organization needs `issues` or `metadata` read to list the organization's types. The default seed is synthetic. Configure `seed` and `tokens` for your tests. The instance provides `url`, `generatedSecrets`, `reset()`, and `close()`; tokens are resolved to seeded user IDs. Reset clears dynamic credentials and replays fixture state while preserving generated App keys.