-
Notifications
You must be signed in to change notification settings - Fork 4
/
mitm.js
48 lines (39 loc) · 1.05 KB
/
mitm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var Mitm = require("mitm")
var Router = require("express").Router
var parseBody = require("body-parser").json()
exports = module.exports = function() {
beforeEach(exports.listen)
afterEach(exports.close)
}
exports.listen = function() {
this.mitm = Mitm()
this.mitm.on("connect", bypassLocalhost)
// Using setImmediate for intercept checks failed when using Express Router.
this.mitm.on("request", setTimeout.bind(null, checkIntercept, 0))
}
exports.router = function() {
this.router = Router().use(parseBody)
this.mitm.on("request", route.bind(null, this.router))
}
exports.close = function() {
this.mitm.disable()
}
exports.route = route
function route(router, req, res) {
router(req, res, function(err) {
if (err == null) return
res.writeHead(502)
throw err
})
}
function checkIntercept(req, res) {
if (res.headersSent) return
res.statusCode = 504
res.statusMessage = "Not Intercepted: " + req.method + " " + req.url
res.end()
}
function bypassLocalhost(socket, opts) {
switch (opts.host) {
case "localhost": socket.bypass(); break
}
}