@abhishek944/pi-web-access 0.0.0-stage → 0.1.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 (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
@@ -0,0 +1,602 @@
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, loadConfiguredProxy, normalizeProxyUrl } 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
+ // Proxy schemes where the proxy, not curl, resolves the target hostname.
10
+ const REMOTE_DNS_PROXY_PROTOCOLS = new Set(["http:", "https:", "socks4a:", "socks5h:"]);
11
+
12
+ export type LookupAddress = { address: string; family: number };
13
+ export type Lookup = (hostname: string) => Promise<LookupAddress[]>;
14
+ type Fetch = typeof fetch;
15
+
16
+ const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
17
+
18
+ let cachedConfigRoot: { signature: string; value: Record<string, unknown> | null } | null = null;
19
+
20
+ function loadConfigRoot(): Record<string, unknown> | null {
21
+ if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return null;
22
+
23
+ let signature: string;
24
+ try {
25
+ const stat = statSync(WEB_SEARCH_CONFIG_PATH);
26
+ signature = `${stat.mtimeMs}:${stat.size}`;
27
+ } catch {
28
+ return null;
29
+ }
30
+
31
+ if (cachedConfigRoot?.signature === signature) return cachedConfigRoot.value;
32
+
33
+ let raw: string;
34
+ try {
35
+ raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
36
+ } catch {
37
+ // Do not memoize read failures: a chmod fix changes neither mtime nor size,
38
+ // so a cached failure would permanently fail-open the domain policy.
39
+ return null;
40
+ }
41
+
42
+ let parsed: unknown;
43
+ try {
44
+ parsed = JSON.parse(raw);
45
+ } catch (err) {
46
+ const message = err instanceof Error ? err.message : String(err);
47
+ throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
48
+ }
49
+
50
+ const value = parsed && typeof parsed === "object" && !Array.isArray(parsed)
51
+ ? parsed as Record<string, unknown>
52
+ : null;
53
+ cachedConfigRoot = { signature, value };
54
+ return value;
55
+ }
56
+
57
+ export interface SsrfConfig {
58
+ allowRanges: string[];
59
+ trustEnvProxy: boolean;
60
+ }
61
+
62
+ export interface DomainPolicy {
63
+ allow: string[];
64
+ deny: string[];
65
+ }
66
+
67
+ const DEFAULT_DOMAIN_POLICY: DomainPolicy = { allow: [], deny: [] };
68
+
69
+ export type RedirectPolicy = "same-origin";
70
+
71
+ function loadFetchContentConfig(): Record<string, unknown> | undefined {
72
+ const parsed = loadConfigRoot();
73
+ if (!parsed) return undefined;
74
+ const fetchContent = parsed.fetchContent;
75
+ if (fetchContent === undefined || fetchContent === null) return undefined;
76
+ if (typeof fetchContent !== "object" || Array.isArray(fetchContent)) {
77
+ throw new Error(`fetchContent in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
78
+ }
79
+ return fetchContent as Record<string, unknown>;
80
+ }
81
+
82
+ export function loadFetchContentRedirectPolicy(): RedirectPolicy | undefined {
83
+ const redirects = loadFetchContentConfig()?.redirects;
84
+ if (redirects === undefined || redirects === null) return undefined;
85
+ if (redirects !== "same-origin") {
86
+ throw new Error(`fetchContent.redirects in ${WEB_SEARCH_CONFIG_PATH} must be "same-origin"`);
87
+ }
88
+ return redirects;
89
+ }
90
+
91
+ const DEFAULT_FETCH_CONTENT_USER_AGENT = "OpenAI File Downloader, XaiImageApiFetch/1.0";
92
+
93
+ export function loadFetchContentUserAgent(): string {
94
+ return loadConfiguredFetchContentUserAgent() ?? DEFAULT_FETCH_CONTENT_USER_AGENT;
95
+ }
96
+
97
+ /** fetchContent.userAgent when it is set, without the default. */
98
+ export function loadConfiguredFetchContentUserAgent(): string | undefined {
99
+ const userAgent = loadFetchContentConfig()?.userAgent;
100
+ if (userAgent === undefined || userAgent === null) return undefined;
101
+ if (typeof userAgent !== "string" || userAgent.trim().length === 0 || !/^[\t\x20-\x7e]+$/.test(userAgent)) {
102
+ throw new Error(`fetchContent.userAgent in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty string of printable ASCII characters`);
103
+ }
104
+ return userAgent.trim();
105
+ }
106
+
107
+ /** fetchContent.curl as an executable plus leading arguments, or null to use Node's fetch. */
108
+ export function loadFetchContentCurl(): string[] | null {
109
+ const curl = loadFetchContentConfig()?.curl;
110
+ if (curl === undefined || curl === null) return null;
111
+ const command: unknown[] | null = typeof curl === "string" ? [curl] : Array.isArray(curl) ? curl : null;
112
+ if (!command || command.length === 0 || command.some((part) => typeof part !== "string" || part.trim().length === 0 || part.includes("\0"))) {
113
+ throw new Error(`fetchContent.curl in ${WEB_SEARCH_CONFIG_PATH} must be a command name or path, or a non-empty array of a command and its arguments`);
114
+ }
115
+ return command.map((part) => (part as string).trim());
116
+ }
117
+
118
+ export function loadFetchContentDomainPolicy(): DomainPolicy {
119
+ const policy = loadFetchContentConfig()?.domainPolicy;
120
+ if (policy === undefined || policy === null) return { ...DEFAULT_DOMAIN_POLICY };
121
+ if (typeof policy !== "object" || Array.isArray(policy)) {
122
+ throw new Error(`fetchContent.domainPolicy in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
123
+ }
124
+ const config = policy as { allow?: unknown; deny?: unknown };
125
+ return {
126
+ allow: parseDomainEntries(config.allow, "allow"),
127
+ deny: parseDomainEntries(config.deny, "deny"),
128
+ };
129
+ }
130
+
131
+ function parseDomainEntries(value: unknown, field: "allow" | "deny"): string[] {
132
+ if (value === undefined || value === null) return [];
133
+ if (!Array.isArray(value)) {
134
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hostnames`);
135
+ }
136
+ return value.map((entry, index) => {
137
+ if (typeof entry !== "string") {
138
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames; entry ${index + 1} is ${typeof entry}`);
139
+ }
140
+ const hostname = normalizeDomainEntry(entry);
141
+ if (!hostname) {
142
+ throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(entry)}`);
143
+ }
144
+ return hostname;
145
+ });
146
+ }
147
+
148
+ function normalizeDomainEntry(entry: string): string | null {
149
+ const hostname = normalizeHostname(entry.trim());
150
+ if (!hostname || /\s|[\\/?:#@]/.test(hostname)) return null;
151
+ if (net.isIP(hostname)) return hostname;
152
+ 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;
153
+ return hostname;
154
+ }
155
+
156
+ export function loadSsrfConfig(): SsrfConfig {
157
+ const parsed = loadConfigRoot();
158
+ if (!parsed) return { allowRanges: [], trustEnvProxy: false };
159
+ const ssrf = parsed.ssrf;
160
+ if (ssrf === undefined || ssrf === null) return { allowRanges: [], trustEnvProxy: false };
161
+ if (typeof ssrf !== "object" || Array.isArray(ssrf)) {
162
+ throw new Error(`ssrf in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
163
+ }
164
+ const config = ssrf as { allowRanges?: unknown; trustEnvProxy?: unknown };
165
+ if (config.allowRanges !== undefined && config.allowRanges !== null && !Array.isArray(config.allowRanges)) {
166
+ throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must be an array of CIDR strings`);
167
+ }
168
+ if (config.trustEnvProxy !== undefined && typeof config.trustEnvProxy !== "boolean") {
169
+ throw new Error(`ssrf.trustEnvProxy in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
170
+ }
171
+ const allowRangesValue: unknown[] = Array.isArray(config.allowRanges) ? config.allowRanges : [];
172
+ const allowRanges = allowRangesValue.map((entry, index) => {
173
+ if (typeof entry !== "string") {
174
+ throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must contain only CIDR strings; entry ${index + 1} is ${typeof entry}`);
175
+ }
176
+ return entry.trim();
177
+ }).filter(Boolean);
178
+ parseAllowRanges(allowRanges);
179
+ return { allowRanges, trustEnvProxy: config.trustEnvProxy === true };
180
+ }
181
+
182
+ interface ValidationOptions {
183
+ lookup?: Lookup;
184
+ /** Optional hostname policy for fetch_content target URLs. */
185
+ domainPolicy?: DomainPolicy;
186
+ /**
187
+ * CIDR ranges (e.g. "198.18.0.0/15") to exempt from the SSRF guard.
188
+ * Useful when a host runs a TUN/fake-IP proxy (Surge, Clash, Mihomo, ...)
189
+ * that resolves public domains into a reserved range. Entries are validated
190
+ * strictly; an invalid entry throws so misconfiguration is not silent.
191
+ */
192
+ allowRanges?: string[];
193
+ /**
194
+ * When true, let the proxy carrying the request resolve hostnames instead of
195
+ * performing local DNS lookups: an HTTP(S) proxy from the environment, or the
196
+ * `proxy` configured in web-search.json. A different per-call proxy never
197
+ * qualifies. Literal IPs and localhost remain blocked, and NO_PROXY hosts still
198
+ * use the local SSRF preflight. This does not configure proxy transport.
199
+ */
200
+ trustEnvProxy?: boolean;
201
+ /** Proxy pinned on the request via `__proxy`; defaults to the scoped proxy, like the transport. */
202
+ proxy?: string;
203
+ /** Allow loopback URLs for explicit provider base endpoints, not fetched targets. */
204
+ allowLoopback?: boolean;
205
+ }
206
+
207
+ /** Parsed entry from `allowRanges`: a network address (4 or 16 bytes) + prefix length. */
208
+ interface ParsedCidr {
209
+ bytes: Uint8Array;
210
+ prefix: number;
211
+ }
212
+
213
+ interface RedirectRequestInitArgs {
214
+ from: URL;
215
+ to: URL;
216
+ init: RequestInit;
217
+ response: Response;
218
+ }
219
+
220
+ interface FetchRemoteOptions extends ValidationOptions {
221
+ fetch?: Fetch;
222
+ maxRedirects?: number;
223
+ onRedirect?: (args: RedirectRequestInitArgs) => RequestInit;
224
+ /** "same-origin" refuses any redirect that leaves the original URL's origin. */
225
+ redirects?: RedirectPolicy;
226
+ }
227
+
228
+ async function defaultLookup(hostname: string): Promise<LookupAddress[]> {
229
+ return dnsLookup(hostname, { all: true, verbatim: true });
230
+ }
231
+
232
+ export async function validateRemoteUrl(rawUrl: string | URL, options: ValidationOptions = {}): Promise<URL> {
233
+ const url = rawUrl instanceof URL ? rawUrl : new URL(rawUrl);
234
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
235
+ throw new Error("Only HTTP and HTTPS URLs can be fetched remotely");
236
+ }
237
+
238
+ const hostname = normalizeHostname(url.hostname);
239
+ if (!hostname) throw new Error("URL must include a hostname");
240
+ if (hostname === "localhost") {
241
+ if (options.allowLoopback === true) return url;
242
+ throw new Error(`Blocked internal hostname: ${hostname}`);
243
+ }
244
+ if (hostname.endsWith(".localhost")) {
245
+ throw new Error(`Blocked internal hostname: ${hostname}`);
246
+ }
247
+
248
+ const allowRanges = parseAllowRanges(options.allowRanges);
249
+ assertDomainPolicy(hostname, options.domainPolicy);
250
+
251
+ if (net.isIP(hostname)) {
252
+ const addressAllowRanges = options.allowLoopback === true
253
+ ? [...allowRanges, ...parseAllowRanges(LOOPBACK_ALLOW_RANGES)]
254
+ : allowRanges;
255
+ assertPublicAddress(hostname, hostname, addressAllowRanges);
256
+ return url;
257
+ }
258
+
259
+ const trustProxy = options.trustEnvProxy === true;
260
+ const proxy = options.proxy !== undefined
261
+ ? normalizeProxyUrl(options.proxy, "proxy")
262
+ : hasScopedProxyDecision() ? getActiveProxy() : undefined;
263
+ if (proxy === undefined ? shouldTrustEnvProxy(url, trustProxy) : trustProxy && isConfiguredRemoteDnsProxy(url, proxy)) return url;
264
+
265
+ let addresses: LookupAddress[];
266
+ try {
267
+ addresses = await (options.lookup ?? defaultLookup)(hostname);
268
+ } catch (err) {
269
+ const message = err instanceof Error ? err.message : String(err);
270
+ const hint = !trustProxy && proxy && isConfiguredRemoteDnsProxy(url, proxy)
271
+ ? ". If your configured proxy resolves hostnames, set ssrf.trustEnvProxy to true in web-search.json."
272
+ : "";
273
+ throw new Error(`Failed to resolve ${hostname}: ${message}${hint}`);
274
+ }
275
+
276
+ if (addresses.length === 0) throw new Error(`Failed to resolve ${hostname}: no addresses returned`);
277
+ for (const { address } of addresses) {
278
+ assertPublicAddress(address, hostname, allowRanges);
279
+ }
280
+ return url;
281
+ }
282
+
283
+ export async function fetchRemoteUrl(
284
+ url: string | URL,
285
+ init: RequestInit = {},
286
+ options: FetchRemoteOptions = {},
287
+ ): Promise<Response> {
288
+ const fetchImpl = options.fetch ?? fetch;
289
+ const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
290
+ let current = await validateRemoteUrl(url, options);
291
+ const configuredOrigin = current.origin;
292
+ let requestInit = init;
293
+
294
+ for (let redirects = 0; redirects <= maxRedirects; redirects++) {
295
+ const response = await fetchImpl(current, { ...requestInit, redirect: "manual" });
296
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
297
+
298
+ const location = response.headers.get("location");
299
+ if (!location) return response;
300
+ if (redirects === maxRedirects) throw new Error(`Too many redirects fetching ${current.toString()}`);
301
+
302
+ const from = current;
303
+ const next = new URL(location, current);
304
+ if (options.redirects === "same-origin" && next.origin !== configuredOrigin) {
305
+ throw new Error(`Refused cross-origin redirect by fetch_content redirect policy: ${configuredOrigin} -> ${next.origin}`);
306
+ }
307
+ // allowLoopback exempts an explicitly configured endpoint, never a redirect target: a loopback
308
+ // base must not be able to pivot the request onto a different loopback origin.
309
+ current = await validateRemoteUrl(next, next.origin === configuredOrigin ? options : { ...options, allowLoopback: false });
310
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
311
+ const { body: _body, ...nextInit } = requestInit;
312
+ requestInit = { ...nextInit, method: "GET" };
313
+ }
314
+ if (options.onRedirect) requestInit = options.onRedirect({ from, to: current, init: requestInit, response });
315
+ }
316
+
317
+ throw new Error(`Too many redirects fetching ${current.toString()}`);
318
+ }
319
+
320
+ function normalizeHostname(hostname: string): string {
321
+ return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
322
+ }
323
+
324
+ function assertDomainPolicy(hostname: string, policy?: DomainPolicy): void {
325
+ if (!policy) return;
326
+ if (policy.deny.some((entry) => domainMatches(hostname, entry))) {
327
+ throw new Error(`Blocked hostname by fetch_content domain policy: ${hostname}`);
328
+ }
329
+ if (policy.allow.length > 0 && !policy.allow.some((entry) => domainMatches(hostname, entry))) {
330
+ throw new Error(`Hostname not allowed by fetch_content domain policy: ${hostname}`);
331
+ }
332
+ }
333
+
334
+ function domainMatches(hostname: string, entry: string): boolean {
335
+ return hostname === entry || hostname.endsWith(`.${entry}`);
336
+ }
337
+
338
+ function getProxyForProtocol(protocol: string): string {
339
+ const candidates = protocol === "http:"
340
+ ? [process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
341
+ : protocol === "https:"
342
+ ? [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy, process.env.ALL_PROXY, process.env.all_proxy]
343
+ : [];
344
+ for (const candidate of candidates) {
345
+ const value = candidate?.trim();
346
+ if (!value) continue;
347
+ try {
348
+ const proxyUrl = new URL(value);
349
+ if ((proxyUrl.protocol === "http:" || proxyUrl.protocol === "https:") && proxyUrl.hostname) return value;
350
+ } catch {
351
+ // Invalid proxy env vars should not weaken local DNS SSRF checks.
352
+ }
353
+ }
354
+ return "";
355
+ }
356
+
357
+ function hostnameMatchesNoProxy(hostname: string, port: string, entry: string): boolean {
358
+ const trimmed = entry.trim();
359
+ if (!trimmed) return false;
360
+ if (trimmed === "*") return true;
361
+
362
+ // NO_PROXY entries may include a port. Strip it only after handling
363
+ // bracketed IPv6 literals, which can contain several colons.
364
+ let hostEntry = trimmed;
365
+ let entryPort: string | undefined;
366
+ if (hostEntry.startsWith("[")) {
367
+ const closingBracket = hostEntry.indexOf("]");
368
+ if (closingBracket >= 0) {
369
+ const suffix = hostEntry.slice(closingBracket + 1);
370
+ if (/^:\\d+$/.test(suffix)) entryPort = suffix.slice(1);
371
+ hostEntry = hostEntry.slice(0, closingBracket + 1);
372
+ }
373
+ } else {
374
+ const colon = hostEntry.lastIndexOf(":");
375
+ if (colon > -1 && /^\d+$/.test(hostEntry.slice(colon + 1))) {
376
+ entryPort = hostEntry.slice(colon + 1);
377
+ hostEntry = hostEntry.slice(0, colon);
378
+ }
379
+ }
380
+ if (entryPort !== undefined && entryPort !== port) return false;
381
+
382
+ const normalizedEntry = normalizeHostname(hostEntry);
383
+ if (!normalizedEntry) return false;
384
+ if (normalizedEntry === hostname) return true;
385
+ const suffix = normalizedEntry.startsWith("*.")
386
+ ? normalizedEntry.slice(1)
387
+ : normalizedEntry.startsWith(".")
388
+ ? normalizedEntry
389
+ : `.${normalizedEntry}`;
390
+ return hostname.endsWith(suffix);
391
+ }
392
+
393
+ function shouldTrustEnvProxy(url: URL, enabled: boolean): boolean {
394
+ if (!enabled || !getProxyForProtocol(url.protocol)) return false;
395
+ const hostname = normalizeHostname(url.hostname);
396
+ const port = url.port || (url.protocol === "https:" ? "443" : "80");
397
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
398
+ return !noProxy.split(",").some(entry => hostnameMatchesNoProxy(hostname, port, entry));
399
+ }
400
+
401
+ /** The env proxy validateRemoteUrl trusts to resolve this URL instead of checking DNS locally, or null.
402
+ * A fetch that skipped the local check because of it must connect through it. */
403
+ export function trustedEnvProxyFor(url: URL, trustEnvProxy: boolean): string | null {
404
+ // IP literals are always checked locally, so they keep connecting directly.
405
+ if (net.isIP(normalizeHostname(url.hostname))) return null;
406
+ return shouldTrustEnvProxy(url, trustEnvProxy) ? getProxyForProtocol(url.protocol) : null;
407
+ }
408
+
409
+ /** Only the operator's configured proxy qualifies: a model-supplied per-call proxy must not skip DNS validation. */
410
+ function isConfiguredRemoteDnsProxy(url: URL, proxy: string | null): boolean {
411
+ return proxy !== null &&
412
+ REMOTE_DNS_PROXY_PROTOCOLS.has(new URL(proxy).protocol) &&
413
+ !isProxyBypassedUrl(url) &&
414
+ proxy === loadConfiguredProxy();
415
+ }
416
+
417
+ function assertPublicAddress(address: string, hostname: string, allowRanges: ParsedCidr[] = []): void {
418
+ const normalized = normalizeHostname(address);
419
+ const ipVersion = net.isIP(normalized);
420
+ if (ipVersion === 0) throw new Error(`Resolved non-IP address for ${hostname}: ${address}`);
421
+ // Explicitly-allowed ranges bypass the private/reserved checks below. This lets
422
+ // users exempt synthetic ranges produced by TUN/fake-IP proxies (e.g. 198.18/15).
423
+ if (isInAllowedRange(normalized, ipVersion, allowRanges)) return;
424
+ if (ipVersion === 4 && isBlockedIPv4(normalized)) {
425
+ const hint = isFakeIpProxyAddress(normalized)
426
+ ? '. 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.'
427
+ : "";
428
+ throw new Error(`Blocked internal address for ${hostname}: ${normalized}${hint}`);
429
+ }
430
+ if (ipVersion === 6 && isBlockedIPv6(normalized)) {
431
+ throw new Error(`Blocked internal address for ${hostname}: ${normalized}`);
432
+ }
433
+ }
434
+
435
+ function isFakeIpProxyAddress(address: string): boolean {
436
+ const [a, b] = address.split(".").map(part => Number(part));
437
+ return a === 198 && (b === 18 || b === 19);
438
+ }
439
+
440
+ function isBlockedIPv4(address: string): boolean {
441
+ const parts = address.split(".").map(part => Number(part));
442
+ if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return true;
443
+ const [a, b] = parts;
444
+ return a === 0 ||
445
+ a === 10 ||
446
+ a === 127 ||
447
+ (a === 100 && b >= 64 && b <= 127) ||
448
+ (a === 169 && b === 254) ||
449
+ (a === 172 && b >= 16 && b <= 31) ||
450
+ (a === 192 && b === 168) ||
451
+ isFakeIpProxyAddress(address) ||
452
+ a >= 224;
453
+ }
454
+
455
+ function isBlockedIPv6(address: string): boolean {
456
+ const groups = parseIPv6(address);
457
+ if (!groups) return true;
458
+
459
+ const first = groups[0];
460
+ if (groups.every(group => group === 0)) return true;
461
+ if (groups.slice(0, 7).every(group => group === 0) && groups[7] === 1) return true;
462
+ if ((first & 0xfe00) === 0xfc00) return true;
463
+ if ((first & 0xffc0) === 0xfe80) return true;
464
+
465
+ const isMappedIPv4 = groups.slice(0, 5).every(group => group === 0) && groups[5] === 0xffff;
466
+ if (isMappedIPv4) {
467
+ const ipv4 = [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff].join(".");
468
+ return isBlockedIPv4(ipv4);
469
+ }
470
+
471
+ return false;
472
+ }
473
+
474
+ function parseIPv6(address: string): number[] | null {
475
+ if (address.includes(".")) {
476
+ const lastColon = address.lastIndexOf(":");
477
+ const ipv4 = address.slice(lastColon + 1);
478
+ if (net.isIP(ipv4) !== 4) return null;
479
+ const octets = ipv4.split(".").map(part => Number(part));
480
+ address = `${address.slice(0, lastColon)}:${((octets[0] << 8) | octets[1]).toString(16)}:${((octets[2] << 8) | octets[3]).toString(16)}`;
481
+ }
482
+
483
+ const pieces = address.split("::");
484
+ if (pieces.length > 2) return null;
485
+
486
+ const left = pieces[0] ? pieces[0].split(":") : [];
487
+ const right = pieces.length === 2 && pieces[1] ? pieces[1].split(":") : [];
488
+ const missing = 8 - left.length - right.length;
489
+ if (pieces.length === 1 && missing !== 0) return null;
490
+ if (pieces.length === 2 && missing < 0) return null;
491
+
492
+ const groups = [...left, ...Array(missing).fill("0"), ...right].map(part => {
493
+ if (!/^[0-9a-f]{1,4}$/i.test(part)) return -1;
494
+ return parseInt(part, 16);
495
+ });
496
+ return groups.length === 8 && groups.every(group => group >= 0 && group <= 0xffff) ? groups : null;
497
+ }
498
+
499
+ /** Parse `allowRanges` config value into validated CIDR rules. Throws on malformed entries. */
500
+ function parseAllowRanges(input: unknown): ParsedCidr[] {
501
+ if (input === undefined || input === null) return [];
502
+ if (!Array.isArray(input)) {
503
+ throw new Error("ssrf.allowRanges must be an array of CIDR strings");
504
+ }
505
+ const rules: ParsedCidr[] = [];
506
+ for (const entry of input) {
507
+ if (typeof entry !== "string") {
508
+ throw new Error(`ssrf.allowRanges entries must be strings, got ${typeof entry}`);
509
+ }
510
+ const rule = parseCidr(entry.trim());
511
+ if (!rule) {
512
+ throw new Error(`Invalid CIDR notation in ssrf.allowRanges: "${entry}"`);
513
+ }
514
+ rules.push(rule);
515
+ }
516
+ return rules;
517
+ }
518
+
519
+ /** Parse a single CIDR (e.g. "198.18.0.0/15", "fd00::/8") or bare host ("1.2.3.4"). Returns null if invalid. */
520
+ function parseCidr(raw: string): ParsedCidr | null {
521
+ if (!raw) return null;
522
+ const slash = raw.lastIndexOf("/");
523
+ const addrPart = slash >= 0 ? raw.slice(0, slash) : raw;
524
+ const prefixPart = slash >= 0 ? raw.slice(slash + 1) : null;
525
+ // A slash must be followed by digits. Number("")/Number(" ") are 0, which
526
+ // would silently turn "198.18.0.0/" into /0 and exempt every address.
527
+ if (prefixPart !== null && !/^\d+$/.test(prefixPart)) return null;
528
+ const version = net.isIP(addrPart);
529
+
530
+ if (version === 4) {
531
+ const bytes = ipv4ToBytes(addrPart);
532
+ if (!bytes) return null;
533
+ const prefix = prefixPart === null ? 32 : Number(prefixPart);
534
+ if (!Number.isInteger(prefix) || prefix < 1 || prefix > 32) return null;
535
+ return { bytes, prefix };
536
+ }
537
+ if (version === 6) {
538
+ const groups = parseIPv6(addrPart);
539
+ if (!groups) return null;
540
+ const prefix = prefixPart === null ? 128 : Number(prefixPart);
541
+ if (!Number.isInteger(prefix) || prefix < 1 || prefix > 128) return null;
542
+ return { bytes: ipv6GroupsToBytes(groups), prefix };
543
+ }
544
+ return null;
545
+ }
546
+
547
+ function ipv4ToBytes(address: string): Uint8Array | null {
548
+ const parts = address.split(".");
549
+ if (parts.length !== 4) return null;
550
+ const bytes = new Uint8Array(4);
551
+ for (let i = 0; i < 4; i++) {
552
+ const octet = Number(parts[i]);
553
+ if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;
554
+ bytes[i] = octet;
555
+ }
556
+ return bytes;
557
+ }
558
+
559
+ function ipv6GroupsToBytes(groups: number[]): Uint8Array {
560
+ const bytes = new Uint8Array(16);
561
+ for (let i = 0; i < 8; i++) {
562
+ bytes[i * 2] = groups[i] >> 8;
563
+ bytes[i * 2 + 1] = groups[i] & 0xff;
564
+ }
565
+ return bytes;
566
+ }
567
+
568
+ function ipToBytes(address: string, version: number): Uint8Array | null {
569
+ if (version === 4) return ipv4ToBytes(address);
570
+ if (version === 6) {
571
+ const groups = parseIPv6(address);
572
+ return groups ? ipv6GroupsToBytes(groups) : null;
573
+ }
574
+ return null;
575
+ }
576
+
577
+ /** True if `address` (already validated as `ipVersion`) falls within any allowed CIDR. */
578
+ function isInAllowedRange(address: string, ipVersion: number, allowRanges: ParsedCidr[]): boolean {
579
+ if (allowRanges.length === 0) return false;
580
+ const addrBytes = ipToBytes(address, ipVersion);
581
+ if (!addrBytes) return false;
582
+ for (const rule of allowRanges) {
583
+ // Only compare same-family rules (4-byte IPv4 vs 16-byte IPv6).
584
+ if (rule.bytes.length !== addrBytes.length) continue;
585
+ if (bytesMatchPrefix(addrBytes, rule.bytes, rule.prefix)) return true;
586
+ }
587
+ return false;
588
+ }
589
+
590
+ /** Compare the leading `prefix` bits of two equal-length byte arrays. */
591
+ function bytesMatchPrefix(addr: Uint8Array, network: Uint8Array, prefix: number): boolean {
592
+ const fullBytes = prefix >> 3;
593
+ const remBits = prefix & 7;
594
+ for (let i = 0; i < fullBytes; i++) {
595
+ if (addr[i] !== network[i]) return false;
596
+ }
597
+ if (remBits > 0 && fullBytes < addr.length) {
598
+ const mask = (0xff << (8 - remBits)) & 0xff;
599
+ if ((addr[fullBytes] & mask) !== (network[fullBytes] & mask)) return false;
600
+ }
601
+ return true;
602
+ }