-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.js
64 lines (52 loc) · 1.68 KB
/
server.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
var http = Npm.require('http');
var templateText = Assets.getText('lib/inject.html');
var injectDataTemplate = _.template(templateText);
// custome API
InjectData.pushData = function pushData(res, key, value) {
if(!res._injectPayload) {
res._injectPayload = {};
}
res._injectPayload[key] = value;
InjectData._hijackWriteIfNeeded(res);
};
InjectData.getData = function getData(res, key) {
if(res._injectPayload) {
return _.clone(res._injectPayload[key]);
} else {
return null;
}
};
InjectData._hijackWriteIfNeeded = function(res) {
if(res._writeHijacked) {
return;
}
res._writeHijacked = true;
var originalWrite = res.write;
res.write = function(chunk, encoding) {
var condition =
res._injectPayload && !res._injected &&
encoding === undefined &&
/<!DOCTYPE html>/.test(chunk);
if(condition) {
// if cors headers included if may cause some security holes
// so we simply turn off injecting if we detect an cors header
// read more: http://goo.gl/eGwb4e
if(res._headers['access-control-allow-origin']) {
var warnMessage =
'warn: injecting data turned off due to CORS headers. ' +
'read more: http://goo.gl/eGwb4e';
console.warn(warnMessage);
originalWrite.call(res, chunk, encoding);
return;
}
// inject data
var data = InjectData._encode(res._injectPayload);
var injectHtml = injectDataTemplate({data: data});
// if this is a buffer, convert it to string
chunk = chunk.toString();
chunk = chunk.replace('<script', injectHtml + '<script');
res._injected = true;
}
originalWrite.call(res, chunk, encoding);
};
};