Free SSL and Automatic HTTPS (ACME / Let's Encrypt v2 client) for node.js with Express, Connect, and other middleware systems
Go to file
AJ ONeal 6df0dc2f76 some sni bugfixes 2019-10-27 01:19:44 -06:00
dist/etc/systemd/system auto redirect www/no-www 2019-03-30 02:35:23 -06:00
examples make Prettier 2019-06-03 03:47:07 -06:00
lib make Prettier 2019-06-03 03:47:07 -06:00
scripts v2.7.14: announce deadline 2019-08-17 21:59:00 -06:00
test make Prettier 2019-06-03 03:47:07 -06:00
.gitignore Add VSCode to gitignore 2017-04-14 11:13:44 -06:00
.prettierrc make Prettier 2019-06-03 03:47:07 -06:00
LICENSE doc updates 2019-05-15 22:19:58 -06:00
README.md v2.7.18: Notify of upcoming Greenlock v3 2019-10-19 06:18:39 -06:00
config.js example server: add proxy and wildcard support 2019-08-01 05:44:24 +00:00
demo.js some sni bugfixes 2019-10-27 01:19:44 -06:00
greenlock-express.js wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00
http-middleware.js some sni bugfixes 2019-10-27 01:19:44 -06:00
https-middleware.js wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00
install.sh v2.7.4: add a server I use 2019-04-04 00:35:15 -06:00
main.js wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00
master.js wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00
package-lock.json v2.7.18: Notify of upcoming Greenlock v3 2019-10-19 06:18:39 -06:00
package.json v2.7.18: Notify of upcoming Greenlock v3 2019-10-19 06:18:39 -06:00
servers.js some sni bugfixes 2019-10-27 01:19:44 -06:00
single.js some sni bugfixes 2019-10-27 01:19:44 -06:00
sni.js some sni bugfixes 2019-10-27 01:19:44 -06:00
worker.js wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00

README.md

Greenlock v3 on its way (Nov 1st, 2019)

Greenlock v3 is in private beta (for backers) and will be available publicly by Nov 1st.

You can keep an eye for updates on the campaign page and, if this has been a useful project that's saved you time, please contribute.

Greenlock Logo

"Greenlock Function"

Greenlock™ for Express.js | a Root project

formerly letsencrypt-express

Free SSL, Free Wildcard SSL, and Fully Automated HTTPS made dead simple
certificates issued by Let's Encrypt v2 via ACME

"Lifetime Downloads" "Monthly Downloads" "Weekly Downloads" "Stackoverflow Questions" Twitter Badge

Greenlock™ is for Web Servers, Web Browsers, and node.js middleware systems.

Features

  • Automatic HTTPS
    • Free SSL
    • Free Wildcard SSL
    • Multiple domain support (up to 100 altnames per SAN)
    • Dynamic Virtual Hosting (vhost)
    • Automatical renewal (10 to 14 days before expiration)
  • Great ACME support
    • ACME draft 11
    • Let's Encrypt v2
    • Let's Encrypt v1
  • Full node.js support
    • node v6+
    • core https module
    • Express.js
    • Koa
    • hapi
  • Extensible Plugin Support
    • AWS (S3, Route53)
    • Azure
    • CloudFlare
    • Consul
    • Digital Ocean
    • etcd
    • Redis

Install

npm install --save greenlock-express@2.x

QuickStart

Screencast

Watch the QuickStart demonstration: https://youtu.be/e8vaR4CEZ5s

YouTube Video Preview

  • 0:00 - Intro
  • 2:22 - Demonstrating QuickStart Example
  • 6:37 - Troubleshooting / Gotchas

Beyond the QuickStart (Part 2)

  • 1:00 - Bringing Greenlock into an Existing Express Project
  • 2:26 - The approveDomains callback

Security Concerns (Part 3)

  • 0:00 - Potential Attacks, and Mitigation

Working Example Code

Here's a completely working example that will get you started.

git clone https://git.rootprojects.org/root/greenlock-express.js.git
pushd greenlock-express.js
  npm install
popd

# edit 'email' and 'approveDomains' in
# greenlock-express.js/examples/simple.js

node greenlock-express.js/examples/simple.js

All you have to do is start the webserver and then visit it at its domain name.

server.js:

"use strict";

require("greenlock-express")
	.create({
		email: "john.doe@example.com", // The email address of the ACME user / hosting provider
		agreeTos: true, // You must accept the ToS as the host which handles the certs
		configDir: "~/.config/acme/", // Writable directory where certs will be saved
		communityMember: true, // Join the community to get notified of important updates
		telemetry: true, // Contribute telemetry data to the project

		// Using your express app:
		// simply export it as-is, then include it here
		app: require("./app.js")

		//, debug: true
	})
	.listen(80, 443);

app.js:

"use strict";

var express = require("express");
var app = express();

app.use("/", function(req, res) {
	res.setHeader("Content-Type", "text/html; charset=utf-8");
	res.end("Hello, World!\n\n💚 🔒.js");
});

// Don't do this:
// app.listen(3000)

// Do this instead:
module.exports = app;

communityMember

If you're the kind of person that likes the kinds of stuff that I do, well, I want to do more of it and I'd like to get you involved.

As expected, by default we keep your email private and only use it for transactional messaging, urgent security or API updates (such as the mandatory upgrade to Let's Encrypt v2), and ACME account registration.

However, when you set the communityMember option to true we'll also inform you when there are meaningful and relavant feature updates (no bugfix noise), and give you early access to similar projects.

You can see our full privacy policy at https://greenlock.domains/legal/#privacy.

What if the example didn't work?

Double check the following:

  • Public Facing IP for http-01 challenges
    • Are you running this as a public-facing webserver (good)? or localhost (bad)?
    • Does ifconfig show a public address (good)? or a private one - 10.x, 192.168.x, etc (bad)?
    • If you're on a non-public server, are you using the dns-01 challenge?
  • correct ACME version
    • Let's Encrypt v2 (ACME v2) must use version: 'draft-11'
    • Let's Encrypt v1 must use version: 'v01'
  • valid email
    • You MUST set email to a valid address
    • MX records must validate (dig MX example.com for 'john@example.com')
  • valid DNS records
    • Must have public DNS records (test with dig +trace A example.com; dig +trace www.example.com for [ 'example.com', 'www.example.com' ])
  • write access
    • You MUST set configDir to a writeable location (test with touch ~/acme/etc/tmp.tmp)
  • port binding privileges
    • You MUST be able to bind to ports 80 and 443
    • You can do this via sudo or setcap
  • API limits
    • You MUST NOT exceed the API usage limits per domain, certificate, IP address, etc
  • Red Lock, Untrusted
    • You MUST use the production server url, not staging
    • The API URL should not have 'acme-staging-v02', but should have 'acme-v02'
    • Delete the configDir used for getting certificates in staging

Production vs Staging

If at first you don't succeed, stop and switch to staging.

There are a number of common problems related to system configuration - firewalls, ports, permissions, etc - that you are likely to run up against when using greenlock for your first time.

I've put a "dry run" in place with built-in diagnostics, so hopefully you get everything right on your first or second try.

However, in order to avoid being blocked by hitting the bad request rate limits you should switch to using the staging server for any testing or debugging.

https://acme-staging-v02.api.letsencrypt.org/directory

Working Examples

Example Location + Description
QuickStart examples/quickstart.js uses the fewest options and accepts all default settings. It's guaranteed to work for you.
Production examples/production.js shows how to require an express app (or other middleware system), expand the approveDomains callback, provides an example database shim, and exposes the server instance.
Virtual Hosting examples/vhost.js shows how to dynamically secure and serve domains based on their existance on the file system.
Wildcard Domains examples/wildcard.js shows how to use the acme-dns-01-cli and wildcard cetificates.
HTTPS (raw) examples/spdy.js demonstrates how to manually configure a node web server using the node's built-in http and https modules.
HTTP2 (spdy) Presently spdy is incompatible with node v11, but examples/spdy.js demonstrates how to manually configure a node web server with spdy-compatible versions of node and Greenlock.
HTTP2 (node) examples/http2.js uses node's new HTTP2 module, which is NOT compatible with the existing middleware systems (and is not "stable" as of v10.0).
WebSockets (ws) examples/websockets.js demonstrates how to use Greenlock express with a websocket server.
socket.io examples/socket.io.js demonstrates how to use Greenlock express with socket.io (even though ws is far simpler, faster, and better and every way).
- Build Your Own
Be sure to tell me (@solderjs) / us (@GreenlockHTTPS) about it. :)
Full List Check out the examples/ directory

Plugins

Plugins developed by root are officially maintained, written in Vanilla JS, and typically have 0 dependencies.

IMPORTANT: Community plugins may or may not be maintained and working. Please try with the defaults before switching to community plugins.

HTTP-01 Challenges

Plugins for ACME / Let's Encrypt HTTP-01 Challenges.

Plugin
Default (fs) root/acme-http-01-fs
Manual (cli) root/acme-http-01-cli
standalone root/acme-http-01-standalone
AWS S3 root/acme-http-01-s3
Azure kolarcz/node-le-challenge-azure-storage
- Build Your Own
acme-http-01-test
Full List Search acme-http-01- on npm (or le-challenge- for older versions)

DNS-01 Challenges

Plugins for ACME / Let's Encrypt DNS-01 Challenges.

Plugin
Manual (cli) root/acme-dns-01-cli
Cloudflare nodecraft/acme-dns-01-cloudflare
DNSimple root/acme-dns-01-dnsimple
Digital Ocean root/acme-dns-01-digitalocean
Duck DNS root/acme-dns-01-duckdns
Gandi root/acme-dns-01-gandi
GoDaddy root/acme-dns-01-godaddy
NameCheap root/acme-dns-01-namecheap
Name.com root/acme-dns-01-namedotcom
Route 53 (AWS) hgezim/acme-dsns-01-route53
Vultr root/acme-dns-01-vultr
etcd ceecko/le-challenge-etcd
- Build Your Own
acme-dns-01-test
Full List Search acme-dns-01- or le-challenge- on npm

Account & Certificate Storage

Plugin
Simplest greenlock-store-fs
certbot (v2 default) le-store-certbot
AWS S3 gl-store-s3
Consul sebastian-software/le-store-consul
json (fs) paulgrove/le-store-simple-fs
Redis digitalbazaar/le-store-redis
- Build Your Own
greenlock-store-test
Full List Search le-store- on npm

Auto-SNI

Plugin
Default le-sni-auto

(you probably wouldn't need or want to replace this)

Bugs: Please report bugs with the community plugins to the appropriate owner first, then here if you don't get a response.

Usage

The oversimplified example was the bait (because everyone seems to want an example that fits in 3 lines, even if it's terribly bad practices), now here's the switch.

We have another completely working example that will provides a little more to build off of.

git clone https://git.rootprojects.org/root/greenlock-express.js.git
pushd greenlock-express.js
  npm install
popd

# replace 'fooCheckDb' in
# greenlock-express.js/examples/normal.js

node greenlock-express.js/examples/normal.js

It looks a little more like this:

serve.js:

"use strict";

// returns an instance of greenlock.js with additional helper methods
var glx = require("greenlock-express").create({
	server: "https://acme-v02.api.letsencrypt.org/directory",
	// Note: If at first you don't succeed, stop and switch to staging:
	// https://acme-staging-v02.api.letsencrypt.org/directory
	version: "draft-11", // Let's Encrypt v2 (ACME v2)

	// If you wish to replace the default account and domain key storage plugin
	store: require("le-store-certbot").create({
		configDir: require("path").join(require("os").homedir(), "acme", "etc"),
		webrootPath: "/tmp/acme-challenges"
	}),

	// Contribute telemetry data to the project
	telemetry: true,

	// the default servername to use when the client doesn't specify
	// (because some IoT devices don't support servername indication)
	servername: "example.com",

	approveDomains: approveDomains
});

var server = glx.listen(80, 443, function() {
	console.log("Listening on port 80 for ACME challenges and 443 for express app.");
});

Note: You shouldn't be using the plain HTTP server for anything except, potentially, for error handling on the listen event (if the default print-and-quit behavior doesn't work for your use case). If you need to do that, here's how:

var plainServer = server.unencrypted;
plainServer.on('error', function (err) { ... });

The Automatic Certificate Issuance is initiated via SNI (httpsOptions.SNICallback). For security, domain validation MUST have an approval callback in production.

var http01 = require("le-challenge-fs").create({ webrootPath: "/tmp/acme-challenges" });
function approveDomains(opts, certs, cb) {
	// This is where you check your database and associated
	// email addresses with domains and agreements and such
	// if (!isAllowed(opts.domains)) { return cb(new Error("not allowed")); }

	// The domains being approved for the first time are listed in opts.domains
	// Certs being renewed are listed in certs.altnames (if that's useful)

	// Opt-in to submit stats and get important updates
	opts.communityMember = true;

	// If you wish to replace the default challenge plugin, you may do so here
	opts.challenges = { "http-01": http01 };

	opts.email = "john.doe@example.com";
	opts.agreeTos = true;

	// NOTE: you can also change other options such as `challengeType` and `challenge`
	// opts.challengeType = 'http-01';
	// opts.challenge = require('le-challenge-fs').create({});

	cb(null, { options: opts, certs: certs });
}
// handles acme-challenge and redirects to https
require("http")
	.createServer(glx.middleware(require("redirect-https")()))
	.listen(80, function() {
		console.log("Listening for ACME http-01 challenges on", this.address());
	});

var app = require("express")();
app.use("/", function(req, res) {
	res.end("Hello, World!");
});

// handles your app
require("https")
	.createServer(glx.httpsOptions, app)
	.listen(443, function() {
		console.log("Listening for ACME tls-sni-01 challenges and serve app on", this.address());
	});

Security:

Greenlock will do a self-check on all domain registrations to prevent you from hitting rate limits.

API

This module is an elaborate ruse (to provide an oversimplified example and to nab some SEO).

The API is actually located at greenlock.js options (because all options are simply passed through to greenlock.js proper without modification).

The only "API" consists of two options, the rest is just a wrapper around greenlock.js to take LOC from 15 to 5:

  • opts.app An express app in the format function (req, res) { ... } (no next).
  • server = glx.listen(plainAddr, tlsAddr, onListen) Accepts port numbers (or arrays of port numbers) to listen on, returns secure server.
    • listen(80, 443)
    • listen(80, 443, onListenSecure)
    • listen(80, 443, onListenPlain, onListenSecure)
    • listen('localhost:80', '0.0.0.0:443')
    • listen('[::1]:80', '[::]:443')
    • listen('/tmp/glx.plain.sock', '/tmp/glx.secure.sock')

Brief overview of some simple options for greenlock.js:

  • opts.server set to https://acme-v02.api.letsencrypt.org/directory in production
  • opts.version set to v01 for Let's Encrypt v1 or draft-11 for Let's Encrypt v2 (mistakenly called ACME v2)
  • opts.email The default email to use to accept agreements.
  • opts.agreeTos When set to true, this always accepts the LetsEncrypt TOS. When a string it checks the agreement url first.
  • opts.communityMember Join the community to get notified of important updates and help make greenlock better
  • opts.approveDomains can be either of:
    • An explicit array of allowed domains such as [ 'example.com', 'www.example.com' ]
    • A callback function (opts, certs, cb) { cb(null, { options: opts, certs: certs }); } for setting email, agreeTos, domains, etc (as shown in usage example above)
  • opts.renewWithin is the maximum number of days (in ms) before expiration to renew a certificate.
  • opts.renewBy is the minimum number of days (in ms) before expiration to renew a certificate.

Supported ACME versions

  • Let's Encrypt v1 (aka v01)
  • Let's Encrypt v2 (aka v02 or ACME draft 11)
  • ACME draft 11 (ACME v2 is a misnomer)
  • Wildcard domains (via dns-01 challenges)
    • *.example.com

tags: letsencrypt acme free ssl automated https node express.js

Legal & Rules of the Road

Greenlock™ is a trademark of AJ ONeal

The rule of thumb is "attribute, but don't confuse". For example:

Built with Greenlock Express (a Root project).

Please contact us if you have any questions in regards to our trademark, attribution, and/or visible source policies. We want to build great software and a great community.

Greenlock™ | MPL-2.0 | Terms of Use | Privacy Policy