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 with/without passkey
  • Loading branch information
schemburkar committed Jul 9, 2022
1 parent 77c3165 commit c1bf840
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 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
40 changes: 34 additions & 6 deletions source/utilities/server.ts
Expand Up @@ -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'] ||
/[.](?<extension>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.
Expand Down

0 comments on commit c1bf840

Please sign in to comment.