self-cert
This is a simple library for generating a self-signed x509 keypair and certificate.
Installation
CDN
Import library from the UNPKG CDN for fast and easy setup:
import {create} from "//unpkg.com/@raha.group/self-cert?module";
NPM registry
Use the package manager npm to install self-cert.
$ npm install "@raha.group/self-cert"
Usage
Self-signed Certificate
- Create a new project with the entry point "index.mjs".
- Add the project dependency by
npm i "@raha.group/self-cert"
. - Put the following script in file "index.mjs".
import {create as createCertificate} from '@raha.group/self-cert';
import fs from 'fs/promises';
import os from 'os';
let hosts = [];
for (let networkInterface of Object.values(os.networkInterfaces())) {
for (let assignedNetworkAddress of networkInterface) {
hosts.push(assignedNetworkAddress.address);
}
}
let certificate = createCertificate({
domains: [ // List the hostnames (including wildcards) on your origin that the certificate should protect.
'localhost',
'*.local', // wildcards
...hosts
],
expires: new Date(2025, 1),
/*
attributes: {
commonName: domains[0],
countryName: 'IR',
stateName: 'Isfahan',
locality: 'Isfahan',
organizationName: 'None',
},
keySize: 2048,
*/
});
await fs.writeFile('privateKey.pem', certificate.privateKey);
await fs.writeFile('publicKey.pem', certificate.publicKey);
await fs.writeFile('fullChain.pem', certificate.fullChain);
Basic HTTPS
Here is an example for creating an SSL key/cert on the fly, and running an HTTPS server on port 443. Use https://localhost:443 to access created server.
import {create as createCertificate} from '@raha.group/self-cert';
import https from 'https';
let certificate = createCertificate({
domains: ['localhost'],
});
https.createServer({key: certificate.privateKey, cert: certificate.fullChain}, function(request, response) {
response.end('Hello World :-)');
}).listen(443);