@stacksjs/rpx 0.11.14 → 0.11.15
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 +188 -184
- package/dist/chunk-0zdj72ps.js +161 -0
- package/dist/{chunk-3pgh05pc.js → chunk-hf6e07v4.js} +1 -1
- package/dist/{chunk-a0ddh9cv.js → chunk-kv17r01q.js} +1 -1
- package/dist/{chunk-5ygwd93k.js → chunk-pjwm8py7.js} +1 -1
- package/dist/daemon.d.ts +6 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -6
- package/dist/on-demand.d.ts +40 -0
- package/dist/types.d.ts +31 -0
- package/package.json +2 -2
- package/src/daemon.ts +115 -24
- package/src/index.ts +3 -0
- package/src/on-demand.ts +264 -0
- package/src/types.ts +59 -0
- package/dist/chunk-tx5hnj92.js +0 -157
|
@@ -46,4 +46,4 @@ export type ConfigOf = Config
|
|
|
46
46
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",X);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${q}${H} ${K.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
47
47
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=K.green("━".repeat(Z)),G=K.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?K.green("✓"):K.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=L.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,L.stdout.write(Q.lastRenderedLine),U)L.stdout.write(`
|
|
48
48
|
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await DQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await YQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var A8=new BQ("stacks");var h0=new BQ("rpx",{showTags:!1});function d0(){return process.env.SUDO_PASSWORD}function R8(Q){let U=d0(),X=Q.replace(/'/g,"'\\''");if(U)return PX(`echo '${U}' | sudo -S sh -c '${X}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return PX(`sudo -n sh -c '${X}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function bX(Q,U,X){if(X)h0.debug(`[rpx:${Q}] ${U}`)}var yX="[redacted]",f0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),p0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function u0(Q){let U=Q.toLowerCase();return f0.has(U)||U.endsWith("password")||U.includes("secret")||U.includes("token")}function EU(Q){if(Array.isArray(Q))return Q.map((X)=>EU(X));if(typeof Q==="string")return p0.test(Q)?yX:Q;if(!Q||typeof Q!=="object")return Q;let U={};for(let[X,Z]of Object.entries(Q)){if(u0(X)){U[X]=yX;continue}U[X]=EU(Z)}return U}function L8(Q,U){return JSON.stringify(EU(Q),null,U)}function w8(Q){if(hX(Q))return Q.proxies.map((U)=>{let X=U.to||"stacks.localhost";return X.startsWith("http")?new URL(X).hostname:X});if(dX(Q)){let U=Q.to||"stacks.localhost";return[U.startsWith("http")?new URL(U).hostname:U]}return["stacks.localhost"]}function K8(Q){return typeof Q==="object"&&Q!==null&&"certificate"in Q&&"privateKey"in Q&&typeof Q.certificate==="string"&&typeof Q.privateKey==="string"}function j8(Q){if(!Q)return"stacks.localhost";if(hX(Q)&&Q.proxies.length>0)return Q.proxies[0].to||"stacks.localhost";if(dX(Q))return Q.to||"stacks.localhost";return"stacks.localhost"}function F8(Q){return!!(Q&&("proxies"in Q)&&Array.isArray(Q.proxies))}function hX(Q){return"proxies"in Q&&Array.isArray(Q.proxies)}function dX(Q){return"to"in Q&&typeof Q.to==="string"}function I8(Q){return!!(Q&&("to"in Q)&&!("proxies"in Q))}function M8(Q,U){if(!U||U.length===0)return null;for(let X of U)if(Q===X.from||Q.startsWith(`${X.from}/`)){let Z=X.to.startsWith("http")?new URL(X.to).host:X.to,$=X.stripPrefix===!0?Q.slice(X.from.length)||"/":Q;return{targetHost:Z,targetPath:$}}return null}async function V8(Q,U){try{await vX.unlink(Q),bX("certificates",`Successfully deleted: ${Q}`,U)}catch(X){if(X.code!=="ENOENT")bX("certificates",`Warning: Could not delete ${Q}: ${X}`,U)}}
|
|
49
|
-
export{r as
|
|
49
|
+
export{r as Da,d0 as Ea,R8 as Fa,bX as Ga,EU as Ha,L8 as Ia,w8 as Ja,K8 as Ka,j8 as La,F8 as Ma,hX as Na,dX as Oa,I8 as Pa,M8 as Qa,V8 as Ra};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f,Ka as g,La as h,Ma as i,Na as j,Oa as k,Pa as l,Qa as m,Ra as n}from"./chunk-hf6e07v4.js";export{e as safeStringify,n as safeDeleteFile,m as resolvePathRewrite,d as redactSensitive,g as isValidRootCA,k as isSingleProxyOptions,l as isSingleProxyConfig,j as isMultiProxyOptions,i as isMultiProxyConfig,a as getSudoPassword,h as getPrimaryDomain,f as extractHostname,b as execSudoSync,c as debugLog};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ea as a,fa as b,ga as c,ha as d,ia as e,ja as f,ka as g,la as h,ma as i,na as j,oa as k,pa as l,qa as m,ra as n}from"./chunk-0zdj72ps.js";import"./chunk-hf6e07v4.js";export{l as tearDownDevelopmentDns,k as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,h as setupResolver,j as setupDevelopmentDns,f as resolverFilePath,m as removeResolver,i as removeLegacyTldResolvers,n as reconcileStaleDevelopmentDns,e as isDnsServerRunning,g as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
|
package/dist/daemon.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ProductionTlsConfig, TlsOption } from './types';
|
|
1
|
+
import type { OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
|
|
2
2
|
export declare function getDaemonRpxDir(): string;
|
|
3
3
|
export declare function getDaemonPidPath(rpxDir?: string): string;
|
|
4
4
|
/**
|
|
@@ -27,6 +27,9 @@ export declare function releaseDaemonLock(rpxDir?: string): Promise<void>;
|
|
|
27
27
|
* listeners are bound and the initial routing table is populated. Use
|
|
28
28
|
* `handle.done` for the lifetime promise.
|
|
29
29
|
*/
|
|
30
|
+
// `opts` IS used throughout; pickier's no-unused-vars mis-fires on this fn after
|
|
31
|
+
// the on-demand serve refactor (its --fix would wrongly rename to `_opts`).
|
|
32
|
+
// eslint-disable-next-line pickier/no-unused-vars
|
|
30
33
|
export declare function runDaemon(opts?: DaemonOptions): Promise<DaemonHandle>;
|
|
31
34
|
/**
|
|
32
35
|
* Best-effort default for the spawn command used by lazy-spawn. Compiled
|
|
@@ -68,6 +71,7 @@ export declare interface DaemonOptions {
|
|
|
68
71
|
hostname?: string
|
|
69
72
|
https?: TlsOption
|
|
70
73
|
productionCerts?: ProductionTlsConfig
|
|
74
|
+
onDemandTls?: OnDemandTlsConfig
|
|
71
75
|
gcIntervalMs?: number
|
|
72
76
|
}
|
|
73
77
|
export declare interface DaemonHandle {
|
|
@@ -76,6 +80,7 @@ export declare interface DaemonHandle {
|
|
|
76
80
|
httpsPort: number
|
|
77
81
|
httpPort: number
|
|
78
82
|
pidPath: string
|
|
83
|
+
ensureCert: (host: string) => Promise<boolean>
|
|
79
84
|
}
|
|
80
85
|
export declare interface EnsureDaemonOptions {
|
|
81
86
|
rpxDir?: string
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export type {
|
|
|
12
12
|
export type { GetRoute, ProxyFetchHandler, ProxyRoute, ProxyServer } from './proxy-handler';
|
|
13
13
|
export type { ResolvedStaticRoute, StaticResolution } from './static-files';
|
|
14
14
|
export type { SniTlsEntry } from './sni';
|
|
15
|
+
export type { CertIssuer, OnDemandCertManagerOptions } from './on-demand';
|
|
15
16
|
export type { DaemonRunnerOptions, DaemonRunnerProxy } from './daemon-runner';
|
|
16
17
|
export { colors } from './colors';
|
|
17
18
|
export { config, config as defaultConfig } from './config';
|
|
@@ -111,6 +112,7 @@ export {
|
|
|
111
112
|
serveStaticFile,
|
|
112
113
|
} from './static-files';
|
|
113
114
|
export { buildSniTlsConfig, serverNameFromCertFilename } from './sni';
|
|
115
|
+
export { isLikelyHostname, matchesAllowedSuffix, OnDemandCertManager } from './on-demand';
|
|
114
116
|
export { deriveIdFromTarget, runViaDaemon } from './daemon-runner';
|
|
115
117
|
export { cleanup } from './start';
|
|
116
118
|
export { startProxies, startProxy, startServer } from './start';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{$ as hD,A as z_,B as
|
|
1
|
+
import{$ as hD,A as z_,Aa as W_,B as FD,Ba as W2,C as M_,Ca as X2,D as TD,E as ED,F as ID,G as wD,H as F_,I as T_,J as E_,K as jD,L as I_,M as HD,N as kD,O as CD,P as xD,Q as qD,R as Y_,S as $_,T as fD,U as G_,V as R_,W as yD,X as UD,Y as OD,Z as PD,_ as LD,a as X,aa as cD,b as B_,ba as uD,c as o_,ca as mD,d as e_,da as vD,e as _D,ea as bD,f as DD,fa as lD,g as BD,ga as aD,h as ND,ha as dD,i as KD,ia as pD,j as YD,ja as gD,k as $D,ka as iD,l as GD,la as nD,m as RD,ma as tD,n as WD,na as rD,o as XD,oa as sD,p as JD,pa as oD,q as QD,qa as eD,r as ZD,ra as _2,s as AD,sa as D2,t as SD,ta as B2,u as VD,ua as N2,v as zD,va as K2,w as N_,wa as Y2,x as MD,xa as $2,y as u,ya as G2,z as K_,za as R2}from"./chunk-0zdj72ps.js";import{Da as V_,Ea as v,Fa as MB,Ga as N,Ha as FB,Ia as f,Ja as TB,Ka as EB,La as IB,Ma as wB,Na as jB,Oa as HB,Pa as kB,Qa as CB,Ra as xB}from"./chunk-hf6e07v4.js";import{execSync as p_}from"node:child_process";import*as L from"node:http";import*as c_ from"node:http2";import*as u_ from"node:net";import*as T from"node:process";var n=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,C={bold:n(1,22),dim:n(2,22),green:n(32,39),cyan:n(36,39)};import*as q_ from"node:fs";import*as f_ from"node:path";import*as q from"node:process";function y_(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,K=new Set,Y=D.proxies.map((V)=>{let E=V.id??y_(V.to);if(!$_(E))throw Error(`invalid registry id "${E}" derived from to="${V.to}"`);if(K.has(E))throw Error(`duplicate registry id "${E}" — set an explicit \`id\` on one of the proxies`);return K.add(E),{...V,id:E}}),R=new Date().toISOString();for(let V of Y)await G_({id:V.id,from:V.from,to:V.to,pid:D.persistent?void 0:q.pid,cwd:q.cwd(),createdAt:R,cleanUrls:V.cleanUrls,changeOrigin:V.changeOrigin,pathRewrites:V.pathRewrites,static:V.static},B,_);let G=await W_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let V of Y){let E=V.static?`static ${typeof V.static==="string"?V.static:V.static.dir}`:V.from;X.success(`https://${V.to} → ${E}`)}if(X.info(`(via rpx daemon pid=${G.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let A=!1,W=B??Y_(),Q=Y.map((V)=>V.id),I=async()=>{if(A)return;A=!0;for(let V of Q)await R_(V,B,_).catch((E)=>{N("runner",`removeEntry(${V}) failed: ${E}`,_)})},j=(V)=>{N("runner",`received ${V}, unregistering ${Q.length} entries`,_),I().finally(()=>q.exit(0))};q.once("SIGINT",j),q.once("SIGTERM",j),q.once("exit",()=>{if(A)return;for(let V of Q)try{q_.unlinkSync(f_.join(W,`${V}.json`))}catch{}}),await new Promise(()=>{})}import{exec as b_}from"node:child_process";import O from"node:fs";import O_ from"node:os";import J_ from"node:path";import*as b from"node:process";import{promisify as l_}from"node:util";var r=l_(b_);function U_(D){let _=D.trim().toLowerCase();return _==="localhost"||_.endsWith(".localhost")||_.endsWith(".localhost.")}var k=b.platform==="win32"?J_.join(b.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",X_=!1;async function s(D){if(b.platform==="win32")throw Error("Administrator privileges required on Windows");let _=v(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:K}=await r(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return X_=!0,K}if(X_)try{let{stdout:K}=await r(`sudo -n sh -c '${B}'`);return K}catch(K){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:K}=await r(`sudo -n sh -c '${B}'`);return X_=!0,K}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(K){throw Error(`Failed to execute sudo command: ${K.message}`)}}async function h(D,_){let B=D.filter((Y)=>!U_(Y)),K=D.filter((Y)=>U_(Y));if(K.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${K.join(", ")}`,_);if(B.length===0)return;N("hosts",`Adding hosts: ${B.join(", ")}`,_),N("hosts",`Using hosts file at: ${k}`,_);try{let Y;try{Y=await O.promises.readFile(k,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{Y=await s(`cat "${k}"`)}catch(W){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${W}`,_),Error(`Cannot read hosts file: ${W}`)}}let R=B.filter((W)=>{let Q=`127.0.0.1 ${W}`,I=`::1 ${W}`;return!Y.includes(Q)&&!Y.includes(I)});if(R.length===0){N("hosts","All hosts already exist in hosts file",_);return}let G=R.map((W)=>`
|
|
2
2
|
# Added by rpx
|
|
3
|
-
127.0.0.1 ${
|
|
4
|
-
::1 ${
|
|
5
|
-
`),
|
|
6
|
-
`),Y=!1,R=
|
|
3
|
+
127.0.0.1 ${W}
|
|
4
|
+
::1 ${W}`).join(`
|
|
5
|
+
`),A=J_.join(O_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await O.promises.writeFile(A,Y+G,"utf8"),await s(`cat "${A}" | tee "${k}" > /dev/null`),console.log(` Hosts updated: ${R.join(", ")}`)}catch(W){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),R.forEach((Q)=>{console.log(` 127.0.0.1 ${Q}`),console.log(` ::1 ${Q}`)}),console.log(` Or run: sudo nano ${k}`)}finally{try{await O.promises.unlink(A)}catch{}}}catch(Y){N("hosts",`Failed to manage hosts file: ${Y.message}`,_)}}async function Q_(D,_){N("hosts",`Removing hosts: ${D.join(", ")}`,_);try{let B;try{B=await O.promises.readFile(k,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await s(`cat "${k}"`)}catch(W){throw N("hosts",`sudo read also failed: ${W}`,_),Error(`Cannot read hosts file: ${W}`)}}let K=B.split(`
|
|
6
|
+
`),Y=!1,R=K.filter((W)=>{if(D.some((I)=>W.includes(` ${I}`)&&(W.includes("127.0.0.1")||W.includes("::1"))))return Y=!0,!1;if(W.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){N("hosts","No matching hosts found to remove",_);return}while(R[R.length-1]?.trim()==="")R.pop();let G=`${R.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,V=J_.join(O_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await O.promises.writeFile(V,G,"utf8"),await s(`cat "${V}" | tee "${k}" > /dev/null`),K("hosts","Hosts removed successfully",_)}catch(X){K("hosts","Could not clean up hosts file automatically",_)}finally{try{await O.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 c(D,_){K("hosts",`Checking hosts: ${D}`,_);let B;try{B=await O.promises.readFile(k,"utf-8")}catch(N){K("hosts",`Error reading hosts file: ${N}`,_);try{let Y=v(),R;if(Y)R=`echo '${Y}' | sudo -S cat "${k}" 2>/dev/null`;else R=`sudo -n cat "${k}" 2>/dev/null || cat "${k}" 2>/dev/null || echo ""`;let{stdout:G}=await r(R);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}`,R=`::1 ${N}`;return B.includes(Y)||B.includes(R)})}import*as o from"node:net";function U(D,_,B){return K("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((N)=>{let Y=o.createServer(),R=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(R),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(R),K("port",`Port ${D} is available`,B),Y.close(),N(!1)});try{Y.listen(D,_)}catch(G){clearTimeout(R),K("port",`Exception checking port ${D}: ${G}`,B),N(!0)}})}async function L_(D,_,B,N=50){K("port",`Finding available port starting from ${D} (max attempts: ${N})`,B);let Y=D,R=0;while(R<N){if(R++,!await U(Y,_,B))return K("port",`Found available port: ${Y} after ${R} attempts`,B),Y;K("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${R}/${N})`,B),Y++}throw Error(`Unable to find available port after ${N} attempts starting from ${D}`)}function P_(D,_,B=5000,N){return K("port",`Testing connection to ${_}:${D}`,N),new Promise((Y)=>{let R=o.connect({host:_,port:D,timeout:B});R.once("connect",()=>{K("port",`Successfully connected to ${_}:${D}`,N),R.end(),Y(!0)}),R.once("timeout",()=>{K("port",`Connection to ${_}:${D} timed out`,N),R.destroy(),Y(!1)}),R.once("error",(G)=>{K("port",`Failed to connect to ${_}:${D}: ${G.message}`,N),R.destroy(),Y(!1)})})}class l{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 U(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await P_(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 L_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await P_(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 a_=new l;import{spawn as d_}from"node:child_process";import*as P 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(" "),R=_.cwd||P.cwd();K("start",`Starting process ${D}:`,B),K("start",` Command: ${N} ${Y.join(" ")}`,B),K("start",` Working directory: ${R}`,B),K("start",` Environment variables: ${f(_.env)}`,B);let G=d_(N,Y,{cwd:R,env:{...P.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:R,process:G,env:_.env}),new Promise((V,X)=>{if(G.on("error",(Q)=>{if(!this.isShuttingDown)K("start",`Process ${D} failed to start: ${Q}`,B),this.processes.delete(D),X(Q),P.emit("SIGINT")}),G.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)K("start",`Process ${D} exited with code ${Q}`,B),this.processes.delete(D),X(Error(`Process ${D} exited with code ${Q}`)),P.emit("SIGINT")}),B)G.stdout?.on("data",(Q)=>{K("process",`[${D}] ${Q.toString().trim()}`,!0)}),G.stderr?.on("data",(Q)=>{K("process",`[${D}] ERR: ${Q.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)=>{W.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 k2=new e;var D_=new e,g_="0.12.0",i_=new l("0.0.0.0"),a=new Set,Z_=!1,__=null,V_=null;async function p(D){if(Z_)return K("cleanup","Cleanup already in progress, skipping",D?.verbose),V_||Promise.resolve();Z_=!0,K("cleanup","Starting cleanup process",D?.verbose),V_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),W.info("Shutting down proxy servers...");let _=[],B=Array.from(a).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)W.info("Cleaning up hosts file entries..."),_.push(Q_(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),W.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),W.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(R){K("cleanup",`Failed to remove certificates for ${Y}: ${R}`,D?.verbose),W.warn(`Failed to clean up certificates for ${Y}:`,R)}});_.push(...N)}await Promise.allSettled(_),K("cleanup","All cleanup tasks completed successfully",D?.verbose),W.success("All cleanup tasks completed successfully")}catch(_){K("cleanup",`Error during cleanup: ${_}`,D?.verbose),W.error("Error during cleanup:",_)}finally{if(__)__();__=null,Z_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(M.env.NODE_ENV!=="test"&&M.env.BUN_ENV!=="test"&&!_)M.exit(0)}return V_}var A_=!1;function I_(D){if(A_){K("signal",`Received second ${D} signal, forcing exit`,!0),M.exit(1);return}A_=!0,K("signal",`Received ${D} signal, initiating cleanup`,!0),p().catch((_)=>{K("signal",`Cleanup failed after ${D}: ${_}`,!0),M.exit(1)}).finally(()=>{A_=!1})}M.once("SIGINT",()=>I_("SIGINT"));M.once("SIGTERM",()=>I_("SIGTERM"));M.on("uncaughtException",(D)=>{K("process",`Uncaught exception: ${D}`,!0),W.error("Uncaught exception:",D),I_("uncaughtException")});async function d(D,_,B,N=5){K("connection",`Testing connection to ${D}:${_} (retries left: ${N})`,B);let Y=15000,R=Date.now();if(M.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 Q=u_.connect({host:D,port:_,timeout:3000});Q.once("connect",()=>{K("connection",`Successfully connected to ${D}:${_}`,B),Q.end(),V()}),Q.once("timeout",()=>{K("connection",`Connection to ${D}:${_} timed out`,B),Q.destroy(),X(Error("Connection timed out"))}),Q.once("error",(E)=>{K("connection",`Failed to connect to ${D}:${_}: ${E}`,B),Q.destroy(),X(E)})});try{await G()}catch(V){if(Date.now()-R>Y){K("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),W.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((Q)=>setTimeout(Q,2000)),d(D,_,B,N-1);if(N>0)try{K("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((Q,E)=>{let j=L.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(S)=>{K("connection",`Received HTTP response with status: ${S.statusCode}`,B),Q()});j.on("error",(S)=>E(S)),j.on("timeout",()=>{j.destroy(),E(Error("HTTP request timed out"))}),j.end()}),K("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(Q){return K("connection",`HTTP request to ${D}:${_} failed: ${Q}`,B),K("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,B),await new Promise((E)=>setTimeout(E,2000)),d(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),W.warn(X),W.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 j_(D){K("server",`Starting server with options: ${f(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(H_(D)&&!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 c(Y,D.verbose))[0]){W.info(`Adding ${B.hostname} to hosts file...`),W.info("This may require sudo/administrator privileges");try{await h(Y,D.verbose)}catch(V){if(W.error("Failed to add hosts entry:",V.message),W.warn("You can manually add this entry to your hosts file:"),W.warn(`127.0.0.1 ${B.hostname}`),W.warn(`::1 ${B.hostname}`),M.platform==="win32")W.warn("On Windows:"),W.warn("1. Run notepad as administrator"),W.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else W.warn("On Unix systems:"),W.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch(G){W.error("Failed to check hosts file:",G.message)}}try{await d(_.hostname,N,D.verbose)}catch(G){K("server",`Connection test failed: ${G}`,D.verbose),W.error(G.message),W.warn("Continuing with proxy setup despite connection test failure..."),W.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let R=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=N_({...D,to:B.hostname});if(R=await u({...D,to:B.hostname,https:D.https}),!R){if(K("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await K_({...D,from:_.toString(),to:B.hostname,https:D.https}),R=await u({...D,to:B.hostname,https:D.https}),!R)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 t_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:N,sourceUrl:{hostname:_.hostname,host:_.host},ssl:R})}async function n_(D,_,B,N,Y,R,G,V,X,Q,E){K("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${Q}`,X);function j(Z){let J={};for(let[A,z]of Object.entries(Z))if(!A.startsWith(":"))J[A]=z;return J}let S=(Z,J)=>{K("request",`Incoming request: ${Z.method} ${Z.url}`,X);let A=Z.url||"/",z=Z.method||"GET";if(Z instanceof c_.Http2ServerRequest){let F=Z.headers;z=F[":method"]||z,A=F[":path"]||A}if(Q){if(!A.match(/\.[a-z0-9]+$/i))if(A.endsWith("/"))A=`${A}index.html`;else A=`${A}.html`}let H=j(Z.headers);if(E)H.host=`${R.hostname}:${B}`,K("request",`Changed origin: setting host header to ${H.host}`,X);let T={hostname:R.hostname,port:B,path:A,method:z,headers:H};K("request",`Proxy request options: ${f(T)}`,X);let I=L.request(T,(F)=>{if(K("response",`Proxy response received with status ${F.statusCode}`,X),Q&&F.statusCode===404){let y=[];if(A.endsWith(".html"))y.push(A.slice(0,-5));else if(!A.match(/\.[a-z0-9]+$/i))y.push(`${A}.html`);if(!A.endsWith("/"))y.push(`${A}/index.html`);if(y.length>0){K("cleanUrls",`Trying alternative paths: ${y.join(", ")}`,X);let m=(g)=>{if(g.length===0){J.writeHead(F.statusCode||404,F.headers),F.pipe(J);return}let C_=g[0],v_={...T,path:C_},q_=L.request(v_,(i)=>{if(i.statusCode===200)K("cleanUrls",`Found matching path: ${C_}`,X),J.writeHead(i.statusCode,i.headers),i.pipe(J);else m(g.slice(1))});q_.on("error",()=>m(g.slice(1))),q_.end()};m(y);return}}let q={...F.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};J.writeHead(F.statusCode||500,q),F.pipe(J)});I.on("error",(F)=>{K("request",`Proxy request failed: ${F}`,X),W.error("Proxy request failed:",F),J.writeHead(502),J.end(`Proxy Error: ${F.message}`)}),Z.pipe(I)};if(K("server",`Creating server with SSL config: ${!!G}`,X),G)return new Promise((Z,J)=>{try{let A=Bun.serve({port:N,hostname:Y,tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(z){let H=new URL(z.url);K("request",`Bun.serve received: ${z.method} ${H.pathname}`,X);let T=`http://${R.host}`,I=new URL(H.pathname+H.search,T);try{let F=new Headers(z.headers);if(F.set("host",R.host),E)F.set("origin",T);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",_);let q=await fetch(I.toString(),{method:z.method,headers:F,body:z.body,redirect:"manual"}),y=new Headers(q.headers);if(Q&&H.pathname.endsWith(".html")){let m=H.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}return new Response(q.body,{status:q.status,statusText:q.statusText,headers:y})}catch(F){return K("request",`Proxy error: ${F}`,X),new Response(`Proxy Error: ${F}`,{status:502})}},error(z){return K("server",`Bun.serve error: ${z}`,X),new Response(`Server Error: ${z.message}`,{status:500})}});a.add(A),h_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!0,cleanUrls:Q,verbose:X}),Z()}catch(A){J(A)}});let w=L.createServer(S);function $(Z){return a.add(Z),new Promise((J,A)=>{Z.listen(N,Y,()=>{K("server",`Server listening on port ${N}`,X),h_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!!G,cleanUrls:Q,verbose:X}),J()}),Z.on("error",(z)=>{K("server",`Server error: ${z}`,X),A(z)})})}return $(w)}async function t_(D){K("setup",`Setting up reverse proxy: ${f(D)}`,D.verbose);let{from:_,to:B,fromPort:N,sourceUrl:Y,ssl:R,verbose:G,cleanup:V,vitePluginUsage:X,changeOrigin:Q,cleanUrls:E}=D,j=80,S=443,w="0.0.0.0",$=D.portManager||i_,Z=H_(D);try{if(Z&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await c([B],G))[0]){W.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await h([B],G),W.success(`Added ${B} to your hosts file.`)}catch(T){W.error(`Failed to add ${B} to your hosts file: ${T}`),W.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(Z&&M.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await c([B],G))[0]){K("hosts",`${B} not found in hosts file, adding...`,G);try{await h([B],G)}catch(T){K("hosts",`Failed to add ${B} to hosts file: ${T}`,G)}}}if(R&&!$.usedPorts.has(j)){if(!await U(j,w,G))K("setup","Starting HTTP redirect server",G),m_(G),$.usedPorts.add(j);else if(K("setup","Port 80 is in use, skipping HTTP redirect",G),G)W.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let J=R?S:j,A=await U(J,w,G),z;if(A){if(K("setup",`Port ${J} is already in use`,G),G)W.warn(`Port ${J} is already in use. This may be another instance of rpx or another service.`);if(J===443){if(z=await $.getNextAvailablePort(3443,!0),K("setup",`Using port ${z} instead of ${J}`,G),G)W.info(`Using port ${z} instead. Access your site at https://${B}:${z}`)}else if(z=await $.getNextAvailablePort(J+1000,!0),K("setup",`Using port ${z} instead of ${J}`,G),G)W.info(`Using port ${z} instead. Access your site at http://${B}:${z}`)}else z=J,$.usedPorts.add(z),K("setup",`Using standard ${J===443?"HTTPS":"HTTP"} port ${J} for ${B}`,G);await n_(_,B,N,z,w,Y,R,X,G,E,Q)}catch(J){K("setup",`Setup failed: ${J}`,G),W.error(`Failed to setup reverse proxy: ${J.message}`),p({domains:[B],hosts:typeof V==="boolean"?V:V?.hosts,certs:typeof V==="boolean"?V:V?.certs,verbose:G,vitePluginUsage:X})}}function m_(D){K("redirect","Starting HTTP redirect server",D);let _=L.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);a.add(_),K("redirect","HTTP redirect server started",D)}function r_(D){let _={...B_,...D};if(K("proxy",`Starting proxy with options: ${f(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){W.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)=>{W.error(`Failed to register with rpx daemon: ${X.message}`),M.exit(1)});return}let B=_.to||"",N=B.split(".").pop()?.toLowerCase()||"",Y=M.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),R=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"];if(Y&&R.includes(N)&&_?.verbose)W.warn(`The .${N} TLD may not work reliably for local development`),W.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),W.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-5ygwd93k.js").then(({setupDevelopmentDns:X})=>{X({domains:[B],verbose:_.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if(_.verbose)if(G.includes(N))W.success(`DNS server started for .${N} domains`);else W.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: ${f(V)}`,_.verbose),j_(V).catch((X)=>{K("proxy",`Failed to start proxy: ${X}`,_.verbose),W.error(`Failed to start proxy: ${X.message}`),p({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function s_(D){return D?.verbose||!1}function H_(D){if(D?.hostsManagement===!1)return!1;let _=D?.cleanup;if(_===!1)return!1;if(_&&typeof _==="object"&&_.hosts===!1)return!1;return!0}async function k_(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=s_(_),N=H_(_);if(K("config",`Starting with config: ${f(_,2)}`,B),K("config",`Is multi-proxy? ${"proxies"in _}`,B),K("config",`Hosts management enabled? ${N}`,B),_.viaDaemon){let Z="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((J)=>({id:J.id,from:J.from,to:J.to,cleanUrls:J.cleanUrls??_.cleanUrls,changeOrigin:J.changeOrigin??_.changeOrigin,pathRewrites:J.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:Z,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 Z=`${$.from}-${$.to}`;try{K("watch",`Starting command for ${Z} with command: ${$.start.command}`,B),W.info(`Starting command for ${Z}...`),await D_.startProcess(Z,$.start,B);let J=new URL($.from.startsWith("http")?$.from:`http://${$.from}`),A=J.hostname||"localhost",z=Number(J.port)||80;try{await d(A,z,B),K("watch",`Dev server is ready at ${A}:${z}`,B)}catch(H){K("watch",`Connection check failed, but continuing with proxy setup: ${H}`,B),W.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(J){throw K("watch",`Failed to start command for ${Z}: ${J}`,B),Error(`Failed to start command for ${Z}: ${J}`)}}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 Z=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),J=Z.hostname||"localhost",A=Number(Z.port)||80;try{await d(J,A,B),K("watch",`Dev server is ready at ${J}:${A}`,B)}catch(z){K("watch",`Connection check failed, but continuing with proxy setup: ${z}`,B),W.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw K("watch",`Failed to run start command: ${Z}`,B),Error(`Failed to run start command: ${Z}`)}}else K("watch","No start command found in config",B);let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(M.platform!=="win32"&&(_.https||N)){if(!v())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",B),p_("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let $=await u(_);if(!$){if(K("ssl",`No valid or trusted certificates found for ${Y}, generating new ones`,_.verbose),await K_(_),$=await u(_),!$)throw Error(`Failed to load SSL certificates after generation for ${Y}`)}else K("ssl",`Using existing and trusted certificates for ${Y}`,_.verbose);_._cachedSSLConfig=$}let R="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}],G=R.map(($)=>$.to||"rpx.localhost"),V=_._cachedSSLConfig,X=G.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],j=[...new Set(X.map(($)=>$.split(".").pop()?.toLowerCase()))],S=j.filter(($)=>!!$&&Q.includes($));if(S.length>0&&B)W.warn(`The following TLDs may not work reliably for local development: ${S.map(($)=>`.${$}`).join(", ")}`),W.info(" These TLDs have HSTS preloading which can bypass local DNS"),W.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(N&&M.platform==="darwin"&&X.length>0){let{setupDevelopmentDns:$}=await import("./chunk-5ygwd93k.js");if(await $({domains:X,verbose:B})){if(B)if(j.every((A)=>!!A&&E.includes(A)))W.success(`DNS server started for ${j.map((A)=>`.${A}`).join(", ")} domains`);else W.success(`DNS server started for ${j.map((A)=>`.${A}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",B)}let w=async()=>{K("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-5ygwd93k.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 p({domains:G,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(M.on("SIGINT",w),M.on("SIGTERM",w),M.on("uncaughtException",($)=>{K("process",`Uncaught exception: ${$}`,!0),console.error("Uncaught exception:",$),w()}),V&&R.length>1){K("proxies",`Creating shared HTTPS server for ${R.length} domains`,B);let $=new Map;for(let T of R){let I=T.to||"rpx.localhost",F=T.cleanUrls||!1;if(T.static)$.set(I,{static:F_(T.static,F),cleanUrls:F}),K("proxies",`Route: ${I} → static ${typeof T.static==="string"?T.static:T.static.dir}`,B);else{let q=new URL(T.from?.startsWith("http")?T.from:`http://${T.from}`);$.set(I,{sourceHost:q.host,cleanUrls:F,changeOrigin:T.changeOrigin||!1,pathRewrites:T.pathRewrites}),K("proxies",`Route: ${I} → ${q.host}`,B)}if(N&&!w_(I)&&!I.includes("localhost")&&!I.includes("127.0.0.1"))try{if(!(await c([I],B))[0])await h([I],B)}catch{K("hosts",`Could not add hosts entry for ${I}`,B)}}if(!await U(80,"0.0.0.0",B))m_(B);let J=443;if(await U(J,"0.0.0.0",B)){if(K("proxies",`Port ${J} is already in use, cannot start shared proxy`,B),B)W.warn(`Port ${J} is in use. Shared HTTPS proxy cannot start.`);return}let z=T_((T)=>E_($,T),B),H=M_(B);try{let T=Bun.serve({port:J,hostname:"0.0.0.0",tls:{key:V.key,cert:V.cert,ca:V.ca,requestCert:!1,rejectUnauthorized:!1},fetch(I,F){return z(I,F)},websocket:H,error(I){return K("server",`Shared proxy server error: ${I}`,B),new Response(`Server Error: ${I.message}`,{status:500})}});a.add(T),K("proxies",`Shared HTTPS proxy listening on port ${J} for ${$.size} domains`,B)}catch(T){K("proxies",`Failed to start shared proxy: ${T}`,B),console.error("Failed to start shared HTTPS proxy:",T),w()}}else for(let $ of R)try{let Z=$.to||"rpx.localhost";K("proxy",`Starting proxy for ${Z} with SSL config: ${!!V}`,$.verbose),await j_({from:$.from||"localhost:5173",to:Z,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:V,changeOrigin:$.changeOrigin||!1})}catch(Z){K("proxies",`Failed to start proxy for ${$.to}: ${Z}`,$.verbose),console.error(`Failed to start proxy for ${$.to}:`,Z),w()}}function h_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${C.green(C.bold("rpx"))} ${C.green(`v${g_}`)}`),console.log(` ${C.green("➜")} ${C.dim(D?.from??"")} ${C.dim("➜")} ${C.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${C.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${C.green("➜")} Clean URLs enabled`)}var ZB=k_;export{G_ as writeEntry,yD as watchRegistry,BD as verifyHttpsChain,ZD as trustRootCaForBrowsers,tD as tearDownDevelopmentDns,nD as syncDevelopmentDnsFromRegistry,bD as stopDnsServer,$2 as stopDaemon,j_ as startServer,r_ as startProxy,k_ as startProxies,vD as startDnsServer,pD as setupResolver,iD as setupDevelopmentDns,HD as serverNameFromCertFilename,ID as serveStaticFile,f as safeStringify,wD as safeRelativePath,jB as safeDeleteFile,t as runViaDaemon,N2 as runDaemon,aD as resolverFilePath,hD as resolverBasenamesForDomains,LD as resolverBasenameForDomain,F_ as resolveStaticRoute,ED as resolveStaticFile,IB as resolvePathRewrite,rD as removeResolver,gD as removeLegacyTldResolvers,Q_ as removeHosts,R_ as removeEntry,K2 as releaseDaemonLock,AB as redactSensitive,sD as reconcileStaleDevelopmentDns,G2 as reconcileDevelopmentDnsOnIdle,qD as readEntry,_2 as readDaemonPid,e_ as readCertSha256Fingerprint,_D as readCertCommonName,xD as readAll,WD as pruneStaleRootCas,a_ as portManager,KD as parseSha256HashesFromSecurityListing,o_ as normalizeSha256Fingerprint,PD as normalizeDevDomain,jD as matchesWildcard,E_ as matchHost,SD as loadSSLConfig,XD as listCertSha256HashesByCommonName,w_ as isWildcardPattern,zB as isValidRootCA,$_ as isValidId,wB as isSingleProxyOptions,EB as isSingleProxyConfig,JD as isRootCaTrustedForSsl,QD as isRootCaFingerprintInKeychains,U as isPortInUse,CD as isPidAlive,MB as isMultiProxyOptions,TB as isMultiProxyConfig,lD as isDnsServerRunning,D2 as isDaemonRunning,TD as isCertTrusted,N_ as httpsConfig,v as getSudoPassword,AD as getSharedDaemonCertPaths,VD as getRootCAPaths,Y_ as getRegistryDir,FB as getPrimaryDomain,RD as getMacosTrustKeychains,GD as getMacosLoginKeychainPath,oD as getDaemonRpxDir,eD as getDaemonPidPath,K_ as generateCertificate,fD as gcStaleEntries,zD as forceTrustCertificate,L_ as findAvailablePort,SB as extractHostname,VB as execSudoSync,X_ as ensureDaemonRunning,cD as devDomainsFromHosts,y_ as deriveIdFromTarget,Y2 as defaultDaemonSpawnCommand,B_ as defaultConfig,ZB as default,K as debugLog,M_ as createProxyWebSocketHandler,T_ as createProxyFetchHandler,MD as contentTypeFor,dD as contentLooksLikeRpxResolver,B_ as config,C as colors,FD as clearSslConfigCache,z_ as cleanupCertificates,p as cleanup,c as checkHosts,u as checkExistingCertificates,DD as certIncludesSanHostnames,kD as buildSniTlsConfig,h as addHosts,B2 as acquireDaemonLock,$D as RPX_ROOT_CA_COMMON_NAME,mD as RPX_RESOLVER_MARKER,YD as MACOS_SYSTEM_KEYCHAIN,ND as MACOS_CA_TRUST_FLAGS,OD as LEGACY_TLD_RESOLVER_LABELS,l as DefaultPortManager,UD as DNS_STATE_VERSION,uD as DNS_PORT};
|
|
8
|
+
`,A=J_.join(O_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await O.promises.writeFile(A,G,"utf8"),await s(`cat "${A}" | tee "${k}" > /dev/null`),N("hosts","Hosts removed successfully",_)}catch(W){N("hosts","Could not clean up hosts file automatically",_)}finally{try{await O.promises.unlink(A)}catch(W){N("hosts",`Failed to remove temporary file: ${W}`,_)}}}catch(B){N("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function c(D,_){N("hosts",`Checking hosts: ${D}`,_);let B;try{B=await O.promises.readFile(k,"utf-8")}catch(K){N("hosts",`Error reading hosts file: ${K}`,_);try{let Y=v(),R;if(Y)R=`echo '${Y}' | sudo -S cat "${k}" 2>/dev/null`;else R=`sudo -n cat "${k}" 2>/dev/null || cat "${k}" 2>/dev/null || echo ""`;let{stdout:G}=await r(R);B=G}catch(Y){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,_),D.map(()=>!1)}}return D.map((K)=>{let Y=`127.0.0.1 ${K}`,R=`::1 ${K}`;return B.includes(Y)||B.includes(R)})}import*as o from"node:net";function U(D,_,B){return N("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((K)=>{let Y=o.createServer(),R=setTimeout(()=>{N("port",`Checking port ${D} timed out, assuming it's in use`,B),Y.close(),K(!0)},3000);Y.once("error",(G)=>{if(clearTimeout(R),G.code==="EADDRINUSE")N("port",`Port ${D} is in use`,B),K(!0);else N("port",`Error checking port ${D}: ${G.message}`,B),K(!0)}),Y.once("listening",()=>{clearTimeout(R),N("port",`Port ${D} is available`,B),Y.close(),K(!1)});try{Y.listen(D,_)}catch(G){clearTimeout(R),N("port",`Exception checking port ${D}: ${G}`,B),K(!0)}})}async function L_(D,_,B,K=50){N("port",`Finding available port starting from ${D} (max attempts: ${K})`,B);let Y=D,R=0;while(R<K){if(R++,!await U(Y,_,B))return N("port",`Found available port: ${Y} after ${R} attempts`,B),Y;N("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${R}/${K})`,B),Y++}throw Error(`Unable to find available port after ${K} attempts starting from ${D}`)}function P_(D,_,B=5000,K){return N("port",`Testing connection to ${_}:${D}`,K),new Promise((Y)=>{let R=o.connect({host:_,port:D,timeout:B});R.once("connect",()=>{N("port",`Successfully connected to ${_}:${D}`,K),R.end(),Y(!0)}),R.once("timeout",()=>{N("port",`Connection to ${_}:${D} timed out`,K),R.destroy(),Y(!1)}),R.once("error",(G)=>{N("port",`Failed to connect to ${_}:${D}: ${G.message}`,K),R.destroy(),Y(!1)})})}class l{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 U(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await P_(D,this.hostname,3000,this.verbose))return N("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 L_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await P_(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){N("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var a_=new l;import{spawn as d_}from"node:child_process";import*as P from"node:process";class e{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){N("start",`Process ${D} is already running`,B);return}let[K,...Y]=_.command.split(" "),R=_.cwd||P.cwd();N("start",`Starting process ${D}:`,B),N("start",` Command: ${K} ${Y.join(" ")}`,B),N("start",` Working directory: ${R}`,B),N("start",` Environment variables: ${f(_.env)}`,B);let G=d_(K,Y,{cwd:R,env:{...P.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:R,process:G,env:_.env}),new Promise((A,W)=>{if(G.on("error",(Q)=>{if(!this.isShuttingDown)N("start",`Process ${D} failed to start: ${Q}`,B),this.processes.delete(D),W(Q),P.emit("SIGINT")}),G.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)N("start",`Process ${D} exited with code ${Q}`,B),this.processes.delete(D),W(Error(`Process ${D} exited with code ${Q}`)),P.emit("SIGINT")}),B)G.stdout?.on("data",(Q)=>{N("process",`[${D}] ${Q.toString().trim()}`,!0)}),G.stderr?.on("data",(Q)=>{N("process",`[${D}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&G.killed)this.processes.delete(D),W(Error(`Process ${D} was killed during startup`));else N("start",`Process ${D} started successfully`,B),A()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){N("start",`No process found for ${D}`,_);return}return N("start",`Stopping process ${D}`,_),new Promise((K)=>{if(!B.process){K();return}B.process.once("exit",()=>{this.processes.delete(D),N("start",`Process ${D} stopped`,_),K()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){N("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){N("start",`Error stopping process ${D}: ${Y}`,_),this.processes.delete(D),K()}})}async stopAll(D){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,N("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((K)=>{X.error(`Failed to stop process ${B}:`,K)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var q2=new e;var D_=new e,g_="0.12.0",i_=new l("0.0.0.0"),a=new Set,Z_=!1,__=null,A_=null;async function p(D){if(Z_)return N("cleanup","Cleanup already in progress, skipping",D?.verbose),A_||Promise.resolve();Z_=!0,N("cleanup","Starting cleanup process",D?.verbose),A_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),X.info("Shutting down proxy servers...");let _=[],B=Array.from(a).map((K)=>new Promise((Y)=>{K.close(()=>{N("cleanup","Server closed successfully",D?.verbose),Y()})}));if(_.push(...B),D?.hosts&&D.domains?.length){N("cleanup","Cleaning up hosts file entries",D?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let K=D.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(K)}`,D?.verbose),K.length>0)X.info("Cleaning up hosts file entries..."),_.push(Q_(K,D?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${K.join(", ")}`,D?.verbose)}).catch((Y)=>{N("cleanup",`Failed to remove hosts entries: ${Y}`,D?.verbose),X.warn(`Failed to clean up hosts file entries for ${K.join(", ")}:`,Y)}))}if(D?.certs&&D.domains?.length){N("cleanup","Cleaning up SSL certificates",D?.verbose),X.info("Cleaning up SSL certificates...");let K=D.domains.map(async(Y)=>{try{await z_(Y,D?.verbose),N("cleanup",`Removed certificates for ${Y}`,D?.verbose)}catch(R){N("cleanup",`Failed to remove certificates for ${Y}: ${R}`,D?.verbose),X.warn(`Failed to clean up certificates for ${Y}:`,R)}});_.push(...K)}await Promise.allSettled(_),N("cleanup","All cleanup tasks completed successfully",D?.verbose),X.success("All cleanup tasks completed successfully")}catch(_){N("cleanup",`Error during cleanup: ${_}`,D?.verbose),X.error("Error during cleanup:",_)}finally{if(__)__();__=null,Z_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(T.env.NODE_ENV!=="test"&&T.env.BUN_ENV!=="test"&&!_)T.exit(0)}return A_}var S_=!1;function w_(D){if(S_){N("signal",`Received second ${D} signal, forcing exit`,!0),T.exit(1);return}S_=!0,N("signal",`Received ${D} signal, initiating cleanup`,!0),p().catch((_)=>{N("signal",`Cleanup failed after ${D}: ${_}`,!0),T.exit(1)}).finally(()=>{S_=!1})}T.once("SIGINT",()=>w_("SIGINT"));T.once("SIGTERM",()=>w_("SIGTERM"));T.on("uncaughtException",(D)=>{N("process",`Uncaught exception: ${D}`,!0),X.error("Uncaught exception:",D),w_("uncaughtException")});async function d(D,_,B,K=5){N("connection",`Testing connection to ${D}:${_} (retries left: ${K})`,B);let Y=15000,R=Date.now();if(T.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let G=()=>new Promise((A,W)=>{let Q=u_.connect({host:D,port:_,timeout:3000});Q.once("connect",()=>{N("connection",`Successfully connected to ${D}:${_}`,B),Q.end(),A()}),Q.once("timeout",()=>{N("connection",`Connection to ${D}:${_} timed out`,B),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(I)=>{N("connection",`Failed to connect to ${D}:${_}: ${I}`,B),Q.destroy(),W(I)})});try{await G()}catch(A){if(Date.now()-R>Y){N("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),X.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(A.code==="ECONNREFUSED"&&K>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${K} retries left)`,B),await new Promise((Q)=>setTimeout(Q,2000)),d(D,_,B,K-1);if(K>0)try{N("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((Q,I)=>{let j=L.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(V)=>{N("connection",`Received HTTP response with status: ${V.statusCode}`,B),Q()});j.on("error",(V)=>I(V)),j.on("timeout",()=>{j.destroy(),I(Error("HTTP request timed out"))}),j.end()}),N("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(Q){return N("connection",`HTTP request to ${D}:${_} failed: ${Q}`,B),N("connection",`Retrying socket connection in 2 seconds... (${K} retries left)`,B),await new Promise((I)=>setTimeout(I,2000)),d(D,_,B,K-1)}let W=`Failed to connect to ${D}:${_} after ${5-K} attempts: ${A.message}`;N("connection",`${W}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),X.warn(W),X.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 j_(D){N("server",`Starting server with options: ${f(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"),K=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),Y=[B.hostname];if(H_(D)&&!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await c(Y,D.verbose))[0]){X.info(`Adding ${B.hostname} to hosts file...`),X.info("This may require sudo/administrator privileges");try{await h(Y,D.verbose)}catch(A){if(X.error("Failed to add hosts entry:",A.message),X.warn("You can manually add this entry to your hosts file:"),X.warn(`127.0.0.1 ${B.hostname}`),X.warn(`::1 ${B.hostname}`),T.platform==="win32")X.warn("On Windows:"),X.warn("1. Run notepad as administrator"),X.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else X.warn("On Unix systems:"),X.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch(G){X.error("Failed to check hosts file:",G.message)}}try{await d(_.hostname,K,D.verbose)}catch(G){N("server",`Connection test failed: ${G}`,D.verbose),X.error(G.message),X.warn("Continuing with proxy setup despite connection test failure..."),X.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let R=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=K_({...D,to:B.hostname});if(R=await u({...D,to:B.hostname,https:D.https}),!R){if(N("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await N_({...D,from:_.toString(),to:B.hostname,https:D.https}),R=await u({...D,to:B.hostname,https:D.https}),!R)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch(G){throw N("server",`SSL setup failed: ${G}`,D.verbose),G}N("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await t_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:K,sourceUrl:{hostname:_.hostname,host:_.host},ssl:R})}async function n_(D,_,B,K,Y,R,G,A,W,Q,I){N("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${Q}`,W);function j(Z){let J={};for(let[S,z]of Object.entries(Z))if(!S.startsWith(":"))J[S]=z;return J}let V=(Z,J)=>{N("request",`Incoming request: ${Z.method} ${Z.url}`,W);let S=Z.url||"/",z=Z.method||"GET";if(Z instanceof c_.Http2ServerRequest){let M=Z.headers;z=M[":method"]||z,S=M[":path"]||S}if(Q){if(!S.match(/\.[a-z0-9]+$/i))if(S.endsWith("/"))S=`${S}index.html`;else S=`${S}.html`}let H=j(Z.headers);if(I)H.host=`${R.hostname}:${B}`,N("request",`Changed origin: setting host header to ${H.host}`,W);let F={hostname:R.hostname,port:B,path:S,method:z,headers:H};N("request",`Proxy request options: ${f(F)}`,W);let w=L.request(F,(M)=>{if(N("response",`Proxy response received with status ${M.statusCode}`,W),Q&&M.statusCode===404){let y=[];if(S.endsWith(".html"))y.push(S.slice(0,-5));else if(!S.match(/\.[a-z0-9]+$/i))y.push(`${S}.html`);if(!S.endsWith("/"))y.push(`${S}/index.html`);if(y.length>0){N("cleanUrls",`Trying alternative paths: ${y.join(", ")}`,W);let m=(g)=>{if(g.length===0){J.writeHead(M.statusCode||404,M.headers),M.pipe(J);return}let C_=g[0],v_={...F,path:C_},x_=L.request(v_,(i)=>{if(i.statusCode===200)N("cleanUrls",`Found matching path: ${C_}`,W),J.writeHead(i.statusCode,i.headers),i.pipe(J);else m(g.slice(1))});x_.on("error",()=>m(g.slice(1))),x_.end()};m(y);return}}let x={...M.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};J.writeHead(M.statusCode||500,x),M.pipe(J)});w.on("error",(M)=>{N("request",`Proxy request failed: ${M}`,W),X.error("Proxy request failed:",M),J.writeHead(502),J.end(`Proxy Error: ${M.message}`)}),Z.pipe(w)};if(N("server",`Creating server with SSL config: ${!!G}`,W),G)return new Promise((Z,J)=>{try{let S=Bun.serve({port:K,hostname:Y,tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(z){let H=new URL(z.url);N("request",`Bun.serve received: ${z.method} ${H.pathname}`,W);let F=`http://${R.host}`,w=new URL(H.pathname+H.search,F);try{let M=new Headers(z.headers);if(M.set("host",R.host),I)M.set("origin",F);M.set("x-forwarded-for","127.0.0.1"),M.set("x-forwarded-proto","https"),M.set("x-forwarded-host",_);let x=await fetch(w.toString(),{method:z.method,headers:M,body:z.body,redirect:"manual"}),y=new Headers(x.headers);if(Q&&H.pathname.endsWith(".html")){let m=H.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}return new Response(x.body,{status:x.status,statusText:x.statusText,headers:y})}catch(M){return N("request",`Proxy error: ${M}`,W),new Response(`Proxy Error: ${M}`,{status:502})}},error(z){return N("server",`Bun.serve error: ${z}`,W),new Response(`Server Error: ${z.message}`,{status:500})}});a.add(S),h_({from:D,to:_,vitePluginUsage:A,listenPort:K,ssl:!0,cleanUrls:Q,verbose:W}),Z()}catch(S){J(S)}});let E=L.createServer(V);function $(Z){return a.add(Z),new Promise((J,S)=>{Z.listen(K,Y,()=>{N("server",`Server listening on port ${K}`,W),h_({from:D,to:_,vitePluginUsage:A,listenPort:K,ssl:!!G,cleanUrls:Q,verbose:W}),J()}),Z.on("error",(z)=>{N("server",`Server error: ${z}`,W),S(z)})})}return $(E)}async function t_(D){N("setup",`Setting up reverse proxy: ${f(D)}`,D.verbose);let{from:_,to:B,fromPort:K,sourceUrl:Y,ssl:R,verbose:G,cleanup:A,vitePluginUsage:W,changeOrigin:Q,cleanUrls:I}=D,j=80,V=443,E="0.0.0.0",$=D.portManager||i_,Z=H_(D);try{if(Z&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await c([B],G))[0]){X.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await h([B],G),X.success(`Added ${B} to your hosts file.`)}catch(F){X.error(`Failed to add ${B} to your hosts file: ${F}`),X.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(Z&&T.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await c([B],G))[0]){N("hosts",`${B} not found in hosts file, adding...`,G);try{await h([B],G)}catch(F){N("hosts",`Failed to add ${B} to hosts file: ${F}`,G)}}}if(R&&!$.usedPorts.has(j)){if(!await U(j,E,G))N("setup","Starting HTTP redirect server",G),m_(G),$.usedPorts.add(j);else if(N("setup","Port 80 is in use, skipping HTTP redirect",G),G)X.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let J=R?V:j,S=await U(J,E,G),z;if(S){if(N("setup",`Port ${J} is already in use`,G),G)X.warn(`Port ${J} is already in use. This may be another instance of rpx or another service.`);if(J===443){if(z=await $.getNextAvailablePort(3443,!0),N("setup",`Using port ${z} instead of ${J}`,G),G)X.info(`Using port ${z} instead. Access your site at https://${B}:${z}`)}else if(z=await $.getNextAvailablePort(J+1000,!0),N("setup",`Using port ${z} instead of ${J}`,G),G)X.info(`Using port ${z} instead. Access your site at http://${B}:${z}`)}else z=J,$.usedPorts.add(z),N("setup",`Using standard ${J===443?"HTTPS":"HTTP"} port ${J} for ${B}`,G);await n_(_,B,K,z,E,Y,R,W,G,I,Q)}catch(J){N("setup",`Setup failed: ${J}`,G),X.error(`Failed to setup reverse proxy: ${J.message}`),p({domains:[B],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:G,vitePluginUsage:W})}}function m_(D){N("redirect","Starting HTTP redirect server",D);let _=L.createServer((B,K)=>{let Y=B.headers.host||"";N("redirect",`Redirecting request from ${Y}${B.url} to HTTPS`,D),K.writeHead(301,{Location:`https://${Y}${B.url}`}),K.end()}).listen(80);a.add(_),N("redirect","HTTP redirect server started",D)}function r_(D){let _={...B_,...D};if(N("proxy",`Starting proxy with options: ${f(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){X.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((W)=>{X.error(`Failed to register with rpx daemon: ${W.message}`),T.exit(1)});return}let B=_.to||"",K=B.split(".").pop()?.toLowerCase()||"",Y=T.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),R=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"];if(Y&&R.includes(K)&&_?.verbose)X.warn(`The .${K} TLD may not work reliably for local development`),X.info(` Google owns .${K} with HSTS preloading, which can bypass local DNS`),X.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-pjwm8py7.js").then(({setupDevelopmentDns:W})=>{W({domains:[B],verbose:_.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if(_.verbose)if(G.includes(K))X.success(`DNS server started for .${K} domains`);else X.success(`DNS server started for .${K} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,_.verbose)});let A={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:K_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};N("proxy",`Server options: ${f(A)}`,_.verbose),j_(A).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,_.verbose),X.error(`Failed to start proxy: ${W.message}`),p({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function s_(D){return D?.verbose||!1}function H_(D){if(D?.hostsManagement===!1)return!1;let _=D?.cleanup;if(_===!1)return!1;if(_&&typeof _==="object"&&_.hosts===!1)return!1;return!0}async function k_(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=s_(_),K=H_(_);if(N("config",`Starting with config: ${f(_,2)}`,B),N("config",`Is multi-proxy? ${"proxies"in _}`,B),N("config",`Hosts management enabled? ${K}`,B),_.viaDaemon){let Z="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((J)=>({id:J.id,from:J.from,to:J.to,cleanUrls:J.cleanUrls??_.cleanUrls,changeOrigin:J.changeOrigin??_.changeOrigin,pathRewrites:J.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:Z,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){N("servers",`Found ${_.proxies.length} proxies in config`,B);for(let $ of _.proxies)if($.start){let Z=`${$.from}-${$.to}`;try{N("watch",`Starting command for ${Z} with command: ${$.start.command}`,B),X.info(`Starting command for ${Z}...`),await D_.startProcess(Z,$.start,B);let J=new URL($.from.startsWith("http")?$.from:`http://${$.from}`),S=J.hostname||"localhost",z=Number(J.port)||80;try{await d(S,z,B),N("watch",`Dev server is ready at ${S}:${z}`,B)}catch(H){N("watch",`Connection check failed, but continuing with proxy setup: ${H}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(J){throw N("watch",`Failed to start command for ${Z}: ${J}`,B),Error(`Failed to start command for ${Z}: ${J}`)}}else N("watch",`No start command for proxy ${$.from} -> ${$.to}`,B)}else if("start"in _&&_.start){N("watch","Found start command in single proxy config",B);let $=`${_.from}-${_.to}`;try{if(_.start)N("watch",`Starting command: ${_.start.command}`,B),await D_.startProcess($,_.start,B);let Z=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),J=Z.hostname||"localhost",S=Number(Z.port)||80;try{await d(J,S,B),N("watch",`Dev server is ready at ${J}:${S}`,B)}catch(z){N("watch",`Connection check failed, but continuing with proxy setup: ${z}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw N("watch",`Failed to run start command: ${Z}`,B),Error(`Failed to run start command: ${Z}`)}}else N("watch","No start command found in config",B);let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(T.platform!=="win32"&&(_.https||K)){if(!v())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",B),p_("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let $=await u(_);if(!$){if(N("ssl",`No valid or trusted certificates found for ${Y}, generating new ones`,_.verbose),await N_(_),$=await u(_),!$)throw Error(`Failed to load SSL certificates after generation for ${Y}`)}else N("ssl",`Using existing and trusted certificates for ${Y}`,_.verbose);_._cachedSSLConfig=$}let R="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}],G=R.map(($)=>$.to||"rpx.localhost"),A=_._cachedSSLConfig,W=G.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],I=["test","localhost","local","example","invalid"],j=[...new Set(W.map(($)=>$.split(".").pop()?.toLowerCase()))],V=j.filter(($)=>!!$&&Q.includes($));if(V.length>0&&B)X.warn(`The following TLDs may not work reliably for local development: ${V.map(($)=>`.${$}`).join(", ")}`),X.info(" These TLDs have HSTS preloading which can bypass local DNS"),X.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(K&&T.platform==="darwin"&&W.length>0){let{setupDevelopmentDns:$}=await import("./chunk-pjwm8py7.js");if(await $({domains:W,verbose:B})){if(B)if(j.every((S)=>!!S&&I.includes(S)))X.success(`DNS server started for ${j.map((S)=>`.${S}`).join(", ")} domains`);else X.success(`DNS server started for ${j.map((S)=>`.${S}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",B)}let E=async()=>{N("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-pjwm8py7.js");await $({verbose:_.verbose})}catch($){N("cleanup",`Error stopping DNS server: ${$}`,_.verbose)}try{await D_.stopAll(_.verbose)}catch($){N("cleanup",`Error stopping processes: ${$}`,_.verbose)}await p({domains:G,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(T.on("SIGINT",E),T.on("SIGTERM",E),T.on("uncaughtException",($)=>{N("process",`Uncaught exception: ${$}`,!0),console.error("Uncaught exception:",$),E()}),A&&R.length>1){N("proxies",`Creating shared HTTPS server for ${R.length} domains`,B);let $=new Map;for(let F of R){let w=F.to||"rpx.localhost",M=F.cleanUrls||!1;if(F.static)$.set(w,{static:M_(F.static,M),cleanUrls:M}),N("proxies",`Route: ${w} → static ${typeof F.static==="string"?F.static:F.static.dir}`,B);else{let x=new URL(F.from?.startsWith("http")?F.from:`http://${F.from}`);$.set(w,{sourceHost:x.host,cleanUrls:M,changeOrigin:F.changeOrigin||!1,pathRewrites:F.pathRewrites}),N("proxies",`Route: ${w} → ${x.host}`,B)}if(K&&!E_(w)&&!w.includes("localhost")&&!w.includes("127.0.0.1"))try{if(!(await c([w],B))[0])await h([w],B)}catch{N("hosts",`Could not add hosts entry for ${w}`,B)}}if(!await U(80,"0.0.0.0",B))m_(B);let J=443;if(await U(J,"0.0.0.0",B)){if(N("proxies",`Port ${J} is already in use, cannot start shared proxy`,B),B)X.warn(`Port ${J} is in use. Shared HTTPS proxy cannot start.`);return}let z=F_((F)=>I_($,F),B),H=T_(B);try{let F=Bun.serve({port:J,hostname:"0.0.0.0",tls:{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1},fetch(w,M){return z(w,M)},websocket:H,error(w){return N("server",`Shared proxy server error: ${w}`,B),new Response(`Server Error: ${w.message}`,{status:500})}});a.add(F),N("proxies",`Shared HTTPS proxy listening on port ${J} for ${$.size} domains`,B)}catch(F){N("proxies",`Failed to start shared proxy: ${F}`,B),console.error("Failed to start shared HTTPS proxy:",F),E()}}else for(let $ of R)try{let Z=$.to||"rpx.localhost";N("proxy",`Starting proxy for ${Z} with SSL config: ${!!A}`,$.verbose),await j_({from:$.from||"localhost:5173",to:Z,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:A,changeOrigin:$.changeOrigin||!1})}catch(Z){N("proxies",`Failed to start proxy for ${$.to}: ${Z}`,$.verbose),console.error(`Failed to start proxy for ${$.to}:`,Z),E()}}function h_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${C.green(C.bold("rpx"))} ${C.green(`v${g_}`)}`),console.log(` ${C.green("➜")} ${C.dim(D?.from??"")} ${C.dim("➜")} ${C.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${C.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${C.green("➜")} Clean URLs enabled`)}var zB=k_;export{G_ as writeEntry,PD as watchRegistry,BD as verifyHttpsChain,ZD as trustRootCaForBrowsers,oD as tearDownDevelopmentDns,sD as syncDevelopmentDnsFromRegistry,dD as stopDnsServer,W2 as stopDaemon,j_ as startServer,r_ as startProxy,k_ as startProxies,aD as startDnsServer,nD as setupResolver,rD as setupDevelopmentDns,HD as serverNameFromCertFilename,wD as serveStaticFile,f as safeStringify,ED as safeRelativePath,xB as safeDeleteFile,t as runViaDaemon,G2 as runDaemon,gD as resolverFilePath,mD as resolverBasenamesForDomains,uD as resolverBasenameForDomain,M_ as resolveStaticRoute,ID as resolveStaticFile,CB as resolvePathRewrite,eD as removeResolver,tD as removeLegacyTldResolvers,Q_ as removeHosts,R_ as removeEntry,$2 as releaseDaemonLock,FB as redactSensitive,_2 as reconcileStaleDevelopmentDns,X2 as reconcileDevelopmentDnsOnIdle,yD as readEntry,N2 as readDaemonPid,e_ as readCertSha256Fingerprint,_D as readCertCommonName,UD as readAll,XD as pruneStaleRootCas,a_ as portManager,ND as parseSha256HashesFromSecurityListing,o_ as normalizeSha256Fingerprint,cD as normalizeDevDomain,jD as matchesWildcard,CD as matchesAllowedSuffix,I_ as matchHost,VD as loadSSLConfig,WD as listCertSha256HashesByCommonName,E_ as isWildcardPattern,EB as isValidRootCA,$_ as isValidId,HB as isSingleProxyOptions,kB as isSingleProxyConfig,JD as isRootCaTrustedForSsl,QD as isRootCaFingerprintInKeychains,U as isPortInUse,fD as isPidAlive,jB as isMultiProxyOptions,wB as isMultiProxyConfig,xD as isLikelyHostname,pD as isDnsServerRunning,K2 as isDaemonRunning,FD as isCertTrusted,K_ as httpsConfig,v as getSudoPassword,SD as getSharedDaemonCertPaths,AD as getRootCAPaths,Y_ as getRegistryDir,IB as getPrimaryDomain,RD as getMacosTrustKeychains,GD as getMacosLoginKeychainPath,D2 as getDaemonRpxDir,B2 as getDaemonPidPath,N_ as generateCertificate,OD as gcStaleEntries,zD as forceTrustCertificate,L_ as findAvailablePort,TB as extractHostname,MB as execSudoSync,W_ as ensureDaemonRunning,vD as devDomainsFromHosts,y_ as deriveIdFromTarget,R2 as defaultDaemonSpawnCommand,B_ as defaultConfig,zB as default,N as debugLog,T_ as createProxyWebSocketHandler,F_ as createProxyFetchHandler,TD as contentTypeFor,iD as contentLooksLikeRpxResolver,B_ as config,C as colors,MD as clearSslConfigCache,z_ as cleanupCertificates,p as cleanup,c as checkHosts,u as checkExistingCertificates,DD as certIncludesSanHostnames,kD as buildSniTlsConfig,h as addHosts,Y2 as acquireDaemonLock,$D as RPX_ROOT_CA_COMMON_NAME,lD as RPX_RESOLVER_MARKER,qD as OnDemandCertManager,YD as MACOS_SYSTEM_KEYCHAIN,KD as MACOS_CA_TRUST_FLAGS,hD as LEGACY_TLD_RESOLVER_LABELS,l as DefaultPortManager,LD as DNS_STATE_VERSION,bD as DNS_PORT};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Http01Store, ObtainCertificateOptions, ObtainCertificateResult } from '@stacksjs/tlsx';
|
|
2
|
+
import type { OnDemandTlsConfig } from './types';
|
|
3
|
+
import type { SniTlsEntry } from './sni';
|
|
4
|
+
/**
|
|
5
|
+
* True if `host` is covered by the `allowedSuffixes` allowlist: it equals a
|
|
6
|
+
* suffix, or is a subdomain of one (`a.example.com` for suffix `example.com`).
|
|
7
|
+
*/
|
|
8
|
+
export declare function matchesAllowedSuffix(host: string, suffixes: string[] | undefined): boolean;
|
|
9
|
+
/** Strict-ish hostname guard so we never feed junk Host headers into ACME. */
|
|
10
|
+
export declare function isLikelyHostname(host: string): boolean;
|
|
11
|
+
export declare interface OnDemandCertManagerOptions {
|
|
12
|
+
config: OnDemandTlsConfig
|
|
13
|
+
certsDir: string
|
|
14
|
+
initial?: SniTlsEntry[]
|
|
15
|
+
onCertAdded?: (entries: SniTlsEntry[]) => void | Promise<void>
|
|
16
|
+
http01Store?: Http01Store
|
|
17
|
+
issuer?: CertIssuer
|
|
18
|
+
verbose?: boolean
|
|
19
|
+
negativeCacheMs?: number
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The issuance function the manager calls. Defaults to tlsx's
|
|
23
|
+
* {@link obtainCertificate}; tests inject a stub so the suite never touches
|
|
24
|
+
* Let's Encrypt.
|
|
25
|
+
*/
|
|
26
|
+
export type CertIssuer = (options: ObtainCertificateOptions) => Promise<ObtainCertificateResult>;
|
|
27
|
+
/**
|
|
28
|
+
* Holds the live SNI cert set and lazily issues certs for approved hosts.
|
|
29
|
+
*
|
|
30
|
+
* The set is keyed by SNI server name; `ensureCert(host)` is the entry point for
|
|
31
|
+
* both the reactive `:80` path and programmatic pre-warming.
|
|
32
|
+
*/
|
|
33
|
+
export declare class OnDemandCertManager {
|
|
34
|
+
constructor(opts: OnDemandCertManagerOptions);
|
|
35
|
+
get challengeStore(): Http01Store;
|
|
36
|
+
sniEntries(): SniTlsEntry[];
|
|
37
|
+
hasCert(host: string): boolean;
|
|
38
|
+
isApproved(host: string): Promise<boolean>;
|
|
39
|
+
ensureCert(host: string): Promise<boolean>;
|
|
40
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -47,6 +47,36 @@ export declare interface ProductionTlsConfig {
|
|
|
47
47
|
domains?: Record<string, DomainCert>
|
|
48
48
|
certsDir?: string
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* On-demand TLS: issue a real (Let's Encrypt, http-01) certificate for an
|
|
52
|
+
* unknown host the first time it's needed, gated by an `ask` callback and/or an
|
|
53
|
+
* `allowedSuffixes` allowlist to prevent abuse.
|
|
54
|
+
*
|
|
55
|
+
* ## Why this is "ask-gated issuance + listener recreate", not at-handshake
|
|
56
|
+
*
|
|
57
|
+
* Bun (verified on 1.3.14 + 1.4.0) has **no working SNICallback** and
|
|
58
|
+
* `server.reload({ tls })` does **not** update certs at runtime. So rpx cannot
|
|
59
|
+
* mint a cert during the TLS handshake the way Caddy's on-demand TLS does.
|
|
60
|
+
* Instead rpx:
|
|
61
|
+
* 1. Sees the first plaintext request for the host on its `:80` listener.
|
|
62
|
+
* 2. Asks `ask(host)` / checks `allowedSuffixes`; if approved, drives the
|
|
63
|
+
* ACME http-01 flow (serving the challenge from its own `:80`).
|
|
64
|
+
* 3. Writes the PEMs into `certsDir` and rebuilds the `:443` listener with the
|
|
65
|
+
* augmented SNI cert set (a sub-second `server.stop()` + re-`Bun.serve`).
|
|
66
|
+
* The subsequent HTTPS request then finds the freshly-issued cert.
|
|
67
|
+
*
|
|
68
|
+
* Issuance can also be triggered programmatically via the manager's
|
|
69
|
+
* `ensureCert(host)` (e.g. a tunnel server pre-warming a subdomain's cert on
|
|
70
|
+
* registration) so the cert exists before the first browser hit.
|
|
71
|
+
*/
|
|
72
|
+
export declare interface OnDemandTlsConfig {
|
|
73
|
+
enabled?: boolean
|
|
74
|
+
ask?: (host: string) => boolean | Promise<boolean>
|
|
75
|
+
allowedSuffixes?: string[]
|
|
76
|
+
email?: string
|
|
77
|
+
staging?: boolean
|
|
78
|
+
certsDir?: string
|
|
79
|
+
}
|
|
50
80
|
export declare interface SharedProxyConfig {
|
|
51
81
|
https: boolean | TlsOption
|
|
52
82
|
cleanup: boolean | CleanupOptions
|
|
@@ -60,6 +90,7 @@ export declare interface SharedProxyConfig {
|
|
|
60
90
|
viaDaemon?: boolean
|
|
61
91
|
hostsManagement?: boolean
|
|
62
92
|
productionCerts?: ProductionTlsConfig
|
|
93
|
+
onDemandTls?: OnDemandTlsConfig
|
|
63
94
|
}
|
|
64
95
|
export declare interface SingleProxyConfig extends BaseProxyConfig, SharedProxyConfig {}
|
|
65
96
|
export declare interface MultiProxyConfig extends SharedProxyConfig {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/rpx",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.15",
|
|
5
5
|
"description": "A modern and smart reverse proxy.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@stacksjs/clapp": "^0.2.10",
|
|
72
|
-
"@stacksjs/tlsx": "^0.13.
|
|
72
|
+
"@stacksjs/tlsx": "^0.13.7"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"bunfig": "^0.15.6",
|
package/src/daemon.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* paths are reachable without touching `~/.stacks/rpx` or :443.
|
|
17
17
|
*/
|
|
18
18
|
/* eslint-disable no-console */
|
|
19
|
-
import type { ProductionTlsConfig, ProxyOptions, SSLConfig, TlsOption } from './types'
|
|
19
|
+
import type { OnDemandTlsConfig, ProductionTlsConfig, ProxyOptions, SSLConfig, TlsOption } from './types'
|
|
20
20
|
import type { ProxyRoute, ProxyServer as ProxyServerLike } from './proxy-handler'
|
|
21
21
|
import { spawn as nodeSpawn } from 'node:child_process'
|
|
22
22
|
import * as fsp from 'node:fs/promises'
|
|
@@ -28,6 +28,7 @@ import { checkExistingCertificates, generateCertificate } from './https'
|
|
|
28
28
|
import { createProxyFetchHandler, createProxyWebSocketHandler } from './proxy-handler'
|
|
29
29
|
import { matchHost } from './host-match'
|
|
30
30
|
import { buildSniTlsConfig } from './sni'
|
|
31
|
+
import { OnDemandCertManager } from './on-demand'
|
|
31
32
|
import { resolveStaticRoute } from './static-files'
|
|
32
33
|
import { gcStaleEntries, getRegistryDir, isPidAlive, readAll, watchRegistry } from './registry'
|
|
33
34
|
import type { RegistryEntry } from './registry'
|
|
@@ -58,6 +59,12 @@ export interface DaemonOptions {
|
|
|
58
59
|
* self-signed shared cert.
|
|
59
60
|
*/
|
|
60
61
|
productionCerts?: ProductionTlsConfig
|
|
62
|
+
/**
|
|
63
|
+
* On-demand TLS: lazily issue real certs for approved unknown hosts via ACME
|
|
64
|
+
* http-01 (served from this daemon's `:80` listener). Opt-in via `enabled`.
|
|
65
|
+
* Seeded with the `productionCerts`/`certsDir` certs already on disk.
|
|
66
|
+
*/
|
|
67
|
+
onDemandTls?: OnDemandTlsConfig
|
|
61
68
|
/** PID-GC interval in ms. Defaults to 5000. */
|
|
62
69
|
gcIntervalMs?: number
|
|
63
70
|
}
|
|
@@ -70,6 +77,13 @@ export interface DaemonHandle {
|
|
|
70
77
|
httpsPort: number
|
|
71
78
|
httpPort: number
|
|
72
79
|
pidPath: string
|
|
80
|
+
/**
|
|
81
|
+
* Pre-warm an on-demand cert for `host` (issue it now if approved & missing,
|
|
82
|
+
* rebuilding the `:443` listener). Resolves `true` if a cert is available
|
|
83
|
+
* afterwards. No-op resolving `false` when on-demand TLS isn't enabled. Lets a
|
|
84
|
+
* tunnel server warm a subdomain's cert at registration time.
|
|
85
|
+
*/
|
|
86
|
+
ensureCert: (host: string) => Promise<boolean>
|
|
73
87
|
}
|
|
74
88
|
|
|
75
89
|
const DEFAULT_GC_INTERVAL_MS = 5000
|
|
@@ -290,6 +304,9 @@ async function elevateDaemonToRoot(
|
|
|
290
304
|
try { process.kill(pid, 'SIGTERM') }
|
|
291
305
|
catch { /* EPERM — root-owned shared daemon */ }
|
|
292
306
|
},
|
|
307
|
+
// On-demand issuance runs inside the elevated child's own runDaemon
|
|
308
|
+
// handle; this caller-side stub can't reach it directly.
|
|
309
|
+
ensureCert: () => Promise.resolve(false),
|
|
293
310
|
}
|
|
294
311
|
}
|
|
295
312
|
// sudo exits fast when auth fails; while the daemon runs it stays alive.
|
|
@@ -312,6 +329,9 @@ async function elevateDaemonToRoot(
|
|
|
312
329
|
* listeners are bound and the initial routing table is populated. Use
|
|
313
330
|
* `handle.done` for the lifetime promise.
|
|
314
331
|
*/
|
|
332
|
+
// `opts` IS used throughout; pickier's no-unused-vars mis-fires on this fn after
|
|
333
|
+
// the on-demand serve refactor (its --fix would wrongly rename to `_opts`).
|
|
334
|
+
// eslint-disable-next-line pickier/no-unused-vars
|
|
315
335
|
export async function runDaemon(opts: DaemonOptions = {}): Promise<DaemonHandle> {
|
|
316
336
|
const verbose = opts.verbose ?? false
|
|
317
337
|
const rpxDir = opts.rpxDir ?? getDaemonRpxDir()
|
|
@@ -372,34 +392,88 @@ export async function runDaemon(opts: DaemonOptions = {}): Promise<DaemonHandle>
|
|
|
372
392
|
const fetchHandler = createProxyFetchHandler(getRoute, verbose)
|
|
373
393
|
const wsHandler = createProxyWebSocketHandler(verbose)
|
|
374
394
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
395
|
+
// Bootstrap the dev shared cert once when there's no real SNI set, so a single
|
|
396
|
+
// SNI listener with on-demand can still answer hosts that aren't covered yet.
|
|
397
|
+
let devSslConfig: SSLConfig | null = null
|
|
398
|
+
if (sniTls.length === 0)
|
|
399
|
+
devSslConfig = await bootstrapTls(opts, registryDir)
|
|
400
|
+
|
|
401
|
+
// On-demand TLS manager (opt-in). Holds the live SNI set; lazily issues real
|
|
402
|
+
// certs for approved unknown hosts via ACME http-01 served from our :80
|
|
403
|
+
// listener (Bun can't issue at handshake time — see on-demand.ts header).
|
|
404
|
+
const onDemandCfg = opts.onDemandTls
|
|
405
|
+
const onDemand: OnDemandCertManager | null = onDemandCfg?.enabled
|
|
406
|
+
? new OnDemandCertManager({
|
|
407
|
+
config: onDemandCfg,
|
|
408
|
+
certsDir: onDemandCfg.certsDir ?? opts.productionCerts?.certsDir ?? path.join(rpxDir, 'on-demand-certs'),
|
|
409
|
+
initial: sniTls,
|
|
410
|
+
verbose,
|
|
411
|
+
// A new cert was issued/adopted — rebuild :443 with the augmented set.
|
|
412
|
+
onCertAdded: (entries) => { void rebuildTls(entries) },
|
|
413
|
+
})
|
|
414
|
+
: null
|
|
415
|
+
|
|
416
|
+
/** Build the TLS option for Bun.serve from the current SNI set (or dev cert). */
|
|
417
|
+
function tlsFor(entries: Array<{ serverName: string, cert: string, key: string }>): unknown {
|
|
418
|
+
if (entries.length > 0)
|
|
419
|
+
return entries.map(e => ({ serverName: e.serverName, cert: e.cert, key: e.key }))
|
|
420
|
+
// No real certs: fall back to the dev self-signed shared cert.
|
|
421
|
+
return {
|
|
422
|
+
key: devSslConfig!.key,
|
|
423
|
+
cert: devSslConfig!.cert,
|
|
424
|
+
ca: devSslConfig!.ca,
|
|
385
425
|
requestCert: false,
|
|
386
426
|
rejectUnauthorized: false,
|
|
387
427
|
}
|
|
388
428
|
}
|
|
389
429
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
430
|
+
/** (Re)create the :443 listener. Factored so on-demand can rebuild it. */
|
|
431
|
+
function serveHttps(entries: Array<{ serverName: string, cert: string, key: string }>): ReturnType<typeof Bun.serve> {
|
|
432
|
+
return Bun.serve({
|
|
433
|
+
port: httpsPort,
|
|
434
|
+
hostname,
|
|
435
|
+
tls: tlsFor(entries) as any,
|
|
436
|
+
fetch(req: Request, server: unknown) {
|
|
437
|
+
return fetchHandler(req, server as ProxyServerLike)
|
|
438
|
+
},
|
|
439
|
+
websocket: wsHandler,
|
|
440
|
+
error(err: Error) {
|
|
441
|
+
debugLog('daemon', `https server error: ${err}`, verbose)
|
|
442
|
+
return new Response(`Server Error: ${err.message}`, { status: 500 })
|
|
443
|
+
},
|
|
444
|
+
})
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let httpsServer = serveHttps(onDemand ? onDemand.sniEntries() : sniTls)
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Bun has no working SNICallback and `server.reload({ tls })` does not update
|
|
451
|
+
* certs at runtime (verified Bun 1.3.14/1.4.0). So to serve a freshly-issued
|
|
452
|
+
* cert we tear the old listener down and re-bind with the augmented SNI set.
|
|
453
|
+
* The rebind is sub-second; if the OS hasn't freed the port yet we retry on a
|
|
454
|
+
* short async backoff. In-flight requests on the old listener drain
|
|
455
|
+
* (`stop(false)`). Only ever invoked from the (async) issuance callback.
|
|
456
|
+
*/
|
|
457
|
+
async function rebuildTls(entries: Array<{ serverName: string, cert: string, key: string }>): Promise<void> {
|
|
458
|
+
if (stopped)
|
|
459
|
+
return
|
|
460
|
+
debugLog('daemon', `rebuilding :443 with ${entries.length} SNI cert(s)`, verbose)
|
|
461
|
+
httpsServer.stop(false)
|
|
462
|
+
let lastErr: unknown
|
|
463
|
+
for (let attempt = 0; attempt < 20 && !stopped; attempt++) {
|
|
464
|
+
try {
|
|
465
|
+
httpsServer = serveHttps(entries)
|
|
466
|
+
return
|
|
467
|
+
}
|
|
468
|
+
catch (err) {
|
|
469
|
+
// EADDRINUSE while the old socket releases — back off briefly, retry.
|
|
470
|
+
lastErr = err
|
|
471
|
+
await new Promise(resolve => setTimeout(resolve, 25))
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
// Could not rebind: the old listener is already down. Surface the failure.
|
|
475
|
+
log.error(`rpx: failed to rebuild :443 after issuing cert: ${(lastErr as Error)?.message}`)
|
|
476
|
+
}
|
|
403
477
|
|
|
404
478
|
let httpServer: ReturnType<typeof Bun.serve> | null = null
|
|
405
479
|
if (httpPort > 0) {
|
|
@@ -409,6 +483,22 @@ export async function runDaemon(opts: DaemonOptions = {}): Promise<DaemonHandle>
|
|
|
409
483
|
fetch(req: Request) {
|
|
410
484
|
const u = new URL(req.url)
|
|
411
485
|
const host = (req.headers.get('host') ?? u.hostname).split(':')[0]
|
|
486
|
+
|
|
487
|
+
// Serve ACME http-01 challenges for in-flight on-demand issuances.
|
|
488
|
+
if (onDemand && u.pathname.startsWith('/.well-known/acme-challenge/')) {
|
|
489
|
+
const keyAuth = onDemand.challengeStore.handlePath(u.pathname)
|
|
490
|
+
if (keyAuth !== undefined)
|
|
491
|
+
return new Response(keyAuth, { status: 200, headers: { 'content-type': 'text/plain' } })
|
|
492
|
+
return new Response('challenge not found', { status: 404 })
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// First plaintext hit for an approved-but-uncovered host: kick off
|
|
496
|
+
// issuance so the cert exists for the subsequent HTTPS request. We don't
|
|
497
|
+
// block the redirect on it (the browser retries over HTTPS anyway).
|
|
498
|
+
if (onDemand && !onDemand.hasCert(host)) {
|
|
499
|
+
onDemand.ensureCert(host).catch(() => {})
|
|
500
|
+
}
|
|
501
|
+
|
|
412
502
|
return new Response(null, {
|
|
413
503
|
status: 301,
|
|
414
504
|
headers: { Location: `https://${host}${u.pathname}${u.search}` },
|
|
@@ -483,6 +573,7 @@ export async function runDaemon(opts: DaemonOptions = {}): Promise<DaemonHandle>
|
|
|
483
573
|
httpsPort: typeof httpsServer.port === 'number' ? httpsServer.port : httpsPort,
|
|
484
574
|
httpPort: httpServer && typeof httpServer.port === 'number' ? httpServer.port : httpPort,
|
|
485
575
|
pidPath,
|
|
576
|
+
ensureCert: (host: string) => (onDemand ? onDemand.ensureCert(host) : Promise.resolve(false)),
|
|
486
577
|
}
|
|
487
578
|
}
|
|
488
579
|
|
package/src/index.ts
CHANGED
|
@@ -129,6 +129,9 @@ export type { ResolvedStaticRoute, StaticResolution } from './static-files'
|
|
|
129
129
|
export { buildSniTlsConfig, serverNameFromCertFilename } from './sni'
|
|
130
130
|
export type { SniTlsEntry } from './sni'
|
|
131
131
|
|
|
132
|
+
export { isLikelyHostname, matchesAllowedSuffix, OnDemandCertManager } from './on-demand'
|
|
133
|
+
export type { CertIssuer, OnDemandCertManagerOptions } from './on-demand'
|
|
134
|
+
|
|
132
135
|
export { deriveIdFromTarget, runViaDaemon } from './daemon-runner'
|
|
133
136
|
export type { DaemonRunnerOptions, DaemonRunnerProxy } from './daemon-runner'
|
|
134
137
|
|