Make this cloudflare worker's based proxy more robust with as effective and efficient as possible. Improve the whole code as much as possible and send the full improved code. --- // Default Configuration
const DEFAULT_CONFIG = {
  ALLOWED_ORIGINS: new Set([
    'https://api.abhibhai.com',
    'https://lnee.netlify.app',
    'https://proxe.netlify.app',
    'http://localhost:8080',
  ]),
  ALLOWED_TARGET_DOMAINS: new Set(['*']), // Use specific domains if possible for better security
  BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
  FORWARD_HEADERS: new Set([
    // Standard headers that don't reveal user identity
    'accept',
    'accept-language',
    'content-type',
    'cache-control',
    'pragma',
    'expires',
    'last-modified',
    'if-modified-since',
    'if-none-match',
    'connection',
    'keep-alive',
    'upgrade-insecure-requests',
  ]),
  REMOVE_HEADERS: new Set([
    // Headers that may reveal user or proxy information
    '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', // Remove cookies to avoid tracking
    'authorization', // Remove authorization headers to prevent credential leakage
    'set-cookie', // Prevent cookies from being set on the client
    'server', // Remove server header for anonymity
  ]),
  TIMEOUT: 29000, // milliseconds (Cloudflare Workers have a max timeout of 50 seconds)
  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';", // Hardened CSP
  },
  CUSTOM_ERROR_RESPONSES: {}, // e.g., { 404: { error: 'Not Found' } }
  CACHE_CONTROL: {
    DEFAULT_MAX_AGE: 0, // seconds; set to 0 to disable caching by default
    CUSTOM_RULES: {}, // e.g., { '/path': 'public, max-age=600' }
  },
  MAX_REQUEST_BODY_SIZE: 1_000_000, // 1 MB limit
};

// Initialize and normalize configuration
const CONFIG = {
  ...DEFAULT_CONFIG,
  ALLOWED_ORIGINS: new Set([...DEFAULT_CONFIG.ALLOWED_ORIGINS].map((origin) => origin.toLowerCase())),
  ALLOWED_TARGET_DOMAINS: new Set([...DEFAULT_CONFIG.ALLOWED_TARGET_DOMAINS].map((domain) => domain.toLowerCase())),
  BLOCKED_TARGET_HOSTS: new Set([...DEFAULT_CONFIG.BLOCKED_TARGET_HOSTS].map((host) => host.toLowerCase())),
  FORWARD_HEADERS: new Set([...DEFAULT_CONFIG.FORWARD_HEADERS].map((header) => header.toLowerCase())),
  REMOVE_HEADERS: new Set([...DEFAULT_CONFIG.REMOVE_HEADERS].map((header) => header.toLowerCase())),
};

// Custom Error Class for Proxy-Specific Errors
class ProxyError extends Error {
  constructor(message, status) {
    super(message);
    this.name = 'ProxyError';
    this.status = status;
  }
}

// Fetch Event Listener
addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request));
});

// Main Request Handler
async function handleRequest(request) {
  try {
    // Preflight CORS Check
    if (request.method === 'OPTIONS') {
      return handlePreflight(request);
    }

    // Validate Origin
    const origin = request.headers.get('Origin');
    if (origin && !isAllowedOrigin(origin)) {
      throw new ProxyError('Forbidden: Origin not allowed', 403);
    }

    // Forward the Request
    return await forwardRequest(request);
  } catch (error) {
    return handleError(error, request);
  }
}

// Check if Origin is Allowed
function isAllowedOrigin(origin) {
  const normalized = origin.toLowerCase();
  return CONFIG.ALLOWED_ORIGINS.has(normalized) || CONFIG.ALLOWED_ORIGINS.has('*');
}

// Forward Incoming Request to Target
async function forwardRequest(request) {
  const url = new URL(request.url);
  const targetUrl = request.headers.get('x-target-url') || url.searchParams.get('target');

  if (!targetUrl) {
    throw new ProxyError('Bad Request: Missing target URL', 400);
  }

  let parsedTarget;
  try {
    parsedTarget = new URL(targetUrl);
  } catch {
    throw new ProxyError('Invalid target URL', 400);
  }

  const targetHost = parsedTarget.host.toLowerCase();
  if (CONFIG.BLOCKED_TARGET_HOSTS.has(targetHost)) {
    throw new ProxyError('Forbidden: Target host is blocked', 403);
  }

  if (!isTargetAllowed(parsedTarget.hostname.toLowerCase())) {
    throw new ProxyError('Forbidden: Target domain not allowed', 403);
  }

  // Prevent unsupported protocols
  if (!/^https?:$/.test(parsedTarget.protocol)) {
    throw new ProxyError('Forbidden: Unsupported protocol', 403);
  }

  // Prepare Forwarded Headers
  const forwardedHeaders = filterHeaders(request.headers);
  forwardedHeaders.set('Host', parsedTarget.host);

  // Handle Request Body
  const options = {
    method: request.method,
    headers: forwardedHeaders,
    redirect: 'manual', // Handle redirects manually
    signal: AbortSignal.timeout(CONFIG.TIMEOUT),
  };

  // Attach the request body if necessary
  if (!['GET', 'HEAD'].includes(request.method)) {
    // Limit request body size to prevent abuse
    const contentLength = parseInt(request.headers.get('Content-Length') || '0', 10);
    if (isNaN(contentLength) || contentLength > CONFIG.MAX_REQUEST_BODY_SIZE) {
      throw new ProxyError('Request Entity Too Large', 413);
    }
    // Clone the request to safely read the body
    options.body = request.body;
  }

  // Fetch Response
  let response;
  try {
    response = await fetch(parsedTarget.toString(), options);

    // Handle redirects
    if (response.status >= 300 && response.status < 400 && response.headers.has('Location')) {
      const location = response.headers.get('Location');
      if (location) {
        const redirectUrl = new URL(location, parsedTarget);
        if (!isTargetAllowed(redirectUrl.hostname.toLowerCase())) {
          throw new ProxyError('Forbidden: Redirected domain not allowed', 403);
        }
        // Follow the redirect
        return await forwardRequest(new Request(redirectUrl.toString(), request));
      }
    }
  } catch (err) {
    if (err.name === 'AbortError') {
      throw new ProxyError('Request Timed Out', 504);
    }
    throw new ProxyError('Error Fetching Target URL', 502);
  }

  // Modify and Return Response
  return modifyResponse(response, request);
}

