"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"),j="OpenrouterX MITM Root CA",k="OpenrouterX";function l(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&&!l(i)&&function(a){try{let b=f.pki.certificateFromPem(e.readFileSync(a,"utf8")),c=b.subject.getField("CN")?.value,d=b.subject.getField("O")?.value;return c===j&&d===k}catch{return!1}}(i))return console.log("✅ Root CA already exists"),{key:h,cert:i};if(a){console.log("\uD83D\uDD10 Root CA expired, stale, or branded for legacy 9Router — 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:j},{name:"organizationName",value:k},{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 m=f.pki.privateKeyToPem(b.privateKey),n=f.pki.certificateToPem(c);return e.writeFileSync(h,m),e.writeFileSync(i,n),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:l,ROOT_CA_CERT_PATH:i,ROOT_CA_KEY_PATH:h,ROOT_CA_CN:j,ROOT_CA_ORG:k}},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),{ROOT_CA_CN:m}=c(8578),n="win32"===process.platform,o="darwin"===process.platform,p="/usr/local/share/ca-certificates",q="9Router MITM Root CA",r=`${p}/openrouterx-root-ca.crt`,s=`${p}/9router-root-ca.crt`;function t(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 u(a){var b,c;return n?(b=a,new Promise(a=>{let c;try{c=t(b).replace(/:/g,"")}catch{return a(!1)}f(`certutil -store Root ${c}`,{windowsHide:!0},b=>{a(!b)})})):o?(c=a,new Promise(a=>{try{let b=t(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)}})):Promise.resolve(d.existsSync(r))}async function v(a,b){let c=`security delete-certificate -c "${q}" /Library/Keychains/System.keychain 2>/dev/null || true && security delete-certificate -c "${m}" /Library/Keychains/System.keychain 2>/dev/null || true`,d=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${b}"`;try{await g(`${c} && ${d}`,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 w(a){let b=`
    certutil -delstore Root ${j(q)} 2>$null | Out-Null
    certutil -delstore Root ${j(m)} 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 x(a,b){let c=t(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 y(){let a=`certutil -delstore Root ${j(m)}`;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 z(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 A(a,b){if(!h()){k(`🔐 Cert: cannot install to system store without sudo — trust this file on clients: ${b}`),await z(b,"add");return}let c=`rm -f "${s}" && cp "${b}" "${r}" && (update-ca-certificates 2>/dev/null || update-ca-trust 2>/dev/null || true)`;try{await g(c,a),await z(b,"add"),k(`🔐 Cert: ✅ installed to Linux trust store (${config.dir}) and user browser databases`)}catch(a){throw Error(`Certificate install failed: ${a.message}`)}}async function B(a){if(await z(null,"delete"),!h())return;let b=`rm -f "${r}" "${s}" && (update-ca-certificates 2>/dev/null || update-ca-trust 2>/dev/null || true)`;try{await g(b,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 u(b)?k("\uD83D\uDD10 Cert: already trusted ✅"):n?await w(b):o?await v(a,b):await A(a,b)},uninstallCert:async function a(a,b){await u(b)?n?await y():o?await x(a,b):await B(a):k("\uD83D\uDD10 Cert: not found in system store")},checkCertInstalled:u}},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}}}},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,{generateCert:x}=c(26033),{installCert:y,uninstallCert:z}=c(9631),{isCertExpired:A}=c(8578),{DATA_DIR:B,MITM_DIR:C}=c(82193),{log:D,err:E}=c(87777),F="http://localhost:20502";function G(a){return null==a||""===a?"''":`'${String(a).replace(/'/g,"'\\''")}'`}function H(a){let b=null==a?"":String(a).trim();if(!b)return"";try{let a=new URL(b.replace(/\/+$/,""));if("http:"!==a.protocol&&"https:"!==a.protocol)return"";return a.toString().replace(/\/+$/,"")}catch{return""}}function I(){try{let a=g.join(B,"server.json");if(!h.existsSync(a))return"";let b=JSON.parse(h.readFileSync(a,"utf8"));return H(b&&b.baseUrl)}catch{return""}}function J(a,b=350){return new Promise(c=>{let d;try{d=new URL(a)}catch{c(!1);return}let e=Number(d.port||("https:"===d.protocol?443:80)),f=j.connect({host:d.hostname,port:e}),g=a=>{f.removeAllListeners(),f.destroy(),c(a)};f.setTimeout(b,()=>g(!1)),f.once("connect",()=>g(!0)),f.once("error",()=>g(!1))})}async function K(){let a=I();if(!_)return a||F;try{let b=await _(),c=H(b&&b.mitmRouterBaseUrl);if(!c)return a||F;if(function(a){try{let b=new URL(a).hostname.toLowerCase();return"localhost"===b||"127.0.0.1"===b||"::1"===b}catch{return!1}}(c)&&a&&c!==a&&!await J(c)&&await J(a))return aa&&aa({mitmRouterBaseUrl:a}).catch(()=>{}),D(`🚀 MITM router base auto-corrected: ${c} → ${a}`),a;return c}catch{return a||F}}let L=g.join(C,".mitm.pid"),M=[5e3,1e4,2e4,3e4,6e4],N=0,O=0,P=!1;function Q(){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}let R=Q(),S="aes-256-gcm",T="openrouterx-mitm-pwd",U=null,V=null;function W(){return globalThis.__mitmSudoPassword||null}function X(a){globalThis.__mitmSudoPassword=a}function Y(a){try{return process.kill(a,0),!0}catch(a){return"EACCES"===a.code}}function Z(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 $(){try{let{machineIdSync:a}=c(19713),b=a();return l.createHash("sha256").update(b+T).digest()}catch{return l.createHash("sha256").update(T).digest()}}let _=null,aa=null;async function ab(a,b){if(aa)try{let c,d,e,f,g,h={mitmEnabled:a};b&&(c=$(),d=l.randomBytes(12),e=l.createCipheriv(S,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 aa(h)}catch(a){E(`Failed to save settings: ${a.message}`)}}async function ac(){if(aa)try{await aa({mitmSudoEncrypted:null})}catch(a){E(`Failed to clear encrypted password: ${a.message}`)}}async function ad(){if(!_)return null;try{let a=await _();if(!a.mitmSudoEncrypted)return null;return function(a){try{let[b,c,d]=a.split(":");if(!b||!c||!d)return null;let e=$(),f=l.createDecipheriv(S,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 ae(a,b){if(aa&&_)try{let c={...(await _()).dnsToolEnabled||{},[a]:b};await aa({dnsToolEnabled:c})}catch(a){E(`Failed to save DNS state: ${a.message}`)}}async function af(){if(!_)return{};try{return(await _()).dnsToolEnabled||{}}catch{return{}}}async function ag(a){let b=await af(),c=a||W()||await ad();for(let[a,d]of Object.entries(b))if(d&&r[a])try{await m(a,c)}catch(b){E(`DNS ${a}: restore failed — ${b.message}`)}}async function ah(){return v?u():!(!u()&&t())||!!(W()||await ad())}function ai(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 aj(a){if(U&&!U.killed){try{U.kill("SIGKILL")}catch{}U=null,V=null}try{if(h.existsSync(L)){let b=parseInt(h.readFileSync(L,"utf-8").trim(),10);b&&Y(b)&&(Z(b,!0,a),await new Promise(a=>setTimeout(a,500))),h.unlinkSync(L)}}catch{}if(!v&&R)try{let b=R.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 ak(){let a=null!==U&&!U.killed,b=V;if(!a)try{if(h.existsSync(L)){let c=parseInt(h.readFileSync(L,"utf-8").trim(),10);c&&Y(c)?(a=!0,b=c):h.unlinkSync(L)}}catch{}let d=q(),e=g.join(C,"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 al(a){if(P)return;if(Date.now()-O>=6e4&&(N=0),N>=5)return void E("Max restart attempts reached. Giving up.");let b=M[Math.min(N,M.length-1)];N++,P=!0,D(`Restarting in ${b/1e3}s... (${N}/5)`),await new Promise(a=>setTimeout(a,b));try{let b=_?await _():null;if(b&&!b.mitmEnabled){D("MITM disabled, skipping restart"),P=!1;return}let c=W()||await ad();if(!c&&!v){E("No cached password, cannot auto-restart"),P=!1;return}await an(a,c),D("\uD83D\uDD04 Restarted successfully"),N=0,P=!1}catch(b){E(`Restart attempt ${N}/5 failed: ${b.message}`),P=!1,al(a)}}async function am(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 an(a,b,d=!1){if(!U||U.killed)try{if(h.existsSync(L)){let a=parseInt(h.readFileSync(L,"utf-8").trim(),10);if(a&&Y(a))return V=a,D(`♻️ Reusing existing process (PID: ${a})`),await ab(!0,b),b&&X(b),{running:!0,pid:a};h.unlinkSync(L)}}catch{}if(U&&!U.killed)throw Error("MITM server is already running");if(await aj(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 ai(b);if(a){let c=a.name.includes("/")?a.name.split("/").filter(Boolean).pop():a.name;if(d)D(`Killing process on port 443 (PID ${a.pid}, name=${c})...`),await am(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(C,"rootCA.crt"),m=g.join(C,"rootCA.key"),n=h.existsSync(l)&&h.existsSync(m);if(!n||A(l)){if(n){D("\uD83D\uDD10 Cert expired — uninstalling old cert...");let a=b||W()||await ad();try{await z(a,l)}catch{}}D("\uD83D\uDD10 Generating Root CA..."),await x()}let{checkCertInstalled:o}=c(9631),p=await o(l),r=!v&&!w&&!s();if(p)D("\uD83D\uDD10 Cert: already trusted ✅");else{D("\uD83D\uDD10 Cert: not trusted → installing...");let a=b||W()||await ad();if(r)D(`🔐 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 y(a,l),D("\uD83D\uDD10 Cert: ✅ trusted")}catch(a){throw Error(`Failed to trust certificate: ${a.message}`)}}}let u=R;if((!u||!h.existsSync(u))&&(D(`[MITM] server.js missing at ${u} → recopying`),!(u=ensureRuntimeServer(Q()))||!h.existsSync(u)))throw Error(`MITM server.js not found at ${u}. Reinstall openrouterX.`);let B=await K(),F=C||i.homedir();h.mkdirSync(F,{recursive:!0});let H="1"===process.env.OPENROUTERX_AG_MOCK_BOOTSTRAP?"1":"0";if(D(`🚀 Starting server... (router: ${B})`),v){let c=await ai(b);if(c)if(d)D(`Killing process on port 443 (PID ${c.pid}, name=${c.name})...`),await am(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}U=e(process.execPath,[u],{cwd:F,detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:B,OPENROUTERX_AG_MOCK_BOOTSTRAP:H}}),aa&&await aa({mitmCertInstalled:!0}).catch(()=>{})}else s()?((U=e("sudo",["-S","-E","sh","-c",[`HOME=${G(i.homedir())}`,`ROUTER_API_KEY=${G(a)}`,`MITM_ROUTER_BASE=${G(B)}`,`OPENROUTERX_AG_MOCK_BOOTSTRAP=${G(H)}`,"NODE_ENV=production",G(process.execPath),G(u)].join(" ")],{cwd:F,detached:!1,windowsHide:!0,stdio:["pipe","pipe","pipe"]})).stdin.write(`${b}
`),U.stdin.end()):U=e(process.execPath,[u],{cwd:F,detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:B,OPENROUTERX_AG_MOCK_BOOTSTRAP:H}});U&&(V=U.pid,h.writeFileSync(L,String(V)),O=Date.now());let I=null;U&&(U.stdout.on("data",a=>{process.stdout.write(a)}),U.stderr.on("data",a=>{let b=a.toString().trim();b&&(v||!b.includes("Password:")&&!b.includes("password for"))&&(E(b),I=b),!v&&(b.includes("incorrect password")||b.includes("no password was provided"))&&(X(null),ac(),P=!0)}),U.on("exit",b=>{D(`Server exited (code: ${b})`),U=null,V=null;try{h.unlinkSync(L)}catch{}0===b||P||al(a)}));let J=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(!J){if(U&&!U.killed){try{U.kill()}catch{}U=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=I||`Check sudo password or port 443 access.${b}`;throw Error(`MITM server failed to start. ${c}`)}for(let[a,b]of(aa&&await aa({mitmCertInstalled:!0}).catch(()=>{}),D(`✅ Server healthy (PID: ${V||J.pid})`),Object.entries(q())))D(`🌐 DNS ${a}: ${b?"✅ active":"❌ inactive"}`);return await ab(!0,b),b&&X(b),{running:!0,pid:V}}async function ao(a){P=!0,N=0,D("⏹ Stopping server...");let b=U,d=b&&!b.killed?b.pid:(()=>{try{return parseInt(h.readFileSync(L,"utf-8").trim(),10)}catch{return null}})();if(d&&Y(d)&&(D(`Killing server (PID: ${d})...`),Z(d,!1,a),await new Promise(a=>setTimeout(a,1e3)),Y(d)&&Z(d,!0,a)),U=null,V=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{}D("\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){E(`Failed to clean hosts: ${a.message}`)}}else await o(a);try{h.unlinkSync(L)}catch{}return await ab(!1,null),P=!1,{running:!1,pid:null}}async function ap(a,b){if(!(await ak()).running)throw Error("MITM server is not running. Start the server first.");let c=b||W()||await ad();return await m(a,c),await ae(a,!0),{success:!0}}a.exports={getMitmStatus:ak,startServer:an,stopServer:ao,enableToolDNS:ap,disableToolDNS:async function a(a,b){let c=b||W()||await ad();return await n(a,c),await ae(a,!1),{success:!0}},trustCert:async function a(a){let b=g.join(C,"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())return void D(`🔐 Cert: system trust unavailable (no sudo). Use file: ${b}`);let e=a||W()||await ad();if(!e&&t())throw Error("Sudo password required to trust certificate");await d(e,b),e&&X(e)},startMitm:an,stopMitm:ao,getCachedPassword:W,setCachedPassword:X,loadEncryptedPassword:ad,clearEncryptedPassword:ac,isSudoPasswordRequired:t,initDbHooks:function(a,b){_=a,aa=b},restoreToolDNS:ag,hasDnsPrivilege:ah,removeAllDNSEntriesSync:p,resolveMitmRouterBaseUrl:K,normalizeHttpBaseUrl:H,readCurrentServerBaseUrl:I}}};