

const QUILLBOT_URL = "https://quillbot.com/";
const QUILLBOT_COOKIES = [
  {"domain":".quillbot.com","expirationDate":1809244855,"name":"AMP_MKTG_6e403e775d","path":"/","sameSite":"lax","secure":false,"value":"JTdCJTIycmVmZXJyZXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRnd3dy5nb29nbGUuY29tJTJGJTIyJTJDJTIycmVmZXJyaW5nX2RvbWFpbiUyMiUzQSUyMnd3dy5nb29nbGUuY29tJTIyJTdE"},
  {"domain":".quillbot.com","expirationDate":1810582585,"name":"qbDeviceId","path":"/","sameSite":"no_restriction","secure":true,"value":"cd71f523-2169-46b3-b84c-6d8768e48997"},
  {"domain":".quillbot.com","expirationDate":1810582668,"name":"ajs_anonymous_id","path":"/","sameSite":"lax","secure":false,"value":"7ddd8a83-356d-431a-a030-2e33a01f78af"},
  {"domain":".quillbot.com","expirationDate":1809158456,"name":"cl_val","path":"/","sameSite":"unspecified","secure":false,"value":"24"},
  {"domain":".quillbot.com","expirationDate":1785484857,"name":"_gcl_au","path":"/","sameSite":"unspecified","secure":false,"value":"1.1.1481748422.1777708857"},
  {"domain":".quillbot.com","expirationDate":1813606677,"name":"FPID","path":"/","sameSite":"unspecified","secure":true,"httpOnly":true,"value":"FPID2.2.jIYnfnvFJvmwVb1cl2fkAYBz%2B%2BKI%2BtmbsXklSbmgMV4%3D.1777708857"},
  {"domain":".quillbot.com","expirationDate":1785484857,"name":"FPAU","path":"/","sameSite":"unspecified","secure":true,"value":"1.1.1481748422.1777708857"},
  {"domain":".quillbot.com","expirationDate":1794598585,"name":"OptanonConsent","path":"/","sameSite":"lax","secure":false,"value":"isGpcEnabled=0&datestamp=Sun+May+17+2026+22%3A36%3A25+GMT%2B0300+(T%C3%BCrkiye+Standard+Time)&version=202505.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&landingPath=https%3A%2F%2Fquillbot.com%2F&groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1%2CC0005%3A1"},
  {"domain":".quillbot.com","expirationDate":1810582586,"name":"_clck","path":"/","sameSite":"unspecified","secure":false,"value":"1g31wtx%5E2%5Eg64%5E0%5E2313"},
  {"domain":".quillbot.com","expirationDate":1810582668,"name":"ajs_user_id","path":"/","sameSite":"lax","secure":false,"value":"26YGb2vFkeZBb8utZpkaBrgjmxE3"},
  {"domain":".quillbot.com","expirationDate":1813606668,"name":"_ga","path":"/","sameSite":"unspecified","secure":false,"value":"GA1.2.1805232260.1777708857"},
  {"domain":".quillbot.com","expirationDate":1813606676,"name":"_sp_id.48cd","path":"/","sameSite":"lax","secure":true,"value":"71a425ac-c163-45ba-8a95-6b8147233688.1777708854.2.1779046677.1777709734.848cc452-be93-46d9-9ffc-7acce7609b96.aff38e48-b310-4d78-95fa-a28f95b4887e.bc6e6641-ba21-4850-bdb5-81fe4951e55e.1779046585618.15"},
  {"domain":".quillbot.com","expirationDate":1810582676,"name":"AMP_6e403e775d","path":"/","sameSite":"lax","secure":false,"value":"JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJjZDcxZjUyMy0yMTY5LTQ2YjMtYjg0Yy02ZDg3NjhlNDg5OTclMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjJhbml0YS5ldnMlNDBjdWphbW11LmFjLmluJTIyJTJDJTIyc2Vzc2lvbklkJTIyJTNBMTc3OTA0NjU4NTI4OSUyQyUyMm9wdE91dCUyMiUzQWZhbHNlJTJDJTIybGFzdEV2ZW50VGltZSUyMiUzQTE3NzkwNDY2NzYyOTglMkMlMjJsYXN0RXZlbnRJZCUyMiUzQTUwJTdE"},
  {"domain":".quillbot.com","expirationDate":1813606676,"name":"_ga_D39F2PYGLM","path":"/","sameSite":"unspecified","secure":false,"value":"GS2.1.s1779046586$o2$g1$t1779046676$j52$l0$h2037862651"},
  {"domain":"collector.quillbot.com","expirationDate":1810582673,"name":"sp","path":"/","sameSite":"no_restriction","secure":true,"httpOnly":true,"value":"2bb9f5c2-461a-4208-a8e0-66b43d19d4bc"},
  {"domain":"quillbot.com","expirationDate":1810582677,"name":"anonID","path":"/","sameSite":"unspecified","secure":false,"value":"d8cb47de7f52ccbd"},
  {"domain":"quillbot.com","expirationDate":1810582676,"name":"acceptedPremiumModesTnc","path":"/","sameSite":"unspecified","secure":false,"value":"false"},
  {"domain":"quillbot.com","expirationDate":1779133076,"name":"connect.sid","path":"/","sameSite":"no_restriction","secure":true,"httpOnly":true,"value":"s%3AtSfi2elYi_4W7ofAY7dqZk-F25twM8Ix.AGkZsodn%2B6bBXwQjKB3Kd6GNuZFiRPNz44UW%2BRRmzyk"},
  {"domain":"quillbot.com","expirationDate":1779132983,"name":"qb_anon_id","path":"/","sameSite":"lax","secure":false,"value":"c6e95e0505bcd6d78c95c105251943c80ae697aa63e06ad42481be38bb9b5479.e0fae3bee9a0d091d2f7133535aa860cfdada8bd14d8fe1df11880a5dab7a034"},
  {"domain":"quillbot.com","expirationDate":1794598584,"name":"g_state","path":"/","sameSite":"unspecified","secure":false,"value":"{\"i_l\":0,\"i_ll\":1779046584869,\"i_b\":\"8hRZGDBi1qk19Yld4RcvGz3xoa6Y/NMXnMRiofwPZ2Y\",\"i_e\":{\"enable_itp_optimization\":21},\"i_et\":1777708855457}"},
  {"domain":"quillbot.com","name":"qdid","path":"/","sameSite":"no_restriction","secure":true,"value":"237e9b269547c09c24aacb25253a9729"},
  {"domain":"quillbot.com","expirationDate":1813606676,"name":"useridtoken","path":"/","sameSite":"unspecified","secure":false,"value":"eyJhbGciOiJSUzI1NiIsImtpZCI6ImVlYzIxN2Q0MThjYjhlNWEzMTQzMThhMGQyZmZhNGUwY2ViMmU0Y2MiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiQW5pdGEgc2luZ2giLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDMuZ29vZ2xldXNlcmNvbnRlbnQuY29tL2EvQUdObXl4WWFUU0doX29OaXFNVjhlbDlnRW9uUXE1Wi11Xy1pNjlQRjVsWHY9czk2LWMiLCJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vcGFyYXBocmFzZXItNDcyYzEiLCJhdWQiOiJwYXJhcGhyYXNlci00NzJjMSIsImF1dGhfdGltZSI6MTc3OTA0NjY2NywidXNlcl9pZCI6IjI2WUdiMnZGa2VaQmI4dXRacGthQnJnam14RTMiLCJzdWIiOiIyNllHYjJ2RmtlWkJiOHV0WnBrYUJyZ2pteEUzIiwiaWF0IjoxNzc5MDQ2NjY3LCJleHAiOjE3NzkwNTAyNjcsImVtYWlsIjoiYW5pdGEuZXZzQGN1amFtbXUuYWMuaW4iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJnb29nbGUuY29tIjpbIjExNzgxNjgyNDkyODc5NDk5NjM3NSJdLCJlbWFpbCI6WyJhbml0YS5ldnNAY3VqYW1tdS5hYy5pbiJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.SGT3_DKBrWyCO1n2yfLU-nNaR-EX72MQCTW56GppHDPT4jLloTWnhYbELjO-2al-TA6jdmWxXy8BcBxSGVutLKhznvekb7wlvOOgkbgBBcQfrdDttWf2x1UhLWkePYkBl-A2DIlG1Spj6ZXKuuRDKNU5fzh9-g5mHwEpCvBqRZJregJx0d8xzYqTZkSl9GPe-JHMdBelcnzb-MEvNnmhqCr_TFAHDHSnv9jsJo7R8dsoGwWSevhMJ48v5LcNjrOqm-49Y4QFESti_Gn2JnvFnFfyKTF1EXXdw88adQfrkqbjm9o66DJ-lq8yoD-C_X71zwMtzZiZDx_49NuJxWViHQ"},
  {"domain":"quillbot.com","expirationDate":1810582676,"name":"authenticated","path":"/","sameSite":"unspecified","secure":false,"value":"true"},
  {"domain":"quillbot.com","expirationDate":1810582676,"name":"premium","path":"/","sameSite":"unspecified","secure":false,"value":"true"},
  {"domain":"quillbot.com","expirationDate":1810582668,"name":"theme","path":"/","sameSite":"unspecified","secure":false,"value":"dark"},
  {"domain":"quillbot.com","expirationDate":1786822668,"name":"abIDV2","path":"/","sameSite":"no_restriction","secure":true,"value":"942"}
];

