javascript Copy code
// Use strict mode for better error handling
'use strict';
// Constants and Configuration
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,
MAX_ERRORS: 100
};
// Allowed methods and headers for CORS
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'
];
// Global state
const state = {
enabledDomains: new Map(), // tabId => Set(domains)
securityConfigs: new Map() // domain => DomainSecurity
};
// 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 Utilities
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) {
if (!domain || typeof domain !== 'string') return false;
const domainRegex = /^(?!:\/\/)([a-zA-Z0-9-_~]+\.)*[a-zA-Z0-9-_~]+$/;
return domain.length <= SECURITY_CONSTANTS.MAX_DOMAIN_LENGTH &&
domainRegex.test(domain) &&
!domain.includes('..') &&
!/[<>{}()']/.test(domain);
},
isValidOrigin(origin) {
try {
const url = new URL(origin);
const validProtocols = ['http:', 'https:'];
return validProtocols.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) {
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;
}
}
logError(message, details) {
const error = new CORSHandlerError(message, 'SECURITY_ERROR', details);
this.errors.push(error);
if (this.errors.length > SECURITY_CONSTANTS.MAX_ERRORS) this.errors.shift();
console.error(error);
}
}
// CORS Rules Generator
class CORSRulesGenerator {
static createRules(domain, securityConfig) {
const origins = Array.from(securityConfig.allowedOrigins);
if (!origins.length) return [];
const primaryOrigin = origins[0];
const corsRule = {
id: RULE_IDS.CORS,
priority: 1,
action: {
type: "modifyHeaders",
responseHeaders: [
{
header: "Access-Control-Allow-Origin",
operation: "set",
value: primaryOrigin
},
{
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"
},
{
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: [
"main_frame",
"sub_frame",
"stylesheet",
"script",
"image",
"font",
"object",
"xmlhttprequest",
"media",
"websocket",
"other"
]
}
};
const preflightRule = {
id: RULE_IDS.PREFLIGHT,
priority: 2,
action: {
type: "modifyHeaders",
responseHeaders: [
{
header: "Access-Control-Allow-Origin",
operation: "set",
value: primaryOrigin
},
{
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: ["xmlhttprequest", "websocket", "other"],
requestMethods: ["options"]
}
};
const originCheckRule = {
id: RULE_IDS.ORIGIN_CHECK,
priority: 3,
action: {
type: "modifyHeaders",
requestHeaders: [
{
header: "Origin",
operation: "set",
value: primaryOrigin
}
]
},
condition: {
domains: [domain],
urlFilter: "*",
resourceTypes: ["xmlhttprequest", "fetch", "other"]
}
};
return [corsRule, preflightRule, originCheckRule];
}
}
// Rule Manager
class RuleManager {
static async updateRules(domain, enabled, tabId) {
try {
if (!SecurityUtils.isValidDomain(domain)) {
throw new CORSHandlerError('Invalid domain', 'INVALID_DOMAIN', { 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);
const initialized = await securityConfig.initialize();
if (!initialized) throw new Error('Failed to initialize security config');
state.securityConfigs.set(domain, securityConfig);
}
// Get tab info and validate origin
const tab = await chrome.tabs.get(tabId);
if (tab && tab.url) {
const origin = new URL(tab.url).origin;
securityConfig.addAllowedOrigin(origin);
}
// Create and apply rules
const rules = CORSRulesGenerator.createRules(domain, securityConfig);
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, domain, 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));
}
}
}
}
// Event Handlers
class EventHandlers {
static async handleClick(tab) {
try {
if (!tab || !tab.url) {
throw new CORSHandlerError('Invalid tab or URL', 'INVALID_TAB');
}
const url = new URL(tab.url);
const domain = url.hostname;
if (!SecurityUtils.isValidDomain(domain)) {
throw new CORSHandlerError('Invalid domain', 'INVALID_DOMAIN', { domain });
}
const tabState = state.enabledDomains.get(tab.id) || new Set();
const wasEnabled = tabState.has(domain);
if (wasEnabled) {
tabState.delete(domain);
} else {
if (tabState.size >= SECURITY_CONSTANTS.MAX_DOMAINS_PER_TAB) {
throw new CORSHandlerError('Too many enabled domains', 'MAX_DOMAINS_EXCEEDED');
}
tabState.add(domain);
}
state.enabledDomains.set(tab.id, tabState);
await RuleManager.updateRules(domain, !wasEnabled, tab.id);
await UIManager.updateIcon(tab.id, domain, !wasEnabled);
await chrome.tabs.reload(tab.id);
} catch (error) {
console.error('Error in click handler:', error);
}
}
static async handleTabUpdate(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab && tab.url) {
try {
const url = new URL(tab.url);
const domain = url.hostname;
if (!SecurityUtils.isValidDomain(domain)) return;
const tabState = state.enabledDomains.get(tabId);
const enabled = tabState && tabState.has(domain);
await UIManager.updateIcon(tabId, domain, enabled);
if (enabled) {
const config = state.securityConfigs.get(domain);
if (!config || !config.isTokenValid()) {
await RuleManager.updateRules(domain, true, tabId);
}
}
} catch (error) {
console.error('Error in tab update handler:', error);
}
}
}
static handleTabRemoval(tabId) {
state.enabledDomains.delete(tabId);
}
static async handleInstall() {
try {
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: Object.values(RULE_IDS)
});
await EventHandlers.initializeStorage();
} catch (error) {
console.error('Error in initialization:', error);
}
}
static async initializeStorage() {
try {
await chrome.storage.local.set({
installationDate: Date.now(),
lastCleanup: Date.now(),
statistics: {
totalRequests: 0,
blockedRequests: 0,
uniqueDomains: [],
errors: []
}
});
} catch (error) {
console.error('Error initializing storage:', error);
}
}
}
// Cleanup Manager
class CleanupManager {
static async performCleanup() {
try {
const now = Date.now();
// Clean up security configs
for (const [domain, config] of state.securityConfigs) {
if (now - config.timestamp > SECURITY_CONSTANTS.TOKEN_REFRESH_INTERVAL * 2) {
state.securityConfigs.delete(domain);
}
}
// Clean up enabled domains
for (const [tabId, domains] of state.enabledDomains) {
if (!(await chrome.tabs.get(tabId))) {
state.enabledDomains.delete(tabId);
}
}
// Update storage statistics
const stats = await chrome.storage.local.get('statistics');
if (stats.statistics) {
stats.statistics.lastCleanup = now;
await chrome.storage.local.set({ statistics: stats.statistics });
}
} catch (error) {
console.error('Error in cleanup:', error);
}
}
}
// Statistics Manager
class StatisticsManager {
static async logRequest(details) {
try {
const stats = await chrome.storage.local.get('statistics');
if (stats.statistics) {
stats.statistics.totalRequests++;
const domain = new URL(details.url).hostname;
if (!stats.statistics.uniqueDomains.includes(domain)) {
stats.statistics.uniqueDomains.push(domain);
}
await chrome.storage.local.set({ statistics: stats.statistics });
}
} catch (error) {
console.error('Error logging request:', error);
}
}
static async logError(error) {
try {
const stats = await chrome.storage.local.get('statistics');
if (stats.statistics) {
stats.statistics.errors.push({
timestamp: Date.now(),
error: error.message,
code: error.code,
details: error.details
});
// Keep only last MAX_ERRORS errors
if (stats.statistics.errors.length > SECURITY_CONSTANTS.MAX_ERRORS) {
stats.statistics.errors = stats.statistics.errors.slice(-SECURITY_CONSTANTS.MAX_ERRORS);
}
await chrome.storage.local.set({ statistics: stats.statistics });
}
} catch (err) {
console.error('Error logging error:', err);
}
}
}
// Initialize Event Listeners
chrome.action.onClicked.addListener(EventHandlers.handleClick);
chrome.tabs.onUpdated.addListener(EventHandlers.handleTabUpdate);
chrome.tabs.onRemoved.addListener(EventHandlers.handleTabRemoval);
chrome.runtime.onInstalled.addListener(EventHandlers.handleInstall);
// Initialize periodic cleanup
self.setInterval(() => {
CleanupManager.performCleanup();
}, SECURITY_CONSTANTS.CLEANUP_INTERVAL);
// Error Boundary
self.onunhandledrejection = (event) => {
console.error('Unhandled promise rejection:', event.reason);
StatisticsManager.logError(event.reason);
};
self.onerror = (message, source, lineno, colno, error) => {
console.error('Global error:', error);
if (error) {
StatisticsManager.logError(error);
} else {
StatisticsManager.logError(new Error(message));
}
};
By incorporating these changes, the extension should now handle all CORS-related requests securely and efficiently, ensuring that only the request initiator can access the resources without compromising on speed, security, reliability, or robustness.