Skip to content

Commit

Permalink
Add support for manual SSL certs/keys (#520)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattdodge authored and leo committed Sep 26, 2019
1 parent 2316382 commit 70d957b
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions bin/serve.js
Expand Up @@ -2,6 +2,7 @@

// Native
const http = require('http');
const https = require('https');
const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
Expand Down Expand Up @@ -89,6 +90,10 @@ const getHelp = () => chalk`
-S, --symlinks Resolve symlinks instead of showing 404 errors
--ssl-cert Optional path to an SSL/TLS certificate to serve with HTTPS
--ssl-key Optional path to the SSL/TLS certificate\'s private key
{bold ENDPOINTS}
Listen endpoints (specified by the {bold --listen} or {bold -l} options above) instruct {cyan serve}
Expand Down Expand Up @@ -175,14 +180,22 @@ const startEndpoint = (endpoint, config, args, previous) => {
const {isTTY} = process.stdout;
const clipboard = args['--no-clipboard'] !== true;
const compress = args['--no-compression'] !== true;
const httpMode = args['--ssl-cert'] && args['--ssl-key'] ? 'https' : 'http';

const server = http.createServer(async (request, response) => {
const serverHandler = async (request, response) => {
if (compress) {
await compressionHandler(request, response);
}

return handler(request, response, config);
});
};

const server = httpMode === 'https'
? https.createServer({
key: fs.readFileSync(args['--ssl-key']),
cert: fs.readFileSync(args['--ssl-cert'])
}, serverHandler)
: http.createServer(serverHandler);

server.on('error', (err) => {
if (err.code === 'EADDRINUSE' && endpoint.length === 1 && !isNaN(endpoint[0])) {
Expand All @@ -207,8 +220,8 @@ const startEndpoint = (endpoint, config, args, previous) => {
const address = details.address === '::' ? 'localhost' : details.address;
const ip = getNetworkAddress();

localAddress = `http://${address}:${details.port}`;
networkAddress = `http://${ip}:${details.port}`;
localAddress = `${httpMode}://${address}:${details.port}`;
networkAddress = `${httpMode}://${ip}:${details.port}`;
}

if (isTTY && process.env.NODE_ENV !== 'production') {
Expand Down Expand Up @@ -352,6 +365,8 @@ const loadConfig = async (cwd, entry, args) => {
'--no-compression': Boolean,
'--no-etag': Boolean,
'--symlinks': Boolean,
'--ssl-cert': String,
'--ssl-key': String,
'-h': '--help',
'-v': '--version',
'-l': '--listen',
Expand Down

0 comments on commit 70d957b

Please sign in to comment.