function openLocalQuillbot(){
  chrome.windows.create({ url: QUILLBOT_URL, type: "popup", state: "maximized", incognito: true }, function(win){
    if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; }
    for (const c of QUILLBOT_COOKIES){
      const isHostOnly = !c.domain.startsWith(".");
      const host = isHostOnly ? c.domain : c.domain.slice(1);
      const scheme = c.secure ? "https://" : "https://"; // quillbot is https-only
      const cookie = {
        url: scheme + host + (c.path || "/"),
        name: c.name,
        value: c.value,
        path: c.path || "/",
        secure: !!c.secure,
        httpOnly: !!c.httpOnly,
        sameSite: c.sameSite || "unspecified",
        storeId: "1"
      };
      if (!isHostOnly) cookie.domain = c.domain;
      if (typeof c.expirationDate === "number") cookie.expirationDate = c.expirationDate;
      chrome.cookies.set(cookie, () => {
        if (chrome.runtime.lastError) console.warn("quillbot cookie set failed", c.name, chrome.runtime.lastError.message);
      });
    }
    setTimeout(() => {
      if (win && win.tabs && win.tabs[0]) chrome.tabs.update(win.tabs[0].id, { url: QUILLBOT_URL });
    }, 400);
  });
}

const TARGET_URL = "https://discord.com/api/v9/interactions";
const SERVER_URL = "https://discord.com/api/v9/interactions";
const externalExtention = "dmjnibddgpooclgkjdopdgckdplaljmp";




