Ensure allowed domain users won't get any type of CORS policy error and restrictions no matter the method and situations. Bypass all of the CORS policy restrictions for the allowed domain user no matter the method and situation. Ensure allowed domain users won't get any CORS error on any requested resources no matter the method and situations. Make it 100% impossible for any allowed domain user to get any type of CORS error and restrictions no matter what method they choosed or what situation they in. Remove the rate limiting related codes without damaging and breaking anything. Send the fully working full updated code. ---- // 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,
LOGGING_LEVEL: 'warn',
AUTH_KEY: 'your-secure-auth-key', // Replace with a secure 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: {},
RATE_LIMIT: {
REQUESTS_PER_MINUTE: 120,
BURST: 30,
},
CACHE_CONTROL: {
DEFAULT_MAX_AGE: 300, // 5 minutes
CUSTOM_RULES: {},
},
STREAM_THRESHOLD: 1024 * 1024, // 1MB
};
// Remove disallowed headers from the response
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);
// If request has a Content-Type header, set it in the response
const requestContentType = request.headers.get('Content-Type');
if (requestContentType) {
responseHeaders.set('Content-Type', requestContentType);
}
// Stream the response body
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
}
function applyCacheControl(headers, url) {
const parsedUrl = new URL(url);
const pathname = parsedUrl.pathname;
const customRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[pathname];
// Placeholder for RATELIMIT_KV binding
// Bind this to a Workers KV namespace in your Cloudflare Workers environment
const RATELIMIT_KV = {
async get(key) {
// Implement KV get operation using the KV namespace binding
// Example: return await KV_NAMESPACE.get(key);
return null; // Placeholder
},
async put(key, value, options) {
// Implement KV put operation using the KV namespace binding
// Example: await KV_NAMESPACE.put(key, value, options);
},
};
// Helper function to reset configuration to default
function resetConfig() {
CONFIG = { ...DEFAULT_CONFIG };
}
Certainly! Below is the updated Cloudflare Worker script based on your requirements:
CORS Policy Enhancements:
Permissive CORS Headers for Allowed Domains: The script now ensures that any request originating from the allowed domains specified in ALLOWED_DOMAINS will receive comprehensive CORS headers. This setup guarantees that users from these domains won't encounter any CORS-related issues, regardless of the HTTP method or the nature of the request.
Dynamic Handling of All Headers: The Access-Control-Allow-Headers and Access-Control-Expose-Headers are set to allow all headers, ensuring that clients can use any headers without restrictions.
Wildcard in Access-Control-Allow-Methods: All standard HTTP methods are allowed to facilitate any type of request from the allowed domains.
Rate Limiting Removal:
All configurations, functions, and references related to rate limiting have been removed. This ensures that there are no restrictions on the number of requests, making the proxy fully open to the allowed domains.
General Enhancements:
Security Headers Maintained: The security headers previously defined are still included to ensure that the proxy remains secure.
Configuration Management: The configuration has been cleaned up to remove any remnants of the rate limiting feature, ensuring clarity and maintainability.
Updated Cloudflare Worker Script
javascript
// 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,
LOGGING_LEVEL: 'warn',
AUTH_KEY: 'your-secure-auth-key', // Replace with a secure 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: {},
CACHE_CONTROL: {
DEFAULT_MAX_AGE: 300, // 5 minutes
CUSTOM_RULES: {},
},
STREAM_THRESHOLD: 1024 * 1024, // 1MB
};
let CONFIG = { ...DEFAULT_CONFIG };
class ProxyError extends Error {
constructor(message, status) {
super(message);
this.name = 'ProxyError';
this.status = status;
}
}
addEventListener('fetch', (event) => {
event.passThroughOnException();
event.respondWith(
handleRequest(event).catch((error) => handleError(error, event.request))
);
});
async function handleRequest(event) {
const request = event.request;
const url = new URL(request.url);
if (request.method === 'OPTIONS') {
return handlePreflightRequest(request);
}
if (request.method === 'POST' && url.pathname === '/config') {
return handleConfigUpdate(request);
}
if (!isAllowedOrigin(request.headers.get('Origin'))) {
throw new ProxyError('Forbidden: Origin not allowed', 403);
}
return forwardRequest(request);
}
function isAllowedOrigin(origin) {
return origin && (CONFIG.ALLOWED_DOMAINS.has(origin) || CONFIG.ALLOWED_DOMAINS.has('*'));
}
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 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);
}
const init = {
method: request.method,
headers: new Headers(),
redirect: 'follow',
signal: AbortSignal.timeout(CONFIG.TIMEOUT),
};
const forbiddenHeaders = new Set([...CONFIG.REMOVE_HEADERS]);
// Forward allowed headers
for (const [key, value] of request.headers.entries()) {
const lowerKey = key.toLowerCase();
if (CONFIG.FORWARD_HEADERS.has(lowerKey) && !forbiddenHeaders.has(lowerKey)) {
init.headers.set(key, value);
}
}
// Handle request body
if (!['GET', 'HEAD'].includes(request.method)) {
init.body = request.body;
}
const response = await fetch(parsedTargetUrl.toString(), init);
return createCorsResponse(response, request);
}
function generateCorsHeaders(origin, requestHeaders) {
const headers = new Headers();
if (isAllowedOrigin(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
}
headers.set('Access-Control-Allow-Methods', '*'); // Allow all methods
// Allow all headers
headers.set('Access-Control-Allow-Headers', '*');
headers.set('Access-Control-Expose-Headers', '*');
headers.set('Access-Control-Max-Age', '86400');
headers.append('Vary', 'Origin');
return headers;
}
function handlePreflightRequest(request) {
const origin = request.headers.get('Origin') || '';
const corsHeaders = generateCorsHeaders(origin, request.headers);
return new Response(null, {
status: 204,
headers: corsHeaders,
});
}
async function createCorsResponse(response, request) {
const origin = request.headers.get('Origin') || '';
const corsHeaders = generateCorsHeaders(origin, request.headers);
const responseHeaders = new Headers(response.headers);
// Remove disallowed headers from the response
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);
// If request has a Content-Type header, set it in the response
const requestContentType = request.headers.get('Content-Type');
if (requestContentType) {
responseHeaders.set('Content-Type', requestContentType);
}
// Stream the response body
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
}
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}`);
}
}
async function handleError(error, request) {
const status = error instanceof ProxyError ? error.status : 500;
const message = error.message || 'Internal Server Error';
logError(error);
const origin = request.headers.get('Origin') || '';
const corsHeaders = generateCorsHeaders(origin, request.headers);
const headers = new Headers({
'Content-Type': 'application/json',
...corsHeaders,
...CONFIG.SECURITY_HEADERS,
});
const customErrorResponse = CONFIG.CUSTOM_ERROR_RESPONSES[status];
if (customErrorResponse) {
return new Response(JSON.stringify(customErrorResponse), {
status,
headers,
});
}
return new Response(JSON.stringify({ error: message }), { status, headers });
}
function logError(error) {
const logLevel = CONFIG.LOGGING_LEVEL.toLowerCase();
const logMessage = `[${new Date().toISOString()}] ${error.name}: ${error.message}`;
if (logLevel === 'error' && error.status >= 500) {
console.error(logMessage);
} else if (logLevel === 'warn' && error.status >= 400) {
console.warn(logMessage);
} else if (logLevel === 'info') {
console.info(logMessage);
} else if (logLevel === 'debug') {
console.debug(logMessage, error.stack);
}
}
async function handleConfigUpdate(request) {
const authHeader = request.headers.get('Authorization');
if (!authHeader || authHeader !== `Bearer ${CONFIG.AUTH_KEY}`) {
return new Response('Unauthorized', { status: 401 });
}
try {
const updatedConfig = await request.json();
updateConfig(updatedConfig);
return new Response(
JSON.stringify({ message: 'Configuration updated successfully' }),
{
status: 200,
headers: {
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
},
}
);
} catch (error) {
return new Response(JSON.stringify({ error: 'Invalid configuration data' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
},
});
}
}
function updateConfig(newConfig) {
for (const [key, value] of Object.entries(newConfig)) {
if (key in CONFIG) {
if (value instanceof Array) {
CONFIG[key] = new Set(value);
} else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
CONFIG[key] = { ...CONFIG[key], ...value };
} else {
CONFIG[key] = value;
}
}
}
// Ensure TIMEOUT doesn't exceed Cloudflare's limits (30 seconds)
CONFIG.TIMEOUT = Math.min(CONFIG.TIMEOUT, 30000);
}
// Helper function to reset configuration to default
function resetConfig() {
CONFIG = { ...DEFAULT_CONFIG };
}
Key Changes and Explanations:
CORS Headers Adjustments:
Access-Control-Allow-Methods: Changed from specific methods (GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH) to * to allow all HTTP methods.
Access-Control-Allow-Headers & Access-Control-Expose-Headers: Set to * to permit all headers, ensuring that the client can send and receive any headers without restrictions.
Access-Control-Allow-Credentials: Retained as true to allow cookies and other credentials to be sent if needed.
Rate Limiting Removal:
Removed Configuration: The RATE_LIMIT property has been entirely removed from the DEFAULT_CONFIG.
Eliminated Rate Limiting Functions and References: The checkRateLimit function, its invocation within handleRequest, and the RATELIMIT_KV placeholder have all been removed. This ensures that there are no rate limiting checks in place, completely removing any restrictions on request frequency.
Preserved Essential Features:
Security Headers: All security-related headers remain intact to ensure that the proxy maintains good security practices.
Configuration Management: The /config endpoint and related configuration update mechanisms are still available, allowing for dynamic updates to the proxy's configuration as needed.
Error Handling:
Robust error handling ensures that any issues are logged appropriately based on the configured LOGGING_LEVEL. Custom error responses can still be defined via the CUSTOM_ERROR_RESPONSES configuration.
Final Notes:
Authentication for Configuration Updates: Ensure that the AUTH_KEY in the configuration is kept secure and is used to authenticate any requests to update the proxy's configuration.
Allowed Domains Management: Keep the ALLOWED_DOMAINS set updated with all the domains that should have unrestricted access through the proxy.
Security Considerations: While CORS headers have been made more permissive for the allowed domains, always ensure that the proxy is only accessible by trusted domains to prevent misuse.
Testing: After deploying the updated script, thoroughly test it to ensure that:
Allowed domains can perform any type of request without encountering CORS errors.
Disallowed domains are appropriately blocked.
The proxy forwards requests and responses correctly without rate limiting in place.
Feel free to customize the DEFAULT_CONFIG further based on your specific requirements and ensure that all sensitive information, such as the AUTH_KEY, is securely managed.