forked from Stuk/server-replay
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·238 lines (204 loc) · 8.16 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
* Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var _fs = require("fs");
var https = require('https');
var URL = require("url");
var PATH = require("path");
var mime = require("mime");
var heuristic = require("./heuristic");
var httpProxy = require('http-proxy');
exports = module.exports = serverReplay;
var httpsOptions = {
key: _fs.readFileSync('key.pem'),
cert: _fs.readFileSync('cert.pem')
}
var proxyServer = httpProxy.createProxyServer({secure: false})
proxyServer.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
console.error(`Something went wrong with proxying ${req.url}: ${err.message}`)
res.end('Something went wrong. And we are reporting a custom error message.');
});
function serverReplay(har, options) {
var server = https.createServer(httpsOptions, makeRequestListener(har.log.entries, options));
server.listen(options.port);
}
// Export for testing
exports.makeRequestListener = makeRequestListener;
function makeRequestListener(entries, options) {
var config = options.config;
var proxy = options.proxy
var resolvePath = options.resolvePath;
var debug = options.debug;
// for mocking
var fs = options.fs || _fs;
return async function (request, response) {
if (debug) {
console.log(request.method, request.url);
}
request.parsedUrl = URL.parse(request.url, true);
if (config.features.ratePost && request.method === "POST" && request.headers["content-type"] === "application/json") {
const buffers = []
for await (const chunk of request) {
buffers.push(chunk);
}
const data = Buffer.concat(buffers).toString()
try {
request.postData = JSON.parse(data)
} catch (e) {
console.error('Could not parse POST data', data)
}
}
var entry = heuristic(entries, request, options);
var localPath;
for (var i = 0; i < config.mappings.length; i++) {
if ((localPath = config.mappings[i](request.url))) {
localPath = PATH.resolve(resolvePath, localPath);
break;
}
}
if (localPath) {
// If there's local content, but no entry in the HAR, create a shim
// entry so that we can still serve the file
if (!entry) {
var mimeType = mime.lookup(localPath);
entry = {
response: {
status: 200,
headers: [{
name: 'Content-Type',
value: mimeType
}],
content: {
mimeType: mimeType
}
}
};
}
// If we have a file location, then try and read it. If that fails, then
// return a 404
fs.readFile(localPath, function (err, content) {
if (err) {
console.error("Error: Could not read", localPath, "requested from", request.url);
serveError(request.url, response, null, {localPath});
return;
}
entry.response.content.buffer = content;
serveEntry(request, response, entry, config);
});
} else {
if (!serveError(request.url, response, entry && entry.response, {proxy, request, config})) {
serveEntry(request, response, entry, config);
}
}
};
}
function serveError(requestUrl, response, entryResponse, {localPath, proxy, request, config} = {}) {
if (!entryResponse || (config && config.ignore(requestUrl))) {
if (proxy) {
console.log("Proxying:", requestUrl);
proxyServer.web(request, response, { target: proxy });
return true
}
console.log("Not found:", requestUrl);
response.writeHead(404, "Not found", {"content-type": "text/plain"});
response.end("404 Not found" + (localPath ? ", while looking for " + localPath : ""));
return true;
}
// A resource can be blocked by the client recording the HAR file. Chrome
// adds an `_error` string property to the response object. Also try
// detecting missing status for other generators.
if (entryResponse._error || !entryResponse.status) {
var error = entryResponse._error ? JSON.stringify(entryResponse._error) : "Missing status";
response.writeHead(410, error, {"content-type": "text/plain"});
response.end(
"HAR response error: " + error +
"\n\nThis resource might have been blocked by the client recording the HAR file. For example, by the AdBlock or Ghostery extensions."
);
return true;
}
return false;
}
function serveHeaders(response, entryResponse) {
// Not really a header, but...
response.statusCode = (entryResponse.status === 304) ? 200 : entryResponse.status;
for (var h = 0; h < entryResponse.headers.length; h++) {
var name = entryResponse.headers[h].name;
var value = entryResponse.headers[h].value;
if (name.toLowerCase() === "content-length") continue;
if (name.toLowerCase() === "content-encoding") continue;
if (name.toLowerCase() === "cache-control") continue;
if (name.toLowerCase() === "pragma") continue;
var existing = response.getHeader(name);
if (existing) {
if (Array.isArray(existing)) {
response.setHeader(name, existing.concat(value));
} else {
response.setHeader(name, [existing, value]);
}
} else {
response.setHeader(name, value);
}
}
// Try to make sure nothing is cached
response.setHeader("cache-control", "no-cache, no-store, must-revalidate");
response.setHeader("pragma", "no-cache");
}
function manipulateContent(request, entry, replacements) {
var entryResponse = entry.response;
var content;
if (isBinary(entryResponse)) {
content = entryResponse.content.buffer;
} else {
content = entryResponse.content.buffer.toString("utf8");
var context = {
request: request,
entry: entry
};
replacements.forEach(function (replacement) {
content = replacement(content, context);
});
}
if (entryResponse.content.size > 0 && !content) {
console.error("Error:", entry.request.url, "has a non-zero size, but there is no content in the HAR file");
}
return content;
}
function isBase64Encoded(entryResponse) {
if (!entryResponse.content.text) {
return false;
}
var base64Size = entryResponse.content.size / 0.75;
var contentSize = entryResponse.content.text.length;
return contentSize && contentSize >= base64Size && contentSize <= base64Size + 4;
}
// FIXME
function isBinary(entryResponse) {
return /^image\/|application\/octet-stream/.test(entryResponse.content.mimeType);
}
function serveEntry(request, response, entry, config) {
var entryResponse = entry.response;
serveHeaders(response, entryResponse);
if (!entryResponse.content.buffer) {
if (isBase64Encoded(entryResponse)) {
entryResponse.content.buffer = new Buffer(entryResponse.content.text || "", 'base64');
} else {
entryResponse.content.buffer = new Buffer(entryResponse.content.text || "", 'utf8');
}
}
response.end(manipulateContent(request, entry, config.replacements));
}