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

main
ts 162 lines 6.09 KB
Raw
1 import { Webhooks } from "@distilled.cloud/stripe";
2 import { AlchemyContext } from "alchemy/AlchemyContext";
3 import * as Namespace from "alchemy/Namespace";
4 import * as Output from "alchemy/Output";
5 import { isRedactedMarker, RuntimeContext } from "alchemy/RuntimeContext";
6 import { WebhookHost } from "alchemy/WebhookHost";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import {
12 EventSource,
13 webhookPath,
14 webhookSecretEnvName,
15 type ConsumeEventsProps,
16 type EventSourceService,
17 } from "./ConsumeEvents.ts";
18 import type { StripeEventClass, StripeEventInstance } from "./Events.ts";
19 import { WebhookEndpoint } from "./WebhookEndpoint.ts";
20
21 /** A host that accepts environment bindings, such as a Cloudflare Worker. */
22 export interface EnvBindingHost {
23 readonly bind: (id: string, data: { env: Record<string, unknown> }) => Effect.Effect<void>;
24 }
25
26 /**
27 * Attach a webhook signing secret to a host's environment, under the key
28 * {@link consumeEvents} reads for `path`.
29 *
30 * {@link consumeEvents} binds the secret itself for the endpoint it
31 * provisions. Declare a {@link WebhookEndpoint} manually only when you need
32 * a URL you already own; then bind the minted secret yourself.
33 */
34 export const bindWebhookSecret = (
35 host: EnvBindingHost,
36 secret: WebhookEndpoint["secret"],
37 path?: string,
38 ): Effect.Effect<void> =>
39 host.bind(`stripe-webhook:${webhookPath(path)}`, {
40 env: {
41 [webhookSecretEnvName(path)]: secret,
42 },
43 });
44
45 /**
46 * {@link consumeEvents} on any {@link WebhookHost}.
47 *
48 * Deploy-time: provisions a {@link WebhookEndpoint} pointing at the host (at
49 * the subscribed path) and binds its minted signing secret so deliveries can
50 * be verified. Under `alchemy dev` the host is not publicly
51 * reachable, so no endpoint is provisioned. Runtime: claims requests on that
52 * path, verifies `Stripe-Signature`, and runs the handler once per event.
53 *
54 * Every Cloudflare Worker is a {@link WebhookHost}, so this is the only layer
55 * to provide.
56 *
57 * @layer
58 * @product Webhook
59 * @provides Stripe.EventSource
60 */
61 export const ConsumeEventsLive = Layer.effect(
62 EventSource,
63 Effect.gen(function* () {
64 const host = yield* WebhookHost;
65
66 return Effect.fn(function* (
67 id: string,
68 props: ConsumeEventsProps,
69 process: (event: StripeEventInstance) => Effect.Effect<void, never, never>,
70 ) {
71 // The signing secret is bound through the host's RuntimeContext, which
72 // every host provides its init, like `GitHub.RepositoryEventSourceLive`.
73 const runtime = yield* RuntimeContext;
74 const path = webhookPath(props.path);
75 const secretKey = webhookSecretEnvName(path);
76 const byType = new Map(props.events.map((event) => [event.type, event] as const));
77
78 if (!globalThis.__ALCHEMY_RUNTIME__) {
79 yield* Namespace.push(
80 host.LogicalId,
81 Effect.gen(function* () {
82 // Stripe only delivers to public URLs, and under `alchemy dev` the
83 // host is on localhost: skip the endpoint rather than fail the
84 // whole stack. Deliveries then answer 500 (no signing secret).
85 const context = yield* Effect.serviceOption(AlchemyContext);
86 if (Option.isSome(context) && context.value.dev) {
87 yield* Effect.logWarning(
88 `Stripe.consumeEvents: no webhook endpoint for ${path} under alchemy dev; Stripe only delivers to public URLs, so deploy to receive events.`,
89 );
90 return;
91 }
92 const endpoint = yield* WebhookEndpoint(id, {
93 url: Output.interpolate`${host.url}${path}`,
94 enabledEvents: [...props.events],
95 });
96 // A binding, not a prop: the endpoint depends on the host's URL.
97 yield* bindWebhookSecret(host, endpoint.secret, path);
98 }),
99 );
100 }
101
102 const secret = runtime.get<unknown>(secretKey);
103 yield* host.route(path, (request) => handleDelivery(request, secret, byType, process));
104 }) as EventSourceService;
105 }),
106 );
107
108 const asWebhookSecret = (raw: unknown): Redacted.Redacted<string> | undefined => {
109 if (raw === undefined || raw === null || raw === "") return undefined;
110 if (Redacted.isRedacted(raw)) {
111 const value = Redacted.value(raw);
112 return typeof value === "string" && value.length > 0
113 ? (raw as Redacted.Redacted<string>)
114 : undefined;
115 }
116 if (isRedactedMarker(raw) && typeof raw.value === "string") {
117 return raw.value.length > 0 ? Redacted.make(raw.value) : undefined;
118 }
119 if (typeof raw === "string") return Redacted.make(raw);
120 return undefined;
121 };
122
123 const handleDelivery = <Req>(
124 request: Request,
125 secret: Effect.Effect<unknown>,
126 byType: Map<string, StripeEventClass>,
127 process: (event: StripeEventInstance) => Effect.Effect<void, never, Req>,
128 ): Effect.Effect<Response, never, Req> =>
129 Effect.gen(function* () {
130 if (request.method !== "POST") {
131 return new Response("method not allowed", { status: 405 });
132 }
133 const payload = yield* Effect.promise(() => request.text());
134 const signature = request.headers.get("stripe-signature") ?? "";
135 const resolved = asWebhookSecret(yield* secret);
136 if (resolved === undefined) {
137 return new Response("webhook secret missing", { status: 500 });
138 }
139 const parsed = yield* Webhooks.constructEvent({
140 payload,
141 signature,
142 secret: Redacted.value(resolved),
143 }).pipe(
144 Effect.catchTag(
145 ["StripeWebhookSignatureError", "StripeWebhookPayloadParseError"],
146 () => Effect.undefined,
147 ),
148 );
149 if (parsed === undefined) {
150 return new Response("invalid signature", { status: 401 });
151 }
152 const Ctor = byType.get(parsed.type ?? "");
153 if (Ctor === undefined) {
154 return new Response(null, { status: 200 });
155 }
156 const data =
157 typeof parsed.data === "object" && parsed.data !== null && "object" in parsed.data
158 ? (parsed.data as { object: unknown }).object
159 : parsed.data;
160 yield* process(new Ctor(data as never)).pipe(Effect.orDie);
161 return new Response(null, { status: 200 });
162 });