-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
188 lines (161 loc) · 5.2 KB
/
index.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
'use strict';
/**
* Usage: node index.js
*
* Act as a regular HTTP proxy, but replace or modify some responses.
*
* Used for development of front-end javascript, when all the website's
* environment can't be reproduced locally easily.
*
*/
var ok = require('assert'),
http = require('http'),
https = require('https'),
watch = require('node-watch'),
harmon = require('./vendor/harmon'),
httpProxy = require('http-proxy'),
url = require('url'),
path = require('path'),
fs = require('fs'),
underscore = require('underscore')
var _ = underscore;
_.mixin({
concat: function (arr, other) {
return _([].concat.call(arr, other || []))
}
})
var homedir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
var argv = require('optimist')
.options('c', {
alias: 'config',
default: path.join(homedir, '.magicproxyrc'),
})
.options({
alias: 'plugin',
default: [],
})
.options('p', {
alias: 'port',
})
.argv;
var defaultPlugins = [
'./replace.js',
'./fakeDir.js',
'./ui.js',
'./weinre.js',
'./empty.js',
'./markup.js',
'./cacheBreaker.js',
]
var plugins;
var pluginsInArgv = typeof argv.plugin === 'string' ? [argv.plugin] : argv.plugin
var config = {};
function updateConfig() {
/* jshint evil:true */
// TODO: set up watches and check file changed. Return early if flag not checked.
try {
config = eval('(' +
fs.readFileSync(argv.config, {encoding: 'utf-8'}) +
')');
} catch(e) {
console.log('Warning: Configuration file (%s) not found', argv.config)
}
plugins = _([])
.concat(defaultPlugins)
.concat(pluginsInArgv || [])
.concat(config.plugins || [])
.uniq()
.map(require)
}
watch(argv.config, {recursive: false}, updateConfig);
updateConfig();
function pluginAppliesHere(plugin, op, req) {
if (plugin.filter) {
return plugin.filter(op, req);
}
if (!op) { return false; }
return (
op.url && (req.url === op.url) ||
typeof op.urlRegExp === 'string' && (new RegExp(op.urlRegExp)).test(req.url) ||
op.urlRegExp instanceof RegExp && op.urlRegExp.test(req.url) || false)
}
function immediateResponse(req, res) {
return plugins.some(function (plugin) {
if (plugin.v2_proxy) {
// V2 API
return config[plugin.configName || plugin.name]
.filter(function (op) {
return pluginAppliesHere(plugin, op, req);
})
.some(function (item) {
return plugin.v2_proxy(req, res, item);
});
return plugin.v2_proxy(req, res);
} else if (plugin.proxy) {
// V1 API
return plugin.proxy(req, res, {
config: config
})
} else {
return;
ok(false, 'plugin ' + (plugin.name || JSON.stringify(plugin)) + ' does not have a "proxy_v2" or "proxy" function');
}
})
}
/* [todo] "streamingResponse"? */
function harmonResponse(req, res) {
var result = plugins
.map(function (plugin) {
if (!plugin.harmon) return null;
return (config[plugin.configName || plugin.name] || [null]).map(function (op) {
if (pluginAppliesHere(plugin, op, req)) {
return plugin.harmon(req, res, op);
}
})
})
// Remove falsy values and empty arrays, making it
// possible to return an array of actions, and letting
// plugins cancel
return _.compact(_.flatten(result));
}
var proxy = new httpProxy.RoutingProxy()
/* Listen to HTTP requests */
var proxyServer = httpProxy.createServer(function staticPlugins(req, res, next) {
/* Check if any plugin wishes to intercept and respond to the request immediately */
if (!immediateResponse(req, res)) {
return next()
}
}, function harmonPlugins(req, res, next) {
var harmonActions = harmonResponse(req, res);
if (harmonActions.length) {
return harmon(null, harmonActions)(req, res, next)
} else {
return next()
}
}, function (req, res, next) {
var parsed = url.parse(req.url)
// Protect Wordpress, Wikipedia and other sites from their naiveté
// in assuming that the URIs in the path field aren't absolute.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
req.url = req.url.replace(/.*?\/\/.*?\//, '/');
proxy.proxyRequest(req, res, {
host: parsed.hostname,
port: parsed.port || 80,
})
}).listen(argv.port || config.port || 8080)
proxy.on('proxyError', function (err, req, res) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
if (req.method !== 'HEAD') {
res.write('An error has occurred: ' + JSON.stringify(err, null, 4));
res.write('\n')
res.write('\n')
res.write('So yeah you can\'t go to your dear URL, ' + JSON.stringify(req.url) + ' lol')
}
try { res.end() }
catch (ex) { console.error("res.end error: %s", ex.message) }
})
// Testing hooks
module.exports = {
plugins: plugins,
proxyServer: proxyServer,
}