Compare commits

...

117 Commits

Author SHA1 Message Date
AJ ONeal 480352835a 4.0.4 2020-08-03 23:18:26 -06:00
AJ ONeal ce14a410d7 update deps for #38 2020-08-03 23:18:21 -06:00
AJ ONeal ca0ba9bc68 Add missing tlsOptions to http2 example 2020-08-03 06:37:24 +00:00
AJ ONeal 2ac272ba9d update TL;DR 2020-07-29 02:39:47 +00:00
AJ ONeal 374c360967 add TL;DR 2020-07-29 02:38:55 +00:00
AJ ONeal 4b24cc48e9 clarify staging certificates 2020-07-29 02:33:36 +00:00
AJ ONeal a025022fb2 add more paragraph text to QuickStart 2020-07-29 02:31:25 +00:00
AJ ONeal f2abc44601 update node installer instructions 2020-07-28 22:39:34 +00:00
AJ ONeal 477e7a07ec move FAQ 2020-04-30 18:24:29 +00:00
AJ ONeal 657ebe0756 update FAQ 2020-04-30 18:22:50 +00:00
AJ ONeal aaed863ef8 update FAQ 2020-04-30 18:19:33 +00:00
AJ ONeal 67d6a60a37 add FAQ 2020-04-30 18:17:06 +00:00
AJ ONeal 894e603a64 fix broken link 2020-04-29 16:04:34 +00:00
AJ ONeal adf0c97301 fix altnames example 2020-04-29 15:29:45 +00:00
AJ ONeal e8f2c39f79 update altnames example 2020-04-29 15:29:14 +00:00
AJ ONeal f81d2614f4 fix typo 2020-04-26 23:13:02 +00:00
AJ ONeal f18eae4073 update docs 2020-01-16 17:16:30 -07:00
AJ ONeal 83d4a9204e v4.0.3: update deps for bugfixes, better logging 2020-01-13 18:47:01 -07:00
AJ ONeal e5456249a2 update docs 2020-01-11 17:02:13 -07:00
AJ ONeal 1df2bc0ad4 update docs 2020-01-11 13:36:13 -07:00
AJ ONeal cf93c77bd5 v4.0.2: update deps 2020-01-11 13:21:31 -07:00
AJ ONeal c9363bd1a3 update docs 2020-01-11 13:16:48 -07:00
AJ ONeal 99f6ab0c1e update docs 2020-01-11 13:15:39 -07:00
AJ ONeal a9feafeab3 update docs 2020-01-10 18:03:59 -07:00
AJ ONeal bae832d65a update docs 2020-01-10 18:00:08 -07:00
AJ ONeal e6a008d498 update docs 2020-01-10 17:51:25 -07:00
AJ ONeal 2d5125821e v4.0.1: launch v4 2020-01-09 04:29:18 -07:00
AJ ONeal 8e29cafdf5 updates for v4 2020-01-05 17:32:20 -07:00
AJ ONeal 224f258daa bugfixes 2019-11-19 01:19:27 -07:00
AJ ONeal 375524873d wip: require correct init file 2019-11-18 22:56:28 -07:00
AJ ONeal 28aad4f29d wip: simpler config and defaults 2019-11-18 00:53:26 -07:00
AJ ONeal 48b892c323 wip: move to configDir 2019-11-16 16:50:12 -07:00
AJ ONeal 01ff1d7da5 wip: refining API 2019-11-12 01:46:47 -07:00
AJ ONeal 347402a4d4 force cluster false for pre-worker systems (issue #80) 2019-11-06 18:17:37 -07:00
AJ ONeal bd5ee84e25 allow without callbacks, issue #9 2019-11-05 11:50:38 -07:00
AJ ONeal 4e9a6c0719 readme typo fix 2019-11-05 04:20:21 -07:00
AJ ONeal 548faed139 v3.1.1: update docs 2019-11-05 04:17:51 -07:00
AJ ONeal 5a7db51a36 update docs 2019-11-05 04:17:31 -07:00
AJ ONeal 654a64d7f4 update docs 2019-11-05 04:15:11 -07:00
AJ ONeal ec14a224f9 v3.1.0: updates and docs for CLI 2019-11-05 04:01:58 -07:00
AJ ONeal 47140f6296 update docs 2019-11-05 03:30:53 -07:00
AJ ONeal 6296c8a737 update docs 2019-11-05 03:30:07 -07:00
AJ ONeal e1d5e9a692 update docs 2019-11-05 03:09:42 -07:00
AJ ONeal 6bbb5f78e9 remove cruft 2019-11-04 15:03:24 -07:00
AJ ONeal a360abda01 serve -> ready 2019-11-03 01:28:37 -07:00
AJ ONeal 5068097090 possible fix for notify bug 2019-11-02 21:01:29 -06:00
AJ ONeal 3994c7fd5c output invalid and unknown sni 2019-11-02 20:54:09 -06:00
AJ ONeal 4482e97dcb add debug for headers issue (issue #9 on root git) 2019-11-02 20:39:59 -06:00
AJ ONeal 37c3aee99f use https-redirect as default app for httpServer 2019-11-01 22:55:39 -06:00
AJ ONeal 1eba51ea22 update deps 2019-11-01 17:18:26 -06:00
AJ ONeal 61fb942dda whitespace 2019-11-01 15:14:07 -06:00
AJ ONeal b80537f07b v3.0.12: from http2 back to old https.. :-/ 2019-11-01 15:13:04 -06:00
AJ ONeal 627ad8272e v3.0.11: bump 2019-11-01 14:32:27 -06:00
AJ ONeal ce5e31bbf7 moved getAcmeHttp01ChallengeResponse to greenlock proper 2019-11-01 13:45:52 -06:00
ryanburnette d11b45c409 fix typo 2019-11-01 12:57:32 +00:00
AJ ONeal 36abf769be v3.0.10: doc updates 2019-11-01 04:30:45 -06:00
AJ ONeal c93ecf307b update quickstart 2019-11-01 04:29:49 -06:00
AJ ONeal 3ea7d3e97b move quickstart, add challenge integrations 2019-11-01 04:26:40 -06:00
AJ ONeal fff5192fb4 on second thought, just the node app example 2019-11-01 04:19:32 -06:00
AJ ONeal fceeb8c72c v3.0.9: add examples 2019-11-01 04:12:47 -06:00
AJ ONeal a7526ffad8 v3.0.8: update deps, add example 2019-10-31 06:46:35 -06:00
AJ ONeal d324179cb1 fix maintainerEmail and httpsServer() return 2019-10-31 05:52:30 -06:00
AJ ONeal 18b36d7d23 fix maintainer email 2019-10-30 13:14:26 -06:00
AJ ONeal 7a2de022fa v3.0.7: bugfixes and update deps 2019-10-30 02:38:31 -06:00
AJ ONeal e478d27628 v3.0.6: bugfixes and update deps 2019-10-30 02:35:47 -06:00
AJ ONeal 6f2c1ec5ba bugfix domain fronting check 2019-10-30 08:34:54 +00:00
AJ ONeal 894a01fa4e more attention on the simple example 2019-10-29 23:04:32 -06:00
AJ ONeal df1259cd9d v3.0.5: update deps 2019-10-29 13:57:55 -06:00
AJ ONeal 3f8a54a988 v3.0.4: update deps 2019-10-29 12:50:43 -06:00
AJ ONeal 26adaf2037 bugfix packageAgent 2019-10-29 11:21:36 -06:00
AJ ONeal 2a9b463964 v3.0.3: update deps for bugfixes 2019-10-29 04:27:13 -06:00
AJ ONeal bc4a5b44ae v3.0.6: update deps for bugfixes 2019-10-29 03:22:50 -06:00
AJ ONeal 378b9310aa change demo agent 2019-10-29 06:53:19 +00:00
AJ ONeal 405e98620c v3.0.1: http-01 and other bugfixes, update deps 2019-10-29 06:48:31 +00:00
AJ ONeal 3f437c6ebb whitespace 2019-10-28 03:52:38 -06:00
AJ ONeal 00e9d96f8b v3.0.0: first draft of docs 2019-10-28 03:43:53 -06:00
AJ ONeal 31ba1186be updates for cluster 2019-10-28 03:43:42 -06:00
AJ ONeal af7c75a0f7 small api rework and bugfixes 2019-10-28 01:06:43 -06:00
AJ ONeal 8d464d6810 chimney (burn some logs) 2019-10-27 04:41:05 -06:00
AJ ONeal de051dd3a2 staging, duh 2019-10-27 04:13:34 -06:00
AJ ONeal d14163d153 minor refac 2019-10-27 03:59:49 -06:00
AJ ONeal 6df0dc2f76 some sni bugfixes 2019-10-27 01:19:44 -06:00
AJ ONeal 0dd3641dc2 wip: API looks good, on to testing 2019-10-26 23:52:19 -06:00
AJ ONeal 9ab7844ea8 v2.7.18: Notify of upcoming Greenlock v3 2019-10-19 06:18:39 -06:00
AJ ONeal afac2b01a6 v2.7.17: bump deps 2019-09-07 02:35:59 -06:00
AJ ONeal 0dcefa77d8 v2.7.16: add EoL notice 2019-09-04 00:15:02 -06:00
AJ ONeal c9e62ccb05 2.7.15: update Greenlock version, remove banner 2019-08-24 12:59:23 -04:00
AJ ONeal 8732029eb1 v2.7.14: announce deadline 2019-08-17 21:59:00 -06:00
AJ ONeal f3bae8580b v2.7.13: add igg banner 2019-08-17 21:24:18 -06:00
AJ ONeal ada2b9ccfe example server: add proxy and wildcard support 2019-08-01 05:44:24 +00:00
AJ ONeal 4d400a9828 v2.7.12: doc updates 2019-07-31 00:19:27 -06:00
AJ ONeal 0f34e81d8a v2.7.11: doc updates 2019-07-11 23:01:39 -06:00
AJ ONeal f539de2611 example server: re-allow non-api prefixed apis 2019-07-07 07:11:25 +00:00
AJ ONeal 8f369226cf v2.7.10: improve error handling 2019-06-30 21:46:38 -06:00
AJ ONeal 44ff0ac5df better logging 2019-06-30 18:11:28 -06:00
AJ ONeal fbe7549604 better logging 2019-06-30 18:08:04 -06:00
AJ ONeal 6cdbe36e6c catch request errors 2019-06-30 18:07:13 -06:00
AJ ONeal 778416d49b made testable and tested server example 2019-06-26 22:49:44 -06:00
AJ ONeal c73ad565a3 make Prettier 2019-06-03 03:47:07 -06:00
AJ ONeal a49ccb7398 v2.7.9: version bump, readme typo fixes 2019-06-03 03:44:11 -06:00
AJ ONeal 8ba4b88e00 minor bugfixes for node v6 2019-06-03 09:34:52 +00:00
AJ ONeal 78fcebd567 v2.7.8 2019-05-15 22:39:35 -06:00
AJ ONeal 1843f03d87 doc updates 2019-05-15 22:19:58 -06:00
AJ ONeal 81a63b365d add latest s3 2019-05-10 04:23:09 +00:00
AJ ONeal c187bd0fb7 add socket.io example 2019-04-27 06:54:10 +00:00
AJ ONeal bcc1c16ec2 update links 2019-04-27 05:54:20 +00:00
AJ ONeal fec660bfeb update diy links 2019-04-26 20:53:37 +00:00
AJ ONeal 1b42d866fb add socket.io example 2019-04-22 19:50:52 -06:00
AJ ONeal 579709ae40 add safety checks, fix error 2019-04-19 21:25:46 -06:00
AJ ONeal c7dfec515d better security / education in example 2019-04-10 11:44:24 -06:00
AJ ONeal 0d2d571458 v2.7.6: update to latest greenlock for upcoming v3 compat 2019-04-08 02:06:29 -06:00
AJ ONeal b71311b1bc v2.7.5: update deps to fix log messages 2019-04-04 10:44:36 -06:00
AJ ONeal f6cc67ff53 v2.7.4: add a server I use 2019-04-04 00:35:15 -06:00
AJ ONeal feeafc5c97 v2.7.3: doc updates 2019-04-02 23:39:48 -06:00
AJ ONeal 3634965e70 update docs 2019-04-03 05:37:23 +00:00
AJ ONeal 74b3419507 v2.7.2: use correct deps 2019-04-02 23:27:43 -06:00
AJ ONeal a6f4de6c78 fix require path 2019-04-02 23:26:58 -06:00
56 changed files with 3152 additions and 2093 deletions

5
.gitignore vendored
View File

@ -1,3 +1,8 @@
app.js
server.js
greenlock.js
.greenlockrc
# Logs
logs
*.log

7
.prettierrc Normal file
View File

@ -0,0 +1,7 @@
{
"bracketSpacing": true,
"printWidth": 120,
"tabWidth": 4,
"trailingComma": "none",
"useTabs": false
}

396
LICENSE
View File

@ -1,41 +1,375 @@
Copyright 2017 AJ ONeal
Copyright 2015-2019 AJ ONeal
This is open source software; you can redistribute it and/or modify it under the
terms of either:
Mozilla Public License Version 2.0
==================================
a) the "MIT License"
b) the "Apache-2.0 License"
1. Definitions
--------------
MIT License
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1.3. "Contribution"
means Covered Software of a particular Contributor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
Apache-2.0 License Summary
1.5. "Incompatible With Secondary Licenses"
means
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
http://www.apache.org/licenses/LICENSE-2.0
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

