New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@small-tech/auto-encrypt-localhost

Package Overview
Dependencies
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@small-tech/auto-encrypt-localhost - npm Package Compare versions

Comparing version 4.0.1 to 5.0.0

artefacts/dependency-graph.svg

3

bin/auto-encrypt-localhost.js
#!/usr/bin/env node
require('../index.js')()
const AutoEncryptLocalhost = require('../index.js')
AutoEncryptLocalhost.https.createServer()

@@ -12,2 +12,8 @@ # Changelog

## [5.0.0] - 2020-04-14
### Changed
- __Breaking change:__ New API to maintain consistency with [Auto Encrypt](https://source.small-tech.org/site.js/lib/auto-encrypt).
## [4.0.1] - 2020-03-09

@@ -14,0 +20,0 @@

// Create an https server using locally-trusted certificates.
const https = require('https')
const autoEncryptLocalhost = require('../index')
const AutoEncryptLocalhost = require('../index')
const server = https.createServer(autoEncryptLocalhost(), (request, response) => {
const server = AutoEncryptLocalhost.https.createServer((request, response) => {
response.end('Hello, world!')
})
server.listen(() => {
server.listen(443, () => {
console.log('Web server is running at https://localhost')
})

@@ -1,280 +0,132 @@

const os = require('os')
const path = require('path')
const fs = require('fs-extra')
const childProcess = require('child_process')
/**
* Automatically provisions and installs locally-trusted TLS certificates for Node.js® https servers
* (including Express.js, etc.) using mkcert.
*
* @module @small-tech/auto-encrypt-localhost
* @copyright © 2020 Aral Balkan, Small Technology Foundation.
* @license AGPLv3 or later.
*/
const _platform = os.platform()
const _architecture = os.arch()
const os = require('os')
const fs = require('fs-extra')
const path = require('path')
const https = require('https')
const childProcess = require('child_process')
const syswidecas = require('syswide-cas')
const mkcertBinaryForThisMachine = require('./lib/mkcertBinaryForThisMachine')
const installCertutil = require('./lib/installCertutil')
const { log } = require('./lib/util/log')
const homeDir = os.homedir()
const syswidecas = require('syswide-cas')
let tlsOptions
let settingsPath
function log(...args) {
if (process.env.QUIET) {
return
}
console.log(...args)
}
/**
* Automatically provisions trusted development-time (localhost) certificates in Node.js via mkcert.
* @function autoEncryptLocalhost
* Auto Encrypt Localhost is a static class. Please do not instantiate.
*
* @param {Object} parameterObject
* @param {Object} [parameterObject.options] Standard https server options.
* @param {String} [parameterObject.settingsPath=~/.small-tech.org/auto-encrypt-localhost/] Custom path to save the certificate and private key to.
* @returns {Object} An options object to be passed to the https.createServer() method.
* Use: AutoEncryptLocalhost.https.createServer(…)
*
* @alias module:@small-tech/auto-encrypt-localhost
*/
function autoEncryptLocalhost (parameterObject) {
class AutoEncryptLocalhost {
/**
* By aliasing the https property to the AutoEncryptLocalhost static class itself, we enable
* people to add AutoEncryptLocalhost to their existing apps by requiring the module
* and prefixing their https.createServer(…) line with AutoEncryptLocalhost:
*
* @example const AutoEncryptLocalhost = require('@small-tech/auto-encrypt-localhost')
* const server = AutoEncryptLocalhost.https.createServer()
*
* @static
*/
static get https () { return AutoEncryptLocalhost }
if (parameterObject == undefined) { parameterObject = {} }
tlsOptions = parameterObject.options || {}
settingsPath = parameterObject.settingsPath || path.join(homeDir, '.small-tech.org', 'auto-encrypt-localhost')
/**
* Automatically provisions trusted development-time (localhost) certificates in Node.js via mkcert.
*
* @static
* @param {Object} [options] Optional HTTPS options object with optional additional
* Auto Encrypt-specific configuration settings.
* @param {String} [options.settingsPath=~/.small-tech.org/auto-encrypt-localhost/]
* Custom path to save the certificate and private key to.
* @returns {https.Server} The server instance returned by Node’s https.createServer() method.
*/
static createServer(_options, _listener) {
// The first parameter is optional. If omitted, the first argument, if any, is treated as the request listener.
if (typeof _options === 'function') {
_listener = _options
_options = {}
}
const keyFilePath = path.join(settingsPath, 'localhost-key.pem')
const certFilePath = path.join(settingsPath, 'localhost.pem')
const defaultSettingsPath = path.join(os.homedir(), '.small-tech.org', 'auto-encrypt-localhost')
const options = _options || {}
const listener = _listener || null
const settingsPath = options.settingsPath || defaultSettingsPath
// Create certificates.
if (!allOK()) {
const keyFilePath = path.join(settingsPath, 'localhost-key.pem')
const certFilePath = path.join(settingsPath, 'localhost.pem')
log(' 📜 ❨Auto Encrypt Localhost❩ Setting up…')
// Ensure the Auto Encrypt Localhost directory exists.
fs.ensureDirSync(settingsPath)
// Get a path to the mkcert binary for this machine.
const mkcertBinary = mkcertBinaryForThisMachine()
// On Linux and on macOS, mkcert uses the Mozilla nss library.
// Try to install this automatically and warn the person if we can’t so
// that they can do it manually themselves.
tryToInstallTheDependency()
// mkcert uses the CAROOT environment variable to know where to create/find the certificate authority.
// We also pass the rest of the system environment to the spawned processes.
const options = {
env: process.env,
stdio: 'pipe' // suppress output
const allOK = () => {
return fs.existsSync(path.join(settingsPath, 'rootCA.pem')) && fs.existsSync(path.join(settingsPath, 'rootCA-key.pem')) && fs.existsSync(path.join(settingsPath, 'localhost.pem')) && fs.existsSync(path.join(settingsPath, 'localhost-key.pem'))
}
options.env.CAROOT = settingsPath
try {
// Create the local certificate authority.
log(' 📜 ❨Auto Encrypt Localhost❩ Creating local certificate authority (local CA) using mkcert…')
childProcess.execFileSync(mkcertBinary, ['-install'], options)
log(' 📜 ❨Auto Encrypt Localhost❩ Local certificate authority created.')
// Create the local certificate.
log(' 📜 ❨Auto Encrypt Localhost❩ Creating local TLS certificates using mkcert…')
const createCertificateArguments = [
`-key-file=${keyFilePath}`,
`-cert-file=${certFilePath}`,
'localhost', '127.0.0.1', '::1'
]
childProcess.execFileSync(mkcertBinary, createCertificateArguments, options)
log(' 📜 ❨Auto Encrypt Localhost❩ Local TLS certificates created.')
} catch (error) {
log('\n', error)
}
// Create certificates.
if (!allOK()) {
process.exit(1)
}
} else {
log(' 📜 ❨Auto Encrypt Localhost❩ Local development TLS certificate exists.')
}
addRootStoreToNode()
log(' 📜 ❨Auto Encrypt Localhost❩ Setting up…')
// Load in and return the certificates in an object that can be passed
// directly to https.createServer() if required.
tlsOptions.key = fs.readFileSync(keyFilePath, 'utf-8')
tlsOptions.cert = fs.readFileSync(certFilePath, 'utf-8')
// Ensure the Auto Encrypt Localhost directory exists.
fs.ensureDirSync(settingsPath)
return tlsOptions
}
// Get a path to the mkcert binary for this machine.
const mkcertBinary = mkcertBinaryForThisMachine(settingsPath)
module.exports = autoEncryptLocalhost
// On Linux and on macOS, mkcert uses the Mozilla nss library.
// Try to install this automatically and warn the person if we can’t so
// that they can do it manually themselves.
installCertutil()
// Write to stdout without a newline
function print(str) {
process.stdout.write(str)
}
// mkcert uses the CAROOT environment variable to know where to create/find the certificate authority.
// We also pass the rest of the system environment to the spawned processes.
const mkcertProcessOptions = {
env: process.env,
stdio: 'pipe' // suppress output
}
mkcertProcessOptions.env.CAROOT = settingsPath
try {
// Create the local certificate authority.
log(' 📜 ❨Auto Encrypt Localhost❩ Creating local certificate authority (local CA) using mkcert…')
childProcess.execFileSync(mkcertBinary, ['-install'], mkcertProcessOptions)
log(' 📜 ❨Auto Encrypt Localhost❩ Local certificate authority created.')
// Create the local certificate.
log(' 📜 ❨Auto Encrypt Localhost❩ Creating local TLS certificates using mkcert…')
const createCertificateArguments = [
`-key-file=${keyFilePath}`,
`-cert-file=${certFilePath}`,
'localhost', '127.0.0.1', '::1'
]
childProcess.execFileSync(mkcertBinary, createCertificateArguments, mkcertProcessOptions)
log(' 📜 ❨Auto Encrypt Localhost❩ Local TLS certificates created.')
} catch (error) {
log('\n', error)
}
// Check if the local certificate authority and local keys exist.
function allOK() {
return fs.existsSync(path.join(settingsPath, 'rootCA.pem')) && fs.existsSync(path.join(settingsPath, 'rootCA-key.pem')) && fs.existsSync(path.join(settingsPath, 'localhost.pem')) && fs.existsSync(path.join(settingsPath, 'localhost-key.pem'))
}
// Ensure that node recognises the certificates (e.g., when using https.get(), etc.)
function addRootStoreToNode () {
const rootCA = path.join(settingsPath, 'rootCA.pem')
syswidecas.addCAs(rootCA)
}
// Returns the mkcert binary for this machine (platform + architecture) and
// throws an error if there isn’t one for it.
function mkcertBinaryForThisMachine() {
const platformMap = {
linux: 'linux',
darwin: 'darwin',
win32: 'windows'
}
const architectureMap = {
arm: 'arm',
x64: 'amd64'
}
const platform = platformMap[_platform]
const architecture = architectureMap[_architecture]
if (platform === undefined) throw new Error('Unsupported platform', _platform)
if (architecture === undefined) throw new Error('Unsupported architecture', _architecture)
const mkcertVersion = '1.4.0'
const mkcertBinaryName = `mkcert-v${mkcertVersion}-${platform}-${architecture}`
const mkcertBinaryRelativePath = path.join('mkcert-bin', mkcertBinaryName)
let mkcertBinaryInternalPath = path.join(__dirname, mkcertBinaryRelativePath)
if (platform === 'windows') mkcertBinaryInternalPath += '.exe'
// Check if the platform + architecture combination is supported.
if (!fs.existsSync(mkcertBinaryInternalPath)) throw new Error(`Unsupported platform + architecture combination for ${platform}-${architecture}`)
// Copy the mkcert binary to the external Auto Encrypt Localhost directory so that we can call execSync() on it if
// the app using this module is wrapped into an executable using Nexe (https://github.com/nexe/nexe) – like
// Indie Web Server (https://ind.ie/web-server) is, for example. We use readFileSync() and writeFileSync() as
// Nexe does not support copyFileSync() yet (see https://github.com/nexe/nexe/issues/607).
const mkcertBinaryExternalPath = path.join(settingsPath, mkcertBinaryName)
try {
const mkcertBuffer = fs.readFileSync(mkcertBinaryInternalPath, 'binary')
fs.writeFileSync(mkcertBinaryExternalPath, mkcertBuffer, {encoding: 'binary', mode: 0o755})
} catch (error) {
throw new Error(` 🤯 ❨Auto Encrypt Localhost❩ Panic: Could not copy mkcert to external directory: ${error.message}`)
}
return mkcertBinaryExternalPath
}
// Does the passed command exist? Returns: bool.
function commandExists (command) {
try {
childProcess.execFileSync('which', [command], {env: process.env})
return true
} catch (error) {
return false
}
}
// Mozilla’s nss is used on Linux to install the certificate in Chrome and Firefox
// and on macOS for Firefox. Ensure it exists.
// Source: https://github.com/FiloSottile/mkcert/blob/master/README.md#installation
function tryToInstallTheDependency() {
if (_platform === 'linux') {
tryToInstallCertutilOnLinux()
} else if (_platform === 'darwin') {
tryToInstallCertutilOnDarwin()
} else if (_platform === 'win32') {
// Do nothing. According to the mkcert documentation, certutil is not
// required on Windows.
} else {
// Unknown platform. This should have been caught earlier. Panic.
throw new Error(' 🤯 ❨Auto Encrypt Localhost❩ Panic: Unknown platform detected.', _platform)
}
}
// On Linux, we must install nss for mkcert to work with both Chrome and Firefox.
// Depending on the platform we try to do so using apt, yum, or pacman. If none of
// those exist, we fail.
function tryToInstallCertutilOnLinux() {
if (commandExists('certutil')) return // Already installed
print(' 📜 ❨Auto Encrypt Localhost❩ Installing certutil dependency (Linux) ')
let options = {env: process.env}
try {
if (commandExists('apt')) {
print('using apt… \n')
options.env.DEBIAN_FRONTEND = 'noninteractive'
childProcess.execSync('sudo apt-get install -y -q libnss3-tools', options)
} else if (commandExists('yum')) {
// Untested: if you test this, please let me know https://github.com/indie-mirror/https-server/issues
log('\n 🤪 ❨Auto Encrypt Localhost❩ Attempting to install required dependency using yum. This is currently untested. If it works (or blows up) for you, I’d appreciate it if you could open an issue at https://github.com/indie-mirror/https-server/issues and let me know. Thanks! – Aral\n')
childProcess.execSync('sudo yum install nss-tools', options)
log(' 📜 ❨Auto Encrypt Localhost❩ Certutil installed using yum.')
} else if (commandExists('pacman')) {
childProcess.execSync('sudo pacman -S nss', options)
log(' 📜 ❨Auto Encrypt Localhost❩ Certutil installed using pacman.')
if (!allOK()) {
process.exit(1)
}
} else {
// Neither Homebrew nor MacPorts is installed. Warn the person.
log('\n ⚠️ ❨Auto Encrypt Localhost❩ Linux: No supported package manager found for installing certutil on Linux (tried apt, yum, and pacman. Please install certutil manually and run Auto Encrypt Localhost again. For more instructions on installing mkcert dependencies, please see https://github.com/FiloSottile/mkcert/\n')
log(' 📜 ❨Auto Encrypt Localhost❩ Local development TLS certificate exists.')
}
} catch (error) {
// There was an error and we couldn’t install the dependency. Warn the person.
log('\n ⚠️ ❨Auto Encrypt Localhost❩ Linux: Failed to install nss. Please install it manually and run Auto Encrypt Localhost again if you want your certificate to work in Chrome and Firefox', error)
}
}
// Add root store to Node to ensure Node recognises the certificates (e.g., when using https.get(), etc.)
const rootCA = path.join(settingsPath, 'rootCA.pem')
syswidecas.addCAs(rootCA)
// On macOS, we install nss for mkcert to work with Firefox. To
// install nss, we can use either Homebrew or Macports.
// If neither Homebrew or MacPorts is installed, we warn the person that
// they need to install it manually if they want their certificates to work
// in Firefox.
function tryToInstallCertutilOnDarwin() {
const options = {env: process.env}
// Load in and return the certificates in an object that can be passed
// directly to https.createServer() if required.
options.key = fs.readFileSync(keyFilePath, 'utf-8')
options.cert = fs.readFileSync(certFilePath, 'utf-8')
if (commandExists('brew')) {
// Check if nss installed using brew (we can’t just check using commandExists as
// nss is installed as keg-only and not symlinked to /usr/local due to issues
// with Firefox crashing).
try {
// Homebrew can take a long time start, show current status.
print(' 📜 ❨Auto Encrypt Localhost❩ Checking if certutil dependency is installed (Darwin) using Homebrew… ')
childProcess.execSync('brew list nss >/dev/null 2>&1', options)
log(' ok.')
} catch (error) {
// NSS is not installed. Install it.
try {
print(' 📜 ❨Auto Encrypt Localhost❩ Installing certutil dependency (Darwin) using Homebrew… ')
childProcess.execSync('brew install nss >/dev/null 2>&1', options)
log('done.')
} catch (error) {
log('\n ⚠️ ❨Auto Encrypt Localhost❩ macOS: Failed to install nss via Homebrew. Please install it manually and run Auto Encrypt Localhost again if you want your certificate to work in Firefox', error)
return
}
}
} else if (commandExists('port')) {
// Untested. This is based on the documentation at https://guide.macports.org/#using.port.installed. I don’t have MacPorts installed
// and it doesn’t play well with Homebrew so I won’t be testing this anytime soon. If you do, please let me know how it works
// by opening an issue on https://github.com/indie-mirror/https-server/issues
log('\n 🤪 ❨Auto Encrypt Localhost❩ Attempting to install required dependency using MacPorts. This is currently untested. If it works (or blows up) for you, I’d appreciate it if you could open an issue at https://github.com/indie-mirror/https-server/issues and let me know. Thanks! – Aral\n')
try {
childProcess.execSync('port installed nss', options)
} catch (error) {
// nss is not installed, attempt to install it using MacPorts.
try {
childProcess.execSync('sudo port install nss', options)
} catch (error) {
log('\n ⚠️ ❨Auto Encrypt Localhost❩ macOS: Failed to install nss via MacPorts. Please install it manually and run Auto Encrypt Localhost again if you want your certificate to work in Firefox', error)
return
}
}
} else {
// Neither Homebrew nor MacPorts is installed. Warn the person.
log('\n ⚠️ ❨Auto Encrypt Localhost❩ macOS: Cannot install certutil (nss) as you don’t have Homebrew or MacPorts installed.\n\n If you want your certificate to work in Firefox, please install one of those package managers and then install nss manually:\n\n * Homebrew (https://brew.sh): brew install nss\n * MacPorts(https://macports.org): sudo port install nss\n')
return
const server = https.createServer(options, listener)
return server
}
}
module.exports = AutoEncryptLocalhost
{
"name": "@small-tech/auto-encrypt-localhost",
"version": "4.0.1",
"description": "Automatically provision and use locally-trusted TLS certificates in Node.js using mkcert.",
"version": "5.0.0",
"description": "Automatically provisions and installs locally-trusted TLS certificates for Node.js® https servers (including Express.js, etc.) using mkcert.",
"keywords": [
"mkcert",
"https",
"tls",
"auto encrypt",
"localhost",
"small tech",
"automatic"
],
"main": "index.js",

@@ -9,3 +18,8 @@ "bin": "bin/auto-encrypt-localhost.js",

"start": "node index.js",
"test": "QUIET=true tape test.js"
"test": "QUIET=true tape 'test/**/*.js' | tap-spec",
"coverage": "QUIET=true nyc tape 'test/**/*.js' | tap-nyc",
"test-debug": "tape 'test/**/*.js' | tap-spec",
"coverage-debug": "nyc tape 'test/**/*.js' | tap-nyc",
"generate-dependency-diagram": "mkdir -p artefacts && node_modules/.bin/depcruise --max-depth 1 --output-type dot index.js | dot -T svg > artefacts/dependency-graph.svg",
"generate-developer-documentation": "npm run generate-dependency-diagram && node_modules/.bin/jsdoc2md --private --template developer-documentation.hbs --files index.js > developer-documentation.md"
},

@@ -22,2 +36,8 @@ "repository": {

"license": "AGPL-3.0-or-later",
"nyc": {
"exclude": [
"test/**/*.js",
"lib/util/*.js"
]
},
"dependencies": {

@@ -28,3 +48,10 @@ "fs-extra": "^8.1.0",

"devDependencies": {
"tape": "^4.10.1"
"bent": "^7.3.0",
"dependency-cruiser": "^8.1.0",
"jsdoc": "^3.6.3",
"jsdoc-to-markdown": "^5.0.3",
"nyc": "^14.1.1",
"tap-nyc": "^1.0.3",
"tap-spec": "^5.0.0",
"tape": "^4.13.0"
},

@@ -31,0 +58,0 @@ "pkg": {

# Auto Encrypt Localhost
Automatically provisions trusted localhost TLS certificates via [mkcert](https://github.com/FiloSottile/mkcert/) for development without browser security warnings in Node.js.
Adds automatic provisioning and renewal of trusted localhost TLS certificates via [mkcert](https://github.com/FiloSottile/mkcert/) for development without browser security warnings in Node.js.
## How it works
Before creating your HTTPS server, uses mkcert to create a local certificate authority, adds it to the various trust stores, and uses it to create locally-trusted TLS certificates that are installed in your server.
## Installation

@@ -13,9 +17,25 @@

### Instructions
1. Import the module:
```js
const AutoEncryptLocalhost = require('@small-tech/auto-encrypt-localhost')
```
2. Prefix your server creation code with a reference to the Auto Encrypt Localhost class:
```js
// const server = https.createServer(…) becomes
const server = AutoEncryptLocalhost.https.createServer(…)
```
### Example
```js
// Create an https server using locally-trusted certificates.
const https = require('https')
const autoEncryptLocalhost = require('@small-tech/auto-encrypt-localhost')
const AutoEncryptLocalhost = require('@small-tech/auto-encrypt-localhost')
const server = https.createServer(autoEncryptLocalhost(), (request, response) => {
const server = AutoEncryptLocalhost.https.createServer((request, response) => {
response.end('Hello, world!')

@@ -31,64 +51,42 @@ })

## Like this? Fund us!
Note that on Linux, ports 80 and 443 require special privileges. Please see [A note on Linux and the security farce that is “privileged ports”](#a-note-on-linux-and-the-security-farce-that-is-priviliged-ports). If you just need a Node web server that handles all that and more for you (or to see how to implement privilege escalation seamlessly in your own servers, see [Site.js](https://sitejs.org)).
[Small Technology Foundation](https://small-tech.org) is a tiny, independent not-for-profit.
## Configuration
We exist in part thanks to patronage by people like you. If you share [our vision](https://small-tech.org/about/#small-technology) and want to support our work, please [become a patron or donate to us](https://small-tech.org/fund-us) today and help us continue to exist.
You can specify a custom settings path for your local certificate authority and certificate data to be stored in by adding the Auto Encrypt Localhost-specific `settingsPath` option to the options object you pass to the Node `https` server. If not specified, the default settings path (_~/.small-tech.org/auto-encrypt-localhost/_) is used.
## Audience
### Example
This is [small technology](https://small-tech.org/about/#small-technology).
```js
const AutoEncrypt = require('@small-tech/auto-encrypt-localhost')
If you’re evaluating this for a “startup” or an enterprise, let us save you some time: this is not the right tool for you. This tool is for individual developers to build personal web sites and apps for themselves and for others in a non-colonial manner that respects the human rights of the people who use them.
const options = {
// Regular HTTPS server and TLS server options, if any, go here.
## How it works
// Optional Auto Encrypt options:
settingsPath: '/custom/settings/path'
}
Auto Encrypt Localhost is a Node.js wrapper for [mkcert](https://github.com/FiloSottile/mkcert/) that:
// Pass the options object to https.createServer()
const server = AutoEncryptLocalhost.https.createServer(options, listener)
* Uses the 64-bit release binaries to support Linux, macOS, and Windows.
// …
```
* Automatically installs the _certutil_ (nss) dependency on Linux on systems with apt, pacman, yum (untested) and and on macOS if you have [Homebrew](https://brew.sh) or [MacPorts](https://www.macports.org/) (untested).
## Developer documentation
* Creates a root Certificate Authority
If you want to help improve Auto Encrypt Localhost or better understand how it is structured and operates, please see the [developer documentation](developer-documentation.md).
* Creates locally-trusted TLS certificates for localhost, 127.0.0.1, and ::1
## Like this? Fund us!
You can use these certificates for local development without triggering self-signed certificate errors.
[Small Technology Foundation](https://small-tech.org) is a tiny, independent not-for-profit.
For more details on how Auto Encrypt Localhost works behind the scenes, please [see the mkcert README](https://github.com/FiloSottile/mkcert/blob/master/README.md).
We exist in part thanks to patronage by people like you. If you share [our vision](https://small-tech.org/about/#small-technology) and want to support our work, please [become a patron or donate to us](https://small-tech.org/fund-us) today and help us continue to exist.
## Detailed usage
## Audience
Auto Encrypt Localhost is exported as a function that accepts an optional parameter object with optional `options` and `settingsPath` properties. The defaults for both are shown below.
This is [small technology](https://small-tech.org/about/#small-technology).
```js
autoEncryptLocalhost({ options: {}, settingsPath: '~/.small-tech.org/auto-encrypt-localhost' })
```
If you’re evaluating this for a “startup” or an enterprise, let us save you some time: this is not the right tool for you. This tool is for individual developers to build personal web sites and apps for themselves and for others in a non-colonial manner that respects the human rights of the people who use them.
### Use custom https server options
Auto Encrypt Localhost generates a locally-trusted private key and certificate using mkcert and then loads them in and returns an options object that you can pass directly to the `https.createServer()` method. If you want to pass other options to the server while creating it, just pass your regular options object to Auto Encrypt Localhost wrapped in a parameter object as shown below.
```js
const options = { /* your other https server options go here */ }
const server = https.createServer(autoEncryptLocalhost({ options }), (request, response) => {
response.end('Hello, world!')
})
```
### Use a custom settings path
By default, Auto Encrypt Localhost creates and uses the _~/.small-tech.org/auto-encrypt-localhost_ directory as its settings path, to store your certificate and its private key. You can tell it to use a different path instead by specifying the path to use in the `settingsPath` property of its parameter object.
```js
const os = require('os')
const path = require('path')
const settingsPath = path.join(os.homedir(), '.my-namespace', 'magic-localhost-certificates')
const server = https.createServer(autoEncryptLocalhost({ settingsPath }), (request, response) => {
response.end('Hello, world!')
})
```
In the above example, your certificate and its private key will be stored in the _~/.my-namespace/magic-localhost-certificates_ directory (with the names _localhost.pem_ and _localhost-key.pem_, respectively).
## Command-line interface

@@ -113,3 +111,3 @@

Locally-trusted certificates do not work under Firefox. Please use Edge or Chrome on this platform. This is [a mkcert limitation](https://github.com/FiloSottile/mkcert#supported-root-stores)
Locally-trusted certificates do not work under Firefox. Please use Edge or Chrome on this platform. This is [a mkcert limitation](https://github.com/FiloSottile/mkcert#supported-root-stores).

@@ -120,14 +118,34 @@ ## Related projects

### [@small-tech/auto-encrypt](https://source.small-tech.org/site.js/lib/auto-encrypt)
### Auto Encrypt
Automatically provisions and renews [Let’s Encrypt](https://letsencrypt.org)™ TLS certificates for [Node.js](https://nodejs.org)® [https](https://nodejs.org/dist/latest-v12.x/docs/api/https.html) servers (including [Express.js](https://expressjs.com/), etc.)
- Source: https://source.small-tech.org/site.js/lib/auto-encrypt
- Package: [@small-tech/auto-encrypt](https://www.npmjs.com/package/@small-tech/auto-encrypt-localhost)
### [@small-tech/https](https://source.small-tech.org/site.js/lib/https)
Adds automatic provisioning and renewal of [Let’s Encrypt](https://letsencrypt.org) TLS certificates with [OCSP Stapling](https://letsencrypt.org/docs/integration-guide/#implement-ocsp-stapling) to [Node.js](https://nodejs.org) [https](https://nodejs.org/dist/latest-v12.x/docs/api/https.html) servers (including [Express.js](https://expressjs.com/), etc.)
A drop-in standard Node.js `https` module replacement with both automatic development-time (localhost) certificates via Auto Encrypt Localhost and automatic production certificates via Auto Encrypt, see [@small-tech/https](https://source.small-tech.org/site.js/lib/https).
### HTTPS
### [Site.js](https://sitejs.org)
- Source: https://source.small-tech.org/site.js/lib/https
- Package: [@small-tech/https](https://www.npmjs.com/package/@small-tech/https)
A complete [small technology](https://small-tech.org/about/#small-technology) tool to develop, test, and deploy a secure static or dynamic personal web site or app with zero configuration.
A drop-in replacement for the [standard Node.js HTTPS module](https://nodejs.org/dist/latest-v12.x/docs/api/https.html) with automatic development-time (localhost) certificates via Auto Encrypt Localhost and automatic production certificates via Auto Encrypt.
### Site.js
- Web site: https://sitejs.org
A complete [small technology](https://small-tech.org/about/#small-technology) tool for developing, testing, and deploying a secure static or dynamic personal web site or app with zero configuration.
## A note on Linux and the security farce that is “privileged ports”
Linux has an outdated feature dating from the mainframe days that requires a process that wants to bind to ports < 1024 to have elevated privileges. While this was a security feature in the days of dumb terminals, today it is a security anti-feature. (macOS has dropped this requirement as of macOS Mojave.)
On Linux, ensure your Node process has the right to bind to so-called “privileged” ports by issuing the following command before use:
```sh
sudo setcap cap_net_bind_service=+ep $(which node)
```
If you are wrapping your Node app into an executable binary using a module like [Nexe](https://github.com/nexe/nexe), you will have to ensure that every build of your app has that capability set. For an example of how we do this in [Site.js](https://sitejs.org), [see this listing](https://source.ind.ie/site.js/app/blob/master/bin/lib/ensure.js#L124).
## Help wanted

@@ -134,0 +152,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc