"use strict";exports.id=6182,exports.ids=[6182],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:"9Router MITM Root CA"},{name:"organizationName",value:"9Router"},{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}=c(64809),{log:k,err:l}=c(87777),m="win32"===process.platform,n="darwin"===process.platform,o=[{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 p(){for(let a of o)if(d.existsSync(a.dir))return a;return o[0]}let q="9Router MITM Root CA";function r(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 s(a){var b,c;let e,g;return m?(b=a,new Promise(a=>{let c;try{c=r(b).replace(/:/g,"")}catch{return a(!1)}f(`certutil -store Root ${c}`,{windowsHide:!0},b=>{a(!b)})})):n?(c=a,new Promise(a=>{try{let b=r(c).replace(/:/g,"");f(`security find-certificate -a -c "${q}" -Z /Library/Keychains/System.keychain 2>/dev/null`,{windowsHide:!0},(d,e)=>{if(d||!e||!RegExp(`SHA-1 hash:\\s*${b}`,"i").test(e))return a(!1);f(`security verify-cert -c "${c}" -p ssl -k /Library/Keychains/System.keychain 2>/dev/null`,{windowsHide:!0},b=>{a(!b)})})}catch{a(!1)}})):(e=p(),g=`${e.dir}/9router-root-ca.crt`,Promise.resolve(d.existsSync(g)))}async function t(a,b){let c=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${b}"`;try{await g(`security delete-certificate -c "9Router MITM Root CA" /Library/Keychains/System.keychain 2>/dev/null || true && ${c}`,a),k("\uD83D\uDD10 Cert: ✅ installed to system keychain")}catch(a){throw Error(a.message?.includes("canceled")?"User canceled authorization":"Certificate install failed")}}async function u(a){let b=`
    certutil -delstore Root ${j(q)} 2>$null | Out-Null
    $exit = & certutil -addstore Root ${j(a)} 2>&1
    if ($LASTEXITCODE -ne 0) { throw "certutil exit $LASTEXITCODE" }
  `;try{await i(b),k("\uD83D\uDD10 Cert: ✅ installed to Windows Root store")}catch(a){throw Error(`Failed to install certificate: ${a.message}`)}}async function v(a,b){let c=r(b).replace(/:/g,""),d=`security delete-certificate -Z "${c}" /Library/Keychains/System.keychain`;try{await g(d,a),k("\uD83D\uDD10 Cert: ✅ uninstalled from system keychain")}catch(a){throw Error("Failed to uninstall certificate")}}async function w(){let a=`certutil -delstore Root ${j(q)}`;try{await i(a),k("\uD83D\uDD10 Cert: ✅ uninstalled from Windows Root store")}catch(a){throw Error(`Failed to uninstall certificate: ${a.message}`)}}async function x(a,b="add"){let c="9Router 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 y(a,b){if(!h()){k(`🔐 Cert: cannot install to system store without sudo — trust this file on clients: ${b}`),await x(b,"add");return}let c=p(),d=`${c.dir}/9router-root-ca.crt`,e=`cp "${b}" "${d}" && (${c.cmd} 2>/dev/null || true)`;try{await g(e,a),await x(b,"add"),k(`🔐 Cert: ✅ installed to Linux trust store (${c.dir}) and user browser databases`)}catch(a){throw Error(`Certificate install failed: ${a.message}`)}}async function z(a){if(await x(null,"delete"),!h())return;let b=p(),c=`${b.dir}/9router-root-ca.crt`,d=`rm -f "${c}" && (${b.cmd} 2>/dev/null || true)`;try{await g(d,a),k("\uD83D\uDD10 Cert: ✅ 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 s(b)?k("\uD83D\uDD10 Cert: already trusted ✅"):m?await u(b):n?await t(a,b):await y(a,b)},uninstallCert:async function a(a,b){await s(b)?m?await w():n?await v(a,b):await z(a):k("\uD83D\uDD10 Cert: not found in system store")},checkCertInstalled:s}},17511:(a,b,c)=>{let d=c(29021);a.exports={IS_DEV:!1,LSOF_BIN:(()=>{if("win32"===process.platform)return null;for(let a of["/usr/sbin/lsof","/usr/bin/lsof","/sbin/lsof"])try{return d.accessSync(a,d.constants.X_OK),a}catch{}return"lsof"})(),TARGET_HOSTS:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com","api.individual.githubcopilot.com","q.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-low","gemini-3.1-pro-high":"gemini-pro-agent","gemini-3-pro-high":"gemini-pro-agent","gemini-3-pro-low":"gemini-3.1-pro-low"}},MODEL_PATTERNS:{antigravity:[{match:/flash.*low|low.*flash|flash.*medium|medium.*flash/i,alias:"gemini-3.5-flash-low"},{match:/flash.*agent|agent.*flash|flash/i,alias:"gemini-3-flash-agent"},{match:/pro.*low|low.*pro/i,alias:"gemini-3.1-pro-low"},{match:/gemini.*pro|pro.*gemini/i,alias:"gemini-pro-agent"},{match:/opus/i,alias:"claude-opus-4-6-thinking"},{match:/sonnet|claude/i,alias:"claude-sonnet-4-6"},{match:/gpt.*oss|oss/i,alias:"gpt-oss-120b-medium"}]},LOG_BLACKLIST_URL_PARTS:["recordCodeAssistMetrics","recordTrajectoryAnalytics","fetchAdminControls","listExperiments","fetchUserInfo"],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?"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,quotePs:m}=c(64809),n="win32"===process.platform,o="darwin"===process.platform,p=n?h.join(process.env.SystemRoot||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts";function q(a){return null==a?"":String(a).replace(/\s+/g," ").trim()}function r(a,b={}){let c=[];c.push(b.action||"DNS operation failed"),b.tool&&c.push(`tool=${b.tool}`),b.hostsFile&&c.push(`hostsFile=${b.hostsFile}`),b.hosts&&b.hosts.length&&c.push(`hosts=${b.hosts.join(", ")}`),a?.code&&c.push(`code=${a.code}`),a?.syscall&&c.push(`syscall=${a.syscall}`),a?.path&&c.push(`path=${a.path}`);let d=q(a?.stdout),e=q(a?.stderr),f=q(a?.message);return f&&c.push(`message=${f}`),e&&c.push(`stderr=${e}`),d&&c.push(`stdout=${d}`),c.join(" | ")}function s(a=p){return`Windows DNS changes require Administrator privileges. Restart 9Router as Administrator so it can update ${a} and flush the DNS cache.`}function t(a,b={}){let c=r(a,b);return(b.isWindows??n)&&(a?.code==="EACCES"||a?.code==="EPERM")?`${c} | hint=${s(b.hostsFile||p)}`:c}function u(a,b){let c=k[a]||[],d=g.readFileSync(p,"utf8");if(c.every(a=>d.includes(a))!==b)throw function(a,b={}){let c=Error(a);return Object.assign(c,b),c}(`DNS verification failed | tool=${a} | hostsFile=${p} | expected=${b?"present":"absent"} | hosts=${c.join(", ")}`)}function v(){if(n)return!1;try{return f("command -v sudo",{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function w(a,b){return new Promise((c,d)=>{let f=v(),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())})}async function x(a){n||(o?await w("dscacheutil -flushcache && killall -HUP mDNSResponder",a):await w("resolvectl flush-caches 2>/dev/null || true",a))}function y(a=null){try{let b=g.readFileSync(p,"utf8");if(a)return b.includes(a);return k.antigravity.every(a=>b.includes(a))}catch{return!1}}async function z(a,b){let c=k[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>!y(a));if(0===d.length)return void i(`🌐 DNS ${a}: already active`);let e=d.map(a=>`127.0.0.1 ${a}`).join("\n");try{if(i(`🌐 DNS ${a}: enabling (${d.join(", ")})`),n){let b=d.map(a=>`127.0.0.1 ${a}`).join("\r\n"),c=`
        Add-Content -LiteralPath ${m(p)} -Value ${m(b)}
        ipconfig /flushdns | Out-Null
      `;await l(c),u(a,!0)}else await w(`echo "${e}" >> ${p}`,b),await x(b);i(`🌐 DNS ${a}: ✅ added ${d.join(", ")} (hosts=${p})`)}catch(c){let b=c.message?.includes("incorrect password")?"Wrong sudo password":t(c,{action:"Failed to add DNS entry",tool:a,hostsFile:p,hosts:d});throw j(`DNS ${a}: add failed — ${b}`),Error(b)}}async function A(a,b){let c=k[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>y(a));if(0===d.length)return void i(`🌐 DNS ${a}: already inactive`);try{if(i(`🌐 DNS ${a}: disabling (${d.join(", ")})`),n){let b=d.map(m).join(","),c=`
        $hosts = @(${b})
        $lines = Get-Content -LiteralPath ${m(p)}
        $filtered = $lines | Where-Object {
          $line = $_
          -not ($hosts | Where-Object { $line -match [regex]::Escape($_) })
        }
        Set-Content -LiteralPath ${m(p)} -Value $filtered
        ipconfig /flushdns | Out-Null
      `;await l(c),u(a,!1)}else{for(let a of d){let c=o?`sed -i '' '/${a}/d' ${p}`:`sed -i '/${a}/d' ${p}`;await w(c,b)}await x(b)}i(`🌐 DNS ${a}: ✅ removed ${d.join(", ")} (hosts=${p})`)}catch(c){let b=c.message?.includes("incorrect password")?"Wrong sudo password":t(c,{action:"Failed to remove DNS entry",tool:a,hostsFile:p,hosts:d});throw j(`DNS ${a}: remove failed — ${b}`),Error(b)}}async function B(a){for(let b of Object.keys(k))try{await A(b,a)}catch(a){j(`DNS ${b}: failed to remove — ${a.message}`)}}a.exports={TOOL_HOSTS:k,addDNSEntry:z,removeDNSEntry:A,removeAllDNSEntries:B,removeAllDNSEntriesSync:function(){try{if(!g.existsSync(p))return;let a=Object.values(k).flat(),b=g.readFileSync(p,"utf8"),c=b.split(/\r?\n/).filter(b=>!a.some(a=>b.includes(a))).join(n?"\r\n":"\n");if(c===b)return;if(g.writeFileSync(p,c,"utf8"),n)try{f("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}else if(o)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:w,isSudoAvailable:v,checkDNSEntry:y,checkAllDNSStatus:function(){try{let a=g.readFileSync(p,"utf8"),b={};for(let[c,d]of Object.entries(k))b[c]=d.every(b=>a.includes(b));return b}catch{return Object.fromEntries(Object.keys(k).map(a=>[a,!1]))}},buildWindowsAdminHint:s,buildDnsOperationError:t,describeDnsError:r,isWindowsAdmin:function(){if(!n)return!1;try{return f("net session >nul 2>&1",{windowsHide:!0,stdio:"ignore"}),!0}catch{return!1}}}},82193:(a,b,c)=>{let d=c(33873),e=c(21820),f=c(29021),g=process.env.DATA_DIR?process.env.DATA_DIR:"win32"===process.platform?d.join(process.env.APPDATA||d.join(e.homedir(),"AppData","Roaming"),"n9router"):d.join(e.homedir(),".n9router"),h=d.join(g,"mitm");if("win32"===process.platform)try{let a=d.join(e.homedir(),".n9router","mitm"),b=d.join(h,"rootCA.key"),c=d.join(a,"rootCA.key");!f.existsSync(b)&&f.existsSync(c)&&(f.mkdirSync(h,{recursive:!0}),f.cpSync(a,h,{recursive:!0}))}catch(a){console.error("[n9router mitm] Could not sync MITM from ~/.n9router/mitm:",a.message)}a.exports={DATA_DIR:g,MITM_DIR:h}},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");d.existsSync(j)||d.mkdirSync(j,{recursive:!0});let k=/^\s*(\{\s*\}|\[\s*\]|null)?\s*$/;function l(a,b=80){return String(a).replace(/[^a-zA-Z0-9]/g,"_").substring(0,b)}function m(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(m(a.url))return null;try{let f=new Date().toISOString().replace(/[:.]/g,"-"),g=l((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:a.headers,body:i??b.toString("utf8")},null,2)),h}catch{return null}},createResponseDumper:function(a,b="raw"){if(m(a.url))return null;let c=new Date().toISOString().replace(/[:.]/g,"-"),g=l((a.headers.host||"")+a.url),h=e.join(j,`${c}_${b}_${g}.res.txt`),i=0,n={},o=[];return{writeHeader:(a,b)=>{i=a,n=b||{}},writeChunk:a=>{null!=a&&o.push(Buffer.isBuffer(a)?a:Buffer.from(a))},end:()=>{try{let a=Buffer.concat(o),b=n["content-encoding"]||n["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(k.test(c))return;let e={...n};delete e["content-encoding"],delete e["Content-Encoding"];let g=`STATUS: ${i}
HEADERS: ${JSON.stringify(e,null,2)}
---BODY---
${c}`;d.writeFileSync(h,g)}catch{}},file:h}},clearDumpDir:function(){try{if(!d.existsSync(j))return;for(let a of d.readdirSync(j))try{d.rmSync(e.join(j,a),{recursive:!0,force:!0})}catch{}}catch{}}}},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}=c(66936),t="win32"===process.platform,u="darwin"===process.platform,{generateCert:v}=c(26033),{installCert:w,uninstallCert:x,checkCertInstalled:y,isWSL:z}=c(9631),{isCertExpired:A}=c(8578),{MITM_DIR:B}=c(82193),{log:C,err:D}=c(87777),E="http://localhost:20128";function F(a){return null==a||""===a?"''":`'${String(a).replace(/'/g,"'\\''")}'`}async function G(){if(!W)return E;try{let a=await W(),b=a&&null!=a.mitmRouterBaseUrl?String(a.mitmRouterBaseUrl).trim():"";if(!b)return E;let c=new URL(b);if("http:"!==c.protocol&&"https:"!==c.protocol)return E;return b.replace(/\/+$/,"")}catch{return E}}let H=g.join(B,".mitm.pid"),I=[5e3,1e4,2e4,3e4,6e4],J=0,K=0,L=!1,M=function(){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}(),N="aes-256-gcm",O="9router-mitm-pwd",P=null,Q=null;function R(){return globalThis.__mitmSudoPassword||null}function S(a){globalThis.__mitmSudoPassword=a}function T(a){try{return process.kill(a,0),!0}catch(a){return"EACCES"===a.code}}function U(a,b=!1,e=null){if(t)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){let{execWithPassword:a}=c(66936);a(g,e).catch(()=>d(g,{windowsHide:!0},()=>{}))}else d(g,{windowsHide:!0},()=>{})}}function V(){try{let{machineIdSync:a}=c(19713),b=a();return l.createHash("sha256").update(b+O).digest()}catch{return l.createHash("sha256").update(O).digest()}}let W=null,X=null;async function Y(a,b){if(X)try{let c,d,e,f,g,h={mitmEnabled:a};b&&(c=V(),d=l.randomBytes(12),e=l.createCipheriv(N,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 X(h)}catch(a){D(`Failed to save settings: ${a.message}`)}}async function Z(){if(X)try{await X({mitmSudoEncrypted:null})}catch(a){D(`Failed to clear encrypted password: ${a.message}`)}}async function $(){if(!W)return null;try{let a=await W();if(!a.mitmSudoEncrypted)return null;return function(a){try{let[b,c,d]=a.split(":");if(!b||!c||!d)return null;let e=V(),f=l.createDecipheriv(N,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 _(a){if(P&&!P.killed){try{P.kill("SIGKILL")}catch{}P=null,Q=null}try{if(h.existsSync(H)){let b=parseInt(h.readFileSync(H,"utf-8").trim(),10);b&&T(b)&&(U(b,!0,a),await new Promise(a=>setTimeout(a,500))),h.unlinkSync(H)}}catch{}if(!t&&M)try{let b=M.replace(/'/g,"'\\''");if(a){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 aa(){let a=null!==P&&!P.killed,b=Q;if(!a)try{if(h.existsSync(H)){let c=parseInt(h.readFileSync(H,"utf-8").trim(),10);c&&T(c)?(a=!0,b=c):h.unlinkSync(H)}}catch{}let c=q(),d=g.join(B,"rootCA.crt"),e=h.existsSync(d),f=!!e&&await y(d);return{running:a,pid:b,certExists:e,certTrusted:f,dnsStatus:c}}async function ab(a){if(L)return;if(Date.now()-K>=6e4&&(J=0),J>=5)return void D("Max restart attempts reached. Giving up.");let b=I[Math.min(J,I.length-1)];J++,L=!0,C(`Restarting in ${b/1e3}s... (${J}/5)`),await new Promise(a=>setTimeout(a,b));try{let b=W?await W():null;if(b&&!b.mitmEnabled){C("MITM disabled, skipping restart"),L=!1;return}let c=R()||await $();if(!c&&!t){D("No cached password, cannot auto-restart"),L=!1;return}await ac(a,c),C("\uD83D\uDD04 Restarted successfully"),J=0,L=!1}catch(b){D(`Restart attempt ${J}/5 failed: ${b.message}`),L=!1,ab(a)}}async function ac(a,b){if(!P||P.killed)try{if(h.existsSync(H)){let a=parseInt(h.readFileSync(H,"utf-8").trim(),10);if(a&&T(a))return Q=a,C(`♻️ Reusing existing process (PID: ${a})`),await Y(!0,b),b&&S(b),{running:!0,pid:a};h.unlinkSync(H)}}catch{}if(P&&!P.killed)throw Error("MITM server is already running");if(await _(b),!t){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 new Promise(a=>{t?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"})})})});if(a&&("node"===a.name||a.name.includes("node"))){C(`Killing orphan node process on port 443 (PID ${a.pid}, name=${a.name})...`);try{let{execWithPassword:d}=c(66936);await d(`kill -9 ${a.pid}`,b),await new Promise(a=>setTimeout(a,800))}catch{}}else if(a){let b=a.name.includes("/")?a.name.split("/").filter(Boolean).pop():a.name;throw Error(`Port 443 is already in use by "${b}" (PID ${a.pid}). Stop that process first.`)}}}let l=g.join(B,"rootCA.crt"),m=g.join(B,"rootCA.key"),n=h.existsSync(l)&&h.existsSync(m);if(!n||A(l)){if(n){C("\uD83D\uDD10 Cert expired — uninstalling old cert...");let a=b||R()||await $();try{await x(a,l)}catch{}}C("\uD83D\uDD10 Generating Root CA..."),await v()}let o=await y(l),p=!t&&!u&&!s()&&!z();if(o)C("\uD83D\uDD10 Cert: already trusted ✅");else{C("\uD83D\uDD10 Cert: not trusted → installing...");let a=b||R()||await $();if(p)C(`🔐 Cert: skipping system trust (no sudo). Install ${l} as a trusted CA on machines that use this proxy.`);else{if(!a&&!t&&!z())throw Error("Sudo password required to install Root CA certificate");try{await w(a,l),C("\uD83D\uDD10 Cert: ✅ trusted")}catch(a){throw Error(`Failed to trust certificate: ${a.message}`)}}}let r=await G();if(C(`🚀 Starting server... (router: ${r})`),t){try{f('powershell -NonInteractive -WindowStyle Hidden -Command "$c = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if ($c -and $c.OwningProcess -gt 4) { Stop-Process -Id $c.OwningProcess -Force -ErrorAction SilentlyContinue }"',{windowsHide:!0}),await new Promise(a=>setTimeout(a,500))}catch{}P=e(process.execPath,[M],{detached:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:r}}),X&&await X({mitmCertInstalled:!0}).catch(()=>{})}else s()?((P=e("sudo",["-S","-E","sh","-c",[`HOME=${F(i.homedir())}`,`ROUTER_API_KEY=${F(a)}`,`MITM_ROUTER_BASE=${F(r)}`,"NODE_ENV=production",F(process.execPath),F(M)].join(" ")],{detached:!1,windowsHide:!0,stdio:["pipe","pipe","pipe"]})).stdin.write(`${b}
`),P.stdin.end()):P=e(process.execPath,[M],{detached:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:r}});if(P&&(Q=P.pid,h.writeFileSync(H,String(Q)),K=Date.now()),u){let a=g.join(B,"rootCA.crt");h.existsSync(a)&&d(`launchctl setenv NODE_EXTRA_CA_CERTS "${a}"`,{windowsHide:!0},b=>{b?C(`[launchctl] Failed to set NODE_EXTRA_CA_CERTS: ${b.message}`):C(`[launchctl] NODE_EXTRA_CA_CERTS set to ${a}`)})}else if(t){let a=g.join(B,"rootCA.crt");h.existsSync(a)&&d(`setx NODE_EXTRA_CA_CERTS "${a}"`,{windowsHide:!0},a=>{a?C(`[setx] Failed to set NODE_EXTRA_CA_CERTS: ${a.message}`):C("[setx] NODE_EXTRA_CA_CERTS set for current user")})}let E=null;P&&(P.stdout.on("data",a=>{process.stdout.write(a)}),P.stderr.on("data",a=>{let b=a.toString().trim();b&&(t||!b.includes("Password:")&&!b.includes("password for"))&&(D(b),E=b),!t&&(b.includes("incorrect password")||b.includes("no password was provided"))&&(S(null),Z(),L=!0)}),P.on("exit",b=>{C(`Server exited (code: ${b})`),P=null,Q=null;try{h.unlinkSync(H)}catch{}0===b||L||ab(a)}));let I=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(!I){if(P&&!P.killed){try{P.kill()}catch{}P=null}let a=function(){try{if(t){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=E||`Check sudo password or port 443 access.${b}`;throw Error(`MITM server failed to start. ${c}`)}for(let[a,b]of(X&&await X({mitmCertInstalled:!0}).catch(()=>{}),C(`✅ Server healthy (PID: ${Q||I.pid})`),Object.entries(q())))C(`🌐 DNS ${a}: ${b?"✅ active":"❌ inactive"}`);return await Y(!0,b),b&&S(b),{running:!0,pid:Q}}async function ad(a){L=!0,J=0,C("⏹ Stopping server...");let b=P,e=b&&!b.killed?b.pid:(()=>{try{return parseInt(h.readFileSync(H,"utf-8").trim(),10)}catch{return null}})();if(e&&T(e)&&(C(`Killing server (PID: ${e})...`),U(e,!1,a),await new Promise(a=>setTimeout(a,1e3)),T(e)&&U(e,!0,a)),P=null,Q=null,t){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");e!==d&&h.writeFileSync(a,e,"utf8");try{c(79646).execSync("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}C("\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){D(`Failed to clean hosts: ${a.message}`)}}else await o(a);try{h.unlinkSync(H)}catch{}return u?d("launchctl unsetenv NODE_EXTRA_CA_CERTS",{windowsHide:!0},a=>{a?C(`[launchctl] Failed to unset NODE_EXTRA_CA_CERTS: ${a.message}`):C("[launchctl] NODE_EXTRA_CA_CERTS unset")}):t&&d('setx NODE_EXTRA_CA_CERTS ""',{windowsHide:!0},a=>{a?C(`[setx] Failed to unset NODE_EXTRA_CA_CERTS: ${a.message}`):C("[setx] NODE_EXTRA_CA_CERTS unset for current user")}),await Y(!1,null),L=!1,{running:!1,pid:null}}async function ae(a,b){C(`🌐 DNS ${a}: enable requested (platform=${process.platform})`);let c=await aa();if(!c.running)throw Error("MITM server is not running. Start the server first.");C(`🌐 DNS ${a}: pre-check running=${c.running} active=${!!c.dnsStatus?.[a]}`);let d=b||R()||await $();try{await m(a,d)}catch(b){throw D(`DNS ${a}: enable failed in manager — ${b?.message||String(b)}`),b}let e=q();return C(`🌐 DNS ${a}: post-check active=${!!e[a]}`),{success:!0,dnsStatus:e}}a.exports={getMitmStatus:aa,startServer:ac,stopServer:ad,enableToolDNS:ae,disableToolDNS:async function a(a,b){C(`🌐 DNS ${a}: disable requested (platform=${process.platform})`);let c=b||R()||await $();try{await n(a,c)}catch(b){throw D(`DNS ${a}: disable failed in manager — ${b?.message||String(b)}`),b}let d=q();return C(`🌐 DNS ${a}: post-check active=${!!d[a]}`),{success:!0,dnsStatus:d}},restoreToolDNS:async function a(){return{success:!0,dnsStatus:q()}},removeAllDNSEntriesSync:p,trustCert:async function a(a){let b=g.join(B,"rootCA.crt");if(!h.existsSync(b))throw Error("Root CA not found. Start server first to generate it.");if(!t&&!u&&!s()&&!z())return void C(`🔐 Cert: system trust unavailable (no sudo). Use file: ${b}`);let c=a||R()||await $();if(!c&&!t&&!z())throw Error("Sudo password required to trust certificate");await w(c,b),c&&S(c)},startMitm:ac,stopMitm:ad,getCachedPassword:R,setCachedPassword:S,loadEncryptedPassword:$,clearEncryptedPassword:Z,initDbHooks:function(a,b){W=a,X=b}}}};