@faulpeltz/dertunnel 0.7.6 → 0.7.8
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/dertunnel-client.js +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
package/dertunnel-client.js
CHANGED
|
@@ -133,5 +133,5 @@ ${e}`,R1=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),N1=Objec
|
|
|
133
133
|
`)+t,i=s+1,s=r.indexOf(`
|
|
134
134
|
`,i)}while(s!==-1);return n+=r.slice(i),n}var{stdout:__,stderr:v_}=m_,Mc=Symbol("GENERATOR"),Cr=Symbol("STYLER"),Ls=Symbol("IS_EMPTY"),b_=["ansi","ansi","ansi256","ansi16m"],Rr=Object.create(null),eR=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=__?__.level:0;r.level=e.level===void 0?t:e.level};var tR=r=>{let e=(...t)=>t.join(" ");return eR(e,r),Object.setPrototypeOf(e,Vs.prototype),e};function Vs(r){return tR(r)}Object.setPrototypeOf(Vs.prototype,Function.prototype);for(let[r,e]of Object.entries(Ke))Rr[r]={get(){let t=fn(this,Vc(e.open,e.close,this[Cr]),this[Ls]);return Object.defineProperty(this,r,{value:t}),t}};Rr.visible={get(){let r=fn(this,this[Cr],!0);return Object.defineProperty(this,"visible",{value:r}),r}};var Lc=(r,e,t,...s)=>r==="rgb"?e==="ansi16m"?Ke[t].ansi16m(...s):e==="ansi256"?Ke[t].ansi256(Ke.rgbToAnsi256(...s)):Ke[t].ansi(Ke.rgbToAnsi(...s)):r==="hex"?Lc("rgb",e,t,...Ke.hexToRgb(...s)):Ke[t][r](...s),rR=["rgb","hex","ansi256"];for(let r of rR){Rr[r]={get(){let{level:t}=this;return function(...s){let i=Vc(Lc(r,b_[t],"color",...s),Ke.color.close,this[Cr]);return fn(this,i,this[Ls])}}};let e="bg"+r[0].toUpperCase()+r.slice(1);Rr[e]={get(){let{level:t}=this;return function(...s){let i=Vc(Lc(r,b_[t],"bgColor",...s),Ke.bgColor.close,this[Cr]);return fn(this,i,this[Ls])}}}}var sR=Object.defineProperties(()=>{},{...Rr,level:{enumerable:!0,get(){return this[Mc].level},set(r){this[Mc].level=r}}}),Vc=(r,e,t)=>{let s,i;return t===void 0?(s=r,i=e):(s=t.openAll+r,i=e+t.closeAll),{open:r,close:e,openAll:s,closeAll:i,parent:t}},fn=(r,e,t)=>{let s=(...i)=>iR(s,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(s,sR),s[Mc]=r,s[Cr]=e,s[Ls]=t,s},iR=(r,e)=>{if(r.level<=0||!e)return r[Ls]?"":e;let t=r[Cr];if(t===void 0)return e;let{openAll:s,closeAll:i}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=g_(e,t.close,t.open),t=t.parent;let n=e.indexOf(`
|
|
135
135
|
`);return n!==-1&&(e=y_(e,i,s,n)),s+e+i};Object.defineProperties(Vs.prototype,Rr);var nR=Vs(),RD=Vs({level:v_?v_.level:0});var ue=nR;var N_=Y(R_(),1),{program:q_,createCommand:FD,createArgument:UD,createOption:HD,CommanderError:GD,InvalidArgumentError:zD,InvalidOptionArgumentError:BD,Command:KD,Argument:WD,Option:YD,Help:XD}=N_.default;var k_=/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i;function j_(){let r,e,t=new Promise((s,i)=>{r=s,e=i});return t.resolve=r,t.reject=e,t}var Nr=class{constructor(e,t){this.interval=e;this.func=t}lastUpdated=0;updateTimer;update(e,t){let s=new Date().valueOf();t||s-this.lastUpdated>this.interval?(clearTimeout(this.updateTimer),this.func(e),this.lastUpdated=s):this.updateTimer=setTimeout(()=>{this.func(e),this.updateTimer=void 0},this.interval-s+this.lastUpdated).unref()}};function $t(r){return r.toLocaleString("en-US",{useGrouping:!0})}function yn(r){if(r.length<=24)return{service:"",user:"",token:r};let e=Buffer.from(wR(r),"base64").toString("utf8").split("#");return{service:e[0]??"",user:e[1]??"",token:e[2]??""}}function wR(r){let e="",t=r.length;for(let s=0;s<2;s++,t--)for(let i=t-1;i>=0;i-=2)e+=r[i];return e}var nv=require("net"),ov=Y(require("tls"));var _n=(l=>(l[l.HELLO_REQ=1]="HELLO_REQ",l[l.HELLO_RESP=2]="HELLO_RESP",l[l.END=3]="END",l[l.SERVER_OPEN=4]="SERVER_OPEN",l[l.SERVER_CLOSE=5]="SERVER_CLOSE",l[l.CLIENT_CLOSE=6]="CLIENT_CLOSE",l[l.PING=7]="PING",l[l.PONG=8]="PONG",l[l.SERVER_DATA=65]="SERVER_DATA",l[l.CLIENT_DATA=66]="CLIENT_DATA",l))(_n||{});function D_(r){return{name:Object.keys(_n).find(e=>_n[e]===r)??"UNKNOWN",isBinary:!!(r&64)}}var M_=1;var $R="service";var il=$R+".",L_=5e3;var ER=1*1024*1024,Us=12,V_=70,F_=80,U_=0,H_=1,G_=2,z_=4,B_=8,K_=!!process.env.DERTUNNEL_DEBUG,vn=class{constructor(e){this.onMessage=e}buffer=void 0;async receive(e){let t=this.buffer?Buffer.concat([this.buffer,e]):e,s=0;for(;s<t.length;){if(t.length<s+Us)return this.buffer=t.subarray(s),!0;if(t[s+U_]!=V_||t[s+H_]!=F_)return this.reset(),!1;let i=t.readUint16LE(s+G_),n=t.readUint32LE(s+z_),o=t.readUint32LE(s+B_),u=o+Us+s;if(o>ER)return this.reset(),!1;if(t.length>=u)try{let c=t.subarray(s+Us,u);K_&&W_(i,n,c,!1),await this.onMessage(i,n,c)}catch{return this.reset(),!1}else break;s=u}return this.buffer=t.length>s?t.subarray(s):void 0,!0}reset(){this.buffer=void 0}};function qr(r,e,t,s){let i=Buffer.isBuffer(s)?s:s?Buffer.from(JSON.stringify(s)):void 0,n=Buffer.allocUnsafe(Us+(i?i.length:0));n.writeUint8(V_,U_),n.writeUint8(F_,H_),n.writeUint16LE(e,G_),n.writeUint32LE(t,z_),n.writeUint32LE(i?i.length:0,B_),i?.copy(n,Us,0);let o=r.write(n);return K_&&W_(e,t,i,!0),o}function Hs(r){return JSON.parse(r.toString("utf8"))}function W_(r,e,t,s){let{name:i,isBinary:n}=D_(r);console.debug(`[msg-${s?"out":"in"} ${i} ${e>0?e:""}] ${t?n?`- ${t.length} payload bytes`:t.toString("utf8"):"- empty"}`)}var nl=require("node:crypto");var SR=128,rr,kr;function OR(r){!rr||rr.length<r?(rr=Buffer.allocUnsafe(r*SR),nl.webcrypto.getRandomValues(rr),kr=0):kr+r>rr.length&&(nl.webcrypto.getRandomValues(rr),kr=0),kr+=r}function xR(r){return OR(r|=0),rr.subarray(kr-r,kr)}function TR(r,e,t){let s=(2<<31-Math.clz32(r.length-1|1))-1,i=Math.ceil(1.6*s*e/r.length);return(n=e)=>{if(!n)return"";let o="";for(;;){let a=t(i),u=i;for(;u--;)if(o+=r[a[u]&s]||"",o.length>=n)return o}}}function ol(r,e=21){return TR(r,e,xR)}var bn=ol("0123456789abcdef",8),a2=ol("0123456789abcdefghijklmnopqrstuvwxyz",24);var ev=4096,jr=13,Dr=10,Y_=new Uint8Array([72,84,84,80,47,49,46,49,jr,Dr]),PR=new Uint8Array([72,84,84,80,47,49,46,49,32]),al=0,wn=1,$n=2,ul=3,X_=4,tv=5,Gs=class{constructor(e){this.onParsed=e}state=al;id="";contentData;headers=[];expectedBodyLen=0;isRequest=!1;method="";path="";status=0;statusText="";startAt=0;onData(e){let s=0,i=0;for(;s<e.length&&s!==-1&&i++<100;)if(this.state===al||this.state===wn||this.state===$n){this.contentData=void 0;let n=s;if((s=e.indexOf(Y_,n))>=0)for(let o=0;o<1;o++){let a=s+Y_.length;for(;s>0&&e[s-1]!==Dr&&e[s-1]!==jr;)s--;let u=e.subarray(s,a).toString("ascii").split(" ");if(u.length!==3){s=a;break}let c=Z_(e,a);if(c){s=a+c.length,this.headers=Q_(c);let{nextState:l,len:h}=J_(this.headers,!0);this.state=l,this.expectedBodyLen=h}else break;this.isRequest=!0,this.id=bn(12),this.method=u[0].toUpperCase(),this.path=decodeURI(u[1]),this.onParsed?.({id:this.id,type:"http-request-header",headers:this.headers,method:this.method,path:this.path,status:0,statusText:"",startAt:this.startAt=new Date().valueOf()})}else if((s=e.indexOf(PR,n))>=0){let o=s,a=e.length;for(;s<a&&!(e[s+1]===jr&&e[s+2]===Dr);)s++;for(let u=0;u<1;u++){let c=e.subarray(o,s+1).toString("ascii").split(" ");if(c.length<3)break;let l=Z_(e,o);if(l){s=o+l.length,this.headers=Q_(l);let{nextState:f,len:p}=J_(this.headers,!1);this.state=f,this.expectedBodyLen=p}else break;let h=Number.parseInt(c[1]);if(!Number.isFinite(h)||h<100||h>999)break;this.isRequest=!1,this.status=h,this.statusText=c.slice(2).join(" "),this.onParsed?.({id:this.id,type:"http-response-header",headers:this.headers,status:this.status,statusText:this.statusText,method:this.method,path:this.path,endAt:new Date().valueOf()})}}}else if(this.state===ul){let{ok:n,p:o,size:a}=IR(e,s);s=o,a>0?(this.expectedBodyLen=a,this.state=n?X_:al):n&&(this.isRequest?this.onParsed?.({id:this.id,type:"http-request-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}):this.onParsed?.({id:this.id,type:"http-response-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}),s+=2,this.state=this.isRequest?$n:wn)}else if(this.state===X_){let n=Math.min(e.length-s,this.expectedBodyLen),o=e.slice(s,s+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,o]):Buffer.from(o),this.expectedBodyLen-=n,s+=n,this.expectedBodyLen===0&&(s+=2,this.state=ul)}else if(this.state===tv){let n=Math.min(e.length-s,this.expectedBodyLen),o=e.slice(s,s+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,o]):Buffer.from(o),this.expectedBodyLen-=n,s+=n,this.expectedBodyLen===0&&(this.isRequest?this.onParsed?.({id:this.id,type:"http-request-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}):this.onParsed?.({id:this.id,type:"http-response-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}),this.state=this.isRequest?$n:wn)}if(i>=100)throw new Error("Internal parser error: "+this.state)}};function J_(r,e){let t=Number.parseInt(r.find(s=>s.name==="content-length")?.value??"0");return r.find(s=>s.name==="transfer-encoding")?.value.includes("chunked")?{nextState:ul,isChunked:!0,len:0}:t>0?{nextState:tv,isChunked:!1,len:t}:{nextState:e?$n:wn,isChunked:!1,len:0}}function Z_(r,e){let t=e,s=Math.min(r.length-3,e+ev);for(;t<s&&!(r[t]===jr&&r[t+1]===Dr&&r[t+2]===jr&&r[t+3]===Dr);)t++;return t<s?r.slice(e,t+4):void 0}function Q_(r){let e=[],t=r.toString("ascii").split(`\r
|
|
136
|
-
`);for(let s of t){let i=s.indexOf(":");if(i<0)continue;let n=s.substring(0,i).toLowerCase().trim(),o=s.substring(i+1).trim();n.length>0&&o.length>0&&e.push({name:n,value:o})}return e}function IR(r,e){let t=0,s=e,i=!1,n=AR(r,e);return n!==void 0&&(t=Number.parseInt(n,16))>=0&&Number.isFinite(t)&&(s=e+n.length+2,i=!0),{ok:i,p:s,size:t}}function AR(r,e){let t=e,s=Math.min(r.length-1,e+ev);for(;t<s&&!(r[t]===jr&&r[t+1]===Dr);)t++;return t<s?r.slice(e,t).toString("ascii"):void 0}var rv="0.7.
|
|
136
|
+
`);for(let s of t){let i=s.indexOf(":");if(i<0)continue;let n=s.substring(0,i).toLowerCase().trim(),o=s.substring(i+1).trim();n.length>0&&o.length>0&&e.push({name:n,value:o})}return e}function IR(r,e){let t=0,s=e,i=!1,n=AR(r,e);return n!==void 0&&(t=Number.parseInt(n,16))>=0&&Number.isFinite(t)&&(s=e+n.length+2,i=!0),{ok:i,p:s,size:t}}function AR(r,e){let t=e,s=Math.min(r.length-1,e+ev);for(;t<s&&!(r[t]===jr&&r[t+1]===Dr);)t++;return t<s?r.slice(e,t).toString("ascii"):void 0}var rv="0.7.8";var Q={headerLines:[`/__\\ DERTUNNEL v${rv} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function zs(){let r=process.stdout,[e,t]=r.getWindowSize();if(Q.inspectedRequests.length>t-15){let n=Q.inspectedRequests.findIndex(o=>o.type==="http-response-body"||o.type==="http-response-header");Q.inspectedRequests.splice(n>=0?n:0,1)}let s=Q.inspectedRequests.map(n=>{let o;n.status===0?o="...":n.status<400?o=ue.blue(n.status):n.status<500?o=ue.yellow(n.status):o=ue.redBright(n.status);let a=new Date(n.startAt).toISOString(),u=n.endAt?`${n.endAt-n.startAt}ms`:"",c=a.slice(0,10)+" "+a.slice(11,19),l=n.headers.find(m=>m.name==="content-type")?.value??"(none)",h=l.split(";")[0],f=n.path.slice(0,Math.min(e-45-(l?l.length:2),n.path.length)),p=ue.white(n.content?" "+$t(n.content.length)+"b ":"");return`${ue.cyan(`${c} -`)} ${o} ${ue.green(n.method)} ${ue.white(f)} ${n.content?ue.gray(h):""} ${p} ${ue.cyanBright(u)}`});for(;Q.headerLines.length+Q.statusLines.length+s.length+Q.logLines.length+2>t&&Q.logLines.length>2;)Q.logLines.splice(0,1);let i=[...Q.headerLines,"",...Q.statusLines,...s,"",...Q.logLines];r.cursorTo(0,0),r.clearScreenDown(),i.forEach(n=>{r.write(n??""),r.write(`
|
|
137
137
|
`)})}function Mr(r,e){process.stdout.isTTY?(e!==void 0?Q.headerLines[e]=r:Q.headerLines.push(r),zs()):console.log(r)}function Bs(r){process.stdout.isTTY?(Q.logLines.push(r),Q.logLines.length>20&&Q.logLines.splice(0,1),zs()):console.log(r)}var CR=new Nr(200,()=>zs());function sv(r,e,t){if(r==="http-request-header"){let s=Q.inspectedRequests.find(i=>i.cid===e);s&&(s.cid=""),Q.inspectedRequests.push({cid:e,...t})}else{let s=Q.inspectedRequests.findIndex(i=>i.cid===e);if(s>=0){let i=Q.inspectedRequests[s];Q.inspectedRequests[s]={id:i.id,cid:i.cid,type:t.type,headers:t.headers,method:t.method||i.method,path:t.path||i.path,status:t.status||i.status,statusText:t.statusText||i.statusText,content:t.content??i.content,startAt:t.startAt||i.startAt,endAt:t.endAt}}}CR.update(void 0)}function iv(r){return["STATS | SENT chunks bytes | RECV chunks bytes | CONN active total errors |",` |${$t(r.chunksSent).padStart(14)}${$t(r.bytesSent).padStart(14)} |${$t(r.chunksReceived).padStart(14)}${$t(r.bytesReceived).padStart(14)} |${$t(r.currentConnections).padStart(14)}${$t(r.totalConnections).padStart(8)}${$t(r.connectionErrors).padStart(9)} |`,""]}async function av(r){let e=!1,t=!1,s,i=300,n=1.4,o=1e4,a={reconnectTime:i};if(!r.endpoint&&!r.endpointPrefix)throw new Error("Must either define 'endpoint' or 'endpointPrefix'");if(!r.clientToken||!r.localPort&&!r.localUrl)throw new Error("Missing required options");let u=yn(r.clientToken);r.serviceHost??=u.service;let c=u.user,l=u.token,h,f;if(r.localPort)h=r.localServer??"127.0.0.1",f=r.localPort;else{let y=new URL(r.localUrl||"http://localhost");if(y.protocol!=="http:")throw new Error("Local endpoints only support http protocol");h=y.hostname,f=Number.parseInt(y.port??"80")}let p=j_(),m=r.serviceHost;m.startsWith(il)||(m=il+m);let g=()=>{let y=new Nr(200,()=>S("data")),_={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function S(U,De){try{r.onEndpoint?.(U,_,De??"")}catch{}}s?.destroy(),r.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),s=ov.default.connect({timeout:1e4,host:m,port:r.servicePort||443,servername:m,...r.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{s&&(s.setKeepAlive(!0,L_),qr(s,1,0,{version:M_,user:c,token:l,endpoint:r.endpoint,endpointPrefix:r.endpointPrefix}))}),s.setMaxListeners(0);let O=new Map,E,$,ce=new vn(async(U,De,xe)=>{if(!e&&U===2){let G=Hs(xe);if(!G.success){s?.destroy();let N="Server connection error: "+(G.error??"Unknown error");p.reject(new Error(N)),r.onError?.(N);return}r.onConnected?.(G.endpoint||""),y.update(void 0,!0),p.resolve(),e=!0,a.reconnectTime=i,E=setInterval(()=>{if(!s){E&&clearInterval(E),$&&clearTimeout($);return}try{qr(s,7,0)}catch{E&&clearInterval(E)}$=setTimeout(()=>{r.onError?.("Server pong timeout"),s?.destroy()},7e3).unref()},15e3).unref()}if(U===3){s?.destroy();let G=Hs(xe);G.error&&r.onError?.(G.error);return}if(e){if(U===7)qr(s,8,0);else if(U===8)$&&clearTimeout($);else if(U===65){let G=O.get(De);if(G){if(_.bytesSent+=xe.length,_.chunksSent++,G.bytesSent+=xe.length,G.parserOut)try{G.parserOut.onData(xe)}catch(N){S("error",N?.message)}G.write(xe),y.update(void 0,!1)}}else if(U===4){let G=Hs(xe),N=(0,nv.createConnection)({host:h,port:f,allowHalfOpen:!1});N.channelId=G.channelId,N.wasConnected=!1;let Ks=bn(),Lr=Me=>{try{r.onProtocolData?.(Me.type,Ks,Me)}catch{}};r.protocols?.inspect&&(N.parserIn=new Gs(Lr),N.parserOut=new Gs(Lr)),N.bytesReceived=N.bytesSent=0,O.set(G.channelId,N),N.on("connect",()=>{N.wasConnected=!0,_.currentConnections++,_.totalConnections++,S("connect"),y.update(void 0,!0)}),N.on("close",()=>{N.wasConnected&&(_.currentConnections=Math.max(0,_.currentConnections-1)),O.delete(G.channelId),qr(s,6,0,{channelId:N.channelId}),S("disconnect"),y.update(void 0,!0)}),N.on("data",Me=>{if(N.bytesReceived+=Me.length,_.bytesReceived+=Me.length,_.chunksReceived++,N.parserIn)try{N.parserIn.onData(Me)}catch(cv){S("error",cv?.message)}!qr(s,66,N.channelId,Me)&&!N.isPaused()&&(N.pause(),s.once("drain",()=>{N.resume()})),y.update(void 0,!1)}),N.on("error",Me=>{_.connectionErrors++,S("error",Me?.message),y.update(void 0,!0)})}else if(U===5){let G=Hs(xe),N=O.get(G.channelId);N&&(O.delete(G.channelId),N.end(()=>N.destroy()))}}});s.on("error",U=>{e=!1,!t&&(p.reject(U),r.onError?.("Server connection error: "+U.message))}),s.on("close",()=>{e=!1,E&&clearInterval(E),$&&clearTimeout($),O.forEach(U=>U.destroy()),!t&&(setTimeout(g,a.reconnectTime),a.reconnectTime=Math.min(o,a.reconnectTime*n))}),s.on("data",U=>{t||!s||(s.pause(),ce.receive(U).then(De=>{De||s?.destroy(),s?.resume()}).catch(De=>Bs(`Unexpected parser error: ${De.message}`)))})};return g(),r.waitForInitialConnection!==!1&&await p,()=>{t=!0,s?.destroy()}}(async function(){let e=new Ts({projectName:"dertunnel",defaults:{configured:!1,serviceUrl:"",user:"",token:""}}),t=e.get("configured"),s=q_.name("dertunnel").option("-s, --service <url>","Service URL or host name").option("-u, --user <username>","The username for authenticating to the service").option("--reset","Removes stored user configuration").option("--ignore-cert-errors","Ignore all certificate errors (UNSAFE)").option("--no-inspect","Do not inspect traffic - HTTP logging will be unavailable").argument("[public-endpoint-name]","Public name for the tunnel endpoint").argument("[local-endpoint]","Local port name or URL").parse(process.argv),i=s.opts();i.reset&&(e.clear(),console.log("Stored configuration was purged"),process.exit());let n=i.service||(t?e.get("serviceUrl"):void 0),o=i.user||(t?e.get("user"):void 0),a=process.env.DERTUNNEL_TOKEN||(t?e.get("token"):void 0);if(!a){if(a=(await(0,En.default)({name:"value",type:"password",message:"Connection token"})).value,!a)throw new Error("Must specify a connection token");e.set("token",a)}e.set("configured",!0);let{service:u,user:c}=yn(a);c=o||c;let[l,h]=s.args;if(!l&&(l=(await(0,En.default)({name:"value",type:"text",message:"Public endpoint name",validate:E=>k_.test(E)})).value,!l))throw new Error("Must specify a public endpoint name");if(!h&&(h=(await(0,En.default)({name:"value",type:"text",message:"Local endpoint URL or port"})).value,!h))throw new Error("Must specify a local endpoint");let f,p,m,g=Number.parseInt(h);if(Number.isNaN(g)){let E=new URL(h);if(E.protocol!=="http:")throw new Error("Ony http protocol is supported for local endpoints");m=E.toString()}else f="127.0.0.1",p=g;Mr(`Service: ${ue.cyanBright(n||u)}`,3),Mr(`User: ${ue.cyanBright(c)}`,4),Mr(`Local: ${ue.cyanBright(m??`${f} ${p}`)}`,5);let y=!!i.inspect,_,S;if(n){let E=new URL(n);_=E.hostname,S=Number.parseInt(E.port||"443")}let O=await av({clientToken:a,localServer:f,localPort:p,localUrl:m,serviceHost:_,servicePort:S,endpoint:l,endpointPrefix:void 0,ignoreCertErrors:!!i.ignoreCertErrors,waitForInitialConnection:!0,protocols:{inspect:y},onConnected:E=>{Mr(`Connected - public endpoint: ${ue.green(E)}`,6)},onError:E=>{Mr(ue.redBright(E),6)},onEndpoint(E,$,ce){Q.statusLines=iv($),E==="error"&&Bs(ue.redBright(ce)),zs()},onProtocolData(E,$,ce){sv(E,$,ce)}});["SIGINT","SIGTERM","SIGQUIT"].forEach(E=>{process.on(E,()=>{Bs("Shutting down"),O(),process.exit(0)})})})().catch(r=>{console.error(r)});
|
package/index.js
CHANGED
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
`:`
|
|
4
4
|
`)+r,o=e+1,e=t.indexOf(`
|
|
5
5
|
`,o)}while(e!==-1);return s+=t.slice(o),s}var{stdout:Ge,stderr:Ve}=$e,ce=Symbol("GENERATOR"),U=Symbol("STYLER"),G=Symbol("IS_EMPTY"),Ye=["ansi","ansi","ansi256","ansi16m"],F=Object.create(null),At=(t,n={})=>{if(n.level&&!(Number.isInteger(n.level)&&n.level>=0&&n.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=Ge?Ge.level:0;t.level=n.level===void 0?r:n.level};var Pt=t=>{let n=(...r)=>r.join(" ");return At(n,t),Object.setPrototypeOf(n,V.prototype),n};function V(t){return Pt(t)}Object.setPrototypeOf(V.prototype,Function.prototype);for(let[t,n]of Object.entries(x))F[t]={get(){let r=te(this,ue(n.open,n.close,this[U]),this[G]);return Object.defineProperty(this,t,{value:r}),r}};F.visible={get(){let t=te(this,this[U],!0);return Object.defineProperty(this,"visible",{value:t}),t}};var le=(t,n,r,...e)=>t==="rgb"?n==="ansi16m"?x[r].ansi16m(...e):n==="ansi256"?x[r].ansi256(x.rgbToAnsi256(...e)):x[r].ansi(x.rgbToAnsi(...e)):t==="hex"?le("rgb",n,r,...x.hexToRgb(...e)):x[r][t](...e),Lt=["rgb","hex","ansi256"];for(let t of Lt){F[t]={get(){let{level:r}=this;return function(...e){let o=ue(le(t,Ye[r],"color",...e),x.color.close,this[U]);return te(this,o,this[G])}}};let n="bg"+t[0].toUpperCase()+t.slice(1);F[n]={get(){let{level:r}=this;return function(...e){let o=ue(le(t,Ye[r],"bgColor",...e),x.bgColor.close,this[U]);return te(this,o,this[G])}}}}var Dt=Object.defineProperties(()=>{},{...F,level:{enumerable:!0,get(){return this[ce].level},set(t){this[ce].level=t}}}),ue=(t,n,r)=>{let e,o;return r===void 0?(e=t,o=n):(e=r.openAll+t,o=n+r.closeAll),{open:t,close:n,openAll:e,closeAll:o,parent:r}},te=(t,n,r)=>{let e=(...o)=>kt(e,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(e,Dt),e[ce]=t,e[U]=n,e[G]=r,e},kt=(t,n)=>{if(t.level<=0||!n)return t[G]?"":n;let r=t[U];if(r===void 0)return n;let{openAll:e,closeAll:o}=r;if(n.includes("\x1B"))for(;r!==void 0;)n=je(n,r.close,r.open),r=r.parent;let s=n.indexOf(`
|
|
6
|
-
`);return s!==-1&&(n=qe(n,o,e,s)),e+n+o};Object.defineProperties(V.prototype,F);var Bt=V(),nn=V({level:Ve?Ve.level:0});var E=Bt;var We="0.7.
|
|
6
|
+
`);return s!==-1&&(n=qe(n,o,e,s)),e+n+o};Object.defineProperties(V.prototype,F);var Bt=V(),nn=V({level:Ve?Ve.level:0});var E=Bt;var We="0.7.8";var g={headerLines:[`/__\\ DERTUNNEL v${We} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function Ke(){let t=process.stdout,[n,r]=t.getWindowSize();if(g.inspectedRequests.length>r-15){let s=g.inspectedRequests.findIndex(i=>i.type==="http-response-body"||i.type==="http-response-header");g.inspectedRequests.splice(s>=0?s:0,1)}let e=g.inspectedRequests.map(s=>{let i;s.status===0?i="...":s.status<400?i=E.blue(s.status):s.status<500?i=E.yellow(s.status):i=E.redBright(s.status);let f=new Date(s.startAt).toISOString(),d=s.endAt?`${s.endAt-s.startAt}ms`:"",m=f.slice(0,10)+" "+f.slice(11,19),a=s.headers.find(A=>A.name==="content-type")?.value??"(none)",b=a.split(";")[0],O=s.path.slice(0,Math.min(n-45-(a?a.length:2),s.path.length)),R=E.white(s.content?" "+Ae(s.content.length)+"b ":"");return`${E.cyan(`${m} -`)} ${i} ${E.green(s.method)} ${E.white(O)} ${s.content?E.gray(b):""} ${R} ${E.cyanBright(d)}`});for(;g.headerLines.length+g.statusLines.length+e.length+g.logLines.length+2>r&&g.logLines.length>2;)g.logLines.splice(0,1);let o=[...g.headerLines,"",...g.statusLines,...e,"",...g.logLines];t.cursorTo(0,0),t.clearScreenDown(),o.forEach(s=>{t.write(s??""),t.write(`
|
|
7
7
|
`)})}function ze(t){process.stdout.isTTY?(g.logLines.push(t),g.logLines.length>20&&g.logLines.splice(0,1),Ke()):console.log(t)}var ln=new _(200,()=>Ke());async function It(t){let n=!1,r=!1,e,o=300,s=1.4,i=1e4,f={reconnectTime:o};if(!t.endpoint&&!t.endpointPrefix)throw new Error("Must either define 'endpoint' or 'endpointPrefix'");if(!t.clientToken||!t.localPort&&!t.localUrl)throw new Error("Missing required options");let d=Pe(t.clientToken);t.serviceHost??=d.service;let m=d.user,a=d.token,b,O;if(t.localPort)b=t.localServer??"127.0.0.1",O=t.localPort;else{let v=new URL(t.localUrl||"http://localhost");if(v.protocol!=="http:")throw new Error("Local endpoints only support http protocol");b=v.hostname,O=Number.parseInt(v.port??"80")}let R=Oe(),A=t.serviceHost;A.startsWith(ne)||(A=ne+A);let fe=()=>{let v=new _(200,()=>B("data")),y={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function B(p,D){try{t.onEndpoint?.(p,y,D??"")}catch{}}e?.destroy(),t.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),e=Xe.default.connect({timeout:1e4,host:A,port:t.servicePort||443,servername:A,...t.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{e&&(e.setKeepAlive(!0,ge),N(e,1,0,{version:me,user:m,token:a,endpoint:t.endpoint,endpointPrefix:t.endpointPrefix}))}),e.setMaxListeners(0);let I=new Map,P,L,Qe=new z(async(p,D,S)=>{if(!n&&p===2){let h=j(S);if(!h.success){e?.destroy();let c="Server connection error: "+(h.error??"Unknown error");R.reject(new Error(c)),t.onError?.(c);return}t.onConnected?.(h.endpoint||""),v.update(void 0,!0),R.resolve(),n=!0,f.reconnectTime=o,P=setInterval(()=>{if(!e){P&&clearInterval(P),L&&clearTimeout(L);return}try{N(e,7,0)}catch{P&&clearInterval(P)}L=setTimeout(()=>{t.onError?.("Server pong timeout"),e?.destroy()},7e3).unref()},15e3).unref()}if(p===3){e?.destroy();let h=j(S);h.error&&t.onError?.(h.error);return}if(n){if(p===7)N(e,8,0);else if(p===8)L&&clearTimeout(L);else if(p===65){let h=I.get(D);if(h){if(y.bytesSent+=S.length,y.chunksSent++,h.bytesSent+=S.length,h.parserOut)try{h.parserOut.onData(S)}catch(c){B("error",c?.message)}h.write(S),v.update(void 0,!1)}}else if(p===4){let h=j(S),c=(0,Je.createConnection)({host:b,port:O,allowHalfOpen:!1});c.channelId=h.channelId,c.wasConnected=!1;let Ze=J(),de=C=>{try{t.onProtocolData?.(C.type,Ze,C)}catch{}};t.protocols?.inspect&&(c.parserIn=new q(de),c.parserOut=new q(de)),c.bytesReceived=c.bytesSent=0,I.set(h.channelId,c),c.on("connect",()=>{c.wasConnected=!0,y.currentConnections++,y.totalConnections++,B("connect"),v.update(void 0,!0)}),c.on("close",()=>{c.wasConnected&&(y.currentConnections=Math.max(0,y.currentConnections-1)),I.delete(h.channelId),N(e,6,0,{channelId:c.channelId}),B("disconnect"),v.update(void 0,!0)}),c.on("data",C=>{if(c.bytesReceived+=C.length,y.bytesReceived+=C.length,y.chunksReceived++,c.parserIn)try{c.parserIn.onData(C)}catch(tt){B("error",tt?.message)}!N(e,66,c.channelId,C)&&!c.isPaused()&&(c.pause(),e.once("drain",()=>{c.resume()})),v.update(void 0,!1)}),c.on("error",C=>{y.connectionErrors++,B("error",C?.message),v.update(void 0,!0)})}else if(p===5){let h=j(S),c=I.get(h.channelId);c&&(I.delete(h.channelId),c.end(()=>c.destroy()))}}});e.on("error",p=>{n=!1,!r&&(R.reject(p),t.onError?.("Server connection error: "+p.message))}),e.on("close",()=>{n=!1,P&&clearInterval(P),L&&clearTimeout(L),I.forEach(p=>p.destroy()),!r&&(setTimeout(fe,f.reconnectTime),f.reconnectTime=Math.min(i,f.reconnectTime*s))}),e.on("data",p=>{r||!e||(e.pause(),Qe.receive(p).then(D=>{D||e?.destroy(),e?.resume()}).catch(D=>ze(`Unexpected parser error: ${D.message}`)))})};return fe(),t.waitForInitialConnection!==!1&&await R,()=>{r=!0,e?.destroy()}}0&&(module.exports={connectTunnel});
|