local-traffic 0.0.67 → 0.0.69

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
@@ -5,7 +5,7 @@ That is a secure http/2 (or insecure http1.1) reverse-proxy installed on your ma
5
5
  - with 0 transitive dependency
6
6
  - with 1 install step
7
7
  - with a startup time of a few milliseconds
8
- - with one 30kb index.js file
8
+ - with one 36kb index.js file
9
9
 
10
10
  How simple is that ?
11
11
 
@@ -48,17 +48,26 @@ 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
 
57
+ ### from command line
58
+
56
59
  ```bash
57
60
  npx local-traffic [location-of-the-local-traffic-config-file]
58
61
  ```
59
62
 
60
63
  > When not specified, the location of the config file will be `$HOME/.local-traffic.json`
61
64
 
65
+ ### from node.js application (>= 0.0.69)
66
+
67
+ ```bash
68
+ node -e 'const { start } = require("local-traffic"); start({ })'
69
+ ```
70
+
62
71
  ## how to change mappings to local / non-local
63
72
 
64
73
  1. Open `.local-traffic.json` while running it
@@ -70,7 +79,7 @@ npx local-traffic [location-of-the-local-traffic-config-file]
70
79
  All boolean settings default to false when unspecified.
71
80
 
72
81
  - `mapping`: (`{[path: string]: string | {replaceBody: string ; downstreamUrl: string}`) routing rules (required)
