UNPKG

10.7 kBJavaScriptView Raw
1/**
2 * Copyright 2013-2022 the PM2 project authors. All rights reserved.
3 * Use of this source code is governed by a license that
4 * can be found in the LICENSE file.
5 */
6'use strict';
7
8var fs = require('fs');
9var http = require('http');
10var url = require('url');
11var path = require('path');
12var debug = require('debug')('pm2:serve');
13
14var probe = require('@pm2/io');
15var errorMeter = probe.meter({
16 name : '404/sec',
17 samples : 1,
18 timeframe : 60
19})
20/**
21 * list of supported content types.
22 */
23var contentTypes = {
24 '3gp': 'video/3gpp',
25 'a': 'application/octet-stream',
26 'ai': 'application/postscript',
27 'aif': 'audio/x-aiff',
28 'aiff': 'audio/x-aiff',
29 'asc': 'application/pgp-signature',
30 'asf': 'video/x-ms-asf',
31 'asm': 'text/x-asm',
32 'asx': 'video/x-ms-asf',
33 'atom': 'application/atom+xml',
34 'au': 'audio/basic',
35 'avi': 'video/x-msvideo',
36 'bat': 'application/x-msdownload',
37 'bin': 'application/octet-stream',
38 'bmp': 'image/bmp',
39 'bz2': 'application/x-bzip2',
40 'c': 'text/x-c',
41 'cab': 'application/vnd.ms-cab-compressed',
42 'cc': 'text/x-c',
43 'chm': 'application/vnd.ms-htmlhelp',
44 'class': 'application/octet-stream',
45 'com': 'application/x-msdownload',
46 'conf': 'text/plain',
47 'cpp': 'text/x-c',
48 'crt': 'application/x-x509-ca-cert',
49 'css': 'text/css',
50 'csv': 'text/csv',
51 'cxx': 'text/x-c',
52 'deb': 'application/x-debian-package',
53 'der': 'application/x-x509-ca-cert',
54 'diff': 'text/x-diff',
55 'djv': 'image/vnd.djvu',
56 'djvu': 'image/vnd.djvu',
57 'dll': 'application/x-msdownload',
58 'dmg': 'application/octet-stream',
59 'doc': 'application/msword',
60 'dot': 'application/msword',
61 'dtd': 'application/xml-dtd',
62 'dvi': 'application/x-dvi',
63 'ear': 'application/java-archive',
64 'eml': 'message/rfc822',
65 'eps': 'application/postscript',
66 'exe': 'application/x-msdownload',
67 'f': 'text/x-fortran',
68 'f77': 'text/x-fortran',
69 'f90': 'text/x-fortran',
70 'flv': 'video/x-flv',
71 'for': 'text/x-fortran',
72 'gem': 'application/octet-stream',
73 'gemspec': 'text/x-script.ruby',
74 'gif': 'image/gif',
75 'gz': 'application/x-gzip',
76 'h': 'text/x-c',
77 'hh': 'text/x-c',
78 'htm': 'text/html',
79 'html': 'text/html',
80 'ico': 'image/vnd.microsoft.icon',
81 'ics': 'text/calendar',
82 'ifb': 'text/calendar',
83 'iso': 'application/octet-stream',
84 'jar': 'application/java-archive',
85 'java': 'text/x-java-source',
86 'jnlp': 'application/x-java-jnlp-file',
87 'jpeg': 'image/jpeg',
88 'jpg': 'image/jpeg',
89 'js': 'application/javascript',
90 'json': 'application/json',
91 'log': 'text/plain',
92 'm3u': 'audio/x-mpegurl',
93 'm4v': 'video/mp4',
94 'man': 'text/troff',
95 'mathml': 'application/mathml+xml',
96 'mbox': 'application/mbox',
97 'mdoc': 'text/troff',
98 'me': 'text/troff',
99 'mid': 'audio/midi',
100 'midi': 'audio/midi',
101 'mime': 'message/rfc822',
102 'mml': 'application/mathml+xml',
103 'mng': 'video/x-mng',
104 'mov': 'video/quicktime',
105 'mp3': 'audio/mpeg',
106 'mp4': 'video/mp4',
107 'mp4v': 'video/mp4',
108 'mpeg': 'video/mpeg',
109 'mpg': 'video/mpeg',
110 'ms': 'text/troff',
111 'msi': 'application/x-msdownload',
112 'odp': 'application/vnd.oasis.opendocument.presentation',
113 'ods': 'application/vnd.oasis.opendocument.spreadsheet',
114 'odt': 'application/vnd.oasis.opendocument.text',
115 'ogg': 'application/ogg',
116 'p': 'text/x-pascal',
117 'pas': 'text/x-pascal',
118 'pbm': 'image/x-portable-bitmap',
119 'pdf': 'application/pdf',
120 'pem': 'application/x-x509-ca-cert',
121 'pgm': 'image/x-portable-graymap',
122 'pgp': 'application/pgp-encrypted',
123 'pkg': 'application/octet-stream',
124 'pl': 'text/x-script.perl',
125 'pm': 'text/x-script.perl-module',
126 'png': 'image/png',
127 'pnm': 'image/x-portable-anymap',
128 'ppm': 'image/x-portable-pixmap',
129 'pps': 'application/vnd.ms-powerpoint',
130 'ppt': 'application/vnd.ms-powerpoint',
131 'ps': 'application/postscript',
132 'psd': 'image/vnd.adobe.photoshop',
133 'py': 'text/x-script.python',
134 'qt': 'video/quicktime',
135 'ra': 'audio/x-pn-realaudio',
136 'rake': 'text/x-script.ruby',
137 'ram': 'audio/x-pn-realaudio',
138 'rar': 'application/x-rar-compressed',
139 'rb': 'text/x-script.ruby',
140 'rdf': 'application/rdf+xml',
141 'roff': 'text/troff',
142 'rpm': 'application/x-redhat-package-manager',
143 'rss': 'application/rss+xml',
144 'rtf': 'application/rtf',
145 'ru': 'text/x-script.ruby',
146 's': 'text/x-asm',
147 'sgm': 'text/sgml',
148 'sgml': 'text/sgml',
149 'sh': 'application/x-sh',
150 'sig': 'application/pgp-signature',
151 'snd': 'audio/basic',
152 'so': 'application/octet-stream',
153 'svg': 'image/svg+xml',
154 'svgz': 'image/svg+xml',
155 'swf': 'application/x-shockwave-flash',
156 't': 'text/troff',
157 'tar': 'application/x-tar',
158 'tbz': 'application/x-bzip-compressed-tar',
159 'tcl': 'application/x-tcl',
160 'tex': 'application/x-tex',
161 'texi': 'application/x-texinfo',
162 'texinfo': 'application/x-texinfo',
163 'text': 'text/plain',
164 'tif': 'image/tiff',
165 'tiff': 'image/tiff',
166 'torrent': 'application/x-bittorrent',
167 'tr': 'text/troff',
168 'txt': 'text/plain',
169 'vcf': 'text/x-vcard',
170 'vcs': 'text/x-vcalendar',
171 'vrml': 'model/vrml',
172 'war': 'application/java-archive',
173 'wav': 'audio/x-wav',
174 'wma': 'audio/x-ms-wma',
175 'wmv': 'video/x-ms-wmv',
176 'wmx': 'video/x-ms-wmx',
177 'wrl': 'model/vrml',
178 'wsdl': 'application/wsdl+xml',
179 'xbm': 'image/x-xbitmap',
180 'xhtml': 'application/xhtml+xml',
181 'xls': 'application/vnd.ms-excel',
182 'xml': 'application/xml',
183 'xpm': 'image/x-xpixmap',
184 'xsl': 'application/xml',
185 'xslt': 'application/xslt+xml',
186 'yaml': 'text/yaml',
187 'yml': 'text/yaml',
188 'zip': 'application/zip',
189 'woff': 'application/font-woff',
190 'woff2': 'application/font-woff',
191 'otf': 'application/font-sfnt',
192 'otc': 'application/font-sfnt',
193 'ttf': 'application/font-sfnt'
194};
195
196var options = {
197 port: process.env.PM2_SERVE_PORT || process.argv[3] || 8080,
198 host: process.env.PM2_SERVE_HOST || process.argv[4] || '0.0.0.0',
199 path: path.resolve(process.env.PM2_SERVE_PATH || process.argv[2] || '.'),
200 spa: process.env.PM2_SERVE_SPA === 'true',
201 homepage: process.env.PM2_SERVE_HOMEPAGE || '/index.html',
202 basic_auth: process.env.PM2_SERVE_BASIC_AUTH === 'true' ? {
203 username: process.env.PM2_SERVE_BASIC_AUTH_USERNAME,
204 password: process.env.PM2_SERVE_BASIC_AUTH_PASSWORD
205 } : null,
206 monitor: process.env.PM2_SERVE_MONITOR
207};
208
209if (typeof options.port === 'string') {
210 options.port = parseInt(options.port) || 8080
211}
212
213if (typeof options.monitor === 'string' && options.monitor !== '') {
214 try {
215 let fileContent = fs.readFileSync(path.join(process.env.PM2_HOME, 'agent.json5')).toString()
216 // Handle old configuration with json5
217 fileContent = fileContent.replace(/\s(\w+):/g, '"$1":')
218 // parse
219 let conf = JSON.parse(fileContent)
220 options.monitorBucket = conf.public_key
221 } catch (e) {
222 console.log('Interaction file does not exist')
223 }
224}
225
226// start an HTTP server
227http.createServer(function (request, response) {
228 if (options.basic_auth) {
229 if (!request.headers.authorization || request.headers.authorization.indexOf('Basic ') === -1) {
230 return sendBasicAuthResponse(response)
231 }
232
233 var user = parseBasicAuth(request.headers.authorization)
234 if (user.username !== options.basic_auth.username || user.password !== options.basic_auth.password) {
235 return sendBasicAuthResponse(response)
236 }
237 }
238
239 serveFile(request.url, request, response);
240
241}).listen(options.port, options.host, function (err) {
242 if (err) {
243 console.error(err);
244 process.exit(1);
245 }
246 console.log('Exposing %s directory on %s:%d', options.path, options.host, options.port);
247});
248
249function serveFile(uri, request, response) {
250 var file = decodeURIComponent(url.parse(uri || request.url).pathname);
251
252 if (file === '/' || file === '') {
253 file = options.homepage;
254 request.wantHomepage = true;
255 }
256 var filePath = path.resolve(options.path + file);
257
258 // since we call filesystem directly so we need to verify that the
259 // url doesn't go outside the serve path
260 if (filePath.indexOf(options.path) !== 0) {
261 response.writeHead(403, { 'Content-Type': 'text/html' });
262 return response.end('403 Forbidden');
263 }
264
265 var contentType = contentTypes[filePath.split('.').pop().toLowerCase()] || 'text/plain';
266
267 fs.readFile(filePath, function (error, content) {
268 if (error) {
269 if ((!options.spa || file === options.homepage)) {
270 console.error('[%s] Error while serving %s with content-type %s : %s',
271 new Date(), filePath, contentType, error.message || error);
272 }
273 errorMeter.mark();
274 if (error.code === 'ENOENT') {
275 if (options.spa && !request.wantHomepage) {
276 request.wantHomepage = true;
277 return serveFile(`/${path.basename(file)}`, request, response);
278 } else if (options.spa && file !== options.homepage) {
279 return serveFile(options.homepage, request, response);
280 }
281 fs.readFile(options.path + '/404.html', function (err, content) {
282 content = err ? '404 Not Found' : content;
283 response.writeHead(404, { 'Content-Type': 'text/html' });
284 return response.end(content, 'utf-8');
285 });
286 return;
287 }
288 response.writeHead(500);
289 return response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
290 }
291
292 // Add CORS headers to allow browsers to fetch data directly
293 response.writeHead(200, {
294 'Content-Type': contentType,
295 'Access-Control-Allow-Origin': '*',
296 'Access-Control-Allow-Methods': 'GET'
297 });
298 if (options.monitorBucket && contentType === 'text/html') {
299 content = content.toString().replace('</body>', `
300<script>
301;(function (b,e,n,o,i,t) {
302 b[o]=b[o]||function(f){(b[o].c=b[o].c||[]).push(f)};
303 t=e.createElement(i);e=e.getElementsByTagName(i)[0];
304 t.async=1;t.src=n;e.parentNode.insertBefore(t,e);
305}(window,document,'https://apm.pm2.io/pm2-io-apm-browser.v1.js','pm2Ready','script'))
306
307pm2Ready(function(apm) {
308 apm.setBucket('${options.monitorBucket}')
309 apm.setApplication('${options.monitor}')
310 apm.reportTimings()
311 apm.reportIssues()
312})
313</script>
314</body>
315`);
316 }
317 response.end(content, 'utf-8');
318 debug('[%s] Serving %s with content-type %s', Date.now(), filePath, contentType);
319 });
320}
321
322function parseBasicAuth(auth) {
323 // auth is like `Basic Y2hhcmxlczoxMjM0NQ==`
324 var tmp = auth.split(' ');
325
326 var buf = Buffer.from(tmp[1], 'base64');
327 var plain = buf.toString();
328
329 var creds = plain.split(':');
330 return {
331 username: creds[0],
332 password: creds[1]
333 }
334}
335
336function sendBasicAuthResponse(response) {
337 response.writeHead(401, {
338 'Content-Type': 'text/html',
339 'WWW-Authenticate': 'Basic realm="Authentication service"'
340 });
341 return response.end('401 Unauthorized');
342}