@contember/engine-common 2.2.0-alpha.16 → 2.2.0-alpha.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/development/index.cjs +7 -0
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +8 -1
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/egress/EgressGuard.cjs +170 -0
  6. package/dist/development/src/egress/EgressGuard.cjs.map +1 -0
  7. package/dist/development/src/egress/EgressGuard.js +170 -0
  8. package/dist/development/src/egress/EgressGuard.js.map +1 -0
  9. package/dist/development/src/egress/EgressPolicy.cjs +110 -0
  10. package/dist/development/src/egress/EgressPolicy.cjs.map +1 -0
  11. package/dist/development/src/egress/EgressPolicy.js +110 -0
  12. package/dist/development/src/egress/EgressPolicy.js.map +1 -0
  13. package/dist/development/src/egress/createEgressGuard.cjs +7 -0
  14. package/dist/development/src/egress/createEgressGuard.cjs.map +1 -0
  15. package/dist/development/src/egress/createEgressGuard.js +7 -0
  16. package/dist/development/src/egress/createEgressGuard.js.map +1 -0
  17. package/dist/production/index.cjs +7 -0
  18. package/dist/production/index.cjs.map +1 -1
  19. package/dist/production/index.js +8 -1
  20. package/dist/production/index.js.map +1 -1
  21. package/dist/production/src/egress/EgressGuard.cjs +170 -0
  22. package/dist/production/src/egress/EgressGuard.cjs.map +1 -0
  23. package/dist/production/src/egress/EgressGuard.js +170 -0
  24. package/dist/production/src/egress/EgressGuard.js.map +1 -0
  25. package/dist/production/src/egress/EgressPolicy.cjs +110 -0
  26. package/dist/production/src/egress/EgressPolicy.cjs.map +1 -0
  27. package/dist/production/src/egress/EgressPolicy.js +110 -0
  28. package/dist/production/src/egress/EgressPolicy.js.map +1 -0
  29. package/dist/production/src/egress/createEgressGuard.cjs +7 -0
  30. package/dist/production/src/egress/createEgressGuard.cjs.map +1 -0
  31. package/dist/production/src/egress/createEgressGuard.js +7 -0
  32. package/dist/production/src/egress/createEgressGuard.js.map +1 -0
  33. package/dist/types/egress/EgressGuard.d.ts +37 -0
  34. package/dist/types/egress/EgressGuard.d.ts.map +1 -0
  35. package/dist/types/egress/EgressPolicy.d.ts +25 -0
  36. package/dist/types/egress/EgressPolicy.d.ts.map +1 -0
  37. package/dist/types/egress/createEgressGuard.d.ts +9 -0
  38. package/dist/types/egress/createEgressGuard.d.ts.map +1 -0
  39. package/dist/types/egress/index.d.ts +4 -0
  40. package/dist/types/egress/index.d.ts.map +1 -0
  41. package/dist/types/index.d.ts +1 -0
  42. package/dist/types/index.d.ts.map +1 -1
  43. package/dist/types/tsconfig.tsbuildinfo +1 -1
  44. package/package.json +2 -2
  45. package/src/egress/EgressGuard.ts +197 -0
  46. package/src/egress/EgressPolicy.ts +129 -0
  47. package/src/egress/createEgressGuard.ts +14 -0
  48. package/src/egress/index.ts +3 -0
  49. package/src/index.ts +1 -0
  50. package/tests/cases/egress/egressGuard.test.ts +147 -0
  51. package/tests/cases/egress/egressPolicy.test.ts +78 -0
@@ -4,8 +4,15 @@ const PromiseMap = require("./src/utils/PromiseMap.cjs");
4
4
  const Supervisor = require("./src/runnable/Supervisor.cjs");
5
5
  const events = require("./src/eventEmitter/events.cjs");
6
6
  const MigrationVersionHelper = require("./src/MigrationVersionHelper.cjs");
7
+ const EgressPolicy = require("./src/egress/EgressPolicy.cjs");
8
+ const EgressGuard = require("./src/egress/EgressGuard.cjs");
9
+ const createEgressGuard = require("./src/egress/createEgressGuard.cjs");
7
10
  exports.PromiseMap = PromiseMap.PromiseMap;
8
11
  exports.Supervisor = Supervisor.Supervisor;
9
12
  exports.EventManager = events.EventManager;
10
13
  exports.MigrationVersionHelper = MigrationVersionHelper.MigrationVersionHelper;
14
+ exports.EgressError = EgressPolicy.EgressError;
15
+ exports.EgressPolicy = EgressPolicy.EgressPolicy;
16
+ exports.EgressGuard = EgressGuard.EgressGuard;
17
+ exports.createEgressGuard = createEgressGuard.createEgressGuard;
11
18
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;"}
@@ -2,10 +2,17 @@ import { PromiseMap } from "./src/utils/PromiseMap.js";
2
2
  import { Supervisor } from "./src/runnable/Supervisor.js";
3
3
  import { EventManager } from "./src/eventEmitter/events.js";
4
4
  import { MigrationVersionHelper } from "./src/MigrationVersionHelper.js";
5
+ import { EgressError, EgressPolicy } from "./src/egress/EgressPolicy.js";
6
+ import { EgressGuard } from "./src/egress/EgressGuard.js";
7
+ import { createEgressGuard } from "./src/egress/createEgressGuard.js";
5
8
  export {
9
+ EgressError,
10
+ EgressGuard,
11
+ EgressPolicy,
6
12
  EventManager,
7
13
  MigrationVersionHelper,
8
14
  PromiseMap,
9
- Supervisor
15
+ Supervisor,
16
+ createEgressGuard
10
17
  };
