Compare commits
55 Commits
Author | SHA1 | Date |
---|---|---|
AJ ONeal | 480352835a | |
AJ ONeal | ce14a410d7 | |
AJ ONeal | ca0ba9bc68 | |
AJ ONeal | 2ac272ba9d | |
AJ ONeal | 374c360967 | |
AJ ONeal | 4b24cc48e9 | |
AJ ONeal | a025022fb2 | |
AJ ONeal | f2abc44601 | |
AJ ONeal | 477e7a07ec | |
AJ ONeal | 657ebe0756 | |
AJ ONeal | aaed863ef8 | |
AJ ONeal | 67d6a60a37 | |
AJ ONeal | 894e603a64 | |
AJ ONeal | adf0c97301 | |
AJ ONeal | e8f2c39f79 | |
AJ ONeal | f81d2614f4 | |
AJ ONeal | f18eae4073 | |
AJ ONeal | 83d4a9204e | |
AJ ONeal | e5456249a2 | |
AJ ONeal | 1df2bc0ad4 | |
AJ ONeal | cf93c77bd5 | |
AJ ONeal | c9363bd1a3 | |
AJ ONeal | 99f6ab0c1e | |
AJ ONeal | a9feafeab3 | |
AJ ONeal | bae832d65a | |
AJ ONeal | e6a008d498 | |
AJ ONeal | 2d5125821e | |
AJ ONeal | 8e29cafdf5 | |
AJ ONeal | 224f258daa | |
AJ ONeal | 375524873d | |
AJ ONeal | 28aad4f29d | |
AJ ONeal | 48b892c323 | |
AJ ONeal | 01ff1d7da5 | |
AJ ONeal | 347402a4d4 | |
AJ ONeal | bd5ee84e25 | |
AJ ONeal | 4e9a6c0719 | |
AJ ONeal | 548faed139 | |
AJ ONeal | 5a7db51a36 | |
AJ ONeal | 654a64d7f4 | |
AJ ONeal | ec14a224f9 | |
AJ ONeal | 47140f6296 | |
AJ ONeal | 6296c8a737 | |
AJ ONeal | e1d5e9a692 | |
AJ ONeal | 6bbb5f78e9 | |
AJ ONeal | a360abda01 | |
AJ ONeal | 5068097090 | |
AJ ONeal | 3994c7fd5c | |
AJ ONeal | 4482e97dcb | |
AJ ONeal | 37c3aee99f | |
AJ ONeal | 1eba51ea22 | |
AJ ONeal | 61fb942dda | |
AJ ONeal | b80537f07b | |
AJ ONeal | 627ad8272e | |
AJ ONeal | ce5e31bbf7 | |
Ryan Burnette | d11b45c409 |
|
@ -1,3 +1,8 @@
|
|||
app.js
|
||||
server.js
|
||||
greenlock.js
|
||||
.greenlockrc
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"bracketSpacing": true,
|
||||
"printWidth": 120,
|
||||
"tabWidth": 2,
|
||||
"tabWidth": 4,
|
||||
"trailingComma": "none",
|
||||
"useTabs": true
|
||||
"useTabs": false
|
||||
}
|
||||
|
|
656
README.md
656
README.md
|
@ -1,296 +1,418 @@
|
|||
# New Documentation & [v2/v3 Migration Guide](https://git.rootprojects.org/root/greenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md)
|
||||
# [Greenlock Express v4](https://git.rootprojects.org/root/greenlock-express.js) is Let's Encrypt for Node
|
||||
|
||||
Greenlock v3 just came out of private beta **today** (Nov 1st, 2019).
|
||||
|
||||
The code is complete and we're working on great documentation.
|
||||
|
||||
Many **examples** and **full API** documentation are still coming.
|
||||
|
||||
# [Greenlock Express](https://git.rootprojects.org/root/greenlock-express.js) is Let's Encrypt for Node
|
||||
| Built by [Root](https://therootcompany.com) for [Hub](https://rootprojects.org/hub/) |
|
||||
|
||||
![Greenlock Logo](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/greenlock-1063x250.png "Greenlock Logo")
|
||||
|
||||
| Built by [Root](https://therootcompany.com) for [Hub](https://rootprojects.org/hub/)
|
||||
|
||||
Free SSL, Automated HTTPS / HTTP2, served with Node via Express, Koa, hapi, etc.
|
||||
|
||||
### Let's Encrypt for Node, Express, etc
|
||||
### Free SSL for Node Web Servers
|
||||
|
||||
Greenlock Express is a **Web Server** with **Fully Automated HTTPS** and renewals.
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
|
||||
glx.serveApp(function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
}
|
||||
|
||||
var pkg = require("./package.json");
|
||||
require("greenlock-express")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
|
||||
return {
|
||||
package: { name: pkg.name, version: pkg.version },
|
||||
maintainerEmail: pkg.author,
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
```
|
||||
|
||||
Manage via API or the config file:
|
||||
|
||||
`~/.config/greenlock/manage.json`: (default filesystem config)
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "letsencrypt-test@therootcompany.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# Let's Encrypt for...
|
||||
|
||||
- IoT
|
||||
- Enterprise On-Prem
|
||||
- Local Development
|
||||
- Home Servers
|
||||
- Quitting Heroku
|
||||
|
||||
# Features
|
||||
|
||||
- [x] Let's Encrypt v2 (November 2019)
|
||||
- [x] ACME Protocol (RFC 8555)
|
||||
- [x] HTTP Validation (HTTP-01)
|
||||
- [x] DNS Validation (DNS-01)
|
||||
- [ ] ALPN Validation (TLS-ALPN-01)
|
||||
- Need ALPN validation? [contact us](mailto:greenlock-support@therootcompany.com)
|
||||
- [x] Automated HTTPS
|
||||
- [x] Fully Automatic Renewals every 45 days
|
||||
- [x] Free SSL
|
||||
- [x] **Wildcard** SSL
|
||||
- [x] **Localhost** certificates
|
||||
- [x] HTTPS-enabled Secure **WebSockets** (`wss://`)
|
||||
- [x] Fully customizable
|
||||
- [x] **Reasonable defaults**
|
||||
- [x] Domain Management
|
||||
- [x] Key and Certificate Management
|
||||
- [x] ACME Challenge Plugins
|
||||
|
||||
# QuickStart Guide
|
||||
|
||||
Easy as 1, 2, 3... 4
|
||||
|
||||
<details>
|
||||
<summary>1. Create a node project</summary>
|
||||
|
||||
## 1. Create a node project
|
||||
|
||||
Create an empty node project.
|
||||
|
||||
Be sure to fill out the package name, version, and an author email.
|
||||
You define your app and let Greenlock handle issuing and renewing Free SSL Certificates.
|
||||
|
||||
```bash
|
||||
mkdir ~/my-project
|
||||
pushd ~/my-project
|
||||
npm init
|
||||
npm install --save greenlock-express@v4
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2. Create an http app (i.e. express)</summary>
|
||||
|
||||
## 2. Create an http app (i.e. express)
|
||||
|
||||
This example is shown with Express, but any node app will doGreenlock
|
||||
works with everything.
|
||||
(or any node-style http app)
|
||||
|
||||
`my-express-app.js`:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
// A plain, node-style app
|
||||
|
||||
function myPlainNodeHttpApp(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
}
|
||||
|
||||
// Wrap that plain app in express,
|
||||
// because that's what you're used to
|
||||
|
||||
var express = require("express");
|
||||
var app = express();
|
||||
app.get("/", myPlainNodeHttpApp);
|
||||
|
||||
// export the app normally
|
||||
// do not .listen()
|
||||
|
||||
module.exports = app;
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>3. Serve with Greenlock Express</summary>
|
||||
|
||||
## 3. Serve with Greenlock Express
|
||||
|
||||
Greenlock Express is designed with these goals in mind:
|
||||
|
||||
- Simplicity and ease-of-use
|
||||
- Performance and scalability
|
||||
- Configurability and control
|
||||
|
||||
You can start with **near-zero configuration** and
|
||||
slowly add options for greater performance and customization
|
||||
later, if you need them.
|
||||
|
||||
`server.js`:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
var app = require("./app.js");
|
||||
|
||||
require("greenlock-express")
|
||||
.init(getConfig)
|
||||
.serve(worker);
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
function getConfig() {
|
||||
return {
|
||||
// uses name and version as part of the ACME client user-agent
|
||||
// uses author as the contact for support notices
|
||||
package: require("./package.json")
|
||||
};
|
||||
}
|
||||
// contact for security and critical bug notices
|
||||
maintainerEmail: "jon@example.com",
|
||||
|
||||
function worker(server) {
|
||||
// Works with any Node app (Express, etc)
|
||||
var app = require("my-express-app.js");
|
||||
server.serveApp(app);
|
||||
}
|
||||
// whether or not to run at cloudscale
|
||||
cluster: false
|
||||
})
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
.serve(app);
|
||||
```
|
||||
|
||||
And start your server:
|
||||
`./greenlock.d/config.json`:
|
||||
|
||||
```bash
|
||||
# Allow non-root node to use ports 80 (HTTP) and 443 (HTTPS)
|
||||
sudo setcap 'cap_net_bind_service=+ep' $(which node)
|
||||
```json
|
||||
{ "sites": [{ "subject": "example.com", "altnames": ["example.com"] }] }
|
||||
```
|
||||
|
||||
# Let's Encrypt for...
|
||||
|
||||
- IoT
|
||||
- Enterprise On-Prem
|
||||
- Local Development
|
||||
- Home Servers
|
||||
- Quitting Heroku
|
||||
|
||||
# Features
|
||||
|
||||
- [x] Let's Encrypt v2 (November 2019)
|
||||
- [x] ACME Protocol (RFC 8555)
|
||||
- [x] HTTP Validation (HTTP-01)
|
||||
- [x] DNS Validation (DNS-01)
|
||||
- [ ] ALPN Validation (TLS-ALPN-01)
|
||||
- Need ALPN validation? [contact us](mailto:greenlock-support@therootcompany.com)
|
||||
- [x] Automated HTTPS
|
||||
- [x] Fully Automatic Renewals every 45 days
|
||||
- [x] Free SSL
|
||||
- [x] **Wildcard** SSL
|
||||
- [x] **Localhost** certificates
|
||||
- [x] HTTPS-enabled Secure **WebSockets** (`wss://`)
|
||||
- [x] **Cloud-ready** with Node `cluster`.
|
||||
- [x] Fully customizable
|
||||
- [x] **Reasonable defaults**
|
||||
- [x] Domain Management
|
||||
- [x] Key and Certificate Management
|
||||
- [x] ACME Challenge Plugins
|
||||
|
||||
# Compatibility
|
||||
|
||||
Works with _any_ node http app, including
|
||||
|
||||
- [x] Express
|
||||
- [x] Koa
|
||||
- [x] hapi
|
||||
- [x] rill
|
||||
- [x] http2
|
||||
- [x] cluster
|
||||
- [x] etc...
|
||||
|
||||
# v4 QuickStart
|
||||
|
||||
Serving sites with Free SSL is as easy as 1, 2, 3... 4
|
||||
|
||||
## Overview
|
||||
|
||||
1. Create a Project with Greenlock Express
|
||||
- `server.js`
|
||||
- `app.js`
|
||||
2. Setup the config file (or database)
|
||||
- `.greenlockrc`
|
||||
- `greenlock.d/config.json`
|
||||
3. Add Domains
|
||||
- `npx greenlock add --subject example.com --altnames example.com`
|
||||
4. Hello, World!
|
||||
- `npm start -- --staging`
|
||||
|
||||
### TL;DR
|
||||
|
||||
If you're familiar with node, npm, and npx: this is all you need to do:
|
||||
|
||||
```bash
|
||||
# `npm start` will call `node ./server.js` by default
|
||||
npm start
|
||||
npm init
|
||||
npm install --save greenlock-express@v4
|
||||
|
||||
npx greenlock init --config-dir greenlock.d --maintainer-email jon@example.com
|
||||
npx greenlock add --subject example.com --altnames example.com
|
||||
|
||||
npm start -- --staging
|
||||
```
|
||||
|
||||
Once you've tested that that works, you can change `app.js` to suit your needs replace the built-in callbacks for things like certificate storage as you like.
|
||||
|
||||
## 1. Create your Project
|
||||
|
||||
If you need to install Node.js, do so:
|
||||
|
||||
Mac, Linux:
|
||||
|
||||
```bash
|
||||
curl -fsS https://webinstall.dev/node | bash
|
||||
```
|
||||
|
||||
Windows 10:
|
||||
|
||||
```pwsh
|
||||
curl -fsSA "MS" https://webinstall.dev/node | powershell
|
||||
```
|
||||
|
||||
Then create a directory for your project, and initialize it:
|
||||
|
||||
```bash
|
||||
mkdir -p my-sites
|
||||
pushd my-sites
|
||||
npm init
|
||||
npm install --save greenlock-express@v4
|
||||
```
|
||||
|
||||
## 2. Initialize and Config (Dir or DB)
|
||||
|
||||
You can use **local file storage** or a **database**. The default is to use file storage.
|
||||
|
||||
You'll need to create `server.js` and `greenlock.d/config.json`. You can do so using the CLI, API, or by hand.
|
||||
|
||||
### Using the CLI (simplest, recommended)
|
||||
|
||||
Anytime you install an npm module that contains an executable,
|
||||
you can run it using `npx`.
|
||||
|
||||
To initialize the Greenlock config, run `npx greenlock init`:
|
||||
|
||||
```bash
|
||||
npx greenlock init --config-dir ./greenlock.d --maintainer-email 'jon@example.com'
|
||||
```
|
||||
|
||||
### By Hand (for advanced users)
|
||||
|
||||
Create `server.js` like so:
|
||||
|
||||
`server.js`:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
var app = require('./app.js');
|
||||
|
||||
require('greenlock-express')
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
|
||||
// where to look for configuration
|
||||
configDir: './greenlock.d',
|
||||
|
||||
// whether or not to run at cloudscale
|
||||
cluster: false
|
||||
})
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
.serve(app);
|
||||
```
|
||||
|
||||
Create `app.js` like so:
|
||||
|
||||
`app.js`:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
// Here's a vanilla HTTP app to start,
|
||||
// but feel free to replace it with Express, Koa, etc
|
||||
var app = function(req, res) {
|
||||
res.end('Hello, Encrypted World!');
|
||||
};
|
||||
|
||||
module.exports = app;
|
||||
```
|
||||
|
||||
Greenlock uses `.greenlockrc` to figure out whether to use the file system or a database for config,
|
||||
as well as where its root directory is.
|
||||
|
||||
`.greenlockrc`
|
||||
|
||||
```json
|
||||
{"manager":{"module":"@greenlock/manager"},"configDir":"greenlock.d"}
|
||||
```
|
||||
|
||||
The `greenlock.d/config.json` is NOT intended to be edited by hand, as it is a substitute for a database, but it looks like this:
|
||||
|
||||
```json
|
||||
{ "defaults": { "subscriberEmail": "john.doe@example.com" }, "sites": [] }
|
||||
```
|
||||
|
||||
## 3. Add Sites
|
||||
|
||||
For security, you must specify which sites you allow to request certificates. If you need this to be dynamic (i.e. checking a database or API, see the section below on custom site managers).
|
||||
|
||||
Every site has a "subject" (its primary domain name) and one or more "altnames" (secondary or related domain names on the same certificate).
|
||||
|
||||
### Using CLI (simple, recommended)
|
||||
|
||||
Simply supply the names of sites that you manage and they will be added to the file system config, or database.
|
||||
|
||||
```bash
|
||||
npx greenlock add --subject example.com --altnames example.com,www.example.com
|
||||
```
|
||||
|
||||
### By Hand (debugging only)
|
||||
|
||||
You should NOT edit `greenlock.d/config.json` with your own tools. Use `greenlock.manager.add({})` instead.
|
||||
|
||||
`greenlock.d/config.json`:
|
||||
|
||||
<!-- TODO update manager to write array rather than object -->
|
||||
|
||||
```json
|
||||
{ "sites": [{ "subject": "example.com", "altnames": [ "example.com", "www.example.com" ] }] }
|
||||
```
|
||||
|
||||
## 4. Hello, Encrypted World!
|
||||
|
||||
That was it! Now you can run your server!
|
||||
|
||||
When you run `npm start`, it will automatically run `node server.js` (or `package.json.scripts.start`).
|
||||
|
||||
For arguments that `npm start` should ignore, place them after `--`.
|
||||
|
||||
Here we use `--staging` in order to tell greenlock to issue test certificates rather than real certificates.
|
||||
|
||||
```bash
|
||||
# Note: you can use npm start to run server.js with the --staging flag set
|
||||
npm start -- --staging
|
||||
```
|
||||
|
||||
```txt
|
||||
Greenlock v3.0.0
|
||||
Greenlock Manager Config File: ~/.config/greenlock/manager.json
|
||||
Greenlock Storage Directory: ~/.config/greenlock/
|
||||
> my-project@1.0.0 start /srv/www/my-project
|
||||
> node server.js
|
||||
|
||||
Listening on 0.0.0.0:80 for ACME challenges and HTTPS redirects
|
||||
Listening on 0.0.0.0:443 for secure traffic
|
||||
```
|
||||
|
||||
</details>
|
||||
If everything worked you can visit your site in your browser, and after a few seconds you'll get a certificate warning and, after that, see a "Hello World" message. The debug (staging) certificates will be saved in `greenlock.d/staging`. Run again without `--staging` and you will get real certificates.
|
||||
|
||||
<details>
|
||||
<summary>4. Manage SSL Certificates and Domains</summary>
|
||||
### Season to taste
|
||||
|
||||
## 4. Manage domains
|
||||
Now you're ready to update `app.js` with your code. For example, try this next:
|
||||
|
||||
The management API is built to work with Databases, S3, etc.
|
||||
```bash
|
||||
npm install --save express
|
||||
mkdir -p public
|
||||
echo '<h1>Hello!</h1>' >> public/index.html
|
||||
```
|
||||
|
||||
HOWEVER, by default it starts with a simple config file.
|
||||
`app.js`:
|
||||
|
||||
<!--
|
||||
This will update the config file (assuming the default fs-based management plugin):
|
||||
-->
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
`~/.config/greenlock/manager.json`:
|
||||
var path = require('path');
|
||||
var express = require('express');
|
||||
var app = express();
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "letsencrypt-test@therootcompany.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
}
|
||||
app.get('/', express.static(path.join(__dirname, "public")));
|
||||
|
||||
module.exports = app;
|
||||
|
||||
// for development and debugging
|
||||
if (require.main === module) {
|
||||
require('http').createServer(app).listen(3000, function () {
|
||||
console.info("Listening for HTTP on", this.address());
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
COMING SOON
|
||||
# Walkthrough
|
||||
|
||||
Management can be done via the **CLI** or the JavaScript [**API**](https://git.rootprojects.org/root/greenlock.js/).
|
||||
Since this is the QuickStart, we'll demo the **CLI**:
|
||||
For a more detail read the full
|
||||
[WALKTHROUGH](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/WALKTHROUGH.md).
|
||||
|
||||
You need to create a Let's Encrypt _subscriber account_, which can be done globally, or per-site.
|
||||
All individuals, and most businesses, should set this globally:
|
||||
# Examples
|
||||
|
||||
```bash
|
||||
# COMING SOON
|
||||
# (this command should be here by Nov 5th)
|
||||
# (edit the config by hand for now)
|
||||
#
|
||||
# Set a global subscriber account
|
||||
npx greenlock config --subscriber-email 'mycompany@example.com' --agree-to-terms true
|
||||
```
|
||||
To see all of the examples, just browse [greenlock-express.js/examples/](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples)
|
||||
|
||||
<!-- todo print where the key was saved -->
|
||||
| Example | Location + Description |
|
||||
| :--------------------: | :----------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Express | [./examples/express/][ex-express] how to export an express app |
|
||||
| Node's **http2** | [./examples/http2/][ex-http2] how to use Node's built-in http2 server |
|
||||
| Node's https | [./examples/https][ex-https] how to customize the https server |
|
||||
| **WebSockets** | [./examples/websockets/][ex-websockets] how to use `on('upgrade')` |
|
||||
| <span>Socket.IO</span> | [./examples/socket.io][ex-socketio] how to overcomplicate a persistent connection |
|
||||
| Cluster | [./examples/cluster/][ex-cluster] how to use Node's built-in clustering with master and worker processes |
|
||||
| **Wildcards** | [coming someday][ex-wildcards] (ask to help create this) how to use DNS-01 for wildcard certs |
|
||||
| **Localhost** | [coming someday][ex-localhost] (ask to help create this) how to use DNS-01 for domains that resolve to private networks, such as 127.0.0.1 |
|
||||
| **CI/CD** | [coming someday][ex-cicd] (ask to help create this) how to use the `--staging` environment for test deployments |
|
||||
| HTTP Proxy | [examples/http-proxy][ex-http-proxy] how to (reverse) proxy decrypted traffic to another server |
|
||||
| - | Build your own<br>Be sure to tell me about it (open an issue) |
|
||||
|
||||
A Let's Encrypt SSL certificate has a "Subject" (Primary Domain) and up to 100 "Alternative Names"
|
||||
(of which the first _must_ be the subject).
|
||||
[ex-express]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/express/
|
||||
[ex-http2]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http2/
|
||||
[ex-https]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/https/
|
||||
[ex-websockets]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/websockets/
|
||||
[ex-socketio]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/socketo.io/
|
||||
[ex-cluster]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/cluster/
|
||||
[ex-wildcards]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/wildcards/
|
||||
[ex-localhost]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/localhost/
|
||||
[ex-cicd]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/ci-cd/
|
||||
[ex-http-proxy]: https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http-proxy/
|
||||
|
||||
```bash
|
||||
# COMING SOON
|
||||
# (this command should be here by Nov 5th)
|
||||
# (edit the config by hand for now)
|
||||
#
|
||||
# Add a certificate with specific domains
|
||||
npx greenlock add --subject example.com --altnames example.com,www.example.com
|
||||
```
|
||||
|
||||
<!-- todo print where the cert was saved -->
|
||||
# FAQ
|
||||
## 1. But did YOU read the QuickStart?
|
||||
|
||||
Note: **Localhost**, **Wildcard**, and Certificates for Private Networks require
|
||||
[**DNS validation**](https://git.rootprojects.org/root/greenlock-exp).
|
||||
99% of the questions I get are answered in the QuickStart, or in the Examples.
|
||||
|
||||
- DNS Validation
|
||||
- [**Wildcards**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/wildcards/) (coming soon)
|
||||
- [**Localhost**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/localhost/) (coming soon)
|
||||
- [**CI/CD**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/ci-cd/) (coming soon)
|
||||
Before you go into your specific use case, just try out the QuickStart from start to finish so that you can see that the default setup works, you get feel for the "lay of the land", and you know what to edit.
|
||||
|
||||
</details>
|
||||
## 2. How to use JavaScript configuration?
|
||||
|
||||
# Plenty of Examples
|
||||
You don't. It's JSON on purpose.
|
||||
|
||||
**These are in-progress** Check back tomorrow (Nov 2nd, 2019).
|
||||
The configuration has to be serializable (i.e. could go in a database).
|
||||
|
||||
- [greenlock-express.js/examples/](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples)
|
||||
- [Express](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/express/)
|
||||
- [Node's **http2**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http2/)
|
||||
- [Node's https](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/https/)
|
||||
- [**WebSockets**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/websockets/)
|
||||
- [Socket.IO](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/socket-io/)
|
||||
- [Cluster](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/cluster/)
|
||||
- [**Wildcards**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/wildcards/) (coming soon)
|
||||
- [**Localhost**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/localhost/) (coming soon)
|
||||
- [**CI/CD**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/ci-cd/) (coming soon)
|
||||
- [HTTP Proxy](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http-proxy/)
|
||||
The config file is meant for **simple** use cases, for the average dev and it is managed with `npx greenlock ...`, as shown in the QuickStart.
|
||||
|
||||
If you have a **dynamic** or **advanced** use case (i.e. you need stuff in a database, or to change config on-the-fly), you can use the Greenlock API (not Greenlock Express) and you'll love it.
|
||||
|
||||
If you're layering a lot of **complexity** with dev ops tools, but you don't really understand the tools that well (i.e. **Docker**), either use ENVIRONMENT variables or put the `npx greenlock ...` commands in your setup script. You MUST use a database for **lambda** "cloud functions" and such.
|
||||
|
||||
You can also just mangle the Greenlock API to do what you want... but I don't recommend it. Keep it simple and your future self with thank you.
|
||||
|
||||
General rule of thumb: commit code, not data / config.
|
||||
|
||||
## 3. How to use non-standard ports (not 80, 443)?
|
||||
|
||||
You don't. Not usually.
|
||||
|
||||
Let's Encrypt **REQUIRES port 80** for HTTP-01 challenges.
|
||||
|
||||
But if you're using DNS-01 or you have a proxy in place, just use the raw node server. See these examples:
|
||||
|
||||
- [examples/http/server.js](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http/server.js)
|
||||
- [examples/https/server.js](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/https/server.js)
|
||||
|
||||
If you want to use Greenlock as a proxy, see this example:
|
||||
|
||||
- [examples/http-proxy/server.js](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/http-proxy/server.js)
|
||||
|
||||
# Troubleshooting
|
||||
|
||||
### 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?
|
||||
- **valid email**
|
||||
- You MUST set `maintainerEmail` 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 ./greenlock.d/config.json`)
|
||||
- **port binding privileges**
|
||||
- You MUST be able to bind to ports 80 and 443
|
||||
- You can do this via `sudo` or [`setcap`](https://gist.github.com/firstdoit/6389682)
|
||||
- **API limits**
|
||||
- You MUST NOT exceed the API [**usage limits**](https://letsencrypt.org/docs/staging-environment/) per domain, certificate, IP address, etc
|
||||
- **Red Lock, Untrusted**
|
||||
- You MUST switch from `npm start -- --staging` to `npm start` to use the **production** server
|
||||
- The API URL should not have 'acme-staging-v02', but should have 'acme-v02'
|
||||
|
||||
# Using a Database, S3, etc
|
||||
|
||||
If you have a small site, the default file storage will work well for you.
|
||||
|
||||
If you have many sites with many users, you'll probably want to store config in a database of some sort.
|
||||
|
||||
See the section on **Custom** callbacks and plugins below.
|
||||
|
||||
# Advanced Configuration
|
||||
|
||||
All of the advanced configuration is done by replacing the default behavior with callbacks.
|
||||
|
||||
You can whip up your own, or you can use something that's published to npm.
|
||||
|
||||
See the section on **Custom** callbacks and plugins below.
|
||||
|
||||
# Easy to Customize
|
||||
|
||||
|
@ -300,10 +422,41 @@ Note: **Localhost**, **Wildcard**, and Certificates for Private Networks require
|
|||
- [greenlock.js/examples/](https://git.rootprojects.org/root/greenlock.js/src/branch/master/examples)
|
||||
-->
|
||||
|
||||
- [Custom Domain Management](https://git.rootprojects.org/root/greenlock-manager-test.js)
|
||||
- [Custom Key & Cert Storage](https://git.rootprojects.org/root/greenlock-store-test.js)
|
||||
- [Custom ACME HTTP-01 Challenges](https://git.rootprojects.org/root/acme-http-01-test.js)
|
||||
- [Custom ACME DNS-01 Challenges](https://git.rootprojects.org/root/acme-dns-01-test.js)
|
||||
- [Custom Domain Management](https://git.rootprojects.org/root/greenlock-manager-test.js)
|
||||
- edit `server.js` and/or `.greenlockrc` to switch from the default `configDir` manager to your config system or database
|
||||
- CLI example: `npx greenlock init --manager ./path-or-npm-name.js --manager-FOO 'set option FOO'`
|
||||
- [Custom Key & Cert Storage](https://git.rootprojects.org/root/greenlock-store-test.js)
|
||||
- edit the `defaults` section of `greenlock.d/config.json` to change the certificate store or database
|
||||
- CLI example: `npx greenlock defaults --store greenlock-store-fs --store-base-path ./greenlock.d`
|
||||
- [Custom ACME HTTP-01 Challenges](https://git.rootprojects.org/root/acme-http-01-test.js)
|
||||
- edit the `defaults` section of `greenlock.d/config.json` to change the challenges by hand
|
||||
- CLI example: `npx greenlock defaults --challenge-http-01 ./you-http-01.js`
|
||||
- [Custom ACME DNS-01 Challenges](https://git.rootprojects.org/root/acme-dns-01-test.js)
|
||||
- edit the `defaults` section of `greenlock.d/config.json` to change the challenges by hand
|
||||
- CLI example: `npx greenlock defaults --challenge-dns-01 acme-dns-01-ovh --challenge-dns-01-token xxxx`
|
||||
- Per-site example: `npx greenlock update --subject example.com --challenge-dns-01 ./your-dns-01.js`
|
||||
- API example:
|
||||
```js
|
||||
greenlock.sites.set({
|
||||
subject: "example.com",
|
||||
challenges: {
|
||||
"dns-01": {
|
||||
module: "my-npm-module-name",
|
||||
foo: "some option",
|
||||
bar: "some other option"
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
If you're using the default `configDir` management you can edit `greenlock.d/config.json` by hand to change
|
||||
which default and per-site modules are used.
|
||||
|
||||
You can use the CLI, even if you're using a database, buckets, or your own file storage.
|
||||
|
||||
You can also use the API, particularly if you need to set values dynamically per-site or per-user
|
||||
rather than using the global defaults. The certificate store and all challenges can be set
|
||||
per-site, but most per-site use cases are for DNS-01.
|
||||
|
||||
# Ready-made Integrations
|
||||
|
||||
|
@ -327,6 +480,13 @@ Greenlock Express integrates between Let's Encrypt's ACME Challenges and many po
|
|||
| http-01 | [Build your own](https://git.rootprojects.org/root/acme-http-01-test.js) | acme-http-01-test |
|
||||
| tls-alpn-01 | [Contact us](mailto:support@therootcompany.com) | - |
|
||||
|
||||
Example Usage:
|
||||
|
||||
```bash
|
||||
npx greenlock defaults --challenge-dns-01 acme-dns-01-ovh --challenge-dns-01-token xxxx
|
||||
npx greenlock defaults --challenge-http-01 acme-http-01-s3 --challenge-http-01-bucket my-bucket
|
||||
```
|
||||
|
||||
Search `acme-http-01-` or `acme-dns-01-` on npm to find more.
|
||||
|
||||
# Full Documentation
|
||||
|
@ -345,12 +505,12 @@ We're working on more comprehensive documentation for this newly released versio
|
|||
|
||||
Do you need...
|
||||
|
||||
- training?
|
||||
- specific features?
|
||||
- different integrations?
|
||||
- bugfixes, on _your_ timeline?
|
||||
- custom code, built by experts?
|
||||
- commercial support and licensing?
|
||||
- training?
|
||||
- specific features?
|
||||
- different integrations?
|
||||
- bugfixes, on _your_ timeline?
|
||||
- custom code, built by experts?
|
||||
- commercial support and licensing?
|
||||
|
||||
You're welcome to [contact us](mailto:aj@therootcompany.com) in regards to IoT, On-Prem,
|
||||
Enterprise, and Internal installations, integrations, and deployments.
|
||||
|
|
|
@ -0,0 +1,256 @@
|
|||
# Greenlock Express Walkthrough
|
||||
|
||||
This will show you the basics of how to
|
||||
|
||||
1. Create a node project
|
||||
2. Create an http app (i.e. express)
|
||||
3. Serve with Greenlock Express
|
||||
4. Manage SSL Certificates and Domains
|
||||
|
||||
## 1. Create a node project
|
||||
|
||||
Create an empty node project.
|
||||
|
||||
Be sure to fill out the package name, version, and an author email.
|
||||
|
||||
```bash
|
||||
mkdir ~/my-project
|
||||
pushd ~/my-project
|
||||
npm init
|
||||
```
|
||||
|
||||
## 2. Create an http app (i.e. express)
|
||||
|
||||
This example is shown with Express, but any node app will do. Greenlock
|
||||
works with everything.
|
||||
(or any node-style http app)
|
||||
|
||||
`my-express-app.js`:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
// A plain, node-style app
|
||||
|
||||
function myPlainNodeHttpApp(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
}
|
||||
|
||||
// Wrap that plain app in express,
|
||||
// because that's what you're used to
|
||||
|
||||
var express = require("express");
|
||||
var app = express();
|
||||
app.get("/", myPlainNodeHttpApp);
|
||||
|
||||
// export the app normally
|
||||
// do not .listen()
|
||||
|
||||
module.exports = app;
|
||||
```
|
||||
|
||||
## 3. Serve with Greenlock Express
|
||||
|
||||
Greenlock Express is designed with these goals in mind:
|
||||
|
||||
- Simplicity and ease-of-use
|
||||
- Performance and scalability
|
||||
- Configurability and control
|
||||
|
||||
You can start with **near-zero configuration** and
|
||||
slowly add options for greater performance and customization
|
||||
later, if you need them.
|
||||
|
||||
`server.js`:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
//var pkg = require("./package.json");
|
||||
var app = require("./app.js");
|
||||
|
||||
require("greenlock-express")
|
||||
.init({
|
||||
// where to find .greenlockrc and set default paths
|
||||
packageRoot: __dirname,
|
||||
|
||||
// where config and certificate stuff go
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
// contact for security and critical bug notices
|
||||
maintainerEmail: pkg.author,
|
||||
|
||||
// name & version for ACME client user agent
|
||||
//packageAgent: pkg.name + "/" + pkg.version,
|
||||
|
||||
// whether or not to run at cloudscale
|
||||
cluster: false
|
||||
})
|
||||
.serve(app);
|
||||
```
|
||||
|
||||
And start your server:
|
||||
|
||||
```bash
|
||||
# Allow non-root node to use ports 80 (HTTP) and 443 (HTTPS)
|
||||
sudo setcap 'cap_net_bind_service=+ep' $(which node)
|
||||
```
|
||||
|
||||
```bash
|
||||
# `npm start` will call `node ./server.js` by default
|
||||
npm start
|
||||
```
|
||||
|
||||
```bash
|
||||
# use --staging to use the development API until you're ready to get real certificates
|
||||
npm start -- --staging
|
||||
```
|
||||
|
||||
```txt
|
||||
Greenlock v4.0.0
|
||||
Greenlock Config Dir/File: ./greenlock.d/config.json
|
||||
|
||||
Listening on 0.0.0.0:80 for ACME challenges and HTTPS redirects
|
||||
Listening on 0.0.0.0:443 for secure traffic
|
||||
```
|
||||
|
||||
## 4. Manage SSL Certificates and Domains
|
||||
|
||||
The management API is built to work with Databases, S3, etc.
|
||||
|
||||
By default, it's just a simple config file and directory.
|
||||
|
||||
```bash
|
||||
# see which manager and what options are in use
|
||||
cat .greenlockrc
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example Output</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"manager": {
|
||||
"module": "@greenlock/manager"
|
||||
},
|
||||
"configDir": "./greenlock.d"
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
```bash
|
||||
# show the global defaults with the CLI
|
||||
npx greenlock defaults
|
||||
```
|
||||
|
||||
```js
|
||||
// show the global defaults with the API
|
||||
var defaults = await greenlock.defaults();
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example Output</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"store": {
|
||||
"module": "greenlock-store-fs",
|
||||
"basePath": "./greenlock.d"
|
||||
},
|
||||
"challenges": {
|
||||
"http-01": {
|
||||
"module": "acme-http-01-standalone"
|
||||
}
|
||||
},
|
||||
"renewOffset": "-45d",
|
||||
"renewStagger": "3d",
|
||||
"accountKeyType": "EC-P256",
|
||||
"serverKeyType": "RSA-2048",
|
||||
"subscriberEmail": "jon@example.com",
|
||||
"agreeToTerms": true
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
```bash
|
||||
# show per-site configs with the CLI
|
||||
npx greenlock config --subject example.com
|
||||
```
|
||||
|
||||
```js
|
||||
// show a site config with the API
|
||||
greenlock.sites.get({ subject: "example.com" });
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example Output</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com"],
|
||||
"renewAt": 1576638107754,
|
||||
"defaults": {
|
||||
"store": {
|
||||
"module": "greenlock-store-fs",
|
||||
"basePath": "./greenlock.d"
|
||||
},
|
||||
"challenges": {
|
||||
"http-01": {
|
||||
"module": "acme-http-01-standalone"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Management can be done via the **CLI** or the JavaScript [**API**](https://git.rootprojects.org/root/greenlock.js).
|
||||
Since this is the QuickStart, we'll demo the **CLI**:
|
||||
|
||||
You need to create a Let's Encrypt _subscriber account_, which can be done globally, or per-site.
|
||||
All individuals, and most businesses, should set this globally:
|
||||
|
||||
```bash
|
||||
# Set a global subscriber account with the CLI
|
||||
npx greenlock defaults --subscriber-email 'mycompany@example.com' --agree-to-terms true
|
||||
```
|
||||
|
||||
```js
|
||||
// set a global subscriber account with the API
|
||||
greenlock.manager.defaults({
|
||||
subscriberEmail: "mycompany@example.com",
|
||||
agreeToTerms: true
|
||||
});
|
||||
```
|
||||
|
||||
<!-- todo print where the key was saved -->
|
||||
|
||||
A Let's Encrypt SSL certificate has a "Subject" (Primary Domain) and up to 100 "Alternative Names"
|
||||
(of which the first _must_ be the subject).
|
||||
|
||||
```bash
|
||||
# Add a certificate with specific domains with the CLI
|
||||
npx greenlock add --subject example.com --altnames example.com,www.example.com
|
||||
```
|
||||
|
||||
```js
|
||||
// Add a certificate with specific domains with the API
|
||||
greenlock.sites.add({
|
||||
subject: "example.com",
|
||||
altnames: ["example.com"]
|
||||
});
|
||||
```
|
||||
|
||||
<!-- todo print where the cert was saved -->
|
||||
|
||||
Note: **Localhost**, **Wildcard**, and Certificates for Private Networks require
|
||||
[**DNS validation**](https://git.rootprojects.org/root/greenlock-exp).
|
||||
|
||||
- DNS Validation
|
||||
- [**Wildcards**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/wildcards/) (coming soon)
|
||||
- [**Localhost**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/localhost/) (coming soon)
|
||||
- [**CI/CD**](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/ci-cd/) (coming soon)
|
28
config.js
28
config.js
|
@ -2,19 +2,19 @@
|
|||
|
||||
var path = require("path");
|
||||
module.exports = {
|
||||
email: "jon.doe@example.com",
|
||||
configDir: path.join(__dirname, "acme"),
|
||||
srv: "/srv/www/",
|
||||
api: "/srv/api/",
|
||||
proxy: {
|
||||
"example.com": "http://localhost:4080",
|
||||
"*.example.com": "http://localhost:4080"
|
||||
},
|
||||
email: "jon.doe@example.com",
|
||||
configDir: path.join(__dirname, "acme"),
|
||||
srv: "/srv/www/",
|
||||
api: "/srv/api/",
|
||||
proxy: {
|
||||
"example.com": "http://localhost:4080",
|
||||
"*.example.com": "http://localhost:4080"
|
||||
},
|
||||
|
||||
// DNS-01 challenges only
|
||||
challenges: {
|
||||
"*.example.com": require("acme-dns-01-YOUR_DNS_HOST").create({
|
||||
token: "xxxx"
|
||||
})
|
||||
}
|
||||
// DNS-01 challenges only
|
||||
challenges: {
|
||||
"*.example.com": require("acme-dns-01-YOUR_DNS_HOST").create({
|
||||
token: "xxxx"
|
||||
})
|
||||
}
|
||||
};
|
||||
|
|
48
demo.js
48
demo.js
|
@ -1,35 +1,35 @@
|
|||
"use strict";
|
||||
|
||||
require("./")
|
||||
.init(initialize)
|
||||
.serve(worker)
|
||||
.master(function() {
|
||||
console.log("Hello from master");
|
||||
});
|
||||
.init(initialize)
|
||||
.serve(worker)
|
||||
.master(function() {
|
||||
console.log("Hello from master");
|
||||
});
|
||||
|
||||
function initialize() {
|
||||
var pkg = require("./package.json");
|
||||
var config = {
|
||||
package: {
|
||||
name: "Greenlock_Express_Demo",
|
||||
version: pkg.version,
|
||||
author: pkg.author
|
||||
},
|
||||
staging: true,
|
||||
cluster: true,
|
||||
var pkg = require("./package.json");
|
||||
var config = {
|
||||
package: {
|
||||
name: "Greenlock_Express_Demo",
|
||||
version: pkg.version,
|
||||
author: pkg.author
|
||||
},
|
||||
staging: true,
|
||||
cluster: true,
|
||||
|
||||
notify: function(ev, params) {
|
||||
console.info(ev, params);
|
||||
}
|
||||
};
|
||||
return config;
|
||||
notify: function(ev, params) {
|
||||
console.info(ev, params);
|
||||
}
|
||||
};
|
||||
return config;
|
||||
}
|
||||
|
||||
function worker(glx) {
|
||||
console.info();
|
||||
console.info("Hello from worker #" + glx.id());
|
||||
console.info();
|
||||
console.info("Hello from worker #" + glx.id());
|
||||
|
||||
glx.serveApp(function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
glx.serveApp(function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
}
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "cluster-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,39 +1,41 @@
|
|||
"use strict";
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "websocket-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
maintainerEmail: "jon@example.com",
|
||||
|
||||
// When you're ready to go full cloud scale, you just change this to true:
|
||||
// Note: in cluster you CANNOT use in-memory state (see below)
|
||||
cluster: true,
|
||||
// When you're ready to go full cloud scale, you just change this to true:
|
||||
// Note: in cluster you CANNOT use in-memory state (see below)
|
||||
cluster: true,
|
||||
|
||||
// This will default to the number of workers being equal to
|
||||
// n-1 cpus, with a minimum of 2
|
||||
workers: 4
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
// This will default to the number of workers being equal to
|
||||
// n-1 cpus, with a minimum of 2
|
||||
workers: 4
|
||||
})
|
||||
// ready is only executed by workers (no-op in master)
|
||||
.ready(httpsWorker)
|
||||
// master is only executed by master (no-op in a worker)
|
||||
.master(function() {
|
||||
console.info("I'm the master");
|
||||
});
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// WRONG
|
||||
// This won't work like you
|
||||
// think because EACH worker
|
||||
// has ITS OWN `count`.
|
||||
var count = 0;
|
||||
// WRONG
|
||||
// This won't work like you
|
||||
// think because EACH worker
|
||||
// has ITS OWN `count`.
|
||||
var count = 0;
|
||||
|
||||
var app = function(req, res) {
|
||||
res.end("Hello... how many times now? Oh, " + count + " times");
|
||||
count += 1;
|
||||
};
|
||||
var app = function(req, res) {
|
||||
res.end("Hello... how many times now? Oh, " + count + " times");
|
||||
count += 1;
|
||||
};
|
||||
|
||||
// Serves on 80 and 443... for each worker
|
||||
// Get's SSL certificates magically!
|
||||
glx.serveApp(app);
|
||||
// Serves on 80 and 443... for each worker
|
||||
// Get's SSL certificates magically!
|
||||
glx.serveApp(app);
|
||||
}
|
||||
|
|
|
@ -4,13 +4,13 @@ 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");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
});
|
||||
|
||||
// DO NOT DO app.listen() unless we're testing this directly
|
||||
if (require.main === module) {
|
||||
app.listen(3000);
|
||||
app.listen(3000);
|
||||
}
|
||||
|
||||
// Instead do export the app:
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "express-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,27 +1,22 @@
|
|||
"use strict";
|
||||
|
||||
function httpsWorker(glx) {
|
||||
var app = require("./my-express-app.js");
|
||||
var app = require("./my-express-app.js");
|
||||
|
||||
app.get("/hello", function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
app.get("/hello", function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
glx.serveApp(app);
|
||||
}
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "http2-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
|
||||
cluster: false
|
||||
})
|
||||
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
.serve(app);
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "http-proxy-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,44 +1,46 @@
|
|||
"use strict";
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
var proxy = require("http-proxy").createProxyServer({ xfwd: true });
|
||||
|
||||
// catches error events during proxying
|
||||
proxy.on("error", function(err, req, res) {
|
||||
console.error(err);
|
||||
res.statusCode = 500;
|
||||
res.end();
|
||||
return;
|
||||
});
|
||||
|
||||
// We'll proxy websockets too
|
||||
server.on("upgrade", function(req, socket, head) {
|
||||
proxy.ws(req, socket, head, {
|
||||
ws: true,
|
||||
target: "ws://localhost:3000"
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
proxy.web(req, res, {
|
||||
target: "http://localhost:3000"
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
|
||||
return {
|
||||
package: { name: "http-proxy-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
return {
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
maintainerEmail: "jon@example.com",
|
||||
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
var proxy = require("http-proxy").createProxyServer({ xfwd: true });
|
||||
|
||||
// catches error events during proxying
|
||||
proxy.on("error", function(err, req, res) {
|
||||
console.error(err);
|
||||
res.statusCode = 500;
|
||||
res.end();
|
||||
return;
|
||||
});
|
||||
|
||||
// We'll proxy websockets too
|
||||
server.on("upgrade", function(req, socket, head) {
|
||||
proxy.ws(req, socket, head, {
|
||||
ws: true,
|
||||
target: "ws://localhost:3000"
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
proxy.web(req, res, {
|
||||
target: "http://localhost:3000"
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "http-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,42 +1,38 @@
|
|||
"use strict";
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
|
||||
// The WRONG way:
|
||||
//var http = require('http');
|
||||
//var httpServer = https.createSecureServer(redirectToHttps);
|
||||
//var httpServer = http.createServer(redirectToHttps);
|
||||
//
|
||||
// Why is that wrong?
|
||||
// Greenlock needs to change some low-level http and https options.
|
||||
// Use glx.httpServer(redirectToHttps) instead.
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTP can only be used for ACME HTTP-01 Challenges
|
||||
// (and it is not required for DNS-01 challenges)
|
||||
//
|
||||
|
||||
// Get the raw http server:
|
||||
var httpServer = glx.httpServer(function(req, res) {
|
||||
res.statusCode = 301;
|
||||
res.setHeader("Location", "https://" + req.headers.host + req.path);
|
||||
res.end("Insecure connections are not allowed. Redirecting...");
|
||||
});
|
||||
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "plain-http-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTP can only be used for ACME HTTP-01 Challenges
|
||||
// (and it is not required for DNS-01 challenges)
|
||||
//
|
||||
|
||||
// Get the raw http server:
|
||||
var httpServer = glx.httpServer(function(req, res) {
|
||||
res.statusCode = 301;
|
||||
res.setHeader("Location", "https://" + req.headers.host + req.path);
|
||||
res.end("Insecure connections are not allowed. Redirecting...");
|
||||
});
|
||||
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "http2-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
"use strict";
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
|
||||
// The WRONG way:
|
||||
//var http2 = require('http2');
|
||||
//var http2Server = https.createSecureServer(tlsOptions, app);
|
||||
|
@ -10,39 +8,39 @@ var pkg = require("../../package.json");
|
|||
// Greenlock needs to change some low-level http and https options.
|
||||
// Use glx.httpsServer(tlsOptions, app) instead.
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTP2 is the default httpsServer for node v12+
|
||||
// (HTTPS/1.1 is used for node <= v11)
|
||||
//
|
||||
|
||||
// Get the raw http2 server:
|
||||
var http2Server = glx.httpsServer(function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
|
||||
http2Server.listen(443, "0.0.0.0", function() {
|
||||
console.info("Listening on ", http2Server.address());
|
||||
});
|
||||
|
||||
// Note:
|
||||
// You must ALSO listen on port 80 for ACME HTTP-01 Challenges
|
||||
// (the ACME and http->https middleware are loaded by glx.httpServer)
|
||||
var httpServer = glx.httpServer();
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "http2-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTP2 would have been the default httpsServer for node v12+
|
||||
// However... https://github.com/expressjs/express/issues/3388
|
||||
//
|
||||
|
||||
// Get the raw http2 server:
|
||||
var tlsOptions = null;
|
||||
var http2Server = glx.http2Server(tlsOptions, function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
|
||||
http2Server.listen(443, "0.0.0.0", function() {
|
||||
console.info("Listening on ", http2Server.address());
|
||||
});
|
||||
|
||||
// Note:
|
||||
// You must ALSO listen on port 80 for ACME HTTP-01 Challenges
|
||||
// (the ACME and http->https middleware are loaded by glx.httpServer)
|
||||
var httpServer = glx.httpServer();
|
||||
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "https1-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
"use strict";
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
|
||||
// The WRONG way:
|
||||
//var https = require('https');
|
||||
//var httpsServer = https.createServer(tlsOptions, app);
|
||||
|
@ -10,40 +8,38 @@ var pkg = require("../../package.json");
|
|||
// Greenlock needs to change some low-level http and https options.
|
||||
// Use glx.httpsServer(tlsOptions, app) instead.
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTPS/1.1 is only used for node v11 or lower
|
||||
// (HTTP2 is used for node v12+)
|
||||
//
|
||||
// Why not just require('https')?
|
||||
|
||||
// Get the raw https server:
|
||||
var httpsServer = glx.httpsServer(null, function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
|
||||
httpsServer.listen(443, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpsServer.address());
|
||||
});
|
||||
|
||||
// Note:
|
||||
// You must ALSO listen on port 80 for ACME HTTP-01 Challenges
|
||||
// (the ACME and http->https middleware are loaded by glx.httpServer)
|
||||
var httpServer = glx.httpServer();
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "https1-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
//
|
||||
// HTTPS 1.1 is the default
|
||||
// (HTTP2 would be the default but... https://github.com/expressjs/express/issues/3388)
|
||||
//
|
||||
|
||||
// Get the raw https server:
|
||||
var httpsServer = glx.httpsServer(null, function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
});
|
||||
|
||||
httpsServer.listen(443, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpsServer.address());
|
||||
});
|
||||
|
||||
// Note:
|
||||
// You must ALSO listen on port 80 for ACME HTTP-01 Challenges
|
||||
// (the ACME and http->https middleware are loaded by glx.httpServer)
|
||||
var httpServer = glx.httpServer();
|
||||
|
||||
httpServer.listen(80, "0.0.0.0", function() {
|
||||
console.info("Listening on ", httpServer.address());
|
||||
});
|
||||
}
|
||||
|
|
|
@ -10,13 +10,13 @@ Manage via API or the config file:
|
|||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "letsencrypt-test@therootcompany.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
}
|
||||
"subscriberEmail": "letsencrypt-test@therootcompany.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "quickstart-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,32 +1,27 @@
|
|||
"use strict";
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// This can be a node http app (shown),
|
||||
// an Express app, or Hapi, Koa, Rill, etc
|
||||
var app = function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
};
|
||||
// This can be a node http app (shown),
|
||||
// an Express app, or Hapi, Koa, Rill, etc
|
||||
var app = function(req, res) {
|
||||
res.end("Hello, Encrypted World!");
|
||||
};
|
||||
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
glx.serveApp(app);
|
||||
}
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
// Package name+version are taken from <packageRoot>/package.json and used for ACME client user agent
|
||||
packageRoot: __dirname,
|
||||
// configDir is relative to packageRoot, not _this_ file
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
// Package name+version is used for ACME client user agent
|
||||
package: { name: "websocket-example", version: pkg.version },
|
||||
// Maintainer email is the contact for critical bug and security notices
|
||||
// by default package.json.author.email will be used
|
||||
//maintainerEmail: "jon@example.com",
|
||||
|
||||
// Maintainer email is the contact for critical bug and security notices
|
||||
maintainerEmail: "jon@example.com",
|
||||
// Change to true when you're ready to make your app cloud-scale
|
||||
cluster: false
|
||||
})
|
||||
|
||||
// Change to true when you're ready to make your app cloud-scale
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
// Serves on 80 and 443
|
||||
// Get's SSL certificates magically!
|
||||
.serve(app);
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "socket-io-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -8,42 +8,39 @@
|
|||
// You can just use WebSockets
|
||||
// (see the websocket example)
|
||||
|
||||
function httpsWorker(glx) {
|
||||
var socketio = require("socket.io");
|
||||
var io;
|
||||
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
|
||||
io = socketio(server);
|
||||
|
||||
// Then you do your socket.io stuff
|
||||
io.on("connection", function(socket) {
|
||||
console.log("a user connected");
|
||||
socket.emit("Welcome");
|
||||
|
||||
socket.on("chat message", function(msg) {
|
||||
socket.broadcast.emit("chat message", msg);
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
});
|
||||
}
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "socket-io-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
var socketio = require("socket.io");
|
||||
var io;
|
||||
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
|
||||
io = socketio(server);
|
||||
|
||||
// Then you do your socket.io stuff
|
||||
io.on("connection", function(socket) {
|
||||
console.log("a user connected");
|
||||
socket.emit("Welcome");
|
||||
|
||||
socket.on("chat message", function(msg) {
|
||||
socket.broadcast.emit("chat message", msg);
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
// SPDY is dead. It was replaced by HTTP2, which is a native node module
|
||||
//
|
||||
// Greenlock uses HTTP2 as the default https server in node v12+
|
||||
// Check out the http2 example just up one folder
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"name": "websockets-example",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"author": "John Doe <j.doe@example.com> (https://example.com/)",
|
||||
"license": "ISC"
|
||||
}
|
|
@ -1,42 +1,39 @@
|
|||
"use strict";
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
var WebSocket = require("ws");
|
||||
var ws = new WebSocket.Server({ server: server });
|
||||
ws.on("connection", function(ws, req) {
|
||||
// inspect req.headers.authorization (or cookies) for session info
|
||||
ws.send(
|
||||
"[Secure Echo Server] Hello!\nAuth: '" +
|
||||
(req.headers.authorization || "none") +
|
||||
"'\n" +
|
||||
"Cookie: '" +
|
||||
(req.headers.cookie || "none") +
|
||||
"'\n"
|
||||
);
|
||||
ws.on("message", function(data) {
|
||||
ws.send(data);
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
});
|
||||
}
|
||||
|
||||
var pkg = require("../../package.json");
|
||||
//require("greenlock-express")
|
||||
require("../../")
|
||||
.init(function getConfig() {
|
||||
// Greenlock Config
|
||||
.init({
|
||||
packageRoot: __dirname,
|
||||
configDir: "./greenlock.d",
|
||||
|
||||
return {
|
||||
package: { name: "websocket-example", version: pkg.version },
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
};
|
||||
})
|
||||
.serve(httpsWorker);
|
||||
maintainerEmail: "jon@example.com",
|
||||
cluster: false
|
||||
})
|
||||
.ready(httpsWorker);
|
||||
|
||||
function httpsWorker(glx) {
|
||||
// we need the raw https server
|
||||
var server = glx.httpsServer();
|
||||
var WebSocket = require("ws");
|
||||
var ws = new WebSocket.Server({ server: server });
|
||||
ws.on("connection", function(ws, req) {
|
||||
// inspect req.headers.authorization (or cookies) for session info
|
||||
ws.send(
|
||||
"[Secure Echo Server] Hello!\nAuth: '" +
|
||||
(req.headers.authorization || "none") +
|
||||
"'\n" +
|
||||
"Cookie: '" +
|
||||
(req.headers.cookie || "none") +
|
||||
"'\n"
|
||||
);
|
||||
ws.on("message", function(data) {
|
||||
ws.send(data);
|
||||
});
|
||||
});
|
||||
|
||||
// servers a node app that proxies requests to a localhost
|
||||
glx.serveApp(function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
});
|
||||
}
|
||||
|
|
|
@ -17,28 +17,32 @@ var GLE = module.exports;
|
|||
// under the hood. That's the hope, anyway.
|
||||
|
||||
GLE.init = function(fn) {
|
||||
if (cluster.isWorker) {
|
||||
// ignore the init function and launch the worker
|
||||
return require("./worker.js").create();
|
||||
}
|
||||
// See https://git.coolaj86.com/coolaj86/greenlock-express.js/issues/80
|
||||
if (fn && false !== fn.cluster && cluster.isWorker) {
|
||||
// ignore the init function and launch the worker
|
||||
return require("./worker.js").create();
|
||||
}
|
||||
|
||||
var opts = fn();
|
||||
if (!opts || "object" !== typeof opts) {
|
||||
throw new Error(
|
||||
"the `Greenlock.init(fn)` function should return an object `{ maintainerEmail, packageAgent, notify }`"
|
||||
);
|
||||
}
|
||||
var opts;
|
||||
if ("function" === typeof fn) {
|
||||
opts = fn();
|
||||
} else if ("object" === typeof fn) {
|
||||
opts = fn;
|
||||
}
|
||||
if (!opts || "object" !== typeof opts) {
|
||||
throw new Error("the `Greenlock.init(fn)` function should return an object `{ packageRoot, cluster }`");
|
||||
}
|
||||
|
||||
// just for ironic humor
|
||||
["cloudnative", "cloudscale", "webscale", "distributed", "blockchain"].forEach(function(k) {
|
||||
if (opts[k]) {
|
||||
opts.cluster = true;
|
||||
}
|
||||
});
|
||||
// just for ironic humor
|
||||
["cloudnative", "cloudscale", "webscale", "distributed", "blockchain"].forEach(function(k) {
|
||||
if (opts[k]) {
|
||||
opts.cluster = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (opts.cluster) {
|
||||
return require("./master.js").create(opts);
|
||||
}
|
||||
if (opts.cluster) {
|
||||
return require("./master.js").create(opts);
|
||||
}
|
||||
|
||||
return require("./single.js").create(opts);
|
||||
return require("./single.js").create(opts);
|
||||
};
|
||||
|
|
|
@ -0,0 +1,72 @@
|
|||
"use strict";
|
||||
|
||||
module.exports.create = function(opts) {
|
||||
var Greenlock = require("@root/greenlock");
|
||||
//var Init = require("@root/greenlock/lib/init.js");
|
||||
var greenlock = opts.greenlock;
|
||||
|
||||
/*
|
||||
if (!greenlock && opts.packageRoot) {
|
||||
try {
|
||||
greenlock = require(path.resolve(opts.packageRoot, "greenlock.js"));
|
||||
} catch (e) {
|
||||
if ("MODULE_NOT_FOUND" !== e.code) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
if (!greenlock) {
|
||||
//opts = Init._init(opts);
|
||||
greenlock = Greenlock.create(opts);
|
||||
}
|
||||
opts.packageAgent = addGreenlockAgent(opts);
|
||||
|
||||
try {
|
||||
if (opts.notify) {
|
||||
greenlock._defaults.notify = opts.notify;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Developer Error: notify not attached correctly");
|
||||
}
|
||||
|
||||
// re-export as top-level function to simplify rpc with workers
|
||||
greenlock.getAcmeHttp01ChallengeResponse = function(opts) {
|
||||
return greenlock.challenges.get(opts);
|
||||
};
|
||||
|
||||
greenlock._find({}).then(function(sites) {
|
||||
if (sites.length <= 0) {
|
||||
console.warn("Warning: `find({})` returned 0 sites.");
|
||||
console.warn(" Does `" + greenlock.manager._modulename + "` implement `find({})`?");
|
||||
console.warn(" Did you add sites?");
|
||||
console.warn(" npx greenlock add --subject example.com --altnames example.com");
|
||||
return;
|
||||
}
|
||||
console.info("Ready to Serve:");
|
||||
|
||||
var max = 3;
|
||||
if (sites.length >= 1) {
|
||||
sites.slice(0, max).forEach(function(site) {
|
||||
console.info("\t", site.altnames.join(" "));
|
||||
});
|
||||
}
|
||||
if (sites.length > max) {
|
||||
console.info("and %d others", sites.length - max);
|
||||
}
|
||||
});
|
||||
|
||||
return greenlock;
|
||||
};
|
||||
|
||||
function addGreenlockAgent(opts) {
|
||||
// Add greenlock as part of Agent, unless this is greenlock
|
||||
var packageAgent = opts.packageAgent || "";
|
||||
if (!/greenlock(-express|-pro)?/i.test(packageAgent)) {
|
||||
var pkg = require("./package.json");
|
||||
packageAgent += " Greenlock_Express/" + pkg.version;
|
||||
}
|
||||
|
||||
return packageAgent.trim();
|
||||
}
|
119
greenlock.js
119
greenlock.js
|
@ -1,119 +0,0 @@
|
|||
"use strict";
|
||||
|
||||
module.exports.create = function(opts) {
|
||||
opts = parsePackage(opts);
|
||||
opts.packageAgent = addGreenlockAgent(opts);
|
||||
|
||||
var Greenlock = require("@root/greenlock");
|
||||
var greenlock = Greenlock.create(opts);
|
||||
|
||||
// TODO move to greenlock proper
|
||||
greenlock.getAcmeHttp01ChallengeResponse = function(opts) {
|
||||
// TODO some sort of caching to prevent database hits?
|
||||
return greenlock
|
||||
._config({ servername: opts.servername })
|
||||
.then(function(site) {
|
||||
if (!site) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Hmm... this _should_ be impossible
|
||||
if (!site.challenges || !site.challenges["http-01"]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Greenlock._loadChallenge(site.challenges, "http-01");
|
||||
})
|
||||
.then(function(plugin) {
|
||||
return plugin
|
||||
.get({
|
||||
challenge: {
|
||||
type: opts.type,
|
||||
//hostname: opts.servername,
|
||||
altname: opts.servername,
|
||||
identifier: { value: opts.servername },
|
||||
token: opts.token
|
||||
}
|
||||
})
|
||||
.then(function(result) {
|
||||
var keyAuth;
|
||||
if (result) {
|
||||
// backwards compat that shouldn't be dropped
|
||||
// because new v3 modules had to do this to be
|
||||
// backwards compatible with Greenlock v2.7 at
|
||||
// the time.
|
||||
if (result.challenge) {
|
||||
result = challenge;
|
||||
}
|
||||
keyAuth = result.keyAuthorization;
|
||||
}
|
||||
return {
|
||||
keyAuthorization: keyAuth
|
||||
};
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return greenlock;
|
||||
};
|
||||
|
||||
function addGreenlockAgent(opts) {
|
||||
// Add greenlock as part of Agent, unless this is greenlock
|
||||
var packageAgent = opts.packageAgent || "";
|
||||
if (!/greenlock(-express|-pro)?/i.test(packageAgent)) {
|
||||
var pkg = require("./package.json");
|
||||
packageAgent += " Greenlock_Express/" + pkg.version;
|
||||
}
|
||||
|
||||
return packageAgent.trim();
|
||||
}
|
||||
|
||||
// ex: "John Doe <john@example.com> (https://john.doe)"
|
||||
// ex: "John Doe <john@example.com>"
|
||||
// ex: "<john@example.com>"
|
||||
// ex: "john@example.com"
|
||||
var looseEmailRe = /(^|[\s<])([^'" <>:;`]+@[^'" <>:;`]+\.[^'" <>:;`]+)/;
|
||||
function parsePackage(opts) {
|
||||
// 'package' is sometimes a reserved word
|
||||
var pkg = opts.package || opts.pkg;
|
||||
if (!pkg) {
|
||||
opts.maintainerEmail = parseMaintainer(opts.maintainerEmail);
|
||||
return opts;
|
||||
}
|
||||
|
||||
if (!opts.packageAgent) {
|
||||
var err = "missing `package.THING`, which is used for the ACME client user agent string";
|
||||
if (!pkg.name) {
|
||||
throw new Error(err.replace("THING", "name"));
|
||||
}
|
||||
if (!pkg.version) {
|
||||
throw new Error(err.replace("THING", "version"));
|
||||
}
|
||||
opts.packageAgent = pkg.name + "/" + pkg.version;
|
||||
}
|
||||
|
||||
if (!opts.maintainerEmail) {
|
||||
try {
|
||||
opts.maintainerEmail = pkg.author.email || pkg.author.match(looseEmailRe)[2];
|
||||
} catch (e) {}
|
||||
}
|
||||
if (!opts.maintainerEmail) {
|
||||
throw new Error("missing or malformed `package.author`, which is used as the contact for support notices");
|
||||
}
|
||||
opts.package = undefined;
|
||||
opts.maintainerEmail = parseMaintainer(opts.maintainerEmail);
|
||||
|
||||
return opts;
|
||||
}
|
||||
|
||||
function parseMaintainer(maintainerEmail) {
|
||||
try {
|
||||
maintainerEmail = maintainerEmail.match(looseEmailRe)[2];
|
||||
} catch (e) {
|
||||
maintainerEmail = null;
|
||||
}
|
||||
if (!maintainerEmail) {
|
||||
throw new Error("missing or malformed `maintainerEmail`, which is used as the contact for support notices");
|
||||
}
|
||||
return maintainerEmail;
|
||||
}
|
|
@ -5,102 +5,150 @@ var servernameRe = /^[a-z0-9\.\-]+$/i;
|
|||
var challengePrefix = "/.well-known/acme-challenge/";
|
||||
|
||||
HttpMiddleware.create = function(gl, defaultApp) {
|
||||
if (defaultApp && "function" !== typeof defaultApp) {
|
||||
throw new Error("use greenlock.httpMiddleware() or greenlock.httpMiddleware(function (req, res) {})");
|
||||
}
|
||||
if (defaultApp && "function" !== typeof defaultApp) {
|
||||
throw new Error("use greenlock.httpMiddleware() or greenlock.httpMiddleware(function (req, res) {})");
|
||||
}
|
||||
|
||||
return function(req, res, next) {
|
||||
var hostname = HttpMiddleware.sanitizeHostname(req);
|
||||
return function(req, res, next) {
|
||||
var hostname = HttpMiddleware.sanitizeHostname(req);
|
||||
|
||||
req.on("error", function(err) {
|
||||
explainError(gl, err, "http_01_middleware_socket", hostname);
|
||||
});
|
||||
req.on("error", function(err) {
|
||||
explainError(gl, err, "http_01_middleware_socket", hostname);
|
||||
});
|
||||
|
||||
if (skipIfNeedBe(req, res, next, defaultApp, hostname)) {
|
||||
return;
|
||||
}
|
||||
// Skip unless the path begins with /.well-known/acme-challenge/
|
||||
if (!hostname || 0 !== req.url.indexOf(challengePrefix)) {
|
||||
skipChallenge(req, res, next, defaultApp);
|
||||
return;
|
||||
}
|
||||
|
||||
var token = req.url.slice(challengePrefix.length);
|
||||
// HEADERS SENT DEBUG NOTE #2
|
||||
// at this point, it's most likely Let's Encrypt server
|
||||
// (or greenlock itself) performing the verification process
|
||||
// Hmmm... perhaps we should change the greenlock prefix to test
|
||||
// Anyway, we just got fast the first place where we could
|
||||
// be sending headers.
|
||||
|
||||
gl.getAcmeHttp01ChallengeResponse({ type: "http-01", servername: hostname, token: token })
|
||||
.catch(function(err) {
|
||||
respondToError(gl, res, err, "http_01_middleware_challenge_response", hostname);
|
||||
return { __done: true };
|
||||
})
|
||||
.then(function(result) {
|
||||
if (result && result.__done) {
|
||||
return;
|
||||
}
|
||||
return respondWithGrace(res, result, hostname, token);
|
||||
});
|
||||
};
|
||||
var token = req.url.slice(challengePrefix.length);
|
||||
|
||||
var done = false;
|
||||
var countA = 0;
|
||||
var countB = 0;
|
||||
gl.getAcmeHttp01ChallengeResponse({ type: "http-01", servername: hostname, token: token })
|
||||
.catch(function(err) {
|
||||
countA += 1;
|
||||
// HEADERS SENT DEBUG NOTE #3
|
||||
// This is the second possible time we could be sending headers
|
||||
respondToError(gl, res, err, "http_01_middleware_challenge_response", hostname);
|
||||
done = true;
|
||||
return { __done: true };
|
||||
})
|
||||
.then(function(result) {
|
||||
countB += 1;
|
||||
if (result && result.__done) {
|
||||
return;
|
||||
}
|
||||
if (done) {
|
||||
console.error("Sanity check fail: `done` is in a quantum state of both true and false... huh?");
|
||||
return;
|
||||
}
|
||||
// HEADERS SENT DEBUG NOTE #4b
|
||||
// This is the third/fourth possible time send headers
|
||||
return respondWithGrace(res, result, hostname, token);
|
||||
})
|
||||
.catch(function(err) {
|
||||
// HEADERS SENT DEBUG NOTE #5
|
||||
// I really don't see how this can be possible.
|
||||
// Every case appears to be accounted for
|
||||
console.error();
|
||||
console.error("[warning] Developer Error:" + (err.code || err.context || ""), countA, countB);
|
||||
console.error(err.stack);
|
||||
console.error();
|
||||
console.error(
|
||||
"This is probably the error that happens routinely on http2 connections, but we're not sure why."
|
||||
);
|
||||
console.error("To track the status or help contribute,");
|
||||
console.error("visit: https://git.rootprojects.org/root/greenlock-express.js/issues/9");
|
||||
console.error();
|
||||
try {
|
||||
res.end("Internal Server Error [1003]: See logs for details.");
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
function skipIfNeedBe(req, res, next, defaultApp, hostname) {
|
||||
if (!hostname || 0 !== req.url.indexOf(challengePrefix)) {
|
||||
if ("function" === typeof defaultApp) {
|
||||
defaultApp(req, res, next);
|
||||
} else if ("function" === typeof next) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 500;
|
||||
res.end("[500] Developer Error: app.use('/', greenlock.httpMiddleware()) or greenlock.httpMiddleware(app)");
|
||||
}
|
||||
}
|
||||
function skipChallenge(req, res, next, defaultApp) {
|
||||
if ("function" === typeof defaultApp) {
|
||||
defaultApp(req, res, next);
|
||||
} else if ("function" === typeof next) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 500;
|
||||
res.end("[500] Developer Error: app.use('/', greenlock.httpMiddleware()) or greenlock.httpMiddleware(app)");
|
||||
}
|
||||
}
|
||||
|
||||
function respondWithGrace(res, result, hostname, token) {
|
||||
var keyAuth = result && result.keyAuthorization;
|
||||
if (keyAuth && "string" === typeof keyAuth) {
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end(keyAuth);
|
||||
return;
|
||||
}
|
||||
var keyAuth = result && result.keyAuthorization;
|
||||
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
res.end(JSON.stringify({ error: { message: "domain '" + hostname + "' has no token '" + token + "'." } }));
|
||||
// HEADERS SENT DEBUG NOTE #4b
|
||||
// This is (still) the third/fourth possible time we could be sending headers
|
||||
if (keyAuth && "string" === typeof keyAuth) {
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end(keyAuth);
|
||||
return;
|
||||
}
|
||||
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
res.end(JSON.stringify({ error: { message: "domain '" + hostname + "' has no token '" + token + "'." } }));
|
||||
}
|
||||
|
||||
function explainError(gl, err, ctx, hostname) {
|
||||
if (!err.servername) {
|
||||
err.servername = hostname;
|
||||
}
|
||||
if (!err.context) {
|
||||
err.context = ctx;
|
||||
}
|
||||
(gl.notify || gl._notify)("error", err);
|
||||
return err;
|
||||
if (!err.servername) {
|
||||
err.servername = hostname;
|
||||
}
|
||||
if (!err.context) {
|
||||
err.context = ctx;
|
||||
}
|
||||
// leaving this in the build for now because it will help with existing error reports
|
||||
console.error("[warning] network connection error:", (err.context || "") + " " + err.message);
|
||||
(gl.notify || gl._notify)("error", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
function respondToError(gl, res, err, ctx, hostname) {
|
||||
err = explainError(gl, err, ctx, hostname);
|
||||
res.statusCode = 500;
|
||||
res.end("Internal Server Error: See logs for details.");
|
||||
// HEADERS SENT DEBUG NOTE #3b
|
||||
// This is (still) the second possible time we could be sending headers
|
||||
err = explainError(gl, err, ctx, hostname);
|
||||
res.statusCode = 500;
|
||||
res.end("Internal Server Error [1004]: See logs for details.");
|
||||
}
|
||||
|
||||
HttpMiddleware.getHostname = function(req) {
|
||||
return req.hostname || req.headers["x-forwarded-host"] || (req.headers.host || "");
|
||||
return req.hostname || req.headers["x-forwarded-host"] || (req.headers.host || "");
|
||||
};
|
||||
HttpMiddleware.sanitizeHostname = function(req) {
|
||||
// we can trust XFH because spoofing causes no ham in this limited use-case scenario
|
||||
// (and only telebit would be legitimately setting XFH)
|
||||
var servername = HttpMiddleware.getHostname(req)
|
||||
.toLowerCase()
|
||||
.replace(/:.*/, "");
|
||||
try {
|
||||
req.hostname = servername;
|
||||
} catch (e) {
|
||||
// read-only express property
|
||||
}
|
||||
if (req.headers["x-forwarded-host"]) {
|
||||
req.headers["x-forwarded-host"] = servername;
|
||||
}
|
||||
try {
|
||||
req.headers.host = servername;
|
||||
} catch (e) {
|
||||
// TODO is this a possible error?
|
||||
}
|
||||
// we can trust XFH because spoofing causes no ham in this limited use-case scenario
|
||||
// (and only telebit would be legitimately setting XFH)
|
||||
var servername = HttpMiddleware.getHostname(req)
|
||||
.toLowerCase()
|
||||
.replace(/:.*/, "");
|
||||
try {
|
||||
req.hostname = servername;
|
||||
} catch (e) {
|
||||
// read-only express property
|
||||
}
|
||||
if (req.headers["x-forwarded-host"]) {
|
||||
req.headers["x-forwarded-host"] = servername;
|
||||
}
|
||||
try {
|
||||
req.headers.host = servername;
|
||||
} catch (e) {
|
||||
// TODO is this a possible error?
|
||||
}
|
||||
|
||||
return (servernameRe.test(servername) && -1 === servername.indexOf("..") && servername) || "";
|
||||
return (servernameRe.test(servername) && -1 === servername.indexOf("..") && servername) || "";
|
||||
};
|
||||
|
|
|
@ -4,56 +4,56 @@ var SanitizeHost = module.exports;
|
|||
var HttpMiddleware = require("./http-middleware.js");
|
||||
|
||||
SanitizeHost.create = function(gl, app) {
|
||||
return function(req, res, next) {
|
||||
function realNext() {
|
||||
if ("function" === typeof app) {
|
||||
app(req, res);
|
||||
} else if ("function" === typeof next) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 500;
|
||||
res.end("Error: no middleware assigned");
|
||||
}
|
||||
}
|
||||
return function(req, res, next) {
|
||||
function realNext() {
|
||||
if ("function" === typeof app) {
|
||||
app(req, res);
|
||||
} else if ("function" === typeof next) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 500;
|
||||
res.end("Error: no middleware assigned");
|
||||
}
|
||||
}
|
||||
|
||||
var hostname = HttpMiddleware.getHostname(req);
|
||||
// Replace the hostname, and get the safe version
|
||||
var safehost = HttpMiddleware.sanitizeHostname(req);
|
||||
var hostname = HttpMiddleware.getHostname(req);
|
||||
// Replace the hostname, and get the safe version
|
||||
var safehost = HttpMiddleware.sanitizeHostname(req);
|
||||
|
||||
// if no hostname, move along
|
||||
if (!hostname) {
|
||||
realNext();
|
||||
return;
|
||||
}
|
||||
// if no hostname, move along
|
||||
if (!hostname) {
|
||||
realNext();
|
||||
return;
|
||||
}
|
||||
|
||||
// if there were unallowed characters, complain
|
||||
if (safehost.length !== hostname.length) {
|
||||
res.statusCode = 400;
|
||||
res.end("Malformed HTTP Header: 'Host: " + hostname + "'");
|
||||
return;
|
||||
}
|
||||
// if there were unallowed characters, complain
|
||||
if (safehost.length !== hostname.length) {
|
||||
res.statusCode = 400;
|
||||
res.end("Malformed HTTP Header: 'Host: " + hostname + "'");
|
||||
return;
|
||||
}
|
||||
|
||||
// Note: This sanitize function is also called on plain sockets, which don't need Domain Fronting checks
|
||||
if (req.socket.encrypted) {
|
||||
if (req.socket && "string" === typeof req.socket.servername) {
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
if (!SanitizeHost._checkServername(safehost, req.socket)) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(
|
||||
"<h1>Domain Fronting Error</h1>" +
|
||||
"<p>This connection was secured using TLS/SSL for '" +
|
||||
(req.socket.servername || "").toLowerCase() +
|
||||
"'</p>" +
|
||||
"<p>The HTTP request specified 'Host: " +
|
||||
safehost +
|
||||
"', which is (obviously) different.</p>" +
|
||||
"<p>Because this looks like a domain fronting attack, the connection has been terminated.</p>"
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
/*
|
||||
// Note: This sanitize function is also called on plain sockets, which don't need Domain Fronting checks
|
||||
if (req.socket.encrypted) {
|
||||
if (req.socket && "string" === typeof req.socket.servername) {
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
if (!SanitizeHost._checkServername(safehost, req.socket)) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(
|
||||
"<h1>Domain Fronting Error</h1>" +
|
||||
"<p>This connection was secured using TLS/SSL for '" +
|
||||
(req.socket.servername || "").toLowerCase() +
|
||||
"'</p>" +
|
||||
"<p>The HTTP request specified 'Host: " +
|
||||
safehost +
|
||||
"', which is (obviously) different.</p>" +
|
||||
"<p>Because this looks like a domain fronting attack, the connection has been terminated.</p>"
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
/*
|
||||
else if (safehost && !gl._skip_fronting_check) {
|
||||
|
||||
// We used to print a log message here, but it turns out that it's
|
||||
|
@ -66,74 +66,74 @@ SanitizeHost.create = function(gl, app) {
|
|||
//gl._skip_fronting_check = true;
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
// carry on
|
||||
realNext();
|
||||
};
|
||||
// carry on
|
||||
realNext();
|
||||
};
|
||||
};
|
||||
|
||||
var warnDomainFronting = true;
|
||||
var warnUnexpectedError = true;
|
||||
SanitizeHost._checkServername = function(safeHost, tlsSocket) {
|
||||
var servername = (tlsSocket.servername || "").toLowerCase();
|
||||
var servername = (tlsSocket.servername || "").toLowerCase();
|
||||
|
||||
// acceptable: older IoT devices may lack SNI support
|
||||
if (!servername) {
|
||||
return true;
|
||||
}
|
||||
// acceptable: odd... but acceptable
|
||||
if (!safeHost) {
|
||||
return true;
|
||||
}
|
||||
if (safeHost === servername) {
|
||||
return true;
|
||||
}
|
||||
// acceptable: older IoT devices may lack SNI support
|
||||
if (!servername) {
|
||||
return true;
|
||||
}
|
||||
// acceptable: odd... but acceptable
|
||||
if (!safeHost) {
|
||||
return true;
|
||||
}
|
||||
if (safeHost === servername) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ("function" !== typeof tlsSocket.getCertificate) {
|
||||
// domain fronting attacks allowed
|
||||
if (warnDomainFronting) {
|
||||
// https://github.com/nodejs/node/issues/24095
|
||||
console.warn(
|
||||
"Warning: node " +
|
||||
process.version +
|
||||
" is vulnerable to domain fronting attacks. Please use node v11.2.0 or greater."
|
||||
);
|
||||
warnDomainFronting = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if ("function" !== typeof tlsSocket.getCertificate) {
|
||||
// domain fronting attacks allowed
|
||||
if (warnDomainFronting) {
|
||||
// https://github.com/nodejs/node/issues/24095
|
||||
console.warn(
|
||||
"Warning: node " +
|
||||
process.version +
|
||||
" is vulnerable to domain fronting attacks. Please use node v11.2.0 or greater."
|
||||
);
|
||||
warnDomainFronting = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// connection established with servername and session is re-used for allowed name
|
||||
// See https://github.com/nodejs/node/issues/24095
|
||||
var cert = tlsSocket.getCertificate();
|
||||
try {
|
||||
// TODO optimize / cache?
|
||||
// *should* always have a string, right?
|
||||
// *should* always be lowercase already, right?
|
||||
//console.log(safeHost, cert.subject.CN, cert.subjectaltname);
|
||||
var isSubject = (cert.subject.CN || "").toLowerCase() === safeHost;
|
||||
if (isSubject) {
|
||||
return true;
|
||||
}
|
||||
// connection established with servername and session is re-used for allowed name
|
||||
// See https://github.com/nodejs/node/issues/24095
|
||||
var cert = tlsSocket.getCertificate();
|
||||
try {
|
||||
// TODO optimize / cache?
|
||||
// *should* always have a string, right?
|
||||
// *should* always be lowercase already, right?
|
||||
//console.log(safeHost, cert.subject.CN, cert.subjectaltname);
|
||||
var isSubject = (cert.subject.CN || "").toLowerCase() === safeHost;
|
||||
if (isSubject) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var dnsnames = (cert.subjectaltname || "").split(/,\s+/);
|
||||
var inSanList = dnsnames.some(function(name) {
|
||||
// always prefixed with "DNS:"
|
||||
return safeHost === name.slice(4).toLowerCase();
|
||||
});
|
||||
var dnsnames = (cert.subjectaltname || "").split(/,\s+/);
|
||||
var inSanList = dnsnames.some(function(name) {
|
||||
// always prefixed with "DNS:"
|
||||
return safeHost === name.slice(4).toLowerCase();
|
||||
});
|
||||
|
||||
if (inSanList) {
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
// not sure what else to do in this situation...
|
||||
if (warnUnexpectedError) {
|
||||
console.warn("Warning: encoutered error while performing domain fronting check: " + e.message);
|
||||
warnUnexpectedError = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (inSanList) {
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
// not sure what else to do in this situation...
|
||||
if (warnUnexpectedError) {
|
||||
console.warn("Warning: encoutered error while performing domain fronting check: " + e.message);
|
||||
warnUnexpectedError = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return false;
|
||||
};
|
||||
|
|
|
@ -1,37 +1,37 @@
|
|||
"use strict";
|
||||
|
||||
function requireBluebird() {
|
||||
try {
|
||||
return require("bluebird");
|
||||
} catch (e) {
|
||||
console.error("");
|
||||
console.error("DON'T PANIC. You're running an old version of node with incomplete Promise support.");
|
||||
console.error("EASY FIX: `npm install --save bluebird`");
|
||||
console.error("");
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
return require("bluebird");
|
||||
} catch (e) {
|
||||
console.error("");
|
||||
console.error("DON'T PANIC. You're running an old version of node with incomplete Promise support.");
|
||||
console.error("EASY FIX: `npm install --save bluebird`");
|
||||
console.error("");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
if ("undefined" === typeof Promise) {
|
||||
global.Promise = requireBluebird();
|
||||
global.Promise = requireBluebird();
|
||||
}
|
||||
|
||||
if ("function" !== typeof require("util").promisify) {
|
||||
require("util").promisify = requireBluebird().promisify;
|
||||
require("util").promisify = requireBluebird().promisify;
|
||||
}
|
||||
|
||||
if (!console.debug) {
|
||||
console.debug = console.log;
|
||||
console.debug = console.log;
|
||||
}
|
||||
|
||||
var fs = require("fs");
|
||||
var fsAsync = {};
|
||||
Object.keys(fs).forEach(function(key) {
|
||||
var fn = fs[key];
|
||||
if ("function" !== typeof fn || !/[a-z]/.test(key[0])) {
|
||||
return;
|
||||
}
|
||||
fsAsync[key] = require("util").promisify(fn);
|
||||
var fn = fs[key];
|
||||
if ("function" !== typeof fn || !/[a-z]/.test(key[0])) {
|
||||
return;
|
||||
}
|
||||
fsAsync[key] = require("util").promisify(fn);
|
||||
});
|
||||
|
||||
exports.fsAsync = fsAsync;
|
||||
|
|
28
main.js
28
main.js
|
@ -8,29 +8,25 @@ var minor = process.versions.node.split(".")[1];
|
|||
var _hasSetSecureContext = false;
|
||||
var shouldUpgrade = false;
|
||||
|
||||
// TODO can we trust earlier versions as well?
|
||||
if (major >= 12) {
|
||||
_hasSetSecureContext = !!require("http2").createSecureServer({}, function() {}).setSecureContext;
|
||||
} else {
|
||||
_hasSetSecureContext = !!require("https").createServer({}, function() {}).setSecureContext;
|
||||
}
|
||||
// this applies to http2 as well (should exist in both or neither)
|
||||
_hasSetSecureContext = !!require("https").createServer({}, function() {}).setSecureContext;
|
||||
|
||||
// TODO document in issues
|
||||
if (!_hasSetSecureContext) {
|
||||
// TODO this isn't necessary if greenlock options are set with options.cert
|
||||
console.warn("Warning: node " + process.version + " is missing tlsSocket.setSecureContext().");
|
||||
console.warn(" The default certificate may not be set.");
|
||||
shouldUpgrade = true;
|
||||
// TODO this isn't necessary if greenlock options are set with options.cert
|
||||
console.warn("Warning: node " + process.version + " is missing tlsSocket.setSecureContext().");
|
||||
console.warn(" The default certificate may not be set.");
|
||||
shouldUpgrade = true;
|
||||
}
|
||||
|
||||
if (major < 11 || (11 === major && minor < 2)) {
|
||||
// https://github.com/nodejs/node/issues/24095
|
||||
console.warn("Warning: node " + process.version + " is missing tlsSocket.getCertificate().");
|
||||
console.warn(" This is necessary to guard against domain fronting attacks.");
|
||||
shouldUpgrade = true;
|
||||
// https://github.com/nodejs/node/issues/24095
|
||||
console.warn("Warning: node " + process.version + " is missing tlsSocket.getCertificate().");
|
||||
console.warn(" This is necessary to guard against domain fronting attacks.");
|
||||
shouldUpgrade = true;
|
||||
}
|
||||
|
||||
if (shouldUpgrade) {
|
||||
console.warn("Warning: Please upgrade to node v11.2.0 or greater.");
|
||||
console.warn();
|
||||
console.warn("Warning: Please upgrade to node v11.2.0 or greater.");
|
||||
console.warn();
|
||||
}
|
||||
|
|
248
master.js
248
master.js
|
@ -9,152 +9,156 @@ var os = require("os");
|
|||
var msgPrefix = "greenlock:";
|
||||
|
||||
Master.create = function(opts) {
|
||||
var resolveCb;
|
||||
var _readyCb;
|
||||
var _kicked = false;
|
||||
var resolveCb;
|
||||
var _readyCb;
|
||||
var _kicked = false;
|
||||
|
||||
var greenlock = require("./greenlock.js").create(opts);
|
||||
var greenlock = require("./greenlock-shim.js").create(opts);
|
||||
|
||||
var ready = new Promise(function(resolve) {
|
||||
resolveCb = resolve;
|
||||
}).then(function(fn) {
|
||||
_readyCb = fn;
|
||||
return fn;
|
||||
});
|
||||
var ready = new Promise(function(resolve) {
|
||||
resolveCb = resolve;
|
||||
}).then(function(fn) {
|
||||
_readyCb = fn;
|
||||
return fn;
|
||||
});
|
||||
|
||||
function kickoff() {
|
||||
if (_kicked) {
|
||||
return;
|
||||
}
|
||||
_kicked = true;
|
||||
function kickoff() {
|
||||
if (_kicked) {
|
||||
return;
|
||||
}
|
||||
_kicked = true;
|
||||
|
||||
Master._spawnWorkers(opts, greenlock);
|
||||
Master._spawnWorkers(opts, greenlock);
|
||||
|
||||
ready.then(function(fn) {
|
||||
// not sure what this API should be yet
|
||||
fn();
|
||||
});
|
||||
}
|
||||
ready.then(function(fn) {
|
||||
// not sure what this API should be yet
|
||||
fn();
|
||||
});
|
||||
}
|
||||
|
||||
var master = {
|
||||
serve: function() {
|
||||
kickoff();
|
||||
return master;
|
||||
},
|
||||
master: function(fn) {
|
||||
if (_readyCb) {
|
||||
throw new Error("can't call master twice");
|
||||
}
|
||||
kickoff();
|
||||
resolveCb(fn);
|
||||
return master;
|
||||
}
|
||||
};
|
||||
return master;
|
||||
var master = {
|
||||
ready: function() {
|
||||
kickoff();
|
||||
return master;
|
||||
},
|
||||
master: function(fn) {
|
||||
if (_readyCb) {
|
||||
throw new Error("can't call master twice");
|
||||
}
|
||||
kickoff();
|
||||
resolveCb(fn);
|
||||
return master;
|
||||
},
|
||||
serve: function(fn) {
|
||||
// ignore
|
||||
master.ready(fn);
|
||||
}
|
||||
};
|
||||
return master;
|
||||
};
|
||||
|
||||
function range(n) {
|
||||
n = parseInt(n, 10);
|
||||
if (!n) {
|
||||
return [];
|
||||
}
|
||||
return new Array(n).join(",").split(",");
|
||||
n = parseInt(n, 10);
|
||||
if (!n) {
|
||||
return [];
|
||||
}
|
||||
return new Array(n).join(",").split(",");
|
||||
}
|
||||
|
||||
Master._spawnWorkers = function(opts, greenlock) {
|
||||
var numCpus = parseInt(process.env.NUMBER_OF_PROCESSORS, 10) || os.cpus().length;
|
||||
var numCpus = parseInt(process.env.NUMBER_OF_PROCESSORS, 10) || os.cpus().length;
|
||||
|
||||
// process rpc messages
|
||||
// start when dead
|
||||
var numWorkers = parseInt(opts.workers || opts.numWorkers, 10);
|
||||
if (!numWorkers) {
|
||||
if (numCpus <= 2) {
|
||||
numWorkers = 2;
|
||||
} else {
|
||||
numWorkers = numCpus - 1;
|
||||
}
|
||||
}
|
||||
// process rpc messages
|
||||
// start when dead
|
||||
var numWorkers = parseInt(opts.workers || opts.numWorkers, 10);
|
||||
if (!numWorkers) {
|
||||
if (numCpus <= 2) {
|
||||
numWorkers = 2;
|
||||
} else {
|
||||
numWorkers = numCpus - 1;
|
||||
}
|
||||
}
|
||||
|
||||
cluster.once("exit", function() {
|
||||
setTimeout(function() {
|
||||
process.exit(3);
|
||||
}, 100);
|
||||
});
|
||||
cluster.once("exit", function() {
|
||||
setTimeout(function() {
|
||||
process.exit(3);
|
||||
}, 100);
|
||||
});
|
||||
|
||||
var workers = range(numWorkers);
|
||||
function next() {
|
||||
if (!workers.length) {
|
||||
return;
|
||||
}
|
||||
workers.pop();
|
||||
var workers = range(numWorkers);
|
||||
function next() {
|
||||
if (!workers.length) {
|
||||
return;
|
||||
}
|
||||
workers.pop();
|
||||
|
||||
// for a nice aesthetic
|
||||
setTimeout(function() {
|
||||
Master._spawnWorker(opts, greenlock);
|
||||
next();
|
||||
}, 250);
|
||||
}
|
||||
// for a nice aesthetic
|
||||
setTimeout(function() {
|
||||
Master._spawnWorker(opts, greenlock);
|
||||
next();
|
||||
}, 250);
|
||||
}
|
||||
|
||||
next();
|
||||
next();
|
||||
};
|
||||
|
||||
Master._spawnWorker = function(opts, greenlock) {
|
||||
var w = cluster.fork();
|
||||
// automatically added to master's `cluster.workers`
|
||||
w.once("exit", function(code, signal) {
|
||||
// TODO handle failures
|
||||
// Should test if the first starts successfully
|
||||
// Should exit if failures happen too quickly
|
||||
var w = cluster.fork();
|
||||
// automatically added to master's `cluster.workers`
|
||||
w.once("exit", function(code, signal) {
|
||||
// TODO handle failures
|
||||
// Should test if the first starts successfully
|
||||
// Should exit if failures happen too quickly
|
||||
|
||||
// For now just kill all when any die
|
||||
if (signal) {
|
||||
console.error("worker was killed by signal:", signal);
|
||||
} else if (code !== 0) {
|
||||
console.error("worker exited with error code:", code);
|
||||
} else {
|
||||
console.error("worker unexpectedly quit without exit code or signal");
|
||||
}
|
||||
process.exit(2);
|
||||
// For now just kill all when any die
|
||||
if (signal) {
|
||||
console.error("worker was killed by signal:", signal);
|
||||
} else if (code !== 0) {
|
||||
console.error("worker exited with error code:", code);
|
||||
} else {
|
||||
console.error("worker unexpectedly quit without exit code or signal");
|
||||
}
|
||||
process.exit(2);
|
||||
|
||||
//addWorker();
|
||||
});
|
||||
//addWorker();
|
||||
});
|
||||
|
||||
function handleMessage(msg) {
|
||||
if (0 !== (msg._id || "").indexOf(msgPrefix)) {
|
||||
return;
|
||||
}
|
||||
if ("string" !== typeof msg._funcname) {
|
||||
// TODO developer error
|
||||
return;
|
||||
}
|
||||
function handleMessage(msg) {
|
||||
if (0 !== (msg._id || "").indexOf(msgPrefix)) {
|
||||
return;
|
||||
}
|
||||
if ("string" !== typeof msg._funcname) {
|
||||
// TODO developer error
|
||||
return;
|
||||
}
|
||||
|
||||
function rpc() {
|
||||
return greenlock[msg._funcname](msg._input)
|
||||
.then(function(result) {
|
||||
w.send({
|
||||
_id: msg._id,
|
||||
_result: result
|
||||
});
|
||||
})
|
||||
.catch(function(e) {
|
||||
var error = new Error(e.message);
|
||||
Object.getOwnPropertyNames(e).forEach(function(k) {
|
||||
error[k] = e[k];
|
||||
});
|
||||
w.send({
|
||||
_id: msg._id,
|
||||
_error: error
|
||||
});
|
||||
});
|
||||
}
|
||||
function rpc() {
|
||||
return greenlock[msg._funcname](msg._input)
|
||||
.then(function(result) {
|
||||
w.send({
|
||||
_id: msg._id,
|
||||
_result: result
|
||||
});
|
||||
})
|
||||
.catch(function(e) {
|
||||
var error = new Error(e.message);
|
||||
Object.getOwnPropertyNames(e).forEach(function(k) {
|
||||
error[k] = e[k];
|
||||
});
|
||||
w.send({
|
||||
_id: msg._id,
|
||||
_error: error
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
rpc();
|
||||
} catch (e) {
|
||||
console.error("Unexpected and uncaught greenlock." + msg._funcname + " error:");
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
try {
|
||||
rpc();
|
||||
} catch (e) {
|
||||
console.error("Unexpected and uncaught greenlock." + msg._funcname + " error:");
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
w.on("message", handleMessage);
|
||||
w.on("message", handleMessage);
|
||||
};
|
||||
|
|
|
@ -1,140 +1,149 @@
|
|||
{
|
||||
"name": "@root/greenlock-express",
|
||||
"version": "3.0.7",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
"@root/acme": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@root/acme/-/acme-3.0.8.tgz",
|
||||
"integrity": "sha512-VmBvLvWdCDkolkanI9Dzm1ouSWPaAa2eCCwcDZcVQbWoNiUIOqbbd57fcMA/gZxLyuJPStD2WXFuEuSMPDxcww==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/keypairs": "^0.9.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/request": "^1.3.11",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/asn1": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/asn1/-/asn1-1.0.0.tgz",
|
||||
"integrity": "sha512-0lfZNuOULKJDJmdIkP8V9RnbV3XaK6PAHD3swnFy4tZwtlMDzLKoM/dfNad7ut8Hu3r91wy9uK0WA/9zym5mig==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"@root/csr": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/csr/-/csr-0.8.1.tgz",
|
||||
"integrity": "sha512-hKl0VuE549TK6SnS2Yn9nRvKbFZXn/oAg+dZJU/tlKl/f/0yRXeuUzf8akg3JjtJq+9E592zDqeXZ7yyrg8fSQ==",
|
||||
"requires": {
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/encoding": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/encoding/-/encoding-1.0.1.tgz",
|
||||
"integrity": "sha512-OaEub02ufoU038gy6bsNHQOjIn8nUjGiLcaRmJ40IUykneJkIW5fxDqKxQx48cszuNflYldsJLPPXCrGfHs8yQ=="
|
||||
},
|
||||
"@root/greenlock": {
|
||||
"version": "3.0.17",
|
||||
"resolved": "https://registry.npmjs.org/@root/greenlock/-/greenlock-3.0.17.tgz",
|
||||
"integrity": "sha512-1XKhcLFEx1WFdn1Bc2rkAE/SL1ZUJYYMZdbnehTrfhCr5Y+9U1gdkNZnR/jInhoUvcicF/PXuZkGVucU50RNUg==",
|
||||
"requires": {
|
||||
"@root/acme": "^3.0.8",
|
||||
"@root/csr": "^0.8.1",
|
||||
"@root/keypairs": "^0.9.0",
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"@root/request": "^1.3.10",
|
||||
"acme-http-01-standalone": "^3.0.5",
|
||||
"cert-info": "^1.5.1",
|
||||
"greenlock-manager-fs": "^3.0.1",
|
||||
"greenlock-store-fs": "^3.2.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"@root/keypairs": {
|
||||
"version": "0.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/keypairs/-/keypairs-0.9.0.tgz",
|
||||
"integrity": "sha512-NXE2L9Gv7r3iC4kB/gTPZE1vO9Ox/p14zDzAJ5cGpTpytbWOlWF7QoHSJbtVX4H7mRG/Hp7HR3jWdWdb2xaaXg==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/mkdirp": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/mkdirp/-/mkdirp-1.0.0.tgz",
|
||||
"integrity": "sha512-hxGAYUx5029VggfG+U9naAhQkoMSXtOeXtbql97m3Hi6/sQSRL/4khKZPyOF6w11glyCOU38WCNLu9nUcSjOfA=="
|
||||
},
|
||||
"@root/pem": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@root/pem/-/pem-1.0.4.tgz",
|
||||
"integrity": "sha512-rEUDiUsHtild8GfIjFE9wXtcVxeS+ehCJQBwbQQ3IVfORKHK93CFnRtkr69R75lZFjcmKYVc+AXDB+AeRFOULA=="
|
||||
},
|
||||
"@root/request": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/request/-/request-1.4.1.tgz",
|
||||
"integrity": "sha512-2zSP1v9VhJ3gvm4oph0C4BYCoM3Sj84/Wx4iKdt0IbqbJzfON04EodBq5dsV65UxO/aHZciUBwY2GCZcHqaTYg=="
|
||||
},
|
||||
"@root/x509": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@root/x509/-/x509-0.7.2.tgz",
|
||||
"integrity": "sha512-ENq3LGYORK5NiMFHEVeNMt+fTXaC7DTS6sQXoqV+dFdfT0vmiL5cDLjaXQhaklJQq0NiwicZegzJRl1ZOTp3WQ==",
|
||||
"requires": {
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"acme-http-01-standalone": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/acme-http-01-standalone/-/acme-http-01-standalone-3.0.5.tgz",
|
||||
"integrity": "sha512-W4GfK+39GZ+u0mvxRVUcVFCG6gposfzEnSBF20T/NUwWAKG59wQT1dUbS1NixRIAsRuhpGc4Jx659cErFQH0Pg=="
|
||||
},
|
||||
"cert-info": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/cert-info/-/cert-info-1.5.1.tgz",
|
||||
"integrity": "sha512-eoQC/yAgW3gKTKxjzyClvi+UzuY97YCjcl+lSqbsGIy7HeGaWxCPOQFivhUYm27hgsBMhsJJFya3kGvK6PMIcQ=="
|
||||
},
|
||||
"escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
|
||||
},
|
||||
"greenlock-manager-fs": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-manager-fs/-/greenlock-manager-fs-3.0.1.tgz",
|
||||
"integrity": "sha512-vZfGFq1TTKxaAqdGDUwNservrNzXx0xCwT/ovG/N378GrhS+U5S8B8LUlNtQU7Fdw6RToMiBcm22OOxSrvZ2zw==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"greenlock-store-fs": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-store-fs/-/greenlock-store-fs-3.2.0.tgz",
|
||||
"integrity": "sha512-zqcPnF+173oYq5qU7FoGtuqeG8dmmvAiSnz98kEHAHyvgRF9pE1T0MM0AuqDdj45I3kXlCj2gZBwutnRi37J3g==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"redirect-https": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/redirect-https/-/redirect-https-1.3.0.tgz",
|
||||
"integrity": "sha512-9GzwI/+Cqw3jlSg0CW6TgBQbhiVhkHSDvW8wjgRQ9IK34wtxS71YJiQeazSCSEqbvowHCJuQZgmQFl1xUHKEgg==",
|
||||
"requires": {
|
||||
"escape-html": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"safe-replace": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-replace/-/safe-replace-1.1.0.tgz",
|
||||
"integrity": "sha512-9/V2E0CDsKs9DWOOwJH7jYpSl9S3N05uyevNjvsnDauBqRowBPOyot1fIvV5N2IuZAbYyvrTXrYFVG0RZInfFw=="
|
||||
}
|
||||
}
|
||||
"name": "@root/greenlock-express",
|
||||
"version": "4.0.4",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
"@greenlock/manager": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@greenlock/manager/-/manager-3.1.0.tgz",
|
||||
"integrity": "sha512-PBy5CMK+j4oD7sj7hF5qE+xKEOSiiuL2hHd5X5ttEbtnTSDKjNeqbrR5k2ZddwVNdjOVeBIeuqlm81IFZ+Ftew==",
|
||||
"requires": {
|
||||
"greenlock-manager-fs": "^3.1.0"
|
||||
}
|
||||
},
|
||||
"@root/acme": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/acme/-/acme-3.1.0.tgz",
|
||||
"integrity": "sha512-GAyaW63cpSYd2KvVp5lHLbCWeEhJPKZK9nsJvZJOKsD9Uv88KEttn4FpDZEJ+2q3Jsey0DWpuQ2I4ft0JV9p2w==",
|
||||
"requires": {
|
||||
"@root/csr": "^0.8.1",
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/keypairs": "^0.10.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/request": "^1.6.1",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/asn1": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/asn1/-/asn1-1.0.0.tgz",
|
||||
"integrity": "sha512-0lfZNuOULKJDJmdIkP8V9RnbV3XaK6PAHD3swnFy4tZwtlMDzLKoM/dfNad7ut8Hu3r91wy9uK0WA/9zym5mig==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"@root/csr": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/csr/-/csr-0.8.1.tgz",
|
||||
"integrity": "sha512-hKl0VuE549TK6SnS2Yn9nRvKbFZXn/oAg+dZJU/tlKl/f/0yRXeuUzf8akg3JjtJq+9E592zDqeXZ7yyrg8fSQ==",
|
||||
"requires": {
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/encoding": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/encoding/-/encoding-1.0.1.tgz",
|
||||
"integrity": "sha512-OaEub02ufoU038gy6bsNHQOjIn8nUjGiLcaRmJ40IUykneJkIW5fxDqKxQx48cszuNflYldsJLPPXCrGfHs8yQ=="
|
||||
},
|
||||
"@root/greenlock": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@root/greenlock/-/greenlock-4.0.5.tgz",
|
||||
"integrity": "sha512-KR9w3mYE9aH33FCibI8oSYBQV+f7lc3MVPdZ9nxY2tqRLmJp05cMOMz340mtG14VnWDuznLj4TbBj3sHIuoQPQ==",
|
||||
"requires": {
|
||||
"@greenlock/manager": "^3.1.0",
|
||||
"@root/acme": "^3.1.0",
|
||||
"@root/csr": "^0.8.1",
|
||||
"@root/keypairs": "^0.10.0",
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"@root/request": "^1.6.1",
|
||||
"acme-http-01-standalone": "^3.0.5",
|
||||
"cert-info": "^1.5.1",
|
||||
"greenlock-store-fs": "^3.2.2",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"@root/keypairs": {
|
||||
"version": "0.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/keypairs/-/keypairs-0.10.0.tgz",
|
||||
"integrity": "sha512-t8VocY46Mtb0NTsxzyLLf5tsgfw0BXLYVADAyiRdEdqHcvPFGJdjkXNtHVQuSV/FMaC65iTOHVP4E6X8iT3Ikg==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/mkdirp": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/mkdirp/-/mkdirp-1.0.0.tgz",
|
||||
"integrity": "sha512-hxGAYUx5029VggfG+U9naAhQkoMSXtOeXtbql97m3Hi6/sQSRL/4khKZPyOF6w11glyCOU38WCNLu9nUcSjOfA=="
|
||||
},
|
||||
"@root/pem": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@root/pem/-/pem-1.0.4.tgz",
|
||||
"integrity": "sha512-rEUDiUsHtild8GfIjFE9wXtcVxeS+ehCJQBwbQQ3IVfORKHK93CFnRtkr69R75lZFjcmKYVc+AXDB+AeRFOULA=="
|
||||
},
|
||||
"@root/request": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/request/-/request-1.6.1.tgz",
|
||||
"integrity": "sha512-8wrWyeBLRp7T8J36GkT3RODJ6zYmL0/maWlAUD5LOXT28D3TDquUepyYDKYANNA3Gc8R5ZCgf+AXvSTYpJEWwQ=="
|
||||
},
|
||||
"@root/x509": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@root/x509/-/x509-0.7.2.tgz",
|
||||
"integrity": "sha512-ENq3LGYORK5NiMFHEVeNMt+fTXaC7DTS6sQXoqV+dFdfT0vmiL5cDLjaXQhaklJQq0NiwicZegzJRl1ZOTp3WQ==",
|
||||
"requires": {
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"acme-http-01-standalone": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/acme-http-01-standalone/-/acme-http-01-standalone-3.0.5.tgz",
|
||||
"integrity": "sha512-W4GfK+39GZ+u0mvxRVUcVFCG6gposfzEnSBF20T/NUwWAKG59wQT1dUbS1NixRIAsRuhpGc4Jx659cErFQH0Pg=="
|
||||
},
|
||||
"cert-info": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/cert-info/-/cert-info-1.5.1.tgz",
|
||||
"integrity": "sha512-eoQC/yAgW3gKTKxjzyClvi+UzuY97YCjcl+lSqbsGIy7HeGaWxCPOQFivhUYm27hgsBMhsJJFya3kGvK6PMIcQ=="
|
||||
},
|
||||
"escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
|
||||
},
|
||||
"greenlock-manager-fs": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-manager-fs/-/greenlock-manager-fs-3.1.1.tgz",
|
||||
"integrity": "sha512-np6qdnPIOZx40PAcSQcqK1eMPWjTKxsxcgRd/OVg0ai49WC1Ds74CTrwmB84pq2n53ikbnDBQFmKEQ4AC0DK8w==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"greenlock-store-fs": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-store-fs/-/greenlock-store-fs-3.2.2.tgz",
|
||||
"integrity": "sha512-92ejLB4DyV4qv/2b6VLGF2nKfYQeIfg3o+e/1cIoYLjlIaUFdbBXkzLTRozFlHsQPZt2ALi5qYrpC9IwH7GK8A==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"redirect-https": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/redirect-https/-/redirect-https-1.3.1.tgz",
|
||||
"integrity": "sha512-Stex2nI+tMpZXKvy++32TiBXEy+GdpAfp3EUnl5BqCiJ5f5i6XvUSFrs7TR7IoRSlthM7ZtD89uYGTtJBXlFYg==",
|
||||
"requires": {
|
||||
"escape-html": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"safe-replace": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-replace/-/safe-replace-1.1.0.tgz",
|
||||
"integrity": "sha512-9/V2E0CDsKs9DWOOwJH7jYpSl9S3N05uyevNjvsnDauBqRowBPOyot1fIvV5N2IuZAbYyvrTXrYFVG0RZInfFw=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
98
package.json
98
package.json
|
@ -1,51 +1,51 @@
|
|||
{
|
||||
"name": "@root/greenlock-express",
|
||||
"version": "3.0.10",
|
||||
"description": "Free SSL and managed or automatic HTTPS for node.js with Express, Koa, Connect, Hapi, and all other middleware systems.",
|
||||
"main": "greenlock-express.js",
|
||||
"homepage": "https://greenlock.domains",
|
||||
"files": [
|
||||
"*.js",
|
||||
"lib",
|
||||
"scripts"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node_todo server.js ./config.js",
|
||||
"test": "node_todo test/greenlock.js"
|
||||
},
|
||||
"directories": {
|
||||
"example": "examples"
|
||||
},
|
||||
"dependencies": {
|
||||
"@root/greenlock": "^3.0.17",
|
||||
"redirect-https": "^1.1.5"
|
||||
},
|
||||
"trulyOptionalDependencies": {
|
||||
"http-proxy": "^1.17.0",
|
||||
"express": "^4.16.3",
|
||||
"express-basic-auth": "^1.2.0",
|
||||
"finalhandler": "^1.1.1",
|
||||
"serve-index": "^1.9.1",
|
||||
"serve-static": "^1.13.2",
|
||||
"ws": "^5.2.1"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.rootprojects.org/root/greenlock-express.js.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Let's Encrypt",
|
||||
"ACME",
|
||||
"greenlock",
|
||||
"Free SSL",
|
||||
"Automated HTTPS",
|
||||
"https",
|
||||
"tls"
|
||||
],
|
||||
"author": "AJ ONeal <coolaj86@gmail.com> (https://solderjs.com/)",
|
||||
"license": "MPL-2.0",
|
||||
"bugs": {
|
||||
"url": "https://git.rootprojects.org/root/greenlock-express.js/issues"
|
||||
}
|
||||
"name": "@root/greenlock-express",
|
||||
"version": "4.0.4",
|
||||
"description": "Free SSL and managed or automatic HTTPS for node.js with Express, Koa, Connect, Hapi, and all other middleware systems.",
|
||||
"main": "greenlock-express.js",
|
||||
"homepage": "https://greenlock.domains",
|
||||
"files": [
|
||||
"*.js",
|
||||
"lib",
|
||||
"scripts"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node_todo server.js ./config.js",
|
||||
"test": "node_todo test/greenlock.js"
|
||||
},
|
||||
"directories": {
|
||||
"example": "examples"
|
||||
},
|
||||
"dependencies": {
|
||||
"@root/greenlock": "^4.0.5",
|
||||
"redirect-https": "^1.3.1"
|
||||
},
|
||||
"trulyOptionalDependencies": {
|
||||
"http-proxy": "^1.17.0",
|
||||
"express": "^4.16.3",
|
||||
"express-basic-auth": "^1.2.0",
|
||||
"finalhandler": "^1.1.1",
|
||||
"serve-index": "^1.9.1",
|
||||
"serve-static": "^1.13.2",
|
||||
"ws": "^5.2.1"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.rootprojects.org/root/greenlock-express.js.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Let's Encrypt",
|
||||
"ACME",
|
||||
"greenlock",
|
||||
"Free SSL",
|
||||
"Automated HTTPS",
|
||||
"https",
|
||||
"tls"
|
||||
],
|
||||
"author": "AJ ONeal <coolaj86@gmail.com> (https://solderjs.com/)",
|
||||
"license": "MPL-2.0",
|
||||
"bugs": {
|
||||
"url": "https://git.rootprojects.org/root/greenlock-express.js/issues"
|
||||
}
|
||||
}
|
||||
|
|
248
servers.js
248
servers.js
|
@ -9,149 +9,163 @@ var sni = require("./sni.js");
|
|||
var cluster = require("cluster");
|
||||
|
||||
Servers.create = function(greenlock) {
|
||||
var servers = {};
|
||||
var _httpServer;
|
||||
var _httpsServer;
|
||||
var servers = {};
|
||||
var _httpServer;
|
||||
var _httpsServer;
|
||||
|
||||
function startError(e) {
|
||||
explainError(e);
|
||||
process.exit(1);
|
||||
}
|
||||
function startError(e) {
|
||||
explainError(e);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
servers.httpServer = function(defaultApp) {
|
||||
if (_httpServer) {
|
||||
return _httpServer;
|
||||
}
|
||||
servers.httpServer = function(defaultApp) {
|
||||
if (_httpServer) {
|
||||
if (defaultApp) {
|
||||
console.error("error: can only call httpServer(app) once");
|
||||
process.exit(1);
|
||||
}
|
||||
return _httpServer;
|
||||
}
|
||||
|
||||
_httpServer = http.createServer(HttpMiddleware.create(greenlock, defaultApp));
|
||||
_httpServer.once("error", startError);
|
||||
if (!defaultApp) {
|
||||
defaultApp = require("redirect-https")();
|
||||
}
|
||||
// HEADERS SENT DEBUG NOTE #1
|
||||
// As seen above, it's only possible to create the server once.
|
||||
// It always gets the http middleware, it always gets a single default app
|
||||
// Therefore it seems impossible to be an http.on('connection', app) problem
|
||||
_httpServer = http.createServer(HttpMiddleware.create(greenlock, defaultApp));
|
||||
_httpServer.once("error", startError);
|
||||
|
||||
return _httpServer;
|
||||
};
|
||||
return _httpServer;
|
||||
};
|
||||
|
||||
var _middlewareApp;
|
||||
var _middlewareApp;
|
||||
|
||||
servers.httpsServer = function(secureOpts, defaultApp) {
|
||||
if (defaultApp) {
|
||||
// TODO guard against being set twice?
|
||||
_middlewareApp = defaultApp;
|
||||
}
|
||||
servers.http2Server = function(secureOpts, defaultApp) {
|
||||
return servers._httpsServer(secureOpts, defaultApp, function(secureOpts, fn) {
|
||||
secureOpts.allowHTTP1 = true;
|
||||
return require("http2").createSecureServer(secureOpts, fn);
|
||||
});
|
||||
};
|
||||
servers.httpsServer = function(secureOpts, defaultApp) {
|
||||
return servers._httpsServer(secureOpts, defaultApp, function(secureOpts, fn) {
|
||||
return require("https").createServer(secureOpts, fn);
|
||||
});
|
||||
};
|
||||
servers._httpsServer = function(secureOpts, defaultApp, createSecureServer) {
|
||||
if (defaultApp) {
|
||||
// TODO guard against being set twice?
|
||||
_middlewareApp = defaultApp;
|
||||
}
|
||||
|
||||
if (_httpsServer) {
|
||||
if (secureOpts && Object.keys(secureOpts).length) {
|
||||
throw new Error("Call glx.httpsServer(tlsOptions) before calling glx.serveApp(app)");
|
||||
}
|
||||
return _httpsServer;
|
||||
}
|
||||
if (_httpsServer) {
|
||||
if (secureOpts && Object.keys(secureOpts).length) {
|
||||
throw new Error("Call glx.httpsServer(tlsOptions) before calling glx.serveApp(app)");
|
||||
}
|
||||
return _httpsServer;
|
||||
}
|
||||
|
||||
if (!secureOpts) {
|
||||
secureOpts = {};
|
||||
}
|
||||
if (!secureOpts) {
|
||||
secureOpts = {};
|
||||
}
|
||||
|
||||
_httpsServer = createSecureServer(
|
||||
wrapDefaultSniCallback(greenlock, secureOpts),
|
||||
HttpsMiddleware.create(greenlock, function(req, res) {
|
||||
if (!_middlewareApp) {
|
||||
throw new Error("Set app with `glx.serveApp(app)` or `glx.httpsServer(tlsOptions, app)`");
|
||||
}
|
||||
_middlewareApp(req, res);
|
||||
})
|
||||
);
|
||||
_httpsServer.once("error", startError);
|
||||
_httpsServer = createSecureServer(
|
||||
wrapDefaultSniCallback(greenlock, secureOpts),
|
||||
HttpsMiddleware.create(greenlock, function(req, res) {
|
||||
if (!_middlewareApp) {
|
||||
throw new Error("Set app with `glx.serveApp(app)` or `glx.httpsServer(tlsOptions, app)`");
|
||||
}
|
||||
_middlewareApp(req, res);
|
||||
})
|
||||
);
|
||||
_httpsServer.once("error", startError);
|
||||
|
||||
return _httpsServer;
|
||||
};
|
||||
return _httpsServer;
|
||||
};
|
||||
|
||||
servers.id = function() {
|
||||
return (cluster.isWorker && cluster.worker.id) || "0";
|
||||
};
|
||||
servers.serveApp = function(app) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
if ("function" !== typeof app) {
|
||||
reject(new Error("glx.serveApp(app) expects a node/express app in the format `function (req, res) { ... }`"));
|
||||
return;
|
||||
}
|
||||
servers.id = function() {
|
||||
return (cluster.isWorker && cluster.worker.id) || "0";
|
||||
};
|
||||
servers.serveApp = function(app) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
if ("function" !== typeof app) {
|
||||
reject(
|
||||
new Error(
|
||||
"glx.serveApp(app) expects a node/express app in the format `function (req, res) { ... }`"
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var id = cluster.isWorker && cluster.worker.id;
|
||||
var idstr = (id && "#" + id + " ") || "";
|
||||
var plainServer = servers.httpServer(require("redirect-https")());
|
||||
var plainAddr = "0.0.0.0";
|
||||
var plainPort = 80;
|
||||
plainServer.listen(plainPort, plainAddr, function() {
|
||||
console.info(
|
||||
idstr + "Listening on",
|
||||
plainAddr + ":" + plainPort,
|
||||
"for ACME challenges, and redirecting to HTTPS"
|
||||
);
|
||||
var id = cluster.isWorker && cluster.worker.id;
|
||||
var idstr = (id && "#" + id + " ") || "";
|
||||
var plainServer = servers.httpServer();
|
||||
var plainAddr = "0.0.0.0";
|
||||
var plainPort = 80;
|
||||
plainServer.listen(plainPort, plainAddr, function() {
|
||||
console.info(
|
||||
idstr + "Listening on",
|
||||
plainAddr + ":" + plainPort,
|
||||
"for ACME challenges, and redirecting to HTTPS"
|
||||
);
|
||||
|
||||
// TODO fetch greenlock.servername
|
||||
_middlewareApp = app || _middlewareApp;
|
||||
var secureServer = servers.httpsServer(null, app);
|
||||
var secureAddr = "0.0.0.0";
|
||||
var securePort = 443;
|
||||
secureServer.listen(securePort, secureAddr, function() {
|
||||
console.info(idstr + "Listening on", secureAddr + ":" + securePort, "for secure traffic");
|
||||
// TODO fetch greenlock.servername
|
||||
_middlewareApp = app || _middlewareApp;
|
||||
var secureServer = servers.httpsServer(null, app);
|
||||
var secureAddr = "0.0.0.0";
|
||||
var securePort = 443;
|
||||
secureServer.listen(securePort, secureAddr, function() {
|
||||
console.info(idstr + "Listening on", secureAddr + ":" + securePort, "for secure traffic");
|
||||
|
||||
plainServer.removeListener("error", startError);
|
||||
secureServer.removeListener("error", startError);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
plainServer.removeListener("error", startError);
|
||||
secureServer.removeListener("error", startError);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return servers;
|
||||
return servers;
|
||||
};
|
||||
|
||||
function explainError(e) {
|
||||
console.error();
|
||||
console.error("Error: " + e.message);
|
||||
if ("EACCES" === e.errno) {
|
||||
console.error("You don't have prmission to access '" + e.address + ":" + e.port + "'.");
|
||||
console.error('You probably need to use "sudo" or "sudo setcap \'cap_net_bind_service=+ep\' $(which node)"');
|
||||
} else if ("EADDRINUSE" === e.errno) {
|
||||
console.error("'" + e.address + ":" + e.port + "' is already being used by some other program.");
|
||||
console.error("You probably need to stop that program or restart your computer.");
|
||||
} else {
|
||||
console.error(e.code + ": '" + e.address + ":" + e.port + "'");
|
||||
}
|
||||
console.error();
|
||||
console.error();
|
||||
console.error("Error: " + e.message);
|
||||
if ("EACCES" === e.errno) {
|
||||
console.error("You don't have prmission to access '" + e.address + ":" + e.port + "'.");
|
||||
console.error('You probably need to use "sudo" or "sudo setcap \'cap_net_bind_service=+ep\' $(which node)"');
|
||||
} else if ("EADDRINUSE" === e.errno) {
|
||||
console.error("'" + e.address + ":" + e.port + "' is already being used by some other program.");
|
||||
console.error("You probably need to stop that program or restart your computer.");
|
||||
} else {
|
||||
console.error(e.code + ": '" + e.address + ":" + e.port + "'");
|
||||
}
|
||||
console.error();
|
||||
}
|
||||
|
||||
function wrapDefaultSniCallback(greenlock, secureOpts) {
|
||||
// I'm not sure yet if the original SNICallback
|
||||
// should be called before or after, so I'm just
|
||||
// going to delay making that choice until I have the use case
|
||||
/*
|
||||
// I'm not sure yet if the original SNICallback
|
||||
// should be called before or after, so I'm just
|
||||
// going to delay making that choice until I have the use case
|
||||
/*
|
||||
if (!secureOpts.SNICallback) {
|
||||
secureOpts.SNICallback = function(servername, cb) {
|
||||
cb(null, null);
|
||||
};
|
||||
}
|
||||
*/
|
||||
if (secureOpts.SNICallback) {
|
||||
console.warn();
|
||||
console.warn("[warning] Ignoring the given tlsOptions.SNICallback function.");
|
||||
console.warn();
|
||||
console.warn(" We're very open to implementing support for this,");
|
||||
console.warn(" we just don't understand the use case yet.");
|
||||
console.warn(" Please open an issue to discuss. We'd love to help.");
|
||||
console.warn();
|
||||
}
|
||||
if (secureOpts.SNICallback) {
|
||||
console.warn();
|
||||
console.warn("[warning] Ignoring the given tlsOptions.SNICallback function.");
|
||||
console.warn();
|
||||
console.warn(" We're very open to implementing support for this,");
|
||||
console.warn(" we just don't understand the use case yet.");
|
||||
console.warn(" Please open an issue to discuss. We'd love to help.");
|
||||
console.warn();
|
||||
}
|
||||
|
||||
// TODO greenlock.servername for workers
|
||||
secureOpts.SNICallback = sni.create(greenlock, secureOpts);
|
||||
return secureOpts;
|
||||
}
|
||||
|
||||
function createSecureServer(secureOpts, fn) {
|
||||
var major = process.versions.node.split(".")[0];
|
||||
|
||||
// TODO can we trust earlier versions as well?
|
||||
if (major >= 12) {
|
||||
secureOpts.allowHTTP1 = true;
|
||||
return require("http2").createSecureServer(secureOpts, fn);
|
||||
} else {
|
||||
return require("https").createServer(secureOpts, fn);
|
||||
}
|
||||
// TODO greenlock.servername for workers
|
||||
secureOpts.SNICallback = sni.create(greenlock, secureOpts);
|
||||
return secureOpts;
|
||||
}
|
||||
|
|
39
single.js
39
single.js
|
@ -6,20 +6,31 @@ var Single = module.exports;
|
|||
var Servers = require("./servers.js");
|
||||
|
||||
Single.create = function(opts) {
|
||||
var greenlock = require("./greenlock.js").create(opts);
|
||||
var greenlock = require("./greenlock-shim.js").create(opts);
|
||||
|
||||
var servers = Servers.create(greenlock);
|
||||
var servers = Servers.create(greenlock);
|
||||
|
||||
var single = {
|
||||
serve: function(fn) {
|
||||
fn(servers);
|
||||
return single;
|
||||
},
|
||||
master: function(/*fn*/) {
|
||||
// ignore
|
||||
//fn(master);
|
||||
return single;
|
||||
}
|
||||
};
|
||||
return single;
|
||||
var single = {
|
||||
ready: function(fn) {
|
||||
fn(servers);
|
||||
return single;
|
||||
},
|
||||
master: function(/*fn*/) {
|
||||
// ignore
|
||||
//fn(master);
|
||||
return single;
|
||||
},
|
||||
serve: function(fn) {
|
||||
// keeping backwards compat
|
||||
if (1 === fn.length) {
|
||||
single.ready(fn);
|
||||
return;
|
||||
}
|
||||
// serving the app, right away
|
||||
single.ready(function(glx) {
|
||||
glx.serveApp(fn);
|
||||
});
|
||||
}
|
||||
};
|
||||
return single;
|
||||
};
|
||||
|
|
317
sni.js
317
sni.js
|
@ -13,182 +13,203 @@ var smallStagger = Math.round(Math.PI * (30 * 1000));
|
|||
|
||||
//secureOpts.SNICallback = sni.create(greenlock, secureOpts);
|
||||
sni.create = function(greenlock, secureOpts) {
|
||||
var _cache = {};
|
||||
var defaultServername = greenlock.servername || "";
|
||||
var _cache = {};
|
||||
var defaultServername = greenlock.servername || "";
|
||||
|
||||
if (secureOpts.cert) {
|
||||
// Note: it's fine if greenlock.servername is undefined,
|
||||
// but if the caller wants this to auto-renew, they should define it
|
||||
_cache[defaultServername] = {
|
||||
refreshAt: 0,
|
||||
secureContext: tls.createSecureContext(secureOpts)
|
||||
};
|
||||
}
|
||||
if (secureOpts.cert) {
|
||||
// Note: it's fine if greenlock.servername is undefined,
|
||||
// but if the caller wants this to auto-renew, they should define it
|
||||
_cache[defaultServername] = {
|
||||
refreshAt: 0,
|
||||
secureContext: tls.createSecureContext(secureOpts)
|
||||
};
|
||||
}
|
||||
|
||||
return getSecureContext;
|
||||
return getSecureContext;
|
||||
|
||||
function notify(ev, args) {
|
||||
try {
|
||||
// TODO _notify() or notify()?
|
||||
(greenlock.notify || greenlock._notify)(ev, args);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.error(ev, args);
|
||||
}
|
||||
}
|
||||
function notify(ev, args) {
|
||||
try {
|
||||
// TODO _notify() or notify()?
|
||||
(greenlock.notify || greenlock._notify)(ev, args);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.error(ev, args);
|
||||
}
|
||||
}
|
||||
|
||||
function getSecureContext(servername, cb) {
|
||||
//console.log("debug sni", servername);
|
||||
if ("string" !== typeof servername) {
|
||||
// this will never happen... right? but stranger things have...
|
||||
console.error("[sanity fail] non-string servername:", servername);
|
||||
cb(new Error("invalid servername"), null);
|
||||
return;
|
||||
}
|
||||
function getSecureContext(servername, cb) {
|
||||
//console.log("debug sni", servername);
|
||||
if ("string" !== typeof servername) {
|
||||
// this will never happen... right? but stranger things have...
|
||||
console.error("[sanity fail] non-string servername:", servername);
|
||||
cb(new Error("invalid servername"), null);
|
||||
return;
|
||||
}
|
||||
|
||||
var secureContext = getCachedContext(servername);
|
||||
if (secureContext) {
|
||||
//console.log("debug sni got cached context", servername, getCachedMeta(servername));
|
||||
cb(null, secureContext);
|
||||
return;
|
||||
}
|
||||
var secureContext = getCachedContext(servername);
|
||||
if (secureContext) {
|
||||
//console.log("debug sni got cached context", servername, getCachedMeta(servername));
|
||||
cb(null, secureContext);
|
||||
return;
|
||||
}
|
||||
|
||||
getFreshContext(servername)
|
||||
.then(function(secureContext) {
|
||||
if (secureContext) {
|
||||
//console.log("debug sni got fresh context", servername, getCachedMeta(servername));
|
||||
cb(null, secureContext);
|
||||
return;
|
||||
}
|
||||
// Note: this does not replace tlsSocket.setSecureContext()
|
||||
// as it only works when SNI has been sent
|
||||
//console.log("debug sni got default context", servername, getCachedMeta(servername));
|
||||
cb(null, getDefaultContext());
|
||||
})
|
||||
.catch(function(err) {
|
||||
if (!err.context) {
|
||||
err.context = "sni_callback";
|
||||
}
|
||||
notify("error", err);
|
||||
//console.log("debug sni error", servername, err);
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
getFreshContext(servername)
|
||||
.then(function(secureContext) {
|
||||
if (secureContext) {
|
||||
//console.log("debug sni got fresh context", servername, getCachedMeta(servername));
|
||||
cb(null, secureContext);
|
||||
return;
|
||||
}
|
||||
|
||||
function getCachedMeta(servername) {
|
||||
var meta = _cache[servername];
|
||||
if (!meta) {
|
||||
if (!_cache[wildname(servername)]) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
// Note: this does not replace tlsSocket.setSecureContext()
|
||||
// as it only works when SNI has been sent
|
||||
//console.log("debug sni got default context", servername, getCachedMeta(servername));
|
||||
if (!/PROD/.test(process.env.ENV) || /DEV|STAG/.test(process.env.ENV)) {
|
||||
// Change this once
|
||||
// A) the 'notify' message passing is verified fixed in cluster mode
|
||||
// B) we have a good way to let people know their server isn't configured
|
||||
console.debug("debug: ignoring servername " + JSON.stringify(servername));
|
||||
console.debug(" (it's probably either missing from your config, or a bot)");
|
||||
notify("servername_unknown", {
|
||||
servername: servername
|
||||
});
|
||||
}
|
||||
cb(null, getDefaultContext());
|
||||
})
|
||||
.catch(function(err) {
|
||||
if (!err.context) {
|
||||
err.context = "sni_callback";
|
||||
}
|
||||
notify("error", err);
|
||||
//console.log("debug sni error", servername, err);
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
|
||||
function getCachedContext(servername) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta) {
|
||||
return null;
|
||||
}
|
||||
function getCachedMeta(servername) {
|
||||
var meta = _cache[servername];
|
||||
if (!meta) {
|
||||
if (!_cache[wildname(servername)]) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
// always renew in background
|
||||
if (!meta.refreshAt || Date.now() >= meta.refreshAt) {
|
||||
getFreshContext(servername).catch(function(e) {
|
||||
if (!e.context) {
|
||||
e.context = "sni_background_refresh";
|
||||
}
|
||||
notify("error", e);
|
||||
});
|
||||
}
|
||||
function getCachedContext(servername) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// under normal circumstances this would never be expired
|
||||
// and, if it is expired, something is so wrong it's probably
|
||||
// not worth wating for the renewal - it has probably failed
|
||||
return meta.secureContext;
|
||||
}
|
||||
// always renew in background
|
||||
if (!meta.refreshAt || Date.now() >= meta.refreshAt) {
|
||||
getFreshContext(servername).catch(function(e) {
|
||||
if (!e.context) {
|
||||
e.context = "sni_background_refresh";
|
||||
}
|
||||
notify("error", e);
|
||||
});
|
||||
}
|
||||
|
||||
function getFreshContext(servername) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta && !validServername(servername)) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
// under normal circumstances this would never be expired
|
||||
// and, if it is expired, something is so wrong it's probably
|
||||
// not worth wating for the renewal - it has probably failed
|
||||
return meta.secureContext;
|
||||
}
|
||||
|
||||
if (meta) {
|
||||
// prevent stampedes
|
||||
meta.refreshAt = Date.now() + randomRefreshOffset();
|
||||
}
|
||||
function getFreshContext(servername) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta && !validServername(servername)) {
|
||||
if ((servername && !/PROD/.test(process.env.ENV)) || /DEV|STAG/.test(process.env.ENV)) {
|
||||
// Change this once
|
||||
// A) the 'notify' message passing is verified fixed in cluster mode
|
||||
// B) we have a good way to let people know their server isn't configured
|
||||
console.debug("debug: invalid servername " + JSON.stringify(servername));
|
||||
console.debug(" (it's probably just a bot trolling for vulnerable servers)");
|
||||
notify("servername_invalid", {
|
||||
servername: servername
|
||||
});
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
// TODO don't get unknown certs at all, rely on auto-updates from greenlock
|
||||
// Note: greenlock.get() will return an existing fresh cert or issue a new one
|
||||
return greenlock.get({ servername: servername }).then(function(result) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta) {
|
||||
meta = _cache[servername] = { secureContext: { _valid: false } };
|
||||
}
|
||||
// prevent from being punked by bot trolls
|
||||
meta.refreshAt = Date.now() + smallStagger;
|
||||
if (meta) {
|
||||
// prevent stampedes
|
||||
meta.refreshAt = Date.now() + randomRefreshOffset();
|
||||
}
|
||||
|
||||
// nothing to do
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
// TODO don't get unknown certs at all, rely on auto-updates from greenlock
|
||||
// Note: greenlock.get() will return an existing fresh cert or issue a new one
|
||||
return greenlock.get({ servername: servername }).then(function(result) {
|
||||
var meta = getCachedMeta(servername);
|
||||
if (!meta) {
|
||||
meta = _cache[servername] = { secureContext: { _valid: false } };
|
||||
}
|
||||
// prevent from being punked by bot trolls
|
||||
meta.refreshAt = Date.now() + smallStagger;
|
||||
|
||||
// we only care about the first one
|
||||
var pems = result.pems;
|
||||
var site = result.site;
|
||||
if (!pems || !pems.cert) {
|
||||
// nothing to do
|
||||
// (and the error should have been reported already)
|
||||
return null;
|
||||
}
|
||||
// nothing to do
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
meta = {
|
||||
refreshAt: Date.now() + randomRefreshOffset(),
|
||||
secureContext: tls.createSecureContext({
|
||||
// TODO support passphrase-protected privkeys
|
||||
key: pems.privkey,
|
||||
cert: pems.cert + "\n" + pems.chain + "\n"
|
||||
})
|
||||
};
|
||||
meta.secureContext._valid = true;
|
||||
// we only care about the first one
|
||||
var pems = result.pems;
|
||||
var site = result.site;
|
||||
if (!pems || !pems.cert) {
|
||||
// nothing to do
|
||||
// (and the error should have been reported already)
|
||||
return null;
|
||||
}
|
||||
|
||||
// copy this same object into every place
|
||||
(result.altnames || site.altnames || [result.subject || site.subject]).forEach(function(altname) {
|
||||
_cache[altname] = meta;
|
||||
});
|
||||
meta = {
|
||||
refreshAt: Date.now() + randomRefreshOffset(),
|
||||
secureContext: tls.createSecureContext({
|
||||
// TODO support passphrase-protected privkeys
|
||||
key: pems.privkey,
|
||||
cert: pems.cert + "\n" + pems.chain + "\n"
|
||||
})
|
||||
};
|
||||
meta.secureContext._valid = true;
|
||||
|
||||
return meta.secureContext;
|
||||
});
|
||||
}
|
||||
// copy this same object into every place
|
||||
(result.altnames || site.altnames || [result.subject || site.subject]).forEach(function(altname) {
|
||||
_cache[altname] = meta;
|
||||
});
|
||||
|
||||
function getDefaultContext() {
|
||||
return getCachedContext(defaultServername);
|
||||
}
|
||||
return meta.secureContext;
|
||||
});
|
||||
}
|
||||
|
||||
function getDefaultContext() {
|
||||
return getCachedContext(defaultServername);
|
||||
}
|
||||
};
|
||||
|
||||
// whenever we need to know when to refresh next
|
||||
function randomRefreshOffset() {
|
||||
var stagger = Math.round(refreshStagger / 2) - Math.round(Math.random() * refreshStagger);
|
||||
return refreshOffset + stagger;
|
||||
var stagger = Math.round(refreshStagger / 2) - Math.round(Math.random() * refreshStagger);
|
||||
return refreshOffset + stagger;
|
||||
}
|
||||
|
||||
function validServername(servername) {
|
||||
// format and (lightly) sanitize sni so that users can be naive
|
||||
// and not have to worry about SQL injection or fs discovery
|
||||
// format and (lightly) sanitize sni so that users can be naive
|
||||
// and not have to worry about SQL injection or fs discovery
|
||||
|
||||
servername = (servername || "").toLowerCase();
|
||||
// hostname labels allow a-z, 0-9, -, and are separated by dots
|
||||
// _ is sometimes allowed, but not as a "hostname", and not by Let's Encrypt ACME
|
||||
// REGEX // https://www.codeproject.com/Questions/1063023/alphanumeric-validation-javascript-without-regex
|
||||
return servernameRe.test(servername) && -1 === servername.indexOf("..");
|
||||
servername = (servername || "").toLowerCase();
|
||||
// hostname labels allow a-z, 0-9, -, and are separated by dots
|
||||
// _ is sometimes allowed, but not as a "hostname", and not by Let's Encrypt ACME
|
||||
// REGEX // https://www.codeproject.com/Questions/1063023/alphanumeric-validation-javascript-without-regex
|
||||
return servernameRe.test(servername) && -1 === servername.indexOf("..");
|
||||
}
|
||||
|
||||
function wildname(servername) {
|
||||
return (
|
||||
"*." +
|
||||
servername
|
||||
.split(".")
|
||||
.slice(1)
|
||||
.join(".")
|
||||
);
|
||||
return (
|
||||
"*." +
|
||||
servername
|
||||
.split(".")
|
||||
.slice(1)
|
||||
.join(".")
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,83 +1,83 @@
|
|||
#!/usr/bin/env node
|
||||
var Greenlock = require("../");
|
||||
var greenlock = Greenlock.create({
|
||||
version: "draft-11",
|
||||
server: "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||
agreeTos: true,
|
||||
approvedDomains: ["example.com", "www.example.com"],
|
||||
configDir: require("path").join(require("os").tmpdir(), "acme"),
|
||||
version: "draft-11",
|
||||
server: "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||
agreeTos: true,
|
||||
approvedDomains: ["example.com", "www.example.com"],
|
||||
configDir: require("path").join(require("os").tmpdir(), "acme"),
|
||||
|
||||
app: require("express")().use("/", function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
})
|
||||
app: require("express")().use("/", function(req, res) {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end("Hello, World!\n\n💚 🔒.js");
|
||||
})
|
||||
});
|
||||
|
||||
var server1 = greenlock.listen(5080, 5443);
|
||||
server1.on("listening", function() {
|
||||
console.log("### THREE 3333 - All is well server1", this.address());
|
||||
setTimeout(function() {
|
||||
// so that the address() object doesn't disappear
|
||||
server1.close();
|
||||
server1.unencrypted.close();
|
||||
}, 10);
|
||||
console.log("### THREE 3333 - All is well server1", this.address());
|
||||
setTimeout(function() {
|
||||
// so that the address() object doesn't disappear
|
||||
server1.close();
|
||||
server1.unencrypted.close();
|
||||
}, 10);
|
||||
});
|
||||
setTimeout(function() {
|
||||
var server2 = greenlock.listen(6080, 6443, function() {
|
||||
console.log("### FIVE 55555 - Started server 2!");
|
||||
setTimeout(function() {
|
||||
server2.close();
|
||||
server2.unencrypted.close();
|
||||
server6.close();
|
||||
server6.unencrypted.close();
|
||||
server7.close();
|
||||
server7.unencrypted.close();
|
||||
setTimeout(function() {
|
||||
// TODO greenlock needs a close event (and to listen to its server's close event)
|
||||
process.exit(0);
|
||||
}, 1000);
|
||||
}, 1000);
|
||||
});
|
||||
server2.on("listening", function() {
|
||||
console.log("### FOUR 44444 - All is well server2", server2.address());
|
||||
});
|
||||
var server2 = greenlock.listen(6080, 6443, function() {
|
||||
console.log("### FIVE 55555 - Started server 2!");
|
||||
setTimeout(function() {
|
||||
server2.close();
|
||||
server2.unencrypted.close();
|
||||
server6.close();
|
||||
server6.unencrypted.close();
|
||||
server7.close();
|
||||
server7.unencrypted.close();
|
||||
setTimeout(function() {
|
||||
// TODO greenlock needs a close event (and to listen to its server's close event)
|
||||
process.exit(0);
|
||||
}, 1000);
|
||||
}, 1000);
|
||||
});
|
||||
server2.on("listening", function() {
|
||||
console.log("### FOUR 44444 - All is well server2", server2.address());
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
var server3 = greenlock.listen(
|
||||
22,
|
||||
22,
|
||||
function() {
|
||||
console.error("Error: expected to get an error when launching plain server on port 22");
|
||||
},
|
||||
function() {
|
||||
console.error("Error: expected to get an error when launching " + server3.type + " server on port 22");
|
||||
}
|
||||
22,
|
||||
22,
|
||||
function() {
|
||||
console.error("Error: expected to get an error when launching plain server on port 22");
|
||||
},
|
||||
function() {
|
||||
console.error("Error: expected to get an error when launching " + server3.type + " server on port 22");
|
||||
}
|
||||
);
|
||||
server3.unencrypted.on("error", function() {
|
||||
console.log("Success: caught expected (plain) error");
|
||||
console.log("Success: caught expected (plain) error");
|
||||
});
|
||||
server3.on("error", function() {
|
||||
console.log("Success: caught expected " + server3.type + " error");
|
||||
//server3.close();
|
||||
console.log("Success: caught expected " + server3.type + " error");
|
||||
//server3.close();
|
||||
});
|
||||
|
||||
var server4 = greenlock.listen(
|
||||
7080,
|
||||
7443,
|
||||
function() {
|
||||
console.log("Success: server4: plain");
|
||||
server4.unencrypted.close();
|
||||
},
|
||||
function() {
|
||||
console.log("Success: server4: " + server4.type);
|
||||
server4.close();
|
||||
}
|
||||
7080,
|
||||
7443,
|
||||
function() {
|
||||
console.log("Success: server4: plain");
|
||||
server4.unencrypted.close();
|
||||
},
|
||||
function() {
|
||||
console.log("Success: server4: " + server4.type);
|
||||
server4.close();
|
||||
}
|
||||
);
|
||||
|
||||
var server5 = greenlock.listen(10080, 10443, function() {
|
||||
console.log("Server 5 with one fn", this.address());
|
||||
server5.close();
|
||||
server5.unencrypted.close();
|
||||
console.log("Server 5 with one fn", this.address());
|
||||
server5.close();
|
||||
server5.unencrypted.close();
|
||||
});
|
||||
|
||||
var server6 = greenlock.listen("[::]:11080", "[::1]:11443");
|
||||
|
|
103
worker.js
103
worker.js
|
@ -6,57 +6,68 @@ var messageTimeout = 30 * 1000;
|
|||
var msgPrefix = "greenlock:";
|
||||
|
||||
Worker.create = function() {
|
||||
var greenlock = {};
|
||||
["getAcmeHttp01ChallengeResponse", "get", "notify"].forEach(function(k) {
|
||||
greenlock[k] = function(args) {
|
||||
return rpc(k, args);
|
||||
};
|
||||
});
|
||||
var greenlock = {};
|
||||
["getAcmeHttp01ChallengeResponse", "get", "notify", "_notify"].forEach(function(k) {
|
||||
greenlock[k] = function(args) {
|
||||
return rpc(k, args);
|
||||
};
|
||||
});
|
||||
|
||||
var worker = {
|
||||
serve: function(fn) {
|
||||
var servers = require("./servers.js").create(greenlock);
|
||||
fn(servers);
|
||||
return worker;
|
||||
},
|
||||
master: function() {
|
||||
// ignore
|
||||
return worker;
|
||||
}
|
||||
};
|
||||
return worker;
|
||||
var worker = {
|
||||
ready: function(fn) {
|
||||
var servers = require("./servers.js").create(greenlock);
|
||||
fn(servers);
|
||||
return worker;
|
||||
},
|
||||
master: function() {
|
||||
// ignore
|
||||
return worker;
|
||||
},
|
||||
serve: function(fn) {
|
||||
// keeping backwards compat
|
||||
if (1 === fn.length) {
|
||||
worker.ready(fn);
|
||||
return;
|
||||
}
|
||||
// serving the express app, right away
|
||||
worker.ready(function(glx) {
|
||||
glx.serveApp(fn);
|
||||
});
|
||||
}
|
||||
};
|
||||
return worker;
|
||||
};
|
||||
|
||||
function rpc(funcname, msg) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
var rnd = Math.random()
|
||||
.toString()
|
||||
.slice(2)
|
||||
.toString(16);
|
||||
var id = msgPrefix + rnd;
|
||||
var timeout;
|
||||
return new Promise(function(resolve, reject) {
|
||||
var rnd = Math.random()
|
||||
.toString()
|
||||
.slice(2)
|
||||
.toString(16);
|
||||
var id = msgPrefix + rnd;
|
||||
var timeout;
|
||||
|
||||
function getResponse(msg) {
|
||||
if (msg._id !== id) {
|
||||
return;
|
||||
}
|
||||
process.removeListener("message", getResponse);
|
||||
clearTimeout(timeout);
|
||||
resolve(msg._result);
|
||||
}
|
||||
function getResponse(msg) {
|
||||
if (msg._id !== id) {
|
||||
return;
|
||||
}
|
||||
process.removeListener("message", getResponse);
|
||||
clearTimeout(timeout);
|
||||
resolve(msg._result);
|
||||
}
|
||||
|
||||
// TODO keep a single listener than just responds
|
||||
// via a collection of callbacks? or leave as is?
|
||||
process.on("message", getResponse);
|
||||
process.send({
|
||||
_id: id,
|
||||
_funcname: funcname,
|
||||
_input: msg
|
||||
});
|
||||
// TODO keep a single listener than just responds
|
||||
// via a collection of callbacks? or leave as is?
|
||||
process.on("message", getResponse);
|
||||
process.send({
|
||||
_id: id,
|
||||
_funcname: funcname,
|
||||
_input: msg
|
||||
});
|
||||
|
||||
timeout = setTimeout(function() {
|
||||
process.removeListener("message", getResponse);
|
||||
reject(new Error("worker rpc request timeout"));
|
||||
}, messageTimeout);
|
||||
});
|
||||
timeout = setTimeout(function() {
|
||||
process.removeListener("message", getResponse);
|
||||
reject(new Error("worker rpc request timeout"));
|
||||
}, messageTimeout);
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue