Make sure it can Handle all of preflight or option request for the enabled domain so that The enabled domain can make Cross Origin Request successfully without getting any CORS errors. 

Make it more secure, eg; What I mean is to make sure that only the request insiater can check the response or requested resources while no one else can.

Don't compromise speed, security, reliability, robustness and powerfullness.

Make sure that only the request insiater or the requester can check the response or requested resources.

Don't use '*' until neccery. Restrict the response access to the requester only.

Make it more robust.

Handle all of the edge cases, errors, bottle necks, memory leaks, information leaks, etc.

Reinforce it further.

Make it as perfect as possible.

Don't compromise speed, security, reliability, robustness and powerfullness.

Fix all of the potential issues, edge cases, bottle necks, memory leaks, consumption, errors, etc.

Make this work correctly in all circumstances possible.

Send the fully working full codes.

// 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
};

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 = {
  enabledDomains: new Map(),
  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) {
    try {
      if (!domain || typeof domain !== 'string') return false;

      return domain.length <= SECURITY_CONSTANTS.MAX_DOMAIN_LENGTH &&
             /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)(?:\.[A-Za-z0-9-]{1,63})*$/.test(domain) &&
             !domain.includes('..') &&
             !/[<>{}()']/.test(domain);
    } catch {
      return false;
    }
  },

  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) {
    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: ["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"]
      }
    };

    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);
        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) {
        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 {
      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.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: [], // Use an array instead of a Set
          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);
        }
      }

      // 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 100 errors
        if (stats.statistics.errors.length > 100) {
          stats.statistics.errors = stats.statistics.errors.slice(-100);
        }

        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));
  }
};


{
  "manifest_version": 3,
  "name": "Secure CORS Handler Pro",
  "version": "1.3",
  "description": "Ultra-secure CORS handler with strict origin control and advanced security features",
  "permissions": [
    "storage",
    "activeTab",
    "declarativeNetRequest",
    "tabs"
  ],
  "host_permissions": [
    "*://*/*"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "action": {
    "default_icon": {
      "16": "icons/disabled-16.png",
      "32": "icons/disabled-32.png",
      "48": "icons/disabled-48.png",
      "128": "icons/disabled-128.png"
    }
  },
  "icons": {
    "16": "icons/disabled-16.png",
    "32": "icons/disabled-32.png",
    "48": "icons/disabled-48.png",
    "128": "icons/disabled-128.png"
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none'; base-uri 'none'"
  }
}