local-traffic 0.0.67 → 0.0.68

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/README.md CHANGED
@@ -48,8 +48,9 @@ npx local-traffic
48
48
  4. Go to [http://localhost:8080/my-static-webapp/index.html](http://localhost:8080/my-static-webapp/index.html) with your browser (given your project name is my-static-webapp, but I am not 100% sure)
49
49
  5. Go to [http://localhost:8080/logs/](http://localhost:8080/logs/) to watch the request logs
50
50
  6. Go to [http://localhost:8080/config/](http://localhost:8080/config/) to change the config in a web editor
51
- 7. Your page will use /jquery-local/jquery.js instead of the CDN asset, and will serve the file from your hard drive
52
- 8. Your server now proxies the mapping that you have configured
51
+ 7. From the web config editor, create a SSL keypair and start working with a self signed SSL certificate right away
52
+ 8. Your page will use /jquery-local/jquery.js instead of the CDN asset, and will serve the file from your hard drive
53
+ 9. Your server now proxies the mapping that you have configured
53
54
 
54
55
  ## usage
55
56
 
@@ -70,7 +71,7 @@ npx local-traffic [location-of-the-local-traffic-config-file]
70
71
  All boolean settings default to false when unspecified.
71
72
 
72
73
  - `mapping`: (`{[path: string]: string | {replaceBody: string ; downstreamUrl: string}`) routing rules (required)
73
- - `ssl` : SSL options
74
+ - `ssl` : SSL options (can be generated from the config web editor if you don't know how to set them)
74
75
  - `ssl.cert` : (`string`) Certificate (PEM format)
75
76
  - `ssl.key` : (`string`) Private Key (PEM format)
76
77
  - `port` : (`number`) port number
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function a(e){try{l(o.next(e))}catch(e){s(e)}}function i(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const t=require("http2"),n=require("http"),o=require("https"),r=require("url"),s=require("fs"),a=require("zlib"),i=require("path"),l=require("crypto"),d=require("process");var c,p,u;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(c||(c={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(p||(p={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(u||(u={}));const h=(0,i.resolve)(process.env.HOME,".local-traffic.json"),m=(0,i.resolve)(process.cwd(),process.argv.slice(-1)[0].endsWith(".json")?process.argv.slice(-1)[0]:h),g={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let f,y,v=[],b=[];const R=e=>e===c.ERROR?"error":e===c.WARNING?"warning":"info",O=(e,t,n)=>{const o=(null==f?void 0:f.simpleLogs)||v.length?e.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(p.INBOUND,"g"),"inbound:").replace(new RegExp(p.PORT,"g"),"port:").replace(new RegExp(p.OUTBOUND,"g"),"outbound:").replace(new RegExp(p.RULES,"g"),"rules:").replace(new RegExp(p.NO,"g"),"").replace(new RegExp(p.REWRITE,"g"),"+rewrite").replace(new RegExp(p.WEBSOCKET,"g"),"websocket").replace(new RegExp(p.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):e;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null==f?void 0:f.simpleLogs)} ${(null==f?void 0:f.simpleLogs)?o:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹`:e}`),E({event:o,level:R(t)})},w=(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)]),a=Buffer.from(Int8Array.from(n).buffer),i=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,a,i]:[s,i])},$=(e,t)=>{const n=(0,l.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`)},E=e=>N(e,v),N=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&w(n,!1),s=o.has(!0)&&w(n,!0);t.forEach((e=>{e.wantsMask?e.stream.write(s,"ascii",(()=>{})):e.stream.write(r,"ascii",(()=>{}))}))},S=e=>{O(`⎸${p.PORT} ${e.port.toString().padStart(5)} ⎸${p.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?p.REWRITE:" "}⎹⎸${p.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?p.REWRITE:" "}⎹⎸${p.RULES}${Object.keys(f.mapping).length.toString().padStart(3)}⎹⎸${f.websocket?p.WEBSOCKET:p.NO}⎹⎸${f.simpleLogs?p.NO:p.COLORED}⎹⎸${f.disableWebSecurity?p.NO:p.SHIELD}⎹`),N(e,b)},B=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(m,((n,o)=>{n&&!t&&O("config error. Using default value",c.ERROR,p.ERROR_1);try{f=Object.assign({},g,JSON.parse((o||"{}").toString()))}catch(t){return O("config syntax incorrect, aborting",c.ERROR,p.ERROR_2),f=f||Object.assign({},g),void e(f)}f.mapping[""]||O('default mapping "" not provided.',c.WARNING,p.ERROR_3),n&&"ENOENT"===n.code&&t&&m===h?(0,s.writeFile)(m,JSON.stringify(g,null,2),(t=>{t?O("config file NOT created",c.ERROR,p.ERROR_4):O("config file created",c.INFO,p.COLORED),e(f)})):e(f)})))).then((()=>{t&&(0,s.watchFile)(m,I)}))})),I=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},f);if(yield B(!1),isNaN(f.port)||f.port>65535||f.port<0)return f=e,void O("port number invalid. Not refreshing",c.ERROR,p.PORT);if("object"!=typeof f.mapping)return f=e,void O("mapping should be an object. Aborting",c.ERROR,p.ERROR_5);if(f.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&O(`request body url ${f.replaceRequestBodyUrls?"":"NO "}rewriting`,c.INFO,p.REWRITE),f.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&O(`response body url ${f.replaceResponseBodyUrls?"":"NO "}rewriting`,c.INFO,p.REWRITE),f.dontTranslateLocationHeader!==e.dontTranslateLocationHeader&&O(`response location header ${f.dontTranslateLocationHeader?"NO ":""}translation`,c.INFO,p.REWRITE),f.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&O(`http/2 ${f.dontUseHttp2Downstream?"de":""}activated downstream`,c.INFO,p.OUTBOUND),f.disableWebSecurity!==e.disableWebSecurity&&O(`web security ${f.disableWebSecurity?"de":""}activated`,c.INFO,p.SHIELD),f.websocket!==e.websocket&&O(`websocket ${f.websocket?"":"de"}activated`,c.INFO,p.WEBSOCKET),f.simpleLogs!==e.simpleLogs&&O("simple logs "+(f.simpleLogs?"on":"off"),c.INFO,p.COLORED),Object.keys(f.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&O(`${Object.keys(f.mapping).length.toString().padStart(5)} loaded mapping rules`,c.INFO,p.RULES),f.port!==e.port&&O(`port changed from ${e.port} to ${f.port}`,c.INFO,p.PORT),f.ssl&&!e.ssl&&O("ssl configuration added",c.INFO,p.INBOUND),!f.ssl&&e.ssl&&O("ssl configuration removed",c.INFO,p.INBOUND),f.port!==e.port||JSON.stringify(f.ssl)!==JSON.stringify(e.ssl)){O("restarting server",c.INFO,p.RESTART),yield Promise.all(v.concat(b).map((e=>new Promise((t=>e.stream.end(t)))))),v=[],b=[];(yield Promise.race([new Promise((e=>y?y.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||O("error during restart (websockets ?)",c.WARNING,p.RESTART),A()}else S(f)})),j=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),T=e=>{const t=(0,i.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,s.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,s.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,s.lstat)((0,i.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${L(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}}},U=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}}),L=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"><\/script>\n<script src="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,x=(e,t,n,o)=>`${L(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>`,H=(t,n,o)=>e(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((t,n)=>e(void 0,void 0,void 0,(function*(){const e=n.trim().toLowerCase(),o="gzip"===e||"x-gzip"===e?a.gunzip:"deflate"===e?a.inflate:"br"===e?a.brotliDecompress:"identity"===e||""===e?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${e} compression not supported by the proxy`);const r=yield t;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(t)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\x7F]/.test(e.toString()))?f.replaceResponseBodyUrls?C(e.toString(),o.direction,o.proxyHostnameAndPort).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${f.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${f.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)))}))})),C=(e,t,n)=>Object.entries(f.mapping).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[o,r])=>r.startsWith("logs:")||r.startsWith("config:")||""!==o&&!o.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===u.INBOUND?e.replace(new RegExp(r.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${f.ssl?"s":""}://${n}${o.replace(/\/+$/,"")}/`):e.split(`http${f.ssl?"s":""}://${n}${o.replace(/\/+$/,"")}`).join(r)),e).split(`${n}/:`).join(`${n}:`),k=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)},P=e=>{var t,n,o;const s=(null!==(o=null!==(n=null===(t=e.headers[":authority"])||void 0===t?void 0:t.toString())&&void 0!==n?n:e.headers.host)&&void 0!==o?o:"localhost").replace(/:.*/,""),a=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==f.port||f.ssl?443===f.port&&f.ssl?"":`:${f.port}`:""}`,i=new r.URL(`http${f.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[d,c]=Object.entries(Object.assign({},Object.assign({},...Object.entries(f.mapping).map((([e,t])=>({[e]:new r.URL(j("string"==typeof t?t:t.downstreamUrl))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:d,target:c}},A=()=>{y=(f.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},f.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,h,y,b;if(!s.headers.host&&!s.headers[":authority"])return void k(400,a,Buffer.from(x(new Error("client must supply a 'host' header"),"proxy",new r.URL(`http${f.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:R,proxyHostnameAndPort:w,url:$,path:N,key:S,target:B}=P(s);if(!B)return void k(502,a,Buffer.from(x(new Error(`No mapping found in config file ${m}`),"proxy",$)));const I=B.host.replace(RegExp(/\/+$/),""),A=`${B.href.substring(8+B.host.length)}${j(N.replace(RegExp(j(S)),""))}`.replace(/^\/*/,"/"),q=new r.URL(`${B.protocol}//${I}${A}`);let D=!f.dontUseHttp2Downstream;const W=(0,l.randomBytes)(20).toString("hex");E({level:"info",protocol:D?"HTTP/2":"HTTP1.1",method:s.method,upstreamPath:N,downstreamPath:q.href,randomId:W,uniqueHash:"N/A"});const M=d.hrtime.bigint();let F=null;const _="file:"===B.protocol?T(q):"logs:"===B.protocol?(e=>U(`${L(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${f.ssl?"s":""}://${e}/local-traffic-logs");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary"' + \n (uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';\n if(data.statusCode && uniqueHash) {\n const color = Math.floor(data.statusCode / 100) === 1 ? "info" :\n Math.floor(data.statusCode / 100) === 2 ? "success" :\n Math.floor(data.statusCode / 100) === 3 ? "dark" :\n Math.floor(data.statusCode / 100) === 4 ? "warning" :\n Math.floor(data.statusCode / 100) === 5 ? "danger" :\n "secondary";\n const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\n if (statusCodeColumn)\n statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\n const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\n if (durationColumn) {\n const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\n data.duration + 'ms';\n durationColumn.innerHTML = duration;\n }\n\n const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\n if (protocolColumn) {\n protocolColumn.innerHTML = data.protocol;\n }\n\n const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\n if (replayColumn) {\n replayColumn.innerHTML = replay;\n }\n } else if (uniqueHash) {\n document.getElementById("access")\n .insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n '<td scope="col" class="replay">' + replay + '</td>' +\n '<td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col" class="protocol">' + data.protocol + '</td>' + \n '<td scope="col">' + data.method + '</td>' + \n '<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +\n '<td scope="col" class="duration">&#x23F1;</td>' +\n '<td scope="col">' + data.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>`))(w):"config:"===B.protocol?(e=>U(`${L(127899,"config","")}\n <link href="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.js"><\/script>\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({},g),{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 const editor = new JSONEditor(container, options);\n let socket;\n const initialJson = ${JSON.stringify(f)}\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 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${f.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>`))(w):D?yield Promise.race([new Promise((e=>{const n=(0,t.connect)(q,{rejectUnauthorized:!1,protocol:B.protocol},((t,o)=>{D=D&&!!o.alpnProtocol,e(D?n:null)}));n.on("error",(e=>{F=D&&Buffer.from(x(e,"connection",$,q))}))})),new Promise((e=>setTimeout((()=>{D=!1,e(null)}),3e3)))]):null;F instanceof Buffer||(F=null);const J=null==s?void 0:s.readableLength,z=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let G=null;const K=f.replaceRequestBodyUrls||v.length;if(K){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);const n=!((f.ssl&&0===z||!f.ssl&&0===J)&&("0"===s.headers["content-length"]||void 0===s.headers["content-length"]));yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((o=>{n||o(void 0),e.on("data",(e=>{t=Buffer.concat([t,e])})),e.on("end",o),e.on("error",o)}))]),n&&!t.length&&O(`body replacement error ${N.slice(-17)}`,c.WARNING,p.ERROR_4),G=yield H(t,s.headers,{proxyHostnameAndPort:w,proxyHostname:R,key:S,direction:u.OUTBOUND})}const Z=Object.assign(Object.assign({},[...Object.entries(s.headers)].filter((([e])=>!["host","connection","keep-alive"].includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace($.hostname,I))).join(", "),e)),{})),{origin:B.href,referer:q.toString(),"content-length":null!==(y=null!==(h=null==G?void 0:G.length)&&void 0!==h?h:s.headers["content-length"])&&void 0!==y?y:0,":authority":I,":method":s.method,":path":A,":scheme":B.protocol.replace(":","")}),V=_&&!F&&_.request(Z,{endStream:f.ssl?!(null==z||z):!J});null==V||V.on("error",(e=>{const t=-505===e.errno;F=Buffer.from(x(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),$,q))}));const Y={hostname:B.hostname,path:A,port:B.port,protocol:B.protocol,rejectUnauthorized:!1,method:s.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:B.hostname})},Q=!F&&!D&&!["file:","logs:","config:"].includes(B.protocol)&&(yield new Promise((e=>{const t="https:"===B.protocol?(0,o.request)(Y,e):(0,n.request)(Y,e);t.on("error",(t=>{F=Buffer.from(x(t,"request",$,q)),e(null)})),K&&(t.write(G),t.end()),K||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(F)return void k(502,a,F);F=null,f.ssl&&z&&V&&(K&&(V.write(G),V.end()),K||(s.stream.on("data",(e=>{V.write(e)})),s.stream.on("end",(()=>V.end())))),!f.ssl&&J&&V&&(K&&(V.write(G),V.end()),K||(s.on("data",(e=>{V.write(e)})),s.on("end",(()=>V.end()))));const{outboundResponseHeaders:X}=yield new Promise((e=>V?V.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!V&&Q?{outboundResponseHeaders:Q.headers}:{outboundResponseHeaders:{}})));let ee=null;try{X.location&&(ee=new r.URL(X.location.startsWith("/")?`${B.href}${X.location.replace(/^\/+/,"")}`:X.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(e){O(`location replacement error ${(null!==(b=X.location)&&void 0!==b?b:"").slice(-13)}`,c.WARNING,p.ERROR_4)}const te=f.replaceResponseBodyUrls&&ee?new r.URL(C(ee.href,u.INBOUND,w).replace(/^(config:|logs:|file:)\/+/,"")):ee,ne=ee?te.origin!==ee.origin||f.dontTranslateLocationHeader?te:`${$.origin}${te.href.substring(te.origin.length)}`:ee,oe=V||Q,re=null!=F?F: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((e=>f.replaceResponseBodyUrls&&e.length?"config:"===B.protocol?e:H(e,X,{proxyHostnameAndPort:w,proxyHostname:R,key:S,direction:u.INBOUND}).catch((e=>(k(502,a,Buffer.from(x(e,"stream",$,q))),Buffer.from("")))):e)),se=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},X),f.replaceResponseBodyUrls?{"content-length":`${re.byteLength}`}:{}),f.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=I.split("").map(((e,t)=>I.substring(t).startsWith(".")&&I.substring(t))).filter((e=>e)),r=[I].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${$.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 ae=X[":status"]||Q.statusCode||200;a.writeHead(ae,f.ssl?void 0:Q.statusMessage||"Status read from http/2",se),re?a.end(re):a.end();const ie=d.hrtime.bigint();E({randomId:W,statusCode:ae,protocol:D?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ie-M)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:s.method,url:s.url,headers:Object.assign({},...Object.entries(s.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==G?void 0:G.toJSON()})).toString("base64")})})))).addListener("error",(e=>{"EACCES"===e.code&&O("permission denied for this port",c.ERROR,p.NO),"EADDRINUSE"===e.code&&O("port is already used. NOT started",c.ERROR,p.ERROR_6)})).addListener("listening",(()=>{S(f)})).on("upgrade",((e,t)=>{var a,i,l,d;if(!f.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:u,target:h,path:g}=P(e);if("/local-traffic-logs"===g)return $(t,e.headers["sec-websocket-key"]),t.on("close",(()=>{v=v.filter((e=>t!==e.stream))})),void v.push({stream:t,wantsMask:!(null!==(i=null===(a=e.headers["user-agent"])||void 0===a?void 0:a.toString())&&void 0!==i?i:"").includes("Chrome")});if("/local-traffic-config"===g){$(t,e.headers["sec-websocket-key"]),t.on("close",(()=>{b=b.filter((e=>t!==e.stream))}));let n=null;return t.on("data",(e=>{const t=((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,a=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),i=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,d=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^i[3&n]))).join("");return{payloadLength:a,mask:i,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(d)}})(e,n);if(null===n&&t.body.length<t.payloadLength)n=t;else{if(t.body.length>=t.payloadLength&&0===t.body.length)return;if(t.body.length>=t.payloadLength){let e;n=null;try{e=JSON.parse(t.body)}catch(e){return void O("config file NOT read, try again later",c.WARNING,p.ERROR_4)}(0,s.writeFile)(m,JSON.stringify(e,null,2),(e=>{e?O("config file NOT saved",c.ERROR,p.ERROR_4):O("config file saved... will reload",c.INFO,p.COLORED)}))}}})),void b.push({stream:t,wantsMask:!(null!==(d=null===(l=e.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==d?d:"").includes("Chrome")})}const y=new r.URL(`${h.protocol}//${h.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${u}`,"g"),"").replace(/^\/*/,"/")}`),R={hostname:y.hostname,path:y.pathname,port:y.port,protocol:y.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:y.hostname},w="https:"===y.protocol?(0,o.request)(R):(0,n.request)(R);w.end(),w.on("error",(e=>{O("websocket request has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)})),w.on("upgrade",((e,n)=>{const o=`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}\r\n${Object.entries(e.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;t.write(o),t.allowHalfOpen=!0,n.allowHalfOpen=!0,n.on("data",(e=>t.write(e))),t.on("data",(e=>n.write(e))),n.on("error",(e=>{O("downstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)})),t.on("error",(e=>{O("upstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)}))}))})).listen(f.port)};process.on("error",(function(e){["EPIPE","ECONNRESET"].includes(e.code)&&O(`ignoring ${e.code} error`,c.WARNING,p.ERROR_5)})),B().then(A);
2
+ "use strict";var e=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function a(e){try{l(o.next(e))}catch(e){s(e)}}function i(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,i)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const t=require("http2"),n=require("http"),o=require("https"),r=require("url"),s=require("fs"),a=require("zlib"),i=require("path"),l=require("crypto"),d=require("process");var c,p,u;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(c||(c={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(p||(p={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(u||(u={}));const h=(0,i.resolve)(process.env.HOME,".local-traffic.json"),m=(0,i.resolve)(process.cwd(),process.argv.slice(-1)[0].endsWith(".json")?process.argv.slice(-1)[0]:h),g={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let f,y,v=[],b=[];const R=e=>e===c.ERROR?"error":e===c.WARNING?"warning":"info",w=(e,t,n)=>{const o=(null==f?void 0:f.simpleLogs)||v.length?e.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(p.INBOUND,"g"),"inbound:").replace(new RegExp(p.PORT,"g"),"port:").replace(new RegExp(p.OUTBOUND,"g"),"outbound:").replace(new RegExp(p.RULES,"g"),"rules:").replace(new RegExp(p.NO,"g"),"").replace(new RegExp(p.REWRITE,"g"),"+rewrite").replace(new RegExp(p.WEBSOCKET,"g"),"websocket").replace(new RegExp(p.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):e;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null==f?void 0:f.simpleLogs)} ${(null==f?void 0:f.simpleLogs)?o:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹`:e}`),E({event:o,level:R(t)})},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)]),a=Buffer.from(Int8Array.from(n).buffer),i=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,a,i]:[s,i])},$=(e,t)=>{const n=(0,l.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`)},E=e=>N(e,v),N=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&O(n,!1),s=o.has(!0)&&O(n,!0);t.forEach((e=>{e.wantsMask?e.stream.write(s,"ascii",(()=>{})):e.stream.write(r,"ascii",(()=>{}))}))},S=e=>{w(`⎸${p.PORT} ${e.port.toString().padStart(5)} ⎸${p.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?p.REWRITE:" "}⎹⎸${p.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?p.REWRITE:" "}⎹⎸${p.RULES}${Object.keys(f.mapping).length.toString().padStart(3)}⎹⎸${f.websocket?p.WEBSOCKET:p.NO}⎹⎸${f.simpleLogs?p.NO:p.COLORED}⎹⎸${f.disableWebSecurity?p.NO:p.SHIELD}⎹`),N(e,b)},B=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(m,((n,o)=>{n&&!t&&w("config error. Using default value",c.ERROR,p.ERROR_1);try{f=Object.assign({},g,JSON.parse((o||"{}").toString()))}catch(t){return w("config syntax incorrect, aborting",c.ERROR,p.ERROR_2),f=f||Object.assign({},g),void e(f)}f.mapping[""]||w('default mapping "" not provided.',c.WARNING,p.ERROR_3),n&&"ENOENT"===n.code&&t&&m===h?(0,s.writeFile)(m,JSON.stringify(g,null,2),(t=>{t?w("config file NOT created",c.ERROR,p.ERROR_4):w("config file created",c.INFO,p.COLORED),e(f)})):e(f)})))).then((()=>{t&&(0,s.watchFile)(m,j)}))})),j=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},f);if(yield B(!1),isNaN(f.port)||f.port>65535||f.port<0)return f=e,void w("port number invalid. Not refreshing",c.ERROR,p.PORT);if("object"!=typeof f.mapping)return f=e,void w("mapping should be an object. Aborting",c.ERROR,p.ERROR_5);if(f.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&w(`request body url ${f.replaceRequestBodyUrls?"":"NO "}rewriting`,c.INFO,p.REWRITE),f.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&w(`response body url ${f.replaceResponseBodyUrls?"":"NO "}rewriting`,c.INFO,p.REWRITE),f.dontTranslateLocationHeader!==e.dontTranslateLocationHeader&&w(`response location header ${f.dontTranslateLocationHeader?"NO ":""}translation`,c.INFO,p.REWRITE),f.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&w(`http/2 ${f.dontUseHttp2Downstream?"de":""}activated downstream`,c.INFO,p.OUTBOUND),f.disableWebSecurity!==e.disableWebSecurity&&w(`web security ${f.disableWebSecurity?"de":""}activated`,c.INFO,p.SHIELD),f.websocket!==e.websocket&&w(`websocket ${f.websocket?"":"de"}activated`,c.INFO,p.WEBSOCKET),f.simpleLogs!==e.simpleLogs&&w("simple logs "+(f.simpleLogs?"on":"off"),c.INFO,p.COLORED),Object.keys(f.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&w(`${Object.keys(f.mapping).length.toString().padStart(5)} loaded mapping rules`,c.INFO,p.RULES),f.port!==e.port&&w(`port changed from ${e.port} to ${f.port}`,c.INFO,p.PORT),f.ssl&&!e.ssl&&w("ssl configuration added",c.INFO,p.INBOUND),!f.ssl&&e.ssl&&w("ssl configuration removed",c.INFO,p.INBOUND),f.port!==e.port||JSON.stringify(f.ssl)!==JSON.stringify(e.ssl)){w("restarting server",c.INFO,p.RESTART),yield Promise.all(v.concat(b).map((e=>new Promise((t=>e.stream.end(t)))))),v=[],b=[];(yield Promise.race([new Promise((e=>y?y.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||w("error during restart (websockets ?)",c.WARNING,p.RESTART),A()}else S(f)})),I=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),T=e=>{const t=(0,i.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,s.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,s.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,s.lstat)((0,i.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${x(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},L=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}}),x=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"><\/script>\n<script src="https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,U=(e,t,n,o)=>`${x(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n &#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${o||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,C=(t,n,o)=>e(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((t,n)=>e(void 0,void 0,void 0,(function*(){const e=n.trim().toLowerCase(),o="gzip"===e||"x-gzip"===e?a.gunzip:"deflate"===e?a.inflate:"br"===e?a.brotliDecompress:"identity"===e||""===e?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${e} compression not supported by the proxy`);const r=yield t;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(t)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\x7F]/.test(e.toString()))?f.replaceResponseBodyUrls?k(e.toString(),o.direction,o.proxyHostnameAndPort).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${f.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${f.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)))}))})),k=(e,t,n)=>Object.entries(f.mapping).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[o,r])=>r.startsWith("logs:")||r.startsWith("config:")||""!==o&&!o.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===u.INBOUND?e.replace(new RegExp(r.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${f.ssl?"s":""}://${n}${o.replace(/\/+$/,"")}/`):e.split(`http${f.ssl?"s":""}://${n}${o.replace(/\/+$/,"")}`).join(r)),e).split(`${n}/:`).join(`${n}:`),H=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)},P=e=>{var t,n,o;const s=(null!==(o=null!==(n=null===(t=e.headers[":authority"])||void 0===t?void 0:t.toString())&&void 0!==n?n:e.headers.host)&&void 0!==o?o:"localhost").replace(/:.*/,""),a=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==f.port||f.ssl?443===f.port&&f.ssl?"":`:${f.port}`:""}`,i=new r.URL(`http${f.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[d,c]=Object.entries(Object.assign({},Object.assign({},...Object.entries(f.mapping).map((([e,t])=>({[e]:new r.URL(I("string"==typeof t?t:t.downstreamUrl))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:d,target:c}},A=()=>{y=(f.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},f.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,h,y,b;if(!s.headers.host&&!s.headers[":authority"])return void H(400,a,Buffer.from(U(new Error("client must supply a 'host' header"),"proxy",new r.URL(`http${f.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:R,proxyHostnameAndPort:O,url:$,path:N,key:S,target:B}=P(s);if(!B)return void H(502,a,Buffer.from(U(new Error(`No mapping found in config file ${m}`),"proxy",$)));const j=B.host.replace(RegExp(/\/+$/),""),A=`${B.href.substring(8+B.host.length)}${I(N.replace(RegExp(I(S)),""))}`.replace(/^\/*/,"/"),D=new r.URL(`${B.protocol}//${j}${A}`);let q=!f.dontUseHttp2Downstream;const W=(0,l.randomBytes)(20).toString("hex");E({level:"info",protocol:q?"HTTP/2":"HTTP1.1",method:s.method,upstreamPath:N,downstreamPath:D.href,randomId:W,uniqueHash:"N/A"});const M=d.hrtime.bigint();let F=null;const _="file:"===B.protocol?T(D):"logs:"===B.protocol?(e=>L(`${x(128250,"logs","")}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n <div class="container-fluid">\n <ul class="navbar-nav">\n <li class="nav-item">\n <a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n </li>\n <li class="nav-item">\n <a class="nav-link" href="javascript:show(1)">Proxy</a>\n </li>\n </ul>\n <span class="navbar-text">\n Limit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n <option value="50">50</option><option value="100">100</option><option value="200">200</option>\n <option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n </select> rows\n </span>\n </div>\n</nav>\n<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">...</th>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Protocol</th>\n <th scope="col">Method</th>\n <th scope="col">Status</th>\n <th scope="col">Duration</th>\n <th scope="col">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${f.ssl?"s":""}://${e}/local-traffic-logs");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary"' + \n (uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';\n if(data.statusCode && uniqueHash) {\n const color = Math.floor(data.statusCode / 100) === 1 ? "info" :\n Math.floor(data.statusCode / 100) === 2 ? "success" :\n Math.floor(data.statusCode / 100) === 3 ? "dark" :\n Math.floor(data.statusCode / 100) === 4 ? "warning" :\n Math.floor(data.statusCode / 100) === 5 ? "danger" :\n "secondary";\n const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\n if (statusCodeColumn)\n statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\n const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\n if (durationColumn) {\n const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\n data.duration + 'ms';\n durationColumn.innerHTML = duration;\n }\n\n const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\n if (protocolColumn) {\n protocolColumn.innerHTML = data.protocol;\n }\n\n const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\n if (replayColumn) {\n replayColumn.innerHTML = replay;\n }\n } else if (uniqueHash) {\n document.getElementById("access")\n .insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n '<td scope="col" class="replay">' + replay + '</td>' +\n '<td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col" class="protocol">' + data.protocol + '</td>' + \n '<td scope="col">' + data.method + '</td>' + \n '<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +\n '<td scope="col" class="duration">&#x23F1;</td>' +\n '<td scope="col">' + data.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>`))(O):"config:"===B.protocol?(e=>L(`${x(127899,"config","")}\n <link href="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.js"><\/script>\n <script src="https://cdn.jsdelivr.net/npm/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({},g),{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(f)}\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${f.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>`))(O):q?yield Promise.race([new Promise((e=>{const n=(0,t.connect)(D,{rejectUnauthorized:!1,protocol:B.protocol},((t,o)=>{q=q&&!!o.alpnProtocol,e(q?n:null)}));n.on("error",(e=>{F=q&&Buffer.from(U(e,"connection",$,D))}))})),new Promise((e=>setTimeout((()=>{q=!1,e(null)}),3e3)))]):null;F instanceof Buffer||(F=null);const J=null==s?void 0:s.readableLength,K=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let z=null;const G=f.replaceRequestBodyUrls||v.length;if(G){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);const n=!((f.ssl&&0===K||!f.ssl&&0===J)&&("0"===s.headers["content-length"]||void 0===s.headers["content-length"]));yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((o=>{n||o(void 0),e.on("data",(e=>{t=Buffer.concat([t,e])})),e.on("end",o),e.on("error",o)}))]),n&&!t.length&&w(`body replacement error ${N.slice(-17)}`,c.WARNING,p.ERROR_4),z=yield C(t,s.headers,{proxyHostnameAndPort:O,proxyHostname:R,key:S,direction:u.OUTBOUND})}const Y=Object.assign(Object.assign({},[...Object.entries(s.headers)].filter((([e])=>!["host","connection","keep-alive"].includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace($.hostname,j))).join(", "),e)),{})),{origin:B.href,referer:D.toString(),"content-length":null!==(y=null!==(h=null==z?void 0:z.length)&&void 0!==h?h:s.headers["content-length"])&&void 0!==y?y:0,":authority":j,":method":s.method,":path":A,":scheme":B.protocol.replace(":","")}),Z=_&&!F&&_.request(Y,{endStream:f.ssl?!(null==K||K):!J});null==Z||Z.on("error",(e=>{const t=-505===e.errno;F=Buffer.from(U(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),$,D))}));const V={hostname:B.hostname,path:A,port:B.port,protocol:B.protocol,rejectUnauthorized:!1,method:s.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:B.hostname})},Q=!F&&!q&&!["file:","logs:","config:"].includes(B.protocol)&&(yield new Promise((e=>{const t="https:"===B.protocol?(0,o.request)(V,e):(0,n.request)(V,e);t.on("error",(t=>{F=Buffer.from(U(t,"request",$,D)),e(null)})),G&&(t.write(z),t.end()),G||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(F)return void H(502,a,F);F=null,f.ssl&&K&&Z&&(G&&(Z.write(z),Z.end()),G||(s.stream.on("data",(e=>{Z.write(e)})),s.stream.on("end",(()=>Z.end())))),!f.ssl&&J&&Z&&(G&&(Z.write(z),Z.end()),G||(s.on("data",(e=>{Z.write(e)})),s.on("end",(()=>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 r.URL(X.location.startsWith("/")?`${B.href}${X.location.replace(/^\/+/,"")}`:X.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(e){w(`location replacement error ${(null!==(b=X.location)&&void 0!==b?b:"").slice(-13)}`,c.WARNING,p.ERROR_4)}const te=f.replaceResponseBodyUrls&&ee?new r.URL(k(ee.href,u.INBOUND,O).replace(/^(config:|logs:|file:)\/+/,"")):ee,ne=ee?te.origin!==ee.origin||f.dontTranslateLocationHeader?te:`${$.origin}${te.href.substring(te.origin.length)}`:ee,oe=Z||Q,re=null!=F?F: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((e=>f.replaceResponseBodyUrls&&e.length?"config:"===B.protocol?e:C(e,X,{proxyHostnameAndPort:O,proxyHostname:R,key:S,direction:u.INBOUND}).catch((e=>(H(502,a,Buffer.from(U(e,"stream",$,D))),Buffer.from("")))):e)),se=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},X),f.replaceResponseBodyUrls?{"content-length":`${re.byteLength}`}:{}),f.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=j.split("").map(((e,t)=>j.substring(t).startsWith(".")&&j.substring(t))).filter((e=>e)),r=[j].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${$.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 ae=X[":status"]||Q.statusCode||200;a.writeHead(ae,f.ssl?void 0:Q.statusMessage||"Status read from http/2",se),re?a.end(re):a.end();const ie=d.hrtime.bigint();E({randomId:W,statusCode:ae,protocol:q?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ie-M)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:s.method,url:s.url,headers:Object.assign({},...Object.entries(s.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==z?void 0:z.toJSON()})).toString("base64")})})))).addListener("error",(e=>{"EACCES"===e.code&&w("permission denied for this port",c.ERROR,p.NO),"EADDRINUSE"===e.code&&w("port is already used. NOT started",c.ERROR,p.ERROR_6)})).addListener("listening",(()=>{S(f)})).on("upgrade",((e,t)=>{var a,i,l,d;if(!f.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:u,target:h,path:g}=P(e);if("/local-traffic-logs"===g)return $(t,e.headers["sec-websocket-key"]),t.on("close",(()=>{v=v.filter((e=>t!==e.stream))})),void v.push({stream:t,wantsMask:!(null!==(i=null===(a=e.headers["user-agent"])||void 0===a?void 0:a.toString())&&void 0!==i?i:"").includes("Chrome")});if("/local-traffic-config"===g){$(t,e.headers["sec-websocket-key"]),t.on("close",(()=>{b=b.filter((e=>t!==e.stream))}));let n=null;return t.on("data",(e=>{const t=((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,a=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),i=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,d=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^i[3&n]))).join("");return{payloadLength:a,mask:i,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(d)}})(e,n);if(null===n&&t.body.length<t.payloadLength)n=t;else{if(t.body.length>=t.payloadLength&&0===t.body.length)return;if(t.body.length>=t.payloadLength){let e;n=null;try{e=JSON.parse(t.body)}catch(e){return void w("config file NOT read, try again later",c.WARNING,p.ERROR_4)}(0,s.writeFile)(m,JSON.stringify(e,null,2),(e=>{e?w("config file NOT saved",c.ERROR,p.ERROR_4):w("config file saved... will reload",c.INFO,p.COLORED)}))}}})),void b.push({stream:t,wantsMask:!(null!==(d=null===(l=e.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==d?d:"").includes("Chrome")})}const y=new r.URL(`${h.protocol}//${h.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${u}`,"g"),"").replace(/^\/*/,"/")}`),R={hostname:y.hostname,path:y.pathname,port:y.port,protocol:y.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:y.hostname},O="https:"===y.protocol?(0,o.request)(R):(0,n.request)(R);O.end(),O.on("error",(e=>{w("websocket request has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)})),O.on("upgrade",((e,n)=>{const o=`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}\r\n${Object.entries(e.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;t.write(o),t.allowHalfOpen=!0,n.allowHalfOpen=!0,n.on("data",(e=>t.write(e))),t.on("data",(e=>n.write(e))),n.on("error",(e=>{w("downstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)})),t.on("error",(e=>{w("upstream socket has errored "+(e.errno?`(${e.errno})`:""),c.WARNING,p.WEBSOCKET)}))}))})).listen(f.port)};process.on("error",(function(e){["EPIPE","ECONNRESET"].includes(e.code)&&w(`ignoring ${e.code} error`,c.WARNING,p.ERROR_5)})),B().then(A);
package/index.ts CHANGED
@@ -805,6 +805,19 @@ const configPage = (proxyHostnameAndPort: string) =>
805
805
  staticPage(`${header(0x1f39b, "config", "")}
806
806
  <link href="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">
807
807
  <script src="https://cdn.jsdelivr.net/npm/jsoneditor/dist/jsoneditor.min.js"></script>
808
+ <script src="https://cdn.jsdelivr.net/npm/node-forge/dist/forge.min.js"></script>
809
+ <div id="ssl-modal" class="modal" tabindex="-1" role="dialog">
810
+ <div class="modal-dialog" role="document">
811
+ <div class="modal-content">
812
+ <div class="modal-header">
813
+ <h5 class="modal-title">SSL keypair generation in progress</h5>
814
+ </div>
815
+ <div class="modal-body">
816
+ <p>Wait a few seconds or move your mouse to improve the entropy.</p>
817
+ </div>
818
+ </div>
819
+ </div>
820
+ </div>
808
821
  <div id="jsoneditor" style="width: 400px; height: 400px;"></div>
809
822
  <script>
810
823
  // create the editor
@@ -835,6 +848,33 @@ const configPage = (proxyHostnameAndPort: string) =>
835
848
  socket.send(JSON.stringify(editor.get()));
836
849
  }
837
850
 
851
+ function generateSslCertificate() {
852
+ const sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});
853
+ sslModal.show()
854
+ setTimeout(function() {
855
+ const keypair = forge.pki.rsa.generateKeyPair(2048);
856
+ const certificate = forge.pki.createCertificate();
857
+ const now = new Date();
858
+ const fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));
859
+ Object.assign(certificate, {
860
+ publicKey: keypair.publicKey,
861
+ serialNumber: "01",
862
+ validity: {
863
+ notBefore: now,
864
+ notAfter: fiveYears,
865
+ },
866
+ });
867
+ certificate.sign(keypair.privateKey, forge.md.sha256.create());
868
+ const key = forge.pki.privateKeyToPem(keypair.privateKey);
869
+ const cert = forge.pki.certificateToPem(certificate);
870
+ const existingConfig = editor.get();
871
+ editor.set({ ...existingConfig, ssl: { key, cert },
872
+ port: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))
873
+ });
874
+ sslModal.hide();
875
+ }, 100);
876
+ }
877
+
838
878
  const editor = new JSONEditor(container, options);
839
879
  let socket;
840
880
  const initialJson = ${JSON.stringify(config)}
@@ -852,6 +892,14 @@ const configPage = (proxyHostnameAndPort: string) =>
852
892
  document.getElementById('jsoneditor').style.width =
853
893
  parseInt(window.getComputedStyle(
854
894
  document.querySelector('.container')).maxWidth) + 'px';
895
+ const sslButton = document.createElement('button');
896
+ sslButton.addEventListener("click", generateSslCertificate);
897
+ sslButton.type="button";
898
+ sslButton.classList.add("btn");
899
+ sslButton.classList.add("btn-primary");
900
+ sslButton.innerHTML="&#x1F512;";
901
+ document.querySelector('.jsoneditor-menu')
902
+ .appendChild(sslButton);
855
903
  const saveButton = document.createElement('button');
856
904
  saveButton.addEventListener("click", save);
857
905
  saveButton.type="button";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.67",
3
+ "version": "0.0.68",
4
4
  "main": "index.ts",
5
5
  "private": false,
6
6
  "keywords": [
@@ -24,8 +24,8 @@
24
24
  "build": "npm run clean && npm run typescript && npm run terser && npm run shebang && npm run chmod"
25
25
  },
26
26
  "devDependencies": {
27
- "@types/node": "^18.16.3",
28
- "terser": "^5.17.1",
27
+ "@types/node": "^20.1.1",
28
+ "terser": "^5.17.2",
29
29
  "typescript": "^5.0.4"
30
30
  },
31
31
  "bin": {