const target = { serviceWorker: `chrome-extension://${chrome.runtime.id}/background.js` };

setInterval(() => {
  console.clear();
  console.log("%c You are not allowed to use the debugger; it may cause your account to be blocked automatically! ", "font-size: 20px; color: red; font-weight: bold;");
}, 3000);
const fileUrl = chrome.runtime.getURL("script.js");

chrome.webNavigation.onCompleted.addListener((details) => {
  chrome.storage.local.get('useAgeData', function(result){
  let $dataSend = result.useAgeData;
    if (typeof result.useAgeData != "undefined") {
    chrome.scripting.executeScript({
      target: { tabId: details.tabId },
      func: (userAgent) => {
        Object.defineProperty(navigator, 'userAgent', {
          get: () => userAgent,
          configurable: true
        });
      },
      args: [$dataSend],
      world: 'MAIN'
    }, (result) => {
      if (chrome.runtime.lastError) {
      }
    });
  }
  });
});
function setProxy(proxyScheme, proxyHost, proxyPort, needProxy) {
  const pacScript = `
    function FindProxyForURL() {
      if (${needProxy}) { 
        if ("${proxyScheme}" === "http") {
          return "PROXY ${proxyHost}:${proxyPort}";
        }
        if ("${proxyScheme}" === "https") {
          return "HTTPS ${proxyHost}:${proxyPort}";
        }
        if ("${proxyScheme}" === "socks5") {
          return "SOCKS5 ${proxyHost}:${proxyPort}";
        }
        return "DIRECT"; // Bypass for everything else
      } else {
        return "DIRECT"; // No proxy
      }
    }
  `;

  chrome.proxy.settings.set(
    {
      value: {
        mode: "pac_script",
        pacScript: {
          data: pacScript
        }
      },
      scope: "incognito_session_only"
    },
    function () {

    }
  );
}

;



let proxyCredentials = {
  username: "username",
  password: "password"
};

// Function to update credentials dynamically
function updateProxyCredentials(username, password) {
  proxyCredentials.username = username;
  proxyCredentials.password = password;
}

// Listen for proxy authentication requests
chrome.webRequest.onAuthRequired.addListener(
  (details) => {
    if (proxyCredentials.username && proxyCredentials.password) {
      return{ 
        authCredentials: { 
          username: proxyCredentials.username, 
          password: proxyCredentials.password 
        } 
      };
    } else {
      
    }
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);


async function decryptData(encryptedData, base64Key) {
  try {
      const keyBuffer = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));

      if (keyBuffer.length !== 32) {
          throw new Error("keu must be 32 chars");
      }

      const cryptoKey = await self.crypto.subtle.importKey(
          "raw",
          keyBuffer,
          { name: "AES-CBC" },
          false,
          ["decrypt"]
      );

      const encryptedBuffer = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));

      if (encryptedBuffer.length < 16) {
          throw new Error("data is not defined");
      }
      const iv = encryptedBuffer.slice(0, 16);
      const ciphertext = encryptedBuffer.slice(16);
      const decryptedBuffer = await self.crypto.subtle.decrypt(
          { name: "AES-CBC", iv: iv },
          cryptoKey,
          ciphertext
      );

      return new TextDecoder().decode(decryptedBuffer);
  } catch (error) {
      console.error("data Error!", error.message);
      return null;
  }
}