841
README.md
View File

@ -1,443 +1,536 @@
![Greenlock Logo](https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/greenlock-1063x250.png "Greenlock Logo")
# [Greenlock Express v4](https://git.rootprojects.org/root/greenlock-express.js) is Let's Encrypt for Node
!["Greenlock Function"](https://git.coolaj86.com/coolaj86/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")
| Built by [Root](https://therootcompany.com) for [Hub](https://rootprojects.org/hub/) |
<table>
<tr>
<td><a href="https://medium.com/@bohou/secure-your-nodejs-server-with-letsencrypt-for-free-f8925742faa9" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/ibm-301x112.png"></a></td>
<td><a href="https://github.com/mozilla-iot/le-store-certbot/issues/4" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/mozilla-iot-301x112.png"></a></td>
<td><a href="https://github.com/digitalbazaar/bedrock-letsencrypt" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/digital-bazaar-301x112.png"></a></td>
</tr>
</table>
<table>
<tr>
<td><a href="https://github.com/beakerbrowser/homebase" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/beaker-browser-301x112.png"></a></td>
<td><a href="https://telebit.cloud" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/telebit-301x112.png"></a></td>
<td><a href="https://rootprojects.org" target="_blank"><img src="https://git.coolaj86.com/coolaj86/greenlock.js/raw/branch/master/logo/ppl-301x112.png"></a></td>
</tr>
</table>
![Greenlock Logo](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/greenlock-1063x250.png "Greenlock Logo")
# [Greenlock](https://git.coolaj86.com/coolaj86/greenlock-express.js)&trade; for Express.js
### Free SSL for Node Web Servers
<small>formerly letsencrypt-express</small>
Greenlock Express is a **Web Server** with **Fully Automated HTTPS** and renewals.
Free SSL, Free Wildcard SSL, and Fully Automated HTTPS made dead simple<br>
<small>certificates issued by Let's Encrypt v2 via [ACME](https://git.coolaj86.com/coolaj86/acme-v2.js)</small>
You define your app and let Greenlock handle issuing and renewing Free SSL Certificates.
!["Lifetime Downloads"](https://img.shields.io/npm/dt/greenlock.svg "Lifetime Download Count can't be shown")
!["Monthly Downloads"](https://img.shields.io/npm/dm/greenlock.svg "Monthly Download Count can't be shown")
!["Weekly Downloads"](https://img.shields.io/npm/dw/greenlock.svg "Weekly Download Count can't be shown")
!["Stackoverflow Questions"](https://img.shields.io/stackexchange/stackoverflow/t/greenlock.svg "S.O. Question count can't be shown")
<a href="https://twitter.com/intent/follow?screen_name=GreenlockHTTPS"><img src="https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow%20@GreenlockHTTPS" title="Follow @GreenlockHTTPS on Twitter" alt="Twitter Badge"></a>
```bash
npm init
npm install --save greenlock-express@v4
```
| A [Root](https://rootprojects.org) Project |
[Greenlock&trade;](https://git.coolaj86.com/coolaj86/greenlock.js) is for
[Web Servers](https://git.coolaj86.com/coolaj86/greenlock-cli.js),
[Web Browsers](https://greenlock.domains),
and **node.js middleware systems**.
`server.js`:
```js
"use strict";
var app = require("./app.js");
require("greenlock-express")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
// contact for security and critical bug notices
maintainerEmail: "jon@example.com",
// whether or not to run at cloudscale
cluster: false
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.serve(app);
```
`./greenlock.d/config.json`:
```json
{ "sites": [{ "subject": "example.com", "altnames": ["example.com"] }] }
```
# Let's Encrypt for...
- IoT
- Enterprise On-Prem
- Local Development
- Home Servers
- Quitting Heroku
# Features
- [x] Automatic HTTPS
- [x] Free SSL
- [x] Free Wildcard SSL
- [x] Multiple domain support (up to 100 altnames per SAN)
- [x] Dynamic Virtual Hosting (vhost)
- [x] Automatical renewal (10 to 14 days before expiration)
- [x] Great ACME support
- [x] ACME draft 11
- [x] Let's Encrypt v2
- [x] Let's Encrypt v1
- [x] Full node.js support
- [x] core https module
- [x] Express.js
- [x] [Koa](https://git.coolaj86.com/coolaj86/greenlock-koa.js)
- [x] [hapi](https://git.coolaj86.com/coolaj86/greenlock-hapi.js)
- [x] Extensible Plugin Support
- [x] AWS (S3, Route53)
- [x] Azure
- [x] CloudFlare
- [x] Consul
- [x] Digital Ocean
- [x] etcd
- [x] Redis
- [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
# Install
# 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 install --save greenlock-express@2.x
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
```
# QuickStart
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.
<!-- TODO better quickstart (fewer options) -->
## 1. Create your Project
### Screencast
If you need to install Node.js, do so:
Watch the QuickStart demonstration: [https://youtu.be/e8vaR4CEZ5s](https://youtu.be/e8vaR4CEZ5s&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk)
Mac, Linux:
<a href="https://www.youtube.com/watch?v=e8vaR4CEZ5s&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk"><img src="https://i.imgur.com/Y8ix6Ts.png" title="QuickStart Video" alt="YouTube Video Preview" /></a>
* [0:00](https://www.youtube.com/watch?v=e8vaR4CEZ5s&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk#t=0) - Intro
* [2:22](https://www.youtube.com/watch?v=e8vaR4CEZ5s&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk#t=142) - Demonstrating QuickStart Example
* [6:37](https://www.youtube.com/watch?v=e8vaR4CEZ5s&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk?t=397) - Troubleshooting / Gotchas
#### Beyond the QuickStart (Part 2)
* [1:00](https://www.youtube.com/watch?v=bTEn93gxY50&index=2&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk&t=60) - Bringing Greenlock into an Existing Express Project
* [2:26](https://www.youtube.com/watch?v=bTEn93gxY50&index=2&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk&t=146) - The `approveDomains` callback
#### Security Concerns (Part 3)
* [0:00](https://www.youtube.com/watch?v=aZgVqPzoZTY&index=3&list=PLZaEVINf2Bq_lrS-OOzTUJB4q3HxarlXk) - Potential Attacks, and Mitigation
### Working Example Code
Here's a completely working example that will get you started.
```
git clone https://git.coolaj86.com/coolaj86/greenlock-express.js.git
pushd greenlock-express.js
npm install
popd
# edit 'email' and 'approveDomains' in
# greenlock-express.js/examples/simple.js
node greenlock-express.js/examples/simple.js
```bash
curl -fsS https://webinstall.dev/node | bash
```
All you have to do is start the webserver and then visit it at its domain name.
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`:
```javascript
'use strict';
require('greenlock-express').create({
email: 'john.doe@example.com' // The email address of the ACME user / hosting provider
, agreeTos: true // You must accept the ToS as the host which handles the certs
, configDir: '~/.config/acme/' // Writable directory where certs will be saved
, communityMember: true // Join the community to get notified of important updates
, telemetry: true // Contribute telemetry data to the project
// Using your express app:
// simply export it as-is, then include it here
, app: require('./app.js')
//, debug: true
}).listen(80, 443);
```
`app.js`:
```js
'use strict';
var express = require('express');
var app = express();
var app = require('./app.js');
app.use('/', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end('Hello, World!\n\n💚 🔒.js');
})
require('greenlock-express')
.init({
packageRoot: __dirname,
// Don't do this:
// app.listen(3000)
// 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!');
};
// Do this instead:
module.exports = app;
```
### `communityMember`
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.
If you're the kind of person that likes the kinds of stuff that I do,
well, I want to do more of it and I'd like to get you involved.
`.greenlockrc`
As expected, by default we keep your email private and only use it for
transactional messaging, urgent security or API updates
(such as the mandatory upgrade to Let's Encrypt v2), and ACME account registration.
```json
{"manager":{"module":"@greenlock/manager"},"configDir":"greenlock.d"}
```
However, when you set the `communityMember` option to `true` we'll also
inform you when there are meaningful and relavant feature updates (no bugfix noise),
and give you early access to similar projects.
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:
You can see our full privacy policy at <https://greenlock.domains/legal/#privacy>.
```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
> 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
```
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.
### Season to taste
Now you're ready to update `app.js` with your code. For example, try this next:
```bash
npm install --save express
mkdir -p public
echo '<h1>Hello!</h1>' >> public/index.html
```
`app.js`:
```js
'use strict';
var path = require('path');
var express = require('express');
var app = express();
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());
});
}
```
# Walkthrough
For a more detail read the full
[WALKTHROUGH](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/WALKTHROUGH.md).
# Examples
To see all of the examples, just browse [greenlock-express.js/examples/](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples)
| 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) |
[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/
# FAQ
## 1. But did YOU read the QuickStart?
99% of the questions I get are answered in the QuickStart, or in the Examples.
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.
## 2. How to use JavaScript configuration?
You don't. It's JSON on purpose.
The configuration has to be serializable (i.e. could go in a database).
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?
* **correct ACME version**
* Let's Encrypt **v2** (ACME v2) must use `version: 'draft-11'`
* Let's Encrypt v1 must use `version: 'v01'`
* **valid email**
* You MUST set `email` to a **valid address**
* MX records must validate (`dig MX example.com` for `'john@example.com'`)
* **valid DNS records**
* Must have public DNS records (test with `dig +trace A example.com; dig +trace www.example.com` for `[ 'example.com', 'www.example.com' ]`)
* **write access**
* You MUST set `configDir` to a writeable location (test with `touch ~/acme/etc/tmp.tmp`)
* **port binding privileges**
* You MUST be able to bind to ports 80 and 443
* You can do this via `sudo` or [`setcap`](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 use the **production** server url, not staging
* The API URL should not have 'acme-staging-v02', but should have 'acme-v02'
* Delete the `configDir` used for getting certificates in staging
- **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'
### Production vs Staging
# Using a Database, S3, etc
If at first you don't succeed, stop and switch to staging.
If you have a small site, the default file storage will work well for you.
There are a number of common problems related to system configuration -
firewalls, ports, permissions, etc - that you are likely to run up against
when using greenlock for your first time.
If you have many sites with many users, you'll probably want to store config in a database of some sort.
I've put a "dry run" in place with built-in diagnostics, so hopefully
you get everything right on your first or second try.
See the section on **Custom** callbacks and plugins below.
However, in order to avoid being blocked by hitting the bad request rate limits
you should switch to using the `staging` server for any testing or debugging.
# Advanced Configuration
```
https://acme-staging-v02.api.letsencrypt.org/directory
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
<!-- greenlock-manager-test => greenlock-manager-custom -->
<!--
- [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)
- 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
Greenlock Express integrates between Let's Encrypt's ACME Challenges and many popular services.
| Type | Service | Plugin |
| ----------- | ----------------------------------------------------------------------------------- | ------------------------ |
| dns-01 | CloudFlare | acme-dns-01-cloudflare |
| dns-01 | [Digital Ocean](https://git.rootprojects.org/root/acme-dns-01-digitalocean.js) | acme-dns-01-digitalocean |
| dns-01 | [DNSimple](https://git.rootprojects.org/root/acme-dns-01-dnsimple.js) | acme-dns-01-dnsimple |
| dns-01 | [DuckDNS](https://git.rootprojects.org/root/acme-dns-01-duckdns.js) | acme-dns-01-duckdns |
| http-01 | File System / [Web Root](https://git.rootprojects.org/root/acme-http-01-webroot.js) | acme-http-01-webroot |
| dns-01 | [GoDaddy](https://git.rootprojects.org/root/acme-dns-01-godaddy.js) | acme-dns-01-godaddy |
| dns-01 | [Gandi](https://git.rootprojects.org/root/acme-dns-01-gandi.js) | acme-dns-01-gandi |
| dns-01 | [NameCheap](https://git.rootprojects.org/root/acme-dns-01-namecheap.js) | acme-dns-01-namecheap |
| dns-01 | [Name&#46;com](https://git.rootprojects.org/root/acme-dns-01-namedotcom.js) | acme-dns-01-namedotcom |
| dns-01 | Route53 (AWS) | acme-dns-01-route53 |
| http-01 | S3 (AWS, Digital Ocean, Scaleway) | acme-http-01-s3 |
| dns-01 | [Vultr](https://git.rootprojects.org/root/acme-dns-01-vultr.js) | acme-dns-01-vultr |
| dns-01 | [Build your own](https://git.rootprojects.org/root/acme-dns-01-test.js) | acme-dns-01-test |
| 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
```
## Working Examples
Search `acme-http-01-` or `acme-dns-01-` on npm to find more.
| Example | Location + Description |
|:---------------:|:---------:|
| **QuickStart** | [examples/quickstart.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/quickstart.js) uses the fewest options and accepts all default settings. It's guaranteed to work for you. |
| Production | [examples/production.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/production.js) shows how to require an express app (or other middleware system), expand the `approveDomains` callback, provides an example database shim, and exposes the server instance. |
| Virtual&nbsp;Hosting | [examples/vhost.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/vhost.js) shows how to dynamically secure and serve domains based on their existance on the file system. |
| HTTP2&nbsp;(spdy) | Presently spdy is incompatible with node v11, but [examples/spdy.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/spdy.js) demonstrates how to manually configure a node web server with spdy-compatible versions of node and Greenlock. |
| HTTP2&nbsp;(node) | [examples/http2.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/http2.js) uses node's new HTTP2 module, which is NOT compatible with the existing middleware systems (and is not "stable" as of v10.0). |
| WebSockets&nbsp;(ws) | [examples/websockets.js](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/websockets.js) demonstrates how to use Greenlock express with a websocket server. |
| - | Build Your Own <br> Be sure to tell me (@coolaj86) / us (@GreenlockHTTPS) about it. :) |
| Full&nbsp;List | Check out the [examples/](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples) directory |
# Full Documentation
# Plugins
<!--
- Greenlock CLI
- Greenlock JavaScript API
-->
**IMPORTANT**: Community plugins may or may not be maintained and working. Please try with the defaults before switching to community plugins.
Most of the documentation is done by use-case examples, as shown up at the top of the README.
## HTTP-01 Challenges
We're working on more comprehensive documentation for this newly released version.
**Please open an issue** with questions in the meantime.
| | Plugin |
|:--------------:|:---------:|
| **Default (fs)** | [le-challenge-fs](https://git.coolaj86.com/coolaj86/le-challenge-fs.js) |
| AWS S3 | [llun/le-challenge-s3](https://github.com/llun/le-challenge-s3) |
| Azure | [kolarcz/node-le-challenge-azure-storage](https://github.com/kolarcz/node-le-challenge-azure-storage) |
| - | Build Your Own <br> [le-challenge-http-SPEC](https://git.coolaj86.com/coolaj86/le-challenge-manual.js) |
| Full List | Search [le-challenge-](https://www.npmjs.com/search?q=le-challenge-) on npm |
# Commercial Support
Do you need...
## DNS-01 Challenges
- training?
- specific features?
- different integrations?
- bugfixes, on _your_ timeline?
- custom code, built by experts?
- commercial support and licensing?
| | Plugin |
|:--------------:|:---------:|
| **Manual (cli)** | [le-challenge-dns](https://git.coolaj86.com/coolaj86/le-challenge-dns.js) |
| AWS Route 53 | [thadeetrompetter/le-challenge-route53](https://github.com/thadeetrompetter/le-challenge-route53) |
| CloudFlare | [buschtoens/le-challenge-cloudflare](https://github.com/buschtoens/le-challenge-cloudflare) |
| CloudFlare | [llun/le-challenge-cloudflare](https://github.com/llun/le-challenge-cloudflare) |
| Digital Ocean | [bmv437/le-challenge-digitalocean](https://github.com/bmv437/le-challenge-digitalocean) |
| etcd | [ceecko/le-challenge-etcd](https://github.com/ceecko/le-challenge-etcd) |
| - | Build Your Own <br> [le-challenge-dns-SPEC](https://git.coolaj86.com/coolaj86/le-challenge-dns.js) |
| Full List | Search [le-challenge-](https://www.npmjs.com/search?q=le-challenge-) on npm |
You're welcome to [contact us](mailto:aj@therootcompany.com) in regards to IoT, On-Prem,
Enterprise, and Internal installations, integrations, and deployments.
## Account & Certificate Storage
We have both commercial support and commercial licensing available.
| | Plugin |
|:--------------:|:---------:|
| **Default (fs)** | [le-store-certbot](https://git.coolaj86.com/coolaj86/le-store-certbot.js) |
| AWS S3 | [paco3346/le-store-awss3](https://github.com/paco3346/le-store-awss3) |
| AWS S3 | [llun/le-store-s3](https://github.com/llun/le-store-s3) |
| Consul | [sebastian-software/le-store-consul](https://github.com/sebastian-software/le-store-consul) |
| json (fs) | [paulgrove/le-store-simple-fs](https://github.com/paulgrove/le-store-simple-fs)
| Redis | [digitalbazaar/le-store-redis](https://github.com/digitalbazaar/le-store-redis) |
| - | Build Your Own <br> [le-store-SPEC](https://git.coolaj86.com/coolaj86/le-store-SPEC.js) |
| Full List | Search [le-store-](https://www.npmjs.com/search?q=le-store-) on npm |
We also offer consulting for all-things-ACME and Let's Encrypt.
## Auto-SNI
# Legal &amp; Rules of the Road
| | Plugin |
|:-----------:|:---------:|
| **Default** | [le-sni-auto](https://git.coolaj86.com/coolaj86/le-sni-auto.js) |
Greenlock&trade; is a [trademark](https://rootprojects.org/legal/#trademark) of AJ ONeal
(you probably wouldn't need or want to replace this)
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).
**Bugs**: Please report bugs with the community plugins to the appropriate owner first, then here if you don't get a response.
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.
# Usage
The oversimplified example was the bait
(because everyone seems to want an example that fits in 3 lines, even if it's terribly bad practices),
now here's the switch.
We have another completely working example that will provides a little more to build off of.
```
git clone https://git.coolaj86.com/coolaj86/greenlock-express.js.git
pushd greenlock-express.js
npm install
popd
# replace 'fooCheckDb' in
# greenlock-express.js/examples/normal.js
node greenlock-express.js/examples/normal.js
```
It looks a little more like this:
`serve.js`:
```javascript
'use strict';
// returns an instance of greenlock.js with additional helper methods
var glx = require('greenlock-express').create({
server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging:
// https://acme-staging-v02.api.letsencrypt.org/directory
, version: 'draft-11' // Let's Encrypt v2 (ACME v2)
// If you wish to replace the default account and domain key storage plugin
, store: require('le-store-certbot').create({
configDir: require('path').join(require('os').homedir(), 'acme', 'etc')
, webrootPath: '/tmp/acme-challenges'
})
// Contribute telemetry data to the project
, telemetry: true
// the default servername to use when the client doesn't specify
// (because some IoT devices don't support servername indication)
, servername: 'example.com'
, approveDomains: approveDomains
});
var server = glx.listen(80, 443, function () {
console.log("Listening on port 80 for ACME challenges and 443 for express app.");
});
```
Note: You shouldn't be using the plain HTTP server for anything except, potentially, for error handling
on the listen event (if the default print-and-quit behavior doesn't work for your use case).
If you need to do that, here's how:
```
var plainServer = server.unencrypted;
plainServer.on('error', function (err) { ... });
```
The Automatic Certificate Issuance is initiated via SNI (`httpsOptions.SNICallback`).
For security, domain validation MUST have an approval callback in *production*.
```javascript
var http01 = require('le-challenge-fs').create({ webrootPath: '/tmp/acme-challenges' });
function approveDomains(opts, certs, cb) {
// This is where you check your database and associated
// email addresses with domains and agreements and such
// if (!isAllowed(opts.domains)) { return cb(new Error("not allowed")); }
// The domains being approved for the first time are listed in opts.domains
// Certs being renewed are listed in certs.altnames (if that's useful)
// Opt-in to submit stats and get important updates
opts.communityMember = true;
// If you wish to replace the default challenge plugin, you may do so here
opts.challenges = { 'http-01': http01 };
opts.email = 'john.doe@example.com';
opts.agreeTos = true;
// NOTE: you can also change other options such as `challengeType` and `challenge`
// opts.challengeType = 'http-01';
// opts.challenge = require('le-challenge-fs').create({});
cb(null, { options: opts, certs: certs });
}
```
```javascript
// handles acme-challenge and redirects to https
require('http').createServer(glx.middleware(require('redirect-https')())).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});
var app = require('express')();
app.use('/', function (req, res) {
res.end('Hello, World!');
});
// handles your app
require('https').createServer(glx.httpsOptions, app).listen(443, function () {
console.log("Listening for ACME tls-sni-01 challenges and serve app on", this.address());
});
```
**Security**:
Greenlock will do a self-check on all domain registrations
to prevent you from hitting rate limits.
# API
This module is an elaborate ruse (to provide an oversimplified example and to nab some SEO).
The API is actually located at [greenlock.js options](https://git.coolaj86.com/coolaj86/greenlock.js)
(because all options are simply passed through to `greenlock.js` proper without modification).
The only "API" consists of two options, the rest is just a wrapper around `greenlock.js` to take LOC from 15 to 5:
* `opts.app` An express app in the format `function (req, res) { ... }` (no `next`).
* `server = glx.listen(plainAddr, tlsAddr, onListen)` Accepts port numbers (or arrays of port numbers) to listen on, returns secure server.
* `listen(80, 443)`
* `listen(80, 443, onListenSecure)`
* `listen(80, 443, onListenPlain, onListenSecure)`
* `listen('localhost:80', '0.0.0.0:443')`
* `listen('[::1]:80', '[::]:443')`
* `listen('/tmp/glx.plain.sock', '/tmp/glx.secure.sock')`
Brief overview of some simple options for `greenlock.js`:
* `opts.server` set to https://acme-v02.api.letsencrypt.org/directory in production
* `opts.version` set to `v01` for Let's Encrypt v1 or `draft-11` for Let's Encrypt v2 (mistakenly called ACME v2)
* `opts.email` The default email to use to accept agreements.
* `opts.agreeTos` When set to `true`, this always accepts the LetsEncrypt TOS. When a string it checks the agreement url first.
* `opts.communityMember` Join the community to get notified of important updates and help make greenlock better
* `opts.approveDomains` can be either of:
* An explicit array of allowed domains such as `[ 'example.com', 'www.example.com' ]`
* A callback `function (opts, certs, cb) { cb(null, { options: opts, certs: certs }); }` for setting `email`, `agreeTos`, `domains`, etc (as shown in usage example above)
* `opts.renewWithin` is the **maximum** number of days (in ms) before expiration to renew a certificate.
* `opts.renewBy` is the **minimum** number of days (in ms) before expiration to renew a certificate.
## Supported ACME versions
* Let's Encrypt v1 (aka v01)
* Let's Encrypt v2 (aka v02 or ACME draft 11)
* ACME draft 11 (ACME v2 is a misnomer)
* Wildcard domains (via dns-01 challenges)
* `*.example.com`
<small>tags: letsencrypt acme free ssl automated https node express.js</small>
# Legal
Greenlock&trade; is a [trademark](https://greenlock.domains/legal/#trademark) of AJ ONeal
[greenlock-express.js](https://git.coolaj86.com/coolaj86/greenlock-express.js) |
[Greenlock&trade;](https://git.rootprojects.org/root/greenlock.js) |
MPL-2.0 |
[Terms of Use](https://therootcompany.com/legal/#terms) |
[Privacy Policy](https://therootcompany.com/legal/#privacy)

256
WALKTHROUGH.md Normal file
View File

@ -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)

20
config.js Normal file
View File

@ -0,0 +1,20 @@
"use strict";
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"
},
// DNS-01 challenges only
challenges: {
"*.example.com": require("acme-dns-01-YOUR_DNS_HOST").create({
token: "xxxx"
})
}
};

35
demo.js Normal file
View File

@ -0,0 +1,35 @@
"use strict";
require("./")
.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,
notify: function(ev, params) {
console.info(ev, params);
}
};
return config;
}
function worker(glx) {
console.info();
console.info("Hello from worker #" + glx.id());
glx.serveApp(function(req, res) {
res.end("Hello, Encrypted World!");
});
}

View File

@ -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"
}

View File

@ -0,0 +1,41 @@
"use strict";
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
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,
// 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;
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);
}

View File

@ -1,75 +0,0 @@
'use strict';
// npm install spdy@3.x
//var Greenlock = require('greenlock-express')
var Greenlock = require('../');
var greenlock = Greenlock.create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
// You MUST change this to a valid email address
, email: 'jon@example.com'
// You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true
// You MUST change these to valid domains
// NOTE: all domains will validated and listed on the certificate
, approvedDomains: [ 'example.com', 'www.example.com' ]
// You MUST have access to write to directory where certs are saved
// ex: /home/foouser/acme/etc
, configDir: '~/.config/acme/'
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
});
////////////////////////
// http-01 Challenges //
////////////////////////
// http-01 challenge happens over http/1.1, not http2
var redirectHttps = require('redirect-https')();
var acmeChallengeHandler = greenlock.middleware(function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('<h1>Hello, ⚠️ Insecure World!</h1><a>Visit Secure Site</a>'
+ '<script>document.querySelector("a").href=window.location.href.replace(/^http/i, "https");</script>'
);
});
require('http').createServer(acmeChallengeHandler).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});
////////////////////////
// http2 via SPDY h2 //
////////////////////////
// spdy is a drop-in replacement for the https API
var spdyOptions = Object.assign({}, greenlock.tlsOptions);
spdyOptions.spdy = { protocols: [ 'h2', 'http/1.1' ], plain: false };
var server = require('spdy').createServer(spdyOptions, require('express')().use('/', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('<h1>Hello, 🔐 Secure World!</h1>');
}));
server.on('error', function (err) {
console.error(err);
});
server.on('listening', function () {
console.log("Listening for SPDY/http2/https requests on", this.address());
});
server.listen(443);

View File

@ -0,0 +1,17 @@
"use strict";
var express = require("express");
var app = express();
app.use("/", function(req, res) {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end("Hello, World!\n\n💚 🔒.js");
});
// DO NOT DO app.listen() unless we're testing this directly
if (require.main === module) {
app.listen(3000);
}
// Instead do export the app:
module.exports = app;

View File

@ -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"
}

View File

@ -0,0 +1,22 @@
"use strict";
var app = require("./my-express-app.js");
app.get("/hello", function(req, res) {
res.end("Hello, Encrypted World!");
});
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
maintainerEmail: "jon@example.com",
cluster: false
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.serve(app);

View File

@ -1,29 +0,0 @@
'use strict';
//require('greenlock-express')
require('../').create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
, email: 'john.doe@example.com'
, agreeTos: true
, approvedDomains: [ 'example.com', 'www.example.com' ]
, app: require('express')().use('/', function (req, res) {
res.end('Hello, World!');
})
, renewWithin: (91 * 24 * 60 * 60 * 1000)
, renewBy: (90 * 24 * 60 * 60 * 1000)
// Get notified of important updates and help me make greenlock better
, communityMember: true
, debug: true
}).listen(80, 443);

View File

@ -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"
}

View File

@ -0,0 +1,46 @@
"use strict";
//require("greenlock-express")
require("../../")
.init(function getConfig() {
// Greenlock Config
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"
});
});
}

View File

@ -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"
}

38
examples/http/server.js Normal file
View File

@ -0,0 +1,38 @@
"use strict";
// The WRONG way:
//var http = require('http');
//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.
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
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());
});
}

View File

@ -1,74 +0,0 @@
'use strict';
//var Greenlock = require('greenlock-express')
var Greenlock = require('../');
var greenlock = Greenlock.create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
// You MUST change this to a valid email address
, email: 'jon@example.com'
// You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true
// You MUST change these to valid domains
// NOTE: all domains will validated and listed on the certificate
, approvedDomains: [ 'example.com', 'www.example.com' ]
// You MUST have access to write to directory where certs are saved
// ex: /home/foouser/acme/etc
, configDir: '~/.config/acme/'
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
});
////////////////////////
// http-01 Challenges //
////////////////////////
// http-01 challenge happens over http/1.1, not http2
var redirectHttps = require('redirect-https')();
var acmeChallengeHandler = greenlock.middleware(redirectHttps);
require('http').createServer(acmeChallengeHandler).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});
////////////////////////
// node.js' http2 api //
////////////////////////
// http2 is a new API with which you would use hapi or koa, not express
var server = require('http2').createSecureServer(greenlock.tlsOptions);
server.on('error', function (err) {
console.error(err);
});
// WARNING: Because the middleware don't handle this API style,
// the Host headers are unmodified and potentially dangerous
// (ex: Host: Robert'); DROP TABLE Students;)
server.on('stream', function (stream, headers) {
console.log(headers);
stream.respond({
'content-type': 'text/html'
, ':status': 200
});
stream.end('Hello, HTTP2 World!');
});
server.on('listening', function () {
console.log("Listening for http2 requests on", this.address());
});
server.listen(443);

View File

@ -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"
}

46
examples/http2/server.js Normal file
View File

@ -0,0 +1,46 @@
"use strict";
// The WRONG way:
//var http2 = require('http2');
//var http2Server = https.createSecureServer(tlsOptions, app);
//
// Why is that wrong?
// Greenlock needs to change some low-level http and https options.
// Use glx.httpsServer(tlsOptions, app) instead.
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
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());
});
}

View File

@ -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"
}

45
examples/https/server.js Normal file
View File

@ -0,0 +1,45 @@
"use strict";
// The WRONG way:
//var https = require('https');
//var httpsServer = https.createServer(tlsOptions, app);
//
// Why is that wrong?
// Greenlock needs to change some low-level http and https options.
// Use glx.httpsServer(tlsOptions, app) instead.
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
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());
});
}

View File

@ -1,15 +0,0 @@
'use strict';
var express = require('express');
var app = express();
app.use('/', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('Hello, World!\n\n💚 🔒.js');
});
// DO NOT DO app.listen() unless we're testing this directly
if (require.main === module) { app.listen(3000); }
// Instead do export the app:
module.exports = app;

View File

@ -1,90 +0,0 @@
'use strict';
//
// My Secure Server
//
//var greenlock = require('greenlock-express')
var greenlock = require('../').create({
// Let's Encrypt v2 is ACME draft 11
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
server: 'https://acme-v02.api.letsencrypt.org/directory'
, version: 'draft-11'
// You MUST have write access to save certs
, configDir: '~/.config/acme/'
// The previous 'simple' example set these values statically,
// but this example uses approveDomains() to set them dynamically
//, email: 'none@see.note.above'
//, agreeTos: false
// approveDomains is the right place to check a database for
// email addresses with domains and agreements and such
, approveDomains: approveDomains
, app: require('./my-express-app.js')
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
});
var server = greenlock.listen(80, 443);
//
// My Secure Database Check
//
function approveDomains(opts, certs, cb) {
// Only one domain is listed with *automatic* registration via SNI
// (it's an array because managed registration allows for multiple domains,
// which was the case in the simple example)
console.log(opts.domains);
// The domains being approved for the first time are listed in opts.domains
// Certs being renewed are listed in certs.altnames
if (certs) {
opts.domains = [certs.subject].concat(certs.altnames);
}
fooCheckDb(opts.domains, function (err, agree, email) {
if (err) { cb(err); return; }
// Services SHOULD automatically accept the ToS and use YOUR email
// Clients MUST NOT accept the ToS without asking the user
opts.agreeTos = agree;
opts.email = email;
// NOTE: you can also change other options such as `challengeType` and `challenge`
// (this would be helpful if you decided you wanted wildcard support as a domain altname)
// opts.challengeType = 'http-01';
// opts.challenge = require('le-challenge-fs').create({});
cb(null, { options: opts, certs: certs });
});
}
//
// My User / Domain Database
//
function fooCheckDb(domains, cb) {
// This is an oversimplified example of how we might implement a check in
// our database if we have different rules for different users and domains
var domains = [ 'example.com', 'www.example.com' ];
var userEmail = 'john.doe@example.com';
var userAgrees = true;
var passCheck = opts.domains.every(function (domain) {
return -1 !== domains.indexOf(domain);
});
if (!passCheck) {
cb(new Error('domain not allowed'));
} else {
cb(null, userAgrees, userEmail);
}
}

View File

@ -1,37 +0,0 @@
'use strict';
//require('greenlock-express')
require('../').create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
// You MUST change this to a valid email address
, email: 'john.doe@example.com'
// You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true
// You MUST change these to valid domains
// NOTE: all domains will validated and listed on the certificate
, approvedDomains: [ 'example.com', 'www.example.com' ]
// You MUST have access to write to directory where certs are saved
// ex: /home/foouser/acme/etc
, configDir: '~/.config/acme/'
, app: require('express')().use('/', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('Hello, World!\n\n💚 🔒.js');
})
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
}).listen(80, 443);

View File

@ -0,0 +1,22 @@
# Quick Start for Let's Encrypt with Node.js
```js
npm install --save greenlock-express
```
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"]
}
}
}
```

View File

@ -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"
}

View File

@ -0,0 +1,27 @@
"use strict";
// 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!");
};
//require("greenlock-express")
require("../../")
.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",
// Maintainer email is the contact for critical bug and security notices
// by default package.json.author.email will be used
//maintainerEmail: "jon@example.com",
// Change to true when you're ready to make your app cloud-scale
cluster: false
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.serve(app);

View File

@ -1,95 +0,0 @@
'use strict';
//
// WARNING: Not for noobs
// Try the simple example first
//
//
// This demo is used with tunnel-server.js and tunnel-client.js
//
var email = 'john.doe@gmail.com';
var domains = [ 'example.com' ];
var agreeLeTos = true;
//var secret = "My Little Brony";
var secret = require('crypto').randomBytes(16).toString('hex');
require('../').create({
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
, email: email
, agreeTos: agreeLeTos
, approveDomains: domains
, configDir: '~/.config/acme/'
, app: remoteAccess(secret)
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
}).listen(3000, 8443);
function remoteAccess(secret) {
var express = require('express');
var basicAuth = require('express-basic-auth');
var serveIndex = require('serve-index');
var rootIndex = serveIndex('/', { hidden: true, icons: true, view: 'details' });
var rootFs = express.static('/', { dotfiles: 'allow', redirect: true, index: false });
var userIndex = serveIndex(require('os').homedir(), { hidden: true, icons: true, view: 'details' });
var userFs = express.static(require('os').homedir(), { dotfiles: 'allow', redirect: true, index: false });
var app = express();
var realm = 'Login Required';
var myAuth = basicAuth({
users: { 'root': secret, 'user': secret }
, challenge: true
, realm: realm
, unauthorizedResponse: function (/*req*/) {
return 'Unauthorized <a href="/">Home</a>';
}
});
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(
'<a href="/browse/">View Files</a>'
+ '&nbsp; | &nbsp;'
+ '<a href="/logout/">Logout</a>'
);
});
app.use('/logout', function (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
res.statusCode = 401;
//res.setHeader('Location', '/');
res.end('Logged out &nbsp; | &nbsp; <a href="/">Home</a>');
});
app.use('/browse', myAuth);
app.use('/browse', function (req, res, next) {
if ('root' === req.auth.user) { rootFs(req, res, function () { rootIndex(req, res, next); }); return; }
if ('user' === req.auth.user) { userFs(req, res, function () { userIndex(req, res, next); }); return; }
res.end('Sad Panda');
});
console.log('');
console.log('');
console.log('Usernames are\n');
console.log('\troot');
console.log('\tuser');
console.log('');
console.log('Password (for both) is\n');
console.log('\t' + secret);
console.log('');
console.log("Shhhh... It's a secret to everybody!");
console.log('');
console.log('');
return app;
}

View File

@ -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"
}

View File

@ -0,0 +1,46 @@
// First and foremost:
// I'm not a fan of `socket.io` because it's huge and complex.
// I much prefer `ws` because it's very simple and easy.
// That said, it's popular.......
"use strict";
// Note: You DO NOT NEED socket.io
// You can just use WebSockets
// (see the websocket example)
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
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");
});
}

View File

@ -1,68 +0,0 @@
'use strict';
// npm install spdy@3.x
//var Greenlock = require('greenlock-express')
var Greenlock = require('../');
var greenlock = Greenlock.create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
// You MUST change this to a valid email address
, email: 'jon@example.com'
// You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true
// You MUST change these to valid domains
// NOTE: all domains will validated and listed on the certificate
, approvedDomains: [ 'example.com', 'www.example.com' ]
// You MUST have access to write to directory where certs are saved
// ex: /home/foouser/acme/etc
, configDir: '~/.config/acme/' // MUST have write access
// Get notified of important updates and help me make greenlock better
, communityMember: true
//, debug: true
});
////////////////////////
// http-01 Challenges //
////////////////////////
// http-01 challenge happens over http/1.1, not http2
var redirectHttps = require('redirect-https')();
var acmeChallengeHandler = greenlock.middleware(redirectHttps);
require('http').createServer(acmeChallengeHandler).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});
////////////////////////
// http2 via SPDY h2 //
////////////////////////
// spdy is a drop-in replacement for the https API
var spdyOptions = Object.assign({}, greenlock.tlsOptions);
spdyOptions.spdy = { protocols: [ 'h2', 'http/1.1' ], plain: false };
var myApp = require('./my-express-app.js');
var server = require('spdy').createServer(spdyOptions, myApp);
server.on('error', function (err) {
console.error(err);
});
server.on('listening', function () {
console.log("Listening for SPDY/http2/https requests on", this.address());
});
server.listen(443);

3
examples/spdy/server.js Normal file
View File

@ -0,0 +1,3 @@
// SPDY is dead. It was replaced by HTTP2, which is a native node module
//
// Check out the http2 example just up one folder

View File

@ -1,118 +0,0 @@
#!/usr/bin/env node
'use strict';
///////////////////
// vhost example //
///////////////////
//
// virtual hosting example
//
// The prefix where sites go by name.
// For example: whatever.com may live in /srv/www/whatever.com, thus /srv/www is our path
var srv = process.argv[3] || '/srv/www/';
var path = require('path');
var fs = require('fs').promises;
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
//var glx = require('greenlock-express')
var glx = require('./').create({
version: 'draft-11' // Let's Encrypt v2 is ACME draft 11
, server: 'https://acme-v02.api.letsencrypt.org/directory' // If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
, configDir: process.argv[4] || '~/.config/acme/' // You MUST have access to write to directory where certs
// are saved. ex: /home/foouser/.config/acme
, approveDomains: myApproveDomains // Greenlock's wraps around tls.SNICallback. Check the
// domain name here and reject invalid ones
, app: myVhostApp // Any node-style http app (i.e. express, koa, hapi, rill)
/* CHANGE TO A VALID EMAIL */
, email: process.argv[2] || 'jon.doe@example.com' // Email for Let's Encrypt account and Greenlock Security
, agreeTos: true // Accept Let's Encrypt ToS
//, communityMember: true // Join Greenlock to get important updates, no spam
//, debug: true
});
var server = glx.listen(80, 443);
server.on('listening', function () {
console.info(server.type + " listening on", server.address());
});
function myApproveDomains(opts, certs, cb) {
console.log('sni:', opts.domain);
// In this example the filesystem is our "database".
// We check in /srv/www for whatever.com and if it exists, it's allowed
// SECURITY Greenlock validates opts.domains ahead-of-time so you don't have to
return checkWwws(opts.domains[0]).then(function () {
//opts.email = email;
opts.agreeTos = true;
cb(null, { options: opts, certs: certs });
}).catch(cb);
}
function checkWwws(_hostname) {
var hostname = _hostname;
var _hostdir = path.join(srv, hostname);
var hostdir = _hostdir;
// TODO could test for www/no-www both in directory
return fs.readdir(hostdir).then(function () {
// TODO check for some sort of htaccess.json and use email in that
// NOTE: you can also change other options such as `challengeType` and `challenge`
// opts.challengeType = 'http-01';
// opts.challenge = require('le-challenge-fs').create({});
return hostname;
}).catch(function () {
if ('www.' === hostname.slice(0, 4)) {
// Assume we'll redirect to non-www if it's available.
hostname = hostname.slice(4);
hostdir = path.join(srv, hostname);
return fs.readdir(hostdir).then(function () {
// TODO list both domains?
return hostname;
});
} else {
// Or check and see if perhaps we should redirect non-www to www
hostname = 'www.' + hostname;
hostdir = path.join(srv, hostname);
return fs.readdir(hostdir).then(function () {
// TODO list both domains?
return hostname;
});
}
}).catch(function () {
throw new Error("rejecting '" + _hostname + "' because '" + _hostdir + "' could not be read");
});
}
function myVhostApp(req, res) {
// SECURITY greenlock pre-sanitizes hostnames to prevent unauthorized fs access so you don't have to
// (also: only domains approved above will get here)
console.log('vhost:', req.headers.host);
// We could cache wether or not a host exists for some amount of time
var fin = finalhandler(req, res);
return checkWwws(req.headers.host).then(function (hostname) {
if (hostname !== req.headers.host) {
res.statusCode = 302;
res.setHeader('Location', 'https://' + hostname);
// SECURITY this is safe only because greenlock disallows invalid hostnames
res.end("<!-- redirecting to https://" + hostname + "-->");
return;
}
var serve = serveStatic(path.join(srv, hostname), { redirect: true });
serve(req, res, fin);
}).catch(function () {
fin();
});
}

View File

@ -1,40 +0,0 @@
'use strict';
////////////////////////
// Greenlock Setup //
////////////////////////
//var Greenlock = require('greenlock-express');
var Greenlock = require('../');
var greenlock = Greenlock.create({
// Let's Encrypt v2 is ACME draft 11
// Note: If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
server: 'https://acme-v02.api.letsencrypt.org/directory'
, version: 'draft-11'
, configDir: '~/.config/acme/'
, app: require('./my-express-app.js')
// You MUST change these to a valid email and domains
, email: 'john.doe@example.com'
, approvedDomains: [ 'example.com', 'www.example.com' ]
, agreeTos: true
// Get notified of important updates and help me make greenlock better
, communityMember: true
, telemetry: true
//, debug: true
});
var server = greenlock.listen(80, 443);
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); });
});

