local-traffic 0.0.53 → 0.0.55

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.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function i(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}l((r=r.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const t=require("http2"),n=require("http"),r=require("https"),o=require("url"),s=require("fs"),a=require("zlib"),i=require("path"),l=require("crypto");var c,d,p;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(c||(c={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(d||(d={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(p||(p={}));const u=(0,i.resolve)(process.env.HOME,".local-traffic.json"),h=(0,i.resolve)(process.cwd(),process.argv.slice(-1)[0].endsWith(".json")?process.argv.slice(-1)[0]:u),m={mapping:{"/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let g,f,y=[];const v=e=>e===c.ERROR?"error":e===c.WARNING?"warning":"info",R=(e,t,n)=>{const r=(null==g?void 0:g.simpleLogs)||y.length?e.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(d.INBOUND,"g"),"inbound:").replace(new RegExp(d.PORT,"g"),"port:").replace(new RegExp(d.OUTBOUND,"g"),"outbound:").replace(new RegExp(d.RULES,"g"),"rules:").replace(new RegExp(d.NO,"g"),"").replace(new RegExp(d.REWRITE,"g"),"+rewrite").replace(new RegExp(d.WEBSOCKET,"g"),"websocket").replace(new RegExp(d.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):e;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null==g?void 0:g.simpleLogs)} ${(null==g?void 0:g.simpleLogs)?r:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹`:e}`),b({logEvent:r,level:v(t)})},b=e=>{if(!y.length)return;const t=JSON.stringify(e),n=Array(4).fill(0).map((()=>Math.floor(256*Math.random()))),r=[...t.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),o=Math.min(65535,t.length),s=t.length<126?Buffer.from(Uint8Array.from([129,128+o]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,254]).buffer),Buffer.from(Uint8Array.from([o>>8]).buffer),Buffer.from(Uint8Array.from([255&o]).buffer)]),a=Buffer.from(Int8Array.from(n).buffer),i=Buffer.from(Int8Array.from(r).buffer),l=Buffer.concat([s,a,i]);y.forEach((e=>{try{e.write(l)}catch(e){}}))},O=e=>{R(`⎸${d.PORT} ${e.port.toString().padStart(5)} ⎸${d.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?d.REWRITE:" "}⎹⎸${d.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?d.REWRITE:" "}⎹⎸${d.RULES}${Object.keys(g.mapping).length.toString().padStart(3)}⎹⎸${g.websocket?d.WEBSOCKET:d.NO}⎹⎸${g.simpleLogs?d.NO:d.COLORED}⎹⎸${g.disableWebSecurity?d.NO:d.SHIELD}⎹`)},w=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(h,((n,r)=>{n&&!t&&R("config error. Using default value",c.ERROR,d.ERROR_1);try{g=Object.assign({},m,JSON.parse((r||"{}").toString()))}catch(t){return R("config syntax incorrect, aborting",c.ERROR,d.ERROR_2),g=g||Object.assign({},m),void e(g)}g.mapping[""]||R('default mapping "" not provided.',c.WARNING,d.ERROR_3),n&&"ENOENT"===n.code&&t&&h===u?(0,s.writeFile)(h,JSON.stringify(m),(t=>{t?R("config file NOT created",c.ERROR,d.ERROR_4):R("config file created",c.INFO,d.COLORED),e(g)})):e(g)})))).then((()=>{t&&(0,s.watchFile)(h,$)}))})),$=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},g);if(yield w(!1),isNaN(g.port)||g.port>65535||g.port<0)return g=e,void R("port number invalid. Not refreshing",c.ERROR,d.PORT);if("object"!=typeof g.mapping)return g=e,void R("mapping should be an object. Aborting",c.ERROR,d.ERROR_5);if(g.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&R(`request body url ${g.replaceRequestBodyUrls?"":"NO "}rewriting`,c.INFO,d.REWRITE),g.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&R(`response body url ${g.replaceResponseBodyUrls?"":"NO "}rewriting`,c.INFO,d.REWRITE),g.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&R(`http/2 ${g.dontUseHttp2Downstream?"de":""}activated downstream`,c.INFO,d.OUTBOUND),g.disableWebSecurity!==e.disableWebSecurity&&R(`web security ${g.disableWebSecurity?"de":""}activated`,c.INFO,d.SHIELD),g.websocket!==e.websocket&&R(`websocket ${g.websocket?"":"de"}activated`,c.INFO,d.WEBSOCKET),g.simpleLogs!==e.simpleLogs&&R("simple logs "+(g.simpleLogs?"on":"off"),c.INFO,d.COLORED),Object.keys(g.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&R(`${Object.keys(g.mapping).length.toString().padStart(5)} loaded mapping rules`,c.INFO,d.RULES),g.port!==e.port&&R(`port changed from ${e.port} to ${g.port}`,c.INFO,d.PORT),g.ssl&&!e.ssl&&R("ssl configuration added",c.INFO,d.INBOUND),!g.ssl&&e.ssl&&R("ssl configuration removed",c.INFO,d.INBOUND),g.port!==e.port||JSON.stringify(g.ssl)!==JSON.stringify(e.ssl)){R("restarting server",c.INFO,d.RESTART),yield Promise.all(y.map((e=>new Promise((t=>e.end(t)))))),y=[];(yield Promise.race([new Promise((e=>f?f.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||R("error during restart (websockets ?)",c.WARNING,d.RESTART),H()}else O(g)})),E=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),N=e=>{const t=(0,i.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,s.readFile)(t,((r,o)=>{if(this.hasRun=!0,!r||"EISDIR"!==r.code)return this.error=r,this.data=o,void n(void 0);(0,s.readdir)(t,((t,r)=>{this.error=t,this.data=r,t?n(void 0):Promise.all(r.map((t=>new Promise((n=>(0,s.lstat)((0,i.resolve)(e.pathname,t),((e,r)=>n([t,r,e])))))))).then((t=>{const r=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${B(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${r.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},S=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=`${B(128250,"logs","")}<p>Logs page, limited to <select id="limit" onchange="javascript:cleanup()">\n <option value="-1">0 (clear)</option><option value="10">10</option>\n <option value="50">50</option><option value="100">100</option><option value="200">200</option>\n <option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n </select></p>\n <table id="table" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Message</th>\n </tr>\n </thead>\n <tbody id="logs">\n </tbody>\n </table>\n <script type="text/javascript">\n function start() {\n document.getElementById('table').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${g.ssl?"s":""}://${e}/local-traffic-logs");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n const eventText = typeof data === 'object' ? '<pre>' + JSON.stringify(data, null, 3)\n .replace(/&/g, '&amp;').replace(/\\\\"/g, '&quot;')\n .replace(/</g, '&lt;').replace(/>/g, '&gt;')\n .replace(/^( *)("[\\w]+": )?("[^"]*"|[\\w.+-]*)?([,[{])?$/mg, (match, pIndent, pKey, pVal, pEnd) => {\n const key = '<span class="json-key">';\n const val = '<span class="json-value">';\n const str = '<span class="json-string">';\n let r = pIndent || '';\n if (pKey)\n r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';\n if (pVal)\n r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';\n return r + (pEnd || '');\n }) + '</pre>'\n : data;\n const button = uniqueHash ? '<button data-uniquehash="'+uniqueHash+'" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary">Replay</button>' : '';\n document.getElementById("logs")\n .insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + new Date().toUTCString() + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col">' + eventText + button + '</td></tr>');\n cleanup();\n };\n socket.onerror = function(error) {\n console.log(\`[error] \${error}\`);\n setTimeout(start, 5000);\n };\n };\n function cleanup() {\n const currentLimit = parseInt(document.getElementById('limit').value)\n while (currentLimit && document.getElementById('logs').childNodes.length && \n document.getElementById('logs').childNodes.length > currentLimit) {\n [...document.getElementById('logs').childNodes].slice(-1)[0].remove();\n }\n }\n function replay(event) {\n const uniqueHash = event.target.dataset.uniquehash;\n const { method, url, headers, body } = JSON.parse(atob(uniqueHash));\n fetch(url, {\n method,\n headers,\n body: !body.data || !body.data.length \n ? undefined\n : new TextDecoder().decode(new Int8Array(body.data))\n });\n }\n window.addEventListener("DOMContentLoaded", start);\n <\/script>\n <style type="text/css">\n pre {\n background-color: ghostwhite;\n border: 1px solid silver;\n padding: 10px 20px;\n margin: 20px; \n }\n .json-key {\n color: brown;\n }\n .json-value {\n color: navy;\n }\n .json-string {\n color: olive;\n }\n </style>\n </body></html>`,t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{"response"===e&&this.events.response({Server:"local","Content-Type":"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}),B=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"><\/script>\n<script src="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,U=(e,t,n,r)=>`${B(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n &#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${r||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,j=(t,n,r)=>e(void 0,void 0,void 0,(function*(){var o,s;return(null!==(s=null===(o=n["content-encoding"])||void 0===o?void 0:o.toString())&&void 0!==s?s:"").split(",").reduce(((t,n)=>e(void 0,void 0,void 0,(function*(){const e=n.trim().toLowerCase(),r="gzip"===e||"x-gzip"===e?a.gunzip:"deflate"===e?a.inflate:"br"===e?a.brotliDecompress:"identity"===e||""===e?(e,t)=>{t(null,e)}:null;if(null===r)throw new Error(`${e} compression not supported by the proxy`);const o=yield t;return yield new Promise(((e,t)=>r(o,((n,r)=>{n&&t(n),e(r)}))))}))),Promise.resolve(t)).then((e=>{const t=e.length>1e7,o=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(o||!/[^\x00-\x7F]/.test(e.toString()))?g.replaceResponseBodyUrls?Object.entries(g.mapping).reduce(((e,[t,n])=>n.startsWith("logs:")||""!==t&&!t.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:r.direction===p.INBOUND?e.replace(new RegExp(n.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${g.ssl?"s":""}://${r.proxyHostnameAndPort}${t.replace(/\/+$/,"")}/`):e.split(`http${g.ssl?"s":""}://${r.proxyHostnameAndPort}${t.replace(/\/+$/,"")}`).join(n)),e.toString()).split(`${r.proxyHostnameAndPort}/:`).join(`${r.proxyHostnameAndPort}:`).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${g.ssl?"s":""}%3A&hostname=${r.proxyHostname}&port=${g.port}&pathname=${encodeURIComponent(r.key.replace(/\/+$/,""))}`):e.toString():e})).then((e=>{var t,r;return(null!==(r=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==r?r:"").split(",").reduce(((e,t)=>{const n=t.trim().toLowerCase(),r="gzip"===n||"x-gzip"===n?a.gzip:"deflate"===n?a.deflate:"br"===n?a.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===r)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>r(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))})),x=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)},T=e=>{var t,n,r;const s=(null!==(r=null!==(n=null===(t=e.headers[":authority"])||void 0===t?void 0:t.toString())&&void 0!==n?n:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),a=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==g.port||g.ssl?443===g.port&&g.ssl?"":`:${g.port}`:""}`,i=new o.URL(`http${g.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[c,d]=Object.entries(Object.assign({},Object.assign({},...Object.entries(g.mapping).map((([e,t])=>({[e]:new o.URL(E(t))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:c,target:d}},H=()=>{f=(g.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},g.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,l,c;if(!s.headers.host&&!s.headers[":authority"])return void x(400,a,Buffer.from(U(new Error("client must supply a 'host' header"),"proxy",new o.URL(`http${g.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:d,proxyHostnameAndPort:u,url:m,path:f,key:v,target:R}=T(s);if(!R)return void x(502,a,Buffer.from(U(new Error(`No mapping found in config file ${h}`),"proxy",m)));const O=R.host.replace(RegExp(/\/+$/),""),w=`${R.href.substring(8+R.host.length)}${E(f.replace(RegExp(E(v)),""))}`.replace(/^\/*/,"/"),$=new o.URL(`${R.protocol}//${O}${w}`);let B=null,H=!g.dontUseHttp2Downstream;const I="file:"===R.protocol?N($):"logs:"===R.protocol?S(u):H?yield Promise.race([new Promise((e=>{const n=(0,t.connect)($,{rejectUnauthorized:!1,protocol:R.protocol},((t,r)=>{H=H&&!!r.alpnProtocol,e(H?n:null)}));n.on("error",(e=>{B=H&&Buffer.from(U(e,"connection",m,$))}))})),new Promise((e=>setTimeout((()=>{H=!1,e(null)}),3e3)))]):null;B instanceof Buffer||(B=null);const D=null==s?void 0:s.readableLength,L=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let A=null;const P=g.replaceRequestBodyUrls||y.length;if(P){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);yield new Promise((n=>{0===L&&n(void 0),e.on("data",(e=>{t=Buffer.concat([t,e])})),e.on("end",n),e.on("error",n)})),A=yield j(t,s.headers,{proxyHostnameAndPort:u,proxyHostname:d,key:v,direction:p.OUTBOUND})}const k=Object.assign(Object.assign({},[...Object.entries(s.headers)].filter((([e])=>!["host","connection","keep-alive"].includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(m.hostname,O))).join(", "),e)),{})),{origin:R.href,referer:$.toString(),"content-length":null!==(c=null!==(l=null==A?void 0:A.length)&&void 0!==l?l:s.headers["content-length"])&&void 0!==c?c:0,":authority":O,":method":s.method,":path":w,":scheme":R.protocol.replace(":","")}),q=I&&!B&&I.request(k,{endStream:g.ssl?!(null==L||L):!D});null==q||q.on("error",(e=>{const t=-505===e.errno;B=Buffer.from(U(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),m,$))}));const W={hostname:R.hostname,path:w,port:R.port,protocol:R.protocol,rejectUnauthorized:!1,method:s.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(k).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:R.hostname})},C=!B&&!H&&!["file:","logs:"].includes(R.protocol)&&(yield new Promise((e=>{const t="https:"===R.protocol?(0,r.request)(W,e):(0,n.request)(W,e);t.on("error",(t=>{B=Buffer.from(U(t,"request",m,$)),e(null)})),P&&(t.write(A),t.end()),P||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(B)return void x(502,a,B);B=null,g.ssl&&L&&q&&(P&&(q.write(A),q.end()),P||(s.stream.on("data",(e=>{q.write(e)})),s.stream.on("end",(()=>q.end())))),!g.ssl&&D&&q&&(P&&(q.write(A),q.end()),P||(s.on("data",(e=>{q.write(e)})),s.on("end",(()=>q.end()))));const{outboundResponseHeaders:F}=yield new Promise((e=>q?q.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!q&&C?{outboundResponseHeaders:C.headers}:{outboundResponseHeaders:{}})));b({level:"info",protocol:H?"HTTP/2":"HTTP1.1",method:s.method,path:w,uniqueHash:Buffer.from(JSON.stringify({method:s.method,url:s.url,headers:Object.assign({},...Object.entries(s.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==A?void 0:A.toJSON()})).toString("base64")});const _=F.location?new o.URL(F.location.startsWith("/")?`${R.href}${F.location.replace(/^\/+/,"")}`:F.location):null,M=_?_.href.substring(_.origin.length):null,z=m.origin,J=_?`${z}${M}`:null,K=q||C,G=null!=B?B:yield new Promise((e=>{let t=Buffer.alloc(0);K?(K.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),K.on("end",(()=>{e(t)}))):e(t)})).then((e=>g.replaceResponseBodyUrls&&e.length?j(e,F,{proxyHostnameAndPort:u,proxyHostname:d,key:v,direction:p.INBOUND}).catch((e=>(x(502,a,Buffer.from(U(e,"stream",m,$))),Buffer.from("")))):e)),V=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},F),g.replaceResponseBodyUrls?{"content-length":`${G.byteLength}`}:{}),g.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase()&&"connection"!==e.toLowerCase()&&"keep-alive"!==e.toLowerCase())).reduce(((e,[t,n])=>{const r=O.split("").map(((e,t)=>O.substring(t).startsWith(".")&&O.substring(t))).filter((e=>e)),o=[O].concat(r).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${m.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(o),e}),{})),J?{location:[J]}:{});try{Object.entries(V).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}a.writeHead(F[":status"]||C.statusCode||200,g.ssl?void 0:C.statusMessage||"Status read from http/2",V),G?a.end(G):a.end()})))).addListener("error",(e=>{"EACCES"===e.code&&R("permission denied for this port",c.ERROR,d.NO),"EADDRINUSE"===e.code&&R("port is already used. NOT started",c.ERROR,d.ERROR_6)})).addListener("listening",(()=>{O(g)})).on("upgrade",((e,t)=>{if(!g.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:s,target:a,path:i}=T(e);if("/local-traffic-logs"===i){const n=(0,l.createHash)("sha1");n.update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const r=n.digest("base64");return t.allowHalfOpen=!0,t.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${r}\r\n\r\n`),t.on("close",(()=>{y=y.filter((e=>t!==e))})),void y.push(t)}const p=new o.URL(`${a.protocol}//${a.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${s}`,"g"),"").replace(/^\/*/,"/")}`),u={hostname:p.hostname,path:p.pathname,port:p.port,protocol:p.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:p.hostname},h="https:"===p.protocol?(0,r.request)(u):(0,n.request)(u);h.end(),h.on("error",(e=>{R("websocket request has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,d.WEBSOCKET)})),h.on("upgrade",((e,n)=>{const r=`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}\r\n${Object.entries(e.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;t.write(r),t.allowHalfOpen=!0,n.allowHalfOpen=!0,n.on("data",(e=>t.write(e))),t.on("data",(e=>n.write(e))),n.on("error",(e=>{R("downstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,d.WEBSOCKET)})),t.on("error",(e=>{R("upstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,d.WEBSOCKET)}))}))})).listen(g.port)};w().then(H);
2
+ "use strict";var e=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function a(e){try{l(o.next(e))}catch(e){s(e)}}function i(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const t=require("http2"),n=require("http"),o=require("https"),r=require("url"),s=require("fs"),a=require("zlib"),i=require("path"),l=require("crypto"),c=require("process");var d,p,u;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(d||(d={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(p||(p={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(u||(u={}));const h=(0,i.resolve)(process.env.HOME,".local-traffic.json"),m=(0,i.resolve)(process.cwd(),process.argv.slice(-1)[0].endsWith(".json")?process.argv.slice(-1)[0]:h),f={mapping:{"/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let g,y,v=[];const b=e=>e===d.ERROR?"error":e===d.WARNING?"warning":"info",R=(e,t,n)=>{const o=(null==g?void 0:g.simpleLogs)||v.length?e.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(p.INBOUND,"g"),"inbound:").replace(new RegExp(p.PORT,"g"),"port:").replace(new RegExp(p.OUTBOUND,"g"),"outbound:").replace(new RegExp(p.RULES,"g"),"rules:").replace(new RegExp(p.NO,"g"),"").replace(new RegExp(p.REWRITE,"g"),"+rewrite").replace(new RegExp(p.WEBSOCKET,"g"),"websocket").replace(new RegExp(p.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):e;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null==g?void 0:g.simpleLogs)} ${(null==g?void 0:g.simpleLogs)?o:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹`:e}`),O({event:o,level:b(t)})},O=e=>{if(!v.length)return;const t=JSON.stringify(e),n=Array(4).fill(0).map((()=>Math.floor(256*Math.random()))),o=[...t.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,t.length),s=t.length<126?Buffer.from(Uint8Array.from([129,128+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,254]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]),a=Buffer.from(Int8Array.from(n).buffer),i=Buffer.from(Int8Array.from(o).buffer),l=Buffer.concat([s,a,i]);v.forEach((e=>{try{e.write(l)}catch(e){}}))},w=e=>{R(`⎸${p.PORT} ${e.port.toString().padStart(5)} ⎸${p.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?p.REWRITE:" "}⎹⎸${p.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?p.REWRITE:" "}⎹⎸${p.RULES}${Object.keys(g.mapping).length.toString().padStart(3)}⎹⎸${g.websocket?p.WEBSOCKET:p.NO}⎹⎸${g.simpleLogs?p.NO:p.COLORED}⎹⎸${g.disableWebSecurity?p.NO:p.SHIELD}⎹`)},$=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(m,((n,o)=>{n&&!t&&R("config error. Using default value",d.ERROR,p.ERROR_1);try{g=Object.assign({},f,JSON.parse((o||"{}").toString()))}catch(t){return R("config syntax incorrect, aborting",d.ERROR,p.ERROR_2),g=g||Object.assign({},f),void e(g)}g.mapping[""]||R('default mapping "" not provided.',d.WARNING,p.ERROR_3),n&&"ENOENT"===n.code&&t&&m===h?(0,s.writeFile)(m,JSON.stringify(f),(t=>{t?R("config file NOT created",d.ERROR,p.ERROR_4):R("config file created",d.INFO,p.COLORED),e(g)})):e(g)})))).then((()=>{t&&(0,s.watchFile)(m,E)}))})),E=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},g);if(yield $(!1),isNaN(g.port)||g.port>65535||g.port<0)return g=e,void R("port number invalid. Not refreshing",d.ERROR,p.PORT);if("object"!=typeof g.mapping)return g=e,void R("mapping should be an object. Aborting",d.ERROR,p.ERROR_5);if(g.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&R(`request body url ${g.replaceRequestBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&R(`response body url ${g.replaceResponseBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&R(`http/2 ${g.dontUseHttp2Downstream?"de":""}activated downstream`,d.INFO,p.OUTBOUND),g.disableWebSecurity!==e.disableWebSecurity&&R(`web security ${g.disableWebSecurity?"de":""}activated`,d.INFO,p.SHIELD),g.websocket!==e.websocket&&R(`websocket ${g.websocket?"":"de"}activated`,d.INFO,p.WEBSOCKET),g.simpleLogs!==e.simpleLogs&&R("simple logs "+(g.simpleLogs?"on":"off"),d.INFO,p.COLORED),Object.keys(g.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&R(`${Object.keys(g.mapping).length.toString().padStart(5)} loaded mapping rules`,d.INFO,p.RULES),g.port!==e.port&&R(`port changed from ${e.port} to ${g.port}`,d.INFO,p.PORT),g.ssl&&!e.ssl&&R("ssl configuration added",d.INFO,p.INBOUND),!g.ssl&&e.ssl&&R("ssl configuration removed",d.INFO,p.INBOUND),g.port!==e.port||JSON.stringify(g.ssl)!==JSON.stringify(e.ssl)){R("restarting server",d.INFO,p.RESTART),yield Promise.all(v.map((e=>new Promise((t=>e.end(t)))))),v=[];(yield Promise.race([new Promise((e=>y?y.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||R("error during restart (websockets ?)",d.WARNING,p.RESTART),j()}else w(g)})),N=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),S=e=>{const t=(0,i.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,s.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,s.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,s.lstat)((0,i.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${x(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},B=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=`${x(128250,"logs","")}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n <div class="container-fluid">\n <ul class="navbar-nav">\n <li class="nav-item">\n <a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n </li>\n <li class="nav-item">\n <a class="nav-link" href="javascript:show(1)">Proxy</a>\n </li>\n </ul>\n <span class="navbar-text">\n Limit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n <option value="50">50</option><option value="100">100</option><option value="200">200</option>\n <option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n </select> rows\n </span>\n </div>\n</nav>\n<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">...</th>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Protocol</th>\n <th scope="col">Method</th>\n <th scope="col">Status</th>\n <th scope="col">Duration</th>\n <th scope="col">Path</th>\n </tr>\n </thead>\n <tbody id="access">\n </tbody>\n</table>\n<table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Message</th>\n </tr>\n </thead>\n <tbody id="proxy">\n </tbody>\n</table>\n<script type="text/javascript">\n function start() {\n document.getElementById('table-access').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n document.getElementById('table-proxy').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${g.ssl?"s":""}://${e}/local-traffic-logs");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary"' + \n (uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';\n if(data.statusCode && uniqueHash) {\n const color = Math.floor(data.statusCode / 100) === 1 ? "info" :\n Math.floor(data.statusCode / 100) === 2 ? "success" :\n Math.floor(data.statusCode / 100) === 3 ? "dark" :\n Math.floor(data.statusCode / 100) === 4 ? "warning" :\n Math.floor(data.statusCode / 100) === 5 ? "danger" :\n "secondary";\n const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\n if (statusCodeColumn)\n statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\n const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\n if (durationColumn) {\n const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\n data.duration + 'ms';\n durationColumn.innerHTML = duration;\n }\n\n const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\n if (protocolColumn) {\n protocolColumn.innerHTML = data.protocol;\n }\n\n const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\n if (replayColumn) {\n replayColumn.innerHTML = replay;\n }\n } else if (uniqueHash) {\n document.getElementById("access")\n .insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n '<td scope="col" class="replay">' + replay + '</td>' +\n '<td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col" class="protocol">' + data.protocol + '</td>' + \n '<td scope="col">' + data.method + '</td>' + \n '<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +\n '<td scope="col" class="duration">&#x23F1;</td>' +\n '<td scope="col">' + data.path + '</td>' + \n '</tr>');\n } else if(data.event) {\n document.getElementById("proxy")\n .insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col">' + data.event + '</td></tr>');\n }\n cleanup();\n };\n socket.onerror = function(error) {\n console.log(\`[error] \${error}\`);\n setTimeout(start, 5000);\n };\n };\n function show(id) {\n [...document.querySelectorAll('table')].forEach((table, index) => {\n table.style.display = index === id ? 'block': 'none'\n });\n [...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\n if (index === id) { link.classList.add('active') } else link.classList.remove('active');\n });\n }\n function cleanup() {\n const currentLimit = parseInt(document.getElementById('limit').value)\n for (let table of ['access', 'proxy']) {\n while (currentLimit && document.getElementById(table).childNodes.length && \n document.getElementById(table).childNodes.length > currentLimit) {\n [...document.getElementById(table).childNodes].slice(-1)[0].remove();\n }\n }\n }\n function replay(event) {\n const uniqueHash = event.target.dataset.uniquehash;\n const { method, url, headers, body } = JSON.parse(atob(uniqueHash));\n fetch(url, {\n method,\n headers,\n body: !body.data || !body.data.length \n ? undefined\n : new TextDecoder().decode(new Int8Array(body.data))\n });\n }\n window.addEventListener("DOMContentLoaded", start);\n<\/script>\n</body></html>`,t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{"response"===e&&this.events.response({Server:"local","Content-Type":"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}),x=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"><\/script>\n<script src="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,H=(e,t,n,o)=>`${x(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n &#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${o||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,T=(t,n,o)=>e(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((t,n)=>e(void 0,void 0,void 0,(function*(){const e=n.trim().toLowerCase(),o="gzip"===e||"x-gzip"===e?a.gunzip:"deflate"===e?a.inflate:"br"===e?a.brotliDecompress:"identity"===e||""===e?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${e} compression not supported by the proxy`);const r=yield t;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(t)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\x7F]/.test(e.toString()))?g.replaceResponseBodyUrls?Object.entries(g.mapping).reduce(((e,[t,n])=>n.startsWith("logs:")||""!==t&&!t.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:o.direction===u.INBOUND?e.replace(new RegExp(n.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${g.ssl?"s":""}://${o.proxyHostnameAndPort}${t.replace(/\/+$/,"")}/`):e.split(`http${g.ssl?"s":""}://${o.proxyHostnameAndPort}${t.replace(/\/+$/,"")}`).join(n)),e.toString()).split(`${o.proxyHostnameAndPort}/:`).join(`${o.proxyHostnameAndPort}:`).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${g.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${g.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e.toString():e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?a.gzip:"deflate"===n?a.deflate:"br"===n?a.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))})),U=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)},I=e=>{var t,n,o;const s=(null!==(o=null!==(n=null===(t=e.headers[":authority"])||void 0===t?void 0:t.toString())&&void 0!==n?n:e.headers.host)&&void 0!==o?o:"localhost").replace(/:.*/,""),a=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==g.port||g.ssl?443===g.port&&g.ssl?"":`:${g.port}`:""}`,i=new r.URL(`http${g.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[c,d]=Object.entries(Object.assign({},Object.assign({},...Object.entries(g.mapping).map((([e,t])=>({[e]:new r.URL(N(t))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:c,target:d}},j=()=>{y=(g.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},g.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,d,p;if(!s.headers.host&&!s.headers[":authority"])return void U(400,a,Buffer.from(H(new Error("client must supply a 'host' header"),"proxy",new r.URL(`http${g.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:h,proxyHostnameAndPort:f,url:y,path:b,key:R,target:w}=I(s);if(!w)return void U(502,a,Buffer.from(H(new Error(`No mapping found in config file ${m}`),"proxy",y)));const $=w.host.replace(RegExp(/\/+$/),""),E=`${w.href.substring(8+w.host.length)}${N(b.replace(RegExp(N(R)),""))}`.replace(/^\/*/,"/"),x=new r.URL(`${w.protocol}//${$}${E}`);let j=!g.dontUseHttp2Downstream;const C=(0,l.randomBytes)(20).toString("hex");O({level:"info",protocol:j?"HTTP/2":"HTTP1.1",method:s.method,path:E,randomId:C,uniqueHash:"N/A"});const L=c.hrtime.bigint();let A=null;const q="file:"===w.protocol?S(x):"logs:"===w.protocol?B(f):j?yield Promise.race([new Promise((e=>{const n=(0,t.connect)(x,{rejectUnauthorized:!1,protocol:w.protocol},((t,o)=>{j=j&&!!o.alpnProtocol,e(j?n:null)}));n.on("error",(e=>{A=j&&Buffer.from(H(e,"connection",y,x))}))})),new Promise((e=>setTimeout((()=>{j=!1,e(null)}),3e3)))]):null;A instanceof Buffer||(A=null);const D=null==s?void 0:s.readableLength,P=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let k=null;const W=g.replaceRequestBodyUrls||v.length;if(W){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);yield new Promise((n=>{0===P&&n(void 0),e.on("data",(e=>{t=Buffer.concat([t,e])})),e.on("end",n),e.on("error",n)})),k=yield T(t,s.headers,{proxyHostnameAndPort:f,proxyHostname:h,key:R,direction:u.OUTBOUND})}const M=Object.assign(Object.assign({},[...Object.entries(s.headers)].filter((([e])=>!["host","connection","keep-alive"].includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(y.hostname,$))).join(", "),e)),{})),{origin:w.href,referer:x.toString(),"content-length":null!==(p=null!==(d=null==k?void 0:k.length)&&void 0!==d?d:s.headers["content-length"])&&void 0!==p?p:0,":authority":$,":method":s.method,":path":E,":scheme":w.protocol.replace(":","")}),F=q&&!A&&q.request(M,{endStream:g.ssl?!(null==P||P):!D});null==F||F.on("error",(e=>{const t=-505===e.errno;A=Buffer.from(H(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),y,x))}));const _={hostname:w.hostname,path:E,port:w.port,protocol:w.protocol,rejectUnauthorized:!1,method:s.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(M).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:w.hostname})},z=!A&&!j&&!["file:","logs:"].includes(w.protocol)&&(yield new Promise((e=>{const t="https:"===w.protocol?(0,o.request)(_,e):(0,n.request)(_,e);t.on("error",(t=>{A=Buffer.from(H(t,"request",y,x)),e(null)})),W&&(t.write(k),t.end()),W||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(A)return void U(502,a,A);A=null,g.ssl&&P&&F&&(W&&(F.write(k),F.end()),W||(s.stream.on("data",(e=>{F.write(e)})),s.stream.on("end",(()=>F.end())))),!g.ssl&&D&&F&&(W&&(F.write(k),F.end()),W||(s.on("data",(e=>{F.write(e)})),s.on("end",(()=>F.end()))));const{outboundResponseHeaders:J}=yield new Promise((e=>F?F.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!F&&z?{outboundResponseHeaders:z.headers}:{outboundResponseHeaders:{}}))),G=J.location?new r.URL(J.location.startsWith("/")?`${w.href}${J.location.replace(/^\/+/,"")}`:J.location):null,K=G?G.href.substring(G.origin.length):null,Z=y.origin,V=G?`${Z}${K}`:null,Y=F||z,Q=null!=A?A:yield new Promise((e=>{let t=Buffer.alloc(0);Y?(Y.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),Y.on("end",(()=>{e(t)}))):e(t)})).then((e=>g.replaceResponseBodyUrls&&e.length?T(e,J,{proxyHostnameAndPort:f,proxyHostname:h,key:R,direction:u.INBOUND}).catch((e=>(U(502,a,Buffer.from(H(e,"stream",y,x))),Buffer.from("")))):e)),X=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},J),g.replaceResponseBodyUrls?{"content-length":`${Q.byteLength}`}:{}),g.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase()&&"connection"!==e.toLowerCase()&&"keep-alive"!==e.toLowerCase())).reduce(((e,[t,n])=>{const o=$.split("").map(((e,t)=>$.substring(t).startsWith(".")&&$.substring(t))).filter((e=>e)),r=[$].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${y.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),V?{location:[V]}:{});try{Object.entries(X).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ee=J[":status"]||z.statusCode||200;a.writeHead(ee,g.ssl?void 0:z.statusMessage||"Status read from http/2",X),Q?a.end(Q):a.end();const te=c.hrtime.bigint();O({randomId:C,statusCode:ee,protocol:j?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(te-L)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:s.method,url:s.url,headers:Object.assign({},...Object.entries(s.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==k?void 0:k.toJSON()})).toString("base64")})})))).addListener("error",(e=>{"EACCES"===e.code&&R("permission denied for this port",d.ERROR,p.NO),"EADDRINUSE"===e.code&&R("port is already used. NOT started",d.ERROR,p.ERROR_6)})).addListener("listening",(()=>{w(g)})).on("upgrade",((e,t)=>{if(!g.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:s,target:a,path:i}=I(e);if("/local-traffic-logs"===i){const n=(0,l.createHash)("sha1");n.update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");return t.allowHalfOpen=!0,t.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`),t.on("close",(()=>{v=v.filter((e=>t!==e))})),void v.push(t)}const c=new r.URL(`${a.protocol}//${a.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${s}`,"g"),"").replace(/^\/*/,"/")}`),u={hostname:c.hostname,path:c.pathname,port:c.port,protocol:c.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:c.hostname},h="https:"===c.protocol?(0,o.request)(u):(0,n.request)(u);h.end(),h.on("error",(e=>{R("websocket request has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),h.on("upgrade",((e,n)=>{const o=`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}\r\n${Object.entries(e.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;t.write(o),t.allowHalfOpen=!0,n.allowHalfOpen=!0,n.on("data",(e=>t.write(e))),t.on("data",(e=>n.write(e))),n.on("error",(e=>{R("downstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),t.on("error",(e=>{R("upstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)}))}))})).listen(g.port)};$().then(j);
package/index.ts CHANGED
@@ -32,7 +32,8 @@ import {
32
32
  brotliDecompress,
33
33
  } from "zlib";
34
34
  import { resolve, normalize } from "path";
35
- import { createHash } from "crypto";
35
+ import { createHash, randomBytes } from "crypto";
36
+ import { hrtime } from "process";
36
37
  import type { Duplex, Readable } from "stream";
37
38
 
38
39
  type ErrorWithErrno = NodeJS.ErrnoException;
@@ -149,7 +150,7 @@ const log = (text: string, level?: LogLevel, emoji?: string) => {
149
150
  }`,
150
151
  );
151
152
  notifyLogsListener({
152
- logEvent: simpleLog,
153
+ event: simpleLog,
153
154
  level: levelToString(level),
154
155
  });
155
156
  };
@@ -190,13 +191,13 @@ const quickStatus = (thisConfig: LocalConfiguration) => {
190
191
  .toString()
191
192
  .padStart(5)} \u001b[48;5;53m⎸${EMOJIS.OUTBOUND} ${
192
193
  thisConfig.dontUseHttp2Downstream ? "H1.1" : "H/2 "
193
- }${
194
- thisConfig.replaceRequestBodyUrls ? EMOJIS.REWRITE : " "
195
- }⎹⎸${EMOJIS.INBOUND} ${
196
- thisConfig.ssl ? "H/2 " : "H1.1"
197
- }${
194
+ }${thisConfig.replaceRequestBodyUrls ? EMOJIS.REWRITE : " "}⎹⎸${
195
+ EMOJIS.INBOUND
196
+ } ${thisConfig.ssl ? "H/2 " : "H1.1"}${
198
197
  thisConfig.replaceResponseBodyUrls ? EMOJIS.REWRITE : " "
199
- }⎹\u001b[48;5;54m\u001b[48;5;55m⎸${EMOJIS.RULES}${Object.keys(config.mapping)
198
+ }⎹\u001b[48;5;54m\u001b[48;5;55m⎸${EMOJIS.RULES}${Object.keys(
199
+ config.mapping,
200
+ )
200
201
  .length.toString()
201
202
  .padStart(3)}⎹\u001b[48;5;56m⎸${
202
203
  config.websocket ? EMOJIS.WEBSOCKET : EMOJIS.NO
@@ -504,29 +505,57 @@ const logsPage = (proxyHostnameAndPort: string): ClientHttp2Session =>
504
505
  data: null as string | Buffer,
505
506
  run: function () {
506
507
  return new Promise(resolve => {
507
- this.data = `${header(
508
- 0x1f4fa,
509
- "logs",
510
- "",
511
- )}<p>Logs page, limited to <select id="limit" onchange="javascript:cleanup()">
512
- <option value="-1">0 (clear)</option><option value="10">10</option>
508
+ this.data = `${header(0x1f4fa, "logs", "")}
509
+ <nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">
510
+ <div class="container-fluid">
511
+ <ul class="navbar-nav">
512
+ <li class="nav-item">
513
+ <a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>
514
+ </li>
515
+ <li class="nav-item">
516
+ <a class="nav-link" href="javascript:show(1)">Proxy</a>
517
+ </li>
518
+ </ul>
519
+ <span class="navbar-text">
520
+ Limit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>
513
521
  <option value="50">50</option><option value="100">100</option><option value="200">200</option>
514
522
  <option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>
515
- </select></p>
516
- <table id="table" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">
517
- <thead>
518
- <tr>
519
- <th scope="col">Date</th>
520
- <th scope="col">Level</th>
521
- <th scope="col">Message</th>
522
- </tr>
523
- </thead>
524
- <tbody id="logs">
525
- </tbody>
526
- </table>
527
- <script type="text/javascript">
523
+ </select> rows
524
+ </span>
525
+ </div>
526
+ </nav>
527
+ <table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">
528
+ <thead>
529
+ <tr>
530
+ <th scope="col">...</th>
531
+ <th scope="col">Date</th>
532
+ <th scope="col">Level</th>
533
+ <th scope="col">Protocol</th>
534
+ <th scope="col">Method</th>
535
+ <th scope="col">Status</th>
536
+ <th scope="col">Duration</th>
537
+ <th scope="col">Path</th>
538
+ </tr>
539
+ </thead>
540
+ <tbody id="access">
541
+ </tbody>
542
+ </table>
543
+ <table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">
544
+ <thead>
545
+ <tr>
546
+ <th scope="col">Date</th>
547
+ <th scope="col">Level</th>
548
+ <th scope="col">Message</th>
549
+ </tr>
550
+ </thead>
551
+ <tbody id="proxy">
552
+ </tbody>
553
+ </table>
554
+ <script type="text/javascript">
528
555
  function start() {
529
- document.getElementById('table').style.height =
556
+ document.getElementById('table-access').style.height =
557
+ (document.documentElement.clientHeight - 150) + 'px';
558
+ document.getElementById('table-proxy').style.height =
530
559
  (document.documentElement.clientHeight - 150) + 'px';
531
560
  const socket = new WebSocket("ws${
532
561
  config.ssl ? "s" : ""
@@ -539,27 +568,55 @@ const logsPage = (proxyHostnameAndPort: string): ClientHttp2Session =>
539
568
  data = data1;
540
569
  uniqueHash = uniqueHash1;
541
570
  } catch(e) { }
542
- const eventText = typeof data === 'object' ? '<pre>' + JSON.stringify(data, null, 3)
543
- .replace(/&/g, '&amp;').replace(/\\\\"/g, '&quot;')
544
- .replace(/</g, '&lt;').replace(/>/g, '&gt;')
545
- .replace(/^( *)("[\\w]+": )?("[^"]*"|[\\w.+-]*)?([,[{])?$/mg, (match, pIndent, pKey, pVal, pEnd) => {
546
- const key = '<span class="json-key">';
547
- const val = '<span class="json-value">';
548
- const str = '<span class="json-string">';
549
- let r = pIndent || '';
550
- if (pKey)
551
- r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
552
- if (pVal)
553
- r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
554
- return r + (pEnd || '');
555
- }) + '</pre>'
556
- : data;
557
- const button = uniqueHash ? '<button data-uniquehash="'+uniqueHash+'" onclick="javascript:replay(event)" ' +
558
- 'type="button" class="btn btn-primary">Replay</button>' : '';
559
- document.getElementById("logs")
560
- .insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + new Date().toUTCString() + '</td>' +
571
+ const time = new Date().toISOString().split('T')[1].replace('Z', '');
572
+ const replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +
573
+ 'type="button" class="btn btn-primary"' +
574
+ (uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';
575
+ if(data.statusCode && uniqueHash) {
576
+ const color = Math.floor(data.statusCode / 100) === 1 ? "info" :
577
+ Math.floor(data.statusCode / 100) === 2 ? "success" :
578
+ Math.floor(data.statusCode / 100) === 3 ? "dark" :
579
+ Math.floor(data.statusCode / 100) === 4 ? "warning" :
580
+ Math.floor(data.statusCode / 100) === 5 ? "danger" :
581
+ "secondary";
582
+ const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");
583
+ if (statusCodeColumn)
584
+ statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';
585
+
586
+ const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");
587
+ if (durationColumn) {
588
+ const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :
589
+ data.duration + 'ms';
590
+ durationColumn.innerHTML = duration;
591
+ }
592
+
593
+ const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");
594
+ if (protocolColumn) {
595
+ protocolColumn.innerHTML = data.protocol;
596
+ }
597
+
598
+ const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");
599
+ if (replayColumn) {
600
+ replayColumn.innerHTML = replay;
601
+ }
602
+ } else if (uniqueHash) {
603
+ document.getElementById("access")
604
+ .insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +
605
+ '<td scope="col" class="replay">' + replay + '</td>' +
606
+ '<td scope="col">' + time + '</td>' +
607
+ '<td scope="col">' + (data.level || 'info')+ '</td>' +
608
+ '<td scope="col" class="protocol">' + data.protocol + '</td>' +
609
+ '<td scope="col">' + data.method + '</td>' +
610
+ '<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +
611
+ '<td scope="col" class="duration">&#x23F1;</td>' +
612
+ '<td scope="col">' + data.path + '</td>' +
613
+ '</tr>');
614
+ } else if(data.event) {
615
+ document.getElementById("proxy")
616
+ .insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +
561
617
  '<td scope="col">' + (data.level || 'info')+ '</td>' +
562
- '<td scope="col">' + eventText + button + '</td></tr>');
618
+ '<td scope="col">' + data.event + '</td></tr>');
619
+ }
563
620
  cleanup();
564
621
  };
565
622
  socket.onerror = function(error) {
@@ -567,11 +624,21 @@ const logsPage = (proxyHostnameAndPort: string): ClientHttp2Session =>
567
624
  setTimeout(start, 5000);
568
625
  };
569
626
  };
627
+ function show(id) {
628
+ [...document.querySelectorAll('table')].forEach((table, index) => {
629
+ table.style.display = index === id ? 'block': 'none'
630
+ });
631
+ [...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {
632
+ if (index === id) { link.classList.add('active') } else link.classList.remove('active');
633
+ });
634
+ }
570
635
  function cleanup() {
571
636
  const currentLimit = parseInt(document.getElementById('limit').value)
572
- while (currentLimit && document.getElementById('logs').childNodes.length &&
573
- document.getElementById('logs').childNodes.length > currentLimit) {
574
- [...document.getElementById('logs').childNodes].slice(-1)[0].remove();
637
+ for (let table of ['access', 'proxy']) {
638
+ while (currentLimit && document.getElementById(table).childNodes.length &&
639
+ document.getElementById(table).childNodes.length > currentLimit) {
640
+ [...document.getElementById(table).childNodes].slice(-1)[0].remove();
641
+ }
575
642
  }
576
643
  }
577
644
  function replay(event) {
@@ -586,25 +653,8 @@ const logsPage = (proxyHostnameAndPort: string): ClientHttp2Session =>
586
653
  });
587
654
  }
588
655
  window.addEventListener("DOMContentLoaded", start);
589
- </script>
590
- <style type="text/css">
591
- pre {
592
- background-color: ghostwhite;
593
- border: 1px solid silver;
594
- padding: 10px 20px;
595
- margin: 20px;
596
- }
597
- .json-key {
598
- color: brown;
599
- }
600
- .json-value {
601
- color: navy;
602
- }
603
- .json-string {
604
- color: olive;
605
- }
606
- </style>
607
- </body></html>`;
656
+ </script>
657
+ </body></html>`;
608
658
  resolve(void 0);
609
659
  });
610
660
  },
@@ -936,9 +986,20 @@ const start = () => {
936
986
  `${target.protocol}//${targetHost}${fullPath}`,
937
987
  );
938
988
 
989
+ let http2IsSupported = !config.dontUseHttp2Downstream;
990
+ const randomId = randomBytes(20).toString("hex");
991
+ notifyLogsListener({
992
+ level: "info",
993
+ protocol: http2IsSupported ? "HTTP/2" : "HTTP1.1",
994
+ method: inboundRequest.method,
995
+ path: fullPath,
996
+ randomId,
997
+ uniqueHash: "N/A",
998
+ });
999
+
939
1000
  // phase: connection
1001
+ const startTime = hrtime.bigint();
940
1002
  let error: Buffer = null;
941
- let http2IsSupported = !config.dontUseHttp2Downstream;
942
1003
  const outboundRequest: ClientHttp2Session =
943
1004
  target.protocol === "file:"
944
1005
  ? fileRequest(targetUrl)
@@ -1178,26 +1239,6 @@ const start = () => {
1178
1239
  }),
1179
1240
  );
1180
1241
 
1181
- notifyLogsListener({
1182
- level: "info",
1183
- protocol: http2IsSupported ? "HTTP/2" : "HTTP1.1",
1184
- method: inboundRequest.method,
1185
- path: fullPath,
1186
- uniqueHash: Buffer.from(
1187
- JSON.stringify({
1188
- method: inboundRequest.method,
1189
- url: inboundRequest.url,
1190
- headers: Object.assign(
1191
- {},
1192
- ...Object.entries(inboundRequest.headers)
1193
- .filter(([headerName]) => !headerName.startsWith(":"))
1194
- .map(([key, value]) => ({ [key]: value })),
1195
- ),
1196
- body: requestBody?.toJSON(),
1197
- }),
1198
- ).toString("base64"),
1199
- });
1200
-
1201
1242
  const newUrl = !outboundResponseHeaders["location"]
1202
1243
  ? null
1203
1244
  : new URL(
@@ -1319,10 +1360,12 @@ const start = () => {
1319
1360
  } catch (e) {
1320
1361
  // ERR_HTTP2_HEADERS_SENT
1321
1362
  }
1322
- inboundResponse.writeHead(
1363
+ const statusCode =
1323
1364
  outboundResponseHeaders[":status"] ||
1324
- outboundHttp1Response.statusCode ||
1325
- 200,
1365
+ outboundHttp1Response.statusCode ||
1366
+ 200;
1367
+ inboundResponse.writeHead(
1368
+ statusCode,
1326
1369
  config.ssl
1327
1370
  ? undefined // statusMessage is discarded in http/2
1328
1371
  : outboundHttp1Response.statusMessage || "Status read from http/2",
@@ -1330,6 +1373,27 @@ const start = () => {
1330
1373
  );
1331
1374
  if (payload) inboundResponse.end(payload);
1332
1375
  else inboundResponse.end();
1376
+ const endTime = hrtime.bigint();
1377
+
1378
+ notifyLogsListener({
1379
+ randomId,
1380
+ statusCode,
1381
+ protocol: http2IsSupported ? "HTTP/2" : "HTTP1.1",
1382
+ duration: Math.floor(Number(endTime - startTime) / 1000000),
1383
+ uniqueHash: Buffer.from(
1384
+ JSON.stringify({
1385
+ method: inboundRequest.method,
1386
+ url: inboundRequest.url,
1387
+ headers: Object.assign(
1388
+ {},
1389
+ ...Object.entries(inboundRequest.headers)
1390
+ .filter(([headerName]) => !headerName.startsWith(":"))
1391
+ .map(([key, value]) => ({ [key]: value })),
1392
+ ),
1393
+ body: requestBody?.toJSON(),
1394
+ }),
1395
+ ).toString("base64"),
1396
+ });
1333
1397
  },
1334
1398
  ) as Server
1335
1399
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.53",
3
+ "version": "0.0.55",
4
4
  "main": "index.ts",
5
5
  "private": false,
6
6
  "keywords": [
@@ -24,7 +24,7 @@
24
24
  "build": "npm run clean && npm run typescript && npm run terser && npm run shebang && npm run chmod"
25
25
  },
26
26
  "devDependencies": {
27
- "@types/node": "^18.15.11",
27
+ "@types/node": "^18.15.12",
28
28
  "terser": "^5.17.1",
29
29
  "typescript": "^5.0.4"
30
30
  },