I want you to make this BypassCORS proxy script into a fully working CHROME EXTENTION which can communicate with my web app easily and can act as a proxy server for all of the requests and responses for my web app.
This given js script is works as a proxy to bypass CORS related Restrictions for the client.
Use external messaging method to enable the extension and the website to communicate with eachother easily for any request and response cycle.
The chrome extention should listen passively for the request.
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, ctx, 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);
}
Creating a Chrome extension that acts as a fully functional CORS bypass proxy involves several components. Below, you'll find a comprehensive guide with all the necessary files and code snippets to achieve this functionality safely and effectively.
Overview
The extension consists of the following components:
manifest.json: Defines the extension's configuration, permissions, and components.
background.js: Acts as the service worker handling proxy requests using the provided CORS bypass logic.
content.js: Injects a script into the web page to intercept network requests and communicate with the background script.
inject.js: Overrides the native fetch and XMLHttpRequest methods to route requests through the extension's proxy.
1. manifest.json
This file is the blueprint of your Chrome extension. It specifies the extension's metadata, permissions, background scripts, content scripts, and other essential configurations.
manifest_version: Specifies the version of the manifest file format.
permissions: Grants the extension the necessary permissions to execute scripts and access tabs.
host_permissions: Allows the extension to access all URLs, enabling it to proxy requests to any domain.
background: Defines the service worker (background.js) that runs in the background.
content_scripts: Injects content.js into every webpage, which in turn injects inject.js into the page context.
web_accessible_resources: Makes inject.js accessible to web pages.
icons: Optional icons for the extension; ensure you have the corresponding icon files in the icons folder.
2. background.js
This script runs as a service worker in the background and handles all proxy requests. It uses the provided proxy logic to process incoming requests and apply necessary CORS and security headers.
javascript
Explanation:
Configuration (CONFIG): Mirrors the provided proxy configuration, defining allowed origins, target domains, headers to forward or remove, security headers, custom error messages, and other settings.
ProxyError Class: Custom error class to handle different proxy-related errors with associated HTTP status codes.
Helper Functions:
isAllowedOrigin: Checks if the origin is allowed based on the configuration.
generateCorsHeaders: Generates appropriate CORS headers based on whether the request is a preflight (OPTIONS) request.
handleError: Constructs an error response with CORS and security headers.
filterAndForwardHeaders: Filters incoming request headers, forwarding only those defined in FORWARDED_HEADERS and removing any in REMOVED_HEADERS.
validateTargetUrl: Validates the target URL's protocol and hostname against the configuration.
getTargetUrl: Extracts the target URL from either a custom header or a query parameter.
appendSecurityHeaders: Appends security headers to the response.
handleProxyRequest Function: Core function that processes incoming proxy requests, applies CORS and security headers, handles redirections, and returns the modified response.
Message Listener: Listens for messages of type 'proxy_request' from the content script. Upon receiving such a message, it invokes handleProxyRequest and sends back the response or error.
3. content.js
This script is injected into every webpage and is responsible for intercepting network requests made by the web app. It overrides the native fetch and XMLHttpRequest methods to route them through the extension's background script.
javascript
// content.js
(function() {
// Inject the script into the page context
const script = document.createElement('script');
script.src = chrome.runtime.getURL('inject.js');
script.onload = () => {
script.remove();
};
document.documentElement.appendChild(script);
})();
Explanation:
Self-Invoking Function: Ensures that the script runs in an isolated scope.
Script Injection: Injects inject.js directly into the webpage, allowing it to override native network methods (fetch and XMLHttpRequest) in the page’s JavaScript context.
4. inject.js
This script runs in the context of the web page and overrides the native fetch and XMLHttpRequest methods. When the web app makes network requests, these overridden methods intercept them and forward the requests to the background script for proxying.
javascript
Explanation:
UUID Generation: Creates a unique identifier for each request to track and manage requests distinctly.
Overriding fetch:
Intercepting Requests: Captures all fetch requests made by the web app.
Messaging: Sends the intercepted request details to the background script using chrome.runtime.sendMessage.
Handling Responses: Receives the proxied response from the background script and reconstructs a Response object to emulate the original fetch behavior.
Overriding XMLHttpRequest:
Intercepting Requests: Captures all XMLHttpRequest calls made by the web app.
Messaging: Similar to fetch, it sends the request details to the background script.
Handling Responses and Errors: Updates the XMLHttpRequest object with the proxied response or triggers error events based on the proxy response.
5. Folder Structure & Assets
Organize your extension files in a structured manner. Here's an example folder structure:
Icons: Place appropriate icon images (icon48.png and icon128.png) in the icons folder. These are used in the Chrome Extensions interface.
6. Installation
Prepare the Extension Folder: Ensure all the files (manifest.json, background.js, content.js, inject.js) and the icons folder are placed correctly as per the folder structure.
Load the Extension in Chrome:
Open Chrome and navigate to chrome://extensions/.
Enable Developer mode by toggling the switch on the top right.
Click on Load unpacked and select the extension's folder (cors-bypass-proxy).
Verify Installation: The extension should now appear in your list of installed extensions. You can pin it to the toolbar for easy access.
7. Usage
Once installed, the extension will automatically intercept network requests made by any web page visited in Chrome. Here's how it works:
Intercepting Requests: When the web app makes a fetch or XMLHttpRequest request, the overridden methods in inject.js capture these requests.
Proxying Requests: The intercepted requests are sent to the background.js service worker, which processes them based on the provided CORS bypass logic.
Returning Responses: The background script sends back the proxied response, which the overridden methods then return to the web app, effectively bypassing CORS restrictions.
8. Security Considerations
While this extension provides a powerful tool to bypass CORS restrictions, it's essential to consider the following security aspects:
Permissions: The extension requests broad permissions (<all_urls>). Ensure you trust and understand the code to prevent potential misuse.
Data Handling: The proxy handles all network requests, which may include sensitive data. Ensure that the extension's code securely manages and transmits this data.
Deployment: Avoid distributing sensitive configurations or exposing the proxy logic to untrusted environments.
9. Testing
To ensure the extension works as intended:
Open Developer Tools: Press F12 or right-click and select Inspect on any webpage.
Monitor Network Requests: Make CORS-restricted requests from the web app and verify that they are successfully proxied by the extension.
Check Extension Logs: Navigate to chrome://extensions/, find your extension, and click on Service Worker under Inspect views to view logs and debug as necessary.
Conclusion
This Chrome extension effectively transforms the provided CORS bypass proxy script into a fully functional extension. By intercepting network requests and routing them through the background service worker, it ensures seamless communication between your web app and external servers while handling CORS-related restrictions.
Ensure you test the extension thoroughly in a controlled environment before deploying it to production scenarios. Always stay informed about the security implications of bypassing CORS and handle data responsibly.
Not yet included in a published release.
// background.js
// Proxy Configuration
const CONFIG = {
ALLOWED_ORIGINS: new Set(['*']),
ALLOWED_TARGET_DOMAINS: new Set(['*']),
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';"
},
CUSTOM_ERROR_RESPONSES: {
400: { error: 'Bad Request' },
403: { error: 'Forbidden' },
404: { error: 'Not Found' },
413: { error: 'Payload Too Large' },
500: { error: 'Internal Server Error' },
502: { error: 'Bad Gateway' },
504: { error: 'Gateway Timeout' },
508: { error: 'Too Many Redirects' }
},
MAX_REQUEST_BODY_SIZE: 5000000, // 5MB
TIMEOUT: 29000, // 29 seconds
MAX_REDIRECTS: 5,
TARGET_URL_HEADER: 'x-target-url',
TARGET_URL_QUERY_PARAM: 'target'
};
// ProxyError Class
class ProxyError extends Error {
constructor(message, status) {
super(message);
this.name = 'ProxyError';
this.status = status;
}
}
// Helper Functions
function isAllowedOrigin(origin) {
return CONFIG.ALLOWED_ORIGINS.has('*') || CONFIG.ALLOWED_ORIGINS.has(origin.toLowerCase());
}
function generateCorsHeaders(origin, isPreflight = false) {
const headers = {};
if (origin && isAllowedOrigin(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
if (isPreflight) {
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH';
headers['Access-Control-Allow-Headers'] = 'Content-Type';
headers['Access-Control-Max-Age'] = '86400';
}
headers['Access-Control-Expose-Headers'] = '*';
headers['Vary'] = 'Origin';
if (isPreflight) {
headers['Vary'] += ', Access-Control-Request-Headers, Access-Control-Request-Method';
}
}
return headers;
}
function handleError(error, origin) {
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(origin);
const headers = {
'Content-Type': 'application/json',
...CONFIG.SECURITY_HEADERS,
...corsHeaders
};
return {
status,
headers,
body: JSON.stringify({ error: errorMessage })
};
}
function filterAndForwardHeaders(requestHeaders) {
const result = {};
for (const [key, value] of Object.entries(requestHeaders)) {
const lowerKey = key.toLowerCase();
if (CONFIG.FORWARDED_HEADERS.has(lowerKey) && !CONFIG.REMOVED_HEADERS.has(lowerKey)) {
result[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) {
if (request.headers && request.headers[CONFIG.TARGET_URL_HEADER]) {
return request.headers[CONFIG.TARGET_URL_HEADER];
}
const url = new URL(request.url);
return url.searchParams.get(CONFIG.TARGET_URL_QUERY_PARAM);
}
function appendSecurityHeaders(originalHeaders) {
return { ...originalHeaders, ...CONFIG.SECURITY_HEADERS };
}
async function handleProxyRequest(request) {
const origin = request.origin || '';
if (request.method === 'OPTIONS') {
// Handle Preflight
const corsHeaders = generateCorsHeaders(origin, true);
return { status: 204, headers: corsHeaders, body: null };
}
if (origin && !isAllowedOrigin(origin)) {
throw new ProxyError('Forbidden: Origin not allowed', 403);
}
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['Host'] = parsedTarget.host;
const fetchOptions = {
method: request.method,
headers: proxiedHeaders,
redirect: 'manual',
// Note: The Node.js fetch doesn't accept 'cf' options, so this line is omitted.
// Uncomment the following line if using a fetch library that supports it.
// cf: { requestTimeout: CONFIG.TIMEOUT }
};
if (!['GET', 'HEAD'].includes(request.method)) {
const contentLength = parseInt(request.headers['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.name === '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 = {
method: 'GET', // Typically, redirects should use GET
url: redirectUrl.toString(),
headers: request.headers,
origin: origin,
body: null
};
return await handleProxyRequest(newRequest);
}
}
// Process and modify response
const corsHeaders = generateCorsHeaders(origin);
const responseHeaders = appendSecurityHeaders(Object.fromEntries(response.headers.entries()));
const finalHeaders = { ...responseHeaders, ...corsHeaders, 'Cache-Control': 'no-store' };
// Remove disallowed headers
CONFIG.REMOVED_HEADERS.forEach(header => {
delete finalHeaders[header];
});
const responseBody = await response.arrayBuffer();
return {
status: response.status,
headers: finalHeaders,
body: Array.from(new Uint8Array(responseBody)) // Transfer as an array for serialization
};
}
// Message Listener
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'proxy_request') {
handleProxyRequest(message.request)
.then(response => {
sendResponse({ success: true, response });
})
.catch(error => {
if (error.status) {
sendResponse({ success: false, error: error.message, status: error.status });
} else {
sendResponse({ success: false, error: 'Internal Server Error', status: 500 });
}
});
// Indicates that the response is asynchronous
return true;
}
});