Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for manual SSL certs/keys #520

Merged
merged 1 commit into from Sep 26, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -85,6 +86,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 @@ -171,14 +176,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 @@ -203,8 +216,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 @@ -344,6 +357,8 @@ const loadConfig = async (cwd, entry, args) => {
'--no-clipboard': Boolean,
'--no-compression': Boolean,
'--symlinks': Boolean,
'--ssl-cert': String,
'--ssl-key': String,
'-h': '--help',
'-v': '--version',
'-l': '--listen',
Expand Down