local-traffic 0.0.76 → 0.0.78
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.
- package/dist/local-traffic.js +1 -1
- package/package.json +2 -2
package/dist/local-traffic.js
CHANGED
|
@@ -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 h=(0,l.resolve)(d.env.HOME,".local-traffic.json"),f=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:h),m={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},v=()=>{var e,t;return null!==(t=null===(e=d.hrtime.bigint)||void 0===e?void 0:e.call(d.hrtime))&&void 0!==t?t:(()=>{const e=(0,d.hrtime)();return 1e3*e[0]+e[1]/1e6})()},y=e=>e===p.ERROR?"error":e===p.WARNING?"warning":"info",b=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?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(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)} ⎹[0m`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:y(n)})},R=(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=R;const O=(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=O;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 $=function(e){return x(this,e,this.configListeners)},E=function(e){return x(this,e,this.logsListeners)},x=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&R(o,!1),i=r.has(!0)&&R(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(`[48;5;52m⎸${u.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${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:" "}⎹[48;5;54m[48;5;55m⎸${u.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹[48;5;56m⎸${this.config.websocket?u.WEBSOCKET:u.NO}⎹[48;5;57m⎸${this.config.simpleLogs?u.NO:u.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?u.NO:u.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=L;const S=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(f,((n,o)=>{n&&!e&&b(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 b({config:r},"config syntax incorrect, aborting",p.ERROR,u.ERROR_2),r=null!=r?r:Object.assign({},m),void t(r)}r.mapping[""]||b({config:r},'default mapping "" not provided.',p.WARNING,u.ERROR_3),n&&"ENOENT"===n.code&&e&&f===h?(0,i.writeFile)(f,JSON.stringify(m,null,2),(e=>{e?b(null,"config file NOT created",p.ERROR,u.ERROR_4):b(null,"config file created",p.INFO,u.COLORED),t(r)})):t(r)}))))}));exports.load=S;const N=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),B="https://cdn.jsdelivr.net/npm/",j=(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="${B}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${B}jquery/dist/jquery.min.js"><\/script>\n<script src="${B}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=`${j(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></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}}},C=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}}),T=(e,t,n,o)=>`${j(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ⓘ 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||"<no-target-url>"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,I=(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()))?U(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})).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(",").reverse().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=I;const U=(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=U;const H=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=H;const P=(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(N("string"==typeof t?t:t.downstreamUrl))}))))),[g,h]=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:h}};exports.determineMapping=P;const q=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:h}=P(t,e.config);if("/local-traffic-logs"===h)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"===h){w(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=O(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)}M(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 f=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:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},v="https:"===f.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=q;const A=function(e,i,a){var l,d,h,y,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void H(400,a,Buffer.from(T(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:O,path:w,key:$,target:E}=P(i,e.config);if(!E)return void H(502,a,Buffer.from(T(new Error(`No mapping found in config file ${f}`),"proxy",O)));const x=E.host.replace(RegExp(/\/+$/),""),L=`${E.href.substring(8+E.host.length)}${N(w.replace(RegExp(N($)),""))}`.replace(/^\/*/,"/"),S=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:w,downstreamPath:S.href,randomId:A,uniqueHash:"N/A"});const D=v();let W=null;const M="file:"===E.protocol?k(S):"logs:"===E.protocol?((e,t)=>C(`${j(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">\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${t?"s":""}://${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"' : '') + '>🔁</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">⏱</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>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>C(`${j(127899,"config","")}\n<link href="${B}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${B}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${B}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(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},\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(t)}\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="🔒";\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="💾";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`))(R,e.config):q?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(S,{rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{q=q&&!!o.alpnProtocol,e(q?t:null)}));t.on("error",(e=>{W=q&&Buffer.from(T(e,"connection",O,S))}))})),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,z=!((e.config.ssl&&0===_||!e.config.ssl&&0===F)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));if(K){const n=null!==(d=null==i?void 0:i.stream)&&void 0!==d?d:i;let o=Buffer.from([]);yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{z?(n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)):e(void 0)}))]),z&&!o.length&&e.log(`body replacement error ${w.slice(-17)}`,p.WARNING,u.ERROR_4),J=e.config.replaceRequestBodyUrls?yield I(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:g.OUTBOUND}):o}const G=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(O.hostname,x))).join(", "),e)),{})),{origin:E.href,referer:S.toString(),"content-length":null!==(y=null!==(h=null==J?void 0:J.length)&&void 0!==h?h:i.headers["content-length"])&&void 0!==y?y:0,":authority":x,":method":i.method,":path":L,":scheme":E.protocol.replace(":","")}),Y=M&&!W&&M.request(G,{endStream:e.config.ssl?!(null==_||_):!F});null==Y||Y.on("error",(e=>{const t=-505===e.errno;W=Buffer.from(T(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),O,S))}));const Z={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(G).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},V=!W&&!q&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(Z,e):(0,o.request)(Z,e);t.on("error",(t=>{W=Buffer.from(T(t,"request",O,S)),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 H(502,a,W);W=null,_&&Y&&!K?(i.stream.on("data",(e=>{Y.write(e)})),i.stream.on("end",(()=>Y.end()))):F&&Y&&!K?(i.on("data",(e=>{Y.write(e)})),i.on("end",(()=>Y.end()))):Y&&K&&z&&(Y.write(J),Y.end());const{outboundResponseHeaders:Q}=yield new Promise((e=>Y?Y.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!Y&&V?{outboundResponseHeaders:V.headers}:{outboundResponseHeaders:{}})));let X=null;try{Q.location&&(X=new s.URL(Q.location.startsWith("/")?`${E.href}${Q.location.replace(/^\/+/,"")}`:Q.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=Q.location)&&void 0!==b?b:"").slice(-13)}`,p.WARNING,u.ERROR_4)}const ee=e.config.replaceResponseBodyUrls&&X?new s.URL(U(X.href,{direction:g.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):X,te=X?ee.origin!==X.origin||e.config.dontTranslateLocationHeader?ee:`${O.origin}${ee.href.substring(ee.origin.length)}`:X,ne=Y||V,oe=null!=W?W:yield new Promise((e=>{let t=Buffer.alloc(0);ne?(ne.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),ne.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:I(n,Q,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((e=>(H(502,a,Buffer.from(T(e,"stream",O,S))),Buffer.from("")))):n)),re=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},Q),e.config.replaceResponseBodyUrls?{"content-length":`${oe.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=${O.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),te?{location:[te]}:{});try{Object.entries(re).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const se=Q[":status"]||V.statusCode||200;a.writeHead(se,e.config.ssl?void 0:V.statusMessage||"Status read from http/2",re),oe?a.end(oe):a.end();const ie=v();e.notifyLogsListeners({randomId:A,statusCode:se,protocol:q?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ie-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=A;const D=(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=D;const W=e=>M({config:Object.assign(Object.assign({},m),e)},{});exports.start=W;const M=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,g,h,m,v;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(f,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 y=null!==(l=r.config)&&void 0!==l?l:e.config,R=(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)),O=(null===r.logsListeners?[]:null!==(h=null!==(g=r.logsListeners)&&void 0!==g?g:e.logsListeners)&&void 0!==h?h:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:y,logsListeners:O,configListeners:R,configFileWatcher:void 0===w.configFileWatcher?(0,i.watchFile)(f,(()=>t(void 0,void 0,void 0,(function*(){return M(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield S(!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))})))):w.configFileWatcher,log:b.bind(w,w),notifyConfigListeners:$.bind(w),notifyLogsListeners:E.bind(w),quickStatus:L.bind(w),server:null!==r.server&&w.server||(null!==(v=null===(m=r.config)||void 0===m?void 0:m.port)&&void 0!==v?v:0)<0?null===r.server?null:w.server:(y.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},y.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>A(w,e,t))).addListener("error",(e=>D(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>M(w,q(w,e,t)))).listen(y.port)}),w}));exports.update=M;const F=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:"",_=F.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!F.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),J=d.argv.some((e=>"--crash-test"===e));if(J){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,o.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();M({config:Object.assign(Object.assign({},m),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):M(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):b(e,"Crash test successful",p.INFO,u.COLORED))).then((()=>(0,d.exit)(0))).catch((()=>(0,d.exit)(1)))}!J&&_&&S().then(W);
|
|
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"),p=require("os");var u,g,h;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(u||(u={})),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="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={}));const f=(0,l.resolve)((0,p.homedir)(),".local-traffic.json"),m=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:f),v={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},y=()=>{var e,t;return null!==(t=null===(e=d.hrtime.bigint)||void 0===e?void 0:e.call(d.hrtime))&&void 0!==t?t:(()=>{const e=(0,d.hrtime)();return 1e3*e[0]+e[1]/1e6})()},b=e=>e===u.ERROR?"error":e===u.WARNING?"warning":"info",R=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(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(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)} ⎹[0m`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:b(n)})},O=(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=O;const w=(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=w;const $=(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=$;const E=function(e){return L(this,e,this.configListeners)},x=function(e){return L(this,e,this.logsListeners)},L=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&O(o,!1),i=r.has(!0)&&O(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))))}))},S=function(){this.log(`[48;5;52m⎸${g.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹[48;5;56m⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹[48;5;57m⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=S;const N=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(m,((n,o)=>{n&&!e&&R(null,"config error. Using default value",u.ERROR,g.ERROR_1);let r=null;try{r=Object.assign({},v,JSON.parse((o||"{}").toString()))}catch(e){return R({config:r},"config syntax incorrect, aborting",u.ERROR,g.ERROR_2),r=null!=r?r:Object.assign({},v),void t(r)}r.mapping[""]||R({config:r},'default mapping "" not provided.',u.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&m===f?(0,i.writeFile)(m,JSON.stringify(v,null,2),(e=>{e?R(null,"config file NOT created",u.ERROR,g.ERROR_4):R(null,"config file created",u.INFO,g.COLORED),t(r)})):t(r)}))))}));exports.load=N;const B=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),j="https://cdn.jsdelivr.net/npm/",k=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],T=(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="${j}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${j}jquery/dist/jquery.min.js"><\/script>\n<script src="${j}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/>`,C=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=`${T(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></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}}},I=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}}),U=(e,t,n,o)=>`${T(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ⓘ 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||"<no-target-url>"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,H=(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()))?P(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})).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(",").reverse().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=H;const P=(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===h.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=P;const q=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=q;const A=(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(B("string"==typeof t?t:t.downstreamUrl))}))))),[g,h]=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:h}};exports.determineMapping=A;const D=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:p,path:h}=A(t,e.config);if("/local-traffic-logs"===h)return $(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"===h){$(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=w(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",u.WARNING,g.ERROR_4)}_(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 f=new s.URL(`${p.protocol}//${p.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),m={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},v="https:"===f.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})`:""),u.WARNING,g.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})`:""),u.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),u.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=D;const W=function(e,i,a){var l,d,p,f,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void q(400,a,Buffer.from(U(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:O,path:w,key:$,target:E}=A(i,e.config);if(!E)return void q(502,a,Buffer.from(U(new Error(`No mapping found in config file ${m}`),"proxy",O)));const x=E.host.replace(RegExp(/\/+$/),""),L=`${E.href.substring(8+E.host.length)}${B(w.replace(RegExp(B($)),""))}`.replace(/^\/*/,"/"),S=new s.URL(`${E.protocol}//${x}${L}`);let N=!e.config.dontUseHttp2Downstream;const D=(0,c.randomBytes)(20).toString("hex");e.notifyLogsListeners({level:"info",protocol:N?"HTTP/2":"HTTP1.1",method:i.method,upstreamPath:w,downstreamPath:S.href,randomId:D,uniqueHash:"N/A"});const W=y();let M=null;const F="file:"===E.protocol?C(S):"logs:"===E.protocol?((e,t)=>I(`${T(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">\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${t?"s":""}://${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"' : '') + '>🔁</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">⏱</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>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>I(`${T(127899,"config","")}\n<link href="${j}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${j}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${j}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(Object.assign(Object.assign({},v),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\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(t)}\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="🔒";\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="💾";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`))(R,e.config):N?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(S,{timeout:3e3,sessionTimeout:3e3,rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{N=N&&!!o.alpnProtocol,e(N?t:null)}));t.on("error",(e=>{M=N&&Buffer.from(U(e,"connection",O,S))}))})),new Promise((e=>setTimeout((()=>{N=!1,e(null)}),3e3)))]):null;M instanceof Buffer||(M=null);const _=null==i?void 0:i.readableLength,J=null===(l=null==i?void 0:i.stream)||void 0===l?void 0:l.readableLength;let K=null;const z=e.config.replaceRequestBodyUrls||e.logsListeners.length,G=!((e.config.ssl&&0===J||!e.config.ssl&&0===_)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));if(z){const n=null!==(d=null==i?void 0:i.stream)&&void 0!==d?d:i;let o=Buffer.from([]);yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{G?(n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)):e(void 0)}))]),G&&!o.length&&e.log(`body replacement error ${w.slice(-17)}`,u.WARNING,g.ERROR_4),K=e.config.replaceRequestBodyUrls?yield H(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):o}const Y=Object.assign(Object.assign({},[...Object.entries(i.headers)].filter((([e])=>!k.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(O.hostname,x))).join(", "),e)),{})),{origin:E.href,referer:S.toString(),"content-length":null!==(f=null!==(p=null==K?void 0:K.length)&&void 0!==p?p:i.headers["content-length"])&&void 0!==f?f:0,":authority":x,":method":i.method,":path":L,":scheme":E.protocol.replace(":","")}),Z=F&&!M&&F.request(Y,{endStream:e.config.ssl?!(null==J||J):!_});null==Z||Z.on("error",(e=>{const t=-505===e.errno;M=Buffer.from(U(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),O,S))}));const V={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(Y).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},Q=!M&&!N&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(V,e):(0,o.request)(V,e);t.on("error",(t=>{M=Buffer.from(U(t,"request",O,S)),e(null)})),z&&(t.write(K),t.end()),z||(i.on("data",(e=>t.write(e))),i.on("end",(()=>t.end())))})));if(M)return void q(502,a,M);M=null,J&&Z&&!z?(i.stream.on("data",(e=>{Z.write(e)})),i.stream.on("end",(()=>Z.end()))):_&&Z&&!z?(i.on("data",(e=>{Z.write(e)})),i.on("end",(()=>Z.end()))):Z&&z&&G&&(Z.write(K),Z.end());const{outboundResponseHeaders:X}=yield new Promise((e=>Z?Z.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!Z&&Q?{outboundResponseHeaders:Q.headers}:{outboundResponseHeaders:{}})));let ee=null;try{X.location&&(ee=new s.URL(X.location.startsWith("/")?`${E.origin}${X.location.replace(/^\/+/,"/")}`:X.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=X.location)&&void 0!==b?b:"").slice(-13)}`,u.WARNING,g.ERROR_4)}const te=e.config.replaceResponseBodyUrls&&ee?new s.URL(P(ee.href,{direction:h.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):ee,ne=ee?te.origin!==ee.origin||e.config.dontTranslateLocationHeader?te:`${O.origin}${te.href.substring(te.origin.length)}`:ee,oe=Z||Q,re=null!=M?M:yield new Promise((e=>{let t=Buffer.alloc(0);oe?(oe.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),oe.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:H(n,X,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((e=>(q(502,a,Buffer.from(U(e,"stream",O,S))),Buffer.from("")))):n)),se=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},X),e.config.replaceResponseBodyUrls?{"content-length":`${re.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(":")&&!k.includes(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=${O.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),ne?{location:[ne]}:{});try{Object.entries(se).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ie=X[":status"]||Q.statusCode||200;a.writeHead(ie,e.config.ssl?void 0:Q.statusMessage||"Status read from http/2",se),re?a.end(re):a.end();const ae=y();e.notifyLogsListeners({randomId:D,statusCode:ie,protocol:N?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ae-W)/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==K?void 0:K.toJSON()})).toString("base64")})}))};exports.serve=W;const M=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",u.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",u.ERROR,g.ERROR_6)};exports.errorListener=M;const F=e=>_({config:Object.assign(Object.assign({},v),e)},{});exports.start=F;const _=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,p,h,f,v;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(m,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",u.ERROR,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",u.INFO,g.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 ?)",u.WARNING,g.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 y=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)),O=(null===r.logsListeners?[]:null!==(h=null!==(p=r.logsListeners)&&void 0!==p?p:e.logsListeners)&&void 0!==h?h:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:y,logsListeners:O,configListeners:b,configFileWatcher:void 0===w.configFileWatcher?(0,i.watchFile)(m,(()=>t(void 0,void 0,void 0,(function*(){return _(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield N(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",u.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",u.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,u.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,u.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,u.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,u.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,u.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,u.INFO,g.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),u.INFO,g.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`,u.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,u.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",u.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",u.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",u.INFO,g.RESTART),S.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(S.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(w))})))):w.configFileWatcher,log:R.bind(w,w),notifyConfigListeners:E.bind(w),notifyLogsListeners:x.bind(w),quickStatus:S.bind(w),server:null!==r.server&&w.server||(null!==(v=null===(f=r.config)||void 0===f?void 0:f.port)&&void 0!==v?v:0)<0?null===r.server?null:w.server:(y.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},y.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>W(w,e,t))).addListener("error",(e=>M(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>_(w,D(w,e,t)))).listen(y.port)}),w}));exports.update=_;const J=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:"",K=J.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!J.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),z=d.argv.some((e=>"--crash-test"===e));if(z){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,o.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();_({config:Object.assign(Object.assign({},v),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):_(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):R(e,"Crash test successful",u.INFO,g.COLORED))).then((()=>(0,d.exit)(0))).catch((()=>(0,d.exit)(1)))}!z&&K&&N().then(F);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-traffic",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.78",
|
|
4
4
|
"main": "./dist/local-traffic.js",
|
|
5
5
|
"private": false,
|
|
6
6
|
"keywords": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/node": "^20.3.1",
|
|
31
|
-
"terser": "^5.18.
|
|
31
|
+
"terser": "^5.18.1",
|
|
32
32
|
"typescript": "^5.1.3"
|
|
33
33
|
},
|
|
34
34
|
"bin": {
|