@faulpeltz/dertunnel 0.7.10 → 0.7.11

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.
@@ -133,5 +133,5 @@ ${e}`,N1=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),q1=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_,Ml=Symbol("GENERATOR"),Rr=Symbol("STYLER"),Vs=Symbol("IS_EMPTY"),b_=["ansi","ansi","ansi256","ansi16m"],Nr=Object.create(null),tR=(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 rR=r=>{let e=(...t)=>t.join(" ");return tR(e,r),Object.setPrototypeOf(e,Fs.prototype),e};function Fs(r){return rR(r)}Object.setPrototypeOf(Fs.prototype,Function.prototype);for(let[r,e]of Object.entries(Ke))Nr[r]={get(){let t=fn(this,Vl(e.open,e.close,this[Rr]),this[Vs]);return Object.defineProperty(this,r,{value:t}),t}};Nr.visible={get(){let r=fn(this,this[Rr],!0);return Object.defineProperty(this,"visible",{value:r}),r}};var Ll=(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"?Ll("rgb",e,t,...Ke.hexToRgb(...s)):Ke[t][r](...s),sR=["rgb","hex","ansi256"];for(let r of sR){Nr[r]={get(){let{level:t}=this;return function(...s){let i=Vl(Ll(r,b_[t],"color",...s),Ke.color.close,this[Rr]);return fn(this,i,this[Vs])}}};let e="bg"+r[0].toUpperCase()+r.slice(1);Nr[e]={get(){let{level:t}=this;return function(...s){let i=Vl(Ll(r,b_[t],"bgColor",...s),Ke.bgColor.close,this[Rr]);return fn(this,i,this[Vs])}}}}var iR=Object.defineProperties(()=>{},{...Nr,level:{enumerable:!0,get(){return this[Ml].level},set(r){this[Ml].level=r}}}),Vl=(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)=>nR(s,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(s,iR),s[Ml]=r,s[Rr]=e,s[Vs]=t,s},nR=(r,e)=>{if(r.level<=0||!e)return r[Vs]?"":e;let t=r[Rr];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(Fs.prototype,Nr);var oR=Fs(),ND=Fs({level:v_?v_.level:0});var ue=oR;var N_=Y(R_(),1),{program:q_,createCommand:UD,createArgument:HD,createOption:GD,CommanderError:zD,InvalidArgumentError:BD,InvalidOptionArgumentError:KD,Command:WD,Argument:YD,Option:XD,Help:JD}=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 qr=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($R(r),"base64").toString("utf8").split("#");return{service:e[0]??"",user:e[1]??"",token:e[2]??""}}function $R(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=(c=>(c[c.HELLO_REQ=1]="HELLO_REQ",c[c.HELLO_RESP=2]="HELLO_RESP",c[c.END=3]="END",c[c.SERVER_OPEN=4]="SERVER_OPEN",c[c.SERVER_CLOSE=5]="SERVER_CLOSE",c[c.CLIENT_CLOSE=6]="CLIENT_CLOSE",c[c.PING=7]="PING",c[c.PONG=8]="PONG",c[c.SERVER_DATA=65]="SERVER_DATA",c[c.CLIENT_DATA=66]="CLIENT_DATA",c))(_n||{});function D_(r){return{name:Object.keys(_n).find(e=>_n[e]===r)??"UNKNOWN",isBinary:!!(r&64)}}var M_=1;var ER="service";var ic=ER+".",L_=5e3;var SR=1*1024*1024,Hs=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+Hs)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+Hs+s;if(o>SR)return this.reset(),!1;if(t.length>=u)try{let l=t.subarray(s+Hs,u);K_&&W_(i,n,l,!1),await this.onMessage(i,n,l)}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 kr(r,e,t,s){let i=Buffer.isBuffer(s)?s:s?Buffer.from(JSON.stringify(s)):void 0,n=Buffer.allocUnsafe(Hs+(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,Hs,0);let o=r.write(n);return K_&&W_(e,t,i,!0),o}function Gs(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 nc=require("node:crypto");var OR=128,rr,jr;function xR(r){!rr||rr.length<r?(rr=Buffer.allocUnsafe(r*OR),nc.webcrypto.getRandomValues(rr),jr=0):jr+r>rr.length&&(nc.webcrypto.getRandomValues(rr),jr=0),jr+=r}function TR(r){return xR(r|=0),rr.subarray(jr-r,jr)}function PR(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 oc(r,e=21){return PR(r,e,TR)}var bn=oc("0123456789abcdef",8),u2=oc("0123456789abcdefghijklmnopqrstuvwxyz",24);var ev=4096,Dr=13,Mr=10,Y_=new Uint8Array([72,84,84,80,47,49,46,49,Dr,Mr]),IR=new Uint8Array([72,84,84,80,47,49,46,49,32]),ac=0,wn=1,$n=2,uc=3,X_=4,tv=5,zs=class{constructor(e){this.onParsed=e}state=ac;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===ac||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]!==Mr&&e[s-1]!==Dr;)s--;let u=e.subarray(s,a).toString("ascii").split(" ");if(u.length!==3){s=a;break}let l=Z_(e,a);if(l){s=a+l.length,this.headers=Q_(l);let{nextState:c,len:h}=J_(this.headers,!0);this.state=c,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(IR,n))>=0){let o=s,a=e.length;for(;s<a&&!(e[s+1]===Dr&&e[s+2]===Mr);)s++;for(let u=0;u<1;u++){let l=e.subarray(o,s+1).toString("ascii").split(" ");if(l.length<3)break;let c=Z_(e,o);if(c){s=o+c.length,this.headers=Q_(c);let{nextState:f,len:p}=J_(this.headers,!1);this.state=f,this.expectedBodyLen=p}else break;let h=Number.parseInt(l[1]);if(!Number.isFinite(h)||h<100||h>999)break;this.isRequest=!1,this.status=h,this.statusText=l.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===uc){let{ok:n,p:o,size:a}=AR(e,s);s=o,a>0?(this.expectedBodyLen=a,this.state=n?X_:ac):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=uc)}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:uc,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]===Dr&&r[t+1]===Mr&&r[t+2]===Dr&&r[t+3]===Mr);)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 AR(r,e){let t=0,s=e,i=!1,n=CR(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 CR(r,e){let t=e,s=Math.min(r.length-1,e+ev);for(;t<s&&!(r[t]===Dr&&r[t+1]===Mr);)t++;return t<s?r.slice(e,t).toString("ascii"):void 0}var rv="0.7.10";var Q={headerLines:[`/__\\ DERTUNNEL v${rv} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function Bs(){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`:"",l=a.slice(0,10)+" "+a.slice(11,19),c=n.headers.find(m=>m.name==="content-type")?.value??"(none)",h=c.split(";")[0],f=n.path.slice(0,Math.min(e-45-(c?c.length:2),n.path.length)),p=ue.white(n.content?" "+$t(n.content.length)+"b ":"");return`${ue.cyan(`${l} -`)} ${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(`
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 AR(r,e){let t=0,s=e,i=!1,n=CR(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 CR(r,e){let t=e,s=Math.min(r.length-1,e+ev);for(;t<s&&!(r[t]===Dr&&r[t+1]===Mr);)t++;return t<s?r.slice(e,t).toString("ascii"):void 0}var rv="0.7.11";var Q={headerLines:[`/__\\ DERTUNNEL v${rv} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function Bs(){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`:"",l=a.slice(0,10)+" "+a.slice(11,19),c=n.headers.find(m=>m.name==="content-type")?.value??"(none)",h=c.split(";")[0],f=n.path.slice(0,Math.min(e-45-(c?c.length:2),n.path.length)),p=ue.white(n.content?" "+$t(n.content.length)+"b ":"");return`${ue.cyan(`${l} -`)} ${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 Lr(r,e){process.stdout.isTTY?(e!==void 0?Q.headerLines[e]=r:Q.headerLines.push(r),Bs()):console.log(r)}function Ks(r){process.stdout.isTTY?(Q.logLines.push(r),Q.logLines.length>20&&Q.logLines.splice(0,1),Bs()):console.log(r)}var RR=new qr(200,()=>Bs());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}}}RR.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 l=u.user,c=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(ic)||(m=ic+m);let g=()=>{let y=new qr(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_),kr(s,1,0,{version:M_,user:l,token:c,endpoint:r.endpoint,endpointPrefix:r.endpointPrefix}))}),s.setMaxListeners(0);let O=new Map,E,$,le=new vn(async(U,De,xe)=>{if(!e&&U===2){let G=Gs(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{kr(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=Gs(xe);G.error&&r.onError?.(G.error);return}if(e){if(U===7)kr(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=Gs(xe),N=(0,nv.createConnection)({host:h,port:f,allowHalfOpen:!1});N.channelId=G.channelId,N.wasConnected=!1;let Ws=bn(),Vr=Me=>{try{r.onProtocolData?.(Me.type,Ws,Me)}catch{}};r.protocols?.inspect&&(N.parserIn=new zs(Vr),N.parserOut=new zs(Vr)),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),kr(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(lv){S("error",lv?.message)}!kr(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=Gs(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(),le.receive(U).then(De=>{De||s?.destroy(),s?.resume()}).catch(De=>Ks(`Unexpected parser error: ${De.message}`)))})};return g(),r.waitForInitialConnection!==!1&&await p,()=>{t=!0,s?.destroy()}}(async function(){let e=new Ps({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:l}=yn(a);l=o||l;let[c,h]=s.args;if(!c&&(c=(await(0,En.default)({name:"value",type:"text",message:"Public endpoint name",validate:E=>k_.test(E)})).value,!c))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;Lr(`Service: ${ue.cyanBright(n||u)}`,3),Lr(`User: ${ue.cyanBright(l)}`,4),Lr(`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:c,endpointPrefix:void 0,ignoreCertErrors:!!i.ignoreCertErrors,waitForInitialConnection:!0,protocols:{inspect:y},onConnected:E=>{Lr(`Connected - public endpoint: ${ue.green(E)}`,6)},onError:E=>{Lr(ue.redBright(E),6)},onEndpoint(E,$,le){Q.statusLines=iv($),E==="error"&&Ks(ue.redBright(le)),Bs()},onProtocolData(E,$,le){sv(E,$,le)}});["SIGINT","SIGTERM","SIGQUIT"].forEach(E=>{process.on(E,()=>{Ks("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.10";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(`
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.11";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});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faulpeltz/dertunnel",
3
- "version": "0.7.10",
3
+ "version": "0.7.11",
4
4
  "description": "A client for the dertunnel public endpoint forwarder",
5
5
  "main": "./index.js",
6
6
  "typings": "./client.d.ts",