Compare commits
No commits in common. "94fd6575624bbc1f174d6b560cc58c88dfaeebd3" and "4294bf387084f99ed1d2e6e9ebc25f7017c53656" have entirely different histories.
94fd657562
...
4294bf3870
|
@ -1,15 +1,20 @@
|
|||
letsencrypt.work
|
||||
letsencrypt.logs
|
||||
letsencrypt.config
|
||||
TODO.txt
|
||||
link.sh
|
||||
.env
|
||||
|
||||
# ---> Node
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
@ -17,15 +22,61 @@ lib-cov
|
|||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
||||
node_modules
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
|
||||
# next.js build output
|
||||
.next
|
||||
|
||||
# nuxt.js build output
|
||||
.nuxt
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
|
|
16
.jshintrc
16
.jshintrc
|
@ -1,16 +0,0 @@
|
|||
{ "node": true
|
||||
, "browser": true
|
||||
, "jquery": true
|
||||
, "strict": true
|
||||
, "indent": 2
|
||||
, "onevar": true
|
||||
, "laxcomma": true
|
||||
, "laxbreak": true
|
||||
, "eqeqeq": true
|
||||
, "immed": true
|
||||
, "undef": true
|
||||
, "unused": true
|
||||
, "latedef": true
|
||||
, "curly": true
|
||||
, "trailing": true
|
||||
}
|
|
@ -4,5 +4,5 @@
|
|||
"singleQuote": true,
|
||||
"tabWidth": 4,
|
||||
"trailingComma": "none",
|
||||
"useTabs": true
|
||||
"useTabs": false
|
||||
}
|
||||
|
|
519
LICENSE
519
LICENSE
|
@ -1,375 +1,312 @@
|
|||
Copyright 2015-2019 AJ ONeal
|
||||
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
1. Definitions
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
1.1. "Contributor" means each individual or legal entity that creates, contributes
|
||||
to the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
1.2. "Contributor Version" means the combination of the Contributions of others
|
||||
(if any) used by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
1.3. "Contribution" means Covered Software of a particular Contributor.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
1.5. "Incompatible With Secondary Licenses" means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
(a) that the initial Contributor has attached the notice described in Exhibit
|
||||
B to the Covered Software; or
|
||||
|
||||
(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.
|
||||
(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.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
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.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.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.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:
|
||||
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
|
||||
(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.
|
||||
(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.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.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.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.
|
||||
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. License Grants and Conditions
|
||||
|
||||
2.1. Grants
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
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
|
||||
(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.
|
||||
(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
|
||||
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.
|
||||
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
|
||||
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:
|
||||
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
|
||||
(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
|
||||
(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.
|
||||
(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).
|
||||
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
|
||||
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).
|
||||
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
|
||||
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.
|
||||
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
|
||||
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.
|
||||
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
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
|
||||
Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
3. Responsibilities
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
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.
|
||||
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
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
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
|
||||
(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.
|
||||
(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
|
||||
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
|
||||
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
|
||||
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.
|
||||
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
|
||||
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.
|
||||
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
|
||||
---------------------------------------------------
|
||||
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.
|
||||
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. 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.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.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.
|
||||
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. *
|
||||
* *
|
||||
************************************************************************
|
||||
6. Disclaimer of Warranty
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 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. *
|
||||
* *
|
||||
************************************************************************
|
||||
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.
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
7. Limitation of Liability
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
8. Litigation
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
9. Miscellaneous
|
||||
|
||||
10.1. New Versions
|
||||
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.
|
||||
|
||||
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. Versions of the License
|
||||
|
||||
10.2. Effect of New Versions
|
||||
10.1. 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.
|
||||
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.3. Modified Versions
|
||||
10.2. Effect of New 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).
|
||||
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.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
10.3. Modified Versions
|
||||
|
||||
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.
|
||||
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).
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
|
||||
|
||||
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 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
|
||||
|
||||
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.
|
||||
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.
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as defined
|
||||
by the Mozilla Public License, v. 2.0.
|
||||
|
|
|
@ -0,0 +1,517 @@
|
|||
# Migrating from Greenlock v2 to v3
|
||||
|
||||
**Greenlock Express** uses Greenlock directly, the same as before.
|
||||
|
||||
All options described for `Greenlock.create({...})` also apply to the Greenlock Express `init()` callback.
|
||||
|
||||
# Overview of Major Differences
|
||||
|
||||
- Reduced API
|
||||
- No code in the config
|
||||
- (config is completely serializable)
|
||||
- Manager callbacks replace `approveDomains`
|
||||
- Greenlock Express does more, with less config
|
||||
- cluster is supported out-of-the-box
|
||||
- high-performance
|
||||
- scalable
|
||||
- ACME challenges are simplified
|
||||
- init
|
||||
- zones (dns-01)
|
||||
- set
|
||||
- get
|
||||
- remove
|
||||
- Store callbacks are simplified
|
||||
- accounts
|
||||
- checkKeypairs
|
||||
- certificates
|
||||
- checkKeypairs
|
||||
- check
|
||||
- set
|
||||
|
||||
# Greenlock JavaScript API greatly reduced
|
||||
|
||||
Whereas before there were many different methods with nuance differences,
|
||||
now there's just `create`, `get`, `renew`, and sometimes `add` ().
|
||||
|
||||
- Greenlock.create({ maintainerEmail, packageAgent, notify })
|
||||
- Greenlock.get({ servername, wildname, duplicate, force })
|
||||
- (just a convenience wrapper around renew)
|
||||
- Greenlock.renew({ subject, altnames, issuedBefore, expiresAfter })
|
||||
- (retrieves, issues, renews, all-in-one)
|
||||
- _optional_ Greenlock.add({ subject, altnames, subscriberEmail })
|
||||
- (partially replaces `approveDomains`)
|
||||
|
||||
Also, some disambiguation on terms:
|
||||
|
||||
- `domains` was often ambiguous and confusing, it has been replaced by:
|
||||
- `subject` refers to the subject of a certificate - the primary domain
|
||||
- `altnames` refers to the domains in the SAN (Subject Alternative Names) section of the certificate
|
||||
- `servername` refers to the TLS (SSL) SNI (Server Name Indication) request for a cetificate
|
||||
- `wildname` refers to the wildcard version of the servername (ex: `www.example.com => *.example.com`)
|
||||
|
||||
When you create an instance of Greenlock, you only supply package and maintainer info.
|
||||
|
||||
All other configuration is A) optional and B) handled by the _Manager_.
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
var pkg = require('./package.json');
|
||||
|
||||
var Greenlock = require('greenlock');
|
||||
var greenlock = Greenlock.create({
|
||||
// used for the ACME client User-Agent string as per RFC 8555 and RFC 7231
|
||||
packageAgent: pkg.name + '/' + pkg.version,
|
||||
|
||||
// used as the contact for critical bug and security notices
|
||||
// should be the same as pkg.author.email
|
||||
maintainerEmail: 'jon@example.com',
|
||||
|
||||
// used for logging background events and errors
|
||||
notify: function(ev, args) {
|
||||
if ('error' === ev || 'warning' === ev) {
|
||||
console.error(ev, args);
|
||||
return;
|
||||
}
|
||||
console.info(ev, args);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
By default **no certificates will be issued**. See the _manager_ section.
|
||||
|
||||
When you want to get a single certificate, you use `get`, which will:
|
||||
|
||||
- will return null if neither the `servername` or its `wildname` (wildcard) variant can be found
|
||||
- retrieve a non-expired certificate, if possible
|
||||
- will renew the certificate in the background, if stale
|
||||
- will wait for the certificate to be issued if new
|
||||
|
||||
```js
|
||||
greenlock
|
||||
.get({ servername: 'www.example.com' })
|
||||
.then(function(result) {
|
||||
if (!result) {
|
||||
// certificate is not on the approved list
|
||||
return null;
|
||||
}
|
||||
|
||||
var fullchain = result.pems.cert + '\n' + result.pems.chain + '\n';
|
||||
var privkey = result.pems.privkey;
|
||||
|
||||
return {
|
||||
fullchain: fullchain,
|
||||
privkey: privkey
|
||||
};
|
||||
})
|
||||
.catch(function(e) {
|
||||
// something went wrong in the renew process
|
||||
console.error(e);
|
||||
});
|
||||
```
|
||||
|
||||
By default **no certificates will be issued**. See the _manager_ section.
|
||||
|
||||
When you want to renew certificates, _en masse_, you use `renew`, which will:
|
||||
|
||||
- check all certificates matching the given criteria
|
||||
- only renew stale certificates by default
|
||||
- return error objects (will NOT throw exception for failed renewals)
|
||||
|
||||
```js
|
||||
greenlock
|
||||
.renew({})
|
||||
.then(function(results) {
|
||||
if (!result.length) {
|
||||
// no certificates found
|
||||
return null;
|
||||
}
|
||||
|
||||
// [{ site, error }]
|
||||
return results;
|
||||
})
|
||||
.catch(function(e) {
|
||||
// an unexpected error, not related to renewal
|
||||
console.error(e);
|
||||
});
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
| Option | Description |
|
||||
| ------------- | -------------------------------------------------------------------------- |
|
||||
| `altnames` | only check and renew certs matching these altnames (including wildcards) |
|
||||
| `renewBefore` | only check and renew certs marked for renewal before the given date, in ms |
|
||||
| `duplicate` | renew certificates regardless of timing |
|
||||
| `force` | allow silly things, like tiny `renewOffset`s |
|
||||
|
||||
By default **no certificates will be issued**. See the _manager_ section.
|
||||
|
||||
# Greenlock Express Example
|
||||
|
||||
The options that must be returned from `init()` are the same that are used in `Greenlock.create()`,
|
||||
with a few extra that are specific to Greenlock Express:
|
||||
|
||||
```js
|
||||
require('@root/greenlock-express')
|
||||
.init(function() {
|
||||
// This object will be passed to Greenlock.create()
|
||||
|
||||
var options = {
|
||||
// some options, like cluster, are special to Greenlock Express
|
||||
|
||||
cluster: false,
|
||||
|
||||
// The rest are the same as for Greenlock
|
||||
|
||||
packageAgent: pkg.name + '/' + pkg.version,
|
||||
maintainerEmail: 'jon@example.com',
|
||||
notify: function(ev, args) {
|
||||
console.info(ev, args);
|
||||
}
|
||||
};
|
||||
|
||||
return options;
|
||||
})
|
||||
.serve(function(glx) {
|
||||
// will start servers on port 80 and 443
|
||||
|
||||
glx.serveApp(function(req, res) {
|
||||
res.end('Hello, Encrypted World!');
|
||||
});
|
||||
|
||||
// you can get access to the raw server (i.e. for websockets)
|
||||
|
||||
glx.httpsServer(); // returns raw server object
|
||||
});
|
||||
```
|
||||
|
||||
# _Manager_ replaces `approveDomains`
|
||||
|
||||
`approveDomains` was always a little confusing. Most people didn't need it.
|
||||
|
||||
Instead, now there is a simple config file that will work for most people,
|
||||
as well as a set of callbacks for easy configurability.
|
||||
|
||||
### Default Manager
|
||||
|
||||
The default manager is `greenlock-manager-fs` and the default `configFile` is `~/.config/greenlock/manager.json`.
|
||||
|
||||
The config file should look something like this:
|
||||
|
||||
`~/.config/greenlock/manager.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "jon@example.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can specify a `acme-dns-01-*` or `acme-http-01-*` challenge plugin globally, or per-site.
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "jon@example.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"],
|
||||
"challenges": {
|
||||
"dns-01": {
|
||||
"module": "acme-dns-01-digitalocean",
|
||||
"token": "apikey-xxxxx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The same is true with `greenlock-store-*` plugins:
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "jon@example.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
},
|
||||
"store": {
|
||||
"module": "greenlock-store-fs",
|
||||
"basePath": "~/.config/greenlock"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Customer Manager, the lazy way
|
||||
|
||||
At the very least you have to implement `find({ servername })`.
|
||||
|
||||
Since this is a very common use case, it's supported out of the box as part of the default manager plugin:
|
||||
|
||||
```js
|
||||
var greenlock = Greenlock.create({
|
||||
packageAgent: pkg.name + '/' + pkg.version,
|
||||
maintainerEmail: 'jon@example.com',
|
||||
notify: notify,
|
||||
find: find
|
||||
});
|
||||
|
||||
// In the simplest case you can ignore all incoming options
|
||||
// and return a single site config in the same format as the config file
|
||||
|
||||
function find(options) {
|
||||
var servername = options.servername; // www.example.com
|
||||
var wildname = options.wildname; // *.example.com
|
||||
return Promise.resolve([
|
||||
{ subject: 'example.com', altnames: ['example.com', 'www.example.com'] }
|
||||
]);
|
||||
}
|
||||
|
||||
function notify(ev, args) {
|
||||
if ('error' === ev || 'warning' === ev) {
|
||||
console.error(ev, args);
|
||||
return;
|
||||
}
|
||||
console.info(ev, args);
|
||||
}
|
||||
```
|
||||
|
||||
If you want to use wildcards or local domains, you must specify the `dns-01` challenge plugin to use:
|
||||
|
||||
```js
|
||||
function find(options) {
|
||||
var subject = options.subject;
|
||||
// may include wildcard
|
||||
var altnames = options.altnames;
|
||||
var wildname = options.wildname; // *.example.com
|
||||
return Promise.resolve([
|
||||
{
|
||||
subject: 'example.com',
|
||||
altnames: ['example.com', 'www.example.com'],
|
||||
challenges: {
|
||||
'dns-01': { module: 'acme-dns-01-namedotcom', apikey: 'xxxx' }
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
### Customer Manager, complete
|
||||
|
||||
To use a fully custom manager, you give the npm package name, or absolute path to the file to load
|
||||
|
||||
```js
|
||||
Greenlock.create({
|
||||
// Greenlock Options
|
||||
maintainerEmail: 'jon@example.com',
|
||||
packageAgent: 'my-package/v2.1.1',
|
||||
notify: notify,
|
||||
|
||||
// file path or npm package name
|
||||
manager: '/path/to/manager.js',
|
||||
// options that get passed to the manager
|
||||
myFooOption: 'whatever'
|
||||
});
|
||||
```
|
||||
|
||||
The manager itself is, again relatively simple:
|
||||
|
||||
- find(options)
|
||||
- set(siteConfig)
|
||||
- remove(options)
|
||||
- defaults(globalOptions) (as setter)
|
||||
- defaults() => globalOptions (as getter)
|
||||
|
||||
`/path/to/manager.js`:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
module.exports.create = function() {
|
||||
var manager = {};
|
||||
|
||||
manager.find = async function({ subject, altnames, renewBefore }) {
|
||||
if (subject) {
|
||||
return getSiteConfigBySubject(subject);
|
||||
}
|
||||
|
||||
if (altnames) {
|
||||
// may include wildcards
|
||||
return getSiteConfigByAnyAltname(altnames);
|
||||
}
|
||||
|
||||
if (renewBefore) {
|
||||
return getSiteConfigsWhereRenewAtIsLessThan(renewBefore);
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
manage.set = function(opts) {
|
||||
// this is called by greenlock.add({ subject, altnames })
|
||||
// it's also called by greenlock._update({ subject, renewAt })
|
||||
|
||||
return mergSiteConfig(subject, opts);
|
||||
};
|
||||
|
||||
manage.remove = function({ subject, altname }) {
|
||||
if (subject) {
|
||||
return removeSiteConfig(subject);
|
||||
}
|
||||
|
||||
return removeFromSiteConfigAndResetRenewAtToZero(altname);
|
||||
};
|
||||
|
||||
// set the global config
|
||||
manage.defaults = function(options) {
|
||||
if (!options) {
|
||||
return getGlobalConfig();
|
||||
}
|
||||
return mergeGlobalConfig(options);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
# ACME Challenge Plugins
|
||||
|
||||
The ACME challenge plugins are just a few simple callbacks:
|
||||
|
||||
- `init`
|
||||
- `zones` (dns-01 only)
|
||||
- `set`
|
||||
- `get`
|
||||
- `remove`
|
||||
|
||||
They are described here:
|
||||
|
||||
- [dns-01 documentation](https://git.rootprojects.org/root/acme-dns-01-test.js)
|
||||
- [http-01 documentation](https://git.rootprojects.org/root/acme-http-01-test.js)
|
||||
|
||||
# Key and Cert Store Plugins
|
||||
|
||||
Again, these are just a few simple callbacks:
|
||||
|
||||
- `certificates.checkKeypair`
|
||||
- `certificates.check`
|
||||
- `certificates.setKeypair`
|
||||
- `certificates.set`
|
||||
- `accounts.checkKeypair`
|
||||
- `accounts.check` (optional)
|
||||
- `accounts.setKeypair`
|
||||
- `accounts.set` (optional)
|
||||
|
||||
The name `check` is used instead of `get` because they only need to return something if it exists. They do not need to fail, nor do they need to generate anything.
|
||||
|
||||
They are described here:
|
||||
|
||||
- [greenlock store documentation](https://git.rootprojects.org/root/greenlock-store-test.js)
|
||||
|
||||
If you are just implenting in-house and are not going to publish a module, you can also do some hack things like this:
|
||||
|
||||
### Custome Store, The hacky / lazy way
|
||||
|
||||
`/path/to/project/my-hacky-store.js`:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
module.exports.create = function(options) {
|
||||
// ex: /path/to/account.ecdsa.jwk.json
|
||||
var accountJwk = require(options.accountJwkPath);
|
||||
// ex: /path/to/privkey.rsa.pem
|
||||
var serverPem = fs.readFileSync(options.serverPemPath, 'ascii');
|
||||
var accounts = {};
|
||||
var certificates = {};
|
||||
var store = { accounts, certificates };
|
||||
|
||||
// bare essential account callbacks
|
||||
accounts.checkKeypair = function() {
|
||||
// ignore all options and just return a single, global keypair
|
||||
|
||||
return Promise.resolve({
|
||||
privateKeyJwk: accountJwk
|
||||
});
|
||||
};
|
||||
accounts.setKeypair = function() {
|
||||
// this will never get called if checkKeypair always returns
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
// bare essential cert and key callbacks
|
||||
certificates.checkKeypair = function() {
|
||||
// ignore all options and just return a global server keypair
|
||||
|
||||
return {
|
||||
privateKeyPem: serverPem
|
||||
};
|
||||
};
|
||||
certificates.setKeypair = function() {
|
||||
// never gets called if checkKeypair always returns an existing key
|
||||
|
||||
return Promise.resolve(null);
|
||||
};
|
||||
|
||||
certificates.check = function(args) {
|
||||
var subject = args.subject;
|
||||
// make a database call or whatever to get a certificate
|
||||
return goGetCertBySubject(subject).then(function() {
|
||||
return {
|
||||
pems: {
|
||||
chain: '<PEM>',
|
||||
cert: '<PEM>'
|
||||
}
|
||||
};
|
||||
});
|
||||
};
|
||||
certificates.set = function(args) {
|
||||
var subject = args.subject;
|
||||
var cert = args.pems.cert;
|
||||
var chain = args.pems.chain;
|
||||
|
||||
// make a database call or whatever to get a certificate
|
||||
return goSaveCert({
|
||||
subject,
|
||||
cert,
|
||||
chain
|
||||
});
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### Using the hacky / lazy store plugin
|
||||
|
||||
That sort of implementation won't pass the test suite, but it'll work just fine a use case where you only have one subscriber email (most of the time),
|
||||
you only have one server key (not recommended, but works), and you only really want to worry about storing cetificates.
|
||||
|
||||
Then you could assign it as the default for all of your sites:
|
||||
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "jon@example.com",
|
||||
"agreeToTerms": true,
|
||||
"sites": {
|
||||
"example.com": {
|
||||
"subject": "example.com",
|
||||
"altnames": ["example.com", "www.example.com"]
|
||||
}
|
||||
},
|
||||
"store": {
|
||||
"module": "/path/to/project/my-hacky-store.js",
|
||||
"accountJwkPath": "/path/to/account.ecdsa.jwk.json",
|
||||
"serverPemPath": "/path/to/privkey.rsa.pem"
|
||||
}
|
||||
}
|
||||
```
|
906
README.md
906
README.md
|
@ -1,556 +1,462 @@
|
|||
# Greenlock v3 on its way (Nov 1st, 2019)
|
||||
# New Documentation & [v2/v3 Migration Guide](https://git.rootprojects.org/root/greenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md)
|
||||
|
||||
Greenlock v3 is in private beta (for backers) and will be available publicly by Nov 1st.
|
||||
Greenlock v3 was just released from private beta **today** (Nov 1st, 2019).
|
||||
|
||||
You can keep an eye for updates on the [campaign page](https://indiegogo.com/at/greenlock) and,
|
||||
if this has been a useful project that's saved you time, [please contribute](https://paypal.me/rootprojects/99).
|
||||
We're still working on the full documentation for this new version,
|
||||
so please be patient.
|
||||
|
||||
To start, check out the
|
||||
[Migration Guide](https://git.rootprojects.org/root/greenlock.js/src/branch/v3/MIGRATION_GUIDE_V2_V3.md).
|
||||
|
||||
!["Greenlock Logo"](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/greenlock-1063x250.png 'Greenlock lock logo and work mark')
|
||||
|
||||
!["Greenlock Function"](https://git.rootprojects.org/root/greenlock.js/raw/branch/master/logo/from-not-secure-to-secure-url-bar.png 'from url bar showing not secure to url bar showing secure')
|
||||
|
||||
# [Greenlock](https://git.rootprojects.org/root/greenlock.js)™ for node.js | a [Root](https://rootprojects.org) project
|
||||
# [Greenlock](https://git.rootprojects.org/root/greenlock.js) is Let's Encrypt for JavaScript
|
||||
|
||||
Greenlock provides Free SSL, Free Wildcard SSL, and Fully Automated HTTPS <br>
|
||||
<small>certificates issued by Let's Encrypt v2 via [ACME](https://git.rootprojects.org/root/acme-v2.js)</small>
|
||||
| Built by [Root](https://rootprojects.org) for [Hub](https://rootprojects.org/hub/)
|
||||
|
||||
!["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")
|
||||
Greenlock™ is an Automated Certificate Management Environement 🔐.
|
||||
|
||||
Greenlock works
|
||||
in the [Commandline](https://git.rootprojects.org/root/greenlock-cli.js) (cli),
|
||||
as a [Web Server](https://git.rootprojects.org/root/greenlock-express.js),
|
||||
in [Web Browsers](https://greenlock.domains) (WebCrypto),
|
||||
and with **node.js** ([npm](https://www.npmjs.com/package/greenlock)).
|
||||
It uses **Let's Encrypt** to generate Free SSL Certificates, including **Wildcard** SSL.
|
||||
It supports **Automated Renewal** of certs for Fully Automated HTTPS.
|
||||
|
||||
# Features
|
||||
It's written in plain JavaScript and works in Node, Browsers, and WebPack.
|
||||
|
||||
- [x] Actively Maintained and Commercially Supported
|
||||
- [x] VanillaJS
|
||||
- [x] Limited Dependencies
|
||||
- [x] MPL-2.0 licensed (great for hobbyists and DIYers)
|
||||
- [x] [Contact us](mailto:support@rootprojects.org?subject=Greenlock%20Commercial%20Support) for Business Support Plans and Commercial LTS Licensing (great for IoT, On-Prem, Web Hosting, etc)
|
||||
- [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 via [acme.js](https://git.rootprojects.org/root/acme-v2.js)
|
||||
- [x] "dry run" with self-diagnostics
|
||||
- [x] ACME draft 12
|
||||
- [x] Let's Encrypt v2
|
||||
- [x] ~Let's Encrypt v1~ (deprecated)
|
||||
- [x] [Commandline](https://git.rootprojects.org/root/greenlock-cli.js) (cli) Utilities
|
||||
- [x] Works with `bash`, `fish`, `zsh`, `cmd.exe`, `PowerShell`, and more
|
||||
- [x] [Browser](https://git.rootprojects.org/root/greenlock.html) Support
|
||||
- [x] Full node.js support, with modules for
|
||||
- [x] [http/https](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples), [Express.js](https://git.rootprojects.org/root/greenlock-express.js), [hapi](https://git.rootprojects.org/root/greenlock-hapi.js), [Koa](https://git.rootprojects.org/root/greenlock-koa.js), [rill](https://git.rootprojects.org/root/greenlock-rill.js), spdy, etc
|
||||
- [x] Great for securing your Raspberry Pi and IoT projects
|
||||
- [x] Extensible Plugin Support
|
||||
- [x] AWS S3, AWS Route53, Azure, CloudFlare, Consul, Digital Ocean, etcd, Redis
|
||||
the easiest way to integrate Let's Encrypt into your projects, products, and infrastructure.
|
||||
|
||||
## Greenlock.js for Middleware
|
||||
- [x] **Wildcard** Certificates
|
||||
- [x] **IoT** Environments
|
||||
- [x] **Enterprise** and **On-Prem**
|
||||
- [x] **Private** Networks
|
||||
- [x] **Localhost** Development
|
||||
- [x] **Web Hosting** Providers
|
||||
- [x] **Commercial** support
|
||||
|
||||
Documentation for using Greenlock with
|
||||
[http/https](https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples),
|
||||
[Express.js](https://git.rootprojects.org/root/greenlock-express.js),
|
||||
[hapi](https://git.rootprojects.org/root/greenlock-hapi.js),
|
||||
[Koa](https://git.rootprojects.org/root/greenlock-koa.js),
|
||||
[rill](https://git.rootprojects.org/root/greenlock-rill.js).
|
||||
We've built it simple enough for Hobbyists, and robust enough for the Enterprise.
|
||||
|
||||
# Table of Contents
|
||||
<!--
|
||||
# Localhost Development
|
||||
|
||||
- Install
|
||||
- **QuickStart**
|
||||
- Simple Examples
|
||||
- Example with ALL OPTIONS
|
||||
- API
|
||||
- Developer API
|
||||
- Change History
|
||||
- License
|
||||
<details>
|
||||
<summary>HTTPS on Localhost</summary>
|
||||
TODO
|
||||
|
||||
# Install
|
||||
</details>
|
||||
|
||||
# WebServer with Automatic HTTPS
|
||||
|
||||
<details>
|
||||
<summary>Learn more about the Greenlock Web Server</summary>
|
||||
TODO
|
||||
</details>
|
||||
|
||||
# Commandline
|
||||
|
||||
<details>
|
||||
<summary>Learn more about the Greenlock CLI</summary>
|
||||
TODO
|
||||
</details>
|
||||
|
||||
-->
|
||||
|
||||
# Easy to Customize
|
||||
|
||||
<!-- greenlock-manager-test => greenlock-manager-custom -->
|
||||
|
||||
<!--
|
||||
- [greenlock.js/examples/](https://git.rootprojects.org/root/greenlock.js/src/branch/master/examples)
|
||||
-->
|
||||
|
||||
<details>
|
||||
<summary>[Custom SSL Cert & Domain Management](https://git.rootprojects.org/root/greenlock-manager-test.js)</summary>
|
||||
|
||||
# SSL Certificate & Domain Management
|
||||
|
||||
Full Docs: https://git.rootprojects.org/root/greenlock-manager-test.js
|
||||
|
||||
This is what keeps the mapping of domains <-> certificates.
|
||||
In many cases it will interact with the same database as the Key & Cert Store, and probably the code as well.
|
||||
|
||||
- set({ subject, altnames, renewAt })
|
||||
- find({ altnames, renewBefore })
|
||||
```js
|
||||
// should return a list of site configs:
|
||||
[
|
||||
{
|
||||
subject: 'example.com',
|
||||
altnames: ['example.com', 'exampleapi.com'],
|
||||
renewAt: 1575197231760
|
||||
},
|
||||
{
|
||||
subject: '*.example.com',
|
||||
altnames: ['*.example.com'],
|
||||
renewAt: 1575197231760,
|
||||
challenges: {
|
||||
'dns-01': {
|
||||
module: 'acme-dns-01-dnsimple',
|
||||
apikey: 'xxxx'
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
```
|
||||
- remove({ subject })
|
||||
- defaults() (both getter and setter)
|
||||
```json
|
||||
{
|
||||
"subscriberEmail": "jane@example.com",
|
||||
"agreeToTerms": true,
|
||||
"challenges": {
|
||||
"http-01": {
|
||||
"module": "acme-http-01-standalone"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>[Custom Key & Cert Storage](https://git.rootprojects.org/root/greenlock-store-test.js)</summary>
|
||||
|
||||
# Key and Certificate Store
|
||||
|
||||
Full Docs: https://git.rootprojects.org/root/greenlock-store-test.js
|
||||
|
||||
This set of callbacks update your service with new certificates and keypairs.
|
||||
|
||||
Account Keys (JWK)
|
||||
|
||||
(though typically you only have one account key - because you only have one subscriber email)
|
||||
|
||||
- accounts.setKeypair({ email, keypair })
|
||||
- accounts.checkKeypair({ email })
|
||||
|
||||
Certificate Keys (JWK + PEM)
|
||||
|
||||
(typically you have one for each set of domains, and each load balancer)
|
||||
|
||||
- certificates.setKeypair({ subject, keypair })
|
||||
- certificates.checkKeypair({ subject })
|
||||
(these are fine to implement the same as above, swapping subject/email)
|
||||
|
||||
Certificate PEMs
|
||||
|
||||
- certificates.set({ subject, pems })
|
||||
- certificates.check({ subject })
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>[Custom ACME HTTP-01 Challenges](https://git.rootprojects.org/root/acme-http-01-test.js)</summary>
|
||||
|
||||
# ACME Challenge HTTP-01 Strategies
|
||||
|
||||
Full Docs: https://git.rootprojects.org/root/acme-http-01-test.js
|
||||
|
||||
This validation and authorization strategy is done over plain HTTP on Port 80.
|
||||
|
||||
These are used to set files containing tokens that Let's Encrypt will fetch from each domain
|
||||
before authorizing a certificate.
|
||||
|
||||
**NOT for Wildcards**.
|
||||
|
||||
- init({ request })
|
||||
- set({ challenge: { type, token, keyAuthorization, challengeUrl } })
|
||||
- get({ challenge: { type, token } })
|
||||
- remove({ challenge: { type, token } })
|
||||
|
||||
<!--
|
||||
TODO: getAcmeHttp01Challenge
|
||||
-->
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>[Custom ACME DNS-01 Challenges](https://git.rootprojects.org/root/acme-dns-01-test.js)</summary>
|
||||
|
||||
# ACME Challenge DNS-01 Strategies
|
||||
|
||||
Full Docs https://git.rootprojects.org/root/acme-dns-01-test.js
|
||||
|
||||
This validation and authorization strategy is done over DNS on UDP and TCP ports 53.
|
||||
|
||||
**For Wildcards**
|
||||
|
||||
These are used to set TXT records containing tokens that Let's Encrypt will fetch for
|
||||
each domain before authorizing a certificate.
|
||||
|
||||
- init({ request })
|
||||
- zones()
|
||||
- set({ challenge: { type, dnsZone, dnsPrefix, dnsHost, keyAuthorizationDigest } })
|
||||
- get({ challenge: { type, dnsZone, dnsPrefix, dnsHost } })
|
||||
- remove({ challenge: { type, dnsZone, dnsPrefix, dnsHost } })
|
||||
|
||||
</details>
|
||||
|
||||
# JavaScript Library
|
||||
|
||||
<!--
|
||||
<details>
|
||||
<summary>Greenlock API (shared among JS implementations)</summary>
|
||||
-->
|
||||
|
||||
### Instantiate
|
||||
|
||||
```js
|
||||
// Creates an instance of greenlock with certain default values
|
||||
|
||||
var gl = Greenlock.create({
|
||||
// Staging for testing environments
|
||||
staging: true,
|
||||
|
||||
// This should be the contact who receives critical bug and security notifications
|
||||
// Optionally, you may receive other (very few) updates, such as important new features
|
||||
maintainerEmail: 'jon@example.com'
|
||||
});
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| --------------- | ------------------------------------------------------------------------------------ |
|
||||
| maintainerEmail | the developer contact for critical bug and security notifications |
|
||||
| packageAgent | if you publish your package for others to use, `require('./package.json').name` here |
|
||||
|
||||
<!--
|
||||
| maintainerUpdates | (default: false) receive occasional non-critical notifications |
|
||||
maintainerUpdates: true // default: false
|
||||
-->
|
||||
|
||||
### Add Approved Domains
|
||||
|
||||
```js
|
||||
greenlock.manager.defaults({
|
||||
// The "Let's Encrypt Subscriber" (often the same as the maintainer)
|
||||
// NOT the end customer (except where that is also the maintainer)
|
||||
subscriberEmail: 'jon@example.com',
|
||||
agreeToTerms: true
|
||||
challenges: {
|
||||
"http-01": {
|
||||
module: "acme-http-01-webroot",
|
||||
webroot: "/path/to/webroot"
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| agreeToTerms | (default: false) either 'true' or a function that presents the Terms of Service and returns it once accepted |
|
||||
| challenges['http-01'] | provide an http-01 challenge module |
|
||||
| challenges['dns-01'] | provide a dns-01 challenge module |
|
||||
| challenges['tls-alpn-01'] | provide a tls-alpn-01 challenge module |
|
||||
| challenges[type].module | the name of your challenge module |
|
||||
| challenges[type].xxxx | module-specific options |
|
||||
| servername | the default servername to use for non-sni requests (many IoT clients) |
|
||||
| subscriberEmail | the contact who agrees to the Let's Encrypt Subscriber Agreement and the Greenlock Terms of Service<br>this contact receives renewal failure notifications |
|
||||
| store | override the default storage module |
|
||||
| store.module | the name of your storage module |
|
||||
| store.xxxx | options specific to your storage module |
|
||||
|
||||
<!--
|
||||
|
||||
| serverId | an arbitrary name to distinguish this server within a cluster of servers |
|
||||
|
||||
-->
|
||||
|
||||
```js
|
||||
gl.add({
|
||||
subject: 'example.com',
|
||||
altnames: ['example.com', 'www.example.com', 'exampleapi.com']
|
||||
});
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| --------------- | -------------------------------------------------------------------------------------------- |
|
||||
| subject | the first domain on, and identifier of the certificate |
|
||||
| altnames | first domain, plus additional domains<br>note: the order should always be the same |
|
||||
| subscriberEmail | if different from the default (i.e. multi-tenant, whitelabel) |
|
||||
| challenges | (same as main config) use if this site needs to use non-default http-01 or dns-01 validation |
|
||||
|
||||
### Retrieve Certificates (One-Off)
|
||||
|
||||
**Disclaimer**: This is only intended for testing, demos, and SNICallback
|
||||
(in [Greenlock Express](https://git.rootprojects.org/root/greenlock-express.js)).
|
||||
|
||||
Greenlock is intended to be left running to allow it to fetech and renew certifictates automatically.
|
||||
|
||||
It is intended that you use the `store` callbacks to new certificates instantly as soon as they renew.
|
||||
This also protects you from accidentally stampeding the Let's Encrypt API with hundreds (or thousands)
|
||||
of certificate requests.
|
||||
|
||||
- [Store Callback Documentation](https://git.rootprojects.org/root/greenlock-store-test.js)
|
||||
|
||||
```js
|
||||
return greenlock.get({ servername }).then(function(site) {
|
||||
if (!site) {
|
||||
console.log(servername + ' was not found in any site config');
|
||||
return;
|
||||
}
|
||||
|
||||
var privkey = site.pems.privkey;
|
||||
var fullchain = site.pems.cert + '\n' + site.pems.chain + '\n';
|
||||
console.log(privkey);
|
||||
console.log(fullchain);
|
||||
});
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| ---------- | ------------------------------------------------------ |
|
||||
| servername | the first domain on, and identifier of the certificate |
|
||||
|
||||
### Renew Certificates
|
||||
|
||||
This will renew only domains that have reached their `renewAt` or are within the befault `renewOffset`.
|
||||
|
||||
**Note**: This runs at regular intervals, multiple times a day, in the background.
|
||||
You are not required to call it. If you implement the `store` callbacks, the certificates
|
||||
will automatically be saved (and if you don't implement them, they all get saved to disk).
|
||||
|
||||
```js
|
||||
return greenlock.renew({}).then(function(results) {
|
||||
results.forEach(function(site) {
|
||||
if (site.error) {
|
||||
console.error(site.subject, site.error);
|
||||
return;
|
||||
}
|
||||
console.log('Renewed certificate for', site.subject, site.altnames);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| ----------- | ---- | ------------------------------------------------------------------------------- |
|
||||
| (optional) | | ALL parameters are optional, but some should be paired |
|
||||
| force | bool | force silly options, such as tiny durations |
|
||||
| renewBefore | ms | Check domains that are scheduled to renew before the given date in milliseconds |
|
||||
|
||||
<!--
|
||||
| issuedBefore | ms | Check domains issued before the given date in milliseconds |
|
||||
| expiresBefore | ms | Check domains that expire before the given date in milliseconds |
|
||||
-->
|
||||
|
||||
<!--
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Node.js</summary>
|
||||
-->
|
||||
|
||||
# Node
|
||||
|
||||
```bash
|
||||
npm install --save greenlock@2.x
|
||||
npm install --save @root/greenlock
|
||||
npm install --save greenlock-manager-fs
|
||||
npm install --save greenlock-store-fs
|
||||
npm install --save acme-http-01-standalone
|
||||
```
|
||||
|
||||
**Optional** for _more efficient_ RSA key generation you must use node v10.12+
|
||||
<small>(important for those on ARM devices like Raspberry Pi)</small>
|
||||
<!--
|
||||
|
||||
### Production vs Staging
|
||||
TODO
|
||||
|
||||
If at first you don't succeed, stop and switch to staging.
|
||||
</details>
|
||||
|
||||
I've implemented a "dry run" loopback test with self diagnostics
|
||||
so it's pretty safe to start off with the production URLs
|
||||
and be far less likely to hit the bad request rate limits.
|
||||
|
||||
However, if your first attempt to get a certificate fails
|
||||
I'd recommend switching to the staging acme server to debug -
|
||||
unless you're very clear on what the failure was and how to fix it.
|
||||
|
||||
```
|
||||
{ server: 'https://acme-staging-v02.api.letsencrypt.org/directory' }
|
||||
```
|
||||
|
||||
### QuickStart Screencast
|
||||
|
||||
Watch the QuickStart demonstration: [https://youtu.be/e8vaR4CEZ5s](https://youtu.be/e8vaR4CEZ5s)
|
||||
|
||||
<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
|
||||
|
||||
#### Production Configuration (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
|
||||
|
||||
# Easy as 1, 2, 3... 4
|
||||
|
||||
Greenlock is built to incredibly easy to use, without sacrificing customization or extensibility.
|
||||
|
||||
The following examples range from just a few lines of code for getting started,
|
||||
to more robust examples that you might start with for an enterprise-grade use of the ACME api.
|
||||
|
||||
- Automatic HTTPS (for single sites)
|
||||
- Fully Automatic HTTPS (for multi-domain vhosts)
|
||||
- Manual HTTPS (for API integration)
|
||||
|
||||
## Automatic HTTPS
|
||||
|
||||
**Note**: For (fully) automatic HTTPS you may prefer
|
||||
the [Express.js module](https://git.rootprojects.org/root/greenlock-express.js)
|
||||
|
||||
This works for most people, but it's not as fun as some of the other examples.
|
||||
|
||||
Great when
|
||||
|
||||
- [x] You only need a limited number of certificates
|
||||
- [x] You want to use the bare node http and https modules without fluff
|
||||
<details>
|
||||
<summary>Express.js</summary>
|
||||
|
||||
```js
|
||||
////////////////////
|
||||
// INIT GREENLOCK //
|
||||
////////////////////
|
||||
|
||||
var greenlock = require('greenlock').create({
|
||||
email: 'user@example.com', // IMPORTANT: Change email and domains
|
||||
agreeTos: true, // Accept Let's Encrypt v2 Agreement
|
||||
configDir: '~/.config/acme', // A writable folder (a non-fs plugin)
|
||||
|
||||
communityMember: true, // Get (rare) non-mandatory updates about cool greenlock-related stuff (default false)
|
||||
securityUpdates: true // Important and mandatory notices related to security or breaking API changes (default true)
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
////////////////////
|
||||
// CREATE SERVERS //
|
||||
////////////////////
|
||||
|
||||
var redir = require('redirect-https')();
|
||||
require('http')
|
||||
.createServer(greenlock.middleware(redir))
|
||||
.listen(80);
|
||||
|
||||
require('spdy')
|
||||
.createServer(greenlock.tlsOptions, function(req, res) {
|
||||
res.end('Hello, Secure World!');
|
||||
})
|
||||
.listen(443);
|
||||
```
|
||||
|
||||
## Fully Automatic HTTPS
|
||||
|
||||
**Note**: For (fully) automatic HTTPS you may prefer
|
||||
the [Express.js module](https://git.rootprojects.org/root/greenlock-express.js)
|
||||
|
||||
Great when
|
||||
|
||||
- [x] You have a growing number of domains
|
||||
- [x] You're integrating into your own hosting solution
|
||||
- [x] Customize ACME http-01 or dns-01 challenge
|
||||
|
||||
```js
|
||||
////////////////////
|
||||
// INIT GREENLOCK //
|
||||
////////////////////
|
||||
|
||||
var path = require('path');
|
||||
var os = require('os');
|
||||
var Greenlock = require('greenlock');
|
||||
|
||||
var greenlock = Greenlock.create({
|
||||
version: 'draft-12',
|
||||
server: 'https://acme-v02.api.letsencrypt.org/directory',
|
||||
|
||||
// Use the approveDomains callback to set per-domain config
|
||||
// (default: approve any domain that passes self-test of built-in challenges)
|
||||
approveDomains: approveDomains,
|
||||
|
||||
// the default servername to use when the client doesn't specify
|
||||
servername: 'example.com',
|
||||
|
||||
// If you wish to replace the default account and domain key storage plugin
|
||||
store: require('le-store-fs').create({
|
||||
configDir: path.join(os.homedir(), 'acme/etc'),
|
||||
webrootPath: '/tmp/acme-challenges'
|
||||
})
|
||||
});
|
||||
|
||||
/////////////////////
|
||||
// APPROVE DOMAINS //
|
||||
/////////////////////
|
||||
|
||||
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
|
||||
|
||||
// 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 };
|
||||
|
||||
// The domains being approved for the first time are listed in opts.domains
|
||||
// Certs being renewed are listed in certs.altnames
|
||||
// certs.domains;
|
||||
// certs.altnames;
|
||||
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 });
|
||||
}
|
||||
|
||||
////////////////////
|
||||
// CREATE SERVERS //
|
||||
////////////////////
|
||||
|
||||
var redir = require('redirect-https')();
|
||||
require('http')
|
||||
.createServer(greenlock.middleware(redir))
|
||||
.listen(80);
|
||||
|
||||
require('https')
|
||||
.createServer(greenlock.tlsOptions, function(req, res) {
|
||||
res.end('Hello, Secure World!');
|
||||
})
|
||||
.listen(443);
|
||||
```
|
||||
|
||||
## Manual HTTPS
|
||||
|
||||
Here's a taste of the API that you might use if building a commandline tool or API integration
|
||||
that doesn't use node's SNICallback.
|
||||
|
||||
```
|
||||
|
||||
|
||||
/////////////////////
|
||||
// SET USER PARAMS //
|
||||
/////////////////////
|
||||
|
||||
var opts = {
|
||||
domains: [ 'example.com' // CHANGE EMAIL AND DOMAINS
|
||||
, 'www.example.com' ]
|
||||
, email: 'user@example.com'
|
||||
, agreeTos: true // Accept Let's Encrypt v2 Agreement
|
||||
, communityMember: true // Help make Greenlock better by submitting
|
||||
// stats and getting updates
|
||||
};
|
||||
|
||||
|
||||
////////////////////
|
||||
// INIT GREENLOCK //
|
||||
////////////////////
|
||||
|
||||
var greenlock = require('greenlock').create({
|
||||
version: 'draft-12'
|
||||
, server: 'https://acme-v02.api.letsencrypt.org/directory'
|
||||
, configDir: '/tmp/acme/etc'
|
||||
});
|
||||
|
||||
|
||||
///////////////////
|
||||
// GET TLS CERTS //
|
||||
///////////////////
|
||||
|
||||
greenlock.register(opts).then(function (certs) {
|
||||
console.log(certs);
|
||||
// privkey, cert, chain, expiresAt, issuedAt, subject, altnames
|
||||
}, function (err) {
|
||||
console.error(err);
|
||||
});
|
||||
```
|
||||
|
||||
The domain key and ssl certificates you get back can be used in a webserver like this:
|
||||
|
||||
```js
|
||||
var tlsOptions = {
|
||||
key: certs.privkey,
|
||||
cert: certs.cert + '\r\n' + certs.chain
|
||||
};
|
||||
require('https')
|
||||
.createServer(tlsOptions, function(req, res) {
|
||||
res.end('Hello, Secure World!');
|
||||
})
|
||||
.listen(443);
|
||||
```
|
||||
|
||||
# Example with ALL OPTIONS
|
||||
|
||||
The configuration consists of 3 components:
|
||||
|
||||
- Storage Backend (search npm for projects starting with 'le-store-')
|
||||
- ACME Challenge Handlers (search npm for projects starting with 'le-challenge-')
|
||||
- Letsencryt Config (this is all you)
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
var Greenlock = require('greenlock');
|
||||
var greenlock;
|
||||
var Greenlock = require(@root/greenlock-express);
|
||||
|
||||
var greenlock = Greenlock.create({
|
||||
// for security and critical bug notices
|
||||
maintainerEmail: 'jon@example.com'
|
||||
|
||||
// Storage Backend
|
||||
var leStore = require('greenlock-store-fs').create({
|
||||
configDir: '~/acme/etc' // or /etc/letsencrypt or wherever
|
||||
, debug: false
|
||||
});
|
||||
|
||||
|
||||
// ACME Challenge Handlers
|
||||
var leHttpChallenge = require('le-challenge-fs').create({
|
||||
webrootPath: '~/acme/var/' // or template string such as
|
||||
, debug: false // '/srv/www/:hostname/.well-known/acme-challenge'
|
||||
});
|
||||
|
||||
|
||||
function leAgree(opts, agreeCb) {
|
||||
// opts = { email, domains, tosUrl }
|
||||
agreeCb(null, opts.tosUrl);
|
||||
}
|
||||
|
||||
greenlock = Greenlock.create({
|
||||
version: 'draft-12' // 'draft-12' or 'v01'
|
||||
// 'draft-12' is for Let's Encrypt v2 otherwise known as ACME draft 12
|
||||
// 'v02' is an alias for 'draft-12'
|
||||
// 'v01' is for the pre-spec Let's Encrypt v1
|
||||
//
|
||||
// staging API
|
||||
//server: 'https://acme-staging-v02.api.letsencrypt.org/directory'
|
||||
|
||||
//
|
||||
// production API
|
||||
server: 'https://acme-v02.api.letsencrypt.org/directory'
|
||||
|
||||
, store: leStore // handles saving of config, accounts, and certificates
|
||||
, challenges: {
|
||||
'http-01': leHttpChallenge // handles /.well-known/acme-challege keys and tokens
|
||||
}
|
||||
, challengeType: 'http-01' // default to this challenge type
|
||||
, agreeToTerms: leAgree // hook to allow user to view and accept LE TOS
|
||||
//, sni: require('le-sni-auto').create({}) // handles sni callback
|
||||
|
||||
// renewals happen at a random time within this window
|
||||
, renewWithin: 14 * 24 * 60 * 60 * 1000 // certificate renewal may begin at this time
|
||||
, renewBy: 10 * 24 * 60 * 60 * 1000 // certificate renewal should happen by this time
|
||||
|
||||
, debug: false
|
||||
//, log: function (debug) {console.log.apply(console, args);} // handles debug outputs
|
||||
});
|
||||
|
||||
|
||||
// If using express you should use the middleware
|
||||
// app.use('/', greenlock.middleware());
|
||||
//
|
||||
// Otherwise you should see the test file for usage of this:
|
||||
// greenlock.challenges['http-01'].get(opts.domain, key, val, done)
|
||||
|
||||
|
||||
|
||||
// Check in-memory cache of certificates for the named domain
|
||||
greenlock.check({ domains: [ 'example.com' ] }).then(function (results) {
|
||||
if (results) {
|
||||
// we already have certificates
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Register Certificate manually
|
||||
greenlock.register({
|
||||
|
||||
domains: ['example.com'] // CHANGE TO YOUR DOMAIN (list for SANS)
|
||||
, email: 'user@email.com' // CHANGE TO YOUR EMAIL
|
||||
, agreeTos: '' // set to tosUrl string (or true) to pre-approve (and skip agreeToTerms)
|
||||
, rsaKeySize: 2048 // 2048 or higher
|
||||
, challengeType: 'http-01' // http-01, tls-sni-01, or dns-01
|
||||
|
||||
}).then(function (results) {
|
||||
|
||||
console.log('success');
|
||||
|
||||
}, function (err) {
|
||||
|
||||
// Note: you must either use greenlock.middleware() with express,
|
||||
// manually use greenlock.challenges['http-01'].get(opts, domain, key, val, done)
|
||||
// or have a webserver running and responding
|
||||
// to /.well-known/acme-challenge at `webrootPath`
|
||||
console.error('[Error]: node-greenlock/examples/standalone');
|
||||
console.error(err.stack);
|
||||
|
||||
});
|
||||
|
||||
// for
|
||||
maintainerNewsletter: true
|
||||
});
|
||||
```
|
||||
|
||||
Here's what `results` looks like:
|
||||
</details>
|
||||
|
||||
```javascript
|
||||
{ privkey: '' // PEM encoded private key
|
||||
, cert: '' // PEM encoded cert
|
||||
, chain: '' // PEM encoded intermediate cert
|
||||
, issuedAt: 0 // notBefore date (in ms) parsed from cert
|
||||
, expiresAt: 0 // notAfter date (in ms) parsed from cert
|
||||
, subject: '' // example.com
|
||||
, altnames: [] // example.com,www.example.com
|
||||
}
|
||||
```
|
||||
<details>
|
||||
<summary>WebPack</summary>
|
||||
TODO
|
||||
</details>
|
||||
|
||||
## API
|
||||
<details>
|
||||
<summary>VanillaJS for Browsers</summary>
|
||||
TODO
|
||||
</details>
|
||||
|
||||
The full end-user API is exposed in the example above and includes all relevant options.
|
||||
-->
|
||||
|
||||
```
|
||||
greenlock.register(opts)
|
||||
greenlock.check(opts)
|
||||
```
|
||||
# HTTP-01 & DNS-01 Integrations
|
||||
|
||||
### Helper Functions
|
||||
For Public Web Servers running on a VPS, the **default HTTP-01 challenge plugin**
|
||||
will work just fine for most people.
|
||||
|
||||
We do expose a few helper functions:
|
||||
However, for
|
||||
|
||||
- Greenlock.validDomain(hostname) // returns '' or the hostname string if it's a valid ascii or punycode domain name
|
||||
- **Wildcard Certificates**
|
||||
- **IoT Environments**
|
||||
- **Enterprise On-Prem**
|
||||
- **Private Networks**
|
||||
|
||||
TODO fetch domain tld list
|
||||
Greenlock provides an easy way to integrate Let's Encrypt with your existing services
|
||||
through a variety of **DNS-01** infrastructure
|
||||
|
||||
### Template Strings
|
||||
Why
|
||||
Typically file propagation is faster and more reliably than DNS propagation.
|
||||
Therefore, http-01 will be preferred to dns-01 except when wildcards or **private domains** are in use.
|
||||
|
||||
The following variables will be tempalted in any strings passed to the options object:
|
||||
http-01 will only be supplied as a defaut if no other challenge is provided.
|
||||
|
||||
- `~/` replaced with `os.homedir()` i.e. `/Users/aj`
|
||||
- `:hostname` replaced with the first domain in the list i.e. `example.com`
|
||||
You can use ACME (Let's Encrypt) with several ready-made integrations
|
||||
|
||||
### Dangerous Options
|
||||
# Ready-made Integrations
|
||||
|
||||
By default SNI is made to lowercase and is automatically rejected if it contains invalid characters for a domain.
|
||||
This behavior can be modified:
|
||||
Greenlock Express integrates between Let's Encrypt's ACME Challenges and many popular services.
|
||||
|
||||
- `__dns_allow_dangerous_names` allow SNI names like "Robert'); DROP TABLE Students;"
|
||||
- `__dns_preserve_case` passes SNI names such as "ExAMpLE.coM" without converting to lower case
|
||||
| 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.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) | - |
|
||||
|
||||
## Developer API
|
||||
Search `acme-http-01-` or `acme-dns-01-` on npm to find more.
|
||||
|
||||
If you are developing an `le-store-*` or `le-challenge-*` plugin you need to be aware of
|
||||
additional internal API expectations.
|
||||
# Commercial Support
|
||||
|
||||
**IMPORTANT**:
|
||||
Do you need...
|
||||
|
||||
Use `v3.0.0` as your initial version - NOT v0.1.0 and NOT v1.0.0 and NOT v2.0.0.
|
||||
This is to indicate that your module is compatible with v3 (v2.7+) of node-greenlock.
|
||||
- training?
|
||||
- specific features?
|
||||
- different integrations?
|
||||
- bugfixes, on _your_ timeline?
|
||||
- custom code, built by experts?
|
||||
- commercial support and licensing?
|
||||
|
||||
Since the public API for your module is defined by node-greenlock the major version
|
||||
should be kept in sync.
|
||||
You're welcome to [contact us](mailto:aj@therootcompany.com) in regards to IoT, On-Prem,
|
||||
Enterprise, and Internal installations, integrations, and deployments.
|
||||
|
||||
### store implementation
|
||||
We have both commercial support and commercial licensing available.
|
||||
|
||||
See [greenlock-store-test](https://git.rootprojects.org/root/greenlock-store-test.js)
|
||||
and [greenlock-store-fs](https://git.rootprojects.org/root/greenlock-store-fs.js)
|
||||
|
||||
- accounts.
|
||||
- checkKeypair(opts)
|
||||
- check(opts)
|
||||
- setKeypair(opts)
|
||||
- set(opts)
|
||||
- certificates.
|
||||
- checkKeypair(opts)
|
||||
- check(opts)
|
||||
- setKeypair(opts)
|
||||
- set(opts)
|
||||
|
||||
### challenge implementation
|
||||
|
||||
See [greenlock-challenge-test](https://git.rootprojects.org/root/greenlock-challenge-test.js),
|
||||
[acme-http-01-cli](https://git.rootprojects.org/root/acme-http-01-cli.js),
|
||||
and [acme-dns-01-cli](https://git.rootprojects.org/root/acme-dns-01-cli.js)
|
||||
|
||||
- `.set(opts);`
|
||||
- `.get(opts);`
|
||||
- `.remove(opts);`
|
||||
|
||||
# Change History
|
||||
|
||||
- v2.7
|
||||
- API: transitional for v3 API (Promies, async/await)
|
||||
- Security: Zero external dependencies
|
||||
- Plugins: `greenlock-store-fs` replaces `le-store-certbot` as the default storage plugin
|
||||
- Features: Full wildcard support
|
||||
- Licensing: Commercial licensing and support plans now available
|
||||
- v2.6
|
||||
- better defaults, fewer explicit options
|
||||
- better pre-flight self-tests, explicit domains not required
|
||||
- v2.5
|
||||
- bugfix JWK (update rsa-compat)
|
||||
- eliminate all external non-optional dependencies
|
||||
- v2.4
|
||||
- v2.4.3 - add security updates (default true) independent of community updates (default false)
|
||||
- v2.2 - Let's Encrypt v2 Support
|
||||
- v2.2.11 - documentation updates
|
||||
- v2.2.10 - don't let SNICallback swallow approveDomains errors 6286883fc2a6ebfff711a540a2e4d92f3ac2907c
|
||||
- v2.2.8 - communityMember option support
|
||||
- v2.2.7 - bugfix for wildcard support
|
||||
- v2.2.5 - node v6.x compat
|
||||
- v2.2.4 - don't promisify all of `dns`
|
||||
- v2.2.3 - `renewWithin` default to 14 days
|
||||
- v2.2.2 - replace git dependency with npm
|
||||
- v2.2.1 - April 2018 **Let's Encrypt v2** support
|
||||
- v2.1.17 - Nov 5th 2017 migrate back to personal repo
|
||||
- v2.1.9 - Jan 18th 2017 renamed to greenlock
|
||||
- v2.0.2 - Aug 9th 2016 update readme
|
||||
- v2.0.1 - Aug 9th 2016
|
||||
- major refactor
|
||||
- simplified API
|
||||
- modular plugins
|
||||
- knock out bugs
|
||||
- v1.5.0 now using letiny-core v2.0.0 and rsa-compat
|
||||
- v1.4.x I can't remember... but it's better!
|
||||
- v1.1.0 Added letiny-core, removed node-letsencrypt-python
|
||||
- v1.0.2 Works with node-letsencrypt-python
|
||||
- v1.0.0 Thar be dragons
|
||||
|
||||
# Commercial Licensing
|
||||
|
||||
As the number of businesses using Greenlock commercially has increased, we've become more aware of the need for quick-turnaround support and licenses that allow for local private modifications. Currently we offer LTS support and commercial licensing models for IoT, On-Prem, and Web Hosting. Please [contact us](mailto:support@rootprojects.org?subject=Greenlock%20Commercial%20Support) to learn more.
|
||||
|
||||
Our [trademark policy](https://therootcompany.com/legal/#trademark) is pretty much "attribute, but don't confuse". Your users should understand that your product _uses_ Greenlock and not be confused to think that it _is_ Greenlock.
|
||||
We also offer consulting for all-things-ACME and Let's Encrypt.
|
||||
|
||||
# Legal & Rules of the Road
|
||||
|
||||
|
@ -558,7 +464,7 @@ Greenlock™ is a [trademark](https://rootprojects.org/legal/#trademark) of
|
|||
|
||||
The rule of thumb is "attribute, but don't confuse". For example:
|
||||
|
||||
> Built with [Greenlock.js](https://git.rootprojects.org/root/greenlock.js) (a [Root](https://rootprojects.org) project).
|
||||
> Built with [Greenlock Express](https://git.rootprojects.org/root/greenlock.js) (a [Root](https://rootprojects.org) project).
|
||||
|
||||
Please [contact us](mailto:aj@therootcompany.com) if you have any questions in regards to our trademark,
|
||||
attribution, and/or visible source policies. We want to build great software and a great community.
|
||||
|
|
|
@ -0,0 +1,219 @@
|
|||
'use strict';
|
||||
|
||||
var A = module.exports;
|
||||
var U = require('./utils.js');
|
||||
var E = require('./errors.js');
|
||||
|
||||
var pending = {};
|
||||
|
||||
A._getOrCreate = function(gnlck, mconf, db, acme, args) {
|
||||
var email = args.subscriberEmail || mconf.subscriberEmail;
|
||||
|
||||
if (!email) {
|
||||
throw E.NO_SUBSCRIBER('get account', args.subject);
|
||||
}
|
||||
|
||||
// TODO send welcome message with benefit info
|
||||
return U._validMx(email)
|
||||
.catch(function() {
|
||||
throw E.NO_SUBSCRIBER('get account', args.subcriberEmail);
|
||||
})
|
||||
.then(function() {
|
||||
if (pending[email]) {
|
||||
return pending[email];
|
||||
}
|
||||
|
||||
pending[email] = A._rawGetOrCreate(
|
||||
gnlck,
|
||||
mconf,
|
||||
db,
|
||||
acme,
|
||||
args,
|
||||
email
|
||||
)
|
||||
.catch(function(e) {
|
||||
delete pending[email];
|
||||
throw e;
|
||||
})
|
||||
.then(function(result) {
|
||||
delete pending[email];
|
||||
return result;
|
||||
});
|
||||
|
||||
return pending[email];
|
||||
});
|
||||
};
|
||||
|
||||
// What we really need out of this is the private key and the ACME "key" id
|
||||
A._rawGetOrCreate = function(gnlck, mconf, db, acme, args, email) {
|
||||
var p;
|
||||
if (db.check) {
|
||||
p = A._checkStore(gnlck, mconf, db, acme, args, email);
|
||||
} else {
|
||||
p = Promise.resolve(null);
|
||||
}
|
||||
|
||||
return p.then(function(fullAccount) {
|
||||
if (!fullAccount) {
|
||||
return A._newAccount(gnlck, mconf, db, acme, args, email, null);
|
||||
}
|
||||
|
||||
if (fullAccount.keypair && fullAccount.key && fullAccount.key.kid) {
|
||||
return fullAccount;
|
||||
}
|
||||
|
||||
return A._newAccount(gnlck, mconf, db, acme, args, email, fullAccount);
|
||||
});
|
||||
};
|
||||
|
||||
A._newAccount = function(gnlck, mconf, db, acme, args, email, fullAccount) {
|
||||
var keyType = args.accountKeyType || mconf.accountKeyType;
|
||||
var query = {
|
||||
subject: args.subject,
|
||||
email: email,
|
||||
subscriberEmail: email,
|
||||
customerEmail: args.customerEmail,
|
||||
account: fullAccount || {},
|
||||
directoryUrl:
|
||||
args.directoryUrl ||
|
||||
mconf.directoryUrl ||
|
||||
gnlck._defaults.directoryUrl
|
||||
};
|
||||
|
||||
return U._getOrCreateKeypair(db, args.subject, query, keyType).then(
|
||||
function(kresult) {
|
||||
var keypair = kresult.keypair;
|
||||
var accReg = {
|
||||
subscriberEmail: email,
|
||||
agreeToTerms:
|
||||
args.agreeToTerms ||
|
||||
mconf.agreeToTerms ||
|
||||
gnlck._defaults.agreeToTerms,
|
||||
accountKey: keypair.privateKeyJwk || keypair.private,
|
||||
debug: args.debug
|
||||
};
|
||||
return acme.accounts.create(accReg).then(function(receipt) {
|
||||
var reg = {
|
||||
keypair: keypair,
|
||||
receipt: receipt,
|
||||
// shudder... not actually a KeyID... but so it is called anyway...
|
||||
kid:
|
||||
receipt &&
|
||||
receipt.key &&
|
||||
(receipt.key.kid || receipt.kid),
|
||||
email: args.email,
|
||||
subscriberEmail: email,
|
||||
customerEmail: args.customerEmail
|
||||
};
|
||||
|
||||
var keyP;
|
||||
if (kresult.exists) {
|
||||
keyP = Promise.resolve();
|
||||
} else {
|
||||
query.keypair = keypair;
|
||||
query.receipt = receipt;
|
||||
/*
|
||||
query.server = gnlck._defaults.directoryUrl.replace(
|
||||
/^https?:\/\//i,
|
||||
''
|
||||
);
|
||||
*/
|
||||
keyP = db.setKeypair(query, keypair);
|
||||
}
|
||||
|
||||
return keyP
|
||||
.then(function() {
|
||||
if (!db.set) {
|
||||
return Promise.resolve({
|
||||
keypair: keypair
|
||||
});
|
||||
}
|
||||
return db.set(
|
||||
{
|
||||
// id to be set by Store
|
||||
email: email,
|
||||
subscriberEmail: email,
|
||||
customerEmail: args.customerEmail,
|
||||
agreeTos: true,
|
||||
agreeToTerms: true,
|
||||
directoryUrl:
|
||||
args.directoryUrl ||
|
||||
mconf.directoryUrl ||
|
||||
gnlck._defaults.directoryUrl
|
||||
/*
|
||||
server: gnlck._defaults.directoryUrl.replace(
|
||||
/^https?:\/\//i,
|
||||
''
|
||||
)
|
||||
*/
|
||||
},
|
||||
reg
|
||||
);
|
||||
})
|
||||
.then(function(fullAccount) {
|
||||
if (fullAccount && 'object' !== typeof fullAccount) {
|
||||
throw new Error(
|
||||
"accounts.set should either return 'null' or an object with an 'id' string"
|
||||
);
|
||||
}
|
||||
|
||||
if (!fullAccount) {
|
||||
fullAccount = {};
|
||||
}
|
||||
fullAccount.keypair = keypair;
|
||||
if (!fullAccount.key) {
|
||||
fullAccount.key = {};
|
||||
}
|
||||
fullAccount.key.kid = reg.kid;
|
||||
|
||||
return fullAccount;
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
A._checkStore = function(gnlck, mconf, db, acme, args, email) {
|
||||
if ((args.domain || args.domains) && !args.subject) {
|
||||
console.warn("use 'subject' instead of 'domain'");
|
||||
args.subject = args.domain;
|
||||
}
|
||||
|
||||
var account = args.account;
|
||||
if (!account) {
|
||||
account = {};
|
||||
}
|
||||
|
||||
if (args.accountKey) {
|
||||
console.warn(
|
||||
'rather than passing accountKey, put it directly into your account key store'
|
||||
);
|
||||
// TODO we probably don't need this
|
||||
return U._importKeypair(args.accountKey);
|
||||
}
|
||||
|
||||
if (!db.check) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
return db
|
||||
.check({
|
||||
//keypair: undefined,
|
||||
//receipt: undefined,
|
||||
email: email,
|
||||
subscriberEmail: email,
|
||||
customerEmail: args.customerEmail || mconf.customerEmail,
|
||||
account: account,
|
||||
directoryUrl:
|
||||
args.directoryUrl ||
|
||||
mconf.directoryUrl ||
|
||||
gnlck._defaults.directoryUrl
|
||||
})
|
||||
.then(function(fullAccount) {
|
||||
if (!fullAccount) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return fullAccount;
|
||||
});
|
||||
};
|
|
@ -0,0 +1,378 @@
|
|||
'use strict';
|
||||
|
||||
var mkdirp = require('@root/mkdirp');
|
||||
var cli = require('./cli.js');
|
||||
|
||||
cli.parse({
|
||||
'directory-url': [
|
||||
false,
|
||||
' ACME Directory Resource URL',
|
||||
'string',
|
||||
'https://acme-v02.api.letsencrypt.org/directory',
|
||||
'server,acme-url'
|
||||
],
|
||||
email: [
|
||||
false,
|
||||
' Email used for registration and recovery contact. (default: null)',
|
||||
'email'
|
||||
],
|
||||
'agree-tos': [
|
||||
false,
|
||||
" Agree to the Greenlock and Let's Encrypt Subscriber Agreements",
|
||||
'boolean',
|
||||
false
|
||||
],
|
||||
'community-member': [
|
||||
false,
|
||||
' Submit stats to and get updates from Greenlock',
|
||||
'boolean',
|
||||
false
|
||||
],
|
||||
domains: [
|
||||
false,
|
||||
' Domain names to apply. For multiple domains you can enter a comma separated list of domains as a parameter. (default: [])',
|
||||
'string'
|
||||
],
|
||||
'renew-offset': [
|
||||
false,
|
||||
' Positive (time after issue) or negative (time before expiry) offset, such as 30d or -45d',
|
||||
'string',
|
||||
'45d'
|
||||
],
|
||||
'renew-within': [
|
||||
false,
|
||||
' (ignored) use renew-offset instead',
|
||||
'ignore',
|
||||
undefined
|
||||
],
|
||||
'cert-path': [
|
||||
false,
|
||||
' Path to where new cert.pem is saved',
|
||||
'string',
|
||||
':configDir/live/:hostname/cert.pem'
|
||||
],
|
||||
'fullchain-path': [
|
||||
false,
|
||||
' Path to where new fullchain.pem (cert + chain) is saved',
|
||||
'string',
|
||||
':configDir/live/:hostname/fullchain.pem'
|
||||
],
|
||||
'bundle-path': [
|
||||
false,
|
||||
' Path to where new bundle.pem (fullchain + privkey) is saved',
|
||||
'string',
|
||||
':configDir/live/:hostname/bundle.pem'
|
||||
],
|
||||
'chain-path': [
|
||||
false,
|
||||
' Path to where new chain.pem is saved',
|
||||
'string',
|
||||
':configDir/live/:hostname/chain.pem'
|
||||
],
|
||||
'privkey-path': [
|
||||
false,
|
||||
' Path to where privkey.pem is saved',
|
||||
'string',
|
||||
':configDir/live/:hostname/privkey.pem'
|
||||
],
|
||||
'config-dir': [
|
||||
false,
|
||||
' Configuration directory.',
|
||||
'string',
|
||||
'~/letsencrypt/etc/'
|
||||
],
|
||||
store: [
|
||||
false,
|
||||
' The name of the storage module to use',
|
||||
'string',
|
||||
'greenlock-store-fs'
|
||||
],
|
||||
'store-xxxx': [
|
||||
false,
|
||||
' An option for the chosen storage module, such as --store-apikey or --store-bucket',
|
||||
'bag'
|
||||
],
|
||||
'store-json': [
|
||||
false,
|
||||
' A JSON string containing all option for the chosen store module (instead of --store-xxxx)',
|
||||
'json',
|
||||
'{}'
|
||||
],
|
||||
challenge: [
|
||||
false,
|
||||
' The name of the HTTP-01, DNS-01, or TLS-ALPN-01 challenge module to use',
|
||||
'string',
|
||||
'@greenlock/acme-http-01-fs'
|
||||
],
|
||||
'challenge-xxxx': [
|
||||
false,
|
||||
' An option for the chosen challenge module, such as --challenge-apikey or --challenge-bucket',
|
||||
'bag'
|
||||
],
|
||||
'challenge-json': [
|
||||
false,
|
||||
' A JSON string containing all option for the chosen challenge module (instead of --challenge-xxxx)',
|
||||
'json',
|
||||
'{}'
|
||||
],
|
||||
'skip-dry-run': [
|
||||
false,
|
||||
' Use with caution (and test with the staging url first). Creates an Order on the ACME server without a self-test.',
|
||||
'boolean'
|
||||
],
|
||||
'skip-challenge-tests': [
|
||||
false,
|
||||
' Use with caution (and with the staging url first). Presents challenges to the ACME server without first testing locally.',
|
||||
'boolean'
|
||||
],
|
||||
'http-01-port': [
|
||||
false,
|
||||
' Required to be 80 for live servers. Do not use. For special test environments only.',
|
||||
'int'
|
||||
],
|
||||
'dns-01': [false, ' Use DNS-01 challange type', 'boolean', false],
|
||||
standalone: [
|
||||
false,
|
||||
' Obtain certs using a "standalone" webserver.',
|
||||
'boolean',
|
||||
false
|
||||
],
|
||||
manual: [
|
||||
false,
|
||||
' Print the token and key to the screen and wait for you to hit enter, giving you time to copy it somewhere before continuing (uses acme-http-01-cli or acme-dns-01-cli)',
|
||||
'boolean',
|
||||
false
|
||||
],
|
||||
debug: [false, ' show traces and logs', 'boolean', false],
|
||||
root: [
|
||||
false,
|
||||
' public_html / webroot path (may use the :hostname template such as /srv/www/:hostname)',
|
||||
'string',
|
||||
undefined,
|
||||
'webroot-path'
|
||||
],
|
||||
|
||||
//
|
||||
// backwards compat
|
||||
//
|
||||
duplicate: [
|
||||
false,
|
||||
' Allow getting a certificate that duplicates an existing one/is an early renewal',
|
||||
'boolean',
|
||||
false
|
||||
],
|
||||
'rsa-key-size': [
|
||||
false,
|
||||
' (ignored) use server-key-type or account-key-type instead',
|
||||
'ignore',
|
||||
2048
|
||||
],
|
||||
'server-key-path': [
|
||||
false,
|
||||
' Path to privkey.pem to use for certificate (default: generate new)',
|
||||
'string',
|
||||
undefined,
|
||||
'domain-key-path'
|
||||
],
|
||||
'server-key-type': [
|
||||
false,
|
||||
" One of 'RSA' (2048), 'RSA-3084', 'RSA-4096', 'ECDSA' (P-256), or 'P-384'. For best compatibility, security, and efficiency use the default (More bits != More security)",
|
||||
'string',
|
||||
'RSA'
|
||||
],
|
||||
'account-key-path': [
|
||||
false,
|
||||
' Path to privkey.pem to use for account (default: generate new)',
|
||||
'string'
|
||||
],
|
||||
'account-key-type': [
|
||||
false,
|
||||
" One of 'ECDSA' (P-256), 'P-384', 'RSA', 'RSA-3084', or 'RSA-4096'. Stick with 'ECDSA' (P-256) unless you need 'RSA' (2048) for legacy compatibility. (More bits != More security)",
|
||||
'string',
|
||||
'P-256'
|
||||
],
|
||||
webroot: [false, ' (ignored) for certbot compatibility', 'ignore', false],
|
||||
//, 'standalone-supported-challenges': [ false, " Supported challenges, order preferences are randomly chosen. (default: http-01,tls-alpn-01)", 'string', 'http-01']
|
||||
'work-dir': [
|
||||
false,
|
||||
' for certbot compatibility (ignored)',
|
||||
'string',
|
||||
'~/letsencrypt/var/lib/'
|
||||
],
|
||||
'logs-dir': [
|
||||
false,
|
||||
' for certbot compatibility (ignored)',
|
||||
'string',
|
||||
'~/letsencrypt/var/log/'
|
||||
],
|
||||
'acme-version': [
|
||||
false,
|
||||
' (ignored) ACME is now RFC 8555 and prior drafts are no longer supported',
|
||||
'ignore',
|
||||
'rfc8555'
|
||||
]
|
||||
});
|
||||
|
||||
// ignore certonly and extraneous arguments
|
||||
cli.main(function(_, options) {
|
||||
console.info('');
|
||||
|
||||
[
|
||||
'configDir',
|
||||
'privkeyPath',
|
||||
'certPath',
|
||||
'chainPath',
|
||||
'fullchainPath',
|
||||
'bundlePath'
|
||||
].forEach(function(k) {
|
||||
if (options[k]) {
|
||||
options.storeOpts[k] = options[k];
|
||||
}
|
||||
delete options[k];
|
||||
});
|
||||
|
||||
if (options.workDir) {
|
||||
options.challengeOpts.workDir = options.workDir;
|
||||
delete options.workDir;
|
||||
}
|
||||
|
||||
if (options.debug) {
|
||||
console.debug(options);
|
||||
}
|
||||
|
||||
var args = {};
|
||||
var homedir = require('os').homedir();
|
||||
|
||||
Object.keys(options).forEach(function(key) {
|
||||
var val = options[key];
|
||||
|
||||
if ('string' === typeof val) {
|
||||
val = val.replace(/^~/, homedir);
|
||||
}
|
||||
|
||||
key = key.replace(/\-([a-z0-9A-Z])/g, function(c) {
|
||||
return c[1].toUpperCase();
|
||||
});
|
||||
args[key] = val;
|
||||
});
|
||||
|
||||
Object.keys(args).forEach(function(key) {
|
||||
var val = args[key];
|
||||
|
||||
if ('string' === typeof val) {
|
||||
val = val.replace(/(\:configDir)|(\:config)/, args.configDir);
|
||||
}
|
||||
|
||||
args[key] = val;
|
||||
});
|
||||
|
||||
if (args.domains) {
|
||||
args.domains = args.domains.split(',');
|
||||
}
|
||||
|
||||
if (
|
||||
!(Array.isArray(args.domains) && args.domains.length) ||
|
||||
!args.email ||
|
||||
!args.agreeTos ||
|
||||
(!args.server && !args.directoryUrl)
|
||||
) {
|
||||
console.error('\nUsage:\n\ngreenlock certonly --standalone \\');
|
||||
console.error(
|
||||
'\t--agree-tos --email user@example.com --domains example.com \\'
|
||||
);
|
||||
console.error('\t--config-dir ~/acme/etc \\');
|
||||
console.error('\nSee greenlock --help for more details\n');
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.http01Port) {
|
||||
// [@agnat]: Coerce to string. cli returns a number although we request a string.
|
||||
args.http01Port = '' + args.http01Port;
|
||||
args.http01Port = args.http01Port.split(',').map(function(port) {
|
||||
return parseInt(port, 10);
|
||||
});
|
||||
}
|
||||
|
||||
function run() {
|
||||
var challenges = {};
|
||||
if (/http.?01/i.test(args.challenge)) {
|
||||
challenges['http-01'] = args.challengeOpts;
|
||||
}
|
||||
if (/dns.?01/i.test(args.challenge)) {
|
||||
challenges['dns-01'] = args.challengeOpts;
|
||||
}
|
||||
if (/alpn.?01/i.test(args.challenge)) {
|
||||
challenges['tls-alpn-01'] = args.challengeOpts;
|
||||
}
|
||||
if (!Object.keys(challenges).length) {
|
||||
throw new Error(
|
||||
"Could not determine the challenge type for '" +
|
||||
args.challengeOpts.module +
|
||||
"'. Expected a name like @you/acme-xxxx-01-foo. Please name the module with http-01, dns-01, or tls-alpn-01."
|
||||
);
|
||||
}
|
||||
args.challengeOpts.module = args.challenge;
|
||||
args.storeOpts.module = args.store;
|
||||
|
||||
console.log('\ngot to the run step');
|
||||
require(args.challenge);
|
||||
require(args.store);
|
||||
|
||||
var greenlock = require('../').create({
|
||||
maintainerEmail: args.maintainerEmail || 'coolaj86@gmail.com',
|
||||
manager: './manager.js',
|
||||
configFile: '~/.config/greenlock/certs.json',
|
||||
challenges: challenges,
|
||||
store: args.storeOpts,
|
||||
renewOffset: args.renewOffset || '30d',
|
||||
renewStagger: '1d'
|
||||
});
|
||||
|
||||
// for long-running processes
|
||||
if (args.renewEvery) {
|
||||
setInterval(function() {
|
||||
greenlock.renew({
|
||||
period: args.renewEvery
|
||||
});
|
||||
}, args.renewEvery);
|
||||
}
|
||||
|
||||
// TODO should greenlock.add simply always include greenlock.renew?
|
||||
// the concern is conflating error events
|
||||
return greenlock
|
||||
.add({
|
||||
subject: args.subject,
|
||||
altnames: args.altnames,
|
||||
subscriberEmail: args.subscriberEmail || args.email
|
||||
})
|
||||
.then(function(changes) {
|
||||
console.info(changes);
|
||||
// renew should always
|
||||
return greenlock
|
||||
.renew({
|
||||
subject: args.subject,
|
||||
force: false
|
||||
})
|
||||
.then(function() {});
|
||||
});
|
||||
}
|
||||
|
||||
if ('greenlock-store-fs' !== args.store) {
|
||||
run();
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO remove mkdirp and let greenlock-store-fs do this?
|
||||
mkdirp(args.storeOpts.configDir, function(err) {
|
||||
if (!err) {
|
||||
run();
|
||||
}
|
||||
|
||||
console.error(
|
||||
"Could not create --config-dir '" + args.configDir + "':",
|
||||
err.code
|
||||
);
|
||||
console.error("Try setting --config-dir '/tmp'");
|
||||
return;
|
||||
});
|
||||
}, process.argv.slice(3));
|
|
@ -0,0 +1,234 @@
|
|||
'use strict';
|
||||
|
||||
var CLI = module.exports;
|
||||
|
||||
var defaultConf;
|
||||
var defaultOpts;
|
||||
var bags = [];
|
||||
|
||||
CLI.parse = function(conf) {
|
||||
var opts = (defaultOpts = {});
|
||||
defaultConf = conf;
|
||||
|
||||
Object.keys(conf).forEach(function(k) {
|
||||
var v = conf[k];
|
||||
var aliases = v[5];
|
||||
var bag;
|
||||
var bagName;
|
||||
|
||||
// the name of the argument set is now the 0th argument
|
||||
v.unshift(k);
|
||||
// v[0] flagname
|
||||
// v[1] short flagname
|
||||
// v[2] description
|
||||
// v[3] type
|
||||
// v[4] default value
|
||||
// v[5] aliases
|
||||
|
||||
if ('bag' === v[3]) {
|
||||
bag = v[0]; // 'bag-option-xxxx' => '--bag-option-'
|
||||
bag = '--' + bag.replace(/xxx.*/, '');
|
||||
bags.push(bag);
|
||||
|
||||
bagName = toBagName(bag.replace(/^--/, ''));
|
||||
opts[bagName] = {};
|
||||
}
|
||||
|
||||
if ('json' === v[3]) {
|
||||
bagName = toBagName(v[0].replace(/-json$/, '')); // 'bag-option-json' => 'bagOptionOpts'
|
||||
opts[bagName] = {};
|
||||
} else if ('ignore' !== v[3] && 'undefined' !== typeof v[4]) {
|
||||
// set the default values (where 'undefined' is not an allowed value)
|
||||
opts[toCamel(k)] = v[4];
|
||||
}
|
||||
|
||||
if (!aliases) {
|
||||
aliases = [];
|
||||
} else if ('string' === typeof aliases) {
|
||||
aliases = aliases.split(',');
|
||||
}
|
||||
aliases.forEach(function(alias) {
|
||||
if (alias in conf) {
|
||||
throw new Error(
|
||||
"Cannot alias '" +
|
||||
alias +
|
||||
"' from '" +
|
||||
k +
|
||||
"': option already exists"
|
||||
);
|
||||
}
|
||||
conf[alias] = v;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
CLI.main = function(cb, args) {
|
||||
var leftovers = [];
|
||||
var conf = defaultConf;
|
||||
var opts = defaultOpts;
|
||||
|
||||
if (!opts) {
|
||||
throw new Error("you didn't call `CLI.parse(configuration)`");
|
||||
}
|
||||
|
||||
// TODO what's the existing API for this?
|
||||
if (!args) {
|
||||
args = process.argv.slice(2);
|
||||
}
|
||||
|
||||
var flag;
|
||||
var cnf;
|
||||
var typ;
|
||||
|
||||
function grab(bag) {
|
||||
var bagName = toBagName(bag);
|
||||
if (bag !== flag.slice(0, bag.length)) {
|
||||
return false;
|
||||
}
|
||||
console.log(bagName, toCamel(flag.slice(bag.length)));
|
||||
opts[bagName][toCamel(flag.slice(bag.length))] = args.shift();
|
||||
return true;
|
||||
}
|
||||
|
||||
while (args.length) {
|
||||
// take one off the top
|
||||
flag = args.shift();
|
||||
|
||||
// mind the gap
|
||||
if ('--' === flag) {
|
||||
leftovers = leftovers.concat(args);
|
||||
break;
|
||||
}
|
||||
|
||||
// help!
|
||||
if (
|
||||
'--help' === flag ||
|
||||
'-h' === flag ||
|
||||
'/?' === flag ||
|
||||
'help' === flag
|
||||
) {
|
||||
printHelp(conf);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// only long names are actually used
|
||||
if ('--' !== flag.slice(0, 2)) {
|
||||
console.error("Unrecognized argument '" + flag + "'");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
cnf = conf[flag.slice(2)];
|
||||
if (!cnf) {
|
||||
// look for arbitrary flags
|
||||
if (bags.some(grab)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// other arbitrary args are not used
|
||||
console.error("Unrecognized flag '" + flag + "'");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// encourage switching to non-aliased version
|
||||
if (flag !== '--' + cnf[0]) {
|
||||
console.warn(
|
||||
"use of '" +
|
||||
flag +
|
||||
"' is deprecated, use '--" +
|
||||
cnf[0] +
|
||||
"' instead"
|
||||
);
|
||||
}
|
||||
|
||||
// look for xxx-json flags
|
||||
if ('json' === cnf[3]) {
|
||||
try {
|
||||
var json = JSON.parse(args.shift());
|
||||
var bagName = toBagName(cnf[0].replace(/-json$/, ''));
|
||||
Object.keys(json).forEach(function(k) {
|
||||
opts[bagName][k] = json[k];
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Could not parse option '" + flag + "' as JSON:");
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// set booleans, otherwise grab the next arg in line
|
||||
typ = cnf[3];
|
||||
// TODO --no-<whatever> to negate
|
||||
if (Boolean === typ || 'boolean' === typ) {
|
||||
opts[toCamel(cnf[0])] = true;
|
||||
continue;
|
||||
}
|
||||
opts[toCamel(cnf[0])] = args.shift();
|
||||
continue;
|
||||
}
|
||||
|
||||
cb(leftovers, opts);
|
||||
};
|
||||
|
||||
function toCamel(str) {
|
||||
return str.replace(/-([a-z0-9])/g, function(m) {
|
||||
return m[1].toUpperCase();
|
||||
});
|
||||
}
|
||||
|
||||
function toBagName(bag) {
|
||||
// trim leading and trailing '-'
|
||||
bag = bag.replace(/^-+/g, '').replace(/-+$/g, '');
|
||||
return toCamel(bag) + 'Opts'; // '--bag-option-' => bagOptionOpts
|
||||
}
|
||||
|
||||
function printHelp(conf) {
|
||||
var flagLen = 0;
|
||||
var typeLen = 0;
|
||||
var defLen = 0;
|
||||
|
||||
Object.keys(conf).forEach(function(k) {
|
||||
flagLen = Math.max(flagLen, conf[k][0].length);
|
||||
typeLen = Math.max(typeLen, conf[k][3].length);
|
||||
if ('undefined' !== typeof conf[k][4]) {
|
||||
defLen = Math.max(
|
||||
defLen,
|
||||
'(Default: )'.length + String(conf[k][4]).length
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Object.keys(conf).forEach(function(k) {
|
||||
var v = conf[k];
|
||||
|
||||
// skip aliases
|
||||
if (v[0] !== k) {
|
||||
return;
|
||||
}
|
||||
|
||||
var def = v[4];
|
||||
if ('undefined' === typeof def) {
|
||||
def = '';
|
||||
} else {
|
||||
def = '(default: ' + JSON.stringify(def) + ')';
|
||||
}
|
||||
|
||||
var msg =
|
||||
' --' +
|
||||
v[0].padEnd(flagLen) +
|
||||
' ' +
|
||||
v[3].padStart(typeLen + 1) +
|
||||
' ' +
|
||||
(v[2] || '') +
|
||||
' ' +
|
||||
def; /*.padStart(defLen)*/
|
||||
// v[0] flagname
|
||||
// v[1] short flagname
|
||||
// v[2] description
|
||||
// v[3] type
|
||||
// v[4] default value
|
||||
// v[5] aliases
|
||||
|
||||
console.info(msg);
|
||||
});
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
var args = process.argv.slice(2);
|
||||
console.log(args);
|
||||
if ('certonly' === args[0]) {
|
||||
require('./certonly.js');
|
||||
return;
|
||||
}
|
|
@ -0,0 +1,318 @@
|
|||
'use strict';
|
||||
|
||||
var C = module.exports;
|
||||
var U = require('./utils.js');
|
||||
var CSR = require('@root/csr');
|
||||
var Enc = require('@root/encoding');
|
||||
var Keypairs = require('@root/keypairs');
|
||||
|
||||
var pending = {};
|
||||
var rawPending = {};
|
||||
|
||||
// What the abbreviations mean
|
||||
//
|
||||
// gnlkc => greenlock
|
||||
// mconf => manager config
|
||||
// db => greenlock store instance
|
||||
// acme => instance of ACME.js
|
||||
// chs => instances of challenges
|
||||
// acc => account
|
||||
// args => site / extra options
|
||||
|
||||
// Certificates
|
||||
C._getOrOrder = function(gnlck, mconf, db, acme, chs, acc, args) {
|
||||
var email = args.subscriberEmail || mconf.subscriberEmail;
|
||||
|
||||
var id = args.altnames
|
||||
.slice(0)
|
||||
.sort()
|
||||
.join(' ');
|
||||
if (pending[id]) {
|
||||
return pending[id];
|
||||
}
|
||||
|
||||
pending[id] = C._rawGetOrOrder(
|
||||
gnlck,
|
||||
mconf,
|
||||
db,
|
||||
acme,
|
||||
chs,
|
||||
acc,
|
||||
email,
|
||||
args
|
||||
)
|
||||
.then(function(pems) {
|
||||
delete pending[id];
|
||||
return pems;
|
||||
})
|
||||
.catch(function(err) {
|
||||
delete pending[id];
|
||||
throw err;
|
||||
});
|
||||
|
||||
return pending[id];
|
||||
};
|
||||
|
||||
// Certificates
|
||||
C._rawGetOrOrder = function(gnlck, mconf, db, acme, chs, acc, email, args) {
|
||||
return C._check(gnlck, mconf, db, args).then(function(pems) {
|
||||
// Nice and fresh? We're done!
|
||||
if (pems) {
|
||||
if (!C._isStale(gnlck, mconf, args, pems)) {
|
||||
// return existing unexpired (although potentially stale) certificates when available
|
||||
// there will be an additional .renewing property if the certs are being asynchronously renewed
|
||||
//pems._type = 'current';
|
||||
return pems;
|
||||
}
|
||||
}
|
||||
|
||||
// We're either starting fresh or freshening up...
|
||||
var p = C._rawOrder(gnlck, mconf, db, acme, chs, acc, email, args);
|
||||
var evname = pems ? 'cert_renewal' : 'cert_issue';
|
||||
p.then(function(newPems) {
|
||||
// notify in the background
|
||||
var renewAt = C._renewWithStagger(gnlck, mconf, args, newPems);
|
||||
gnlck._notify(evname, {
|
||||
renewAt: renewAt,
|
||||
subject: args.subject,
|
||||
altnames: args.altnames
|
||||
});
|
||||
gnlck._notify('_cert_issue', {
|
||||
renewAt: renewAt,
|
||||
subject: args.subject,
|
||||
altnames: args.altnames,
|
||||
pems: newPems
|
||||
});
|
||||
}).catch(function(err) {
|
||||
if (!err.context) {
|
||||
err.context = evname;
|
||||
}
|
||||
err.subject = args.subject;
|
||||
err.altnames = args.altnames;
|
||||
gnlck._notify('error', err);
|
||||
});
|
||||
|
||||
// No choice but to hang tight and wait for it
|
||||
if (
|
||||
!pems ||
|
||||
pems.renewAt < Date.now() - 24 * 60 * 60 * 1000 ||
|
||||
pems.expiresAt <= Date.now() + 24 * 60 * 60 * 1000
|
||||
) {
|
||||
return p;
|
||||
}
|
||||
|
||||
// Wait it out
|
||||
// TODO should we call this waitForRenewal?
|
||||
if (args.waitForRenewal) {
|
||||
return p;
|
||||
}
|
||||
|
||||
// Let the certs renew in the background
|
||||
return pems;
|
||||
});
|
||||
};
|
||||
|
||||
// we have another promise here because it the optional renewal
|
||||
// may resolve in a different stack than the returned pems
|
||||
C._rawOrder = function(gnlck, mconf, db, acme, chs, acc, email, args) {
|
||||
var id = args.altnames
|
||||
.slice(0)
|
||||
.sort()
|
||||
.join(' ');
|
||||
if (rawPending[id]) {
|
||||
return rawPending[id];
|
||||
}
|
||||
|
||||
var keyType = args.serverKeyType || mconf.serverKeyType;
|
||||
var query = {
|
||||
subject: args.subject,
|
||||
certificate: args.certificate || {},
|
||||
directoryUrl: args.directoryUrl || gnlck._defaults.directoryUrl
|
||||
};
|
||||
rawPending[id] = U._getOrCreateKeypair(db, args.subject, query, keyType)
|
||||
.then(function(kresult) {
|
||||
var serverKeypair = kresult.keypair;
|
||||
var domains = args.altnames.slice(0);
|
||||
|
||||
return CSR.csr({
|
||||
jwk: serverKeypair.privateKeyJwk || serverKeypair.private,
|
||||
domains: domains,
|
||||
encoding: 'der'
|
||||
})
|
||||
.then(function(csrDer) {
|
||||
// TODO let CSR support 'urlBase64' ?
|
||||
return Enc.bufToUrlBase64(csrDer);
|
||||
})
|
||||
.then(function(csr) {
|
||||
function notify(ev, opts) {
|
||||
gnlck._notify(ev, opts);
|
||||
}
|
||||
var certReq = {
|
||||
debug: args.debug || gnlck._defaults.debug,
|
||||
|
||||
challenges: chs,
|
||||
account: acc, // only used if accounts.key.kid exists
|
||||
accountKey:
|
||||
acc.keypair.privateKeyJwk || acc.keypair.private,
|
||||
keypair: acc.keypair, // TODO
|
||||
csr: csr,
|
||||
domains: domains, // because ACME.js v3 uses `domains` still, actually
|
||||
onChallengeStatus: notify,
|
||||
notify: notify // TODO
|
||||
|
||||
// TODO handle this in acme-v2
|
||||
//subject: args.subject,
|
||||
//altnames: args.altnames.slice(0),
|
||||
};
|
||||
return acme.certificates
|
||||
.create(certReq)
|
||||
.then(U._attachCertInfo);
|
||||
})
|
||||
.then(function(pems) {
|
||||
if (kresult.exists) {
|
||||
return pems;
|
||||
}
|
||||
query.keypair = serverKeypair;
|
||||
return db.setKeypair(query, serverKeypair).then(function() {
|
||||
return pems;
|
||||
});
|
||||
});
|
||||
})
|
||||
.then(function(pems) {
|
||||
// TODO put this in the docs
|
||||
// { cert, chain, privkey, subject, altnames, issuedAt, expiresAt }
|
||||
// Note: the query has been updated
|
||||
query.pems = pems;
|
||||
return db.set(query);
|
||||
})
|
||||
.then(function() {
|
||||
return C._check(gnlck, mconf, db, args);
|
||||
})
|
||||
.then(function(bundle) {
|
||||
// TODO notify Manager
|
||||
delete rawPending[id];
|
||||
return bundle;
|
||||
})
|
||||
.catch(function(err) {
|
||||
// Todo notify manager
|
||||
delete rawPending[id];
|
||||
throw err;
|
||||
});
|
||||
|
||||
return rawPending[id];
|
||||
};
|
||||
|
||||
// returns pems, if they exist
|
||||
C._check = function(gnlck, mconf, db, args) {
|
||||
var query = {
|
||||
subject: args.subject,
|
||||
// may contain certificate.id
|
||||
certificate: args.certificate,
|
||||
directoryUrl: args.directoryUrl || gnlck._defaults.directoryUrl
|
||||
};
|
||||
return db.check(query).then(function(pems) {
|
||||
if (!pems) {
|
||||
return null;
|
||||
}
|
||||
|
||||
pems = U._attachCertInfo(pems);
|
||||
|
||||
// For eager management
|
||||
if (args.subject && !U._certHasDomain(pems, args.subject)) {
|
||||
// TODO report error, but continue the process as with no cert
|
||||
return null;
|
||||
}
|
||||
|
||||
// For lazy SNI requests
|
||||
if (args.domain && !U._certHasDomain(pems, args.domain)) {
|
||||
// TODO report error, but continue the process as with no cert
|
||||
return null;
|
||||
}
|
||||
|
||||
return U._getKeypair(db, args.subject, query)
|
||||
.then(function(keypair) {
|
||||
return Keypairs.export({
|
||||
jwk: keypair.privateKeyJwk || keypair.private,
|
||||
encoding: 'pem'
|
||||
}).then(function(pem) {
|
||||
pems.privkey = pem;
|
||||
return pems;
|
||||
});
|
||||
})
|
||||
.catch(function() {
|
||||
// TODO report error, but continue the process as with no cert
|
||||
return null;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Certificates
|
||||
C._isStale = function(gnlck, mconf, args, pems) {
|
||||
if (args.duplicate) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var renewAt = C._renewableAt(gnlck, mconf, args, pems);
|
||||
|
||||
if (Date.now() >= renewAt) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
C._renewWithStagger = function(gnlck, mconf, args, pems) {
|
||||
var renewOffset = C._renewOffset(gnlck, mconf, args, pems);
|
||||
var renewStagger;
|
||||
try {
|
||||
renewStagger = U._parseDuration(
|
||||
args.renewStagger || mconf.renewStagger || 0
|
||||
);
|
||||
} catch (e) {
|
||||
renewStagger = U._parseDuration(
|
||||
args.renewStagger || mconf.renewStagger
|
||||
);
|
||||
}
|
||||
|
||||
// TODO check this beforehand
|
||||
if (!args.force && renewStagger / renewOffset >= 0.5) {
|
||||
renewStagger = renewOffset * 0.1;
|
||||
}
|
||||
|
||||
if (renewOffset > 0) {
|
||||
// stagger forward, away from issued at
|
||||
return Math.round(
|
||||
pems.issuedAt + renewOffset + Math.random() * renewStagger
|
||||
);
|
||||
}
|
||||
|
||||
// stagger backward, toward issued at
|
||||
return Math.round(
|
||||
pems.expiresAt + renewOffset - Math.random() * renewStagger
|
||||
);
|
||||
};
|
||||
C._renewOffset = function(gnlck, mconf, args /*, pems*/) {
|
||||
var renewOffset = U._parseDuration(
|
||||
args.renewOffset || mconf.renewOffset || 0
|
||||
);
|
||||
var week = 1000 * 60 * 60 * 24 * 6;
|
||||
if (!args.force && Math.abs(renewOffset) < week) {
|
||||
throw new Error(
|
||||
'developer error: `renewOffset` should always be at least a week, use `force` to not safety-check renewOffset'
|
||||
);
|
||||
}
|
||||
return renewOffset;
|
||||
};
|
||||
C._renewableAt = function(gnlck, mconf, args, pems) {
|
||||
if (args.renewAt) {
|
||||
return args.renewAt;
|
||||
}
|
||||
|
||||
var renewOffset = C._renewOffset(gnlck, mconf, args, pems);
|
||||
|
||||
if (renewOffset > 0) {
|
||||
return pems.issuedAt + renewOffset;
|
||||
}
|
||||
|
||||
return pems.expiresAt + renewOffset;
|
||||
};
|
|
@ -0,0 +1,58 @@
|
|||
'use strict';
|
||||
|
||||
var E = module.exports;
|
||||
|
||||
function create(code, msg) {
|
||||
E[code] = function(ctx, msg2) {
|
||||
var err = new Error(msg);
|
||||
err.code = code;
|
||||
err.context = ctx;
|
||||
if (msg2) {
|
||||
err.message += ': ' + msg2;
|
||||
}
|
||||
/*
|
||||
Object.keys(extras).forEach(function(k) {
|
||||
if ('message' === k) {
|
||||
err.message += ': ' + extras[k];
|
||||
} else {
|
||||
err[k] = extras[k];
|
||||
}
|
||||
});
|
||||
*/
|
||||
return err;
|
||||
};
|
||||
}
|
||||
|
||||
// TODO open issues and link to them as the error url
|
||||
create(
|
||||
'NO_MAINTAINER',
|
||||
'please supply `maintainerEmail` as a contact for security and critical bug notices'
|
||||
);
|
||||
create(
|
||||
'BAD_ORDER',
|
||||
'altnames should be in deterministic order, with subject as the first altname'
|
||||
);
|
||||
create('NO_SUBJECT', 'no certificate subject given');
|
||||
create(
|
||||
'NO_SUBSCRIBER',
|
||||
'please supply `subscriberEmail` as a contact for failed renewal and certificate revocation'
|
||||
);
|
||||
create(
|
||||
'INVALID_SUBSCRIBER',
|
||||
'`subscriberEmail` is not a valid address, please check for typos'
|
||||
);
|
||||
create(
|
||||
'INVALID_HOSTNAME',
|
||||
'valid hostnames must be restricted to a-z0-9_.- and contain at least one "."'
|
||||
);
|
||||
create(
|
||||
'INVALID_DOMAIN',
|
||||
'one or more domains do not exist on public DNS SOA record'
|
||||
);
|
||||
create(
|
||||
'NOT_UNIQUE',
|
||||
'found duplicate domains, or a subdomain that overlaps a wildcard'
|
||||
);
|
||||
|
||||
// exported for testing only
|
||||
E._create = create;
|
|
@ -1,30 +0,0 @@
|
|||
# STOP
|
||||
|
||||
**These aren't the droids you're looking for.**
|
||||
|
||||
You probably don't want to use `greenlock` directly.
|
||||
|
||||
Instead, look here:
|
||||
|
||||
## Webservers
|
||||
|
||||
For any type of webserver (express, hapi, koa, connect, https, spdy, etc),
|
||||
you're going to want to take a look at
|
||||
[greenlock-express](https://git.coolaj86.com/coolaj86/greenlock-express.js).
|
||||
|
||||
<https://git.coolaj86.com/coolaj86/greenlock-express.js>
|
||||
|
||||
## CLIs
|
||||
|
||||
For any type of CLI (like what you want to use with bash, fish, zsh, cmd.exe, PowerShell, etc),
|
||||
you're going to want to take a look at
|
||||
[greenlock-cli](https://git.coolaj86.com/coolaj86/greenlock-cli.js).
|
||||
|
||||
<https://git.coolaj86.com/coolaj86/greenlock-cli.js>
|
||||
|
||||
# No, I wanted greenlock
|
||||
|
||||
Well, take a look at the API in the main README
|
||||
and you can also check out the code in the repos above.
|
||||
|
||||
Feel free to open an issues to request any particular type of example.
|
|
@ -1,77 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
//var Greenlock = require('greenlock');
|
||||
var Greenlock = require('../');
|
||||
var db = {};
|
||||
|
||||
var config = {
|
||||
server: 'https://acme-v02.api.letsencrypt.org/directory',
|
||||
version: 'draft-11',
|
||||
|
||||
configDir: require('os').homedir() + '/acme/etc', // or /etc/acme or wherever
|
||||
|
||||
privkeyPath: ':config/live/:hostname/privkey.pem', //
|
||||
fullchainPath: ':config/live/:hostname/fullchain.pem', // Note: both that :config and :hostname
|
||||
certPath: ':config/live/:hostname/cert.pem', // will be templated as expected
|
||||
chainPath: ':config/live/:hostname/chain.pem', //
|
||||
|
||||
rsaKeySize: 2048,
|
||||
|
||||
debug: true
|
||||
};
|
||||
|
||||
var handlers = {
|
||||
setChallenge: function(opts, hostname, key, val, cb) {
|
||||
// called during the ACME server handshake, before validation
|
||||
db[key] = {
|
||||
hostname: hostname,
|
||||
key: key,
|
||||
val: val
|
||||
};
|
||||
|
||||
cb(null);
|
||||
},
|
||||
removeChallenge: function(opts, hostname, key, cb) {
|
||||
// called after validation on both success and failure
|
||||
db[key] = null;
|
||||
cb(null);
|
||||
},
|
||||
getChallenge: function(opts, hostname, key, cb) {
|
||||
// this is special because it is called by the webserver
|
||||
cb(null, db[key].val); // (see greenlock-cli/bin & greenlock-express/standalone),
|
||||
// not by the library itself
|
||||
},
|
||||
agreeToTerms: function(tosUrl, cb) {
|
||||
// gives you an async way to expose the legal agreement
|
||||
cb(null, tosUrl); // (terms of use) to your users before accepting
|
||||
}
|
||||
};
|
||||
|
||||
var greenlock = Greenlock.create(config, handlers);
|
||||
console.error(
|
||||
'CHANGE THE EMAIL, DOMAINS, AND AGREE TOS IN THE EXAMPLE BEFORE RUNNING IT'
|
||||
);
|
||||
process.exit(1);
|
||||
// checks :conf/renewal/:hostname.conf
|
||||
greenlock.register(
|
||||
{
|
||||
// and either renews or registers
|
||||
domains: ['example.com'], // CHANGE TO YOUR DOMAIN
|
||||
email: 'user@email.com', // CHANGE TO YOUR EMAIL
|
||||
agreeTos: false, // set to true to automatically accept an agreement
|
||||
// which you have pre-approved (not recommended)
|
||||
rsaKeySize: 2048
|
||||
},
|
||||
function(err) {
|
||||
if (err) {
|
||||
// Note: you must have a webserver running
|
||||
// and expose handlers.getChallenge to it
|
||||
// in order to pass validation
|
||||
// See greenlock-cli and or greenlock-express
|
||||
console.error('[Error]: greenlock/examples/standalone');
|
||||
console.error(err.stack);
|
||||
} else {
|
||||
console.log('success');
|
||||
}
|
||||
}
|
||||
);
|
|
@ -0,0 +1,665 @@
|
|||
'use strict';
|
||||
|
||||
var pkg = require('./package.json');
|
||||
|
||||
var ACME = require('@root/acme');
|
||||
var Greenlock = module.exports;
|
||||
var request = require('@root/request');
|
||||
|
||||
var G = Greenlock;
|
||||
var U = require('./utils.js');
|
||||
var E = require('./errors.js');
|
||||
var P = require('./plugins.js');
|
||||
var A = require('./accounts.js');
|
||||
var C = require('./certificates.js');
|
||||
var UserEvents = require('./user-events.js');
|
||||
|
||||
var caches = {};
|
||||
|
||||
// { maintainerEmail, directoryUrl, subscriberEmail, store, challenges }
|
||||
G.create = function(gconf) {
|
||||
var greenlock = {};
|
||||
var gdefaults = {};
|
||||
if (!gconf) {
|
||||
gconf = {};
|
||||
}
|
||||
|
||||
if (!gconf.maintainerEmail) {
|
||||
throw E.NO_MAINTAINER('create');
|
||||
}
|
||||
|
||||
// TODO send welcome message with benefit info
|
||||
U._validMx(gconf.maintainerEmail).catch(function() {
|
||||
console.error(
|
||||
'invalid maintainer contact info:',
|
||||
gconf.maintainerEmail
|
||||
);
|
||||
|
||||
// maybe move this to init and don't exit the process, just in case
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
if ('function' === typeof gconf.notify) {
|
||||
gdefaults.notify = gconf.notify;
|
||||
} else {
|
||||
gdefaults.notify = _notify;
|
||||
}
|
||||
|
||||
if (gconf.directoryUrl) {
|
||||
gdefaults = gconf.directoryUrl;
|
||||
if (gconf.staging) {
|
||||
throw new Error('supply `directoryUrl` or `staging`, but not both');
|
||||
}
|
||||
} else if (gconf.staging) {
|
||||
gdefaults.directoryUrl =
|
||||
'https://acme-staging-v02.api.letsencrypt.org/directory';
|
||||
} else {
|
||||
gdefaults.directoryUrl =
|
||||
'https://acme-v02.api.letsencrypt.org/directory';
|
||||
}
|
||||
console.info('ACME Directory URL:', gdefaults.directoryUrl);
|
||||
|
||||
var manager = normalizeManager(gconf);
|
||||
require('./manager-underlay.js').wrap(greenlock, manager, gconf);
|
||||
//console.log('debug greenlock.manager', Object.keys(greenlock.manager));
|
||||
|
||||
greenlock.notify = greenlock._notify = function(ev, params) {
|
||||
var mng = greenlock.manager;
|
||||
|
||||
if ('_' === String(ev)[0]) {
|
||||
if ('_cert_issue' === ev) {
|
||||
try {
|
||||
mng.update({
|
||||
subject: params.subject,
|
||||
renewAt: params.renewAt
|
||||
}).catch(function(e) {
|
||||
e.context = '_cert_issue';
|
||||
greenlock._notify('error', e);
|
||||
});
|
||||
} catch (e) {
|
||||
e.context = '_cert_issue';
|
||||
greenlock._notify('error', e);
|
||||
}
|
||||
}
|
||||
// trap internal events internally
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var p = greenlock._defaults.notify(ev, params);
|
||||
if (p && p.catch) {
|
||||
p.catch(function(e) {
|
||||
console.error("Promise Rejection on event '" + ev + "':");
|
||||
console.error(e);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Thrown Exception on event '" + ev + "':");
|
||||
console.error(e);
|
||||
console.error(params);
|
||||
}
|
||||
|
||||
if (-1 !== ['cert_issue', 'cert_renewal'].indexOf(ev)) {
|
||||
// We will notify all greenlock users of mandatory and security updates
|
||||
// We'll keep track of versions and os so we can make sure things work well
|
||||
// { name, version, email, domains, action, communityMember, telemetry }
|
||||
// TODO look at the other one
|
||||
UserEvents.notify({
|
||||
/*
|
||||
// maintainer should be only on pre-publish, or maybe install, I think
|
||||
maintainerEmail: greenlock._defaults._maintainerEmail,
|
||||
name: greenlock._defaults._packageAgent,
|
||||
version: greenlock._defaults._maintainerPackageVersion,
|
||||
//action: params.pems._type,
|
||||
domains: params.altnames,
|
||||
subscriberEmail: greenlock._defaults._subscriberEmail,
|
||||
// TODO enable for Greenlock Pro
|
||||
//customerEmail: args.customerEmail
|
||||
telemetry: greenlock._defaults.telemetry
|
||||
*/
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// The purpose of init is to make MCONF the source of truth
|
||||
greenlock._init = function() {
|
||||
var p;
|
||||
greenlock._init = function() {
|
||||
return p;
|
||||
};
|
||||
|
||||
if (manager.init) {
|
||||
// TODO punycode?
|
||||
p = manager.init({
|
||||
request: request
|
||||
//punycode: require('punycode')
|
||||
});
|
||||
} else {
|
||||
p = Promise.resolve();
|
||||
}
|
||||
p = p
|
||||
.then(function() {
|
||||
return manager.defaults().then(function(MCONF) {
|
||||
mergeDefaults(MCONF, gconf);
|
||||
if (true === MCONF.agreeToTerms) {
|
||||
gdefaults.agreeToTerms = function(tos) {
|
||||
return Promise.resolve(tos);
|
||||
};
|
||||
}
|
||||
return manager.defaults(MCONF);
|
||||
});
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error('Fatal error during greenlock init:');
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
return p;
|
||||
};
|
||||
|
||||
// The goal here is to reduce boilerplate, such as error checking
|
||||
// and duration parsing, that a manager must implement
|
||||
greenlock.sites.add = greenlock.add = greenlock.manager.add;
|
||||
|
||||
// certs.get
|
||||
greenlock.get = function(args) {
|
||||
return greenlock
|
||||
._single(args)
|
||||
.then(function() {
|
||||
args._includePems = true;
|
||||
return greenlock.renew(args);
|
||||
})
|
||||
.then(function(results) {
|
||||
if (!results || !results.length) {
|
||||
// TODO throw an error here?
|
||||
return null;
|
||||
}
|
||||
|
||||
// just get the first one
|
||||
var result = results[0];
|
||||
|
||||
// (there should be only one, ideally)
|
||||
if (results.length > 1) {
|
||||
var err = new Error(
|
||||
"a search for '" +
|
||||
args.servername +
|
||||
"' returned multiple certificates"
|
||||
);
|
||||
err.context = 'duplicate_certs';
|
||||
err.servername = args.servername;
|
||||
err.subjects = results.map(function(r) {
|
||||
return (r.site || {}).subject || 'N/A';
|
||||
});
|
||||
|
||||
greenlock._notify('warning', err);
|
||||
}
|
||||
|
||||
if (result.error) {
|
||||
return Promise.reject(result.error);
|
||||
}
|
||||
|
||||
// site for plugin options, such as http-01 challenge
|
||||
// pems for the obvious reasons
|
||||
return result;
|
||||
});
|
||||
};
|
||||
|
||||
greenlock._single = function(args) {
|
||||
if ('string' !== typeof args.servername) {
|
||||
return Promise.reject(new Error('no `servername` given'));
|
||||
}
|
||||
// www.example.com => *.example.com
|
||||
args.wildname =
|
||||
'*.' +
|
||||
args.servername
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
if (
|
||||
args.servernames ||
|
||||
args.subject ||
|
||||
args.renewBefore ||
|
||||
args.issueBefore ||
|
||||
args.expiresBefore
|
||||
) {
|
||||
return Promise.reject(
|
||||
new Error(
|
||||
'bad arguments, did you mean to call greenlock.renew()?'
|
||||
)
|
||||
);
|
||||
}
|
||||
// duplicate, force, and others still allowed
|
||||
return Promise.resolve(args);
|
||||
};
|
||||
|
||||
greenlock._config = function(args) {
|
||||
return greenlock
|
||||
._single(args)
|
||||
.then(function() {
|
||||
return greenlock._find(args);
|
||||
})
|
||||
.then(function(sites) {
|
||||
if (!sites || !sites.length) {
|
||||
return null;
|
||||
}
|
||||
var site = sites[0];
|
||||
site = JSON.parse(JSON.stringify(site));
|
||||
if (site.store && site.challenges) {
|
||||
return site;
|
||||
}
|
||||
return manager.defaults().then(function(mconf) {
|
||||
if (!site.store) {
|
||||
site.store = mconf.store;
|
||||
}
|
||||
if (!site.challenges) {
|
||||
site.challenges = mconf.challenges;
|
||||
}
|
||||
return site;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// needs to get info about the renewal, such as which store and challenge(s) to use
|
||||
greenlock.renew = function(args) {
|
||||
return greenlock._init().then(function() {
|
||||
return manager.defaults().then(function(mconf) {
|
||||
return greenlock._renew(mconf, args);
|
||||
});
|
||||
});
|
||||
};
|
||||
greenlock._renew = function(mconf, args) {
|
||||
if (!args) {
|
||||
args = {};
|
||||
}
|
||||
|
||||
var renewedOrFailed = [];
|
||||
//console.log('greenlock._renew find', args);
|
||||
return greenlock._find(args).then(function(sites) {
|
||||
// Note: the manager must guaranteed that these are mutable copies
|
||||
//console.log('greenlock._renew found', sites);;
|
||||
|
||||
function next() {
|
||||
var site = sites.shift();
|
||||
if (!site) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
var order = { site: site };
|
||||
renewedOrFailed.push(order);
|
||||
// TODO merge args + result?
|
||||
return greenlock
|
||||
._order(mconf, site)
|
||||
.then(function(pems) {
|
||||
if (args._includePems) {
|
||||
order.pems = pems;
|
||||
}
|
||||
})
|
||||
.catch(function(err) {
|
||||
order.error = err;
|
||||
|
||||
// For greenlock express serialization
|
||||
err.toJSON = errorToJSON;
|
||||
err.context = err.context || 'cert_order';
|
||||
err.subject = site.subject;
|
||||
if (args.servername) {
|
||||
err.servername = args.servername;
|
||||
}
|
||||
// for debugging, but not to be relied on
|
||||
err._site = site;
|
||||
// TODO err.context = err.context || 'renew_certificate'
|
||||
greenlock._notify('error', err);
|
||||
})
|
||||
.then(function() {
|
||||
return next();
|
||||
});
|
||||
}
|
||||
|
||||
return next().then(function() {
|
||||
return renewedOrFailed;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
greenlock._acme = function(args) {
|
||||
var packageAgent = gconf.packageAgent || '';
|
||||
// because Greenlock_Express/v3.x Greenlock/v3 is redundant
|
||||
if (!/greenlock/i.test(packageAgent)) {
|
||||
packageAgent = (packageAgent + ' Greenlock/' + pkg.version).trim();
|
||||
}
|
||||
var acme = ACME.create({
|
||||
maintainerEmail: gconf.maintainerEmail,
|
||||
packageAgent: packageAgent,
|
||||
notify: greenlock._notify,
|
||||
debug: greenlock._defaults.debug || args.debug
|
||||
});
|
||||
var dirUrl = args.directoryUrl || greenlock._defaults.directoryUrl;
|
||||
|
||||
var dir = caches[dirUrl];
|
||||
|
||||
// don't cache more than an hour
|
||||
if (dir && Date.now() - dir.ts < 1 * 60 * 60 * 1000) {
|
||||
return dir.promise;
|
||||
}
|
||||
|
||||
return acme
|
||||
.init(dirUrl)
|
||||
.then(function(/*meta*/) {
|
||||
caches[dirUrl] = {
|
||||
promise: Promise.resolve(acme),
|
||||
ts: Date.now()
|
||||
};
|
||||
return acme;
|
||||
})
|
||||
.catch(function(err) {
|
||||
// TODO
|
||||
// let's encrypt is possibly down for maintenaince...
|
||||
// this is a special kind of failure mode
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
|
||||
greenlock.order = function(args) {
|
||||
return greenlock._init().then(function() {
|
||||
return manager.defaults().then(function(mconf) {
|
||||
return greenlock._order(mconf, args);
|
||||
});
|
||||
});
|
||||
};
|
||||
greenlock._order = function(mconf, args) {
|
||||
// packageAgent, maintainerEmail
|
||||
return greenlock._acme(args).then(function(acme) {
|
||||
var storeConf = args.store || mconf.store;
|
||||
return P._loadStore(storeConf).then(function(store) {
|
||||
return A._getOrCreate(
|
||||
greenlock,
|
||||
mconf,
|
||||
store.accounts,
|
||||
acme,
|
||||
args
|
||||
).then(function(account) {
|
||||
var challengeConfs = args.challenges || mconf.challenges;
|
||||
return Promise.all(
|
||||
Object.keys(challengeConfs).map(function(typ01) {
|
||||
return P._loadChallenge(challengeConfs, typ01);
|
||||
})
|
||||
).then(function(arr) {
|
||||
var challenges = {};
|
||||
arr.forEach(function(el) {
|
||||
challenges[el._type] = el;
|
||||
});
|
||||
return C._getOrOrder(
|
||||
greenlock,
|
||||
mconf,
|
||||
store.certificates,
|
||||
acme,
|
||||
challenges,
|
||||
account,
|
||||
args
|
||||
).then(function(pems) {
|
||||
if (!pems) {
|
||||
throw new Error('no order result');
|
||||
}
|
||||
if (!pems.privkey) {
|
||||
throw new Error(
|
||||
'missing private key, which is kinda important'
|
||||
);
|
||||
}
|
||||
return pems;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
greenlock._defaults = gdefaults;
|
||||
greenlock._defaults.debug = gconf.debug;
|
||||
|
||||
// renew every 90-ish minutes (random for staggering)
|
||||
// the weak setTimeout (unref) means that when run as a CLI process this
|
||||
// will still finish as expected, and not wait on the timeout
|
||||
(function renew() {
|
||||
setTimeout(function() {
|
||||
greenlock.renew({});
|
||||
renew();
|
||||
}, Math.PI * 30 * 60 * 1000).unref();
|
||||
})();
|
||||
|
||||
return greenlock;
|
||||
};
|
||||
|
||||
G._loadChallenge = P._loadChallenge;
|
||||
|
||||
function errorToJSON(e) {
|
||||
var error = {};
|
||||
Object.getOwnPropertyNames(e).forEach(function(k) {
|
||||
error[k] = e[k];
|
||||
});
|
||||
return error;
|
||||
}
|
||||
|
||||
function normalizeManager(gconf) {
|
||||
var m;
|
||||
// 1. Get the manager
|
||||
// 2. Figure out if we need to wrap it
|
||||
|
||||
if (!gconf.manager) {
|
||||
gconf.manager = 'greenlock-manager-fs';
|
||||
if (gconf.find) {
|
||||
// { manager: 'greenlock-manager-fs', find: function () { } }
|
||||
warpFind(gconf);
|
||||
}
|
||||
}
|
||||
|
||||
if ('string' === typeof gconf.manager) {
|
||||
try {
|
||||
// wrap this to be safe for greenlock-manager-fs
|
||||
m = require(gconf.manager).create(gconf);
|
||||
} catch (e) {
|
||||
console.error(e.code);
|
||||
console.error(e.message);
|
||||
}
|
||||
} else {
|
||||
m = gconf.manager;
|
||||
}
|
||||
|
||||
if (!m) {
|
||||
console.error();
|
||||
console.error(
|
||||
'Failed to load manager plugin ',
|
||||
JSON.stringify(gconf.manager)
|
||||
);
|
||||
console.error();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (
|
||||
['set', 'remove', 'find', 'defaults'].every(function(k) {
|
||||
return 'function' === typeof m[k];
|
||||
})
|
||||
) {
|
||||
return m;
|
||||
}
|
||||
|
||||
// { manager: { find: function () { } } }
|
||||
if (m.find) {
|
||||
warpFind(m);
|
||||
}
|
||||
// m.configFile could also be set
|
||||
m = require('greenlock-manager-fs').create(m);
|
||||
|
||||
if ('function' !== typeof m.find) {
|
||||
console.error();
|
||||
console.error(
|
||||
JSON.stringify(gconf.manager),
|
||||
'must implement `find()` and should implement `set()`, `remove()`, `defaults()`, and `init()`'
|
||||
);
|
||||
console.error();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
function warpFind(gconf) {
|
||||
gconf.__gl_find = gconf.find;
|
||||
gconf.find = function(args) {
|
||||
// the incoming args will be normalized by greenlock
|
||||
return gconf.__gl_find(args).then(function(sites) {
|
||||
// we also need to error check the incoming sites,
|
||||
// as if they were being passed through `add()` or `set()`
|
||||
// (effectively they are) because the manager assumes that
|
||||
// they're not bad
|
||||
sites.forEach(function(s) {
|
||||
if (!s || 'string' !== typeof s.subject) {
|
||||
throw new Error('missing subject');
|
||||
}
|
||||
if (
|
||||
!Array.isArray(s.altnames) ||
|
||||
!s.altnames.length ||
|
||||
!s.altnames[0] ||
|
||||
s.altnames[0] !== s.subject
|
||||
) {
|
||||
throw new Error('missing or malformed altnames');
|
||||
}
|
||||
['renewAt', 'issuedAt', 'expiresAt'].forEach(function(k) {
|
||||
if (s[k]) {
|
||||
throw new Error(
|
||||
'`' +
|
||||
k +
|
||||
'` should be updated by `set()`, not by `find()`'
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function mergeDefaults(MCONF, gconf) {
|
||||
if (
|
||||
gconf.agreeToTerms === true ||
|
||||
MCONF.agreeToTerms === true ||
|
||||
// TODO deprecate
|
||||
gconf.agreeTos === true ||
|
||||
MCONF.agreeTos === true
|
||||
) {
|
||||
MCONF.agreeToTerms = true;
|
||||
}
|
||||
|
||||
if (!MCONF.subscriberEmail && gconf.subscriberEmail) {
|
||||
MCONF.subscriberEmail = gconf.subscriberEmail;
|
||||
}
|
||||
|
||||
var homedir;
|
||||
// Load the default store module
|
||||
if (!MCONF.store) {
|
||||
if (gconf.store) {
|
||||
MCONF.store = gconf.store;
|
||||
} else {
|
||||
homedir = require('os').homedir();
|
||||
MCONF.store = {
|
||||
module: 'greenlock-store-fs',
|
||||
basePath: homedir + '/.config/greenlock/'
|
||||
};
|
||||
}
|
||||
}
|
||||
// just to test that it loads
|
||||
P._loadSync(MCONF.store.module);
|
||||
|
||||
// Load the default challenge modules
|
||||
var challenges = MCONF.challenges || gconf.challenges;
|
||||
if (!challenges) {
|
||||
challenges = {};
|
||||
}
|
||||
if (!challenges['http-01'] && !challenges['dns-01']) {
|
||||
challenges['http-01'] = { module: 'acme-http-01-standalone' };
|
||||
}
|
||||
if (challenges['http-01']) {
|
||||
if ('string' !== typeof challenges['http-01'].module) {
|
||||
throw new Error(
|
||||
'bad challenge http-01 module config:' +
|
||||
JSON.stringify(challenges['http-01'])
|
||||
);
|
||||
}
|
||||
P._loadSync(challenges['http-01'].module);
|
||||
}
|
||||
if (challenges['dns-01']) {
|
||||
if ('string' !== typeof challenges['dns-01'].module) {
|
||||
throw new Error(
|
||||
'bad challenge dns-01 module config' +
|
||||
JSON.stringify(challenges['dns-01'])
|
||||
);
|
||||
}
|
||||
P._loadSync(challenges['dns-01'].module);
|
||||
}
|
||||
MCONF.challenges = challenges;
|
||||
|
||||
if (!MCONF.renewOffset) {
|
||||
MCONF.renewOffset = gconf.renewOffset || '-45d';
|
||||
}
|
||||
if (!MCONF.renewStagger) {
|
||||
MCONF.renewStagger = gconf.renewStagger || '3d';
|
||||
}
|
||||
|
||||
if (!MCONF.accountKeyType) {
|
||||
MCONF.accountKeyType = gconf.accountKeyType || 'EC-P256';
|
||||
}
|
||||
if (!MCONF.serverKeyType) {
|
||||
MCONF.serverKeyType = gconf.serverKeyType || 'RSA-2048';
|
||||
}
|
||||
}
|
||||
|
||||
function _notify(ev, args) {
|
||||
if (!args) {
|
||||
args = ev;
|
||||
ev = args.event;
|
||||
delete args.event;
|
||||
}
|
||||
|
||||
// TODO define message types
|
||||
if (!_notify._notice) {
|
||||
console.info(
|
||||
'set greenlockOptions.notify to override the default logger'
|
||||
);
|
||||
_notify._notice = true;
|
||||
}
|
||||
var prefix = 'Warning';
|
||||
switch (ev) {
|
||||
case 'error':
|
||||
prefix = 'Error';
|
||||
/* falls through */
|
||||
case 'warning':
|
||||
console.error(
|
||||
prefix + '%s:',
|
||||
(' ' + (args.context || '')).trimRight()
|
||||
);
|
||||
console.error(args.message);
|
||||
if (args.description) {
|
||||
console.error(args.description);
|
||||
}
|
||||
if (args.code) {
|
||||
console.error('code:', args.code);
|
||||
}
|
||||
if (args.stack) {
|
||||
console.error(args.stack);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (/status/.test(ev)) {
|
||||
console.info(
|
||||
ev,
|
||||
args.altname || args.subject || '',
|
||||
args.status || ''
|
||||
);
|
||||
if (!args.status) {
|
||||
console.info(args);
|
||||
}
|
||||
break;
|
||||
}
|
||||
console.info(
|
||||
ev,
|
||||
'(more info available: ' + Object.keys(args).join(' ') + ')'
|
||||
);
|
||||
}
|
||||
}
|
870
index.js
870
index.js
|
@ -1,870 +0,0 @@
|
|||
'use strict';
|
||||
/*global Promise*/
|
||||
require('./lib/compat.js');
|
||||
|
||||
// I hate this code so much.
|
||||
// Soooo many shims for backwards compatibility (some stuff dating back to v1)
|
||||
// v3 will be a clean break and I'll delete half of the code...
|
||||
|
||||
var DAY = 24 * 60 * 60 * 1000;
|
||||
//var MIN = 60 * 1000;
|
||||
var ACME = require('acme-v2/compat').ACME;
|
||||
var pkg = require('./package.json');
|
||||
var util = require('util');
|
||||
|
||||
function promisifyAllSelf(obj) {
|
||||
if (obj.__promisified) {
|
||||
return obj;
|
||||
}
|
||||
Object.keys(obj).forEach(function(key) {
|
||||
if ('function' === typeof obj[key] && !/Async$/.test(key)) {
|
||||
obj[key + 'Async'] = util.promisify(obj[key]);
|
||||
}
|
||||
});
|
||||
obj.__promisified = true;
|
||||
return obj;
|
||||
}
|
||||
function promisifyAllStore(obj) {
|
||||
Object.keys(obj).forEach(function(key) {
|
||||
if ('function' !== typeof obj[key] || /Async$/.test(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var p;
|
||||
if (0 === obj[key].length || 1 === obj[key].length) {
|
||||
// wrap just in case it's synchronous (or improperly throws)
|
||||
p = function(opts) {
|
||||
return Promise.resolve().then(function() {
|
||||
return obj[key](opts);
|
||||
});
|
||||
};
|
||||
} else {
|
||||
p = util.promisify(obj[key]);
|
||||
}
|
||||
// internal backwards compat
|
||||
obj[key + 'Async'] = p;
|
||||
});
|
||||
obj.__promisified = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
var Greenlock = module.exports;
|
||||
Greenlock.Greenlock = Greenlock;
|
||||
Greenlock.LE = Greenlock;
|
||||
// in-process cache, shared between all instances
|
||||
var ipc = {};
|
||||
|
||||
function _log(debug) {
|
||||
if (debug) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.shift();
|
||||
args.unshift('[gl/index.js]');
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
}
|
||||
|
||||
Greenlock.defaults = {
|
||||
productionServerUrl: 'https://acme-v01.api.letsencrypt.org/directory',
|
||||
stagingServerUrl: 'https://acme-staging.api.letsencrypt.org/directory',
|
||||
|
||||
rsaKeySize: ACME.rsaKeySize || 2048,
|
||||
challengeType: ACME.challengeType || 'http-01',
|
||||
challengeTypes: ACME.challengeTypes || ['http-01', 'dns-01'],
|
||||
|
||||
acmeChallengePrefix: ACME.acmeChallengePrefix
|
||||
};
|
||||
|
||||
// backwards compat
|
||||
Object.keys(Greenlock.defaults).forEach(function(key) {
|
||||
Greenlock[key] = Greenlock.defaults[key];
|
||||
});
|
||||
|
||||
// show all possible options
|
||||
var u; // undefined
|
||||
Greenlock._undefined = {
|
||||
acme: u,
|
||||
store: u,
|
||||
//, challenge: u
|
||||
challenges: u,
|
||||
sni: u,
|
||||
tlsOptions: u,
|
||||
|
||||
register: u,
|
||||
check: u,
|
||||
|
||||
renewWithin: u, // le-auto-sni and core
|
||||
//, renewBy: u // le-auto-sni
|
||||
acmeChallengePrefix: u,
|
||||
rsaKeySize: u,
|
||||
challengeType: u,
|
||||
server: u,
|
||||
version: u,
|
||||
agreeToTerms: u,
|
||||
_ipc: u,
|
||||
duplicate: u,
|
||||
_acmeUrls: u
|
||||
};
|
||||
Greenlock._undefine = function(gl) {
|
||||
Object.keys(Greenlock._undefined).forEach(function(key) {
|
||||
if (!(key in gl)) {
|
||||
gl[key] = u;
|
||||
}
|
||||
});
|
||||
|
||||
return gl;
|
||||
};
|
||||
Greenlock.create = function(gl) {
|
||||
if (!gl.store) {
|
||||
console.warn(
|
||||
"Deprecation Notice: You're haven't chosen a storage strategy." +
|
||||
" The old default is 'le-store-certbot', but the new default will be 'greenlock-store-fs'." +
|
||||
" Please `npm install greenlock-store-fs@3` and explicitly set `{ store: require('greenlock-store-fs') }`."
|
||||
);
|
||||
gl.store = require('le-store-certbot').create({
|
||||
debug: gl.debug,
|
||||
configDir: gl.configDir,
|
||||
logsDir: gl.logsDir,
|
||||
webrootPath: gl.webrootPath
|
||||
});
|
||||
}
|
||||
gl.core = require('./lib/core');
|
||||
var log = gl.log || _log;
|
||||
|
||||
if (!gl.challenges) {
|
||||
gl.challenges = {};
|
||||
}
|
||||
if (!gl.challenges['http-01']) {
|
||||
gl.challenges['http-01'] = require('le-challenge-fs').create({
|
||||
debug: gl.debug,
|
||||
webrootPath: gl.webrootPath
|
||||
});
|
||||
}
|
||||
if (!gl.challenges['dns-01']) {
|
||||
try {
|
||||
gl.challenges['dns-01'] = require('le-challenge-ddns').create({
|
||||
debug: gl.debug
|
||||
});
|
||||
} catch (e) {
|
||||
try {
|
||||
gl.challenges['dns-01'] = require('le-challenge-dns').create({
|
||||
debug: gl.debug
|
||||
});
|
||||
} catch (e) {
|
||||
// not yet implemented
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gl = Greenlock._undefine(gl);
|
||||
gl.acmeChallengePrefix = Greenlock.acmeChallengePrefix;
|
||||
gl.rsaKeySize = gl.rsaKeySize || Greenlock.rsaKeySize;
|
||||
gl.challengeType = gl.challengeType || Greenlock.challengeType;
|
||||
gl._ipc = ipc;
|
||||
gl._communityPackage = gl._communityPackage || 'greenlock.js';
|
||||
if ('greenlock.js' === gl._communityPackage) {
|
||||
gl._communityPackageVersion = pkg.version;
|
||||
} else {
|
||||
gl._communityPackageVersion =
|
||||
gl._communityPackageVersion || 'greenlock.js-' + pkg.version;
|
||||
}
|
||||
gl.agreeToTerms =
|
||||
gl.agreeToTerms ||
|
||||
function(args, agreeCb) {
|
||||
agreeCb(
|
||||
new Error(
|
||||
"'agreeToTerms' was not supplied to Greenlock and 'agreeTos' was not supplied to Greenlock.register"
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
if (!gl.renewWithin) {
|
||||
gl.renewWithin = 14 * DAY;
|
||||
}
|
||||
// renewBy has a default in le-sni-auto
|
||||
|
||||
///////////////////////////
|
||||
// BEGIN VERSION MADNESS //
|
||||
///////////////////////////
|
||||
|
||||
gl.version = gl.version || 'draft-11';
|
||||
gl.server = gl.server || 'https://acme-v02.api.letsencrypt.org/directory';
|
||||
if (!gl.version) {
|
||||
//console.warn("Please specify version: 'v01' (Let's Encrypt v1) or 'draft-12' (Let's Encrypt v2 / ACME draft 12)");
|
||||
console.warn('');
|
||||
console.warn('');
|
||||
console.warn('');
|
||||
console.warn(
|
||||
'=========================================================='
|
||||
);
|
||||
console.warn(
|
||||
'== greenlock.js (v2.2.0+) =='
|
||||
);
|
||||
console.warn(
|
||||
'=========================================================='
|
||||
);
|
||||
console.warn('');
|
||||
console.warn("Please specify 'version' option:");
|
||||
console.warn('');
|
||||
console.warn(
|
||||
" 'draft-12' for Let's Encrypt v2 and ACME draft 12"
|
||||
);
|
||||
console.warn(" ('v02' is an alias of 'draft-12'");
|
||||
console.warn('');
|
||||
console.warn('or');
|
||||
console.warn('');
|
||||
console.warn(" 'v01' for Let's Encrypt v1 (deprecated)");
|
||||
console.warn(
|
||||
" (also 'npm install --save le-acme-core' as this legacy dependency will soon be removed)"
|
||||
);
|
||||
console.warn('');
|
||||
console.warn('This will be required in versions v2.3+');
|
||||
console.warn('');
|
||||
console.warn('');
|
||||
} else if ('v02' === gl.version) {
|
||||
gl.version = 'draft-11';
|
||||
} else if ('draft-12' === gl.version) {
|
||||
gl.version = 'draft-11';
|
||||
} else if ('draft-11' === gl.version) {
|
||||
// no-op
|
||||
} else if ('v01' !== gl.version) {
|
||||
throw new Error("Unrecognized version '" + gl.version + "'");
|
||||
}
|
||||
|
||||
if (!gl.server) {
|
||||
throw new Error(
|
||||
"opts.server must specify an ACME directory URL, such as 'https://acme-staging-v02.api.letsencrypt.org/directory'"
|
||||
);
|
||||
}
|
||||
if ('staging' === gl.server || 'production' === gl.server) {
|
||||
if ('staging' === gl.server) {
|
||||
gl.server = 'https://acme-staging.api.letsencrypt.org/directory';
|
||||
gl.version = 'v01';
|
||||
gl._deprecatedServerName = 'staging';
|
||||
} else if ('production' === gl.server) {
|
||||
gl.server = 'https://acme-v01.api.letsencrypt.org/directory';
|
||||
gl.version = 'v01';
|
||||
gl._deprecatedServerName = 'production';
|
||||
}
|
||||
console.warn('');
|
||||
console.warn('');
|
||||
console.warn('=== WARNING ===');
|
||||
console.warn('');
|
||||
console.warn(
|
||||
"Due to versioning issues the '" +
|
||||
gl._deprecatedServerName +
|
||||
"' option is deprecated."
|
||||
);
|
||||
console.warn('Please specify the full url and version.');
|
||||
console.warn('');
|
||||
console.warn('For APIs add:');
|
||||
console.warn('\t, "version": "' + gl.version + '"');
|
||||
console.warn('\t, "server": "' + gl.server + '"');
|
||||
console.warn('');
|
||||
console.warn('For the CLI add:');
|
||||
console.warn("\t--acme-url '" + gl.server + "' \\");
|
||||
console.warn("\t--acme-version '" + gl.version + "' \\");
|
||||
console.warn('');
|
||||
console.warn('');
|
||||
}
|
||||
|
||||
function loadLeV01() {
|
||||
console.warn('');
|
||||
console.warn('=== WARNING ===');
|
||||
console.warn('');
|
||||
console.warn("Let's Encrypt v1 is deprecated.");
|
||||
console.warn("Please update to Let's Encrypt v2 (ACME draft 12)");
|
||||
console.warn('');
|
||||
try {
|
||||
return require('le-acme-core').ACME;
|
||||
} catch (e) {
|
||||
console.error('');
|
||||
console.error('=== Error (easy-to-fix) ===');
|
||||
console.error('');
|
||||
console.error(
|
||||
"Hey, this isn't a big deal, but you need to manually add v1 support:"
|
||||
);
|
||||
console.error('');
|
||||
console.error(' npm install --save le-acme-core');
|
||||
console.error('');
|
||||
console.error(
|
||||
'Just run that real quick, restart, and everything will work great.'
|
||||
);
|
||||
console.error('');
|
||||
console.error('');
|
||||
process.exit(e.code || 13);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
-1 !==
|
||||
[
|
||||
'https://acme-v02.api.letsencrypt.org/directory',
|
||||
'https://acme-staging-v02.api.letsencrypt.org/directory'
|
||||
].indexOf(gl.server)
|
||||
) {
|
||||
if ('draft-11' !== gl.version) {
|
||||
console.warn(
|
||||
"Detected Let's Encrypt v02 URL. Changing version to draft-12."
|
||||
);
|
||||
gl.version = 'draft-11';
|
||||
}
|
||||
} else if (
|
||||
-1 !==
|
||||
[
|
||||
'https://acme-v01.api.letsencrypt.org/directory',
|
||||
'https://acme-staging.api.letsencrypt.org/directory'
|
||||
].indexOf(gl.server) ||
|
||||
'v01' === gl.version
|
||||
) {
|
||||
if ('v01' !== gl.version) {
|
||||
console.warn(
|
||||
"Detected Let's Encrypt v01 URL (deprecated). Changing version to v01."
|
||||
);
|
||||
gl.version = 'v01';
|
||||
}
|
||||
}
|
||||
if ('v01' === gl.version) {
|
||||
ACME = loadLeV01();
|
||||
}
|
||||
/////////////////////////
|
||||
// END VERSION MADNESS //
|
||||
/////////////////////////
|
||||
|
||||
gl.acme =
|
||||
gl.acme ||
|
||||
ACME.create({
|
||||
debug: gl.debug,
|
||||
skipChallengeTest: gl.skipChallengeTest,
|
||||
skipDryRun: gl.skipDryRun
|
||||
});
|
||||
if (gl.acme.create) {
|
||||
gl.acme = gl.acme.create(gl);
|
||||
}
|
||||
gl.acme = promisifyAllSelf(gl.acme);
|
||||
gl._acmeOpts =
|
||||
(gl.acme.getOptions && gl.acme.getOptions()) || gl.acme.options || {};
|
||||
Object.keys(gl._acmeOpts).forEach(function(key) {
|
||||
if (!(key in gl)) {
|
||||
gl[key] = gl._acmeOpts[key];
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
if (gl.store.create) {
|
||||
gl.store = gl.store.create(gl);
|
||||
}
|
||||
gl.store = promisifyAllSelf(gl.store);
|
||||
gl.store.accounts = promisifyAllStore(gl.store.accounts);
|
||||
gl.store.certificates = promisifyAllStore(gl.store.certificates);
|
||||
gl._storeOpts =
|
||||
(gl.store.getOptions && gl.store.getOptions()) ||
|
||||
gl.store.options ||
|
||||
{};
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.error(
|
||||
'\nPROBABLE CAUSE:\n' +
|
||||
'\tYour greenlock-store module should have a create function and return { options, accounts, certificates }\n'
|
||||
);
|
||||
process.exit(18);
|
||||
return;
|
||||
}
|
||||
Object.keys(gl._storeOpts).forEach(function(key) {
|
||||
if (!(key in gl)) {
|
||||
gl[key] = gl._storeOpts[key];
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// Backwards compat for <= v2.1.7
|
||||
//
|
||||
if (gl.challenge) {
|
||||
console.warn(
|
||||
"Deprecated use of gl.challenge. Use gl.challenges['" +
|
||||
Greenlock.challengeType +
|
||||
"'] instead."
|
||||
);
|
||||
gl.challenges[gl.challengeType] = gl.challenge;
|
||||
gl.challenge = undefined;
|
||||
}
|
||||
|
||||
Object.keys(gl.challenges || {}).forEach(function(challengeType) {
|
||||
var challenger = gl.challenges[challengeType];
|
||||
|
||||
if (challenger.create) {
|
||||
challenger = gl.challenges[challengeType] = challenger.create(gl);
|
||||
}
|
||||
challenger = gl.challenges[challengeType] = promisifyAllSelf(
|
||||
challenger
|
||||
);
|
||||
gl['_challengeOpts_' + challengeType] =
|
||||
(challenger.getOptions && challenger.getOptions()) ||
|
||||
challenger.options ||
|
||||
{};
|
||||
Object.keys(gl['_challengeOpts_' + challengeType]).forEach(function(
|
||||
key
|
||||
) {
|
||||
if (!(key in gl)) {
|
||||
gl[key] = gl['_challengeOpts_' + challengeType][key];
|
||||
}
|
||||
});
|
||||
|
||||
// TODO wrap these here and now with tplCopy?
|
||||
if (!challenger.set || ![5, 2, 1].includes(challenger.set.length)) {
|
||||
throw new Error(
|
||||
'gl.challenges[' +
|
||||
challengeType +
|
||||
'].set receives the wrong number of arguments.' +
|
||||
' You must define setChallenge as function (opts) { return Promise.resolve(); }'
|
||||
);
|
||||
}
|
||||
if (challenger.get && ![4, 2, 1].includes(challenger.get.length)) {
|
||||
throw new Error(
|
||||
'gl.challenges[' +
|
||||
challengeType +
|
||||
'].get receives the wrong number of arguments.' +
|
||||
' You must define getChallenge as function (opts) { return Promise.resolve(); }'
|
||||
);
|
||||
}
|
||||
if (
|
||||
!challenger.remove ||
|
||||
![4, 2, 1].includes(challenger.remove.length)
|
||||
) {
|
||||
throw new Error(
|
||||
'gl.challenges[' +
|
||||
challengeType +
|
||||
'].remove receives the wrong number of arguments.' +
|
||||
' You must define removeChallenge as function (opts) { return Promise.resolve(); }'
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
if (!gl._challengeWarn && (!challenger.loopback || 4 !== challenger.loopback.length)) {
|
||||
gl._challengeWarn = true;
|
||||
console.warn("gl.challenges[" + challengeType + "].loopback should be defined as function (opts, domain, token, cb) { ... } and should prove (by external means) that the ACME server challenge '" + challengeType + "' will succeed");
|
||||
}
|
||||
else if (!gl._challengeWarn && (!challenger.test || 5 !== challenger.test.length)) {
|
||||
gl._challengeWarn = true;
|
||||
console.warn("gl.challenges[" + challengeType + "].test should be defined as function (opts, domain, token, keyAuthorization, cb) { ... } and should prove (by external means) that the ACME server challenge '" + challengeType + "' will succeed");
|
||||
}
|
||||
*/
|
||||
});
|
||||
|
||||
gl.sni = gl.sni || null;
|
||||
gl.tlsOptions = gl.tlsOptions || gl.httpsOptions || {};
|
||||
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
gl._updateServernames = function(cert) {
|
||||
if (!gl._certnames) {
|
||||
gl._certnames = {};
|
||||
}
|
||||
|
||||
// Note: Any given domain could exist on multiple certs
|
||||
// (especially during renewal where some may be added)
|
||||
// hence we use a separate object for each domain and list each domain on it
|
||||
// to get the minimal full set associated with each cert and domain
|
||||
var allDomains = [cert.subject].concat(cert.altnames.slice(0));
|
||||
allDomains.forEach(function(name) {
|
||||
name = name.toLowerCase();
|
||||
if (!gl._certnames[name]) {
|
||||
gl._certnames[name] = {};
|
||||
}
|
||||
allDomains.forEach(function(name2) {
|
||||
name2 = name2.toLowerCase();
|
||||
gl._certnames[name][name2] = true;
|
||||
});
|
||||
});
|
||||
};
|
||||
gl._checkServername = function(safeHost, servername) {
|
||||
// odd, but acceptable
|
||||
if (!safeHost || !servername) {
|
||||
return true;
|
||||
}
|
||||
if (safeHost === servername) {
|
||||
return true;
|
||||
}
|
||||
// connection established with servername and session is re-used for allowed name
|
||||
if (gl._certnames[servername] && gl._certnames[servername][safeHost]) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
if (!gl.tlsOptions.SNICallback) {
|
||||
if (!gl.getCertificatesAsync && !gl.getCertificates) {
|
||||
if (Array.isArray(gl.approveDomains)) {
|
||||
gl.approvedDomains = gl.approveDomains;
|
||||
gl.approveDomains = null;
|
||||
}
|
||||
if (!gl.approveDomains) {
|
||||
gl.approveDomains = function(lexOpts, cb) {
|
||||
var err;
|
||||
var emsg;
|
||||
|
||||
if (!gl.email) {
|
||||
throw new Error(
|
||||
'le-sni-auto is not properly configured. Missing email'
|
||||
);
|
||||
}
|
||||
if (!gl.agreeTos) {
|
||||
throw new Error(
|
||||
'le-sni-auto is not properly configured. Missing agreeTos'
|
||||
);
|
||||
}
|
||||
if (!/[a-z]/i.test(lexOpts.domain)) {
|
||||
cb(
|
||||
new Error(
|
||||
'le-sni-auto does not allow IP addresses in SNI'
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Array.isArray(gl.approvedDomains)) {
|
||||
// The acme-v2 package uses pre-flight test challenges to
|
||||
// verify that each requested domain is hosted by the server
|
||||
// these checks are sufficient for most use cases
|
||||
return cb(null, lexOpts);
|
||||
}
|
||||
|
||||
if (
|
||||
lexOpts.domains.every(function(domain) {
|
||||
return -1 !== gl.approvedDomains.indexOf(domain);
|
||||
})
|
||||
) {
|
||||
// commented this out because people expect to be able to edit the list of domains
|
||||
// lexOpts.domains = gl.approvedDomains.slice(0);
|
||||
lexOpts.email = gl.email;
|
||||
lexOpts.agreeTos = gl.agreeTos;
|
||||
lexOpts.communityMember = gl.communityMember;
|
||||
lexOpts.telemetry = gl.telemetry;
|
||||
return cb(null, lexOpts);
|
||||
}
|
||||
|
||||
emsg =
|
||||
"tls SNI for '" +
|
||||
lexOpts.domains.join(',') +
|
||||
"' rejected: not in list '" +
|
||||
gl.approvedDomains +
|
||||
"'";
|
||||
log(gl.debug, emsg, lexOpts.domains, gl.approvedDomains);
|
||||
err = new Error(emsg);
|
||||
err.code = 'E_REJECT_SNI';
|
||||
cb(err);
|
||||
};
|
||||
}
|
||||
|
||||
gl.getCertificates = function(domain, certs, cb) {
|
||||
// certs come from current in-memory cache, not lookup
|
||||
log(
|
||||
gl.debug,
|
||||
'gl.getCertificates called for',
|
||||
domain,
|
||||
'with certs for',
|
||||
(certs && certs.altnames) || 'NONE'
|
||||
);
|
||||
var opts = {
|
||||
domain: domain,
|
||||
domains: (certs && certs.altnames) || [domain],
|
||||
certs: certs,
|
||||
certificate: {},
|
||||
account: {}
|
||||
};
|
||||
opts.wildname =
|
||||
'*.' +
|
||||
(domain || '')
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
|
||||
function cb2(results) {
|
||||
log(
|
||||
gl.debug,
|
||||
'gl.approveDomains called with certs for',
|
||||
(results.certs && results.certs.altnames) || 'NONE',
|
||||
'and options:'
|
||||
);
|
||||
log(gl.debug, results.options || results);
|
||||
var err;
|
||||
if (!results) {
|
||||
err = new Error('E_REJECT_SNI');
|
||||
err.code = 'E_REJECT_SNI';
|
||||
eb2(err);
|
||||
return;
|
||||
}
|
||||
|
||||
var options = results.options || results;
|
||||
if (opts !== options) {
|
||||
Object.keys(options).forEach(function(key) {
|
||||
if (
|
||||
'undefined' !== typeof options[key] &&
|
||||
'domain' !== key
|
||||
) {
|
||||
opts[key] = options[key];
|
||||
}
|
||||
});
|
||||
options = opts;
|
||||
}
|
||||
if (
|
||||
Array.isArray(options.altnames) &&
|
||||
options.altnames.length
|
||||
) {
|
||||
options.domains = options.altnames;
|
||||
}
|
||||
options.altnames = options.domains;
|
||||
// just in case we get a completely different object from the one we originally created
|
||||
if (!options.account) {
|
||||
options.account = {};
|
||||
}
|
||||
if (!options.certificate) {
|
||||
options.certificate = {};
|
||||
}
|
||||
if (results.certs) {
|
||||
log(gl.debug, 'gl renewing');
|
||||
return gl.core.certificates
|
||||
.renewAsync(options, results.certs)
|
||||
.then(
|
||||
function(certs) {
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
gl._updateServernames(certs);
|
||||
cb(null, certs);
|
||||
},
|
||||
function(e) {
|
||||
console.debug(
|
||||
"Error renewing certificate for '" +
|
||||
domain +
|
||||
"':"
|
||||
);
|
||||
console.debug(e);
|
||||
console.error('');
|
||||
cb(e);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
log(
|
||||
gl.debug,
|
||||
'gl getting from disk or registering new'
|
||||
);
|
||||
return gl.core.certificates.getAsync(options).then(
|
||||
function(certs) {
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
gl._updateServernames(certs);
|
||||
cb(null, certs);
|
||||
},
|
||||
function(e) {
|
||||
console.debug(
|
||||
"Error loading/registering certificate for '" +
|
||||
domain +
|
||||
"':"
|
||||
);
|
||||
console.debug(e);
|
||||
console.error('');
|
||||
cb(e);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
function eb2(_err) {
|
||||
if (false !== gl.logRejectedDomains) {
|
||||
console.error(
|
||||
"[Error] approveDomains rejected tls sni '" +
|
||||
domain +
|
||||
"'"
|
||||
);
|
||||
console.error(
|
||||
'[Error] (see https://git.coolaj86.com/coolaj86/greenlock.js/issues/11)'
|
||||
);
|
||||
if ('E_REJECT_SNI' !== _err.code) {
|
||||
console.error(
|
||||
'[Error] This is the rejection message:'
|
||||
);
|
||||
console.error(_err.message);
|
||||
}
|
||||
console.error('');
|
||||
}
|
||||
cb(_err);
|
||||
return;
|
||||
}
|
||||
function mb2(_err, results) {
|
||||
if (_err) {
|
||||
eb2(_err);
|
||||
return;
|
||||
}
|
||||
cb2(results);
|
||||
}
|
||||
|
||||
try {
|
||||
if (1 === gl.approveDomains.length) {
|
||||
Promise.resolve(gl.approveDomains(opts))
|
||||
.then(cb2)
|
||||
.catch(eb2);
|
||||
} else if (2 === gl.approveDomains.length) {
|
||||
gl.approveDomains(opts, mb2);
|
||||
} else {
|
||||
gl.approveDomains(opts, certs, mb2);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
'[ERROR] Something went wrong in approveDomains:'
|
||||
);
|
||||
console.error(e);
|
||||
console.error(
|
||||
"BUT WAIT! Good news: It's probably your fault, so you can probably fix it."
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
gl.sni = gl.sni || require('le-sni-auto');
|
||||
if (gl.sni.create) {
|
||||
gl.sni = gl.sni.create(gl);
|
||||
}
|
||||
gl.tlsOptions.SNICallback = function(_domain, cb) {
|
||||
// format and (lightly) sanitize sni so that users can be naive
|
||||
// and not have to worry about SQL injection or fs discovery
|
||||
var domain = (_domain || '').toLowerCase();
|
||||
// hostname labels allow a-z, 0-9, -, and are separated by dots
|
||||
// _ is sometimes allowed
|
||||
// REGEX // https://www.codeproject.com/Questions/1063023/alphanumeric-validation-javascript-without-regex
|
||||
if (
|
||||
!gl.__sni_allow_dangerous_names &&
|
||||
(!/^[a-z0-9_\.\-]+$/i.test(domain) ||
|
||||
-1 !== domain.indexOf('..'))
|
||||
) {
|
||||
log(gl.debug, "invalid sni '" + domain + "'");
|
||||
cb(new Error('invalid SNI'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
gl.sni.sniCallback(
|
||||
(gl.__sni_preserve_case && _domain) || domain,
|
||||
cb
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
'[ERROR] Something went wrong in the SNICallback:'
|
||||
);
|
||||
console.error(e);
|
||||
cb(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// We want to move to using tlsOptions instead of httpsOptions, but we also need to make
|
||||
// sure anything that uses this object will still work if looking for httpsOptions.
|
||||
gl.httpsOptions = gl.tlsOptions;
|
||||
|
||||
if (gl.core.create) {
|
||||
gl.core = gl.core.create(gl);
|
||||
}
|
||||
|
||||
gl.renew = function(args, certs) {
|
||||
return gl.core.certificates.renewAsync(args, certs);
|
||||
};
|
||||
|
||||
gl.register = function(args) {
|
||||
return gl.core.certificates.getAsync(args);
|
||||
};
|
||||
|
||||
gl.check = function(args) {
|
||||
// TODO must return email, domains, tos, pems
|
||||
return gl.core.certificates.checkAsync(args);
|
||||
};
|
||||
|
||||
gl.middleware = gl.middleware || require('./lib/middleware');
|
||||
if (gl.middleware.create) {
|
||||
gl.middleware = gl.middleware.create(gl);
|
||||
}
|
||||
|
||||
//var SERVERNAME_RE = /^[a-z0-9\.\-_]+$/;
|
||||
var SERVERNAME_G = /[^a-z0-9\.\-_]/;
|
||||
gl.middleware.sanitizeHost = function(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');
|
||||
}
|
||||
}
|
||||
// Get the host:port combo, if it exists
|
||||
var host = (req.headers.host || '').split(':');
|
||||
|
||||
// if not, move along
|
||||
if (!host[0]) {
|
||||
realNext();
|
||||
return;
|
||||
}
|
||||
|
||||
// if so, remove non-allowed characters
|
||||
var safehost = host[0].toLowerCase().replace(SERVERNAME_G, '');
|
||||
|
||||
// if there were unallowed characters, complain
|
||||
if (
|
||||
!gl.__sni_allow_dangerous_names &&
|
||||
safehost.length !== host[0].length
|
||||
) {
|
||||
res.statusCode = 400;
|
||||
res.end("Malformed HTTP Header: 'Host: " + host[0] + "'");
|
||||
return;
|
||||
}
|
||||
|
||||
// make lowercase
|
||||
if (!gl.__sni_preserve_case) {
|
||||
host[0] = safehost;
|
||||
req.headers.host = host.join(':');
|
||||
}
|
||||
|
||||
// Note: This sanitize function is also called on plain sockets, which don't need Domain Fronting checks
|
||||
if (req.socket.encrypted && !gl.__sni_allow_domain_fronting) {
|
||||
if (req.socket && 'string' === typeof req.socket.servername) {
|
||||
// Workaround for https://github.com/nodejs/node/issues/22389
|
||||
if (
|
||||
!gl._checkServername(
|
||||
safehost,
|
||||
req.socket.servername.toLowerCase()
|
||||
)
|
||||
) {
|
||||
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.middleware.sanitizeHost._skip_fronting_check
|
||||
) {
|
||||
// TODO how to handle wrapped sockets, as with telebit?
|
||||
console.warn(
|
||||
'\n\n\n[greenlock] WARN: no string for req.socket.servername,' +
|
||||
" skipping fronting check for '" +
|
||||
safehost +
|
||||
"'\n\n\n"
|
||||
);
|
||||
gl.middleware.sanitizeHost._skip_fronting_check = true;
|
||||
}
|
||||
}
|
||||
|
||||
// carry on
|
||||
realNext();
|
||||
};
|
||||
};
|
||||
gl.middleware.sanitizeHost._skip_fronting_check = false;
|
||||
|
||||
return gl;
|
||||
};
|
|
@ -1,80 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
function addCommunityMember(opts) {
|
||||
// { name, version, email, domains, action, communityMember, telemetry }
|
||||
var https = require('https');
|
||||
var req = https.request(
|
||||
{
|
||||
hostname: 'api.ppl.family',
|
||||
port: 443,
|
||||
path: '/api/ppl.family/public/list',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
},
|
||||
function(err, resp) {
|
||||
if (err) {
|
||||
return;
|
||||
}
|
||||
resp.on('data', function() {});
|
||||
}
|
||||
);
|
||||
req.on('error', function(error) {
|
||||
/* ignore */
|
||||
});
|
||||
var os = require('os');
|
||||
var data = {
|
||||
address: opts.email,
|
||||
// greenlock-security is transactional and security only
|
||||
list: opts.communityMember
|
||||
? opts.name + '@ppl.family'
|
||||
: 'greenlock-security@ppl.family',
|
||||
action: opts.action, // reg | renew
|
||||
package: opts.name,
|
||||
// hashed for privacy, but so we can still get some telemetry and inform users
|
||||
// if abnormal things are happening (like several registrations for the same domain each day)
|
||||
domain: (opts.domains || [])
|
||||
.map(function(d) {
|
||||
return require('crypto')
|
||||
.createHash('sha1')
|
||||
.update(d)
|
||||
.digest('base64')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/=/g, '');
|
||||
})
|
||||
.join(',')
|
||||
};
|
||||
if (false !== opts.telemetry) {
|
||||
data.arch = process.arch || os.arch();
|
||||
data.platform = process.platform || os.platform();
|
||||
data.release = os.release();
|
||||
data.version = opts.version;
|
||||
data.node = process.version;
|
||||
}
|
||||
req.write(JSON.stringify(data, 2, null));
|
||||
req.end();
|
||||
}
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise(function(resolve) {
|
||||
return setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports.add = function(opts) {
|
||||
return delay(50)
|
||||
.then(() => {
|
||||
return addCommunityMember(opts);
|
||||
})
|
||||
.catch(function(ex) {
|
||||
/* ignore */
|
||||
});
|
||||
};
|
||||
|
||||
if (require.main === module) {
|
||||
//addCommunityMember('greenlock-express.js', 'reg', 'coolaj86+test42@gmail.com', ['coolaj86.com'], true);
|
||||
//addCommunityMember('greenlock.js', 'reg', 'coolaj86+test37@gmail.com', ['oneal.im'], false);
|
||||
//addCommunityMember('greenlock.js', 'reg', 'coolaj86+test11@gmail.com', ['ppl.family'], true);
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
'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;
|
||||
}
|
958
lib/core.js
958
lib/core.js
|
@ -1,958 +0,0 @@
|
|||
'use strict';
|
||||
/*global Promise*/
|
||||
require('./compat.js');
|
||||
|
||||
var util = require('util');
|
||||
function promisifyAll(obj) {
|
||||
var aobj = {};
|
||||
Object.keys(obj).forEach(function(key) {
|
||||
if ('function' === typeof obj[key]) {
|
||||
aobj[key] = obj[key];
|
||||
aobj[key + 'Async'] = util.promisify(obj[key]);
|
||||
}
|
||||
});
|
||||
return aobj;
|
||||
}
|
||||
|
||||
function _log(debug) {
|
||||
if (debug) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.shift();
|
||||
args.unshift('[greenlock/lib/core.js]');
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.create = function(gl) {
|
||||
var utils = require('./utils');
|
||||
var RSA = promisifyAll(require('rsa-compat').RSA);
|
||||
var log = gl.log || _log; // allow custom log
|
||||
var pendingRegistrations = {};
|
||||
|
||||
var core = {
|
||||
//
|
||||
// Helpers
|
||||
//
|
||||
getAcmeUrlsAsync: function(args) {
|
||||
var now = Date.now();
|
||||
|
||||
// TODO check response header on request for cache time
|
||||
if (now - gl._ipc.acmeUrlsUpdatedAt < 10 * 60 * 1000) {
|
||||
return Promise.resolve(gl._ipc.acmeUrls);
|
||||
}
|
||||
|
||||
// TODO acme-v2/nocompat
|
||||
return gl.acme.getAcmeUrlsAsync(args.server).then(function(data) {
|
||||
gl._ipc.acmeUrlsUpdatedAt = Date.now();
|
||||
gl._ipc.acmeUrls = data;
|
||||
|
||||
return gl._ipc.acmeUrls;
|
||||
});
|
||||
},
|
||||
|
||||
//
|
||||
// The Main Enchilada
|
||||
//
|
||||
|
||||
//
|
||||
// Accounts
|
||||
//
|
||||
accounts: {
|
||||
// Accounts
|
||||
registerAsync: function(args) {
|
||||
var err;
|
||||
var copy = utils.merge(args, gl);
|
||||
var disagreeTos;
|
||||
args = utils.tplCopy(copy);
|
||||
if (!args.account) {
|
||||
args.account = {};
|
||||
}
|
||||
if ('object' === typeof args.account && !args.account.id) {
|
||||
args.account.id = args.accountId || args.email || '';
|
||||
}
|
||||
|
||||
disagreeTos =
|
||||
!args.agreeTos && 'undefined' !== typeof args.agreeTos;
|
||||
if (
|
||||
!args.email ||
|
||||
disagreeTos ||
|
||||
parseInt(args.rsaKeySize, 10) < 2048
|
||||
) {
|
||||
err = new Error(
|
||||
"In order to register an account both 'email' and 'agreeTos' must be present" +
|
||||
" and 'rsaKeySize' must be 2048 or greater."
|
||||
);
|
||||
err.code = 'E_ARGS';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
return utils.testEmail(args.email).then(function() {
|
||||
if (
|
||||
args.account &&
|
||||
args.account.privkey &&
|
||||
(args.account.privkey.jwk || args.account.privkey.pem)
|
||||
) {
|
||||
// TODO import jwk or pem and return it here
|
||||
console.warn(
|
||||
'TODO: implement accounts.checkKeypairAsync skipping'
|
||||
);
|
||||
}
|
||||
var accountKeypair;
|
||||
var newAccountKeypair = true;
|
||||
var promise = gl.store.accounts
|
||||
.checkKeypairAsync(args)
|
||||
.then(function(keypair) {
|
||||
if (keypair) {
|
||||
// TODO keypairs
|
||||
newAccountKeypair = false;
|
||||
accountKeypair = RSA.import(keypair);
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.accountKeypair) {
|
||||
// TODO keypairs
|
||||
accountKeypair = RSA.import(
|
||||
args.accountKeypair
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var keypairOpts = {
|
||||
bitlen: args.rsaKeySize,
|
||||
exp: 65537,
|
||||
public: true,
|
||||
pem: true
|
||||
};
|
||||
// TODO keypairs
|
||||
return (args.generateKeypair ||
|
||||
RSA.generateKeypairAsync)(keypairOpts).then(
|
||||
function(keypair) {
|
||||
keypair.privateKeyPem = RSA.exportPrivatePem(
|
||||
keypair
|
||||
);
|
||||
keypair.publicKeyPem = RSA.exportPublicPem(
|
||||
keypair
|
||||
);
|
||||
keypair.privateKeyJwk = RSA.exportPrivateJwk(
|
||||
keypair
|
||||
);
|
||||
accountKeypair = keypair;
|
||||
}
|
||||
);
|
||||
})
|
||||
.then(function() {
|
||||
return accountKeypair;
|
||||
});
|
||||
|
||||
return promise.then(function(keypair) {
|
||||
// Note: the ACME urls are always fetched fresh on purpose
|
||||
// TODO acme-v2/nocompat
|
||||
return core.getAcmeUrlsAsync(args).then(function(urls) {
|
||||
args._acmeUrls = urls;
|
||||
|
||||
// TODO acme-v2/nocompat
|
||||
return gl.acme
|
||||
.registerNewAccountAsync({
|
||||
email: args.email,
|
||||
newRegUrl: args._acmeUrls.newReg,
|
||||
newAuthzUrl: args._acmeUrls.newAuthz,
|
||||
agreeToTerms: function(tosUrl, agreeCb) {
|
||||
if (
|
||||
true === args.agreeTos ||
|
||||
tosUrl === args.agreeTos ||
|
||||
tosUrl === gl.agreeToTerms
|
||||
) {
|
||||
agreeCb(null, tosUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
// args.email = email; // already there
|
||||
// args.domains = domains // already there
|
||||
args.tosUrl = tosUrl;
|
||||
gl.agreeToTerms(args, agreeCb);
|
||||
},
|
||||
accountKeypair: keypair,
|
||||
|
||||
debug: gl.debug || args.debug
|
||||
})
|
||||
.then(function(receipt) {
|
||||
var reg = {
|
||||
keypair: keypair,
|
||||
receipt: receipt,
|
||||
kid:
|
||||
receipt &&
|
||||
receipt.key &&
|
||||
(receipt.key.kid || receipt.kid),
|
||||
email: args.email,
|
||||
newRegUrl: args._acmeUrls.newReg,
|
||||
newAuthzUrl: args._acmeUrls.newAuthz
|
||||
};
|
||||
|
||||
var accountKeypairPromise;
|
||||
args.keypair = keypair;
|
||||
args.receipt = receipt;
|
||||
if (newAccountKeypair) {
|
||||
accountKeypairPromise = gl.store.accounts.setKeypairAsync(
|
||||
args,
|
||||
keypair
|
||||
);
|
||||
}
|
||||
return Promise.resolve(
|
||||
accountKeypairPromise
|
||||
).then(function() {
|
||||
// TODO move templating of arguments to right here?
|
||||
if (!gl.store.accounts.setAsync) {
|
||||
return Promise.resolve({
|
||||
keypair: keypair
|
||||
});
|
||||
}
|
||||
return gl.store.accounts
|
||||
.setAsync(args, reg)
|
||||
.then(function(account) {
|
||||
if (
|
||||
account &&
|
||||
'object' !== typeof account
|
||||
) {
|
||||
throw new Error(
|
||||
"store.accounts.setAsync should either return 'null' or an object with at least a string 'id'"
|
||||
);
|
||||
}
|
||||
if (!account) {
|
||||
account = {};
|
||||
}
|
||||
account.keypair = keypair;
|
||||
return account;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// Accounts
|
||||
// (only used for keypair)
|
||||
getAsync: function(args) {
|
||||
var accountPromise = null;
|
||||
if (gl.store.accounts.checkAsync) {
|
||||
accountPromise = core.accounts.checkAsync(args);
|
||||
}
|
||||
return Promise.resolve(accountPromise).then(function(account) {
|
||||
if (!account) {
|
||||
return core.accounts.registerAsync(args);
|
||||
}
|
||||
if (account.keypair) {
|
||||
return account;
|
||||
}
|
||||
|
||||
if (!args.account) {
|
||||
args.account = {};
|
||||
}
|
||||
if ('object' === typeof args.account && !args.account.id) {
|
||||
args.account.id = args.accountId || args.email || '';
|
||||
}
|
||||
var copy = utils.merge(args, gl);
|
||||
args = utils.tplCopy(copy);
|
||||
return gl.store.accounts
|
||||
.checkKeypairAsync(args)
|
||||
.then(function(keypair) {
|
||||
if (keypair) {
|
||||
return { keypair: keypair };
|
||||
}
|
||||
return core.accounts.registerAsync(args);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// Accounts
|
||||
checkAsync: function(args) {
|
||||
var requiredArgs = ['accountId', 'email', 'domains', 'domain'];
|
||||
if (
|
||||
!(args.account && (args.account.id || args.account.kid)) &&
|
||||
!requiredArgs.some(function(key) {
|
||||
return -1 !== Object.keys(args).indexOf(key);
|
||||
})
|
||||
) {
|
||||
return Promise.reject(
|
||||
new Error(
|
||||
"In order to register or retrieve an account one of '" +
|
||||
requiredArgs.join("', '") +
|
||||
"' must be present"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
var copy = utils.merge(args, gl);
|
||||
args = utils.tplCopy(copy);
|
||||
if (!args.account) {
|
||||
args.account = {};
|
||||
}
|
||||
if ('object' === typeof args.account && !args.account.id) {
|
||||
args.account.id = args.accountId || args.email || '';
|
||||
}
|
||||
|
||||
// we can re-register the same account until we're blue in the face and it's all the same
|
||||
// of course, we can also skip the lookup if we do store the account, but whatever
|
||||
if (!gl.store.accounts.checkAsync) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return gl.store.accounts
|
||||
.checkAsync(args)
|
||||
.then(function(account) {
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
|
||||
args.account = account;
|
||||
args.accountId = account.id;
|
||||
|
||||
return account;
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
certificates: {
|
||||
// Certificates
|
||||
registerAsync: function(args) {
|
||||
var err;
|
||||
var challengeDefaults =
|
||||
gl[
|
||||
'_challengeOpts_' +
|
||||
(args.challengeType || gl.challengeType)
|
||||
] || {};
|
||||
var copy = utils.merge(args, challengeDefaults || {});
|
||||
copy = utils.merge(copy, gl);
|
||||
if (!copy.subject) {
|
||||
copy.subject = copy.domains[0];
|
||||
}
|
||||
if (!copy.domain) {
|
||||
copy.domain = copy.domains[0];
|
||||
}
|
||||
args = utils.tplCopy(copy);
|
||||
|
||||
if (!Array.isArray(args.domains)) {
|
||||
return Promise.reject(
|
||||
new Error('args.domains should be an array of domains')
|
||||
);
|
||||
}
|
||||
//if (-1 === args.domains.indexOf(args.subject)) // TODO relax the constraint once acme-v2 handles subject?
|
||||
if (args.subject !== args.domains[0]) {
|
||||
console.warn(
|
||||
"The certificate's subject (primary domain) should be first in the list of opts.domains"
|
||||
);
|
||||
console.warn(
|
||||
'\topts.subject: (set by you approveDomains(), falling back to opts.domain) ' +
|
||||
args.subject
|
||||
);
|
||||
console.warn(
|
||||
'\topts.domain: (set by SNICallback()) ' + args.domain
|
||||
);
|
||||
console.warn(
|
||||
'\topts.domains: (set by you in approveDomains()) ' +
|
||||
args.domains.join(',')
|
||||
);
|
||||
console.warn(
|
||||
'Updating your code will prevent weird, random, hard-to-repro bugs during renewals'
|
||||
);
|
||||
console.warn(
|
||||
'(also this will be required in the next major version of greenlock)'
|
||||
);
|
||||
//return Promise.reject(new Error('certificate subject (primary domain) must be the first in opts.domains'));
|
||||
}
|
||||
if (
|
||||
!(
|
||||
args.domains.length &&
|
||||
args.domains.every(utils.isValidDomain)
|
||||
)
|
||||
) {
|
||||
// NOTE: this library can't assume to handle the http loopback
|
||||
// (or dns-01 validation may be used)
|
||||
// so we do not check dns records or attempt a loopback here
|
||||
err = new Error(
|
||||
"invalid domain name(s): '(" +
|
||||
args.subject +
|
||||
') ' +
|
||||
args.domains.join(',') +
|
||||
"'"
|
||||
);
|
||||
err.code = 'INVALID_DOMAIN';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
// If a previous request to (re)register a certificate is already underway we need
|
||||
// to return the same promise created before rather than registering things twice.
|
||||
// I'm not 100% sure how to properly handle the case where someone registers domain
|
||||
// lists with some but not all elements common, nor am I sure that's even a case that
|
||||
// is allowed to happen anyway. But for now we act like the list is completely the
|
||||
// same if any elements are the same.
|
||||
var promise;
|
||||
args.domains.some(function(name) {
|
||||
if (pendingRegistrations.hasOwnProperty(name)) {
|
||||
promise = pendingRegistrations[name];
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (promise) {
|
||||
return promise;
|
||||
}
|
||||
|
||||
promise = core.certificates._runRegistration(args);
|
||||
|
||||
// Now that the registration is actually underway we need to make sure any subsequent
|
||||
// registration attempts return the same promise until it is completed (but not after
|
||||
// it is completed).
|
||||
args.domains.forEach(function(name) {
|
||||
pendingRegistrations[name] = promise;
|
||||
});
|
||||
function clearPending() {
|
||||
args.domains.forEach(function(name) {
|
||||
delete pendingRegistrations[name];
|
||||
});
|
||||
}
|
||||
promise.then(clearPending, clearPending);
|
||||
|
||||
return promise;
|
||||
},
|
||||
_runRegistration: function(args) {
|
||||
// TODO renewal cb
|
||||
// accountId and or email
|
||||
return core.accounts.getAsync(args).then(function(account) {
|
||||
args.account = account;
|
||||
|
||||
if (
|
||||
args.certificate &&
|
||||
args.certificate.privkey &&
|
||||
(args.certificate.privkey.jwk ||
|
||||
args.certificate.privkey.pem)
|
||||
) {
|
||||
// TODO import jwk or pem and return it here
|
||||
console.warn(
|
||||
'TODO: implement certificates.checkKeypairAsync skipping'
|
||||
);
|
||||
}
|
||||
var domainKeypair;
|
||||
var newDomainKeypair = true;
|
||||
// This has been done in the getAsync already, so we skip it here
|
||||
// if approveDomains doesn't set subject, we set it here
|
||||
//args.subject = args.subject || args.domains[0];
|
||||
var promise = gl.store.certificates
|
||||
.checkKeypairAsync(args)
|
||||
.then(function(keypair) {
|
||||
if (keypair) {
|
||||
domainKeypair = RSA.import(keypair);
|
||||
newDomainKeypair = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.domainKeypair) {
|
||||
domainKeypair = RSA.import(args.domainKeypair);
|
||||
return;
|
||||
}
|
||||
|
||||
var keypairOpts = {
|
||||
bitlen: args.rsaKeySize,
|
||||
exp: 65537,
|
||||
public: true,
|
||||
pem: true
|
||||
};
|
||||
return (args.generateKeypair ||
|
||||
RSA.generateKeypairAsync)(keypairOpts).then(
|
||||
function(keypair) {
|
||||
keypair.privateKeyPem = RSA.exportPrivatePem(
|
||||
keypair
|
||||
);
|
||||
keypair.publicKeyPem = RSA.exportPublicPem(
|
||||
keypair
|
||||
);
|
||||
keypair.privateKeyJwk = RSA.exportPrivateJwk(
|
||||
keypair
|
||||
);
|
||||
domainKeypair = keypair;
|
||||
}
|
||||
);
|
||||
})
|
||||
.then(function() {
|
||||
return domainKeypair;
|
||||
});
|
||||
|
||||
return promise
|
||||
.then(function(domainKeypair) {
|
||||
args.domainKeypair = domainKeypair;
|
||||
//args.registration = domainKey;
|
||||
|
||||
// Note: the ACME urls are always fetched fresh on purpose
|
||||
// TODO is this the right place for this?
|
||||
return core
|
||||
.getAcmeUrlsAsync(args)
|
||||
.then(function(urls) {
|
||||
args._acmeUrls = urls;
|
||||
|
||||
var certReq = {
|
||||
debug: args.debug || gl.debug,
|
||||
|
||||
newAuthzUrl: args._acmeUrls.newAuthz,
|
||||
newCertUrl: args._acmeUrls.newCert,
|
||||
|
||||
accountKeypair: RSA.import(
|
||||
account.keypair
|
||||
),
|
||||
domainKeypair: domainKeypair,
|
||||
subject: args.subject, // TODO handle this in acme-v2
|
||||
domains: args.domains,
|
||||
challengeTypes: Object.keys(
|
||||
args.challenges
|
||||
)
|
||||
};
|
||||
|
||||
//
|
||||
// IMPORTANT
|
||||
//
|
||||
// setChallenge and removeChallenge are handed defaults
|
||||
// instead of args because getChallenge does not have
|
||||
// access to args
|
||||
// (args is per-request, defaults is per instance)
|
||||
//
|
||||
// Each of these fires individually for each domain,
|
||||
// even though the certificate on the whole may have many domains
|
||||
//
|
||||
certReq.setChallenge = function(
|
||||
challenge,
|
||||
done
|
||||
) {
|
||||
log(
|
||||
args.debug,
|
||||
"setChallenge called for '" +
|
||||
challenge.altname +
|
||||
"'"
|
||||
);
|
||||
// NOTE: First arg takes precedence
|
||||
var copy = utils.merge(
|
||||
{ domains: [challenge.altname] },
|
||||
args
|
||||
);
|
||||
copy = utils.merge(copy, gl);
|
||||
utils.tplCopy(copy);
|
||||
copy.challenge = challenge;
|
||||
|
||||
if (
|
||||
1 ===
|
||||
copy.challenges[challenge.type].set
|
||||
.length
|
||||
) {
|
||||
copy.challenges[challenge.type]
|
||||
.set(copy)
|
||||
.then(function(result) {
|
||||
done(null, result);
|
||||
})
|
||||
.catch(done);
|
||||
} else if (
|
||||
2 ===
|
||||
copy.challenges[challenge.type].set
|
||||
.length
|
||||
) {
|
||||
copy.challenges[challenge.type].set(
|
||||
copy,
|
||||
done
|
||||
);
|
||||
} else {
|
||||
Object.keys(challenge).forEach(
|
||||
function(key) {
|
||||
done[key] = challenge[key];
|
||||
}
|
||||
);
|
||||
// regression bugfix for le-challenge-cloudflare
|
||||
// (_acme-challege => _greenlock-dryrun-XXXX)
|
||||
copy.acmePrefix =
|
||||
(
|
||||
challenge.dnsHost || ''
|
||||
).replace(/\.*/, '') ||
|
||||
copy.acmePrefix;
|
||||
copy.challenges[challenge.type].set(
|
||||
copy,
|
||||
challenge.altname,
|
||||
challenge.token,
|
||||
challenge.keyAuthorization,
|
||||
done
|
||||
);
|
||||
}
|
||||
};
|
||||
certReq.removeChallenge = function(
|
||||
challenge,
|
||||
done
|
||||
) {
|
||||
log(
|
||||
args.debug,
|
||||
"removeChallenge called for '" +
|
||||
challenge.altname +
|
||||
"'"
|
||||
);
|
||||
var copy = utils.merge(
|
||||
{ domains: [challenge.altname] },
|
||||
args
|
||||
);
|
||||
copy = utils.merge(copy, gl);
|
||||
utils.tplCopy(copy);
|
||||
copy.challenge = challenge;
|
||||
|
||||
if (
|
||||
1 ===
|
||||
copy.challenges[challenge.type]
|
||||
.remove.length
|
||||
) {
|
||||
copy.challenges[challenge.type]
|
||||
.remove(copy)
|
||||
.then(function(result) {
|
||||
done(null, result);
|
||||
})
|
||||
.catch(done);
|
||||
} else if (
|
||||
2 ===
|
||||
copy.challenges[challenge.type]
|
||||
.remove.length
|
||||
) {
|
||||
copy.challenges[
|
||||
challenge.type
|
||||
].remove(copy, done);
|
||||
} else {
|
||||
Object.keys(challenge).forEach(
|
||||
function(key) {
|
||||
done[key] = challenge[key];
|
||||
}
|
||||
);
|
||||
copy.challenges[
|
||||
challenge.type
|
||||
].remove(
|
||||
copy,
|
||||
challenge.altname,
|
||||
challenge.token,
|
||||
done
|
||||
);
|
||||
}
|
||||
};
|
||||
certReq.init = function(deps) {
|
||||
var copy = utils.merge(deps, args);
|
||||
copy = utils.merge(copy, gl);
|
||||
utils.tplCopy(copy);
|
||||
|
||||
Object.keys(copy.challenges).forEach(
|
||||
function(key) {
|
||||
if (
|
||||
'function' ===
|
||||
typeof copy.challenges[key]
|
||||
.init
|
||||
) {
|
||||
copy.challenges[key].init(
|
||||
copy
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return null;
|
||||
};
|
||||
certReq.getZones = function(challenge) {
|
||||
var copy = utils.merge(
|
||||
{
|
||||
dnsHosts: args.domains.map(
|
||||
function(x) {
|
||||
return 'xxxx.' + x;
|
||||
}
|
||||
)
|
||||
},
|
||||
args
|
||||
);
|
||||
copy = utils.merge(copy, gl);
|
||||
utils.tplCopy(copy);
|
||||
copy.challenge = challenge;
|
||||
|
||||
if (
|
||||
!copy.challenges[challenge.type] ||
|
||||
'function' !==
|
||||
typeof copy.challenges[
|
||||
challenge.type
|
||||
].zones
|
||||
) {
|
||||
// may not be available, that's fine.
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return copy.challenges[
|
||||
challenge.type
|
||||
].zones(copy);
|
||||
};
|
||||
|
||||
log(
|
||||
args.debug,
|
||||
'calling greenlock.acme.getCertificateAsync',
|
||||
certReq.subject,
|
||||
certReq.domains
|
||||
);
|
||||
|
||||
// TODO acme-v2/nocompat
|
||||
return gl.acme
|
||||
.getCertificateAsync(certReq)
|
||||
.then(utils.attachCertInfo);
|
||||
});
|
||||
})
|
||||
.then(function(results) {
|
||||
//var requested = {};
|
||||
//var issued = {};
|
||||
// { cert, chain, privkey /*TODO, subject, altnames, issuedAt, expiresAt */ }
|
||||
|
||||
// args.certs.privkey = RSA.exportPrivatePem(options.domainKeypair);
|
||||
args.certs = results;
|
||||
// args.pems is deprecated
|
||||
args.pems = results;
|
||||
// This has been done in the getAsync already, so we skip it here
|
||||
// if approveDomains doesn't set subject, we set it here
|
||||
//args.subject = args.subject || args.domains[0];
|
||||
var promise;
|
||||
if (newDomainKeypair) {
|
||||
args.keypair = domainKeypair;
|
||||
promise = gl.store.certificates.setKeypairAsync(
|
||||
args,
|
||||
domainKeypair
|
||||
);
|
||||
}
|
||||
return Promise.resolve(promise).then(function() {
|
||||
return gl.store.certificates
|
||||
.setAsync(args)
|
||||
.then(function() {
|
||||
return results;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
// Certificates
|
||||
renewAsync: function(args, certs) {
|
||||
var renewableAt = core.certificates._getRenewableAt(
|
||||
args,
|
||||
certs
|
||||
);
|
||||
var err;
|
||||
//var halfLife = (certs.expiresAt - certs.issuedAt) / 2;
|
||||
//var renewable = (Date.now() - certs.issuedAt) > halfLife;
|
||||
|
||||
log(
|
||||
args.debug,
|
||||
'(Renew) Expires At',
|
||||
new Date(certs.expiresAt).toISOString()
|
||||
);
|
||||
log(
|
||||
args.debug,
|
||||
'(Renew) Renewable At',
|
||||
new Date(renewableAt).toISOString()
|
||||
);
|
||||
|
||||
if (!args.duplicate && Date.now() < renewableAt) {
|
||||
err = new Error(
|
||||
"[ERROR] Certificate issued at '" +
|
||||
new Date(certs.issuedAt).toISOString() +
|
||||
"' and expires at '" +
|
||||
new Date(certs.expiresAt).toISOString() +
|
||||
"'. Ignoring renewal attempt until '" +
|
||||
new Date(renewableAt).toISOString() +
|
||||
"'. Set { duplicate: true } to force."
|
||||
);
|
||||
err.code = 'E_NOT_RENEWABLE';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
// Either the cert has entered its renewal period
|
||||
// or we're forcing a refresh via 'dupliate: true'
|
||||
log(args.debug, 'Renewing!');
|
||||
|
||||
if (!args.domains || !args.domains.length) {
|
||||
args.domains =
|
||||
args.servernames ||
|
||||
[certs.subject].concat(certs.altnames);
|
||||
}
|
||||
|
||||
return core.certificates.registerAsync(args);
|
||||
},
|
||||
// Certificates
|
||||
_isRenewable: function(args, certs) {
|
||||
var renewableAt = core.certificates._getRenewableAt(
|
||||
args,
|
||||
certs
|
||||
);
|
||||
|
||||
log(
|
||||
args.debug,
|
||||
'Check Expires At',
|
||||
new Date(certs.expiresAt).toISOString()
|
||||
);
|
||||
log(
|
||||
args.debug,
|
||||
'Check Renewable At',
|
||||
new Date(renewableAt).toISOString()
|
||||
);
|
||||
|
||||
if (args.duplicate || Date.now() >= renewableAt) {
|
||||
log(args.debug, 'certificates are renewable');
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
_getRenewableAt: function(args, certs) {
|
||||
return certs.expiresAt - (args.renewWithin || gl.renewWithin);
|
||||
},
|
||||
checkAsync: function(args) {
|
||||
var copy = utils.merge(args, gl);
|
||||
// if approveDomains doesn't set subject, we set it here
|
||||
if (!(copy.domains && copy.domains.length)) {
|
||||
copy.domains = [copy.subject || copy.domain].filter(
|
||||
Boolean
|
||||
);
|
||||
}
|
||||
if (!copy.subject) {
|
||||
copy.subject = copy.domains[0];
|
||||
}
|
||||
if (!copy.domain) {
|
||||
copy.domain = copy.domains[0];
|
||||
}
|
||||
args = utils.tplCopy(copy);
|
||||
|
||||
// returns pems
|
||||
return gl.store.certificates
|
||||
.checkAsync(args)
|
||||
.then(function(cert) {
|
||||
if (!cert) {
|
||||
log(
|
||||
args.debug,
|
||||
'checkAsync failed to find certificates'
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
cert = utils.attachCertInfo(cert);
|
||||
if (utils.certHasDomain(cert, args.domain)) {
|
||||
log(
|
||||
args.debug,
|
||||
'checkAsync found existing certificates'
|
||||
);
|
||||
|
||||
if (cert.privkey) {
|
||||
return cert;
|
||||
} else {
|
||||
return gl.store.certificates
|
||||
.checkKeypairAsync(args)
|
||||
.then(function(keypair) {
|
||||
cert.privkey =
|
||||
keypair.privateKeyPem ||
|
||||
RSA.exportPrivatePem(keypair);
|
||||
return cert;
|
||||
});
|
||||
}
|
||||
}
|
||||
log(
|
||||
args.debug,
|
||||
'checkAsync found mismatched / incomplete certificates'
|
||||
);
|
||||
});
|
||||
},
|
||||
// Certificates
|
||||
getAsync: function(args) {
|
||||
var copy = utils.merge(args, gl);
|
||||
// if approveDomains doesn't set subject, we set it here
|
||||
if (!(copy.domains && copy.domains.length)) {
|
||||
copy.domains = [copy.subject || copy.domain].filter(
|
||||
Boolean
|
||||
);
|
||||
}
|
||||
if (!copy.subject) {
|
||||
copy.subject = copy.domains[0];
|
||||
}
|
||||
if (!copy.domain) {
|
||||
copy.domain = copy.domains[0];
|
||||
}
|
||||
args = utils.tplCopy(copy);
|
||||
|
||||
if (
|
||||
args.certificate &&
|
||||
args.certificate.privkey &&
|
||||
args.certificate.cert &&
|
||||
args.certificate.chain
|
||||
) {
|
||||
// TODO skip fetching a certificate if it's fetched during approveDomains
|
||||
console.warn(
|
||||
'TODO: implement certificates.checkAsync skipping'
|
||||
);
|
||||
}
|
||||
return core.certificates
|
||||
.checkAsync(args)
|
||||
.then(function(certs) {
|
||||
if (certs) {
|
||||
certs = utils.attachCertInfo(certs);
|
||||
}
|
||||
if (
|
||||
!certs ||
|
||||
!utils.certHasDomain(certs, args.domain)
|
||||
) {
|
||||
// There is no cert available
|
||||
if (
|
||||
false !== args.securityUpdates &&
|
||||
!args._communityMemberAdded
|
||||
) {
|
||||
// We will notify all greenlock users of mandatory and security updates
|
||||
// We'll keep track of versions and os so we can make sure things work well
|
||||
// { name, version, email, domains, action, communityMember, telemetry }
|
||||
require('./community').add({
|
||||
name: args._communityPackage,
|
||||
version: args._communityPackageVersion,
|
||||
email: args.email,
|
||||
domains: args.domains || args.servernames,
|
||||
action: 'reg',
|
||||
communityMember: args.communityMember,
|
||||
telemetry: args.telemetry
|
||||
});
|
||||
args._communityMemberAdded = true;
|
||||
}
|
||||
return core.certificates.registerAsync(args);
|
||||
}
|
||||
|
||||
if (core.certificates._isRenewable(args, certs)) {
|
||||
// it's time to renew the available cert
|
||||
if (
|
||||
false !== args.securityUpdates &&
|
||||
!args._communityMemberAdded
|
||||
) {
|
||||
// We will notify all greenlock users of mandatory and security updates
|
||||
// We'll keep track of versions and os so we can make sure things work well
|
||||
// { name, version, email, domains, action, communityMember, telemetry }
|
||||
require('./community').add({
|
||||
name: args._communityPackage,
|
||||
version: args._communityPackageVersion,
|
||||
email: args.email,
|
||||
domains: args.domains || args.servernames,
|
||||
action: 'renew',
|
||||
communityMember: args.communityMember,
|
||||
telemetry: args.telemetry
|
||||
});
|
||||
args._communityMemberAdded = true;
|
||||
}
|
||||
certs.renewing = core.certificates.renewAsync(
|
||||
args,
|
||||
certs
|
||||
);
|
||||
if (args.waitForRenewal) {
|
||||
return certs.renewing;
|
||||
}
|
||||
}
|
||||
|
||||
// return existing unexpired (although potentially stale) certificates when available
|
||||
// there will be an additional .renewing property if the certs are being asynchronously renewed
|
||||
return certs;
|
||||
})
|
||||
.then(function(results) {
|
||||
// returns pems
|
||||
return results;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return core;
|
||||
};
|
|
@ -1,108 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
|
||||
function _log(debug) {
|
||||
if (debug) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.shift();
|
||||
args.unshift('[greenlock/lib/middleware.js]');
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.create = function(gl) {
|
||||
if (!gl.challenges['http-01'] || !gl.challenges['http-01'].get) {
|
||||
throw new Error('middleware requires challenge plugin with get method');
|
||||
}
|
||||
var log = gl.log || _log;
|
||||
|
||||
log(gl.debug, 'created middleware');
|
||||
return function(_app) {
|
||||
if (_app && 'function' !== typeof _app) {
|
||||
throw new Error(
|
||||
'use greenlock.middleware() or greenlock.middleware(function (req, res) {})'
|
||||
);
|
||||
}
|
||||
var prefix = gl.acmeChallengePrefix || '/.well-known/acme-challenge/';
|
||||
|
||||
return function(req, res, next) {
|
||||
if (0 !== req.url.indexOf(prefix)) {
|
||||
log(gl.debug, 'no match, skipping middleware');
|
||||
if ('function' === typeof _app) {
|
||||
_app(req, res, next);
|
||||
} else if ('function' === typeof next) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 500;
|
||||
res.end(
|
||||
"[500] Developer Error: app.use('/', greenlock.middleware()) or greenlock.middleware(app)"
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
log(gl.debug, "this must be tinder, 'cuz it's a match!");
|
||||
|
||||
var token = req.url.slice(prefix.length);
|
||||
var hostname =
|
||||
req.hostname ||
|
||||
(req.headers.host || '').toLowerCase().replace(/:.*/, '');
|
||||
|
||||
log(gl.debug, 'hostname', hostname, 'token', token);
|
||||
|
||||
var copy = utils.merge({ domains: [hostname] }, gl);
|
||||
copy = utils.tplCopy(copy);
|
||||
copy.challenge = {};
|
||||
copy.challenge.type = 'http-01'; // obviously...
|
||||
copy.challenge.identifier = { type: 'dns', value: hostname };
|
||||
copy.challenge.wildcard = false;
|
||||
copy.challenge.token = token;
|
||||
copy.challenge.altname = hostname;
|
||||
|
||||
function cb(opts) {
|
||||
var secret = opts.keyAuthorization || opts;
|
||||
if (secret && 'string' === typeof secret) {
|
||||
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
res.end(secret);
|
||||
return;
|
||||
}
|
||||
eb(new Error("couldn't retrieve keyAuthorization"));
|
||||
return;
|
||||
}
|
||||
function eb(/*err*/) {
|
||||
res.statusCode = 404;
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/json; charset=utf-8'
|
||||
);
|
||||
res.end(
|
||||
'{ "error": { "message": "Error: These aren\'t the tokens you\'re looking for. Move along." } }'
|
||||
);
|
||||
return;
|
||||
}
|
||||
function mb(err, result) {
|
||||
if (err) {
|
||||
eb(err);
|
||||
return;
|
||||
}
|
||||
cb(result);
|
||||
}
|
||||
|
||||
var challenger = gl.challenges['http-01'].get;
|
||||
if (1 === challenger.length) {
|
||||
/*global Promise*/
|
||||
return Promise.resolve()
|
||||
.then(function() {
|
||||
return gl.challenges['http-01'].get(copy);
|
||||
})
|
||||
.then(cb)
|
||||
.catch(eb);
|
||||
} else if (2 === challenger.length) {
|
||||
gl.challenges['http-01'].get(copy, mb);
|
||||
} else {
|
||||
gl.challenges['http-01'].get(copy, hostname, token, mb);
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
|
@ -1,24 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var utils = require('./utils.js');
|
||||
var cert = { subject: 'example.com', altnames: ['*.bar.com', 'foo.net'] };
|
||||
if (utils.certHasDomain(cert, 'bad.com')) {
|
||||
throw new Error('allowed bad domain');
|
||||
}
|
||||
if (!utils.certHasDomain(cert, 'example.com')) {
|
||||
throw new Error('missed subject');
|
||||
}
|
||||
if (utils.certHasDomain(cert, 'bar.com')) {
|
||||
throw new Error('allowed bad (missing) sub');
|
||||
}
|
||||
if (!utils.certHasDomain(cert, 'foo.bar.com')) {
|
||||
throw new Error("didn't allow valid wildcarded-domain");
|
||||
}
|
||||
if (utils.certHasDomain(cert, 'dub.foo.bar.com')) {
|
||||
throw new Error('allowed sub-sub domain');
|
||||
}
|
||||
if (!utils.certHasDomain(cert, 'foo.net')) {
|
||||
throw new Error('missed altname');
|
||||
}
|
||||
|
||||
console.info('PASSED');
|
165
lib/utils.js
165
lib/utils.js
|
@ -1,165 +0,0 @@
|
|||
'use strict';
|
||||
require('./compat.js');
|
||||
|
||||
var path = require('path');
|
||||
var homeRe = new RegExp('^~(\\/|\\\\|\\' + path.sep + ')');
|
||||
// very basic check. Allows *.example.com.
|
||||
var re = /^(\*\.)?[a-zA-Z0-9\.\-]+$/;
|
||||
var punycode = require('punycode');
|
||||
var dnsResolveMxAsync = require('util').promisify(require('dns').resolveMx);
|
||||
|
||||
module.exports.attachCertInfo = function(results) {
|
||||
var certInfo = require('cert-info').info(results.cert);
|
||||
|
||||
// subject, altnames, issuedAt, expiresAt
|
||||
Object.keys(certInfo).forEach(function(key) {
|
||||
results[key] = certInfo[key];
|
||||
});
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
module.exports.certHasDomain = function(certInfo, _domain) {
|
||||
var names = (certInfo.altnames || []).slice(0);
|
||||
names.push(certInfo.subject);
|
||||
return names.some(function(name) {
|
||||
var domain = _domain.toLowerCase();
|
||||
name = name.toLowerCase();
|
||||
if ('*.' === name.substr(0, 2)) {
|
||||
name = name.substr(2);
|
||||
domain = domain
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
}
|
||||
return name === domain;
|
||||
});
|
||||
};
|
||||
|
||||
module.exports.isValidDomain = function(domain) {
|
||||
if (re.test(domain)) {
|
||||
return domain;
|
||||
}
|
||||
|
||||
domain = punycode.toASCII(domain);
|
||||
|
||||
if (re.test(domain)) {
|
||||
return domain;
|
||||
}
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
module.exports.merge = function(/*defaults, args*/) {
|
||||
var allDefaults = Array.prototype.slice.apply(arguments);
|
||||
var args = allDefaults.shift();
|
||||
var copy = {};
|
||||
|
||||
allDefaults.forEach(function(defaults) {
|
||||
Object.keys(defaults).forEach(function(key) {
|
||||
/*
|
||||
if ('challenges' === key && copy[key] && defaults[key]) {
|
||||
Object.keys(defaults[key]).forEach(function (k) {
|
||||
copy[key][k] = defaults[key][k];
|
||||
});
|
||||
} else {
|
||||
copy[key] = defaults[key];
|
||||
}
|
||||
*/
|
||||
copy[key] = defaults[key];
|
||||
});
|
||||
});
|
||||
|
||||
Object.keys(args).forEach(function(key) {
|
||||
/*
|
||||
if ('challenges' === key && copy[key] && args[key]) {
|
||||
Object.keys(args[key]).forEach(function (k) {
|
||||
copy[key][k] = args[key][k];
|
||||
});
|
||||
} else {
|
||||
copy[key] = args[key];
|
||||
}
|
||||
*/
|
||||
copy[key] = args[key];
|
||||
});
|
||||
|
||||
return copy;
|
||||
};
|
||||
|
||||
module.exports.tplCopy = function(copy) {
|
||||
var homedir = require('os').homedir();
|
||||
var tplKeys;
|
||||
|
||||
copy.hostnameGet = function(copy) {
|
||||
return copy.subject || (copy.domains || [])[0] || copy.domain;
|
||||
};
|
||||
|
||||
Object.keys(copy).forEach(function(key) {
|
||||
var newName;
|
||||
if (!/Get$/.test(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
newName = key.replace(/Get$/, '');
|
||||
copy[newName] = copy[newName] || copy[key](copy);
|
||||
});
|
||||
|
||||
tplKeys = Object.keys(copy);
|
||||
tplKeys.sort(function(a, b) {
|
||||
return b.length - a.length;
|
||||
});
|
||||
|
||||
tplKeys.forEach(function(key) {
|
||||
if ('string' !== typeof copy[key]) {
|
||||
return;
|
||||
}
|
||||
|
||||
copy[key] = copy[key].replace(homeRe, homedir + path.sep);
|
||||
});
|
||||
|
||||
tplKeys.forEach(function(key) {
|
||||
if ('string' !== typeof copy[key]) {
|
||||
return;
|
||||
}
|
||||
|
||||
tplKeys.forEach(function(tplname) {
|
||||
if (!copy[tplname]) {
|
||||
// what can't be templated now may be templatable later
|
||||
return;
|
||||
}
|
||||
copy[key] = copy[key].replace(':' + tplname, copy[tplname]);
|
||||
});
|
||||
});
|
||||
|
||||
return copy;
|
||||
};
|
||||
|
||||
module.exports.testEmail = function(email) {
|
||||
var parts = (email || '').split('@');
|
||||
var err;
|
||||
|
||||
if (2 !== parts.length || !parts[0] || !parts[1]) {
|
||||
err = new Error("malformed email address '" + email + "'");
|
||||
err.code = 'E_EMAIL';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
return dnsResolveMxAsync(parts[1]).then(
|
||||
function(records) {
|
||||
// records only returns when there is data
|
||||
if (!records.length) {
|
||||
throw new Error(
|
||||
'sanity check fail: success, but no MX records returned'
|
||||
);
|
||||
}
|
||||
return email;
|
||||
},
|
||||
function(err) {
|
||||
if ('ENODATA' === err.code) {
|
||||
err = new Error("no MX records found for '" + parts[1] + "'");
|
||||
err.code = 'E_EMAIL';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
Binary file not shown.
Before Width: | Height: | Size: 5.6 KiB |
Binary file not shown.
Before Width: | Height: | Size: 2.2 KiB |
Binary file not shown.
Before Width: | Height: | Size: 1.9 KiB |
|
@ -0,0 +1,258 @@
|
|||
'use strict';
|
||||
|
||||
var U = require('./utils.js');
|
||||
var E = require('./errors.js');
|
||||
|
||||
var warned = {};
|
||||
|
||||
module.exports.wrap = function(greenlock, manager) {
|
||||
greenlock.manager = {};
|
||||
greenlock.sites = {};
|
||||
//greenlock.accounts = {};
|
||||
//greenlock.certs = {};
|
||||
|
||||
var allowed = [
|
||||
'accountKeyType', //: ["P-256", "RSA-2048"],
|
||||
'serverKeyType', //: ["RSA-2048", "P-256"],
|
||||
'store', // : { module, specific opts },
|
||||
'challenges', // : { "http-01", "dns-01", "tls-alpn-01" },
|
||||
'subscriberEmail',
|
||||
'agreeToTerms',
|
||||
'agreeTos',
|
||||
'customerEmail',
|
||||
'renewOffset',
|
||||
'renewStagger',
|
||||
'module', // not allowed, just ignored
|
||||
'manager'
|
||||
];
|
||||
|
||||
// get / set default site settings such as
|
||||
// subscriberEmail, store, challenges, renewOffset, renewStagger
|
||||
greenlock.manager.defaults = function(conf) {
|
||||
return greenlock._init().then(function() {
|
||||
if (!conf) {
|
||||
return manager.defaults();
|
||||
}
|
||||
|
||||
if (conf.sites) {
|
||||
throw new Error('cannot set sites as global config');
|
||||
}
|
||||
if (conf.routes) {
|
||||
throw new Error('cannot set routes as global config');
|
||||
}
|
||||
|
||||
// disallow keys we know to be bad
|
||||
[
|
||||
'subject',
|
||||
'deletedAt',
|
||||
'altnames',
|
||||
'lastAttemptAt',
|
||||
'expiresAt',
|
||||
'issuedAt',
|
||||
'renewAt',
|
||||
'sites',
|
||||
'routes'
|
||||
].some(function(k) {
|
||||
if (k in conf) {
|
||||
throw new Error(
|
||||
'`' + k + '` not allowed as a default setting'
|
||||
);
|
||||
}
|
||||
});
|
||||
Object.keys(conf).forEach(function(k) {
|
||||
if (!allowed.includes(k) && !warned[k]) {
|
||||
warned[k] = true;
|
||||
console.warn(
|
||||
k +
|
||||
" isn't a known key. Please open an issue and let us know the use case."
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Object.keys(conf).forEach(function(k) {
|
||||
if (-1 !== ['module', 'manager'].indexOf(k)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ('undefined' === typeof k) {
|
||||
throw new Error(
|
||||
"'" +
|
||||
k +
|
||||
"' should be set to a value, or `null`, but not left `undefined`"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return manager.defaults(conf);
|
||||
});
|
||||
};
|
||||
|
||||
greenlock.add = greenlock.manager.add = function(args) {
|
||||
if (!args || !Array.isArray(args.altnames) || !args.altnames.length) {
|
||||
throw new Error(
|
||||
'you must specify `altnames` when adding a new site'
|
||||
);
|
||||
}
|
||||
if (args.renewAt) {
|
||||
throw new Error(
|
||||
'you cannot specify `renewAt` when adding a new site'
|
||||
);
|
||||
}
|
||||
|
||||
return greenlock.manager.set(args);
|
||||
};
|
||||
|
||||
// TODO agreeToTerms should be handled somewhere... maybe?
|
||||
|
||||
// Add and update remains because I said I had locked the API
|
||||
greenlock.manager.set = greenlock.manager.update = function(args) {
|
||||
return greenlock._init().then(function() {
|
||||
// The goal is to make this decently easy to manage by hand without mistakes
|
||||
// but also reasonably easy to error check and correct
|
||||
// and to make deterministic auto-corrections
|
||||
|
||||
args.subject = checkSubject(args);
|
||||
|
||||
//var subscriberEmail = args.subscriberEmail;
|
||||
|
||||
// TODO shortcut the other array checks when not necessary
|
||||
if (Array.isArray(args.altnames)) {
|
||||
args.altnames = checkAltnames(args.subject, args);
|
||||
}
|
||||
|
||||
// at this point we know that subject is the first of altnames
|
||||
return Promise.all(
|
||||
(args.altnames || []).map(function(d) {
|
||||
d = d.replace('*.', '');
|
||||
return U._validDomain(d);
|
||||
})
|
||||
).then(function() {
|
||||
if (!U._uniqueNames(args.altnames || [])) {
|
||||
throw E.NOT_UNIQUE(
|
||||
'add',
|
||||
"'" + args.altnames.join("' '") + "'"
|
||||
);
|
||||
}
|
||||
|
||||
// durations
|
||||
if (args.renewOffset) {
|
||||
args.renewOffset = U._parseDuration(args.renewOffset);
|
||||
}
|
||||
if (args.renewStagger) {
|
||||
args.renewStagger = U._parseDuration(args.renewStagger);
|
||||
}
|
||||
|
||||
return manager.set(args).then(function(result) {
|
||||
greenlock.renew({}).catch(function(err) {
|
||||
if (!err.context) {
|
||||
err.contxt = 'renew';
|
||||
}
|
||||
greenlock._notify('error', err);
|
||||
});
|
||||
return result;
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
greenlock.manager.remove = function(args) {
|
||||
args.subject = checkSubject(args);
|
||||
// TODO check no altnames
|
||||
return manager.remove(args);
|
||||
};
|
||||
|
||||
/*
|
||||
{
|
||||
subject: site.subject,
|
||||
altnames: site.altnames,
|
||||
//issuedAt: site.issuedAt,
|
||||
//expiresAt: site.expiresAt,
|
||||
renewOffset: site.renewOffset,
|
||||
renewStagger: site.renewStagger,
|
||||
renewAt: site.renewAt,
|
||||
subscriberEmail: site.subscriberEmail,
|
||||
customerEmail: site.customerEmail,
|
||||
challenges: site.challenges,
|
||||
store: site.store
|
||||
};
|
||||
*/
|
||||
|
||||
greenlock._find = function(args) {
|
||||
var altnames = args.altnames || [];
|
||||
|
||||
// servername, wildname, and altnames are all the same
|
||||
['wildname', 'servername'].forEach(function(k) {
|
||||
var altname = args[k] || '';
|
||||
if (altname && !altnames.includes(altname)) {
|
||||
altnames.push(altname);
|
||||
}
|
||||
});
|
||||
|
||||
if (altnames.length) {
|
||||
args.altnames = altnames;
|
||||
args.altnames = args.altnames.map(U._encodeName);
|
||||
args.altnames = checkAltnames(false, args);
|
||||
}
|
||||
|
||||
return manager.find(args);
|
||||
};
|
||||
};
|
||||
|
||||
function checkSubject(args) {
|
||||
if (!args || !args.subject) {
|
||||
throw new Error('you must specify `subject` when configuring a site');
|
||||
}
|
||||
/*
|
||||
if (!args.subject) {
|
||||
throw E.NO_SUBJECT('add');
|
||||
}
|
||||
*/
|
||||
|
||||
var subject = (args.subject || '').toLowerCase();
|
||||
if (subject !== args.subject) {
|
||||
console.warn('`subject` must be lowercase', args.subject);
|
||||
}
|
||||
|
||||
return U._encodeName(subject);
|
||||
}
|
||||
|
||||
function checkAltnames(subject, args) {
|
||||
// the things we have to check and get right
|
||||
var altnames = (args.altnames || []).map(function(name) {
|
||||
return String(name || '').toLowerCase();
|
||||
});
|
||||
|
||||
if (subject && subject !== altnames[0]) {
|
||||
throw new Error(
|
||||
'`subject` must be the first domain in `altnames`',
|
||||
args.subject,
|
||||
altnames.join(' ')
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
if (args.subject !== args.altnames[0]) {
|
||||
throw E.BAD_ORDER(
|
||||
'add',
|
||||
'(' + args.subject + ") '" + args.altnames.join("' '") + "'"
|
||||
);
|
||||
}
|
||||
*/
|
||||
|
||||
// punycode BEFORE validation
|
||||
// (set, find, remove)
|
||||
args.altnames = args.altnames.map(U._encodeName);
|
||||
if (
|
||||
!args.altnames.every(function(d) {
|
||||
return U._validName(d);
|
||||
})
|
||||
) {
|
||||
throw E.INVALID_HOSTNAME('add', "'" + args.altnames.join("' '") + "'");
|
||||
}
|
||||
|
||||
if (altnames.join() !== args.altnames.join()) {
|
||||
console.warn('all domains in `altnames` must be lowercase', altnames);
|
||||
}
|
||||
|
||||
return altnames;
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
var accountKeypair = await Keypairs.generate({ kty: accKty });
|
||||
if (config.debug) {
|
||||
console.info('Account Key Created');
|
||||
console.info(JSON.stringify(accountKeypair, null, 2));
|
||||
console.info();
|
||||
console.info();
|
||||
}
|
||||
|
||||
var account = await acme.accounts.create({
|
||||
agreeToTerms: agree,
|
||||
// TODO detect jwk/pem/der?
|
||||
accountKeypair: { privateKeyJwk: accountKeypair.private },
|
||||
subscriberEmail: config.email
|
||||
});
|
||||
|
||||
// TODO top-level agree
|
||||
function agree(tos) {
|
||||
if (config.debug) {
|
||||
console.info('Agreeing to Terms of Service:');
|
||||
console.info(tos);
|
||||
console.info();
|
||||
console.info();
|
||||
}
|
||||
agreed = true;
|
||||
return Promise.resolve(tos);
|
||||
}
|
||||
if (config.debug) {
|
||||
console.info('New Subscriber Account');
|
||||
console.info(JSON.stringify(account, null, 2));
|
||||
console.info();
|
||||
console.info();
|
||||
}
|
||||
if (!agreed) {
|
||||
throw new Error('Failed to ask the user to agree to terms');
|
||||
}
|
||||
|
||||
var certKeypair = await Keypairs.generate({ kty: srvKty });
|
||||
var pem = await Keypairs.export({
|
||||
jwk: certKeypair.private,
|
||||
encoding: 'pem'
|
||||
});
|
||||
if (config.debug) {
|
||||
console.info('Server Key Created');
|
||||
console.info('privkey.jwk.json');
|
||||
console.info(JSON.stringify(certKeypair, null, 2));
|
||||
// This should be saved as `privkey.pem`
|
||||
console.info();
|
||||
console.info('privkey.' + srvKty.toLowerCase() + '.pem:');
|
||||
console.info(pem);
|
||||
console.info();
|
||||
}
|
||||
|
||||
// 'subject' should be first in list
|
||||
var domains = randomDomains(rnd);
|
||||
if (config.debug) {
|
||||
console.info('Get certificates for random domains:');
|
||||
console.info(
|
||||
domains
|
||||
.map(function(puny) {
|
||||
var uni = punycode.toUnicode(puny);
|
||||
if (puny !== uni) {
|
||||
return puny + ' (' + uni + ')';
|
||||
}
|
||||
return puny;
|
||||
})
|
||||
.join('\n')
|
||||
);
|
||||
console.info();
|
||||
}
|
||||
|
||||
// Create CSR
|
||||
var csrDer = await CSR.csr({
|
||||
jwk: certKeypair.private,
|
||||
domains: domains,
|
||||
encoding: 'der'
|
||||
});
|
||||
var csr = Enc.bufToUrlBase64(csrDer);
|
||||
var csrPem = PEM.packBlock({
|
||||
type: 'CERTIFICATE REQUEST',
|
||||
bytes: csrDer /* { jwk: jwk, domains: opts.domains } */
|
||||
});
|
||||
if (config.debug) {
|
||||
console.info('Certificate Signing Request');
|
||||
console.info(csrPem);
|
||||
console.info();
|
||||
}
|
||||
|
||||
var results = await acme.certificates.create({
|
||||
account: account,
|
||||
accountKeypair: { privateKeyJwk: accountKeypair.private },
|
||||
csr: csr,
|
||||
domains: domains,
|
||||
challenges: challenges, // must be implemented
|
||||
customerEmail: null
|
||||
});
|
|
@ -1,112 +1,122 @@
|
|||
{
|
||||
"name": "greenlock",
|
||||
"version": "2.8.8",
|
||||
"name": "@root/greenlock",
|
||||
"version": "3.0.16",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
"@root/acme": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@root/acme/-/acme-3.0.8.tgz",
|
||||
"integrity": "sha512-VmBvLvWdCDkolkanI9Dzm1ouSWPaAa2eCCwcDZcVQbWoNiUIOqbbd57fcMA/gZxLyuJPStD2WXFuEuSMPDxcww==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/keypairs": "^0.9.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/request": "^1.3.11",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/asn1": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/asn1/-/asn1-1.0.0.tgz",
|
||||
"integrity": "sha512-0lfZNuOULKJDJmdIkP8V9RnbV3XaK6PAHD3swnFy4tZwtlMDzLKoM/dfNad7ut8Hu3r91wy9uK0WA/9zym5mig==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"@root/csr": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/csr/-/csr-0.8.1.tgz",
|
||||
"integrity": "sha512-hKl0VuE549TK6SnS2Yn9nRvKbFZXn/oAg+dZJU/tlKl/f/0yRXeuUzf8akg3JjtJq+9E592zDqeXZ7yyrg8fSQ==",
|
||||
"requires": {
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/encoding": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@root/encoding/-/encoding-1.0.1.tgz",
|
||||
"integrity": "sha512-OaEub02ufoU038gy6bsNHQOjIn8nUjGiLcaRmJ40IUykneJkIW5fxDqKxQx48cszuNflYldsJLPPXCrGfHs8yQ=="
|
||||
},
|
||||
"@root/keypairs": {
|
||||
"version": "0.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/keypairs/-/keypairs-0.9.0.tgz",
|
||||
"integrity": "sha512-NXE2L9Gv7r3iC4kB/gTPZE1vO9Ox/p14zDzAJ5cGpTpytbWOlWF7QoHSJbtVX4H7mRG/Hp7HR3jWdWdb2xaaXg==",
|
||||
"requires": {
|
||||
"@root/encoding": "^1.0.1",
|
||||
"@root/pem": "^1.0.4",
|
||||
"@root/x509": "^0.7.2"
|
||||
}
|
||||
},
|
||||
"@root/mkdirp": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@root/mkdirp/-/mkdirp-1.0.0.tgz",
|
||||
"integrity": "sha512-hxGAYUx5029VggfG+U9naAhQkoMSXtOeXtbql97m3Hi6/sQSRL/4khKZPyOF6w11glyCOU38WCNLu9nUcSjOfA=="
|
||||
},
|
||||
"@root/pem": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@root/pem/-/pem-1.0.4.tgz",
|
||||
"integrity": "sha512-rEUDiUsHtild8GfIjFE9wXtcVxeS+ehCJQBwbQQ3IVfORKHK93CFnRtkr69R75lZFjcmKYVc+AXDB+AeRFOULA=="
|
||||
},
|
||||
"@root/request": {
|
||||
"version": "1.3.11",
|
||||
"resolved": "https://registry.npmjs.org/@root/request/-/request-1.3.11.tgz",
|
||||
"integrity": "sha512-3a4Eeghcjsfe6zh7EJ+ni1l8OK9Fz2wL1OjP4UCa0YdvtH39kdXB9RGWuzyNv7dZi0+Ffkc83KfH0WbPMiuJFw=="
|
||||
},
|
||||
"acme": {
|
||||
"version": "1.3.5",
|
||||
"resolved": "https://registry.npmjs.org/acme/-/acme-1.3.5.tgz",
|
||||
"integrity": "sha512-KIFVyMho7y3RxRSTzkuX031TmfXwzl0ioy8+r2pnfLz6YWFQ5q7a/cYUDTgIbrFMPe/syY26Qv1DOdHQ5ARWcw==",
|
||||
"@root/x509": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@root/x509/-/x509-0.7.2.tgz",
|
||||
"integrity": "sha512-ENq3LGYORK5NiMFHEVeNMt+fTXaC7DTS6sQXoqV+dFdfT0vmiL5cDLjaXQhaklJQq0NiwicZegzJRl1ZOTp3WQ==",
|
||||
"requires": {
|
||||
"acme-v2": "^1.8.6"
|
||||
"@root/asn1": "^1.0.0",
|
||||
"@root/encoding": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"acme-dns-01-cli": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/acme-dns-01-cli/-/acme-dns-01-cli-3.0.7.tgz",
|
||||
"integrity": "sha512-Aa4bUpq6ftX1VODiShOetOY5U0tsXY5EV7+fQwme3Q8Y9rjYBArBXHgFCAVKtK1AF+Ev8pIuF6Z42hzMFa73/w=="
|
||||
"acme-dns-01-digitalocean": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/acme-dns-01-digitalocean/-/acme-dns-01-digitalocean-3.0.1.tgz",
|
||||
"integrity": "sha512-LUdOGluDERQWJG4CwlC9HbzUai4mtKzCz8nzpVTirXup2WwH60iRFAcd81hRGaoWbd0Bc0m6RVjN9YFkXB84yA=="
|
||||
},
|
||||
"acme-v2": {
|
||||
"version": "1.8.6",
|
||||
"resolved": "https://registry.npmjs.org/acme-v2/-/acme-v2-1.8.6.tgz",
|
||||
"integrity": "sha512-LWdicUYHTGDtYX7LlgsQurmM9txwfAFydg7mQLPKHrFMnNNtfJEtHC2fWfr+pFGNb3XKIbvyFUoyFB6cOmWRpA==",
|
||||
"requires": {
|
||||
"@root/request": "^1.3.11",
|
||||
"rsa-compat": "^2.0.8"
|
||||
}
|
||||
"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=="
|
||||
},
|
||||
"eckles": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/eckles/-/eckles-1.4.1.tgz",
|
||||
"integrity": "sha512-auWyk/k8oSkVHaD4RxkPadKsLUcIwKgr/h8F7UZEueFDBO7BsE4y+H6IMUDbfqKIFPg/9MxV6KcBdJCmVVcxSA=="
|
||||
"dotenv": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz",
|
||||
"integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw==",
|
||||
"dev": true
|
||||
},
|
||||
"greenlock-manager-fs": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-manager-fs/-/greenlock-manager-fs-3.0.1.tgz",
|
||||
"integrity": "sha512-vZfGFq1TTKxaAqdGDUwNservrNzXx0xCwT/ovG/N378GrhS+U5S8B8LUlNtQU7Fdw6RToMiBcm22OOxSrvZ2zw==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"greenlock-store-fs": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-store-fs/-/greenlock-store-fs-3.0.2.tgz",
|
||||
"integrity": "sha512-t4So75yKs1+7TqmxD5UKdf+zOQU0/4o0lb2auf5zUcAo7fwwNLOAXyWnnZRL3WuFBUiBGh1qXWleuMua0d3LPg==",
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/greenlock-store-fs/-/greenlock-store-fs-3.2.0.tgz",
|
||||
"integrity": "sha512-zqcPnF+173oYq5qU7FoGtuqeG8dmmvAiSnz98kEHAHyvgRF9pE1T0MM0AuqDdj45I3kXlCj2gZBwutnRi37J3g==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"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-fs": {
|
||||
"version": "2.0.9",
|
||||
"resolved": "https://registry.npmjs.org/le-challenge-fs/-/le-challenge-fs-2.0.9.tgz",
|
||||
"integrity": "sha512-stzI6rxd+aXGxBl87QJKKY/i/wl3uz6EoWzX2xSazJvCPSYBQys1RVNgOcf0SfUQPh6TBCFJFSJkiR4mznb4sg==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"le-sni-auto": {
|
||||
"version": "2.1.9",
|
||||
"resolved": "https://registry.npmjs.org/le-sni-auto/-/le-sni-auto-2.1.9.tgz",
|
||||
"integrity": "sha512-QmQHNwQDi/56GY8+qczFZ06FZbxaeJQjbjEhwwQHhkJ9IHhIQFkPfCT/OyDfLj4gqLIrg5ZX8CemxxVZnLEYfg=="
|
||||
},
|
||||
"le-store-certbot": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/le-store-certbot/-/le-store-certbot-2.2.3.tgz",
|
||||
"integrity": "sha512-c4ACR+v+JKMiAOOshLh6gdCKA7wIWR16+mROMLpQjq3rXJ3Vm8FaBHe2H+crT+flP+g7FmciAwUlfOJEJpIuCQ==",
|
||||
"requires": {
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"pyconf": "^1.1.7",
|
||||
"safe-replace": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"pyconf": {
|
||||
"version": "1.1.7",
|
||||
"resolved": "https://registry.npmjs.org/pyconf/-/pyconf-1.1.7.tgz",
|
||||
"integrity": "sha512-v4clh33m68sjtMsh8XMpjhGWb/MQODAYZ1y7ORG5Qv58UK25OddoB+oXyexgDkK8ttFui/lZm2sQDgA2Ftjfkw==",
|
||||
"requires": {
|
||||
"safe-replace": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"rasha": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/rasha/-/rasha-1.2.5.tgz",
|
||||
"integrity": "sha512-KxtX+/fBk+wM7O3CNgwjSh5elwFilLvqWajhr6wFr2Hd63JnKTTi43Tw+Jb1hxJQWOwoya+NZWR2xztn3hCrTw=="
|
||||
},
|
||||
"rsa-compat": {
|
||||
"version": "2.0.8",
|
||||
"resolved": "https://registry.npmjs.org/rsa-compat/-/rsa-compat-2.0.8.tgz",
|
||||
"integrity": "sha512-BFiiSEbuxzsVdaxpejbxfX07qs+rtous49Y6mL/zw6YHh9cranDvm2BvBmqT3rso84IsxNlP5BXnuNvm1Wn3Tw==",
|
||||
"requires": {
|
||||
"keypairs": "^1.2.14"
|
||||
}
|
||||
"punycode": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz",
|
||||
"integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=",
|
||||
"dev": true
|
||||
},
|
||||
"safe-replace": {
|
||||
"version": "1.1.0",
|
||||
|
|
101
package.json
101
package.json
|
@ -1,52 +1,53 @@
|
|||
{
|
||||
"name": "greenlock",
|
||||
"version": "2.8.8",
|
||||
"description": "Greenlock is Let's Encrypt (ACME) client for node.js",
|
||||
"homepage": "https://greenlock.domains/",
|
||||
"main": "index.js",
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.rootprojects.org/root/greenlock.js.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Let's Encrypt",
|
||||
"letsencrypt",
|
||||
"ACME",
|
||||
"v2",
|
||||
"auto-sni",
|
||||
"Free SSL",
|
||||
"Automated HTTPS",
|
||||
"tls",
|
||||
"https"
|
||||
],
|
||||
"author": "AJ ONeal <coolaj86@gmail.com> (https://solderjs.com/)",
|
||||
"license": "MPL-2.0",
|
||||
"bugs": {
|
||||
"url": "https://git.rootprojects.org/root/greenlock.js/issues"
|
||||
},
|
||||
"trulyOptionalDependencies": {
|
||||
"bluebird": "^3.5.1",
|
||||
"le-acme-core": "^2.1.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"acme": "^1.3.5",
|
||||
"acme-dns-01-cli": "^3.0.0",
|
||||
"acme-v2": "^1.8.6",
|
||||
"cert-info": "^1.5.1",
|
||||
"greenlock-store-fs": "^3.0.2",
|
||||
"keypairs": "^1.2.14",
|
||||
"le-challenge-fs": "^2.0.2",
|
||||
"le-sni-auto": "^2.1.9",
|
||||
"le-store-certbot": "^2.2.3",
|
||||
"rsa-compat": "^2.0.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.5"
|
||||
}
|
||||
"name": "@root/greenlock",
|
||||
"version": "3.0.17",
|
||||
"description": "The easiest Let's Encrypt client for Node.js and Browsers",
|
||||
"homepage": "https://rootprojects.org/greenlock/",
|
||||
"main": "greenlock.js",
|
||||
"browser": {},
|
||||
"files": [
|
||||
"*.js",
|
||||
"lib",
|
||||
"bin",
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "nodex bin/bundle.js",
|
||||
"lint": "jshint lib bin",
|
||||
"test": "node server.js",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.rootprojects.org/root/greenlock.js.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Let's Encrypt",
|
||||
"ACME",
|
||||
"browser",
|
||||
"EC",
|
||||
"RSA",
|
||||
"CSR",
|
||||
"greenlock",
|
||||
"VanillaJS",
|
||||
"ZeroSSL"
|
||||
],
|
||||
"author": "AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com/)",
|
||||
"license": "MPL-2.0",
|
||||
"dependencies": {
|
||||
"@root/acme": "^3.0.8",
|
||||
"@root/csr": "^0.8.1",
|
||||
"@root/keypairs": "^0.9.0",
|
||||
"@root/mkdirp": "^1.0.0",
|
||||
"@root/request": "^1.3.10",
|
||||
"acme-http-01-standalone": "^3.0.5",
|
||||
"cert-info": "^1.5.1",
|
||||
"greenlock-manager-fs": "^3.0.1",
|
||||
"greenlock-store-fs": "^3.2.0",
|
||||
"safe-replace": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"dotenv": "^8.2.0",
|
||||
"punycode": "^1.4.1"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,331 @@
|
|||
'use strict';
|
||||
|
||||
var P = module.exports;
|
||||
|
||||
var spawn = require('child_process').spawn;
|
||||
var spawnSync = require('child_process').spawnSync;
|
||||
var promisify = require('util').promisify;
|
||||
|
||||
// Exported for CLIs and such to override
|
||||
P.PKG_DIR = __dirname;
|
||||
|
||||
P._loadStore = function(storeConf) {
|
||||
return P._loadHelper(storeConf.module).then(function(plugin) {
|
||||
return P._normalizeStore(storeConf.module, plugin.create(storeConf));
|
||||
});
|
||||
};
|
||||
P._loadChallenge = function(chConfs, typ01) {
|
||||
return P._loadHelper(chConfs[typ01].module).then(function(plugin) {
|
||||
var ch = P._normalizeChallenge(
|
||||
chConfs[typ01].module,
|
||||
plugin.create(chConfs[typ01])
|
||||
);
|
||||
ch._type = typ01;
|
||||
return ch;
|
||||
});
|
||||
};
|
||||
P._loadHelper = function(modname) {
|
||||
try {
|
||||
return Promise.resolve(require(modname));
|
||||
} catch (e) {
|
||||
console.error("Could not load '%s'", modname);
|
||||
console.error('Did you install it?');
|
||||
console.error('\tnpm install --save %s', modname);
|
||||
throw e;
|
||||
|
||||
// Fun experiment, bad idea
|
||||
/*
|
||||
return P._install(modname).then(function() {
|
||||
return require(modname);
|
||||
});
|
||||
*/
|
||||
}
|
||||
};
|
||||
|
||||
P._normalizeStore = function(name, store) {
|
||||
var acc = store.accounts;
|
||||
var crt = store.certificates;
|
||||
|
||||
var warned = false;
|
||||
function warn() {
|
||||
if (warned) {
|
||||
return;
|
||||
}
|
||||
warned = true;
|
||||
console.warn(
|
||||
"'" +
|
||||
name +
|
||||
"' may have incorrect function signatures, or contains deprecated use of callbacks"
|
||||
);
|
||||
}
|
||||
|
||||
// accs
|
||||
if (acc.check && 2 === acc.check.length) {
|
||||
warn();
|
||||
acc._thunk_check = acc.check;
|
||||
acc.check = promisify(acc._thunk_check);
|
||||
}
|
||||
if (acc.set && 3 === acc.set.length) {
|
||||
warn();
|
||||
acc._thunk_set = acc.set;
|
||||
acc.set = promisify(acc._thunk_set);
|
||||
}
|
||||
if (2 === acc.checkKeypair.length) {
|
||||
warn();
|
||||
acc._thunk_checkKeypair = acc.checkKeypair;
|
||||
acc.checkKeypair = promisify(acc._thunk_checkKeypair);
|
||||
}
|
||||
if (3 === acc.setKeypair.length) {
|
||||
warn();
|
||||
acc._thunk_setKeypair = acc.setKeypair;
|
||||
acc.setKeypair = promisify(acc._thunk_setKeypair);
|
||||
}
|
||||
|
||||
// certs
|
||||
if (2 === crt.check.length) {
|
||||
warn();
|
||||
crt._thunk_check = crt.check;
|
||||
crt.check = promisify(crt._thunk_check);
|
||||
}
|
||||
if (3 === crt.set.length) {
|
||||
warn();
|
||||
crt._thunk_set = crt.set;
|
||||
crt.set = promisify(crt._thunk_set);
|
||||
}
|
||||
if (2 === crt.checkKeypair.length) {
|
||||
warn();
|
||||
crt._thunk_checkKeypair = crt.checkKeypair;
|
||||
crt.checkKeypair = promisify(crt._thunk_checkKeypair);
|
||||
}
|
||||
if (2 === crt.setKeypair.length) {
|
||||
warn();
|
||||
crt._thunk_setKeypair = crt.setKeypair;
|
||||
crt.setKeypair = promisify(crt._thunk_setKeypair);
|
||||
}
|
||||
|
||||
return store;
|
||||
};
|
||||
P._normalizeChallenge = function(name, ch) {
|
||||
var gch = {};
|
||||
var warned = false;
|
||||
function warn() {
|
||||
if (warned) {
|
||||
return;
|
||||
}
|
||||
warned = true;
|
||||
console.warn(
|
||||
"'" +
|
||||
name +
|
||||
"' may have incorrect function signatures, or contains deprecated use of callbacks"
|
||||
);
|
||||
}
|
||||
|
||||
var warned2 = false;
|
||||
function warn2() {
|
||||
if (warned2) {
|
||||
return;
|
||||
}
|
||||
warned2 = true;
|
||||
console.warn(
|
||||
"'" +
|
||||
name +
|
||||
"' did not return a Promise when called. This should be fixed by the maintainer."
|
||||
);
|
||||
}
|
||||
|
||||
function wrappy(fn) {
|
||||
return function(_params) {
|
||||
return Promise.resolve().then(function() {
|
||||
var result = fn.call(ch, _params);
|
||||
if (!result || !result.then) {
|
||||
warn2();
|
||||
}
|
||||
return result;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// init, zones, set, get, remove
|
||||
if (ch.init) {
|
||||
if (2 === ch.init.length) {
|
||||
warn();
|
||||
ch._thunk_init = ch.init;
|
||||
ch.init = promisify(ch._thunk_init);
|
||||
}
|
||||
gch.init = wrappy(ch.init);
|
||||
}
|
||||
if (ch.zones) {
|
||||
if (2 === ch.zones.length) {
|
||||
warn();
|
||||
ch._thunk_zones = ch.zones;
|
||||
ch.zones = promisify(ch._thunk_zones);
|
||||
}
|
||||
gch.zones = wrappy(ch.zones);
|
||||
}
|
||||
if (2 === ch.set.length) {
|
||||
warn();
|
||||
ch._thunk_set = ch.set;
|
||||
ch.set = promisify(ch._thunk_set);
|
||||
}
|
||||
gch.set = wrappy(ch.set);
|
||||
if (2 === ch.remove.length) {
|
||||
warn();
|
||||
ch._thunk_remove = ch.remove;
|
||||
ch.remove = promisify(ch._thunk_remove);
|
||||
}
|
||||
gch.remove = wrappy(ch.remove);
|
||||
if (ch.get) {
|
||||
if (2 === ch.get.length) {
|
||||
warn();
|
||||
ch._thunk_get = ch.get;
|
||||
ch.get = promisify(ch._thunk_get);
|
||||
}
|
||||
gch.get = wrappy(ch.get);
|
||||
}
|
||||
|
||||
return gch;
|
||||
};
|
||||
|
||||
P._loadSync = function(modname) {
|
||||
try {
|
||||
return require(modname);
|
||||
} catch (e) {
|
||||
console.error("Could not load '%s'", modname);
|
||||
console.error('Did you install it?');
|
||||
console.error('\tnpm install --save %s', modname);
|
||||
throw e;
|
||||
}
|
||||
/*
|
||||
try {
|
||||
mod = require(modname);
|
||||
} catch (e) {
|
||||
P._installSync(modname);
|
||||
mod = require(modname);
|
||||
}
|
||||
*/
|
||||
};
|
||||
|
||||
P._installSync = function(moduleName) {
|
||||
var npm = 'npm';
|
||||
var args = ['install', '--save', moduleName];
|
||||
var out = '';
|
||||
var cmd;
|
||||
|
||||
try {
|
||||
cmd = spawnSync(npm, args, {
|
||||
cwd: P.PKG_DIR,
|
||||
windowsHide: true
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"Failed to start: '" +
|
||||
npm +
|
||||
' ' +
|
||||
args.join(' ') +
|
||||
"' in '" +
|
||||
P.PKG_DIR +
|
||||
"'"
|
||||
);
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!cmd.status) {
|
||||
return;
|
||||
}
|
||||
|
||||
out += cmd.stdout.toString('utf8');
|
||||
out += cmd.stderr.toString('utf8');
|
||||
|
||||
if (out) {
|
||||
console.error(out);
|
||||
console.error();
|
||||
console.error();
|
||||
}
|
||||
|
||||
console.error(
|
||||
"Failed to run: '" +
|
||||
npm +
|
||||
' ' +
|
||||
args.join(' ') +
|
||||
"' in '" +
|
||||
P.PKG_DIR +
|
||||
"'"
|
||||
);
|
||||
|
||||
console.error(
|
||||
'Try for yourself:\n\tcd ' + P.PKG_DIR + '\n\tnpm ' + args.join(' ')
|
||||
);
|
||||
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
P._install = function(moduleName) {
|
||||
return new Promise(function(resolve) {
|
||||
if (!moduleName) {
|
||||
throw new Error('no module name given');
|
||||
}
|
||||
|
||||
var npm = 'npm';
|
||||
var args = ['install', '--save', moduleName];
|
||||
var out = '';
|
||||
var cmd = spawn(npm, args, {
|
||||
cwd: P.PKG_DIR,
|
||||
windowsHide: true
|
||||
});
|
||||
|
||||
cmd.stdout.on('data', function(chunk) {
|
||||
out += chunk.toString('utf8');
|
||||
});
|
||||
cmd.stdout.on('data', function(chunk) {
|
||||
out += chunk.toString('utf8');
|
||||
});
|
||||
|
||||
cmd.on('error', function(e) {
|
||||
console.error(
|
||||
"Failed to start: '" +
|
||||
npm +
|
||||
' ' +
|
||||
args.join(' ') +
|
||||
"' in '" +
|
||||
P.PKG_DIR +
|
||||
"'"
|
||||
);
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
cmd.on('exit', function(code) {
|
||||
if (!code) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (out) {
|
||||
console.error(out);
|
||||
console.error();
|
||||
console.error();
|
||||
}
|
||||
console.error(
|
||||
"Failed to run: '" +
|
||||
npm +
|
||||
' ' +
|
||||
args.join(' ') +
|
||||
"' in '" +
|
||||
P.PKG_DIR +
|
||||
"'"
|
||||
);
|
||||
console.error(
|
||||
'Try for yourself:\n\tcd ' +
|
||||
P.PKG_DIR +
|
||||
'\n\tnpm ' +
|
||||
args.join(' ')
|
||||
);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (require.main === module) {
|
||||
P._installSync(process.argv[2]);
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var LE = require('../').LE;
|
||||
var le = LE.create({
|
||||
server: 'staging',
|
||||
acme: require('le-acme-core').ACME.create(),
|
||||
store: require('le-store-certbot').create({
|
||||
configDir: '~/letsencrypt.test/etc/',
|
||||
webrootPath: '~/letsencrypt.test/tmp/:hostname'
|
||||
}),
|
||||
debug: true
|
||||
});
|
||||
|
||||
// TODO test generateRsaKey code path separately
|
||||
// and then provide opts.accountKeypair to create account
|
||||
|
||||
//var testId = Math.round(Date.now() / 1000).toString();
|
||||
var testId = 'test1000';
|
||||
var testEmail = 'coolaj86+le.' + testId + '@gmail.com';
|
||||
var testAccountId = '939573edbf2506c92c9ab32131209d7b';
|
||||
|
||||
var tests = [
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.checkAsync({
|
||||
accountId: testAccountId
|
||||
})
|
||||
.then(function(account) {
|
||||
if (!account) {
|
||||
throw new Error(
|
||||
'Test account should exist when searched by account id.'
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.checkAsync({
|
||||
email: testEmail
|
||||
})
|
||||
.then(function(account) {
|
||||
console.log('account.regr');
|
||||
console.log(account.regr);
|
||||
if (!account) {
|
||||
throw new Error(
|
||||
'Test account should exist when searched by email.'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
];
|
||||
|
||||
function run() {
|
||||
var test = tests.shift();
|
||||
if (!test) {
|
||||
console.info('All tests passed');
|
||||
return;
|
||||
}
|
||||
|
||||
test().then(run);
|
||||
}
|
||||
|
||||
run();
|
|
@ -1,134 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var LE = require('../').LE;
|
||||
var le = LE.create({
|
||||
server: 'staging',
|
||||
acme: require('le-acme-core').ACME.create(),
|
||||
store: require('le-store-certbot').create({
|
||||
configDir: '~/letsencrypt.test/etc/',
|
||||
webrootPath: '~/letsencrypt.test/tmp/:hostname'
|
||||
}),
|
||||
debug: true
|
||||
});
|
||||
|
||||
//var testId = Math.round(Date.now() / 1000).toString();
|
||||
var testId = 'test1000';
|
||||
var fakeEmail = 'coolaj86+le.' + testId + '@example.com';
|
||||
var testEmail = 'coolaj86+le.' + testId + '@gmail.com';
|
||||
var testAccount;
|
||||
|
||||
var tests = [
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.checkAsync({
|
||||
email: testEmail
|
||||
})
|
||||
.then(function(account) {
|
||||
if (account) {
|
||||
console.error(account);
|
||||
throw new Error('Test account should not exist.');
|
||||
}
|
||||
});
|
||||
},
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.registerAsync({
|
||||
email: testEmail,
|
||||
agreeTos: false,
|
||||
rsaKeySize: 2048
|
||||
})
|
||||
.then(
|
||||
function(/*account*/) {
|
||||
throw new Error(
|
||||
"Should not register if 'agreeTos' is not truthy."
|
||||
);
|
||||
},
|
||||
function(err) {
|
||||
if (err.code !== 'E_ARGS') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.registerAsync({
|
||||
email: testEmail,
|
||||
agreeTos: true,
|
||||
rsaKeySize: 1024
|
||||
})
|
||||
.then(
|
||||
function(/*account*/) {
|
||||
throw new Error(
|
||||
"Should not register if 'rsaKeySize' is less than 2048."
|
||||
);
|
||||
},
|
||||
function(err) {
|
||||
if (err.code !== 'E_ARGS') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.registerAsync({
|
||||
email: fakeEmail,
|
||||
agreeTos: true,
|
||||
rsaKeySize: 2048
|
||||
})
|
||||
.then(
|
||||
function(/*account*/) {
|
||||
// TODO test mx record
|
||||
throw new Error(
|
||||
'Registration should NOT succeed with a bad email address.'
|
||||
);
|
||||
},
|
||||
function(err) {
|
||||
if (err.code !== 'E_EMAIL') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
function() {
|
||||
return le.core.accounts
|
||||
.registerAsync({
|
||||
email: testEmail,
|
||||
agreeTos: true,
|
||||
rsaKeySize: 2048
|
||||
})
|
||||
.then(function(account) {
|
||||
testAccount = account;
|
||||
|
||||
console.log(testEmail);
|
||||
console.log(testAccount);
|
||||
|
||||
if (!account) {
|
||||
throw new Error(
|
||||
'Registration should always return a new account.'
|
||||
);
|
||||
}
|
||||
if (!account.email) {
|
||||
throw new Error('Registration should return the email.');
|
||||
}
|
||||
if (!account.id) {
|
||||
throw new Error(
|
||||
'Registration should return the account id.'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
];
|
||||
|
||||
function run() {
|
||||
var test = tests.shift();
|
||||
if (!test) {
|
||||
console.info('All tests passed');
|
||||
return;
|
||||
}
|
||||
|
||||
test().then(run);
|
||||
}
|
||||
|
||||
run();
|
|
@ -1,18 +0,0 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# This test is intended to run on a digital ocean instance on which all of the
|
||||
# following domains are listed on the same certificate as either subject or altnames:
|
||||
# test.ppl.family, www.test.ppl.family, test.greenlock.domains, www.test.greenlock.domains
|
||||
|
||||
# -k for insecure to allow staging certificates
|
||||
curl -k -sf https://test.ppl.family | grep -i Hello >/dev/null && echo "PASS no servername" || echo "FAIL no servername"
|
||||
curl -k -sf https://test.ppl.family -H "Host: test.ppl.family" | grep -i Hello >/dev/null && echo "PASS same servername" || echo "FAIL same servername"
|
||||
curl -k -sf https://test.ppl.family -H "Host: www.test.ppl.family" | grep -i Hello >/dev/null && echo "PASS similar altnames" || echo "FAIL similar altnames"
|
||||
curl -k -sf https://test.ppl.family -H "Host: www.test.greenlock.domains" | grep -i Hello >/dev/null && echo "PASS full altnames" || echo "FAIL full altnames"
|
||||
|
||||
curl -k -sf https://test.greenlock.domains -H "Host: test.greenlock.domains" | grep -i Hello >/dev/null && echo "PASS use altname first" || echo "FAIL altname only"
|
||||
curl -k -sf https://test.greenlock.domains -H "Host: test.ppl.family" | grep -i Hello >/dev/null && echo "PASS use altname, pass subject" || echo "FAIL sub + altname"
|
||||
|
||||
curl -k -s https://test.ppl.family -H "Host: example.com" | grep -i 'Domain Fronting' >/dev/null && echo "PASS detect fronting" || echo "FAIL detect fronting"
|
||||
echo "PASS ALL"
|
|
@ -1,29 +0,0 @@
|
|||
-----BEGIN CERTIFICATE-----
|
||||
MIIE+DCCA+CgAwIBAgISA2ZPXaADSdfNg48RtgfQGS9IMA0GCSqGSIb3DQEBCwUA
|
||||
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
|
||||
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xNjA1MTMyMzM4MDBaFw0x
|
||||
NjA4MTEyMzM4MDBaMBUxEzARBgNVBAMTCm9hdXRoMy5vcmcwggEiMA0GCSqGSIb3
|
||||
DQEBAQUAA4IBDwAwggEKAoIBAQDpm3D2yi79yHcnyv7JdNs7fVUO7Kcxq52qruyI
|
||||
svMfq1gd7W1m6L7OPlRNvsae3/Yuca2Ip+JPXcCphhhb63/ChUSp5efbo0JYg6EZ
|
||||
L/5TaV8HyovONEfleuYWSaBZ6RaRAZYBDclIJ13wgsYbJPYE5lSV2ufdAr9OIYrk
|
||||
myo5+WPVxZpDS7+fBY+fUnxJ8BOs1R7q/xfnDaipTc0ZsNQlQwOIkvQOy0D4otwx
|
||||
61MsrjPoQf686fex/HPwWi5sfKmH3YyB2ClnaIFv2wFs9fxCyb2htBn79Y98l4rV
|
||||
Ved21MllyReMKsk9J2Sx+3ONHr8Qpo1chHEu56MbbMXgqsmlAgMBAAGjggILMIIC
|
||||
BzAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC
|
||||
MAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFK8RJxCWMQgo8OHf2ILIIqatdHZkMB8G
|
||||
A1UdIwQYMBaAFKhKamMEfd265tE5t6ZFZe/zqOyhMHAGCCsGAQUFBwEBBGQwYjAv
|
||||
BggrBgEFBQcwAYYjaHR0cDovL29jc3AuaW50LXgzLmxldHNlbmNyeXB0Lm9yZy8w
|
||||
LwYIKwYBBQUHMAKGI2h0dHA6Ly9jZXJ0LmludC14My5sZXRzZW5jcnlwdC5vcmcv
|
||||
MBUGA1UdEQQOMAyCCm9hdXRoMy5vcmcwgf4GA1UdIASB9jCB8zAIBgZngQwBAgEw
|
||||
geYGCysGAQQBgt8TAQEBMIHWMCYGCCsGAQUFBwIBFhpodHRwOi8vY3BzLmxldHNl
|
||||
bmNyeXB0Lm9yZzCBqwYIKwYBBQUHAgIwgZ4MgZtUaGlzIENlcnRpZmljYXRlIG1h
|
||||
eSBvbmx5IGJlIHJlbGllZCB1cG9uIGJ5IFJlbHlpbmcgUGFydGllcyBhbmQgb25s
|
||||
eSBpbiBhY2NvcmRhbmNlIHdpdGggdGhlIENlcnRpZmljYXRlIFBvbGljeSBmb3Vu
|
||||
ZCBhdCBodHRwczovL2xldHNlbmNyeXB0Lm9yZy9yZXBvc2l0b3J5LzANBgkqhkiG
|
||||
9w0BAQsFAAOCAQEAfD/fMRxCZqMeQKFjyM6LIt9k84aHDdkem0ZmMUlYDuiz9iI5
|
||||
ZeL20gYopLQ+vcKe/1vHnODnEcEhBjzNM/aVXQVHi/xokDf4Loks6fP2cslGMMFy
|
||||
Kqgz3JaEcIs3ENjBBIU0xGQGuN67eZK8yhfrQxQuZOIx9J+IyP1jyFQSGA2c9wQD
|
||||
KRPUCef3EZhBaL1DXlMB8fqQOq0EP0IF2Qsp5MlkYaM9N3U/xbjku74lGBkJnS5n
|
||||
f2GE45RdY8KlIkJtkNhbGNX+nYHgbATUoO5uTKlcBslC+uwVqDDF3gbpdvAKE4a8
|
||||
eh6155o4h8lnhZD4Okr0KvdZT17jH+j4cbkRXw==
|
||||
-----END CERTIFICATE-----
|
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
|
||||
require('dotenv').config();
|
||||
|
||||
var Greenlock = require('../');
|
||||
|
||||
var subject = process.env.BASE_DOMAIN;
|
||||
var altnames = [subject, '*.' + subject, 'foo.bar.' + subject];
|
||||
var email = process.env.SUBSCRIBER_EMAIL;
|
||||
var challenge = JSON.parse(process.env.CHALLENGE_OPTIONS);
|
||||
challenge.module = process.env.CHALLENGE_PLUGIN;
|
||||
|
||||
var greenlock = Greenlock.create({
|
||||
packageAgent: 'Greenlock_Test/v0',
|
||||
maintainerEmail: email,
|
||||
staging: true,
|
||||
manager: require('greenlock-manager-fs').create({
|
||||
//configFile: '~/.config/greenlock/certs.json',
|
||||
})
|
||||
});
|
||||
|
||||
greenlock.manager
|
||||
.defaults({
|
||||
agreeToTerms: true,
|
||||
subscriberEmail: email,
|
||||
challenges: {
|
||||
'dns-01': challenge
|
||||
}
|
||||
//store: args.storeOpts,
|
||||
//renewOffset: args.renewOffset || '30d',
|
||||
//renewStagger: '1d'
|
||||
})
|
||||
.then(function() {
|
||||
return greenlock
|
||||
.add({
|
||||
subject: subject,
|
||||
altnames: altnames,
|
||||
subscriberEmail: email
|
||||
})
|
||||
.then(function() {
|
||||
return greenlock
|
||||
.get({ servername: subject })
|
||||
.then(function(pems) {
|
||||
if (pems && pems.privkey && pems.cert && pems.chain) {
|
||||
console.info('Success');
|
||||
}
|
||||
//console.log(pems);
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(function(e) {
|
||||
console.error('Big bad error:', e.code);
|
||||
console.error(e);
|
||||
});
|
|
@ -1,82 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var LE = require('../').LE;
|
||||
var le = LE.create({
|
||||
server: 'staging',
|
||||
acme: require('le-acme-core').ACME.create(),
|
||||
store: require('le-store-certbot').create({
|
||||
configDir: '~/letsencrypt.test/etc',
|
||||
webrootPath: '~/letsencrypt.test/var/:hostname'
|
||||
}),
|
||||
challenge: require('le-challenge-fs').create({
|
||||
webrootPath: '~/letsencrypt.test/var/:hostname'
|
||||
}),
|
||||
debug: true
|
||||
});
|
||||
|
||||
// TODO test generateRsaKey code path separately
|
||||
// and then provide opts.accountKeypair to create account
|
||||
|
||||
//var testId = Math.round(Date.now() / 1000).toString();
|
||||
var testId = 'test1000';
|
||||
var testEmail = 'coolaj86+le.' + testId + '@gmail.com';
|
||||
// TODO integrate with Daplie Domains for junk domains to test with
|
||||
var testDomains = ['pokemap.hellabit.com', 'www.pokemap.hellabit.com'];
|
||||
|
||||
var tests = [
|
||||
function() {
|
||||
return le.core.certificates
|
||||
.checkAsync({
|
||||
domains: ['example.com', 'www.example.com']
|
||||
})
|
||||
.then(function(cert) {
|
||||
if (cert) {
|
||||
throw new Error(
|
||||
'Bogus domain should not have certificate.'
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
function() {
|
||||
return le.core.certificates
|
||||
.getAsync({
|
||||
email: testEmail,
|
||||
domains: testDomains
|
||||
})
|
||||
.then(function(certs) {
|
||||
if (!certs) {
|
||||
throw new Error(
|
||||
'Should have acquired certificate for domains.'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
];
|
||||
|
||||
function run() {
|
||||
//var express = require(express);
|
||||
var server = require('http').createServer(le.middleware());
|
||||
server.listen(80, function() {
|
||||
console.log('Server running, proceeding to test.');
|
||||
|
||||
function next() {
|
||||
var test = tests.shift();
|
||||
if (!test) {
|
||||
server.close();
|
||||
console.info('All tests passed');
|
||||
return;
|
||||
}
|
||||
|
||||
test().then(next, function(err) {
|
||||
console.error('ERROR');
|
||||
console.error(err.stack);
|
||||
server.close();
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
run();
|
|
@ -1,137 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var LE = require('../').LE;
|
||||
var le = LE.create({
|
||||
server: 'staging',
|
||||
acme: require('le-acme-core').ACME.create(),
|
||||
store: require('le-store-certbot').create({
|
||||
configDir: '~/letsencrypt.test/etc',
|
||||
webrootPath: '~/letsencrypt.test/var/:hostname'
|
||||
}),
|
||||
challenge: require('le-challenge-fs').create({
|
||||
webrootPath: '~/letsencrypt.test/var/:hostname'
|
||||
}),
|
||||
debug: true
|
||||
});
|
||||
|
||||
// TODO test generateRsaKey code path separately
|
||||
// and then provide opts.accountKeypair to create account
|
||||
|
||||
//var testId = Math.round(Date.now() / 1000).toString();
|
||||
var testId = 'test1000';
|
||||
var testEmail = 'coolaj86+le.' + testId + '@gmail.com';
|
||||
// TODO integrate with Daplie Domains for junk domains to test with
|
||||
var testDomains = ['pokemap.hellabit.com', 'www.pokemap.hellabit.com'];
|
||||
var testCerts;
|
||||
|
||||
var tests = [
|
||||
function() {
|
||||
// TODO test that an altname also fetches the proper certificate
|
||||
return le.core.certificates
|
||||
.checkAsync({
|
||||
domains: testDomains
|
||||
})
|
||||
.then(function(certs) {
|
||||
if (!certs) {
|
||||
throw new Error(
|
||||
'Either certificates.registerAsync (in previous test)' +
|
||||
' or certificates.checkAsync (in this test) failed.'
|
||||
);
|
||||
}
|
||||
|
||||
testCerts = certs;
|
||||
console.log(
|
||||
'Issued At',
|
||||
new Date(certs.issuedAt).toISOString()
|
||||
);
|
||||
console.log(
|
||||
'Expires At',
|
||||
new Date(certs.expiresAt).toISOString()
|
||||
);
|
||||
|
||||
if (certs.expiresAt <= Date.now()) {
|
||||
throw new Error(
|
||||
'Certificates are already expired. They cannot be tested for duplicate or forced renewal.'
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
function() {
|
||||
return le.core.certificates
|
||||
.renewAsync(
|
||||
{
|
||||
email: testEmail,
|
||||
domains: testDomains
|
||||
},
|
||||
testCerts
|
||||
)
|
||||
.then(
|
||||
function() {
|
||||
throw new Error(
|
||||
'Should not have renewed non-expired certificates.'
|
||||
);
|
||||
},
|
||||
function(err) {
|
||||
if ('E_NOT_RENEWABLE' !== err.code) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
function() {
|
||||
return le.core.certificates
|
||||
.renewAsync(
|
||||
{
|
||||
email: testEmail,
|
||||
domains: testDomains,
|
||||
renewWithin: 720 * 24 * 60 * 60 * 1000
|
||||
},
|
||||
testCerts
|
||||
)
|
||||
.then(function(certs) {
|
||||
console.log(
|
||||
'Issued At',
|
||||
new Date(certs.issuedAt).toISOString()
|
||||
);
|
||||
console.log(
|
||||
'Expires At',
|
||||
new Date(certs.expiresAt).toISOString()
|
||||
);
|
||||
|
||||
if (certs.issuedAt === testCerts.issuedAt) {
|
||||
throw new Error(
|
||||
'Should not have returned existing certificates.'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
];
|
||||
|
||||
function run() {
|
||||
//var express = require(express);
|
||||
var server = require('http').createServer(le.middleware());
|
||||
server.listen(80, function() {
|
||||
console.log('Server running, proceeding to test.');
|
||||
|
||||
function next() {
|
||||
var test = tests.shift();
|
||||
if (!test) {
|
||||
server.close();
|
||||
console.info('All tests passed');
|
||||
return;
|
||||
}
|
||||
|
||||
test().then(next, function(err) {
|
||||
console.error('ERROR');
|
||||
console.error(err.stack);
|
||||
server.close();
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
run();
|
|
@ -0,0 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
var UserEvents = module.exports;
|
||||
|
||||
UserEvents.notify = function() {
|
||||
// TODO not implemented yet
|
||||
};
|
|
@ -0,0 +1,281 @@
|
|||
'use strict';
|
||||
|
||||
var U = module.exports;
|
||||
|
||||
var promisify = require('util').promisify;
|
||||
//var resolveSoa = promisify(require('dns').resolveSoa);
|
||||
var resolveMx = promisify(require('dns').resolveMx);
|
||||
var punycode = require('punycode');
|
||||
var Keypairs = require('@root/keypairs');
|
||||
// TODO move to @root
|
||||
var certParser = require('cert-info');
|
||||
|
||||
U._parseDuration = function(str) {
|
||||
if ('number' === typeof str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
var pattern = /^(\-?\d+(\.\d+)?)([wdhms]|ms)$/;
|
||||
var matches = str.match(pattern);
|
||||
if (!matches || !matches[0]) {
|
||||
throw new Error('invalid duration string: ' + str);
|
||||
}
|
||||
|
||||
var n = parseInt(matches[1], 10);
|
||||
var unit = matches[3];
|
||||
|
||||
switch (unit) {
|
||||
case 'w':
|
||||
n *= 7;
|
||||
/*falls through*/
|
||||
case 'd':
|
||||
n *= 24;
|
||||
/*falls through*/
|
||||
case 'h':
|
||||
n *= 60;
|
||||
/*falls through*/
|
||||
case 'm':
|
||||
n *= 60;
|
||||
/*falls through*/
|
||||
case 's':
|
||||
n *= 1000;
|
||||
/*falls through*/
|
||||
case 'ms':
|
||||
n *= 1; // for completeness
|
||||
}
|
||||
|
||||
return n;
|
||||
};
|
||||
|
||||
U._encodeName = function(str) {
|
||||
return punycode.toASCII(str.toLowerCase(str));
|
||||
};
|
||||
|
||||
U._validName = function(str) {
|
||||
// A quick check of the 38 and two ½ valid characters
|
||||
// 253 char max full domain, including dots
|
||||
// 63 char max each label segment
|
||||
// Note: * is not allowed, but it's allowable here
|
||||
// Note: _ (underscore) is only allowed for "domain names", not "hostnames"
|
||||
// Note: - (hyphen) is not allowed as a first character (but a number is)
|
||||
return (
|
||||
/^(\*\.)?[a-z0-9_\.\-]+$/.test(str) &&
|
||||
str.length < 254 &&
|
||||
str.split('.').every(function(label) {
|
||||
return label.length > 0 && label.length < 64;
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
U._validMx = function(email) {
|
||||
var host = email.split('@').slice(1)[0];
|
||||
// try twice, just because DNS hiccups sometimes
|
||||
// Note: we don't care if the domain exists, just that it *can* exist
|
||||
return resolveMx(host).catch(function() {
|
||||
return U._timeout(1000).then(function() {
|
||||
return resolveMx(host);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// should be called after _validName
|
||||
U._validDomain = function(str) {
|
||||
// TODO use @root/dns (currently dns-suite)
|
||||
// because node's dns can't read Authority records
|
||||
return Promise.resolve(str);
|
||||
/*
|
||||
// try twice, just because DNS hiccups sometimes
|
||||
// Note: we don't care if the domain exists, just that it *can* exist
|
||||
return resolveSoa(str).catch(function() {
|
||||
return U._timeout(1000).then(function() {
|
||||
return resolveSoa(str);
|
||||
});
|
||||
});
|
||||
*/
|
||||
};
|
||||
|
||||
// foo.example.com and *.example.com overlap
|
||||
// should be called after _validName
|
||||
// (which enforces *. or no *)
|
||||
U._uniqueNames = function(altnames) {
|
||||
var dups = {};
|
||||
var wilds = {};
|
||||
if (
|
||||
altnames.some(function(w) {
|
||||
if ('*.' !== w.slice(0, 2)) {
|
||||
return;
|
||||
}
|
||||
if (wilds[w]) {
|
||||
return true;
|
||||
}
|
||||
wilds[w] = true;
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return altnames.every(function(name) {
|
||||
var w;
|
||||
if ('*.' !== name.slice(0, 2)) {
|
||||
w =
|
||||
'*.' +
|
||||
name
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!dups[name] && !dups[w]) {
|
||||
dups[name] = true;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
U._timeout = function(d) {
|
||||
return new Promise(function(resolve) {
|
||||
setTimeout(resolve, d);
|
||||
});
|
||||
};
|
||||
|
||||
U._genKeypair = function(keyType) {
|
||||
var keyopts;
|
||||
var len = parseInt(keyType.replace(/.*?(\d)/, '$1') || 0, 10);
|
||||
if (/RSA/.test(keyType)) {
|
||||
keyopts = {
|
||||
kty: 'RSA',
|
||||
modulusLength: len || 2048
|
||||
};
|
||||
} else if (/^(EC|P\-?\d)/i.test(keyType)) {
|
||||
keyopts = {
|
||||
kty: 'EC',
|
||||
namedCurve: 'P-' + (len || 256)
|
||||
};
|
||||
} else {
|
||||
// TODO put in ./errors.js
|
||||
throw new Error('invalid key type: ' + keyType);
|
||||
}
|
||||
|
||||
return Keypairs.generate(keyopts).then(function(pair) {
|
||||
return U._jwkToSet(pair.private);
|
||||
});
|
||||
};
|
||||
|
||||
// TODO use ACME._importKeypair ??
|
||||
U._importKeypair = function(keypair) {
|
||||
// this should import all formats equally well:
|
||||
// 'object' (JWK), 'string' (private key pem), kp.privateKeyPem, kp.privateKeyJwk
|
||||
if (keypair.private || keypair.d) {
|
||||
return U._jwkToSet(keypair.private || keypair);
|
||||
}
|
||||
if (keypair.privateKeyJwk) {
|
||||
return U._jwkToSet(keypair.privateKeyJwk);
|
||||
}
|
||||
|
||||
if ('string' !== typeof keypair && !keypair.privateKeyPem) {
|
||||
// TODO put in errors
|
||||
throw new Error('missing private key');
|
||||
}
|
||||
|
||||
return Keypairs.import({ pem: keypair.privateKeyPem || keypair }).then(
|
||||
function(priv) {
|
||||
if (!priv.d) {
|
||||
throw new Error('missing private key');
|
||||
}
|
||||
return U._jwkToSet(priv);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
U._jwkToSet = function(jwk) {
|
||||
var keypair = {
|
||||
privateKeyJwk: jwk
|
||||
};
|
||||
return Promise.all([
|
||||
Keypairs.export({
|
||||
jwk: jwk,
|
||||
encoding: 'pem'
|
||||
}).then(function(pem) {
|
||||
keypair.privateKeyPem = pem;
|
||||
}),
|
||||
Keypairs.export({
|
||||
jwk: jwk,
|
||||
encoding: 'pem',
|
||||
public: true
|
||||
}).then(function(pem) {
|
||||
keypair.publicKeyPem = pem;
|
||||
}),
|
||||
Keypairs.publish({
|
||||
jwk: jwk
|
||||
}).then(function(pub) {
|
||||
keypair.publicKeyJwk = pub;
|
||||
})
|
||||
]).then(function() {
|
||||
return keypair;
|
||||
});
|
||||
};
|
||||
|
||||
U._attachCertInfo = function(results) {
|
||||
var certInfo = certParser.info(results.cert);
|
||||
|
||||
// subject, altnames, issuedAt, expiresAt
|
||||
Object.keys(certInfo).forEach(function(key) {
|
||||
results[key] = certInfo[key];
|
||||
});
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
U._certHasDomain = function(certInfo, _domain) {
|
||||
var names = (certInfo.altnames || []).slice(0);
|
||||
return names.some(function(name) {
|
||||
var domain = _domain.toLowerCase();
|
||||
name = name.toLowerCase();
|
||||
if ('*.' === name.substr(0, 2)) {
|
||||
name = name.substr(2);
|
||||
domain = domain
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
}
|
||||
return name === domain;
|
||||
});
|
||||
};
|
||||
|
||||
// a bit heavy to be labeled 'utils'... perhaps 'common' would be better?
|
||||
U._getOrCreateKeypair = function(db, subject, query, keyType, mustExist) {
|
||||
var exists = false;
|
||||
return db
|
||||
.checkKeypair(query)
|
||||
.then(function(kp) {
|
||||
if (kp) {
|
||||
exists = true;
|
||||
return U._importKeypair(kp);
|
||||
}
|
||||
|
||||
if (mustExist) {
|
||||
// TODO put in errors
|
||||
throw new Error(
|
||||
'required keypair not found: ' +
|
||||
(subject || '') +
|
||||
' ' +
|
||||
JSON.stringify(query)
|
||||
);
|
||||
}
|
||||
|
||||
return U._genKeypair(keyType);
|
||||
})
|
||||
.then(function(keypair) {
|
||||
return { exists: exists, keypair: keypair };
|
||||
});
|
||||
};
|
||||
|
||||
U._getKeypair = function(db, subject, query) {
|
||||
return U._getOrCreateKeypair(db, subject, query, '', true).then(function(
|
||||
result
|
||||
) {
|
||||
return result.keypair;
|
||||
});
|
||||
};
|
Loading…
Reference in New Issue