Open History to see the last commit
1import * as NodeDns from "node:dns";
2import * as NodeNet from "node:net";
3
4import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
5import * as Config from "effect/Config";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8
9/**
10 * Hosts that may receive webhooks although they are private or plain `http:`, for testing
11 * against a local receiver. Comma-separated host names or addresses; unset denies them all.
12 */
13export const ALLOWED_HOSTS_ENV = "T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS";
14
15export const allowedHosts = Config.String(ALLOWED_HOSTS_ENV).pipe(
16 Config.withDefault(""),
17 Config.map((value) => value.split(",").filter((host) => host.trim() !== "")),
18);
19
20export class WebhookAddressRejected extends Schema.TaggedError<WebhookAddressRejected>()(
21 "WebhookAddressRejected",
22 { message: Schema.String },
23) {}
24
25// The IANA special-purpose ranges that are not globally reachable. An IPv6 address must also be
26// in global unicast (2000::/3), which leaves out every form that embeds an IPv4 address. Two
27// lists, because a list checks an IPv4 address against its IPv4-mapped IPv6 rules too.
28const notGlobalV4 = new NodeNet.BlockList();
29for (const [network, prefix] of [
30 ["0.0.0.0", 8],
31 ["10.0.0.0", 8],
32 ["100.64.0.0", 10],
33 ["127.0.0.0", 8],
34 ["169.254.0.0", 16],
35 ["172.16.0.0", 12],
36 ["192.0.0.0", 24],
37 ["192.0.2.0", 24],
38 ["192.88.99.0", 24],
39 ["192.168.0.0", 16],
40 ["198.18.0.0", 15],
41 ["198.51.100.0", 24],
42 ["203.0.113.0", 24],
43 ["224.0.0.0", 4],
44 ["240.0.0.0", 4],
45] as const) {
46 notGlobalV4.addSubnet(network, prefix, "ipv4");
47}
48const globalUnicastV6 = new NodeNet.BlockList();
49globalUnicastV6.addSubnet("2000::", 3, "ipv6");
50const notGlobalV6 = new NodeNet.BlockList();
51for (const [network, prefix] of [
52 ["2001::", 23],
53 ["2001:db8::", 32],
54 ["2002::", 16],
55 ["3fff::", 20],
56] as const) {
57 notGlobalV6.addSubnet(network, prefix, "ipv6");
58}
59
60export const isGloballyRoutable = (address: string): boolean => {
61 const family = NodeNet.isIP(address);
62 if (family === 4) return !notGlobalV4.check(address, "ipv4");
63 return (
64 family === 6 && globalUnicastV6.check(address, "ipv6") && !notGlobalV6.check(address, "ipv6")
65 );
66};
67
68const hostOf = (url: URL) => url.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase();
69
70const resolveAll = (host: string) =>
71 Effect.callback<ReadonlyArray<NodeDns.LookupAddress>, Error>((resume) => {
72 NodeDns.lookup(host, { all: true }, (error, addresses) =>
73 resume(error === null ? Effect.succeed(addresses) : Effect.fail(error)),
74 );
75 });
76
77/**
78 * The webhook address check and the client deliveries go through. The client resolves again
79 * as it connects, to the address it checks, so DNS rebinding cannot reach a private address;
80 * TLS still sees the host name. Undici's dispatcher never follows redirects.
81 */
82export const make = (hosts: ReadonlyArray<string>) => {
83 const allowed = new Set(hosts.map((host) => host.trim().toLowerCase()));
84 const check = Effect.fn("McpWebhookTransport.check")(function* (url: URL) {
85 const host = hostOf(url);
86 if (allowed.has(host)) return;
87 const addresses =
88 NodeNet.isIP(host) !== 0
89 ? [host]
90 : (yield* resolveAll(host).pipe(
91 // A subscribe holds its slot while this runs, and a delivery's request timeout
92 // does not cover it, so a slow resolver counts as no answer.
93 Effect.timeout("5 seconds"),
94 Effect.mapError(
95 () => new WebhookAddressRejected({ message: `${host} could not be resolved` }),
96 ),
97 )).map((resolved) => resolved.address);
98 if (addresses.length === 0 || !addresses.every(isGloballyRoutable)) {
99 return yield* new WebhookAddressRejected({ message: `${host} is not a public address` });
100 }
101 });
102 const lookup: NodeNet.LookupFunction = (hostname, lookupOptions, callback) => {
103 NodeDns.lookup(hostname, { ...lookupOptions, all: true }, (error, addresses) => {
104 if (error !== null) return callback(error, "");
105 if (
106 !allowed.has(hostname.toLowerCase()) &&
107 (addresses.length === 0 ||
108 addresses.some((address) => !isGloballyRoutable(address.address)))
109 ) {
110 return callback(
111 Object.assign(new Error(`${hostname} is not a public address`), {
112 code: "ECONNREFUSED",
113 }),
114 "",
115 );
116 }
117 if (lookupOptions.all === true) return callback(null, addresses);
118 const [first] = addresses;
119 return callback(null, first!.address, first!.family);
120 });
121 };
122 return {
123 check,
124 allowsPlaintext: (url: URL) => allowed.has(hostOf(url)),
125 // The Undici client statically imports undici, which a single-executable cannot load.
126 layerClient: NodeHttpClient.layerNodeHttpOptions({ lookup }),
127 };
128};