Your Cloudflare Worker script serves as a proxy to bypass CORS policy restrictions by forwarding requests from allowed origins to target URLs. While the script is comprehensive and includes various configurations and error handling mechanisms, there are a few areas that could potentially lead to unexpected behaviors or prevent the proxy from fulfilling requests effectively. Below, I will highlight the key issues and provide corrected code snippets to enhance the robustness and compliance of your proxy service.
Key Issues Identified
-
Improper Use of Wildcards in CORS Headers
Access-Control-Allow-Headers and Access-Control-Expose-Headers: According to the CORS specification, wildcards (*) are not permitted for these headers. Instead, you should explicitly specify the allowed headers or echo back the headers requested by the client.
-
Request Body Handling
- Parsing Request Bodies: The current implementation parses the request body based on the
Content-Type and reconstructs it. This approach can lead to discrepancies, especially with streaming data or large payloads. Instead, it's more efficient and less error-prone to pass the request body directly to the target without parsing unless modification is necessary.
-
Unused Configuration Parameter
STREAM_THRESHOLD: This configuration parameter is defined but not utilized in the script, which can lead to confusion. It's advisable to either implement its intended functionality or remove it to maintain code clarity.
-
Potential Overexposure of the Proxy
- Allowed Domains vs. Target URLs: The current configuration allows any origins specified in
ALLOWED_DOMAINS to proxy requests to any target URLs not listed in BLOCKED_TARGET_HOSTS. Ensure that this behavior aligns with your security requirements to prevent misuse.
-
Error Handling Enhancements
- While the script includes robust error handling, ensuring that all possible edge cases are covered will further enhance reliability.
Recommended Corrections and Enhancements
1. Correcting CORS Headers
Update the generateCorsHeaders function to avoid using wildcards and instead explicitly specify allowed headers. You can dynamically echo back the headers requested by the client.
// Generate CORS Headers
function generateCorsHeaders(request) {
const origin = request.headers.get('Origin') || '';
const headers = new Headers();
if (isAllowedOrigin(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
// Echo back the requested headers
const requestHeaders = request.headers.get('Access-Control-Request-Headers');
if (requestHeaders) {
headers.set('Access-Control-Allow-Headers', requestHeaders);
} else {
// Define default allowed headers if none are requested
headers.set('Access-Control-Allow-Headers', Array.from(CONFIG.FORWARD_HEADERS).join(', '));
}
} else {
headers.set('Access-Control-Allow-Origin', 'null');
}
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
headers.set('Access-Control-Expose-Headers', Array.from(CONFIG.FORWARD_HEADERS).join(', '));
headers.set('Access-Control-Max-Age', '86400'); // 1 day
headers.append('Vary', 'Origin');
return headers;
}
2. Streamlining Request Body Handling
Modify the getRequestBody and forwardRequest functions to pass the request body directly without parsing. This approach maintains the integrity of the original request and improves performance.
// Forward the Incoming Request to the Target URL
async function forwardRequest(request, origin) {
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 parsedTargetUrl;
try {
parsedTargetUrl = new URL(targetUrl);
} catch (err) {
throw new ProxyError('Invalid URL format', 400);
}
if (CONFIG.BLOCKED_TARGET_HOSTS.has(parsedTargetUrl.host)) {
throw new ProxyError('Forbidden: Target host is not allowed', 403);
}
// Prepare Headers for the Forwarded Request
const init = {
method: request.method,
headers: filterRequestHeaders(request.headers),
redirect: 'follow',
signal: AbortSignal.timeout(CONFIG.TIMEOUT),
};
// Attach the Request Body if Applicable
if (!['GET', 'HEAD'].includes(request.method)) {
init.body = request.body;
}
// Perform the Fetch to the Target URL
let response;
try {
response = await fetch(parsedTargetUrl.toString(), init);
} catch (err) {
if (err.name === 'AbortError') {
throw new ProxyError('Request Timed Out', 504);
} else {
throw new ProxyError('Error Fetching Target URL', 502);
}
}
// Process and Return the Response with CORS and Security Headers
return createCorsResponse(response, origin);
}
Explanation:
-
Directly Passing the Body: Instead of parsing and reconstructing the body based on Content-Type, the script now directly assigns request.body to the init.body. This method ensures that the request payload remains unaltered, preserving data integrity and improving performance, especially for large or binary payloads.
-
Avoiding Cloning: By passing the body directly, we eliminate the need to clone and process the body, thereby reducing potential points of failure.
3. Removing Unused Configuration Parameters
If the STREAM_THRESHOLD is not being used, it's best to remove it to keep the configuration clean and prevent confusion.
// Remove STREAM_THRESHOLD if not used
const DEFAULT_CONFIG = {
ALLOWED_DOMAINS: new Set([
'https://api.abhibhai.com',
'https://lnee.netlify.app',
'https://proxe.netlify.app',
'http://localhost:8080',
]),
BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
FORWARD_HEADERS: new Set([
'accept',
'accept-language',
'user-agent',
'content-type',
'authorization',
'cache-control',
'pragma',
'expires',
'last-modified',
'if-modified-since',
'if-none-match',
'range',
'content-range',
'accept-encoding',
'accept-datetime',
'cookie',
]),
REMOVE_HEADERS: new Set([
'cf-connecting-ip',
'x-forwarded-for',
'x-real-ip',
'forwarded',
'via',
'proxy-authorization',
'proxy-authenticate',
'client-ip',
'true-client-ip',
'x-forwarded-host',
'x-forwarded-port',
'x-forwarded-proto',
'x-forwarded-protocol',
'x-forwarded-ssl',
'x-url-scheme',
'x-original-forwarded-for',
'x-http-forwarded-for',
'x-original-host',
'x-forwarded-by',
'x-proxy-user-ip',
'x-cluster-client-ip',
'x-forwarded',
'x-real-ip',
'forwarded-for',
'forwarded-proto',
]),
TIMEOUT: 29000, // in milliseconds (29 seconds)
AUTH_KEY: 'your-secure-auth-key',
SECURITY_HEADERS: {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Frame-Options': 'DENY',
},
CUSTOM_ERROR_RESPONSES: {
// Example:
// 404: { error: 'Not Found' },
},
CACHE_CONTROL: {
DEFAULT_MAX_AGE: 300, // 5 minutes
CUSTOM_RULES: {
// '/specific-path': 'public, max-age=600',
},
},
// STREAM_THRESHOLD has been removed
};
4. Ensuring Comprehensive Validation During Configuration Updates
Enhance the validateConfig function to include validations for all nested configurations, ensuring that any updates maintain the integrity of the CONFIG object.
// Validate the Incoming Configuration
function validateConfig(newConfig) {
// ALLOWED_DOMAINS Validation
if ('ALLOWED_DOMAINS' in newConfig) {
if (!Array.isArray(newConfig.ALLOWED_DOMAINS)) {
throw new ProxyError('Invalid ALLOWED_DOMAINS format', 400);
}
newConfig.ALLOWED_DOMAINS.forEach(domain => {
try {
new URL(domain);
} catch {
throw new ProxyError(`Invalid URL in ALLOWED_DOMAINS: ${domain}`, 400);
}
});
}
// BLOCKED_TARGET_HOSTS Validation
if ('BLOCKED_TARGET_HOSTS' in newConfig && !Array.isArray(newConfig.BLOCKED_TARGET_HOSTS)) {
throw new ProxyError('Invalid BLOCKED_TARGET_HOSTS format', 400);
}
// FORWARD_HEADERS Validation
if ('FORWARD_HEADERS' in newConfig && !Array.isArray(newConfig.FORWARD_HEADERS)) {
throw new ProxyError('Invalid FORWARD_HEADERS format', 400);
}
// REMOVE_HEADERS Validation
if ('REMOVE_HEADERS' in newConfig && !Array.isArray(newConfig.REMOVE_HEADERS)) {
throw new ProxyError('Invalid REMOVE_HEADERS format', 400);
}
// SECURITY_HEADERS Validation
if ('SECURITY_HEADERS' in newConfig && typeof newConfig.SECURITY_HEADERS !== 'object') {
throw new ProxyError('Invalid SECURITY_HEADERS format', 400);
}
// CACHE_CONTROL Validation
if ('CACHE_CONTROL' in newConfig) {
if (
typeof newConfig.CACHE_CONTROL !== 'object' ||
Array.isArray(newConfig.CACHE_CONTROL)
) {
throw new ProxyError('Invalid CACHE_CONTROL format', 400);
}
if (
'DEFAULT_MAX_AGE' in newConfig.CACHE_CONTROL &&
typeof newConfig.CACHE_CONTROL.DEFAULT_MAX_AGE !== 'number'
) {
throw new ProxyError('Invalid DEFAULT_MAX_AGE in CACHE_CONTROL', 400);
}
if (
'CUSTOM_RULES' in newConfig.CACHE_CONTROL &&
typeof newConfig.CACHE_CONTROL.CUSTOM_RULES !== 'object'
) {
throw new ProxyError('Invalid CUSTOM_RULES in CACHE_CONTROL', 400);
}
}
// Additional Nested Validations
if ('CUSTOM_ERROR_RESPONSES' in newConfig && typeof newConfig.CUSTOM_ERROR_RESPONSES !== 'object') {
throw new ProxyError('Invalid CUSTOM_ERROR_RESPONSES format', 400);
}
// Add more validation rules as necessary
}
Explanation:
-
URL Validation: Ensures that each domain in ALLOWED_DOMAINS is a valid URL, preventing malformed entries that could disrupt the proxy's functionality.
-
Comprehensive Checks: Adds validation for all nested configurations to prevent partial or incorrect updates that could lead to inconsistent proxy behavior.
5. Finalized Corrected Script
Below is the corrected and enhanced version of your Cloudflare Worker script incorporating the aforementioned recommendations:
// Default Configuration
const DEFAULT_CONFIG = {
ALLOWED_DOMAINS: new Set([
'https://api.abhibhai.com',
'https://lnee.netlify.app',
'https://proxe.netlify.app',
'http://localhost:8080',
]),
BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
FORWARD_HEADERS: new Set([
'accept',
'accept-language',
'user-agent',
'content-type',
'authorization',
'cache-control',
'pragma',
'expires',
'last-modified',
'if-modified-since',
'if-none-match',
'range',
'content-range',
'accept-encoding',
'accept-datetime',
'cookie',
]),
REMOVE_HEADERS: new Set([
'cf-connecting-ip',
'x-forwarded-for',
'x-real-ip',
'forwarded',
'via',
'proxy-authorization',
'proxy-authenticate',
'client-ip',
'true-client-ip',
'x-forwarded-host',
'x-forwarded-port',
'x-forwarded-proto',
'x-forwarded-protocol',
'x-forwarded-ssl',
'x-url-scheme',
'x-original-forwarded-for',
'x-http-forwarded-for',
'x-original-host',
'x-forwarded-by',
'x-proxy-user-ip',
'x-cluster-client-ip',
'x-forwarded',
'x-real-ip',
'forwarded-for',
'forwarded-proto',
]),
TIMEOUT: 29000, // in milliseconds (29 seconds)
AUTH_KEY: 'your-secure-auth-key',
SECURITY_HEADERS: {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Frame-Options': 'DENY',
},
CUSTOM_ERROR_RESPONSES: {
// Example:
// 404: { error: 'Not Found' },
},
CACHE_CONTROL: {
DEFAULT_MAX_AGE: 300, // 5 minutes
CUSTOM_RULES: {
// '/specific-path': 'public, max-age=600',
},
},
};
// Clone the default configuration to allow runtime modifications
let CONFIG = { ...DEFAULT_CONFIG };
// Custom Error Class for Proxy-Specific Errors
class ProxyError extends Error {
constructor(message, status) {
super(message);
this.name = 'ProxyError';
this.status = status;
}
}
// Event Listener for Fetch Events
addEventListener('fetch', (event) => {
event.respondWith(
handleRequest(event).catch((error) => handleError(error, event.request))
);
});
// Main Request Handler
async function handleRequest(event) {
const request = event.request;
const url = new URL(request.url);
// Handle Preflight CORS Requests
if (request.method === 'OPTIONS') {
return handlePreflightRequest(request);
}
// Handle Configuration Updates
if (request.method === 'POST' && url.pathname === '/config') {
return handleConfigUpdate(request);
}
// Check for Allowed Origin
const origin = request.headers.get('Origin');
if (!isAllowedOrigin(origin)) {
throw new ProxyError('Forbidden: Origin not allowed', 403);
}
// Forward the Request
return forwardRequest(request, origin);
}
// Check if the Origin is Allowed
function isAllowedOrigin(origin) {
return origin && (CONFIG.ALLOWED_DOMAINS.has(origin) || CONFIG.ALLOWED_DOMAINS.has('*'));
}
// Forward the Incoming Request to the Target URL
async function forwardRequest(request, origin) {
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 parsedTargetUrl;
try {
parsedTargetUrl = new URL(targetUrl);
} catch (err) {
throw new ProxyError('Invalid URL format', 400);
}
if (CONFIG.BLOCKED_TARGET_HOSTS.has(parsedTargetUrl.host)) {
throw new ProxyError('Forbidden: Target host is not allowed', 403);
}
// Prepare Headers for the Forwarded Request
const init = {
method: request.method,
headers: filterRequestHeaders(request.headers),
redirect: 'follow',
signal: AbortSignal.timeout(CONFIG.TIMEOUT),
};
// Attach the Request Body if Applicable
if (!['GET', 'HEAD'].includes(request.method)) {
init.body = request.body;
}
// Perform the Fetch to the Target URL
let response;
try {
response = await fetch(parsedTargetUrl.toString(), init);
} catch (err) {
if (err.name === 'AbortError') {
throw new ProxyError('Request Timed Out', 504);
} else {
throw new ProxyError('Error Fetching Target URL', 502);
}
}
// Process and Return the Response with CORS and Security Headers
return createCorsResponse(response, origin);
}
// Filter and Forward Only Allowed Headers
function filterRequestHeaders(headers) {
const forwardedHeaders = new Headers();
for (const [key, value] of headers.entries()) {
const lowerKey = key.toLowerCase();
if (CONFIG.FORWARD_HEADERS.has(lowerKey) && !CONFIG.REMOVE_HEADERS.has(lowerKey)) {
forwardedHeaders.set(key, value);
}
}
return forwardedHeaders;
}
// Generate CORS Headers
function generateCorsHeaders(request) {
const origin = request.headers.get('Origin') || '';
const headers = new Headers();
if (isAllowedOrigin(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
// Echo back the requested headers
const requestHeaders = request.headers.get('Access-Control-Request-Headers');
if (requestHeaders) {
headers.set('Access-Control-Allow-Headers', requestHeaders);
} else {
// Define default allowed headers if none are requested
headers.set('Access-Control-Allow-Headers', Array.from(CONFIG.FORWARD_HEADERS).join(', '));
}
} else {
headers.set('Access-Control-Allow-Origin', 'null');
}
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
headers.set('Access-Control-Expose-Headers', Array.from(CONFIG.FORWARD_HEADERS).join(', '));
headers.set('Access-Control-Max-Age', '86400'); // 1 day
headers.append('Vary', 'Origin');
return headers;
}
// Handle Preflight CORS Requests
function handlePreflightRequest(request) {
const corsHeaders = generateCorsHeaders(request);
return new Response(null, {
status: 204,
headers: corsHeaders,
});
}
// Create CORS-Compliant Response with Security Headers
async function createCorsResponse(response, origin) {
const corsHeaders = generateCorsHeaders(response.req || {}) // Adjust based on actual request reference
const responseHeaders = new Headers(response.headers);
// Remove Disallowed Headers
for (const header of CONFIG.REMOVE_HEADERS) {
responseHeaders.delete(header);
}
// Apply CORS Headers
for (const [key, value] of corsHeaders.entries()) {
responseHeaders.set(key, value);
}
// Apply Security Headers
for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
responseHeaders.set(key, value);
}
// Handle Cache Control
applyCacheControl(responseHeaders, response.url);
// Clone the response if streaming is needed
if (response.body && response.body.locked) {
// For cases where the body is locked and can't be used directly
const clonedBody = await response.blob();
return new Response(clonedBody, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
}
// Return the Modified Response
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
}
// Apply Cache Control Headers
function applyCacheControl(headers, url) {
const parsedUrl = new URL(url);
const pathname = parsedUrl.pathname;
const customRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[pathname];
if (customRule) {
headers.set('Cache-Control', customRule);
} else {
headers.set(
'Cache-Control',
`public, max-age=${CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE}`
);
}
}
// Handle Errors and Generate Appropriate Responses
async function handleError(error, request) {
const status = error instanceof ProxyError ? error.status : 500;
const message = error.message || 'Internal Server Error';
const corsHeaders = generateCorsHeaders(request);
const headers = new Headers({
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
});
// Apply CORS Headers
for (const [key, value] of corsHeaders.entries()) {
headers.set(key, value);
}
// Check for Custom Error Response
const customErrorResponse = CONFIG.CUSTOM_ERROR_RESPONSES[status];
if (customErrorResponse) {
return new Response(JSON.stringify(customErrorResponse), {
status,
headers,
});
}
// Default Error Response
return new Response(JSON.stringify({ error: message }), { status, headers });
}
// Handle Configuration Updates via POST /config
async function handleConfigUpdate(request) {
const authHeader = request.headers.get('Authorization');
if (!isAuthorized(authHeader)) {
throw new ProxyError('Unauthorized', 401);
}
try {
const updatedConfig = await request.json();
validateConfig(updatedConfig);
updateConfig(updatedConfig);
return new Response(
JSON.stringify({ message: 'Configuration updated successfully' }),
{
status: 200,
headers: {
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
},
}
);
} catch (error) {
if (error instanceof ProxyError) {
return handleError(error, request);
}
return new Response(JSON.stringify({ error: 'Invalid configuration data' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
},
});
}
}
// Authorization Check for Configuration Updates
function isAuthorized(authHeader) {
return authHeader && authHeader === `Bearer ${CONFIG.AUTH_KEY}`;
}
// Validate the Incoming Configuration
function validateConfig(newConfig) {
// ALLOWED_DOMAINS Validation
if ('ALLOWED_DOMAINS' in newConfig) {
if (!Array.isArray(newConfig.ALLOWED_DOMAINS)) {
throw new ProxyError('Invalid ALLOWED_DOMAINS format', 400);
}
newConfig.ALLOWED_DOMAINS.forEach(domain => {
try {
new URL(domain);
} catch {
throw new ProxyError(`Invalid URL in ALLOWED_DOMAINS: ${domain}`, 400);
}
});
}
// BLOCKED_TARGET_HOSTS Validation
if ('BLOCKED_TARGET_HOSTS' in newConfig && !Array.isArray(newConfig.BLOCKED_TARGET_HOSTS)) {
throw new ProxyError('Invalid BLOCKED_TARGET_HOSTS format', 400);
}
// FORWARD_HEADERS Validation
if ('FORWARD_HEADERS' in newConfig && !Array.isArray(newConfig.FORWARD_HEADERS)) {
throw new ProxyError('Invalid FORWARD_HEADERS format', 400);
}
// REMOVE_HEADERS Validation
if ('REMOVE_HEADERS' in newConfig && !Array.isArray(newConfig.REMOVE_HEADERS)) {
throw new ProxyError('Invalid REMOVE_HEADERS format', 400);
}
// SECURITY_HEADERS Validation
if ('SECURITY_HEADERS' in newConfig && typeof newConfig.SECURITY_HEADERS !== 'object') {
throw new ProxyError('Invalid SECURITY_HEADERS format', 400);
}
// CACHE_CONTROL Validation
if ('CACHE_CONTROL' in newConfig) {
if (
typeof newConfig.CACHE_CONTROL !== 'object' ||
Array.isArray(newConfig.CACHE_CONTROL)
) {
throw new ProxyError('Invalid CACHE_CONTROL format', 400);
}
if (
'DEFAULT_MAX_AGE' in newConfig.CACHE_CONTROL &&
typeof newConfig.CACHE_CONTROL.DEFAULT_MAX_AGE !== 'number'
) {
throw new ProxyError('Invalid DEFAULT_MAX_AGE in CACHE_CONTROL', 400);
}
if (
'CUSTOM_RULES' in newConfig.CACHE_CONTROL &&
typeof newConfig.CACHE_CONTROL.CUSTOM_RULES !== 'object'
) {
throw new ProxyError('Invalid CUSTOM_RULES in CACHE_CONTROL', 400);
}
}
// CUSTOM_ERROR_RESPONSES Validation
if ('CUSTOM_ERROR_RESPONSES' in newConfig && typeof newConfig.CUSTOM_ERROR_RESPONSES !== 'object') {
throw new ProxyError('Invalid CUSTOM_ERROR_RESPONSES format', 400);
}
// Add more validation rules as necessary
}
// Update the Configuration with New Values
function updateConfig(newConfig) {
for (const [key, value] of Object.entries(newConfig)) {
if (key in CONFIG) {
if (value instanceof Array && CONFIG[key] instanceof Set) {
CONFIG[key] = new Set(value.map(v => v.toLowerCase())); // Ensure headers are lowercased
} else if (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
typeof CONFIG[key] === 'object' &&
!(CONFIG[key] instanceof Set)
) {
CONFIG[key] = { ...CONFIG[key], ...value };
} else {
CONFIG[key] = value;
}
}
}
// Ensure TIMEOUT doesn't exceed Cloudflare's limits (30 seconds)
if ('TIMEOUT' in newConfig) {
CONFIG.TIMEOUT = Math.min(CONFIG.TIMEOUT, 30000);
}
}
// Optional: Helper Function to Reset Configuration to Default
function resetConfig() {
CONFIG = { ...DEFAULT_CONFIG };
}
6. Additional Recommendations
-
Logging and Monitoring: Implement logging within the Worker to monitor usage patterns, errors, and potential abuse. This can aid in troubleshooting and ensuring the proxy operates as intended.
-
Rate Limiting: Consider adding rate limiting to prevent abuse of the proxy service, ensuring it remains available and performant for legitimate users.
-
Security Audits: Regularly audit the proxy's configurations and access controls to ensure they align with evolving security best practices.
Conclusion
By addressing the identified issues and implementing the recommended corrections, your Cloudflare Worker proxy will be more robust, compliant with CORS specifications, and less prone to unexpected behaviors. Always ensure that configuration updates are handled securely and that the proxy's exposure aligns with your intended use cases to maintain both functionality and security.