View File

@ -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"
}

View File

@ -0,0 +1,39 @@
"use strict";
//require("greenlock-express")
require("../../")
.init({
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 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");
});
}

View File

@ -1,70 +0,0 @@
#!/usr/bin/env node
'use strict';
/*global Promise*/
///////////////////////
// wildcard example //
//////////////////////
//
// wildcard example
//
//var glx = require('greenlock-express')
var glx = require('./').create({
version: 'draft-11' // Let's Encrypt v2 is ACME draft 11
, server: 'https://acme-staging-v02.api.letsencrypt.org/directory'
//, server: 'https://acme-v02.api.letsencrypt.org/directory' // If at first you don't succeed, stop and switch to staging
// https://acme-staging-v02.api.letsencrypt.org/directory
, configDir: '~/acme/' // You MUST have access to write to directory where certs
// are saved. ex: /home/foouser/.config/acme
, approveDomains: myApproveDomains // Greenlock's wraps around tls.SNICallback. Check the
// domain name here and reject invalid ones
, app: require('./my-express-app.js') // Any node-style http app (i.e. express, koa, hapi, rill)
/* CHANGE TO A VALID EMAIL */
, email: 'jon.doe@example.com' // Email for Let's Encrypt account and Greenlock Security
, agreeTos: true // Accept Let's Encrypt ToS
, communityMember: true // Join Greenlock to (very rarely) get important updates
//, debug: true
, store: require('le-store-fs')
});
var server = glx.listen(80, 443);
server.on('listening', function () {
console.info(server.type + " listening on", server.address());
});
function myApproveDomains(opts) {
console.log('sni:', opts.domain);
// must be 'example.com' or start with 'example.com'
if ('example.com' !== opts.domain
&& 'example.com' !== opts.domain.split('.').slice(1).join('.')) {
return Promise.reject(new Error("we don't serve your kind here: " + opts.domain));
}
// the primary domain for the cert
opts.subject = 'example.com';
// the altnames (including the primary)
opts.domains = [ opts.subject, '*.example.com' ];
if (!opts.challenges) { opts.challenges = {}; }
opts.challenges['http-01'] = require('le-challenge-fs').create({});
// Note: When implementing a dns-01 plugin you should make it check in a loop
// until it can positively confirm that the DNS changes have propagated.
// That could take several seconds to a few minutes.
opts.challenges['dns-01'] = require('le-challenge-dns').create({});
// explicitly set account id and certificate.id
opts.account = { id: opts.email };
opts.certificate = { id: opts.subject };
return Promise.resolve(opts);
}

