-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
204 lines (186 loc) · 5.6 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
//----------------------------------
// Imports
//----------------------------------
import * as http from 'http';
import * as net from 'net';
import puppeteer from 'puppeteer';
//----------------------------------
// Variables
//----------------------------------
const ACCEPTED_EXTENSIONS = ['html', 'htm'];
const SERVER_HOST = process.env.HOST || null;
const SERVER_PORT = process.env.PORT || 3000;
const LOG_LEVEL = process.env.LOG || 'error';
const LOGGER = {
time: () => new Date().toISOString(),
error: (msg) => {
console.log(`${LOGGER.time()} - ERROR - ${msg}`);
},
info: (msg) => {
console.log(`${LOGGER.time()} - INFO - ${msg}`);
},
log: (msg) => {
if (LOG_LEVEL === 'verbose') {
console.log(`${LOGGER.time()} - LOG - ${msg}`);
}
},
};
//---------------------------------------------------
//
// Pupppeteer Render Service
//
//---------------------------------------------------
class RenderService {
//---------------------------------------------------
//
// Initialization
//
//---------------------------------------------------
constructor() {
try {
this.server = null;
this.browser = null;
this.createBrowser().then((browser) => {
if (browser) {
this.browser = browser;
this.server = this.createServer();
} else {
LOGGER.info('Exiting as Browser could not be started..');
process.exit(1);
}
});
} catch (err) {
LOGGER.error(`Unable to create Browser/Service: ${err.message}`);
process.exit(1);
}
}
//---------------------------------------------------
//
// Server Methods
//
//---------------------------------------------------
createServer() {
const server = http.createServer();
server.on('request', this.handleServerRequest.bind(this));
server.listen(SERVER_PORT, SERVER_HOST, () => {
LOGGER.info(`Service is running on port: ${SERVER_PORT}`);
});
return server;
}
handleServerRequest(request, response) {
const { url, origin } = this.parseRequestUrls(request);
let testUrl = origin ? `${origin}/${url}` : url;
try {
testUrl = new URL(testUrl);
if (testUrl) {
if (this.ignoreRequest(url)) {
this.redirect(url, origin, response);
} else {
this.retrieveSite(url, response);
}
}
} catch (err) {
LOGGER.log(`Ignoring request for: "${url}" - ${err.message}`);
this.sendHttpStatus(400, null, response);
}
}
redirect(url, origin, response) {
if (origin) {
const newLocation = `${origin}/${url}`;
LOGGER.log(`Redirecting to: ${newLocation}`);
this.sendHttpStatus(301, { 'Location': newLocation }, response);
} else {
LOGGER.log(`Ignoring request for: "${url}"`);
this.sendHttpStatus(400, null, response);
}
}
sendHtmlResponse(html, response) {
// replace origin.casper.network references
const output = (html || '').replace(/origin\.casper\.network/gm, 'casper.network');
response.writeHead(200, { 'Content-Type': 'text/html; charset=UTF-8' });
response.end(output);
}
sendHttpStatus(status, headers, response) {
response.writeHead(status, headers);
response.end();
}
//---------------------------------------------------
//
// Puppeteer Methods
//
//---------------------------------------------------
async createBrowser() {
let browser = null;
LOGGER.info('Launching Chrome...');
try {
browser = await puppeteer.launch({
headless: 'new',
args: [
'--blink-settings=imagesEnabled=false',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--no-sandbox',
],
ignoreDefaultArgs: ["--disable-extensions"], // Optional
executablePath: "/usr/bin/google-chrome",
});
const version = await browser.version();
LOGGER.info(`${version} started..`);
} catch (err) {
LOGGER.error(err.message);
}
return browser;
}
async retrieveSite(url, response) {
let page = null;
try {
const browser = this.browser;
page = await browser.newPage();
await page.setCacheEnabled(false);
await page.setJavaScriptEnabled(true);
await page.goto(url, { timeout: 20000, waitUntil: 'networkidle0' });
const html = await page.content();
await page.close();
LOGGER.log(`Sending HTML for: ${url}`);
this.sendHtmlResponse(html, response);
} catch (err) {
LOGGER.error(`Couldn't retrieve "${url}": ${err.message}`);
if (page) {
await page.close();
page = null;
}
this.sendHttpStatus(500, null, response);
}
}
//----------------------------------
// Helpers
//----------------------------------
parseRequestUrls(request) {
const url = (request.url || '').replace(/^\//,'');
const referer = request.headers.referer;
try {
if (referer) {
const refUrl = new URL(referer.replace(/^.*\/http/, 'http').replace(/\/$/, ''));
if (!net.isIP(refUrl.hostname) && refUrl.port !== SERVER_PORT) {
return { url, origin: refUrl.origin }
}
}
} catch (err) {
LOGGER.error(`Unable to retrieve origin from referer "${referer}": ${err.message}`);
}
return { url };
}
ignoreRequest(url = '') {
const segment = (url.split('/') || []).pop();
if (segment.indexOf('.') !== -1) {
const ext = (segment.split('.') || []).pop();
return !ACCEPTED_EXTENSIONS.includes(ext);
}
return false;
}
}
try {
new RenderService();
} catch (err) {
LOGGER.error(err.message);
}