The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Repos from "@distilled.cloud/github/repos"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import type { Input } from "alchemy/Input"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Redacted from "effect/Redacted"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts"; |
| 10 | import type * as GitHub from "./Providers.ts"; |
| 11 | import type { WebhookEventName } from "./RepositoryEventSource.ts"; |
| 12 | |
| 13 | export interface WebhookProps { |
| 14 | /** |
| 15 | * Repository owner (user or organization). |
| 16 | */ |
| 17 | owner: string; |
| 18 | |
| 19 | /** |
| 20 | * Repository name. |
| 21 | */ |
| 22 | repository: string; |
| 23 | |
| 24 | /** |
| 25 | * The URL that GitHub will `POST` events to. Accepts an `Output<string>` |
| 26 | * (e.g. a Cloudflare Worker's `url`) so the webhook can target a |
| 27 | * resource provisioned in the same stack. |
| 28 | */ |
| 29 | url: Input<string>; |
| 30 | |
| 31 | /** |
| 32 | * GitHub event names to subscribe to (e.g. `["push", "pull_request"]`). |
| 33 | * Use `["*"]` to receive every event GitHub emits. |
| 34 | * @default ["push"] |
| 35 | */ |
| 36 | events?: WebhookEventName[]; |
| 37 | |
| 38 | /** |
| 39 | * Secret used to sign each delivery with `HMAC-SHA256`. The signature is |
| 40 | * sent in the `X-Hub-Signature-256` header so the receiver can verify the |
| 41 | * payload originated from GitHub. Wrap with `Redacted.make` to keep it out |
| 42 | * of logs and state. |
| 43 | */ |
| 44 | secret?: Redacted.Redacted<string>; |
| 45 | |
| 46 | /** |
| 47 | * Payload media type. |
| 48 | * @default "json" |
| 49 | */ |
| 50 | contentType?: "json" | "form"; |
| 51 | |
| 52 | /** |
| 53 | * Whether deliveries are active. |
| 54 | * @default true |
| 55 | */ |
| 56 | active?: boolean; |
| 57 | |
| 58 | /** |
| 59 | * Skip TLS verification of the delivery URL (`insecure_ssl`). Only use for |
| 60 | * local/testing endpoints. |
| 61 | * @default false |
| 62 | */ |
| 63 | insecureSsl?: boolean; |
| 64 | |
| 65 | /** |
| 66 | * Override the GitHub host or API base URL for this resource only (e.g. |
| 67 | * `github.example.com` for GitHub Enterprise). Falls back to |
| 68 | * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth |
| 69 | * provider. Changing it replaces the resource — the same name on a |
| 70 | * different GitHub instance is a different physical resource. |
| 71 | */ |
| 72 | baseUrl?: string; |
| 73 | } |
| 74 | |
| 75 | export interface Webhook extends Resource< |
| 76 | "GitHub.Webhook", |
| 77 | WebhookProps, |
| 78 | { |
| 79 | /** |
| 80 | * Numeric ID of the webhook in GitHub. |
| 81 | */ |
| 82 | webhookId: number; |
| 83 | |
| 84 | /** |
| 85 | * The configured delivery URL. |
| 86 | */ |
| 87 | url: string; |
| 88 | |
| 89 | /** |
| 90 | * URL used by GitHub to send a `ping` event. |
| 91 | */ |
| 92 | pingUrl: string | undefined; |
| 93 | |
| 94 | /** |
| 95 | * URL used by GitHub to re-deliver the last event. |
| 96 | */ |
| 97 | testUrl: string | undefined; |
| 98 | |
| 99 | /** |
| 100 | * ISO-8601 timestamp of the last update. |
| 101 | */ |
| 102 | updatedAt: string; |
| 103 | }, |
| 104 | never, |
| 105 | GitHub.Providers |
| 106 | > {} |
| 107 | |
| 108 | /** |
| 109 | * A GitHub repository webhook. |
| 110 | * |
| 111 | * `Webhook` manages the lifecycle of a repository webhook that `POST`s |
| 112 | * events to a delivery URL. It is created on the first deploy and updated |
| 113 | * in place on subsequent deploys, and is deleted when the resource is |
| 114 | * destroyed. |
| 115 | * |
| 116 | * Authentication is resolved via the GitHub `Credentials` service supplied |
| 117 | * by `GitHub.providers()` (env, stored PAT, or `gh` CLI). The token needs |
| 118 | * `repo` scope (admin access to the repository) to manage webhooks. |
| 119 | * |
| 120 | * Most users don't construct `Webhook` directly — prefer |
| 121 | * {@link import("./RepositoryEventSource.ts").events | events(repository, handler)} |
| 122 | * inside a Cloudflare Worker, which provisions the webhook, wires the |
| 123 | * delivery URL to the Worker, and forwards verified events to your handler. |
| 124 | * ### Creating a Webhook |
| 125 | * **Example:** Forward push events to a URL |
| 126 | * ```typescript |
| 127 | * yield* GitHub.Webhook("ci-webhook", { |
| 128 | * owner: "my-org", |
| 129 | * repository: "my-repo", |
| 130 | * url: "https://example.com/github", |
| 131 | * events: ["push", "pull_request"], |
| 132 | * secret: Redacted.make(process.env.WEBHOOK_SECRET!), |
| 133 | * }); |
| 134 | * ``` |
| 135 | * |
| 136 | * **Example:** Point a webhook at a Worker |
| 137 | * ```typescript |
| 138 | * const worker = yield* Cloudflare.Worker("Api", { ... }); |
| 139 | * |
| 140 | * yield* GitHub.Webhook("repo-webhook", { |
| 141 | * owner: "my-org", |
| 142 | * repository: "my-repo", |
| 143 | * url: worker.url!, |
| 144 | * events: ["*"], |
| 145 | * }); |
| 146 | * ``` |
| 147 | * |
| 148 | * @resource |
| 149 | * @product Webhook |
| 150 | */ |
| 151 | export const Webhook = Resource<Webhook>("GitHub.Webhook"); |
| 152 | |
| 153 | export const WebhookProvider = () => |
| 154 | Provider.succeed(Webhook, { |
| 155 | stables: ["webhookId"], |
| 156 | |
| 157 | // A webhook belongs to (host, owner, repository) — its server-assigned |
| 158 | // id is meaningless in any other repo, so moving it replaces the |
| 159 | // resource: the engine creates the new webhook first, then `delete` |
| 160 | // removes the old one from the old repo. Everything else (url, events, |
| 161 | // secret, active) is mutated in place by `reconcile`. Replacement is |
| 162 | // safe here — a webhook is declarative config that is fully |
| 163 | // re-creatable from props. |
| 164 | diff: Effect.fn(function* ({ news, olds }) { |
| 165 | if (!isResolved(news)) return; |
| 166 | if (olds === undefined) return; |
| 167 | if ( |
| 168 | news.owner !== olds.owner || |
| 169 | news.repository !== olds.repository || |
| 170 | (yield* gitHubBaseUrlChanged(olds, news)) |
| 171 | ) { |
| 172 | return { action: "replace" }; |
| 173 | } |
| 174 | }), |
| 175 | |
| 176 | reconcile: Effect.fn( |
| 177 | function* ({ news, output }) { |
| 178 | const scope = { owner: news.owner, repo: news.repository }; |
| 179 | |
| 180 | const config = { |
| 181 | url: news.url as string, |
| 182 | content_type: news.contentType ?? "json", |
| 183 | // Sensitive on the wire: the SDK unwraps the Redacted when it sends. |
| 184 | secret: news.secret, |
| 185 | insecure_ssl: news.insecureSsl ? "1" : "0", |
| 186 | }; |
| 187 | const events = news.events ?? ["push"]; |
| 188 | const active = news.active ?? true; |
| 189 | |
| 190 | // Observe — GitHub assigns the hook id server-side. Probe for live |
| 191 | // state via the cached id; a 404 (deleted out-of-band, or never |
| 192 | // created) collapses to "no observed webhook" so we converge by |
| 193 | // creating a fresh one. |
| 194 | const observed = output?.webhookId |
| 195 | ? yield* Repos.getWebhook({ ...scope, hook_id: output.webhookId }).pipe( |
| 196 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 197 | ) |
| 198 | : undefined; |
| 199 | |
| 200 | // Ensure — POST creates the webhook. |
| 201 | if (observed === undefined) { |
| 202 | return toAttrs( |
| 203 | yield* Repos.createWebhook({ ...scope, name: "web", active, events, config }), |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | // Sync — PATCH the existing webhook with the desired config. The |
| 208 | // secret can never be read back, so we always send the full config |
| 209 | // to converge rather than diffing. |
| 210 | return toAttrs( |
| 211 | yield* Repos.updateWebhook({ ...scope, hook_id: observed.id, active, events, config }), |
| 212 | ); |
| 213 | }, |
| 214 | (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)), |
| 215 | ), |
| 216 | |
| 217 | // GitHub has no global webhook list — hooks are repo-scoped. Enumerate every |
| 218 | // repository the authenticated token can see, then list each repo's webhooks. |
| 219 | list: Effect.fn(function* () { |
| 220 | const repos = yield* Stream.runCollect( |
| 221 | Repos.listForAuthenticatedUser.items({ per_page: 100 }), |
| 222 | ); |
| 223 | const perRepo = yield* Effect.forEach( |
| 224 | repos, |
| 225 | (repo) => |
| 226 | Stream.runCollect( |
| 227 | Repos.listWebhooks.items({ |
| 228 | owner: repo.owner.login, |
| 229 | repo: repo.name, |
| 230 | per_page: 100, |
| 231 | }), |
| 232 | ).pipe( |
| 233 | Effect.map((hooks) => hooks.map(toAttrs)), |
| 234 | // Repos where the token lacks admin access reject the webhooks |
| 235 | // endpoint with 403/404 — skip them per the per-item not-found |
| 236 | // rule rather than failing the whole enumeration. |
| 237 | Effect.catchTag(["Forbidden", "NotFound"], () => Effect.succeed([])), |
| 238 | ), |
| 239 | { concurrency: 10 }, |
| 240 | ); |
| 241 | return perRepo.flat(); |
| 242 | }), |
| 243 | |
| 244 | delete: Effect.fn( |
| 245 | function* ({ olds, output }) { |
| 246 | yield* Repos.deleteWebhook({ |
| 247 | owner: olds.owner, |
| 248 | repo: olds.repository, |
| 249 | hook_id: output.webhookId, |
| 250 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 251 | }, |
| 252 | (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)), |
| 253 | ), |
| 254 | }); |
| 255 | |
| 256 | const toAttrs = (data: { |
| 257 | id: number; |
| 258 | config?: { url?: string } | null; |
| 259 | ping_url?: string | null; |
| 260 | test_url?: string | null; |
| 261 | updated_at?: string | null; |
| 262 | }): Webhook["Attributes"] => ({ |
| 263 | webhookId: data.id, |
| 264 | url: data.config?.url ?? "", |
| 265 | pingUrl: data.ping_url ?? undefined, |
| 266 | testUrl: data.test_url ?? undefined, |
| 267 | updatedAt: data.updated_at ?? new Date().toISOString(), |
| 268 | }); |