Make it practically impossible to work on any domain or requests or web page except the specified one only no matter the circumstances. Send the fully working full codes. // Constants and Configuration (No changes needed)
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 (No changes needed)
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 (No changes needed)
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 (No changes needed)
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 (Modified to use exact origin)
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 (Modified to update rules with exact origin)
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) {
        throw new CORSHandlerError('Invalid tab or URL', 'INVALID_TAB', { tabId });
      }
      
      const origin = new URL(tab.url).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 (No changes needed)
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));
      }
    }
  }

  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 (Modified to handle errors and update icon)
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);
      const enabled = !wasEnabled;

      await RuleManager.updateRules(domain, enabled, tab.id);

      if (enabled) {
        tabState.add(domain);
      } else {
        tabState.delete(domain);
      }
      state.enabledDomains.set(tab.id, tabState);

      await UIManager.updateIcon(tab.id, domain, 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 url = new URL(tab.url);
      const domain = url.hostname;
      const tabState = state.enabledDomains.get(tabId) || new Set();
      const isEnabled = tabState.has(domain);

      if (isEnabled) {
        try {
          await RuleManager.updateRules(domain, true, tabId);
          await UIManager.updateIcon(tabId, domain, true);
        } catch (error) {
          console.error('Error updating rules on tab update:', error);
          await UIManager.updateIcon(tabId, domain, false);
        }
      } else {
        await UIManager.updateIconForInactiveTab(tabId);
      }
    }
  }

  static async handleTabActivation(activeInfo) {
    const tabId = activeInfo.tabId;
    const tab = await chrome.tabs.get(tabId);
    if (tab && tab.url) {
      const url = new URL(tab.url);
      const domain = url.hostname;
      const tabState = state.enabledDomains.get(tabId) || new Set();
      const isEnabled = tabState.has(domain);

      if (isEnabled) {
        try {
          await RuleManager.updateRules(domain, true, tabId);
          await UIManager.updateIcon(tabId, domain, true);
        } catch (error) {
          console.error('Error updating rules on tab activation:', error);
          await UIManager.updateIcon(tabId, domain, false);
        }
      } else {
        await UIManager.updateIconForInactiveTab(tabId);
      }
    }
  }
}

// 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_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": ["<all_urls>"]
    }
  ],
  "host_permissions": [
    "<all_urls>"
  ]
}