Repository navigation
Use a GUID for GitHub App webhook delivery IDs - #13
Conversation
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
| "Content-Type": "application/json", | ||
| "X-GitHub-Event": event, | ||
| "X-GitHub-Delivery": String(Date.now()), | ||
| "X-GitHub-Delivery": crypto.randomUUID(), |
There was a problem hiding this comment.
🟠 Bare crypto global; import randomUUID instead.
--- a/packages/@emulators/github/src/index.ts
+++ b/packages/@emulators/github/src/index.ts
@@
-import { createHmac, generateKeyPair } from "crypto";
+import { createHmac, generateKeyPair, randomUUID } from "crypto";
@@
- "X-GitHub-Delivery": crypto.randomUUID(),
+ "X-GitHub-Delivery": randomUUID(),🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/index.ts:634):
Problem: Bare crypto global; import randomUUID instead
Detail: The new code calls `crypto.randomUUID()` via the ambient WebCrypto global, but this file already imports its crypto primitives by name (`import { createHmac, generateKeyPair } from "crypto"`, line 1). The bare `crypto` identifier is never imported, so the module only compiles/runs where the global exists: the WebCrypto global is only available by default on Node >= 19 (Node 18 needs --experimental-global-webcrypto) and `tsc` only resolves it with recent @types/node. The surrounding code establishes at most a Node 18+ baseline (it uses global `fetch` / `AbortSignal.timeout`), so on Node 18 runtimes every app-webhook dispatch in `deliverToAppWebhookUrls` would throw a ReferenceError, and even where it works the implicit global is inconsistent with the file's own named-import convention. Use the named export from the module already imported.
Suggested fix: Extend the existing import on line 1 and call it directly: `import { createHmac, generateKeyPair, randomUUID } from "crypto";` then `"X-GitHub-Delivery": randomUUID(),`.
Suggested patch:
--- a/packages/@emulators/github/src/index.ts
+++ b/packages/@emulators/github/src/index.ts
@@
-import { createHmac, generateKeyPair } from "crypto";
+import { createHmac, generateKeyPair, randomUUID } from "crypto";
@@
- "X-GitHub-Delivery": crypto.randomUUID(),
+ "X-GitHub-Delivery": randomUUID(),
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
The new code calls crypto.randomUUID() via the ambient WebCrypto global, but this file already imports its crypto primitives by name (import { createHmac, generateKeyPair } from "crypto", line 1). The bare crypto identifier is never imported, so the module only compiles/runs where the global exists: the WebCrypto global is only available by default on Node >= 19 (Node 18 needs --experimental-global-webcrypto) and tsc only resolves it with recent @types/node. The surrounding code establishes at most a Node 18+ baseline (it uses global fetch / AbortSignal.timeout), so on Node 18 runtimes every app-webhook dispatch in deliverToAppWebhookUrls would throw a ReferenceError, and even where it works the implicit global is inconsistent with the file's own named-import convention. Use the named export from the module already imported.
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-GitHub-Event": event,
"X-GitHub-Delivery": crypto.randomUUID(),
};
if (ghApp.webhook_secret) {
const hmac = createHmac("sha256", ghApp.webhook_secret).update(body).digest("hex");
Code reviewVerdict: Address the major findings before merging. · 🔴 0 · 🟠 1 · 🟡 0 · ⚪ 0 · 0/1 resolved
🤖 Fix all 1 open findings with your agent📋 Out-of-diff findings (1)
Reviewed 2 files · 0 inline · view all 1 findings ↗ · AI-generated — verify findings before acting · AI guidance and feedback aictrl · AI code review for fast-moving teams · aictrl.dev |
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
Review response — PR 13Fixes are in Issues addressed (pushed to this stack)
Review claims verified false (no change needed)None. Not addressed hereNone. |
…rrors - 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
… 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
Add organization issue types
| * 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 => |
There was a problem hiding this comment.
🟡 Dependency summary undercounts for authorized callers.
| const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue => | |
| Either document the discrepancy in the README next to the dependency endpoints ("summary counts only same-repo/public blockers even for authorized callers"), or thread the caller into the summary where one is known (per-request GETs) and keep the reader-agnostic filter only for shared webhook payloads. |
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/helpers.ts:422-431):
Problem: Dependency summary undercounts for authorized callers
Detail: issueDependenciesSummary now drops cross-repo private far-ends for every reader, so a caller who CAN read both ends (e.g. the owner of both private repos) gets issue_dependencies_summary.blocked_by = 0 from GET /repos/o/r/issues/N while GET /repos/o/r/issues/N/dependencies/blocked_by on the same issue returns the edge; webhook payload counts are undercounted the same way. The doc comment shows the shared-payload rationale is deliberate, but the summary/list contradiction for fully-authorized callers (who see 0 blockers on the issue yet 1 edge in the list) is neither documented in the README nor matches GitHub, where the summary counts all stored edges.
Suggested fix: Either document the discrepancy in the README next to the dependency endpoints ("summary counts only same-repo/public blockers even for authorized callers"), or thread the caller into the summary where one is known (per-request GETs) and keep the reader-agnostic filter only for shared webhook payloads.
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
issueDependenciesSummary now drops cross-repo private far-ends for every reader, so a caller who CAN read both ends (e.g. the owner of both private repos) gets issue_dependencies_summary.blocked_by = 0 from GET /repos/o/r/issues/N while GET /repos/o/r/issues/N/dependencies/blocked_by on the same issue returns the edge; webhook payload counts are undercounted the same way. The doc comment shows the shared-payload rationale is deliberate, but the summary/list contradiction for fully-authorized callers (who see 0 blockers on the issue yet 1 edge in the list) is neither documented in the README nor matches GitHub, where the summary counts all stored edges.
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(visibleToAllReaders);
const blocked = store.issueDependencies
.findBy("blocking_issue_id", issue.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(); |
There was a problem hiding this comment.
🟡 DELETE dependency status codes reveal hidden edges.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/routes/issue-dependencies.ts:102-106):
Problem: DELETE dependency status codes reveal hidden edges
Detail: The reworked DELETE returns 404 when no edge exists but 204 when an edge exists whose far end the caller cannot read, so a caller with issues-write on the blocked issue can probe arbitrary issue ids and learn which unreadable (e.g. cross-repo private) issues block their issue — exactly the data the GET list endpoints filter out. Each successful probe also destroys the edge, so a writer on the blocked issue can now remove edges whose far end they could never read (the old issueById path 404'd without deleting).
Suggested fix: Make hidden-edge and readable-edge deletions indistinguishable: return 204 (empty body) for every successful deletion — the delete already happens before the visibility check, so the far end is never serialized anyway. Alternatively, restore the old refuse-to-delete 404 when canRead fails if the pre-change protection was intentional.
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
The reworked DELETE returns 404 when no edge exists but 204 when an edge exists whose far end the caller cannot read, so a caller with issues-write on the blocked issue can probe arbitrary issue ids and learn which unreadable (e.g. cross-repo private) issues block their issue — exactly the data the GET list endpoints filter out. Each successful probe also destroys the edge, so a writer on the blocked issue can now remove edges whose far end they could never read (the old issueById path 404'd without deleting).
.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);
// 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));| // 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")!; |
There was a problem hiding this comment.
🟡 DELETE re-implements issueById's id validation.
| const raw = c.req.param("issue_id")!; | |
| Extract a small parseIssueIdParam(raw: string): number (regex + ApiError 422) in this file and use it from both issueById and the DELETE handler, so DELETE keeps its new edge-lookup semantics while sharing the validation. |
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/routes/issue-dependencies.ts:95-97):
Problem: DELETE re-implements issueById's id validation
Detail: The new inline digit-check + ApiError(422, "Validation failed") re-implements the identical contract already performed by issueById (lines 40-41) for the POST handler in the same file. The same parameter-validation rule now lives in two places and can drift (e.g. one later accepting a different id format or error body).
Suggested fix: Extract a small parseIssueIdParam(raw: string): number (regex + ApiError 422) in this file and use it from both issueById and the DELETE handler, so DELETE keeps its new edge-lookup semantics while sharing the validation.
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
The new inline digit-check + ApiError(422, "Validation failed") re-implements the identical contract already performed by issueById (lines 40-41) for the POST handler in the same file. The same parameter-validation rule now lives in two places and can drift (e.g. one later accepting a different id format or error body).
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);| } | ||
| } | ||
|
|
||
| if ("type" in body) patch.type_id = resolveIssueTypeId(gh, repo, body.type); |
There was a problem hiding this comment.
🟡 Type edits emit no webhook or issue event.
| if ("type" in body) patch.type_id = resolveIssueTypeId(gh, repo, body.type); | |
| Capture prevTypeId alongside prevMilestoneId and, when it differs, insert an issue event and dispatch webhooks.dispatch("issues", "edited", { changes: { type: { from, to } } }) mirroring the milestone block, so type edits reach webhook subscribers like every other PATCHed field. |
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/routes/issues.ts:442-443):
Problem: Type edits emit no webhook or issue event
Detail: PATCH now honors `type`, but unlike title/body (issues/edited), labels (labeled/unlabeled), assignees and milestone (milestoned/demilestoned), a type change inserts no issue event and dispatches no webhook — type edits are invisible to webhook subscribers and the events timeline. Real GitHub fires issues/edited with a changes entry when an issue's type changes, and in a webhook-testing emulator this silence is the primary observable contract.
Suggested fix: Capture prevTypeId alongside prevMilestoneId and, when it differs, insert an issue event and dispatch webhooks.dispatch("issues", "edited", { changes: { type: { from, to } } }) mirroring the milestone block, so type edits reach webhook subscribers like every other PATCHed field.
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
PATCH now honors type, but unlike title/body (issues/edited), labels (labeled/unlabeled), assignees and milestone (milestoned/demilestoned), a type change inserts no issue event and dispatches no webhook — type edits are invisible to webhook subscribers and the events timeline. Real GitHub fires issues/edited with a changes entry when an issue's type changes, and in a webhook-testing emulator this silence is the primary observable contract.
}
}
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);
const prevMilestoneId = issue.milestone_id;| app.get("/orgs/:org/issue-types", (c) => { | ||
| const org = gh.orgs.findOneBy("login", c.req.param("org")!); | ||
| if (!org) throw notFoundResponse(); | ||
| const authUser = c.get("authUser"); |
There was a problem hiding this comment.
🟡 Org issue-types skips installation permission checks.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/routes/issue-types.ts:14-19):
Problem: Org issue-types skips installation permission checks
Detail: The /orgs/:org/issue-types handler authorizes an installation purely on accountType/accountId match, so any GitHub App installed on the organization — even with zero granted permissions — can enumerate its issue-type catalog. The sibling /repos/:owner/:repo/issue-types endpoint ten lines below routes through assertRepoPermission, which enforces issues/metadata permissions for installations on private repos, and every other route delegates to a route-helpers helper; this endpoint hand-rolls its authz instead. GitHub's own catalog access for Apps requires the issues read permission.
Suggested fix: For the installation path also require a relevant granted permission (e.g. mirror hasInstallationPermission(["issues","metadata"], "read") as assertRepoPermission does), ideally via a shared org-scoped helper in route-helpers.ts so the endpoint stops hand-rolling authz.
Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters
The /orgs/:org/issue-types handler authorizes an installation purely on accountType/accountId match, so any GitHub App installed on the organization — even with zero granted permissions — can enumerate its issue-type catalog. The sibling /repos/:owner/:repo/issue-types endpoint ten lines below routes through assertRepoPermission, which enforces issues/metadata permissions for installations on private repos, and every other route delegates to a route-helpers helper; this endpoint hand-rolls its authz instead. GitHub's own catalog access for Apps requires the issues read permission.
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();
Code reviewVerdict: Looks good — only minor / nit comments below. · 🔴 0 · 🟠 0 · 🟡 5 · ⚪ 0 · 0/5 resolved
🤖 Fix all 5 open findings with your agent📋 Out-of-diff findings (5)
Reviewed 15 files · 0 inline · view all 5 findings ↗ · AI-generated — verify findings before acting · AI guidance and feedback aictrl · AI code review for fast-moving teams · aictrl.dev |
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx
Review response — PR #13All five minor findings from the latest review are real and fixed in one commit on this branch. Issues addressed (pushed to this PR)
Tests: github package 196/196 (2 new), Review claims verified false (no change needed)None. Not addressed hereNone. |
Summary
App webhook deliveries now send
crypto.randomUUID()asX-GitHub-Deliveryinstead ofString(Date.now()), so two deliveries in the same millisecond no longer share an ID (closes #10). This is the same change as the upstream PR vercel-labs#413; the next upstream sync brings it in either way.aictrl can then remove its build-time patch (
scripts/e2e/patch-github-emulator-delivery-id.mjs).Stacked on #12; retarget after #11 and #12 merge.
Verification
webhook-installation.test.tspinsDate.now()and expects two distinct GUIDs. It fails before the change and passes after.node:24-bookworm-slim, all of these pass: build,type-check,type-check:tsc, lint (0 errors), format, and all package tests (core 113, github 188, github-emulator 6).🤖 Generated with Claude Code
https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx