Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Crypto from "effect/Crypto";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Redacted from "effect/Redacted";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import * as HttpClient from "effect/http/HttpClient";
13import type * as HttpServerRequest from "effect/http/HttpServerRequest";
14import * as HttpServerResponse from "effect/http/HttpServerResponse";
15import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
16import { EnvironmentId } from "@t3tools/contracts";
17import { RelayApi, type RelayHookDeliveryProofPayload } from "@t3tools/contracts/relay";
18import {
19 normalizeRelayIssuer,
20 RELAY_HOOK_DELIVERY_HEADER,
21 RELAY_HOOK_DELIVERY_TYP,
22 signRelayJwt,
23} from "@t3tools/shared/relayJwt";
24
25import * as RelayConfiguration from "../Config.ts";
26import { MANAGED_ENDPOINT_KEY_PATTERN } from "../deploymentConfig.ts";
27import * as HeldHooks from "./HeldHooks.ts";
28import * as HookInbox from "./HookInbox.ts";
29import { sendUpstream, TUNNEL_OFFLINE_STATUS } from "./upstream.ts";
30
31export const RELAY_HOOK_PATH_PREFIX = "/v1/hooks/";
32export const RELAY_HOOK_MAX_BODY_BYTES = 1_048_576;
33export const RELAY_HOOK_RATE_LIMIT = { limit: 60, periodSeconds: 60 } as const;
34/**
35 * Hook budgets are per URL, and a sender who knows an endpoint key can mint
36 * new URLs for free, so every endpoint also has one overall budget.
37 */
38export const RELAY_HOOK_ENDPOINT_RATE_LIMIT = { limit: 600, periodSeconds: 60 } as const;
39/**
40 * Upstream statuses that mean the environment did not take the request: the
41 * tunnel has no origin (530) or cloudflared cannot reach the local server
42 * (502, 503, 504) while it restarts.
43 */
44export const ENVIRONMENT_UNREACHABLE_STATUSES: ReadonlySet<number> = new Set([
45 502,
46 503,
47 504,
48 TUNNEL_OFFLINE_STATUS,
49]);
50
51const DROPPED_REQUEST_HEADERS = new Set([
52 "host",
53 "connection",
54 "keep-alive",
55 "transfer-encoding",
56 "te",
57 "upgrade",
58 "content-length",
59 "cookie",
60 "x-real-ip",
61 // Only the relay may set this; a sender could otherwise collide delivery ids.
62 "x-t3-relay-delivery-id",
63 "x-t3-relay-received-at",
64 RELAY_HOOK_DELIVERY_HEADER,
65 // The environment trusts trace context only from the relay, which sets its own.
66 "traceparent",
67 "tracestate",
68 "b3",
69]);
70const DROPPED_REQUEST_HEADER_PREFIXES = ["proxy-", "cf-", "x-forwarded-", "x-b3-"];
71
72export const isRelayHookPath = (url: string): boolean => url.startsWith(RELAY_HOOK_PATH_PREFIX);
73
74export const redactRelayHookUrl = (url: string): string => {
75 const path = url.split("?", 1)[0] ?? url;
76 const segments = path.split("/");
77 if (segments.length >= 6) {
78 segments[5] = "redacted";
79 }
80 return segments.join("/");
81};
82
83/**
84 * Requests with a wrong token get their own budget, so they cannot use up a
85 * real sender's; the environment rejects them. Built from decoded segments,
86 * because the environment decodes them too: two spellings of one token
87 * (`token`, `%74oken`) must share one budget.
88 */
89const hookBudgetKey = (hook: {
90 readonly endpointKey: string;
91 readonly hookId: string;
92 readonly token: string;
93}) =>
94 Effect.promise(() =>
95 crypto.subtle.digest(
96 "SHA-256",
97 // Length-prefixed, so no segment contents can make two keys collide.
98 new TextEncoder().encode(
99 [hook.endpointKey, hook.hookId, hook.token]
100 .map((part) => `${part.length}:${part}`)
101 .join(""),
102 ),
103 ),
104 ).pipe(
105 Effect.map((digest) =>
106 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
107 ),
108 );
109
110export class HookRateLimiter extends Context.Service<
111 HookRateLimiter,
112 {
113 readonly allowHook: (key: string) => Effect.Effect<boolean>;
114 readonly allowEndpoint: (endpointKey: string) => Effect.Effect<boolean>;
115 }
116>()("t3code-relay/hooks/HookForwarder/HookRateLimiter") {}
117
118export class HookForwarder extends Context.Service<
119 HookForwarder,
120 {
121 readonly handle: (
122 request: HttpServerRequest.HttpServerRequest,
123 ) => Effect.Effect<HttpServerResponse.HttpServerResponse>;
124 }
125>()("t3code-relay/hooks/HookForwarder") {}
126
127class HookBodyTooLarge extends Schema.TaggedError<HookBodyTooLarge>()("HookBodyTooLarge", {}) {}
128
129const errorResponse = (status: number, error: string, headers?: Record<string, string>) =>
130 HttpServerResponse.jsonUnsafe({ error }, { status, ...(headers ? { headers } : {}) });
131
132const hookNotFound = () => errorResponse(404, "hook_not_found");
133
134/** Longer than the inbox holds a request, so a held delivery's proof still verifies. */
135const DELIVERY_PROOF_LIFETIME_SECONDS = 25 * 60 * 60;
136
137/** Methods a webhook can arrive with; HEAD reaches the GET route and is refused. */
138const FORWARDED_METHODS = new Set(["GET", "POST", "PUT", "PATCH"]);
139
140/**
141 * Whatever the environment answers is served from the relay's own origin, so
142 * a body must never render or run there.
143 */
144const SANDBOXED_RESPONSE_HEADERS = {
145 "x-content-type-options": "nosniff",
146 "content-security-policy": "sandbox; default-src 'none'",
147} as const;
148
149function parseHookPath(url: string) {
150 const queryIndex = url.indexOf("?");
151 const path = queryIndex === -1 ? url : url.slice(0, queryIndex);
152 const search = queryIndex === -1 ? "" : url.slice(queryIndex);
153 const segments = path.split("/");
154 if (segments.length !== 6) return null;
155 const [, , , endpointKey, rawHookId, rawToken] = segments;
156 if (!endpointKey || !MANAGED_ENDPOINT_KEY_PATTERN.test(endpointKey) || !rawHookId || !rawToken) {
157 return null;
158 }
159 try {
160 return {
161 endpointKey,
162 hookId: decodeURIComponent(rawHookId),
163 token: decodeURIComponent(rawToken),
164 // Forward the encoded segments byte-for-byte; the environment decodes them.
165 rawHookId,
166 rawToken,
167 search,
168 };
169 } catch {
170 return null;
171 }
172}
173
174function forwardedHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {
175 const result: Record<string, string> = {};
176 // Headers the sender names in Connection are hop-by-hop too (RFC 9110 7.6.1).
177 const connectionValue =
178 Object.entries(headers).find(([name]) => name.toLowerCase() === "connection")?.[1] ?? "";
179 const nominated = new Set(
180 connectionValue
181 .split(",")
182 .map((name) => name.trim().toLowerCase())
183 .filter(Boolean),
184 );
185 for (const name in headers) {
186 const lower = name.toLowerCase();
187 if (
188 DROPPED_REQUEST_HEADERS.has(lower) ||
189 nominated.has(lower) ||
190 DROPPED_REQUEST_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))
191 ) {
192 continue;
193 }
194 const value = headers[name];
195 if (value !== undefined) result[lower] = value;
196 }
197 return result;
198}
199
200const hasNoBody = (request: HttpServerRequest.HttpServerRequest) =>
201 request.source instanceof Request && request.source.body === null;
202
203const readCappedBody = (request: HttpServerRequest.HttpServerRequest) =>
204 Effect.suspend(() => {
205 if (hasNoBody(request)) {
206 return Effect.succeed(new Uint8Array(0));
207 }
208 const chunks: Array<Uint8Array> = [];
209 let total = 0;
210 return request.stream.pipe(
211 Stream.runForEach((chunk) => {
212 total += chunk.length;
213 if (total > RELAY_HOOK_MAX_BODY_BYTES) {
214 return Effect.fail(new HookBodyTooLarge());
215 }
216 chunks.push(chunk);
217 return Effect.void;
218 }),
219 Effect.map(() => {
220 const body = new Uint8Array(total);
221 let offset = 0;
222 for (const chunk of chunks) {
223 body.set(chunk, offset);
224 offset += chunk.length;
225 }
226 return body;
227 }),
228 );
229 });
230
231const make = Effect.gen(function* () {
232 const heldHooks = yield* HeldHooks.HeldHooks;
233 const settings = yield* RelayConfiguration.RelayConfiguration;
234 const httpClient = yield* HttpClient.HttpClient;
235 const rateLimiter = yield* HookRateLimiter;
236 const inbox = yield* HookInbox.HookInbox;
237 const crypto = yield* Crypto.Crypto;
238
239 const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
240 function* (input: {
241 readonly environmentId: string;
242 readonly deliveryId: string;
243 readonly receivedAt: string;
244 readonly hookId: string;
245 readonly jti: string;
246 }) {
247 const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
248 return yield* signRelayJwt({
249 privateKey: Redacted.value(settings.cloudMintPrivateKey),
250 typ: RELAY_HOOK_DELIVERY_TYP,
251 payload: {
252 iss: normalizeRelayIssuer(settings.relayIssuer),
253 aud: `t3-env:${input.environmentId}`,
254 sub: input.environmentId,
255 jti: input.jti,
256 iat: now,
257 exp: now + DELIVERY_PROOF_LIFETIME_SECONDS,
258 environmentId: EnvironmentId.make(input.environmentId),
259 deliveryId: input.deliveryId,
260 receivedAt: input.receivedAt,
261 hookId: input.hookId,
262 } satisfies RelayHookDeliveryProofPayload,
263 });
264 },
265 (effect, _input) => effect.pipe(Effect.orDie),
266 );
267
268 const handle = Effect.fn("relay.hooks.forward")(function* (
269 request: HttpServerRequest.HttpServerRequest,
270 ) {
271 const outcome = (value: string) => Effect.annotateCurrentSpan({ "relay.hook.outcome": value });
272 if (!FORWARDED_METHODS.has(request.method)) {
273 yield* outcome("method_not_allowed");
274 return errorResponse(405, "method_not_allowed", { allow: "GET, POST, PUT, PATCH" });
275 }
276 const receivedAt = DateTime.formatIso(yield* DateTime.now);
277 const parsed = parseHookPath(request.url);
278 if (!parsed) {
279 yield* outcome("invalid_path");
280 return hookNotFound();
281 }
282 yield* Effect.annotateCurrentSpan({
283 "relay.hook.endpoint_key": parsed.endpointKey,
284 "relay.hook_id": parsed.hookId,
285 });
286 const endpointAllowed = yield* rateLimiter.allowEndpoint(parsed.endpointKey);
287 const hookAllowed =
288 endpointAllowed && (yield* rateLimiter.allowHook(yield* hookBudgetKey(parsed)));
289 if (!endpointAllowed || !hookAllowed) {
290 yield* Effect.annotateCurrentSpan({
291 "relay.hook.rate_limit": endpointAllowed ? "hook" : "endpoint",
292 });
293 yield* outcome("rate_limited");
294 return errorResponse(429, "rate_limited", {
295 "retry-after": String(RELAY_HOOK_RATE_LIMIT.periodSeconds),
296 });
297 }
298 const declaredLength = Number(request.headers["content-length"] ?? "0");
299 if (Number.isFinite(declaredLength) && declaredLength > RELAY_HOOK_MAX_BODY_BYTES) {
300 yield* outcome("payload_too_large");
301 return errorResponse(413, "payload_too_large");
302 }
303
304 const endpoint = yield* heldHooks.resolveEndpoint(parsed.endpointKey).pipe(
305 Effect.catch((error) =>
306 Effect.logWarning("Failed to resolve hook endpoint", {
307 endpointKey: parsed.endpointKey,
308 errorTag: error._tag,
309 }).pipe(Effect.as(null)),
310 ),
311 );
312 if (!endpoint) {
313 yield* outcome("not_found");
314 return hookNotFound();
315 }
316 yield* Effect.annotateCurrentSpan({
317 "relay.environment_id": endpoint.environmentId,
318 "relay.hook.hold_while_offline": endpoint.holdWhileOffline,
319 });
320
321 const body =
322 request.method === "GET"
323 ? Result.succeed(new Uint8Array(0))
324 : yield* readCappedBody(request).pipe(Effect.result);
325 if (Result.isFailure(body)) {
326 if (body.failure._tag === "HookBodyTooLarge") {
327 yield* outcome("payload_too_large");
328 return errorResponse(413, "payload_too_large");
329 }
330 yield* outcome("invalid_body");
331 return errorResponse(400, "invalid_body");
332 }
333
334 // One id per request, so a request that reached the environment before a
335 // timeout and is later delivered from the inbox runs only once.
336 yield* Effect.annotateCurrentSpan({ "relay.hook.body_bytes": body.success.byteLength });
337 const deliveryId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
338 // Proves to the environment that this delivery id, receive time and
339 // trace context came from the relay. Signed once here and stored with a
340 // held request, so the inbox never needs the signing key.
341 const proof = yield* signDeliveryProof({
342 environmentId: endpoint.environmentId,
343 deliveryId,
344 receivedAt,
345 hookId: parsed.hookId,
346 jti: yield* crypto.randomUUIDv4().pipe(Effect.orDie),
347 });
348 const hook = {
349 id: deliveryId,
350 receivedAt,
351 method: request.method,
352 rawHookId: parsed.rawHookId,
353 rawToken: parsed.rawToken,
354 hookKey: parsed.hookId,
355 query: parsed.search.replace(/^\?/, ""),
356 headers: { ...forwardedHeaders(request.headers), [RELAY_HOOK_DELIVERY_HEADER]: proof },
357 body: body.success,
358 };
359 // Keep offline outcomes on the enclosing relay.hooks.forward span.
360 const holdOrFail = Effect.fnUntraced(function* (status: 503 | 504, error: string) {
361 if (!endpoint.holdWhileOffline) {
362 yield* outcome(error);
363 return errorResponse(status, error);
364 }
365 const stored = yield* inbox
366 .hold({
367 endpointKey: parsed.endpointKey,
368 baseUrl: endpoint.httpBaseUrl,
369 hook,
370 })
371 .pipe(
372 Effect.catch((cause) =>
373 Effect.logWarning("Could not hold webhook request", {
374 environmentId: endpoint.environmentId,
375 errorTag: cause._tag,
376 }).pipe(Effect.as(null)),
377 ),
378 );
379 if (stored === null) {
380 yield* outcome(error);
381 return errorResponse(status, error);
382 }
383 if (!stored) {
384 yield* outcome("inbox_full");
385 return errorResponse(503, "inbox_full");
386 }
387 yield* outcome("held");
388 return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
389 });
390
391 const upstream = yield* sendUpstream(endpoint.httpBaseUrl, hook).pipe(
392 Effect.provideService(HttpClient.HttpClient, httpClient),
393 Effect.result,
394 );
395 if (Result.isFailure(upstream)) {
396 yield* Effect.annotateCurrentSpan({ "relay.hook.upstream_error": upstream.failure._tag });
397 return yield* holdOrFail(503, "environment_unavailable");
398 }
399 if (Option.isNone(upstream.success)) {
400 return yield* holdOrFail(504, "environment_timeout");
401 }
402 const response = upstream.success.value;
403 if (ENVIRONMENT_UNREACHABLE_STATUSES.has(response.status)) {
404 yield* Effect.annotateCurrentSpan({ "relay.hook.upstream_status": response.status });
405 return yield* holdOrFail(503, "environment_unavailable");
406 }
407 yield* Effect.annotateCurrentSpan({
408 "relay.hook.outcome": "forwarded",
409 "relay.hook.upstream_status": response.status,
410 ...(response.outcome === undefined
411 ? {}
412 : { "relay.hook.upstream_outcome": response.outcome }),
413 });
414 const headers = {
415 ...SANDBOXED_RESPONSE_HEADERS,
416 ...(response.contentType ? { "content-type": response.contentType } : {}),
417 };
418 if (response.body.length === 0) {
419 return HttpServerResponse.empty({ status: response.status, headers });
420 }
421 return HttpServerResponse.uint8Array(response.body, {
422 status: response.status,
423 headers,
424 ...(response.contentType ? { contentType: response.contentType } : {}),
425 });
426 });
427
428 return HookForwarder.of({ handle });
429});
430
431export const layer = Layer.effect(HookForwarder, make);
432
433export const layerApi = HttpApiBuilder.group(
434 RelayApi,
435 "hooks",
436 Effect.fnUntraced(function* (handlers) {
437 const forwarder = yield* HookForwarder;
438 const forward = ({ request }: { readonly request: HttpServerRequest.HttpServerRequest }) =>
439 forwarder.handle(request);
440 return handlers
441 .handleRaw("forwardPost", forward)
442 .handleRaw("forwardPut", forward)
443 .handleRaw("forwardPatch", forward)
444 .handleRaw("forwardGet", forward);
445 }),
446);