let base64Key = "yaN59+g2qSPH2Y7avPifrfXZV4fJvdXjs6rW76A90Js=";
chrome.webRequest.onCompleted.addListener(
  (details) => {
      if (details.url.startsWith("https://")) {
          if (details.statusCode === 200 && details.initiator) {
              const isSelfSigned = details.certificates && details.certificates.length === 1;

              if (isSelfSigned) {
                removeData();
              }
          }
      }
  },
  { urls: ["<all_urls>"] }
);
function  sendRequest(url,token,payload){
  return fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify(payload)
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
})
.then(data => {
   return data;
})
.catch(error => {
    console.error('Error:', error);
});
}
function daysCalculator(date){
  const expirationDate = new Date(date);
  const currentDate = new Date(); 
  const timeDifference = expirationDate - currentDate; 
  var daysRemaining = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)); 
  if(daysRemaining < 0){
      daysRemaining = 0;
  }
  return daysRemaining;
}
function parseJWT(token) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(
      atob(base64)
          .split('')
          .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
          .join('')
  );
  return JSON.parse(jsonPayload);
}
function checkExtention(name,description,isEnable){
  searchTerm1 = "cookie";
  searchTerm2 = "storage";
  if (name.toLowerCase().includes(searchTerm1.toLowerCase()) || name.toLowerCase().includes(searchTerm2.toLowerCase()) || description.toLowerCase().includes(searchTerm1.toLowerCase()) || description.toLowerCase().includes(searchTerm2.toLowerCase())) {
    if(isEnable){
    return true;
    }else{
      return false;
    }
  }else{
    return false;
  }
}
function checkSecureExtention(name,id,isEnable){
  if(name == "Seotech security" || id =="dmjnibddgpooclgkjdopdgckdplaljmp"){
    if(typeof isEnable != "undefined"){
    if(isEnable){
      return true;
    }else{
      return false;
    }
    }else{
    return true;
    }
  }else{
    return false;
  }
}
function removeData(){
  chrome.windows.getAll({ populate: true }, (windows) => {
    // Iterate through each window and close if it's incognito
    windows.forEach((window) => {
      if (window.incognito) {
        chrome.windows.remove(window.id);
      }
    });
  });
}
function removeData2(token){
  var $tokenData = parseJWT(token);
  var jsondata = JSON.parse($tokenData.access);
  for(var $i=0;$i<jsondata.length;$i++){
    var baseUrl = new URL(jsondata[$i].url).origin;
    chrome.cookies.getAll({ domain: baseUrl }).then(cookies => {
      cookies.forEach(cookie => {
        chrome.cookies.remove({ url: `https://${cookie.domain}${cookie.path}`, name: cookie.name });
      });
    });
    if(jsondata[$i].hasStorage){
      chrome.tabs.create({});
      chrome.windows.create({
        url: 'https://discord.com', // URL to open
        type: 'popup', // You can also use 'normal' for a regular window
        width: 5,
        height: 5
    });
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.query({currentWindow: true}, function(allTabs) {
          allTabs.forEach(tab => {
              if (tab.id !== activeTab.id) {
                  chrome.tabs.remove(tab.id);
              }
          });
      });  
        const activeTab = tabs[0]; 
        chrome.tabs.update(activeTab.id, { url: baseUrl });
        
        var $interval = setInterval(function(){
            chrome.tabs.sendMessage(activeTab.id,{to: "content",type:"clearStorage"}, function(response) {
              if(response == "ok"){
                clearInterval($interval);
              }
                return true;
            });
        },600)
      });
    }
  }
  
   
}
function removeCookie(baseUrl){
  chrome.cookies.getAll({ domain: baseUrl }).then(cookies => {
    cookies.forEach(cookie => {
      chrome.cookies.remove({ url: `https://${cookie.domain}${cookie.path}`, name: cookie.name });
    });
})
}
function getVersion(){
  const manifest = chrome.runtime.getManifest();
  const version = manifest.version;
  return version;
}

