"use strict";exports.id=182,exports.ids=[182],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:"arouter MITM Root CA"},{name:"organizationName",value:"arouter"},{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="arouter 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}/arouter-root-ca.crt`,Promise.resolve(d.existsSync(g)))}async function t(a,b){let c=`security delete-certificate -c "${q}" /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 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=`
    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 "${q}" -i "${a}" 2>/dev/null || \\
          certutil -d "$db" -A -t "C,," -n "${q}" -i "${a}" 2>/dev/null || true
        else
          certutil -d sql:"$db" -D -n "${q}" 2>/dev/null || \\
          certutil -d "$db" -D -n "${q}" 2>/dev/null || true
        fi
      fi
    done
  `;return new Promise(a=>{f(c,{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}/arouter-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}/arouter-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"],URL_PATTERNS:{antigravity:[":generateContent",":streamGenerateContent"],copilot:["/chat/completions","/v1/messages","/responses"]},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":null}}},26033:(a,b,c)=>{c(33873);let d=c(29021),{MITM_DIR:e}=c(82193),{generateRootCA:f,loadRootCA:g,generateLeafCert:h}=c(8578);a.exports={generateCert:async function a(){return await f()},getCertForDomain:function(a){try{let b=g(),c=h(a,b);return{key:c.key,cert:c.cert}}catch(b){return console.error(`Failed to generate cert for ${a}:`,b.message),null}},getCertParams:function(){let{ROOT_CA_CERT_PATH:a,ROOT_CA_KEY_PATH:b}=c(8578);return d.existsSync(a)&&d.existsSync(b)?{certPath:a,cert:d.readFileSync(a,"utf8"),key:d.readFileSync(b,"utf8")}: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),{runElevatedPowerShell:k,isAdmin:l,quotePs:m}=c(64809),n={antigravity:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com"],copilot:["api.individual.githubcopilot.com"]};function o(a,b,c){let d=`${a}.arouter.new`,e=`${a}.arouter.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 p="win32"===process.platform,q="darwin"===process.platform,r=p?h.join(process.env.SystemRoot||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts";function s(){if(p)return!1;try{return f("command -v sudo",{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function t(){if(p||!s())return!0;try{return f("sudo -n true",{stdio:"ignore",windowsHide:!0}),!0}catch{return!1}}function u(a,b){return new Promise((c,d)=>{let f=s(),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 v(a){p||(q?await u("dscacheutil -flushcache && killall -HUP mDNSResponder",a):await u("resolvectl flush-caches 2>/dev/null || true",a))}function w(a=null){try{let b=g.readFileSync(r,"utf8");if(a)return b.includes(a);return n.antigravity.every(a=>b.includes(a))}catch{return!1}}async function x(a,b){let c=n[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>!w(a));if(0===d.length)return void i(`🌐 DNS ${a}: already active`);try{if(p){let a=g.readFileSync(r,"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
`;if(l()){o(r,a,e);try{f("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}}else await k("ipconfig /flushdns | Out-Null")}else{let a=g.readFileSync(r,"utf8").replace(/[\r\n\s]+$/g,""),c=d.map(a=>`127.0.0.1 ${a}`).join("\n"),e=`${a}
${c}
`.replace(/'/g,"'\\''");await u(`printf '%s' '${e}' | tee ${r} > /dev/null`,b),await v(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 y(a,b){let c=n[a];if(!c)throw Error(`Unknown tool: ${a}`);let d=c.filter(a=>w(a));if(0===d.length)return void i(`🌐 DNS ${a}: already inactive`);try{if(p){let a=g.readFileSync(r,"utf8"),b=a.split(/\r?\n/).filter(a=>!d.some(b=>a.includes(b))).join("\r\n").replace(/[\r\n\s]+$/g,"")+"\r\n";if(l()){o(r,a,b);try{f("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}}else await k("ipconfig /flushdns | Out-Null")}else{let a=(g.readFileSync(r,"utf8").split(/\r?\n/).filter(a=>!d.some(b=>a.includes(b))).join("\n").replace(/[\r\n\s]+$/g,"")+"\n").replace(/'/g,"'\\''");await u(`printf '%s' '${a}' | tee ${r} > /dev/null`,b),await v(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 z(a){for(let b of Object.keys(n))try{await y(b,a)}catch(a){j(`DNS ${b}: failed to remove — ${a.message}`)}}a.exports={TOOL_HOSTS:n,addDNSEntry:x,removeDNSEntry:y,removeAllDNSEntries:z,removeAllDNSEntriesSync:function(){try{if(!g.existsSync(r))return;let a=Object.values(n).flat(),b=g.readFileSync(r,"utf8"),c=p?"\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(r,d,"utf8"),p)try{f("ipconfig /flushdns",{windowsHide:!0,stdio:"ignore"})}catch{}else if(q)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:u,isSudoAvailable:s,canRunSudoWithoutPassword:t,isSudoPasswordRequired:function(){return!p&&s()&&!t()},checkDNSEntry:w,checkAllDNSStatus:function(){try{let a=g.readFileSync(r,"utf8"),b={};for(let[c,d]of Object.entries(n))b[c]=d.every(b=>a.includes(b));return b}catch{return Object.fromEntries(Object.keys(n).map(a=>[a,!1]))}}}},82193:(a,b,c)=>{let d=c(29021),e=c(33873),f=c(21820),g="arouter";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}},87777:(a,b,c)=>{let d=c(94735),e=c(29021),f=c(33873),g=c(74075),{DATA_DIR:h}=c(82193),i=new d,j=[];function k(a,b){j.push({type:a,message:b}),j.length>100&&j.shift(),i.emit("log",{type:a,message:b})}function l(a){console.error(`[MITM ERROR] ${a}`),k("error",a)}let m=f.join(h,"logs","mitm");function n(a,b,c,d){e.mkdirSync(m,{recursive:!0});let g=b.replace(/[^a-zA-Z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"");return f.join(m,`${a}_${g}_${d}_${c}.txt`)}a.exports={log:function(a){console.log(`[MITM] ${a}`),k("log",a)},err:l,onLog:function(a){j.forEach(b=>a(b.message)),i.on("log",b=>a(b.message))},dumpRequest:function(a,b,c,d){try{let f=Date.now();a.mitmRequestId=f,a.mitmTool=c||"unknown";let g=n(c||"unknown",a.url,"req",f),h=`${a.method} https://${d}${a.url} HTTP/${a.httpVersion}`,i=Object.entries(a.headers).map(([a,b])=>`${a}: ${b}`).join("\n"),j="";if(b&&b.length>0)try{j=JSON.stringify(JSON.parse(b.toString()),null,2)}catch{j=b.toString("utf8")}e.writeFileSync(g,`${h}
${i}

${j}`)}catch(a){l(`Failed to dump request: ${a.message}`)}},createResponseDumper:function(a,b){let c,d=a.mitmRequestId||Date.now(),f=n(a.mitmTool||"unknown",`${a.url}_${b}`,"res",d);try{e.mkdirSync(m,{recursive:!0}),c=e.openSync(f,"w")}catch(a){return l(`Failed to open dump file ${f}: ${a.message}`),null}let h=null;return{writeHeader(b,d){try{let f=Object.entries(d).map(([a,b])=>`${a}: ${b}`).join("\n");e.writeSync(c,`HTTP/${a.httpVersion} ${b}
${f}

`);let i=(d["content-encoding"]||"").toLowerCase();"gzip"===i?h=g.createGunzip():"deflate"===i?h=g.createInflate():"br"===i&&(h=g.createBrotliDecompress()),h&&(h.on("data",a=>{try{e.writeSync(c,a)}catch(a){}}),h.on("error",a=>{try{e.writeSync(c,`
[Decompression Error: ${a.message}]
`)}catch(a){}}))}catch(a){}},writeChunk(a){try{if(!a)return;h?h.write(a):e.writeSync(c,a)}catch(a){}},end(){try{h?(h.end(),setTimeout(()=>{try{e.closeSync(c)}catch(a){}},50)):e.closeSync(c)}catch(a){}}}},clearDumpDir:function(){try{if(e.existsSync(m)){let a=e.readdirSync(m);a.length>100&&a.map(a=>({name:a,time:e.statSync(f.join(m,a)).mtime.getTime()})).sort((a,b)=>b.time-a.time).slice(100).forEach(a=>e.unlinkSync(f.join(m,a.name)))}}catch(a){}}}},96182:(a,b,c)=>{let d=c(29021),e=c(33873),{spawn:f,execSync:g}=c(79646),h=c(81630),{getCertParams:i}=c(26033),{addDNSEntry:j,removeDNSEntry:k,checkDNSEntry:l,checkAllDNSStatus:m,TOOL_HOSTS:n,removeAllDNSEntriesSync:o,isSudoAvailable:p,canRunSudoWithoutPassword:q,isSudoPasswordRequired:r}=c(66936),{installCert:s,uninstallCert:t,checkCertInstalled:u}=c(9631),{MITM_DIR:v,DATA_DIR:w}=c(82193),{log:x,err:y}=c(87777),{isAdmin:z}=c(64809),{LSOF_BIN:A}=c(17511),B=e.join(v,"mitm.pid"),C=e.join(__dirname,"server.js"),D="win32"===process.platform,E="darwin"===process.platform,F=null,G=null;function H(){return(0,c(19713).machineIdSync)()}function I(){let a=e.join(w,"db.json");try{if(!d.existsSync(a))return null;let b=JSON.parse(d.readFileSync(a,"utf8"));return function(a){if(!a)return null;try{let b=c(55511),[d,e]=a.split(":"),f=Buffer.from(d,"hex"),g=b.createDecipheriv("aes-256-cbc",Buffer.from(H().substring(0,32).padEnd(32,"0")),f),h=g.update(e,"hex","utf8");return h+=g.final("utf8")}catch(a){return null}}(b.mitmSudoPassword)}catch(a){return null}}function J(){let a=e.join(w,"db.json");try{if(!d.existsSync(a))return;let b=JSON.parse(d.readFileSync(a,"utf8"));b.mitmSudoPassword&&(delete b.mitmSudoPassword,d.writeFileSync(a,JSON.stringify(b,null,2),"utf8"),x("\uD83D\uDD11 Cleared invalid sudo password from storage"))}catch(a){y(`Failed to clear sudo password: ${a.message}`)}}let K=e.join(v,"dns-state.json");function L(){return D?z():!!p()&&(q()||!!I())}async function M(a){if(!L())return void x("\uD83C\uDF10 DNS Restore: Skipped (no privilege / no password available)");let b=function(){try{if(d.existsSync(K))return JSON.parse(d.readFileSync(K,"utf8"))}catch(a){y(`Failed to load DNS state: ${a.message}`)}return{}}(),c=a||I();for(let[a,d]of Object.entries(b))if(d&&n[a])try{await j(a,c),x(`🌐 DNS Restore: Re-enabled ${a}`)}catch(b){y(`🌐 DNS Restore: Failed to enable ${a} - ${b.message}`)}}function N(){try{if(D){let a=g("netstat -ano | findstr :443",{encoding:"utf8",windowsHide:!0}).split("\n").find(a=>a.includes("LISTENING"));if(!a)return null;let b=a.trim().split(/\s+/).pop();if(!b)return null;return g(`tasklist /fi "pid eq ${b}" /fo csv /nh`,{encoding:"utf8",windowsHide:!0}).split(",")[0].replace(/"/g,"")||"unknown"}if(A){let a=g(`${A} -nP -iTCP:443 -sTCP:LISTEN -t`,{encoding:"utf8",windowsHide:!0}).trim();if(a){let b=a.split("\n")[0];return g(`ps -p ${b} -o comm=`,{encoding:"utf8",windowsHide:!0}).trim()||"unknown"}}return null}catch{return null}}function O(){let a=d.existsSync(B)&&P(parseInt(d.readFileSync(B,"utf8"),10));if(!a&&F)try{let a=N();if(a&&a.includes("node"))return new Promise(a=>{h.get("http://localhost:20128/health",b=>{200===b.statusCode?(x("Recovered MITM status via health check"),a({running:!0,port:443,hasCert:!0,dns:m()})):a({running:!1,port:443,hasCert:!1,dns:m()})}).on("error",()=>{a({running:!1,port:443,hasCert:!1,dns:m()})})})}catch(a){}let b=m(),c=!1;try{let a=i();c=!!(a&&a.cert)}catch(a){}return Promise.resolve({running:a,port:443,hasCert:c,dns:b})}function P(a){if(!a)return!1;try{return process.kill(a,0),!0}catch(a){return!1}}async function Q(a){if(a)try{D?g(`taskkill /PID ${a} /F /T`,{stdio:"ignore",windowsHide:!0}):(process.kill(a,"SIGTERM"),await new Promise(a=>setTimeout(a,1e3)),P(a)&&process.kill(a,"SIGKILL"))}catch(b){y(`[Manager] Failed to kill PID ${a}: ${b.message}`)}}async function R(a,b,c=!1){if((await O()).running&&!F&&d.existsSync(B))return x("Server already running, adopting process..."),{success:!0};let j=N();if(j&&"unknown"!==j){if(j.includes("node")||j.includes(process.title))x("Port 443 owned by another node process, killing...");else if(!c)throw Error(`Port 443 is currently in use by: ${j}. MITM server cannot start.`)}let k=i(),l=b||I();try{await s(l,k.certPath)}catch(a){throw(a.message.includes("password")||a.message.includes("canceled"))&&J(),a}if(E)try{var m;g(`launchctl setenv NODE_EXTRA_CA_CERTS ${!(m=k.certPath)?"''":`'${m.replace(/'/g,"'\\''")}'`}`)}catch(a){y(`Failed to set NODE_EXTRA_CA_CERTS via launchctl: ${a.message}`)}else if(D)try{g(`setx NODE_EXTRA_CA_CERTS "${k.certPath}"`,{windowsHide:!0})}catch(a){y(`Failed to set NODE_EXTRA_CA_CERTS via setx: ${a.message}`)}let n=function(){let a=process.env.MITM_ROUTER_BASE||"http://localhost:20128",b=e.join(w,"db.json");try{if(d.existsSync(b)){let c=JSON.parse(d.readFileSync(b,"utf8"));c.mitmRouterBaseUrl&&(a=c.mitmRouterBaseUrl)}}catch(a){}return a.replace(/\/+$/,"")}(),o={...process.env,ROUTER_API_KEY:a||process.env.ROUTER_API_KEY||"",MITM_ROUTER_BASE:n},p=function(){let a=e.join(w,"runtime","mitm");d.mkdirSync(a,{recursive:!0});let b=e.join(a,"server.js");try{let a=d.statSync(C),c=null;try{c=d.statSync(b)}catch(a){}(!c||a.mtimeMs>c.mtimeMs)&&(d.copyFileSync(C,b),x("✅ Copied server.js to runtime directory"))}catch(a){return y(`Failed to copy runtime server: ${a.message}`),C}return b}();x(`Starting MITM server... (Target: ${n})`);let q=f("node",[p],{detached:!0,stdio:"ignore",env:o,windowsHide:!0});return q.unref(),d.writeFileSync(B,q.pid.toString()),F=q,x(`✅ MITM Server started (PID: ${q.pid})`),new Promise((a,b)=>{let c=0,d=setInterval(()=>{c++,h.get("http://localhost:20128/health",b=>{200===b.statusCode&&(clearInterval(d),a({success:!0,pid:q.pid}))}).on("error",()=>{c>10&&(clearInterval(d),b(Error("Server failed to start in time")))})},500)})}async function S(){try{if((z()||q()||I())&&o(),E)try{g("launchctl unsetenv NODE_EXTRA_CA_CERTS")}catch(a){}}catch(a){y(`Cleanup error during stop: ${a.message}`)}if(F&&(await Q(F.pid),F=null),d.existsSync(B)){let a=parseInt(d.readFileSync(B,"utf8"),10);await Q(a),d.unlinkSync(B)}return G&&(clearInterval(G),G=null),x("\uD83D\uDED1 MITM Server stopped"),{success:!0}}async function T(a,b,c){let e=c||I();try{b?await j(a,e):await k(a,e);try{let c={};d.existsSync(K)&&(c=JSON.parse(d.readFileSync(K,"utf8"))),c[a]=b,d.writeFileSync(K,JSON.stringify(c,null,2),"utf8")}catch(b){y(`Failed to save DNS state for ${a}: ${b.message}`)}}catch(a){throw(a.message.includes("password")||a.message.includes("canceled"))&&J(),a}}!function a(){let b=h.request("http://localhost:20128/_mitm_logs",a=>{200===a.statusCode&&a.on("data",a=>{a.toString().split("\n").forEach(a=>{if(a.startsWith("data: "))try{let b=JSON.parse(a.slice(6));"log"===b.type?x(b.message):"error"===b.type&&y(b.message)}catch(a){}})})});b.on("error",()=>{setTimeout(a,2e3)}),b.end()}(),a.exports={getMitmStatus:O,startServer:R,stopServer:S,toggleTool:T,getCertParams:i,encryptPassword:function(a){if(!a)return null;let b=c(55511),d=b.randomBytes(16),e=b.createCipheriv("aes-256-cbc",Buffer.from(H().substring(0,32).padEnd(32,"0")),d),f=e.update(a,"utf8","hex");return f+=e.final("hex"),`${d.toString("hex")}:${f}`},uninstallCert:async a=>t(a||I(),i().certPath),clearEncryptedPassword:J,isSudoPasswordRequired:r,restoreToolDNS:M,hasDnsPrivilege:L,removeAllDNSEntriesSync:o,startMitm:R,stopMitm:S,initDbHooks:()=>{},loadEncryptedPassword:async()=>I()}}};