Spaces:
Paused
Paused
File size: 8,353 Bytes
f55c62a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | import {
Cache,
HEADERS_FOR_IP_FORWARDING,
INTERNAL_SECRET_HEADER,
Env,
maskSensitiveInfo,
} from './index.js';
import { config as appConfig } from '../config/index.js';
import {
BodyInit,
Dispatcher,
fetch,
Headers,
HeadersInit,
ProxyAgent,
RequestInit,
} from 'undici';
import { socksDispatcher } from 'fetch-socks';
import { createLogger } from '../logging/logger.js';
const logger = createLogger('http');
const urlCount = Cache.getInstance<string, number>(
'url-count',
undefined,
'memory'
);
export class PossibleRecursiveRequestError extends Error {
constructor(message: string) {
super(message);
this.name = 'PossibleRecursiveRequestError';
}
}
export function makeUrlLogSafe(url: string) {
// for each component of the path, if it is longer than 10 characters, mask it
// and replace the query params of key 'password' with '****'
return url
.split('/')
.map((component) => {
if (component.length > 10 && !component.includes('.')) {
return maskSensitiveInfo(component);
}
return component;
})
.join('/')
.replace(/(?<![^?&])(password=[^&]+)/g, 'password=****')
.replace(/(?<![^?&])(apikey=[^&]+)/gi, 'apikey=****');
}
export interface RequestOptions {
timeout: number;
method?: string;
forwardIp?: string;
ignoreRecursion?: boolean;
headers?: HeadersInit;
body?: BodyInit;
forceProxy?: string;
rawOptions?: RequestInit;
}
export async function makeRequest(url: string, options: RequestOptions) {
const urlObj = new URL(url);
if (
appConfig.bootstrap.baseUrl &&
urlObj.origin === appConfig.bootstrap.baseUrl
) {
const internalUrl = new URL(appConfig.bootstrap.internalUrl);
urlObj.protocol = internalUrl.protocol;
urlObj.host = internalUrl.host;
urlObj.port = internalUrl.port;
}
if (appConfig.http.requestUrlMappings) {
for (const [key, value] of Object.entries(
appConfig.http.requestUrlMappings
)) {
if (urlObj.origin === key) {
const mappedUrl = new URL(value);
urlObj.protocol = mappedUrl.protocol;
urlObj.host = mappedUrl.host;
urlObj.port = mappedUrl.port;
break;
}
}
}
const { useProxy, proxyIndex } = shouldProxy(urlObj);
const headers = new Headers(options.headers);
if (options.forwardIp) {
for (const header of HEADERS_FOR_IP_FORWARDING) {
headers.set(header, options.forwardIp);
}
}
if (urlObj.toString().startsWith(appConfig.bootstrap.internalUrl)) {
headers.set(INTERNAL_SECRET_HEADER, appConfig.bootstrap.internalSecret);
}
let domainUserAgent = domainHasUserAgent(urlObj);
if (domainUserAgent) {
headers.set('User-Agent', domainUserAgent);
}
if (
['none', 'false', '', 'undefined'].includes(
(headers.get('User-Agent') ?? '').toLowerCase().trim()
)
) {
headers.delete('User-Agent');
}
// block recursive requests
const key = `${urlObj.toString()}-${options.forwardIp}`;
const currentCount = (await urlCount.get(key)) ?? 0;
if (
currentCount > appConfig.recursion.thresholdLimit &&
!options.ignoreRecursion
) {
logger.warn(
{ url: makeUrlLogSafe(urlObj.toString()), count: currentCount },
'detected possible recursive requests, blocking'
);
throw new PossibleRecursiveRequestError(
`Possible recursive request to ${urlObj.toString()}`
);
}
if (currentCount > 0) {
await urlCount.update(key, currentCount + 1);
} else {
await urlCount.set(key, 1, appConfig.recursion.thresholdWindow);
}
let dispatcher: Dispatcher | undefined;
if (options.forceProxy) {
dispatcher = getProxyAgent(options.forceProxy);
} else if (useProxy) {
dispatcher = getProxyAgent(appConfig.http.addonProxy[proxyIndex]);
}
logger.trace(
{
url: makeUrlLogSafe(urlObj.toString()),
method: options.method ?? 'GET',
proxy: useProxy
? `proxy-${proxyIndex + 1}`
: options.forceProxy
? 'forced'
: 'direct',
},
'http request'
);
let response;
try {
response = await fetch(urlObj.toString(), {
...options.rawOptions,
method: options.method,
body: options.body,
headers: headers,
dispatcher: dispatcher,
signal: AbortSignal.timeout(options.timeout),
});
} catch (err) {
if (
err instanceof Error &&
err.name === 'TypeError' &&
err.message === 'fetch failed' &&
err.cause
) {
const cause = { ...(err.cause as Record<string, any>) };
delete cause.stack;
logger.error({ cause }, 'fetch failed due to network error');
}
throw err;
}
return response;
}
const proxyAgents = new Map<string, Dispatcher>();
export function getProxyAgent(proxyUrl: string): Dispatcher | undefined {
if (!proxyUrl) {
return undefined;
}
let proxyAgent = proxyAgents.get(proxyUrl);
if (!proxyAgent) {
const proxyUrlObj = new URL(proxyUrl);
if (
proxyUrlObj.protocol === 'socks5:' ||
proxyUrlObj.protocol === 'socks5h:'
) {
proxyAgent = socksDispatcher({
type: 5,
port: parseInt(proxyUrlObj.port),
host: proxyUrlObj.hostname,
userId: proxyUrlObj.username || undefined,
password: proxyUrlObj.password || undefined,
});
} else {
proxyAgent = new ProxyAgent(proxyUrl);
}
}
return proxyAgent;
}
export function shouldProxy(url: URL): {
useProxy: boolean;
proxyIndex: number;
} {
let useProxy = false;
let hostname = url.hostname;
let proxyIndex = -1;
if (!appConfig.http.addonProxy || appConfig.http.addonProxy.length === 0) {
return { useProxy: false, proxyIndex };
}
if (hostname === 'localhost') {
return { useProxy: false, proxyIndex };
}
useProxy = true;
if (
appConfig.http.addonProxyConfig &&
Object.keys(appConfig.http.addonProxyConfig).length > 0
) {
for (const [ruleHostname, ruleValue] of Object.entries(
appConfig.http.addonProxyConfig
)) {
const ruleProxyIndexOrBool = String(ruleValue);
if (
['true', 'false'].includes(ruleProxyIndexOrBool) === false &&
isNaN(parseInt(ruleProxyIndexOrBool))
) {
logger.error(
{ hostname: ruleHostname, value: ruleProxyIndexOrBool },
'invalid proxy config value'
);
continue;
}
if (ruleHostname === '*') {
useProxy = !(ruleProxyIndexOrBool === 'false');
proxyIndex = Number.isInteger(parseInt(ruleProxyIndexOrBool))
? parseInt(ruleProxyIndexOrBool)
: ruleProxyIndexOrBool === 'true'
? 0
: -1;
} else if (ruleHostname.startsWith('*')) {
if (hostname.endsWith(ruleHostname.slice(1))) {
useProxy = !(ruleProxyIndexOrBool === 'false');
proxyIndex = Number.isInteger(parseInt(ruleProxyIndexOrBool))
? parseInt(ruleProxyIndexOrBool)
: ruleProxyIndexOrBool === 'true'
? 0
: -1;
}
}
if (hostname === ruleHostname) {
useProxy = !(ruleProxyIndexOrBool === 'false');
proxyIndex = Number.isInteger(parseInt(ruleProxyIndexOrBool))
? parseInt(ruleProxyIndexOrBool)
: ruleProxyIndexOrBool === 'true'
? 0
: -1;
}
}
} else {
proxyIndex = 0;
}
if (useProxy && appConfig.http.addonProxy[proxyIndex] === undefined) {
logger.error({ proxyIndex }, 'proxy index out of range');
return { useProxy: false, proxyIndex: -1 };
}
return { useProxy, proxyIndex };
}
export function domainHasUserAgent(url: URL) {
let userAgent: string | undefined;
let hostname = url.hostname;
if (
!appConfig.http.hostnameUserAgentOverrides ||
Object.keys(appConfig.http.hostnameUserAgentOverrides).length === 0
) {
return undefined;
}
const mappings = Object.entries(appConfig.http.hostnameUserAgentOverrides);
for (const [ruleHostname, ruleUserAgent] of mappings) {
if (ruleHostname === '*') {
userAgent = ruleUserAgent;
} else if (ruleHostname.startsWith('*')) {
if (hostname.endsWith(ruleHostname.slice(1))) {
userAgent = ruleUserAgent;
}
} else if (hostname === ruleHostname) {
userAgent = ruleUserAgent;
}
}
return userAgent;
}
|