// Check if Target Domain is Allowed
function isTargetAllowed(domain) {
  return CONFIG.ALLOWED_TARGET_DOMAINS.has('*') || CONFIG.ALLOWED_TARGET_DOMAINS.has(domain);
}

// Filter Headers: Forward allowed headers and remove disallowed ones
function filterHeaders(headers) {
  const result = new Headers();
  for (const [key, value] of headers.entries()) {
    const lowerKey = key.toLowerCase();
    if (CONFIG.FORWARD_HEADERS.has(lowerKey)) {
      result.set(key, value);
    }
  }
  return result;
}

// Handle Preflight CORS Requests
function handlePreflight(request) {
  const headers = generateCorsHeaders(request, true);
  return new Response(null, {
    status: 204,
    headers,
  });
}

// Generate CORS Headers
function generateCorsHeaders(request, isPreflight = false) {
  const origin = request.headers.get('Origin');
  const headers = new Headers();

  if (origin && isAllowedOrigin(origin)) {
    headers.set('Access-Control-Allow-Origin', origin);
    headers.set('Access-Control-Allow-Credentials', 'true');
    if (isPreflight) {
      const reqMethod = request.headers.get('Access-Control-Request-Method');
      const reqHeaders = request.headers.get('Access-Control-Request-Headers');
      headers.set(
        'Access-Control-Allow-Methods',
        reqMethod || 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH'
      );
      headers.set(
        'Access-Control-Allow-Headers',
        reqHeaders || 'Content-Type'
      );
      headers.set('Access-Control-Max-Age', '86400'); // 1 day
    }
    headers.set('Access-Control-Expose-Headers', '*'); // Expose all headers
    headers.append('Vary', 'Origin');
    if (isPreflight) {
      headers.append('Vary', 'Access-Control-Request-Headers');
      headers.append('Vary', 'Access-Control-Request-Method');
    }
  }

  return headers;
}

// Modify Response: Add CORS and Security Headers, Stream Response
function modifyResponse(response, request) {
  const corsHeaders = generateCorsHeaders(request);
  const resHeaders = new Headers(response.headers);

  // Remove Disallowed Headers
  for (const header of resHeaders.keys()) {
    const lowerHeader = header.toLowerCase();
    if (CONFIG.REMOVE_HEADERS.has(lowerHeader)) {
      resHeaders.delete(header);
    }
  }

  // Add CORS Headers
  if (request.headers.get('Origin')) {
    for (const [key, value] of corsHeaders.entries()) {
      resHeaders.set(key, value);
    }
  }

  // Add Security Headers
  for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
    resHeaders.set(key, value);
  }

  // Handle Cache Control
  const responseUrl = new URL(response.url);
  const cacheRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[responseUrl.pathname];

  if (cacheRule) {
    // Apply custom cache rules if specified
    resHeaders.set('Cache-Control', cacheRule);
  } else if (CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE > 0) {
    // Apply default caching if max-age is set to a positive value
    resHeaders.set('Cache-Control', `public, max-age=${CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE}`);
  } else {
    // Disable caching by default
    resHeaders.set('Cache-Control', 'no-store');
  }

  // Remove Hop-by-Hop headers as per RFC 2616
  const hopByHopHeaders = [
    'connection',
    'keep-alive',
    'proxy-authenticate',
    'proxy-authorization',
    'te',
    'trailers',
    'transfer-encoding',
    'upgrade',
  ];
  for (const header of hopByHopHeaders) {
    resHeaders.delete(header);
  }

  // Stream the response directly to the user
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: resHeaders,
  });
}

// Handle Errors and Generate Responses
function handleError(error, request) {
  // Log error for debugging (consider adjusting for production)
  console.error('Error:', error);

  const status = error instanceof ProxyError ? error.status : 500;

  // Avoid exposing stack traces or sensitive information
  const message =
    status >= 500
      ? 'Internal Server Error'
      : error.message || 'An error occurred';

  const corsHeaders = generateCorsHeaders(request);
  const headers = new Headers({
    'Content-Type': 'application/json',
  });

  // Merge Security Headers
  for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
    headers.set(key, value);
  }

  // Add CORS Headers
  if (request.headers.get('Origin')) {
    for (const [key, value] of corsHeaders.entries()) {
      headers.set(key, value);
    }
  }

  const customResponse = CONFIG.CUSTOM_ERROR_RESPONSES[status];
  const body = customResponse
    ? JSON.stringify(customResponse)
    : JSON.stringify({ error: message });

  return new Response(body, {
    status,
    headers,
  });
}