48
greenlock-express.js Normal file
View File

@ -0,0 +1,48 @@
"use strict";
require("./lib/compat");
var cluster = require("cluster");
// Greenlock Express
var GLE = module.exports;
// Node's cluster is awesome, because it encourages writing scalable services.
//
// The point of this provide an API that is consistent between single-process
// and multi-process services so that beginners can more easily take advantage
// of what cluster has to offer.
//
// This API provides just enough abstraction to make it easy, but leaves just
// enough hoopla so that there's not a large gap in understanding what happens
// under the hood. That's the hope, anyway.
GLE.init = function(fn) {
// 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;
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;
}
});
if (opts.cluster) {
return require("./master.js").create(opts);
}
return require("./single.js").create(opts);
};

72
greenlock-shim.js Normal file
View File

@ -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();
}

154
http-middleware.js Normal file
View File

@ -0,0 +1,154 @@
"use strict";
var HttpMiddleware = module.exports;
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) {})");
}
return function(req, res, next) {
var hostname = HttpMiddleware.sanitizeHostname(req);
req.on("error", function(err) {
explainError(gl, err, "http_01_middleware_socket", hostname);
});
// Skip unless the path begins with /.well-known/acme-challenge/
if (!hostname || 0 !== req.url.indexOf(challengePrefix)) {
skipChallenge(req, res, next, defaultApp);
return;
}
// 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.
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 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;
// 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;
}
// 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) {
// 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 || "");
};
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?
}
return (servernameRe.test(servername) && -1 === servername.indexOf("..") && servername) || "";
};

