@faulpeltz/dertunnel 0.6.0 → 0.6.4

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