From c1bf8408f38a61c76a68a19691616f0d60b9efd0 Mon Sep 17 00:00:00 2001 From: Shubhan Chemburkar Date: Sat, 9 Jul 2022 13:58:39 +0530 Subject: [PATCH] Add support for PFX or PKCS12 encoded certificates Add support for PFX or PKCS12 encoded certificates with/without passkey --- source/utilities/cli.ts | 2 ++ source/utilities/server.ts | 40 ++++++++++++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/source/utilities/cli.ts b/source/utilities/cli.ts index a0131896..0ec618f6 100644 --- a/source/utilities/cli.ts +++ b/source/utilities/cli.ts @@ -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 diff --git a/source/utilities/server.ts b/source/utilities/server.ts index eb287eed..b785470e 100644 --- a/source/utilities/server.ts +++ b/source/utilities/server.ts @@ -50,19 +50,47 @@ export const startServer = async ( }; // Create the server. - const httpMode = args['--ssl-cert'] && args['--ssl-key'] ? 'https' : 'http'; + // Detect HTTPS when cert is provided with a ssl-key or ssl-pass or if its a no password PFX cert. + const httpMode = + args['--ssl-cert'] && + (args['--ssl-key'] || + args['--ssl-pass'] || + /[.](?pfx|p12)$/.exec(args['--ssl-cert'])) + ? 'https' + : 'http'; const sslPass = args['--ssl-pass']; - const server = - httpMode === 'https' - ? https.createServer( + + let server: http.Server | https.Server; + + if (httpMode === 'http') { + server = http.createServer(serverHandler); // eslint-disable-line @typescript-eslint/no-misused-promises + } else { + // --ssl-key is required for PEM certificates only + const format = args['--ssl-key'] ? 'pem' : 'pfx'; + + switch (format) { + case 'pfx': + server = https.createServer( + { + pfx: await readFile(args['--ssl-cert']), + passphrase: sslPass ? await readFile(sslPass, 'utf8') : '', + }, + // eslint-disable-next-line @typescript-eslint/no-misused-promises + serverHandler, + ); + break; + case 'pem': + default: + server = https.createServer( { key: await readFile(args['--ssl-key']), cert: await readFile(args['--ssl-cert']), passphrase: sslPass ? await readFile(sslPass, 'utf8') : '', }, serverHandler, // eslint-disable-line @typescript-eslint/no-misused-promises - ) - : http.createServer(serverHandler); // eslint-disable-line @typescript-eslint/no-misused-promises + ); + } + } // Once the server starts, return the address it is running on so the CLI // can tell the user.