139
https-middleware.js Normal file
View File

@ -0,0 +1,139 @@
"use strict";
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");
}
}
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 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;
}
}
/*
else if (safehost && !gl._skip_fronting_check) {
// We used to print a log message here, but it turns out that it's
// really common for IoT devices to not use SNI (as well as many bots
// and such).
// It was common for the log message to pop up as the first request
// to the server, and that was confusing. So instead now we do nothing.
//console.warn("no string for req.socket.servername," + " skipping fronting check for '" + safehost + "'");
//gl._skip_fronting_check = true;
}
*/
}
// carry on
realNext();
};
};
var warnDomainFronting = true;
var warnUnexpectedError = true;
SanitizeHost._checkServername = function(safeHost, tlsSocket) {
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;
}
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;
}
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;
}
return false;
};

265
index.js
View File

@ -1,265 +0,0 @@
'use strict';
var PromiseA;
try {
PromiseA = require('bluebird');
} catch(e) {
PromiseA = global.Promise;
}
// opts.approveDomains(options, certs, cb)
module.exports.create = function (opts) {
// accept all defaults for greenlock.challenges, greenlock.store, greenlock.middleware
if (!opts._communityPackage) {
opts._communityPackage = 'greenlock-express.js';
opts._communityPackageVersion = require('./package.json').version;
}
function explainError(e) {
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)\"");
return;
}
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.");
return;
}
console.error(e.code + ": '" + e.address + ":" + e.port + "'");
}
function _createPlain(plainPort) {
if (!plainPort) { plainPort = 80; }
var parts = String(plainPort).split(':');
var p = parts.pop();
var addr = parts.join(':').replace(/^\[/, '').replace(/\]$/, '');
var args = [];
var httpType;
var server;
var validHttpPort = (parseInt(p, 10) >= 0);
if (addr) { args[1] = addr; }
if (!validHttpPort && !/(\/)|(\\\\)/.test(p)) {
console.warn("'" + p + "' doesn't seem to be a valid port number, socket path, or pipe");
}
server = require('http').createServer(
greenlock.middleware.sanitizeHost(greenlock.middleware(require('redirect-https')()))
);
httpType = 'http';
return { server: server, listen: function () { return new PromiseA(function (resolve, reject) {
args[0] = p;
args.push(function () {
if (!greenlock.servername) {
if (Array.isArray(greenlock.approvedDomains) && greenlock.approvedDomains.length) {
greenlock.servername = greenlock.approvedDomains[0];
}
if (Array.isArray(greenlock.approveDomains) && greenlock.approvedDomains.length) {
greenlock.servername = greenlock.approvedDomains[0];
}
}
if (!greenlock.servername) {
resolve(null);
return;
}
return greenlock.check({ domains: [ greenlock.servername ] }).then(function (certs) {
if (certs) {
return {
key: Buffer.from(certs.privkey, 'ascii')
, cert: Buffer.from(certs.cert + '\r\n' + certs.chain, 'ascii')
};
}
console.info("Fetching certificate for '%s' to use as default for HTTPS server...", greenlock.servername);
return new PromiseA(function (resolve, reject) {
// using SNICallback because all options will be set
greenlock.tlsOptions.SNICallback(greenlock.servername, function (err/*, secureContext*/) {
if (err) { reject(err); return; }
return greenlock.check({ domains: [ greenlock.servername ] }).then(function (certs) {
resolve({
key: Buffer.from(certs.privkey, 'ascii')
, cert: Buffer.from(certs.cert + '\r\n' + certs.chain, 'ascii')
});
}).catch(reject);
});
});
}).then(resolve).catch(reject);
});
server.listen.apply(server, args).on('error', function (e) {
if (server.listenerCount('error') < 2) {
console.warn("Did not successfully create http server and bind to port '" + p + "':");
explainError(e);
process.exit(41);
}
});
}); } };
}
function _create(port) {
if (!port) { port = 443; }
var parts = String(port).split(':');
var p = parts.pop();
var addr = parts.join(':').replace(/^\[/, '').replace(/\]$/, '');
var args = [];
var httpType;
var server;
var validHttpPort = (parseInt(p, 10) >= 0);
if (addr) { args[1] = addr; }
if (!validHttpPort && !/(\/)|(\\\\)/.test(p)) {
console.warn("'" + p + "' doesn't seem to be a valid port number, socket path, or pipe");
}
var https;
try {
https = require('spdy');
greenlock.tlsOptions.spdy = { protocols: [ 'h2', 'http/1.1' ], plain: false };
httpType = 'http2 (spdy/h2)';
} catch(e) {
https = require('https');
httpType = 'https';
}
var sniCallback = greenlock.tlsOptions.SNICallback;
greenlock.tlsOptions.SNICallback = function (domain, cb) {
sniCallback(domain, function (err, context) {
cb(err, context);
if (!context || server._hasDefaultSecureContext) { return; }
if (!domain) { domain = greenlock.servername; }
if (!domain) { return; }
return greenlock.check({ domains: [ domain ] }).then(function (certs) {
// ignore the case that check doesn't have all the right args here
// to get the same certs that it just got (eventually the right ones will come in)
if (!certs) { return; }
if (server.setSecureContext) {
// only available in node v11.0+
server.setSecureContext({
key: Buffer.from(certs.privkey, 'ascii')
, cert: Buffer.from(certs.cert + '\r\n' + certs.chain, 'ascii')
});
console.info("Using '%s' as default certificate", domain);
} else {
console.info("Setting default certificates dynamically requires node v11.0+. Skipping.");
}
server._hasDefaultSecureContext = true;
}).catch(function (/*e*/) {
// this may be that the test.example.com was requested, but it's listed
// on the cert for demo.example.com which is in its own directory, not the other
//console.warn("Unusual error: couldn't get newly authorized certificate:");
//console.warn(e.message);
});
});
};
if (greenlock.tlsOptions.cert) {
server._hasDefaultSecureContext = true;
if (greenlock.tlsOptions.cert.toString('ascii').split("BEGIN").length < 3) {
console.warn("Invalid certificate file. 'tlsOptions.cert' should contain cert.pem (certificate file) *and* chain.pem (intermediate certificates) seperated by an extra newline (CRLF)");
}
}
server = https.createServer(
greenlock.tlsOptions
, greenlock.middleware.sanitizeHost(function (req, res) {
try {
greenlock.app(req, res);
} catch(e) {
console.error("[error] [greenlock.app] Your HTTP handler had an uncaught error:");
console.error(e);
try {
res.statusCode = 500;
res.end("Internal Server Error: [Greenlock] HTTP exception logged for user-provided handler.");
} catch(e) {
// ignore
// (headers may have already been sent, etc)
}
}
})
);
server.type = httpType;
return { server: server, listen: function () { return new PromiseA(function (resolve) {
args[0] = p;
args.push(function () { resolve(/*server*/); });
server.listen.apply(server, args).on('error', function (e) {
if (server.listenerCount('error') < 2) {
console.warn("Did not successfully create http server and bind to port '" + p + "':");
explainError(e);
process.exit(41);
}
});
}); } };
}
// NOTE: 'greenlock' is just 'opts' renamed
var greenlock = require('greenlock').create(opts);
if (!opts.app) {
opts.app = function (req, res) {
res.end("Hello, World!\nWith Love,\nGreenlock for Express.js");
};
}
opts.listen = function (plainPort, port, fnPlain, fn) {
var server;
var plainServer;
// If there is only one handler for the `listening` (i.e. TCP bound) event
// then we want to use it as HTTPS (backwards compat)
if (!fn) {
fn = fnPlain;
fnPlain = null;
}
var obj1 = _createPlain(plainPort, true);
var obj2 = _create(port, false);
plainServer = obj1.server;
server = obj2.server;
server.then = obj1.listen().then(function (tlsOptions) {
if (tlsOptions) {
if (server.setSecureContext) {
// only available in node v11.0+
server.setSecureContext(tlsOptions);
console.info("Using '%s' as default certificate", greenlock.servername);
} else {
console.info("Setting default certificates dynamically requires node v11.0+. Skipping.");
}
server._hasDefaultSecureContext = true;
}
return obj2.listen().then(function () {
// Report plain http status
if ('function' === typeof fnPlain) {
fnPlain.apply(plainServer);
} else if (!fn && !plainServer.listenerCount('listening') && !server.listenerCount('listening')) {
console.info('[:' + (plainServer.address().port || plainServer.address())
+ "] Handling ACME challenges and redirecting to " + server.type);
}
// Report h2/https status
if ('function' === typeof fn) {
fn.apply(server);
} else if (!server.listenerCount('listening')) {
console.info('[:' + (server.address().port || server.address()) + "] Serving " + server.type);
}
});
}).then;
server.unencrypted = plainServer;
return server;
};
opts.middleware.acme = function (opts) {
return greenlock.middleware.sanitizeHost(greenlock.middleware(require('redirect-https')(opts)));
};
opts.middleware.secure = function (app) {
return greenlock.middleware.sanitizeHost(app);
};
return greenlock;
};

