Certainly! Below is the modified version of your Chrome extension code. This version is hardcoded to work only on a specified domain and is designed to be practically impossible to make it work on any other domain, no matter the circumstances.
Please replace 'example.com' with the domain you want the extension to work with.
background.js
// Constants and Configuration
const SPECIFIED_DOMAIN = 'example.com'; // Replace with your specified domain
const RULE_IDS = {
CORS: 1,
PREFLIGHT: 2,
ORIGIN_CHECK: 3
};
const SECURITY_CONSTANTS = {
TOKEN_REFRESH_INTERVAL: 1800000, // 30 minutes
MAX_REQUESTS_PER_MINUTE: 100,
TOKEN_LENGTH: 32,
MAX_DOMAINS_PER_TAB: 10,
CLEANUP_INTERVAL: 300000, // 5 minutes
MAX_RETRIES: 3,
RETRY_DELAY: 100,
MAX_DOMAIN_LENGTH: 255,
MAX_HEADER_LENGTH: 8192,
REQUEST_TIMEOUT: 30000
};
const ALLOWED_METHODS = [
'GET',
'POST',
'PUT',
'DELETE',
'PATCH',
'OPTIONS',
'HEAD'
];
const ALLOWED_HEADERS = [
'Content-Type',
'Authorization',
'X-Requested-With',
'X-Security-Token',
'Origin',
'Accept',
'Access-Control-Request-Method',
'Access-Control-Request-Headers'
];
// Use Map instead of WeakMap for explicit control over cleanup
const state = {
enabledTabs: new Set(),
securityConfigs: new Map()
};
// Enhanced Error handling
class CORSHandlerError extends Error {
constructor(message, code, details = {}) {
super(message);
this.name = 'CORSHandlerError';
this.code = code;
this.details = details;
this.timestamp = new Date().toISOString();
}
}
// Security Utils
const SecurityUtils = {
async generateStrongToken() {
const array = new Uint8Array(SECURITY_CONSTANTS.TOKEN_LENGTH);
crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
},
sanitizeHeader(value) {
if (!value) return '';
return String(value)
.slice(0, SECURITY_CONSTANTS.MAX_HEADER_LENGTH)
.replace(/[<>{}()'\n\r]/g, '');
},
isValidDomain(domain) {
return domain === SPECIFIED_DOMAIN;
},
isValidOrigin(origin) {
try {
const url = new URL(origin);
return ['http:', 'https:'].includes(url.protocol) &&
SecurityUtils.isValidDomain(url.hostname);
} catch {
return false;
}
}
};
// Domain Security Class
class DomainSecurity {
constructor(domain) {
this.domain = domain;
this.token = null;
this.timestamp = Date.now();
this.allowedOrigins = new Set();
this.requestCount = new Map();
this.lastCleanup = Date.now();
this.errors = [];
}
async initialize() {
try {
this.token = await SecurityUtils.generateStrongToken();
return true;
} catch (error) {
this.logError('Token generation failed', error);
return false;
}
}
isTokenValid() {
return this.token &&
(Date.now() - this.timestamp) < SECURITY_CONSTANTS.TOKEN_REFRESH_INTERVAL;
}
addAllowedOrigin(origin) {
if (SecurityUtils.isValidOrigin(origin)) {
this.allowedOrigins.add(origin);
return true;
}
this.logError('Invalid origin attempted', { origin });
return false;
}
checkRateLimit(origin) {
const now = Date.now();
const minute = Math.floor(now / 60000);
if (!this.requestCount.has(minute)) {
this.cleanup(now);
this.requestCount.set(minute, new Map());
}
const originCount = this.requestCount.get(minute);
const count = (originCount.get(origin) || 0) + 1;
if (count > SECURITY_CONSTANTS.MAX_REQUESTS_PER_MINUTE) {
this.logError('Rate limit exceeded', { origin, count });
return false;
}
originCount.set(origin, count);
return true;
}
cleanup(now) {
try {
if (now - this.lastCleanup > SECURITY_CONSTANTS.CLEANUP_INTERVAL) {
const currentMinute = Math.floor(now / 60000);
for (const [minute] of this.requestCount) {
if (minute < currentMinute - 1) {
this.requestCount.delete(minute);
}
}
this.lastCleanup = now;
}
} catch (error) {
this.logError('Cleanup failed', error);
}
}
logError(message, details) {
const error = new CORSHandlerError(message, 'SECURITY_ERROR', details);
this.errors.push(error);
if (this.errors.length > 100) this.errors.shift();
console.error(error);
}
}
// CORS Rules Generator
class CORSRulesGenerator {
static createRules(domain, securityConfig, origin) {
if (!origin) return [];
const corsRule = {
id: RULE_IDS.CORS,
priority: 1,
action: {
type: "modifyHeaders",
responseHeaders: [
{
header: "Access-Control-Allow-Origin",
operation: "set",
value: origin
},
{
header: "Access-Control-Allow-Methods",
operation: "set",
value: ALLOWED_METHODS.join(', ')
},
{
header: "Access-Control-Allow-Headers",
operation: "set",
value: ALLOWED_HEADERS.join(', ')
},
{
header: "Access-Control-Allow-Credentials",
operation: "set",
value: "false"
},
{
header: "Access-Control-Max-Age",
operation: "set",
value: "3600"
},
{
header: "Access-Control-Expose-Headers",
operation: "set",
value: "Content-Length, Content-Type, X-Security-Token"
},
{
header: "X-Security-Token",
operation: "set",
value: securityConfig.token
},
{
header: "Vary",
operation: "set",
value: "Origin"
},
{
header: "Cross-Origin-Resource-Policy",
operation: "set",
value: "same-site"
},
{
header: "Cross-Origin-Opener-Policy",
operation: "set",
value: "same-origin"
},
{
header: "Referrer-Policy",
operation: "set",
value: "strict-origin-when-cross-origin"
},
{
header: "X-Content-Type-Options",
operation: "set",
value: "nosniff"
},
{
header: "X-Frame-Options",
operation: "set",
value: "SAMEORIGIN"
}
]
},
condition: {
domains: [domain],
urlFilter: "*",
resourceTypes: [
"xmlhttprequest"
]
}
};
const preflightRule = {
id: RULE_IDS.PREFLIGHT,
priority: 2,
action: {
type: "modifyHeaders",
responseHeaders: [
{
header: "Access-Control-Allow-Origin",
operation: "set",
value: origin
},
{
header: "Access-Control-Allow-Methods",
operation: "set",
value: ALLOWED_METHODS.join(', ')
},
{
header: "Access-Control-Allow-Headers",
operation: "set",
value: ALLOWED_HEADERS.join(', ')
},
{
header: "Access-Control-Allow-Credentials",
operation: "set",
value: "true"
},
{
header: "Access-Control-Max-Age",
operation: "set",
value: "3600"
}
]
},
condition: {
domains: [domain],
urlFilter: "*",
resourceTypes: ["other"],
requestMethods: ["options"]
}
};
const originCheckRule = {
id: RULE_IDS.ORIGIN_CHECK,
priority: 3,
action: {
type: "modifyHeaders",
requestHeaders: [
{
header: "Origin",
operation: "set",
value: origin
}
]
},
condition: {
domains: [domain],
urlFilter: "*",
resourceTypes: ["xmlhttprequest"]
}
};
return [corsRule, preflightRule, originCheckRule];
}
}
// Rule Manager
class RuleManager {
static async updateRules(enabled, tabId) {
try {
const domain = SPECIFIED_DOMAIN;
// Remove existing rules
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: Object.values(RULE_IDS)
});
if (!enabled) return;
// Get or create security config
let securityConfig = state.securityConfigs.get(domain);
if (!securityConfig || !securityConfig.isTokenValid()) {
securityConfig = new DomainSecurity(domain);
await securityConfig.initialize();
state.securityConfigs.set(domain, securityConfig);
}
// Get tab info and validate origin
const tab = await chrome.tabs.get(tabId);
if (!tab || !tab.url) {
throw new CORSHandlerError('Invalid tab or URL', 'INVALID_TAB', { tabId });
}
const tabUrl = new URL(tab.url);
const origin = tabUrl.origin;
if (!SecurityUtils.isValidOrigin(origin)) {
throw new CORSHandlerError('Invalid origin', 'INVALID_ORIGIN', { origin });
}
securityConfig.addAllowedOrigin(origin);
// Create and apply rules
const rules = CORSRulesGenerator.createRules(domain, securityConfig, origin);
if (rules.length) {
await chrome.declarativeNetRequest.updateDynamicRules({
addRules: rules
});
}
} catch (error) {
console.error('Error updating rules:', error);
throw error;
}
}
}
// UI Manager
class UIManager {
static async updateIcon(tabId, enabled) {
const path = enabled ? {
16: 'icons/enabled-16.png',
32: 'icons/enabled-32.png',
48: 'icons/enabled-48.png',
128: 'icons/enabled-128.png'
} : {
16: 'icons/disabled-16.png',
32: 'icons/disabled-32.png',
48: 'icons/disabled-48.png',
128: 'icons/disabled-128.png'
};
for (let i = 0; i < SECURITY_CONSTANTS.MAX_RETRIES; i++) {
try {
await chrome.action.setIcon({ tabId, path });
return;
} catch (error) {
if (i === SECURITY_CONSTANTS.MAX_RETRIES - 1) throw error;
await new Promise(resolve => setTimeout(resolve, SECURITY_CONSTANTS.RETRY_DELAY));
}
}
}
static async updateIconForInactiveTab(tabId) {
const path = {
16: 'icons/inactive-16.png',
32: 'icons/inactive-32.png',
48: 'icons/inactive-48.png',
128: 'icons/inactive-128.png'
};
for (let i = 0; i < SECURITY_CONSTANTS.MAX_RETRIES; i++) {
try {
await chrome.action.setIcon({ tabId, path });
return;
} catch (error) {
if (i === SECURITY_CONSTANTS.MAX_RETRIES - 1) throw error;
await new Promise(resolve => setTimeout(resolve, SECURITY_CONSTANTS.RETRY_DELAY));
}
}
}
}
// Event Handlers
class EventHandlers {
static async handleClick(tab) {
try {
const tabId = tab.id;
// Check if the tab's URL matches the specified domain
const tabUrl = new URL(tab.url);
const domain = tabUrl.hostname;
if (domain !== SPECIFIED_DOMAIN) {
throw new CORSHandlerError('This extension only works on the specified domain.', 'DOMAIN_MISMATCH', { domain });
}
const isEnabled = state.enabledTabs.has(tabId);
const enabled = !isEnabled;
await RuleManager.updateRules(enabled, tabId);
if (enabled) {
state.enabledTabs.add(tabId);
} else {
state.enabledTabs.delete(tabId);
}
await UIManager.updateIcon(tabId, enabled);
} catch (error) {
console.error('Error handling click:', error);
// Optionally, provide user feedback through notifications or UI updates
}
}
static async handleTabUpdate(tabId, changeInfo, tab) {
if (changeInfo.url) {
const tabUrl = new URL(tab.url);
const domain = tabUrl.hostname;
const isEnabled = state.enabledTabs.has(tabId);
if (domain !== SPECIFIED_DOMAIN) {
await UIManager.updateIconForInactiveTab(tabId);
return;
}
if (isEnabled) {
try {
await RuleManager.updateRules(true, tabId);
await UIManager.updateIcon(tabId, true);
} catch (error) {
console.error('Error updating rules on tab update:', error);
await UIManager.updateIcon(tabId, false);
}
} else {
await UIManager.updateIconForInactiveTab(tabId);
}
}
}
static async handleTabActivation(activeInfo) {
const tabId = activeInfo.tabId;
try {
const tab = await chrome.tabs.get(tabId);
if (tab && tab.url) {
const tabUrl = new URL(tab.url);
const domain = tabUrl.hostname;
const isEnabled = state.enabledTabs.has(tabId);
if (domain !== SPECIFIED_DOMAIN) {
await UIManager.updateIconForInactiveTab(tabId);
return;
}
if (isEnabled) {
try {
await RuleManager.updateRules(true, tabId);
await UIManager.updateIcon(tabId, true);
} catch (error) {
console.error('Error updating rules on tab activation:', error);
await UIManager.updateIcon(tabId, false);
}
} else {
await UIManager.updateIconForInactiveTab(tabId);
}
}
} catch (error) {
console.error('Error handling tab activation:', error);
}
}
}
// Initialization
chrome.runtime.onInstalled.addListener(async () => {
console.log('CORS Handler extension installed.');
});
chrome.action.onClicked.addListener(EventHandlers.handleClick);
chrome.tabs.onUpdated.addListener(EventHandlers.handleTabUpdate);
chrome.tabs.onActivated.addListener(EventHandlers.handleTabActivation);
manifest.json
{
"manifest_version": 3,
"name": "CORS Handler",
"version": "1.0.0",
"description": "A Chrome extension to manage CORS headers and enhance security for web requests.",
"permissions": [
"declarativeNetRequest",
"declarativeNetRequestFeedback",
"tabs",
"activeTab",
"storage"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_icon": {
"16": "icons/disabled-16.png",
"32": "icons/disabled-32.png",
"48": "icons/disabled-48.png",
"128": "icons/disabled-128.png"
},
"default_title": "CORS Handler"
},
"icons": {
"16": "icons/disabled-16.png",
"32": "icons/disabled-32.png",
"48": "icons/disabled-48.png",
"128": "icons/disabled-128.png"
},
"content_scripts": [],
"web_accessible_resources": [
{
"resources": [
"icons/enabled-16.png",
"icons/enabled-32.png",
"icons/enabled-48.png",
"icons/enabled-128.png",
"icons/disabled-16.png",
"icons/disabled-32.png",
"icons/disabled-48.png",
"icons/disabled-128.png",
"icons/inactive-16.png",
"icons/inactive-32.png",
"icons/inactive-48.png",
"icons/inactive-128.png"
],
"matches": ["*://*/*"]
}
],
"host_permissions": [
"*://example.com/*"
]
}
Instructions:
-
Replace 'example.com' with your specified domain:
-
In background.js, change the value of SPECIFIED_DOMAIN to the domain you want the extension to work with. For example:
const SPECIFIED_DOMAIN = 'yourdomain.com';
-
In manifest.json, update the host_permissions field:
"host_permissions": [
"*://yourdomain.com/*"
]
-
Icons:
- Place your icon files in the
icons folder. The extension uses icons for different states (enabled, disabled, and inactive) in sizes 16x16, 32x32, 48x48, and 128x128 pixels.
- The icon filenames should match those referenced in the
manifest.json and background.js.
-
Usage:
- Install the extension in Chrome by loading it as an unpacked extension in developer mode.
- Navigate to your specified domain.
- Click the extension icon to enable or disable the CORS handling for that domain.
- The extension will only work on the specified domain and is designed to prevent operation on any other domains.
How It Works:
Note: This extension is designed to be as secure and restrictive as possible to meet your requirements. If you have any further customizations or need assistance with implementation, feel free to ask!