// Configuration
const CONFIG = {
ALLOWED_ORIGINS: new Set(['*']), // Set to '*' to allow all origins
ALLOWED_TARGET_DOMAINS: new Set(['*']), // Set to '*' to allow all target domains
ALLOW_ALL_TARGETS: true,
BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
FORWARDED_HEADERS: new Set([
'accept',
'accept-language',
'content-type',
'cache-control',
'pragma',
'expires',
'last-modified',
'if-modified-since',
'if-none-match',
'connection',
'keep-alive',
'upgrade-insecure-requests',
]),
REMOVED_HEADERS: new Set([
'cf-connecting-ip',
'x-forwarded-for',
'x-real-ip',
'forwarded',
'via',
'client-ip',
'true-client-ip',
'proxy-connection',
'proxy-authorization',
'proxy-authenticate',
'x-proxy-id',
'x-proxy-location',
'x-proxy-type',
'x-squid-error',
'x-request-id',
'x-correlation-id',
'te',
'trailers',
'transfer-encoding',
'upgrade',
'cookie',
'authorization',
'set-cookie',
'server',
]),
SECURITY_HEADERS: {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Frame-Options': 'DENY',
'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'; base-uri 'none';",
'Permissions-Policy': 'accelerometer=(), camera=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()',
'X-XSS-Protection': '1; mode=block',
},
CUSTOM_ERROR_RESPONSES: {
400: { error: 'Bad Request' },
403: { error: 'Forbidden' },
404: { error: 'Not Found' },
413: { error: 'Payload Too Large' },
429: { error: 'Too Many Requests' },
500: { error: 'Internal Server Error' },
502: { error: 'Bad Gateway' },
504: { error: 'Gateway Timeout' },
508: { error: 'Too Many Redirects' },
},
CACHE_CONTROL: {
DEFAULT_MAX_AGE: 0,
CUSTOM_RULES: {}, // e.g., { '/path': 'public, max-age=3600' }
},
MAX_REQUEST_BODY_SIZE: 5_000_000, // 5 MB
TIMEOUT: 29_000, // 29 seconds
MAX_REDIRECTS: 5,
TARGET_URL_HEADER: 'x-target-url',
TARGET_URL_QUERY_PARAM: 'target',
};
class ProxyError extends Error {
constructor(message, status) {
super(message);
this.name = 'ProxyError';
this.status = status;
}
}
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
try {
if (request.method === 'OPTIONS') {
return handlePreflight(request);
}
const origin = request.headers.get('Origin');
if (origin && !isAllowedOrigin(origin)) {
throw new ProxyError('Forbidden: Origin not allowed', 403);
}
const cacheKey = new URL(request.url);
const cachedResponse = await caches.default.match(cacheKey);
if (cachedResponse) {
return modifyAndReturnResponse(cachedResponse, request);
}
return await forwardRequest(request, 0);
} catch (error) {
return handleError(error, request);
}
}
function isAllowedOrigin(origin) {
const lowerOrigin = origin.toLowerCase();
return CONFIG.ALLOWED_ORIGINS.has('*') || CONFIG.ALLOWED_ORIGINS.has(lowerOrigin);
}
function generateCorsHeaders(request, isPreflight = false) {
const headers = new Headers();
const origin = request.headers.get('Origin');
if (origin && isAllowedOrigin(origin)) {
headers.set('Access-Control-Allow-Origin', origin === '*' ? '*' : origin);
headers.set('Access-Control-Allow-Credentials', 'true');
if (isPreflight) {
const requestedMethod = request.headers.get('Access-Control-Request-Method') || 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH';
const requestedHeaders = request.headers.get('Access-Control-Request-Headers') || 'Content-Type';
headers.set('Access-Control-Allow-Methods', requestedMethod);
headers.set('Access-Control-Allow-Headers', requestedHeaders);
headers.set('Access-Control-Max-Age', '86400');
}
headers.set('Access-Control-Expose-Headers', '*');
headers.append('Vary', 'Origin');
if (isPreflight) {
headers.append('Vary', 'Access-Control-Request-Headers');
headers.append('Vary', 'Access-Control-Request-Method');
}
}
return headers;
}
function handlePreflight(request) {
const headers = generateCorsHeaders(request, true);
return new Response(null, { status: 204, headers });
}
function filterAndForwardHeaders(headers) {
const result = new Headers();
for (const [key, value] of headers.entries()) {
const lowerKey = key.toLowerCase();
if (CONFIG.FORWARDED_HEADERS.has(lowerKey) && !CONFIG.REMOVED_HEADERS.has(lowerKey)) {
result.set(key, value);
}
}
return result;
}
function validateTargetUrl(url) {
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch {
throw new ProxyError('Bad Request: Invalid target URL', 400);
}
const protocol = parsedUrl.protocol.toLowerCase();
if (!['http:', 'https:'].includes(protocol)) {
throw new ProxyError('Forbidden: Unsupported protocol', 403);
}
const hostname = parsedUrl.hostname.toLowerCase();
if (CONFIG.BLOCKED_TARGET_HOSTS.has(hostname)) {
throw new ProxyError('Forbidden: Target host is blocked', 403);
}
if (!CONFIG.ALLOW_ALL_TARGETS && !CONFIG.ALLOWED_TARGET_DOMAINS.has(hostname)) {
throw new ProxyError('Forbidden: Target domain not allowed', 403);
}
return parsedUrl;
}
function getTargetUrl(request) {
const headerTarget = request.headers.get(CONFIG.TARGET_URL_HEADER);
if (headerTarget) {
return headerTarget;
}
const url = new URL(request.url);
return url.searchParams.get(CONFIG.TARGET_URL_QUERY_PARAM);
}
async function cacheResponse(cacheKey, response) {
const cache = caches.default;
const clonedResponse = response.clone();
const cacheControl = clonedResponse.headers.get('Cache-Control') || '';
let maxAge = CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE;
const responseUrl = new URL(clonedResponse.url);
const customCacheRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[responseUrl.pathname];
if (customCacheRule) {
const matches = customCacheRule.match(/max-age=(\d+)/);
if (matches && matches[1]) {
maxAge = parseInt(matches[1], 10);
}
}
if (maxAge > 0) {
await cache.put(cacheKey, clonedResponse, { expirationTtl: maxAge });
}
}
function modifyAndReturnResponse(response, request) {
const corsHeaders = generateCorsHeaders(request);
const newHeaders = new Headers(response.headers);
// Remove unwanted headers
CONFIG.REMOVED_HEADERS.forEach((header) => {
newHeaders.delete(header);
});
// Add CORS headers if Origin is present
if (request.headers.get('Origin')) {
for (const [key, value] of corsHeaders.entries()) {
newHeaders.set(key, value);
}
}
// Set security headers
for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
newHeaders.set(key, value);
}
// Set Cache-Control based on custom rules
const responseUrl = new URL(response.url);
const cacheRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[responseUrl.pathname];
if (cacheRule) {
newHeaders.set('Cache-Control', cacheRule);
} else if (CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE > 0) {
newHeaders.set('Cache-Control', `public, max-age=${CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE}`);
} else {
newHeaders.set('Cache-Control', 'no-store');
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
function handleError(error, request) {
const status = error instanceof ProxyError ? error.status : 500;
const errorMessage = CONFIG.CUSTOM_ERROR_RESPONSES[status]
? CONFIG.CUSTOM_ERROR_RESPONSES[status].error
: 'An unexpected error occurred';
const corsHeaders = generateCorsHeaders(request);
const headers = new Headers({
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
});
if (request.headers.get('Origin')) {
for (const [key, value] of corsHeaders.entries()) {
headers.set(key, value);
}
}
const body = JSON.stringify({ error: errorMessage });
return new Response(body, { status, headers });
}
async function forwardRequest(request, redirectCount) {
if (redirectCount > CONFIG.MAX_REDIRECTS) {
throw new ProxyError('Too Many Redirects', 508);
}
const targetUrl = getTargetUrl(request);
if (!targetUrl) {
throw new ProxyError('Bad Request: Missing target URL', 400);
}
const parsedTarget = validateTargetUrl(targetUrl);
const proxiedHeaders = filterAndForwardHeaders(request.headers);
proxiedHeaders.set('Host', parsedTarget.host);
const fetchOptions = {
method: request.method,
headers: proxiedHeaders,
redirect: 'manual',
cf: { requestTimeout: CONFIG.TIMEOUT },
};
if (!['GET', 'HEAD'].includes(request.method)) {
const contentLength = parseInt(request.headers.get('Content-Length') || '0', 10);
if (isNaN(contentLength) || contentLength > CONFIG.MAX_REQUEST_BODY_SIZE) {
throw new ProxyError('Payload Too Large', 413);
}
fetchOptions.body = request.body;
}
let response;
try {
response = await fetch(parsedTarget.toString(), fetchOptions);
} catch (err) {
if (err instanceof TypeError && err.message.includes('network')) {
throw new ProxyError('Bad Gateway: Network Error', 502);
}
if (err.name === 'AbortError') {
throw new ProxyError('Gateway Timeout', 504);
}
throw new ProxyError('Bad Gateway: Unknown Error', 502);
}
if (response.status >= 300 && response.status < 400 && response.headers.has('Location')) {
const location = response.headers.get('Location');
if (location) {
let redirectUrl;
try {
redirectUrl = new URL(location, parsedTarget);
} catch {
throw new ProxyError('Bad Gateway: Invalid redirect URL', 502);
}
if (!isAllowedOrigin(redirectUrl.hostname)) {
throw new ProxyError('Forbidden: Redirected domain not allowed', 403);
}
const newRequest = new Request(redirectUrl.toString(), request);
return await forwardRequest(newRequest, redirectCount + 1);
}
}
const modifiedResponse = modifyAndReturnResponse(response, request);
if (request.method === 'GET') {
const cacheKey = new URL(request.url);
await cacheResponse(cacheKey, modifiedResponse);
}
return modifiedResponse;
}