Skip to content

Instantly share code, notes, and snippets.

@e-neko
Created September 9, 2020 10:44
Show Gist options
  • Save e-neko/71e246849032fe336184bb43409f7ba5 to your computer and use it in GitHub Desktop.
Save e-neko/71e246849032fe336184bb43409f7ba5 to your computer and use it in GitHub Desktop.
Nodejs express mitm proxy stub
const express = require('express');
var proxy = require('express-http-proxy');
const cheerio = require('cheerio');
const nunjucks = require('nunjucks');
const host = 'http://hostname-or-ip/';
var app = express();
// some engine to serve own pages, not strictly necessary
nunjucks.configure('templates', {
express: app
});
app.use('/', proxy(host, {
userResDecorator: (proxyRes, proxyResData, userReq, userRes)=>{
if (/url_matcher/.test(userReq.url)){
console.log('patching');
let $ = cheerio.load(proxyResData.toString('utf8'));
$('head').append(`<script src="/inject/injected.js"></script>`);
return $.html();
}
else
return proxyResData;
},
filter: function(req, res) {
//return true to proxy, false to not proxy
return !/inject\/.+/.test(req.url);
}
}));
app.use(express.json());
// render a nunjucks template if necessary
app.get('/inject/placeholder', (req, res)=>{
res.render('placeholder.html', {templatevar: 'value'});
});
app.use('/inject', express.static('static', {setHeaders: (res, path)=>{
//allow service worker installations for server paths
if (/service_worker\.js/.test(path))
res.setHeader('Service-Worker-Allowed', '/worker_scope/path');
}}));
// run
app.listen(5000);
{
"name": "proxy stub",
"version": "1.0.0",
"description": "man in the middle http proxy stub",
"license": "MIT",
"author": "e-neko",
"dependencies": {
"body-parser": "^1.19.0",
"cheerio": "^1.0.0-rc.3",
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"express-http-proxy": "^1.6.0",
"http-proxy": "^1.18.1",
"nunjucks": "^3.2.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment