certbot-webroot/certbot-webroot.js

73 lines
2.3 KiB
JavaScript

// certbot_webroot.js
// writted by Benoit LORAND <benoit.lorand@blorand.org>
//
// webservice help certbot when using webroot
// Could be behind a reverse proxy (Apache, Nginx, haproxy) who do basic authentication
//
// inspired from https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http
//
"use strict";
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = Number(process.env.NODE_PORT) || 9000;
const listenip = process.env.NODE_LISTEN_IP || '127.0.0.1';
const base_dir = './data';
http.createServer(function (req, res) {
// parse URL
const parsedUrl = url.parse(req.url);
// extract URL path
let pathname = `${parsedUrl.pathname}`;
// based on the URL path, extract the file extention. e.g. .js, .doc, ...
const ext = path.parse(pathname).ext;
// maps file extention to MIME typere
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
fs.exists(base_dir + pathname, function (exist) {
if(!exist) {
// if the file is not found, return 404
console.log(`certbot_validation_fqdn : ${req.method} ${req.url} - 404`);
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// if is a directory search for index file matching the extention
if (fs.statSync(base_dir + pathname).isDirectory()) pathname += '/index' + ext;
// read file from file system
fs.readFile(base_dir + pathname, function(err, data){
if(err){
console.log(`certbot_validation_fqdn : ${req.method} ${req.url} - 500`);
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
// if the file is found, set Content-type and send data
console.log(`certbot_validation_fqdn : ${req.method} ${req.url} - 200`);
res.setHeader('Content-type', map[ext] || 'text/plain' );
res.end(data);
}
});
});
}).listen(parseInt(port, listenip));
console.log(`Server listening on port ${listenip}:${port}`);