Skip to content

Commit

Permalink
Add support for PFX or PKCS12 encoded certificates
Browse files Browse the repository at this point in the history
Add support for PFX or PKCS12 encoded certificates
  • Loading branch information
schemburkar committed Jul 11, 2022
1 parent 2237b53 commit 8bf73f3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
2 changes: 2 additions & 0 deletions source/utilities/cli.ts
Expand Up @@ -83,8 +83,10 @@ const helpText = chalk`
-S, --symlinks Resolve symlinks instead of showing 404 errors
--ssl-cert Optional path to an SSL/TLS certificate to serve with HTTPS
{grey Supported formats: PEM (default) and PKCS12 (PFX)}
--ssl-key Optional path to the SSL/TLS certificate\'s private key
{grey Applicable only for PEM certificates}
--ssl-pass Optional path to the SSL/TLS certificate\'s passphrase
Expand Down
39 changes: 25 additions & 14 deletions source/utilities/server.ts
Expand Up @@ -62,21 +62,31 @@ export const startServer = async (
};

// Create the server.
const useSsl = args['--ssl-cert'] && args['--ssl-key'];
const httpMode = useSsl ? 'https' : 'http';

const sslCert = args['--ssl-cert'];
const sslKey = args['--ssl-key'];
const sslPass = args['--ssl-pass'];
const serverConfig =
httpMode === 'https' && args['--ssl-cert'] && args['--ssl-key']
? {
key: await readFile(args['--ssl-key']),
cert: await readFile(args['--ssl-cert']),
passphrase: sslPass ? await readFile(sslPass, 'utf8') : '',
}
: {};
const server =
httpMode === 'https'
? https.createServer(serverConfig, serverHandler)
: http.createServer(serverHandler);
const isPFXFormat = sslCert && /[.](?<extension>pfx|p12)$/.exec(sslCert);
const useSsl = sslCert && (sslKey || sslPass || isPFXFormat);

let serverConfig: http.ServerOptions | https.ServerOptions = {};
if (useSsl && sslCert && sslKey) {
// Format is PEM due to usagae of SSL Key and Optional Passphrase
serverConfig = {
key: await readFile(sslKey),
cert: await readFile(sslCert),
passphrase: sslPass ? await readFile(sslPass, 'utf8') : '',
};
} else if (useSsl && sslCert && isPFXFormat) {
serverConfig = {
pfx: await readFile(sslCert),
passphrase: sslPass ? await readFile(sslPass, 'utf8') : '',
};
}

const server = useSsl
? https.createServer(serverConfig, serverHandler)
: http.createServer(serverHandler);

// Once the server starts, return the address it is running on so the CLI
// can tell the user.
Expand All @@ -101,6 +111,7 @@ export const startServer = async (
else address = details.address;
const ip = getNetworkAddress();

const httpMode = useSsl ? 'https' : 'http';
local = `${httpMode}://${address}:${details.port}`;
network = ip ? `${httpMode}://${ip}:${details.port}` : undefined;
}
Expand Down

0 comments on commit 8bf73f3

Please sign in to comment.