@faulpeltz/dertunnel 0.2.1 → 0.3.0

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