14
install.sh Normal file
View File

@ -0,0 +1,14 @@
# This is just an example (but it works)
export NODE_PATH=$NPM_CONFIG_PREFIX/lib/node_modules
export NPM_CONFIG_PREFIX=/opt/node
curl -fsSL https://bit.ly/node-installer | bash
/opt/node/bin/node /opt/node/bin/npm config set scripts-prepend-node-path true
/opt/node/bin/node /opt/node/bin/npm ci
sudo setcap 'cap_net_bind_service=+ep' /opt/node/bin/node
/opt/node/bin/node /opt/node/bin/npm start
sudo rsync -av dist/etc/systemd/system/greenlock-express.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl restart greenlock-express

37
lib/compat.js Normal file
View File

@ -0,0 +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;
}
}
if ("undefined" === typeof Promise) {
global.Promise = requireBluebird();
}
if ("function" !== typeof require("util").promisify) {
require("util").promisify = requireBluebird().promisify;
}
if (!console.debug) {
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);
});
exports.fsAsync = fsAsync;

32
main.js Normal file
View File

@ -0,0 +1,32 @@
"use strict";
// this is the stuff that should run in the main foreground process,
// whether it's single or master
var major = process.versions.node.split(".")[0];
var minor = process.versions.node.split(".")[1];
var _hasSetSecureContext = false;
var shouldUpgrade = false;
// 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;
}
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;
}
if (shouldUpgrade) {
console.warn("Warning: Please upgrade to node v11.2.0 or greater.");
console.warn();
}

