Open History to see the last commit
1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as ByteSize from "effect/ByteSize";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Tracer from "effect/Tracer";
6import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
7import type * as HttpServerRequest from "effect/http/HttpServerRequest";
8import * as HttpServerResponse from "effect/http/HttpServerResponse";
9import * as HttpTraceContext from "effect/http/HttpTraceContext";
10import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
11import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
12
13import * as Metrics from "../observability/Metrics.ts";
14import * as RelayDeliveryProof from "./RelayDeliveryProof.ts";
15import * as ScheduledTaskService from "./ScheduledTaskService.ts";
16
17/** Largest request body a webhook accepts. The relay enforces the same cap. */
18export const WEBHOOK_MAX_BODY_BYTES = 1024 * 1024;
19
20/** Response header naming what happened to the request; the relay records it. */
21const WEBHOOK_OUTCOME_HEADER = "x-t3-hook-outcome";
22
23const json = (status: number, body: Record<string, string>, outcome: string) =>
24 HttpServerResponse.jsonUnsafe(body, { status, headers: { [WEBHOOK_OUTCOME_HEADER]: outcome } });
25
26export const layer = HttpApiBuilder.group(
27 EnvironmentHttpApi,
28 "webhooks",
29 Effect.fnUntraced(function* (handlers) {
30 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
31 const relayDeliveryProof = yield* RelayDeliveryProof.RelayDeliveryProof;
32 /**
33 * Handles `/api/hooks/:hookId/:token` for every accepted method. The endpoint
34 * is raw so the signature is checked over the exact body bytes; the service
35 * checks the token and signature. It is reachable directly, over the managed
36 * tunnel, or through the relay's stable `/v1/hooks/:endpointKey/:hookId/:token`
37 * URL, where the endpoint key is this environment's managed tunnel key.
38 */
39 const handler = ({
40 params,
41 request,
42 }: {
43 readonly params: { readonly hookId: string; readonly token: string };
44 readonly request: HttpServerRequest.HttpServerRequest;
45 }) =>
46 Effect.gen(function* () {
47 const contentLength = Number(request.headers["content-length"] ?? "0");
48 if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
49 return json(413, { error: "body_too_large" }, "body_too_large");
50 }
51 // Chunked requests carry no content-length, so the reader itself is capped.
52 const body = yield* request.arrayBuffer.pipe(
53 Effect.map((buffer) => new Uint8Array(buffer)),
54 Effect.provideService(
55 HttpIncomingMessage.MaxBodySize,
56 ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
57 ),
58 Effect.option,
59 );
60 // Refused before a task is looked up, so the service never sees them.
61 const tooLarge = (error: string) =>
62 Metrics.increment(Metrics.webhookDeliveriesTotal, {
63 outcome: "body_too_large",
64 source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",
65 }).pipe(Effect.as(json(413, { error }, "body_too_large")));
66 if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");
67 if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
68 return yield* tooLarge("body_too_large");
69 }
70
71 const headers: Record<string, string> = {};
72 for (const [name, value] of Object.entries(request.headers)) {
73 if (typeof value === "string") headers[name.toLowerCase()] = value;
74 }
75 const queryIndex = request.url.indexOf("?");
76 // The relay's delivery id and receive time count only with its signed
77 // proof; the URL can also be called directly. The receive time matters
78 // for requests the relay held while we were offline.
79 const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });
80 const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;
81 const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;
82
83 // A relay delivery joins the relay's trace, and goes to the T3 Connect
84 // tracer with it. Anyone else's traceparent is never trusted.
85 const relayParent = Option.isSome(relay)
86 ? HttpTraceContext.fromHeaders(request.headers)
87 : Option.none<Tracer.ExternalSpan>();
88 const result = yield* scheduledTasks
89 .triggerWebhook({
90 hookId: params.hookId,
91 token: params.token,
92 method: request.method,
93 path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
94 query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
95 headers,
96 body: body.value,
97 bodyText: new TextDecoder().decode(body.value),
98 ...(relayDeliveryId ? { relayDeliveryId } : {}),
99 ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),
100 })
101 .pipe(
102 Option.isSome(relayParent)
103 ? (effect) =>
104 effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)
105 : (effect) => effect,
106 // Defects too, so the sender only ever sees the fixed error body.
107 Effect.catchCause((cause) =>
108 Effect.logWarning("Webhook delivery failed").pipe(
109 Effect.annotateLogs({ hookId: params.hookId }),
110 Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
111 Effect.as({ _tag: "error" as const }),
112 ),
113 ),
114 );
115
116 switch (result._tag) {
117 case "accepted":
118 return json(202, { deliveryId: result.deliveryId }, result.outcome);
119 case "not_found":
120 return json(404, { error: "hook_not_found" }, "not_found");
121 case "rejected_signature":
122 return json(401, { error: "invalid_signature" }, "rejected_signature");
123 case "disabled":
124 return json(409, { error: "hook_disabled" }, "disabled");
125 case "rate_limited":
126 return json(429, { error: "rate_limited" }, result.outcome);
127 case "expired":
128 return json(410, { error: "delivery_too_old" }, "expired");
129 case "error":
130 return json(500, { error: "internal_error" }, "error");
131 }
132 });
133 return handlers
134 .handleRaw("webhookPost", handler)
135 .handleRaw("webhookPut", handler)
136 .handleRaw("webhookPatch", handler)
137 .handleRaw("webhookGet", handler);
138 }),
139);