@asterxsk/kiln 0.1.0 → 0.2.0

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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,526 +1,526 @@
1
- import { lookup as dnsLookup } from "node:dns/promises";
2
- import { existsSync, readFileSync, statSync } from "node:fs";
3
- import net from "node:net";
4
- import { getActiveProxy, getWebSearchConfigPath, hasScopedProxyDecision, isProxyBypassedUrl } from "./utils.ts";
5
-
6
- const DEFAULT_MAX_REDIRECTS = 5;
7
- const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
8
- const LOOPBACK_ALLOW_RANGES = ["127.0.0.0/8", "::1", "::ffff:127.0.0.0/104"];
9
-
10
- export type LookupAddress = { address: string; family: number };
11
- export type Lookup = (hostname: string) => Promise<LookupAddress[]>;
12
- type Fetch = typeof fetch;
13
-
14
- const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
15
-
16
- let cachedConfigRoot: { signature: string; value: Record<string, unknown> | null } | null = null;
17
-
18
- function loadConfigRoot(): Record<string, unknown> | null {
19
- if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return null;
20
-
21
- let signature: string;
22
- try {
23
- const stat = statSync(WEB_SEARCH_CONFIG_PATH);
24
- signature = `${stat.mtimeMs}:${stat.size}`;
25
- } catch {
26
- return null;
27
- }
28
-
29
- if (cachedConfigRoot?.signature === signature) return cachedConfigRoot.value;
30
-
31
- let raw: string;
32
- try {
33
- raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
34
- } catch {
35
- // Do not memoize read failures: a chmod fix changes neither mtime nor size,
36
- // so a cached failure would permanently fail-open the domain policy.
37
- return null;
38
- }
39
-
40
- let parsed: unknown;
41
- try {
42
- parsed = JSON.parse(raw);
43
- } catch (err) {
44
- const message = err instanceof Error ? err.message : String(err);
45
- throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
46
- }
47
-
48
- const value = parsed && typeof parsed === "object" && !Array.isArray(parsed)
49
- ? parsed as Record<string, unknown>
50
- : null;
51
- cachedConfigRoot = { signature, value };
52
- return value;
53
- }
54
-
55
- export interface SsrfConfig {
56
- allowRanges: string[];
57
- trustEnvProxy: boolean;
58
- }
59
-
60
- export interface DomainPolicy {
61
- allow: string[];
62
- deny: string[];
63
- }
64
-
65
- const DEFAULT_DOMAIN_POLICY: DomainPolicy = { allow: [], deny: [] };
66
-
67
- export function loadFetchContentDomainPolicy(): DomainPolicy {
68
- const parsed = loadConfigRoot();
69
- if (!parsed) return { ...DEFAULT_DOMAIN_POLICY };
70
- const fetchContent = parsed.fetchContent;
71
- if (fetchContent === undefined || fetchContent === null) return { ...DEFAULT_DOMAIN_POLICY };
72
- if (typeof fetchContent !== "object" || Array.isArray(fetchContent)) {
73
- throw new Error(`fetchContent in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
74
- }
75
- const policy = (fetchContent as { domainPolicy?: unknown }).domainPolicy;
76
- if (policy === undefined || policy === null) return { ...DEFAULT_DOMAIN_POLICY };
77
- if (typeof policy !== "object" || Array.isArray(policy)) {
78
- throw new Error(`fetchContent.domainPolicy in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
79
- }
80
- const config = policy as { allow?: unknown; deny?: unknown };
81
- return {
82
- allow: parseDomainEntries(config.allow, "allow"),
83
- deny: parseDomainEntries(config.deny, "deny"),
84
- };
85
- }
86
-
87
- function parseDomainEntries(value: unknown, field: "allow" | "deny"): string[] {
88
- if (value === undefined || value === null) return [];
89
- if (!Array.isArray(value)) {
90
- throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hostnames`);
91
- }
92
- return value.map((entry, index) => {
93
- if (typeof entry !== "string") {
94
- throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames; entry ${index + 1} is ${typeof entry}`);
95
- }
96
- const hostname = normalizeDomainEntry(entry);
97
- if (!hostname) {
98
- throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(entry)}`);
99
- }
100
- return hostname;
101
- });
102
- }
103
-
104
- function normalizeDomainEntry(entry: string): string | null {
105
- const hostname = normalizeHostname(entry.trim());
106
- if (!hostname || /\s|[\\/?:#@]/.test(hostname)) return null;
107
- if (net.isIP(hostname)) return hostname;
108
- if (hostname.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(hostname)) return null;
109
- return hostname;
110
- }
111
-
112
- export function loadSsrfConfig(): SsrfConfig {
113
- const parsed = loadConfigRoot();
114
- if (!parsed) return { allowRanges: [], trustEnvProxy: false };
115
- const ssrf = parsed.ssrf;
116
- if (ssrf === undefined || ssrf === null) return { allowRanges: [], trustEnvProxy: false };
117
- if (typeof ssrf !== "object" || Array.isArray(ssrf)) {
118
- throw new Error(`ssrf in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
119
- }
120
- const config = ssrf as { allowRanges?: unknown; trustEnvProxy?: unknown };
121
- if (config.allowRanges !== undefined && config.allowRanges !== null && !Array.isArray(config.allowRanges)) {
122
- throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must be an array of CIDR strings`);
123
- }
124
- if (config.trustEnvProxy !== undefined && typeof config.trustEnvProxy !== "boolean") {
125
- throw new Error(`ssrf.trustEnvProxy in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
126
- }
127
- const allowRangesValue: unknown[] = Array.isArray(config.allowRanges) ? config.allowRanges : [];
128
- const allowRanges = allowRangesValue.map((entry, index) => {
129
- if (typeof entry !== "string") {
130
- throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must contain only CIDR strings; entry ${index + 1} is ${typeof entry}`);
131
- }
132
- return entry.trim();
133
- }).filter(Boolean);
134
- parseAllowRanges(allowRanges);
135
- return { allowRanges, trustEnvProxy: config.trustEnvProxy === true };
136
- }
137
-
138
- interface ValidationOptions {
139
- lookup?: Lookup;
140
- /** Optional hostname policy for fetch_content target URLs. */
141
- domainPolicy?: DomainPolicy;
142
- /**
143
- * CIDR ranges (e.g. "198.18.0.0/15") to exempt from the SSRF guard.
144
- * Useful when a host runs a TUN/fake-IP proxy (Surge, Clash, Mihomo, ...)
145
- * that resolves public domains into a reserved range. Entries are validated
146
- * strictly; an invalid entry throws so misconfiguration is not silent.
147
- */
148
- allowRanges?: string[];
149
- /**
150
- * When true, trust an explicitly-configured HTTP(S) proxy for hostname
151
- * resolution instead of performing local DNS lookups inside the sandbox.
152
- * Literal IPs and localhost remain blocked, and NO_PROXY hosts still use
153
- * the local SSRF preflight. This does not configure proxy transport.
154
- */
155
- trustEnvProxy?: boolean;
156
- /** Allow loopback URLs for explicit provider base endpoints, not fetched targets. */
157
- allowLoopback?: boolean;
158
- }
159
-
160
- /** Parsed entry from `allowRanges`: a network address (4 or 16 bytes) + prefix length. */
161
- interface ParsedCidr {
162
- bytes: Uint8Array;
163
- prefix: number;
164
- }
165
-
166
- interface RedirectRequestInitArgs {
167
- from: URL;
168
- to: URL;
169
- init: RequestInit;
170
- response: Response;
171
- }
172
-
173
- interface FetchRemoteOptions extends ValidationOptions {
174
- fetch?: Fetch;
175
- maxRedirects?: number;
176
- onRedirect?: (args: RedirectRequestInitArgs) => RequestInit;
177
- }
178
-
179
- async function defaultLookup(hostname: string): Promise<LookupAddress[]> {
180
- return dnsLookup(hostname, { all: true, verbatim: true });
181
- }
182
-
183
- export async function validateRemoteUrl(rawUrl: string | URL, options: ValidationOptions = {}): Promise<URL> {
184
- const url = rawUrl instanceof URL ? rawUrl : new URL(rawUrl);
185
- if (url.protocol !== "http:" && url.protocol !== "https:") {
186
- throw new Error("Only HTTP and HTTPS URLs can be fetched remotely");
187
- }
188
-
189
- const hostname = normalizeHostname(url.hostname);
190
- if (!hostname) throw new Error("URL must include a hostname");
191
- if (hostname === "localhost") {
192
- if (options.allowLoopback === true) return url;
193
- throw new Error(`Blocked internal hostname: ${hostname}`);
194
- }
195
- if (hostname.endsWith(".localhost")) {
196
- throw new Error(`Blocked internal hostname: ${hostname}`);
197
- }
198
-
199
- const allowRanges = parseAllowRanges(options.allowRanges);
200
- assertDomainPolicy(hostname, options.domainPolicy);
201
-
202
- if (net.isIP(hostname)) {
203
- const addressAllowRanges = options.allowLoopback === true
204
- ? [...allowRanges, ...parseAllowRanges(LOOPBACK_ALLOW_RANGES)]
205
- : allowRanges;
206
- assertPublicAddress(hostname, hostname, addressAllowRanges);
207
- return url;
208
- }
209
-
210
- if (shouldTrustEnvProxy(url, options.trustEnvProxy === true)) return url;
211
-
212
- let addresses: LookupAddress[];
213
- try {
214
- addresses = await (options.lookup ?? defaultLookup)(hostname);
215
- } catch (err) {
216
- const message = err instanceof Error ? err.message : String(err);
217
- throw new Error(`Failed to resolve ${hostname}: ${message}`);
218
- }
219
-
220
- if (addresses.length === 0) throw new Error(`Failed to resolve ${hostname}: no addresses returned`);
221
- for (const { address } of addresses) {
222
- assertPublicAddress(address, hostname, allowRanges);
223
- }
224
- return url;
225
- }
226
-
227
- export async function fetchRemoteUrl(
228
- url: string | URL,
229
- init: RequestInit = {},
230
- options: FetchRemoteOptions = {},
231
- ): Promise<Response> {
232
- const fetchImpl = options.fetch ?? fetch;
233
- const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
234
- let current = await validateRemoteUrl(url, options);
235
- let requestInit = init;
236
-
237
- for (let redirects = 0; redirects <= maxRedirects; redirects++) {
238
- const response = await fetchImpl(current, { ...requestInit, redirect: "manual" });
239
- if (!REDIRECT_STATUSES.has(response.status)) return response;
240
-
241
- const location = response.headers.get("location");
242
- if (!location) return response;
243
- if (redirects === maxRedirects) throw new Error(`Too many redirects fetching ${current.toString()}`);
244
-
245
- const from = current;
246
- current = await validateRemoteUrl(new URL(location, current), options);
247
- if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
248
- const { body: _body, ...nextInit } = requestInit;
249
- requestInit = { ...nextInit, method: "GET" };
250
- }
251
- if (options.onRedirect) requestInit = options.onRedirect({ from, to: current, init: requestInit, response });
252
- }
253
-
254
- throw new Error(`Too many redirects fetching ${current.toString()}`);
255
- }
256
-
257
- function normalizeHostname(hostname: string): string {
258
- return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
259
- }
260
-
261
- function assertDomainPolicy(hostname: string, policy?: DomainPolicy): void {
262
- if (!policy) return;
263
- if (policy.deny.some((entry) => domainMatches(hostname, entry))) {
264
- throw new Error(`Blocked hostname by fetch_content domain policy: ${hostname}`);
265
- }
266
- if (policy.allow.length > 0 && !policy.allow.some((entry) => domainMatches(hostname, entry))) {
267
- throw new Error(`Hostname not allowed by fetch_content domain policy: ${hostname}`);
268
- }
269
- }
270
-
271
- function domainMatches(hostname: string, entry: string): boolean {
272
- return hostname === entry || hostname.endsWith(`.${entry}`);
273
- }
274
-
275
- function getProxyForProtocol(protocol: string): string {
276
- const candidates = protocol === "http:"
277
- ? [process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
278
- : protocol === "https:"
279
- ? [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
280
- : [];
281
- for (const candidate of candidates) {
282
- const value = candidate?.trim();
283
- if (!value) continue;
284
- try {
285
- const proxyUrl = new URL(value);
286
- if ((proxyUrl.protocol === "http:" || proxyUrl.protocol === "https:") && proxyUrl.hostname) return value;
287
- } catch {
288
- // Invalid proxy env vars should not weaken local DNS SSRF checks.
289
- }
290
- }
291
- return "";
292
- }
293
-
294
- function hostnameMatchesNoProxy(hostname: string, port: string, entry: string): boolean {
295
- const trimmed = entry.trim();
296
- if (!trimmed) return false;
297
- if (trimmed === "*") return true;
298
-
299
- // NO_PROXY entries may include a port. Strip it only after handling
300
- // bracketed IPv6 literals, which can contain several colons.
301
- let hostEntry = trimmed;
302
- let entryPort: string | undefined;
303
- if (hostEntry.startsWith("[")) {
304
- const closingBracket = hostEntry.indexOf("]");
305
- if (closingBracket >= 0) {
306
- const suffix = hostEntry.slice(closingBracket + 1);
307
- if (/^:\\d+$/.test(suffix)) entryPort = suffix.slice(1);
308
- hostEntry = hostEntry.slice(0, closingBracket + 1);
309
- }
310
- } else {
311
- const colon = hostEntry.lastIndexOf(":");
312
- if (colon > -1 && /^\d+$/.test(hostEntry.slice(colon + 1))) {
313
- entryPort = hostEntry.slice(colon + 1);
314
- hostEntry = hostEntry.slice(0, colon);
315
- }
316
- }
317
- if (entryPort !== undefined && entryPort !== port) return false;
318
-
319
- const normalizedEntry = normalizeHostname(hostEntry);
320
- if (!normalizedEntry) return false;
321
- if (normalizedEntry === hostname) return true;
322
- const suffix = normalizedEntry.startsWith("*.")
323
- ? normalizedEntry.slice(1)
324
- : normalizedEntry.startsWith(".")
325
- ? normalizedEntry
326
- : `.${normalizedEntry}`;
327
- return hostname.endsWith(suffix);
328
- }
329
-
330
- function shouldTrustEnvProxy(url: URL, enabled: boolean): boolean {
331
- if (!enabled || !getProxyForProtocol(url.protocol)) return false;
332
- if (hasScopedProxyDecision()) return false;
333
- const activeProxy = getActiveProxy();
334
- if (activeProxy && !isProxyBypassedUrl(url)) return false;
335
- const hostname = normalizeHostname(url.hostname);
336
- const port = url.port || (url.protocol === "https:" ? "443" : "80");
337
- const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
338
- return !noProxy.split(",").some(entry => hostnameMatchesNoProxy(hostname, port, entry));
339
- }
340
-
341
- function assertPublicAddress(address: string, hostname: string, allowRanges: ParsedCidr[] = []): void {
342
- const normalized = normalizeHostname(address);
343
- const ipVersion = net.isIP(normalized);
344
- if (ipVersion === 0) throw new Error(`Resolved non-IP address for ${hostname}: ${address}`);
345
- // Explicitly-allowed ranges bypass the private/reserved checks below. This lets
346
- // users exempt synthetic ranges produced by TUN/fake-IP proxies (e.g. 198.18/15).
347
- if (isInAllowedRange(normalized, ipVersion, allowRanges)) return;
348
- if (ipVersion === 4 && isBlockedIPv4(normalized)) {
349
- const hint = isFakeIpProxyAddress(normalized)
350
- ? '. This address is in 198.18.0.0/15, commonly used by TUN/fake-IP proxies. If that matches your setup, configure ssrf.allowRanges with ["198.18.0.0/15"] in web-search.json.'
351
- : "";
352
- throw new Error(`Blocked internal address for ${hostname}: ${normalized}${hint}`);
353
- }
354
- if (ipVersion === 6 && isBlockedIPv6(normalized)) {
355
- throw new Error(`Blocked internal address for ${hostname}: ${normalized}`);
356
- }
357
- }
358
-
359
- function isFakeIpProxyAddress(address: string): boolean {
360
- const [a, b] = address.split(".").map(part => Number(part));
361
- return a === 198 && (b === 18 || b === 19);
362
- }
363
-
364
- function isBlockedIPv4(address: string): boolean {
365
- const parts = address.split(".").map(part => Number(part));
366
- if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return true;
367
- const [a, b] = parts;
368
- return a === 0 ||
369
- a === 10 ||
370
- a === 127 ||
371
- (a === 100 && b >= 64 && b <= 127) ||
372
- (a === 169 && b === 254) ||
373
- (a === 172 && b >= 16 && b <= 31) ||
374
- (a === 192 && b === 168) ||
375
- isFakeIpProxyAddress(address) ||
376
- a >= 224;
377
- }
378
-
379
- function isBlockedIPv6(address: string): boolean {
380
- const groups = parseIPv6(address);
381
- if (!groups) return true;
382
-
383
- const first = groups[0];
384
- if (groups.every(group => group === 0)) return true;
385
- if (groups.slice(0, 7).every(group => group === 0) && groups[7] === 1) return true;
386
- if ((first & 0xfe00) === 0xfc00) return true;
387
- if ((first & 0xffc0) === 0xfe80) return true;
388
-
389
- const isMappedIPv4 = groups.slice(0, 5).every(group => group === 0) && groups[5] === 0xffff;
390
- if (isMappedIPv4) {
391
- const ipv4 = [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff].join(".");
392
- return isBlockedIPv4(ipv4);
393
- }
394
-
395
- return false;
396
- }
397
-
398
- function parseIPv6(address: string): number[] | null {
399
- if (address.includes(".")) {
400
- const lastColon = address.lastIndexOf(":");
401
- const ipv4 = address.slice(lastColon + 1);
402
- if (net.isIP(ipv4) !== 4) return null;
403
- const octets = ipv4.split(".").map(part => Number(part));
404
- address = `${address.slice(0, lastColon)}:${((octets[0] << 8) | octets[1]).toString(16)}:${((octets[2] << 8) | octets[3]).toString(16)}`;
405
- }
406
-
407
- const pieces = address.split("::");
408
- if (pieces.length > 2) return null;
409
-
410
- const left = pieces[0] ? pieces[0].split(":") : [];
411
- const right = pieces.length === 2 && pieces[1] ? pieces[1].split(":") : [];
412
- const missing = 8 - left.length - right.length;
413
- if (pieces.length === 1 && missing !== 0) return null;
414
- if (pieces.length === 2 && missing < 0) return null;
415
-
416
- const groups = [...left, ...Array(missing).fill("0"), ...right].map(part => {
417
- if (!/^[0-9a-f]{1,4}$/i.test(part)) return -1;
418
- return parseInt(part, 16);
419
- });
420
- return groups.length === 8 && groups.every(group => group >= 0 && group <= 0xffff) ? groups : null;
421
- }
422
-
423
- /** Parse `allowRanges` config value into validated CIDR rules. Throws on malformed entries. */
424
- function parseAllowRanges(input: unknown): ParsedCidr[] {
425
- if (input === undefined || input === null) return [];
426
- if (!Array.isArray(input)) {
427
- throw new Error("ssrf.allowRanges must be an array of CIDR strings");
428
- }
429
- const rules: ParsedCidr[] = [];
430
- for (const entry of input) {
431
- if (typeof entry !== "string") {
432
- throw new Error(`ssrf.allowRanges entries must be strings, got ${typeof entry}`);
433
- }
434
- const rule = parseCidr(entry.trim());
435
- if (!rule) {
436
- throw new Error(`Invalid CIDR notation in ssrf.allowRanges: "${entry}"`);
437
- }
438
- rules.push(rule);
439
- }
440
- return rules;
441
- }
442
-
443
- /** Parse a single CIDR (e.g. "198.18.0.0/15", "fd00::/8") or bare host ("1.2.3.4"). Returns null if invalid. */
444
- function parseCidr(raw: string): ParsedCidr | null {
445
- if (!raw) return null;
446
- const slash = raw.lastIndexOf("/");
447
- const addrPart = slash >= 0 ? raw.slice(0, slash) : raw;
448
- const prefixPart = slash >= 0 ? raw.slice(slash + 1) : null;
449
- // A slash must be followed by digits. Number("")/Number(" ") are 0, which
450
- // would silently turn "198.18.0.0/" into /0 and exempt every address.
451
- if (prefixPart !== null && !/^\d+$/.test(prefixPart)) return null;
452
- const version = net.isIP(addrPart);
453
-
454
- if (version === 4) {
455
- const bytes = ipv4ToBytes(addrPart);
456
- if (!bytes) return null;
457
- const prefix = prefixPart === null ? 32 : Number(prefixPart);
458
- if (!Number.isInteger(prefix) || prefix < 1 || prefix > 32) return null;
459
- return { bytes, prefix };
460
- }
461
- if (version === 6) {
462
- const groups = parseIPv6(addrPart);
463
- if (!groups) return null;
464
- const prefix = prefixPart === null ? 128 : Number(prefixPart);
465
- if (!Number.isInteger(prefix) || prefix < 1 || prefix > 128) return null;
466
- return { bytes: ipv6GroupsToBytes(groups), prefix };
467
- }
468
- return null;
469
- }
470
-
471
- function ipv4ToBytes(address: string): Uint8Array | null {
472
- const parts = address.split(".");
473
- if (parts.length !== 4) return null;
474
- const bytes = new Uint8Array(4);
475
- for (let i = 0; i < 4; i++) {
476
- const octet = Number(parts[i]);
477
- if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;
478
- bytes[i] = octet;
479
- }
480
- return bytes;
481
- }
482
-
483
- function ipv6GroupsToBytes(groups: number[]): Uint8Array {
484
- const bytes = new Uint8Array(16);
485
- for (let i = 0; i < 8; i++) {
486
- bytes[i * 2] = groups[i] >> 8;
487
- bytes[i * 2 + 1] = groups[i] & 0xff;
488
- }
489
- return bytes;
490
- }
491
-
492
- function ipToBytes(address: string, version: number): Uint8Array | null {
493
- if (version === 4) return ipv4ToBytes(address);
494
- if (version === 6) {
495
- const groups = parseIPv6(address);
496
- return groups ? ipv6GroupsToBytes(groups) : null;
497
- }
498
- return null;
499
- }
500
-
501
- /** True if `address` (already validated as `ipVersion`) falls within any allowed CIDR. */
502
- function isInAllowedRange(address: string, ipVersion: number, allowRanges: ParsedCidr[]): boolean {
503
- if (allowRanges.length === 0) return false;
504
- const addrBytes = ipToBytes(address, ipVersion);
505
- if (!addrBytes) return false;
506
- for (const rule of allowRanges) {
507
- // Only compare same-family rules (4-byte IPv4 vs 16-byte IPv6).
508
- if (rule.bytes.length !== addrBytes.length) continue;
509
- if (bytesMatchPrefix(addrBytes, rule.bytes, rule.prefix)) return true;
510
- }
511
- return false;
512
- }
513
-
514
- /** Compare the leading `prefix` bits of two equal-length byte arrays. */
515
- function bytesMatchPrefix(addr: Uint8Array, network: Uint8Array, prefix: number): boolean {
516
- const fullBytes = prefix >> 3;
517
- const remBits = prefix & 7;
518
- for (let i = 0; i < fullBytes; i++) {
519
- if (addr[i] !== network[i]) return false;
520
- }
521
- if (remBits > 0 && fullBytes < addr.length) {
522
- const mask = (0xff << (8 - remBits)) & 0xff;
523
- if ((addr[fullBytes] & mask) !== (network[fullBytes] & mask)) return false;
524
- }
525
- return true;
526
- }
1
+ import { lookup as dnsLookup } from "node:dns/promises";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import net from "node:net";
4
+ import { getActiveProxy, getWebSearchConfigPath, hasScopedProxyDecision, isProxyBypassedUrl } from "./utils.ts";
5
+
6
+ const DEFAULT_MAX_REDIRECTS = 5;
7
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
8
+ const LOOPBACK_ALLOW_RANGES = ["127.0.0.0/8", "::1", "::ffff:127.0.0.0/104"];
9
+
10
+ export type LookupAddress = { address: string; family: number };
11
+ export type Lookup = (hostname: string) => Promise<LookupAddress[]>;
12
+ type Fetch = typeof fetch;
13
+
14
+ const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
15
+
16
+ let cachedConfigRoot: { signature: string; value: Record<string, unknown> | null } | null = null;
17
+
18
+ function loadConfigRoot(): Record<string, unknown> | null {
19
+ if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return null;
20
+
21
+ let signature: string;
22
+ try {
23
+ const stat = statSync(WEB_SEARCH_CONFIG_PATH);
24
+ signature = `${stat.mtimeMs}:${stat.size}`;
25
+ } catch {
26
+ return null;
27
+ }
28
+
29
+ if (cachedConfigRoot?.signature === signature) return cachedConfigRoot.value;
30
+
31
+ let raw: string;
32
+ try {
33
+ raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
34
+ } catch {
35
+ // Do not memoize read failures: a chmod fix changes neither mtime nor size,
36
+ // so a cached failure would permanently fail-open the domain policy.
37
+ return null;
38
+ }
39
+
40
+ let parsed: unknown;
41
+ try {
42
+ parsed = JSON.parse(raw);
43
+ } catch (err) {
44
+ const message = err instanceof Error ? err.message : String(err);
45
+ throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
46
+ }
47
+
48
+ const value = parsed && typeof parsed === "object" && !Array.isArray(parsed)
49
+ ? parsed as Record<string, unknown>
50
+ : null;
51
+ cachedConfigRoot = { signature, value };
52
+ return value;
53
+ }
54
+
55
+ export interface SsrfConfig {
56
+ allowRanges: string[];
57
+ trustEnvProxy: boolean;
58
+ }
59
+
60
+ export interface DomainPolicy {
61
+ allow: string[];
62
+ deny: string[];
63
+ }
64
+
65
+ const DEFAULT_DOMAIN_POLICY: DomainPolicy = { allow: [], deny: [] };
66
+
67
+ export function loadFetchContentDomainPolicy(): DomainPolicy {
68
+ const parsed = loadConfigRoot();
69
+ if (!parsed) return { ...DEFAULT_DOMAIN_POLICY };
70
+ const fetchContent = parsed.fetchContent;
71
+ if (fetchContent === undefined || fetchContent === null) return { ...DEFAULT_DOMAIN_POLICY };
72
+ if (typeof fetchContent !== "object" || Array.isArray(fetchContent)) {
73
+ throw new Error(`fetchContent in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
74
+ }
75
+ const policy = (fetchContent as { domainPolicy?: unknown }).domainPolicy;
76
+ if (policy === undefined || policy === null) return { ...DEFAULT_DOMAIN_POLICY };
77
+ if (typeof policy !== "object" || Array.isArray(policy)) {
78
+ throw new Error(`fetchContent.domainPolicy in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
79
+ }
80
+ const config = policy as { allow?: unknown; deny?: unknown };
81
+ return {
82
+ allow: parseDomainEntries(config.allow, "allow"),
83
+ deny: parseDomainEntries(config.deny, "deny"),
84
+ };
85
+ }
86
+
87
+ function parseDomainEntries(value: unknown, field: "allow" | "deny"): string[] {
88
+ if (value === undefined || value === null) return [];
89
+ if (!Array.isArray(value)) {
90
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hostnames`);
91
+ }
92
+ return value.map((entry, index) => {
93
+ if (typeof entry !== "string") {
94
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames; entry ${index + 1} is ${typeof entry}`);
95
+ }
96
+ const hostname = normalizeDomainEntry(entry);
97
+ if (!hostname) {
98
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(entry)}`);
99
+ }
100
+ return hostname;
101
+ });
102
+ }
103
+
104
+ function normalizeDomainEntry(entry: string): string | null {
105
+ const hostname = normalizeHostname(entry.trim());
106
+ if (!hostname || /\s|[\\/?:#@]/.test(hostname)) return null;
107
+ if (net.isIP(hostname)) return hostname;
108
+ if (hostname.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(hostname)) return null;
109
+ return hostname;
110
+ }
111
+
112
+ export function loadSsrfConfig(): SsrfConfig {
113
+ const parsed = loadConfigRoot();
114
+ if (!parsed) return { allowRanges: [], trustEnvProxy: false };
115
+ const ssrf = parsed.ssrf;
116
+ if (ssrf === undefined || ssrf === null) return { allowRanges: [], trustEnvProxy: false };
117
+ if (typeof ssrf !== "object" || Array.isArray(ssrf)) {
118
+ throw new Error(`ssrf in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
119
+ }
120
+ const config = ssrf as { allowRanges?: unknown; trustEnvProxy?: unknown };
121
+ if (config.allowRanges !== undefined && config.allowRanges !== null && !Array.isArray(config.allowRanges)) {
122
+ throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must be an array of CIDR strings`);
123
+ }
124
+ if (config.trustEnvProxy !== undefined && typeof config.trustEnvProxy !== "boolean") {
125
+ throw new Error(`ssrf.trustEnvProxy in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
126
+ }
127
+ const allowRangesValue: unknown[] = Array.isArray(config.allowRanges) ? config.allowRanges : [];
128
+ const allowRanges = allowRangesValue.map((entry, index) => {
129
+ if (typeof entry !== "string") {
130
+ throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must contain only CIDR strings; entry ${index + 1} is ${typeof entry}`);
131
+ }
132
+ return entry.trim();
133
+ }).filter(Boolean);
134
+ parseAllowRanges(allowRanges);
135
+ return { allowRanges, trustEnvProxy: config.trustEnvProxy === true };
136
+ }
137
+
138
+ interface ValidationOptions {
139
+ lookup?: Lookup;
140
+ /** Optional hostname policy for fetch_content target URLs. */
141
+ domainPolicy?: DomainPolicy;
142
+ /**
143
+ * CIDR ranges (e.g. "198.18.0.0/15") to exempt from the SSRF guard.
144
+ * Useful when a host runs a TUN/fake-IP proxy (Surge, Clash, Mihomo, ...)
145
+ * that resolves public domains into a reserved range. Entries are validated
146
+ * strictly; an invalid entry throws so misconfiguration is not silent.
147
+ */
148
+ allowRanges?: string[];
149
+ /**
150
+ * When true, trust an explicitly-configured HTTP(S) proxy for hostname
151
+ * resolution instead of performing local DNS lookups inside the sandbox.
152
+ * Literal IPs and localhost remain blocked, and NO_PROXY hosts still use
153
+ * the local SSRF preflight. This does not configure proxy transport.
154
+ */
155
+ trustEnvProxy?: boolean;
156
+ /** Allow loopback URLs for explicit provider base endpoints, not fetched targets. */
157
+ allowLoopback?: boolean;
158
+ }
159
+
160
+ /** Parsed entry from `allowRanges`: a network address (4 or 16 bytes) + prefix length. */
161
+ interface ParsedCidr {
162
+ bytes: Uint8Array;
163
+ prefix: number;
164
+ }
165
+
166
+ interface RedirectRequestInitArgs {
167
+ from: URL;
168
+ to: URL;
169
+ init: RequestInit;
170
+ response: Response;
171
+ }
172
+
173
+ interface FetchRemoteOptions extends ValidationOptions {
174
+ fetch?: Fetch;
175
+ maxRedirects?: number;
176
+ onRedirect?: (args: RedirectRequestInitArgs) => RequestInit;
177
+ }
178
+
179
+ async function defaultLookup(hostname: string): Promise<LookupAddress[]> {
180
+ return dnsLookup(hostname, { all: true, verbatim: true });
181
+ }
182
+
183
+ export async function validateRemoteUrl(rawUrl: string | URL, options: ValidationOptions = {}): Promise<URL> {
184
+ const url = rawUrl instanceof URL ? rawUrl : new URL(rawUrl);
185
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
186
+ throw new Error("Only HTTP and HTTPS URLs can be fetched remotely");
187
+ }
188
+
189
+ const hostname = normalizeHostname(url.hostname);
190
+ if (!hostname) throw new Error("URL must include a hostname");
191
+ if (hostname === "localhost") {
192
+ if (options.allowLoopback === true) return url;
193
+ throw new Error(`Blocked internal hostname: ${hostname}`);
194
+ }
195
+ if (hostname.endsWith(".localhost")) {
196
+ throw new Error(`Blocked internal hostname: ${hostname}`);
197
+ }
198
+
199
+ const allowRanges = parseAllowRanges(options.allowRanges);
200
+ assertDomainPolicy(hostname, options.domainPolicy);
201
+
202
+ if (net.isIP(hostname)) {
203
+ const addressAllowRanges = options.allowLoopback === true
204
+ ? [...allowRanges, ...parseAllowRanges(LOOPBACK_ALLOW_RANGES)]
205
+ : allowRanges;
206
+ assertPublicAddress(hostname, hostname, addressAllowRanges);
207
+ return url;
208
+ }
209
+
210
+ if (shouldTrustEnvProxy(url, options.trustEnvProxy === true)) return url;
211
+
212
+ let addresses: LookupAddress[];
213
+ try {
214
+ addresses = await (options.lookup ?? defaultLookup)(hostname);
215
+ } catch (err) {
216
+ const message = err instanceof Error ? err.message : String(err);
217
+ throw new Error(`Failed to resolve ${hostname}: ${message}`);
218
+ }
219
+
220
+ if (addresses.length === 0) throw new Error(`Failed to resolve ${hostname}: no addresses returned`);
221
+ for (const { address } of addresses) {
222
+ assertPublicAddress(address, hostname, allowRanges);
223
+ }
224
+ return url;
225
+ }
226
+
227
+ export async function fetchRemoteUrl(
228
+ url: string | URL,
229
+ init: RequestInit = {},
230
+ options: FetchRemoteOptions = {},
231
+ ): Promise<Response> {
232
+ const fetchImpl = options.fetch ?? fetch;
233
+ const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
234
+ let current = await validateRemoteUrl(url, options);
235
+ let requestInit = init;
236
+
237
+ for (let redirects = 0; redirects <= maxRedirects; redirects++) {
238
+ const response = await fetchImpl(current, { ...requestInit, redirect: "manual" });
239
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
240
+
241
+ const location = response.headers.get("location");
242
+ if (!location) return response;
243
+ if (redirects === maxRedirects) throw new Error(`Too many redirects fetching ${current.toString()}`);
244
+
245
+ const from = current;
246
+ current = await validateRemoteUrl(new URL(location, current), options);
247
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
248
+ const { body: _body, ...nextInit } = requestInit;
249
+ requestInit = { ...nextInit, method: "GET" };
250
+ }
251
+ if (options.onRedirect) requestInit = options.onRedirect({ from, to: current, init: requestInit, response });
252
+ }
253
+
254
+ throw new Error(`Too many redirects fetching ${current.toString()}`);
255
+ }
256
+
257
+ function normalizeHostname(hostname: string): string {
258
+ return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
259
+ }
260
+
261
+ function assertDomainPolicy(hostname: string, policy?: DomainPolicy): void {
262
+ if (!policy) return;
263
+ if (policy.deny.some((entry) => domainMatches(hostname, entry))) {
264
+ throw new Error(`Blocked hostname by fetch_content domain policy: ${hostname}`);
265
+ }
266
+ if (policy.allow.length > 0 && !policy.allow.some((entry) => domainMatches(hostname, entry))) {
267
+ throw new Error(`Hostname not allowed by fetch_content domain policy: ${hostname}`);
268
+ }
269
+ }
270
+
271
+ function domainMatches(hostname: string, entry: string): boolean {
272
+ return hostname === entry || hostname.endsWith(`.${entry}`);
273
+ }
274
+
275
+ function getProxyForProtocol(protocol: string): string {
276
+ const candidates = protocol === "http:"
277
+ ? [process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
278
+ : protocol === "https:"
279
+ ? [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
280
+ : [];
281
+ for (const candidate of candidates) {
282
+ const value = candidate?.trim();
283
+ if (!value) continue;
284
+ try {
285
+ const proxyUrl = new URL(value);
286
+ if ((proxyUrl.protocol === "http:" || proxyUrl.protocol === "https:") && proxyUrl.hostname) return value;
287
+ } catch {
288
+ // Invalid proxy env vars should not weaken local DNS SSRF checks.
289
+ }
290
+ }
291
+ return "";
292
+ }
293
+
294
+ function hostnameMatchesNoProxy(hostname: string, port: string, entry: string): boolean {
295
+ const trimmed = entry.trim();
296
+ if (!trimmed) return false;
297
+ if (trimmed === "*") return true;
298
+
299
+ // NO_PROXY entries may include a port. Strip it only after handling
300
+ // bracketed IPv6 literals, which can contain several colons.
301
+ let hostEntry = trimmed;
302
+ let entryPort: string | undefined;
303
+ if (hostEntry.startsWith("[")) {
304
+ const closingBracket = hostEntry.indexOf("]");
305
+ if (closingBracket >= 0) {
306
+ const suffix = hostEntry.slice(closingBracket + 1);
307
+ if (/^:\\d+$/.test(suffix)) entryPort = suffix.slice(1);
308
+ hostEntry = hostEntry.slice(0, closingBracket + 1);
309
+ }
310
+ } else {
311
+ const colon = hostEntry.lastIndexOf(":");
312
+ if (colon > -1 && /^\d+$/.test(hostEntry.slice(colon + 1))) {
313
+ entryPort = hostEntry.slice(colon + 1);
314
+ hostEntry = hostEntry.slice(0, colon);
315
+ }
316
+ }
317
+ if (entryPort !== undefined && entryPort !== port) return false;
318
+
319
+ const normalizedEntry = normalizeHostname(hostEntry);
320
+ if (!normalizedEntry) return false;
321
+ if (normalizedEntry === hostname) return true;
322
+ const suffix = normalizedEntry.startsWith("*.")
323
+ ? normalizedEntry.slice(1)
324
+ : normalizedEntry.startsWith(".")
325
+ ? normalizedEntry
326
+ : `.${normalizedEntry}`;
327
+ return hostname.endsWith(suffix);
328
+ }
329
+
330
+ function shouldTrustEnvProxy(url: URL, enabled: boolean): boolean {
331
+ if (!enabled || !getProxyForProtocol(url.protocol)) return false;
332
+ if (hasScopedProxyDecision()) return false;
333
+ const activeProxy = getActiveProxy();
334
+ if (activeProxy && !isProxyBypassedUrl(url)) return false;
335
+ const hostname = normalizeHostname(url.hostname);
336
+ const port = url.port || (url.protocol === "https:" ? "443" : "80");
337
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
338
+ return !noProxy.split(",").some(entry => hostnameMatchesNoProxy(hostname, port, entry));
339
+ }
340
+
341
+ function assertPublicAddress(address: string, hostname: string, allowRanges: ParsedCidr[] = []): void {
342
+ const normalized = normalizeHostname(address);
343
+ const ipVersion = net.isIP(normalized);
344
+ if (ipVersion === 0) throw new Error(`Resolved non-IP address for ${hostname}: ${address}`);
345
+ // Explicitly-allowed ranges bypass the private/reserved checks below. This lets
346
+ // users exempt synthetic ranges produced by TUN/fake-IP proxies (e.g. 198.18/15).
347
+ if (isInAllowedRange(normalized, ipVersion, allowRanges)) return;
348
+ if (ipVersion === 4 && isBlockedIPv4(normalized)) {
349
+ const hint = isFakeIpProxyAddress(normalized)
350
+ ? '. This address is in 198.18.0.0/15, commonly used by TUN/fake-IP proxies. If that matches your setup, configure ssrf.allowRanges with ["198.18.0.0/15"] in web-search.json.'
351
+ : "";
352
+ throw new Error(`Blocked internal address for ${hostname}: ${normalized}${hint}`);
353
+ }
354
+ if (ipVersion === 6 && isBlockedIPv6(normalized)) {
355
+ throw new Error(`Blocked internal address for ${hostname}: ${normalized}`);
356
+ }
357
+ }
358
+
359
+ function isFakeIpProxyAddress(address: string): boolean {
360
+ const [a, b] = address.split(".").map(part => Number(part));
361
+ return a === 198 && (b === 18 || b === 19);
362
+ }
363
+
364
+ function isBlockedIPv4(address: string): boolean {
365
+ const parts = address.split(".").map(part => Number(part));
366
+ if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return true;
367
+ const [a, b] = parts;
368
+ return a === 0 ||
369
+ a === 10 ||
370
+ a === 127 ||
371
+ (a === 100 && b >= 64 && b <= 127) ||
372
+ (a === 169 && b === 254) ||
373
+ (a === 172 && b >= 16 && b <= 31) ||
374
+ (a === 192 && b === 168) ||
375
+ isFakeIpProxyAddress(address) ||
376
+ a >= 224;
377
+ }
378
+
379
+ function isBlockedIPv6(address: string): boolean {
380
+ const groups = parseIPv6(address);
381
+ if (!groups) return true;
382
+
383
+ const first = groups[0];
384
+ if (groups.every(group => group === 0)) return true;
385
+ if (groups.slice(0, 7).every(group => group === 0) && groups[7] === 1) return true;
386
+ if ((first & 0xfe00) === 0xfc00) return true;
387
+ if ((first & 0xffc0) === 0xfe80) return true;
388
+
389
+ const isMappedIPv4 = groups.slice(0, 5).every(group => group === 0) && groups[5] === 0xffff;
390
+ if (isMappedIPv4) {
391
+ const ipv4 = [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff].join(".");
392
+ return isBlockedIPv4(ipv4);
393
+ }
394
+
395
+ return false;
396
+ }
397
+
398
+ function parseIPv6(address: string): number[] | null {
399
+ if (address.includes(".")) {
400
+ const lastColon = address.lastIndexOf(":");
401
+ const ipv4 = address.slice(lastColon + 1);
402
+ if (net.isIP(ipv4) !== 4) return null;
403
+ const octets = ipv4.split(".").map(part => Number(part));
404
+ address = `${address.slice(0, lastColon)}:${((octets[0] << 8) | octets[1]).toString(16)}:${((octets[2] << 8) | octets[3]).toString(16)}`;
405
+ }
406
+
407
+ const pieces = address.split("::");
408
+ if (pieces.length > 2) return null;
409
+
410
+ const left = pieces[0] ? pieces[0].split(":") : [];
411
+ const right = pieces.length === 2 && pieces[1] ? pieces[1].split(":") : [];
412
+ const missing = 8 - left.length - right.length;
413
+ if (pieces.length === 1 && missing !== 0) return null;
414
+ if (pieces.length === 2 && missing < 0) return null;
415
+
416
+ const groups = [...left, ...Array(missing).fill("0"), ...right].map(part => {
417
+ if (!/^[0-9a-f]{1,4}$/i.test(part)) return -1;
418
+ return parseInt(part, 16);
419
+ });
420
+ return groups.length === 8 && groups.every(group => group >= 0 && group <= 0xffff) ? groups : null;
421
+ }
422
+
423
+ /** Parse `allowRanges` config value into validated CIDR rules. Throws on malformed entries. */
424
+ function parseAllowRanges(input: unknown): ParsedCidr[] {
425
+ if (input === undefined || input === null) return [];
426
+ if (!Array.isArray(input)) {
427
+ throw new Error("ssrf.allowRanges must be an array of CIDR strings");
428
+ }
429
+ const rules: ParsedCidr[] = [];
430
+ for (const entry of input) {
431
+ if (typeof entry !== "string") {
432
+ throw new Error(`ssrf.allowRanges entries must be strings, got ${typeof entry}`);
433
+ }
434
+ const rule = parseCidr(entry.trim());
435
+ if (!rule) {
436
+ throw new Error(`Invalid CIDR notation in ssrf.allowRanges: "${entry}"`);
437
+ }
438
+ rules.push(rule);
439
+ }
440
+ return rules;
441
+ }
442
+
443
+ /** Parse a single CIDR (e.g. "198.18.0.0/15", "fd00::/8") or bare host ("1.2.3.4"). Returns null if invalid. */
444
+ function parseCidr(raw: string): ParsedCidr | null {
445
+ if (!raw) return null;
446
+ const slash = raw.lastIndexOf("/");
447
+ const addrPart = slash >= 0 ? raw.slice(0, slash) : raw;
448
+ const prefixPart = slash >= 0 ? raw.slice(slash + 1) : null;
449
+ // A slash must be followed by digits. Number("")/Number(" ") are 0, which
450
+ // would silently turn "198.18.0.0/" into /0 and exempt every address.
451
+ if (prefixPart !== null && !/^\d+$/.test(prefixPart)) return null;
452
+ const version = net.isIP(addrPart);
453
+
454
+ if (version === 4) {
455
+ const bytes = ipv4ToBytes(addrPart);
456
+ if (!bytes) return null;
457
+ const prefix = prefixPart === null ? 32 : Number(prefixPart);
458
+ if (!Number.isInteger(prefix) || prefix < 1 || prefix > 32) return null;
459
+ return { bytes, prefix };
460
+ }
461
+ if (version === 6) {
462
+ const groups = parseIPv6(addrPart);
463
+ if (!groups) return null;
464
+ const prefix = prefixPart === null ? 128 : Number(prefixPart);
465
+ if (!Number.isInteger(prefix) || prefix < 1 || prefix > 128) return null;
466
+ return { bytes: ipv6GroupsToBytes(groups), prefix };
467
+ }
468
+ return null;
469
+ }
470
+
471
+ function ipv4ToBytes(address: string): Uint8Array | null {
472
+ const parts = address.split(".");
473
+ if (parts.length !== 4) return null;
474
+ const bytes = new Uint8Array(4);
475
+ for (let i = 0; i < 4; i++) {
476
+ const octet = Number(parts[i]);
477
+ if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;
478
+ bytes[i] = octet;
479
+ }
480
+ return bytes;
481
+ }
482
+
483
+ function ipv6GroupsToBytes(groups: number[]): Uint8Array {
484
+ const bytes = new Uint8Array(16);
485
+ for (let i = 0; i < 8; i++) {
486
+ bytes[i * 2] = groups[i] >> 8;
487
+ bytes[i * 2 + 1] = groups[i] & 0xff;
488
+ }
489
+ return bytes;
490
+ }
491
+
492
+ function ipToBytes(address: string, version: number): Uint8Array | null {
493
+ if (version === 4) return ipv4ToBytes(address);
494
+ if (version === 6) {
495
+ const groups = parseIPv6(address);
496
+ return groups ? ipv6GroupsToBytes(groups) : null;
497
+ }
498
+ return null;
499
+ }
500
+
501
+ /** True if `address` (already validated as `ipVersion`) falls within any allowed CIDR. */
502
+ function isInAllowedRange(address: string, ipVersion: number, allowRanges: ParsedCidr[]): boolean {
503
+ if (allowRanges.length === 0) return false;
504
+ const addrBytes = ipToBytes(address, ipVersion);
505
+ if (!addrBytes) return false;
506
+ for (const rule of allowRanges) {
507
+ // Only compare same-family rules (4-byte IPv4 vs 16-byte IPv6).
508
+ if (rule.bytes.length !== addrBytes.length) continue;
509
+ if (bytesMatchPrefix(addrBytes, rule.bytes, rule.prefix)) return true;
510
+ }
511
+ return false;
512
+ }
513
+
514
+ /** Compare the leading `prefix` bits of two equal-length byte arrays. */
515
+ function bytesMatchPrefix(addr: Uint8Array, network: Uint8Array, prefix: number): boolean {
516
+ const fullBytes = prefix >> 3;
517
+ const remBits = prefix & 7;
518
+ for (let i = 0; i < fullBytes; i++) {
519
+ if (addr[i] !== network[i]) return false;
520
+ }
521
+ if (remBits > 0 && fullBytes < addr.length) {
522
+ const mask = (0xff << (8 - remBits)) & 0xff;
523
+ if ((addr[fullBytes] & mask) !== (network[fullBytes] & mask)) return false;
524
+ }
525
+ return true;
526
+ }