local-traffic 0.0.70 → 0.0.71

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,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(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(i,a)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const n=require("http2"),o=require("http"),r=require("https"),s=require("url"),i=require("fs"),a=require("zlib"),l=require("path"),c=require("crypto"),d=require("process");var p,u,g;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(p||(p={})),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="☠️ "}(u||(u={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(g||(g={}));const f=(0,l.resolve)(d.env.HOME,".local-traffic.json"),h=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:f),m={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},v=e=>e===p.ERROR?"error":e===p.WARNING?"warning":"info",y=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(u.INBOUND,"g"),"inbound:").replace(new RegExp(u.PORT,"g"),"port:").replace(new RegExp(u.OUTBOUND,"g"),"outbound:").replace(new RegExp(u.RULES,"g"),"rules:").replace(new RegExp(u.NO,"g"),"").replace(new RegExp(u.REWRITE,"g"),"+rewrite").replace(new RegExp(u.WEBSOCKET,"g"),"websocket").replace(new RegExp(u.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;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===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${d.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:v(n)})},b=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=[...e.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,e.length),s=e.length<126?Buffer.from(Uint8Array.from([129,(t?128:0)+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,126|(t?128:0)]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]),i=Buffer.from(Int8Array.from(n).buffer),a=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,i,a]:[s,a])};exports.createWebsocketBufferFrom=b;const R=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=R;const w=(e,t)=>{const n=(0,c.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.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`)};exports.acknowledgeWebsocket=w;const O=function(e){return E(this,e,this.configListeners)},$=function(e){return E(this,e,this.logsListeners)},E=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&b(o,!1),i=r.has(!0)&&b(o,!0),a=e=>{e.stream.errored&&e.stream.destroy()};n.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(i,"ascii",(()=>a(e))):e.stream.write(s,"ascii",(()=>a(e))))}))},L=function(){this.log(`⎸${u.PORT} ${this.config.port.toString().padStart(5)} ⎸${u.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?u.REWRITE:" "}⎹⎸${u.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?u.REWRITE:" "}⎹⎸${u.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹⎸${this.config.websocket?u.WEBSOCKET:u.NO}⎹⎸${this.config.simpleLogs?u.NO:u.COLORED}⎹⎸${this.config.disableWebSecurity?u.NO:u.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=L;const x=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(h,((n,o)=>{n&&!e&&y(null,"config error. Using default value",p.ERROR,u.ERROR_1);let r=null;try{r=Object.assign({},m,JSON.parse((o||"{}").toString()))}catch(e){return y({config:r},"config syntax incorrect, aborting",p.ERROR,u.ERROR_2),r=null!=r?r:Object.assign({},m),void t(r)}r.mapping[""]||y({config:r},'default mapping "" not provided.',p.WARNING,u.ERROR_3),n&&"ENOENT"===n.code&&e&&h===f?(0,i.writeFile)(h,JSON.stringify(m,null,2),(e=>{e?y(null,"config file NOT created",p.ERROR,u.ERROR_4):y(null,"config file created",p.INFO,u.COLORED),t(r)})):t(r)}))))}));exports.load=x;const S=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),N="https://cdn.jsdelivr.net/npm/",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="${N}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${N}jquery/dist/jquery.min.js"><\/script>\n<script src="${N}bootstrap/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/>`,k=e=>{const t=(0,l.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,i.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,i.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,i.lstat)((0,l.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=`${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>${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}}},j=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=e,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}}),I=(e,t,n,o)=>`${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>${o||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,U=(e,n,o)=>t(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(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?a.gunzip:"deflate"===t?a.inflate:"br"===t?a.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).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()))?o.replaceResponseBodyUrls?T(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.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)))}))}));exports.replaceBody=U;const T=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>s.startsWith("logs:")||s.startsWith("config:")||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===g.INBOUND?e.replace(new RegExp(s.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=T;const C=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=C;const H=(e,t)=>{var n,o,r,i,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(i=t.port)&&void 0!==i?i:8080}`:""}`,d=new s.URL(`http${t.ssl?"s":""}://${c}${e.url}`),p=d.href.substring(d.origin.length),u=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new s.URL(S("string"==typeof t?t:t.downstreamUrl))}))))),[g,f]=null!==(a=Object.entries(u).find((([e])=>p.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:p,key:g,target:f}};exports.determineMapping=H;const P=function(e,t,n){var i,a,l,c;if(!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:g,path:f}=H(t,e.config);if("/local-traffic-logs"===f)return w(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(i=t.headers["user-agent"])||void 0===i?void 0:i.toString())&&void 0!==a?a:"").includes("Chrome")})};if("/local-traffic-config"===f){w(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=R(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",p.WARNING,u.ERROR_4)}W(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const h=new s.URL(`${g.protocol}//${g.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),m={hostname:h.hostname,path:h.pathname,port:h.port,protocol:h.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:h.hostname},v="https:"===h.protocol?(0,r.request)(m):(0,o.request)(m);v.end(),v.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),v.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)}))}))};exports.websocketServe=P;const q=function(e,i,a){var l,f,v,y,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void C(400,a,Buffer.from(I(new Error("client must supply a 'host' header"),"proxy",new s.URL(`http${e.config.ssl?"s":""}://unknowndomain${i.url}`))));const{proxyHostname:t,proxyHostnameAndPort:R,url:w,path:O,key:$,target:E}=H(i,e.config);if(!E)return void C(502,a,Buffer.from(I(new Error(`No mapping found in config file ${h}`),"proxy",w)));const L=E.host.replace(RegExp(/\/+$/),""),x=`${E.href.substring(8+E.host.length)}${S(O.replace(RegExp(S($)),""))}`.replace(/^\/*/,"/"),P=new s.URL(`${E.protocol}//${L}${x}`);let q=!e.config.dontUseHttp2Downstream;const A=(0,c.randomBytes)(20).toString("hex");e.notifyLogsListeners({level:"info",protocol:q?"HTTP/2":"HTTP1.1",method:i.method,upstreamPath:O,downstreamPath:P.href,randomId:A,uniqueHash:"N/A"});const D=d.hrtime.bigint();let W=null;const M="file:"===E.protocol?k(P):"logs:"===E.protocol?((e,t)=>j(`${B(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">Upstream Path</th>\n <th scope="col">Downstream 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 const socket = new WebSocket("ws${t?"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.upstreamPath + '</td>' + \n '<td scope="col">' + data.downstreamPath + '</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>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>j(`${B(127899,"config","")}\n <link href="${N}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="${N}jsoneditor/dist/jsoneditor.min.js"><\/script>\n <script src="${N}node-forge/dist/forge.min.js"><\/script>\n <div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n <div class="modal-dialog" role="document">\n <div class="modal-content">\n <div class="modal-header">\n <h5 class="modal-title">SSL keypair generation in progress</h5>\n </div>\n <div class="modal-body">\n <p>Wait a few seconds or move your mouse to improve the entropy.</p>\n </div>\n </div>\n </div>\n </div>\n <div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n <script>\n // create the editor\n const container = document.getElementById("jsoneditor")\n const options = {mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n ${Object.entries(Object.assign(Object.assign({},m),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n ")}\n },\n required: [],\n additionalProperties: false\n }}\n\n function save() {\n socket.send(JSON.stringify(editor.get()));\n }\n\n function generateSslCertificate() {\n const sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\n sslModal.show()\n setTimeout(function() {\n const keypair = forge.pki.rsa.generateKeyPair(2048);\n const certificate = forge.pki.createCertificate();\n const now = new Date();\n const fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\n Object.assign(certificate, {\n publicKey: keypair.publicKey,\n serialNumber: "01",\n validity: {\n notBefore: now,\n notAfter: fiveYears,\n },\n });\n certificate.sign(keypair.privateKey, forge.md.sha256.create());\n const key = forge.pki.privateKeyToPem(keypair.privateKey);\n const cert = forge.pki.certificateToPem(certificate);\n const existingConfig = editor.get();\n editor.set({ ...existingConfig, ssl: { key, cert },\n port: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n });\n sslModal.hide();\n }, 100);\n }\n\n const editor = new JSONEditor(container, options);\n let socket;\n const initialJson = ${JSON.stringify(t)}\n editor.set(initialJson)\n editor.validate();\n editor.aceEditor.commands.addCommand({\n name: 'save',\n bindKey: {win: 'Ctrl-S', mac: 'Command-S'},\n exec: save,\n });\n\n window.addEventListener("DOMContentLoaded", function() {\n document.getElementById('jsoneditor').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n document.getElementById('jsoneditor').style.width =\n parseInt(window.getComputedStyle(\n document.querySelector('.container')).maxWidth) + 'px';\n const sslButton = document.createElement('button');\n sslButton.addEventListener("click", generateSslCertificate);\n sslButton.type="button";\n sslButton.classList.add("btn");\n sslButton.classList.add("btn-primary");\n sslButton.innerHTML="&#x1F512;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(sslButton);\n const saveButton = document.createElement('button');\n saveButton.addEventListener("click", save);\n saveButton.type="button";\n saveButton.classList.add("btn");\n saveButton.classList.add("btn-primary");\n saveButton.innerHTML="&#x1F4BE;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(saveButton);\n socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\n socket.onmessage = function(event) {\n editor.set(JSON.parse(event.data))\n editor.validate()\n }\n });\n <\/script>\n </body></html>`))(R,e.config):q?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(P,{rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{q=q&&!!o.alpnProtocol,e(q?t:null)}));t.on("error",(e=>{W=q&&Buffer.from(I(e,"connection",w,P))}))})),new Promise((e=>setTimeout((()=>{q=!1,e(null)}),3e3)))]):null;W instanceof Buffer||(W=null);const F=null==i?void 0:i.readableLength,_=null===(l=null==i?void 0:i.stream)||void 0===l?void 0:l.readableLength;let J=null;const K=e.config.replaceRequestBodyUrls||e.logsListeners.length;if(K){const n=null!==(f=null==i?void 0:i.stream)&&void 0!==f?f:i;let o=Buffer.from([]);const r=!((e.config.ssl&&0===_||!e.config.ssl&&0===F)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{r||e(void 0),n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)}))]),r&&!o.length&&e.log(`body replacement error ${O.slice(-17)}`,p.WARNING,u.ERROR_4),J=yield U(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.OUTBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls})}const z=Object.assign(Object.assign({},[...Object.entries(i.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(w.hostname,L))).join(", "),e)),{})),{origin:E.href,referer:P.toString(),"content-length":null!==(y=null!==(v=null==J?void 0:J.length)&&void 0!==v?v:i.headers["content-length"])&&void 0!==y?y:0,":authority":L,":method":i.method,":path":x,":scheme":E.protocol.replace(":","")}),G=M&&!W&&M.request(z,{endStream:e.config.ssl?!(null==_||_):!F});null==G||G.on("error",(e=>{const t=-505===e.errno;W=Buffer.from(I(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),w,P))}));const Y={hostname:E.hostname,path:x,port:E.port,protocol:E.protocol,rejectUnauthorized:!1,method:i.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(z).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},Z=!W&&!q&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(Y,e):(0,o.request)(Y,e);t.on("error",(t=>{W=Buffer.from(I(t,"request",w,P)),e(null)})),K&&(t.write(J),t.end()),K||(i.on("data",(e=>t.write(e))),i.on("end",(()=>t.end())))})));if(W)return void C(502,a,W);W=null,e.config.ssl&&_&&G&&(K&&(G.write(J),G.end()),K||(i.stream.on("data",(e=>{G.write(e)})),i.stream.on("end",(()=>G.end())))),!e.config.ssl&&F&&G&&(K&&(G.write(J),G.end()),K||(i.on("data",(e=>{G.write(e)})),i.on("end",(()=>G.end()))));const{outboundResponseHeaders:V}=yield new Promise((e=>G?G.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!G&&Z?{outboundResponseHeaders:Z.headers}:{outboundResponseHeaders:{}})));let Q=null;try{V.location&&(Q=new s.URL(V.location.startsWith("/")?`${E.href}${V.location.replace(/^\/+/,"")}`:V.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=V.location)&&void 0!==b?b:"").slice(-13)}`,p.WARNING,u.ERROR_4)}const X=e.config.replaceResponseBodyUrls&&Q?new s.URL(T(Q.href,{direction:g.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):Q,ee=Q?X.origin!==Q.origin||e.config.dontTranslateLocationHeader?X:`${w.origin}${X.href.substring(X.origin.length)}`:Q,te=G||Z,ne=null!=W?W:yield new Promise((e=>{let t=Buffer.alloc(0);te?(te.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),te.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:U(n,V,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.INBOUND,mapping:e.config.mapping,port:e.config.port,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls,ssl:!!e.config.ssl}).catch((e=>(C(502,a,Buffer.from(I(e,"stream",w,P))),Buffer.from("")))):n)),oe=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},V),e.config.replaceResponseBodyUrls?{"content-length":`${ne.byteLength}`}:{}),e.config.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=L.split("").map(((e,t)=>L.substring(t).startsWith(".")&&L.substring(t))).filter((e=>e)),r=[L].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),ee?{location:[ee]}:{});try{Object.entries(oe).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const re=V[":status"]||Z.statusCode||200;a.writeHead(re,e.config.ssl?void 0:Z.statusMessage||"Status read from http/2",oe),ne?a.end(ne):a.end();const se=d.hrtime.bigint();e.notifyLogsListeners({randomId:A,statusCode:re,protocol:q?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(se-D)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:i.method,url:i.url,headers:Object.assign({},...Object.entries(i.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==J?void 0:J.toJSON()})).toString("base64")})}))};exports.serve=q;const A=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",p.ERROR,u.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",p.ERROR,u.ERROR_6)};exports.errorListener=A;const D=e=>W({config:Object.assign(Object.assign({},m),e)},{});exports.start=D;const W=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,g,f,m;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(h,JSON.stringify(r.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",p.ERROR,u.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",p.INFO,u.COLORED)}));if(null===r.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",p.WARNING,u.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(a=e.logsListeners)&&void 0!==a?a:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const v=null!==(l=r.config)&&void 0!==l?l:e.config,b=(null===r.configListeners?[]:null!==(d=null!==(c=r.configListeners)&&void 0!==c?c:e.configListeners)&&void 0!==d?d:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),R=(null===r.logsListeners?[]:null!==(f=null!==(g=r.logsListeners)&&void 0!==g?g:e.logsListeners)&&void 0!==f?f:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:v,logsListeners:R,configListeners:b,configFileWatcher:null!==(m=w.configFileWatcher)&&void 0!==m?m:(0,i.watchFile)(h,(()=>t(void 0,void 0,void 0,(function*(){return W(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield x(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",p.ERROR,u.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",p.ERROR,u.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,p.INFO,u.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,p.INFO,u.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,p.INFO,u.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,p.INFO,u.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,p.INFO,u.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,p.INFO,u.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),p.INFO,u.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,p.INFO,u.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,p.INFO,u.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",p.INFO,u.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",p.INFO,u.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",p.INFO,u.RESTART),L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(w))})))),log:y.bind(w,w),notifyConfigListeners:O.bind(w),notifyLogsListeners:$.bind(w),quickStatus:L.bind(w),server:null!==r.server&&w.server?w.server:(v.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},v.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>q(w,e,t))).addListener("error",(e=>A(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>W(w,P(w,e,t)))).listen(v.port)}),w}));exports.update=W;const M=null!==(e=d.argv.filter((e=>!["ts-node","node","npx"].some((t=>e.includes(t)))))[0])&&void 0!==e?e:"";M.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/)&&x().then(D);
2
+ "use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(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(i,a)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const n=require("http2"),o=require("http"),r=require("https"),s=require("url"),i=require("fs"),a=require("zlib"),l=require("path"),c=require("crypto"),d=require("process");var p,u,g;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(p||(p={})),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="☠️ "}(u||(u={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(g||(g={}));const f=(0,l.resolve)(d.env.HOME,".local-traffic.json"),h=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:f),m={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},v=e=>e===p.ERROR?"error":e===p.WARNING?"warning":"info",y=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(u.INBOUND,"g"),"inbound:").replace(new RegExp(u.PORT,"g"),"port:").replace(new RegExp(u.OUTBOUND,"g"),"outbound:").replace(new RegExp(u.RULES,"g"),"rules:").replace(new RegExp(u.NO,"g"),"").replace(new RegExp(u.REWRITE,"g"),"+rewrite").replace(new RegExp(u.WEBSOCKET,"g"),"websocket").replace(new RegExp(u.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;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===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${d.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:v(n)})},b=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=[...e.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,e.length),s=e.length<126?Buffer.from(Uint8Array.from([129,(t?128:0)+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,126|(t?128:0)]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]),i=Buffer.from(Int8Array.from(n).buffer),a=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,i,a]:[s,a])};exports.createWebsocketBufferFrom=b;const R=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=R;const w=(e,t)=>{const n=(0,c.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.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`)};exports.acknowledgeWebsocket=w;const O=function(e){return E(this,e,this.configListeners)},$=function(e){return E(this,e,this.logsListeners)},E=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&b(o,!1),i=r.has(!0)&&b(o,!0),a=e=>{e.stream.errored&&e.stream.destroy()};n.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(i,"ascii",(()=>a(e))):e.stream.write(s,"ascii",(()=>a(e))))}))},L=function(){this.log(`⎸${u.PORT} ${this.config.port.toString().padStart(5)} ⎸${u.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?u.REWRITE:" "}⎹⎸${u.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?u.REWRITE:" "}⎹⎸${u.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹⎸${this.config.websocket?u.WEBSOCKET:u.NO}⎹⎸${this.config.simpleLogs?u.NO:u.COLORED}⎹⎸${this.config.disableWebSecurity?u.NO:u.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=L;const x=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(h,((n,o)=>{n&&!e&&y(null,"config error. Using default value",p.ERROR,u.ERROR_1);let r=null;try{r=Object.assign({},m,JSON.parse((o||"{}").toString()))}catch(e){return y({config:r},"config syntax incorrect, aborting",p.ERROR,u.ERROR_2),r=null!=r?r:Object.assign({},m),void t(r)}r.mapping[""]||y({config:r},'default mapping "" not provided.',p.WARNING,u.ERROR_3),n&&"ENOENT"===n.code&&e&&h===f?(0,i.writeFile)(h,JSON.stringify(m,null,2),(e=>{e?y(null,"config file NOT created",p.ERROR,u.ERROR_4):y(null,"config file created",p.INFO,u.COLORED),t(r)})):t(r)}))))}));exports.load=x;const S=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),N="https://cdn.jsdelivr.net/npm/",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="${N}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${N}jquery/dist/jquery.min.js"><\/script>\n<script src="${N}bootstrap/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/>`,k=e=>{const t=(0,l.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,i.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,i.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,i.lstat)((0,l.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=`${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>${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}}},j=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=e,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}}),I=(e,t,n,o)=>`${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>${o||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,U=(e,n,o)=>t(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(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?a.gunzip:"deflate"===t?a.inflate:"br"===t?a.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).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()))?o.replaceResponseBodyUrls?T(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.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)))}))}));exports.replaceBody=U;const T=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>s.startsWith("logs:")||s.startsWith("config:")||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===g.INBOUND?e.replace(new RegExp(s.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=T;const C=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=C;const H=(e,t)=>{var n,o,r,i,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(i=t.port)&&void 0!==i?i:8080}`:""}`,d=new s.URL(`http${t.ssl?"s":""}://${c}${e.url}`),p=d.href.substring(d.origin.length),u=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new s.URL(S("string"==typeof t?t:t.downstreamUrl))}))))),[g,f]=null!==(a=Object.entries(u).find((([e])=>p.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:p,key:g,target:f}};exports.determineMapping=H;const P=function(e,t,n){var i,a,l,c;if(!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:g,path:f}=H(t,e.config);if("/local-traffic-logs"===f)return w(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(i=t.headers["user-agent"])||void 0===i?void 0:i.toString())&&void 0!==a?a:"").includes("Chrome")})};if("/local-traffic-config"===f){w(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=R(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",p.WARNING,u.ERROR_4)}W(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const h=new s.URL(`${g.protocol}//${g.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),m={hostname:h.hostname,path:h.pathname,port:h.port,protocol:h.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:h.hostname},v="https:"===h.protocol?(0,r.request)(m):(0,o.request)(m);v.end(),v.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),v.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)}))}))};exports.websocketServe=P;const q=function(e,i,a){var l,f,v,y,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void C(400,a,Buffer.from(I(new Error("client must supply a 'host' header"),"proxy",new s.URL(`http${e.config.ssl?"s":""}://unknowndomain${i.url}`))));const{proxyHostname:t,proxyHostnameAndPort:R,url:w,path:O,key:$,target:E}=H(i,e.config);if(!E)return void C(502,a,Buffer.from(I(new Error(`No mapping found in config file ${h}`),"proxy",w)));const L=E.host.replace(RegExp(/\/+$/),""),x=`${E.href.substring(8+E.host.length)}${S(O.replace(RegExp(S($)),""))}`.replace(/^\/*/,"/"),P=new s.URL(`${E.protocol}//${L}${x}`);let q=!e.config.dontUseHttp2Downstream;const A=(0,c.randomBytes)(20).toString("hex");e.notifyLogsListeners({level:"info",protocol:q?"HTTP/2":"HTTP1.1",method:i.method,upstreamPath:O,downstreamPath:P.href,randomId:A,uniqueHash:"N/A"});const D=d.hrtime.bigint();let W=null;const M="file:"===E.protocol?k(P):"logs:"===E.protocol?((e,t)=>j(`${B(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">Upstream Path</th>\n <th scope="col">Downstream 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 const socket = new WebSocket("ws${t?"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.upstreamPath + '</td>' + \n '<td scope="col">' + data.downstreamPath + '</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>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>j(`${B(127899,"config","")}\n <link href="${N}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="${N}jsoneditor/dist/jsoneditor.min.js"><\/script>\n <script src="${N}node-forge/dist/forge.min.js"><\/script>\n <div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n <div class="modal-dialog" role="document">\n <div class="modal-content">\n <div class="modal-header">\n <h5 class="modal-title">SSL keypair generation in progress</h5>\n </div>\n <div class="modal-body">\n <p>Wait a few seconds or move your mouse to improve the entropy.</p>\n </div>\n </div>\n </div>\n </div>\n <div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n <script>\n // create the editor\n const container = document.getElementById("jsoneditor")\n const options = {mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n ${Object.entries(Object.assign(Object.assign({},m),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n ")}\n },\n required: [],\n additionalProperties: false\n }}\n\n function save() {\n socket.send(JSON.stringify(editor.get()));\n }\n\n function generateSslCertificate() {\n const sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\n sslModal.show()\n setTimeout(function() {\n const keypair = forge.pki.rsa.generateKeyPair(2048);\n const certificate = forge.pki.createCertificate();\n const now = new Date();\n const fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\n Object.assign(certificate, {\n publicKey: keypair.publicKey,\n serialNumber: "01",\n validity: {\n notBefore: now,\n notAfter: fiveYears,\n },\n });\n certificate.sign(keypair.privateKey, forge.md.sha256.create());\n const key = forge.pki.privateKeyToPem(keypair.privateKey);\n const cert = forge.pki.certificateToPem(certificate);\n const existingConfig = editor.get();\n editor.set({ ...existingConfig, ssl: { key, cert },\n port: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n });\n sslModal.hide();\n }, 100);\n }\n\n const editor = new JSONEditor(container, options);\n let socket;\n const initialJson = ${JSON.stringify(t)}\n editor.set(initialJson)\n editor.validate();\n editor.aceEditor.commands.addCommand({\n name: 'save',\n bindKey: {win: 'Ctrl-S', mac: 'Command-S'},\n exec: save,\n });\n\n window.addEventListener("DOMContentLoaded", function() {\n document.getElementById('jsoneditor').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n document.getElementById('jsoneditor').style.width =\n parseInt(window.getComputedStyle(\n document.querySelector('.container')).maxWidth) + 'px';\n const sslButton = document.createElement('button');\n sslButton.addEventListener("click", generateSslCertificate);\n sslButton.type="button";\n sslButton.classList.add("btn");\n sslButton.classList.add("btn-primary");\n sslButton.innerHTML="&#x1F512;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(sslButton);\n const saveButton = document.createElement('button');\n saveButton.addEventListener("click", save);\n saveButton.type="button";\n saveButton.classList.add("btn");\n saveButton.classList.add("btn-primary");\n saveButton.innerHTML="&#x1F4BE;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(saveButton);\n socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\n socket.onmessage = function(event) {\n editor.set(JSON.parse(event.data))\n editor.validate()\n }\n });\n <\/script>\n </body></html>`))(R,e.config):q?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(P,{rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{q=q&&!!o.alpnProtocol,e(q?t:null)}));t.on("error",(e=>{W=q&&Buffer.from(I(e,"connection",w,P))}))})),new Promise((e=>setTimeout((()=>{q=!1,e(null)}),3e3)))]):null;W instanceof Buffer||(W=null);const F=null==i?void 0:i.readableLength,_=null===(l=null==i?void 0:i.stream)||void 0===l?void 0:l.readableLength;let J=null;const K=e.config.replaceRequestBodyUrls||e.logsListeners.length;if(K){const n=null!==(f=null==i?void 0:i.stream)&&void 0!==f?f:i;let o=Buffer.from([]);const r=!((e.config.ssl&&0===_||!e.config.ssl&&0===F)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{r||e(void 0),n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)}))]),r&&!o.length&&e.log(`body replacement error ${O.slice(-17)}`,p.WARNING,u.ERROR_4),J=yield U(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.OUTBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls})}const z=Object.assign(Object.assign({},[...Object.entries(i.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(w.hostname,L))).join(", "),e)),{})),{origin:E.href,referer:P.toString(),"content-length":null!==(y=null!==(v=null==J?void 0:J.length)&&void 0!==v?v:i.headers["content-length"])&&void 0!==y?y:0,":authority":L,":method":i.method,":path":x,":scheme":E.protocol.replace(":","")}),G=M&&!W&&M.request(z,{endStream:e.config.ssl?!(null==_||_):!F});null==G||G.on("error",(e=>{const t=-505===e.errno;W=Buffer.from(I(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),w,P))}));const Y={hostname:E.hostname,path:x,port:E.port,protocol:E.protocol,rejectUnauthorized:!1,method:i.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(z).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},Z=!W&&!q&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(Y,e):(0,o.request)(Y,e);t.on("error",(t=>{W=Buffer.from(I(t,"request",w,P)),e(null)})),K&&(t.write(J),t.end()),K||(i.on("data",(e=>t.write(e))),i.on("end",(()=>t.end())))})));if(W)return void C(502,a,W);W=null,e.config.ssl&&_&&G&&(K&&(G.write(J),G.end()),K||(i.stream.on("data",(e=>{G.write(e)})),i.stream.on("end",(()=>G.end())))),!e.config.ssl&&F&&G&&(K&&(G.write(J),G.end()),K||(i.on("data",(e=>{G.write(e)})),i.on("end",(()=>G.end()))));const{outboundResponseHeaders:V}=yield new Promise((e=>G?G.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!G&&Z?{outboundResponseHeaders:Z.headers}:{outboundResponseHeaders:{}})));let Q=null;try{V.location&&(Q=new s.URL(V.location.startsWith("/")?`${E.href}${V.location.replace(/^\/+/,"")}`:V.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=V.location)&&void 0!==b?b:"").slice(-13)}`,p.WARNING,u.ERROR_4)}const X=e.config.replaceResponseBodyUrls&&Q?new s.URL(T(Q.href,{direction:g.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):Q,ee=Q?X.origin!==Q.origin||e.config.dontTranslateLocationHeader?X:`${w.origin}${X.href.substring(X.origin.length)}`:Q,te=G||Z,ne=null!=W?W:yield new Promise((e=>{let t=Buffer.alloc(0);te?(te.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),te.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:U(n,V,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.INBOUND,mapping:e.config.mapping,port:e.config.port,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls,ssl:!!e.config.ssl}).catch((e=>(C(502,a,Buffer.from(I(e,"stream",w,P))),Buffer.from("")))):n)),oe=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},V),e.config.replaceResponseBodyUrls?{"content-length":`${ne.byteLength}`}:{}),e.config.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=L.split("").map(((e,t)=>L.substring(t).startsWith(".")&&L.substring(t))).filter((e=>e)),r=[L].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),ee?{location:[ee]}:{});try{Object.entries(oe).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const re=V[":status"]||Z.statusCode||200;a.writeHead(re,e.config.ssl?void 0:Z.statusMessage||"Status read from http/2",oe),ne?a.end(ne):a.end();const se=d.hrtime.bigint();e.notifyLogsListeners({randomId:A,statusCode:re,protocol:q?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(se-D)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:i.method,url:i.url,headers:Object.assign({},...Object.entries(i.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==J?void 0:J.toJSON()})).toString("base64")})}))};exports.serve=q;const A=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",p.ERROR,u.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",p.ERROR,u.ERROR_6)};exports.errorListener=A;const D=e=>W({config:Object.assign(Object.assign({},m),e)},{});exports.start=D;const W=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,g,f,m;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(h,JSON.stringify(r.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",p.ERROR,u.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",p.INFO,u.COLORED)}));if(null===r.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",p.WARNING,u.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(a=e.logsListeners)&&void 0!==a?a:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const v=null!==(l=r.config)&&void 0!==l?l:e.config,b=(null===r.configListeners?[]:null!==(d=null!==(c=r.configListeners)&&void 0!==c?c:e.configListeners)&&void 0!==d?d:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),R=(null===r.logsListeners?[]:null!==(f=null!==(g=r.logsListeners)&&void 0!==g?g:e.logsListeners)&&void 0!==f?f:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:v,logsListeners:R,configListeners:b,configFileWatcher:null!==(m=w.configFileWatcher)&&void 0!==m?m:(0,i.watchFile)(h,(()=>t(void 0,void 0,void 0,(function*(){return W(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield x(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",p.ERROR,u.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",p.ERROR,u.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,p.INFO,u.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,p.INFO,u.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,p.INFO,u.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,p.INFO,u.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,p.INFO,u.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,p.INFO,u.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),p.INFO,u.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,p.INFO,u.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,p.INFO,u.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",p.INFO,u.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",p.INFO,u.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",p.INFO,u.RESTART),L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(w))})))),log:y.bind(w,w),notifyConfigListeners:O.bind(w),notifyLogsListeners:$.bind(w),quickStatus:L.bind(w),server:null!==r.server&&w.server?w.server:(v.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},v.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>q(w,e,t))).addListener("error",(e=>A(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>W(w,P(w,e,t)))).listen(v.port)}),w}));exports.update=W;const M=null!==(e=d.argv.filter((e=>!["ts-node","node","npx","npm","exec"].some((t=>e.includes(t)))))[0])&&void 0!==e?e:"";M.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/)&&x().then(D);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.70",
3
+ "version": "0.0.71",
4
4
  "main": "./dist/local-traffic.js",
5
5
  "private": false,
6
6
  "keywords": [
package/.prettierrc DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "printWidth": 80,
3
- "tabWidth": 2,
4
- "useTabs": false,
5
- "semi": true,
6
- "singleQuote": false,
7
- "trailingComma": "all",
8
- "bracketSpacing": true,
9
- "jsxBracketSameLine": false,
10
- "arrowParens": "avoid",
11
- "proseWrap": "never"
12
- }
package/renovate.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
- "extends": [
4
- "config:base"
5
- ],
6
- "branchPrefix": "renovate-"
7
- }