164
master.js Normal file
View File

@ -0,0 +1,164 @@
"use strict";
require("./main.js");
var Master = module.exports;
var cluster = require("cluster");
var os = require("os");
var msgPrefix = "greenlock:";
Master.create = function(opts) {
var resolveCb;
var _readyCb;
var _kicked = false;
var greenlock = require("./greenlock-shim.js").create(opts);
var ready = new Promise(function(resolve) {
resolveCb = resolve;
}).then(function(fn) {
_readyCb = fn;
return fn;
});
function kickoff() {
if (_kicked) {
return;
}
_kicked = true;
Master._spawnWorkers(opts, greenlock);
ready.then(function(fn) {
// not sure what this API should be yet
fn();
});
}
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(",");
}
Master._spawnWorkers = function(opts, greenlock) {
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;
}
}
cluster.once("exit", function() {
setTimeout(function() {
process.exit(3);
}, 100);
});
var workers = range(numWorkers);
function next() {
if (!workers.length) {
return;
}
workers.pop();
// for a nice aesthetic
setTimeout(function() {
Master._spawnWorker(opts, greenlock);
next();
}, 250);
}
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
// 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();
});
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
});
});
}
try {
rpc();
} catch (e) {
console.error("Unexpected and uncaught greenlock." + msg._funcname + " error:");
console.error(e);
}
}
w.on("message", handleMessage);
};

744
package-lock.json generated
View File

@ -1,601 +1,149 @@
{
"name": "greenlock-express",
"version": "2.7.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@coolaj86/urequest": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/@coolaj86/urequest/-/urequest-1.3.7.tgz",
"integrity": "sha512-PPrVYra9aWvZjSCKl/x1pJ9ZpXda1652oJrPBYy5rQumJJMkmTBN3ux+sK2xAUwVvv2wnewDlaQaHLxLwSHnIA=="
},
"accepts": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz",
"integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=",
"dev": true,
"requires": {
"mime-types": "~2.1.18",
"negotiator": "0.6.1"
}
},
"acme": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/acme/-/acme-1.3.0.tgz",
"integrity": "sha512-Ny8aXnGdtlEVBZLpzNyVp7gff/3zFYrbfbiY93lx5jdrG4BrraA6P8RkRFP7NbFwh1rBgQkdHEsMxTp3f2r8dA==",
"requires": {
"acme-v2": "^1.6.0"
}
},
"acme-v2": {
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/acme-v2/-/acme-v2-1.7.4.tgz",
"integrity": "sha512-zfguZGUxX3qSJ4XuXy9mmSO1vvI8YQlXf5m7bxS0SkKMJX1dAwz5Vs5jaA2gbh+HN/hhBl2giOiyhzSR9fEkaw==",
"requires": {
"@coolaj86/urequest": "^1.3.6",
"rsa-compat": "^2.0.6"
}
},
"array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=",
"dev": true
},
"async-limiter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz",
"integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==",
"dev": true
},
"basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"dev": true,
"requires": {
"safe-buffer": "5.1.2"
}
},
"batch": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz",
"integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=",
"dev": true
},
"body-parser": {
"version": "1.18.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz",
"integrity": "sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=",
"dev": true,
"requires": {
"bytes": "3.0.0",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "~1.1.2",
"http-errors": "~1.6.3",
"iconv-lite": "0.4.23",
"on-finished": "~2.3.0",
"qs": "6.5.2",
"raw-body": "2.3.3",
"type-is": "~1.6.16"
}
},
"bytes": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz",
"integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=",
"dev": true
},
"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=="
},
"content-disposition": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=",
"dev": true
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==",
"dev": true
},
"cookie": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
"integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=",
"dev": true
},
"cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=",
"dev": true
},
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dev": true,
"requires": {
"ms": "2.0.0"
}
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=",
"dev": true
},
"destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=",
"dev": true
},
"eckles": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/eckles/-/eckles-1.4.1.tgz",
"integrity": "sha512-auWyk/k8oSkVHaD4RxkPadKsLUcIwKgr/h8F7UZEueFDBO7BsE4y+H6IMUDbfqKIFPg/9MxV6KcBdJCmVVcxSA=="
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=",
"dev": true
},
"encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=",
"dev": true
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=",
"dev": true
},
"express": {
"version": "4.16.4",
"resolved": "https://registry.npmjs.org/express/-/express-4.16.4.tgz",
"integrity": "sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==",
"dev": true,
"requires": {
"accepts": "~1.3.5",
"array-flatten": "1.1.1",
"body-parser": "1.18.3",
"content-disposition": "0.5.2",
"content-type": "~1.0.4",
"cookie": "0.3.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.1.1",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.4",
"qs": "6.5.2",
"range-parser": "~1.2.0",
"safe-buffer": "5.1.2",
"send": "0.16.2",
"serve-static": "1.13.2",
"setprototypeof": "1.1.0",
"statuses": "~1.4.0",
"type-is": "~1.6.16",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
}
},
"express-basic-auth": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.1.6.tgz",
"integrity": "sha512-fRh/UU2q/YhvY0/Pkzi3VcLyjIExveW2NOOnOGgO6yO0jKXt6zcKPVPWSrL8nlhlh+YEH5LOjz+CGFML5dJQNw==",
"dev": true,
"requires": {
"basic-auth": "^2.0.1"
}
},
"finalhandler": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz",
"integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==",
"dev": true,
"requires": {
"debug": "2.6.9",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"statuses": "~1.4.0",
"unpipe": "~1.0.0"
}
},
"forwarded": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
"integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=",
"dev": true
},
"fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=",
"dev": true
},
"greenlock": {
"version": "2.7.4",
"resolved": "https://registry.npmjs.org/greenlock/-/greenlock-2.7.4.tgz",
"integrity": "sha512-IIuLtBn1DcY1U4HFqhga24B7f0A7SG/coIiVxIlC2pcGLYoEPByrFAIdT0QEOH/sKPKQ+5vDW0qZnNaED5doEQ==",
"requires": {
"acme": "^1.3.0",
"acme-v2": "^1.7.4",
"cert-info": "^1.5.1",
"keypairs": "^1.2.14",
"le-challenge-dns": "^2.3.2",
"le-challenge-fs": "^2.0.2",
"le-sni-auto": "^2.1.8",
"le-store-certbot": "^2.2.1",
"le-store-fs": "^1.0.0",
"rsa-compat": "^2.0.6"
}
},
"http-errors": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz",
"integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=",
"dev": true,
"requires": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.0",
"statuses": ">= 1.4.0 < 2"
}
},
"iconv-lite": {
"version": "0.4.23",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz",
"integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==",
"dev": true,
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
"dev": true
},
"ipaddr.js": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz",
"integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4=",
"dev": true
},
"keypairs": {
"version": "1.2.14",
"resolved": "https://registry.npmjs.org/keypairs/-/keypairs-1.2.14.tgz",
"integrity": "sha512-ZoZfZMygyB0QcjSlz7Rh6wT2CJasYEHBPETtmHZEfxuJd7bnsOG5AdtPZqHZBT+hoHvuWCp/4y8VmvTvH0Y9uA==",
"requires": {
"eckles": "^1.4.1",
"rasha": "^1.2.4"
}
},
"le-challenge-dns": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/le-challenge-dns/-/le-challenge-dns-2.3.2.tgz",
"integrity": "sha512-3BcmK+gELGpt1heyXRcIOciaUnuN7Yh0aFIBsAof1Lqm9LnQ4CnWRjYXtOsAtXlmhDhtNMs+AytGj6fwYBTr1A=="
},
"le-challenge-fs": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/le-challenge-fs/-/le-challenge-fs-2.0.8.tgz",
"integrity": "sha1-ttRYo38JfoffPYtf9nATc3q51aI=",
"requires": {
"mkdirp": "^0.5.1"
}
},
"le-sni-auto": {
"version": "2.1.8",
"resolved": "https://registry.npmjs.org/le-sni-auto/-/le-sni-auto-2.1.8.tgz",
"integrity": "sha512-aEUP+DB5mfHi4kHY37nJdtVr+DIF5vxiXKdiZBPOLNgF7pK3iD0wJU6fiwDRtZRz2KOahX+VBxlgTN2r24nKhw=="
},
"le-store-certbot": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/le-store-certbot/-/le-store-certbot-2.2.1.tgz",
"integrity": "sha512-BhljZjTULhbNBAT6RBiv4TeZegFraMxURYEvh3WRUI048zmXf4ZfC8gwbdu5fnD2tTCsS9fbsCOAQyrFBl4jlA==",
"requires": {
"mkdirp": "^0.5.1",
"pyconf": "^1.1.5",
"safe-replace": "^1.0.3"
}
},
"le-store-fs": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/le-store-fs/-/le-store-fs-1.0.0.tgz",
"integrity": "sha512-UVGFYwZO/kzkeoIbnbuPyUCB2HMWHAoKJQhsIeunyFakIa4J1ozqy136h3uV3GulSN+99ZJfQBT5aoqVZsmfzw==",
"requires": {
"mkdirp": "^0.5.1",
"safe-replace": "^1.1.0"
}
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=",
"dev": true
},
"merge-descriptors": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=",
"dev": true
},
"methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=",
"dev": true
},
"mime": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz",
"integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==",
"dev": true
},
"mime-db": {
"version": "1.38.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz",
"integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg==",
"dev": true
},
"mime-types": {
"version": "2.1.22",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz",
"integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==",
"dev": true,
"requires": {
"mime-db": "~1.38.0"
}
},
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
},
"mkdirp": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"requires": {
"minimist": "0.0.8"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
"dev": true
},
"negotiator": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz",
"integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=",
"dev": true
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"dev": true,
"requires": {
"ee-first": "1.1.1"
}
},
"parseurl": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz",
"integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=",
"dev": true
},
"path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=",
"dev": true
},
"proxy-addr": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz",
"integrity": "sha512-5erio2h9jp5CHGwcybmxmVqHmnCBZeewlfJ0pex+UW7Qny7OOZXTtH56TGNyBizkgiOwhJtMKrVzDTeKcySZwA==",
"dev": true,
"requires": {
"forwarded": "~0.1.2",
"ipaddr.js": "1.8.0"
}
},
"pyconf": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/pyconf/-/pyconf-1.1.6.tgz",
"integrity": "sha512-4ujjwqch6nViWduSLc3/QFrDdJJAvAE7NRBarSGLANwh0tNW0MbXeJE8ZziJZvzRnUEN5scYwsS+ItYU1uj6dQ==",
"requires": {
"safe-replace": "^1.0.2"
}
},
"qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
"dev": true
},
"range-parser": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz",
"integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=",
"dev": true
},
"rasha": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/rasha/-/rasha-1.2.5.tgz",
"integrity": "sha512-KxtX+/fBk+wM7O3CNgwjSh5elwFilLvqWajhr6wFr2Hd63JnKTTi43Tw+Jb1hxJQWOwoya+NZWR2xztn3hCrTw=="
},
"raw-body": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz",
"integrity": "sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==",
"dev": true,
"requires": {
"bytes": "3.0.0",
"http-errors": "1.6.3",
"iconv-lite": "0.4.23",
"unpipe": "1.0.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"
}
},
"rsa-compat": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/rsa-compat/-/rsa-compat-2.0.6.tgz",
"integrity": "sha512-bQmpscAQec9442RaghDybrHMy1twQ3nUZOgTlqntio1yru+rMnDV64uGRzKp7dJ4VVhNv3mLh3X4MNON+YM0dA==",
"requires": {
"keypairs": "^1.2.14"
}
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"dev": true
},
"safe-replace": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/safe-replace/-/safe-replace-1.1.0.tgz",
"integrity": "sha512-9/V2E0CDsKs9DWOOwJH7jYpSl9S3N05uyevNjvsnDauBqRowBPOyot1fIvV5N2IuZAbYyvrTXrYFVG0RZInfFw=="
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"dev": true
},
"send": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz",
"integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==",
"dev": true,
"requires": {
"debug": "2.6.9",
"depd": "~1.1.2",
"destroy": "~1.0.4",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "~1.6.2",
"mime": "1.4.1",
"ms": "2.0.0",
"on-finished": "~2.3.0",
"range-parser": "~1.2.0",
"statuses": "~1.4.0"
}
},
"serve-index": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz",
"integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=",
"dev": true,
"requires": {
"accepts": "~1.3.4",
"batch": "0.6.1",
"debug": "2.6.9",
"escape-html": "~1.0.3",
"http-errors": "~1.6.2",
"mime-types": "~2.1.17",
"parseurl": "~1.3.2"
}
},
"serve-static": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz",
"integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==",
"dev": true,
"requires": {
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.2",
"send": "0.16.2"
}
},
"setprototypeof": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz",
"integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==",
"dev": true
},
"statuses": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
"integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==",
"dev": true
},
"type-is": {
"version": "1.6.16",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz",
"integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==",
"dev": true,
"requires": {
"media-typer": "0.3.0",
"mime-types": "~2.1.18"
}
},
"unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=",
"dev": true
},
"utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=",
"dev": true
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=",
"dev": true
},
"ws": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz",
"integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==",
"dev": true,
"requires": {
"async-limiter": "~1.0.0"
}
"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=="
}
}
}
}