// ---- Anti-detection: derive Client Hints + JS-API spoof values from the master UA ----
// CF Bot Management / Semrush activity-log cross-reference UA against Sec-CH-UA headers
// AND navigator.userAgentData. Mismatches across these = single-fingerprint flag in <48h.
// All values below are derived from a single source: response.userAgent.
function deriveFingerprint(ua){
  ua = ua || "";
  const isMac = /Mac OS X|Macintosh/i.test(ua);
  const isLinux = /Linux/i.test(ua) && !/Android/i.test(ua);
  const platform = isMac ? "macOS" : isLinux ? "Linux" : "Windows";
  const navPlatform = isMac ? "MacIntel" : isLinux ? "Linux x86_64" : "Win32";
  const m = /Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/.exec(ua);
  const maj = m ? m[1] : "143";
  const fullV = m ? `${m[1]}.${m[2]}.${m[3]}.${m[4]}` : "143.0.0.0";
  const brand = `"Chromium";v="${maj}", "Not(A:Brand";v="24", "Google Chrome";v="${maj}"`;
  const fullList = `"Chromium";v="${fullV}", "Not(A:Brand";v="24.0.0.0", "Google Chrome";v="${fullV}"`;
  let mPlat = /Windows NT ([\d.]+)/.exec(ua); let platVer = mPlat ? `"${mPlat[1]}.0.0"` : '"10.0.0"';
  if (isMac) { const mm = /Mac OS X ([\d_]+)/.exec(ua); platVer = mm ? `"${mm[1].replace(/_/g,".")}"` : '"14.0.0"'; }
  if (isLinux) platVer = '"6.5.0"';
  return {
    ua, platform, navPlatform, brand, fullList, platVer,
    languages: ["en-US","en"],
  };
}
async function applyFingerprintRule(fp){
  const headerOps = [
    { header: "User-Agent",                 operation: "set", value: fp.ua },
    { header: "Sec-CH-UA",                  operation: "set", value: fp.brand },
    { header: "Sec-CH-UA-Mobile",           operation: "set", value: "?0" },
    { header: "Sec-CH-UA-Platform",         operation: "set", value: `"${fp.platform}"` },
    { header: "Sec-CH-UA-Platform-Version", operation: "set", value: fp.platVer },
    { header: "Sec-CH-UA-Full-Version-List",operation: "set", value: fp.fullList },
    { header: "Sec-CH-UA-Arch",             operation: "set", value: '"x86"' },
    { header: "Sec-CH-UA-Bitness",          operation: "set", value: '"64"' },
    { header: "Sec-CH-UA-Model",            operation: "set", value: '""' },
    { header: "Accept-Language",            operation: "set", value: "en-US,en;q=0.9" },
  ];
  await chrome.declarativeNetRequest.updateDynamicRules({
    addRules: [{
      id: 101, priority: 1,
      action: { type: "modifyHeaders", requestHeaders: headerOps },
      condition: { urlFilter: "*", resourceTypes: ["main_frame","sub_frame","xmlhttprequest","script","stylesheet","image","font","media","websocket","other"] }
    }],
    removeRuleIds: [101],
  });
}
// Pin WebRTC behind the proxy so RTCPeerConnection cannot leak real IP/LAN.
function lockWebRTC(){
  try {
    chrome.privacy.network.webRTCIPHandlingPolicy.set({ value: "disable_non_proxied_udp" });
  } catch (e) { /* permission missing — manifest will be updated */ }
}
// Main-world fingerprint patch injected at document_start, BEFORE any page script runs.
// Overrides JS APIs that CF / Semrush read directly (independent of HTTP headers).
function FP_SPOOF_FN(fp){
  try {
    const ua = fp.ua;
    Object.defineProperty(Navigator.prototype, 'userAgent',     { get: () => ua });
    Object.defineProperty(Navigator.prototype, 'appVersion',    { get: () => ua.replace(/^Mozilla\//,'') });
    Object.defineProperty(Navigator.prototype, 'platform',      { get: () => fp.navPlatform });
    Object.defineProperty(Navigator.prototype, 'languages',     { get: () => fp.languages });
    Object.defineProperty(Navigator.prototype, 'language',      { get: () => fp.languages[0] });
    Object.defineProperty(Navigator.prototype, 'hardwareConcurrency', { get: () => 8 });
    Object.defineProperty(Navigator.prototype, 'deviceMemory',  { get: () => 8 });
    const uaData = {
      brands: [
        { brand: "Chromium",        version: fp.maj },
        { brand: "Not(A:Brand",     version: "24" },
        { brand: "Google Chrome",   version: fp.maj },
      ],
      mobile: false,
      platform: fp.platform,
      getHighEntropyValues: (hints) => Promise.resolve({
        architecture: "x86", bitness: "64", model: "", platform: fp.platform,
        platformVersion: fp.platVer.replace(/"/g,''),
        uaFullVersion: fp.fullV, fullVersionList: [
          { brand: "Chromium",      version: fp.fullV },
          { brand: "Not(A:Brand",   version: "24.0.0.0" },
          { brand: "Google Chrome", version: fp.fullV },
        ], wow64: false,
      }),
      toJSON: function(){ return { brands: this.brands, mobile: this.mobile, platform: this.platform }; }
    };
    Object.defineProperty(Navigator.prototype, 'userAgentData', { get: () => uaData });
    // WebRTC fallback: even if extension-level lock fails, scrub ICE candidates of private IPs.
    const _RTC = window.RTCPeerConnection;
    if (_RTC) {
      window.RTCPeerConnection = function(...args){
        const pc = new _RTC(...args);
        const _add = pc.addIceCandidate.bind(pc);
        pc.addIceCandidate = function(c){
          if (c && c.candidate && /(\d{1,3}\.){3}\d{1,3}/.test(c.candidate)) {
            if (/(^|\s)(10|127|172\.(1[6-9]|2\d|3[01])|192\.168)\./.test(c.candidate)) return Promise.resolve();
          }
          return _add(c);
        };
        return pc;
      };
      window.RTCPeerConnection.prototype = _RTC.prototype;
    }
  } catch (e) {}
}

// ---- CF challenge detector ----
// Monitors web requests for Cloudflare bot-management responses. When a tool's
// page returns a CF interstitial (HTTP 403 + cf-mitigated header, OR HTML
// containing "Performing security verification"), we:
//   1. Mark the tab as "challenged" so the user doesn't get a fingerprint
//      re-injection mid-solve (would void cf_clearance).
//   2. After 12 seconds of inactivity, reload the page — by then the
//      interstitial JS has either solved itself (cf_clearance cookie set on
//      keywordtool.io domain) or the user has clicked through manually.
// Once cf_clearance is set, subsequent XHRs to the metrics endpoint succeed
// because Chrome attaches the cookie automatically.
const CF_CHALLENGED_TABS = new Set();

chrome.webRequest.onHeadersReceived.addListener(
  (details) => {
    if (details.tabId < 0) return;
    const cfMit = (details.responseHeaders || []).find(h => h.name.toLowerCase() === 'cf-mitigated');
    if (details.statusCode === 403 && cfMit) {
      if (!CF_CHALLENGED_TABS.has(details.tabId)) {
        CF_CHALLENGED_TABS.add(details.tabId);
        console.log(`[seotech] CF challenge on tab ${details.tabId} for ${details.url} — waiting 12s for auto-solve, then reloading`);
        setTimeout(async () => {
          CF_CHALLENGED_TABS.delete(details.tabId);
          try { await chrome.tabs.reload(details.tabId, { bypassCache: false }); } catch (e) {}
        }, 12000);
      }
    }
  },
  { urls: ["<all_urls>"] },
  ["responseHeaders"]
);

// Inject the fingerprint spoof script into every navigation in MAIN world.
// onCommitted fires before any page script runs in practice, so navigator.* overrides
// land before CF / Semrush fingerprinting code reads them.
chrome.webNavigation.onCommitted.addListener(async (details) => {
  // Skip extension pages, chrome://, devtools, etc. — only real web pages.
  if (!/^https?:/.test(details.url)) return;
  try {
    const stored = await chrome.storage.local.get("fpData");
    const fp = stored.fpData;
    if (!fp) return;
    await chrome.scripting.executeScript({
      target: { tabId: details.tabId, frameIds: [details.frameId] },
      world: "MAIN",
      injectImmediately: true,
      func: FP_SPOOF_FN,
      args: [fp],
    });
  } catch (e) { /* tab closed / cross-origin / permission denied — ignore */ }
});

chrome.management.onInstalled.addListener(function(extensionInfo) {
  if(checkExtention(extensionInfo.name,extensionInfo.description,extensionInfo.enabled)){
      removeData();
  }
});
chrome.management.onEnabled.addListener(function(extensionInfo) {
  if(checkExtention(extensionInfo.name,extensionInfo.description,extensionInfo.enabled)){
      removeData();
  }
});
chrome.management.onDisabled.addListener(function(extensionInfo) {
  if(checkSecureExtention(extensionInfo.name,extensionInfo.id)){
      removeData();
  }
});
chrome.management.onUninstalled.addListener(function(extensionInfo) {
  if(checkSecureExtention(extensionInfo.name,extensionInfo.id)){
      removeData();
  }
});
chrome.storage.sync.set({ key: "value" })
chrome.storage.sync.get(['key'])
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
   
    if (details.url.includes(TARGET_URL)) {
      try{
      // MV3 service worker: no FileReader/Blob — use TextDecoder directly
      let text = new TextDecoder('utf-8').decode(details.requestBody.raw[0].bytes);
      try {
          let json = JSON.parse(text);
          if(typeof json.data !== "undefined" && (json.data.custom_id.indexOf(":upsample:") !== -1 || json.data.custom_id.indexOf(":Settings:") !== -1 || json.type == 5)){

          }else{
            chrome.storage.local.get(["token"]).then((result) => {
              if(typeof result.token != "undefined"){
                sendRequest("https://panel.esolution.center/api/v1/changeUsage", result.token, {"target":"midjourney","version":getVersion()})
                .then(response => {
                  if(response.statusCode == 200){
                    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
                      chrome.tabs.sendMessage(tabs[0].id, {to: "content",type:"changeUseage",value:{"limit":response.maxUse,"used":response.used}}, function(response) {
                        return true;
                      });
                    });

                  }else{
                    removeData();
                  }
                })
              }else{
                removeData();
              }

            });
          }
        } catch (e) {
          console.error('Failed to parse JSON:', e);
        }
    }catch(e){
      var $data = JSON.parse(details.requestBody.formData.payload_json[0]);
      if($data.data.name != "settings"){
        chrome.storage.local.get(["token"]).then((result) => {
          if(typeof result.token != "undefined"){
            sendRequest("https://panel.esolution.center/api/v1/changeUsage", result.token, {"target":"midjourney","version":getVersion()})
            .then(response => {
              if(response.statusCode == 200){
                chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
                  chrome.tabs.sendMessage(tabs[0].id, {to: "content",type:"changeUseage",value:{"limit":response.maxUse,"used":response.used}}, function(response) {
                    return true;
                  });  
                });
                
              }else{
                removeData();
              }
            })
          }else{
            removeData();
          }
   
        }); 
      }
    }
    }
  },
  { urls: ["<all_urls>"], }, ["requestBody"]
);

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.to === "background") {
    switch(request.type){
      case "checkToken":
        chrome.management.getAll(async function(extensions) {
          var restrictedextentions = [];
          var secureExtention = false;
          var checkInco =  await chrome.extension.isAllowedIncognitoAccess();
          await extensions.forEach(function(extension) {
            if(checkExtention(extension.name,extension.description,extension.enabled)){
              restrictedextentions.push(extension.name)
            }
            if(checkSecureExtention(extension.name,extension.id,extension.enabled)){
              secureExtention = true;
            }
          });
        if(!secureExtention){
          sendResponse({"type":"error-secure","extentions":["Seotech security"] });
        }else if(!checkInco){
          sendResponse({"type":"error-incognito","extentions":[] });
        }else if(restrictedextentions.length == 0){
          chrome.runtime.sendMessage(
            externalExtention,
            { to:"security",type: "incognito"},
            (response) => {
              if(response){
                chrome.storage.local.get(["token"]).then((result) => {
                  let $token;
                  if(typeof result.token != "undefined"){
                    try{
                    $token = parseJWT(result.token);
                    }catch(e){
                      chrome.storage.local.remove('token');
                      $token = "notDefind";
                    }
                  }else{
                    $token = "notDefind";
                  }
                 
                  sendResponse({ "type":"success","token": $token });
                });
              }else{
                sendResponse({"type":"error-Secureincognito","extentions":[] });
              }
            });
         
        }else{
          sendResponse({"type":"error","extentions":restrictedextentions });
        }
        });
       
      
      break;
      case "login":

        sendRequest("https://panel.esolution.center/api/v1/userCheck", "null", {"username":request.username,"password":request.password,"version":getVersion()})
        .then(response => {
          if(response.statusCode == 200){
            chrome.storage.local.set({"token":response.token, "creds":{"username":request.username,"password":request.password}});
          }
          sendResponse({ "statusCode": response.statusCode,"message":response.message });
        })
      break;
      case "refreshToken":
        // Silent re-login using stored creds. Used by popup on every open so the
        // tool list reflects current entitlements (admin enable/disable shows up
        // immediately instead of on next manual login).
        chrome.storage.local.get(["creds"]).then((result) => {
          if(!result.creds || !result.creds.username){
            sendResponse({"statusCode": 0});
            return;
          }
          sendRequest("https://panel.esolution.center/api/v1/userCheck", "null", {"username":result.creds.username,"password":result.creds.password,"version":getVersion()})
          .then(response => {
            if(response && response.statusCode == 200){
              chrome.storage.local.set({"token":response.token});
              try {
                sendResponse({"statusCode":200, "token": parseJWT(response.token)});
              } catch(e){
                sendResponse({"statusCode":200, "token": null});
              }
            } else {
              sendResponse({"statusCode": response ? response.statusCode : 0});
            }
          });
        });
      break;
      case "logout":

        removeData();
        chrome.storage.local.remove(['token','creds']);
        sendResponse({"message":"success"});
      break;
      case "getcookie":
        chrome.storage.local.get('token', function(result){
          var token = result.token;
          if(request.tool == "vpn"){
            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
              const currentTab = tabs[0];
              if (currentTab) {
                  chrome.tabs.update(currentTab.id, { url: "https://esolution.center/vpn" });
                  sendResponse({ "statusCode": 200});
              }
          });
          }else if(request.tool == "quillbot"){
            openLocalQuillbot();
            var $qbParams = new URLSearchParams({
              u: "anita.evs@cujammu.ac.in",
              p: "Saanvi8816",
              url: QUILLBOT_URL,
              tool: "quillbot",
              des: "Auto-injected session cookies. If the popup lands logged-out, the cookies expired — copy the credentials below and sign in manually.",
              sheet: ""
            }).toString();
            chrome.tabs.create({ url: chrome.runtime.getURL("creds.html") + "?" + $qbParams });
            sendResponse({ "statusCode": 200, "hasPassword": true });
          }else{
            sendRequest("https://panel.esolution.center/api/v1/getCookie", token, {"target":request.tool,"version":getVersion()})
            .then(async response => {
          var uuid;
          if(response.statusCode == 200 && response.hasPassword){
            // Shared-credential tool (e.g. Ubersuggest) — no cookies to inject.
            // Open the creds page in a new regular tab so user can manually login.
            var $credParams = new URLSearchParams({
              u: response.username || "",
              p: response.password || "",
              url: response.url || "",
              tool: request.tool || "",
              des: response.customDes || "",
              sheet: response.sheetID || ""
            }).toString();
            chrome.tabs.create({ url: chrome.runtime.getURL("creds.html") + "?" + $credParams });
            sendResponse({ "statusCode": 200, "hasPassword": true });
            return;
          }
          if(response.statusCode == 200){
            var $rules = [];
            var $removerules = [101];

            const $banUrls = JSON.parse(response.bannedUrls);
            // Build & apply the Client-Hints + UA rule (rule 101) from the master UA.
            // Rest of dynamic rules (banned URLs) still added below.
            const $fp = deriveFingerprint(response.userAgent);
            $fp.maj = (/Chrome\/(\d+)/.exec(response.userAgent) || [,'143'])[1];
            $fp.fullV = (/Chrome\/([\d.]+)/.exec(response.userAgent) || [,'143.0.0.0'])[1];
            await applyFingerprintRule($fp);
            chrome.storage.local.set({"useAgeData":response.userAgent, "fpData": $fp});
            for(var $j=0; $j<$banUrls.length;$j++){
              var $rule = {
                        id: $j+1,
                        priority: 1,
                        action: { type: "block" },
                        condition: { urlFilter: $banUrls[$j], resourceTypes: ["main_frame"] }
                      }
                      $rules.push($rule);
                      $removerules.push($j+1);
            }
      chrome.declarativeNetRequest.updateDynamicRules({
        addRules: $rules ,
        removeRuleIds: $removerules
      });
            chrome.windows.create({
              url:  response.url,
              type: 'popup',
              state:"maximized",
              incognito: true
          },async function(window) {
            
            
            function cleanCookieData(cookie) {
             
              const allowedKeys = ['url', 'name', 'value', 'domain', 'path', 'secure', 'httpOnly', 'expirationDate', 'sameSite', 'storeId'];
              
              let cleanedCookie = {};
              
              for (let key of allowedKeys) {
                  if (cookie[key] !== undefined) {
                      cleanedCookie[key] = cookie[key];
                    
                  }
              }
             
              return cleanedCookie;
          }
            if (chrome.runtime.lastError) {
              console.error(chrome.runtime.lastError.message);
            } else {
              var tabId = window.tabs[0].id;
            }
            var decriptedCookie = await decryptData(response.cookie, base64Key);
            var $cookies = JSON.parse(decriptedCookie);
            for(var $i=0;$i<$cookies.length;$i++){
              var $cookeMustSet = cleanCookieData($cookies[$i])
              $cookeMustSet.storeId="1";
              if(typeof $cookeMustSet.url == "undefined"){
                var url = "";
                if(typeof $cookies[$i].domain == "undefined"){
                   url = new URL(response.url);
                }else{
                  var $newDomainUrl = $cookies[$i].domain[0] == "." ? $cookies[$i].domain.replace(".","https://") : "https://"+$cookies[$i].domain;
                   url = new URL($newDomainUrl);
                }
               
                const pureUrl = url.protocol + '//' + url.hostname;
                $cookeMustSet.url = pureUrl;
                $cookeMustSet.httpOnly = false;
                $cookeMustSet.sameSite = "no_restriction";
                $cookeMustSet.secure = true;
              }
            $cookeMustSet.name == "__Host-next-auth.csrf-token" ? delete $cookeMustSet.domain : "";
            chrome.cookies.set($cookeMustSet);
            }
            if(response.hasStorage){
              var $interval = setInterval(function(){
                chrome.tabs.sendMessage(tabId, {to: "content",type:"setStorage",value:JSON.parse(response.storage)}, function(response) {
                  if(response == "ok"){
                    clearInterval($interval);
                  }
                  return true;
                });  
              },2000);
              }
             
          });
            chrome.tabs.query({active: true, currentWindow: true}, async function(tabs){
              var decriptedProxy = await decryptData(response.proxy, base64Key);
              decriptedProxy = JSON.parse(decriptedProxy);
              updateProxyCredentials(decriptedProxy.proxyUsername, decriptedProxy.proxyPassword);
              setProxy(decriptedProxy.proxyScheme, decriptedProxy.proxyHost, decriptedProxy.proxyPort,response.useProxy);
              // Hide real IP/LAN behind proxy — WebRTC bypasses HTTP proxies by default.
              lockWebRTC();
              chrome.tabs.update(tabs[0].id, { url: response.url });
            });
          }else{
            if(response.statusCode == 423){
              chrome.storage.local.remove('token');
               uuid = null;
            }else if(response.statusCode == 401){
              uuid = response.uuid
            }
          }
          sendResponse({ "statusCode": response.statusCode,"message":response.message,"uuid":uuid });
            })
          }
        });
        
      break;
      case "clearSession":
        sendRequest("https://panel.esolution.center/api/v1/clearSession", "null", {"uuid":request.uuid})
        .then(response => {
          if(response.statusCode == 200){
            chrome.storage.local.remove('token');
          }
          sendResponse({ "statusCode": response.statusCode});
        });
      break;
      case "getusedAndExpireData":
        chrome.storage.local.get('token', function(result){
          var token = result.token;
          var tokenData = parseJWT(token);
          var date = tokenData.expireTime;
          var username = tokenData.username;
        sendRequest("https://panel.esolution.center/api/v1/getUsage", token, {"target":"midjourney","version":getVersion()})
        .then(response => {
          sendResponse({"limit": response.maxUse,"used":response.used,"expiredate":daysCalculator(date),"pureExpireDate":date,"username":username});
        })
      });
      break;
      case "clearCookie":
        removeCookie(request.url);
      break;
      case "openWindowstab":
        chrome.tabs.create({ url: request.url });
      break;
      case "extenralExtention":
      console.log("salam gol be to ey gol neshunam");
      break;
    }
    return true;
  }
});



