@stacksjs/rpx 0.11.22 → 0.11.24
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/bin/cli.js +139 -139
- package/dist/{chunk-cqkz06bg.js → chunk-2yk7jygq.js} +1 -1
- package/dist/chunk-6m0f5m3q.js +224 -0
- package/dist/{chunk-c9brkawa.js → chunk-6nvjwawp.js} +1 -1
- package/dist/{chunk-ybpnwmfx.js → chunk-r1k4wgag.js} +1 -1
- package/dist/daemon-runner.d.ts +3 -2
- package/dist/daemon.d.ts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +5 -5
- package/dist/load-balancer.d.ts +65 -0
- package/dist/proxy-handler.d.ts +2 -0
- package/dist/registry.d.ts +3 -2
- package/dist/types.d.ts +37 -1
- package/package.json +1 -1
- package/dist/chunk-cd843mzv.js +0 -224
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ab as l,Bb as m,Cb as n,Db as o,Eb as p,pb as a,qb as b,rb as c,sb as d,tb as e,ub as f,vb as g,wb as h,xb as i,yb as j,zb as k}from"./chunk-2yk7jygq.js";export{e as shouldReusePort,g as safeStringify,p as safeDeleteFile,o as resolvePathRewrite,f as redactSensitive,i as isValidRootCA,m as isSingleProxyOptions,n as isSingleProxyConfig,b as isProcessElevated,l as isMultiProxyOptions,k as isMultiProxyConfig,a as getSudoPassword,j as getPrimaryDomain,h as extractHostname,c as execSudoSync,d as debugLog};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o}from"./chunk-6m0f5m3q.js";import"./chunk-2yk7jygq.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
|
package/dist/daemon-runner.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as path from 'node:path';
|
|
2
|
-
import type { PathRewrite, StaticRouteConfig } from './types';
|
|
2
|
+
import type { LoadBalancerConfig, PathRewrite, ProxyFrom, StaticRouteConfig } from './types';
|
|
3
3
|
/**
|
|
4
4
|
* Sanitize an arbitrary `to` host into a valid registry id. Drops anything
|
|
5
5
|
* that isn't `[a-zA-Z0-9._-]`, collapses runs to a single dash, and trims
|
|
@@ -14,13 +14,14 @@ export declare function deriveIdFromTarget(to: string, routePath?: string): stri
|
|
|
14
14
|
export declare function runViaDaemon(opts: DaemonRunnerOptions): Promise<void>;
|
|
15
15
|
export declare interface DaemonRunnerProxy {
|
|
16
16
|
id?: string
|
|
17
|
-
from?:
|
|
17
|
+
from?: ProxyFrom
|
|
18
18
|
to: string
|
|
19
19
|
path?: string
|
|
20
20
|
cleanUrls?: boolean
|
|
21
21
|
changeOrigin?: boolean
|
|
22
22
|
pathRewrites?: PathRewrite[]
|
|
23
23
|
static?: string | StaticRouteConfig
|
|
24
|
+
loadBalancer?: LoadBalancerConfig
|
|
24
25
|
}
|
|
25
26
|
export declare interface DaemonRunnerOptions {
|
|
26
27
|
proxies: DaemonRunnerProxy[]
|
package/dist/daemon.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OnDemandCertManager } from './on-demand';
|
|
1
2
|
import type { OnDemandSitesConfig, OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
|
|
2
3
|
import type { SiteSnapshot } from './site-supervisor';
|
|
3
4
|
export declare function getDaemonRpxDir(): string;
|
|
@@ -20,6 +21,14 @@ export declare function isDaemonRunning(rpxDir?: string): Promise<boolean>;
|
|
|
20
21
|
*/
|
|
21
22
|
export declare function acquireDaemonLock(rpxDir?: string): Promise<string>;
|
|
22
23
|
export declare function releaseDaemonLock(rpxDir?: string): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* The shared `:80` handler: serve ACME http-01 challenges, kick off on-demand
|
|
26
|
+
* issuance for an approved-but-uncovered host, then 301 to HTTPS. The request
|
|
27
|
+
* target is parsed defensively — scanners constantly send malformed/relative
|
|
28
|
+
* targets, and a thrown `new URL` would reject the fetch handler and make Bun
|
|
29
|
+
* drop the connection with no response. A bad target becomes a 400 instead.
|
|
30
|
+
*/
|
|
31
|
+
export declare function handleHttpRedirect(req: Request, onDemand: OnDemandCertManager | null, acmeChallengeWebroot?: string): Response;
|
|
23
32
|
// `opts` IS used throughout; pickier's no-unused-vars mis-fires on this fn after
|
|
24
33
|
// the on-demand serve refactor (its --fix would wrongly rename to `_opts`).
|
|
25
34
|
// eslint-disable-next-line pickier/no-unused-vars
|
|
@@ -73,6 +82,7 @@ export declare interface DaemonOptions {
|
|
|
73
82
|
productionCerts?: ProductionTlsConfig
|
|
74
83
|
onDemandTls?: OnDemandTlsConfig
|
|
75
84
|
onDemandSites?: OnDemandSitesConfig
|
|
85
|
+
acmeChallengeWebroot?: string
|
|
76
86
|
gcIntervalMs?: number
|
|
77
87
|
workers?: number
|
|
78
88
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export type {
|
|
|
10
10
|
StopDaemonResult,
|
|
11
11
|
} from './daemon';
|
|
12
12
|
export type { GetRoute, NoRouteOutcome, OnNoRoute, ProxyFetchHandler, ProxyRoute, ProxyServer } from './proxy-handler';
|
|
13
|
+
export type { UpstreamPool, UpstreamState } from './load-balancer';
|
|
13
14
|
export type { RedirectRouteConfig, ResolvedRedirect } from './redirect';
|
|
14
15
|
export type { OriginGuard, OriginGuardOptions } from './origin-guard';
|
|
15
16
|
export type { ResolvedAuth } from './auth';
|
|
@@ -126,6 +127,15 @@ export {
|
|
|
126
127
|
stopDaemon,
|
|
127
128
|
} from './daemon';
|
|
128
129
|
export { createProxyFetchHandler, createProxyWebSocketHandler, stripBasePath } from './proxy-handler';
|
|
130
|
+
export {
|
|
131
|
+
createUpstreamPool,
|
|
132
|
+
markFailure,
|
|
133
|
+
markSuccess,
|
|
134
|
+
primaryUpstreamUrl,
|
|
135
|
+
selectUpstream,
|
|
136
|
+
startHealthChecks,
|
|
137
|
+
stopHealthChecks,
|
|
138
|
+
} from './load-balancer';
|
|
129
139
|
export { buildRedirectLocation, resolveRedirect } from './redirect';
|
|
130
140
|
export { ACME_CHALLENGE_PREFIX, readAcmeChallenge } from './acme-challenge';
|
|
131
141
|
export { isWildcardPattern, matchesWildcard, matchHost } from './host-match';
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as fR,$a as c_,A as OS,Aa as XR,B as P,Ba as JR,C as DR,Ca as J_,D as kR,Da as Q_,E as cS,Ea as V_,F as L,Fa as Z_,G as NR,Ga as I_,H as hS,Ha as W_,I as uS,Ia as z_,J as vS,Ja as M_,K as AR,Ka as x_,L as BR,La as j_,M as mS,Ma as T_,N as KR,Na as H_,O as bS,Oa as k_,P as wR,Pa as w_,Q as aS,Qa as E_,R as ER,Ra as F_,S as lS,Sa as q_,T as dS,Ta as C_,U as pS,Ua as f_,V as gS,W as nS,Wa as y_,X as FR,Xa as U_,Y as qR,Ya as P_,Z as iS,Za as L_,_ as CR,_a as O_,a as $,aa as WR,ab as h_,b as SR,ba as tS,bb as u_,c as JS,ca as yR,cb as v_,d as QS,da as rS,db as m_,e as VS,ea as UR,eb as b_,f as ZS,fa as sS,fb as a_,g as IS,ga as PR,gb as l_,h as WS,ha as eS,hb as d_,i as zS,ia as LR,ib as p_,j as MS,ja as oS,jb as g_,k as xS,ka as R_,kb as n_,l as jS,la as S_,lb as QR,m as TS,ma as __,mb as i_,n as HS,na as D_,nb as t_,o as kS,oa as N_,p as wS,pa as A_,q as ES,qa as B_,r as FS,ra as K_,s as qS,sa as Y_,t as CS,ta as f,u as fS,ua as $_,v as yS,va as OR,w as US,wa as G_,x as PS,xa as $R,y as LS,ya as GR,z as _R,za as X_}from"./chunk-6m0f5m3q.js";import{Ab as EN,Bb as FN,Cb as qN,Db as CN,Eb as fN,ob as TR,pb as v,qb as lR,rb as xN,sb as D,tb as gR,ub as jN,vb as q,wb as TN,xb as HN,yb as kN,zb as wN}from"./chunk-2yk7jygq.js";import{execSync as NS}from"node:child_process";import*as YR from"node:http";import*as nR from"node:net";import*as z from"node:process";var p=(S,R)=>(_)=>`\x1B[${S}m${_}\x1B[${R}m`,k={bold:p(1,22),dim:p(2,22),green:p(32,39),cyan:p(36,39)};import*as vR from"node:fs";import*as mR from"node:path";import*as E from"node:process";function bR(S,R){let N=(R&&R!=="/"?`${S}${R}`:S).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return N.length>0?N:"rpx"}async function g(S){if(S.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=S.verbose??!1,_=S.registryDir,N=new Set,K=S.proxies.map((Q)=>{let I=Q.id??bR(Q.to,Q.path);if(!GR(I))throw Error(`invalid registry id "${I}" derived from to="${Q.to}"`);if(N.has(I))throw Error(`duplicate registry id "${I}" — set an explicit \`id\` on one of the proxies`);return N.add(I),{...Q,id:I}}),B=new Date().toISOString();for(let Q of K)await XR({id:Q.id,from:Q.from,to:Q.to,path:Q.path,pid:S.persistent?void 0:E.pid,cwd:E.cwd(),createdAt:B,cleanUrls:Q.cleanUrls,changeOrigin:Q.changeOrigin,pathRewrites:Q.pathRewrites,static:Q.static,loadBalancer:Q.loadBalancer},_,R);let A=await QR({rpxDir:S.rpxDir,verbose:R,spawnCommand:S.spawnCommand,startupTimeoutMs:S.startupTimeoutMs,spawnEnv:S.spawnEnv});for(let Q of K){let I=Q.static?`static ${typeof Q.static==="string"?Q.static:Q.static.dir}`:Q.from;$.success(`https://${Q.to} → ${I}`)}if($.info(`(via rpx daemon pid=${A.pid}; \`rpx daemon:status\` to inspect)`),S.detached)return;let X=!1,Y=_??$R(),J=K.map((Q)=>Q.id),V=async()=>{if(X)return;X=!0;for(let Q of J)await JR(Q,_,R).catch((I)=>{D("runner",`removeEntry(${Q}) failed: ${I}`,R)})},Z=(Q)=>{D("runner",`received ${Q}, unregistering ${J.length} entries`,R),V().finally(()=>E.exit(0))};E.once("SIGINT",Z),E.once("SIGTERM",Z),E.once("exit",()=>{if(X)return;for(let Q of J)try{vR.unlinkSync(mR.join(Y,`${Q}.json`))}catch{}}),await new Promise(()=>{})}import{exec as sR}from"node:child_process";import C from"node:fs";import dR from"node:os";import ZR from"node:path";import*as m from"node:process";import{promisify as eR}from"node:util";var u=eR(sR);function aR(S){let R=S.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var H=m.platform==="win32"?ZR.join(m.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",VR=!1;async function n(S){if(m.platform==="win32")throw Error("Administrator privileges required on Windows");if(lR()){let{stdout:N}=await u(S);return N}let R=v(),_=S.replace(/'/g,"'\\''");try{if(R){let{stdout:N}=await u(`echo '${R}' | sudo -S sh -c '${_}' 2>/dev/null`);return VR=!0,N}if(VR)try{let{stdout:N}=await u(`sudo -n sh -c '${_}'`);return N}catch(N){D("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:N}=await u(`sudo -n sh -c '${_}'`);return VR=!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 y(S,R){let _=S.filter((K)=>!aR(K)),N=S.filter((K)=>aR(K));if(N.length>0)D("hosts",`Skipping /etc/hosts for loopback dev names: ${N.join(", ")}`,R);if(_.length===0)return;D("hosts",`Adding hosts: ${_.join(", ")}`,R),D("hosts",`Using hosts file at: ${H}`,R);try{let K;try{K=await C.promises.readFile(H,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{K=await n(`cat "${H}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let B=_.filter((Y)=>{let J=`127.0.0.1 ${Y}`,V=`::1 ${Y}`;return!K.includes(J)&&!K.includes(V)});if(B.length===0){D("hosts","All hosts already exist in hosts file",R);return}let A=B.map((Y)=>`
|
|
2
2
|
# Added by rpx
|
|
3
3
|
127.0.0.1 ${Y}
|
|
4
4
|
::1 ${Y}`).join(`
|
|
5
|
-
`),
|
|
6
|
-
`),K=!1,N
|
|
5
|
+
`),X=ZR.join(dR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(X,K+A,"utf8"),await n(`cat "${X}" | tee "${H}" > /dev/null`),console.log(` Hosts updated: ${B.join(", ")}`)}catch(Y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),B.forEach((J)=>{console.log(` 127.0.0.1 ${J}`),console.log(` ::1 ${J}`)}),console.log(` Or run: sudo nano ${H}`)}finally{try{await C.promises.unlink(X)}catch{}}}catch(K){D("hosts",`Failed to manage hosts file: ${K.message}`,R)}}async function IR(S,R){D("hosts",`Removing hosts: ${S.join(", ")}`,R);try{let _;try{_=await C.promises.readFile(H,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{_=await n(`cat "${H}"`)}catch(Y){throw D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=_.split(`
|
|
6
|
+
`),K=!1,B=N.filter((Y)=>{if(S.some((V)=>Y.includes(` ${V}`)&&(Y.includes("127.0.0.1")||Y.includes("::1"))))return K=!0,!1;if(Y.trim()==="# Added by rpx")return K=!0,!1;return!0});if(!K){D("hosts","No matching hosts found to remove",R);return}while(B[B.length-1]?.trim()==="")B.pop();let A=`${B.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,
|
|
9
|
-
`,A=(Y)=>{let J=i(Y);return D.has(J)||B.some((Q)=>GR(J,Q))},V=(Y)=>{let J=RS(Y);if(!A(J))return;let Q="/";try{Q=new URL(Y.url).pathname}catch{}if(K.some((Z)=>Q.startsWith(Z)))return;if(eR(Y.headers.get(R),S.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=A,V}import*as hR from"node:fs";import*as uR from"node:path";var QR="/.well-known/acme-challenge/";function VR(S,R){if(!S||!R.startsWith(QR))return null;let D=R.slice(QR.length);if(!D||!/^[A-Za-z0-9_-]+$/.test(D))return null;try{return hR.readFileSync(uR.join(S,D),"utf8")}catch{return null}}var r=new g,DS="0.12.0",_S=new CR("0.0.0.0"),t=new Set,XR=!1,n=null,ZR=null;async function u(S){if(XR)return _("cleanup","Cleanup already in progress, skipping",S?.verbose),ZR||Promise.resolve();XR=!0,_("cleanup","Starting cleanup process",S?.verbose),ZR=new Promise((R)=>{n=R});try{await r.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],D=Array.from(t).map((B)=>new Promise((K)=>{let N=B;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",S?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){_("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));if(R.push(...D),t.clear(),S?.hosts&&S.domains?.length){_("cleanup","Cleaning up hosts file entries",S?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let B=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(B)}`,S?.verbose),B.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(B,S?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${B.join(", ")}`,S?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${B.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){_("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let B=S.domains.map(async(K)=>{try{await FR(K,S?.verbose),_("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,N)}});R.push(...B)}await Promise.allSettled(R),_("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){_("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,XR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var WR=!1;function pR(S){if(WR){_("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}WR=!0,_("signal",`Received ${S} signal, initiating cleanup`,!0),u().catch((R)=>{_("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{WR=!1})}z.once("SIGINT",()=>pR("SIGINT"));z.once("SIGTERM",()=>pR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function h(S,R,D,B=5){_("connection",`Testing connection to ${S}:${R} (retries left: ${B})`,D);let K=15000,N=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let A=()=>new Promise((V,Y)=>{let J=aR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{_("connection",`Successfully connected to ${S}:${R}`,D),J.end(),V()}),J.once("timeout",()=>{_("connection",`Connection to ${S}:${R} timed out`,D),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(Q)=>{_("connection",`Failed to connect to ${S}:${R}: ${Q}`,D),J.destroy(),Y(Q)})});try{await A()}catch(V){let Y=V;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,D),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&B>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${B} retries left)`,D),await new Promise((Q)=>setTimeout(Q,2000)),h(S,R,D,B-1);if(B>0)try{_("connection",`Trying HTTP request to ${S}:${R}`,D),await new Promise((Q,Z)=>{let X=SR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(W)=>{_("connection",`Received HTTP response with status: ${W.statusCode}`,D),Q()});X.on("error",(W)=>Z(W)),X.on("timeout",()=>{X.destroy(),Z(Error("HTTP request timed out"))}),X.end()}),_("connection",`HTTP request to ${S}:${R} succeeded`,D);return}catch(Q){return _("connection",`HTTP request to ${S}:${R} failed: ${Q}`,D),_("connection",`Retrying socket connection in 2 seconds... (${B} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),h(S,R,D,B-1)}let J=`Failed to connect to ${S}:${R} after ${5-B} attempts: ${Y.message}`;_("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),G.warn(J),G.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 yR(S){_("server",`Starting server with options: ${E(S)}`,S.verbose);let R=new URL((S.from?.startsWith("http")?S.from:`http://${S.from}`)||"localhost:5173"),D=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),B=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),K=[D.hostname];if(fR(S)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,S?.verbose);try{if(!(await f(K,S.verbose))[0]){G.info(`Adding ${D.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(K,S.verbose)}catch(V){if(G.error("Failed to add hosts entry:",V.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${D.hostname}`),G.warn(`::1 ${D.hostname}`),z.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${D.hostname}`,S.verbose)}catch(A){G.error("Failed to check hosts file:",A.message)}}try{await h(R.hostname,B,S.verbose)}catch(A){_("server",`Connection test failed: ${A}`,S.verbose),G.error(A.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=o({...S,to:D.hostname});if(N=await U({...S,to:D.hostname,https:S.https}),!N){if(_("ssl",`Generating new certificates for ${D.hostname}`,S.verbose),await e({...S,from:R.toString(),to:D.hostname,https:S.https}),N=await U({...S,to:D.hostname,https:S.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch(A){throw _("server",`SSL setup failed: ${A}`,S.verbose),A}_("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,S.verbose),await BS({...S,from:S.from||"localhost:5173",to:D.hostname,fromPort:B,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function NS(S,R,D,B,K,N,A,V,Y,J){_("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${V}`,A);let Q=[{host:R,route:{sourceHost:B.host,cleanUrls:V||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!IR({routeEntries:Q,listenPort:D,sslConfig:K,originGuard:null,verbose:A??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);YS({from:S,to:R,vitePluginUsage:N,listenPort:D,ssl:!!K,cleanUrls:V,verbose:A})}async function BS(S){_("setup",`Setting up reverse proxy: ${E(S)}`,S.verbose);let{from:R,to:D,sourceUrl:B,ssl:K,verbose:N,cleanup:A,vitePluginUsage:V,changeOrigin:Y,cleanUrls:J}=S,Q=80,Z=443,X="0.0.0.0",W=S.portManager||_S,P=fR(S);try{if(P&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await f([D],N))[0]){G.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await y([D],N),G.success(`Added ${D} to your hosts file.`)}catch(L){G.error(`Failed to add ${D} to your hosts file: ${L}`),G.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(P&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([D],N))[0]){_("hosts",`${D} not found in hosts file, adding...`,N);try{await y([D],N)}catch(L){_("hosts",`Failed to add ${D} to hosts file: ${L}`,N)}}}if(K&&!W.usedPorts.has(Q)){if(!await C(Q,X,N))_("setup","Starting HTTP redirect server",N),dR(N),W.usedPorts.add(Q);else if(_("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let x=K?Z:Q,w=await C(x,X,N),F;if(w){if(_("setup",`Port ${x} is already in use`,N),N)G.warn(`Port ${x} is already in use. This may be another instance of rpx or another service.`);if(x===443){if(F=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at https://${D}:${F}`)}else if(F=await W.getNextAvailablePort(x+1000,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at http://${D}:${F}`)}else F=x,W.usedPorts.add(F),_("setup",`Using standard ${x===443?"HTTPS":"HTTP"} port ${x} for ${D}`,N);await NS(R,D,F,B,K,V,N,J,Y,RR(S.auth))}catch(x){_("setup",`Setup failed: ${x}`,N),G.error(`Failed to setup reverse proxy: ${x.message}`),u({domains:[D],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:N,vitePluginUsage:V})}}function dR(S,R=80,D=443,B){_("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=SR.createServer((N,A)=>{if(B&&N.url){let Q=N.url.split("?",1)[0],Z=VR(B,Q);if(Z!=null){_("redirect",`Serving ACME challenge ${Q}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let V=N.headers.host||"",Y=V.includes(":")?V.slice(0,V.indexOf(":")):V,J=D===443?Y:`${Y}:${D}`;_("redirect",`Redirecting request from ${V}${N.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${N.url}`}),A.end()}).listen(R);t.add(K),_("redirect","HTTP redirect server started",S)}function KS(S){let R={...s,...S};if(_("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let D=R.to||"",B=D.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&N.includes(B)&&R?.verbose)G.warn(`The .${B} TLD may not work reliably for local development`),G.info(` Google owns .${B} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-ybpnwmfx.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[D],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(B))G.success(`DNS server started for .${B} domains`);else G.success(`DNS server started for .${B} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((Y)=>{_("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};_("proxy",`Server options: ${E(V)}`,R.verbose),yR(V).catch((Y)=>{_("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function AS(S){return S?.verbose||!1}function fR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function UR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let D=AS(R),B=fR(R);if(_("config",`Starting with config: ${E(R,2)}`,D),_("config",`Is multi-proxy? ${"proxies"in R}`,D),_("config",`Hosts management enabled? ${B}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??R.cleanUrls,changeOrigin:M.changeOrigin??R.changeOrigin,pathRewrites:M.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await a({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){_("servers",`Found ${R.proxies.length} proxies in config`,D);for(let $ of R.proxies)if($.start){let I=`${$.from}-${$.to}`;try{_("watch",`Starting command for ${I} with command: ${$.start.command}`,D),G.info(`Starting command for ${I}...`),await r.startProcess(I,$.start,D);let M=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),T=M.hostname||"localhost",b=Number(M.port)||80;try{await h(T,b,D),_("watch",`Dev server is ready at ${T}:${b}`,D)}catch(iR){_("watch",`Connection check failed, but continuing with proxy setup: ${iR}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw _("watch",`Failed to start command for ${I}: ${M}`,D),Error(`Failed to start command for ${I}: ${M}`)}}else _("watch",`No start command for proxy ${$.from} -> ${$.to}`,D)}else if("start"in R&&R.start){_("watch","Found start command in single proxy config",D);let $=`${R.from}-${R.to}`;try{if(R.start)_("watch",`Starting command: ${R.start.command}`,D),await r.startProcess($,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),M=I.hostname||"localhost",T=Number(I.port)||80;try{await h(M,T,D),_("watch",`Dev server is ready at ${M}:${T}`,D)}catch(b){_("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw _("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else _("watch","No start command found in config",D);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||B)){if(!m())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",D),SS("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",D)}}let N=[];if(R.productionCerts){if(N=await qR(R.productionCerts,D),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,D)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=$}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=A.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,J=V.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],X=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],W=X.filter(($)=>!!$&&Q.includes($));if(W.length>0&&D)G.warn(`The following TLDs may not work reliably for local development: ${W.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(B&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");if(await $({domains:J,verbose:D})){if(D)if(X.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",D)}let P=async()=>{_("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");await $({verbose:R.verbose})}catch($){_("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){_("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",P),z.on("SIGTERM",P);let x=R.singlePortMode===!0,w=R.httpsPort??443,F=R.httpPort??80,O=R.originGuard?JR(R.originGuard):null,L=!!Y&&(A.length>1||x),gR=!Y&&x&&A.length>0;if(L&&Y){_("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${w}`,D);let $=await bR(A,B,D);if(!await C(F,"0.0.0.0",D))dR(D,F,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",D)){if(_("proxies",`Port ${w} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:O,verbose:D})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(gR){_("proxies",`Creating shared HTTP server for ${A.length} domains on port ${F}`,D);let $=await bR(A,B,D);if(await C(F,"0.0.0.0",D)){if(_("proxies",`Port ${F} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${F} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:F,sslConfig:null,originGuard:O,verbose:D})){G.error(`Shared HTTP proxy failed to bind :${F}; not exiting`);return}}else for(let $ of A)try{let I=$.to||"rpx.localhost";_("proxy",`Starting proxy for ${I} with SSL config: ${!!Y}`,$.verbose),await yR({from:$.from||"localhost:5173",to:I,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(I){_("proxies",`Failed to start proxy for ${$.to}: ${I}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,I)}}async function bR(S,R,D){let B=[],K=new Set;for(let N of S){let A=N.to||"rpx.localhost",V=N.cleanUrls||!1,Y=N.path,J=kR(Y),Q=RR(N.auth);if(N.redirect){let Z=MR(N.redirect);B.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${Q?" (auth)":""}`,D)}else if(N.static)B.push({host:A,path:Y,route:{static:xR(N.static,V),cleanUrls:V,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Q?" (auth)":""}`,D);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);B.push({host:A,path:Y,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → ${Z.host}${Q?" (auth)":""}`,D)}if(K.has(A))continue;if(K.add(A),R&&!HR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await f([A],D))[0])await y([A],D)}catch{_("hosts",`Could not add hosts entry for ${A}`,D)}}return B}function IR(S){let{routeEntries:R,listenPort:D,sslConfig:B,originGuard:K,verbose:N}=S,A=wR(R),V=TR((Q,Z)=>ER(A,Q,Z),N),Y=K?(Q,Z)=>K(Q)??V(Q,Z):V,J=jR(N);try{let Q=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:lR(),...B?{tls:Array.isArray(B)?B.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,X){return Y(Z,X)},websocket:J,error(Z){return _("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(Q),_("proxies",`Shared ${B?"HTTPS":"HTTP"} proxy listening on port ${D} for ${A.size} domains`,N),Q}catch(Q){return _("proxies",`Failed to start shared proxy: ${Q}`,N),console.error("Failed to start shared proxy:",Q),null}}function YS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${DS}`)}`),console.log(` ${H.green("➜")} ${H.dim(S?.from??"")} ${H.dim("➜")} ${H.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var JN=UR;export{NR as writeEntry,YD as watchRegistry,VS as verifyHttpsChain,HS as trustRootCaForBrowsers,yD as tearDownDevelopmentDns,CD as syncDevelopmentDnsFromRegistry,bS as stripBasePath,TD as stopDnsServer,bD as stopDaemon,yR as startServer,KS as startProxy,UR as startProxies,xD as startDnsServer,tS as siteIdForHost,lR as shouldReusePort,wD as setupResolver,qD as setupDevelopmentDns,dS as serverNameFromCertFilename,uS as serveStaticFile,E as safeStringify,vS as safeRelativePath,TN as safeDeleteFile,a as runViaDaemon,hD as runDaemon,HD as resolverFilePath,zD as resolverBasenamesForDomains,WD as resolverBasenameForDomain,xR as resolveStaticRoute,hS as resolveStaticFile,MR as resolveRedirect,xN as resolvePathRewrite,RR as resolveAuth,JD as renderStartingPage,QD as renderFailedPage,fD as removeResolver,ED as removeLegacyTldResolvers,$R as removeHosts,BR as removeEntry,vD as releaseDaemonLock,VN as redactSensitive,UD as reconcileStaleDevelopmentDns,lD as reconcileDevelopmentDnsOnIdle,eS as readSiteManifest,BD as readEntry,LD as readDaemonPid,GS as readCertSha256Fingerprint,JS as readCertCommonName,KD as readAll,VR as readAcmeChallenge,xS as pruneStaleRootCas,sS as projectNameFromHost,_D as portManager,aS as pathPrefixMatches,XS as parseSha256HashesFromSecurityListing,OS as parseHtpasswd,$S as normalizeSha256Fingerprint,kR as normalizePathPrefix,ZD as normalizeDevDomain,GR as matchesWildcard,gS as matchesAllowedSuffix,ER as matchHostRoute,pS as matchHostList,lS as matchHost,yS as loadSSLConfig,SD as listDiscoverableSites,MS as listCertSha256HashesByCommonName,HR as isWildcardPattern,ZN as isValidRootCA,_R as isValidId,FN as isSingleProxyOptions,MN as isSingleProxyConfig,TS as isRootCaTrustedForSsl,jS as isRootCaFingerprintInKeychains,mR as isProcessElevated,C as isPortInUse,ND as isPidAlive,IN as isMultiProxyOptions,zN as isMultiProxyConfig,iS as isLikelyHostname,jD as isDnsServerRunning,cD as isDaemonRunning,PS as isCertTrusted,o as httpsConfig,m as getSudoPassword,CS as getSharedDaemonCertPaths,qS as getRootCAPaths,DR as getRegistryDir,WN as getPrimaryDomain,FS as getMacosTrustKeychains,IS as getMacosLoginKeychainPath,PD as getDaemonRpxDir,OD as getDaemonPidPath,e as generateCertificate,AD as gcStaleEntries,fS as forceTrustCertificate,DD as findAvailablePort,XN as extractHostname,rS as expandHome,QN as execSudoSync,GD as escapeHtml,KR as ensureDaemonRunning,LS as enforceBasicAuth,wS as devSslToSniEntries,ID as devDomainsFromHosts,oS as detectProjectPreset,LR as deriveIdFromTarget,uD as defaultDaemonSpawnCommand,s as defaultConfig,JN as default,_ as debugLog,RD as createSiteResolver,jR as createProxyWebSocketHandler,TR as createProxyFetchHandler,JR as createOriginGuard,mS as contentTypeFor,kD as contentLooksLikeRpxResolver,s as config,H as colors,US as clearSslConfigCache,FR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,QS as certIncludesSanHostnames,qR as buildSniTlsConfig,ES as buildRegistryTlsProxyOptions,cS as buildRedirectLocation,wR as buildHostRoutes,y as addHosts,mD as acquireDaemonLock,$D as SiteSupervisor,kS as SHARED_DEV_HOST_CERT_PATH,zS as RPX_ROOT_CA_COMMON_NAME,MD as RPX_RESOLVER_MARKER,nS as OnDemandCertManager,WS as MACOS_SYSTEM_KEYCHAIN,ZS as MACOS_CA_TRUST_FLAGS,XD as LEGACY_TLD_RESOLVER_LABELS,CR as DefaultPortManager,VD as DNS_STATE_VERSION,FD as DNS_PORT,QR as ACME_CHALLENGE_PREFIX};
|
|
8
|
+
`,X=ZR.join(dR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(X,A,"utf8"),await n(`cat "${X}" | tee "${H}" > /dev/null`),D("hosts","Hosts removed successfully",R)}catch(Y){D("hosts","Could not clean up hosts file automatically",R)}finally{try{await C.promises.unlink(X)}catch(Y){D("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(_){D("hosts",`Failed to clean up hosts file: ${_.message}`,R)}}async function U(S,R){D("hosts",`Checking hosts: ${S}`,R);let _;try{_=await C.promises.readFile(H,"utf-8")}catch(N){D("hosts",`Error reading hosts file: ${N}`,R);try{let K=v(),B;if(K)B=`echo '${K}' | sudo -S cat "${H}" 2>/dev/null`;else B=`sudo -n cat "${H}" 2>/dev/null || cat "${H}" 2>/dev/null || echo ""`;let{stdout:A}=await u(B);_=A}catch(K){return D("hosts",`Cannot read hosts file, assuming entries don't exist: ${K}`,R),S.map(()=>!1)}}return S.map((N)=>{let K=`127.0.0.1 ${N}`,B=`::1 ${N}`;return _.includes(K)||_.includes(B)})}import{spawn as oR}from"node:child_process";import*as i from"node:process";class t{processes=new Map;isShuttingDown=!1;async startProcess(S,R,_){if(this.processes.has(S)){D("start",`Process ${S} is already running`,_);return}let[N,...K]=R.command.split(" "),B=R.cwd||i.cwd();D("start",`Starting process ${S}:`,_),D("start",` Command: ${N} ${K.join(" ")}`,_),D("start",` Working directory: ${B}`,_),D("start",` Environment variables: ${q(R.env)}`,_);let A=oR(N,K,{cwd:B,env:{...i.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(S,{command:R.command,cwd:B,process:A,env:R.env}),new Promise((X,Y)=>{if(A.on("error",(J)=>{if(!this.isShuttingDown)D("start",`Process ${S} failed to start: ${J}`,_),this.processes.delete(S),Y(J)}),A.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)D("start",`Process ${S} exited with code ${J}; leaving the proxy running`,_),this.processes.delete(S),Y(Error(`Process ${S} exited with code ${J}`))}),_)A.stdout?.on("data",(J)=>{D("process",`[${S}] ${J.toString().trim()}`,!0)}),A.stderr?.on("data",(J)=>{D("process",`[${S}] ERR: ${J.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&A.killed)this.processes.delete(S),Y(Error(`Process ${S} was killed during startup`));else D("start",`Process ${S} started successfully`,_),X()},1000)})}async stopProcess(S,R){let _=this.processes.get(S);if(!_?.process){D("start",`No process found for ${S}`,R);return}return D("start",`Stopping process ${S}`,R),new Promise((N)=>{if(!_.process){N();return}_.process.once("exit",()=>{this.processes.delete(S),D("start",`Process ${S} stopped`,R),N()});try{_.process.kill("SIGTERM"),setTimeout(()=>{if(_.process){D("start",`Force killing process ${S}`,R);try{_.process.kill("SIGKILL")}catch(K){}}},3000)}catch(K){D("start",`Error stopping process ${S}: ${K}`,R),this.processes.delete(S),N()}})}async stopAll(S){if(this.isShuttingDown){D("start","Already shutting down, skipping duplicate stopAll call",S);return}this.isShuttingDown=!0,D("start","Stopping all processes",S);let R=Array.from(this.processes.keys()).map((_)=>this.stopProcess(_,S).catch((N)=>{$.error(`Failed to stop process ${_}:`,N)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(S){let R=this.processes.get(S);return!!R?.process&&!R.process.killed}}var JD=new t;import{timingSafeEqual as RS}from"node:crypto";function SS(S,R){if(S==null)return!1;let _=Buffer.from(S),N=Buffer.from(R);if(_.length!==N.length)return!1;return RS(_,N)}function r(S){return S.toLowerCase().replace(/\.$/,"")}var _S=["/.well-known/acme-challenge/"];function DS(S){let R=S.headers.get("host");if(R)return r(R.split(":")[0]);try{return r(new URL(S.url).hostname)}catch{return""}}function zR(S){let R=S.header.toLowerCase(),_=new Set,N=[];for(let Y of S.hosts){let J=r(Y);if(J.startsWith("*."))N.push(J);else _.add(J)}let K=S.exemptPaths??_S,B=S.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
9
|
+
`,A=(Y)=>{let J=r(Y);return _.has(J)||N.some((V)=>WR(J,V))},X=(Y)=>{let J=DS(Y);if(!A(J))return;let V="/";try{V=new URL(Y.url).pathname}catch{}if(K.some((Z)=>V.startsWith(Z)))return;if(SS(Y.headers.get(R),S.value))return;return new Response(B,{status:403,headers:{"content-type":"text/plain"}})};return X.protects=A,X}var e=new t,AS="0.12.0",BS=new OR("0.0.0.0"),o=new Set,RR=new Set,MR=!1,s=null,xR=null;async function a(S){if(MR)return D("cleanup","Cleanup already in progress, skipping",S?.verbose),xR||Promise.resolve();MR=!0,D("cleanup","Starting cleanup process",S?.verbose),xR=new Promise((R)=>{s=R});try{await e.stopAll(S?.verbose),$.info("Shutting down proxy servers...");let R=[],_=Array.from(o).map((N)=>new Promise((K)=>{let B=N;try{if(typeof B.stop==="function")B.stop(!0),D("cleanup","Bun server stopped",S?.verbose),K();else if(typeof B.close==="function")B.close(()=>{D("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){D("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));R.push(..._),o.clear();for(let N of RR)BR(N);if(RR.clear(),S?.hosts&&S.domains?.length){D("cleanup","Cleaning up hosts file entries",S?.verbose),D("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let N=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(D("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,S?.verbose),N.length>0)$.info("Cleaning up hosts file entries..."),R.push(IR(N,S?.verbose).then(()=>{D("cleanup",`Removed hosts entries for ${N.join(", ")}`,S?.verbose)}).catch((K)=>{D("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),$.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){D("cleanup","Cleaning up SSL certificates",S?.verbose),$.info("Cleaning up SSL certificates...");let N=S.domains.map(async(K)=>{try{await kR(K,S?.verbose),D("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(B){D("cleanup",`Failed to remove certificates for ${K}: ${B}`,S?.verbose),$.warn(`Failed to clean up certificates for ${K}:`,B)}});R.push(...N)}await Promise.allSettled(R),D("cleanup","All cleanup tasks completed successfully",S?.verbose),$.success("All cleanup tasks completed successfully")}catch(R){D("cleanup",`Error during cleanup: ${R}`,S?.verbose),$.error("Error during cleanup:",R)}finally{if(s)s();s=null,MR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return xR}var jR=!1;function iR(S){if(jR){D("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}jR=!0,D("signal",`Received ${S} signal, initiating cleanup`,!0),a().catch((R)=>{D("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{jR=!1})}z.once("SIGINT",()=>iR("SIGINT"));z.once("SIGTERM",()=>iR("SIGTERM"));z.on("uncaughtException",(S)=>{$.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{$.error("Unhandled rejection (continuing):",S)});async function b(S,R,_,N=5){D("connection",`Testing connection to ${S}:${R} (retries left: ${N})`,_);let K=15000,B=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){D("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,_);return}let A=()=>new Promise((X,Y)=>{let J=nR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{D("connection",`Successfully connected to ${S}:${R}`,_),J.end(),X()}),J.once("timeout",()=>{D("connection",`Connection to ${S}:${R} timed out`,_),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(V)=>{D("connection",`Failed to connect to ${S}:${R}: ${V}`,_),J.destroy(),Y(V)})});try{await A()}catch(X){let Y=X;if(Date.now()-B>K){D("connection",`Connection test timed out after ${K}ms, but continuing anyway`,_),$.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&N>0)return D("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,_),await new Promise((V)=>setTimeout(V,2000)),b(S,R,_,N-1);if(N>0)try{D("connection",`Trying HTTP request to ${S}:${R}`,_),await new Promise((V,Z)=>{let Q=YR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(I)=>{D("connection",`Received HTTP response with status: ${I.statusCode}`,_),V()});Q.on("error",(I)=>Z(I)),Q.on("timeout",()=>{Q.destroy(),Z(Error("HTTP request timed out"))}),Q.end()}),D("connection",`HTTP request to ${S}:${R} succeeded`,_);return}catch(V){return D("connection",`HTTP request to ${S}:${R} failed: ${V}`,_),D("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,_),await new Promise((Z)=>setTimeout(Z,2000)),b(S,R,_,N-1)}let J=`Failed to connect to ${S}:${R} after ${5-N} attempts: ${Y.message}`;D("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,_),$.warn(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 cR(S){D("server",`Starting server with options: ${q(S)}`,S.verbose);let R=L(S.from),_=new URL(R.startsWith("http")?R:`http://${R}`),N=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),K=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),B=[N.hostname];if(hR(S)&&!N.hostname.includes("localhost")&&!N.hostname.includes("127.0.0.1")){D("hosts",`Checking if hosts file entry exists for: ${N.hostname}`,S?.verbose);try{if(!(await U(B,S.verbose))[0]){$.info(`Adding ${N.hostname} to hosts file...`),$.info("This may require sudo/administrator privileges");try{await y(B,S.verbose)}catch(Y){if($.error("Failed to add hosts entry:",Y.message),$.warn("You can manually add this entry to your hosts file:"),$.warn(`127.0.0.1 ${N.hostname}`),$.warn(`::1 ${N.hostname}`),z.platform==="win32")$.warn("On Windows:"),$.warn("1. Run notepad as administrator"),$.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else $.warn("On Unix systems:"),$.warn("sudo nano /etc/hosts")}}else D("hosts",`Host entry already exists for ${N.hostname}`,S.verbose)}catch(X){$.error("Failed to check hosts file:",X.message)}}try{await b(_.hostname,K,S.verbose)}catch(X){D("server",`Connection test failed: ${X}`,S.verbose),$.error(X.message),$.warn("Continuing with proxy setup despite connection test failure..."),$.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let A=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=DR({...S,to:N.hostname});if(A=await P({...S,to:N.hostname,https:S.https}),!A){if(D("ssl",`Generating new certificates for ${N.hostname}`,S.verbose),await _R({...S,from:_.toString(),to:N.hostname,https:S.https}),A=await P({...S,to:N.hostname,https:S.https}),!A)throw Error(`Failed to load SSL configuration after generating certificates for ${N.hostname}`)}}catch(X){throw D("server",`SSL setup failed: ${X}`,S.verbose),X}D("server",`Setting up reverse proxy with SSL config for ${N.hostname}`,S.verbose),await YS({...S,from:R,originalFrom:S.from||R,to:N.hostname,fromPort:K,sourceUrl:{hostname:_.hostname,host:_.host},ssl:A})}async function KS(S,R,_,N,K,B,A,X,Y,J,V,Z){D("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${X}`,A);let Q=NR(V??N.host,Z);AR(Q);let I=[{host:R,route:{sourceHost:N.host,upstreamPool:Q,cleanUrls:X||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!HR({routeEntries:I,listenPort:_,sslConfig:K,originGuard:null,verbose:A??!1}))throw BR(Q),Error(`Failed to start proxy server for ${R} on port ${_}`);RR.add(Q),XS({from:S,to:R,vitePluginUsage:B,listenPort:_,ssl:!!K,cleanUrls:X,verbose:A})}async function YS(S){D("setup",`Setting up reverse proxy: ${q(S)}`,S.verbose);let{from:R,originalFrom:_,to:N,sourceUrl:K,ssl:B,verbose:A,cleanup:X,vitePluginUsage:Y,changeOrigin:J,cleanUrls:V}=S,Z=80,Q=443,I="0.0.0.0",F=S.portManager||BS,O=hR(S);try{if(O&&N&&!N.includes("localhost")&&!N.includes("127.0.0.1")){if(!(await U([N],A))[0]){$.warn(`The hostname ${N} isn't in your hosts file. Adding it now...`);try{await y([N],A),$.success(`Added ${N} to your hosts file.`)}catch(c){$.error(`Failed to add ${N} to your hosts file: ${c}`),$.info(`You may need to manually add '127.0.0.1 ${N}' to your /etc/hosts file.`)}}}else if(O&&z.platform!=="darwin"&&N&&N.includes("localhost")&&!N.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await U([N],A))[0]){D("hosts",`${N} not found in hosts file, adding...`,A);try{await y([N],A)}catch(c){D("hosts",`Failed to add ${N} to hosts file: ${c}`,A)}}}if(B&&!F.usedPorts.has(Z)){if(!await f(Z,I,A))D("setup","Starting HTTP redirect server",A),tR(A),F.usedPorts.add(Z);else if(D("setup","Port 80 is in use, skipping HTTP redirect",A),A)$.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let M=B?Q:Z,w=await f(M,I,A),j;if(w){if(D("setup",`Port ${M} is already in use`,A),A)$.warn(`Port ${M} is already in use. This may be another instance of rpx or another service.`);if(M===443){if(j=await F.getNextAvailablePort(3443,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)$.info(`Using port ${j} instead. Access your site at https://${N}:${j}`)}else if(j=await F.getNextAvailablePort(M+1000,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)$.info(`Using port ${j} instead. Access your site at http://${N}:${j}`)}else j=M,F.usedPorts.add(j),D("setup",`Using standard ${M===443?"HTTPS":"HTTP"} port ${M} for ${N}`,A);await KS(R,N,j,K,B,Y,A,V,J,KR(S.auth),_,S.loadBalancer)}catch(M){D("setup",`Setup failed: ${M}`,A),$.error(`Failed to setup reverse proxy: ${M.message}`),a({domains:[N],hosts:typeof X==="boolean"?X:X?.hosts,certs:typeof X==="boolean"?X:X?.certs,verbose:A,vitePluginUsage:Y})}}function tR(S,R=80,_=443,N){D("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=YR.createServer((B,A)=>{if(N&&B.url){let V=B.url.split("?",1)[0],Z=CR(N,V);if(Z!=null){D("redirect",`Serving ACME challenge ${V}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let X=B.headers.host||"",Y=X.includes(":")?X.slice(0,X.indexOf(":")):X,J=_===443?Y:`${Y}:${_}`;D("redirect",`Redirecting request from ${X}${B.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${B.url}`}),A.end()}).listen(R);o.add(K),D("redirect","HTTP redirect server started",S)}function $S(S){let R={...SR,...S};if(D("proxy",`Starting proxy with options: ${q(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){$.error("viaDaemon mode requires both `from` and `to`");return}g({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{$.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let _=R.to||"",N=_.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&_&&!_.includes("localhost")&&!_.includes("127.0.0.1"),B=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&B.includes(N)&&R?.verbose)$.warn(`The .${N} TLD may not work reliably for local development`),$.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),$.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-r1k4wgag.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[_],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(N))$.success(`DNS server started for .${N} domains`);else $.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else D("dns",`Could not start DNS server - ${_} may not resolve in browser`,R.verbose)})}).catch((Y)=>{D("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let X={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:DR(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};D("proxy",`Server options: ${q(X)}`,R.verbose),cR(X).catch((Y)=>{D("proxy",`Failed to start proxy: ${Y}`,R.verbose),$.error(`Failed to start proxy: ${Y.message}`),a({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function GS(S){return S?.verbose||!1}function hR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function uR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let _=GS(R),N=hR(R);if(D("config",`Starting with config: ${q(R,2)}`,_),D("config",`Is multi-proxy? ${"proxies"in R}`,_),D("config",`Hosts management enabled? ${N}`,_),R.viaDaemon){let W="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((x)=>({id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls??R.cleanUrls,changeOrigin:x.changeOrigin??R.changeOrigin,pathRewrites:x.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await g({proxies:W,verbose:_});return}if("proxies"in R&&Array.isArray(R.proxies)){D("servers",`Found ${R.proxies.length} proxies in config`,_);for(let G of R.proxies)if(G.start){let W=`${G.from}-${G.to}`;try{D("watch",`Starting command for ${W} with command: ${G.start.command}`,_),$.info(`Starting command for ${W}...`),await e.startProcess(W,G.start,_);let x=L(G.from),T=new URL(x.startsWith("http")?x:`http://${x}`),h=T.hostname||"localhost",d=Number(T.port)||80;try{await b(h,d,_),D("watch",`Dev server is ready at ${h}:${d}`,_)}catch(rR){D("watch",`Connection check failed, but continuing with proxy setup: ${rR}`,_),$.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(x){throw D("watch",`Failed to start command for ${W}: ${x}`,_),Error(`Failed to start command for ${W}: ${x}`)}}else D("watch",`No start command for proxy ${G.from} -> ${G.to}`,_)}else if("start"in R&&R.start){D("watch","Found start command in single proxy config",_);let G=`${R.from}-${R.to}`;try{if(R.start)D("watch",`Starting command: ${R.start.command}`,_),await e.startProcess(G,R.start,_);let W=L(R.from),x=new URL(W.startsWith("http")?W:`http://${W}`),T=x.hostname||"localhost",h=Number(x.port)||80;try{await b(T,h,_),D("watch",`Dev server is ready at ${T}:${h}`,_)}catch(d){D("watch",`Connection check failed, but continuing with proxy setup: ${d}`,_),$.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(W){throw D("watch",`Failed to run start command: ${W}`,_),Error(`Failed to run start command: ${W}`)}}else D("watch","No start command found in config",_);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||N)){if(!v())try{D("sudo","Pre-acquiring sudo credentials for privileged operations",_),NS("sudo -v",{stdio:"inherit"})}catch{D("sudo","Could not pre-acquire sudo credentials",_)}}let B=[];if(R.productionCerts){if(B=await LR(R.productionCerts,_),B.length>0)D("ssl",`Using ${B.length} production SNI cert(s): ${B.map((G)=>G.serverName).join(", ")}`,_)}if(R.https){let G=B.length>0?null:await P(R);if(!G&&B.length===0){if(D("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await _R(R),G=await P(R),!G)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else D("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=G}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((G)=>({...G,https:R.https,cleanup:R.cleanup,cleanUrls:G.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:G.changeOrigin??R.changeOrigin,verbose:_,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:_,_cachedSSLConfig:R._cachedSSLConfig}],X=A.map((G)=>G.to||"rpx.localhost"),Y=B.length>0?B:R._cachedSSLConfig??null,J=X.filter((G)=>G&&!G.includes("localhost")&&!G.includes("127.0.0.1")),V=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],Q=[...new Set(J.map((G)=>G.split(".").pop()?.toLowerCase()))],I=Q.filter((G)=>!!G&&V.includes(G));if(I.length>0&&_)$.warn(`The following TLDs may not work reliably for local development: ${I.map((G)=>`.${G}`).join(", ")}`),$.info(" These TLDs have HSTS preloading which can bypass local DNS"),$.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(N&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:G}=await import("./chunk-r1k4wgag.js");if(await G({domains:J,verbose:_})){if(_)if(Q.every((T)=>!!T&&Z.includes(T)))$.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains`);else $.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else D("dns","Could not start DNS server - custom domains may not resolve",_)}let F=async()=>{D("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:G}=await import("./chunk-r1k4wgag.js");await G({verbose:R.verbose})}catch(G){D("cleanup",`Error stopping DNS server: ${G}`,R.verbose)}try{await e.stopAll(R.verbose)}catch(G){D("cleanup",`Error stopping processes: ${G}`,R.verbose)}await a({domains:X,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",F),z.on("SIGTERM",F);let O=R.singlePortMode===!0,M=R.httpsPort??443,w=R.httpPort??80,j=R.originGuard?zR(R.originGuard):null,l=!!Y&&(A.length>1||O),c=!Y&&O&&A.length>0;if(l&&Y){D("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${M}`,_);let G=await pR(A,N,_);if(!await f(w,"0.0.0.0",_))tR(_,w,M,R.acmeChallengeWebroot);if(await f(M,"0.0.0.0",_)){if(D("proxies",`Port ${M} is already in use, cannot start shared proxy`,_),_)$.warn(`Port ${M} is in use. Shared HTTPS proxy cannot start.`);return}if(!HR({routeEntries:G,listenPort:M,sslConfig:Y,originGuard:j,verbose:_})){$.error(`Shared HTTPS proxy failed to bind :${M}; not exiting`);return}}else if(c){D("proxies",`Creating shared HTTP server for ${A.length} domains on port ${w}`,_);let G=await pR(A,N,_);if(await f(w,"0.0.0.0",_)){if(D("proxies",`Port ${w} is already in use, cannot start shared proxy`,_),_)$.warn(`Port ${w} is in use. Shared HTTP proxy cannot start.`);return}if(!HR({routeEntries:G,listenPort:w,sslConfig:null,originGuard:j,verbose:_})){$.error(`Shared HTTP proxy failed to bind :${w}; not exiting`);return}}else for(let G of A)try{let W=G.to||"rpx.localhost";D("proxy",`Starting proxy for ${W} with SSL config: ${!!Y}`,G.verbose),await cR({from:G.from||"localhost:5173",to:W,cleanUrls:G.cleanUrls||!1,https:G.https||!1,cleanup:G.cleanup||!1,vitePluginUsage:G.vitePluginUsage||!1,verbose:G.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:G.changeOrigin||!1})}catch(W){D("proxies",`Failed to start proxy for ${G.to}: ${W}`,G.verbose),$.error(`Failed to start proxy for ${G.to}:`,W)}}async function pR(S,R,_){let N=[],K=new Set;for(let B of S){let A=B.to||"rpx.localhost",X=B.cleanUrls||!1,Y=B.path,J=yR(Y),V=KR(B.auth);if(B.redirect){let Z=wR(B.redirect);N.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${V?" (auth)":""}`,_)}else if(B.static)N.push({host:A,path:Y,route:{static:ER(B.static,X),cleanUrls:X,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → static ${typeof B.static==="string"?B.static:B.static.dir}${V?" (auth)":""}`,_);else{let Z=L(B.from),Q=new URL(Z.startsWith("http")?Z:`http://${Z}`),I=NR(B.from??Q.host,B.loadBalancer);AR(I),RR.add(I),N.push({host:A,path:Y,route:{sourceHost:Q.host,upstreamPool:I,cleanUrls:X,changeOrigin:B.changeOrigin||!1,pathRewrites:B.pathRewrites,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → ${Q.host}${V?" (auth)":""}`,_)}if(K.has(A))continue;if(K.add(A),R&&!fR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await U([A],_))[0])await y([A],_)}catch{D("hosts",`Could not add hosts entry for ${A}`,_)}}return N}function HR(S){let{routeEntries:R,listenPort:_,sslConfig:N,originGuard:K,verbose:B}=S,A=UR(R),X=FR((V,Z)=>PR(A,V,Z),B),Y=K?(V,Z)=>K(V)??X(V,Z):X,J=qR(B);try{let V=Bun.serve({port:_,hostname:"0.0.0.0",reusePort:gR(),...N?{tls:Array.isArray(N)?N.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,Q){return Y(Z,Q)},websocket:J,error(Z){return D("server",`Shared proxy server error: ${Z}`,B),new Response(`Server Error: ${Z.message}`,{status:500})}});return o.add(V),D("proxies",`Shared ${N?"HTTPS":"HTTP"} proxy listening on port ${_} for ${A.size} domains`,B),V}catch(V){return D("proxies",`Failed to start shared proxy: ${V}`,B),console.error("Failed to start shared proxy:",V),null}}function XS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${k.green(k.bold("rpx"))} ${k.green(`v${AS}`)}`),console.log(` ${k.green("➜")} ${k.dim(S?.from??"")} ${k.dim("➜")} ${k.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${k.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${k.green("➜")} Clean URLs enabled`)}var MN=uR;export{XR as writeEntry,Z_ as watchRegistry,IS as verifyHttpsChain,FS as trustRootCaForBrowsers,h_ as tearDownDevelopmentDns,c_ as syncDevelopmentDnsFromRegistry,nS as stripBasePath,BR as stopHealthChecks,C_ as stopDnsServer,i_ as stopDaemon,cR as startServer,$S as startProxy,uR as startProxies,AR as startHealthChecks,q_ as startDnsServer,D_ as siteIdForHost,gR as shouldReusePort,P_ as setupResolver,O_ as setupDevelopmentDns,eS as serverNameFromCertFilename,gS as serveStaticFile,hS as selectUpstream,q as safeStringify,dS as safeRelativePath,fN as safeDeleteFile,g as runViaDaemon,g_ as runDaemon,y_ as resolverFilePath,k_ as resolverBasenamesForDomains,H_ as resolverBasenameForDomain,ER as resolveStaticRoute,pS as resolveStaticFile,wR as resolveRedirect,CN as resolvePathRewrite,KR as resolveAuth,z_ as renderStartingPage,M_ as renderFailedPage,u_ as removeResolver,L_ as removeLegacyTldResolvers,IR as removeHosts,JR as removeEntry,p_ as releaseDaemonLock,jN as redactSensitive,v_ as reconcileStaleDevelopmentDns,t_ as reconcileDevelopmentDnsOnIdle,A_ as readSiteManifest,J_ as readEntry,a_ as readDaemonPid,QS as readCertSha256Fingerprint,VS as readCertCommonName,Q_ as readAll,CR as readAcmeChallenge,kS as pruneStaleRootCas,N_ as projectNameFromHost,L as primaryUpstreamUrl,G_ as portManager,rS as pathPrefixMatches,WS as parseSha256HashesFromSecurityListing,mS as parseHtpasswd,JS as normalizeSha256Fingerprint,yR as normalizePathPrefix,T_ as normalizeDevDomain,WR as matchesWildcard,oS as matchesAllowedSuffix,PR as matchHostRoute,sS as matchHostList,tS as matchHost,uS as markSuccess,vS as markFailure,PS as loadSSLConfig,Y_ as listDiscoverableSites,HS as listCertSha256HashesByCommonName,fR as isWildcardPattern,HN as isValidRootCA,GR as isValidId,FN as isSingleProxyOptions,qN as isSingleProxyConfig,wS as isRootCaTrustedForSsl,ES as isRootCaFingerprintInKeychains,lR as isProcessElevated,f as isPortInUse,X_ as isPidAlive,EN as isMultiProxyOptions,wN as isMultiProxyConfig,R_ as isLikelyHostname,f_ as isDnsServerRunning,l_ as isDaemonRunning,cS as isCertTrusted,DR as httpsConfig,v as getSudoPassword,US as getSharedDaemonCertPaths,yS as getRootCAPaths,$R as getRegistryDir,kN as getPrimaryDomain,TS as getMacosTrustKeychains,jS as getMacosLoginKeychainPath,m_ as getDaemonRpxDir,b_ as getDaemonPidPath,_R as generateCertificate,V_ as gcStaleEntries,LS as forceTrustCertificate,$_ as findAvailablePort,TN as extractHostname,__ as expandHome,xN as execSudoSync,W_ as escapeHtml,QR as ensureDaemonRunning,bS as enforceBasicAuth,CS as devSslToSniEntries,w_ as devDomainsFromHosts,B_ as detectProjectPreset,bR as deriveIdFromTarget,n_ as defaultDaemonSpawnCommand,SR as defaultConfig,MN as default,D as debugLog,NR as createUpstreamPool,K_ as createSiteResolver,qR as createProxyWebSocketHandler,FR as createProxyFetchHandler,zR as createOriginGuard,lS as contentTypeFor,U_ as contentLooksLikeRpxResolver,SR as config,k as colors,OS as clearSslConfigCache,kR as cleanupCertificates,a as cleanup,U as checkHosts,P as checkExistingCertificates,ZS as certIncludesSanHostnames,LR as buildSniTlsConfig,fS as buildRegistryTlsProxyOptions,aS as buildRedirectLocation,UR as buildHostRoutes,y as addHosts,d_ as acquireDaemonLock,I_ as SiteSupervisor,qS as SHARED_DEV_HOST_CERT_PATH,xS as RPX_ROOT_CA_COMMON_NAME,F_ as RPX_RESOLVER_MARKER,S_ as OnDemandCertManager,MS as MACOS_SYSTEM_KEYCHAIN,zS as MACOS_CA_TRUST_FLAGS,j_ as LEGACY_TLD_RESOLVER_LABELS,OR as DefaultPortManager,x_ as DNS_STATE_VERSION,E_ as DNS_PORT,iS as ACME_CHALLENGE_PREFIX};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { LoadBalancerConfig, LoadBalancerStrategy, ProxyFrom } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* The first upstream's `host:port` from a {@link ProxyFrom}, for call sites
|
|
4
|
+
* that need a single representative address (connection testing before the
|
|
5
|
+
* pool exists, hosts-file checks, id derivation, log lines) rather than the
|
|
6
|
+
* full pool. Defaults to `'localhost:5173'` to match rpx's historical
|
|
7
|
+
* single-upstream default when `from` is unset.
|
|
8
|
+
*/
|
|
9
|
+
export declare function primaryUpstreamUrl(from?: ProxyFrom): string;
|
|
10
|
+
/**
|
|
11
|
+
* Build a pool from a route's `from` (single string or array) plus optional
|
|
12
|
+
* load-balancer config. Always returns at least one upstream when `from` is
|
|
13
|
+
* set to a non-empty string/array; callers pass `''`/`[]` only for
|
|
14
|
+
* static/redirect routes that carry no upstream at all (in which case use of
|
|
15
|
+
* the pool is skipped entirely).
|
|
16
|
+
*/
|
|
17
|
+
export declare function createUpstreamPool(from: ProxyFrom, lbConfig?: LoadBalancerConfig): UpstreamPool;
|
|
18
|
+
/**
|
|
19
|
+
* Pick the next upstream per the pool's configured strategy, considering only
|
|
20
|
+
* currently-healthy upstreams (unless the pool is a degenerate single-upstream
|
|
21
|
+
* pool — see {@link healthyUpstreams}). Returns `undefined` when the pool has
|
|
22
|
+
* no upstreams at all, or every upstream (in an N>1 pool) is unhealthy — the
|
|
23
|
+
* caller should respond with a 502 in that case.
|
|
24
|
+
*/
|
|
25
|
+
export declare function selectUpstream(pool: UpstreamPool): UpstreamState | undefined;
|
|
26
|
+
/** Record a successful outcome for `upstream` — passive health-check bookkeeping. */
|
|
27
|
+
export declare function markSuccess(pool: UpstreamPool, upstream: UpstreamState): void;
|
|
28
|
+
/** Record a failed outcome for `upstream` — passive health-check bookkeeping. */
|
|
29
|
+
export declare function markFailure(pool: UpstreamPool, upstream: UpstreamState): void;
|
|
30
|
+
/**
|
|
31
|
+
* Start active health checking for `pool` when `healthCheck.enabled` — probes
|
|
32
|
+
* every upstream on `healthCheck.interval`, independent of live traffic. No-op
|
|
33
|
+
* (and idempotent) when active checks are disabled or already running. Always
|
|
34
|
+
* pair with {@link stopHealthChecks} on server shutdown so the interval
|
|
35
|
+
* doesn't leak.
|
|
36
|
+
*/
|
|
37
|
+
export declare function startHealthChecks(pool: UpstreamPool): void;
|
|
38
|
+
/** Stop active health checking for `pool`, if running. Safe to call repeatedly. */
|
|
39
|
+
export declare function stopHealthChecks(pool: UpstreamPool): void;
|
|
40
|
+
/** Per-upstream runtime state tracked across requests. */
|
|
41
|
+
export declare interface UpstreamState {
|
|
42
|
+
url: string
|
|
43
|
+
weight: number
|
|
44
|
+
healthy: boolean
|
|
45
|
+
activeConnections: number
|
|
46
|
+
consecutiveFailures: number
|
|
47
|
+
consecutiveSuccesses: number
|
|
48
|
+
}
|
|
49
|
+
declare interface ResolvedHealthCheckConfig {
|
|
50
|
+
enabled: boolean
|
|
51
|
+
path: string
|
|
52
|
+
interval: number
|
|
53
|
+
timeout: number
|
|
54
|
+
healthyThreshold: number
|
|
55
|
+
unhealthyThreshold: number
|
|
56
|
+
}
|
|
57
|
+
/** A route's normalized upstream pool + selection/health state. */
|
|
58
|
+
export declare interface UpstreamPool {
|
|
59
|
+
upstreams: UpstreamState[]
|
|
60
|
+
strategy: LoadBalancerStrategy
|
|
61
|
+
healthCheck: ResolvedHealthCheckConfig
|
|
62
|
+
cursor: number
|
|
63
|
+
wrrCurrentWeights: number[]
|
|
64
|
+
healthCheckTimer: ReturnType<typeof setInterval> | null
|
|
65
|
+
}
|
package/dist/proxy-handler.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { PathRewrite } from './types';
|
|
|
2
2
|
import type { ResolvedAuth } from './auth';
|
|
3
3
|
import type { ResolvedRedirect } from './redirect';
|
|
4
4
|
import type { ResolvedStaticRoute } from './static-files';
|
|
5
|
+
import type { UpstreamPool } from './load-balancer';
|
|
5
6
|
/**
|
|
6
7
|
* Cap on client→upstream frames buffered *before the upstream WebSocket opens*.
|
|
7
8
|
* Without it, a fast client (or an upstream that never opens) grows `pending`
|
|
@@ -34,6 +35,7 @@ export declare function createProxyFetchHandler(getRoute: GetRoute, verbose?: bo
|
|
|
34
35
|
export declare function createProxyWebSocketHandler(verbose?: boolean): void;
|
|
35
36
|
export declare interface ProxyRoute {
|
|
36
37
|
sourceHost?: string
|
|
38
|
+
upstreamPool?: UpstreamPool
|
|
37
39
|
cleanUrls?: boolean
|
|
38
40
|
changeOrigin?: boolean
|
|
39
41
|
pathRewrites?: PathRewrite[]
|
package/dist/registry.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as path from 'node:path';
|
|
2
|
-
import type { BasicAuthConfig, PathRewrite, StaticRouteConfig } from './types';
|
|
2
|
+
import type { BasicAuthConfig, LoadBalancerConfig, PathRewrite, ProxyFrom, StaticRouteConfig } from './types';
|
|
3
3
|
/**
|
|
4
4
|
* Default location for the registry directory. The daemon's PID file and log
|
|
5
5
|
* sit alongside it under `~/.stacks/rpx/`.
|
|
@@ -56,7 +56,7 @@ export declare function gcStaleEntries(dir?: string, verbose?: boolean): Promise
|
|
|
56
56
|
export declare function watchRegistry(onChange: (entries: RegistryEntry[]) => void | Promise<void>, opts?: WatchOptions & { dir?: string }): WatchHandle;
|
|
57
57
|
export declare interface RegistryEntry {
|
|
58
58
|
id: string
|
|
59
|
-
from?:
|
|
59
|
+
from?: ProxyFrom
|
|
60
60
|
to: string
|
|
61
61
|
path?: string
|
|
62
62
|
pid?: number
|
|
@@ -67,6 +67,7 @@ export declare interface RegistryEntry {
|
|
|
67
67
|
changeOrigin?: boolean
|
|
68
68
|
static?: string | StaticRouteConfig
|
|
69
69
|
auth?: BasicAuthConfig
|
|
70
|
+
loadBalancer?: LoadBalancerConfig
|
|
70
71
|
}
|
|
71
72
|
export declare interface WatchHandle {
|
|
72
73
|
close: () => void
|
package/dist/types.d.ts
CHANGED
|
@@ -31,9 +31,35 @@ export declare interface BasicAuthConfig {
|
|
|
31
31
|
users?: Array<{ username: string, password: string }>
|
|
32
32
|
htpasswdFile?: string
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* One upstream in a load-balanced pool, with an optional relative weight.
|
|
36
|
+
*/
|
|
37
|
+
export declare interface UpstreamTarget {
|
|
38
|
+
url: string
|
|
39
|
+
weight?: number
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Health checking for a load-balanced pool. Passive checks (derived from live
|
|
43
|
+
* traffic outcomes) are always on; active checks (periodic out-of-band probes)
|
|
44
|
+
* are opt-in via {@link enabled}.
|
|
45
|
+
*/
|
|
46
|
+
export declare interface HealthCheckConfig {
|
|
47
|
+
enabled?: boolean
|
|
48
|
+
path?: string
|
|
49
|
+
interval?: number
|
|
50
|
+
timeout?: number
|
|
51
|
+
healthyThreshold?: number
|
|
52
|
+
unhealthyThreshold?: number
|
|
53
|
+
}
|
|
54
|
+
/** Per-route load-balancing configuration. */
|
|
55
|
+
export declare interface LoadBalancerConfig {
|
|
56
|
+
strategy?: LoadBalancerStrategy
|
|
57
|
+
healthCheck?: HealthCheckConfig
|
|
58
|
+
}
|
|
34
59
|
export declare interface BaseProxyConfig {
|
|
35
|
-
from?:
|
|
60
|
+
from?: ProxyFrom
|
|
36
61
|
to: string
|
|
62
|
+
loadBalancer?: LoadBalancerConfig
|
|
37
63
|
auth?: BasicAuthConfig
|
|
38
64
|
path?: string
|
|
39
65
|
start?: StartOptions
|
|
@@ -173,6 +199,7 @@ export declare interface ProxySetupOptions extends Omit<ProxyOption, 'from'> {
|
|
|
173
199
|
sourceUrl: Pick<URL, 'hostname' | 'host'>
|
|
174
200
|
ssl: SSLConfig | null
|
|
175
201
|
from: string
|
|
202
|
+
originalFrom?: ProxyFrom
|
|
176
203
|
to: string
|
|
177
204
|
portManager?: PortManager
|
|
178
205
|
}
|
|
@@ -187,6 +214,15 @@ export declare interface PortManager {
|
|
|
187
214
|
* - `flat`: `/about` → `<root>/about.html` (flat-file style).
|
|
188
215
|
*/
|
|
189
216
|
export type PathRewriteStyle = 'directory' | 'flat';
|
|
217
|
+
/**
|
|
218
|
+
* Upstream `host:port` to forward to. Either a single string (backward
|
|
219
|
+
* compatible, degenerate one-item pool) or an array of upstreams — either
|
|
220
|
+
* plain `host:port` strings or {@link UpstreamTarget} objects with a weight —
|
|
221
|
+
* to load-balance across.
|
|
222
|
+
*/
|
|
223
|
+
export type ProxyFrom = string | Array<string | UpstreamTarget>;
|
|
224
|
+
/** How {@link selectUpstream} picks the next upstream from a healthy pool. */
|
|
225
|
+
export type LoadBalancerStrategy = 'round-robin' | 'weighted-round-robin' | 'least-connections';
|
|
190
226
|
export type BaseProxyOptions = Partial<BaseProxyConfig>;
|
|
191
227
|
export type CleanupOptions = Partial<CleanupConfig>;
|
|
192
228
|
export type SharedProxyOptions = Partial<SharedProxyConfig>;
|