local-traffic 0.0.72 → 0.0.73

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,1447 @@
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))))}))},x=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=x;const L=(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=L;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 x=E.host.replace(RegExp(/\/+$/),""),L=`${E.href.substring(8+E.host.length)}${S(O.replace(RegExp(S($)),""))}`.replace(/^\/*/,"/"),P=new s.URL(`${E.protocol}//${x}${L}`);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,x))).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":x,":method":i.method,":path":L,":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:L,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=x.split("").map(((e,t)=>x.substring(t).startsWith(".")&&x.substring(t))).filter((e=>e)),r=[x].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 L(!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),x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(w))})))),log:y.bind(w,w),notifyConfigListeners:O.bind(w),notifyLogsListeners:$.bind(w),quickStatus:x.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)&&!e.match(/npm-cache/)&&!e.match(/_npx/)))))[0])&&void 0!==e?e:"";M.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/)&&L().then(D);
2
+ "use strict";
3
+ var e,
4
+ t =
5
+ (this && this.__awaiter) ||
6
+ function (e, t, n, o) {
7
+ return new (n || (n = Promise))(function (r, s) {
8
+ function i(e) {
9
+ try {
10
+ l(o.next(e));
11
+ } catch (e) {
12
+ s(e);
13
+ }
14
+ }
15
+ function a(e) {
16
+ try {
17
+ l(o.throw(e));
18
+ } catch (e) {
19
+ s(e);
20
+ }
21
+ }
22
+ function l(e) {
23
+ var t;
24
+ e.done
25
+ ? r(e.value)
26
+ : ((t = e.value),
27
+ t instanceof n
28
+ ? t
29
+ : new n(function (e) {
30
+ e(t);
31
+ })).then(i, a);
32
+ }
33
+ l((o = o.apply(e, t || [])).next());
34
+ });
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: !0 }),
37
+ (exports.update =
38
+ exports.serve =
39
+ exports.determineMapping =
40
+ exports.send =
41
+ exports.replaceTextUsingMapping =
42
+ exports.replaceBody =
43
+ exports.acknowledgeWebsocket =
44
+ exports.readWebsocketBuffer =
45
+ exports.createWebsocketBufferFrom =
46
+ exports.websocketServe =
47
+ exports.quickStatus =
48
+ exports.errorListener =
49
+ exports.load =
50
+ exports.start =
51
+ void 0);
52
+ const n = require("http2"),
53
+ o = require("http"),
54
+ r = require("https"),
55
+ s = require("url"),
56
+ i = require("fs"),
57
+ a = require("zlib"),
58
+ l = require("path"),
59
+ c = require("crypto"),
60
+ d = require("process");
61
+ var p, u, g;
62
+ !(function (e) {
63
+ (e[(e.ERROR = 124)] = "ERROR"),
64
+ (e[(e.INFO = 93)] = "INFO"),
65
+ (e[(e.WARNING = 172)] = "WARNING");
66
+ })(p || (p = {})),
67
+ (function (e) {
68
+ (e.INBOUND = "↘️ "),
69
+ (e.PORT = "☎️ "),
70
+ (e.OUTBOUND = "↗️ "),
71
+ (e.RULES = "🔗"),
72
+ (e.REWRITE = "✒️ "),
73
+ (e.RESTART = "🔄"),
74
+ (e.WEBSOCKET = "☄️ "),
75
+ (e.COLORED = "✨"),
76
+ (e.SHIELD = "🛡️ "),
77
+ (e.NO = "⛔"),
78
+ (e.ERROR_1 = "❌"),
79
+ (e.ERROR_2 = "⛈️ "),
80
+ (e.ERROR_3 = "☢️ "),
81
+ (e.ERROR_4 = "⁉️ "),
82
+ (e.ERROR_5 = "⚡"),
83
+ (e.ERROR_6 = "☠️ ");
84
+ })(u || (u = {})),
85
+ (function (e) {
86
+ (e.INBOUND = "INBOUND"), (e.OUTBOUND = "OUTBOUND");
87
+ })(g || (g = {}));
88
+ const h = (0, l.resolve)(d.env.HOME, ".local-traffic.json"),
89
+ f = (0, l.resolve)(
90
+ (0, d.cwd)(),
91
+ d.argv.slice(-1)[0].endsWith(".json") ? d.argv.slice(-1)[0] : h,
92
+ ),
93
+ m = {
94
+ mapping: { "/config/": "config://", "/logs/": "logs://" },
95
+ port: 8080,
96
+ replaceRequestBodyUrls: !1,
97
+ replaceResponseBodyUrls: !1,
98
+ dontUseHttp2Downstream: !1,
99
+ dontTranslateLocationHeader: !1,
100
+ simpleLogs: !1,
101
+ websocket: !0,
102
+ disableWebSecurity: !1,
103
+ },
104
+ v = e => (e === p.ERROR ? "error" : e === p.WARNING ? "warning" : "info"),
105
+ y = function (e, t, n, o) {
106
+ var r, s, i, a, l;
107
+ const c =
108
+ (null === (r = null == e ? void 0 : e.config) || void 0 === r
109
+ ? void 0
110
+ : r.simpleLogs) ||
111
+ (null === (s = null == e ? void 0 : e.logsListeners) || void 0 === s
112
+ ? void 0
113
+ : s.length)
114
+ ? t
115
+ .replace(/⎸/g, "|")
116
+ .replace(/⎹/g, "|")
117
+ .replace(/\u001b\[[^m]*m/g, "")
118
+ .replace(new RegExp(u.INBOUND, "g"), "inbound:")
119
+ .replace(new RegExp(u.PORT, "g"), "port:")
120
+ .replace(new RegExp(u.OUTBOUND, "g"), "outbound:")
121
+ .replace(new RegExp(u.RULES, "g"), "rules:")
122
+ .replace(new RegExp(u.NO, "g"), "")
123
+ .replace(new RegExp(u.REWRITE, "g"), "+rewrite")
124
+ .replace(new RegExp(u.WEBSOCKET, "g"), "websocket")
125
+ .replace(new RegExp(u.SHIELD, "g"), "web-security")
126
+ .replace(/\|+/g, "|")
127
+ : t;
128
+ console.log(
129
+ `${(e => {
130
+ const t = new Date();
131
+ return `${e ? "" : ""}${`${t.getHours()}`.padStart(2, "0")}${
132
+ e ? ":" : ":"
133
+ }${`${t.getMinutes()}`.padStart(2, "0")}${
134
+ e ? ":" : ":"
135
+ }${`${t.getSeconds()}`.padStart(2, "0")}${e ? "" : ""}`;
136
+ })(
137
+ null === (i = null == e ? void 0 : e.config) || void 0 === i
138
+ ? void 0
139
+ : i.simpleLogs,
140
+ )} ${
141
+ (
142
+ null === (a = null == e ? void 0 : e.config) || void 0 === a
143
+ ? void 0
144
+ : a.simpleLogs
145
+ )
146
+ ? c
147
+ : n
148
+ ? `[48;5;${n}m⎸ ${(d.stdout.isTTY && o) || ""} ${t.padEnd(40)} ⎹`
149
+ : t
150
+ }`,
151
+ ),
152
+ null === (l = null == e ? void 0 : e.notifyLogsListeners) ||
153
+ void 0 === l ||
154
+ l.call(e, { event: c, level: v(n) });
155
+ },
156
+ b = (e, t) => {
157
+ const n = Array(4)
158
+ .fill(0)
159
+ .map(() => (t ? Math.floor(256 * Math.random()) : 0)),
160
+ o = [...e.substring(0, 65536)].map((e, t) => e.charCodeAt(0) ^ n[3 & t]),
161
+ r = Math.min(65535, e.length),
162
+ s =
163
+ e.length < 126
164
+ ? Buffer.from(Uint8Array.from([129, (t ? 128 : 0) + r]).buffer)
165
+ : Buffer.concat([
166
+ Buffer.from(Uint8Array.from([129, 126 | (t ? 128 : 0)]).buffer),
167
+ Buffer.from(Uint8Array.from([r >> 8]).buffer),
168
+ Buffer.from(Uint8Array.from([255 & r]).buffer),
169
+ ]),
170
+ i = Buffer.from(Int8Array.from(n).buffer),
171
+ a = Buffer.from(Int8Array.from(o).buffer);
172
+ return Buffer.concat(t ? [s, i, a] : [s, a]);
173
+ };
174
+ exports.createWebsocketBufferFrom = b;
175
+ const R = (e, t) => {
176
+ var n;
177
+ if (!t && 0 == (1 & e.readUInt8(0)))
178
+ return { payloadLength: 0, mask: [0, 0, 0, 0], body: "" };
179
+ const o = t ? 0 : e.readUInt8(1),
180
+ r = o >> 7,
181
+ s = 127 & o,
182
+ i = t
183
+ ? t.payloadLength
184
+ : 127 !== s
185
+ ? s
186
+ : e.readUInt8(2) << (8 + e.readUInt8(3)),
187
+ a = t
188
+ ? t.mask
189
+ : r
190
+ ? Array(4)
191
+ .fill(0)
192
+ .map((t, n) => e.readUInt8(n + 4))
193
+ : [0, 0, 0, 0],
194
+ l = t ? 0 : r ? 8 : 4,
195
+ c = Array(e.length - l)
196
+ .fill(0)
197
+ .map((t, n) => String.fromCharCode(e.readUInt8(n + l) ^ a[3 & n]))
198
+ .join("");
199
+ return {
200
+ payloadLength: i,
201
+ mask: a,
202
+ body: (null !== (n = null == t ? void 0 : t.body) && void 0 !== n
203
+ ? n
204
+ : ""
205
+ ).concat(c),
206
+ };
207
+ };
208
+ exports.readWebsocketBuffer = R;
209
+ const w = (e, t) => {
210
+ const n = (0, c.createHash)("sha1");
211
+ n.update(t + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
212
+ const o = n.digest("base64");
213
+ (e.allowHalfOpen = !0),
214
+ e.write(
215
+ `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`,
216
+ );
217
+ };
218
+ exports.acknowledgeWebsocket = w;
219
+ const O = function (e) {
220
+ return E(this, e, this.configListeners);
221
+ },
222
+ $ = function (e) {
223
+ return E(this, e, this.logsListeners);
224
+ },
225
+ E = (e, t, n) => {
226
+ if (!n.length) return;
227
+ const o = JSON.stringify(t),
228
+ r = new Set(n.map(e => e.wantsMask)),
229
+ s = r.has(!1) && b(o, !1),
230
+ i = r.has(!0) && b(o, !0),
231
+ a = e => {
232
+ e.stream.errored && e.stream.destroy();
233
+ };
234
+ n.forEach(e => {
235
+ e.stream.closed ||
236
+ e.stream.errored ||
237
+ (e.wantsMask
238
+ ? e.stream.write(i, "ascii", () => a(e))
239
+ : e.stream.write(s, "ascii", () => a(e)));
240
+ });
241
+ },
242
+ x = function () {
243
+ this.log(
244
+ `⎸${u.PORT} ${this.config.port.toString().padStart(5)} ⎸${u.OUTBOUND} ${
245
+ this.config.dontUseHttp2Downstream ? "H1.1" : "H/2 "
246
+ }${this.config.replaceRequestBodyUrls ? u.REWRITE : " "}⎹⎸${u.INBOUND} ${
247
+ this.config.ssl ? "H/2 " : "H1.1"
248
+ }${this.config.replaceResponseBodyUrls ? u.REWRITE : " "}⎹⎸${
249
+ u.RULES
250
+ }${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹⎸${
251
+ this.config.websocket ? u.WEBSOCKET : u.NO
252
+ }⎹⎸${this.config.simpleLogs ? u.NO : u.COLORED}⎹⎸${
253
+ this.config.disableWebSecurity ? u.NO : u.SHIELD
254
+ }⎹`,
255
+ ),
256
+ this.notifyConfigListeners(this.config);
257
+ };
258
+ exports.quickStatus = x;
259
+ const L = (e = !0) =>
260
+ t(void 0, void 0, void 0, function* () {
261
+ return new Promise(t =>
262
+ (0, i.readFile)(f, (n, o) => {
263
+ n &&
264
+ !e &&
265
+ y(null, "config error. Using default value", p.ERROR, u.ERROR_1);
266
+ let r = null;
267
+ try {
268
+ r = Object.assign({}, m, JSON.parse((o || "{}").toString()));
269
+ } catch (e) {
270
+ return (
271
+ y(
272
+ { config: r },
273
+ "config syntax incorrect, aborting",
274
+ p.ERROR,
275
+ u.ERROR_2,
276
+ ),
277
+ (r = null != r ? r : Object.assign({}, m)),
278
+ void t(r)
279
+ );
280
+ }
281
+ r.mapping[""] ||
282
+ y(
283
+ { config: r },
284
+ 'default mapping "" not provided.',
285
+ p.WARNING,
286
+ u.ERROR_3,
287
+ ),
288
+ n && "ENOENT" === n.code && e && f === h
289
+ ? (0, i.writeFile)(f, JSON.stringify(m, null, 2), e => {
290
+ e
291
+ ? y(null, "config file NOT created", p.ERROR, u.ERROR_4)
292
+ : y(null, "config file created", p.INFO, u.COLORED),
293
+ t(r);
294
+ })
295
+ : t(r);
296
+ }),
297
+ );
298
+ });
299
+ exports.load = L;
300
+ const S = e => ("" == e ? "" : (0, l.normalize)(e).replace(/\\/g, "/")),
301
+ N = "https://cdn.jsdelivr.net/npm/",
302
+ B = (e, t, n) =>
303
+ `<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(
304
+ 16,
305
+ )}; 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(
306
+ 16,
307
+ )}; local-traffic ${t}</h1>\n<br/>`,
308
+ k = e => {
309
+ const t = (0, l.resolve)(
310
+ "/",
311
+ e.hostname,
312
+ ...e.pathname
313
+ .replace(/[?#].*$/, "")
314
+ .replace(/^\/+/, "")
315
+ .split("/"),
316
+ );
317
+ return {
318
+ error: null,
319
+ data: null,
320
+ hasRun: !1,
321
+ run: function () {
322
+ return this.hasRun
323
+ ? Promise.resolve()
324
+ : new Promise(n =>
325
+ (0, i.readFile)(t, (o, r) => {
326
+ if (((this.hasRun = !0), !o || "EISDIR" !== o.code))
327
+ return (this.error = o), (this.data = r), void n(void 0);
328
+ (0, i.readdir)(t, (t, o) => {
329
+ (this.error = t),
330
+ (this.data = o),
331
+ t
332
+ ? n(void 0)
333
+ : Promise.all(
334
+ o.map(
335
+ t =>
336
+ new Promise(n =>
337
+ (0, i.lstat)(
338
+ (0, l.resolve)(e.pathname, t),
339
+ (e, o) => n([t, o, e]),
340
+ ),
341
+ ),
342
+ ),
343
+ ).then(t => {
344
+ const o = t
345
+ .filter(e => !e[2] && e[1].isDirectory())
346
+ .concat(t.filter(e => !e[2] && e[1].isFile()));
347
+ (this.data = `${B(
348
+ 128194,
349
+ "directory",
350
+ e.href,
351
+ )}<p>Directory content of <i>${e.href.replace(
352
+ /\//g,
353
+ "&#x002F;",
354
+ )}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${
355
+ e.pathname.endsWith("/") ? ".." : "."
356
+ }">&lt;parent&gt;</a></li>${o
357
+ .filter(e => !e[2])
358
+ .map(
359
+ t =>
360
+ `<li class="list-group-item">&#x${(t[1].isDirectory()
361
+ ? 128193
362
+ : 128196
363
+ ).toString(16)};<a href="${
364
+ e.pathname.endsWith("/")
365
+ ? ""
366
+ : `${e.pathname.split("/").slice(-1)[0]}/`
367
+ }${t[0]}">${t[0]}</a></li>`,
368
+ )
369
+ .join("\n")}</li></ul></body></html>`),
370
+ n(void 0);
371
+ });
372
+ });
373
+ }),
374
+ );
375
+ },
376
+ events: {},
377
+ on: function (e, n) {
378
+ return (
379
+ (this.events[e] = n),
380
+ this.run().then(() => {
381
+ "response" === e &&
382
+ this.events.response(
383
+ t.endsWith(".svg")
384
+ ? { Server: "local", "Content-Type": "image/svg+xml" }
385
+ : { Server: "local" },
386
+ 0,
387
+ ),
388
+ "data" === e &&
389
+ this.data &&
390
+ (this.events.data(this.data), this.events.end()),
391
+ "error" === e && this.error && this.events.error(this.error);
392
+ }),
393
+ this
394
+ );
395
+ },
396
+ end: function () {
397
+ return this;
398
+ },
399
+ request: function () {
400
+ return this;
401
+ },
402
+ };
403
+ },
404
+ j = e => ({
405
+ error: null,
406
+ data: null,
407
+ run: function () {
408
+ return new Promise(t => {
409
+ (this.data = e), t(void 0);
410
+ });
411
+ },
412
+ events: {},
413
+ on: function (e, t) {
414
+ return (
415
+ (this.events[e] = t),
416
+ this.run().then(() => {
417
+ "response" === e &&
418
+ this.events.response(
419
+ { Server: "local", "Content-Type": "text/html" },
420
+ 0,
421
+ ),
422
+ "data" === e &&
423
+ this.data &&
424
+ (this.events.data(this.data), this.events.end()),
425
+ "error" === e && this.error && this.events.error(this.error);
426
+ }),
427
+ this
428
+ );
429
+ },
430
+ end: function () {
431
+ return this;
432
+ },
433
+ request: function () {
434
+ return this;
435
+ },
436
+ }),
437
+ I = (e, t, n, o) =>
438
+ `${B(
439
+ 128163,
440
+ "error",
441
+ e.message,
442
+ )}\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>${
443
+ e.stack || `<i>${e.name} : ${e.message}</i>`
444
+ }${
445
+ e.errno ? `<br/>(code : ${e.errno})` : ""
446
+ }</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>${
447
+ o || "&lt;no-target-url&gt;"
448
+ }</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,
449
+ T = (e, n, o) =>
450
+ t(void 0, void 0, void 0, function* () {
451
+ var r, s;
452
+ return (
453
+ null !==
454
+ (s =
455
+ null === (r = n["content-encoding"]) || void 0 === r
456
+ ? void 0
457
+ : r.toString()) && void 0 !== s
458
+ ? s
459
+ : ""
460
+ )
461
+ .split(",")
462
+ .reduce(
463
+ (e, n) =>
464
+ t(void 0, void 0, void 0, function* () {
465
+ const t = n.trim().toLowerCase(),
466
+ o =
467
+ "gzip" === t || "x-gzip" === t
468
+ ? a.gunzip
469
+ : "deflate" === t
470
+ ? a.inflate
471
+ : "br" === t
472
+ ? a.brotliDecompress
473
+ : "identity" === t || "" === t
474
+ ? (e, t) => {
475
+ t(null, e);
476
+ }
477
+ : null;
478
+ if (null === o)
479
+ throw new Error(`${t} compression not supported by the proxy`);
480
+ const r = yield e;
481
+ return yield new Promise((e, t) =>
482
+ o(r, (n, o) => {
483
+ n && t(n), e(o);
484
+ }),
485
+ );
486
+ }),
487
+ Promise.resolve(e),
488
+ )
489
+ .then(e => {
490
+ const t = e.length > 1e7,
491
+ r = [
492
+ "text/html",
493
+ "application/javascript",
494
+ "application/json",
495
+ ].some(e => {
496
+ var t;
497
+ return (null !== (t = n["content-type"]) && void 0 !== t ? t : "")
498
+ .toString()
499
+ .includes(e);
500
+ });
501
+ return !t && (r || !/[^\x00-\x7F]/.test(e.toString()))
502
+ ? C(e.toString(), {
503
+ direction: o.direction,
504
+ proxyHostnameAndPort: o.proxyHostnameAndPort,
505
+ ssl: o.ssl,
506
+ mapping: o.mapping,
507
+ }).replace(
508
+ /\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,
509
+ `?protocol=ws${o.ssl ? "s" : ""}%3A&hostname=${
510
+ o.proxyHostname
511
+ }&port=${o.port}&pathname=${encodeURIComponent(
512
+ o.key.replace(/\/+$/, ""),
513
+ )}`,
514
+ )
515
+ : e;
516
+ })
517
+ .then(e => {
518
+ var t, o;
519
+ return (
520
+ null !==
521
+ (o =
522
+ null === (t = n["content-encoding"]) || void 0 === t
523
+ ? void 0
524
+ : t.toString()) && void 0 !== o
525
+ ? o
526
+ : ""
527
+ )
528
+ .split(",")
529
+ .reverse()
530
+ .reduce((e, t) => {
531
+ const n = t.trim().toLowerCase(),
532
+ o =
533
+ "gzip" === n || "x-gzip" === n
534
+ ? a.gzip
535
+ : "deflate" === n
536
+ ? a.deflate
537
+ : "br" === n
538
+ ? a.brotliCompress
539
+ : "identity" === n || "" === n
540
+ ? (e, t) => {
541
+ t(null, e);
542
+ }
543
+ : null;
544
+ if (null === o)
545
+ throw new Error(`${n} compression not supported by the proxy`);
546
+ return e.then(
547
+ e =>
548
+ new Promise(t =>
549
+ o(e, (e, n) => {
550
+ if (e) throw e;
551
+ t(n);
552
+ }),
553
+ ),
554
+ );
555
+ }, Promise.resolve(Buffer.from(e)));
556
+ });
557
+ });
558
+ exports.replaceBody = T;
559
+ const C = (e, { direction: t, proxyHostnameAndPort: n, ssl: o, mapping: r }) =>
560
+ Object.entries(r)
561
+ .map(([e, t]) => [e, "string" == typeof t ? t : t.replaceBody])
562
+ .reduce(
563
+ (e, [r, s]) =>
564
+ s.startsWith("logs:") ||
565
+ s.startsWith("config:") ||
566
+ ("" !== r && !r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/))
567
+ ? e
568
+ : t === g.INBOUND
569
+ ? e.replace(
570
+ new RegExp(
571
+ s
572
+ .replace(/^(file|logs):\/\//, "")
573
+ .replace(/[*+?^${}()|[\]\\]/g, "")
574
+ .replace(/^https/, "https?") + "/*",
575
+ "ig",
576
+ ),
577
+ `http${o ? "s" : ""}://${n}${r.replace(/\/+$/, "")}/`,
578
+ )
579
+ : e
580
+ .split(`http${o ? "s" : ""}://${n}${r.replace(/\/+$/, "")}`)
581
+ .join(s),
582
+ e,
583
+ )
584
+ .split(`${n}/:`)
585
+ .join(`${n}:`);
586
+ exports.replaceTextUsingMapping = C;
587
+ const U = (e, t, n) => {
588
+ t.writeHead(e, void 0, {
589
+ "content-type": "text/html",
590
+ "content-length": n.length,
591
+ }),
592
+ t.end(n);
593
+ };
594
+ exports.send = U;
595
+ const H = (e, t) => {
596
+ var n, o, r, i, a;
597
+ const l = (
598
+ null !==
599
+ (r =
600
+ null !==
601
+ (o =
602
+ null === (n = e.headers[":authority"]) || void 0 === n
603
+ ? void 0
604
+ : n.toString()) && void 0 !== o
605
+ ? o
606
+ : e.headers.host) && void 0 !== r
607
+ ? r
608
+ : "localhost"
609
+ ).replace(/:.*/, ""),
610
+ c =
611
+ e.headers[":authority"] ||
612
+ `${e.headers.host}${
613
+ e.headers.host.match(/:[0-9]+$/)
614
+ ? ""
615
+ : 80 !== t.port || t.ssl
616
+ ? 443 === t.port && t.ssl
617
+ ? ""
618
+ : `:${null !== (i = t.port) && void 0 !== i ? i : 8080}`
619
+ : ""
620
+ }`,
621
+ d = new s.URL(`http${t.ssl ? "s" : ""}://${c}${e.url}`),
622
+ p = d.href.substring(d.origin.length),
623
+ u = Object.assign(
624
+ {},
625
+ Object.assign(
626
+ {},
627
+ ...Object.entries(t.mapping).map(([e, t]) => ({
628
+ [e]: new s.URL(S("string" == typeof t ? t : t.downstreamUrl)),
629
+ })),
630
+ ),
631
+ ),
632
+ [g, h] =
633
+ null !==
634
+ (a = Object.entries(u).find(([e]) =>
635
+ p.match(RegExp(e.replace(/^\//, "^/"))),
636
+ )) && void 0 !== a
637
+ ? a
638
+ : [];
639
+ return {
640
+ proxyHostname: l,
641
+ proxyHostnameAndPort: c,
642
+ url: d,
643
+ path: p,
644
+ key: g,
645
+ target: h,
646
+ };
647
+ };
648
+ exports.determineMapping = H;
649
+ const P = function (e, t, n) {
650
+ var i, a, l, c;
651
+ if (!e.config.websocket)
652
+ return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"), {};
653
+ const { key: d, target: g, path: h } = H(t, e.config);
654
+ if ("/local-traffic-logs" === h)
655
+ return (
656
+ w(n, t.headers["sec-websocket-key"]),
657
+ {
658
+ logsListeners: e.logsListeners.concat({
659
+ stream: n,
660
+ wantsMask: !(
661
+ null !==
662
+ (a =
663
+ null === (i = t.headers["user-agent"]) || void 0 === i
664
+ ? void 0
665
+ : i.toString()) && void 0 !== a
666
+ ? a
667
+ : ""
668
+ ).includes("Chrome"),
669
+ }),
670
+ }
671
+ );
672
+ if ("/local-traffic-config" === h) {
673
+ w(n, t.headers["sec-websocket-key"]);
674
+ let o = null;
675
+ return (
676
+ n.on("data", t => {
677
+ const n = R(t, o);
678
+ if (null === o && n.body.length < n.payloadLength) o = n;
679
+ else {
680
+ if (n.body.length >= n.payloadLength && 0 === n.body.length) return;
681
+ if (n.body.length >= n.payloadLength) {
682
+ let t;
683
+ o = null;
684
+ try {
685
+ t = JSON.parse(n.body);
686
+ } catch (t) {
687
+ return void e.log(
688
+ "config file NOT read, try again later",
689
+ p.WARNING,
690
+ u.ERROR_4,
691
+ );
692
+ }
693
+ W(e, { pendingConfigSave: t });
694
+ }
695
+ }
696
+ }),
697
+ {
698
+ configListeners: e.configListeners.concat({
699
+ stream: n,
700
+ wantsMask: !(
701
+ null !==
702
+ (c =
703
+ null === (l = t.headers["user-agent"]) || void 0 === l
704
+ ? void 0
705
+ : l.toString()) && void 0 !== c
706
+ ? c
707
+ : ""
708
+ ).includes("Chrome"),
709
+ }),
710
+ }
711
+ );
712
+ }
713
+ const f = new s.URL(
714
+ `${g.protocol}//${g.host}${
715
+ t.url.endsWith("/_next/webpack-hmr")
716
+ ? t.url
717
+ : t.url.replace(new RegExp(`^${d}`, "g"), "").replace(/^\/*/, "/")
718
+ }`,
719
+ ),
720
+ m = {
721
+ hostname: f.hostname,
722
+ path: f.pathname,
723
+ port: f.port,
724
+ protocol: f.protocol,
725
+ rejectUnauthorized: !1,
726
+ method: t.method,
727
+ headers: t.headers,
728
+ host: f.hostname,
729
+ },
730
+ v = "https:" === f.protocol ? (0, r.request)(m) : (0, o.request)(m);
731
+ v.end(),
732
+ v.on("error", t => {
733
+ e.log(
734
+ "websocket request has errored " + (t.errno ? `(${t.errno})` : ""),
735
+ p.WARNING,
736
+ u.WEBSOCKET,
737
+ );
738
+ }),
739
+ v.on("upgrade", (t, o) => {
740
+ const r = `HTTP/${t.httpVersion} ${t.statusCode} ${
741
+ t.statusMessage
742
+ }\r\n${Object.entries(t.headers)
743
+ .flatMap(([e, t]) => (Array.isArray(t) ? t : [t]).map(t => [e, t]))
744
+ .map(([e, t]) => `${e}: ${t}\r\n`)
745
+ .join("")}\r\n`;
746
+ n.write(r),
747
+ (n.allowHalfOpen = !0),
748
+ (o.allowHalfOpen = !0),
749
+ o.on("data", e => n.write(e)),
750
+ n.on("data", e => o.write(e)),
751
+ o.on("error", t => {
752
+ e.log(
753
+ "downstream socket has errored " + (t.errno ? `(${t.errno})` : ""),
754
+ p.WARNING,
755
+ u.WEBSOCKET,
756
+ );
757
+ }),
758
+ n.on("error", t => {
759
+ e.log(
760
+ "upstream socket has errored " + (t.errno ? `(${t.errno})` : ""),
761
+ p.WARNING,
762
+ u.WEBSOCKET,
763
+ );
764
+ });
765
+ });
766
+ };
767
+ exports.websocketServe = P;
768
+ const q = function (e, i, a) {
769
+ var l, h, v, y, b;
770
+ return t(this, void 0, void 0, function* () {
771
+ if (!i.headers.host && !i.headers[":authority"])
772
+ return void U(
773
+ 400,
774
+ a,
775
+ Buffer.from(
776
+ I(
777
+ new Error("client must supply a 'host' header"),
778
+ "proxy",
779
+ new s.URL(`http${e.config.ssl ? "s" : ""}://unknowndomain${i.url}`),
780
+ ),
781
+ ),
782
+ );
783
+ const {
784
+ proxyHostname: t,
785
+ proxyHostnameAndPort: R,
786
+ url: w,
787
+ path: O,
788
+ key: $,
789
+ target: E,
790
+ } = H(i, e.config);
791
+ if (!E)
792
+ return void U(
793
+ 502,
794
+ a,
795
+ Buffer.from(
796
+ I(new Error(`No mapping found in config file ${f}`), "proxy", w),
797
+ ),
798
+ );
799
+ const x = E.host.replace(RegExp(/\/+$/), ""),
800
+ L = `${E.href.substring(8 + E.host.length)}${S(
801
+ O.replace(RegExp(S($)), ""),
802
+ )}`.replace(/^\/*/, "/"),
803
+ P = new s.URL(`${E.protocol}//${x}${L}`);
804
+ let q = !e.config.dontUseHttp2Downstream;
805
+ const A = (0, c.randomBytes)(20).toString("hex");
806
+ e.notifyLogsListeners({
807
+ level: "info",
808
+ protocol: q ? "HTTP/2" : "HTTP1.1",
809
+ method: i.method,
810
+ upstreamPath: O,
811
+ downstreamPath: P.href,
812
+ randomId: A,
813
+ uniqueHash: "N/A",
814
+ });
815
+ const D = d.hrtime.bigint();
816
+ let W = null;
817
+ const M =
818
+ "file:" === E.protocol
819
+ ? k(P)
820
+ : "logs:" === E.protocol
821
+ ? ((e, t) =>
822
+ j(
823
+ `${B(
824
+ 128250,
825
+ "logs",
826
+ "",
827
+ )}\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">\nLimit : <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">\nfunction start() {\ndocument.getElementById('table-access').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\nconst socket = new WebSocket("ws${
828
+ t ? "s" : ""
829
+ }://${e}/local-traffic-logs");\nsocket.onmessage = function(event) {\nlet data = event.data\nlet uniqueHash;\ntry {\nconst { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\ndata = data1;\nuniqueHash = uniqueHash1;\n} catch(e) { }\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst 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>' : '';\nif(data.statusCode && uniqueHash) {\nconst color = Math.floor(data.statusCode / 100) === 1 ? "info" :\nMath.floor(data.statusCode / 100) === 2 ? "success" :\nMath.floor(data.statusCode / 100) === 3 ? "dark" :\nMath.floor(data.statusCode / 100) === 4 ? "warning" :\nMath.floor(data.statusCode / 100) === 5 ? "danger" :\n"secondary";\nconst statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\nif (statusCodeColumn)\nstatusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\nconst durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\nif (durationColumn) {\nconst duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\ndata.duration + 'ms';\ndurationColumn.innerHTML = duration;\n}\n\nconst protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\nif (protocolColumn) {\nprotocolColumn.innerHTML = data.protocol;\n}\n\nconst replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\nif (replayColumn) {\nreplayColumn.innerHTML = replay;\n}\n} else if (uniqueHash) {\ndocument.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) {\ndocument.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}\ncleanup();\n};\nsocket.onerror = function(error) {\nconsole.log(\`[error] \${error}\`);\nsetTimeout(start, 5000);\n};\n};\nfunction show(id) {\n[...document.querySelectorAll('table')].forEach((table, index) => {\ntable.style.display = index === id ? 'block': 'none'\n});\n[...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\nif (index === id) { link.classList.add('active') } else link.classList.remove('active');\n});\n}\nfunction cleanup() {\nconst currentLimit = parseInt(document.getElementById('limit').value)\nfor (let table of ['access', 'proxy']) {\nwhile (currentLimit && document.getElementById(table).childNodes.length && \ndocument.getElementById(table).childNodes.length > currentLimit) {\n[...document.getElementById(table).childNodes].slice(-1)[0].remove();\n}\n}\n}\nfunction replay(event) {\nconst uniqueHash = event.target.dataset.uniquehash;\nconst { method, url, headers, body } = JSON.parse(atob(uniqueHash));\nfetch(url, {\nmethod,\nheaders,\nbody: !body.data || !body.data.length \n? undefined\n: new TextDecoder().decode(new Int8Array(body.data))\n});\n}\nwindow.addEventListener("DOMContentLoaded", start);\n<\/script>\n</body></html>`,
830
+ ))(R, !!e.config.ssl)
831
+ : "config:" === E.protocol
832
+ ? ((e, t) =>
833
+ j(
834
+ `${B(
835
+ 127899,
836
+ "config",
837
+ "",
838
+ )}\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\nconst container = document.getElementById("jsoneditor")\nconst options = {mode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\n${Object.entries(
839
+ Object.assign(Object.assign({}, m), {
840
+ ssl: { cert: "", key: "" },
841
+ }),
842
+ )
843
+ .map(
844
+ ([e, t]) =>
845
+ `${e}: {type: "${
846
+ "number" == typeof t
847
+ ? "integer"
848
+ : "string" == typeof t
849
+ ? "string"
850
+ : "boolean" == typeof t
851
+ ? "boolean"
852
+ : "object"
853
+ }"}`,
854
+ )
855
+ .join(
856
+ ",\n",
857
+ )}\n},\nrequired: [],\nadditionalProperties: false\n}}\n\nfunction save() {\nsocket.send(JSON.stringify(editor.get()));\n}\n\nfunction generateSslCertificate() {\nconst sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\nsslModal.show()\nsetTimeout(function() {\nconst keypair = forge.pki.rsa.generateKeyPair(2048);\nconst certificate = forge.pki.createCertificate();\nconst now = new Date();\nconst fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\nObject.assign(certificate, {\npublicKey: keypair.publicKey,\nserialNumber: "01",\nvalidity: {\nnotBefore: now,\nnotAfter: fiveYears,\n},\n});\ncertificate.sign(keypair.privateKey, forge.md.sha256.create());\nconst key = forge.pki.privateKeyToPem(keypair.privateKey);\nconst cert = forge.pki.certificateToPem(certificate);\nconst existingConfig = editor.get();\neditor.set({ ...existingConfig, ssl: { key, cert },\nport: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n});\nsslModal.hide();\n}, 100);\n}\n\nconst editor = new JSONEditor(container, options);\nlet socket;\nconst initialJson = ${JSON.stringify(
858
+ t,
859
+ )}\neditor.set(initialJson)\neditor.validate();\neditor.aceEditor.commands.addCommand({\nname: 'save',\nbindKey: {win: 'Ctrl-S', mac: 'Command-S'},\nexec: save,\n});\n\nwindow.addEventListener("DOMContentLoaded", function() {\ndocument.getElementById('jsoneditor').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\ndocument.getElementById('jsoneditor').style.width =\nparseInt(window.getComputedStyle(\ndocument.querySelector('.container')).maxWidth) + 'px';\nconst sslButton = document.createElement('button');\nsslButton.addEventListener("click", generateSslCertificate);\nsslButton.type="button";\nsslButton.classList.add("btn");\nsslButton.classList.add("btn-primary");\nsslButton.innerHTML="&#x1F512;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(sslButton);\nconst saveButton = document.createElement('button');\nsaveButton.addEventListener("click", save);\nsaveButton.type="button";\nsaveButton.classList.add("btn");\nsaveButton.classList.add("btn-primary");\nsaveButton.innerHTML="&#x1F4BE;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${
860
+ t.ssl ? "s" : ""
861
+ }://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`,
862
+ ))(R, e.config)
863
+ : q
864
+ ? yield Promise.race([
865
+ new Promise(e => {
866
+ const t = (0, n.connect)(
867
+ P,
868
+ { rejectUnauthorized: !1, protocol: E.protocol },
869
+ (n, o) => {
870
+ (q = q && !!o.alpnProtocol), e(q ? t : null);
871
+ },
872
+ );
873
+ t.on("error", e => {
874
+ W = q && Buffer.from(I(e, "connection", w, P));
875
+ });
876
+ }),
877
+ new Promise(e =>
878
+ setTimeout(() => {
879
+ (q = !1), e(null);
880
+ }, 3e3),
881
+ ),
882
+ ])
883
+ : null;
884
+ W instanceof Buffer || (W = null);
885
+ const F = null == i ? void 0 : i.readableLength,
886
+ _ =
887
+ null === (l = null == i ? void 0 : i.stream) || void 0 === l
888
+ ? void 0
889
+ : l.readableLength;
890
+ let J = null;
891
+ const K = e.config.replaceRequestBodyUrls || e.logsListeners.length,
892
+ z = !(
893
+ ((e.config.ssl && 0 === _) || (!e.config.ssl && 0 === F)) &&
894
+ ("0" === i.headers["content-length"] ||
895
+ void 0 === i.headers["content-length"])
896
+ );
897
+ if (K) {
898
+ const n =
899
+ null !== (h = null == i ? void 0 : i.stream) && void 0 !== h ? h : i;
900
+ let o = Buffer.from([]);
901
+ yield Promise.race([
902
+ new Promise(e => setTimeout(e, 1e4)),
903
+ new Promise(e => {
904
+ z
905
+ ? (n.on("data", e => {
906
+ o = Buffer.concat([o, e]);
907
+ }),
908
+ n.on("end", e),
909
+ n.on("error", e))
910
+ : e(void 0);
911
+ }),
912
+ ]),
913
+ z &&
914
+ !o.length &&
915
+ e.log(`body replacement error ${O.slice(-17)}`, p.WARNING, u.ERROR_4),
916
+ (J = e.config.replaceRequestBodyUrls
917
+ ? yield T(o, i.headers, {
918
+ proxyHostnameAndPort: R,
919
+ proxyHostname: t,
920
+ key: $,
921
+ mapping: e.config.mapping,
922
+ port: e.config.port,
923
+ ssl: !!e.config.ssl,
924
+ direction: g.OUTBOUND,
925
+ })
926
+ : o);
927
+ }
928
+ const G = Object.assign(
929
+ Object.assign(
930
+ {},
931
+ [...Object.entries(i.headers)]
932
+ .filter(
933
+ ([e]) =>
934
+ !["host", "connection", "keep-alive"].includes(e.toLowerCase()),
935
+ )
936
+ .reduce(
937
+ (e, [t, n]) => (
938
+ (e[t] =
939
+ (e[t] || "") +
940
+ (Array.isArray(n) ? n : [n])
941
+ .map(e => e.replace(w.hostname, x))
942
+ .join(", ")),
943
+ e
944
+ ),
945
+ {},
946
+ ),
947
+ ),
948
+ {
949
+ origin: E.href,
950
+ referer: P.toString(),
951
+ "content-length":
952
+ null !==
953
+ (y =
954
+ null !== (v = null == J ? void 0 : J.length) && void 0 !== v
955
+ ? v
956
+ : i.headers["content-length"]) && void 0 !== y
957
+ ? y
958
+ : 0,
959
+ ":authority": x,
960
+ ":method": i.method,
961
+ ":path": L,
962
+ ":scheme": E.protocol.replace(":", ""),
963
+ },
964
+ ),
965
+ Y =
966
+ M &&
967
+ !W &&
968
+ M.request(G, { endStream: e.config.ssl ? !(null == _ || _) : !F });
969
+ null == Y ||
970
+ Y.on("error", e => {
971
+ const t = -505 === e.errno;
972
+ W = Buffer.from(
973
+ I(
974
+ e,
975
+ "stream" +
976
+ (t
977
+ ? " (error -505 usually means that the downstream service does not support this http version)"
978
+ : ""),
979
+ w,
980
+ P,
981
+ ),
982
+ );
983
+ });
984
+ const Z = {
985
+ hostname: E.hostname,
986
+ path: L,
987
+ port: E.port,
988
+ protocol: E.protocol,
989
+ rejectUnauthorized: !1,
990
+ method: i.method,
991
+ headers: Object.assign(
992
+ Object.assign(
993
+ {},
994
+ Object.assign(
995
+ {},
996
+ ...Object.entries(G)
997
+ .filter(
998
+ ([e]) =>
999
+ !e.startsWith(":") &&
1000
+ "transfer-encoding" !== e.toLowerCase(),
1001
+ )
1002
+ .map(([e, t]) => ({ [e]: t })),
1003
+ ),
1004
+ ),
1005
+ { host: E.hostname },
1006
+ ),
1007
+ },
1008
+ V =
1009
+ !W &&
1010
+ !q &&
1011
+ !["file:", "logs:", "config:"].includes(E.protocol) &&
1012
+ (yield new Promise(e => {
1013
+ const t =
1014
+ "https:" === E.protocol
1015
+ ? (0, r.request)(Z, e)
1016
+ : (0, o.request)(Z, e);
1017
+ t.on("error", t => {
1018
+ (W = Buffer.from(I(t, "request", w, P))), e(null);
1019
+ }),
1020
+ K && (t.write(J), t.end()),
1021
+ K || (i.on("data", e => t.write(e)), i.on("end", () => t.end()));
1022
+ }));
1023
+ if (W) return void U(502, a, W);
1024
+ (W = null),
1025
+ _ && Y && !K
1026
+ ? (i.stream.on("data", e => {
1027
+ Y.write(e);
1028
+ }),
1029
+ i.stream.on("end", () => Y.end()))
1030
+ : F && Y && !K
1031
+ ? (i.on("data", e => {
1032
+ Y.write(e);
1033
+ }),
1034
+ i.on("end", () => Y.end()))
1035
+ : Y && K && z && (Y.write(J), Y.end());
1036
+ const { outboundResponseHeaders: Q } = yield new Promise(e =>
1037
+ Y
1038
+ ? Y.on("response", t => {
1039
+ e({ outboundResponseHeaders: t });
1040
+ })
1041
+ : e(
1042
+ !Y && V
1043
+ ? { outboundResponseHeaders: V.headers }
1044
+ : { outboundResponseHeaders: {} },
1045
+ ),
1046
+ );
1047
+ let X = null;
1048
+ try {
1049
+ Q.location &&
1050
+ (X = new s.URL(
1051
+ Q.location.startsWith("/")
1052
+ ? `${E.href}${Q.location.replace(/^\/+/, "")}`
1053
+ : Q.location
1054
+ .replace(/^file:\/+/, "file:///")
1055
+ .replace(/^(http)(s?):\/+/, "$1$2://"),
1056
+ ));
1057
+ } catch (t) {
1058
+ e.log(
1059
+ `location replacement error ${(null !== (b = Q.location) && void 0 !== b
1060
+ ? b
1061
+ : ""
1062
+ ).slice(-13)}`,
1063
+ p.WARNING,
1064
+ u.ERROR_4,
1065
+ );
1066
+ }
1067
+ const ee =
1068
+ e.config.replaceResponseBodyUrls && X
1069
+ ? new s.URL(
1070
+ C(X.href, {
1071
+ direction: g.INBOUND,
1072
+ proxyHostnameAndPort: R,
1073
+ ssl: !!e.config.ssl,
1074
+ mapping: e.config.mapping,
1075
+ }).replace(/^(config:|logs:|file:)\/+/, ""),
1076
+ )
1077
+ : X,
1078
+ te = X
1079
+ ? ee.origin !== X.origin || e.config.dontTranslateLocationHeader
1080
+ ? ee
1081
+ : `${w.origin}${ee.href.substring(ee.origin.length)}`
1082
+ : X,
1083
+ ne = Y || V,
1084
+ oe =
1085
+ null != W
1086
+ ? W
1087
+ : yield new Promise(e => {
1088
+ let t = Buffer.alloc(0);
1089
+ ne
1090
+ ? (ne.on(
1091
+ "data",
1092
+ e =>
1093
+ (t = Buffer.concat([
1094
+ t,
1095
+ "string" == typeof e ? Buffer.from(e) : e,
1096
+ ])),
1097
+ ),
1098
+ ne.on("end", () => {
1099
+ e(t);
1100
+ }))
1101
+ : e(t);
1102
+ }).then(n =>
1103
+ e.config.replaceResponseBodyUrls && n.length
1104
+ ? "config:" === E.protocol
1105
+ ? n
1106
+ : T(n, Q, {
1107
+ proxyHostnameAndPort: R,
1108
+ proxyHostname: t,
1109
+ key: $,
1110
+ direction: g.INBOUND,
1111
+ mapping: e.config.mapping,
1112
+ port: e.config.port,
1113
+ ssl: !!e.config.ssl,
1114
+ }).catch(
1115
+ e => (
1116
+ U(502, a, Buffer.from(I(e, "stream", w, P))),
1117
+ Buffer.from("")
1118
+ ),
1119
+ )
1120
+ : n,
1121
+ ),
1122
+ re = Object.assign(
1123
+ Object.assign(
1124
+ {},
1125
+ Object.entries(
1126
+ Object.assign(
1127
+ Object.assign(
1128
+ Object.assign({}, Q),
1129
+ e.config.replaceResponseBodyUrls
1130
+ ? { "content-length": `${oe.byteLength}` }
1131
+ : {},
1132
+ ),
1133
+ e.config.disableWebSecurity
1134
+ ? {
1135
+ "content-security-policy": "report only",
1136
+ "access-control-allow-headers": "*",
1137
+ "access-control-allow-method": "*",
1138
+ "access-control-allow-origin": "*",
1139
+ }
1140
+ : {},
1141
+ ),
1142
+ )
1143
+ .filter(
1144
+ ([e]) =>
1145
+ !e.startsWith(":") &&
1146
+ "transfer-encoding" !== e.toLowerCase() &&
1147
+ "connection" !== e.toLowerCase() &&
1148
+ "keep-alive" !== e.toLowerCase(),
1149
+ )
1150
+ .reduce((e, [t, n]) => {
1151
+ const o = x
1152
+ .split("")
1153
+ .map(
1154
+ (e, t) => x.substring(t).startsWith(".") && x.substring(t),
1155
+ )
1156
+ .filter(e => e),
1157
+ r = [x]
1158
+ .concat(o)
1159
+ .reduce(
1160
+ (e, t) =>
1161
+ (Array.isArray(e) ? e : [e]).map(e =>
1162
+ "string" == typeof e
1163
+ ? e.replace(`Domain=${t}`, `Domain=${w.hostname}`)
1164
+ : e,
1165
+ ),
1166
+ n,
1167
+ );
1168
+ return (e[t] = (e[t] || []).concat(r)), e;
1169
+ }, {}),
1170
+ ),
1171
+ te ? { location: [te] } : {},
1172
+ );
1173
+ try {
1174
+ Object.entries(re).forEach(([e, t]) => t && a.setHeader(e, t));
1175
+ } catch (e) {}
1176
+ const se = Q[":status"] || V.statusCode || 200;
1177
+ a.writeHead(
1178
+ se,
1179
+ e.config.ssl ? void 0 : V.statusMessage || "Status read from http/2",
1180
+ re,
1181
+ ),
1182
+ oe ? a.end(oe) : a.end();
1183
+ const ie = d.hrtime.bigint();
1184
+ e.notifyLogsListeners({
1185
+ randomId: A,
1186
+ statusCode: se,
1187
+ protocol: q ? "HTTP/2" : "HTTP1.1",
1188
+ duration: Math.floor(Number(ie - D) / 1e6),
1189
+ uniqueHash: Buffer.from(
1190
+ JSON.stringify({
1191
+ method: i.method,
1192
+ url: i.url,
1193
+ headers: Object.assign(
1194
+ {},
1195
+ ...Object.entries(i.headers)
1196
+ .filter(([e]) => !e.startsWith(":"))
1197
+ .map(([e, t]) => ({ [e]: t })),
1198
+ ),
1199
+ body: null == J ? void 0 : J.toJSON(),
1200
+ }),
1201
+ ).toString("base64"),
1202
+ });
1203
+ });
1204
+ };
1205
+ exports.serve = q;
1206
+ const A = (e, t) => {
1207
+ "EACCES" === t.code &&
1208
+ e.log("permission denied for this port", p.ERROR, u.NO),
1209
+ "EADDRINUSE" === t.code &&
1210
+ e.log("port is already used. NOT started", p.ERROR, u.ERROR_6);
1211
+ };
1212
+ exports.errorListener = A;
1213
+ const D = e => W({ config: Object.assign(Object.assign({}, m), e) }, {});
1214
+ exports.start = D;
1215
+ const W = (e, r) =>
1216
+ t(void 0, void 0, void 0, function* () {
1217
+ var s, a, l, c, d, g, h, m;
1218
+ if (0 === Object.keys(null != r ? r : {}).length && e.server) return;
1219
+ if (r.pendingConfigSave)
1220
+ return void (0, i.writeFile)(
1221
+ f,
1222
+ JSON.stringify(r.pendingConfigSave, null, 2),
1223
+ t => {
1224
+ var n, o;
1225
+ t
1226
+ ? null === (n = e.log) ||
1227
+ void 0 === n ||
1228
+ n.call(e, "config file NOT saved", p.ERROR, u.ERROR_4)
1229
+ : null === (o = e.log) ||
1230
+ void 0 === o ||
1231
+ o.call(e, "config file saved... will reload", p.INFO, u.COLORED);
1232
+ },
1233
+ );
1234
+ if (
1235
+ (null === r.configListeners &&
1236
+ (yield Promise.all(
1237
+ e.configListeners.map(e => new Promise(t => e.stream.end(t))),
1238
+ )),
1239
+ null === r.logsListeners &&
1240
+ (yield Promise.all(
1241
+ e.logsListeners.map(e => new Promise(t => e.stream.end(t))),
1242
+ )),
1243
+ null === r.server)
1244
+ ) {
1245
+ (yield Promise.race([
1246
+ new Promise(t => e.server.close(t)).then(() => !0),
1247
+ new Promise(e => setTimeout(e, 5e3)).then(() => !1),
1248
+ ])) || e.log("error during restart (websockets ?)", p.WARNING, u.RESTART);
1249
+ }
1250
+ (null !== (s = e.configListeners) && void 0 !== s ? s : [])
1251
+ .concat(null !== (a = e.logsListeners) && void 0 !== a ? a : [])
1252
+ .filter(e => e.stream.errored || e.stream.closed)
1253
+ .forEach(e => e.stream.destroy());
1254
+ const v = null !== (l = r.config) && void 0 !== l ? l : e.config,
1255
+ b = (
1256
+ null === r.configListeners
1257
+ ? []
1258
+ : null !==
1259
+ (d =
1260
+ null !== (c = r.configListeners) && void 0 !== c
1261
+ ? c
1262
+ : e.configListeners) && void 0 !== d
1263
+ ? d
1264
+ : []
1265
+ ).filter(e => !e.stream.errored && !e.stream.closed),
1266
+ R = (
1267
+ null === r.logsListeners
1268
+ ? []
1269
+ : null !==
1270
+ (h =
1271
+ null !== (g = r.logsListeners) && void 0 !== g
1272
+ ? g
1273
+ : e.logsListeners) && void 0 !== h
1274
+ ? h
1275
+ : []
1276
+ ).filter(e => !e.stream.errored && !e.stream.closed),
1277
+ w = e;
1278
+ return (
1279
+ Object.assign(w, {
1280
+ config: v,
1281
+ logsListeners: R,
1282
+ configListeners: b,
1283
+ configFileWatcher:
1284
+ null !== (m = w.configFileWatcher) && void 0 !== m
1285
+ ? m
1286
+ : (0, i.watchFile)(f, () =>
1287
+ t(void 0, void 0, void 0, function* () {
1288
+ return W(
1289
+ w,
1290
+ yield (function (e) {
1291
+ return t(this, void 0, void 0, function* () {
1292
+ const t = e.config,
1293
+ n = yield L(!1);
1294
+ return isNaN(n.port) || n.port > 65535 || n.port < 0
1295
+ ? (e.log(
1296
+ "port number invalid. Not refreshing",
1297
+ p.ERROR,
1298
+ u.PORT,
1299
+ ),
1300
+ {})
1301
+ : "object" != typeof n.mapping
1302
+ ? (e.log(
1303
+ "mapping should be an object. Aborting",
1304
+ p.ERROR,
1305
+ u.ERROR_5,
1306
+ ),
1307
+ {})
1308
+ : (n.replaceRequestBodyUrls !==
1309
+ t.replaceRequestBodyUrls &&
1310
+ e.log(
1311
+ `request body url ${
1312
+ n.replaceRequestBodyUrls ? "" : "NO "
1313
+ }rewriting`,
1314
+ p.INFO,
1315
+ u.REWRITE,
1316
+ ),
1317
+ n.replaceResponseBodyUrls !==
1318
+ t.replaceResponseBodyUrls &&
1319
+ e.log(
1320
+ `response body url ${
1321
+ n.replaceResponseBodyUrls ? "" : "NO "
1322
+ }rewriting`,
1323
+ p.INFO,
1324
+ u.REWRITE,
1325
+ ),
1326
+ n.dontTranslateLocationHeader !==
1327
+ t.dontTranslateLocationHeader &&
1328
+ e.log(
1329
+ `response location header ${
1330
+ n.dontTranslateLocationHeader ? "NO " : ""
1331
+ }translation`,
1332
+ p.INFO,
1333
+ u.REWRITE,
1334
+ ),
1335
+ n.dontUseHttp2Downstream !==
1336
+ t.dontUseHttp2Downstream &&
1337
+ e.log(
1338
+ `http/2 ${
1339
+ n.dontUseHttp2Downstream ? "de" : ""
1340
+ }activated downstream`,
1341
+ p.INFO,
1342
+ u.OUTBOUND,
1343
+ ),
1344
+ n.disableWebSecurity !== t.disableWebSecurity &&
1345
+ e.log(
1346
+ `web security ${
1347
+ n.disableWebSecurity ? "de" : ""
1348
+ }activated`,
1349
+ p.INFO,
1350
+ u.SHIELD,
1351
+ ),
1352
+ n.websocket !== t.websocket &&
1353
+ e.log(
1354
+ `websocket ${n.websocket ? "" : "de"}activated`,
1355
+ p.INFO,
1356
+ u.WEBSOCKET,
1357
+ ),
1358
+ n.simpleLogs !== t.simpleLogs &&
1359
+ e.log(
1360
+ "simple logs " + (n.simpleLogs ? "on" : "off"),
1361
+ p.INFO,
1362
+ u.COLORED,
1363
+ ),
1364
+ Object.keys(n.mapping).join("\n") !==
1365
+ Object.keys(t.mapping).join("\n") &&
1366
+ e.log(
1367
+ `${Object.keys(n.mapping)
1368
+ .length.toString()
1369
+ .padStart(5)} loaded mapping rules`,
1370
+ p.INFO,
1371
+ u.RULES,
1372
+ ),
1373
+ n.port !== t.port &&
1374
+ e.log(
1375
+ `port changed from ${t.port} to ${n.port}`,
1376
+ p.INFO,
1377
+ u.PORT,
1378
+ ),
1379
+ n.ssl &&
1380
+ !t.ssl &&
1381
+ e.log(
1382
+ "ssl configuration added",
1383
+ p.INFO,
1384
+ u.INBOUND,
1385
+ ),
1386
+ !n.ssl &&
1387
+ t.ssl &&
1388
+ e.log(
1389
+ "ssl configuration removed",
1390
+ p.INFO,
1391
+ u.INBOUND,
1392
+ ),
1393
+ n.port !== t.port ||
1394
+ JSON.stringify(n.ssl) !== JSON.stringify(t.ssl)
1395
+ ? (e.log("restarting server", p.INFO, u.RESTART),
1396
+ x.apply(
1397
+ Object.assign(Object.assign({}, e), {
1398
+ config: n,
1399
+ }),
1400
+ ),
1401
+ { config: n, server: null })
1402
+ : (x.apply(
1403
+ Object.assign(Object.assign({}, e), {
1404
+ config: n,
1405
+ }),
1406
+ ),
1407
+ { config: n }));
1408
+ });
1409
+ })(w),
1410
+ );
1411
+ }),
1412
+ ),
1413
+ log: y.bind(w, w),
1414
+ notifyConfigListeners: O.bind(w),
1415
+ notifyLogsListeners: $.bind(w),
1416
+ quickStatus: x.bind(w),
1417
+ server:
1418
+ null !== r.server && w.server
1419
+ ? w.server
1420
+ : (v.ssl
1421
+ ? n.createSecureServer.bind(
1422
+ null,
1423
+ Object.assign(Object.assign({}, v.ssl), { allowHTTP1: !0 }),
1424
+ )
1425
+ : o.createServer)((e, t) => q(w, e, t))
1426
+ .addListener("error", e => A(w, e))
1427
+ .addListener("listening", () => w.quickStatus())
1428
+ .on("upgrade", (e, t) => W(w, P(w, e, t)))
1429
+ .listen(v.port),
1430
+ }),
1431
+ w
1432
+ );
1433
+ });
1434
+ exports.update = W;
1435
+ const M =
1436
+ null !==
1437
+ (e = d.argv.filter(
1438
+ e =>
1439
+ !["ts-node", "node", "npx", "npm", "exec"].some(
1440
+ t => e.includes(t) && !e.match(/npm-cache/) && !e.match(/_npx/),
1441
+ ),
1442
+ )[0]) && void 0 !== e
1443
+ ? e
1444
+ : "";
1445
+ M.toLowerCase().replace(/[-_]/g, "").includes("localtraffic") &&
1446
+ !M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/) &&
1447
+ L().then(D);