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/** 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 * The endpoint is raw so the signature is checked over the exact body
34 * bytes; the service checks the token and signature.
35 */
36 // Only verified relay deliveries join a trace; direct requests keep their existing context.
37 const handler = Effect.fnUntraced(function* ({
38 params,
39 request,
40 }: {
41 readonly params: { readonly hookId: string; readonly token: string };
42 readonly request: HttpServerRequest.HttpServerRequest;
43 }) {
44 const contentLength = Number(request.headers["content-length"] ?? "0");
45 if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
46 return json(413, { error: "body_too_large" }, "body_too_large");
47 }
48 // Chunked requests carry no content-length, so the reader itself is capped.
49 const body = yield* request.arrayBuffer.pipe(
50 Effect.map((buffer) => new Uint8Array(buffer)),
51 Effect.provideService(
52 HttpIncomingMessage.MaxBodySize,
53 ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
54 ),
55 Effect.option,
56 );
57 const tooLarge = (error: string) =>
58 Metrics.increment(Metrics.webhookDeliveriesTotal, {
59 outcome: "body_too_large",
60 source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",
61 }).pipe(Effect.as(json(413, { error }, "body_too_large")));
62 if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");
63 if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
64 return yield* tooLarge("body_too_large");
65 }
66
67 const headers: Record<string, string> = {};
68 for (const [name, value] of Object.entries(request.headers)) {
69 if (typeof value === "string") headers[name.toLowerCase()] = value;
70 }
71 const queryIndex = request.url.indexOf("?");
72 // The relay's delivery id and receive time count only with its signed
73 // proof; the URL can also be called directly. The receive time matters
74 // for requests the relay held while we were offline.
75 const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });
76 const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;
77 const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;
78
79 // A relay delivery joins the relay's trace, and goes to the T3 Connect
80 // tracer with it. Anyone else's traceparent is never trusted.
81 const relayParent = Option.isSome(relay)
82 ? HttpTraceContext.fromHeaders(request.headers)
83 : Option.none<Tracer.ExternalSpan>();
84 const result = yield* scheduledTasks
85 .triggerWebhook({
86 hookId: params.hookId,
87 token: params.token,
88 method: request.method,
89 path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
90 query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
91 headers,
92 body: body.value,
93 bodyText: new TextDecoder().decode(body.value),
94 ...(relayDeliveryId ? { relayDeliveryId } : {}),
95 ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),
96 })
97 .pipe(
98 Option.isSome(relayParent)
99 ? (effect) =>
100 effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)
101 : (effect) => effect,
102 Effect.catchCause((cause) =>
103 Effect.logWarning("Webhook delivery failed").pipe(
104 Effect.annotateLogs({ hookId: params.hookId }),
105 Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
106 Effect.as({ _tag: "error" as const }),
107 ),
108 ),
109 );
110
111 switch (result._tag) {
112 case "accepted":
113 return json(202, { deliveryId: result.deliveryId }, result.outcome);
114 case "not_found":
115 return json(404, { error: "hook_not_found" }, "not_found");
116 case "rejected_signature":
117 return json(401, { error: "invalid_signature" }, "rejected_signature");
118 case "disabled":
119 return json(409, { error: "hook_disabled" }, "disabled");
120 case "rate_limited":
121 return json(429, { error: "rate_limited" }, result.outcome);
122 case "expired":
123 return json(410, { error: "delivery_too_old" }, "expired");
124 case "error":
125 return json(500, { error: "internal_error" }, "error");
126 }
127 });
128 return handlers
129 .handleRaw("webhookPost", handler)
130 .handleRaw("webhookPut", handler)
131 .handleRaw("webhookPatch", handler)
132 .handleRaw("webhookGet", handler);
133 }),
134);