73
- - `ssl` : SSL options
82
+ - `ssl` : SSL options (can be generated from the config web editor if you don't know how to set them)
74
83
  - `ssl.cert` : (`string`) Certificate (PEM format)
75
84
  - `ssl.key` : (`string`) Private Key (PEM format)
76
85
  - `port` : (`number`) port number
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const n=require("http2"),o=require("http"),r=require("https"),s=require("url"),i=require("fs"),a=require("zlib"),l=require("path"),c=require("crypto"),d=require("process");var p,u,g;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(p||(p={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(u||(u={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(g||(g={}));const f=(0,l.resolve)(d.env.HOME,".local-traffic.json"),h=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:f),m={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},v=e=>e===p.ERROR?"error":e===p.WARNING?"warning":"info",y=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(u.INBOUND,"g"),"inbound:").replace(new RegExp(u.PORT,"g"),"port:").replace(new RegExp(u.OUTBOUND,"g"),"outbound:").replace(new RegExp(u.RULES,"g"),"rules:").replace(new RegExp(u.NO,"g"),"").replace(new RegExp(u.REWRITE,"g"),"+rewrite").replace(new RegExp(u.WEBSOCKET,"g"),"websocket").replace(new RegExp(u.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${d.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:v(n)})},b=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=[...e.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,e.length),s=e.length<126?Buffer.from(Uint8Array.from([129,(t?128:0)+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,126|(t?128:0)]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]),i=Buffer.from(Int8Array.from(n).buffer),a=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,i,a]:[s,a])};exports.createWebsocketBufferFrom=b;const R=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=R;const w=(e,t)=>{const n=(0,c.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`)};exports.acknowledgeWebsocket=w;const O=function(e){return E(this,e,this.configListeners)},$=function(e){return E(this,e,this.logsListeners)},E=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&b(o,!1),i=r.has(!0)&&b(o,!0),a=e=>{e.stream.errored&&e.stream.destroy()};n.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(i,"ascii",(()=>a(e))):e.stream.write(s,"ascii",(()=>a(e))))}))},L=function(){this.log(`⎸${u.PORT} ${this.config.port.toString().padStart(5)} ⎸${u.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?u.REWRITE:" "}⎹⎸${u.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?u.REWRITE:" "}⎹⎸${u.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹⎸${this.config.websocket?u.WEBSOCKET:u.NO}⎹⎸${this.config.simpleLogs?u.NO:u.COLORED}⎹⎸${this.config.disableWebSecurity?u.NO:u.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=L;const S=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(h,((n,o)=>{n&&!e&&y(null,"config error. Using default value",p.ERROR,u.ERROR_1);let r=null;try{r=Object.assign({},m,JSON.parse((o||"{}").toString()))}catch(e){return y({config:r},"config syntax incorrect, aborting",p.ERROR,u.ERROR_2),r=null!=r?r:Object.assign({},m),void t(r)}r.mapping[""]||y({config:r},'default mapping "" not provided.',p.WARNING,u.ERROR_3),n&&"ENOENT"===n.code&&e&&h===f?(0,i.writeFile)(h,JSON.stringify(m,null,2),(e=>{e?y(null,"config file NOT created",p.ERROR,u.ERROR_4):y(null,"config file created",p.INFO,u.COLORED),t(r)})):t(r)}))))}));exports.load=S;const x=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),N="https://cdn.jsdelivr.net/npm/",B=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="${N}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${N}jquery/dist/jquery.min.js"><\/script>\n<script src="${N}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,k=e=>{const t=(0,l.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,i.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,i.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,i.lstat)((0,l.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${B(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},j=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=e,t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{"response"===e&&this.events.response({Server:"local","Content-Type":"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}),I=(e,t,n,o)=>`${B(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n &#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${o||"&lt;no-target-url&gt;"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,U=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?a.gunzip:"deflate"===t?a.inflate:"br"===t?a.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\x7F]/.test(e.toString()))?o.replaceResponseBodyUrls?T(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e.toString():e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?a.gzip:"deflate"===n?a.deflate:"br"===n?a.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))}));exports.replaceBody=U;const T=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>s.startsWith("logs:")||s.startsWith("config:")||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===g.INBOUND?e.replace(new RegExp(s.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=T;const C=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=C;const H=(e,t)=>{var n,o,r,i,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(i=t.port)&&void 0!==i?i:8080}`:""}`,d=new s.URL(`http${t.ssl?"s":""}://${c}${e.url}`),p=d.href.substring(d.origin.length),u=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new s.URL(x("string"==typeof t?t:t.downstreamUrl))}))))),[g,f]=null!==(a=Object.entries(u).find((([e])=>p.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:p,key:g,target:f}};exports.determineMapping=H;const P=function(e,t,n){var i,a,l,c;if(!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:g,path:f}=H(t,e.config);if("/local-traffic-logs"===f)return w(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(i=t.headers["user-agent"])||void 0===i?void 0:i.toString())&&void 0!==a?a:"").includes("Chrome")})};if("/local-traffic-config"===f){w(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=R(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",p.WARNING,u.ERROR_4)}W(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const h=new s.URL(`${g.protocol}//${g.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),m={hostname:h.hostname,path:h.pathname,port:h.port,protocol:h.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:h.hostname},v="https:"===h.protocol?(0,r.request)(m):(0,o.request)(m);v.end(),v.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),v.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),p.WARNING,u.WEBSOCKET)}))}))};exports.websocketServe=P;const q=function(e,i,a){var l,f,v,y,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void C(400,a,Buffer.from(I(new Error("client must supply a 'host' header"),"proxy",new s.URL(`http${e.config.ssl?"s":""}://unknowndomain${i.url}`))));const{proxyHostname:t,proxyHostnameAndPort:R,url:w,path:O,key:$,target:E}=H(i,e.config);if(!E)return void C(502,a,Buffer.from(I(new Error(`No mapping found in config file ${h}`),"proxy",w)));const L=E.host.replace(RegExp(/\/+$/),""),S=`${E.href.substring(8+E.host.length)}${x(O.replace(RegExp(x($)),""))}`.replace(/^\/*/,"/"),P=new s.URL(`${E.protocol}//${L}${S}`);let q=!e.config.dontUseHttp2Downstream;const A=(0,c.randomBytes)(20).toString("hex");e.notifyLogsListeners({level:"info",protocol:q?"HTTP/2":"HTTP1.1",method:i.method,upstreamPath:O,downstreamPath:P.href,randomId:A,uniqueHash:"N/A"});const D=d.hrtime.bigint();let W=null;const M="file:"===E.protocol?k(P):"logs:"===E.protocol?((e,t)=>j(`${B(128250,"logs","")}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n <div class="container-fluid">\n <ul class="navbar-nav">\n <li class="nav-item">\n <a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n </li>\n <li class="nav-item">\n <a class="nav-link" href="javascript:show(1)">Proxy</a>\n </li>\n </ul>\n <span class="navbar-text">\n Limit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n <option value="50">50</option><option value="100">100</option><option value="200">200</option>\n <option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n </select> rows\n </span>\n </div>\n</nav>\n<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">...</th>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Protocol</th>\n <th scope="col">Method</th>\n <th scope="col">Status</th>\n <th scope="col">Duration</th>\n <th scope="col">Upstream Path</th>\n <th scope="col">Downstream Path</th>\n </tr>\n </thead>\n <tbody id="access">\n </tbody>\n</table>\n<table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">\n <thead>\n <tr>\n <th scope="col">Date</th>\n <th scope="col">Level</th>\n <th scope="col">Message</th>\n </tr>\n </thead>\n <tbody id="proxy">\n </tbody>\n</table>\n<script type="text/javascript">\n function start() {\n document.getElementById('table-access').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${t?"s":""}://${e}/local-traffic-logs");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary"' +\n (uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';\n if(data.statusCode && uniqueHash) {\n const color = Math.floor(data.statusCode / 100) === 1 ? "info" :\n Math.floor(data.statusCode / 100) === 2 ? "success" :\n Math.floor(data.statusCode / 100) === 3 ? "dark" :\n Math.floor(data.statusCode / 100) === 4 ? "warning" :\n Math.floor(data.statusCode / 100) === 5 ? "danger" :\n "secondary";\n const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\n if (statusCodeColumn)\n statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\n const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\n if (durationColumn) {\n const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\n data.duration + 'ms';\n durationColumn.innerHTML = duration;\n }\n\n const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\n if (protocolColumn) {\n protocolColumn.innerHTML = data.protocol;\n }\n\n const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\n if (replayColumn) {\n replayColumn.innerHTML = replay;\n }\n } else if (uniqueHash) {\n document.getElementById("access")\n .insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n '<td scope="col" class="replay">' + replay + '</td>' +\n '<td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col" class="protocol">' + data.protocol + '</td>' + \n '<td scope="col">' + data.method + '</td>' + \n '<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +\n '<td scope="col" class="duration">&#x23F1;</td>' +\n '<td scope="col">' + data.upstreamPath + '</td>' + \n '<td scope="col">' + data.downstreamPath + '</td>' + \n '</tr>');\n } else if(data.event) {\n document.getElementById("proxy")\n .insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +\n '<td scope="col">' + (data.level || 'info')+ '</td>' + \n '<td scope="col">' + data.event + '</td></tr>');\n }\n cleanup();\n };\n socket.onerror = function(error) {\n console.log(\`[error] \${error}\`);\n setTimeout(start, 5000);\n };\n };\n function show(id) {\n [...document.querySelectorAll('table')].forEach((table, index) => {\n table.style.display = index === id ? 'block': 'none'\n });\n [...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\n if (index === id) { link.classList.add('active') } else link.classList.remove('active');\n });\n }\n function cleanup() {\n const currentLimit = parseInt(document.getElementById('limit').value)\n for (let table of ['access', 'proxy']) {\n while (currentLimit && document.getElementById(table).childNodes.length && \n document.getElementById(table).childNodes.length > currentLimit) {\n [...document.getElementById(table).childNodes].slice(-1)[0].remove();\n }\n }\n }\n function replay(event) {\n const uniqueHash = event.target.dataset.uniquehash;\n const { method, url, headers, body } = JSON.parse(atob(uniqueHash));\n fetch(url, {\n method,\n headers,\n body: !body.data || !body.data.length \n ? undefined\n : new TextDecoder().decode(new Int8Array(body.data))\n });\n }\n window.addEventListener("DOMContentLoaded", start);\n<\/script>\n</body></html>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>j(`${B(127899,"config","")}\n <link href="${N}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="${N}jsoneditor/dist/jsoneditor.min.js"><\/script>\n <script src="${N}node-forge/dist/forge.min.js"><\/script>\n <div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n <div class="modal-dialog" role="document">\n <div class="modal-content">\n <div class="modal-header">\n <h5 class="modal-title">SSL keypair generation in progress</h5>\n </div>\n <div class="modal-body">\n <p>Wait a few seconds or move your mouse to improve the entropy.</p>\n </div>\n </div>\n </div>\n </div>\n <div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n <script>\n // create the editor\n const container = document.getElementById("jsoneditor")\n const options = {mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n ${Object.entries(Object.assign(Object.assign({},m),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n ")}\n },\n required: [],\n additionalProperties: false\n }}\n\n function save() {\n socket.send(JSON.stringify(editor.get()));\n }\n\n function generateSslCertificate() {\n const sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\n sslModal.show()\n setTimeout(function() {\n const keypair = forge.pki.rsa.generateKeyPair(2048);\n const certificate = forge.pki.createCertificate();\n const now = new Date();\n const fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\n Object.assign(certificate, {\n publicKey: keypair.publicKey,\n serialNumber: "01",\n validity: {\n notBefore: now,\n notAfter: fiveYears,\n },\n });\n certificate.sign(keypair.privateKey, forge.md.sha256.create());\n const key = forge.pki.privateKeyToPem(keypair.privateKey);\n const cert = forge.pki.certificateToPem(certificate);\n const existingConfig = editor.get();\n editor.set({ ...existingConfig, ssl: { key, cert },\n port: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n });\n sslModal.hide();\n }, 100);\n }\n\n const editor = new JSONEditor(container, options);\n let socket;\n const initialJson = ${JSON.stringify(t)}\n editor.set(initialJson)\n editor.validate();\n editor.aceEditor.commands.addCommand({\n name: 'save',\n bindKey: {win: 'Ctrl-S', mac: 'Command-S'},\n exec: save,\n });\n\n window.addEventListener("DOMContentLoaded", function() {\n document.getElementById('jsoneditor').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n document.getElementById('jsoneditor').style.width =\n parseInt(window.getComputedStyle(\n document.querySelector('.container')).maxWidth) + 'px';\n const sslButton = document.createElement('button');\n sslButton.addEventListener("click", generateSslCertificate);\n sslButton.type="button";\n sslButton.classList.add("btn");\n sslButton.classList.add("btn-primary");\n sslButton.innerHTML="&#x1F512;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(sslButton);\n const saveButton = document.createElement('button');\n saveButton.addEventListener("click", save);\n saveButton.type="button";\n saveButton.classList.add("btn");\n saveButton.classList.add("btn-primary");\n saveButton.innerHTML="&#x1F4BE;";\n document.querySelector('.jsoneditor-menu')\n .appendChild(saveButton);\n socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\n socket.onmessage = function(event) {\n editor.set(JSON.parse(event.data))\n editor.validate()\n }\n });\n <\/script>\n </body></html>`))(R,e.config):q?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(P,{rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{q=q&&!!o.alpnProtocol,e(q?t:null)}));t.on("error",(e=>{W=q&&Buffer.from(I(e,"connection",w,P))}))})),new Promise((e=>setTimeout((()=>{q=!1,e(null)}),3e3)))]):null;W instanceof Buffer||(W=null);const F=null==i?void 0:i.readableLength,_=null===(l=null==i?void 0:i.stream)||void 0===l?void 0:l.readableLength;let J=null;const K=e.config.replaceRequestBodyUrls||e.logsListeners.length;if(K){const n=null!==(f=null==i?void 0:i.stream)&&void 0!==f?f:i;let o=Buffer.from([]);const r=!((e.config.ssl&&0===_||!e.config.ssl&&0===F)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{r||e(void 0),n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)}))]),r&&!o.length&&e.log(`body replacement error ${O.slice(-17)}`,p.WARNING,u.ERROR_4),J=yield U(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.OUTBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls})}const z=Object.assign(Object.assign({},[...Object.entries(i.headers)].filter((([e])=>!["host","connection","keep-alive"].includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(w.hostname,L))).join(", "),e)),{})),{origin:E.href,referer:P.toString(),"content-length":null!==(y=null!==(v=null==J?void 0:J.length)&&void 0!==v?v:i.headers["content-length"])&&void 0!==y?y:0,":authority":L,":method":i.method,":path":S,":scheme":E.protocol.replace(":","")}),G=M&&!W&&M.request(z,{endStream:e.config.ssl?!(null==_||_):!F});null==G||G.on("error",(e=>{const t=-505===e.errno;W=Buffer.from(I(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),w,P))}));const Y={hostname:E.hostname,path:S,port:E.port,protocol:E.protocol,rejectUnauthorized:!1,method:i.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(z).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},Z=!W&&!q&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(Y,e):(0,o.request)(Y,e);t.on("error",(t=>{W=Buffer.from(I(t,"request",w,P)),e(null)})),K&&(t.write(J),t.end()),K||(i.on("data",(e=>t.write(e))),i.on("end",(()=>t.end())))})));if(W)return void C(502,a,W);W=null,e.config.ssl&&_&&G&&(K&&(G.write(J),G.end()),K||(i.stream.on("data",(e=>{G.write(e)})),i.stream.on("end",(()=>G.end())))),!e.config.ssl&&F&&G&&(K&&(G.write(J),G.end()),K||(i.on("data",(e=>{G.write(e)})),i.on("end",(()=>G.end()))));const{outboundResponseHeaders:V}=yield new Promise((e=>G?G.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!G&&Z?{outboundResponseHeaders:Z.headers}:{outboundResponseHeaders:{}})));let Q=null;try{V.location&&(Q=new s.URL(V.location.startsWith("/")?`${E.href}${V.location.replace(/^\/+/,"")}`:V.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=V.location)&&void 0!==b?b:"").slice(-13)}`,p.WARNING,u.ERROR_4)}const X=e.config.replaceResponseBodyUrls&&Q?new s.URL(T(Q.href,{direction:g.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):Q,ee=Q?X.origin!==Q.origin||e.config.dontTranslateLocationHeader?X:`${w.origin}${X.href.substring(X.origin.length)}`:Q,te=G||Z,ne=null!=W?W:yield new Promise((e=>{let t=Buffer.alloc(0);te?(te.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),te.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:U(n,V,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:g.INBOUND,mapping:e.config.mapping,port:e.config.port,replaceResponseBodyUrls:e.config.replaceResponseBodyUrls,ssl:!!e.config.ssl}).catch((e=>(C(502,a,Buffer.from(I(e,"stream",w,P))),Buffer.from("")))):n)),oe=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},V),e.config.replaceResponseBodyUrls?{"content-length":`${ne.byteLength}`}:{}),e.config.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase()&&"connection"!==e.toLowerCase()&&"keep-alive"!==e.toLowerCase())).reduce(((e,[t,n])=>{const o=L.split("").map(((e,t)=>L.substring(t).startsWith(".")&&L.substring(t))).filter((e=>e)),r=[L].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),ee?{location:[ee]}:{});try{Object.entries(oe).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const re=V[":status"]||Z.statusCode||200;a.writeHead(re,e.config.ssl?void 0:Z.statusMessage||"Status read from http/2",oe),ne?a.end(ne):a.end();const se=d.hrtime.bigint();e.notifyLogsListeners({randomId:A,statusCode:re,protocol:q?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(se-D)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:i.method,url:i.url,headers:Object.assign({},...Object.entries(i.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==J?void 0:J.toJSON()})).toString("base64")})}))};exports.serve=q;const A=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",p.ERROR,u.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",p.ERROR,u.ERROR_6)};exports.errorListener=A;const D=e=>W({config:Object.assign(Object.assign({},m),e)},{});exports.start=D;const W=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,g,f,m;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(h,JSON.stringify(r.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",p.ERROR,u.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",p.INFO,u.COLORED)}));if(null===r.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",p.WARNING,u.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(a=e.logsListeners)&&void 0!==a?a:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const v=null!==(l=r.config)&&void 0!==l?l:e.config,b=(null===r.configListeners?[]:null!==(d=null!==(c=r.configListeners)&&void 0!==c?c:e.configListeners)&&void 0!==d?d:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),R=(null===r.logsListeners?[]:null!==(f=null!==(g=r.logsListeners)&&void 0!==g?g:e.logsListeners)&&void 0!==f?f:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:v,logsListeners:R,configListeners:b,configFileWatcher:null!==(m=w.configFileWatcher)&&void 0!==m?m:(0,i.watchFile)(h,(()=>t(void 0,void 0,void 0,(function*(){return W(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield 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))})))),log:y.bind(w,w),notifyConfigListeners:O.bind(w),notifyLogsListeners:$.bind(w),quickStatus:L.bind(w),server:null!==r.server&&w.server?w.server:(v.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},v.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>q(w,e,t))).addListener("error",(e=>A(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>W(w,P(w,e,t)))).listen(v.port)}),w}));exports.update=W;const M=null!==(e=d.argv.filter((e=>!["ts-node","node"].some((t=>e.includes(t)))))[0])&&void 0!==e?e:"";M.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/)&&S().then(D);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.67",
4
- "main": "index.ts",
3
+ "version": "0.0.69",
4
+ "main": "./dist/local-traffic.js",
5
5
  "private": false,