11
18
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const node_dns = require("node:dns");
4
+ const http = require("node:http");
5
+ const https = require("node:https");
6
+ const EgressPolicy = require("./EgressPolicy.cjs");
7
+ var __defProp = Object.defineProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+ const REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
11
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
12
+ const MAX_REDIRECTS = 20;
13
+ const REQUEST_BODY_HEADERS = ["content-encoding", "content-language", "content-location", "content-type"];
14
+ const CREDENTIAL_HEADERS = ["authorization", "proxy-authorization", "cookie"];
15
+ class EgressGuard {
16
+ constructor(policy) {
17
+ this.policy = policy;
18
+ __publicField(this, "lookup");
19
+ __publicField(this, "httpsAgent");
20
+ __publicField(this, "httpAgent");
21
+ __publicField(this, "fetch", async (input, init) => {
22
+ let url = this.parseUrl(input);
23
+ let method = (init.method ?? "GET").toUpperCase();
24
+ let body = init.body;
25
+ const headers = new Headers(init.headers);
26
+ for (let redirects = 0; ; redirects++) {
27
+ const response = await this.request(url, method, headers, body, init.signal);
28
+ const location = response.headers.get("location");
29
+ if (!REDIRECT_STATUSES.has(response.status) || location === null || init.redirect === "manual") {
30
+ return response;
31
+ }
32
+ if (init.redirect === "error") {
33
+ throw new EgressPolicy.EgressError(`${url.origin} responded with a redirect`);
34
+ }
35
+ if (redirects >= MAX_REDIRECTS) {
36
+ throw new EgressPolicy.EgressError(`Too many redirects from ${url.origin}`);
37
+ }
38
+ const next = this.parseUrl(location, url);
39
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
40
+ method = "GET";
41
+ body = void 0;
42
+ for (const name of REQUEST_BODY_HEADERS) {
43
+ headers.delete(name);
44
+ }
45
+ }
46
+ if (next.origin !== url.origin) {
47
+ for (const name of CREDENTIAL_HEADERS) {
48
+ headers.delete(name);
49
+ }
50
+ }
51
+ url = next;
52
+ }
53
+ });
54
+ this.lookup = (hostname, options, callback) => {
55
+ node_dns.lookup(hostname, { family: options.family ?? 0, hints: options.hints, all: true }, (err, addresses) => {
56
+ if (err) {
57
+ callback(err, []);
58
+ return;
59
+ }
60
+ try {
61
+ if (addresses.length === 0) {
62
+ throw new EgressPolicy.EgressError(`${hostname} did not resolve`);
63
+ }
64
+ for (const address of addresses) {
65
+ this.policy.checkAddress(hostname, address.address);
66
+ }
67
+ } catch (e) {
68
+ callback(e instanceof Error ? e : new Error(String(e)), []);
69
+ return;
70
+ }
71
+ if (options.all) {
72
+ callback(null, addresses);
73
+ } else {
74
+ callback(null, addresses[0].address, addresses[0].family);
75
+ }
76
+ });
77
+ };
78
+ this.httpsAgent = new https.Agent({ keepAlive: false, lookup: this.lookup });
79
+ this.httpAgent = new http.Agent({ keepAlive: false, lookup: this.lookup });
80
+ }
81
+ /** Options for a client that issues its own `node:http(s)` requests; throws when the URL itself is not allowed. */
82
+ httpOptions(url) {
83
+ this.policy.checkUrl(url);
84
+ return {
85
+ agent: url.protocol === "https:" ? this.httpsAgent : this.httpAgent,
86
+ lookup: this.lookup
87
+ };
88
+ }
89
+ dispose() {
90
+ this.httpsAgent.destroy();
91
+ this.httpAgent.destroy();
92
+ }
93
+ parseUrl(value, base) {
94
+ let url;
95
+ try {
96
+ url = new URL(value, base);
97
+ } catch {
98
+ throw new EgressPolicy.EgressError("Invalid URL");
99
+ }
100
+ this.policy.checkUrl(url);
101
+ return url;
102
+ }
103
+ request(url, method, headers, body, signal) {
104
+ return new Promise((resolve, reject) => {
105
+ if (signal?.aborted) {
106
+ reject(signal.reason);
107
+ return;
108
+ }
109
+ const outgoingHeaders = Object.fromEntries(headers.entries());
110
+ if (body !== void 0) {
111
+ outgoingHeaders["content-length"] = String(Buffer.byteLength(body));
112
+ }
113
+ const isHttps = url.protocol === "https:";
114
+ let settled = false;
115
+ const onAbort = () => fail(signal?.reason);
116
+ const fail = (error) => {
117
+ if (settled) {
118
+ return;
119
+ }
120
+ settled = true;
121
+ signal?.removeEventListener("abort", onAbort);
122
+ req.destroy();
123
+ reject(error);
124
+ };
125
+ const req = (isHttps ? https : http).request(url, {
126
+ method,
127
+ headers: outgoingHeaders,
128
+ agent: isHttps ? this.httpsAgent : this.httpAgent,
129
+ lookup: this.lookup
130
+ }, (res) => {
131
+ const chunks = [];
132
+ res.on("data", (chunk) => chunks.push(chunk));
133
+ res.on("error", fail);
134
+ res.on("end", () => {
135
+ if (settled) {
136
+ return;
137
+ }
138
+ try {
139
+ const response = this.createResponse(res, Buffer.concat(chunks));
140
+ settled = true;
141
+ signal?.removeEventListener("abort", onAbort);
142
+ resolve(response);
143
+ } catch (e) {
144
+ fail(e);
145
+ }
146
+ });
147
+ });
148
+ signal?.addEventListener("abort", onAbort, { once: true });
149
+ req.on("error", fail);
150
+ req.end(body);
151
+ });
152
+ }
153
+ createResponse(res, body) {
154
+ const status = res.statusCode ?? 0;
155
+ if (status < 200 || status > 599) {
156
+ throw new EgressPolicy.EgressError(`Unexpected HTTP status ${status}`);
157
+ }
158
+ const headers = new Headers();
159
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
160
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
161
+ }
162
+ return new Response(NULL_BODY_STATUSES.has(status) ? null : new Uint8Array(body), {
163
+ status,
164
+ statusText: res.statusMessage ?? "",
165
+ headers
166
+ });
167
+ }
168
+ }
169
+ exports.EgressGuard = EgressGuard;
170
+ //# sourceMappingURL=EgressGuard.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EgressGuard.cjs","sources":["../../../../../packages/engine-common/src/egress/EgressGuard.ts"],"sourcesContent":["import { lookup as dnsLookup, LookupAddress } from 'node:dns'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { LookupFunction } from 'node:net'\nimport { EgressError, EgressPolicy } from './EgressPolicy.js'\n\nexport interface EgressRequestInit {\n\treadonly method?: string\n\treadonly headers?: HeadersInit\n\treadonly body?: string\n\treadonly signal?: AbortSignal\n\t/** As in `fetch`: `follow` (the default) re-checks every hop against the policy. */\n\treadonly redirect?: 'follow' | 'manual' | 'error'\n}\n\nexport type EgressFetch = (url: string, init: EgressRequestInit) => Promise<Response>\n\nexport interface EgressHttpOptions {\n\treadonly agent: http.Agent\n\treadonly lookup: LookupFunction\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])\nconst MAX_REDIRECTS = 20\nconst REQUEST_BODY_HEADERS = ['content-encoding', 'content-language', 'content-location', 'content-type']\nconst CREDENTIAL_HEADERS = ['authorization', 'proxy-authorization', 'cookie']\n\n/**\n * Outgoing HTTP to URLs chosen by tenants (webhooks, identity providers), under an {@link EgressPolicy}. Built over\n * `node:http(s)` with dedicated agents and a per-request `lookup` that checks every resolved address before connecting:\n * the global agent reuses keep-alive sockets, Bun ignores an agent's `lookup`, and `fetch` takes no `lookup` at all.\n */\nexport class EgressGuard {\n\tprivate readonly lookup: LookupFunction\n\tprivate readonly httpsAgent: https.Agent\n\tprivate readonly httpAgent: http.Agent\n\n\tconstructor(private readonly policy: EgressPolicy) {\n\t\tthis.lookup = (hostname, options, callback) => {\n\t\t\tdnsLookup(hostname, { family: options.family ?? 0, hints: options.hints, all: true }, (err, addresses: LookupAddress[]) => {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(err, [])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tif (addresses.length === 0) {\n\t\t\t\t\t\tthrow new EgressError(`${hostname} did not resolve`)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const address of addresses) {\n\t\t\t\t\t\tthis.policy.checkAddress(hostname, address.address)\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcallback(e instanceof Error ? e : new Error(String(e)), [])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (options.all) {\n\t\t\t\t\tcallback(null, addresses)\n\t\t\t\t} else {\n\t\t\t\t\tcallback(null, addresses[0].address, addresses[0].family)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tthis.httpsAgent = new https.Agent({ keepAlive: false, lookup: this.lookup })\n\t\tthis.httpAgent = new http.Agent({ keepAlive: false, lookup: this.lookup })\n\t}\n\n\t/** Options for a client that issues its own `node:http(s)` requests; throws when the URL itself is not allowed. */\n\tpublic httpOptions(url: URL): EgressHttpOptions {\n\t\tthis.policy.checkUrl(url)\n\t\treturn {\n\t\t\tagent: url.protocol === 'https:' ? this.httpsAgent : this.httpAgent,\n\t\t\tlookup: this.lookup,\n\t\t}\n\t}\n\n\t/** A `fetch` subset that buffers the response body. Redirects follow `fetch` semantics, each hop re-checked. */\n\tpublic readonly fetch: EgressFetch = async (input, init) => {\n\t\tlet url = this.parseUrl(input)\n\t\tlet method = (init.method ?? 'GET').toUpperCase()\n\t\tlet body = init.body\n\t\tconst headers = new Headers(init.headers)\n\t\tfor (let redirects = 0;; redirects++) {\n\t\t\tconst response = await this.request(url, method, headers, body, init.signal)\n\t\t\tconst location = response.headers.get('location')\n\t\t\tif (!REDIRECT_STATUSES.has(response.status) || location === null || init.redirect === 'manual') {\n\t\t\t\treturn response\n\t\t\t}\n\t\t\tif (init.redirect === 'error') {\n\t\t\t\tthrow new EgressError(`${url.origin} responded with a redirect`)\n\t\t\t}\n\t\t\tif (redirects >= MAX_REDIRECTS) {\n\t\t\t\tthrow new EgressError(`Too many redirects from ${url.origin}`)\n\t\t\t}\n\t\t\tconst next = this.parseUrl(location, url)\n\t\t\tif (\n\t\t\t\t((response.status === 301 || response.status === 302) && method === 'POST')\n\t\t\t\t|| (response.status === 303 && method !== 'GET' && method !== 'HEAD')\n\t\t\t) {\n\t\t\t\tmethod = 'GET'\n\t\t\t\tbody = undefined\n\t\t\t\tfor (const name of REQUEST_BODY_HEADERS) {\n\t\t\t\t\theaders.delete(name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (next.origin !== url.origin) {\n\t\t\t\tfor (const name of CREDENTIAL_HEADERS) {\n\t\t\t\t\theaders.delete(name)\n\t\t\t\t}\n\t\t\t}\n\t\t\turl = next\n\t\t}\n\t}\n\n\tpublic dispose(): void {\n\t\tthis.httpsAgent.destroy()\n\t\tthis.httpAgent.destroy()\n\t}\n\n\tprivate parseUrl(value: string, base?: URL): URL {\n\t\tlet url: URL\n\t\ttry {\n\t\t\turl = new URL(value, base)\n\t\t} catch {\n\t\t\tthrow new EgressError('Invalid URL')\n\t\t}\n\t\tthis.policy.checkUrl(url)\n\t\treturn url\n\t}\n\n\tprivate request(url: URL, method: string, headers: Headers, body: string | undefined, signal: AbortSignal | undefined): Promise<Response> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (signal?.aborted) {\n\t\t\t\treject(signal.reason)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst outgoingHeaders: Record<string, string> = Object.fromEntries(headers.entries())\n\t\t\tif (body !== undefined) {\n\t\t\t\toutgoingHeaders['content-length'] = String(Buffer.byteLength(body))\n\t\t\t}\n\t\t\tconst isHttps = url.protocol === 'https:'\n\t\t\tlet settled = false\n\t\t\tconst onAbort = () => fail(signal?.reason)\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsettled = true\n\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\treq.destroy()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst req = (isHttps ? https : http).request(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders: outgoingHeaders,\n\t\t\t\tagent: isHttps ? this.httpsAgent : this.httpAgent,\n\t\t\t\tlookup: this.lookup,\n\t\t\t}, res => {\n\t\t\t\tconst chunks: Buffer[] = []\n\t\t\t\tres.on('data', (chunk: Buffer) => chunks.push(chunk))\n\t\t\t\tres.on('error', fail)\n\t\t\t\tres.on('end', () => {\n\t\t\t\t\tif (settled) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst response = this.createResponse(res, Buffer.concat(chunks))\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\t\t\tresolve(response)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tfail(e)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tsignal?.addEventListener('abort', onAbort, { once: true })\n\t\t\treq.on('error', fail)\n\t\t\treq.end(body)\n\t\t})\n\t}\n\n\tprivate createResponse(res: http.IncomingMessage, body: Buffer): Response {\n\t\tconst status = res.statusCode ?? 0\n\t\tif (status < 200 || status > 599) {\n\t\t\tthrow new EgressError(`Unexpected HTTP status ${status}`)\n\t\t}\n\t\tconst headers = new Headers()\n\t\tfor (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {\n\t\t\theaders.append(res.rawHeaders[i], res.rawHeaders[i + 1])\n\t\t}\n\t\treturn new Response(NULL_BODY_STATUSES.has(status) ? null : new Uint8Array(body), {\n\t\t\tstatus,\n\t\t\tstatusText: res.statusMessage ?? '',\n\t\t\theaders,\n\t\t})\n\t}\n}\n"],"names":["EgressError","dnsLookup"],"mappings":";;;;;;;;;AAsBA,MAAM,wCAAwB,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAC3D,MAAM,yCAAyB,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAC5D,MAAM,gBAAgB;AACtB,MAAM,uBAAuB,CAAC,oBAAoB,oBAAoB,oBAAoB,cAAc;AACxG,MAAM,qBAAqB,CAAC,iBAAiB,uBAAuB,QAAQ;AAOrE,MAAM,YAAY;AAAA,EAKxB,YAA6B,QAAsB;AAAtB,SAAA,SAAA;AAJ7B,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,YAAA;AACjB,kBAAA,MAAiB,WAAA;AAyCjB,kBAAA,MAAgB,SAAqB,OAAO,OAAO,SAAS;AAC3D,UAAI,MAAM,KAAK,SAAS,KAAK;AAC7B,UAAI,UAAU,KAAK,UAAU,OAAO,YAAA;AACpC,UAAI,OAAO,KAAK;AAChB,YAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;AACxC,eAAS,YAAY,KAAI,aAAa;AACrC,cAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,QAAQ,SAAS,MAAM,KAAK,MAAM;AAC3E,cAAM,WAAW,SAAS,Q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AAmB,IAAI,MAAM,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAAA,MACjF;AAAA,MACA,YAAY,IAAI,iBAAiB;AAAA,MACjC;AAAA,IAAA,CACA;AAAA,EACF;AACD;;"}
@@ -0,0 +1,170 @@
1
+ import { lookup } from "node:dns";
2
+ import http__default from "node:http";
3
+ import https from "node:https";
4
+ import { EgressError } from "./EgressPolicy.js";
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ const REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
9
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
10
+ const MAX_REDIRECTS = 20;
11
+ const REQUEST_BODY_HEADERS = ["content-encoding", "content-language", "content-location", "content-type"];
12
+ const CREDENTIAL_HEADERS = ["authorization", "proxy-authorization", "cookie"];
13
+ class EgressGuard {
14
+ constructor(policy) {
15
+ this.policy = policy;
16
+ __publicField(this, "lookup");
17
+ __publicField(this, "httpsAgent");
18
+ __publicField(this, "httpAgent");
19
+ __publicField(this, "fetch", async (input, init) => {
20
+ let url = this.parseUrl(input);
21
+ let method = (init.method ?? "GET").toUpperCase();
22
+ let body = init.body;
23
+ const headers = new Headers(init.headers);
24
+ for (let redirects = 0; ; redirects++) {
25
+ const response = await this.request(url, method, headers, body, init.signal);
26
+ const location = response.headers.get("location");
27
+ if (!REDIRECT_STATUSES.has(response.status) || location === null || init.redirect === "manual") {
28
+ return response;
29
+ }
30
+ if (init.redirect === "error") {
31
+ throw new EgressError(`${url.origin} responded with a redirect`);
32
+ }
33
+ if (redirects >= MAX_REDIRECTS) {
34
+ throw new EgressError(`Too many redirects from ${url.origin}`);
35
+ }
36
+ const next = this.parseUrl(location, url);
37
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
38
+ method = "GET";
39
+ body = void 0;
40
+ for (const name of REQUEST_BODY_HEADERS) {
41
+ headers.delete(name);
42
+ }
43
+ }
44
+ if (next.origin !== url.origin) {
45
+ for (const name of CREDENTIAL_HEADERS) {
46
+ headers.delete(name);
47
+ }
48
+ }
49
+ url = next;
50
+ }
51
+ });
52
+ this.lookup = (hostname, options, callback) => {
53
+ lookup(hostname, { family: options.family ?? 0, hints: options.hints, all: true }, (err, addresses) => {
54
+ if (err) {
55
+ callback(err, []);
56
+ return;
57
+ }
58
+ try {
59
+ if (addresses.length === 0) {
60
+ throw new EgressError(`${hostname} did not resolve`);
61
+ }
62
+ for (const address of addresses) {
63
+ this.policy.checkAddress(hostname, address.address);
64
+ }
65
+ } catch (e) {
66
+ callback(e instanceof Error ? e : new Error(String(e)), []);
67
+ return;
68
+ }
69
+ if (options.all) {
70
+ callback(null, addresses);
71
+ } else {
72
+ callback(null, addresses[0].address, addresses[0].family);
73
+ }
74
+ });
75
+ };
76
+ this.httpsAgent = new https.Agent({ keepAlive: false, lookup: this.lookup });
77
+ this.httpAgent = new http__default.Agent({ keepAlive: false, lookup: this.lookup });
78
+ }
79
+ /** Options for a client that issues its own `node:http(s)` requests; throws when the URL itself is not allowed. */
80
+ httpOptions(url) {
81
+ this.policy.checkUrl(url);
82
+ return {
83
+ agent: url.protocol === "https:" ? this.httpsAgent : this.httpAgent,
84
+ lookup: this.lookup
85
+ };
86
+ }
87
+ dispose() {
88
+ this.httpsAgent.destroy();
89
+ this.httpAgent.destroy();
90
+ }
91
+ parseUrl(value, base) {
92
+ let url;
93
+ try {
94
+ url = new URL(value, base);
95
+ } catch {
96
+ throw new EgressError("Invalid URL");
97
+ }
98
+ this.policy.checkUrl(url);
99
+ return url;
100
+ }
101
+ request(url, method, headers, body, signal) {
102
+ return new Promise((resolve, reject) => {
103
+ if (signal?.aborted) {
104
+ reject(signal.reason);
105
+ return;
106
+ }
107
+ const outgoingHeaders = Object.fromEntries(headers.entries());
108
+ if (body !== void 0) {
109
+ outgoingHeaders["content-length"] = String(Buffer.byteLength(body));
110
+ }
111
+ const isHttps = url.protocol === "https:";
112
+ let settled = false;
113
+ const onAbort = () => fail(signal?.reason);
114
+ const fail = (error) => {
115
+ if (settled) {
116
+ return;
117
+ }
118
+ settled = true;
119
+ signal?.removeEventListener("abort", onAbort);
120
+ req.destroy();
121
+ reject(error);
122
+ };
123
+ const req = (isHttps ? https : http__default).request(url, {
124
+ method,
125
+ headers: outgoingHeaders,
126
+ agent: isHttps ? this.httpsAgent : this.httpAgent,
127
+ lookup: this.lookup
128
+ }, (res) => {
129
+ const chunks = [];
130
+ res.on("data", (chunk) => chunks.push(chunk));
131
+ res.on("error", fail);
132
+ res.on("end", () => {
133
+ if (settled) {
134
+ return;
135
+ }
136
+ try {
137
+ const response = this.createResponse(res, Buffer.concat(chunks));
138
+ settled = true;
139
+ signal?.removeEventListener("abort", onAbort);
140
+ resolve(response);
141
+ } catch (e) {
142
+ fail(e);
143
+ }
144
+ });
145
+ });
146
+ signal?.addEventListener("abort", onAbort, { once: true });
147
+ req.on("error", fail);
148
+ req.end(body);
149
+ });
150
+ }
151
+ createResponse(res, body) {
152
+ const status = res.statusCode ?? 0;
153
+ if (status < 200 || status > 599) {
154
+ throw new EgressError(`Unexpected HTTP status ${status}`);
155
+ }
156
+ const headers = new Headers();
157
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
158
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
159
+ }
160
+ return new Response(NULL_BODY_STATUSES.has(status) ? null : new Uint8Array(body), {
161
+ status,
162
+ statusText: res.statusMessage ?? "",
163
+ headers
164
+ });
165
+ }
166
+ }
167
+ export {
168
+ EgressGuard
169
+ };
170
+ //# sourceMappingURL=EgressGuard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EgressGuard.js","sources":["../../../../../packages/engine-common/src/egress/EgressGuard.ts"],"sourcesContent":["import { lookup as dnsLookup, LookupAddress } from 'node:dns'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { LookupFunction } from 'node:net'\nimport { EgressError, EgressPolicy } from './EgressPolicy.js'\n\nexport interface EgressRequestInit {\n\treadonly method?: string\n\treadonly headers?: HeadersInit\n\treadonly body?: string\n\treadonly signal?: AbortSignal\n\t/** As in `fetch`: `follow` (the default) re-checks every hop against the policy. */\n\treadonly redirect?: 'follow' | 'manual' | 'error'\n}\n\nexport type EgressFetch = (url: string, init: EgressRequestInit) => Promise<Response>\n\nexport interface EgressHttpOptions {\n\treadonly agent: http.Agent\n\treadonly lookup: LookupFunction\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])\nconst MAX_REDIRECTS = 20\nconst REQUEST_BODY_HEADERS = ['content-encoding', 'content-language', 'content-location', 'content-type']\nconst CREDENTIAL_HEADERS = ['authorization', 'proxy-authorization', 'cookie']\n\n/**\n * Outgoing HTTP to URLs chosen by tenants (webhooks, identity providers), under an {@link EgressPolicy}. Built over\n * `node:http(s)` with dedicated agents and a per-request `lookup` that checks every resolved address before connecting:\n * the global agent reuses keep-alive sockets, Bun ignores an agent's `lookup`, and `fetch` takes no `lookup` at all.\n */\nexport class EgressGuard {\n\tprivate readonly lookup: LookupFunction\n\tprivate readonly httpsAgent: https.Agent\n\tprivate readonly httpAgent: http.Agent\n\n\tconstructor(private readonly policy: EgressPolicy) {\n\t\tthis.lookup = (hostname, options, callback) => {\n\t\t\tdnsLookup(hostname, { family: options.family ?? 0, hints: options.hints, all: true }, (err, addresses: LookupAddress[]) => {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(err, [])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tif (addresses.length === 0) {\n\t\t\t\t\t\tthrow new EgressError(`${hostname} did not resolve`)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const address of addresses) {\n\t\t\t\t\t\tthis.policy.checkAddress(hostname, address.address)\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcallback(e instanceof Error ? e : new Error(String(e)), [])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (options.all) {\n\t\t\t\t\tcallback(null, addresses)\n\t\t\t\t} else {\n\t\t\t\t\tcallback(null, addresses[0].address, addresses[0].family)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tthis.httpsAgent = new https.Agent({ keepAlive: false, lookup: this.lookup })\n\t\tthis.httpAgent = new http.Agent({ keepAlive: false, lookup: this.lookup })\n\t}\n\n\t/** Options for a client that issues its own `node:http(s)` requests; throws when the URL itself is not allowed. */\n\tpublic httpOptions(url: URL): EgressHttpOptions {\n\t\tthis.policy.checkUrl(url)\n\t\treturn {\n\t\t\tagent: url.protocol === 'https:' ? this.httpsAgent : this.httpAgent,\n\t\t\tlookup: this.lookup,\n\t\t}\n\t}\n\n\t/** A `fetch` subset that buffers the response body. Redirects follow `fetch` semantics, each hop re-checked. */\n\tpublic readonly fetch: EgressFetch = async (input, init) => {\n\t\tlet url = this.parseUrl(input)\n\t\tlet method = (init.method ?? 'GET').toUpperCase()\n\t\tlet body = init.body\n\t\tconst headers = new Headers(init.headers)\n\t\tfor (let redirects = 0;; redirects++) {\n\t\t\tconst response = await this.request(url, method, headers, body, init.signal)\n\t\t\tconst location = response.headers.get('location')\n\t\t\tif (!REDIRECT_STATUSES.has(response.status) || location === null || init.redirect === 'manual') {\n\t\t\t\treturn response\n\t\t\t}\n\t\t\tif (init.redirect === 'error') {\n\t\t\t\tthrow new EgressError(`${url.origin} responded with a redirect`)\n\t\t\t}\n\t\t\tif (redirects >= MAX_REDIRECTS) {\n\t\t\t\tthrow new EgressError(`Too many redirects from ${url.origin}`)\n\t\t\t}\n\t\t\tconst next = this.parseUrl(location, url)\n\t\t\tif (\n\t\t\t\t((response.status === 301 || response.status === 302) && method === 'POST')\n\t\t\t\t|| (response.status === 303 && method !== 'GET' && method !== 'HEAD')\n\t\t\t) {\n\t\t\t\tmethod = 'GET'\n\t\t\t\tbody = undefined\n\t\t\t\tfor (const name of REQUEST_BODY_HEADERS) {\n\t\t\t\t\theaders.delete(name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (next.origin !== url.origin) {\n\t\t\t\tfor (const name of CREDENTIAL_HEADERS) {\n\t\t\t\t\theaders.delete(name)\n\t\t\t\t}\n\t\t\t}\n\t\t\turl = next\n\t\t}\n\t}\n\n\tpublic dispose(): void {\n\t\tthis.httpsAgent.destroy()\n\t\tthis.httpAgent.destroy()\n\t}\n\n\tprivate parseUrl(value: string, base?: URL): URL {\n\t\tlet url: URL\n\t\ttry {\n\t\t\turl = new URL(value, base)\n\t\t} catch {\n\t\t\tthrow new EgressError('Invalid URL')\n\t\t}\n\t\tthis.policy.checkUrl(url)\n\t\treturn url\n\t}\n\n\tprivate request(url: URL, method: string, headers: Headers, body: string | undefined, signal: AbortSignal | undefined): Promise<Response> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (signal?.aborted) {\n\t\t\t\treject(signal.reason)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst outgoingHeaders: Record<string, string> = Object.fromEntries(headers.entries())\n\t\t\tif (body !== undefined) {\n\t\t\t\toutgoingHeaders['content-length'] = String(Buffer.byteLength(body))\n\t\t\t}\n\t\t\tconst isHttps = url.protocol === 'https:'\n\t\t\tlet settled = false\n\t\t\tconst onAbort = () => fail(signal?.reason)\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsettled = true\n\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\treq.destroy()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst req = (isHttps ? https : http).request(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders: outgoingHeaders,\n\t\t\t\tagent: isHttps ? this.httpsAgent : this.httpAgent,\n\t\t\t\tlookup: this.lookup,\n\t\t\t}, res => {\n\t\t\t\tconst chunks: Buffer[] = []\n\t\t\t\tres.on('data', (chunk: Buffer) => chunks.push(chunk))\n\t\t\t\tres.on('error', fail)\n\t\t\t\tres.on('end', () => {\n\t\t\t\t\tif (settled) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst response = this.createResponse(res, Buffer.concat(chunks))\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\t\t\tresolve(response)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tfail(e)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tsignal?.addEventListener('abort', onAbort, { once: true })\n\t\t\treq.on('error', fail)\n\t\t\treq.end(body)\n\t\t})\n\t}\n\n\tprivate createResponse(res: http.IncomingMessage, body: Buffer): Response {\n\t\tconst status = res.statusCode ?? 0\n\t\tif (status < 200 || status > 599) {\n\t\t\tthrow new EgressError(`Unexpected HTTP status ${status}`)\n\t\t}\n\t\tconst headers = new Headers()\n\t\tfor (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {\n\t\t\theaders.append(res.rawHeaders[i], res.rawHeaders[i + 1])\n\t\t}\n\t\treturn new Response(NULL_BODY_STATUSES.has(status) ? null : new Uint8Array(body), {\n\t\t\tstatus,\n\t\t\tstatusText: res.statusMessage ?? '',\n\t\t\theaders,\n\t\t})\n\t}\n}\n"],"names":["dnsLookup","http"],"mappings":";;;;;;;AAsBA,MAAM,wCAAwB,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAC3D,MAAM,yCAAyB,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAC5D,MAAM,gBAAgB;AACtB,MAAM,uBAAuB,CAAC,oBAAoB,oBAAoB,oBAAoB,cAAc;AACxG,MAAM,qBAAqB,CAAC,iBAAiB,u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zD,UAAI,GAAG,SAAS,IAAI;AACpB,UAAI,IAAI,IAAI;AAAA,IACb,CAAC;AAAA,EACF;AAAA,EAEQ,eAAe,KAA2B,MAAwB;AACzE,UAAM,SAAS,IAAI,cAAc;AACjC,QAAI,SAAS,OAAO,SAAS,KAAK;AACjC,YAAM,IAAI,YAAY,0BAA0B,MAAM,EAAE;AAAA,IACzD;AACA,UAAM,UAAU,IAAI,QAAA;AACpB,aAAS,IAAI,GAAG,IAAI,IAAI,IAAI,WAAW,QAAQ,KAAK,GAAG;AACtD,cAAQ,OAAO,IAAI,WAAW,CAAC,GAAG,IAAI,WAAW,IAAI,CAAC,CAAC;AAAA,IACxD;AACA,WAAO,IAAI,SAAS,mBAAmB,IAAI,MAAM,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAAA,MACjF;AAAA,MACA,YAAY,IAAI,iBAAiB;AAAA,MACjC;AAAA,IAAA,CACA;AAAA,EACF;AACD;"}
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const node_net = require("node:net");
4
+ var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ const SPECIAL_PURPOSE_IPV4 = [
8
+ ["0.0.0.0", 8],
9
+ ["10.0.0.0", 8],
10
+ ["100.64.0.0", 10],
11
+ ["127.0.0.0", 8],
12
+ ["169.254.0.0", 16],
13
+ ["172.16.0.0", 12],
14
+ ["192.0.0.0", 24],
15
+ ["192.0.2.0", 24],
16
+ ["192.88.99.0", 24],
17
+ ["192.168.0.0", 16],
18
+ ["198.18.0.0", 15],
19
+ ["198.51.100.0", 24],
20
+ ["203.0.113.0", 24],
21
+ ["224.0.0.0", 4],
22
+ ["240.0.0.0", 4]
23
+ ];
24
+ const GLOBAL_UNICAST_IPV6 = ["2000::", 3];
25
+ const SPECIAL_PURPOSE_IPV6 = [
26
+ ["2001::", 23],
27
+ ["2001:db8::", 32],
28
+ ["2002::", 16],
29
+ ["3fff::", 20]
30
+ ];
31
+ const normalizeHost = (host) => host.toLowerCase().replace(/^\[(.*)]$/, "$1").replace(/\.$/, "");
32
+ const ipFamily = (address) => {
33
+ const version = node_net.isIP(address);
34
+ return version === 4 ? "ipv4" : version === 6 ? "ipv6" : null;
35
+ };
36
+ class EgressError extends Error {
37
+ }
38
+ class EgressPolicy {
39
+ constructor(config) {
40
+ __publicField(this, "specialPurpose", new node_net.BlockList());
41
+ __publicField(this, "globalUnicastIpv6", new node_net.BlockList());
42
+ __publicField(this, "allowedNetworks", new node_net.BlockList());
43
+ __publicField(this, "allowedHosts");
44
+ __publicField(this, "allowHttp");
45
+ for (const [network, prefix] of SPECIAL_PURPOSE_IPV4) {
46
+ this.specialPurpose.addSubnet(network, prefix, "ipv4");
47
+ }
48
+ for (const [network, prefix] of SPECIAL_PURPOSE_IPV6) {
49
+ this.specialPurpose.addSubnet(network, prefix, "ipv6");
50
+ }
51
+ this.globalUnicastIpv6.addSubnet(GLOBAL_UNICAST_IPV6[0], GLOBAL_UNICAST_IPV6[1], "ipv6");
52
+ const allowedHosts = /* @__PURE__ */ new Set();
53
+ for (const entry of config.allowlist) {
54
+ const [network, prefixText, ...rest] = entry.trim().split("/");
55
+ const family = ipFamily(network);
56
+ if (family === null) {
57
+ if (prefixText !== void 0 || network === "") {
58
+ throw new EgressError(`Invalid egress allowlist entry ${entry}`);
59
+ }
60
+ allowedHosts.add(normalizeHost(network));
61
+ continue;
62
+ }
63
+ const maxPrefix = family === "ipv4" ? 32 : 128;
64
+ if (rest.length > 0 || prefixText !== void 0 && !/^\d{1,3}$/.test(prefixText)) {
65
+ throw new EgressError(`Invalid egress allowlist entry ${entry}`);
66
+ }
67
+ const prefix = prefixText === void 0 ? maxPrefix : Number(prefixText);
68
+ if (prefix > maxPrefix) {
69
+ throw new EgressError(`Invalid egress allowlist entry ${entry}`);
70
+ }
71
+ this.allowedNetworks.addSubnet(network, prefix, family);
72
+ }
73
+ this.allowedHosts = allowedHosts;
74
+ this.allowHttp = config.allowHttp;
75
+ }
76
+ /** Throws unless the URL may be fetched; an IP-literal host is checked here because no lookup will run for it. */
77
+ checkUrl(url) {
78
+ const host = normalizeHost(url.hostname);
79
+ if (url.username !== "" || url.password !== "") {
80
+ throw new EgressError("Outgoing request URLs must not carry credentials");
81
+ }
82
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && this.allowHttp)) {
83
+ throw new EgressError(`Only https:// URLs are allowed, got ${url.protocol}//${host}`);
84
+ }
85
+ if (ipFamily(host) !== null) {
86
+ this.checkAddress(host, host);
87
+ }
88
+ }
89
+ /** Throws unless a connection to `address`, resolved from `host`, is allowed. */
90
+ checkAddress(host, address) {
91
+ const normalizedHost = normalizeHost(host);
92
+ if (this.allowedHosts.has(normalizedHost)) {
93
+ return;
94
+ }
95
+ const family = ipFamily(address);
96
+ if (family === null) {
97
+ throw new EgressError(`Invalid address ${address} for ${normalizedHost}`);
98
+ }
99
+ if (this.allowedNetworks.check(address, family)) {
100
+ return;
101
+ }
102
+ const isPublic = node_net.isIPv4(address) ? !this.specialPurpose.check(address, "ipv4") : this.globalUnicastIpv6.check(address, "ipv6") && !this.specialPurpose.check(address, "ipv6");
103
+ if (!isPublic) {
104
+ throw new EgressError(`${normalizedHost} resolves to the non-public address ${address}`);
105
+ }
106
+ }
107
+ }
108
+ exports.EgressError = EgressError;
109
+ exports.EgressPolicy = EgressPolicy;
110
+ //# sourceMappingURL=EgressPolicy.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EgressPolicy.cjs","sources":["../../../../../packages/engine-common/src/egress/EgressPolicy.ts"],"sourcesContent":["import { BlockList, isIP, isIPv4 } from 'node:net'\n\n// IPv4 special-purpose ranges (IANA): unspecified, private, CGNAT, loopback, link-local, protocol assignments,\n// documentation, 6to4 relay, benchmarking, multicast, reserved and broadcast.\nconst SPECIAL_PURPOSE_IPV4: readonly [string, number][] = [\n\t['0.0.0.0', 8],\n\t['10.0.0.0', 8],\n\t['100.64.0.0', 10],\n\t['127.0.0.0', 8],\n\t['169.254.0.0', 16],\n\t['172.16.0.0', 12],\n\t['192.0.0.0', 24],\n\t['192.0.2.0', 24],\n\t['192.88.99.0', 24],\n\t['192.168.0.0', 16],\n\t['198.18.0.0', 15],\n\t['198.51.100.0', 24],\n\t['203.0.113.0', 24],\n\t['224.0.0.0', 4],\n\t['240.0.0.0', 4],\n]\n\n// Only global unicast (2000::/3) is reachable; within it, protocol assignments (incl. Teredo), documentation and\n// 6to4 (which embeds an arbitrary IPv4 address) are refused too. Everything outside 2000::/3 — unspecified, loopback,\n// IPv4-mapped, NAT64, unique-local, link-local, multicast — never passes.\nconst GLOBAL_UNICAST_IPV6: readonly [string, number] = ['2000::', 3]\nconst SPECIAL_PURPOSE_IPV6: readonly [string, number][] = [\n\t['2001::', 23],\n\t['2001:db8::', 32],\n\t['2002::', 16],\n\t['3fff::', 20],\n]\n\nconst normalizeHost = (host: string): string => host.toLowerCase().replace(/^\\[(.*)]$/, '$1').replace(/\\.$/, '')\n\nconst ipFamily = (address: string): 'ipv4' | 'ipv6' | null => {\n\tconst version = isIP(address)\n\treturn version === 4 ? 'ipv4' : version === 6 ? 'ipv6' : null\n}\n\nexport class EgressError extends Error {}\n\nexport interface EgressPolicyConfig {\n\t/** Allows `http://` URLs; otherwise only `https://` is fetched. */\n\treadonly allowHttp: boolean\n\t/** Host names, addresses and CIDR ranges exempt from the non-public address check. */\n\treadonly allowlist: readonly string[]\n}\n\n/**\n * Which URLs the engine may fetch on behalf of a tenant: `https://` only (unless `allowHttp`), never a special-purpose\n * address unless allow-listed. Checked per connection (on the resolved address), so DNS rebinding cannot bypass it.\n */\nexport class EgressPolicy {\n\tprivate readonly specialPurpose = new BlockList()\n\tprivate readonly globalUnicastIpv6 = new BlockList()\n\tprivate readonly allowedNetworks = new BlockList()\n\tprivate readonly allowedHosts: ReadonlySet<string>\n\tprivate readonly allowHttp: boolean\n\n\tconstructor(config: EgressPolicyConfig) {\n\t\tfor (const [network, prefix] of SPECIAL_PURPOSE_IPV4) {\n\t\t\tthis.specialPurpose.addSubnet(network, prefix, 'ipv4')\n\t\t}\n\t\tfor (const [network, prefix] of SPECIAL_PURPOSE_IPV6) {\n\t\t\tthis.specialPurpose.addSubnet(network, prefix, 'ipv6')\n\t\t}\n\t\tthis.globalUnicastIpv6.addSubnet(GLOBAL_UNICAST_IPV6[0], GLOBAL_UNICAST_IPV6[1], 'ipv6')\n\n\t\tconst allowedHosts = new Set<string>()\n\t\tfor (const entry of config.allowlist) {\n\t\t\tconst [network, prefixText, ...rest] = entry.trim().split('/')\n\t\t\tconst family = ipFamily(network)\n\t\t\tif (family === null) {\n\t\t\t\tif (prefixText !== undefined || network === '') {\n\t\t\t\t\tthrow new EgressError(`Invalid egress allowlist entry ${entry}`)\n\t\t\t\t}\n\t\t\t\tallowedHosts.add(normalizeHost(network))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst maxPrefix = family === 'ipv4' ? 32 : 128\n\t\t\tif (rest.length > 0 || (prefixText !== undefined && !/^\\d{1,3}$/.test(prefixText))) {\n\t\t\t\tthrow new EgressError(`Invalid egress allowlist entry ${entry}`)\n\t\t\t}\n\t\t\tconst prefix = prefixText === undefined ? maxPrefix : Number(prefixText)\n\t\t\tif (prefix > maxPrefix) {\n\t\t\t\tthrow new EgressError(`Invalid egress allowlist entry ${entry}`)\n\t\t\t}\n\t\t\tthis.allowedNetworks.addSubnet(network, prefix, family)\n\t\t}\n\t\tthis.allowedHosts = allowedHosts\n\t\tthis.allowHttp = config.allowHttp\n\t}\n\n\t/** Throws unless the URL may be fetched; an IP-literal host is checked here because no lookup will run for it. */\n\tpublic checkUrl(url: URL): void {\n\t\tconst host = normalizeHost(url.hostname)\n\t\tif (url.username !== '' || url.password !== '') {\n\t\t\tthrow new EgressError('Outgoing request URLs must not carry credentials')\n\t\t}\n\t\tif (url.protocol !== 'https:' && !(url.protocol === 'http:' && this.allowHttp)) {\n\t\t\tthrow new EgressError(`Only https:// URLs are allowed, got ${url.protocol}//${host}`)\n\t\t}\n\t\tif (ipFamily(host) !== null) {\n\t\t\tthis.checkAddress(host, host)\n\t\t}\n\t}\n\n\t/** Throws unless a connection to `address`, resolved from `host`, is allowed. */\n\tpublic checkAddress(host: string, address: string): void {\n\t\tconst normalizedHost = normalizeHost(host)\n\t\tif (this.allowedHosts.has(normalizedHost)) {\n\t\t\treturn\n\t\t}\n\t\tconst family = ipFamily(address)\n\t\tif (family === null) {\n\t\t\tthrow new EgressError(`Invalid address ${address} for ${normalizedHost}`)\n\t\t}\n\t\tif (this.allowedNetworks.check(address, family)) {\n\t\t\treturn\n\t\t}\n\t\tconst isPublic = isIPv4(address)\n\t\t\t? !this.specialPurpose.check(address, 'ipv4')\n\t\t\t: this.globalUnicastIpv6.check(address, 'ipv6') && !this.specialPurpose.check(address, 'ipv6')\n\t\tif (!isPublic) {\n\t\t\tthrow new EgressError(`${normalizedHost} resolves to the non-public address ${address}`)\n\t\t}\n\t}\n}\n"],"names":["isIP","BlockList","isIPv4"],"mappings":";;;;;;AAIA,MAAM,uBAAoD;AAAA,EACzD,CAAC,WAAW,CAAC;AAAA,EACb,CAAC,YAAY,CAAC;AAAA,EACd,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,aAAa,CAAC;AAAA,EACf,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,aAAa,EAAE;AAAA,EAChB,CAAC,aAAa,EAAE;AAAA,EAChB,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,gBAAgB,EAAE;AAAA,EACnB,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,aAAa,CAAC;AAAA,EACf,CAAC,aAAa,CAAC;A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