"use strict";exports.id=5718,exports.ids=[5718],exports.modules={8578:(a,b,c)=>{let d=c(33873),e=c(29021),f=c(15296),{MITM_DIR:g}=c(82193),h=d.join(g,"rootCA.key"),i=d.join(g,"rootCA.crt");function j(a){try{let b=f.pki.certificateFromPem(e.readFileSync(a,"utf8")),c=new Date(Date.now()+2592e6);return b.validity.notAfter<c}catch{return!0}}a.exports={generateRootCA:async function a(){let a=e.existsSync(h)&&e.existsSync(i);if(a&&!j(i))return console.log("✅ Root CA already exists"),{key:h,cert:i};if(a){console.log("\uD83D\uDD10 Root CA expired or expiring soon — regenerating...");try{e.unlinkSync(h)}catch{}try{e.unlinkSync(i)}catch{}}e.existsSync(g)||e.mkdirSync(g,{recursive:!0}),console.log("\uD83D\uDD10 Generating Root CA certificate...");let b=f.pki.rsa.generateKeyPair(2048),c=f.pki.createCertificate();c.publicKey=b.publicKey,c.serialNumber="01",c.validity.notBefore=new Date,c.validity.notAfter=new Date,c.validity.notAfter.setFullYear(c.validity.notBefore.getFullYear()+10);let d=[{name:"commonName",value:"KTRouter MITM Root CA"},{name:"organizationName",value:"KTRouter"},{name:"countryName",value:"US"}];c.setSubject(d),c.setIssuer(d),c.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,cRLSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),c.sign(b.privateKey,f.md.sha256.create());let k=f.pki.privateKeyToPem(b.privateKey),l=f.pki.certificateToPem(c);return e.writeFileSync(h,k),e.writeFileSync(i,l),console.log("✅ Root CA generated successfully"),{key:h,cert:i}},loadRootCA:function(){if(!e.existsSync(h)||!e.existsSync(i))throw Error("Root CA not found. Generate it first.");let a=e.readFileSync(h,"utf8"),b=e.readFileSync(i,"utf8");return{key:f.pki.privateKeyFromPem(a),cert:f.pki.certificateFromPem(b)}},generateLeafCert:function(a,b){let c=f.pki.rsa.generateKeyPair(2048),d=f.pki.createCertificate();return d.publicKey=c.publicKey,d.serialNumber=Math.floor(1e6*Math.random()).toString(),d.validity.notBefore=new Date,d.validity.notAfter=new Date,d.validity.notAfter.setFullYear(d.validity.notBefore.getFullYear()+1),d.setSubject([{name:"commonName",value:a}]),d.setIssuer(b.cert.subject.attributes),d.setExtensions([{name:"basicConstraints",cA:!1},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:a},{type:2,value:`*.${a}`}]}]),d.sign(b.key,f.md.sha256.create()),{key:f.pki.privateKeyToPem(c.privateKey),cert:f.pki.certificateToPem(d)}},isCertExpired:j,ROOT_CA_CERT_PATH:i,ROOT_CA_KEY_PATH:h}},9631:(a,b,c)=>{let d=c(29021),e=c(55511),{exec:f}=c(79646),{execWithPassword:g,isSudoAvailable:h}=c(66936),{runElevatedPowerShell:i,quotePs:j,isAdmin:k}=c(64809),{log:l,err:m}=c(87777),n="win32"===process.platform,o="darwin"===process.platform,p=[{dir:"/usr/local/share/ca-certificates",cmd:"update-ca-certificates"},{dir:"/etc/ca-certificates/trust-source/anchors",cmd:"update-ca-trust"},{dir:"/etc/pki/ca-trust/source/anchors",cmd:"update-ca-trust"},{dir:"/etc/pki/trust/anchors",cmd:"update-ca-certificates"}];function q(){for(let a of p)if(d.existsSync(a.dir))return a;return p[0]}let r="KTRouter MITM Root CA";function s(a){let b=d.readFileSync(a,"utf-8"),c=Buffer.from(b.replace(/-----[^-]+-----/g,"").replace(/\s/g,""),"base64");return e.createHash("sha1").update(c).digest("hex").toUpperCase().match(/.{2}/g).join(":")}async function t(a){var b,c;let e,g;return n?(b=a,new Promise(a=>{let c;try{c=s(b).replace(/:/g,"")}catch{return a(!1)}f(`certutil -store Root ${c}`,{windowsHide:!0},b=>{if(!b)return a(!0);f(`certutil -user -store Root ${c}`,{windowsHide:!0},b=>{a(!b)})})})):o?(c=a,new Promise(a=>{try{let b=s(c).replace(/:/g,"");f(`security verify-cert -c "${c}" -p ssl -k /Library/Keychains/System.keychain 2>/dev/null`,{windowsHide:!0},c=>{if(!c)return a(!0);f(`security dump-trust-settings -d 2>/dev/null | grep -i "${b}"`,{windowsHide:!0},(b,c)=>{a(!b&&!!c?.trim())})})}catch{a(!1)}})):(e=q(),g=`${e.dir}/ktrouter-root-ca.crt`,Promise.resolve(d.existsSync(g)))}async function u(a,b){let c=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${b}"`;try{await g(`security delete-certificate -c "KTRouter MITM Root CA" /Library/Keychains/System.keychain 2>/dev/null || true && ${c}`,a),l("\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: \xc3ƒ\xc2\xa2\xc3…\xe2€œ\xc3\xa2\xe2‚\xac\xc2\xa6 installed to system keychain")}catch(a){throw Error(a.message?.includes("canceled")?"User canceled authorization":"Certificate install failed")}}async function v(a){let b=k()?"":"-user ",c=`
    for ($i = 0; $i -lt 10; $i++) {
      & certutil ${b}-delstore Root ${j(r)} 2>$null | Out-Null
      if ($LASTEXITCODE -ne 0) { break }
    }
    $exit = & certutil ${b}-addstore Root ${j(a)} 2>&1
    if ($LASTEXITCODE -ne 0) { throw "certutil exit $LASTEXITCODE" }
  `;try{await i(c),l("\uD83D\uDD10 Cert: ✅ installed to Windows Root store")}catch(a){throw Error(`Failed to install certificate: ${a.message}`)}}async function w(a,b){let c=s(b).replace(/:/g,""),d=`security delete-certificate -Z "${c}" /Library/Keychains/System.keychain`;try{await g(d,a),l("\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: \xc3ƒ\xc2\xa2\xc3…\xe2€œ\xc3\xa2\xe2‚\xac\xc2\xa6 uninstalled from system keychain")}catch(a){throw Error("Failed to uninstall certificate")}}async function x(){let a=`certutil -delstore Root ${j(r)}`;try{await i(a),l("\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: \xc3ƒ\xc2\xa2\xc3…\xe2€œ\xc3\xa2\xe2‚\xac\xc2\xa6 uninstalled from Windows Root store")}catch(a){throw Error(`Failed to uninstall certificate: ${a.message}`)}}async function y(a,b="add"){let c="KTRouter MITM Root CA",d=`
    if ! command -v certutil &> /dev/null; then
      exit 0
    fi
    
    DIRS="$HOME/.pki/nssdb $HOME/snap/chromium/current/.pki/nssdb"
    
    if [ -d "$HOME/.mozilla/firefox" ]; then
      for profile in "$HOME"/.mozilla/firefox/*/; do
        if [ -f "\${profile}cert9.db" ] || [ -f "\${profile}cert8.db" ]; then
          DIRS="$DIRS $profile"
        fi
      done
    fi

    if [ -d "$HOME/snap/firefox/common/.mozilla/firefox" ]; then
      for profile in "$HOME"/snap/firefox/common/.mozilla/firefox/*/; do
        if [ -f "\${profile}cert9.db" ] || [ -f "\${profile}cert8.db" ]; then
          DIRS="$DIRS $profile"
        fi
      done
    fi

    for db in $DIRS; do
      if [ -d "$db" ]; then
        if [ "${b}" = "add" ]; then
          certutil -d sql:"$db" -A -t "C,," -n "${c}" -i "${a}" 2>/dev/null || \\
          certutil -d "$db" -A -t "C,," -n "${c}" -i "${a}" 2>/dev/null || true
        else
          certutil -d sql:"$db" -D -n "${c}" 2>/dev/null || \\
          certutil -d "$db" -D -n "${c}" 2>/dev/null || true
        fi
      fi
    done
  `;return new Promise(a=>{f(d,{shell:"/bin/bash"},()=>a())})}async function z(a,b){if(!h()){l(`\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: cannot install to system store without sudo \xc3ƒ\xc2\xa2\xc3\xa2\xe2€š\xc2\xac\xc3\xa2\xe2‚\xac\xc2\x9d trust this file on clients: ${b}`),await y(b,"add");return}let c=q(),d=`${c.dir}/ktrouter-root-ca.crt`,e=`cp "${b}" "${d}" && (${c.cmd} 2>/dev/null || true)`;try{await g(e,a),await y(b,"add"),l(`\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: \xc3ƒ\xc2\xa2\xc3…\xe2€œ\xc3\xa2\xe2‚\xac\xc2\xa6 installed to Linux trust store (${c.dir}) and user browser databases`)}catch(a){throw Error(`Certificate install failed: ${a.message}`)}}async function A(a){if(await y(null,"delete"),!h())return;let b=q(),c=`${b.dir}/ktrouter-root-ca.crt`,d=`rm -f "${c}" && (${b.cmd} 2>/dev/null || true)`;try{await g(d,a),l("\xc3ƒ\xc2\xb0\xc3…\xc2\xb8\xc3\xa2\xe2‚\xac\xc2\x9d\xc3‚\xc2\x90 Cert: \xc3ƒ\xc2\xa2\xc3…\xe2€œ\xc3\xa2\xe2‚\xac\xc2\xa6 uninstalled from Linux trust store and user browser databases")}catch(a){throw Error("Failed to uninstall certificate")}}a.exports={installCert:async function a(a,b){if(!d.existsSync(b))throw Error(`Certificate file not found: ${b}`);await t(b)?l("\uD83D\uDD10 Cert: already trusted ✅"):n?await v(b):o?await u(a,b):await z(a,b)},uninstallCert:async function a(a,b){await t(b)?n?await x():o?await w(a,b):await A(a):l("\uD83D\uDD10 Cert: not found in system store")},checkCertInstalled:t}},17511:a=>{a.exports={TARGET_HOSTS:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","api.individual.githubcopilot.com","q.us-east-1.amazonaws.com","codewhisperer.us-east-1.amazonaws.com","api2.cursor.sh"],URL_PATTERNS:{antigravity:[":generateContent",":streamGenerateContent"],copilot:["/chat/completions","/v1/messages","/responses"],kiro:["/generateAssistantResponse"],cursor:["/BidiAppend","/RunSSE","/RunPoll","/Run"]},MODEL_SYNONYMS:{antigravity:{"gemini-default":"gemini-3.5-flash-high","gemini-3-flash-agent":"gemini-3.5-flash-high","gemini-3-flash":"gemini-3.5-flash-medium","gemini-3.0-flash":"gemini-3.5-flash-medium","gemini-3-pro":"gemini-3.1-pro-high","gemini-3.1-pro":"gemini-3.1-pro-high","gemini-3.5-flash":"gemini-3.5-flash-high","gemini-3.5-flash-low":"gemini-3.5-flash-low","gemini-pro-agent":"gemini-3.1-pro-high","claude-sonnet-4-6":"claude-sonnet-4-6-thinking","claude-opus-4-6":"claude-opus-4-6-thinking","gpt-oss-120b":"gpt-oss-120b-medium"}},MODEL_PATTERNS:{antigravity:[{match:/flash.*high|high.*flash/i,alias:"gemini-3.5-flash-high"},{match:/flash.*medium|medium.*flash/i,alias:"gemini-3.5-flash-medium"},{match:/flash.*low|low.*flash/i,alias:"gemini-3.5-flash-low"},{match:/flash/i,alias:"gemini-3.5-flash-medium"},{match:/pro.*low|low.*pro/i,alias:"gemini-3.1-pro-low"},{match:/gemini.*pro|pro.*gemini/i,alias:"gemini-3.1-pro-high"},{match:/opus/i,alias:"claude-opus-4-6-thinking"},{match:/sonnet|claude/i,alias:"claude-sonnet-4-6-thinking"},{match:/gpt.*oss|oss/i,alias:"gpt-oss-120b-medium"}]},LOG_BLACKLIST_URL_PARTS:["recordCodeAssistMetrics","recordTrajectoryAnalytics","fetchAdminControls","listExperiments"],getToolForHost:function(a){let b=(a||"").split(":")[0];return"api.individual.githubcopilot.com"===b?"copilot":"daily-cloudcode-pa.googleapis.com"===b||"cloudcode-pa.googleapis.com"===b?"antigravity":"q.us-east-1.amazonaws.com"===b||"codewhisperer.us-east-1.amazonaws.com"===b?"kiro":"api2.cursor.sh"===b?"cursor":null}}},26033:(a,b,c)=>{c(33873),c(29021);let{MITM_DIR:d}=c(82193),{generateRootCA:e,loadRootCA:f,generateLeafCert:g}=c(8578);a.exports={generateCert:async function a(){return await e()},getCertForDomain:function(a){try{let b=f(),c=g(a,b);return{key:c.key,cert:c.cert}}catch(b){return console.error(`Failed to generate cert for ${a}:`,b.message),null}}}},64809:(a,b,c)=>{let{exec:d,execSync:e}=c(79646),f="win32"===process.platform;function g(){if(f)try{return e("net session >nul 2>&1",{windowsHide:!0,stdio:"ignore"}),!0}catch{return!1}return"function"==typeof process.getuid&&0===process.getuid()}function h(a){return`'${String(a).replace(/'/g,"''")}'`}a.exports={isAdmin:g,runElevatedPowerShell:function(a){if(!f)return Promise.reject(Error("Windows-only"));let b=Buffer.from(a,"utf16le").toString("base64");if(g())return new Promise((a,c)=>{d(`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${b}`,{windowsHide:!0},(b,d,e)=>{b?c(Error(e||b.message)):a(d)})});let c=`
    $proc = Start-Process powershell -ArgumentList @(
      '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass',
      '-WindowStyle','Hidden','-EncodedCommand','${b}'
    ) -Verb RunAs -Wait -PassThru -WindowStyle Hidden;
    if ($proc.ExitCode -ne 0) { throw "Elevated command exited with code $($proc.ExitCode)" }
  `;return new Promise((a,b)=>{d(`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command ${h(c)}`,{windowsHide:!0},(c,d,e)=>{if(c){let a=e||c.message;a.includes("canceled by the user")||a.includes("operation was canceled")?b(Error("User canceled UAC prompt")):b(Error(a))}else a(d)})})},quotePs:h}},66936:(a,b,c)=>{let{exec:d,spawn:e,execSync:f}=c(79646),g=c(29021),h=c(33873);c(21820);let{log:i,err:j}=c(87777),{TOOL_HOSTS:k}=c(85341),{runElevatedPowerShell:l,isAdmin:m}=c(64809);function n(a,b,c){let d=`${a}.ktrouter.new`,e=`${a}.ktrouter.bak`;try{g.writeFileSync(d,c,"utf8");try{g.unlinkSync(e)}catch{}g.renameSync(a,e);try{g.renameSync(d,a)}catch(c){try{g.renameSync(e,a)}catch{g.writeFileSync(a,b,"utf8")}throw c}try{g.unlinkSync(e)}catch{}}finally{try{g.unlinkSync(d)}catch{}}}let o="win32"===process.platform,p="darwin"===process.platform,q=o?h.join(process.env.SystemRoot||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts";function r(){if(o)return!1;try{return f("command -v sudo",{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function s(){if(o||!r())return!0;try{return f("sudo -n true",{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function t(a,b){return new Promise((c,d)=>{let f=r(),g=f?e("sudo",["-S","sh","-c",a],{stdio:["pipe","pipe","pipe"],windowsHide:!0}):e("sh",["-c",a],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),h="",i="";g.stdout.on("data",a=>{h+=a}),g.stderr.on("data",a=>{i+=a}),g.on("close",a=>{0===a?c(h):d(Error(i||`Exit code ${a}`))}),f&&(g.stdin.write(`${b}
