Compare commits

...

15 Commits
master ... npm

  1. 517
      MIGRATION_GUIDE_V2_V3.md
  2. 30
      README.md
  3. 219
      accounts.js
  4. 378
      bin/certonly.js
  5. 234
      bin/cli.js
  6. 13
      bin/greenlock.js
  7. 318
      certificates.js
  8. 96
      challenges-underlay.js
  9. 58
      errors.js
  10. 682
      greenlock.js
  11. BIN
      logo/beaker-browser-301x112.png
  12. BIN
      logo/from-not-secure-to-secure-url-bar.png
  13. BIN
      logo/greenlock-1063x250.png
  14. BIN
      logo/greenlock-850x200.png
  15. BIN
      logo/ibm-301x112.png
  16. BIN
      logo/telebit-301x112.png
  17. 258
      manager-underlay.js
  18. 95
      order.js
  19. 61
      package-lock.json
  20. 7
      package.json
  21. 331
      plugins.js
  22. 20
      publish.sh
  23. 54
      tests/index.js
  24. 7
      user-events.js
  25. 281
      utils.js

517
MIGRATION_GUIDE_V2_V3.md

@ -1,517 +0,0 @@
# Migrating from Greenlock v2 to v3
**Greenlock Express** uses Greenlock directly, the same as before.
All options described for `Greenlock.create({...})` also apply to the Greenlock Express `init()` callback.
# Overview of Major Differences
- Reduced API
- No code in the config
- (config is completely serializable)
- Manager callbacks replace `approveDomains`
- Greenlock Express does more, with less config
- cluster is supported out-of-the-box
- high-performance
- scalable
- ACME challenges are simplified
- init
- zones (dns-01)
- set
- get
- remove
- Store callbacks are simplified
- accounts
- checkKeypairs
- certificates
- checkKeypairs
- check
- set
# Greenlock JavaScript API greatly reduced
Whereas before there were many different methods with nuance differences,
now there's just `create`, `get`, `renew`, and sometimes `add` ().
- Greenlock.create({ maintainerEmail, packageAgent, notify })
- Greenlock.get({ servername, wildname, duplicate, force })
- (just a convenience wrapper around renew)
- Greenlock.renew({ subject, altnames, issuedBefore, expiresAfter })
- (retrieves, issues, renews, all-in-one)
- _optional_ Greenlock.add({ subject, altnames, subscriberEmail })
- (partially replaces `approveDomains`)
Also, some disambiguation on terms:
- `domains` was often ambiguous and confusing, it has been replaced by:
- `subject` refers to the subject of a certificate - the primary domain
- `altnames` refers to the domains in the SAN (Subject Alternative Names) section of the certificate
- `servername` refers to the TLS (SSL) SNI (Server Name Indication) request for a cetificate
- `wildname` refers to the wildcard version of the servername (ex: `www.example.com => *.example.com`)
When you create an instance of Greenlock, you only supply package and maintainer info.
All other configuration is A) optional and B) handled by the _Manager_.
```js
'use strict';
var pkg = require('./package.json');
var Greenlock = require('greenlock');
var greenlock = Greenlock.create({
// used for the ACME client User-Agent string as per RFC 8555 and RFC 7231
packageAgent: pkg.name + '/' + pkg.version,
// used as the contact for critical bug and security notices
// should be the same as pkg.author.email
maintainerEmail: 'jon@example.com',
// used for logging background events and errors
notify: function(ev, args) {
if ('error' === ev || 'warning' === ev) {
console.error(ev, args);
return;
}
console.info(ev, args);
}
});
```
By default **no certificates will be issued**. See the _manager_ section.
When you want to get a single certificate, you use `get`, which will:
- will return null if neither the `servername` or its `wildname` (wildcard) variant can be found
- retrieve a non-expired certificate, if possible
- will renew the certificate in the background, if stale
- will wait for the certificate to be issued if new
```js
greenlock
.get({ servername: 'www.example.com' })
.then(function(result) {
if (!result) {
// certificate is not on the approved list
return null;
}
var fullchain = result.pems.cert + '\n' + result.pems.chain + '\n';
var privkey = result.pems.privkey;
return {
fullchain: fullchain,
privkey: privkey
};
})
.catch(function(e) {
// something went wrong in the renew process
console.error(e);
});
```
By default **no certificates will be issued**. See the _manager_ section.
When you want to renew certificates, _en masse_, you use `renew`, which will:
- check all certificates matching the given criteria
- only renew stale certificates by default
- return error objects (will NOT throw exception for failed renewals)
```js
greenlock
.renew({})
.then(function(results) {
if (!result.length) {
// no certificates found
return null;
}
// [{ site, error }]
return results;
})
.catch(function(e) {
// an unexpected error, not related to renewal
console.error(e);
});
```
Options:
| Option | Description |
| ------------- | -------------------------------------------------------------------------- |
| `altnames` | only check and renew certs matching these altnames (including wildcards) |
| `renewBefore` | only check and renew certs marked for renewal before the given date, in ms |
| `duplicate` | renew certificates regardless of timing |
| `force` | allow silly things, like tiny `renewOffset`s |
By default **no certificates will be issued**. See the _manager_ section.
# Greenlock Express Example
The options that must be returned from `init()` are the same that are used in `Greenlock.create()`,
with a few extra that are specific to Greenlock Express:
```js
require('@root/greenlock-express')
.init(function() {
// This object will be passed to Greenlock.create()
var options = {
// some options, like cluster, are special to Greenlock Express
cluster: false,
// The rest are the same as for Greenlock
packageAgent: pkg.name + '/' + pkg.version,
maintainerEmail: 'jon@example.com',
notify: function(ev, args) {
console.info(ev, args);
}
};
return options;
})
.serve(function(glx) {
// will start servers on port 80 and 443
glx.serveApp(function(req, res) {
res.end('Hello, Encrypted World!');
});
// you can get access to the raw server (i.e. for websockets)
glx.httpsServer(); // returns raw server object
});
```
# _Manager_ replaces `approveDomains`
`approveDomains` was always a little confusing. Most people didn't need it.
Instead, now there is a simple config file that will work for most people,
as well as a set of callbacks for easy configurability.
### Default Manager
The default manager is `greenlock-manager-fs` and the default `configFile` is `~/.config/greenlock/manager.json`.
The config file should look something like this:
`~/.config/greenlock/manager.json`:
```json
{
"subscriberEmail": "jon@example.com",
"agreeToTerms": true,
"sites": {
"example.com": {
"subject": "example.com",
"altnames": ["example.com", "www.example.com"]
}
}
}
```
You can specify a `acme-dns-01-*` or `acme-http-01-*` challenge plugin globally, or per-site.
```json
{
"subscriberEmail": "jon@example.com",
"agreeToTerms": true,
"sites": {
"example.com": {
"subject": "example.com",
"altnames": ["example.com", "www.example.com"],
"challenges": {
"dns-01": {
"module": "acme-dns-01-digitalocean",
"token": "apikey-xxxxx"
}
}
}
}
}
```
The same is true with `greenlock-store-*` plugins:
```json
{
"subscriberEmail": "jon@example.com",
"agreeToTerms": true,
"sites": {
"example.com": {
"subject": "example.com",
"altnames": ["example.com", "www.example.com"]
}
},
"store": {
"module": "greenlock-store-fs",
"basePath": "~/.config/greenlock"
}
}
```
### Customer Manager, the lazy way
At the very least you have to implement `find({ servername })`.
Since this is a very common use case, it's supported out of the box as part of the default manager plugin:
```js
var greenlock = Greenlock.create({
packageAgent: pkg.name + '/' + pkg.version,
maintainerEmail: 'jon@example.com',
notify: notify,
find: find
});
// In the simplest case you can ignore all incoming options
// and return a single site config in the same format as the config file
function find(options) {
var servername = options.servername; // www.example.com
var wildname = options.wildname; // *.example.com
return Promise.resolve([
{ subject: 'example.com', altnames: ['example.com', 'www.example.com'] }
]);
}
function notify(ev, args) {
if ('error' === ev || 'warning' === ev) {
console.error(ev, args);
return;
}
console.info(ev, args);
}
```
If you want to use wildcards or local domains, you must specify the `dns-01` challenge plugin to use:
```js
function find(options) {
var subject = options.subject;
// may include wildcard
var altnames = options.altnames;
var wildname = options.wildname; // *.example.com
return Promise.resolve([
{
subject: 'example.com',
altnames: ['example.com', 'www.example.com'],
challenges: {
'dns-01': { module: 'acme-dns-01-namedotcom', apikey: 'xxxx' }
}
}
]);
}
```
### Customer Manager, complete
To use a fully custom manager, you give the npm package name, or absolute path to the file to load
```js
Greenlock.create({
// Greenlock Options
maintainerEmail: 'jon@example.com',
packageAgent: 'my-package/v2.1.1',
notify: notify,
// file path or npm package name
manager: '/path/to/manager.js',
// options that get passed to the manager
myFooOption: 'whatever'
});
```
The manager itself is, again relatively simple:
- find(options)
- set(siteConfig)
- remove(options)
- defaults(globalOptions) (as setter)
- defaults() => globalOptions (as getter)
`/path/to/manager.js`:
```js
'use strict';
module.exports.create = function() {
var manager = {};
manager.find = async function({ subject, altnames, renewBefore }) {
if (subject) {
return getSiteConfigBySubject(subject);
}
if (altnames) {
// may include wildcards
return getSiteConfigByAnyAltname(altnames);
}
if (renewBefore) {
return getSiteConfigsWhereRenewAtIsLessThan(renewBefore);
}
return [];
};
manage.set = function(opts) {
// this is called by greenlock.add({ subject, altnames })
// it's also called by greenlock._update({ subject, renewAt })
return mergSiteConfig(subject, opts);
};
manage.remove = function({ subject, altname }) {
if (subject) {
return removeSiteConfig(subject);
}
return removeFromSiteConfigAndResetRenewAtToZero(altname);
};
// set the global config
manage.defaults = function(options) {
if (!options) {
return getGlobalConfig();
}
return mergeGlobalConfig(options);
};
};
```
# ACME Challenge Plugins
The ACME challenge plugins are just a few simple callbacks:
- `init`
- `zones` (dns-01 only)
- `set`
- `get`
- `remove`
They are described here:
- [dns-01 documentation](https://git.rootprojects.org/root/acme-dns-01-test.js)
- [http-01 documentation](https://git.rootprojects.org/root/acme-http-01-test.js)
# Key and Cert Store Plugins
Again, these are just a few simple callbacks:
- `certificates.checkKeypair`
- `certificates.check`
- `certificates.setKeypair`
- `certificates.set`
- `accounts.checkKeypair`
- `accounts.check` (optional)
- `accounts.setKeypair`
- `accounts.set` (optional)
The name `check` is used instead of `get` because they only need to return something if it exists. They do not need to fail, nor do they need to generate anything.
They are described here:
- [greenlock store documentation](https://git.rootprojects.org/root/greenlock-store-test.js)
If you are just implenting in-house and are not going to publish a module, you can also do some hack things like this:
### Custome Store, The hacky / lazy way
`/path/to/project/my-hacky-store.js`:
```js
'use strict';
module.exports.create = function(options) {
// ex: /path/to/account.ecdsa.jwk.json
var accountJwk = require(options.accountJwkPath);
// ex: /path/to/privkey.rsa.pem
var serverPem = fs.readFileSync(options.serverPemPath, 'ascii');
var accounts = {};
var certificates = {};
var store = { accounts, certificates };
// bare essential account callbacks
accounts.checkKeypair = function() {
// ignore all options and just return a single, global keypair
return Promise.resolve({
privateKeyJwk: accountJwk
});
};
accounts.setKeypair = function() {
// this will never get called if checkKeypair always returns
return Promise.resolve({});
};
// bare essential cert and key callbacks
certificates.checkKeypair = function() {
// ignore all options and just return a global server keypair
return {
privateKeyPem: serverPem
};
};
certificates.setKeypair = function() {
// never gets called if checkKeypair always returns an existing key
return Promise.resolve(null);
};
certificates.check = function(args) {
var subject = args.subject;
// make a database call or whatever to get a certificate
return goGetCertBySubject(subject).then(function() {
return {
pems: {
chain: '<PEM>',
cert: '<PEM>'
}
};
});
};
certificates.set = function(args) {
var subject = args.subject;
var cert = args.pems.cert;
var chain = args.pems.chain;
// make a database call or whatever to get a certificate
return goSaveCert({
subject,
cert,
chain
});
};
};
```
### Using the hacky / lazy store plugin
That sort of implementation won't pass the test suite, but it'll work just fine a use case where you only have one subscriber email (most of the time),
you only have one server key (not recommended, but works), and you only really want to worry about storing cetificates.
Then you could assign it as the default for all of your sites:
```json
{
"subscriberEmail": "jon@example.com",
"agreeToTerms": true,
"sites": {
"example.com": {
"subject": "example.com",
"altnames": ["example.com", "www.example.com"]
}
},
"store": {
"module": "/path/to/project/my-hacky-store.js",
"accountJwkPath": "/path/to/account.ecdsa.jwk.json",
"serverPemPath": "/path/to/privkey.rsa.pem"
}
}
```

30
README.md

@ -1,4 +1,4 @@
# New Documentation &amp; [v2/v3 Migration Guide](https://git.rootprojects.org/root/greenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md)
# New Documentation &amp; [v2/v3 Migration Guide](https://git.rootprojects.orggreenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md)
Greenlock v3 was just released from private beta **today** (Nov 1st, 2019).
@ -6,19 +6,19 @@ We're still working on the full documentation for this new version,
so please be patient.
To start, check out the
[Migration Guide](https://git.rootprojects.org/root/greenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md).
[Migration Guide](https://git.rootprojects.orggreenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md).
!["Greenlock Logo"](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/greenlock-1063x250.png 'Greenlock lock logo and work mark')
!["Greenlock Logo"](https://git.rootprojects.orggreenlock.js/raw/branch/master/logo/greenlock-1063x250.png 'Greenlock lock logo and work mark')
!["Greenlock Function"](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/from-not-secure-to-secure-url-bar.png 'from url bar showing not secure to url bar showing secure')
!["Greenlock Function"](https://git.rootprojects.orggreenlock.js/raw/branch/master/logo/from-not-secure-to-secure-url-bar.png 'from url bar showing not secure to url bar showing secure')
# [Greenlock](https://git.rootprojects.org/root/greenlock.js) is Let's Encrypt for JavaScript
# [Greenlock](https://git.rootprojects.orggreenlock.js) is Let's Encrypt for JavaScript
| Built by [Root](https://rootprojects.org) for [Hub](https://rootprojects.org/hub/)
Greenlock&trade; is an Automated Certificate Management Environement 🔐.
| **Greenlock** | [Greenlock Express](https://git.rootprojects.org/root/greenlock-express.js) | [ACME.js](https://git.rootprojects.org/root/acme.js) |
| **Greenlock** | [Greenlock Express](https://git.rootprojects.orggreenlock-express.js) | [ACME.js](https://git.rootprojects.org/root/acme.js) |
It uses **Let's Encrypt** to generate Free SSL Certificates, including **Wildcard** SSL.
It supports **Automated Renewal** of certs for Fully Automated HTTPS.
@ -289,7 +289,7 @@ gl.add({
## Greenlock#get()
**Disclaimer**: This is only intended for testing, demos, and SNICallback
(in [Greenlock Express](https://git.rootprojects.org/root/greenlock-express.js)).
(in [Greenlock Express](https://git.rootprojects.orggreenlock-express.js)).
Greenlock is intended to be left running to allow it to fetech and renew certifictates automatically.
@ -297,7 +297,7 @@ It is intended that you use the `store` callbacks to new certificates instantly
This also protects you from accidentally stampeding the Let's Encrypt API with hundreds (or thousands)
of certificate requests.
- [Store Callback Documentation](https://git.rootprojects.org/root/greenlock-store-test.js)
- [Store Callback Documentation](https://git.rootprojects.orggreenlock-store-test.js)
```js
return greenlock.get({ servername }).then(function(site) {
@ -402,7 +402,7 @@ Greenlock comes with reasonable defaults but when you install it,
you should also install any plugins that you need.
```bash
npm install --save @root/greenlock
npm install --save greenlock
npm install --save greenlock-manager-fs
npm install --save greenlock-store-fs
npm install --save acme-http-01-standalone
@ -420,7 +420,7 @@ TODO
```js
'use strict';
var Greenlock = require(@root/greenlock-express);
var Greenlock = require(greenlock-express);
var greenlock = Greenlock.create({
// for security and critical bug notices
@ -450,7 +450,7 @@ TODO
<!-- greenlock-manager-test => greenlock-manager-custom -->
<!--
- [greenlock.js/examples/](https://git.rootprojects.org/root/greenlock.js/src/branch/master/examples)
- [greenlock.js/examples/](https://git.rootprojects.orggreenlock.js/src/branch/master/examples)
-->
<details>
@ -458,7 +458,7 @@ TODO
## SSL Certificate & Domain Management
Full Docs: https://git.rootprojects.org/root/greenlock-manager-test.js
Full Docs: https://git.rootprojects.orggreenlock-manager-test.js
This is what keeps the mapping of domains <-> certificates.
In many cases it will interact with the same database as the Key & Cert Store, and probably the code as well.
@ -507,7 +507,7 @@ In many cases it will interact with the same database as the Key & Cert Store, a
## Key and Certificate Store
Full Docs: https://git.rootprojects.org/root/greenlock-store-test.js
Full Docs: https://git.rootprojects.orggreenlock-store-test.js
This set of callbacks update your service with new certificates and keypairs.
@ -655,12 +655,12 @@ Greenlock&trade; is a [trademark](https://rootprojects.org/legal/#trademark) of
The rule of thumb is "attribute, but don't confuse". For example:
> Built with [Greenlock Express](https://git.rootprojects.org/root/greenlock.js) (a [Root](https://rootprojects.org) project).
> Built with [Greenlock Express](https://git.rootprojects.orggreenlock.js) (a [Root](https://rootprojects.org) project).
Please [contact us](mailto:aj@therootcompany.com) if you have any questions in regards to our trademark,
attribution, and/or visible source policies. We want to build great software and a great community.
[Greenlock&trade;](https://git.rootprojects.org/root/greenlock.js) |
[Greenlock&trade;](https://git.rootprojects.orggreenlock.js) |
MPL-2.0 |
[Terms of Use](https://therootcompany.com/legal/#terms) |
[Privacy Policy](https://therootcompany.com/legal/#privacy)

219
accounts.js

@ -1,219 +0,0 @@
'use strict';
var A = module.exports;
var U = require('./utils.js');
var E = require('./errors.js');
var pending = {};
A._getOrCreate = function(gnlck, mconf, db, acme, args) {
var email = args.subscriberEmail || mconf.subscriberEmail;
if (!email) {
throw E.NO_SUBSCRIBER('get account', args.subject);
}
// TODO send welcome message with benefit info
return U._validMx(email)
.catch(function() {
throw E.NO_SUBSCRIBER('get account', args.subcriberEmail);
})
.then(function() {
if (pending[email]) {
return pending[email];
}
pending[email] = A._rawGetOrCreate(
gnlck,
mconf,
db,
acme,
args,
email
)
.catch(function(e) {
delete pending[email];
throw e;
})
.then(function(result) {
delete pending[email];
return result;
});
return pending[email];
});
};
// What we really need out of this is the private key and the ACME "key" id
A._rawGetOrCreate = function(gnlck, mconf, db, acme, args, email) {
var p;
if (db.check) {
p = A._checkStore(gnlck, mconf, db, acme, args, email);
} else {
p = Promise.resolve(null);
}
return p.then(function(fullAccount) {
if (!fullAccount) {
return A._newAccount(gnlck, mconf, db, acme, args, email, null);
}
if (fullAccount.keypair && fullAccount.key && fullAccount.key.kid) {
return fullAccount;
}
return A._newAccount(gnlck, mconf, db, acme, args, email, fullAccount);
});
};
A._newAccount = function(gnlck, mconf, db, acme, args, email, fullAccount) {
var keyType = args.accountKeyType || mconf.accountKeyType;
var query = {
subject: args.subject,
email: email,
subscriberEmail: email,
customerEmail: args.customerEmail,
account: fullAccount || {},
directoryUrl:
args.directoryUrl ||
mconf.directoryUrl ||
gnlck._defaults.directoryUrl
};
return U._getOrCreateKeypair(db, args.subject, query, keyType).then(
function(kresult) {
var keypair = kresult.keypair;
var accReg = {
subscriberEmail: email,
agreeToTerms:
args.agreeToTerms ||
mconf.agreeToTerms ||
gnlck._defaults.agreeToTerms,
accountKey: keypair.privateKeyJwk || keypair.private,
debug: args.debug
};
return acme.accounts.create(accReg).then(function(receipt) {
var reg = {
keypair: keypair,
receipt: receipt,
// shudder... not actually a KeyID... but so it is called anyway...
kid:
receipt &&
receipt.key &&
(receipt.key.kid || receipt.kid),
email: args.email,
subscriberEmail: email,
customerEmail: args.customerEmail
};
var keyP;
if (kresult.exists) {
keyP = Promise.resolve();
} else {
query.keypair = keypair;
query.receipt = receipt;
/*
query.server = gnlck._defaults.directoryUrl.replace(
/^https?:\/\//i,
''
);
*/
keyP = db.setKeypair(query, keypair);
}
return keyP
.then(function() {
if (!db.set) {
return Promise.resolve({
keypair: keypair
});
}
return db.set(
{
// id to be set by Store
email: email,
subscriberEmail: email,
customerEmail: args.customerEmail,
agreeTos: true,
agreeToTerms: true,
directoryUrl:
args.directoryUrl ||
mconf.directoryUrl ||
gnlck._defaults.directoryUrl
/*
server: gnlck._defaults.directoryUrl.replace(
/^https?:\/\//i,
''
)
*/
},
reg
);
})
.then(function(fullAccount) {
if (fullAccount && 'object' !== typeof fullAccount) {
throw new Error(
"accounts.set should either return 'null' or an object with an 'id' string"
);
}
if (!fullAccount) {
fullAccount = {};
}
fullAccount.keypair = keypair;
if (!fullAccount.key) {
fullAccount.key = {};
}
fullAccount.key.kid = reg.kid;
return fullAccount;
});
});
}
);
};
A._checkStore = function(gnlck, mconf, db, acme, args, email) {
if ((args.domain || args.domains) && !args.subject) {
console.warn("use 'subject' instead of 'domain'");
args.subject = args.domain;
}
var account = args.account;
if (!account) {
account = {};
}
if (args.accountKey) {
console.warn(
'rather than passing accountKey, put it directly into your account key store'
);
// TODO we probably don't need this
return U._importKeypair(args.accountKey);
}
if (!db.check) {
return Promise.resolve(null);
}
return db
.check({
//keypair: undefined,
//receipt: undefined,
email: email,
subscriberEmail: email,
customerEmail: args.customerEmail || mconf.customerEmail,
account: account,
directoryUrl:
args.directoryUrl ||
mconf.directoryUrl ||
gnlck._defaults.directoryUrl
})
.then(function(fullAccount) {
if (!fullAccount) {
return null;
}
return fullAccount;
});
};

378
bin/certonly.js

@ -1,378 +0,0 @@
'use strict';
var mkdirp = require('@root/mkdirp');
var cli = require('./cli.js');
cli.parse({
'directory-url': [
false,
' ACME Directory Resource URL',
'string',
'https://acme-v02.api.letsencrypt.org/directory',
'server,acme-url'
],
email: [
false,
' Email used for registration and recovery contact. (default: null)',
'email'
],
'agree-tos': [
false,
" Agree to the Greenlock and Let's Encrypt Subscriber Agreements",
'boolean',
false
],
'community-member': [
false,
' Submit stats to and get updates from Greenlock',
'boolean',
false
],
domains: [
false,
' Domain names to apply. For multiple domains you can enter a comma separated list of domains as a parameter. (default: [])',
'string'
],
'renew-offset': [
false,
' Positive (time after issue) or negative (time before expiry) offset, such as 30d or -45d',
'string',
'45d'
],
'renew-within': [
false,
' (ignored) use renew-offset instead',
'ignore',
undefined
],
'cert-path': [
false,
' Path to where new cert.pem is saved',
'string',
':configDir/live/:hostname/cert.pem'
],
'fullchain-path': [
false,
' Path to where new fullchain.pem (cert + chain) is saved',
'string',
':configDir/live/:hostname/fullchain.pem'
],
'bundle-path': [
false,
' Path to where new bundle.pem (fullchain + privkey) is saved',
'string',
':configDir/live/:hostname/bundle.pem'
],
'chain-path': [
false,
' Path to where new chain.pem is saved',
'string',
':configDir/live/:hostname/chain.pem'
],
'privkey-path': [
false,
' Path to where privkey.pem is saved',
'string',
':configDir/live/:hostname/privkey.pem'
],
'config-dir': [
false,
' Configuration directory.',
'string',
'~/letsencrypt/etc/'
],
store: [
false,
' The name of the storage module to use',
'string',
'greenlock-store-fs'
],
'store-xxxx': [
false,
' An option for the chosen storage module, such as --store-apikey or --store-bucket',
'bag'
],
'store-json': [
false,
' A JSON string containing all option for the chosen store module (instead of --store-xxxx)',
'json',
'{}'
],
challenge: [
false,
' The name of the HTTP-01, DNS-01, or TLS-ALPN-01 challenge module to use',
'string',
'@greenlock/acme-http-01-fs'
],
'challenge-xxxx': [
false,
' An option for the chosen challenge module, such as --challenge-apikey or --challenge-bucket',
'bag'
],
'challenge-json': [
false,
' A JSON string containing all option for the chosen challenge module (instead of --challenge-xxxx)',
'json',
'{}'
],
'skip-dry-run': [
false,
' Use with caution (and test with the staging url first). Creates an Order on the ACME server without a self-test.',
'boolean'
],
'skip-challenge-tests': [
false,
' Use with caution (and with the staging url first). Presents challenges to the ACME server without first testing locally.',
'boolean'
],
'http-01-port': [
false,
' Required to be 80 for live servers. Do not use. For special test environments only.',
'int'
],
'dns-01': [false, ' Use DNS-01 challange type', 'boolean', false],
standalone: [
false,
' Obtain certs using a "standalone" webserver.',
'boolean',
false
],
manual: [
false,
' Print the token and key to the screen and wait for you to hit enter, giving you time to copy it somewhere before continuing (uses acme-http-01-cli or acme-dns-01-cli)',
'boolean',
false
],
debug: [false, ' show traces and logs', 'boolean', false],
root: [
false,
' public_html / webroot path (may use the :hostname template such as /srv/www/:hostname)',
'string',
undefined,
'webroot-path'
],
//
// backwards compat
//
duplicate: [
false,
' Allow getting a certificate that duplicates an existing one/is an early renewal',
'boolean',
false
],
'rsa-key-size': [
false,
' (ignored) use server-key-type or account-key-type instead',
'ignore',
2048
],
'server-key-path': [
false,
' Path to privkey.pem to use for certificate (default: generate new)',
'string',
undefined,
'domain-key-path'
],
'server-key-type': [
false,
" One of 'RSA' (2048), 'RSA-3084', 'RSA-4096', 'ECDSA' (P-256), or 'P-384'. For best compatibility, security, and efficiency use the default (More bits != More security)",
'string',
'RSA'
],
'account-key-path': [
false,
' Path to privkey.pem to use for account (default: generate new)',
'string'
],
'account-key-type': [
false,
" One of 'ECDSA' (P-256), 'P-384', 'RSA', 'RSA-3084', or 'RSA-4096'. Stick with 'ECDSA' (P-256) unless you need 'RSA' (2048) for legacy compatibility. (More bits != More security)",
'string',
'P-256'
],
webroot: [false, ' (ignored) for certbot compatibility', 'ignore', false],
//, 'standalone-supported-challenges': [ false, " Supported challenges, order preferences are randomly chosen. (default: http-01,tls-alpn-01)", 'string', 'http-01']
'work-dir': [
false,
' for certbot compatibility (ignored)',
'string',
'~/letsencrypt/var/lib/'
],
'logs-dir': [
false,
' for certbot compatibility (ignored)',
'string',
'~/letsencrypt/var/log/'
],
'acme-version': [
false,
' (ignored) ACME is now RFC 8555 and prior drafts are no longer supported',
'ignore',
'rfc8555'
]
});
// ignore certonly and extraneous arguments
cli.main(function(_, options) {
console.info('');
[
'configDir',
'privkeyPath',
'certPath',
'chainPath',
'fullchainPath',
'bundlePath'
].forEach(function(k) {
if (options[k]) {
options.storeOpts[k] = options[k];
}
delete options[k];
});
if (options.workDir) {
options.challengeOpts.workDir = options.workDir;
delete options.workDir;
}
if (options.debug) {
console.debug(options);
}
var args = {};
var homedir = require('os').homedir();
Object.keys(options).forEach(function(key) {
var val = options[key];
if ('string' === typeof val) {
val = val.replace(/^~/, homedir);
}
key = key.replace(/\-([a-z0-9A-Z])/g, function(c) {
return c[1].toUpperCase();
});
args[key] = val;
});
Object.keys(args).forEach(function(key) {
var val = args[key];
if ('string' === typeof val) {
val = val.replace(/(\:configDir)|(\:config)/, args.configDir);
}
args[key] = val;
});
if (args.domains) {
args.domains = args.domains.split(',');
}
if (
!(Array.isArray(args.domains) && args.domains.length) ||
!args.email ||
!args.agreeTos ||
(!args.server && !args.directoryUrl)
) {
console.error('\nUsage:\n\ngreenlock certonly --standalone \\');
console.error(
'\t--agree-tos --email user@example.com --domains example.com \\'
);
console.error('\t--config-dir ~/acme/etc \\');
console.error('\nSee greenlock --help for more details\n');
return;
}
if (args.http01Port) {
// [@agnat]: Coerce to string. cli returns a number although we request a string.
args.http01Port = '' + args.http01Port;
args.http01Port = args.http01Port.split(',').map(function(port) {
return parseInt(port, 10);
});
}
function run() {
var challenges = {};
if (/http.?01/i.test(args.challenge)) {
challenges['http-01'] = args.challengeOpts;
}
if (/dns.?01/i.test(args.challenge)) {
challenges['dns-01'] = args.challengeOpts;
}
if (/alpn.?01/i.test(args.challenge)) {
challenges['tls-alpn-01'] = args.challengeOpts;
}
if (!Object.keys(challenges).length) {
throw new Error(
"Could not determine the challenge type for '" +
args.challengeOpts.module +
"'. Expected a name like @you/acme-xxxx-01-foo. Please name the module with http-01, dns-01, or tls-alpn-01."
);
}
args.challengeOpts.module = args.challenge;
args.storeOpts.module = args.store;
console.log('\ngot to the run step');
require(args.challenge);
require(args.store);
var greenlock = require('../').create({
maintainerEmail: args.maintainerEmail || 'coolaj86@gmail.com',
manager: './manager.js',
configFile: '~/.config/greenlock/certs.json',
challenges: challenges,
store: args.storeOpts,
renewOffset: args.renewOffset || '30d',
renewStagger: '1d'
});
// for long-running processes
if (args.renewEvery) {
setInterval(function() {
greenlock.renew({
period: args.renewEvery
});
}, args.renewEvery);
}
// TODO should greenlock.add simply always include greenlock.renew?
// the concern is conflating error events
return greenlock
.add({
subject: args.subject,
altnames: args.altnames,
subscriberEmail: args.subscriberEmail || args.email
})
.then(function(changes) {
console.info(changes);
// renew should always
return greenlock
.renew({
subject: args.subject,
force: false
})
.then(function() {});
});
}
if ('greenlock-store-fs' !== args.store) {
run();
return;
}
// TODO remove mkdirp and let greenlock-store-fs do this?
mkdirp(args.storeOpts.configDir, function(err) {
if (!err) {
run();
}
console.error(
"Could not create --config-dir '" + args.configDir + "':",
err.code
);
console.error("Try setting --config-dir '/tmp'");
return;
});
}, process.argv.slice(3));

234
bin/cli.js

@ -1,234 +0,0 @@
'use strict';
var CLI = module.exports;
var defaultConf;
var defaultOpts;
var bags = [];
CLI.parse = function(conf) {
var opts = (defaultOpts = {});
defaultConf = conf;
Object.keys(conf).forEach(function(k) {
var v = conf[k];
var aliases = v[5];
var bag;
var bagName;
// the name of the argument set is now the 0th argument
v.unshift(k);
// v[0] flagname
// v[1] short flagname
// v[2] description
// v[3] type
// v[4] default value
// v[5] aliases
if ('bag' === v[3]) {
bag = v[0]; // 'bag-option-xxxx' => '--bag-option-'
bag = '--' + bag.replace(/xxx.*/, '');
bags.push(bag);
bagName = toBagName(bag.replace(/^--/, ''));
opts[bagName] = {};
}
if ('json' === v[3]) {
bagName = toBagName(v[0].replace(/-json$/, '')); // 'bag-option-json' => 'bagOptionOpts'
opts[bagName] = {};
} else if ('ignore' !== v[3] && 'undefined' !== typeof v[4]) {
// set the default values (where 'undefined' is not an allowed value)
opts[toCamel(k)] = v[4];
}
if (!aliases) {
aliases = [];
} else if ('string' === typeof aliases) {
aliases = aliases.split(',');
}
aliases.forEach(function(alias) {
if (alias in conf) {
throw new Error(
"Cannot alias '" +
alias +
"' from '" +
k +
"': option already exists"
);
}
conf[alias] = v;
});
});
};
CLI.main = function(cb, args) {
var leftovers = [];
var conf = defaultConf;
var opts = defaultOpts;
if (!opts) {
throw new Error("you didn't call `CLI.parse(configuration)`");
}
// TODO what's the existing API for this?
if (!args) {
args = process.argv.slice(2);
}
var flag;
var cnf;
var typ;
function grab(bag) {
var bagName = toBagName(bag);
if (bag !== flag.slice(0, bag.length)) {
return false;
}
console.log(bagName, toCamel(flag.slice(bag.length)));
opts[bagName][toCamel(flag.slice(bag.length))] = args.shift();
return true;
}
while (args.length) {
// take one off the top
flag = args.shift();
// mind the gap
if ('--' === flag) {
leftovers = leftovers.concat(args);
break;
}
// help!
if (
'--help' === flag ||
'-h' === flag ||
'/?' === flag ||
'help' === flag
) {
printHelp(conf);
process.exit(1);
}
// only long names are actually used
if ('--' !== flag.slice(0, 2)) {
console.error("Unrecognized argument '" + flag + "'");
process.exit(1);
}
cnf = conf[flag.slice(2)];
if (!cnf) {
// look for arbitrary flags
if (bags.some(grab)) {
continue;
}
// other arbitrary args are not used
console.error("Unrecognized flag '" + flag + "'");
process.exit(1);
}
// encourage switching to non-aliased version
if (flag !== '--' + cnf[0]) {
console.warn(
"use of '" +
flag +
"' is deprecated, use '--" +
cnf[0] +
"' instead"
);
}
// look for xxx-json flags
if ('json' === cnf[3]) {
try {
var json = JSON.parse(args.shift());
var bagName = toBagName(cnf[0].replace(/-json$/, ''));
Object.keys(json).forEach(function(k) {
opts[bagName][k] = json[k];
});
} catch (e) {
console.error("Could not parse option '" + flag + "' as JSON:");
console.error(e.message);
process.exit(1);
}
continue;
}
// set booleans, otherwise grab the next arg in line
typ = cnf[3];
// TODO --no-<whatever> to negate
if (Boolean === typ || 'boolean' === typ) {
opts[toCamel(cnf[0])] = true;
continue;
}
opts[toCamel(cnf[0])] = args.shift();
continue;
}
cb(leftovers, opts);
};
function toCamel(str) {
return str.replace(/-([a-z0-9])/g, function(m) {
return m[1].toUpperCase();
});
}
function toBagName(bag) {
// trim leading and trailing '-'
bag = bag.replace(/^-+/g, '').replace(/-+$/g, '');
return toCamel(bag) + 'Opts'; // '--bag-option-' => bagOptionOpts
}
function printHelp(conf) {
var flagLen = 0;
var typeLen = 0;
var defLen = 0;
Object.keys(conf).forEach(function(k) {
flagLen = Math.max(flagLen, conf[k][0].length);
typeLen = Math.max(typeLen, conf[k][3].length);
if ('undefined' !== typeof conf[k][4]) {
defLen = Math.max(
defLen,
'(Default: )'.length + String(conf[k][4]).length
);
}
});
Object.keys(conf).forEach(function(k) {
var v = conf[k];
// skip aliases
if (v[0] !== k) {
return;
}
var def = v[4];
if ('undefined' === typeof def) {
def = '';
} else {
def = '(default: ' + JSON.stringify(def) + ')';
}
var msg =
' --' +
v[0].padEnd(flagLen) +
' ' +
v[3].padStart(typeLen + 1) +
' ' +
(v[2] || '') +
' ' +
def; /*.padStart(defLen)*/
// v[0] flagname
// v[1] short flagname
// v[2] description
// v[3] type
// v[4] default value
// v[5] aliases
console.info(msg);
});
}

13
bin/greenlock.js

@ -1,13 +0,0 @@
#!/usr/bin/env node
'use strict';
var args = process.argv.slice(2);
//console.log(args);
//['certonly', 'add', 'config', 'defaults', 'remove']
if ('certonly' === args[0]) {
require('./certonly.js');
return;
}
console.error("command not yet implemented");
process.exit();

318
certificates.js

@ -1,318 +0,0 @@
'use strict';
var C = module.exports;
var U = require('./utils.js');
var CSR = require('@root/csr');
var Enc = require('@root/encoding');
var Keypairs = require('@root/keypairs');
var pending = {};
var rawPending = {};
// What the abbreviations mean
//
// gnlkc => greenlock
// mconf => manager config
// db => greenlock store instance
// acme => instance of ACME.js
// chs => instances of challenges
// acc => account
// args => site / extra options
// Certificates
C._getOrOrder = function(gnlck, mconf, db, acme, chs, acc, args) {
var email = args.subscriberEmail || mconf.subscriberEmail;
var id = args.altnames
.slice(0)
.sort()
.join(' ');
if (pending[id]) {
return pending[id];
}
pending[id] = C._rawGetOrOrder(
gnlck,
mconf,
db,
acme,
chs,
acc,
email,
args
)
.then(function(pems) {
delete pending[id];
return pems;
})
.catch(function(err) {
delete pending[id];
throw err;
});
return pending[id];
};
// Certificates
C._rawGetOrOrder = function(gnlck, mconf, db, acme, chs, acc, email, args) {
return C._check(gnlck, mconf, db, args).then(function(pems) {
// Nice and fresh? We're done!
if (pems) {
if (!C._isStale(gnlck, mconf, args, pems)) {
// return existing unexpired (although potentially stale) certificates when available
// there will be an additional .renewing property if the certs are being asynchronously renewed
//pems._type = 'current';
return pems;
}
}
// We're either starting fresh or freshening up...
var p = C._rawOrder(gnlck, mconf, db, acme, chs, acc, email, args);
var evname = pems ? 'cert_renewal' : 'cert_issue';
p.then(function(newPems) {
// notify in the background
var renewAt = C._renewWithStagger(gnlck, mconf, args, newPems);
gnlck._notify(evname, {
renewAt: renewAt,
subject: args.subject,
altnames: args.altnames
});
gnlck._notify('_cert_issue', {
renewAt: renewAt,
subject: args.subject,
altnames: args.altnames,
pems: newPems
});
}).catch(function(err) {
if (!err.context) {
err.context = evname;
}
err.subject = args.subject;
err.altnames = args.altnames;
gnlck._notify('error', err);
});
// No choice but to hang tight and wait for it
if (
!pems ||
pems.renewAt < Date.now() - 24 * 60 * 60 * 1000 ||
pems.expiresAt <= Date.now() + 24 * 60 * 60 * 1000
) {
return p;
}
// Wait it out
// TODO should we call this waitForRenewal?
if (args.waitForRenewal) {
return p;
}
// Let the certs renew in the background
return pems;
});
};
// we have another promise here because it the optional renewal
// may resolve in a different stack than the returned pems
C._rawOrder = function(gnlck, mconf, db, acme, chs, acc, email, args) {
var id = args.altnames
.slice(0)
.sort()
.join(' ');
if (rawPending[id]) {
return rawPending[id];
}
var keyType = args.serverKeyType || mconf.serverKeyType;
var query = {
subject: args.subject,
certificate: args.certificate || {},
directoryUrl: args.directoryUrl || gnlck._defaults.directoryUrl
};
rawPending[id] = U._getOrCreateKeypair(db, args.subject, query, keyType)
.then(function(kresult) {
var serverKeypair = kresult.keypair;
var domains = args.altnames.slice(0);
return CSR.csr({
jwk: serverKeypair.privateKeyJwk || serverKeypair.private,
domains: domains,
encoding: 'der'
})
.then(function(csrDer) {
// TODO let CSR support 'urlBase64' ?
return Enc.bufToUrlBase64(csrDer);
})
.then(function(csr) {
function notify(ev, opts) {
gnlck._notify(ev, opts);
}
var certReq = {
debug: args.debug || gnlck._defaults.debug,
challenges: chs,
account: acc, // only used if accounts.key.kid exists
accountKey:
acc.keypair.privateKeyJwk || acc.keypair.private,
keypair: acc.keypair, // TODO
csr: csr,
domains: domains, // because ACME.js v3 uses `domains` still, actually
onChallengeStatus: notify,
notify: notify // TODO
// TODO handle this in acme-v2
//subject: args.subject,
//altnames: args.altnames.slice(0),
};
return acme.certificates
.create(certReq)
.then(U._attachCertInfo);
})
.then(function(pems) {
if (kresult.exists) {
return pems;
}
query.keypair = serverKeypair;
return db.setKeypair(query, serverKeypair).then(function() {
return pems;
});
});
})
.then(function(pems) {
// TODO put this in the docs
// { cert, chain, privkey, subject, altnames, issuedAt, expiresAt }
// Note: the query has been updated
query.pems = pems;
return db.set(query);
})
.then(function() {
return C._check(gnlck, mconf, db, args);
})
.then(function(bundle) {
// TODO notify Manager
delete rawPending[id];
return bundle;
})
.catch(function(err) {
// Todo notify manager
delete rawPending[id];
throw err;
});
return rawPending[id];
};
// returns pems, if they exist
C._check = function(gnlck, mconf, db, args) {
var query = {
subject: args.subject,
// may contain certificate.id
certificate: args.certificate,
directoryUrl: args.directoryUrl || gnlck._defaults.directoryUrl
};
return db.check(query).then(function(pems) {
if (!pems) {
return null;
}
pems = U._attachCertInfo(pems);
// For eager management
if (args.subject && !U._certHasDomain(pems, args.subject)) {
// TODO report error, but continue the process as with no cert
return null;
}
// For lazy SNI requests
if (args.domain && !U._certHasDomain(pems, args.domain)) {
// TODO report error, but continue the process as with no cert
return null;
}
return U._getKeypair(db, args.subject, query)
.then(function(keypair) {
return Keypairs.export({
jwk: keypair.privateKeyJwk || keypair.private,
encoding: 'pem'
}).then(function(pem) {
pems.privkey = pem;
return pems;
});
})
.catch(function() {
// TODO report error, but continue the process as with no cert
return null;
});
});
};
// Certificates
C._isStale = function(gnlck, mconf, args, pems) {
if (args.duplicate) {
return true;
}
var renewAt = C._renewableAt(gnlck, mconf, args, pems);
if (Date.now() >= renewAt) {
return true;
}
return false;
};
C._renewWithStagger = function(gnlck, mconf, args, pems) {
var renewOffset = C._renewOffset(gnlck, mconf, args, pems);
var renewStagger;
try {
renewStagger = U._parseDuration(
args.renewStagger || mconf.renewStagger || 0
);
} catch (e) {
renewStagger = U._parseDuration(
args.renewStagger || mconf.renewStagger
);
}
// TODO check this beforehand
if (!args.force && renewStagger / renewOffset >= 0.5) {
renewStagger = renewOffset * 0.1;
}
if (renewOffset > 0) {
// stagger forward, away from issued at
return Math.round(
pems.issuedAt + renewOffset + Math.random() * renewStagger
);
}
// stagger backward, toward issued at
return Math.round(
pems.expiresAt + renewOffset - Math.random() * renewStagger
);
};
C._renewOffset = function(gnlck, mconf, args /*, pems*/) {
var renewOffset = U._parseDuration(
args.renewOffset || mconf.renewOffset || 0
);
var week = 1000 * 60 * 60 * 24 * 6;
if (!args.force && Math.abs(renewOffset) < week) {
throw new Error(
'developer error: `renewOffset` should always be at least a week, use `force` to not safety-check renewOffset'
);
}
return renewOffset;
};
C._renewableAt = function(gnlck, mconf, args, pems) {
if (args.renewAt) {
return args.renewAt;
}
var renewOffset = C._renewOffset(gnlck, mconf, args, pems);
if (renewOffset > 0) {
return pems.issuedAt + renewOffset;
}
return pems.expiresAt + renewOffset;
};

96
challenges-underlay.js

@ -1,96 +0,0 @@
'use strict';
var Greenlock = require('./');
module.exports.wrap = function(greenlock) {
greenlock.challenges.get = function(chall) {
// TODO pick one and warn on the others
// (just here due to some backwards compat issues with early v3 plugins)
var servername =
chall.servername ||
chall.altname ||
(chall.identifier && chall.identifier.value);
// TODO some sort of caching to prevent database hits?
return greenlock
._config({ servername: servername })
.then(function(site) {
if (!site) {
return null;
}
// Hmm... this _should_ be impossible
if (!site.challenges || !site.challenges['http-01']) {
var copy = JSON.parse(JSON.stringify(site));
sanitizeCopiedConf(copy);
sanitizeCopiedConf(copy.store);
if (site.challenges) {
sanitizeCopiedConf(copy.challenges['http-01']);
sanitizeCopiedConf(copy.challenges['dns-01']);
sanitizeCopiedConf(copy.challenges['tls-alpn-01']);
}
console.warn('[Bug] Please report this error:');
console.warn(
'\terror: http-01 challenge requested, but not even a default http-01 config exists'
);
console.warn('\tservername:', JSON.stringify(servername));
console.warn('\tsite:', JSON.stringify(copy));
return null;
}
return Greenlock._loadChallenge(site.challenges, 'http-01');
})
.then(function(plugin) {
if (!plugin) {
return null;
}
return plugin
.get({
challenge: {
type: chall.type,
//hostname: chall.servername,
altname: chall.servername,
identifier: { value: chall.servername },
token: chall.token
}
})
.then(function(result) {
var keyAuth;
var keyAuthDigest;
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 = result.challenge;
}
keyAuth = result.keyAuthorization;
keyAuthDigest = result.keyAuthorizationDigest;
}
if (/dns/.test(chall.type)) {
return {
keyAuthorizationDigest: keyAuthDigest
};
}
return {
keyAuthorization: keyAuth
};
});
});
};
};
function sanitizeCopiedConf(copy) {
if (!copy) {
return;
}
Object.keys(copy).forEach(function(k) {
if (/(api|key|token)/i.test(k) && 'string' === typeof copy[k]) {
copy[k] = '**redacted**';
}
});
return copy;
}

58
errors.js

@ -1,58 +0,0 @@
'use strict';
var E = module.exports;
function create(code, msg) {
E[code] = function(ctx, msg2) {
var err = new Error(msg);
err.code = code;
err.context = ctx;
if (msg2) {
err.message += ': ' + msg2;
}
/*
Object.keys(extras).forEach(function(k) {
if ('message' === k) {
err.message += ': ' + extras[k];
} else {
err[k] = extras[k];
}
});
*/
return err;
};
}
// TODO open issues and link to them as the error url
create(
'NO_MAINTAINER',
'please supply `maintainerEmail` as a contact for security and critical bug notices'
);
create(
'BAD_ORDER',
'altnames should be in deterministic order, with subject as the first altname'
);
create('NO_SUBJECT', 'no certificate subject given');
create(
'NO_SUBSCRIBER',
'please supply `subscriberEmail` as a contact for failed renewal and certificate revocation'
);
create(
'INVALID_SUBSCRIBER',
'`subscriberEmail` is not a valid address, please check for typos'
);
create(
'INVALID_HOSTNAME',
'valid hostnames must be restricted to a-z0-9_.- and contain at least one "."'
);
create(
'INVALID_DOMAIN',
'one or more domains do not exist on public DNS SOA record'
);
create(
'NOT_UNIQUE',
'found duplicate domains, or a subdomain that overlaps a wildcard'
);
// exported for testing only
E._create = create;

682
greenlock.js

@ -1,683 +1,3 @@
'use strict';
var pkg = require('./package.json');
var ACME = require('@root/acme');
var Greenlock = module.exports;
var request = require('@root/request');
var G = Greenlock;
var U = require('./utils.js');
var E = require('./errors.js');
var P = require('./plugins.js');
var A = require('./accounts.js');
var C = require('./certificates.js');
var UserEvents = require('./user-events.js');
var caches = {};
// { maintainerEmail, directoryUrl, subscriberEmail, store, challenges }
G.create = function(gconf) {
var greenlock = {};
var gdefaults = {};
if (!gconf) {
gconf = {};
}
var manager;
greenlock._create = function() {
if (!gconf.maintainerEmail) {
throw E.NO_MAINTAINER('create');
}
// TODO send welcome message with benefit info
U._validMx(gconf.maintainerEmail).catch(function() {
console.error(
'invalid maintainer contact info:',
gconf.maintainerEmail
);
// maybe move this to init and don't exit the process, just in case
process.exit(1);
});
if ('function' === typeof gconf.notify) {
gdefaults.notify = gconf.notify;
} else {
gdefaults.notify = _notify;
}
if (gconf.directoryUrl) {
gdefaults = gconf.directoryUrl;
if (gconf.staging) {
throw new Error(
'supply `directoryUrl` or `staging`, but not both'
);
}
} else if (gconf.staging) {
gdefaults.directoryUrl =
'https://acme-staging-v02.api.letsencrypt.org/directory';
} else {
gdefaults.directoryUrl =
'https://acme-v02.api.letsencrypt.org/directory';
}
console.info('ACME Directory URL:', gdefaults.directoryUrl);
manager = normalizeManager(gconf);
// Wraps each of the following with appropriate error checking
// greenlock.manager.defaults
// greenlock.manager.add
// greenlock.manager.update
// greenlock.manager.remove
// greenlock.manager.find
require('./manager-underlay.js').wrap(greenlock, manager, gconf);
// Exports challenges.get for Greenlock Express HTTP-01,
// and whatever odd use case pops up, I suppose
// greenlock.challenges.get
require('./challenges-underlay.js').wrap(greenlock, manager, gconf);
greenlock._defaults = gdefaults;
greenlock._defaults.debug = gconf.debug;
// renew every 90-ish minutes (random for staggering)
// the weak setTimeout (unref) means that when run as a CLI process this
// will still finish as expected, and not wait on the timeout
(function renew() {
setTimeout(function() {
greenlock.renew({});
renew();
}, Math.PI * 30 * 60 * 1000).unref();
})();
};
// The purpose of init is to make MCONF the source of truth
greenlock._init = function() {
var p;
greenlock._init = function() {
return p;
};
if (manager.init) {
// TODO punycode?
p = manager.init({
request: request
//punycode: require('punycode')
});
} else {
p = Promise.resolve();
}
p = p
.then(function() {
return manager.defaults().then(function(MCONF) {
mergeDefaults(MCONF, gconf);
if (true === MCONF.agreeToTerms) {
gdefaults.agreeToTerms = function(tos) {
return Promise.resolve(tos);
};
}
return manager.defaults(MCONF);
});
})
.catch(function(err) {
console.error('Fatal error during greenlock init:');
console.error(err);
process.exit(1);
});
return p;
};
// The goal here is to reduce boilerplate, such as error checking
// and duration parsing, that a manager must implement
greenlock.sites.add = greenlock.add = greenlock.manager.add;
greenlock.notify = greenlock._notify = function(ev, params) {
var mng = greenlock.manager;
if ('_' === String(ev)[0]) {
if ('_cert_issue' === ev) {
try {
mng.update({
subject: params.subject,
renewAt: params.renewAt
}).catch(function(e) {
e.context = '_cert_issue';
greenlock._notify('error', e);
});
} catch (e) {
e.context = '_cert_issue';
greenlock._notify('error', e);
}
}
// trap internal events internally
return;
}
try {
var p = greenlock._defaults.notify(ev, params);
if (p && p.catch) {
p.catch(function(e) {
console.error("Promise Rejection on event '" + ev + "':");
console.error(e);
});
}
} catch (e) {
console.error("Thrown Exception on event '" + ev + "':");
console.error(e);
console.error(params);
}
if (-1 !== ['cert_issue', 'cert_renewal'].indexOf(ev)) {
// We will notify all greenlock users of mandatory and security updates
// We'll keep track of versions and os so we can make sure things work well
// { name, version, email, domains, action, communityMember, telemetry }
// TODO look at the other one
UserEvents.notify({
/*
// maintainer should be only on pre-publish, or maybe install, I think
maintainerEmail: greenlock._defaults._maintainerEmail,
name: greenlock._defaults._packageAgent,
version: greenlock._defaults._maintainerPackageVersion,
//action: params.pems._type,
domains: params.altnames,
subscriberEmail: greenlock._defaults._subscriberEmail,
// TODO enable for Greenlock Pro
//customerEmail: args.customerEmail
telemetry: greenlock._defaults.telemetry
*/
});
}
};
// certs.get
greenlock.get = function(args) {
return greenlock
._single(args)
.then(function() {
args._includePems = true;
return greenlock.renew(args);
})
.then(function(results) {
if (!results || !results.length) {
// TODO throw an error here?
return null;
}
// just get the first one
var result = results[0];
// (there should be only one, ideally)
if (results.length > 1) {
var err = new Error(
"a search for '" +
args.servername +
"' returned multiple certificates"
);
err.context = 'duplicate_certs';
err.servername = args.servername;
err.subjects = results.map(function(r) {
return (r.site || {}).subject || 'N/A';
});
greenlock._notify('warning', err);
}
if (result.error) {
return Promise.reject(result.error);
}
// site for plugin options, such as http-01 challenge
// pems for the obvious reasons
return result;
});
};
greenlock._single = function(args) {
if ('string' !== typeof args.servername) {
return Promise.reject(new Error('no `servername` given'));
}
// www.example.com => *.example.com
args.wildname =
'*.' +
args.servername
.split('.')
.slice(1)
.join('.');
if (
args.servernames ||
args.subject ||
args.renewBefore ||
args.issueBefore ||
args.expiresBefore
) {
return Promise.reject(
new Error(
'bad arguments, did you mean to call greenlock.renew()?'
)
);
}
// duplicate, force, and others still allowed
return Promise.resolve(args);
};
greenlock._config = function(args) {
return greenlock
._single(args)
.then(function() {
return greenlock._find(args);
})
.then(function(sites) {
if (!sites || !sites.length) {
return null;
}
var site = sites[0];
site = JSON.parse(JSON.stringify(site));
if (site.store && site.challenges) {
return site;
}
return manager.defaults().then(function(mconf) {
if (!site.store) {
site.store = mconf.store;
}
if (!site.challenges) {
site.challenges = mconf.challenges;
}
return site;
});
});
};
// needs to get info about the renewal, such as which store and challenge(s) to use
greenlock.renew = function(args) {
return greenlock._init().then(function() {
return manager.defaults().then(function(mconf) {
return greenlock._renew(mconf, args);
});
});
};
greenlock._renew = function(mconf, args) {
if (!args) {
args = {};
}
var renewedOrFailed = [];
//console.log('greenlock._renew find', args);
return greenlock._find(args).then(function(sites) {
// Note: the manager must guaranteed that these are mutable copies
//console.log('greenlock._renew found', sites);;
function next() {
var site = sites.shift();
if (!site) {
return Promise.resolve(null);
}
var order = { site: site };
renewedOrFailed.push(order);
// TODO merge args + result?
return greenlock
._order(mconf, site)
.then(function(pems) {
if (args._includePems) {
order.pems = pems;
}
})
.catch(function(err) {
order.error = err;
// For greenlock express serialization
err.toJSON = errorToJSON;
err.context = err.context || 'cert_order';
err.subject = site.subject;
if (args.servername) {
err.servername = args.servername;
}
// for debugging, but not to be relied on
err._site = site;
// TODO err.context = err.context || 'renew_certificate'
greenlock._notify('error', err);
})
.then(function() {
return next();
});
}
return next().then(function() {
return renewedOrFailed;
});
});
};
greenlock._acme = function(args) {
var packageAgent = gconf.packageAgent || '';
// because Greenlock_Express/v3.x Greenlock/v3 is redundant
if (!/greenlock/i.test(packageAgent)) {
packageAgent = (packageAgent + ' Greenlock/' + pkg.version).trim();
}
var acme = ACME.create({
maintainerEmail: gconf.maintainerEmail,
packageAgent: packageAgent,
notify: greenlock._notify,
debug: greenlock._defaults.debug || args.debug
});
var dirUrl = args.directoryUrl || greenlock._defaults.directoryUrl;
var dir = caches[dirUrl];
// don't cache more than an hour
if (dir && Date.now() - dir.ts < 1 * 60 * 60 * 1000) {
return dir.promise;
}
return acme
.init(dirUrl)
.then(function(/*meta*/) {
caches[dirUrl] = {
promise: Promise.resolve(acme),
ts: Date.now()
};
return acme;
})
.catch(function(err) {
// TODO
// let's encrypt is possibly down for maintenaince...
// this is a special kind of failure mode
throw err;
});
};
greenlock.order = function(args) {
return greenlock._init().then(function() {
return manager.defaults().then(function(mconf) {
return greenlock._order(mconf, args);
});
});
};
greenlock._order = function(mconf, args) {
// packageAgent, maintainerEmail
return greenlock._acme(args).then(function(acme) {
var storeConf = args.store || mconf.store;
return P._loadStore(storeConf).then(function(store) {
return A._getOrCreate(
greenlock,
mconf,
store.accounts,
acme,
args
).then(function(account) {
var challengeConfs = args.challenges || mconf.challenges;
return Promise.all(
Object.keys(challengeConfs).map(function(typ01) {
return P._loadChallenge(challengeConfs, typ01);
})
).then(function(arr) {
var challenges = {};
arr.forEach(function(el) {
challenges[el._type] = el;
});
return C._getOrOrder(
greenlock,
mconf,
store.certificates,
acme,
challenges,
account,
args
).then(function(pems) {
if (!pems) {
throw new Error('no order result');
}
if (!pems.privkey) {
throw new Error(
'missing private key, which is kinda important'
);
}
return pems;
});
});
});
});
});
};
greenlock._create();
return greenlock;
};
G._loadChallenge = P._loadChallenge;
function errorToJSON(e) {
var error = {};
Object.getOwnPropertyNames(e).forEach(function(k) {
error[k] = e[k];
});
return error;
}
function normalizeManager(gconf) {
var m;
// 1. Get the manager
// 2. Figure out if we need to wrap it
if (!gconf.manager) {
gconf.manager = 'greenlock-manager-fs';
if (gconf.find) {
// { manager: 'greenlock-manager-fs', find: function () { } }
warpFind(gconf);
}
}
if ('string' === typeof gconf.manager) {
try {
// wrap this to be safe for greenlock-manager-fs
m = require(gconf.manager).create(gconf);
} catch (e) {
console.error(e.code);
console.error(e.message);
}
} else {
m = gconf.manager;
}
if (!m) {
console.error();
console.error(
'Failed to load manager plugin ',
JSON.stringify(gconf.manager)
);
console.error();
process.exit(1);
}
if (
['set', 'remove', 'find', 'defaults'].every(function(k) {
return 'function' === typeof m[k];
})
) {
return m;
}
// { manager: { find: function () { } } }
if (m.find) {
warpFind(m);
}
// m.configFile could also be set
m = require('greenlock-manager-fs').create(m);
if ('function' !== typeof m.find) {
console.error();
console.error(
JSON.stringify(gconf.manager),
'must implement `find()` and should implement `set()`, `remove()`, `defaults()`, and `init()`'
);
console.error();
process.exit(1);
}
return m;
}
function warpFind(gconf) {
gconf.__gl_find = gconf.find;
gconf.find = function(args) {
// the incoming args will be normalized by greenlock
return gconf.__gl_find(args).then(function(sites) {
// we also need to error check the incoming sites,
// as if they were being passed through `add()` or `set()`
// (effectively they are) because the manager assumes that
// they're not bad
sites.forEach(function(s) {
if (!s || 'string' !== typeof s.subject) {
throw new Error('missing subject');
}
if (
!Array.isArray(s.altnames) ||
!s.altnames.length ||
!s.altnames[0] ||
s.altnames[0] !== s.subject
) {
throw new Error('missing or malformed altnames');
}
['renewAt', 'issuedAt', 'expiresAt'].forEach(function(k) {
if (s[k]) {
throw new Error(
'`' +
k +
'` should be updated by `set()`, not by `find()`'
);
}
});
});
});
};
}
function mergeDefaults(MCONF, gconf) {
if (
gconf.agreeToTerms === true ||
MCONF.agreeToTerms === true ||
// TODO deprecate
gconf.agreeTos === true ||
MCONF.agreeTos === true
) {
MCONF.agreeToTerms = true;
}
if (!MCONF.subscriberEmail && gconf.subscriberEmail) {
MCONF.subscriberEmail = gconf.subscriberEmail;
}
var homedir;
// Load the default store module
if (!MCONF.store) {
if (gconf.store) {
MCONF.store = gconf.store;
} else {
homedir = require('os').homedir();
MCONF.store = {
module: 'greenlock-store-fs',
basePath: homedir + '/.config/greenlock/'
};
}
}
// just to test that it loads
P._loadSync(MCONF.store.module);
// Load the default challenge modules
var challenges = MCONF.challenges || gconf.challenges;
if (!challenges) {
challenges = {};
}
if (!challenges['http-01'] && !challenges['dns-01']) {
challenges['http-01'] = { module: 'acme-http-01-standalone' };
}
if (challenges['http-01']) {
if ('string' !== typeof challenges['http-01'].module) {
throw new Error(
'bad challenge http-01 module config:' +
JSON.stringify(challenges['http-01'])
);
}
P._loadSync(challenges['http-01'].module);
}
if (challenges['dns-01']) {
if ('string' !== typeof challenges['dns-01'].module) {
throw new Error(
'bad challenge dns-01 module config' +
JSON.stringify(challenges['dns-01'])
);
}
P._loadSync(challenges['dns-01'].module);
}
MCONF.challenges = challenges;
if (!MCONF.renewOffset) {
MCONF.renewOffset = gconf.renewOffset || '-45d';
}
if (!MCONF.renewStagger) {
MCONF.renewStagger = gconf.renewStagger || '3d';
}
if (!MCONF.accountKeyType) {
MCONF.accountKeyType = gconf.accountKeyType || 'EC-P256';
}
if (!MCONF.serverKeyType) {
MCONF.serverKeyType = gconf.serverKeyType || 'RSA-2048';
}
}
function _notify(ev, args) {
if (!args) {
args = ev;
ev = args.event;
delete args.event;
}
// TODO define message types
if (!_notify._notice) {
console.info(
'set greenlockOptions.notify to override the default logger'
);
_notify._notice = true;
}
var prefix = 'Warning';
switch (ev) {
case 'error':
prefix = 'Error';
/* falls through */
case 'warning':
console.error(
prefix + '%s:',
(' ' + (args.context || '')).trimRight()
);
console.error(args.message);
if (args.description) {
console.error(args.description);
}
if (args.code) {
console.error('code:', args.code);
}
if (args.stack) {
console.error(args.stack);
}
break;
default:
if (/status/.test(ev)) {
console.info(
ev,
args.altname || args.subject || '',
args.status || ''
);
if (!args.status) {
console.info(args);
}
break;
}
console.info(
ev,
'(more info available: ' + Object.keys(args).join(' ') + ')'
);
}
}
module.exports = require('@root/greenlock');

BIN
logo/beaker-browser-301x112.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

BIN
logo/from-not-secure-to-secure-url-bar.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

BIN
logo/greenlock-1063x250.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

BIN
logo/greenlock-850x200.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

BIN
logo/ibm-301x112.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

BIN
logo/telebit-301x112.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

258
manager-underlay.js

@ -1,258 +0,0 @@
'use strict';
var U = require('./utils.js');
var E = require('./errors.js');
var warned = {};
module.exports.wrap = function(greenlock, manager) {
greenlock.manager = {};
greenlock.sites = {};
//greenlock.accounts = {};
//greenlock.certs = {};
var allowed = [
'accountKeyType', //: ["P-256", "RSA-2048"],
'serverKeyType', //: ["RSA-2048", "P-256"],
'store', // : { module, specific opts },
'challenges', // : { "http-01", "dns-01", "tls-alpn-01" },
'subscriberEmail',
'agreeToTerms',
'agreeTos',
'customerEmail',
'renewOffset',
'renewStagger',
'module', // not allowed, just ignored
'manager'
];
// get / set default site settings such as
// subscriberEmail, store, challenges, renewOffset, renewStagger
greenlock.manager.defaults = function(conf) {
return greenlock._init().then(function() {
if (!conf) {
return manager.defaults();
}
if (conf.sites) {
throw new Error('cannot set sites as global config');
}
if (conf.routes) {
throw new Error('cannot set routes as global config');
}
// disallow keys we know to be bad
[
'subject',
'deletedAt',
'altnames',
'lastAttemptAt',
'expiresAt',
'issuedAt',
'renewAt',
'sites',
'routes'
].some(function(k) {
if (k in conf) {
throw new Error(
'`' + k + '` not allowed as a default setting'
);
}
});
Object.keys(conf).forEach(function(k) {
if (!allowed.includes(k) && !warned[k]) {
warned[k] = true;
console.warn(
k +
" isn't a known key. Please open an issue and let us know the use case."
);
}
});
Object.keys(conf).forEach(function(k) {
if (-1 !== ['module', 'manager'].indexOf(k)) {
return;
}
if ('undefined' === typeof k) {
throw new Error(
"'" +
k +
"' should be set to a value, or `null`, but not left `undefined`"
);
}
});
return manager.defaults(conf);
});
};
greenlock.add = greenlock.manager.add = function(args) {
if (!args || !Array.isArray(args.altnames) || !args.altnames.length) {
throw new Error(
'you must specify `altnames` when adding a new site'
);
}
if (args.renewAt) {
throw new Error(
'you cannot specify `renewAt` when adding a new site'
);
}
return greenlock.manager.set(args);
};
// TODO agreeToTerms should be handled somewhere... maybe?
// Add and update remains because I said I had locked the API
greenlock.manager.set = greenlock.manager.update = function(args) {
return greenlock._init().then(function() {
// The goal is to make this decently easy to manage by hand without mistakes
// but also reasonably easy to error check and correct
// and to make deterministic auto-corrections
args.subject = checkSubject(args);
//var subscriberEmail = args.subscriberEmail;
// TODO shortcut the other array checks when not necessary
if (Array.isArray(args.altnames)) {
args.altnames = checkAltnames(args.subject, args);
}
// at this point we know that subject is the first of altnames
return Promise.all(
(args.altnames || []).map(function(d) {
d = d.replace('*.', '');
return U._validDomain(d);
})
).then(function() {
if (!U._uniqueNames(args.altnames || [])) {
throw E.NOT_UNIQUE(
'add',
"'" + args.altnames.join("' '") + "'"
);
}
// durations
if (args.renewOffset) {
args.renewOffset = U._parseDuration(args.renewOffset);
}
if (args.renewStagger) {
args.renewStagger = U._parseDuration(args.renewStagger);
}
return manager.set(args).then(function(result) {
greenlock.renew({}).catch(function(err) {
if (!err.context) {
err.contxt = 'renew';
}
greenlock._notify('error', err);
});
return result;
});
});
});
};
greenlock.manager.remove = function(args) {
args.subject = checkSubject(args);
// TODO check no altnames
return manager.remove(args);
};
/*
{
subject: site.subject,
altnames: site.altnames,
//issuedAt: site.issuedAt,
//expiresAt: site.expiresAt,
renewOffset: site.renewOffset,
renewStagger: site.renewStagger,
renewAt: site.renewAt,
subscriberEmail: site.subscriberEmail,
customerEmail: site.customerEmail,
challenges: site.challenges,
store: site.store
};
*/
greenlock._find = function(args) {
var altnames = args.altnames || [];
// servername, wildname, and altnames are all the same
['wildname', 'servername'].forEach(function(k) {
var altname = args[k] || '';
if (altname && !altnames.includes(altname)) {
altnames.push(altname);
}
});
if (altnames.length) {
args.altnames = altnames;
args.altnames = args.altnames.map(U._encodeName);
args.altnames = checkAltnames(false, args);
}
return manager.find(args);
};
};
function checkSubject(args) {
if (!args || !args.subject) {
throw new Error('you must specify `subject` when configuring a site');
}
/*
if (!args.subject) {
throw E.NO_SUBJECT('add');
}
*/
var subject = (args.subject || '').toLowerCase();
if (subject !== args.subject) {
console.warn('`subject` must be lowercase', args.subject);
}
return U._encodeName(subject);
}
function checkAltnames(subject, args) {
// the things we have to check and get right
var altnames = (args.altnames || []).map(function(name) {
return String(name || '').toLowerCase();
});
if (subject && subject !== altnames[0]) {
throw new Error(
'`subject` must be the first domain in `altnames`',
args.subject,
altnames.join(' ')
);
}
/*
if (args.subject !== args.altnames[0]) {
throw E.BAD_ORDER(
'add',
'(' + args.subject + ") '" + args.altnames.join("' '") + "'"
);
}
*/
// punycode BEFORE validation
// (set, find, remove)
args.altnames = args.altnames.map(U._encodeName);
if (
!args.altnames.every(function(d) {
return U._validName(d);
})
) {
throw E.INVALID_HOSTNAME('add', "'" + args.altnames.join("' '") + "'");
}
if (altnames.join() !== args.altnames.join()) {
console.warn('all domains in `altnames` must be lowercase', altnames);
}
return altnames;
}

95
order.js

@ -1,95 +0,0 @@
var accountKeypair = await Keypairs.generate({ kty: accKty });
if (config.debug) {
console.info('Account Key Created');
console.info(JSON.stringify(accountKeypair, null, 2));
console.info();
console.info();
}
var account = await acme.accounts.create({
agreeToTerms: agree,
// TODO detect jwk/pem/der?
accountKeypair: { privateKeyJwk: accountKeypair.private },
subscriberEmail: config.email
});
// TODO top-level agree
function agree(tos) {
if (config.debug) {
console.info('Agreeing to Terms of Service:');
console.info(tos);
console.info();
console.info();
}
agreed = true;
return Promise.resolve(tos);
}
if (config.debug) {
console.info('New Subscriber Account');
console.info(JSON.stringify(account, null, 2));
console.info();
console.info();
}
if (!agreed) {
throw new Error('Failed to ask the user to agree to terms');
}
var certKeypair = await Keypairs.generate({ kty: srvKty });
var pem = await Keypairs.export({
jwk: certKeypair.private,
encoding: 'pem'
});
if (config.debug) {
console.info('Server Key Created');
console.info('privkey.jwk.json');
console.info(JSON.stringify(certKeypair, null, 2));
// This should be saved as `privkey.pem`
console.info();
console.info('privkey.' + srvKty.toLowerCase() + '.pem:');
console.info(pem);
console.info();
}
// 'subject' should be first in list
var domains = randomDomains(rnd);
if (config.debug) {
console.info('Get certificates for random domains:');
console.info(
domains
.map(function(puny) {
var uni = punycode.toUnicode(puny);
if (puny !== uni) {
return puny + ' (' + uni + ')';
}
return puny;
})
.join('\n')
);
console.info();
}
// Create CSR
var csrDer = await CSR.csr({
jwk: certKeypair.private,
domains: domains,
encoding: 'der'
});
var csr = Enc.bufToUrlBase64(csrDer);
var csrPem = PEM.packBlock({
type: 'CERTIFICATE REQUEST',
bytes: csrDer /* { jwk: jwk, domains: opts.domains } */
});
if (config.debug) {
console.info('Certificate Signing Request');
console.info(csrPem);
console.info();
}
var results = await acme.certificates.create({
account: account,
accountKeypair: { privateKeyJwk: accountKeypair.private },
csr: csr,
domains: domains,
challenges: challenges, // must be implemented
customerEmail: null
});

61
package-lock.json

@ -1,9 +1,28 @@
{
"name": "@root/greenlock",
"version": "3.0.18",
"name": "greenlock",
"version": "3.1.0-wip",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@greenlock/manager": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@greenlock/manager/-/manager-3.0.0.tgz",
"integrity": "sha512-ijgJrFdzJPmzrDk8aKXYoYR8LNfG3hXd9/s54ZY7IgxTulyPQ/qOPgl7sWgCxxLhZBzSY1xI6eC/6Y5TQ01agg==",
"requires": {
"greenlock-manager-fs": "^3.0.5"
},
"dependencies": {
"greenlock-manager-fs": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/greenlock-manager-fs/-/greenlock-manager-fs-3.0.5.tgz",
"integrity": "sha512-r/q+tEFuDwklfzPfiGhcIrHuJxMrppC+EseESpu5f0DMokh+1iZVm9nGC/VE7/7GETdOYfEYhhQkmspsi8Gr/A==",
"requires": {
"@root/mkdirp": "^1.0.0",
"safe-replace": "^1.1.0"
}
}
}
},
"@root/acme": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/@root/acme/-/acme-3.0.8.tgz",
@ -39,6 +58,35 @@
"resolved": "https://registry.npmjs.org/@root/encoding/-/encoding-1.0.1.tgz",
"integrity": "sha512-OaEub02ufoU038gy6bsNHQOjIn8nUjGiLcaRmJ40IUykneJkIW5fxDqKxQx48cszuNflYldsJLPPXCrGfHs8yQ=="
},
"@root/greenlock": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@root/greenlock/-/greenlock-3.1.5.tgz",
"integrity": "sha512-qJ7OdHj6yQz8zdJCqurPtrUGF3j/L+Tz4cWFYRGN6+owCaAWhjc2rhafC6y/6asisBJWoZyGDypbaSfKh5097w==",
"requires": {
"@greenlock/manager": "^3.0.0",
"@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.5",
"greenlock-store-fs": "^3.2.0",
"safe-replace": "^1.1.0"
},
"dependencies": {
"greenlock-manager-fs": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/greenlock-manager-fs/-/greenlock-manager-fs-3.0.5.tgz",
"integrity": "sha512-r/q+tEFuDwklfzPfiGhcIrHuJxMrppC+EseESpu5f0DMokh+1iZVm9nGC/VE7/7GETdOYfEYhhQkmspsi8Gr/A==",
"requires": {
"@root/mkdirp": "^1.0.0",
"safe-replace": "^1.1.0"
}
}
}
},
"@root/keypairs": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@root/keypairs/-/keypairs-0.9.0.tgz",
@ -89,15 +137,6 @@
"integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw==",
"dev": true
},
"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",

7
package.json

@ -1,10 +1,12 @@
{
"name": "greenlock",
"version": "3.0.21",
"version": "3.1.0-wip",
"description": "The easiest Let's Encrypt client for Node.js and Browsers",
"homepage": "https://rootprojects.org/greenlock/",
"main": "greenlock.js",
"browser": {},
"bin": {
},
"files": [
"*.js",
"lib",
@ -37,12 +39,13 @@
"dependencies": {
"@root/acme": "^3.0.8",
"@root/csr": "^0.8.1",
"@root/greenlock": "^3.1.5",
"@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-manager-fs": "^3.0.3",
"greenlock-store-fs": "^3.2.0",
"safe-replace": "^1.1.0"
},

331
plugins.js

@ -1,331 +0,0 @@
'use strict';
var P = module.exports;
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var promisify = require('util').promisify;
// Exported for CLIs and such to override
P.PKG_DIR = __dirname;
P._loadStore = function(storeConf) {
return P._loadHelper(storeConf.module).then(function(plugin) {
return P._normalizeStore(storeConf.module, plugin.create(storeConf));
});
};
P._loadChallenge = function(chConfs, typ01) {
return P._loadHelper(chConfs[typ01].module).then(function(plugin) {
var ch = P._normalizeChallenge(
chConfs[typ01].module,
plugin.create(chConfs[typ01])
);
ch._type = typ01;
return ch;
});
};
P._loadHelper = function(modname) {
try {
return Promise.resolve(require(modname));
} catch (e) {
console.error("Could not load '%s'", modname);
console.error('Did you install it?');
console.error('\tnpm install --save %s', modname);
throw e;
// Fun experiment, bad idea
/*
return P._install(modname).then(function() {
return require(modname);
});
*/
}
};
P._normalizeStore = function(name, store) {
var acc = store.accounts;
var crt = store.certificates;
var warned = false;
function warn() {
if (warned) {
return;
}
warned = true;
console.warn(
"'" +
name +
"' may have incorrect function signatures, or contains deprecated use of callbacks"
);
}
// accs
if (acc.check && 2 === acc.check.length) {
warn();
acc._thunk_check = acc.check;
acc.check = promisify(acc._thunk_check);
}
if (acc.set && 3 === acc.set.length) {
warn();
acc._thunk_set = acc.set;
acc.set = promisify(acc._thunk_set);
}
if (2 === acc.checkKeypair.length) {
warn();
acc._thunk_checkKeypair = acc.checkKeypair;
acc.checkKeypair = promisify(acc._thunk_checkKeypair);
}
if (3 === acc.setKeypair.length) {
warn();
acc._thunk_setKeypair = acc.setKeypair;
acc.setKeypair = promisify(acc._thunk_setKeypair);
}
// certs
if (2 === crt.check.length) {
warn();
crt._thunk_check = crt.check;
crt.check = promisify(crt._thunk_check);
}
if (3 === crt.set.length) {
warn();
crt._thunk_set = crt.set;
crt.set = promisify(crt._thunk_set);
}
if (2 === crt.checkKeypair.length) {
warn();
crt._thunk_checkKeypair = crt.checkKeypair;
crt.checkKeypair = promisify(crt._thunk_checkKeypair);
}
if (2 === crt.setKeypair.length) {
warn();
crt._thunk_setKeypair = crt.setKeypair;
crt.setKeypair = promisify(crt._thunk_setKeypair);
}
return store;
};
P._normalizeChallenge = function(name, ch) {
var gch = {};
var warned = false;
function warn() {
if (warned) {
return;
}
warned = true;
console.warn(
"'" +
name +
"' may have incorrect function signatures, or contains deprecated use of callbacks"
);
}
var warned2 = false;
function warn2() {
if (warned2) {
return;
}
warned2 = true;
console.warn(
"'" +
name +
"' did not return a Promise when called. This should be fixed by the maintainer."
);
}
function wrappy(fn) {
return function(_params) {
return Promise.resolve().then(function() {
var result = fn.call(ch, _params);
if (!result || !result.then) {
warn2();
}
return result;
});
};
}
// init, zones, set, get, remove
if (ch.init) {
if (2 === ch.init.length) {
warn();
ch._thunk_init = ch.init;
ch.init = promisify(ch._thunk_init);
}
gch.init = wrappy(ch.init);
}
if (ch.zones) {
if (2 === ch.zones.length) {
warn();
ch._thunk_zones = ch.zones;
ch.zones = promisify(ch._thunk_zones);
}
gch.zones = wrappy(ch.zones);
}
if (2 === ch.set.length) {
warn();
ch._thunk_set = ch.set;
ch.set = promisify(ch._thunk_set);
}
gch.set = wrappy(ch.set);
if (2 === ch.remove.length) {
warn();
ch._thunk_remove = ch.remove;
ch.remove = promisify(ch._thunk_remove);
}
gch.remove = wrappy(ch.remove);
if (ch.get) {
if (2 === ch.get.length) {
warn();
ch._thunk_get = ch.get;
ch.get = promisify(ch._thunk_get);
}
gch.get = wrappy(ch.get);
}
return gch;
};
P._loadSync = function(modname) {
try {
return require(modname);
} catch (e) {
console.error("Could not load '%s'", modname);
console.error('Did you install it?');
console.error('\tnpm install --save %s', modname);
throw e;
}
/*
try {
mod = require(modname);
} catch (e) {
P._installSync(modname);
mod = require(modname);
}
*/
};
P._installSync = function(moduleName) {
var npm = 'npm';
var args = ['install', '--save', moduleName];
var out = '';
var cmd;
try {
cmd = spawnSync(npm, args, {
cwd: P.PKG_DIR,
windowsHide: true
});
} catch (e) {
console.error(
"Failed to start: '" +
npm +
' ' +
args.join(' ') +
"' in '" +
P.PKG_DIR +
"'"
);
console.error(e.message);
process.exit(1);
}
if (!cmd.status) {
return;
}
out += cmd.stdout.toString('utf8');
out += cmd.stderr.toString('utf8');
if (out) {
console.error(out);
console.error();
console.error();
}
console.error(
"Failed to run: '" +
npm +
' ' +
args.join(' ') +
"' in '" +
P.PKG_DIR +
"'"
);
console.error(
'Try for yourself:\n\tcd ' + P.PKG_DIR + '\n\tnpm ' + args.join(' ')
);
process.exit(1);
};
P._install = function(moduleName) {
return new Promise(function(resolve) {
if (!moduleName) {
throw new Error('no module name given');
}
var npm = 'npm';
var args = ['install', '--save', moduleName];
var out = '';
var cmd = spawn(npm, args, {
cwd: P.PKG_DIR,
windowsHide: true
});
cmd.stdout.on('data', function(chunk) {
out += chunk.toString('utf8');
});
cmd.stdout.on('data', function(chunk) {
out += chunk.toString('utf8');
});
cmd.on('error', function(e) {
console.error(
"Failed to start: '" +
npm +
' ' +
args.join(' ') +
"' in '" +
P.PKG_DIR +
"'"
);
console.error(e.message);
process.exit(1);
});
cmd.on('exit', function(code) {
if (!code) {
resolve();
return;
}
if (out) {
console.error(out);
console.error();
console.error();
}
console.error(
"Failed to run: '" +
npm +
' ' +
args.join(' ') +
"' in '" +
P.PKG_DIR +
"'"
);
console.error(
'Try for yourself:\n\tcd ' +
P.PKG_DIR +
'\n\tnpm ' +
args.join(' ')
);
process.exit(1);
});
});
};
if (require.main === module) {
P._installSync(process.argv[2]);
}

20
publish.sh

@ -0,0 +1,20 @@
#!/bin/bash
set -e
set -u
git fetch --all
git checkout master
git pull origin master
git checkout npm
git checkout master -- package.json
git checkout master -- README.md
sed -i '' -e 's|"name": ".root.greenlock"|"name": "greenlock"|' package.json
sed -i '' -e 's|.root.greenlock|greenlock|' README.md
sed -i '' '/bin.greenlock.js/d' package.json
npm install --save @root/greenlock@latest
git add package* README.md || true
git commit -m "bump" || true
npm publish ./
git reset --hard

54
tests/index.js

@ -1,54 +0,0 @@
'use strict';
require('dotenv').config();
var Greenlock = require('../');
var subject = process.env.BASE_DOMAIN;
var altnames = [subject, '*.' + subject, 'foo.bar.' + subject];
var email = process.env.SUBSCRIBER_EMAIL;
var challenge = JSON.parse(process.env.CHALLENGE_OPTIONS);
challenge.module = process.env.CHALLENGE_PLUGIN;
var greenlock = Greenlock.create({
packageAgent: 'Greenlock_Test/v0',
maintainerEmail: email,
staging: true,
manager: require('greenlock-manager-fs').create({
//configFile: '~/.config/greenlock/certs.json',
})
});
greenlock.manager
.defaults({
agreeToTerms: true,
subscriberEmail: email,
challenges: {
'dns-01': challenge
}
//store: args.storeOpts,
//renewOffset: args.renewOffset || '30d',
//renewStagger: '1d'
})
.then(function() {
return greenlock
.add({
subject: subject,
altnames: altnames,
subscriberEmail: email
})
.then(function() {
return greenlock
.get({ servername: subject })
.then(function(pems) {
if (pems && pems.privkey && pems.cert && pems.chain) {
console.info('Success');
}
//console.log(pems);
});
});
})
.catch(function(e) {
console.error('Big bad error:', e.code);
console.error(e);
});

7
user-events.js

@ -1,7 +0,0 @@
'use strict';
var UserEvents = module.exports;
UserEvents.notify = function() {
// TODO not implemented yet
};

281
utils.js

@ -1,281 +0,0 @@
'use strict';
var U = module.exports;
var promisify = require('util').promisify;
//var resolveSoa = promisify(require('dns').resolveSoa);
var resolveMx = promisify(require('dns').resolveMx);
var punycode = require('punycode');
var Keypairs = require('@root/keypairs');
// TODO move to @root
var certParser = require('cert-info');
U._parseDuration = function(str) {
if ('number' === typeof str) {
return str;
}
var pattern = /^(\-?\d+(\.\d+)?)([wdhms]|ms)$/;
var matches = str.match(pattern);
if (!matches || !matches[0]) {
throw new Error('invalid duration string: ' + str);
}
var n = parseInt(matches[1], 10);
var unit = matches[3];
switch (unit) {
case 'w':
n *= 7;
/*falls through*/
case 'd':
n *= 24;
/*falls through*/
case 'h':
n *= 60;
/*falls through*/
case 'm':
n *= 60;
/*falls through*/
case 's':
n *= 1000;
/*falls through*/
case 'ms':
n *= 1; // for completeness
}
return n;
};
U._encodeName = function(str) {
return punycode.toASCII(str.toLowerCase(str));
};
U._validName = function(str) {
// A quick check of the 38 and two ½ valid characters
// 253 char max full domain, including dots
// 63 char max each label segment
// Note: * is not allowed, but it's allowable here
// Note: _ (underscore) is only allowed for "domain names", not "hostnames"
// Note: - (hyphen) is not allowed as a first character (but a number is)
return (
/^(\*\.)?[a-z0-9_\.\-]+$/.test(str) &&
str.length < 254 &&
str.split('.').every(function(label) {
return label.length > 0 && label.length < 64;
})
);
};
U._validMx = function(email) {
var host = email.split('@').slice(1)[0];
// try twice, just because DNS hiccups sometimes
// Note: we don't care if the domain exists, just that it *can* exist
return resolveMx(host).catch(function() {
return U._timeout(1000).then(function() {
return resolveMx(host);
});
});
};
// should be called after _validName
U._validDomain = function(str) {
// TODO use @root/dns (currently dns-suite)
// because node's dns can't read Authority records
return Promise.resolve(str);
/*
// try twice, just because DNS hiccups sometimes
// Note: we don't care if the domain exists, just that it *can* exist
return resolveSoa(str).catch(function() {
return U._timeout(1000).then(function() {
return resolveSoa(str);
});
});
*/
};
// foo.example.com and *.example.com overlap
// should be called after _validName
// (which enforces *. or no *)
U._uniqueNames = function(altnames) {
var dups = {};
var wilds = {};
if (
altnames.some(function(w) {
if ('*.' !== w.slice(0, 2)) {
return;
}
if (wilds[w]) {
return true;
}
wilds[w] = true;
})
) {
return false;
}
return altnames.every(function(name) {
var w;
if ('*.' !== name.slice(0, 2)) {
w =
'*.' +
name
.split('.')
.slice(1)
.join('.');
} else {
return true;
}
if (!dups[name] && !dups[w]) {
dups[name] = true;
return true;
}
});
};
U._timeout = function(d) {
return new Promise(function(resolve) {
setTimeout(resolve, d);
});
};
U._genKeypair = function(keyType) {
var keyopts;
var len = parseInt(keyType.replace(/.*?(\d)/, '$1') || 0, 10);
if (/RSA/.test(keyType)) {
keyopts = {
kty: 'RSA',
modulusLength: len || 2048
};
} else if (/^(EC|P\-?\d)/i.test(keyType)) {
keyopts = {
kty: 'EC',
namedCurve: 'P-' + (len || 256)
};
} else {
// TODO put in ./errors.js
throw new Error('invalid key type: ' + keyType);
}
return Keypairs.generate(keyopts).then(function(pair) {
return U._jwkToSet(pair.private);
});
};
// TODO use ACME._importKeypair ??
U._importKeypair = function(keypair) {
// this should import all formats equally well:
// 'object' (JWK), 'string' (private key pem), kp.privateKeyPem, kp.privateKeyJwk
if (keypair.private || keypair.d) {
return U._jwkToSet(keypair.private || keypair);
}
if (keypair.privateKeyJwk) {
return U._jwkToSet(keypair.privateKeyJwk);
}
if ('string' !== typeof keypair && !keypair.privateKeyPem) {
// TODO put in errors
throw new Error('missing private key');
}
return Keypairs.import({ pem: keypair.privateKeyPem || keypair }).then(
function(priv) {
if (!priv.d) {
throw new Error('missing private key');
}
return U._jwkToSet(priv);
}
);
};
U._jwkToSet = function(jwk) {
var keypair = {
privateKeyJwk: jwk
};
return Promise.all([
Keypairs.export({
jwk: jwk,
encoding: 'pem'
}).then(function(pem) {
keypair.privateKeyPem = pem;
}),
Keypairs.export({
jwk: jwk,
encoding: 'pem',
public: true
}).then(function(pem) {
keypair.publicKeyPem = pem;
}),
Keypairs.publish({
jwk: jwk
}).then(function(pub) {
keypair.publicKeyJwk = pub;
})
]).then(function() {
return keypair;
});
};
U._attachCertInfo = function(results) {
var certInfo = certParser.info(results.cert);
// subject, altnames, issuedAt, expiresAt
Object.keys(certInfo).forEach(function(key) {
results[key] = certInfo[key];
});
return results;
};
U._certHasDomain = function(certInfo, _domain) {
var names = (certInfo.altnames || []).slice(0);
return names.some(function(name) {
var domain = _domain.toLowerCase();
name = name.toLowerCase();
if ('*.' === name.substr(0, 2)) {
name = name.substr(2);
domain = domain
.split('.')
.slice(1)
.join('.');
}
return name === domain;
});
};
// a bit heavy to be labeled 'utils'... perhaps 'common' would be better?
U._getOrCreateKeypair = function(db, subject, query, keyType, mustExist) {
var exists = false;
return db
.checkKeypair(query)
.then(function(kp) {
if (kp) {
exists = true;
return U._importKeypair(kp);
}
if (mustExist) {
// TODO put in errors
throw new Error(
'required keypair not found: ' +
(subject || '') +
' ' +
JSON.stringify(query)
);
}
return U._genKeypair(keyType);
})
.then(function(keypair) {
return { exists: exists, keypair: keypair };
});
};
U._getKeypair = function(db, subject, query) {
return U._getOrCreateKeypair(db, subject, query, '', true).then(function(
result
) {
return result.keypair;
});
};
Loading…
Cancel
Save