6
6
  "keywords": [
7
7
  "reverse-proxy",
@@ -15,20 +15,21 @@
15
15
  "repository": "git@github.com:libetl/local-traffic.git",
16
16
  "author": "LiBe <libe4@free.fr>",
17
17
  "scripts": {
18
- "start": "./dist/localTraffic.js",
18
+ "start": "./dist/local-traffic.js",
19
19
  "typescript": "tsc",
20
- "shebang": "echo '#!/usr/bin/env node' | cat - ./dist/terser.js > ./dist/localTraffic.js",
20
+ "shebang": "echo '#!/usr/bin/env node' | cat - ./dist/terser.js > ./dist/local-traffic.js",
21
21
  "terser": "terser ./dist/index.js -c -m --toplevel > ./dist/terser.js",
22
- "chmod": "chmod a+x ./dist/localTraffic.js",
22
+ "chmod": "chmod a+x ./dist/local-traffic.js",
23
23
  "clean": "rm -rf dist",
24
- "build": "npm run clean && npm run typescript && npm run terser && npm run shebang && npm run chmod"
24
+ "build": "npm run clean && npm run typescript && npm run terser && npm run shebang && npm run chmod",
25
+ "test": "node ./test/tests.spec.mjs"
25
26
  },
26
27
  "devDependencies": {
27
- "@types/node": "^18.16.3",
28
- "terser": "^5.17.1",
28
+ "@types/node": "^20.1.1",
29
+ "terser": "^5.17.3",
29
30
  "typescript": "^5.0.4"
30
31
  },
31
32
  "bin": {
32
- "local-traffic": "./dist/localTraffic.js"
33
+ "local-traffic": "./dist/local-traffic.js"
33
34
  }
34
35
  }
@@ -1,2 +0,0 @@
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);