`),g.stdin.end())})}function u(a){let b=[];for(let c of String(a||"").split(/\r?\n/)){let a=c.replace(/#.*/,"").trim();if(!a)continue;let d=a.split(/\s+/),e=d.shift();if(e&&0!==d.length)for(let a of d)b.push({address:e.toLowerCase(),host:a.toLowerCase()})}return b}function v(a,b){let c=String(b||"").toLowerCase();return a.some(a=>{var b;return a.host===c&&("127.0.0.1"===(b=a.address)||"::1"===b)})}async function w(a){o||(p?await t("dscacheutil -flushcache && killall -HUP mDNSResponder",a):await t("resolvectl flush-caches 2>/dev/null || true",a))}function x(a=null){try{let b=g.readFileSync(q,"utf8"),c=u(b);if(a)return v(c,a);return k.antigravity.every(a=>v(c,a))}catch{return!1}}async function y(a,b){let c=k[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>!x(a));if(0===d.length)return void i(`🌐 DNS ${a}: already active`);try{if(o){let a=g.readFileSync(q,"utf8"),b=a.replace(/[\r\n\s]+$/g,""),c=d.map(a=>`127.0.0.1 ${a}`).join("\r\n"),e=`${b}\r
${c}\r
`;n(q,a,e),await l("ipconfig /flushdns | Out-Null")}else{let a=g.readFileSync(q,"utf8").replace(/[\r\n\s]+$/g,""),c=d.map(a=>`127.0.0.1 ${a}`).join("\n"),e=`${a}
${c}
`.replace(/'/g,"'\\''");await t(`printf '%s' '${e}' | tee ${q} > /dev/null`,b),await w(b)}i(`🌐 DNS ${a}: ✅ added ${d.join(", ")}`)}catch(a){throw Error(a.message?.includes("incorrect password")?"Wrong sudo password":`Failed to add DNS entry: ${a.message}`)}}async function z(a,b){let c=k[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>x(a));if(0===d.length)return void i(`🌐 DNS ${a}: already inactive`);try{if(o){let a=g.readFileSync(q,"utf8"),b=a.split(/\r?\n/).filter(a=>!d.some(b=>a.includes(b))).join("\r\n").replace(/[\r\n\s]+$/g,"")+"\r\n";n(q,a,b),await l("ipconfig /flushdns | Out-Null")}else{let a=(g.readFileSync(q,"utf8").split(/\r?\n/).filter(a=>!d.some(b=>a.includes(b))).join("\n").replace(/[\r\n\s]+$/g,"")+"\n").replace(/'/g,"'\\''");await t(`printf '%s' '${a}' | tee ${q} > /dev/null`,b),await w(b)}i(`🌐 DNS ${a}: ✅ removed ${d.join(", ")}`)}catch(a){throw Error(a.message?.includes("incorrect password")?"Wrong sudo password":`Failed to remove DNS entry: ${a.message}`)}}async function A(a){for(let b of Object.keys(k))try{await z(b,a)}catch(a){j(`DNS ${b}: failed to remove — ${a.message}`)}}a.exports={TOOL_HOSTS:k,addDNSEntry:y,removeDNSEntry:z,removeAllDNSEntries:A,removeAllDNSEntriesSync:function(){try{if(!g.existsSync(q))return;let a=Object.values(k).flat(),b=g.readFileSync(q,"utf8"),c=o?"\r\n":"\n",d=b.split(/\r?\n/).filter(b=>!a.some(a=>b.includes(a))).join(c).replace(/[\r\n\s]+$/g,"")+c;if(d===b)return;if(g.writeFileSync(q,d,"utf8"),o)try{f("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}else if(p)try{f("dscacheutil -flushcache && killall -HUP mDNSResponder",{stdio:"ignore"})}catch{}else try{f("resolvectl flush-caches 2>/dev/null || true",{stdio:"ignore"})}catch{}}catch{}},execWithPassword:t,isSudoAvailable:r,canRunSudoWithoutPassword:s,isSudoPasswordRequired:function(){return!o&&r()&&!s()},checkDNSEntry:x,checkAllDNSStatus:function(){try{let a=g.readFileSync(q,"utf8"),b=u(a),c={};for(let[a,d]of Object.entries(k))c[a]=d.every(a=>v(b,a));return c}catch{return Object.fromEntries(Object.keys(k).map(a=>[a,!1]))}}}},76476:(a,b,c)=>{c.d(b,{N:()=>n,v:()=>m});var d=c(29021),e=c.n(d),f=c(33873),g=c.n(f),h=c(21820),i=c.n(h);let j=process.env.DATA_DIR||("win32"===process.platform?g().join(process.env.APPDATA||g().join(i().homedir(),"AppData","Roaming"),"ktrouter"):g().join(i().homedir(),".ktrouter")),k=g().join(j,"mitm","aliases.json");function l(a){let b=g().dirname(k);e().mkdirSync(b,{recursive:!0});let c=`${k}.tmp`;e().writeFileSync(c,JSON.stringify(a,null,2),"utf8"),e().renameSync(c,k)}async function m(){try{let{getMitmAlias:a}=await Promise.resolve().then(c.bind(c,9460)),b=await a();l(b||{})}catch(a){console.log("[mitmAliasCache] sync failed:",a.message)}}function n(a,b){try{let c={};if(e().existsSync(k))try{c=JSON.parse(e().readFileSync(k,"utf8"))}catch{}c[a]=b||{},l(c)}catch(a){console.log("[mitmAliasCache] write failed:",a.message)}}},82193:(a,b,c)=>{let d=c(29021),e=c(33873),f=c(21820),g="ktrouter";function h(){return"win32"===process.platform?e.join(process.env.APPDATA||e.join(f.homedir(),"AppData","Roaming"),g):e.join(f.homedir(),`.${g}`)}let i=function(){let a=process.env.DATA_DIR;if(!a)return h();try{return d.mkdirSync(a,{recursive:!0}),a}catch(b){if(b?.code==="EACCES"||b?.code==="EPERM")return console.warn(`[DATA_DIR] '${a}' not writable → fallback ~/.${g}`),h();throw b}}(),j=e.join(i,"mitm");a.exports={DATA_DIR:i,MITM_DIR:j}},85341:a=>{a.exports={TOOL_HOSTS:{antigravity:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com"],copilot:["api.individual.githubcopilot.com"],kiro:["q.us-east-1.amazonaws.com","codewhisperer.us-east-1.amazonaws.com"],cursor:["api2.cursor.sh"]}}},87777:(a,b,c)=>{let d=c(29021),e=c(33873),f=c(74075),{DATA_DIR:g}=c(82193),{LOG_BLACKLIST_URL_PARTS:h}=c(17511);function i(){return new Date().toLocaleTimeString("en-US",{hour12:!1})}let j=e.join(g,"logs","mitm"),k=["1","true","yes","on"].includes(String(process.env.MITM_FILE_LOG||"").toLowerCase()),l=/^\s*(\{\s*\}|\[\s*\]|null)?\s*$/,m=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","api-key","apikey","access-token","refresh-token","access_token","refresh_token","id_token","token"]);function n(){d.existsSync(j)||d.mkdirSync(j,{recursive:!0})}function o(a){let b=String(a||"").toLowerCase();return m.has(b)||b.includes("token")}function p(a){return Array.isArray(a)?a.map(()=>"[redacted]"):"[redacted]"}function q(a={}){let b={};for(let[c,d]of Object.entries(a||{}))b[c]=o(c)?p(d):d;return b}function r(a,b=80){return String(a).replace(/[^a-zA-Z0-9]/g,"_").substring(0,b)}function s(a){return!!a&&h.some(b=>a.includes(b))}a.exports={log:a=>console.log(`[${i()}] [MITM] ${a}`),err:a=>console.error(`[${i()}] ❌ [MITM] ${a}`),dumpRequest:function(a,b,c="raw"){if(!k||s(a.url))return null;try{n();let f=new Date().toISOString().replace(/[:.]/g,"-"),g=r((a.headers.host||"")+a.url),h=e.join(j,`${f}_${c}_${g}.req.json`),i=null;try{i=JSON.parse(b.toString())}catch{}return d.writeFileSync(h,JSON.stringify({method:a.method,url:a.url,host:a.headers.host,headers:q(a.headers),body:null!==i?function a(b){if(Array.isArray(b))return b.map(a);if(!b||"object"!=typeof b)return b;let c={};for(let[d,e]of Object.entries(b))c[d]=o(d)?p(e):a(e);return c}(i):b.toString("utf8")},null,2)),h}catch{return null}},createResponseDumper:function(a,b="raw"){if(!k||s(a.url))return null;n();let c=new Date().toISOString().replace(/[:.]/g,"-"),g=r((a.headers.host||"")+a.url),h=e.join(j,`${c}_${b}_${g}.res.txt`),i=0,m={},o=[];return{writeHeader:(a,b)=>{i=a,m=b||{}},writeChunk:a=>{null!=a&&o.push(Buffer.isBuffer(a)?a:Buffer.from(a))},end:()=>{try{let a=Buffer.concat(o),b=m["content-encoding"]||m["Content-Encoding"],c=(function(a,b){if(!a||0===a.length)return a;try{let c=(b||"").toLowerCase();if(c.includes("gzip"))return f.gunzipSync(a);if(c.includes("br"))return f.brotliDecompressSync(a);if(c.includes("deflate"))return f.inflateSync(a)}catch{}return a})(a,b).toString("utf8");if(l.test(c))return;let e={...m};delete e["content-encoding"],delete e["Content-Encoding"];let g=`STATUS: ${i}
HEADERS: ${JSON.stringify(q(e),null,2)}
---BODY---
${c}`;d.writeFileSync(h,g)}catch{}},file:h}},isFileLoggingEnabled:function(){return k}}},89718:(a,b,c)=>{c.d(b,{CG:()=>d.CG,Dj:()=>d.Dj,Fh:()=>d.Fh,Iq:()=>d.Iq,K1:()=>d.K1,KJ:()=>d.KJ,L:()=>d.L,L9:()=>d.L9,Lh:()=>d.Lh,Mc:()=>d.Mc,OM:()=>d.OM,PX:()=>d.PX,Pc:()=>d.Pc,Q_:()=>d.Q_,Qu:()=>d.Qu,S8:()=>d.S8,Uv:()=>d.Uv,VT:()=>d.VT,XW:()=>d.XW,Xx:()=>d.Xx,Yd:()=>d.Yd,ZO:()=>d.ZO,bI:()=>d.bI,c:()=>d.c,ek:()=>d.ek,fK:()=>d.fK,fv:()=>d.fv,getProviderConnections:()=>d.P,ho:()=>d.ho,hr:()=>d.hr,i0:()=>d.i0,iE:()=>d.iE,jd:()=>d.jd,mt:()=>d.mt,o5:()=>d.o5,oG:()=>d.oG,op:()=>d.op,r4:()=>d.r4,uL:()=>d.uL,ui:()=>d.ui,updateProviderConnection:()=>d.rj,uv:()=>d.uv,yF:()=>d.yF,yg:()=>d.yg,zP:()=>d.zP});var d=c(9248)},96182:(a,b,c)=>{let{exec:d,spawn:e,execSync:f}=c(79646),g=c(33873),h=c(29021),i=c(21820),j=c(91645),k=c(55591),l=c(55511),{addDNSEntry:m,removeDNSEntry:n,removeAllDNSEntries:o,removeAllDNSEntriesSync:p,checkAllDNSStatus:q,TOOL_HOSTS:r,isSudoAvailable:s,isSudoPasswordRequired:t}=c(66936),{isAdmin:u}=c(64809),v="win32"===process.platform,w="darwin"===process.platform,x="linux"===process.platform,{generateCert:y}=c(26033),{installCert:z,uninstallCert:A}=c(9631),{isCertExpired:B}=c(8578),{DATA_DIR:C,MITM_DIR:D}=c(82193),{log:E,err:F}=c(87777),G="http://localhost:3008";function H(a){return null==a||""===a?"''":`'${String(a).replace(/'/g,"'\\''")}'`}async function I(){if(!af)return G;try{let a=await af(),b=a&&null!=a.mitmRouterBaseUrl?String(a.mitmRouterBaseUrl).trim():"";if(!b)return G;let c=new URL(b);if("http:"!==c.protocol&&"https:"!==c.protocol)return G;return b.replace(/\/+$/,"")}catch{return G}}let J=g.join(D,".mitm.pid"),K=[5e3,1e4,2e4,3e4,6e4],L="NODE_EXTRA_CA_CERTS",M=g.join(i.homedir(),".config","environment.d"),N=g.join(M,"ktrouter-mitm.conf"),O="KTRouter MITM NODE_EXTRA_CA_CERTS",P=0,Q=0,R=!1;function S(a){try{return f(`command -v ${a}`,{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function T(){if(!x)return[];let a=[g.join(i.homedir(),".local","share","applications"),"/usr/local/share/applications","/usr/share/applications","/var/lib/flatpak/exports/share/applications",g.join(i.homedir(),".local","share","flatpak","exports","share","applications")],b=[];for(let c of a)try{if(!h.existsSync(c))continue;for(let a of h.readdirSync(c)){if(!a.toLowerCase().endsWith(".desktop"))continue;let d=g.join(c,a),e="";try{e=h.readFileSync(d,"utf8")}catch{continue}(/antigravity/i.test(a)||/antigravity/i.test(e))&&b.push(d)}}catch{}return[...new Set(b)]}function U(a){!function(a){if(!v||!a||!h.existsSync(a))return;let b=g.resolve(a);process.env[L]=b;try{let a=f(`reg query HKCU\\Environment /v ${L}`,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]});if(a&&a.includes(b))return}catch{}try{f(`setx ${L} "${b}"`,{windowsHide:!0,stdio:"ignore"}),E(`Cert: set ${L} for Windows user env`)}catch(a){E(`Cert: could not set ${L}: ${a.message}`)}}(a),x&&a&&h.existsSync(a)&&(!function(a){if(!x||!a)return;let b=g.resolve(a);process.env[L]=b;try{h.mkdirSync(M,{recursive:!0}),h.writeFileSync(N,`# ${O}
${L}=${b}
`,"utf8")}catch(a){E(`Cert: could not write Linux environment.d: ${a.message}`)}try{S("systemctl")&&f(`systemctl --user set-environment ${L}=${H(b)}`,{stdio:"ignore",windowsHide:!0})}catch{}try{S("dbus-update-activation-environment")&&f(`dbus-update-activation-environment --systemd ${L}`,{stdio:"ignore",windowsHide:!0,env:{...process.env,[L]:b}})}catch{}}(a),function(a){if(!x||!a||!h.existsSync(a))return;let b=g.join(i.homedir(),".local","share","applications");try{h.mkdirSync(b,{recursive:!0})}catch{}let c=0;for(let d of T())try{let e=d.startsWith(b+g.sep)?d:g.join(b,g.basename(d));d===e||h.existsSync(e)||h.copyFileSync(d,e);let f=h.readFileSync(e,"utf8"),i=f.split(/\r?\n/).map(b=>b.startsWith("Exec=")?function(a,b){let c=a.slice(5).trim();if(!c||c.includes(O))return a;let d=`${L}="${String(b).replace(/(["\\])/g,"\\$1")}"`,e=c.replace(RegExp(`(^|\\s)${L}=(?:"[^"]*"|'[^']*'|\\S+)`,"g"),"$1").replace(/\s+/g," ").trim();return/^(?:\/usr\/bin\/)?env(?:\s|$)/.test(e)?`Exec=${e.replace(/^(?:\/usr\/bin\/)?env/,a=>`${a} ${d}`)}`:`Exec=env ${d} ${e}`}(b,g.resolve(a)):b).join("\n");if(i!==f){let a=`${e}.ktrouter-bak`;h.existsSync(a)||h.writeFileSync(a,f,"utf8"),h.writeFileSync(e,i,"utf8"),c++}}catch(a){E(`Cert: could not patch Antigravity desktop entry: ${a.message}`)}c>0&&E(`Cert: patched ${c} Antigravity desktop launcher(s) for ${L}`)}(a),E(`Cert: set ${L} for Linux user env`))}function V(){if(process.env.MITM_SERVER_PATH)return process.env.MITM_SERVER_PATH;let a=g.join(__dirname,"server.js");if(h.existsSync(a))return a;let b=g.join(process.cwd(),"src","mitm","server.js");if(h.existsSync(b))return b;let c=g.join(process.cwd(),"..","src","mitm","server.js");return h.existsSync(c)?c:b}function W(a){try{if(!a||!h.existsSync(a)||!a.includes(`${g.sep}node_modules${g.sep}`))return a;let b=g.join(C,"runtime","mitm"),c=g.join(b,"server.js");if(h.existsSync(c))try{if(h.statSync(a).size===h.statSync(c).size)return c}catch{}return h.mkdirSync(b,{recursive:!0}),h.copyFileSync(a,c),c}catch(b){try{E(`[MITM] runtime copy failed: ${b.message}`)}catch{}return a}}let X=W(V()),Y="aes-256-gcm",Z="ktrouter-mitm-pwd",$=null,_=null;function aa(){return globalThis.__mitmSudoPassword||null}function ab(a){globalThis.__mitmSudoPassword=a}function ac(a){try{return process.kill(a,0),!0}catch(a){return"EACCES"===a.code}}function ad(a,b=!1,e=null){if(v)d(`taskkill ${b?"/F ":""}/PID ${a}`,{windowsHide:!0},()=>{});else{let f=b?"SIGKILL":"SIGTERM",g=`pkill -${f} -P ${a} 2>/dev/null; kill -${f} ${a} 2>/dev/null`;if(e||s()){let{execWithPassword:a}=c(66936);a(g,e||"").catch(()=>d(g,{windowsHide:!0},()=>{}))}else d(g,{windowsHide:!0},()=>{})}}function ae(){try{let{machineIdSync:a}=c(19713),b=a();return l.createHash("sha256").update(b+Z).digest()}catch{return l.createHash("sha256").update(Z).digest()}}let af=null,ag=null;async function ah(a,b){if(ag)try{let c,d,e,f,g,h={mitmEnabled:a};b&&(c=ae(),d=l.randomBytes(12),e=l.createCipheriv(Y,c,d),f=Buffer.concat([e.update(b,"utf8"),e.final()]),g=e.getAuthTag(),h.mitmSudoEncrypted=`${d.toString("hex")}:${g.toString("hex")}:${f.toString("hex")}`),await ag(h)}catch(a){F(`Failed to save settings: ${a.message}`)}}async function ai(){if(ag)try{await ag({mitmSudoEncrypted:null})}catch(a){F(`Failed to clear encrypted password: ${a.message}`)}}async function aj(){if(!af)return null;try{let a=await af();if(!a.mitmSudoEncrypted)return null;return function(a){try{let[b,c,d]=a.split(":");if(!b||!c||!d)return null;let e=ae(),f=l.createDecipheriv(Y,e,Buffer.from(b,"hex"));return f.setAuthTag(Buffer.from(c,"hex")),f.update(Buffer.from(d,"hex"))+f.final("utf8")}catch{return null}}(a.mitmSudoEncrypted)}catch{return null}}async function ak(a,b){if(ag&&af)try{let c={...(await af()).dnsToolEnabled||{},[a]:b};await ag({dnsToolEnabled:c})}catch(a){F(`Failed to save DNS state: ${a.message}`)}}async function al(){if(!af)return{};try{return(await af()).dnsToolEnabled||{}}catch{return{}}}async function am(a){if(af&&ag&&a)try{let b={...(await af()).dnsToolEnabled||{}},c=!1;for(let d of Object.keys(r)){let e=!0===a[d];b[d]!==e&&(b[d]=e,c=!0)}c&&await ag({dnsToolEnabled:b})}catch(a){F(`Failed to sync DNS state: ${a.message}`)}}async function an(a){let b=await al(),c=a||aa()||await aj();for(let[a,d]of Object.entries(b))if(d&&r[a])try{await m(a,c)}catch(b){F(`DNS ${a}: restore failed — ${b.message}`)}}async function ao(){return v?u():!(!u()&&t())||!!(aa()||await aj())}function ap(a){return new Promise(a=>{v?d('powershell -NonInteractive -WindowStyle Hidden -Command "$c = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if ($c) { $c.OwningProcess } else { 0 }"',{windowsHide:!0},(b,c)=>{if(b)return a(null);let e=parseInt(c.trim(),10);if(!e||e<=4)return a(null);d(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{windowsHide:!0},(b,c)=>{let d=c?.match(/"([^"]+)"/);a({pid:e,name:d?d[1]:"unknown"})})}):d("lsof -nP -iTCP:443 -sTCP:LISTEN -t",{windowsHide:!0},(b,c)=>{if(b||!c?.trim())return a(null);let e=parseInt(c.trim().split("\n")[0],10);if(!e||isNaN(e))return a(null);d(`ps -p ${e} -o comm=`,{windowsHide:!0},(b,c)=>{a({pid:e,name:c?.trim()||"unknown"})})})})}async function aq(a){if($&&!$.killed){try{$.kill("SIGKILL")}catch{}$=null,_=null}try{if(h.existsSync(J)){let b=parseInt(h.readFileSync(J,"utf-8").trim(),10);b&&ac(b)&&(ad(b,!0,a),await new Promise(a=>setTimeout(a,500))),h.unlinkSync(J)}}catch{}if(!v&&X)try{let b=X.replace(/'/g,"'\\''");if(a||s()){let{execWithPassword:d}=c(66936);await d(`pkill -SIGKILL -f "${b}" 2>/dev/null || true`,a||"").catch(()=>{})}else d(`pkill -SIGKILL -f "${b}" 2>/dev/null || true`,{windowsHide:!0},()=>{});await new Promise(a=>setTimeout(a,500))}catch{}}async function ar(){let a=null!==$&&!$.killed,b=_;if(!a)try{if(h.existsSync(J)){let c=parseInt(h.readFileSync(J,"utf-8").trim(),10);c&&ac(c)?(a=!0,b=c):h.unlinkSync(J)}}catch{}let d=q();await am(d);let e=g.join(D,"rootCA.crt"),f=h.existsSync(e),{checkCertInstalled:i}=c(9631),j=!!f&&await i(e);return{running:a,pid:b,certExists:f,certTrusted:j,dnsStatus:d}}async function as(a){if(R)return;if(Date.now()-Q>=6e4&&(P=0),P>=5)return void F("Max restart attempts reached. Giving up.");let b=K[Math.min(P,K.length-1)];P++,R=!0,E(`Restarting in ${b/1e3}s... (${P}/5)`),await new Promise(a=>setTimeout(a,b));try{let b=af?await af():null;if(b&&!b.mitmEnabled){E("MITM disabled, skipping restart"),R=!1;return}let c=aa()||await aj();if(!c&&!v){F("No cached password, cannot auto-restart"),R=!1;return}await au(a,c),E("\uD83D\uDD04 Restarted successfully"),P=0,R=!1}catch(b){if(String(b.message||"").includes("MITM server is already running")){E("MITM already running, restart not needed"),P=0,R=!1;return}F(`Restart attempt ${P}/5 failed: ${b.message}`),R=!1,as(a)}}async function at(a,b){if(a&&a.pid){if(v)try{f(`powershell -NonInteractive -WindowStyle Hidden -Command "Stop-Process -Id ${a.pid} -Force -ErrorAction SilentlyContinue"`,{windowsHide:!0})}catch{}else try{let{execWithPassword:d}=c(66936);b||s()?await d(`kill -9 ${a.pid}`,b||""):f(`kill -9 ${a.pid}`,{windowsHide:!0})}catch{}await new Promise(a=>setTimeout(a,800))}}async function au(a,b,d=!1){if(!$||$.killed)try{if(h.existsSync(J)){let a=parseInt(h.readFileSync(J,"utf-8").trim(),10);if(a&&ac(a))return _=a,E(`♻️ Reusing existing process (PID: ${a})`),U(g.join(D,"rootCA.crt")),await ah(!0,b),b&&ab(b),{running:!0,pid:a};h.unlinkSync(J)}}catch{}if($&&!$.killed)throw Error("MITM server is already running");if(await aq(b),!v){let a=await new Promise(a=>{let b=j.createServer();b.once("error",b=>{"EADDRINUSE"===b.code?a("in-use"):a("no-permission")}),b.once("listening",()=>{b.close(()=>a("free"))}),b.listen(443,"127.0.0.1")});if("in-use"===a||"no-permission"===a){let a=await ap(b);if(a){let c=a.name.includes("/")?a.name.split("/").filter(Boolean).pop():a.name;if(d)E(`Killing process on port 443 (PID ${a.pid}, name=${c})...`),await at(a,b);else{let b=Error(`Port 443 is already in use by "${c}" (PID ${a.pid}).`);throw b.code="PORT_443_BUSY",b.portOwner={pid:a.pid,name:c},b}}}}let l=g.join(D,"rootCA.crt"),m=g.join(D,"rootCA.key"),n=h.existsSync(l)&&h.existsSync(m);if(!n||B(l)){if(n){E("\uD83D\uDD10 Cert expired — uninstalling old cert...");let a=b||aa()||await aj();try{await A(a,l)}catch{}}E("\uD83D\uDD10 Generating Root CA..."),await y()}let{checkCertInstalled:o}=c(9631),p=await o(l),r=!v&&!w&&!s();if(p)E("\uD83D\uDD10 Cert: already trusted ✅");else{E("\uD83D\uDD10 Cert: not trusted → installing...");let a=b||aa()||await aj();if(r)E(`🔐 Cert: skipping system trust (no sudo). Install ${l} as a trusted CA on machines that use this proxy.`);else{if(!a&&t())throw Error("Sudo password required to install Root CA certificate");try{await z(a,l),E("\uD83D\uDD10 Cert: ✅ trusted")}catch(a){throw Error(`Failed to trust certificate: ${a.message}`)}}}U(l);let u=X;if((!u||!h.existsSync(u))&&(E(`[MITM] server.js missing at ${u} → recopying`),!(u=W(V()))||!h.existsSync(u)))throw Error(`MITM server.js not found at ${u}. Reinstall ktrouter.`);let x=await I();if(E(`🚀 Starting server... (router: ${x})`),v){let c=await ap(b);if(c)if(d)E(`Killing process on port 443 (PID ${c.pid}, name=${c.name})...`),await at(c,b);else{let a=Error(`Port 443 is already in use by "${c.name}" (PID ${c.pid}).`);throw a.code="PORT_443_BUSY",a.portOwner={pid:c.pid,name:c.name},a}$=e(process.execPath,[u],{detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,DATA_DIR:g.resolve(process.env.DATA_DIR||C),ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:x}}),ag&&await ag({mitmCertInstalled:!0}).catch(()=>{})}else s()?(($=e("sudo",["-S","-E","sh","-c",[`HOME=${H(i.homedir())}`,`ROUTER_API_KEY=${H(a)}`,`MITM_ROUTER_BASE=${H(x)}`,"NODE_ENV=production",H(process.execPath),H(u)].join(" ")],{detached:!1,windowsHide:!0,stdio:["pipe","pipe","pipe"]})).stdin.write(`${b}
`),$.stdin.end()):$=e(process.execPath,[u],{detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,DATA_DIR:g.resolve(process.env.DATA_DIR||C),ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:x}});$&&(_=$.pid,h.writeFileSync(J,String(_)),Q=Date.now());let G=null;$&&($.stdout.on("data",a=>{process.stdout.write(a)}),$.stderr.on("data",a=>{let b=a.toString().trim();b&&(v||!b.includes("Password:")&&!b.includes("password for"))&&(F(b),G=b),!v&&(b.includes("incorrect password")||b.includes("no password was provided"))&&(ab(null),ai(),R=!0)}),$.on("exit",b=>{E(`Server exited (code: ${b})`),$=null,_=null;try{h.unlinkSync(J)}catch{}0===b||R||as(a)}));let K=await function(a=443){return new Promise(b=>{let c=Date.now()+8e3,d=()=>{let e=k.request({hostname:"127.0.0.1",port:a,path:"/_mitm_health",method:"GET",rejectUnauthorized:!1},a=>{let c="";a.on("data",a=>{c+=a}),a.on("end",()=>{try{let a=JSON.parse(c);b(!0===a.ok?{ok:!0,pid:a.pid||null}:null)}catch{b(null)}})});e.on("error",()=>{Date.now()<c?setTimeout(d,500):b(null)}),e.end()};d()})}(443);if(!K){if($&&!$.killed){try{$.kill()}catch{}$=null}let a=function(){try{if(v){let a=f('powershell -NonInteractive -WindowStyle Hidden -Command "$c = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if ($c) { $c.OwningProcess } else { 0 }"',{encoding:"utf8",windowsHide:!0}).trim(),b=parseInt(a,10);if(b&&b>4){let a=f(`tasklist /FI "PID eq ${b}" /FO CSV /NH`,{encoding:"utf8",windowsHide:!0}).match(/"([^"]+)"/);if(a)return a[1].replace(".exe","")}}else{let a=f("lsof -i :443",{encoding:"utf8",windowsHide:!0}).trim().split("\n");if(a.length>1)return a[1].split(/\s+/)[0]}}catch{}return null}(),b=a?` Port 443 already in use by ${a}.`:"",c=G||`Check sudo password or port 443 access.${b}`;throw Error(`MITM server failed to start. ${c}`)}for(let[a,b]of(ag&&await ag({mitmCertInstalled:!0}).catch(()=>{}),E(`✅ Server healthy (PID: ${_||K.pid})`),Object.entries(q())))E(`🌐 DNS ${a}: ${b?"✅ active":"❌ inactive"}`);return await ah(!0,b),b&&ab(b),{running:!0,pid:_}}async function av(a){var b;R=!0,P=0,E("⏹ Stopping server...");let d=$,e=d&&!d.killed?d.pid:(()=>{try{return parseInt(h.readFileSync(J,"utf-8").trim(),10)}catch{return null}})();if(e&&ac(e)&&(E(`Killing server (PID: ${e})...`),ad(e,!1,a),await new Promise(a=>setTimeout(a,1e3)),ac(e)&&ad(e,!0,a)),$=null,_=null,v){let a=g.join(process.env.SystemRoot||"C:\\Windows","System32","drivers","etc","hosts"),b=Object.values(r).flat();try{let{isAdmin:d,runElevatedPowerShell:e,quotePs:f}=c(64809);if(d()){let d=h.readFileSync(a,"utf8"),e=d.split(/\r?\n/).filter(a=>!b.some(b=>a.includes(b))).join("\r\n").replace(/[\r\n\s]+$/g,"")+"\r\n";e!==d&&h.writeFileSync(a,e,"utf8");try{c(79646).execSync("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}E("\uD83C\uDF10 DNS: ✅ all tool hosts removed")}else{let c=b.map(f).join(","),d=`
          $hosts = @(${c})
          $lines = Get-Content -LiteralPath ${f(a)}
          $filtered = $lines | Where-Object {
            $line = $_
            -not ($hosts | Where-Object { $line -match [regex]::Escape($_) })
          }
          Set-Content -LiteralPath ${f(a)} -Value $filtered
          ipconfig /flushdns | Out-Null
        `;await e(d)}}catch(a){F(`Failed to clean hosts: ${a.message}`)}}else await o(a);try{h.unlinkSync(J)}catch{}return!function(a){if(!v||!a)return;let b=g.resolve(a).toLowerCase();String(process.env[L]||"").toLowerCase()===b&&delete process.env[L];try{if(!f(`reg query HKCU\\Environment /v ${L}`,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).toLowerCase().includes(b))return}catch{return}try{f(`reg delete HKCU\\Environment /v ${L} /f`,{windowsHide:!0,stdio:"ignore"}),E(`Cert: removed ${L} from Windows user env`)}catch(a){E(`Cert: could not remove ${L}: ${a.message}`)}}(b=g.join(D,"rootCA.crt")),!function(a){if(!x)return;let b=a?g.resolve(a):"";b&&process.env[L]!==b||delete process.env[L];try{if(h.existsSync(N)){let a=h.readFileSync(N,"utf8");(!b||a.includes(b)||a.includes(O))&&h.unlinkSync(N)}}catch(a){E(`Cert: could not remove Linux environment.d: ${a.message}`)}try{S("systemctl")&&f(`systemctl --user unset-environment ${L}`,{stdio:"ignore",windowsHide:!0})}catch{}}(b),function(a){if(!x)return;let b=a?g.resolve(a):"";for(let a of T())try{let c=`${a}.ktrouter-bak`;if(!h.existsSync(c))continue;let d=h.readFileSync(a,"utf8");if(!d.includes(L)||b&&!d.includes(b))continue;h.copyFileSync(c,a),h.unlinkSync(c),E(`Cert: restored Antigravity desktop launcher ${g.basename(a)}`)}catch(a){E(`Cert: could not restore Antigravity desktop entry: ${a.message}`)}}(b),await ah(!1,null),R=!1,{running:!1,pid:null}}async function aw(a,b){if(!(await ar()).running)throw Error("MITM server is not running. Start the server first.");let c=b||aa()||await aj();return await m(a,c),await ak(a,!0),{success:!0}}a.exports={getMitmStatus:ar,startServer:au,stopServer:av,enableToolDNS:aw,disableToolDNS:async function a(a,b){let c=b||aa()||await aj();return await n(a,c),await ak(a,!1),{success:!0}},trustCert:async function a(a){let b=g.join(D,"rootCA.crt");if(!h.existsSync(b))throw Error("Root CA not found. Start server first to generate it.");let{installCert:d}=c(9631);if(!v&&!w&&!s()){E(`🔐 Cert: system trust unavailable (no sudo). Use file: ${b}`),U(b);return}let e=a||aa()||await aj();if(!e&&t())throw Error("Sudo password required to trust certificate");await d(e,b),U(b),e&&ab(e)},startMitm:au,stopMitm:av,getCachedPassword:aa,setCachedPassword:ab,loadEncryptedPassword:aj,clearEncryptedPassword:ai,isSudoPasswordRequired:t,initDbHooks:function(a,b){af=a,ag=b},restoreToolDNS:an,hasDnsPrivilege:ao,removeAllDNSEntriesSync:p}}};