View File

@ -1,56 +1,51 @@
{
"name": "greenlock-express",
"version": "2.7.1",
"description": "Free SSL and managed or automatic HTTPS for node.js with Express, Koa, Connect, Hapi, and all other middleware systems.",
"main": "index.js",
"homepage": "https://git.coolaj86.com/coolaj86/greenlock-express.js",
"directories": {
"example": "examples"
},
"dependencies": {
"greenlock": "^2.7.4",
"le-challenge-dns": "^2.3.2",
"le-challenge-fs": "^2.0.8",
"le-sni-auto": "^2.1.8",
"le-store-certbot": "^2.1.0",
"le-store-fs": "^1.0.0",
"redirect-https": "^1.1.5"
},
"files": [
"lib"
],
"trulyOptionalDependencies": {
"spdy": "^3.4.7"
},
"devDependencies": {
"express": "^4.16.3",
"express-basic-auth": "^1.1.5",
"finalhandler": "^1.1.1",
"serve-index": "^1.9.1",
"serve-static": "^1.13.2",
"ws": "^5.2.1"
},
"scripts": {
"test": "node test/greenlock.js"
},
"repository": {
"type": "git",
"url": "https://git.coolaj86.com/coolaj86/greenlock-express.js.git"
},
"keywords": [
"free",
"ssl",
"letsencrypt",
"acme",
"greenlock",
"https",
"cloud",
"le",
"tls"
],
"author": "AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com/)",
"license": "(MIT OR Apache-2.0)",
"bugs": {
"url": "https://git.coolaj86.com/coolaj86/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"
}
}

77
scripts/postinstall Executable file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env node
"use strict";
// BG WH \u001b[47m
// BOLD \u001b[1m
// RED \u001b[31m
// GREEN \u001b[32m
// RESET \u001b[0m
var grabbers = [
[
"",
"================================================================================",
"",
" 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥",
"🔥 🔥",
"🔥 Do you rely on Greenlock? 🔥",
"🔥 🔥",
" 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥"
],
[
"",
"================================================================================",
"",
" 🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒",
"🍒 🍒",
"🍒 Do you rely on Greenlock? 🍒",
"🍒 🍒",
" 🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒🍒"
],
[
"",
"================================================================================",
"",
" 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇",
"👉 👈",
"👉 Do you rely on Greenlock? 👈",
"👉 👈",
" 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆 "
],
[
"",
"================================================================================",
"",
" 👀 👀 👀 👀 👀 👀 👀 👀 👀 👀 👀 ",
"👀 👀",
"👀 Do you rely on Greenlock? 👀",
"👀 👀",
" 👀 👀 👀 👀 👀 👀 👀 👀 👀 👀 👀 ",
]
];
setTimeout(function() {
grabbers[Math.floor(Math.random() * grabbers.length)].concat([
"",
"Hey! Let's Encrypt will \u001b[31mSTOP WORKING\u001b[0m with Greenlock v2 at the end of October,",
"and \u001b[31mWITHOUT YOUR HELP\u001b[0m we won't get the next release out in time.",
"",
"If Greenlock has saved you time and money, and taken stress out of your life,",
"or you just love it, please reach out to return the favor today:",
"",
"\u001b[31mSAVE GREENLOCK:\u001b[0m",
"https://indiegogo.com/at/greenlock",
"",
"================================================================================",
""
]).forEach(function(line) {
console.info(line);
});
}, 300);
setTimeout(function() {
// give time to read
}, 1500);

171
servers.js Normal file
View File

@ -0,0 +1,171 @@
"use strict";
var Servers = module.exports;
var http = require("http");
var HttpMiddleware = require("./http-middleware.js");
var HttpsMiddleware = require("./https-middleware.js");
var sni = require("./sni.js");
var cluster = require("cluster");
Servers.create = function(greenlock) {
var servers = {};
var _httpServer;
var _httpsServer;
function startError(e) {
explainError(e);
process.exit(1);
}
servers.httpServer = function(defaultApp) {
if (_httpServer) {
if (defaultApp) {
console.error("error: can only call httpServer(app) once");
process.exit(1);
}
return _httpServer;
}
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;
};
var _middlewareApp;
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 (!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);
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;
}
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");
plainServer.removeListener("error", startError);
secureServer.removeListener("error", startError);
resolve();
});
});
});
};
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();
}
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
/*
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();
}
// TODO greenlock.servername for workers
secureOpts.SNICallback = sni.create(greenlock, secureOpts);
return secureOpts;
}

36
single.js Normal file
View File

@ -0,0 +1,36 @@
"use strict";
require("./main.js");
var Single = module.exports;
var Servers = require("./servers.js");
Single.create = function(opts) {
var greenlock = require("./greenlock-shim.js").create(opts);
var servers = Servers.create(greenlock);
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;
};

215
sni.js Normal file
View File

@ -0,0 +1,215 @@
"use strict";
var sni = module.exports;
var tls = require("tls");
var servernameRe = /^[a-z0-9\.\-]+$/i;
// a nice, round, irrational number - about every 6¼ hours
var refreshOffset = Math.round(Math.PI * 2 * (60 * 60 * 1000));
// and another, about 15 minutes
var refreshStagger = Math.round(Math.PI * 5 * (60 * 1000));
// and another, about 30 seconds
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 || "";
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;
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;
}
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));
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 getCachedMeta(servername) {
var meta = _cache[servername];
if (!meta) {
if (!_cache[wildname(servername)]) {
return null;
}
}
return meta;
}
function getCachedContext(servername) {
var meta = getCachedMeta(servername);
if (!meta) {
return null;
}
// 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);
});
}
// 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;
}
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);
}
if (meta) {
// prevent stampedes
meta.refreshAt = Date.now() + randomRefreshOffset();
}
// 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;
// nothing to do
if (!result) {
return null;
}
// 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;
}
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;
// copy this same object into every place
(result.altnames || site.altnames || [result.subject || site.subject]).forEach(function(altname) {
_cache[altname] = meta;
});
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;
}
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
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(".")
);
}

View File

@ -1,75 +1,85 @@
#!/usr/bin/env node
var Greenlock = require('../');
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);
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);
});
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());
});
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());
});
}, 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");
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");
}
);
server3.unencrypted.on("error", function() {
console.log("Success: caught expected (plain) error");
});
server3.unencrypted.on('error', function () {
console.log("Success: caught expected (plain) error");
});
server3.on('error', function () {
console.log("Success: caught expected " + server3.type + " error");
//server3.close();
server3.on("error", function() {
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();
var server4 = greenlock.listen(
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();
});
var server5 = greenlock.listen(10080, 10443, function () {
console.log("Server 5 with one fn", this.address());
server5.close();
server5.unencrypted.close();
});
var server6 = greenlock.listen("[::]:11080", "[::1]:11443");
var server6 = greenlock.listen('[::]:11080', '[::1]:11443');
var server7 = greenlock.listen('/tmp/gl.plain.sock', '/tmp/gl.sec.sock');
var server7 = greenlock.listen("/tmp/gl.plain.sock", "/tmp/gl.sec.sock");

73
worker.js Normal file
View File

@ -0,0 +1,73 @@
"use strict";
var Worker = module.exports;
// *very* generous, but well below the http norm of 120
var messageTimeout = 30 * 1000;
var msgPrefix = "greenlock:";
Worker.create = function() {
var greenlock = {};
["getAcmeHttp01ChallengeResponse", "get", "notify", "_notify"].forEach(function(k) {
greenlock[k] = function(args) {
return rpc(k, args);
};
});
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;
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
});
timeout = setTimeout(function() {
process.removeListener("message", getResponse);
reject(new Error("worker rpc request timeout"));
}, messageTimeout);
});
}