@faulpeltz/dertunnel 0.4.2 → 0.4.6

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.
Files changed (2) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Pe=Object.create;var I=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var Re=(t,n)=>{for(var r in n)I(t,r,{get:n[r],enumerable:!0})},J=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Ce(n))!Le.call(t,o)&&o!==r&&I(t,o,{get:()=>n[o],enumerable:!(e=De(n,o))||e.enumerable});return t};var X=(t,n,r)=>(r=t!=null?Pe(ke(t)):{},J(n||!t||!t.__esModule?I(r,"default",{value:t,enumerable:!0}):r,t)),Ae=t=>J(I({},"__esModule",{value:!0}),t);var Ge={};Re(Ge,{connectTunnel:()=>je});module.exports=Ae(Ge);var xe=require("net"),ve=X(require("tls"));var H=(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))(H||{});function Q(t){return{name:Object.keys(H).find(n=>H[n]===t)??"UNKNOWN",isBinary:!!(t&64)}}var Y=1;var we="service";var G=we+".",Z=5e3;var Oe=1*1024*1024,w=12,ee=70,te=80,ne=0,re=1,oe=2,ie=4,se=8,ae=!!process.env.DERTUNNEL_DEBUG,N=class{constructor(n){this.onMessage=n}buffer=void 0;async receive(n){let r=this.buffer?Buffer.concat([this.buffer,n]):n,e=0;for(;e<r.length;){if(r.length<e+w)return this.buffer=r,!0;if(r[e+ne]!=ee||r[e+re]!=te)return this.reset(),!1;let o=r.readUint16LE(e+oe),i=r.readUint32LE(e+ie),a=r.readUint32LE(e+se),d=a+w+e;if(a>Oe)return this.reset(),!1;if(r.length>=d)try{let h=r.slice(e+w,d);ae&&ce(o,i,h,!1),await this.onMessage(o,i,h)}catch{return this.reset(),!1}else break;e=d}return this.buffer=r.length>e?r.slice(e):void 0,!0}reset(){this.buffer=void 0}};function D(t,n,r,e){let o=Buffer.isBuffer(e)?e:e?Buffer.from(JSON.stringify(e)):void 0,i=Buffer.allocUnsafe(w+(o?o.length:0));i.writeUint8(ee,ne),i.writeUint8(te,re),i.writeUint16LE(n,oe),i.writeUint32LE(r,ie),i.writeUint32LE(o?o.length:0,se),o?.copy(i,w,0);let a=t.write(i);return ae&&ce(n,r,o,!0),a}function O(t){return JSON.parse(t.toString("utf8"))}function ce(t,n,r,e){let{name:o,isBinary:i}=Q(t);console.debug(`[msg-${e?"out":"in"} ${o} ${n>0?n:""}] ${r?i?`- ${r.length} payload bytes`:r.toString("utf8"):"- empty"}`)}var $=X(require("crypto"),1);var Be=128,T,C,Ie=t=>{!T||T.length<t?(T=Buffer.allocUnsafe(t*Be),$.default.randomFillSync(T),C=0):C+t>T.length&&($.default.randomFillSync(T),C=0),C+=t},He=t=>(Ie(t-=0),T.subarray(C-t,C)),Ne=(t,n,r)=>{let e=(2<<31-Math.clz32(t.length-1|1))-1,o=Math.ceil(1.6*e*n/t.length);return(i=n)=>{let a="";for(;;){let u=r(o),d=o;for(;d--;)if(a+=t[u[d]&e]||"",a.length===i)return a}}},z=(t,n=21)=>Ne(t,n,He);var _=z("0123456789abcdef",8),et=z("0123456789abcdefghijklmnopqrstuvwxyz",24);function le(){let t,n,r=new Promise((e,o)=>{t=e,n=o});return r.resolve=t,r.reject=n,r}var U=class{constructor(n,r){this.interval=n;this.func=r}lastUpdated=0;updateTimer;update(n,r){let e=new Date().valueOf();r||e-this.lastUpdated>this.interval?(clearTimeout(this.updateTimer),this.func(n),this.lastUpdated=e):this.updateTimer=setTimeout(()=>{this.func(n),this.updateTimer=void 0},this.interval-e+this.lastUpdated).unref()}};function ue(t){if(t.length<=24)return{service:"",user:"",token:t};let n=Buffer.from(_e(t),"base64").toString("utf8").split("#");return{service:n[0],user:n[1],token:n[2]}}function _e(t){let n="",r=t.length;for(let e=0;e<2;e++,r--)for(let o=r-1;o>=0;o-=2)n+=t[o];return n}var ge=4096,k=13,L=10,de=new Uint8Array([72,84,84,80,47,49,46,49,k,L]),Ue=new Uint8Array([72,84,84,80,47,49,46,49,32]),V=0,M=1,q=2,F=3,fe=4,be=5,B=class{constructor(n){this.onParsed=n}state=V;id="";contentData;headers=[];expectedBodyLen=0;isRequest=!1;method="";path="";status=0;statusText="";startAt=0;onData(n){let e=0,o=0;for(;e<n.length&&e!==-1&&o++<100;)if(this.state===V||this.state===M||this.state===q){this.contentData=void 0;let i=e;if((e=n.indexOf(de,i))>=0)for(let a=0;a<1;a++){let u=e+de.length;for(;e>0&&n[e-1]!==L&&n[e-1]!==k;)e--;let d=n.slice(e,u).toString("ascii").split(" ");if(d.length!==3){e=u;break}let h=pe(n,u);if(h){e=u+h.length,this.headers=me(h);let{nextState:c,len:p}=he(this.headers,!0);this.state=c,this.expectedBodyLen=p}else break;this.isRequest=!0,this.id=_(12),this.method=d[0].toUpperCase(),this.path=decodeURI(d[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((e=n.indexOf(Ue,i))>=0){let a=e,u=n.length;for(;e<u&&!(n[e+1]===k&&n[e+2]===L);)e++;for(let d=0;d<1;d++){let h=n.slice(a,e+1).toString("ascii").split(" ");if(h.length<3)break;let c=pe(n,a);if(c){e=a+c.length,this.headers=me(c);let{nextState:R,len:y}=he(this.headers,!1);this.state=R,this.expectedBodyLen=y}else break;let p=Number.parseInt(h[1]);if(!Number.isFinite(p)||p<100||p>999)break;this.isRequest=!1,this.status=p,this.statusText=h.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===F){let{ok:i,p:a,size:u}=Me(n,e);e=a,u>0?(this.expectedBodyLen=u,this.state=i?fe:V):i&&(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()}),e+=2,this.state=this.isRequest?q:M)}else if(this.state===fe){let i=Math.min(n.length-e,this.expectedBodyLen),a=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,a]):Buffer.from(a),this.expectedBodyLen-=i,e+=i,this.expectedBodyLen===0&&(e+=2,this.state=F)}else if(this.state===be){let i=Math.min(n.length-e,this.expectedBodyLen),a=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,a]):Buffer.from(a),this.expectedBodyLen-=i,e+=i,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?q:M)}if(o>=100)throw new Error("Internal parser error: "+this.state)}};function he(t,n){let r=Number.parseInt(t.find(e=>e.name==="content-length")?.value??"0");return t.find(e=>e.name==="transfer-encoding")?.value.includes("chunked")?{nextState:F,isChunked:!0,len:0}:r>0?{nextState:be,isChunked:!1,len:r}:{nextState:n?q:M,isChunked:!1,len:0}}function pe(t,n){let r=n,e=Math.min(t.length-3,n+ge);for(;r<e&&!(t[r]===k&&t[r+1]===L&&t[r+2]===k&&t[r+3]===L);)r++;return r<e?t.slice(n,r+4):void 0}function me(t){let n=[],r=t.toString("ascii").split(`\r
2
- `);for(let e of r){let o=e.indexOf(":");if(o<0)continue;let i=e.substring(0,o).toLowerCase().trim(),a=e.substring(o+1).trim();i.length>0&&a.length>0&&n.push({name:i,value:a})}return n}function Me(t,n){let r=0,e=n,o=!1,i=qe(t,n);return i!==void 0&&(r=Number.parseInt(i,16))>=0&&Number.isFinite(r)&&(e=n+i.length+2,o=!0),{ok:o,p:e,size:r}}function qe(t,n){let r=n,e=Math.min(t.length-1,n+ge);for(;r<e&&!(t[r]===k&&t[r+1]===L);)r++;return r<e?t.slice(n,r).toString("ascii"):void 0}async function je(t){let n=!1,r=!1,e,o=300,i=1.4,a=1e4,u={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=ue(t.clientToken);t.serviceHost??=d.service;let h=d.user,c=d.token,p,R;if(t.localPort)p=t.localServer??"127.0.0.1",R=t.localPort;else{let m=new URL(t.localUrl||"http://localhost");if(m.protocol!=="http:")throw new Error("Local endpoints only support http protocol");p=m.hostname,R=Number.parseInt(m.port??"80")}let y=le(),A=t.serviceHost;A.startsWith(G)||(A=G+A);let K=()=>{let m=new U(200,()=>S("data")),g={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function S(f,j){try{t.onEndpoint?.(f,g,j??"")}catch{}}e?.destroy(),t.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),e=ve.default.connect({timeout:1e4,host:A,port:t.servicePort||443,servername:A,...t.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{e&&(e.setKeepAlive(!0,Z),D(e,1,0,{version:Y,user:h,token:c,endpoint:t.endpoint,endpointPrefix:t.endpointPrefix}))}),e.setMaxListeners(0);let P=new Map,v,E,Ee=new N(async(f,j,b)=>{if(!n&&f===2){let l=O(b);if(!l.success){e?.destroy();let s="Server connection error: "+l.error;y.reject(new Error(s)),t.onError?.(s);return}t.onConnected?.(l.endpoint||""),m.update(void 0,!0),y.resolve(),n=!0,u.reconnectTime=o,v=setInterval(()=>{if(!e){v&&clearInterval(v),E&&clearTimeout(E);return}try{D(e,7,0)}catch{v&&clearInterval(v)}E=setTimeout(()=>{t.onError?.("Server pong timeout"),e?.destroy()},7e3).unref()},15e3).unref()}if(f===3){e?.destroy();let l=O(b);l.error&&t.onError?.(l.error);return}if(n){if(f===7)D(e,8,0);else if(f===8)E&&clearTimeout(E);else if(f===65){let l=P.get(j);if(l){if(g.bytesSent+=b.length,g.chunksSent++,l.bytesSent+=b.length,l.parserOut)try{l.parserOut.onData(b)}catch(s){S("error",s?.message)}l.write(b),m.update(void 0,!1)}}else if(f===4){let l=O(b),s=(0,xe.createConnection)({host:p,port:R,allowHalfOpen:!1});s.channelId=l.channelId,s.wasConnected=!1;let Te=_(),W=x=>{try{t.onProtocolData?.(x.type,Te,x)}catch{}};t.protocols?.inspect&&(s.parserIn=new B(W),s.parserOut=new B(W)),s.bytesReceived=s.bytesSent=0,P.set(l.channelId,s),s.on("connect",()=>{s.wasConnected=!0,g.currentConnections++,g.totalConnections++,S("connect"),m.update(void 0,!0)}),s.on("close",()=>{s.wasConnected&&(g.currentConnections=Math.max(0,g.currentConnections-1)),P.delete(l.channelId),D(e,6,0,{channelId:s.channelId}),S("disconnect"),m.update(void 0,!0)}),s.on("data",x=>{if(s.bytesReceived+=x.length,g.bytesReceived+=x.length,g.chunksReceived++,s.parserIn)try{s.parserIn.onData(x)}catch(Se){S("error",Se?.message)}!D(e,66,s.channelId,x)&&!s.isPaused()&&(s.pause(),e.once("drain",()=>{s.resume()})),m.update(void 0,!1)}),s.on("error",x=>{g.connectionErrors++,S("error",x?.message),m.update(void 0,!0)})}else if(f===5){let l=O(b),s=P.get(l.channelId);s&&(P.delete(l.channelId),s.end(()=>s.destroy()))}}});e.on("error",f=>{n=!1,!r&&(y.reject(f),t.onError?.("Server connection error: "+f.message))}),e.on("close",()=>{n=!1,v&&clearInterval(v),E&&clearTimeout(E),P.forEach(f=>f.destroy()),!r&&(setTimeout(K,u.reconnectTime),u.reconnectTime=Math.min(a,u.reconnectTime*i))}),e.on("data",f=>{r||Ee.receive(f)||e?.destroy()})};return K(),t.waitForInitialConnection!==!1&&await y,()=>{r=!0,e?.destroy()}}0&&(module.exports={connectTunnel});
1
+ "use strict";var Pe=Object.create;var I=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var Re=(t,n)=>{for(var r in n)I(t,r,{get:n[r],enumerable:!0})},J=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Ce(n))!Le.call(t,o)&&o!==r&&I(t,o,{get:()=>n[o],enumerable:!(e=De(n,o))||e.enumerable});return t};var X=(t,n,r)=>(r=t!=null?Pe(ke(t)):{},J(n||!t||!t.__esModule?I(r,"default",{value:t,enumerable:!0}):r,t)),Ae=t=>J(I({},"__esModule",{value:!0}),t);var Ge={};Re(Ge,{connectTunnel:()=>je});module.exports=Ae(Ge);var xe=require("net"),ve=X(require("tls"));var H=(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))(H||{});function Q(t){return{name:Object.keys(H).find(n=>H[n]===t)??"UNKNOWN",isBinary:!!(t&64)}}var Y=1;var we="service";var G=we+".",Z=5e3;var Oe=1*1024*1024,w=12,ee=70,te=80,ne=0,re=1,oe=2,se=4,ie=8,ae=!!process.env.DERTUNNEL_DEBUG,N=class{constructor(n){this.onMessage=n}buffer=void 0;async receive(n){let r=this.buffer?Buffer.concat([this.buffer,n]):n,e=0;for(;e<r.length;){if(r.length<e+w)return this.buffer=r,!0;if(r[e+ne]!=ee||r[e+re]!=te)return this.reset(),!1;let o=r.readUint16LE(e+oe),s=r.readUint32LE(e+se),a=r.readUint32LE(e+ie),d=a+w+e;if(a>Oe)return this.reset(),!1;if(r.length>=d)try{let h=r.slice(e+w,d);ae&&ce(o,s,h,!1),await this.onMessage(o,s,h)}catch{return this.reset(),!1}else break;e=d}return this.buffer=r.length>e?r.slice(e):void 0,!0}reset(){this.buffer=void 0}};function D(t,n,r,e){let o=Buffer.isBuffer(e)?e:e?Buffer.from(JSON.stringify(e)):void 0,s=Buffer.allocUnsafe(w+(o?o.length:0));s.writeUint8(ee,ne),s.writeUint8(te,re),s.writeUint16LE(n,oe),s.writeUint32LE(r,se),s.writeUint32LE(o?o.length:0,ie),o?.copy(s,w,0);let a=t.write(s);return ae&&ce(n,r,o,!0),a}function O(t){return JSON.parse(t.toString("utf8"))}function ce(t,n,r,e){let{name:o,isBinary:s}=Q(t);console.debug(`[msg-${e?"out":"in"} ${o} ${n>0?n:""}] ${r?s?`- ${r.length} payload bytes`:r.toString("utf8"):"- empty"}`)}var $=X(require("crypto"),1);var Be=128,T,C,Ie=t=>{!T||T.length<t?(T=Buffer.allocUnsafe(t*Be),$.default.randomFillSync(T),C=0):C+t>T.length&&($.default.randomFillSync(T),C=0),C+=t},He=t=>(Ie(t-=0),T.subarray(C-t,C)),Ne=(t,n,r)=>{let e=(2<<31-Math.clz32(t.length-1|1))-1,o=Math.ceil(1.6*e*n/t.length);return(s=n)=>{let a="";for(;;){let u=r(o),d=o;for(;d--;)if(a+=t[u[d]&e]||"",a.length===s)return a}}},z=(t,n=21)=>Ne(t,n,He);var _=z("0123456789abcdef",8),et=z("0123456789abcdefghijklmnopqrstuvwxyz",24);function le(){let t,n,r=new Promise((e,o)=>{t=e,n=o});return r.resolve=t,r.reject=n,r}var U=class{constructor(n,r){this.interval=n;this.func=r}lastUpdated=0;updateTimer;update(n,r){let e=new Date().valueOf();r||e-this.lastUpdated>this.interval?(clearTimeout(this.updateTimer),this.func(n),this.lastUpdated=e):this.updateTimer=setTimeout(()=>{this.func(n),this.updateTimer=void 0},this.interval-e+this.lastUpdated).unref()}};function ue(t){if(t.length<=24)return{service:"",user:"",token:t};let n=Buffer.from(_e(t),"base64").toString("utf8").split("#");return{service:n[0],user:n[1],token:n[2]}}function _e(t){let n="",r=t.length;for(let e=0;e<2;e++,r--)for(let o=r-1;o>=0;o-=2)n+=t[o];return n}var ge=4096,k=13,L=10,de=new Uint8Array([72,84,84,80,47,49,46,49,k,L]),Ue=new Uint8Array([72,84,84,80,47,49,46,49,32]),V=0,M=1,q=2,F=3,fe=4,be=5,B=class{constructor(n){this.onParsed=n}state=V;id="";contentData;headers=[];expectedBodyLen=0;isRequest=!1;method="";path="";status=0;statusText="";startAt=0;onData(n){let e=0,o=0;for(;e<n.length&&e!==-1&&o++<100;)if(this.state===V||this.state===M||this.state===q){this.contentData=void 0;let s=e;if((e=n.indexOf(de,s))>=0)for(let a=0;a<1;a++){let u=e+de.length;for(;e>0&&n[e-1]!==L&&n[e-1]!==k;)e--;let d=n.slice(e,u).toString("ascii").split(" ");if(d.length!==3){e=u;break}let h=pe(n,u);if(h){e=u+h.length,this.headers=me(h);let{nextState:c,len:p}=he(this.headers,!0);this.state=c,this.expectedBodyLen=p}else break;this.isRequest=!0,this.id=_(12),this.method=d[0].toUpperCase(),this.path=decodeURI(d[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((e=n.indexOf(Ue,s))>=0){let a=e,u=n.length;for(;e<u&&!(n[e+1]===k&&n[e+2]===L);)e++;for(let d=0;d<1;d++){let h=n.slice(a,e+1).toString("ascii").split(" ");if(h.length<3)break;let c=pe(n,a);if(c){e=a+c.length,this.headers=me(c);let{nextState:R,len:y}=he(this.headers,!1);this.state=R,this.expectedBodyLen=y}else break;let p=Number.parseInt(h[1]);if(!Number.isFinite(p)||p<100||p>999)break;this.isRequest=!1,this.status=p,this.statusText=h.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===F){let{ok:s,p:a,size:u}=Me(n,e);e=a,u>0?(this.expectedBodyLen=u,this.state=s?fe:V):s&&(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()}),e+=2,this.state=this.isRequest?q:M)}else if(this.state===fe){let s=Math.min(n.length-e,this.expectedBodyLen),a=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,a]):Buffer.from(a),this.expectedBodyLen-=s,e+=s,this.expectedBodyLen===0&&(e+=2,this.state=F)}else if(this.state===be){let s=Math.min(n.length-e,this.expectedBodyLen),a=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,a]):Buffer.from(a),this.expectedBodyLen-=s,e+=s,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?q:M)}if(o>=100)throw new Error("Internal parser error: "+this.state)}};function he(t,n){let r=Number.parseInt(t.find(e=>e.name==="content-length")?.value??"0");return t.find(e=>e.name==="transfer-encoding")?.value.includes("chunked")?{nextState:F,isChunked:!0,len:0}:r>0?{nextState:be,isChunked:!1,len:r}:{nextState:n?q:M,isChunked:!1,len:0}}function pe(t,n){let r=n,e=Math.min(t.length-3,n+ge);for(;r<e&&!(t[r]===k&&t[r+1]===L&&t[r+2]===k&&t[r+3]===L);)r++;return r<e?t.slice(n,r+4):void 0}function me(t){let n=[],r=t.toString("ascii").split(`\r
2
+ `);for(let e of r){let o=e.indexOf(":");if(o<0)continue;let s=e.substring(0,o).toLowerCase().trim(),a=e.substring(o+1).trim();s.length>0&&a.length>0&&n.push({name:s,value:a})}return n}function Me(t,n){let r=0,e=n,o=!1,s=qe(t,n);return s!==void 0&&(r=Number.parseInt(s,16))>=0&&Number.isFinite(r)&&(e=n+s.length+2,o=!0),{ok:o,p:e,size:r}}function qe(t,n){let r=n,e=Math.min(t.length-1,n+ge);for(;r<e&&!(t[r]===k&&t[r+1]===L);)r++;return r<e?t.slice(n,r).toString("ascii"):void 0}async function je(t){let n=!1,r=!1,e,o=300,s=1.4,a=1e4,u={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=ue(t.clientToken);t.serviceHost??=d.service;let h=d.user,c=d.token,p,R;if(t.localPort)p=t.localServer??"127.0.0.1",R=t.localPort;else{let m=new URL(t.localUrl||"http://localhost");if(m.protocol!=="http:")throw new Error("Local endpoints only support http protocol");p=m.hostname,R=Number.parseInt(m.port??"80")}let y=le(),A=t.serviceHost;A.startsWith(G)||(A=G+A);let K=()=>{let m=new U(200,()=>S("data")),g={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function S(f,j){try{t.onEndpoint?.(f,g,j??"")}catch{}}e?.destroy(),t.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),e=ve.default.connect({timeout:1e4,host:A,port:t.servicePort||443,servername:A,...t.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{e&&(e.setKeepAlive(!0,Z),D(e,1,0,{version:Y,user:h,token:c,endpoint:t.endpoint,endpointPrefix:t.endpointPrefix}))}),e.setMaxListeners(0);let P=new Map,v,E,Ee=new N(async(f,j,b)=>{if(!n&&f===2){let l=O(b);if(!l.success){e?.destroy();let i="Server connection error: "+l.error;y.reject(new Error(i)),t.onError?.(i);return}t.onConnected?.(l.endpoint||""),m.update(void 0,!0),y.resolve(),n=!0,u.reconnectTime=o,v=setInterval(()=>{if(!e){v&&clearInterval(v),E&&clearTimeout(E);return}try{D(e,7,0)}catch{v&&clearInterval(v)}E=setTimeout(()=>{t.onError?.("Server pong timeout"),e?.destroy()},7e3).unref()},15e3).unref()}if(f===3){e?.destroy();let l=O(b);l.error&&t.onError?.(l.error);return}if(n){if(f===7)D(e,8,0);else if(f===8)E&&clearTimeout(E);else if(f===65){let l=P.get(j);if(l){if(g.bytesSent+=b.length,g.chunksSent++,l.bytesSent+=b.length,l.parserOut)try{l.parserOut.onData(b)}catch(i){S("error",i?.message)}l.write(b),m.update(void 0,!1)}}else if(f===4){let l=O(b),i=(0,xe.createConnection)({host:p,port:R,allowHalfOpen:!1});i.channelId=l.channelId,i.wasConnected=!1;let Te=_(),W=x=>{try{t.onProtocolData?.(x.type,Te,x)}catch{}};t.protocols?.inspect&&(i.parserIn=new B(W),i.parserOut=new B(W)),i.bytesReceived=i.bytesSent=0,P.set(l.channelId,i),i.on("connect",()=>{i.wasConnected=!0,g.currentConnections++,g.totalConnections++,S("connect"),m.update(void 0,!0)}),i.on("close",()=>{i.wasConnected&&(g.currentConnections=Math.max(0,g.currentConnections-1)),P.delete(l.channelId),D(e,6,0,{channelId:i.channelId}),S("disconnect"),m.update(void 0,!0)}),i.on("data",x=>{if(i.bytesReceived+=x.length,g.bytesReceived+=x.length,g.chunksReceived++,i.parserIn)try{i.parserIn.onData(x)}catch(Se){S("error",Se?.message)}!D(e,66,i.channelId,x)&&!i.isPaused()&&(i.pause(),e.once("drain",()=>{i.resume()})),m.update(void 0,!1)}),i.on("error",x=>{g.connectionErrors++,S("error",x?.message),m.update(void 0,!0)})}else if(f===5){let l=O(b),i=P.get(l.channelId);i&&(P.delete(l.channelId),i.end(()=>i.destroy()))}}});e.on("error",f=>{n=!1,!r&&(y.reject(f),t.onError?.("Server connection error: "+f.message))}),e.on("close",()=>{n=!1,v&&clearInterval(v),E&&clearTimeout(E),P.forEach(f=>f.destroy()),!r&&(setTimeout(K,u.reconnectTime),u.reconnectTime=Math.min(a,u.reconnectTime*s))}),e.on("data",f=>{r||Ee.receive(f)||e?.destroy()})};return K(),t.waitForInitialConnection!==!1&&await y,()=>{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.4.2",
3
+ "version": "0.4.6",
4
4
  "description": "A client for the dertunnel public endpoint forwarder",
5
5
  "main": "./index.js",
6
6
  "typings": "./client.d.ts",