@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 178 lines 6.29 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Output from "alchemy/Output";
3 import { Random } from "alchemy/Random";
4 import { WebhookHost } from "alchemy/WebhookHost";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Redacted from "effect/Redacted";
8 import {
9 RepositoryEventSource,
10 webhookPath,
11 webhookSecretEnvName,
12 type RepositoryEventSourceProps,
13 type RepositoryEventSourceService,
14 type WebhookEvent,
15 } from "./RepositoryEventSource.ts";
16 import { Webhook } from "./Webhook.ts";
17
18 /**
19 * GitHub event source on any {@link WebhookHost}.
20 *
21 * Deploy-time: provisions a {@link Webhook} on the repository whose delivery
22 * URL points at the host (at a deterministic per-repo path). The webhook
23 * secret (the caller's `secret`, or a generated random one when omitted) is
24 * bound onto the host via an `Output` accessor so the runtime can verify
25 * delivery signatures.
26 *
27 * Runtime: claims requests on the repository's delivery path, verifies the
28 * `HMAC-SHA256` signature against the bound secret, and forwards each
29 * delivery to the subscriber. Requests on any other path fall through to the
30 * host's own handler.
31 *
32 * Every Cloudflare Worker is a {@link WebhookHost}, so this is the only layer
33 * to provide.
34 *
35 * @layer
36 * @product Webhook
37 * @provides GitHub.RepositoryEventSource
38 */
39 export const RepositoryEventSourceLive = Layer.effect(
40 RepositoryEventSource,
41 Effect.gen(function* () {
42 const ctx = yield* WebhookHost;
43 // Loosely-typed constructor — yielding the resource class erases its
44 // `GitHub.Providers` requirement. The requirement is satisfied by the
45 // stack at plan time.
46 const createWebhook = yield* Webhook;
47
48 return Effect.fn(function* (
49 props: RepositoryEventSourceProps,
50 process: (event: WebhookEvent) => Effect.Effect<void, never, never>,
51 ) {
52 const path = webhookPath(props);
53
54 // Every delivery is verified: without a caller-supplied secret, mint a
55 // stable random one shared by the webhook and the host.
56 const webhookSecret =
57 props.secret ??
58 (yield* Namespace.push(
59 ctx.LogicalId,
60 Random(`${props.owner}/${props.repository}WebhookSecret`),
61 )).text;
62
63 // Deploy-time: provision the repository webhook pointing at the host.
64 // Skipped once running inside the deployed host (the global guard).
65 // Namespaced under the host so the webhook's logical identity matches the
66 // previous Binding.Policy.
67 if (!globalThis.__ALCHEMY_RUNTIME__) {
68 yield* Namespace.push(
69 ctx.LogicalId,
70 Effect.asVoid(
71 createWebhook(`${props.owner}/${props.repository}`, {
72 owner: props.owner,
73 repository: props.repository,
74 url: Output.interpolate`${ctx.url}${path}`,
75 events: [...(props.events ?? ["push"])],
76 secret: webhookSecret,
77 contentType: "json",
78 }),
79 ),
80 );
81 }
82
83 // Bind the webhook secret as an env accessor under a deterministic key.
84 // This single `yield*` does both halves: at plan time it registers the
85 // secret on the host, and it returns an Effect that reads the value
86 // back at runtime, reconstructing the `Redacted` wrapper.
87 const secret = yield* Output.named(
88 Output.asOutput(webhookSecret),
89 webhookSecretEnvName(props),
90 );
91
92 yield* ctx.route(path, (request) => handleDelivery(request, secret, process));
93 }) as RepositoryEventSourceService;
94 }),
95 );
96
97 const handleDelivery = <Req>(
98 request: Request,
99 // The bound secret accessor (see `Output.named` above).
100 secret: Effect.Effect<Redacted.Redacted<string> | undefined>,
101 process: (event: WebhookEvent<any>) => Effect.Effect<void, never, Req>,
102 ): Effect.Effect<Response, never, Req> =>
103 Effect.gen(function* () {
104 if (request.method !== "POST") {
105 return new Response("method not allowed", { status: 405 });
106 }
107
108 const body = yield* Effect.promise(() => request.text());
109
110 const resolved = yield* secret;
111 const signature = request.headers.get("x-hub-signature-256") ?? undefined;
112 const valid = yield* verifySignature(
113 resolved ? Redacted.value(resolved) : undefined,
114 body,
115 signature,
116 );
117 if (!valid) {
118 return new Response("invalid signature", { status: 401 });
119 }
120
121 const name = request.headers.get("x-github-event") ?? "unknown";
122 const id = request.headers.get("x-github-delivery") ?? "";
123
124 const payload: unknown = yield* Effect.try(() => JSON.parse(body) as unknown).pipe(
125 Effect.orElseSucceed(() => body),
126 );
127
128 // The wire shape matches `WebhookEvent`, but the runtime can't
129 // statically prove `name`/`payload` line up with a specific member of
130 // the discriminated union — GitHub's headers are the source of truth, so
131 // cast across the boundary.
132 const delivery = { id, name, payload } as unknown as WebhookEvent;
133
134 yield* process(delivery).pipe(Effect.orDie);
135
136 return new Response(null, { status: 202 });
137 });
138
139 const verifySignature = (
140 secret: string | undefined,
141 body: string,
142 signature: string | undefined,
143 ): Effect.Effect<boolean> =>
144 Effect.gen(function* () {
145 if (!secret || !signature || !signature.startsWith("sha256=")) {
146 return false;
147 }
148 const expected = yield* Effect.promise(async () => {
149 const encoder = new TextEncoder();
150 const key = await crypto.subtle.importKey(
151 "raw",
152 encoder.encode(secret),
153 { name: "HMAC", hash: "SHA-256" },
154 false,
155 ["sign"],
156 );
157 const digest = await crypto.subtle.sign("HMAC", key, encoder.encode(body));
158 const hex = Array.from(new Uint8Array(digest))
159 .map((byte) => byte.toString(16).padStart(2, "0"))
160 .join("");
161 return `sha256=${hex}`;
162 });
163 return timingSafeEqual(expected, signature);
164 });
165
166 /**
167 * Constant-time string comparison. Avoids leaking signature bytes through
168 * early-exit timing differences. `crypto.subtle.timingSafeEqual` isn't
169 * available on Workers without `nodejs_compat`, so we roll a small one.
170 */
171 const timingSafeEqual = (a: string, b: string): boolean => {
172 if (a.length !== b.length) return false;
173 let mismatch = 0;
174 for (let i = 0; i < a.length; i++) {
175 mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
176 }
177 return mismatch === 0;
178 };