local-traffic 0.0.56 → 0.0.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/localTraffic.js +1 -1
- package/index.ts +88 -58
- package/package.json +1 -1
package/dist/localTraffic.js
CHANGED
|
@@ -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"),c=require("process");var d,p,u;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(d||(d={})),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),f={mapping:{"/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let g,y,v=[];const b=e=>e===d.ERROR?"error":e===d.WARNING?"warning":"info",R=(e,t,n)=>{const o=(null==g?void 0:g.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?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null==g?void 0:g.simpleLogs)} ${(null==g?void 0:g.simpleLogs)?o:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹[0m`:e}`),O({event:o,level:b(t)})},O=e=>{if(!v.length)return;const t=JSON.stringify(e),n=Array(4).fill(0).map((()=>Math.floor(256*Math.random()))),o=[...t.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,t.length),s=t.length<126?Buffer.from(Uint8Array.from([129,128+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,254]).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),l=Buffer.concat([s,a,i]);v.forEach((e=>{try{e.write(l)}catch(e){}}))},w=e=>{R(`[48;5;52m⎸${p.PORT} ${e.port.toString().padStart(5)} [48;5;53m⎸${p.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?p.REWRITE:" "}⎹⎸${p.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?p.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${p.RULES}${Object.keys(g.mapping).length.toString().padStart(3)}⎹[48;5;56m⎸${g.websocket?p.WEBSOCKET:p.NO}⎹[48;5;57m⎸${g.simpleLogs?p.NO:p.COLORED}⎹[48;5;93m⎸${g.disableWebSecurity?p.NO:p.SHIELD}⎹[0m`)},$=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(m,((n,o)=>{n&&!t&&R("config error. Using default value",d.ERROR,p.ERROR_1);try{g=Object.assign({},f,JSON.parse((o||"{}").toString()))}catch(t){return R("config syntax incorrect, aborting",d.ERROR,p.ERROR_2),g=g||Object.assign({},f),void e(g)}g.mapping[""]||R('default mapping "" not provided.',d.WARNING,p.ERROR_3),n&&"ENOENT"===n.code&&t&&m===h?(0,s.writeFile)(m,JSON.stringify(f),(t=>{t?R("config file NOT created",d.ERROR,p.ERROR_4):R("config file created",d.INFO,p.COLORED),e(g)})):e(g)})))).then((()=>{t&&(0,s.watchFile)(m,E)}))})),E=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},g);if(yield $(!1),isNaN(g.port)||g.port>65535||g.port<0)return g=e,void R("port number invalid. Not refreshing",d.ERROR,p.PORT);if("object"!=typeof g.mapping)return g=e,void R("mapping should be an object. Aborting",d.ERROR,p.ERROR_5);if(g.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&R(`request body url ${g.replaceRequestBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&R(`response body url ${g.replaceResponseBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&R(`http/2 ${g.dontUseHttp2Downstream?"de":""}activated downstream`,d.INFO,p.OUTBOUND),g.disableWebSecurity!==e.disableWebSecurity&&R(`web security ${g.disableWebSecurity?"de":""}activated`,d.INFO,p.SHIELD),g.websocket!==e.websocket&&R(`websocket ${g.websocket?"":"de"}activated`,d.INFO,p.WEBSOCKET),g.simpleLogs!==e.simpleLogs&&R("simple logs "+(g.simpleLogs?"on":"off"),d.INFO,p.COLORED),Object.keys(g.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&R(`${Object.keys(g.mapping).length.toString().padStart(5)} loaded mapping rules`,d.INFO,p.RULES),g.port!==e.port&&R(`port changed from ${e.port} to ${g.port}`,d.INFO,p.PORT),g.ssl&&!e.ssl&&R("ssl configuration added",d.INFO,p.INBOUND),!g.ssl&&e.ssl&&R("ssl configuration removed",d.INFO,p.INBOUND),g.port!==e.port||JSON.stringify(g.ssl)!==JSON.stringify(e.ssl)){R("restarting server",d.INFO,p.RESTART),yield Promise.all(v.map((e=>new Promise((t=>e.end(t)))))),v=[];(yield Promise.race([new Promise((e=>y?y.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||R("error during restart (websockets ?)",d.WARNING,p.RESTART),j()}else w(g)})),N=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),S=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,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},B=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=`${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">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 document.getElementById('table-proxy').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${g.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"' : '') + '>🔁</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">⏱</td>' +\n '<td scope="col">' + data.path + '</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>`,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/>`,H=(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 ⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${o||"<no-target-url>"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,U=(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()))?g.replaceResponseBodyUrls?Object.entries(g.mapping).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[t,n])=>n.startsWith("logs:")||""!==t&&!t.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:o.direction===u.INBOUND?e.replace(new RegExp(n.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${g.ssl?"s":""}://${o.proxyHostnameAndPort}${t.replace(/\/+$/,"")}/`):e.split(`http${g.ssl?"s":""}://${o.proxyHostnameAndPort}${t.replace(/\/+$/,"")}`).join(n)),e.toString()).split(`${o.proxyHostnameAndPort}/:`).join(`${o.proxyHostnameAndPort}:`).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${g.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${g.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)))}))})),T=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)},I=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!==g.port||g.ssl?443===g.port&&g.ssl?"":`:${g.port}`:""}`,i=new r.URL(`http${g.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[c,d]=Object.entries(Object.assign({},Object.assign({},...Object.entries(g.mapping).map((([e,t])=>({[e]:new r.URL(N("string"==typeof t?t:t.downstreamUrl))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:c,target:d}},j=()=>{y=(g.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},g.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,d,p;if(!s.headers.host&&!s.headers[":authority"])return void T(400,a,Buffer.from(H(new Error("client must supply a 'host' header"),"proxy",new r.URL(`http${g.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:h,proxyHostnameAndPort:f,url:y,path:b,key:R,target:w}=I(s);if(!w)return void T(502,a,Buffer.from(H(new Error(`No mapping found in config file ${m}`),"proxy",y)));const $=w.host.replace(RegExp(/\/+$/),""),E=`${w.href.substring(8+w.host.length)}${N(b.replace(RegExp(N(R)),""))}`.replace(/^\/*/,"/"),x=new r.URL(`${w.protocol}//${$}${E}`);let j=!g.dontUseHttp2Downstream;const C=(0,l.randomBytes)(20).toString("hex");O({level:"info",protocol:j?"HTTP/2":"HTTP1.1",method:s.method,path:E,randomId:C,uniqueHash:"N/A"});const L=c.hrtime.bigint();let A=null;const q="file:"===w.protocol?S(x):"logs:"===w.protocol?B(f):j?yield Promise.race([new Promise((e=>{const n=(0,t.connect)(x,{rejectUnauthorized:!1,protocol:w.protocol},((t,o)=>{j=j&&!!o.alpnProtocol,e(j?n:null)}));n.on("error",(e=>{A=j&&Buffer.from(H(e,"connection",y,x))}))})),new Promise((e=>setTimeout((()=>{j=!1,e(null)}),3e3)))]):null;A instanceof Buffer||(A=null);const D=null==s?void 0:s.readableLength,P=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let k=null;const W=g.replaceRequestBodyUrls||v.length;if(W){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);yield new Promise((n=>{0===P&&n(void 0),e.on("data",(e=>{t=Buffer.concat([t,e])})),e.on("end",n),e.on("error",n)})),k=yield U(t,s.headers,{proxyHostnameAndPort:f,proxyHostname:h,key:R,direction:u.OUTBOUND})}const M=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(y.hostname,$))).join(", "),e)),{})),{origin:w.href,referer:x.toString(),"content-length":null!==(p=null!==(d=null==k?void 0:k.length)&&void 0!==d?d:s.headers["content-length"])&&void 0!==p?p:0,":authority":$,":method":s.method,":path":E,":scheme":w.protocol.replace(":","")}),F=q&&!A&&q.request(M,{endStream:g.ssl?!(null==P||P):!D});null==F||F.on("error",(e=>{const t=-505===e.errno;A=Buffer.from(H(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),y,x))}));const _={hostname:w.hostname,path:E,port:w.port,protocol:w.protocol,rejectUnauthorized:!1,method:s.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(M).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:w.hostname})},z=!A&&!j&&!["file:","logs:"].includes(w.protocol)&&(yield new Promise((e=>{const t="https:"===w.protocol?(0,o.request)(_,e):(0,n.request)(_,e);t.on("error",(t=>{A=Buffer.from(H(t,"request",y,x)),e(null)})),W&&(t.write(k),t.end()),W||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(A)return void T(502,a,A);A=null,g.ssl&&P&&F&&(W&&(F.write(k),F.end()),W||(s.stream.on("data",(e=>{F.write(e)})),s.stream.on("end",(()=>F.end())))),!g.ssl&&D&&F&&(W&&(F.write(k),F.end()),W||(s.on("data",(e=>{F.write(e)})),s.on("end",(()=>F.end()))));const{outboundResponseHeaders:J}=yield new Promise((e=>F?F.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!F&&z?{outboundResponseHeaders:z.headers}:{outboundResponseHeaders:{}}))),G=J.location?new r.URL(J.location.startsWith("/")?`${w.href}${J.location.replace(/^\/+/,"")}`:J.location):null,K=G?G.href.substring(G.origin.length):null,Z=y.origin,V=G?`${Z}${K}`:null,Y=F||z,Q=null!=A?A:yield new Promise((e=>{let t=Buffer.alloc(0);Y?(Y.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),Y.on("end",(()=>{e(t)}))):e(t)})).then((e=>g.replaceResponseBodyUrls&&e.length?U(e,J,{proxyHostnameAndPort:f,proxyHostname:h,key:R,direction:u.INBOUND}).catch((e=>(T(502,a,Buffer.from(H(e,"stream",y,x))),Buffer.from("")))):e)),X=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},J),g.replaceResponseBodyUrls?{"content-length":`${Q.byteLength}`}:{}),g.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=$.split("").map(((e,t)=>$.substring(t).startsWith(".")&&$.substring(t))).filter((e=>e)),r=[$].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${y.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),V?{location:[V]}:{});try{Object.entries(X).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ee=J[":status"]||z.statusCode||200;a.writeHead(ee,g.ssl?void 0:z.statusMessage||"Status read from http/2",X),Q?a.end(Q):a.end();const te=c.hrtime.bigint();O({randomId:C,statusCode:ee,protocol:j?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(te-L)/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==k?void 0:k.toJSON()})).toString("base64")})})))).addListener("error",(e=>{"EACCES"===e.code&&R("permission denied for this port",d.ERROR,p.NO),"EADDRINUSE"===e.code&&R("port is already used. NOT started",d.ERROR,p.ERROR_6)})).addListener("listening",(()=>{w(g)})).on("upgrade",((e,t)=>{if(!g.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:s,target:a,path:i}=I(e);if("/local-traffic-logs"===i){const n=(0,l.createHash)("sha1");n.update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");return t.allowHalfOpen=!0,t.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`),t.on("close",(()=>{v=v.filter((e=>t!==e))})),void v.push(t)}const c=new r.URL(`${a.protocol}//${a.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${s}`,"g"),"").replace(/^\/*/,"/")}`),u={hostname:c.hostname,path:c.pathname,port:c.port,protocol:c.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:c.hostname},h="https:"===c.protocol?(0,o.request)(u):(0,n.request)(u);h.end(),h.on("error",(e=>{R("websocket request has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),h.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=>{R("downstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),t.on("error",(e=>{R("upstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)}))}))})).listen(g.port)};$().then(j);
|
|
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"),c=require("process");var d,p,u;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(d||(d={})),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),f={mapping:{"/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1};let g,y,v=[];const b=e=>e===d.ERROR?"error":e===d.WARNING?"warning":"info",R=(e,t,n)=>{const o=(null==g?void 0:g.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?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null==g?void 0:g.simpleLogs)} ${(null==g?void 0:g.simpleLogs)?o:t?`[48;5;${t}m⎸ ${process.stdout.isTTY&&n||""} ${e.padEnd(40)} ⎹[0m`:e}`),O({event:o,level:b(t)})},O=e=>{if(!v.length)return;const t=JSON.stringify(e),n=Array(4).fill(0).map((()=>Math.floor(256*Math.random()))),o=[...t.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,t.length),s=t.length<126?Buffer.from(Uint8Array.from([129,128+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,254]).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),l=Buffer.concat([s,a,i]);v.forEach((e=>{try{e.write(l)}catch(e){}}))},w=e=>{R(`[48;5;52m⎸${p.PORT} ${e.port.toString().padStart(5)} [48;5;53m⎸${p.OUTBOUND} ${e.dontUseHttp2Downstream?"H1.1":"H/2 "}${e.replaceRequestBodyUrls?p.REWRITE:" "}⎹⎸${p.INBOUND} ${e.ssl?"H/2 ":"H1.1"}${e.replaceResponseBodyUrls?p.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${p.RULES}${Object.keys(g.mapping).length.toString().padStart(3)}⎹[48;5;56m⎸${g.websocket?p.WEBSOCKET:p.NO}⎹[48;5;57m⎸${g.simpleLogs?p.NO:p.COLORED}⎹[48;5;93m⎸${g.disableWebSecurity?p.NO:p.SHIELD}⎹[0m`)},$=(t=!0)=>e(void 0,void 0,void 0,(function*(){return new Promise((e=>(0,s.readFile)(m,((n,o)=>{n&&!t&&R("config error. Using default value",d.ERROR,p.ERROR_1);try{g=Object.assign({},f,JSON.parse((o||"{}").toString()))}catch(t){return R("config syntax incorrect, aborting",d.ERROR,p.ERROR_2),g=g||Object.assign({},f),void e(g)}g.mapping[""]||R('default mapping "" not provided.',d.WARNING,p.ERROR_3),n&&"ENOENT"===n.code&&t&&m===h?(0,s.writeFile)(m,JSON.stringify(f),(t=>{t?R("config file NOT created",d.ERROR,p.ERROR_4):R("config file created",d.INFO,p.COLORED),e(g)})):e(g)})))).then((()=>{t&&(0,s.watchFile)(m,E)}))})),E=()=>e(void 0,void 0,void 0,(function*(){const e=Object.assign({},g);if(yield $(!1),isNaN(g.port)||g.port>65535||g.port<0)return g=e,void R("port number invalid. Not refreshing",d.ERROR,p.PORT);if("object"!=typeof g.mapping)return g=e,void R("mapping should be an object. Aborting",d.ERROR,p.ERROR_5);if(g.replaceRequestBodyUrls!==e.replaceRequestBodyUrls&&R(`request body url ${g.replaceRequestBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.replaceResponseBodyUrls!==e.replaceResponseBodyUrls&&R(`response body url ${g.replaceResponseBodyUrls?"":"NO "}rewriting`,d.INFO,p.REWRITE),g.dontUseHttp2Downstream!==e.dontUseHttp2Downstream&&R(`http/2 ${g.dontUseHttp2Downstream?"de":""}activated downstream`,d.INFO,p.OUTBOUND),g.disableWebSecurity!==e.disableWebSecurity&&R(`web security ${g.disableWebSecurity?"de":""}activated`,d.INFO,p.SHIELD),g.websocket!==e.websocket&&R(`websocket ${g.websocket?"":"de"}activated`,d.INFO,p.WEBSOCKET),g.simpleLogs!==e.simpleLogs&&R("simple logs "+(g.simpleLogs?"on":"off"),d.INFO,p.COLORED),Object.keys(g.mapping).join("\n")!==Object.keys(e.mapping).join("\n")&&R(`${Object.keys(g.mapping).length.toString().padStart(5)} loaded mapping rules`,d.INFO,p.RULES),g.port!==e.port&&R(`port changed from ${e.port} to ${g.port}`,d.INFO,p.PORT),g.ssl&&!e.ssl&&R("ssl configuration added",d.INFO,p.INBOUND),!g.ssl&&e.ssl&&R("ssl configuration removed",d.INFO,p.INBOUND),g.port!==e.port||JSON.stringify(g.ssl)!==JSON.stringify(e.ssl)){R("restarting server",d.INFO,p.RESTART),yield Promise.all(v.map((e=>new Promise((t=>e.end(t)))))),v=[];(yield Promise.race([new Promise((e=>y?y.close(e):e(void 0))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||R("error during restart (websockets ?)",d.WARNING,p.RESTART),C()}else w(g)})),N=e=>""==e?"":(0,i.normalize)(e).replace(/\\/g,"/"),S=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=`${U(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},B=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=`${U(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">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 document.getElementById('table-proxy').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${g.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"' : '') + '>🔁</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">⏱</td>' +\n '<td scope="col">' + data.path + '</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>`,t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{"response"===e&&this.events.response({Server:"local","Content-Type":"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}),U=(e,t,n)=>`<!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/>`,I=(e,t,n,o)=>`${U(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n ⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>phase</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${o||"<no-target-url>"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,T=(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()))?g.replaceResponseBodyUrls?x(e.toString(),o.direction,o.proxyHostnameAndPort).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${g.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${g.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)))}))})),x=(e,t,n)=>Object.entries(g.mapping).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[o,r])=>r.startsWith("logs:")||""!==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${g.ssl?"s":""}://${n}${o.replace(/\/+$/,"")}/`):e.split(`http${g.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)},j=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!==g.port||g.ssl?443===g.port&&g.ssl?"":`:${g.port}`:""}`,i=new r.URL(`http${g.ssl?"s":""}://${a}${e.url}`),l=i.href.substring(i.origin.length),[c,d]=Object.entries(Object.assign({},Object.assign({},...Object.entries(g.mapping).map((([e,t])=>({[e]:new r.URL(N("string"==typeof t?t:t.downstreamUrl))})))))).find((([e])=>l.match(RegExp(e.replace(/^\//,"^/")))))||[];return{proxyHostname:s,proxyHostnameAndPort:a,url:i,path:l,key:c,target:d}},C=()=>{y=(g.ssl?t.createSecureServer.bind(null,Object.assign(Object.assign({},g.ssl),{allowHTTP1:!0})):n.createServer)(((s,a)=>e(void 0,void 0,void 0,(function*(){var e,i,h,f;if(!s.headers.host&&!s.headers[":authority"])return void H(400,a,Buffer.from(I(new Error("client must supply a 'host' header"),"proxy",new r.URL(`http${g.ssl?"s":""}://unknowndomain${s.url}`))));const{proxyHostname:y,proxyHostnameAndPort:b,url:w,path:$,key:E,target:U}=j(s);if(!U)return void H(502,a,Buffer.from(I(new Error(`No mapping found in config file ${m}`),"proxy",w)));const C=U.host.replace(RegExp(/\/+$/),""),L=`${U.href.substring(8+U.host.length)}${N($.replace(RegExp(N(E)),""))}`.replace(/^\/*/,"/"),q=new r.URL(`${U.protocol}//${C}${L}`);let A=!g.dontUseHttp2Downstream;const D=(0,l.randomBytes)(20).toString("hex");O({level:"info",protocol:A?"HTTP/2":"HTTP1.1",method:s.method,path:L,randomId:D,uniqueHash:"N/A"});const P=c.hrtime.bigint();let k=null;const W="file:"===U.protocol?S(q):"logs:"===U.protocol?B(b):A?yield Promise.race([new Promise((e=>{const n=(0,t.connect)(q,{rejectUnauthorized:!1,protocol:U.protocol},((t,o)=>{A=A&&!!o.alpnProtocol,e(A?n:null)}));n.on("error",(e=>{k=A&&Buffer.from(I(e,"connection",w,q))}))})),new Promise((e=>setTimeout((()=>{A=!1,e(null)}),3e3)))]):null;k instanceof Buffer||(k=null);const M=null==s?void 0:s.readableLength,F=null===(e=null==s?void 0:s.stream)||void 0===e?void 0:e.readableLength;let _=null;const z=g.replaceRequestBodyUrls||v.length;if(z){const e=null!==(i=null==s?void 0:s.stream)&&void 0!==i?i:s;let t=Buffer.from([]);const n=!(0===F&&("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&&R(`body replacement error ${$.slice(-17)}`,d.WARNING,p.ERROR_4),_=yield T(t,s.headers,{proxyHostnameAndPort:b,proxyHostname:y,key:E,direction:u.OUTBOUND})}const G=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(w.hostname,C))).join(", "),e)),{})),{origin:U.href,referer:q.toString(),"content-length":null!==(f=null!==(h=null==_?void 0:_.length)&&void 0!==h?h:s.headers["content-length"])&&void 0!==f?f:0,":authority":C,":method":s.method,":path":L,":scheme":U.protocol.replace(":","")}),J=W&&!k&&W.request(G,{endStream:g.ssl?!(null==F||F):!M});null==J||J.on("error",(e=>{const t=-505===e.errno;k=Buffer.from(I(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),w,q))}));const K={hostname:U.hostname,path:L,port:U.port,protocol:U.protocol,rejectUnauthorized:!1,method:s.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(G).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:U.hostname})},Z=!k&&!A&&!["file:","logs:"].includes(U.protocol)&&(yield new Promise((e=>{const t="https:"===U.protocol?(0,o.request)(K,e):(0,n.request)(K,e);t.on("error",(t=>{k=Buffer.from(I(t,"request",w,q)),e(null)})),z&&(t.write(_),t.end()),z||(s.on("data",(e=>t.write(e))),s.on("end",(()=>t.end())))})));if(k)return void H(502,a,k);k=null,g.ssl&&F&&J&&(z&&(J.write(_),J.end()),z||(s.stream.on("data",(e=>{J.write(e)})),s.stream.on("end",(()=>J.end())))),!g.ssl&&M&&J&&(z&&(J.write(_),J.end()),z||(s.on("data",(e=>{J.write(e)})),s.on("end",(()=>J.end()))));const{outboundResponseHeaders:V}=yield new Promise((e=>J?J.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!J&&Z?{outboundResponseHeaders:Z.headers}:{outboundResponseHeaders:{}}))),Y=V.location?new r.URL(V.location.startsWith("/")?`${U.href}${V.location.replace(/^\/+/,"")}`:V.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")):null,Q=g.replaceResponseBodyUrls&&Y?new r.URL(x(Y.href,u.INBOUND,b).replace(/^(logs:|file:)\/+/,"")):Y,X=J||Z,ee=null!=k?k:yield new Promise((e=>{let t=Buffer.alloc(0);X?(X.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),X.on("end",(()=>{e(t)}))):e(t)})).then((e=>g.replaceResponseBodyUrls&&e.length?T(e,V,{proxyHostnameAndPort:b,proxyHostname:y,key:E,direction:u.INBOUND}).catch((e=>(H(502,a,Buffer.from(I(e,"stream",w,q))),Buffer.from("")))):e)),te=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},V),g.replaceResponseBodyUrls?{"content-length":`${ee.byteLength}`}:{}),g.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=C.split("").map(((e,t)=>C.substring(t).startsWith(".")&&C.substring(t))).filter((e=>e)),r=[C].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}),{})),Q?{location:[Q]}:{});try{Object.entries(te).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ne=V[":status"]||Z.statusCode||200;a.writeHead(ne,g.ssl?void 0:Z.statusMessage||"Status read from http/2",te),ee?a.end(ee):a.end();const oe=c.hrtime.bigint();O({randomId:D,statusCode:ne,protocol:A?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(oe-P)/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==_?void 0:_.toJSON()})).toString("base64")})})))).addListener("error",(e=>{"EACCES"===e.code&&R("permission denied for this port",d.ERROR,p.NO),"EADDRINUSE"===e.code&&R("port is already used. NOT started",d.ERROR,p.ERROR_6)})).addListener("listening",(()=>{w(g)})).on("upgrade",((e,t)=>{if(!g.websocket)return void t.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");const{key:s,target:a,path:i}=j(e);if("/local-traffic-logs"===i){const n=(0,l.createHash)("sha1");n.update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");return t.allowHalfOpen=!0,t.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`),t.on("close",(()=>{v=v.filter((e=>t!==e))})),void v.push(t)}const c=new r.URL(`${a.protocol}//${a.host}${e.url.endsWith("/_next/webpack-hmr")?e.url:e.url.replace(new RegExp(`^${s}`,"g"),"").replace(/^\/*/,"/")}`),u={hostname:c.hostname,path:c.pathname,port:c.port,protocol:c.protocol,rejectUnauthorized:!1,method:e.method,headers:e.headers,host:c.hostname},h="https:"===c.protocol?(0,o.request)(u):(0,n.request)(u);h.end(),h.on("error",(e=>{R("websocket request has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),h.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=>{R("downstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)})),t.on("error",(e=>{R("upstream socket has errored "+(e.errno?`(${e.errno})`:""),d.WARNING,p.WEBSOCKET)}))}))})).listen(g.port)};$().then(C);
|
package/index.ts
CHANGED
|
@@ -803,48 +803,18 @@ const replaceBody = async (
|
|
|
803
803
|
? uncompressedBuffer
|
|
804
804
|
: !config.replaceResponseBodyUrls
|
|
805
805
|
? uncompressedBuffer.toString()
|
|
806
|
-
:
|
|
807
|
-
.
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
new RegExp(
|
|
819
|
-
value
|
|
820
|
-
.replace(/^(file|logs):\/\//, "")
|
|
821
|
-
.replace(/[*+?^${}()|[\]\\]/g, "")
|
|
822
|
-
.replace(/^https/, "https?") + "/*",
|
|
823
|
-
"ig",
|
|
824
|
-
),
|
|
825
|
-
`http${config.ssl ? "s" : ""}://${
|
|
826
|
-
parameters.proxyHostnameAndPort
|
|
827
|
-
}${path.replace(/\/+$/, "")}/`,
|
|
828
|
-
)
|
|
829
|
-
: inProgress
|
|
830
|
-
.split(
|
|
831
|
-
`http${config.ssl ? "s" : ""}://${
|
|
832
|
-
parameters.proxyHostnameAndPort
|
|
833
|
-
}${path.replace(/\/+$/, "")}`,
|
|
834
|
-
)
|
|
835
|
-
.join(value),
|
|
836
|
-
uncompressedBuffer.toString(),
|
|
837
|
-
)
|
|
838
|
-
.split(`${parameters.proxyHostnameAndPort}/:`)
|
|
839
|
-
.join(`${parameters.proxyHostnameAndPort}:`)
|
|
840
|
-
.replace(
|
|
841
|
-
/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,
|
|
842
|
-
`?protocol=ws${config.ssl ? "s" : ""}%3A&hostname=${
|
|
843
|
-
parameters.proxyHostname
|
|
844
|
-
}&port=${config.port}&pathname=${encodeURIComponent(
|
|
845
|
-
parameters.key.replace(/\/+$/, ""),
|
|
846
|
-
)}`,
|
|
847
|
-
);
|
|
806
|
+
: replaceTextUsingMapping(
|
|
807
|
+
uncompressedBuffer.toString(),
|
|
808
|
+
parameters.direction,
|
|
809
|
+
parameters.proxyHostnameAndPort,
|
|
810
|
+
).replace(
|
|
811
|
+
/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,
|
|
812
|
+
`?protocol=ws${config.ssl ? "s" : ""}%3A&hostname=${
|
|
813
|
+
parameters.proxyHostname
|
|
814
|
+
}&port=${config.port}&pathname=${encodeURIComponent(
|
|
815
|
+
parameters.key.replace(/\/+$/, ""),
|
|
816
|
+
)}`,
|
|
817
|
+
);
|
|
848
818
|
})
|
|
849
819
|
.then((updatedBody: Buffer | string) =>
|
|
850
820
|
(headers["content-encoding"]?.toString() ?? "")
|
|
@@ -880,6 +850,45 @@ const replaceBody = async (
|
|
|
880
850
|
);
|
|
881
851
|
}, Promise.resolve(Buffer.from(updatedBody))),
|
|
882
852
|
);
|
|
853
|
+
const replaceTextUsingMapping = (
|
|
854
|
+
text: string,
|
|
855
|
+
direction: REPLACEMENT_DIRECTION,
|
|
856
|
+
proxyHostnameAndPort: string,
|
|
857
|
+
) =>
|
|
858
|
+
Object.entries(config.mapping)
|
|
859
|
+
.map(([key, value]) => [
|
|
860
|
+
key,
|
|
861
|
+
typeof value === "string" ? value : value.replaceBody,
|
|
862
|
+
])
|
|
863
|
+
.reduce(
|
|
864
|
+
(inProgress, [path, value]) =>
|
|
865
|
+
value.startsWith("logs:") ||
|
|
866
|
+
(path !== "" && !path.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/))
|
|
867
|
+
? inProgress
|
|
868
|
+
: direction === REPLACEMENT_DIRECTION.INBOUND
|
|
869
|
+
? inProgress.replace(
|
|
870
|
+
new RegExp(
|
|
871
|
+
value
|
|
872
|
+
.replace(/^(file|logs):\/\//, "")
|
|
873
|
+
.replace(/[*+?^${}()|[\]\\]/g, "")
|
|
874
|
+
.replace(/^https/, "https?") + "/*",
|
|
875
|
+
"ig",
|
|
876
|
+
),
|
|
877
|
+
`http${
|
|
878
|
+
config.ssl ? "s" : ""
|
|
879
|
+
}://${proxyHostnameAndPort}${path.replace(/\/+$/, "")}/`,
|
|
880
|
+
)
|
|
881
|
+
: inProgress
|
|
882
|
+
.split(
|
|
883
|
+
`http${
|
|
884
|
+
config.ssl ? "s" : ""
|
|
885
|
+
}://${proxyHostnameAndPort}${path.replace(/\/+$/, "")}`,
|
|
886
|
+
)
|
|
887
|
+
.join(value),
|
|
888
|
+
text,
|
|
889
|
+
)
|
|
890
|
+
.split(`${proxyHostnameAndPort}/:`)
|
|
891
|
+
.join(`${proxyHostnameAndPort}:`);
|
|
883
892
|
|
|
884
893
|
const send = (
|
|
885
894
|
code: number,
|
|
@@ -1066,14 +1075,28 @@ const start = () => {
|
|
|
1066
1075
|
(inboundRequest as IncomingMessage);
|
|
1067
1076
|
|
|
1068
1077
|
let requestBodyBuffer: Buffer = Buffer.from([]);
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1078
|
+
const requestBodyExpected = !(
|
|
1079
|
+
http2WithRequestBody === 0 &&
|
|
1080
|
+
(inboundRequest.headers["content-length"] === "0" ||
|
|
1081
|
+
inboundRequest.headers["content-length"] === undefined)
|
|
1082
|
+
);
|
|
1083
|
+
await Promise.race([
|
|
1084
|
+
new Promise(resolve => setTimeout(resolve, 10000)),
|
|
1085
|
+
new Promise(resolve => {
|
|
1086
|
+
if (!requestBodyExpected) resolve(void 0);
|
|
1087
|
+
requestBodyReadable.on("data", chunk => {
|
|
1088
|
+
requestBodyBuffer = Buffer.concat([requestBodyBuffer, chunk]);
|
|
1089
|
+
});
|
|
1090
|
+
requestBodyReadable.on("end", resolve);
|
|
1091
|
+
requestBodyReadable.on("error", resolve);
|
|
1092
|
+
}),
|
|
1093
|
+
]);
|
|
1094
|
+
if (requestBodyExpected && !requestBodyBuffer.length)
|
|
1095
|
+
log(
|
|
1096
|
+
`body replacement error ${path.slice(-17)}`,
|
|
1097
|
+
LogLevel.WARNING,
|
|
1098
|
+
EMOJIS.ERROR_4,
|
|
1099
|
+
);
|
|
1077
1100
|
requestBody = await replaceBody(
|
|
1078
1101
|
requestBodyBuffer,
|
|
1079
1102
|
inboundRequest.headers,
|
|
@@ -1247,7 +1270,7 @@ const start = () => {
|
|
|
1247
1270
|
}),
|
|
1248
1271
|
);
|
|
1249
1272
|
|
|
1250
|
-
const
|
|
1273
|
+
const redirectUrl = !outboundResponseHeaders["location"]
|
|
1251
1274
|
? null
|
|
1252
1275
|
: new URL(
|
|
1253
1276
|
outboundResponseHeaders["location"].startsWith("/")
|
|
@@ -1255,13 +1278,20 @@ const start = () => {
|
|
|
1255
1278
|
/^\/+/,
|
|
1256
1279
|
``,
|
|
1257
1280
|
)}`
|
|
1258
|
-
: outboundResponseHeaders["location"]
|
|
1281
|
+
: outboundResponseHeaders["location"]
|
|
1282
|
+
.replace(/^file:\/+/, "file:///")
|
|
1283
|
+
.replace(/^(http)(s?):\/+/, "$1$2://"),
|
|
1259
1284
|
);
|
|
1260
|
-
const
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1285
|
+
const replacedRedirectUrl =
|
|
1286
|
+
!config.replaceResponseBodyUrls || !redirectUrl
|
|
1287
|
+
? redirectUrl
|
|
1288
|
+
: new URL(
|
|
1289
|
+
replaceTextUsingMapping(
|
|
1290
|
+
redirectUrl.href,
|
|
1291
|
+
REPLACEMENT_DIRECTION.INBOUND,
|
|
1292
|
+
proxyHostnameAndPort,
|
|
1293
|
+
).replace(/^(logs:|file:)\/+/, ""),
|
|
1294
|
+
);
|
|
1265
1295
|
|
|
1266
1296
|
// phase : response body
|
|
1267
1297
|
const payloadSource = outboundExchange || outboundHttp1Response;
|
|
@@ -1357,7 +1387,7 @@ const start = () => {
|
|
|
1357
1387
|
acc[key] = (acc[key] || []).concat(transformedValue);
|
|
1358
1388
|
return acc;
|
|
1359
1389
|
}, {}),
|
|
1360
|
-
...(
|
|
1390
|
+
...(replacedRedirectUrl ? { location: [replacedRedirectUrl] } : {}),
|
|
1361
1391
|
};
|
|
1362
1392
|
try {
|
|
1363
1393
|
Object.entries(responseHeaders).forEach(
|