"use strict";exports.id=6182,exports.ids=[6182],exports.modules={8578:(a,b,c)=>{let d=c(33873),e=c(29021),f=c(15296),{execFileSync:g}=c(79646),{MITM_DIR:h}=c(82193),i=d.join(h,"rootCA.key"),j=d.join(h,"rootCA.crt"),k=d.join(h,"rootCA.csr"),l=d.join(h,"rootCA.csr.cnf"),m=d.join(h,"rootCA.pending.key"),n=d.join(h,"backup");function o(){e.existsSync(h)||e.mkdirSync(h,{recursive:!0})}function p(a,b){let c=String(a||"").trim();if(!c)throw Error(`${b} is empty`);return`${c}
`}function q(a){return f.md.sha256.create().update(f.pki.publicKeyToPem(a),"utf8").digest().toHex()}function r(a){let b=a.getExtension("basicConstraints"),c=a.getExtension("keyUsage");return!!b?.cA&&(!c||!0===c.keyCertSign)}function s(a,b){if(q(a.publicKey)!==q(function(a){if(!a?.n||!a?.e)throw Error("Only RSA private keys are supported for MITM Root CA");return f.pki.setRsaPublicKey(a.n,a.e)}(b)))throw Error("Certificate public key does not match private key")}function t(){o();let a=e.existsSync(i),b=e.existsSync(j);if(!a&&!b)return null;e.mkdirSync(n,{recursive:!0});let c=new Date().toISOString().replace(/[:.]/g,"-"),f={key:d.join(n,`rootCA.${c}.key`),cert:d.join(n,`rootCA.${c}.crt`)};return a&&e.copyFileSync(i,f.key),b&&e.copyFileSync(j,f.cert),f}function u(a,b="Certificate"){try{return f.pki.certificateFromPem(p(a,b))}catch(a){throw Error(`${b} is not a valid PEM certificate: ${a.message}`)}}function v(a,b="Private key"){try{return f.pki.privateKeyFromPem(p(a,b))}catch(a){throw Error(`${b} is not a valid PEM private key: ${a.message}`)}}function w(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}}function x(){let a=e.existsSync(j),b=e.existsSync(i),c={certExists:a,keyExists:b,csrExists:e.existsSync(k),pendingKeyExists:e.existsSync(m),certPath:j,keyPath:i,csrPath:k,pendingKeyPath:m};if(!a)return c;try{let a=u(e.readFileSync(j,"utf8")),b=a.subject.attributes.map(a=>`${a.shortName||a.name}=${a.value}`).join(", "),d=a.issuer.attributes.map(a=>`${a.shortName||a.name}=${a.value}`).join(", ");c.subject=b,c.issuer=d,c.serialNumber=a.serialNumber,c.notBefore=a.validity.notBefore.toISOString(),c.notAfter=a.validity.notAfter.toISOString(),c.expiredOrExpiringSoon=w(j),c.isCa=r(a),c.isSelfSigned=b===d,c.fingerprint=q(a.publicKey)}catch(a){c.error=a.message}return c}function y(a,b){return String(a||b||"").replace(/[\r\n]+/g," ").replace(/[\\]/g,"\\\\").trim()||String(b||"")}a.exports={generateRootCA:async function a(){let a=e.existsSync(i)&&e.existsSync(j);if(a&&!w(j))return console.log("✅ Root CA already exists"),{key:i,cert:j};if(a){console.log("\uD83D\uDD10 Root CA expired or expiring soon — regenerating...");try{e.unlinkSync(i)}catch{}try{e.unlinkSync(j)}catch{}}o(),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:"Blue Router Gateway Root CA"},{name:"organizationName",value:"Blue Router Gateway"},{name:"countryName",value:"VN"}];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 g=f.pki.privateKeyToPem(b.privateKey),h=f.pki.certificateToPem(c);return e.writeFileSync(i,g,{mode:384}),e.writeFileSync(j,h),console.log("✅ Root CA generated successfully"),{key:i,cert:j}},importRootCAPair:function({certPem:a,keyPem:b}){o();let c=p(a,"Certificate"),d=p(b,"Private key"),f=u(c);if(s(f,v(d)),!r(f))throw Error("Certificate must be a CA certificate with basicConstraints CA:true and keyCertSign usage");if(f.validity.notAfter<new Date)throw Error("Certificate is already expired");let g=t();e.writeFileSync(i,d,{mode:384}),e.writeFileSync(j,c);try{e.unlinkSync(k)}catch{}try{e.unlinkSync(m)}catch{}return{key:i,cert:j,backup:g,info:x()}},generateRootCACsr:function({commonName:a,organizationName:b,countryName:c}={}){if(o(),function(){try{return g("openssl",["version"],{stdio:"ignore"}),!0}catch{return!1}}())return function({commonName:a,organizationName:b,countryName:c}={}){let d=y(a,"Fujinet Bluerouter MITM CA"),f=y(b,"Fujinet"),h=y(c,"VN").slice(0,2).toUpperCase()||"VN",i=`[ req ]
default_bits       = 4096
prompt             = no
distinguished_name = dn
req_extensions     = v3_ca

[ dn ]
C  = ${h}
O  = ${f}
OU = AI Gateway
CN = ${d}

[ v3_ca ]
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
`,j=t();e.writeFileSync(l,i,"utf8");try{g("openssl",["genrsa","-out",m,"4096"],{stdio:["ignore","pipe","pipe"]}),g("openssl",["req","-new","-key",m,"-out",k,"-config",l],{stdio:["ignore","pipe","pipe"]});try{e.chmodSync(m,384)}catch{}return{csr:k,pendingKey:m,config:l,backup:j}}catch(b){try{e.unlinkSync(m)}catch{}try{e.unlinkSync(k)}catch{}let a=b?.stderr?String(b.stderr).trim():"";throw Error(`OpenSSL CSR generation failed${a?`: ${a}`:""}`)}}({commonName:a,organizationName:b,countryName:c});let d=[{name:"commonName",value:String(a||"Fujinet Bluerouter MITM CA").trim()||"Fujinet Bluerouter MITM CA"},{name:"organizationName",value:String(b||"Fujinet").trim()||"Fujinet"},{name:"organizationalUnitName",value:"AI Gateway"}],h=String(c||"VN").trim().slice(0,2).toUpperCase();h&&d.push({name:"countryName",value:h});let i=f.pki.rsa.generateKeyPair(4096),j=f.pki.createCertificationRequest();if(j.publicKey=i.publicKey,j.setSubject(d),j.sign(i.privateKey,f.md.sha256.create()),!j.verify())throw Error("Generated CSR failed verification");let n=t(),p=f.pki.certificationRequestToPem(j),q=f.pki.privateKeyToPem(i.privateKey);return e.writeFileSync(m,q,{mode:384}),e.writeFileSync(k,p),{csr:k,pendingKey:m,backup:n}},importSignedRootCACert:function({certPem:a}){if(o(),!e.existsSync(m))throw Error("No pending CSR private key found. Generate a CSR first.");let b=p(a,"Signed certificate"),c=u(b,"Signed certificate");if(s(c,v(e.readFileSync(m,"utf8"),"Pending private key")),!r(c))throw Error("Signed certificate must be a CA certificate with CA:true and keyCertSign usage");if(c.validity.notAfter<new Date)throw Error("Signed certificate is already expired");let d=t();e.copyFileSync(m,i);try{e.chmodSync(i,384)}catch{}e.writeFileSync(j,b);try{e.unlinkSync(k)}catch{}try{e.unlinkSync(m)}catch{}return{key:i,cert:j,backup:d,info:x()}},loadRootCA:function(){if(!e.existsSync(i)||!e.existsSync(j))throw Error("Root CA not found. Generate it first.");let a=e.readFileSync(i,"utf8"),b=e.readFileSync(j,"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:w,readRootCAInfo:x,ROOT_CA_CERT_PATH:j,ROOT_CA_KEY_PATH:i,ROOT_CA_CSR_PATH:k,ROOT_CA_PENDING_KEY_PATH:m}},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="Bluerouter 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 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=p(),g=`${e.dir}/bluerouter-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 "Bluerouter 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="Bluerouter 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}/bluerouter-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}/bluerouter-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}},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),{LSOF_BIN:F}=c(17511),G="http://localhost:20128";function H(a){return null==a||""===a?"''":`'${String(a).replace(/'/g,"'\\''")}'`}async function I(){if(!$)return G;try{let a=await $(),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(C,".mitm.pid"),K=[5e3,1e4,2e4,3e4,6e4],L=0,M=0,N=!1;function O(){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 P(a){try{if(!a||!h.existsSync(a)||!a.includes(`${g.sep}node_modules${g.sep}`))return a;let b=g.join(B,"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{D(`[MITM] runtime copy failed: ${b.message}`)}catch{}return a}}let Q=P(O()),R="aes-256-gcm",S="bluerouter-mitm-pwd",T=null,U=null;function V(){return globalThis.__mitmSudoPassword||null}function W(a){globalThis.__mitmSudoPassword=a}function X(a){try{return process.kill(a,0),!0}catch(a){return"EACCES"===a.code}}function Y(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 Z(){try{let{machineIdSync:a}=c(19713),b=a();return l.createHash("sha256").update(b+S).digest()}catch{return l.createHash("sha256").update(S).digest()}}let $=null,_=null;async function aa(a,b){if(_)try{let c,d,e,f,g,h={mitmEnabled:a};b&&(c=Z(),d=l.randomBytes(12),e=l.createCipheriv(R,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 _(h)}catch(a){E(`Failed to save settings: ${a.message}`)}}async function ab(){if(_)try{await _({mitmSudoEncrypted:null})}catch(a){E(`Failed to clear encrypted password: ${a.message}`)}}async function ac(){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=Z(),f=l.createDecipheriv(R,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 ad(a,b){if(_&&$)try{let c={...(await $()).dnsToolEnabled||{},[a]:b};await _({dnsToolEnabled:c})}catch(a){E(`Failed to save DNS state: ${a.message}`)}}async function ae(){if(!$)return{};try{return(await $()).dnsToolEnabled||{}}catch{return{}}}async function af(a){let b=await ae(),c=a||V()||await ac();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 ag(){return v?u():!(!u()&&t())||!!(V()||await ac())}function ah(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(`${F} -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 ai(a){if(T&&!T.killed){try{T.kill("SIGKILL")}catch{}T=null,U=null}try{if(h.existsSync(J)){let b=parseInt(h.readFileSync(J,"utf-8").trim(),10);b&&X(b)&&(Y(b,!0,a),await new Promise(a=>setTimeout(a,500))),h.unlinkSync(J)}}catch{}if(!v&&Q)try{let b=Q.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 aj(){let a=null!==T&&!T.killed,b=U;if(!a)try{if(h.existsSync(J)){let c=parseInt(h.readFileSync(J,"utf-8").trim(),10);c&&X(c)?(a=!0,b=c):h.unlinkSync(J)}}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 ak(a){if(N)return;if(Date.now()-M>=6e4&&(L=0),L>=5)return void E("Max restart attempts reached. Giving up.");let b=K[Math.min(L,K.length-1)];L++,N=!0,D(`Restarting in ${b/1e3}s... (${L}/5)`),await new Promise(a=>setTimeout(a,b));try{let b=$?await $():null;if(b&&!b.mitmEnabled){D("MITM disabled, skipping restart"),N=!1;return}let c=V()||await ac();if(!c&&!v){E("No cached password, cannot auto-restart"),N=!1;return}await am(a,c),D("\uD83D\uDD04 Restarted successfully"),L=0,N=!1}catch(b){E(`Restart attempt ${L}/5 failed: ${b.message}`),N=!1,ak(a)}}async function al(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 am(a,b,d=!1){if(!T||T.killed)try{if(h.existsSync(J)){let a=parseInt(h.readFileSync(J,"utf-8").trim(),10);if(a&&X(a))return U=a,D(`♻️ Reusing existing process (PID: ${a})`),await aa(!0,b),b&&W(b),{running:!0,pid:a};h.unlinkSync(J)}}catch{}if(T&&!T.killed)throw Error("MITM server is already running");if(await ai(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 ah(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 al(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||V()||await ac();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||V()||await ac();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=Q;if((!u||!h.existsSync(u))&&(D(`[MITM] server.js missing at ${u} → recopying`),!(u=P(O()))||!h.existsSync(u)))throw Error(`MITM server.js not found at ${u}. Reinstall bluerouter.`);let G=await I();if(D(`🚀 Starting server... (router: ${G})`),v){let c=await ah(b);if(c)if(d)D(`Killing process on port 443 (PID ${c.pid}, name=${c.name})...`),await al(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}T=e(process.execPath,[u],{detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,DATA_DIR:B,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:G}}),_&&await _({mitmCertInstalled:!0}).catch(()=>{})}else s()?((T=e("sudo",["-S","-E","sh","-c",[`HOME=${H(i.homedir())}`,`DATA_DIR=${H(B)}`,`ROUTER_API_KEY=${H(a)}`,`MITM_ROUTER_BASE=${H(G)}`,"NODE_ENV=production",H(process.execPath),H(u)].join(" ")],{detached:!1,windowsHide:!0,stdio:["pipe","pipe","pipe"]})).stdin.write(`${b}
`),T.stdin.end()):T=e(process.execPath,[u],{detached:!1,windowsHide:!0,cwd:i.tmpdir(),stdio:["ignore","pipe","pipe"],env:{...process.env,DATA_DIR:B,ROUTER_API_KEY:a,NODE_ENV:"production",MITM_ROUTER_BASE:G}});T&&(U=T.pid,h.writeFileSync(J,String(U)),M=Date.now());let K=null;T&&(T.stdout.on("data",a=>{process.stdout.write(a)}),T.stderr.on("data",a=>{let b=a.toString().trim();b&&(v||!b.includes("Password:")&&!b.includes("password for"))&&(E(b),K=b),!v&&(b.includes("incorrect password")||b.includes("no password was provided"))&&(W(null),ab(),N=!0)}),T.on("exit",b=>{D(`Server exited (code: ${b})`),T=null,U=null;try{h.unlinkSync(J)}catch{}0===b||N||ak(a)}));let L=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(!L){if(T&&!T.killed){try{T.kill()}catch{}T=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(`${F} -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=K||`Check sudo password or port 443 access.${b}`;throw Error(`MITM server failed to start. ${c}`)}for(let[a,b]of(_&&await _({mitmCertInstalled:!0}).catch(()=>{}),D(`✅ Server healthy (PID: ${U||L.pid})`),Object.entries(q())))D(`🌐 DNS ${a}: ${b?"✅ active":"❌ inactive"}`);return await aa(!0,b),b&&W(b),{running:!0,pid:U}}async function an(a){N=!0,L=0,D("⏹ Stopping server...");let b=T,d=b&&!b.killed?b.pid:(()=>{try{return parseInt(h.readFileSync(J,"utf-8").trim(),10)}catch{return null}})();if(d&&X(d)&&(D(`Killing server (PID: ${d})...`),Y(d,!1,a),await new Promise(a=>setTimeout(a,1e3)),X(d)&&Y(d,!0,a)),T=null,U=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(J)}catch{}return await aa(!1,null),N=!1,{running:!1,pid:null}}async function ao(a,b){if(!(await aj()).running)throw Error("MITM server is not running. Start the server first.");let c=b||V()||await ac();return await m(a,c),await ad(a,!0),{success:!0}}a.exports={getMitmStatus:aj,startServer:am,stopServer:an,enableToolDNS:ao,disableToolDNS:async function a(a,b){let c=b||V()||await ac();return await n(a,c),await ad(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||V()||await ac();if(!e&&t())throw Error("Sudo password required to trust certificate");await d(e,b),e&&W(e)},startMitm:am,stopMitm:an,getCachedPassword:V,setCachedPassword:W,loadEncryptedPassword:ac,clearEncryptedPassword:ab,isSudoPasswordRequired:t,initDbHooks:function(a,b){$=a,_=b},restoreToolDNS:af,hasDnsPrivilege:ag,removeAllDNSEntriesSync:p}}};