@stacksjs/rpx 0.11.12 → 0.11.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{$ as L2,A as z_,B as V2,C as M_,D as Y_,E as $_,F as R2,G as G_,H as W_,I as E2,J as z2,K as M2,L as S2,M as T2,N as F2,O as I2,P as w2,Q as j2,R as H2,S as k2,T as C2,U as q2,V as x2,W as U2,X as f2,Y as y2,Z as O2,_ as P2,a as J,aa as h2,b as B_,ba as c2,c as i_,ca as u2,d as n_,da as m2,e as t_,ea as v2,f as r_,fa as b2,g as s_,ga as l2,h as o_,ha as a2,i as e_,ia as d2,j as _2,ja as p2,k as D2,ka as g2,l as B2,la as i2,m as K2,ma as X_,n as N2,na as n2,o as Y2,oa as t2,p as $2,q as G2,r as W2,s as X2,t as J2,u as Q2,v as Z2,w as K_,x as A2,y as c,z as N_}from"./chunk-9dndasyk.js";import{Aa as NB,Ba as YB,Ca as $B,Da as GB,pa as E_,qa as m,ra as sD,sa as K,ta as oD,ua as C,va as eD,wa as _B,xa as DB,ya as BB,za as KB}from"./chunk-zs1tyy8z.js";import{execSync as v_}from"node:child_process";import*as O from"node:http";import*as y_ from"node:http2";import*as O_ from"node:net";import*as F from"node:process";var n=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,H={bold:n(1,22),dim:n(2,22),green:n(32,39),cyan:n(36,39)};import*as j_ from"node:fs";import*as H_ from"node:path";import*as k from"node:process";function k_(D){let _=D.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return _.length>0?_:"rpx"}async function t(D){if(D.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let _=D.verbose??!1,B=D.registryDir,N=new Set,Y=D.proxies.map((R)=>{let $=R.id??k_(R.to);if(!$_($))throw Error(`invalid registry id "${$}" derived from to="${R.to}"`);if(N.has($))throw Error(`duplicate registry id "${$}" — set an explicit \`id\` on one of the proxies`);return N.add($),{...R,id:$}}),W=new Date().toISOString();for(let R of Y)await G_({id:R.id,from:R.from,to:R.to,pid:D.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:W,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites},B,_);let G=await X_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let R of Y)J.success(`https://${R.to} → ${R.from}`);if(J.info(`(via rpx daemon pid=${G.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let V=!1,X=B??Y_(),A=Y.map((R)=>R.id),T=async()=>{if(V)return;V=!0;for(let R of A)await W_(R,B,_).catch(($)=>{K("runner",`removeEntry(${R}) failed: ${$}`,_)})},I=(R)=>{K("runner",`received ${R}, unregistering ${A.length} entries`,_),T().finally(()=>k.exit(0))};k.once("SIGINT",I),k.once("SIGTERM",I),k.once("exit",()=>{if(V)return;for(let R of A)try{j_.unlinkSync(H_.join(X,`${R}.json`))}catch{}}),await new Promise(()=>{})}import{exec as h_}from"node:child_process";import f from"node:fs";import q_ from"node:os";import Q_ from"node:path";import*as v from"node:process";import{promisify as c_}from"node:util";var r=c_(h_);function C_(D){let _=D.trim().toLowerCase();return _==="localhost"||_.endsWith(".localhost")||_.endsWith(".localhost.")}var j=v.platform==="win32"?Q_.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",J_=!1;async function s(D){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");let _=m(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:N}=await r(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return J_=!0,N}if(J_)try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return N}catch(N){K("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return J_=!0,N}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(N){throw Error(`Failed to execute sudo command: ${N.message}`)}}async function L(D,_){let B=D.filter((Y)=>!C_(Y)),N=D.filter((Y)=>C_(Y));if(N.length>0)K("hosts",`Skipping /etc/hosts for loopback dev names: ${N.join(", ")}`,_);if(B.length===0)return;K("hosts",`Adding hosts: ${B.join(", ")}`,_),K("hosts",`Using hosts file at: ${j}`,_);try{let Y;try{Y=await f.promises.readFile(j,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{Y=await s(`cat "${j}"`)}catch(X){throw console.log(" Could not read hosts file — skipping hosts setup"),K("hosts",`sudo read also failed: ${X}`,_),Error(`Cannot read hosts file: ${X}`)}}let W=B.filter((X)=>{let A=`127.0.0.1 ${X}`,T=`::1 ${X}`;return!Y.includes(A)&&!Y.includes(T)});if(W.length===0){K("hosts","All hosts already exist in hosts file",_);return}let G=W.map((X)=>`
1
+ import{$ as L2,A as z_,B as V2,C as M_,D as Y_,E as $_,F as R2,G as G_,H as W_,I as E2,J as z2,K as M2,L as S2,M as T2,N as F2,O as I2,P as w2,Q as j2,R as H2,S as k2,T as C2,U as q2,V as x2,W as U2,X as f2,Y as y2,Z as O2,_ as P2,a as J,aa as h2,b as B_,ba as c2,c as i_,ca as u2,d as n_,da as m2,e as t_,ea as v2,f as r_,fa as b2,g as s_,ga as l2,h as o_,ha as a2,i as e_,ia as d2,j as _2,ja as p2,k as D2,ka as g2,l as B2,la as i2,m as K2,ma as X_,n as N2,na as n2,o as Y2,oa as t2,p as $2,q as G2,r as W2,s as X2,t as J2,u as Q2,v as Z2,w as K_,x as A2,y as c,z as N_}from"./chunk-pncxrxde.js";import{Aa as NB,Ba as YB,Ca as $B,Da as GB,pa as E_,qa as m,ra as sD,sa as K,ta as oD,ua as C,va as eD,wa as _B,xa as DB,ya as BB,za as KB}from"./chunk-zs1tyy8z.js";import{execSync as v_}from"node:child_process";import*as O from"node:http";import*as y_ from"node:http2";import*as O_ from"node:net";import*as F from"node:process";var n=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,H={bold:n(1,22),dim:n(2,22),green:n(32,39),cyan:n(36,39)};import*as j_ from"node:fs";import*as H_ from"node:path";import*as k from"node:process";function k_(D){let _=D.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return _.length>0?_:"rpx"}async function t(D){if(D.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let _=D.verbose??!1,B=D.registryDir,N=new Set,Y=D.proxies.map((R)=>{let $=R.id??k_(R.to);if(!$_($))throw Error(`invalid registry id "${$}" derived from to="${R.to}"`);if(N.has($))throw Error(`duplicate registry id "${$}" — set an explicit \`id\` on one of the proxies`);return N.add($),{...R,id:$}}),W=new Date().toISOString();for(let R of Y)await G_({id:R.id,from:R.from,to:R.to,pid:D.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:W,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites},B,_);let G=await X_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let R of Y)J.success(`https://${R.to} → ${R.from}`);if(J.info(`(via rpx daemon pid=${G.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let V=!1,X=B??Y_(),A=Y.map((R)=>R.id),T=async()=>{if(V)return;V=!0;for(let R of A)await W_(R,B,_).catch(($)=>{K("runner",`removeEntry(${R}) failed: ${$}`,_)})},I=(R)=>{K("runner",`received ${R}, unregistering ${A.length} entries`,_),T().finally(()=>k.exit(0))};k.once("SIGINT",I),k.once("SIGTERM",I),k.once("exit",()=>{if(V)return;for(let R of A)try{j_.unlinkSync(H_.join(X,`${R}.json`))}catch{}}),await new Promise(()=>{})}import{exec as h_}from"node:child_process";import f from"node:fs";import q_ from"node:os";import Q_ from"node:path";import*as v from"node:process";import{promisify as c_}from"node:util";var r=c_(h_);function C_(D){let _=D.trim().toLowerCase();return _==="localhost"||_.endsWith(".localhost")||_.endsWith(".localhost.")}var j=v.platform==="win32"?Q_.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",J_=!1;async function s(D){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");let _=m(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:N}=await r(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return J_=!0,N}if(J_)try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return N}catch(N){K("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return J_=!0,N}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(N){throw Error(`Failed to execute sudo command: ${N.message}`)}}async function L(D,_){let B=D.filter((Y)=>!C_(Y)),N=D.filter((Y)=>C_(Y));if(N.length>0)K("hosts",`Skipping /etc/hosts for loopback dev names: ${N.join(", ")}`,_);if(B.length===0)return;K("hosts",`Adding hosts: ${B.join(", ")}`,_),K("hosts",`Using hosts file at: ${j}`,_);try{let Y;try{Y=await f.promises.readFile(j,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{Y=await s(`cat "${j}"`)}catch(X){throw console.log(" Could not read hosts file — skipping hosts setup"),K("hosts",`sudo read also failed: ${X}`,_),Error(`Cannot read hosts file: ${X}`)}}let W=B.filter((X)=>{let A=`127.0.0.1 ${X}`,T=`::1 ${X}`;return!Y.includes(A)&&!Y.includes(T)});if(W.length===0){K("hosts","All hosts already exist in hosts file",_);return}let G=W.map((X)=>`
2
2
  # Added by rpx
3
3
  127.0.0.1 ${X}
4
4
  ::1 ${X}`).join(`
5
5
  `),V=Q_.join(q_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,Y+G,"utf8"),await s(`cat "${V}" | tee "${j}" > /dev/null`),console.log(` Hosts updated: ${W.join(", ")}`)}catch(X){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),W.forEach((A)=>{console.log(` 127.0.0.1 ${A}`),console.log(` ::1 ${A}`)}),console.log(` Or run: sudo nano ${j}`)}finally{try{await f.promises.unlink(V)}catch{}}}catch(Y){K("hosts",`Failed to manage hosts file: ${Y.message}`,_)}}async function Z_(D,_){K("hosts",`Removing hosts: ${D.join(", ")}`,_);try{let B;try{B=await f.promises.readFile(j,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await s(`cat "${j}"`)}catch(X){throw K("hosts",`sudo read also failed: ${X}`,_),Error(`Cannot read hosts file: ${X}`)}}let N=B.split(`
6
6
  `),Y=!1,W=N.filter((X)=>{if(D.some((T)=>X.includes(` ${T}`)&&(X.includes("127.0.0.1")||X.includes("::1"))))return Y=!0,!1;if(X.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){K("hosts","No matching hosts found to remove",_);return}while(W[W.length-1]?.trim()==="")W.pop();let G=`${W.join(`
7
7
  `)}
8
- `,V=Q_.join(q_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,G,"utf8"),await s(`cat "${V}" | tee "${j}" > /dev/null`),K("hosts","Hosts removed successfully",_)}catch(X){K("hosts","Could not clean up hosts file automatically",_)}finally{try{await f.promises.unlink(V)}catch(X){K("hosts",`Failed to remove temporary file: ${X}`,_)}}}catch(B){K("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function h(D,_){K("hosts",`Checking hosts: ${D}`,_);let B;try{B=await f.promises.readFile(j,"utf-8")}catch(N){K("hosts",`Error reading hosts file: ${N}`,_);try{let Y=m(),W;if(Y)W=`echo '${Y}' | sudo -S cat "${j}" 2>/dev/null`;else W=`sudo -n cat "${j}" 2>/dev/null || cat "${j}" 2>/dev/null || echo ""`;let{stdout:G}=await r(W);B=G}catch(Y){return K("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,_),D.map(()=>!1)}}return D.map((N)=>{let Y=`127.0.0.1 ${N}`,W=`::1 ${N}`;return B.includes(Y)||B.includes(W)})}import*as o from"node:net";function x(D,_,B){return K("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((N)=>{let Y=o.createServer(),W=setTimeout(()=>{K("port",`Checking port ${D} timed out, assuming it's in use`,B),Y.close(),N(!0)},3000);Y.once("error",(G)=>{if(clearTimeout(W),G.code==="EADDRINUSE")K("port",`Port ${D} is in use`,B),N(!0);else K("port",`Error checking port ${D}: ${G.message}`,B),N(!0)}),Y.once("listening",()=>{clearTimeout(W),K("port",`Port ${D} is available`,B),Y.close(),N(!1)});try{Y.listen(D,_)}catch(G){clearTimeout(W),K("port",`Exception checking port ${D}: ${G}`,B),N(!0)}})}async function U_(D,_,B,N=50){K("port",`Finding available port starting from ${D} (max attempts: ${N})`,B);let Y=D,W=0;while(W<N){if(W++,!await x(Y,_,B))return K("port",`Found available port: ${Y} after ${W} attempts`,B),Y;K("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${W}/${N})`,B),Y++}throw Error(`Unable to find available port after ${N} attempts starting from ${D}`)}function x_(D,_,B=5000,N){return K("port",`Testing connection to ${_}:${D}`,N),new Promise((Y)=>{let W=o.connect({host:_,port:D,timeout:B});W.once("connect",()=>{K("port",`Successfully connected to ${_}:${D}`,N),W.end(),Y(!0)}),W.once("timeout",()=>{K("port",`Connection to ${_}:${D} timed out`,N),W.destroy(),Y(!1)}),W.once("error",(G)=>{K("port",`Failed to connect to ${_}:${D}: ${G.message}`,N),W.destroy(),Y(!1)})})}class b{usedPorts=new Set;hostname;verbose;maxRetries;constructor(D="0.0.0.0",_,B=50){this.hostname=D,this.verbose=_,this.maxRetries=B}async getNextAvailablePort(D,_=!1){if(this.usedPorts.has(D))return this.findNextAvailablePort(D+1,_);if(await x(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await x_(D,this.hostname,3000,this.verbose))return K("port",`Port ${D} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(D+1,_)}return this.usedPorts.add(D),D}async findNextAvailablePort(D,_=!1){let B=await U_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await x_(B,this.hostname,3000,this.verbose))if(B<D+this.maxRetries)return this.findNextAvailablePort(B+1,_);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(B),B}releasePort(D){K("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var u_=new b;import{spawn as m_}from"node:child_process";import*as y from"node:process";class e{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){K("start",`Process ${D} is already running`,B);return}let[N,...Y]=_.command.split(" "),W=_.cwd||y.cwd();K("start",`Starting process ${D}:`,B),K("start",` Command: ${N} ${Y.join(" ")}`,B),K("start",` Working directory: ${W}`,B),K("start",` Environment variables: ${C(_.env)}`,B);let G=m_(N,Y,{cwd:W,env:{...y.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:W,process:G,env:_.env}),new Promise((V,X)=>{if(G.on("error",(A)=>{if(!this.isShuttingDown)K("start",`Process ${D} failed to start: ${A}`,B),this.processes.delete(D),X(A),y.emit("SIGINT")}),G.on("exit",(A)=>{if(!this.isShuttingDown&&A!==null&&A!==0)K("start",`Process ${D} exited with code ${A}`,B),this.processes.delete(D),X(Error(`Process ${D} exited with code ${A}`)),y.emit("SIGINT")}),B)G.stdout?.on("data",(A)=>{K("process",`[${D}] ${A.toString().trim()}`,!0)}),G.stderr?.on("data",(A)=>{K("process",`[${D}] ERR: ${A.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&G.killed)this.processes.delete(D),X(Error(`Process ${D} was killed during startup`));else K("start",`Process ${D} started successfully`,B),V()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){K("start",`No process found for ${D}`,_);return}return K("start",`Stopping process ${D}`,_),new Promise((N)=>{if(!B.process){N();return}B.process.once("exit",()=>{this.processes.delete(D),K("start",`Process ${D} stopped`,_),N()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){K("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){K("start",`Error stopping process ${D}: ${Y}`,_),this.processes.delete(D),N()}})}async stopAll(D){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,K("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((N)=>{J.error(`Failed to stop process ${B}:`,N)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var VD=new e;var D_=new e,b_="0.12.0",l_=new b("0.0.0.0"),l=new Set,A_=!1,__=null,V_=null;async function d(D){if(A_)return K("cleanup","Cleanup already in progress, skipping",D?.verbose),V_||Promise.resolve();A_=!0,K("cleanup","Starting cleanup process",D?.verbose),V_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),J.info("Shutting down proxy servers...");let _=[],B=Array.from(l).map((N)=>new Promise((Y)=>{N.close(()=>{K("cleanup","Server closed successfully",D?.verbose),Y()})}));if(_.push(...B),D?.hosts&&D.domains?.length){K("cleanup","Cleaning up hosts file entries",D?.verbose),K("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let N=D.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(K("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,D?.verbose),N.length>0)J.info("Cleaning up hosts file entries..."),_.push(Z_(N,D?.verbose).then(()=>{K("cleanup",`Removed hosts entries for ${N.join(", ")}`,D?.verbose)}).catch((Y)=>{K("cleanup",`Failed to remove hosts entries: ${Y}`,D?.verbose),J.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,Y)}))}if(D?.certs&&D.domains?.length){K("cleanup","Cleaning up SSL certificates",D?.verbose),J.info("Cleaning up SSL certificates...");let N=D.domains.map(async(Y)=>{try{await z_(Y,D?.verbose),K("cleanup",`Removed certificates for ${Y}`,D?.verbose)}catch(W){K("cleanup",`Failed to remove certificates for ${Y}: ${W}`,D?.verbose),J.warn(`Failed to clean up certificates for ${Y}:`,W)}});_.push(...N)}await Promise.allSettled(_),K("cleanup","All cleanup tasks completed successfully",D?.verbose),J.success("All cleanup tasks completed successfully")}catch(_){K("cleanup",`Error during cleanup: ${_}`,D?.verbose),J.error("Error during cleanup:",_)}finally{if(__)__();__=null,A_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(F.env.NODE_ENV!=="test"&&F.env.BUN_ENV!=="test"&&!_)F.exit(0)}return V_}var R_=!1;function S_(D){if(R_){K("signal",`Received second ${D} signal, forcing exit`,!0),F.exit(1);return}R_=!0,K("signal",`Received ${D} signal, initiating cleanup`,!0),d().catch((_)=>{K("signal",`Cleanup failed after ${D}: ${_}`,!0),F.exit(1)}).finally(()=>{R_=!1})}F.once("SIGINT",()=>S_("SIGINT"));F.once("SIGTERM",()=>S_("SIGTERM"));F.on("uncaughtException",(D)=>{K("process",`Uncaught exception: ${D}`,!0),J.error("Uncaught exception:",D),S_("uncaughtException")});async function a(D,_,B,N=5){K("connection",`Testing connection to ${D}:${_} (retries left: ${N})`,B);let Y=15000,W=Date.now();if(F.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let G=()=>new Promise((V,X)=>{let A=O_.connect({host:D,port:_,timeout:3000});A.once("connect",()=>{K("connection",`Successfully connected to ${D}:${_}`,B),A.end(),V()}),A.once("timeout",()=>{K("connection",`Connection to ${D}:${_} timed out`,B),A.destroy(),X(Error("Connection timed out"))}),A.once("error",(T)=>{K("connection",`Failed to connect to ${D}:${_}: ${T}`,B),A.destroy(),X(T)})});try{await G()}catch(V){if(Date.now()-W>Y){K("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),J.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(V.code==="ECONNREFUSED"&&N>0)return K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,B),await new Promise((A)=>setTimeout(A,2000)),a(D,_,B,N-1);if(N>0)try{K("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((A,T)=>{let I=O.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(R)=>{K("connection",`Received HTTP response with status: ${R.statusCode}`,B),A()});I.on("error",(R)=>T(R)),I.on("timeout",()=>{I.destroy(),T(Error("HTTP request timed out"))}),I.end()}),K("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(A){return K("connection",`HTTP request to ${D}:${_} failed: ${A}`,B),K("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,B),await new Promise((T)=>setTimeout(T,2000)),a(D,_,B,N-1)}let X=`Failed to connect to ${D}:${_} after ${5-N} attempts: ${V.message}`;K("connection",`${X}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),J.warn(X),J.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function T_(D){K("server",`Starting server with options: ${C(D)}`,D.verbose);let _=new URL((D.from?.startsWith("http")?D.from:`http://${D.from}`)||"localhost:5173"),B=new URL((D.to?.startsWith("http")?D.to:`http://${D.to}`)||"rpx.localhost"),N=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),Y=[B.hostname];if(!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){K("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await h(Y,D.verbose))[0]){J.info(`Adding ${B.hostname} to hosts file...`),J.info("This may require sudo/administrator privileges");try{await L(Y,D.verbose)}catch(V){if(J.error("Failed to add hosts entry:",V.message),J.warn("You can manually add this entry to your hosts file:"),J.warn(`127.0.0.1 ${B.hostname}`),J.warn(`::1 ${B.hostname}`),F.platform==="win32")J.warn("On Windows:"),J.warn("1. Run notepad as administrator"),J.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else J.warn("On Unix systems:"),J.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch(G){J.error("Failed to check hosts file:",G.message)}}try{await a(_.hostname,N,D.verbose)}catch(G){K("server",`Connection test failed: ${G}`,D.verbose),J.error(G.message),J.warn("Continuing with proxy setup despite connection test failure..."),J.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let W=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=N_({...D,to:B.hostname});if(W=await c({...D,to:B.hostname,https:D.https}),!W){if(K("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await K_({...D,from:_.toString(),to:B.hostname,https:D.https}),W=await c({...D,to:B.hostname,https:D.https}),!W)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch(G){throw K("server",`SSL setup failed: ${G}`,D.verbose),G}K("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await d_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:N,sourceUrl:{hostname:_.hostname,host:_.host},ssl:W})}async function a_(D,_,B,N,Y,W,G,V,X,A,T){K("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${A}`,X);function I(Z){let z={};for(let[Q,E]of Object.entries(Z))if(!Q.startsWith(":"))z[Q]=E;return z}let R=(Z,z)=>{K("request",`Incoming request: ${Z.method} ${Z.url}`,X);let Q=Z.url||"/",E=Z.method||"GET";if(Z instanceof y_.Http2ServerRequest){let S=Z.headers;E=S[":method"]||E,Q=S[":path"]||Q}if(A){if(!Q.match(/\.[a-z0-9]+$/i))if(Q.endsWith("/"))Q=`${Q}index.html`;else Q=`${Q}.html`}let w=I(Z.headers);if(T)w.host=`${W.hostname}:${B}`,K("request",`Changed origin: setting host header to ${w.host}`,X);let U={hostname:W.hostname,port:B,path:Q,method:E,headers:w};K("request",`Proxy request options: ${C(U)}`,X);let p=O.request(U,(S)=>{if(K("response",`Proxy response received with status ${S.statusCode}`,X),A&&S.statusCode===404){let q=[];if(Q.endsWith(".html"))q.push(Q.slice(0,-5));else if(!Q.match(/\.[a-z0-9]+$/i))q.push(`${Q}.html`);if(!Q.endsWith("/"))q.push(`${Q}/index.html`);if(q.length>0){K("cleanUrls",`Trying alternative paths: ${q.join(", ")}`,X);let u=(g)=>{if(g.length===0){z.writeHead(S.statusCode||404,S.headers),S.pipe(z);return}let I_=g[0],L_={...U,path:I_},w_=O.request(L_,(i)=>{if(i.statusCode===200)K("cleanUrls",`Found matching path: ${I_}`,X),z.writeHead(i.statusCode,i.headers),i.pipe(z);else u(g.slice(1))});w_.on("error",()=>u(g.slice(1))),w_.end()};u(q);return}}let P={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};z.writeHead(S.statusCode||500,P),S.pipe(z)});p.on("error",(S)=>{K("request",`Proxy request failed: ${S}`,X),J.error("Proxy request failed:",S),z.writeHead(502),z.end(`Proxy Error: ${S.message}`)}),Z.pipe(p)};if(K("server",`Creating server with SSL config: ${!!G}`,X),G)return new Promise((Z,z)=>{try{let Q=Bun.serve({port:N,hostname:Y,tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(E){let w=new URL(E.url);K("request",`Bun.serve received: ${E.method} ${w.pathname}`,X);let U=`http://${W.host}`,p=new URL(w.pathname+w.search,U);try{let S=new Headers(E.headers);if(S.set("host",W.host),T)S.set("origin",U);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",_);let P=await fetch(p.toString(),{method:E.method,headers:S,body:E.body,redirect:"manual"}),q=new Headers(P.headers);if(A&&w.pathname.endsWith(".html")){let u=w.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:u}})}return new Response(P.body,{status:P.status,statusText:P.statusText,headers:q})}catch(S){return K("request",`Proxy error: ${S}`,X),new Response(`Proxy Error: ${S}`,{status:502})}},error(E){return K("server",`Bun.serve error: ${E}`,X),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!0,cleanUrls:A,verbose:X}),Z()}catch(Q){z(Q)}});let $=O.createServer(R);function M(Z){return l.add(Z),new Promise((z,Q)=>{Z.listen(N,Y,()=>{K("server",`Server listening on port ${N}`,X),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!!G,cleanUrls:A,verbose:X}),z()}),Z.on("error",(E)=>{K("server",`Server error: ${E}`,X),Q(E)})})}return M($)}async function d_(D){K("setup",`Setting up reverse proxy: ${C(D)}`,D.verbose);let{from:_,to:B,fromPort:N,sourceUrl:Y,ssl:W,verbose:G,cleanup:V,vitePluginUsage:X,changeOrigin:A,cleanUrls:T}=D,I=80,R=443,$="0.0.0.0",M=D.portManager||l_;try{if(B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await h([B],G))[0]){J.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await L([B],G),J.success(`Added ${B} to your hosts file.`)}catch(w){J.error(`Failed to add ${B} to your hosts file: ${w}`),J.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(F.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await h([B],G))[0]){K("hosts",`${B} not found in hosts file, adding...`,G);try{await L([B],G)}catch(w){K("hosts",`Failed to add ${B} to hosts file: ${w}`,G)}}}if(W&&!M.usedPorts.has(I)){if(!await x(I,$,G))K("setup","Starting HTTP redirect server",G),P_(G),M.usedPorts.add(I);else if(K("setup","Port 80 is in use, skipping HTTP redirect",G),G)J.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Z=W?R:I,z=await x(Z,$,G),Q;if(z){if(K("setup",`Port ${Z} is already in use`,G),G)J.warn(`Port ${Z} is already in use. This may be another instance of rpx or another service.`);if(Z===443){if(Q=await M.getNextAvailablePort(3443,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at https://${B}:${Q}`)}else if(Q=await M.getNextAvailablePort(Z+1000,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at http://${B}:${Q}`)}else Q=Z,M.usedPorts.add(Q),K("setup",`Using standard ${Z===443?"HTTPS":"HTTP"} port ${Z} for ${B}`,G);await a_(_,B,N,Q,$,Y,W,X,G,T,A)}catch(Z){K("setup",`Setup failed: ${Z}`,G),J.error(`Failed to setup reverse proxy: ${Z.message}`),d({domains:[B],hosts:typeof V==="boolean"?V:V?.hosts,certs:typeof V==="boolean"?V:V?.certs,verbose:G,vitePluginUsage:X})}}function P_(D){K("redirect","Starting HTTP redirect server",D);let _=O.createServer((B,N)=>{let Y=B.headers.host||"";K("redirect",`Redirecting request from ${Y}${B.url} to HTTPS`,D),N.writeHead(301,{Location:`https://${Y}${B.url}`}),N.end()}).listen(80);l.add(_),K("redirect","HTTP redirect server started",D)}function p_(D){let _={...B_,...D};if(K("proxy",`Starting proxy with options: ${C(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){J.error("viaDaemon mode requires both `from` and `to`");return}t({proxies:[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}],verbose:_.verbose}).catch((X)=>{J.error(`Failed to register with rpx daemon: ${X.message}`),F.exit(1)});return}let B=_.to||"",N=B.split(".").pop()?.toLowerCase()||"",Y=F.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),W=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"];if(Y&&W.includes(N)&&_?.verbose)J.warn(`The .${N} TLD may not work reliably for local development`),J.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),J.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-1j4gp3f8.js").then(({setupDevelopmentDns:X})=>{X({domains:[B],verbose:_.verbose}).then((A)=>{if(A)Promise.resolve().then(()=>{if(_.verbose)if(G.includes(N))J.success(`DNS server started for .${N} domains`);else J.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else K("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((X)=>{K("dns",`Failed to start DNS server: ${X}`,_.verbose)});let V={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:N_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};K("proxy",`Server options: ${C(V)}`,_.verbose),T_(V).catch((X)=>{K("proxy",`Failed to start proxy: ${X}`,_.verbose),J.error(`Failed to start proxy: ${X.message}`),d({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function g_(D){return D?.verbose||!1}async function F_(D){let _={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(D)_={..._,...D};let B=g_(_);if(K("config",`Starting with config: ${C(_,2)}`,B),K("config",`Is multi-proxy? ${"proxies"in _}`,B),_.viaDaemon){let M="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,cleanUrls:Z.cleanUrls??_.cleanUrls,changeOrigin:Z.changeOrigin??_.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:M,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){K("servers",`Found ${_.proxies.length} proxies in config`,B);for(let $ of _.proxies)if($.start){let M=`${$.from}-${$.to}`;try{K("watch",`Starting command for ${M} with command: ${$.start.command}`,B),J.info(`Starting command for ${M}...`),await D_.startProcess(M,$.start,B);let Z=new URL($.from.startsWith("http")?$.from:`http://${$.from}`),z=Z.hostname||"localhost",Q=Number(Z.port)||80;try{await a(z,Q,B),K("watch",`Dev server is ready at ${z}:${Q}`,B)}catch(E){K("watch",`Connection check failed, but continuing with proxy setup: ${E}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw K("watch",`Failed to start command for ${M}: ${Z}`,B),Error(`Failed to start command for ${M}: ${Z}`)}}else K("watch",`No start command for proxy ${$.from} -> ${$.to}`,B)}else if("start"in _&&_.start){K("watch","Found start command in single proxy config",B);let $=`${_.from}-${_.to}`;try{if(_.start)K("watch",`Starting command: ${_.start.command}`,B),await D_.startProcess($,_.start,B);let M=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),Z=M.hostname||"localhost",z=Number(M.port)||80;try{await a(Z,z,B),K("watch",`Dev server is ready at ${Z}:${z}`,B)}catch(Q){K("watch",`Connection check failed, but continuing with proxy setup: ${Q}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to run start command: ${M}`,B),Error(`Failed to run start command: ${M}`)}}else K("watch","No start command found in config",B);let N="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(F.platform!=="win32"&&(_.https||_.cleanup?.hosts!==!1)){if(!m())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",B),v_("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let $=await c(_);if(!$){if(K("ssl",`No valid or trusted certificates found for ${N}, generating new ones`,_.verbose),await K_(_),$=await c(_),!$)throw Error(`Failed to load SSL certificates after generation for ${N}`)}else K("ssl",`Using existing and trusted certificates for ${N}`,_.verbose);_._cachedSSLConfig=$}let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map(($)=>({...$,https:_.https,cleanup:_.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in _?_.cleanUrls:!1),vitePluginUsage:_.vitePluginUsage,changeOrigin:$.changeOrigin??_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig})):[{from:"from"in _?_.from:"localhost:5173",to:"to"in _?_.to:"rpx.localhost",cleanUrls:"cleanUrls"in _?_.cleanUrls:!1,https:_.https,cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,start:"start"in _?_.start:void 0,changeOrigin:_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig}],W=Y.map(($)=>$.to||"rpx.localhost"),G=_._cachedSSLConfig,V=W.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),X=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"],T=[...new Set(V.map(($)=>$.split(".").pop()?.toLowerCase()))],I=T.filter(($)=>!!$&&X.includes($));if(I.length>0&&B)J.warn(`The following TLDs may not work reliably for local development: ${I.map(($)=>`.${$}`).join(", ")}`),J.info(" These TLDs have HSTS preloading which can bypass local DNS"),J.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(F.platform==="darwin"&&V.length>0){let{setupDevelopmentDns:$}=await import("./chunk-1j4gp3f8.js");if(await $({domains:V,verbose:B})){if(B)if(T.every((z)=>!!z&&A.includes(z)))J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains`);else J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",B)}let R=async()=>{K("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-1j4gp3f8.js");await $({verbose:_.verbose})}catch($){K("cleanup",`Error stopping DNS server: ${$}`,_.verbose)}try{await D_.stopAll(_.verbose)}catch($){K("cleanup",`Error stopping processes: ${$}`,_.verbose)}await d({domains:W,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(F.on("SIGINT",R),F.on("SIGTERM",R),F.on("uncaughtException",($)=>{K("process",`Uncaught exception: ${$}`,!0),console.error("Uncaught exception:",$),R()}),G&&Y.length>1){K("proxies",`Creating shared HTTPS server for ${Y.length} domains`,B);let $=new Map;for(let Q of Y){let E=Q.to||"rpx.localhost",w=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);if($.set(E,{sourceHost:w.host,cleanUrls:Q.cleanUrls||!1,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites}),K("proxies",`Route: ${E} → ${w.host}`,B),!E.includes("localhost")&&!E.includes("127.0.0.1"))try{if(!(await h([E],B))[0])await L([E],B)}catch{K("hosts",`Could not add hosts entry for ${E}`,B)}}if(!await x(80,"0.0.0.0",B))P_(B);let Z=443;if(await x(Z,"0.0.0.0",B)){if(K("proxies",`Port ${Z} is already in use, cannot start shared proxy`,B),B)J.warn(`Port ${Z} is in use. Shared HTTPS proxy cannot start.`);return}try{let Q=Bun.serve({port:Z,hostname:"0.0.0.0",tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},fetch:M_((E)=>$.get(E),B),error(E){return K("server",`Shared proxy server error: ${E}`,B),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),K("proxies",`Shared HTTPS proxy listening on port ${Z} for ${$.size} domains`,B)}catch(Q){K("proxies",`Failed to start shared proxy: ${Q}`,B),console.error("Failed to start shared HTTPS proxy:",Q),R()}}else for(let $ of Y)try{let M=$.to||"rpx.localhost";K("proxy",`Starting proxy for ${M} with SSL config: ${!!G}`,$.verbose),await T_({from:$.from||"localhost:5173",to:M,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:G,changeOrigin:$.changeOrigin||!1})}catch(M){K("proxies",`Failed to start proxy for ${$.to}: ${M}`,$.verbose),console.error(`Failed to start proxy for ${$.to}:`,M),R()}}function f_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${b_}`)}`),console.log(` ${H.green("➜")} ${H.dim(D?.from??"")} ${H.dim("➜")} ${H.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var rD=F_;export{G_ as writeEntry,S2 as watchRegistry,s_ as verifyHttpsChain,W2 as trustRootCaForBrowsers,c2 as tearDownDevelopmentDns,h2 as syncDevelopmentDnsFromRegistry,x2 as stopDnsServer,n2 as stopDaemon,T_ as startServer,p_ as startProxy,F_ as startProxies,q2 as startDnsServer,O2 as setupResolver,L2 as setupDevelopmentDns,C as safeStringify,GB as safeDeleteFile,t as runViaDaemon,g2 as runDaemon,f2 as resolverFilePath,j2 as resolverBasenamesForDomains,w2 as resolverBasenameForDomain,$B as resolvePathRewrite,u2 as removeResolver,P2 as removeLegacyTldResolvers,Z_ as removeHosts,W_ as removeEntry,p2 as releaseDaemonLock,oD as redactSensitive,m2 as reconcileStaleDevelopmentDns,t2 as reconcileDevelopmentDnsOnIdle,E2 as readEntry,l2 as readDaemonPid,n_ as readCertSha256Fingerprint,t_ as readCertCommonName,z2 as readAll,Y2 as pruneStaleRootCas,u_ as portManager,o_ as parseSha256HashesFromSecurityListing,i_ as normalizeSha256Fingerprint,I2 as normalizeDevDomain,Q2 as loadSSLConfig,N2 as listCertSha256HashesByCommonName,_B as isValidRootCA,$_ as isValidId,NB as isSingleProxyOptions,YB as isSingleProxyConfig,$2 as isRootCaTrustedForSsl,G2 as isRootCaFingerprintInKeychains,x as isPortInUse,R2 as isPidAlive,KB as isMultiProxyOptions,BB as isMultiProxyConfig,U2 as isDnsServerRunning,a2 as isDaemonRunning,V2 as isCertTrusted,N_ as httpsConfig,m as getSudoPassword,J2 as getSharedDaemonCertPaths,X2 as getRootCAPaths,Y_ as getRegistryDir,DB as getPrimaryDomain,K2 as getMacosTrustKeychains,B2 as getMacosLoginKeychainPath,v2 as getDaemonRpxDir,b2 as getDaemonPidPath,K_ as generateCertificate,M2 as gcStaleEntries,Z2 as forceTrustCertificate,U_ as findAvailablePort,eD as extractHostname,sD as execSudoSync,X_ as ensureDaemonRunning,H2 as devDomainsFromHosts,k_ as deriveIdFromTarget,i2 as defaultDaemonSpawnCommand,B_ as defaultConfig,rD as default,K as debugLog,M_ as createProxyFetchHandler,y2 as contentLooksLikeRpxResolver,B_ as config,H as colors,A2 as clearSslConfigCache,z_ as cleanupCertificates,d as cleanup,h as checkHosts,c as checkExistingCertificates,r_ as certIncludesSanHostnames,L as addHosts,d2 as acquireDaemonLock,D2 as RPX_ROOT_CA_COMMON_NAME,C2 as RPX_RESOLVER_MARKER,_2 as MACOS_SYSTEM_KEYCHAIN,e_ as MACOS_CA_TRUST_FLAGS,F2 as LEGACY_TLD_RESOLVER_LABELS,b as DefaultPortManager,T2 as DNS_STATE_VERSION,k2 as DNS_PORT};
8
+ `,V=Q_.join(q_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,G,"utf8"),await s(`cat "${V}" | tee "${j}" > /dev/null`),K("hosts","Hosts removed successfully",_)}catch(X){K("hosts","Could not clean up hosts file automatically",_)}finally{try{await f.promises.unlink(V)}catch(X){K("hosts",`Failed to remove temporary file: ${X}`,_)}}}catch(B){K("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function h(D,_){K("hosts",`Checking hosts: ${D}`,_);let B;try{B=await f.promises.readFile(j,"utf-8")}catch(N){K("hosts",`Error reading hosts file: ${N}`,_);try{let Y=m(),W;if(Y)W=`echo '${Y}' | sudo -S cat "${j}" 2>/dev/null`;else W=`sudo -n cat "${j}" 2>/dev/null || cat "${j}" 2>/dev/null || echo ""`;let{stdout:G}=await r(W);B=G}catch(Y){return K("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,_),D.map(()=>!1)}}return D.map((N)=>{let Y=`127.0.0.1 ${N}`,W=`::1 ${N}`;return B.includes(Y)||B.includes(W)})}import*as o from"node:net";function x(D,_,B){return K("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((N)=>{let Y=o.createServer(),W=setTimeout(()=>{K("port",`Checking port ${D} timed out, assuming it's in use`,B),Y.close(),N(!0)},3000);Y.once("error",(G)=>{if(clearTimeout(W),G.code==="EADDRINUSE")K("port",`Port ${D} is in use`,B),N(!0);else K("port",`Error checking port ${D}: ${G.message}`,B),N(!0)}),Y.once("listening",()=>{clearTimeout(W),K("port",`Port ${D} is available`,B),Y.close(),N(!1)});try{Y.listen(D,_)}catch(G){clearTimeout(W),K("port",`Exception checking port ${D}: ${G}`,B),N(!0)}})}async function U_(D,_,B,N=50){K("port",`Finding available port starting from ${D} (max attempts: ${N})`,B);let Y=D,W=0;while(W<N){if(W++,!await x(Y,_,B))return K("port",`Found available port: ${Y} after ${W} attempts`,B),Y;K("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${W}/${N})`,B),Y++}throw Error(`Unable to find available port after ${N} attempts starting from ${D}`)}function x_(D,_,B=5000,N){return K("port",`Testing connection to ${_}:${D}`,N),new Promise((Y)=>{let W=o.connect({host:_,port:D,timeout:B});W.once("connect",()=>{K("port",`Successfully connected to ${_}:${D}`,N),W.end(),Y(!0)}),W.once("timeout",()=>{K("port",`Connection to ${_}:${D} timed out`,N),W.destroy(),Y(!1)}),W.once("error",(G)=>{K("port",`Failed to connect to ${_}:${D}: ${G.message}`,N),W.destroy(),Y(!1)})})}class b{usedPorts=new Set;hostname;verbose;maxRetries;constructor(D="0.0.0.0",_,B=50){this.hostname=D,this.verbose=_,this.maxRetries=B}async getNextAvailablePort(D,_=!1){if(this.usedPorts.has(D))return this.findNextAvailablePort(D+1,_);if(await x(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await x_(D,this.hostname,3000,this.verbose))return K("port",`Port ${D} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(D+1,_)}return this.usedPorts.add(D),D}async findNextAvailablePort(D,_=!1){let B=await U_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await x_(B,this.hostname,3000,this.verbose))if(B<D+this.maxRetries)return this.findNextAvailablePort(B+1,_);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(B),B}releasePort(D){K("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var u_=new b;import{spawn as m_}from"node:child_process";import*as y from"node:process";class e{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){K("start",`Process ${D} is already running`,B);return}let[N,...Y]=_.command.split(" "),W=_.cwd||y.cwd();K("start",`Starting process ${D}:`,B),K("start",` Command: ${N} ${Y.join(" ")}`,B),K("start",` Working directory: ${W}`,B),K("start",` Environment variables: ${C(_.env)}`,B);let G=m_(N,Y,{cwd:W,env:{...y.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:W,process:G,env:_.env}),new Promise((V,X)=>{if(G.on("error",(A)=>{if(!this.isShuttingDown)K("start",`Process ${D} failed to start: ${A}`,B),this.processes.delete(D),X(A),y.emit("SIGINT")}),G.on("exit",(A)=>{if(!this.isShuttingDown&&A!==null&&A!==0)K("start",`Process ${D} exited with code ${A}`,B),this.processes.delete(D),X(Error(`Process ${D} exited with code ${A}`)),y.emit("SIGINT")}),B)G.stdout?.on("data",(A)=>{K("process",`[${D}] ${A.toString().trim()}`,!0)}),G.stderr?.on("data",(A)=>{K("process",`[${D}] ERR: ${A.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&G.killed)this.processes.delete(D),X(Error(`Process ${D} was killed during startup`));else K("start",`Process ${D} started successfully`,B),V()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){K("start",`No process found for ${D}`,_);return}return K("start",`Stopping process ${D}`,_),new Promise((N)=>{if(!B.process){N();return}B.process.once("exit",()=>{this.processes.delete(D),K("start",`Process ${D} stopped`,_),N()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){K("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){K("start",`Error stopping process ${D}: ${Y}`,_),this.processes.delete(D),N()}})}async stopAll(D){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,K("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((N)=>{J.error(`Failed to stop process ${B}:`,N)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var VD=new e;var D_=new e,b_="0.12.0",l_=new b("0.0.0.0"),l=new Set,A_=!1,__=null,V_=null;async function d(D){if(A_)return K("cleanup","Cleanup already in progress, skipping",D?.verbose),V_||Promise.resolve();A_=!0,K("cleanup","Starting cleanup process",D?.verbose),V_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),J.info("Shutting down proxy servers...");let _=[],B=Array.from(l).map((N)=>new Promise((Y)=>{N.close(()=>{K("cleanup","Server closed successfully",D?.verbose),Y()})}));if(_.push(...B),D?.hosts&&D.domains?.length){K("cleanup","Cleaning up hosts file entries",D?.verbose),K("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let N=D.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(K("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,D?.verbose),N.length>0)J.info("Cleaning up hosts file entries..."),_.push(Z_(N,D?.verbose).then(()=>{K("cleanup",`Removed hosts entries for ${N.join(", ")}`,D?.verbose)}).catch((Y)=>{K("cleanup",`Failed to remove hosts entries: ${Y}`,D?.verbose),J.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,Y)}))}if(D?.certs&&D.domains?.length){K("cleanup","Cleaning up SSL certificates",D?.verbose),J.info("Cleaning up SSL certificates...");let N=D.domains.map(async(Y)=>{try{await z_(Y,D?.verbose),K("cleanup",`Removed certificates for ${Y}`,D?.verbose)}catch(W){K("cleanup",`Failed to remove certificates for ${Y}: ${W}`,D?.verbose),J.warn(`Failed to clean up certificates for ${Y}:`,W)}});_.push(...N)}await Promise.allSettled(_),K("cleanup","All cleanup tasks completed successfully",D?.verbose),J.success("All cleanup tasks completed successfully")}catch(_){K("cleanup",`Error during cleanup: ${_}`,D?.verbose),J.error("Error during cleanup:",_)}finally{if(__)__();__=null,A_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(F.env.NODE_ENV!=="test"&&F.env.BUN_ENV!=="test"&&!_)F.exit(0)}return V_}var R_=!1;function S_(D){if(R_){K("signal",`Received second ${D} signal, forcing exit`,!0),F.exit(1);return}R_=!0,K("signal",`Received ${D} signal, initiating cleanup`,!0),d().catch((_)=>{K("signal",`Cleanup failed after ${D}: ${_}`,!0),F.exit(1)}).finally(()=>{R_=!1})}F.once("SIGINT",()=>S_("SIGINT"));F.once("SIGTERM",()=>S_("SIGTERM"));F.on("uncaughtException",(D)=>{K("process",`Uncaught exception: ${D}`,!0),J.error("Uncaught exception:",D),S_("uncaughtException")});async function a(D,_,B,N=5){K("connection",`Testing connection to ${D}:${_} (retries left: ${N})`,B);let Y=15000,W=Date.now();if(F.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let G=()=>new Promise((V,X)=>{let A=O_.connect({host:D,port:_,timeout:3000});A.once("connect",()=>{K("connection",`Successfully connected to ${D}:${_}`,B),A.end(),V()}),A.once("timeout",()=>{K("connection",`Connection to ${D}:${_} timed out`,B),A.destroy(),X(Error("Connection timed out"))}),A.once("error",(T)=>{K("connection",`Failed to connect to ${D}:${_}: ${T}`,B),A.destroy(),X(T)})});try{await G()}catch(V){if(Date.now()-W>Y){K("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),J.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(V.code==="ECONNREFUSED"&&N>0)return K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,B),await new Promise((A)=>setTimeout(A,2000)),a(D,_,B,N-1);if(N>0)try{K("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((A,T)=>{let I=O.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(R)=>{K("connection",`Received HTTP response with status: ${R.statusCode}`,B),A()});I.on("error",(R)=>T(R)),I.on("timeout",()=>{I.destroy(),T(Error("HTTP request timed out"))}),I.end()}),K("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(A){return K("connection",`HTTP request to ${D}:${_} failed: ${A}`,B),K("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,B),await new Promise((T)=>setTimeout(T,2000)),a(D,_,B,N-1)}let X=`Failed to connect to ${D}:${_} after ${5-N} attempts: ${V.message}`;K("connection",`${X}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),J.warn(X),J.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function T_(D){K("server",`Starting server with options: ${C(D)}`,D.verbose);let _=new URL((D.from?.startsWith("http")?D.from:`http://${D.from}`)||"localhost:5173"),B=new URL((D.to?.startsWith("http")?D.to:`http://${D.to}`)||"rpx.localhost"),N=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),Y=[B.hostname];if(!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){K("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await h(Y,D.verbose))[0]){J.info(`Adding ${B.hostname} to hosts file...`),J.info("This may require sudo/administrator privileges");try{await L(Y,D.verbose)}catch(V){if(J.error("Failed to add hosts entry:",V.message),J.warn("You can manually add this entry to your hosts file:"),J.warn(`127.0.0.1 ${B.hostname}`),J.warn(`::1 ${B.hostname}`),F.platform==="win32")J.warn("On Windows:"),J.warn("1. Run notepad as administrator"),J.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else J.warn("On Unix systems:"),J.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch(G){J.error("Failed to check hosts file:",G.message)}}try{await a(_.hostname,N,D.verbose)}catch(G){K("server",`Connection test failed: ${G}`,D.verbose),J.error(G.message),J.warn("Continuing with proxy setup despite connection test failure..."),J.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let W=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=N_({...D,to:B.hostname});if(W=await c({...D,to:B.hostname,https:D.https}),!W){if(K("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await K_({...D,from:_.toString(),to:B.hostname,https:D.https}),W=await c({...D,to:B.hostname,https:D.https}),!W)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch(G){throw K("server",`SSL setup failed: ${G}`,D.verbose),G}K("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await d_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:N,sourceUrl:{hostname:_.hostname,host:_.host},ssl:W})}async function a_(D,_,B,N,Y,W,G,V,X,A,T){K("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${A}`,X);function I(Z){let z={};for(let[Q,E]of Object.entries(Z))if(!Q.startsWith(":"))z[Q]=E;return z}let R=(Z,z)=>{K("request",`Incoming request: ${Z.method} ${Z.url}`,X);let Q=Z.url||"/",E=Z.method||"GET";if(Z instanceof y_.Http2ServerRequest){let S=Z.headers;E=S[":method"]||E,Q=S[":path"]||Q}if(A){if(!Q.match(/\.[a-z0-9]+$/i))if(Q.endsWith("/"))Q=`${Q}index.html`;else Q=`${Q}.html`}let w=I(Z.headers);if(T)w.host=`${W.hostname}:${B}`,K("request",`Changed origin: setting host header to ${w.host}`,X);let U={hostname:W.hostname,port:B,path:Q,method:E,headers:w};K("request",`Proxy request options: ${C(U)}`,X);let p=O.request(U,(S)=>{if(K("response",`Proxy response received with status ${S.statusCode}`,X),A&&S.statusCode===404){let q=[];if(Q.endsWith(".html"))q.push(Q.slice(0,-5));else if(!Q.match(/\.[a-z0-9]+$/i))q.push(`${Q}.html`);if(!Q.endsWith("/"))q.push(`${Q}/index.html`);if(q.length>0){K("cleanUrls",`Trying alternative paths: ${q.join(", ")}`,X);let u=(g)=>{if(g.length===0){z.writeHead(S.statusCode||404,S.headers),S.pipe(z);return}let I_=g[0],L_={...U,path:I_},w_=O.request(L_,(i)=>{if(i.statusCode===200)K("cleanUrls",`Found matching path: ${I_}`,X),z.writeHead(i.statusCode,i.headers),i.pipe(z);else u(g.slice(1))});w_.on("error",()=>u(g.slice(1))),w_.end()};u(q);return}}let P={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};z.writeHead(S.statusCode||500,P),S.pipe(z)});p.on("error",(S)=>{K("request",`Proxy request failed: ${S}`,X),J.error("Proxy request failed:",S),z.writeHead(502),z.end(`Proxy Error: ${S.message}`)}),Z.pipe(p)};if(K("server",`Creating server with SSL config: ${!!G}`,X),G)return new Promise((Z,z)=>{try{let Q=Bun.serve({port:N,hostname:Y,tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(E){let w=new URL(E.url);K("request",`Bun.serve received: ${E.method} ${w.pathname}`,X);let U=`http://${W.host}`,p=new URL(w.pathname+w.search,U);try{let S=new Headers(E.headers);if(S.set("host",W.host),T)S.set("origin",U);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",_);let P=await fetch(p.toString(),{method:E.method,headers:S,body:E.body,redirect:"manual"}),q=new Headers(P.headers);if(A&&w.pathname.endsWith(".html")){let u=w.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:u}})}return new Response(P.body,{status:P.status,statusText:P.statusText,headers:q})}catch(S){return K("request",`Proxy error: ${S}`,X),new Response(`Proxy Error: ${S}`,{status:502})}},error(E){return K("server",`Bun.serve error: ${E}`,X),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!0,cleanUrls:A,verbose:X}),Z()}catch(Q){z(Q)}});let $=O.createServer(R);function M(Z){return l.add(Z),new Promise((z,Q)=>{Z.listen(N,Y,()=>{K("server",`Server listening on port ${N}`,X),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!!G,cleanUrls:A,verbose:X}),z()}),Z.on("error",(E)=>{K("server",`Server error: ${E}`,X),Q(E)})})}return M($)}async function d_(D){K("setup",`Setting up reverse proxy: ${C(D)}`,D.verbose);let{from:_,to:B,fromPort:N,sourceUrl:Y,ssl:W,verbose:G,cleanup:V,vitePluginUsage:X,changeOrigin:A,cleanUrls:T}=D,I=80,R=443,$="0.0.0.0",M=D.portManager||l_;try{if(B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await h([B],G))[0]){J.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await L([B],G),J.success(`Added ${B} to your hosts file.`)}catch(w){J.error(`Failed to add ${B} to your hosts file: ${w}`),J.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(F.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await h([B],G))[0]){K("hosts",`${B} not found in hosts file, adding...`,G);try{await L([B],G)}catch(w){K("hosts",`Failed to add ${B} to hosts file: ${w}`,G)}}}if(W&&!M.usedPorts.has(I)){if(!await x(I,$,G))K("setup","Starting HTTP redirect server",G),P_(G),M.usedPorts.add(I);else if(K("setup","Port 80 is in use, skipping HTTP redirect",G),G)J.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Z=W?R:I,z=await x(Z,$,G),Q;if(z){if(K("setup",`Port ${Z} is already in use`,G),G)J.warn(`Port ${Z} is already in use. This may be another instance of rpx or another service.`);if(Z===443){if(Q=await M.getNextAvailablePort(3443,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at https://${B}:${Q}`)}else if(Q=await M.getNextAvailablePort(Z+1000,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at http://${B}:${Q}`)}else Q=Z,M.usedPorts.add(Q),K("setup",`Using standard ${Z===443?"HTTPS":"HTTP"} port ${Z} for ${B}`,G);await a_(_,B,N,Q,$,Y,W,X,G,T,A)}catch(Z){K("setup",`Setup failed: ${Z}`,G),J.error(`Failed to setup reverse proxy: ${Z.message}`),d({domains:[B],hosts:typeof V==="boolean"?V:V?.hosts,certs:typeof V==="boolean"?V:V?.certs,verbose:G,vitePluginUsage:X})}}function P_(D){K("redirect","Starting HTTP redirect server",D);let _=O.createServer((B,N)=>{let Y=B.headers.host||"";K("redirect",`Redirecting request from ${Y}${B.url} to HTTPS`,D),N.writeHead(301,{Location:`https://${Y}${B.url}`}),N.end()}).listen(80);l.add(_),K("redirect","HTTP redirect server started",D)}function p_(D){let _={...B_,...D};if(K("proxy",`Starting proxy with options: ${C(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){J.error("viaDaemon mode requires both `from` and `to`");return}t({proxies:[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}],verbose:_.verbose}).catch((X)=>{J.error(`Failed to register with rpx daemon: ${X.message}`),F.exit(1)});return}let B=_.to||"",N=B.split(".").pop()?.toLowerCase()||"",Y=F.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),W=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"];if(Y&&W.includes(N)&&_?.verbose)J.warn(`The .${N} TLD may not work reliably for local development`),J.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),J.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-kbnzcycw.js").then(({setupDevelopmentDns:X})=>{X({domains:[B],verbose:_.verbose}).then((A)=>{if(A)Promise.resolve().then(()=>{if(_.verbose)if(G.includes(N))J.success(`DNS server started for .${N} domains`);else J.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else K("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((X)=>{K("dns",`Failed to start DNS server: ${X}`,_.verbose)});let V={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:N_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};K("proxy",`Server options: ${C(V)}`,_.verbose),T_(V).catch((X)=>{K("proxy",`Failed to start proxy: ${X}`,_.verbose),J.error(`Failed to start proxy: ${X.message}`),d({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function g_(D){return D?.verbose||!1}async function F_(D){let _={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(D)_={..._,...D};let B=g_(_);if(K("config",`Starting with config: ${C(_,2)}`,B),K("config",`Is multi-proxy? ${"proxies"in _}`,B),_.viaDaemon){let M="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,cleanUrls:Z.cleanUrls??_.cleanUrls,changeOrigin:Z.changeOrigin??_.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:M,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){K("servers",`Found ${_.proxies.length} proxies in config`,B);for(let $ of _.proxies)if($.start){let M=`${$.from}-${$.to}`;try{K("watch",`Starting command for ${M} with command: ${$.start.command}`,B),J.info(`Starting command for ${M}...`),await D_.startProcess(M,$.start,B);let Z=new URL($.from.startsWith("http")?$.from:`http://${$.from}`),z=Z.hostname||"localhost",Q=Number(Z.port)||80;try{await a(z,Q,B),K("watch",`Dev server is ready at ${z}:${Q}`,B)}catch(E){K("watch",`Connection check failed, but continuing with proxy setup: ${E}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw K("watch",`Failed to start command for ${M}: ${Z}`,B),Error(`Failed to start command for ${M}: ${Z}`)}}else K("watch",`No start command for proxy ${$.from} -> ${$.to}`,B)}else if("start"in _&&_.start){K("watch","Found start command in single proxy config",B);let $=`${_.from}-${_.to}`;try{if(_.start)K("watch",`Starting command: ${_.start.command}`,B),await D_.startProcess($,_.start,B);let M=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),Z=M.hostname||"localhost",z=Number(M.port)||80;try{await a(Z,z,B),K("watch",`Dev server is ready at ${Z}:${z}`,B)}catch(Q){K("watch",`Connection check failed, but continuing with proxy setup: ${Q}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to run start command: ${M}`,B),Error(`Failed to run start command: ${M}`)}}else K("watch","No start command found in config",B);let N="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(F.platform!=="win32"&&(_.https||_.cleanup?.hosts!==!1)){if(!m())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",B),v_("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let $=await c(_);if(!$){if(K("ssl",`No valid or trusted certificates found for ${N}, generating new ones`,_.verbose),await K_(_),$=await c(_),!$)throw Error(`Failed to load SSL certificates after generation for ${N}`)}else K("ssl",`Using existing and trusted certificates for ${N}`,_.verbose);_._cachedSSLConfig=$}let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map(($)=>({...$,https:_.https,cleanup:_.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in _?_.cleanUrls:!1),vitePluginUsage:_.vitePluginUsage,changeOrigin:$.changeOrigin??_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig})):[{from:"from"in _?_.from:"localhost:5173",to:"to"in _?_.to:"rpx.localhost",cleanUrls:"cleanUrls"in _?_.cleanUrls:!1,https:_.https,cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,start:"start"in _?_.start:void 0,changeOrigin:_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig}],W=Y.map(($)=>$.to||"rpx.localhost"),G=_._cachedSSLConfig,V=W.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),X=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"],T=[...new Set(V.map(($)=>$.split(".").pop()?.toLowerCase()))],I=T.filter(($)=>!!$&&X.includes($));if(I.length>0&&B)J.warn(`The following TLDs may not work reliably for local development: ${I.map(($)=>`.${$}`).join(", ")}`),J.info(" These TLDs have HSTS preloading which can bypass local DNS"),J.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(F.platform==="darwin"&&V.length>0){let{setupDevelopmentDns:$}=await import("./chunk-kbnzcycw.js");if(await $({domains:V,verbose:B})){if(B)if(T.every((z)=>!!z&&A.includes(z)))J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains`);else J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",B)}let R=async()=>{K("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-kbnzcycw.js");await $({verbose:_.verbose})}catch($){K("cleanup",`Error stopping DNS server: ${$}`,_.verbose)}try{await D_.stopAll(_.verbose)}catch($){K("cleanup",`Error stopping processes: ${$}`,_.verbose)}await d({domains:W,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(F.on("SIGINT",R),F.on("SIGTERM",R),F.on("uncaughtException",($)=>{K("process",`Uncaught exception: ${$}`,!0),console.error("Uncaught exception:",$),R()}),G&&Y.length>1){K("proxies",`Creating shared HTTPS server for ${Y.length} domains`,B);let $=new Map;for(let Q of Y){let E=Q.to||"rpx.localhost",w=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);if($.set(E,{sourceHost:w.host,cleanUrls:Q.cleanUrls||!1,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites}),K("proxies",`Route: ${E} → ${w.host}`,B),!E.includes("localhost")&&!E.includes("127.0.0.1"))try{if(!(await h([E],B))[0])await L([E],B)}catch{K("hosts",`Could not add hosts entry for ${E}`,B)}}if(!await x(80,"0.0.0.0",B))P_(B);let Z=443;if(await x(Z,"0.0.0.0",B)){if(K("proxies",`Port ${Z} is already in use, cannot start shared proxy`,B),B)J.warn(`Port ${Z} is in use. Shared HTTPS proxy cannot start.`);return}try{let Q=Bun.serve({port:Z,hostname:"0.0.0.0",tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},fetch:M_((E)=>$.get(E),B),error(E){return K("server",`Shared proxy server error: ${E}`,B),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),K("proxies",`Shared HTTPS proxy listening on port ${Z} for ${$.size} domains`,B)}catch(Q){K("proxies",`Failed to start shared proxy: ${Q}`,B),console.error("Failed to start shared HTTPS proxy:",Q),R()}}else for(let $ of Y)try{let M=$.to||"rpx.localhost";K("proxy",`Starting proxy for ${M} with SSL config: ${!!G}`,$.verbose),await T_({from:$.from||"localhost:5173",to:M,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:G,changeOrigin:$.changeOrigin||!1})}catch(M){K("proxies",`Failed to start proxy for ${$.to}: ${M}`,$.verbose),console.error(`Failed to start proxy for ${$.to}:`,M),R()}}function f_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${b_}`)}`),console.log(` ${H.green("➜")} ${H.dim(D?.from??"")} ${H.dim("➜")} ${H.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var rD=F_;export{G_ as writeEntry,S2 as watchRegistry,s_ as verifyHttpsChain,W2 as trustRootCaForBrowsers,c2 as tearDownDevelopmentDns,h2 as syncDevelopmentDnsFromRegistry,x2 as stopDnsServer,n2 as stopDaemon,T_ as startServer,p_ as startProxy,F_ as startProxies,q2 as startDnsServer,O2 as setupResolver,L2 as setupDevelopmentDns,C as safeStringify,GB as safeDeleteFile,t as runViaDaemon,g2 as runDaemon,f2 as resolverFilePath,j2 as resolverBasenamesForDomains,w2 as resolverBasenameForDomain,$B as resolvePathRewrite,u2 as removeResolver,P2 as removeLegacyTldResolvers,Z_ as removeHosts,W_ as removeEntry,p2 as releaseDaemonLock,oD as redactSensitive,m2 as reconcileStaleDevelopmentDns,t2 as reconcileDevelopmentDnsOnIdle,E2 as readEntry,l2 as readDaemonPid,n_ as readCertSha256Fingerprint,t_ as readCertCommonName,z2 as readAll,Y2 as pruneStaleRootCas,u_ as portManager,o_ as parseSha256HashesFromSecurityListing,i_ as normalizeSha256Fingerprint,I2 as normalizeDevDomain,Q2 as loadSSLConfig,N2 as listCertSha256HashesByCommonName,_B as isValidRootCA,$_ as isValidId,NB as isSingleProxyOptions,YB as isSingleProxyConfig,$2 as isRootCaTrustedForSsl,G2 as isRootCaFingerprintInKeychains,x as isPortInUse,R2 as isPidAlive,KB as isMultiProxyOptions,BB as isMultiProxyConfig,U2 as isDnsServerRunning,a2 as isDaemonRunning,V2 as isCertTrusted,N_ as httpsConfig,m as getSudoPassword,J2 as getSharedDaemonCertPaths,X2 as getRootCAPaths,Y_ as getRegistryDir,DB as getPrimaryDomain,K2 as getMacosTrustKeychains,B2 as getMacosLoginKeychainPath,v2 as getDaemonRpxDir,b2 as getDaemonPidPath,K_ as generateCertificate,M2 as gcStaleEntries,Z2 as forceTrustCertificate,U_ as findAvailablePort,eD as extractHostname,sD as execSudoSync,X_ as ensureDaemonRunning,H2 as devDomainsFromHosts,k_ as deriveIdFromTarget,i2 as defaultDaemonSpawnCommand,B_ as defaultConfig,rD as default,K as debugLog,M_ as createProxyFetchHandler,y2 as contentLooksLikeRpxResolver,B_ as config,H as colors,A2 as clearSslConfigCache,z_ as cleanupCertificates,d as cleanup,h as checkHosts,c as checkExistingCertificates,r_ as certIncludesSanHostnames,L as addHosts,d2 as acquireDaemonLock,D2 as RPX_ROOT_CA_COMMON_NAME,C2 as RPX_RESOLVER_MARKER,_2 as MACOS_SYSTEM_KEYCHAIN,e_ as MACOS_CA_TRUST_FLAGS,F2 as LEGACY_TLD_RESOLVER_LABELS,b as DefaultPortManager,T2 as DNS_STATE_VERSION,k2 as DNS_PORT};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/rpx",
3
3
  "type": "module",
4
- "version": "0.11.12",
4
+ "version": "0.11.13",
5
5
  "description": "A modern and smart reverse proxy.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
package/src/daemon.ts CHANGED
@@ -206,6 +206,87 @@ async function bootstrapTls(opts: DaemonOptions, registryDir: string): Promise<S
206
206
  return sslConfig
207
207
  }
208
208
 
209
+ /**
210
+ * Binding :443/:80 requires root. When the daemon is launched as a normal user
211
+ * (the common case — `./buddy dev`), re-exec it through `sudo` so the elevated
212
+ * copy can bind the privileged ports. HOME/PATH are forwarded explicitly (via
213
+ * `env`) so the root daemon reads the *user's* `~/.stacks/rpx` state, certs and
214
+ * registry instead of root's home. The password is fed on stdin only — never
215
+ * placed in argv — so it can't leak via `ps`, and the root daemon doesn't need
216
+ * it (it can already sudo).
217
+ *
218
+ * Returns a launcher handle: this unprivileged process has done its job once
219
+ * the elevated daemon has written its pid, so `done` resolves immediately and
220
+ * the launcher exits, leaving the root daemon running independently (its pid
221
+ * file is how everyone else finds it).
222
+ */
223
+ async function elevateDaemonToRoot(
224
+ rpxDir: string,
225
+ httpsPort: number,
226
+ httpPort: number,
227
+ verbose: boolean,
228
+ ): Promise<DaemonHandle> {
229
+ const sudoPassword = process.env.SUDO_PASSWORD
230
+ const home = process.env.HOME ?? homedir()
231
+ const inner = [process.execPath, ...process.argv.slice(1)]
232
+ const forwardedEnv = [`HOME=${home}`, `PATH=${process.env.PATH ?? ''}`]
233
+ if (verbose)
234
+ forwardedEnv.push('RPX_VERBOSE=1')
235
+
236
+ // `sudo -S` reads the password from stdin; `-n` (no password) relies on a
237
+ // cached credential. Either way we never block on an interactive prompt.
238
+ const sudoArgs = sudoPassword
239
+ ? ['-S', '-p', '', 'env', ...forwardedEnv, ...inner]
240
+ : ['-n', 'env', ...forwardedEnv, ...inner]
241
+
242
+ debugLog('daemon', `elevating daemon via sudo for privileged ports ${httpsPort}/${httpPort}`, verbose)
243
+ const child = nodeSpawn('sudo', sudoArgs, { detached: true, stdio: ['pipe', 'ignore', 'ignore'] })
244
+
245
+ let spawnError: Error | null = null
246
+ let sudoExitCode: number | null = null
247
+ child.once('error', (err) => { spawnError = err })
248
+ child.once('exit', (code) => { sudoExitCode = code ?? 0 })
249
+
250
+ if (sudoPassword && child.stdin) {
251
+ child.stdin.write(`${sudoPassword}\n`)
252
+ child.stdin.end()
253
+ }
254
+ child.unref()
255
+
256
+ const pidPath = getDaemonPidPath(rpxDir)
257
+ const deadline = Date.now() + 15000
258
+ while (Date.now() < deadline) {
259
+ if (spawnError)
260
+ throw spawnError
261
+ const pid = await readDaemonPid(rpxDir)
262
+ if (pid !== null && isPidAlive(pid)) {
263
+ if (verbose)
264
+ log.success(`rpx daemon elevated to root (pid=${pid}, https on :${httpsPort})`)
265
+ return {
266
+ httpsPort,
267
+ httpPort,
268
+ pidPath,
269
+ done: Promise.resolve(),
270
+ stop: async () => {
271
+ // The daemon is root-owned; a normal user can't signal it. `./buddy
272
+ // dev` intentionally leaves the shared daemon running across sessions.
273
+ try { process.kill(pid, 'SIGTERM') }
274
+ catch { /* EPERM — root-owned shared daemon */ }
275
+ },
276
+ }
277
+ }
278
+ // sudo exits fast when auth fails; while the daemon runs it stays alive.
279
+ if (sudoExitCode !== null && sudoExitCode !== 0) {
280
+ throw new Error(
281
+ `rpx daemon could not elevate to bind :${httpsPort} (sudo exited ${sudoExitCode}). `
282
+ + 'Set SUDO_PASSWORD in .env or run `sudo -v` first.',
283
+ )
284
+ }
285
+ await new Promise(resolve => setTimeout(resolve, 50))
286
+ }
287
+ throw new Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${rpxDir})`)
288
+ }
289
+
209
290
  /**
210
291
  * Start the daemon. Returns a handle that resolves `done` once the daemon has
211
292
  * cleanly shut down (signal received and listeners closed).
@@ -223,6 +304,14 @@ export async function runDaemon(opts: DaemonOptions = {}): Promise<DaemonHandle>
223
304
  const hostname = opts.hostname ?? '0.0.0.0'
224
305
  const gcIntervalMs = opts.gcIntervalMs ?? DEFAULT_GC_INTERVAL_MS
225
306
 
307
+ // Privileged ports need root. If we were launched unprivileged (the usual
308
+ // `./buddy dev` case), re-exec through sudo and hand off to the elevated
309
+ // copy — it becomes the real daemon. Tests inject high ports and so skip this.
310
+ const needsPrivilegedPort = (httpsPort > 0 && httpsPort < 1024) || (httpPort > 0 && httpPort < 1024)
311
+ const alreadyRoot = typeof process.getuid === 'function' && process.getuid() === 0
312
+ if (process.platform !== 'win32' && needsPrivilegedPort && !alreadyRoot)
313
+ return elevateDaemonToRoot(rpxDir, httpsPort, httpPort, verbose)
314
+
226
315
  const pidPath = await acquireDaemonLock(rpxDir)
227
316
 
228
317
  // Module-scoped state so the watcher and fetch handler share one routing view.