mirror of
https://github.com/certd/certd.git
synced 2026-04-03 22:20:51 +08:00
Compare commits
124 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd06f12582 | ||
|
|
d7dcc01c9f | ||
|
|
66f56740b7 | ||
|
|
5bd042d9bc | ||
|
|
60921d9adf | ||
|
|
3a668f1f8b | ||
|
|
609fe5f838 | ||
|
|
e29e528aa2 | ||
|
|
e06c9e07fe | ||
|
|
03ee28c380 | ||
|
|
7474235283 | ||
|
|
4eb6ae92d1 | ||
|
|
0eeba2783b | ||
|
|
8498fa75e3 | ||
|
|
5556bc3a4b | ||
|
|
998200e570 | ||
|
|
420b835b09 | ||
|
|
cc3534cf00 | ||
|
|
062a267a6f | ||
|
|
98ee7fcd8c | ||
|
|
e5ec9f4b62 | ||
|
|
b66bb21777 | ||
|
|
f7e026a132 | ||
|
|
c12e56823e | ||
|
|
042f8e9030 | ||
|
|
9308950550 | ||
|
|
a43c5b0824 | ||
|
|
ebdf9f4b5b | ||
|
|
511be1f3ae | ||
|
|
ceb0454277 | ||
|
|
c553b017af | ||
|
|
c553f63127 | ||
|
|
152cb9b23a | ||
|
|
5eff50e8fe | ||
|
|
cddf01ee68 | ||
|
|
d968c4bbb9 | ||
|
|
1a738403fc | ||
|
|
71428b0181 | ||
|
|
4b538bae97 | ||
|
|
a4bb4fd708 | ||
|
|
99bb7b70e0 | ||
|
|
443f6358c9 | ||
|
|
0bae4851c1 | ||
|
|
66710d33c6 | ||
|
|
73fe1422f3 | ||
|
|
47f3cf7ba5 | ||
|
|
d5ef57542a | ||
|
|
cc3531b9d5 | ||
|
|
95722f46f4 | ||
|
|
5950e1cae7 | ||
|
|
d176ab4886 | ||
|
|
cbccf1024b | ||
|
|
643148d283 | ||
|
|
ac15c8fc0e | ||
|
|
3751fcd4c9 | ||
|
|
6f6606d76d | ||
|
|
8c152371a1 | ||
|
|
f489c59ca3 | ||
|
|
d2897cefaa | ||
|
|
9747d40734 | ||
|
|
e123ec4089 | ||
|
|
f358a0f226 | ||
|
|
003ea9310b | ||
|
|
d602df4c70 | ||
|
|
daa990ee96 | ||
|
|
0fca7dc3ce | ||
|
|
0a946f55ca | ||
|
|
458756e895 | ||
|
|
76dd23174a | ||
|
|
0ad667b00a | ||
|
|
699ab168c1 | ||
|
|
5ccb4a6f08 | ||
|
|
2c10cedb34 | ||
|
|
3b357ef301 | ||
|
|
f686fb0d95 | ||
|
|
3f739daaea | ||
|
|
c9d415f9db | ||
|
|
51249c304c | ||
|
|
83f9a551e7 | ||
|
|
6c450d3249 | ||
|
|
8b828b3f34 | ||
|
|
146d106991 | ||
|
|
b15b2edcdf | ||
|
|
f08f765529 | ||
|
|
f64ea78c44 | ||
|
|
fbde7cbd93 | ||
|
|
d10e80bf83 | ||
|
|
a269d8374e | ||
|
|
49ea196160 | ||
|
|
ddb1bc87bb | ||
|
|
07a45b4530 | ||
|
|
dcd1023a39 | ||
|
|
52522f27e9 | ||
|
|
e4ec4e1404 | ||
|
|
717d203622 | ||
|
|
c23f6172b5 | ||
|
|
b04d4cb5c5 | ||
|
|
d66bc33761 | ||
|
|
f710c00c0d | ||
|
|
e68862b633 | ||
|
|
6094a4af79 | ||
|
|
146ac49703 | ||
|
|
909b75eb40 | ||
|
|
dcdb25d92d | ||
|
|
3dfdd3c31c | ||
|
|
25d5a99b3d | ||
|
|
e1466737e3 | ||
|
|
370a28c10e | ||
|
|
af919c2f6e | ||
|
|
dc3ab544c8 | ||
|
|
708bebe6e3 | ||
|
|
3722e922ff | ||
|
|
8b5d5a8bf9 | ||
|
|
038b1c9ca4 | ||
|
|
b10ff5b6ee | ||
|
|
6950d779e0 | ||
|
|
4c31db427a | ||
|
|
540981e071 | ||
|
|
ed8b9cd5e9 | ||
|
|
3dea83ce31 | ||
|
|
b7bde7b685 | ||
|
|
718028ca62 | ||
|
|
98b2863547 | ||
|
|
b1e60456cf |
21
.github/ISSUE_TEMPLATE.md
vendored
Normal file
21
.github/ISSUE_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
> 感谢您支持certd,请按如下规范提交issue
|
||||
> 如果有条件,请尽量在[github上提交](https://github.com/certd/certd/issues)
|
||||
|
||||
|
||||
## 一、问题描述
|
||||
`请在此处简要描述你所遇到的问题,必要时请贴出相关截图辅助理解和定位`
|
||||
|
||||
### 复现步骤
|
||||
`请描述复现问题的详细步骤`
|
||||
`如果非示例页面的问题,最好能提供最小复现示例的代码、或者仓库链接`
|
||||
|
||||
|
||||
### 报错截图
|
||||
`请贴出报错日志截图`
|
||||
|
||||
### 效果截图
|
||||
`请贴出效果截图`
|
||||
#### 1. 期望效果
|
||||
|
||||
#### 2. 实际效果
|
||||
|
||||
35
.github/workflows/sync-to-gitee.yml
vendored
Normal file
35
.github/workflows/sync-to-gitee.yml
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
name: sync-to-gitee
|
||||
on:
|
||||
push:
|
||||
branches: ['v2']
|
||||
pull_request:
|
||||
branches: ['v2']
|
||||
# schedule:
|
||||
# - # 国际时间 19:17 执行,北京时间3:17 ↙↙↙ 改成你想要每天自动执行的时间
|
||||
# - cron: '17 19 * * *'
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout work repo # 1. 检出当前仓库(certd-sync-work)
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set git user # 2. 给git命令设置用户名和邮箱,↙↙↙ 改成你的name和email
|
||||
run: |
|
||||
git config --global user.name "xiaojunnuo"
|
||||
git config --global user.email "xiaojunnuo@qq.com"
|
||||
|
||||
- name: Set git token # 3. 给git命令设置token,用于push到目标仓库
|
||||
uses: de-vri-es/setup-git-credentials@v2
|
||||
with: # token 格式为: username:password
|
||||
credentials: https://${{secrets.PUSH_TOKEN_GITEE}}@gitee.com
|
||||
|
||||
- name: push to gitee # 4. 执行同步
|
||||
run: |
|
||||
git remote add upstream https://gitee.com/certd/certd
|
||||
git push --set-upstream upstream v2
|
||||
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -6,7 +6,9 @@ yarn-error.log
|
||||
yarn.lock
|
||||
package-lock.json
|
||||
/.idea/
|
||||
|
||||
*/**/dist
|
||||
*/**/pnpm-lock.yaml
|
||||
*/**/stats.html
|
||||
.idea
|
||||
*.iml
|
||||
out
|
||||
@@ -26,4 +28,7 @@ gen
|
||||
/dev-sidecar-test
|
||||
/packages/core/certd/yarn.lock
|
||||
/packages/test
|
||||
/test/own
|
||||
/test/own
|
||||
/pnpm-lock.yaml
|
||||
|
||||
docker/image/workspace
|
||||
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -1,3 +0,0 @@
|
||||
[submodule "packages/base/node-acme-client"]
|
||||
path = packages/base/node-acme-client
|
||||
url = https://github.com/certd/node-acme-client.git
|
||||
28
CHANGELOG.md
Normal file
28
CHANGELOG.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [1.0.6](https://github.com/certd/certd/compare/v1.0.5...v1.0.6) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
## [1.0.5](https://github.com/certd/certd/compare/v1.0.4...v1.0.5) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
## [1.0.4](https://github.com/certd/certd/compare/v1.0.3...v1.0.4) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
## [1.0.3](https://github.com/certd/certd/compare/v1.0.2...v1.0.3) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
## [1.0.2](https://github.com/certd/certd/compare/v1.0.1...v1.0.2) (2023-05-24)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
## [1.0.1](https://github.com/certd/certd/compare/v1.0.0...v1.0.1) (2023-05-24)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
674
LICENSE
674
LICENSE
@@ -1,21 +1,661 @@
|
||||
MIT License
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (c) 2021 Greper
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
80
deploy.js
Normal file
80
deploy.js
Normal file
@@ -0,0 +1,80 @@
|
||||
const http = require("axios")
|
||||
const exec = require('child_process').exec;
|
||||
|
||||
//builder
|
||||
function execute(cmd){
|
||||
return new Promise((resolve,reject)=>{
|
||||
console.log("cmd executing: " + cmd)
|
||||
exec(cmd, function(error, stdout, stderr) {
|
||||
if(error){
|
||||
console.error(error);
|
||||
console.info(stderr)
|
||||
reject(error)
|
||||
}
|
||||
else{
|
||||
console.info(stdout)
|
||||
console.log("success");
|
||||
resolve(true)
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async function build(){
|
||||
await execute("cd ./packages/fast-admin/fs-admin-antdv/ && npm run build")
|
||||
await execute("cd ./packages/fast-admin/fs-admin-element/ && npm run build")
|
||||
await execute("cd ./packages/fast-admin/fs-admin-naive-ui/ && npm run build")
|
||||
await execute("npm run docs:build")
|
||||
}
|
||||
|
||||
|
||||
|
||||
// trigger
|
||||
|
||||
const naive = "http://flow-openapi.aliyun.com/pipeline/webhook/Zm3TJyDtyFZgV4dtJiD1"
|
||||
const doc = "http://flow-openapi.aliyun.com/pipeline/webhook/soOYdQ5sF3kLjTPJGmIO"
|
||||
const antdv = "http://flow-openapi.aliyun.com/pipeline/webhook/HiL0uVYxfUnBzIMJZVXB"
|
||||
const element = "http://flow-openapi.aliyun.com/pipeline/webhook/uFTI0XJ9RgqnofX7jpRD"
|
||||
|
||||
const webhooks = [doc,naive,antdv,element]
|
||||
|
||||
async function sleep(time){
|
||||
return new Promise(resolve => {
|
||||
setTimeout(resolve,time)
|
||||
})
|
||||
}
|
||||
|
||||
async function trigger(){
|
||||
for (const webhook of webhooks) {
|
||||
await http({
|
||||
url:webhook,
|
||||
method:'POST',
|
||||
headers:{
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
data:{}
|
||||
})
|
||||
console.log(`webhook success:${webhook}`)
|
||||
await sleep(1000)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function start(){
|
||||
// await build()
|
||||
console.log("等待60秒")
|
||||
await sleep(60*1000)
|
||||
await trigger()
|
||||
}
|
||||
|
||||
start()
|
||||
|
||||
|
||||
/**
|
||||
* 打包前 修改 lerna
|
||||
* nodemodules里面搜索如下
|
||||
* return childProcess.exec("git", ["add", "--", ...files], execOpts);
|
||||
*
|
||||
* ('git', ['add', '--', ...files]
|
||||
* ('git', ['add', '.']
|
||||
*/
|
||||
9
docker/image/Dockerfile
Normal file
9
docker/image/Dockerfile
Normal file
@@ -0,0 +1,9 @@
|
||||
FROM registry.cn-shenzhen.aliyuncs.com/handsfree/node:16-alpine
|
||||
RUN npm install -g pnpm && npm install -g cross-env
|
||||
ADD ./workspace/certd-server/ /app/
|
||||
WORKDIR /app/
|
||||
RUN pnpm install -P
|
||||
CMD ["npm","run","start"]
|
||||
|
||||
|
||||
|
||||
34
docker/image/build.sh
Normal file
34
docker/image/build.sh
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "请先输入一个版本号:"
|
||||
read version
|
||||
|
||||
echo "您输入的版本号是: $version"
|
||||
echo "登录aliyun镜像仓库"
|
||||
docker login --username=252959493@qq.com registry.cn-shenzhen.aliyuncs.com
|
||||
|
||||
build=$(pwd)
|
||||
cd ../../
|
||||
root=$(pwd)
|
||||
echo "安装依赖"
|
||||
pnpm install
|
||||
|
||||
echo "client build"
|
||||
cd $root/packages/ui/certd-client
|
||||
pnpm run build
|
||||
echo "client build success"
|
||||
|
||||
echo "server build"
|
||||
cd $root/packages/ui/certd-server
|
||||
pnpm run build
|
||||
echo "server build success"
|
||||
|
||||
echo "rm node_modules"
|
||||
rm ./node_modules -rf
|
||||
|
||||
echo "copy to workspace"
|
||||
mkdir -p $build/workspace/certd-server
|
||||
\cp ./* $build/workspace/certd-server -rf
|
||||
\cp ../certd-client/dist/* $build/workspace/certd-server/public/ -rf
|
||||
|
||||
|
||||
14
docker/image/docker-compose.yaml
Normal file
14
docker/image/docker-compose.yaml
Normal file
@@ -0,0 +1,14 @@
|
||||
version: '3.3' # 指定docker-compose 版本
|
||||
services: # 要拉起的服务们
|
||||
certd:
|
||||
build:
|
||||
context: ./
|
||||
dockerfile: Dockerfile
|
||||
image: registry.cn-shenzhen.aliyuncs.com/handsfree/certd:${TAG}
|
||||
container_name: certd # 容器名
|
||||
restart: unless-stopped # 重启
|
||||
ports: # 端口映射
|
||||
- "7001:7001"
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
|
||||
15
docker/run/docker-compose.yaml
Normal file
15
docker/run/docker-compose.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
version: '3.3' # 指定docker-compose 版本
|
||||
services: # 要拉起的服务们
|
||||
certd:
|
||||
image: registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest
|
||||
container_name: certd # 容器名
|
||||
restart: unless-stopped # 重启
|
||||
volumes: # 挂载目录
|
||||
- /data/certd:/app/data
|
||||
ports: # 端口映射
|
||||
- "7001:7001"
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
- CERTD_AUTH_JWT_KEY=changeme
|
||||
#注意修改成你的自定义密钥 ↑↑↑↑↑
|
||||
|
||||
17
lerna.json
17
lerna.json
@@ -1,8 +1,13 @@
|
||||
{
|
||||
"packages": [
|
||||
"packages/base/*",
|
||||
"packages/core/*",
|
||||
"packages/plugins/*"
|
||||
],
|
||||
"version": "0.3.0"
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json",
|
||||
"useWorkspaces": true,
|
||||
"command": {
|
||||
"bootstrap": {
|
||||
"npmClientArgs": [
|
||||
"--no-package-lock"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmClient": "pnpm",
|
||||
"version": "1.0.6"
|
||||
}
|
||||
|
||||
19
package.json
19
package.json
@@ -1,16 +1,27 @@
|
||||
{
|
||||
"name": "root",
|
||||
"version": "1.0.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"lerna": "^3.18.4"
|
||||
"@lerna-lite/cli": "^2.4.0",
|
||||
"@lerna-lite/run": "^2.4.0",
|
||||
"@lerna-lite/publish": "^2.4.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "lerna bootstrap --hoist",
|
||||
"i-all": "lerna link && lerna exec npm install "
|
||||
"i-all": "lerna link && lerna exec npm install ",
|
||||
"publish": "npm run proxy && npm run prepublishOnly1 && lerna publish --conventional-commits && npm run afterpublishOnly",
|
||||
"afterpublishOnly": "",
|
||||
"proxy": "npm config set proxy=http://127.0.0.1:10809",
|
||||
"prepublishOnly1": "npm run before-build && lerna run build ",
|
||||
"before-build": "cd ./packages/core/acme-client && time /t >build.md && git add ./build.md && git commit -m \"build: prepare to build\""
|
||||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash-es": "^4.17.20"
|
||||
}
|
||||
"lodash": "^4.17.21"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/**"
|
||||
]
|
||||
}
|
||||
|
||||
1
packages/core/acme-client/.circleci/.gitignore
vendored
Normal file
1
packages/core/acme-client/.circleci/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.temp.yml
|
||||
133
packages/core/acme-client/.circleci/config.yml
Normal file
133
packages/core/acme-client/.circleci/config.yml
Normal file
@@ -0,0 +1,133 @@
|
||||
---
|
||||
version: 2.1
|
||||
|
||||
commands:
|
||||
pre:
|
||||
steps:
|
||||
- run: node --version
|
||||
- run: npm --version
|
||||
- run: yarn --version
|
||||
- checkout
|
||||
|
||||
enable-eab:
|
||||
steps:
|
||||
- run:
|
||||
name: Enable EAB through environment
|
||||
command: |
|
||||
echo 'export ACME_CAP_EAB_ENABLED=1' >> $BASH_ENV
|
||||
|
||||
install-cts:
|
||||
steps:
|
||||
- run:
|
||||
name: Install Pebble Challenge Test Server
|
||||
command: sudo -E /bin/bash ./scripts/test-suite-install-cts.sh
|
||||
environment:
|
||||
PEBBLECTS_VERSION: 2.3.1
|
||||
|
||||
- run:
|
||||
name: Start Pebble Challenge Test Server
|
||||
command: pebble-challtestsrv -dns01 ":8053" -tlsalpn01 ":5001" -http01 ":5002" -https01 ":5003" -defaultIPv4 "127.0.0.1" -defaultIPv6 ""
|
||||
background: true
|
||||
|
||||
install-pebble:
|
||||
steps:
|
||||
- run:
|
||||
name: Install Pebble
|
||||
command: sudo -E /bin/bash ./scripts/test-suite-install-pebble.sh
|
||||
environment:
|
||||
PEBBLE_VERSION: 2.3.1
|
||||
|
||||
- run:
|
||||
name: Start Pebble
|
||||
command: pebble -strict -config /etc/pebble/pebble.json -dnsserver "127.0.0.1:53"
|
||||
background: true
|
||||
environment:
|
||||
PEBBLE_ALTERNATE_ROOTS: 2
|
||||
|
||||
- run:
|
||||
name: Set up environment
|
||||
command: |
|
||||
echo 'export NODE_EXTRA_CA_CERTS="/etc/pebble/ca.cert.pem"' >> $BASH_ENV
|
||||
echo 'export ACME_CA_CERT_PATH="/etc/pebble/ca.cert.pem"' >> $BASH_ENV
|
||||
echo 'export ACME_DIRECTORY_URL="https://127.0.0.1:14000/dir"' >> $BASH_ENV
|
||||
echo 'export ACME_PEBBLE_MANAGEMENT_URL="https://127.0.0.1:15000"' >> $BASH_ENV
|
||||
|
||||
- run:
|
||||
name: Wait for Pebble
|
||||
command: /bin/bash ./scripts/test-suite-wait-for-ca.sh
|
||||
|
||||
install-step:
|
||||
steps:
|
||||
- run:
|
||||
name: Install Step Certificates
|
||||
command: /bin/bash ./scripts/test-suite-install-step.sh
|
||||
environment:
|
||||
STEPCA_VERSION: 0.18.0
|
||||
STEPCLI_VERSION: 0.18.0
|
||||
|
||||
- run:
|
||||
name: Start Step CA
|
||||
command: /usr/bin/step-ca --resolver="127.0.0.1:53" --password-file="/tmp/password" ~/.step/config/ca.json
|
||||
background: true
|
||||
|
||||
- run:
|
||||
name: Set up environment
|
||||
command: |
|
||||
echo 'export NODE_EXTRA_CA_CERTS="/home/circleci/.step/certs/root_ca.crt"' >> $BASH_ENV
|
||||
echo 'export ACME_CA_CERT_PATH="/home/circleci/.step/certs/root_ca.crt"' >> $BASH_ENV
|
||||
echo 'export ACME_DIRECTORY_URL="https://localhost:8443/acme/acme/directory"' >> $BASH_ENV
|
||||
|
||||
echo 'export ACME_CAP_META_TOS_FIELD=0' >> $BASH_ENV
|
||||
echo 'export ACME_CAP_UPDATE_ACCOUNT_KEY=0' >> $BASH_ENV
|
||||
echo 'export ACME_CAP_ALTERNATE_CERT_ROOTS=0' >> $BASH_ENV
|
||||
|
||||
- run:
|
||||
name: Wait for Step CA
|
||||
command: /bin/bash ./scripts/test-suite-wait-for-ca.sh
|
||||
|
||||
install-coredns:
|
||||
steps:
|
||||
- run:
|
||||
name: Install CoreDNS
|
||||
command: sudo -E /bin/bash ./scripts/test-suite-install-coredns.sh
|
||||
environment:
|
||||
COREDNS_VERSION: 1.8.6
|
||||
PEBBLECTS_DNS_PORT: 8053
|
||||
|
||||
- run:
|
||||
name: Start CoreDNS
|
||||
command: sudo coredns -p 53 -conf /etc/coredns/Corefile
|
||||
background: true
|
||||
|
||||
test:
|
||||
steps:
|
||||
- run: yarn --color
|
||||
- run: yarn run lint --color
|
||||
- run: yarn run lint-types
|
||||
- run: yarn run build-docs
|
||||
|
||||
- run:
|
||||
command: yarn run test --color
|
||||
environment:
|
||||
ACME_DOMAIN_NAME: test.example.com
|
||||
ACME_CHALLTESTSRV_URL: http://127.0.0.1:8055
|
||||
ACME_DNS_RESOLVER: 127.0.0.1
|
||||
ACME_TLSALPN_PORT: 5001
|
||||
ACME_HTTP_PORT: 5002
|
||||
ACME_HTTPS_PORT: 5003
|
||||
|
||||
jobs:
|
||||
v16: { docker: [{ image: cimg/node:16.16 }], steps: [ pre, install-cts, install-pebble, install-coredns, test ]}
|
||||
v18: { docker: [{ image: cimg/node:18.4 }], steps: [ pre, install-cts, install-pebble, install-coredns, test ]}
|
||||
eab-v16: { docker: [{ image: cimg/node:16.16 }], steps: [ pre, enable-eab, install-cts, install-pebble, install-coredns, test ]}
|
||||
eab-v18: { docker: [{ image: cimg/node:18.4 }], steps: [ pre, enable-eab, install-cts, install-pebble, install-coredns, test ]}
|
||||
# step-v12: { docker: [{ image: cimg/node:12.22 }], steps: [ pre, install-cts, install-step, install-coredns, test ]}
|
||||
|
||||
workflows:
|
||||
test-suite:
|
||||
jobs:
|
||||
- v16
|
||||
- v18
|
||||
- eab-v16
|
||||
- eab-v18
|
||||
# - step-v12
|
||||
13
packages/core/acme-client/.editorconfig
Normal file
13
packages/core/acme-client/.editorconfig
Normal file
@@ -0,0 +1,13 @@
|
||||
#
|
||||
# http://editorconfig.org
|
||||
#
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = spaces
|
||||
indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[{*.yml,*.yaml}]
|
||||
indent_size = 2
|
||||
23
packages/core/acme-client/.eslintrc.yml
Normal file
23
packages/core/acme-client/.eslintrc.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
extends:
|
||||
- 'airbnb-base'
|
||||
|
||||
env:
|
||||
browser: false
|
||||
node: true
|
||||
mocha: true
|
||||
|
||||
rules:
|
||||
indent: [2, 4, { SwitchCase: 1, VariableDeclarator: 1 }]
|
||||
brace-style: [2, 'stroustrup', { allowSingleLine: true }]
|
||||
space-before-function-paren: [2, { anonymous: 'never', named: 'never' }]
|
||||
func-names: 0
|
||||
prefer-destructuring: 0
|
||||
object-curly-newline: 0
|
||||
class-methods-use-this: 0
|
||||
wrap-iife: [2, 'inside']
|
||||
no-param-reassign: 0
|
||||
comma-dangle: [2, 'never']
|
||||
max-len: [1, 200, 2, { ignoreUrls: true, ignoreComments: false }]
|
||||
no-multiple-empty-lines: [2, { max: 2, maxBOF: 0, maxEOF: 0 }]
|
||||
prefer-object-spread: 0
|
||||
import/no-useless-path-segments: 0
|
||||
2
packages/core/acme-client/.yarnrc
Normal file
2
packages/core/acme-client/.yarnrc
Normal file
@@ -0,0 +1,2 @@
|
||||
ignore-engines true
|
||||
ignore-optional true
|
||||
216
packages/core/acme-client/CHANGELOG.md
Normal file
216
packages/core/acme-client/CHANGELOG.md
Normal file
@@ -0,0 +1,216 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [1.0.6](https://github.com/publishlab/node-acme-client/compare/v1.0.5...v1.0.6) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
## [1.0.5](https://github.com/publishlab/node-acme-client/compare/v1.0.4...v1.0.5) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
## [1.0.4](https://github.com/publishlab/node-acme-client/compare/v1.0.3...v1.0.4) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
## [1.0.3](https://github.com/publishlab/node-acme-client/compare/v1.0.2...v1.0.3) (2023-05-25)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
## [1.0.2](https://github.com/publishlab/node-acme-client/compare/v1.0.1...v1.0.2) (2023-05-24)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
## [1.0.1](https://github.com/publishlab/node-acme-client/compare/v1.0.0...v1.0.1) (2023-05-24)
|
||||
|
||||
**Note:** Version bump only for package @certd/acme-client
|
||||
|
||||
# Changelog
|
||||
|
||||
## Important upgrade notice
|
||||
|
||||
On September 15, 2022, Let's Encrypt will stop accepting Certificate Signing Requests signed using the obsolete SHA-1 hash. This change affects all `acme-client` versions lower than `3.3.2` and `4.2.4`. Please upgrade ASAP to ensure that your certificates can still be issued following this date.
|
||||
|
||||
A more detailed explanation can be found [at the Let's Encrypt forums](https://community.letsencrypt.org/t/rejecting-sha-1-csrs-and-validation-using-tls-1-0-1-1-urls/175144).
|
||||
|
||||
## v5.0.0 (2022-07-28)
|
||||
|
||||
* [Upgrade guide here](docs/upgrade-v5.md)
|
||||
* `added` New native crypto interface, ECC/ECDSA support
|
||||
* `breaking` Remove support for Node v10, v12 and v14
|
||||
* `breaking` Prioritize issuer closest to root during preferred chain selection - [#46](https://github.com/publishlab/node-acme-client/issues/46)
|
||||
* `changed` Replace `bluebird` dependency with native promise APIs
|
||||
* `changed` Replace `backo2` dependency with internal utility
|
||||
|
||||
## v4.2.5 (2022-03-21)
|
||||
|
||||
* `fixed` Upgrade `axios@0.26.1`
|
||||
* `fixed` Upgrade `node-forge@1.3.0` - [CVE-2022-24771](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24771), [CVE-2022-24772](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24772), [CVE-2022-24773](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24773)
|
||||
|
||||
## 4.2.4 (2022-03-19)
|
||||
|
||||
* `fixed` Use SHA-256 when signing CSRs
|
||||
|
||||
## v3.3.2 (2022-03-19)
|
||||
|
||||
* `backport` Use SHA-256 when signing CSRs
|
||||
|
||||
## v4.2.3 (2022-01-11)
|
||||
|
||||
* `added` Directory URLs for ACME providers [Buypass](https://www.buypass.com) and [ZeroSSL](https://zerossl.com)
|
||||
* `fixed` Skip already valid authorizations when using `client.auto()`
|
||||
|
||||
## v4.2.2 (2022-01-10)
|
||||
|
||||
* `fixed` Upgrade `node-forge@1.2.0`
|
||||
|
||||
## v4.2.1 (2022-01-10)
|
||||
|
||||
* `fixed` ZeroSSL `duplicate_domains_in_array` error when using `client.auto()`
|
||||
|
||||
## v4.2.0 (2022-01-06)
|
||||
|
||||
* `added` Support for external account binding - [RFC 8555 Section 7.3.4](https://tools.ietf.org/html/rfc8555#section-7.3.4)
|
||||
* `added` Ability to pass through custom logger function
|
||||
* `changed` Increase default `backoffAttempts` to 10
|
||||
* `fixed` Deactivate authorizations where challenges can not be completed
|
||||
* `fixed` Attempt authoritative name servers when verifying `dns-01` challenges
|
||||
* `fixed` Error verbosity when failing to read ACME directory
|
||||
* `fixed` Correctly recognize `ready` and `processing` states - [RFC 8555 Section 7.1.6](https://tools.ietf.org/html/rfc8555#section-7.1.6)
|
||||
|
||||
## v4.1.4 (2021-12-23)
|
||||
|
||||
* `fixed` Upgrade `axios@0.21.4` - [CVE-2021-3749](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3749)
|
||||
|
||||
## v4.1.3 (2021-02-22)
|
||||
|
||||
* `fixed` Upgrade `axios@0.21.1` - [CVE-2020-28168](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-28168)
|
||||
|
||||
## v4.1.2 (2020-11-16)
|
||||
|
||||
* `fixed` Bug when encoding PEM payloads, potentially causing malformed requests
|
||||
|
||||
## v4.1.1 (2020-11-13)
|
||||
|
||||
* `fixed` Missing TypeScript definitions
|
||||
|
||||
## v4.1.0 (2020-11-12)
|
||||
|
||||
* `added` Option `preferredChain` added to `client.getCertificate()` and `client.auto()` to indicate which certificate chain is preferred if a CA offers multiple
|
||||
* Related: [https://community.letsencrypt.org/t/transition-to-isrgs-root-delayed-until-jan-11-2021/125516](https://community.letsencrypt.org/t/transition-to-isrgs-root-delayed-until-jan-11-2021/125516)
|
||||
* `added` Method `client.getOrder()` to refresh order from CA
|
||||
* `fixed` Upgrade `axios@0.21.0`
|
||||
* `fixed` Error when attempting to revoke a certificate chain
|
||||
* `fixed` Missing URL augmentation in `client.finalizeOrder()` and `client.deactivateAuthorization()`
|
||||
* `fixed` Add certificate issuer to response from `forge.readCertificateInfo()`
|
||||
|
||||
## v4.0.2 (2020-10-09)
|
||||
|
||||
* `fixed` Explicitly set default `axios` HTTP adapter - [axios/axios#1180](https://github.com/axios/axios/issues/1180)
|
||||
|
||||
## v4.0.1 (2020-09-15)
|
||||
|
||||
* `fixed` Upgrade `node-forge@0.10.0` - [CVE-2020-7720](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-7720)
|
||||
|
||||
## v4.0.0 (2020-05-29)
|
||||
|
||||
* `breaking` Remove support for Node v8
|
||||
* `breaking` Remove deprecated `openssl` crypto module
|
||||
* `fixed` Incorrect TypeScript `CertificateInfo` definitions
|
||||
* `fixed` Allow trailing whitespace character in `http-01` challenge response
|
||||
|
||||
## v3.3.1 (2020-01-07)
|
||||
|
||||
* `fixed` Improvements to TypeScript definitions
|
||||
|
||||
## v3.3.0 (2019-12-19)
|
||||
|
||||
* `added` TypeScript definitions
|
||||
* `fixed` Allow missing ACME directory meta field - [RFC 8555 Section 7.1.1](https://tools.ietf.org/html/rfc8555#section-7.1.1)
|
||||
|
||||
## v3.2.1 (2019-11-14)
|
||||
|
||||
* `added` New option `skipChallengeVerification` added to `client.auto()` to bypass internal challenge verification
|
||||
|
||||
## v3.2.0 (2019-08-26)
|
||||
|
||||
* `added` More extensive testing using [letsencrypt/pebble](https://github.com/letsencrypt/pebble)
|
||||
* `changed` When creating a CSR, `commonName` no longer defaults to `'localhost'`
|
||||
* This change is not considered breaking since `commonName: 'localhost'` will result in an error when ordering a certificate
|
||||
* `fixed` Retry signed API requests on `urn:ietf:params:acme:error:badNonce` - [RFC 8555 Section 6.5](https://tools.ietf.org/html/rfc8555#section-6.5)
|
||||
* `fixed` Minor bugs related to `POST-as-GET` when calling `updateAccount()`
|
||||
* `fixed` Ensure subject common name is present in SAN when creating a CSR - [CAB v1.2.3 Section 9.2.2](https://cabforum.org/wp-content/uploads/BRv1.2.3.pdf)
|
||||
* `fixed` Send empty JSON body when responding to challenges - [RFC 8555 Section 7.5.1](https://tools.ietf.org/html/rfc8555#section-7.5.1)
|
||||
|
||||
## v2.3.1 (2019-08-26)
|
||||
|
||||
* `backport` Minor bugs related to `POST-as-GET` when calling `client.updateAccount()`
|
||||
* `backport` Send empty JSON body when responding to challenges
|
||||
|
||||
## v3.1.0 (2019-08-21)
|
||||
|
||||
* `added` UTF-8 support when generating a CSR subject using forge - [RFC 5280](https://tools.ietf.org/html/rfc5280)
|
||||
* `fixed` Implement `POST-as-GET` for all ACME API requests - [RFC 8555 Section 6.3](https://tools.ietf.org/html/rfc8555#section-6.3)
|
||||
|
||||
## v2.3.0 (2019-08-21)
|
||||
|
||||
* `backport` Implement `POST-as-GET` for all ACME API requests
|
||||
|
||||
## v3.0.0 (2019-07-13)
|
||||
|
||||
* `added` Expose `axios` instance to allow manipulating HTTP client defaults
|
||||
* `breaking` Remove support for Node v4 and v6
|
||||
* `breaking` Remove Babel transpilation
|
||||
|
||||
## v2.2.3 (2019-01-25)
|
||||
|
||||
* `added` DNS CNAME detection when verifying `dns-01` challenges
|
||||
|
||||
## v2.2.2 (2019-01-07)
|
||||
|
||||
* `added` Support for `tls-alpn-01` challenge key authorization
|
||||
|
||||
## v2.2.1 (2019-01-04)
|
||||
|
||||
* `fixed` Handle and throw errors from OpenSSL process
|
||||
|
||||
## v2.2.0 (2018-11-06)
|
||||
|
||||
* `added` New [node-forge](https://www.npmjs.com/package/node-forge) crypto interface, removes OpenSSL CLI dependency
|
||||
* `added` Support native `crypto.generateKeyPair()` API when generating key pairs
|
||||
|
||||
## v2.1.0 (2018-10-21)
|
||||
|
||||
* `added` Ability to set and get current account URL
|
||||
* `fixed` Replace HTTP client `request` with `axios`
|
||||
* `fixed` Auto-mode no longer tries to create account when account URL exists
|
||||
|
||||
## v2.0.1 (2018-08-17)
|
||||
|
||||
* `fixed` Key rollover in compliance with [draft-ietf-acme-13](https://tools.ietf.org/html/draft-ietf-acme-acme-13)
|
||||
|
||||
## v2.0.0 (2018-04-02)
|
||||
|
||||
* `breaking` ACMEv2
|
||||
* `breaking` API changes
|
||||
* `breaking` Rewrite to ES6
|
||||
* `breaking` Promises instead of callbacks
|
||||
|
||||
## v1.0.0 (2017-10-20)
|
||||
|
||||
* API stable
|
||||
|
||||
## v0.2.1 (2017-09-27)
|
||||
|
||||
* `fixed` Bug causing invalid anti-replay nonce
|
||||
|
||||
## v0.2.0 (2017-09-21)
|
||||
|
||||
* `breaking` OpenSSL method `readCsrDomains` and `readCertificateInfo` now return domains as an object
|
||||
* `fixed` Added and fixed some tests
|
||||
|
||||
## v0.1.0 (2017-09-14)
|
||||
|
||||
* `acme-client` released
|
||||
21
packages/core/acme-client/LICENSE
Normal file
21
packages/core/acme-client/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017-2022 Publish Lab
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
262
packages/core/acme-client/README.md
Normal file
262
packages/core/acme-client/README.md
Normal file
@@ -0,0 +1,262 @@
|
||||
# acme-client [](https://circleci.com/gh/publishlab/node-acme-client)
|
||||
|
||||
*A simple and unopinionated ACME client.*
|
||||
|
||||
This module is written to handle communication with a Boulder/Let's Encrypt-style ACME API.
|
||||
|
||||
* RFC 8555 - Automatic Certificate Management Environment (ACME): [https://tools.ietf.org/html/rfc8555](https://tools.ietf.org/html/rfc8555)
|
||||
* Boulder divergences from ACME: [https://github.com/letsencrypt/boulder/blob/master/docs/acme-divergences.md](https://github.com/letsencrypt/boulder/blob/master/docs/acme-divergences.md)
|
||||
|
||||
|
||||
## Important upgrade notice
|
||||
|
||||
On September 15, 2022, Let's Encrypt will stop accepting Certificate Signing Requests signed using the obsolete SHA-1 hash. This change affects all `acme-client` versions lower than `3.3.2` and `4.2.4`. Please upgrade ASAP to ensure that your certificates can still be issued following this date.
|
||||
|
||||
A more detailed explanation can be found [at the Let's Encrypt forums](https://community.letsencrypt.org/t/rejecting-sha-1-csrs-and-validation-using-tls-1-0-1-1-urls/175144).
|
||||
|
||||
|
||||
### Compatibility
|
||||
|
||||
| acme-client | Node.js | |
|
||||
| ------------- | --------- | ----------------------------------------- |
|
||||
| v5.x | >= v16 | [Upgrade guide](docs/upgrade-v5.md) |
|
||||
| v4.x | >= v10 | [Changelog](CHANGELOG.md#v400-2020-05-29) |
|
||||
| v3.x | >= v8 | [Changelog](CHANGELOG.md#v300-2019-07-13) |
|
||||
| v2.x | >= v4 | [Changelog](CHANGELOG.md#v200-2018-04-02) |
|
||||
| v1.x | >= v4 | [Changelog](CHANGELOG.md#v100-2017-10-20) |
|
||||
|
||||
|
||||
### Table of contents
|
||||
|
||||
* [Installation](#installation)
|
||||
* [Usage](#usage)
|
||||
* [Directory URLs](#directory-urls)
|
||||
* [External account binding](#external-account-binding)
|
||||
* [Specifying the account URL](#specifying-the-account-url)
|
||||
* [Cryptography](#cryptography)
|
||||
* [Legacy .forge interface](#legacy-forge-interface)
|
||||
* [Auto mode](#auto-mode)
|
||||
* [Challenge priority](#challenge-priority)
|
||||
* [Internal challenge verification](#internal-challenge-verification)
|
||||
* [API](#api)
|
||||
* [HTTP client defaults](#http-client-defaults)
|
||||
* [Debugging](#debugging)
|
||||
* [License](#license)
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ npm install acme-client
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const acme = require('acme-client');
|
||||
|
||||
const accountPrivateKey = '<PEM encoded private key>';
|
||||
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: accountPrivateKey
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Directory URLs
|
||||
|
||||
```js
|
||||
acme.directory.buypass.staging;
|
||||
acme.directory.buypass.production;
|
||||
|
||||
acme.directory.letsencrypt.staging;
|
||||
acme.directory.letsencrypt.production;
|
||||
|
||||
acme.directory.zerossl.production;
|
||||
```
|
||||
|
||||
|
||||
### External account binding
|
||||
|
||||
To enable [external account binding](https://tools.ietf.org/html/rfc8555#section-7.3.4) when creating your ACME account, provide your KID and HMAC key to the client constructor.
|
||||
|
||||
```js
|
||||
const client = new acme.Client({
|
||||
directoryUrl: 'https://acme-provider.example.com/directory-url',
|
||||
accountKey: accountPrivateKey,
|
||||
externalAccountBinding: {
|
||||
kid: 'YOUR-EAB-KID',
|
||||
hmacKey: 'YOUR-EAB-HMAC-KEY'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Specifying the account URL
|
||||
|
||||
During the ACME account creation process, the server will check the supplied account key and either create a new account if the key is unused, or return the existing ACME account bound to that key.
|
||||
|
||||
In some cases, for example with some EAB providers, this account creation step may be prohibited and might require you to manually specify the account URL beforehand. This can be done through `accountUrl` in the client constructor.
|
||||
|
||||
```js
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: accountPrivateKey,
|
||||
accountUrl: 'https://acme-v02.api.letsencrypt.org/acme/acct/12345678'
|
||||
});
|
||||
```
|
||||
|
||||
You can fetch the clients current account URL, either after creating an account or supplying it through the constructor, using `getAccountUrl()`:
|
||||
|
||||
```js
|
||||
const myAccountUrl = client.getAccountUrl();
|
||||
```
|
||||
|
||||
|
||||
## Cryptography
|
||||
|
||||
For key pairs `acme-client` utilizes native Node.js cryptography APIs, supporting signing and generation of both RSA and ECDSA keys. The module [jsrsasign](https://www.npmjs.com/package/jsrsasign) is used to generate and parse Certificate Signing Requests.
|
||||
|
||||
These utility methods are exposed through `.crypto`.
|
||||
|
||||
* __Documentation: [docs/crypto.md](docs/crypto.md)__
|
||||
|
||||
```js
|
||||
const privateRsaKey = await acme.crypto.createPrivateRsaKey();
|
||||
const privateEcdsaKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
|
||||
const [certificateKey, certificateCsr] = await acme.crypto.createCsr({
|
||||
commonName: '*.example.com',
|
||||
altNames: ['example.com']
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Legacy `.forge` interface
|
||||
|
||||
The legacy `node-forge` crypto interface is still available for backward compatibility, however this interface is now considered deprecated and will be removed in a future major version of `acme-client`.
|
||||
|
||||
You should consider migrating to the new `.crypto` API at your earliest convenience. More details can be found in the [acme-client v5 upgrade guide](docs/upgrade-v5.md).
|
||||
|
||||
* __Documentation: [docs/forge.md](docs/forge.md)__
|
||||
|
||||
|
||||
## Auto mode
|
||||
|
||||
For convenience an `auto()` method is included in the client that takes a single config object. This method will handle the entire process of getting a certificate for one or multiple domains.
|
||||
|
||||
* __Documentation: [docs/client.md#AcmeClient+auto](docs/client.md#AcmeClient+auto)__
|
||||
* __Full example: [examples/auto.js](examples/auto.js)__
|
||||
|
||||
```js
|
||||
const autoOpts = {
|
||||
csr: '<PEM encoded CSR>',
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {},
|
||||
challengeRemoveFn: async (authz, challenge, keyAuthorization) => {}
|
||||
};
|
||||
|
||||
const certificate = await client.auto(autoOpts);
|
||||
```
|
||||
|
||||
|
||||
### Challenge priority
|
||||
|
||||
When ordering a certificate using auto mode, `acme-client` uses a priority list when selecting challenges to respond to. Its default value is `['http-01', 'dns-01']` which translates to "use `http-01` if any challenges exist, otherwise fall back to `dns-01`".
|
||||
|
||||
While most challenges can be validated using the method of your choosing, please note that __wildcard certificates can only be validated through `dns-01`__. More information regarding Let's Encrypt challenge types [can be found here](https://letsencrypt.org/docs/challenge-types/).
|
||||
|
||||
To modify challenge priority, provide a list of challenge types in `challengePriority`:
|
||||
|
||||
```js
|
||||
await client.auto({
|
||||
...,
|
||||
challengePriority: ['http-01', 'dns-01']
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Internal challenge verification
|
||||
|
||||
When using auto mode, `acme-client` will first validate that challenges are satisfied internally before completing the challenge at the ACME provider. In some cases (firewalls, etc) this internal challenge verification might not be possible to complete.
|
||||
|
||||
If internal challenge validation needs to travel through an HTTP proxy, see [HTTP client defaults](#http-client-defaults).
|
||||
|
||||
To completely disable `acme-client`s internal challenge verification, enable `skipChallengeVerification`:
|
||||
|
||||
```js
|
||||
await client.auto({
|
||||
...,
|
||||
skipChallengeVerification: true
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
For more fine-grained control you can interact with the ACME API using the methods documented below.
|
||||
|
||||
* __Documentation: [docs/client.md](docs/client.md)__
|
||||
* __Full example: [examples/api.js](examples/api.js)__
|
||||
|
||||
```js
|
||||
const account = await client.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: ['mailto:test@example.com']
|
||||
});
|
||||
|
||||
const order = await client.createOrder({
|
||||
identifiers: [
|
||||
{ type: 'dns', value: 'example.com' },
|
||||
{ type: 'dns', value: '*.example.com' }
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## HTTP client defaults
|
||||
|
||||
This module uses [axios](https://github.com/axios/axios) when communicating with the ACME HTTP API, and exposes the client instance through `.axios`.
|
||||
|
||||
For example, should you need to change the default axios configuration to route requests through an HTTP proxy, this can be achieved as follows:
|
||||
|
||||
```js
|
||||
const acme = require('acme-client');
|
||||
|
||||
acme.axios.defaults.proxy = {
|
||||
host: '127.0.0.1',
|
||||
port: 9000
|
||||
};
|
||||
```
|
||||
|
||||
A complete list of axios options and documentation can be found at:
|
||||
|
||||
* [https://github.com/axios/axios#request-config](https://github.com/axios/axios#request-config)
|
||||
* [https://github.com/axios/axios#custom-instance-defaults](https://github.com/axios/axios#custom-instance-defaults)
|
||||
|
||||
|
||||
## Debugging
|
||||
|
||||
To get a better grasp of what `acme-client` is doing behind the scenes, you can either pass it a logger function, or enable debugging through an environment variable.
|
||||
|
||||
Setting a logger function may for example be useful for passing messages on to another logging system, or just dumping them to the console.
|
||||
|
||||
```js
|
||||
acme.setLogger((message) => {
|
||||
console.log(message);
|
||||
});
|
||||
```
|
||||
|
||||
Debugging to the console can also be enabled through [debug](https://www.npmjs.com/package/debug) by setting an environment variable.
|
||||
|
||||
```bash
|
||||
DEBUG=acme-client node index.js
|
||||
```
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
1
packages/core/acme-client/build.md
Normal file
1
packages/core/acme-client/build.md
Normal file
@@ -0,0 +1 @@
|
||||
00:19
|
||||
518
packages/core/acme-client/docs/client.md
Normal file
518
packages/core/acme-client/docs/client.md
Normal file
@@ -0,0 +1,518 @@
|
||||
## Classes
|
||||
|
||||
<dl>
|
||||
<dt><a href="#AcmeClient">AcmeClient</a></dt>
|
||||
<dd><p>AcmeClient</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
## Objects
|
||||
|
||||
<dl>
|
||||
<dt><a href="#Client">Client</a> : <code>object</code></dt>
|
||||
<dd><p>ACME client</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<a name="AcmeClient"></a>
|
||||
|
||||
## AcmeClient
|
||||
AcmeClient
|
||||
|
||||
**Kind**: global class
|
||||
|
||||
* [AcmeClient](#AcmeClient)
|
||||
* [new AcmeClient(opts)](#new_AcmeClient_new)
|
||||
* [.getTermsOfServiceUrl()](#AcmeClient+getTermsOfServiceUrl) ⇒ <code>Promise.<(string\|null)></code>
|
||||
* [.getAccountUrl()](#AcmeClient+getAccountUrl) ⇒ <code>string</code>
|
||||
* [.createAccount([data])](#AcmeClient+createAccount) ⇒ <code>Promise.<object></code>
|
||||
* [.updateAccount([data])](#AcmeClient+updateAccount) ⇒ <code>Promise.<object></code>
|
||||
* [.updateAccountKey(newAccountKey, [data])](#AcmeClient+updateAccountKey) ⇒ <code>Promise.<object></code>
|
||||
* [.createOrder(data)](#AcmeClient+createOrder) ⇒ <code>Promise.<object></code>
|
||||
* [.getOrder(order)](#AcmeClient+getOrder) ⇒ <code>Promise.<object></code>
|
||||
* [.finalizeOrder(order, csr)](#AcmeClient+finalizeOrder) ⇒ <code>Promise.<object></code>
|
||||
* [.getAuthorizations(order)](#AcmeClient+getAuthorizations) ⇒ <code>Promise.<Array.<object>></code>
|
||||
* [.deactivateAuthorization(authz)](#AcmeClient+deactivateAuthorization) ⇒ <code>Promise.<object></code>
|
||||
* [.getChallengeKeyAuthorization(challenge)](#AcmeClient+getChallengeKeyAuthorization) ⇒ <code>Promise.<string></code>
|
||||
* [.verifyChallenge(authz, challenge)](#AcmeClient+verifyChallenge) ⇒ <code>Promise</code>
|
||||
* [.completeChallenge(challenge)](#AcmeClient+completeChallenge) ⇒ <code>Promise.<object></code>
|
||||
* [.waitForValidStatus(item)](#AcmeClient+waitForValidStatus) ⇒ <code>Promise.<object></code>
|
||||
* [.getCertificate(order, [preferredChain])](#AcmeClient+getCertificate) ⇒ <code>Promise.<string></code>
|
||||
* [.revokeCertificate(cert, [data])](#AcmeClient+revokeCertificate) ⇒ <code>Promise</code>
|
||||
* [.auto(opts)](#AcmeClient+auto) ⇒ <code>Promise.<string></code>
|
||||
|
||||
<a name="new_AcmeClient_new"></a>
|
||||
|
||||
### new AcmeClient(opts)
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| opts | <code>object</code> | |
|
||||
| opts.directoryUrl | <code>string</code> | ACME directory URL |
|
||||
| opts.accountKey | <code>buffer</code> \| <code>string</code> | PEM encoded account private key |
|
||||
| [opts.accountUrl] | <code>string</code> | Account URL, default: `null` |
|
||||
| [opts.externalAccountBinding] | <code>object</code> | |
|
||||
| [opts.externalAccountBinding.kid] | <code>string</code> | External account binding KID |
|
||||
| [opts.externalAccountBinding.hmacKey] | <code>string</code> | External account binding HMAC key |
|
||||
| [opts.backoffAttempts] | <code>number</code> | Maximum number of backoff attempts, default: `10` |
|
||||
| [opts.backoffMin] | <code>number</code> | Minimum backoff attempt delay in milliseconds, default: `5000` |
|
||||
| [opts.backoffMax] | <code>number</code> | Maximum backoff attempt delay in milliseconds, default: `30000` |
|
||||
|
||||
**Example**
|
||||
Create ACME client instance
|
||||
```js
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: 'Private key goes here'
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Create ACME client instance
|
||||
```js
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: 'Private key goes here',
|
||||
accountUrl: 'Optional account URL goes here',
|
||||
backoffAttempts: 10,
|
||||
backoffMin: 5000,
|
||||
backoffMax: 30000
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Create ACME client with external account binding
|
||||
```js
|
||||
const client = new acme.Client({
|
||||
directoryUrl: 'https://acme-provider.example.com/directory-url',
|
||||
accountKey: 'Private key goes here',
|
||||
externalAccountBinding: {
|
||||
kid: 'YOUR-EAB-KID',
|
||||
hmacKey: 'YOUR-EAB-HMAC-KEY'
|
||||
}
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+getTermsOfServiceUrl"></a>
|
||||
|
||||
### acmeClient.getTermsOfServiceUrl() ⇒ <code>Promise.<(string\|null)></code>
|
||||
Get Terms of Service URL if available
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<(string\|null)></code> - ToS URL
|
||||
**Example**
|
||||
Get Terms of Service URL
|
||||
```js
|
||||
const termsOfService = client.getTermsOfServiceUrl();
|
||||
|
||||
if (!termsOfService) {
|
||||
// CA did not provide Terms of Service
|
||||
}
|
||||
```
|
||||
<a name="AcmeClient+getAccountUrl"></a>
|
||||
|
||||
### acmeClient.getAccountUrl() ⇒ <code>string</code>
|
||||
Get current account URL
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>string</code> - Account URL
|
||||
**Throws**:
|
||||
|
||||
- <code>Error</code> No account URL found
|
||||
|
||||
**Example**
|
||||
Get current account URL
|
||||
```js
|
||||
try {
|
||||
const accountUrl = client.getAccountUrl();
|
||||
}
|
||||
catch (e) {
|
||||
// No account URL exists, need to create account first
|
||||
}
|
||||
```
|
||||
<a name="AcmeClient+createAccount"></a>
|
||||
|
||||
### acmeClient.createAccount([data]) ⇒ <code>Promise.<object></code>
|
||||
Create a new account
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.3
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Account
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [data] | <code>object</code> | Request data |
|
||||
|
||||
**Example**
|
||||
Create a new account
|
||||
```js
|
||||
const account = await client.createAccount({
|
||||
termsOfServiceAgreed: true
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Create a new account with contact info
|
||||
```js
|
||||
const account = await client.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: ['mailto:test@example.com']
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+updateAccount"></a>
|
||||
|
||||
### acmeClient.updateAccount([data]) ⇒ <code>Promise.<object></code>
|
||||
Update existing account
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.3.2
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Account
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [data] | <code>object</code> | Request data |
|
||||
|
||||
**Example**
|
||||
Update existing account
|
||||
```js
|
||||
const account = await client.updateAccount({
|
||||
contact: ['mailto:foo@example.com']
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+updateAccountKey"></a>
|
||||
|
||||
### acmeClient.updateAccountKey(newAccountKey, [data]) ⇒ <code>Promise.<object></code>
|
||||
Update account private key
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.3.5
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Account
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| newAccountKey | <code>buffer</code> \| <code>string</code> | New PEM encoded private key |
|
||||
| [data] | <code>object</code> | Additional request data |
|
||||
|
||||
**Example**
|
||||
Update account private key
|
||||
```js
|
||||
const newAccountKey = 'New private key goes here';
|
||||
const result = await client.updateAccountKey(newAccountKey);
|
||||
```
|
||||
<a name="AcmeClient+createOrder"></a>
|
||||
|
||||
### acmeClient.createOrder(data) ⇒ <code>Promise.<object></code>
|
||||
Create a new order
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Order
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>object</code> | Request data |
|
||||
|
||||
**Example**
|
||||
Create a new order
|
||||
```js
|
||||
const order = await client.createOrder({
|
||||
identifiers: [
|
||||
{ type: 'dns', value: 'example.com' },
|
||||
{ type: 'dns', value: 'test.example.com' }
|
||||
]
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+getOrder"></a>
|
||||
|
||||
### acmeClient.getOrder(order) ⇒ <code>Promise.<object></code>
|
||||
Refresh order object from CA
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Order
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order | <code>object</code> | Order object |
|
||||
|
||||
**Example**
|
||||
```js
|
||||
const order = { ... }; // Previously created order object
|
||||
const result = await client.getOrder(order);
|
||||
```
|
||||
<a name="AcmeClient+finalizeOrder"></a>
|
||||
|
||||
### acmeClient.finalizeOrder(order, csr) ⇒ <code>Promise.<object></code>
|
||||
Finalize order
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Order
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order | <code>object</code> | Order object |
|
||||
| csr | <code>buffer</code> \| <code>string</code> | PEM encoded Certificate Signing Request |
|
||||
|
||||
**Example**
|
||||
Finalize order
|
||||
```js
|
||||
const order = { ... }; // Previously created order object
|
||||
const csr = { ... }; // Previously created Certificate Signing Request
|
||||
const result = await client.finalizeOrder(order, csr);
|
||||
```
|
||||
<a name="AcmeClient+getAuthorizations"></a>
|
||||
|
||||
### acmeClient.getAuthorizations(order) ⇒ <code>Promise.<Array.<object>></code>
|
||||
Get identifier authorizations from order
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.5
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<Array.<object>></code> - Authorizations
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order | <code>object</code> | Order |
|
||||
|
||||
**Example**
|
||||
Get identifier authorizations
|
||||
```js
|
||||
const order = { ... }; // Previously created order object
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
|
||||
authorizations.forEach((authz) => {
|
||||
const { challenges } = authz;
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+deactivateAuthorization"></a>
|
||||
|
||||
### acmeClient.deactivateAuthorization(authz) ⇒ <code>Promise.<object></code>
|
||||
Deactivate identifier authorization
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.5.2
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Authorization
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| authz | <code>object</code> | Identifier authorization |
|
||||
|
||||
**Example**
|
||||
Deactivate identifier authorization
|
||||
```js
|
||||
const authz = { ... }; // Identifier authorization resolved from previously created order
|
||||
const result = await client.deactivateAuthorization(authz);
|
||||
```
|
||||
<a name="AcmeClient+getChallengeKeyAuthorization"></a>
|
||||
|
||||
### acmeClient.getChallengeKeyAuthorization(challenge) ⇒ <code>Promise.<string></code>
|
||||
Get key authorization for ACME challenge
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-8.1
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<string></code> - Key authorization
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| challenge | <code>object</code> | Challenge object returned by API |
|
||||
|
||||
**Example**
|
||||
Get challenge key authorization
|
||||
```js
|
||||
const challenge = { ... }; // Challenge from previously resolved identifier authorization
|
||||
const key = await client.getChallengeKeyAuthorization(challenge);
|
||||
|
||||
// Write key somewhere to satisfy challenge
|
||||
```
|
||||
<a name="AcmeClient+verifyChallenge"></a>
|
||||
|
||||
### acmeClient.verifyChallenge(authz, challenge) ⇒ <code>Promise</code>
|
||||
Verify that ACME challenge is satisfied
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| authz | <code>object</code> | Identifier authorization |
|
||||
| challenge | <code>object</code> | Authorization challenge |
|
||||
|
||||
**Example**
|
||||
Verify satisfied ACME challenge
|
||||
```js
|
||||
const authz = { ... }; // Identifier authorization
|
||||
const challenge = { ... }; // Satisfied challenge
|
||||
await client.verifyChallenge(authz, challenge);
|
||||
```
|
||||
<a name="AcmeClient+completeChallenge"></a>
|
||||
|
||||
### acmeClient.completeChallenge(challenge) ⇒ <code>Promise.<object></code>
|
||||
Notify CA that challenge has been completed
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.5.1
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Challenge
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| challenge | <code>object</code> | Challenge object returned by API |
|
||||
|
||||
**Example**
|
||||
Notify CA that challenge has been completed
|
||||
```js
|
||||
const challenge = { ... }; // Satisfied challenge
|
||||
const result = await client.completeChallenge(challenge);
|
||||
```
|
||||
<a name="AcmeClient+waitForValidStatus"></a>
|
||||
|
||||
### acmeClient.waitForValidStatus(item) ⇒ <code>Promise.<object></code>
|
||||
Wait for ACME provider to verify status on a order, authorization or challenge
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.5.1
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<object></code> - Valid order, authorization or challenge
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| item | <code>object</code> | An order, authorization or challenge object |
|
||||
|
||||
**Example**
|
||||
Wait for valid challenge status
|
||||
```js
|
||||
const challenge = { ... };
|
||||
await client.waitForValidStatus(challenge);
|
||||
```
|
||||
**Example**
|
||||
Wait for valid authoriation status
|
||||
```js
|
||||
const authz = { ... };
|
||||
await client.waitForValidStatus(authz);
|
||||
```
|
||||
**Example**
|
||||
Wait for valid order status
|
||||
```js
|
||||
const order = { ... };
|
||||
await client.waitForValidStatus(order);
|
||||
```
|
||||
<a name="AcmeClient+getCertificate"></a>
|
||||
|
||||
### acmeClient.getCertificate(order, [preferredChain]) ⇒ <code>Promise.<string></code>
|
||||
Get certificate from ACME order
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.4.2
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<string></code> - Certificate
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| order | <code>object</code> | | Order object |
|
||||
| [preferredChain] | <code>string</code> | <code>null</code> | Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null` |
|
||||
|
||||
**Example**
|
||||
Get certificate
|
||||
```js
|
||||
const order = { ... }; // Previously created order
|
||||
const certificate = await client.getCertificate(order);
|
||||
```
|
||||
**Example**
|
||||
Get certificate with preferred chain
|
||||
```js
|
||||
const order = { ... }; // Previously created order
|
||||
const certificate = await client.getCertificate(order, 'DST Root CA X3');
|
||||
```
|
||||
<a name="AcmeClient+revokeCertificate"></a>
|
||||
|
||||
### acmeClient.revokeCertificate(cert, [data]) ⇒ <code>Promise</code>
|
||||
Revoke certificate
|
||||
|
||||
https://tools.ietf.org/html/rfc8555#section-7.6
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| cert | <code>buffer</code> \| <code>string</code> | PEM encoded certificate |
|
||||
| [data] | <code>object</code> | Additional request data |
|
||||
|
||||
**Example**
|
||||
Revoke certificate
|
||||
```js
|
||||
const certificate = { ... }; // Previously created certificate
|
||||
const result = await client.revokeCertificate(certificate);
|
||||
```
|
||||
**Example**
|
||||
Revoke certificate with reason
|
||||
```js
|
||||
const certificate = { ... }; // Previously created certificate
|
||||
const result = await client.revokeCertificate(certificate, {
|
||||
reason: 4
|
||||
});
|
||||
```
|
||||
<a name="AcmeClient+auto"></a>
|
||||
|
||||
### acmeClient.auto(opts) ⇒ <code>Promise.<string></code>
|
||||
Auto mode
|
||||
|
||||
**Kind**: instance method of [<code>AcmeClient</code>](#AcmeClient)
|
||||
**Returns**: <code>Promise.<string></code> - Certificate
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| opts | <code>object</code> | |
|
||||
| opts.csr | <code>buffer</code> \| <code>string</code> | Certificate Signing Request |
|
||||
| opts.challengeCreateFn | <code>function</code> | Function returning Promise triggered before completing ACME challenge |
|
||||
| opts.challengeRemoveFn | <code>function</code> | Function returning Promise triggered after completing ACME challenge |
|
||||
| [opts.email] | <code>string</code> | Account email address |
|
||||
| [opts.termsOfServiceAgreed] | <code>boolean</code> | Agree to Terms of Service, default: `false` |
|
||||
| [opts.skipChallengeVerification] | <code>boolean</code> | Skip internal challenge verification before notifying ACME provider, default: `false` |
|
||||
| [opts.challengePriority] | <code>Array.<string></code> | Array defining challenge type priority, default: `['http-01', 'dns-01']` |
|
||||
| [opts.preferredChain] | <code>string</code> | Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null` |
|
||||
|
||||
**Example**
|
||||
Order a certificate using auto mode
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
});
|
||||
|
||||
const certificate = await client.auto({
|
||||
csr: certificateRequest,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
|
||||
// Satisfy challenge here
|
||||
},
|
||||
challengeRemoveFn: async (authz, challenge, keyAuthorization) => {
|
||||
// Clean up challenge here
|
||||
}
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Order a certificate using auto mode with preferred chain
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
});
|
||||
|
||||
const certificate = await client.auto({
|
||||
csr: certificateRequest,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
preferredChain: 'DST Root CA X3',
|
||||
challengeCreateFn: async () => {},
|
||||
challengeRemoveFn: async () => {}
|
||||
});
|
||||
```
|
||||
<a name="Client"></a>
|
||||
|
||||
## Client : <code>object</code>
|
||||
ACME client
|
||||
|
||||
**Kind**: global namespace
|
||||
267
packages/core/acme-client/docs/crypto.md
Normal file
267
packages/core/acme-client/docs/crypto.md
Normal file
@@ -0,0 +1,267 @@
|
||||
## Objects
|
||||
|
||||
<dl>
|
||||
<dt><a href="#crypto">crypto</a> : <code>object</code></dt>
|
||||
<dd><p>Native Node.js crypto interface</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
## Functions
|
||||
|
||||
<dl>
|
||||
<dt><a href="#createPrivateRsaKey">createPrivateRsaKey([modulusLength])</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Generate a private RSA key</p>
|
||||
</dd>
|
||||
<dt><a href="#createPrivateKey">createPrivateKey()</a></dt>
|
||||
<dd><p>Alias of <code>createPrivateRsaKey()</code></p>
|
||||
</dd>
|
||||
<dt><a href="#createPrivateEcdsaKey">createPrivateEcdsaKey([namedCurve])</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Generate a private ECDSA key</p>
|
||||
</dd>
|
||||
<dt><a href="#getPublicKey">getPublicKey(keyPem)</a> ⇒ <code>buffer</code></dt>
|
||||
<dd><p>Get a public key derived from a RSA or ECDSA key</p>
|
||||
</dd>
|
||||
<dt><a href="#getJwk">getJwk(keyPem)</a> ⇒ <code>object</code></dt>
|
||||
<dd><p>Get a JSON Web Key derived from a RSA or ECDSA key</p>
|
||||
<p><a href="https://datatracker.ietf.org/doc/html/rfc7517">https://datatracker.ietf.org/doc/html/rfc7517</a></p>
|
||||
</dd>
|
||||
<dt><a href="#splitPemChain">splitPemChain(chainPem)</a> ⇒ <code>array</code></dt>
|
||||
<dd><p>Split chain of PEM encoded objects from string into array</p>
|
||||
</dd>
|
||||
<dt><a href="#getPemBodyAsB64u">getPemBodyAsB64u(pem)</a> ⇒ <code>string</code></dt>
|
||||
<dd><p>Parse body of PEM encoded object and return a Base64URL string
|
||||
If multiple objects are chained, the first body will be returned</p>
|
||||
</dd>
|
||||
<dt><a href="#readCsrDomains">readCsrDomains(csrPem)</a> ⇒ <code>object</code></dt>
|
||||
<dd><p>Read domains from a Certificate Signing Request</p>
|
||||
</dd>
|
||||
<dt><a href="#readCertificateInfo">readCertificateInfo(certPem)</a> ⇒ <code>object</code></dt>
|
||||
<dd><p>Read information from a certificate
|
||||
If multiple certificates are chained, the first will be read</p>
|
||||
</dd>
|
||||
<dt><a href="#createCsr">createCsr(data, [keyPem])</a> ⇒ <code>Promise.<Array.<buffer>></code></dt>
|
||||
<dd><p>Create a Certificate Signing Request</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<a name="crypto"></a>
|
||||
|
||||
## crypto : <code>object</code>
|
||||
Native Node.js crypto interface
|
||||
|
||||
**Kind**: global namespace
|
||||
<a name="createPrivateRsaKey"></a>
|
||||
|
||||
## createPrivateRsaKey([modulusLength]) ⇒ <code>Promise.<buffer></code>
|
||||
Generate a private RSA key
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - PEM encoded private RSA key
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [modulusLength] | <code>number</code> | <code>2048</code> | Size of the keys modulus in bits, default: `2048` |
|
||||
|
||||
**Example**
|
||||
Generate private RSA key
|
||||
```js
|
||||
const privateKey = await acme.crypto.createPrivateRsaKey();
|
||||
```
|
||||
**Example**
|
||||
Private RSA key with modulus size 4096
|
||||
```js
|
||||
const privateKey = await acme.crypto.createPrivateRsaKey(4096);
|
||||
```
|
||||
<a name="createPrivateKey"></a>
|
||||
|
||||
## createPrivateKey()
|
||||
Alias of `createPrivateRsaKey()`
|
||||
|
||||
**Kind**: global function
|
||||
<a name="createPrivateEcdsaKey"></a>
|
||||
|
||||
## createPrivateEcdsaKey([namedCurve]) ⇒ <code>Promise.<buffer></code>
|
||||
Generate a private ECDSA key
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - PEM encoded private ECDSA key
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [namedCurve] | <code>string</code> | ECDSA curve name (P-256, P-384 or P-521), default `P-256` |
|
||||
|
||||
**Example**
|
||||
Generate private ECDSA key
|
||||
```js
|
||||
const privateKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
```
|
||||
**Example**
|
||||
Private ECDSA key using P-384 curve
|
||||
```js
|
||||
const privateKey = await acme.crypto.createPrivateEcdsaKey('P-384');
|
||||
```
|
||||
<a name="getPublicKey"></a>
|
||||
|
||||
## getPublicKey(keyPem) ⇒ <code>buffer</code>
|
||||
Get a public key derived from a RSA or ECDSA key
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>buffer</code> - PEM encoded public key
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| keyPem | <code>buffer</code> \| <code>string</code> | PEM encoded private or public key |
|
||||
|
||||
**Example**
|
||||
Get public key
|
||||
```js
|
||||
const publicKey = acme.crypto.getPublicKey(privateKey);
|
||||
```
|
||||
<a name="getJwk"></a>
|
||||
|
||||
## getJwk(keyPem) ⇒ <code>object</code>
|
||||
Get a JSON Web Key derived from a RSA or ECDSA key
|
||||
|
||||
https://datatracker.ietf.org/doc/html/rfc7517
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>object</code> - JSON Web Key
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| keyPem | <code>buffer</code> \| <code>string</code> | PEM encoded private or public key |
|
||||
|
||||
**Example**
|
||||
Get JWK
|
||||
```js
|
||||
const jwk = acme.crypto.getJwk(privateKey);
|
||||
```
|
||||
<a name="splitPemChain"></a>
|
||||
|
||||
## splitPemChain(chainPem) ⇒ <code>array</code>
|
||||
Split chain of PEM encoded objects from string into array
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>array</code> - Array of PEM objects including headers
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| chainPem | <code>buffer</code> \| <code>string</code> | PEM encoded object chain |
|
||||
|
||||
<a name="getPemBodyAsB64u"></a>
|
||||
|
||||
## getPemBodyAsB64u(pem) ⇒ <code>string</code>
|
||||
Parse body of PEM encoded object and return a Base64URL string
|
||||
If multiple objects are chained, the first body will be returned
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>string</code> - Base64URL-encoded body
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| pem | <code>buffer</code> \| <code>string</code> | PEM encoded chain or object |
|
||||
|
||||
<a name="readCsrDomains"></a>
|
||||
|
||||
## readCsrDomains(csrPem) ⇒ <code>object</code>
|
||||
Read domains from a Certificate Signing Request
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>object</code> - {commonName, altNames}
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| csrPem | <code>buffer</code> \| <code>string</code> | PEM encoded Certificate Signing Request |
|
||||
|
||||
**Example**
|
||||
Read Certificate Signing Request domains
|
||||
```js
|
||||
const { commonName, altNames } = acme.crypto.readCsrDomains(certificateRequest);
|
||||
|
||||
console.log(`Common name: ${commonName}`);
|
||||
console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
```
|
||||
<a name="readCertificateInfo"></a>
|
||||
|
||||
## readCertificateInfo(certPem) ⇒ <code>object</code>
|
||||
Read information from a certificate
|
||||
If multiple certificates are chained, the first will be read
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>object</code> - Certificate info
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| certPem | <code>buffer</code> \| <code>string</code> | PEM encoded certificate or chain |
|
||||
|
||||
**Example**
|
||||
Read certificate information
|
||||
```js
|
||||
const info = acme.crypto.readCertificateInfo(certificate);
|
||||
const { commonName, altNames } = info.domains;
|
||||
|
||||
console.log(`Not after: ${info.notAfter}`);
|
||||
console.log(`Not before: ${info.notBefore}`);
|
||||
|
||||
console.log(`Common name: ${commonName}`);
|
||||
console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
```
|
||||
<a name="createCsr"></a>
|
||||
|
||||
## createCsr(data, [keyPem]) ⇒ <code>Promise.<Array.<buffer>></code>
|
||||
Create a Certificate Signing Request
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<Array.<buffer>></code> - [privateKey, certificateSigningRequest]
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>object</code> | |
|
||||
| [data.keySize] | <code>number</code> | Size of newly created RSA private key modulus in bits, default: `2048` |
|
||||
| [data.commonName] | <code>string</code> | FQDN of your server |
|
||||
| [data.altNames] | <code>array</code> | SAN (Subject Alternative Names), default: `[]` |
|
||||
| [data.country] | <code>string</code> | 2 letter country code |
|
||||
| [data.state] | <code>string</code> | State or province |
|
||||
| [data.locality] | <code>string</code> | City |
|
||||
| [data.organization] | <code>string</code> | Organization name |
|
||||
| [data.organizationUnit] | <code>string</code> | Organizational unit name |
|
||||
| [data.emailAddress] | <code>string</code> | Email address |
|
||||
| [keyPem] | <code>string</code> | PEM encoded CSR private key |
|
||||
|
||||
**Example**
|
||||
Create a Certificate Signing Request
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with both common and alternative names
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
keySize: 4096,
|
||||
commonName: 'test.example.com',
|
||||
altNames: ['foo.example.com', 'bar.example.com']
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with additional information
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
commonName: 'test.example.com',
|
||||
country: 'US',
|
||||
state: 'California',
|
||||
locality: 'Los Angeles',
|
||||
organization: 'The Company Inc.',
|
||||
organizationUnit: 'IT Department',
|
||||
emailAddress: 'contact@example.com'
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with ECDSA private key
|
||||
```js
|
||||
const certificateKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
|
||||
const [, certificateRequest] = await acme.crypto.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
}, certificateKey);
|
||||
257
packages/core/acme-client/docs/forge.md
Normal file
257
packages/core/acme-client/docs/forge.md
Normal file
@@ -0,0 +1,257 @@
|
||||
## Objects
|
||||
|
||||
<dl>
|
||||
<dt><a href="#forge">forge</a> : <code>object</code></dt>
|
||||
<dd><p>Legacy node-forge crypto interface</p>
|
||||
<p>DEPRECATION WARNING: This crypto interface is deprecated and will be removed from acme-client in a future
|
||||
major release. Please migrate to the new <code>acme.crypto</code> interface at your earliest convenience.</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
## Functions
|
||||
|
||||
<dl>
|
||||
<dt><a href="#createPrivateKey">createPrivateKey([size])</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Generate a private RSA key</p>
|
||||
</dd>
|
||||
<dt><a href="#createPublicKey">createPublicKey(key)</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Create public key from a private RSA key</p>
|
||||
</dd>
|
||||
<dt><a href="#getPemBody">getPemBody(str)</a> ⇒ <code>string</code></dt>
|
||||
<dd><p>Parse body of PEM encoded object from buffer or string
|
||||
If multiple objects are chained, the first body will be returned</p>
|
||||
</dd>
|
||||
<dt><a href="#splitPemChain">splitPemChain(str)</a> ⇒ <code>Array.<string></code></dt>
|
||||
<dd><p>Split chain of PEM encoded objects from buffer or string into array</p>
|
||||
</dd>
|
||||
<dt><a href="#getModulus">getModulus(input)</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Get modulus</p>
|
||||
</dd>
|
||||
<dt><a href="#getPublicExponent">getPublicExponent(input)</a> ⇒ <code>Promise.<buffer></code></dt>
|
||||
<dd><p>Get public exponent</p>
|
||||
</dd>
|
||||
<dt><a href="#readCsrDomains">readCsrDomains(csr)</a> ⇒ <code>Promise.<object></code></dt>
|
||||
<dd><p>Read domains from a Certificate Signing Request</p>
|
||||
</dd>
|
||||
<dt><a href="#readCertificateInfo">readCertificateInfo(cert)</a> ⇒ <code>Promise.<object></code></dt>
|
||||
<dd><p>Read information from a certificate</p>
|
||||
</dd>
|
||||
<dt><a href="#createCsr">createCsr(data, [key])</a> ⇒ <code>Promise.<Array.<buffer>></code></dt>
|
||||
<dd><p>Create a Certificate Signing Request</p>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<a name="forge"></a>
|
||||
|
||||
## forge : <code>object</code>
|
||||
Legacy node-forge crypto interface
|
||||
|
||||
DEPRECATION WARNING: This crypto interface is deprecated and will be removed from acme-client in a future
|
||||
major release. Please migrate to the new `acme.crypto` interface at your earliest convenience.
|
||||
|
||||
**Kind**: global namespace
|
||||
<a name="createPrivateKey"></a>
|
||||
|
||||
## createPrivateKey([size]) ⇒ <code>Promise.<buffer></code>
|
||||
Generate a private RSA key
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - PEM encoded private RSA key
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [size] | <code>number</code> | <code>2048</code> | Size of the key, default: `2048` |
|
||||
|
||||
**Example**
|
||||
Generate private RSA key
|
||||
```js
|
||||
const privateKey = await acme.forge.createPrivateKey();
|
||||
```
|
||||
**Example**
|
||||
Private RSA key with defined size
|
||||
```js
|
||||
const privateKey = await acme.forge.createPrivateKey(4096);
|
||||
```
|
||||
<a name="createPublicKey"></a>
|
||||
|
||||
## createPublicKey(key) ⇒ <code>Promise.<buffer></code>
|
||||
Create public key from a private RSA key
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - PEM encoded public RSA key
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| key | <code>buffer</code> \| <code>string</code> | PEM encoded private RSA key |
|
||||
|
||||
**Example**
|
||||
Create public key
|
||||
```js
|
||||
const publicKey = await acme.forge.createPublicKey(privateKey);
|
||||
```
|
||||
<a name="getPemBody"></a>
|
||||
|
||||
## getPemBody(str) ⇒ <code>string</code>
|
||||
Parse body of PEM encoded object from buffer or string
|
||||
If multiple objects are chained, the first body will be returned
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>string</code> - PEM body
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| str | <code>buffer</code> \| <code>string</code> | PEM encoded buffer or string |
|
||||
|
||||
<a name="splitPemChain"></a>
|
||||
|
||||
## splitPemChain(str) ⇒ <code>Array.<string></code>
|
||||
Split chain of PEM encoded objects from buffer or string into array
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Array.<string></code> - Array of PEM bodies
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| str | <code>buffer</code> \| <code>string</code> | PEM encoded buffer or string |
|
||||
|
||||
<a name="getModulus"></a>
|
||||
|
||||
## getModulus(input) ⇒ <code>Promise.<buffer></code>
|
||||
Get modulus
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - Modulus
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| input | <code>buffer</code> \| <code>string</code> | PEM encoded private key, certificate or CSR |
|
||||
|
||||
**Example**
|
||||
Get modulus
|
||||
```js
|
||||
const m1 = await acme.forge.getModulus(privateKey);
|
||||
const m2 = await acme.forge.getModulus(certificate);
|
||||
const m3 = await acme.forge.getModulus(certificateRequest);
|
||||
```
|
||||
<a name="getPublicExponent"></a>
|
||||
|
||||
## getPublicExponent(input) ⇒ <code>Promise.<buffer></code>
|
||||
Get public exponent
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<buffer></code> - Exponent
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| input | <code>buffer</code> \| <code>string</code> | PEM encoded private key, certificate or CSR |
|
||||
|
||||
**Example**
|
||||
Get public exponent
|
||||
```js
|
||||
const e1 = await acme.forge.getPublicExponent(privateKey);
|
||||
const e2 = await acme.forge.getPublicExponent(certificate);
|
||||
const e3 = await acme.forge.getPublicExponent(certificateRequest);
|
||||
```
|
||||
<a name="readCsrDomains"></a>
|
||||
|
||||
## readCsrDomains(csr) ⇒ <code>Promise.<object></code>
|
||||
Read domains from a Certificate Signing Request
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<object></code> - {commonName, altNames}
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| csr | <code>buffer</code> \| <code>string</code> | PEM encoded Certificate Signing Request |
|
||||
|
||||
**Example**
|
||||
Read Certificate Signing Request domains
|
||||
```js
|
||||
const { commonName, altNames } = await acme.forge.readCsrDomains(certificateRequest);
|
||||
|
||||
console.log(`Common name: ${commonName}`);
|
||||
console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
```
|
||||
<a name="readCertificateInfo"></a>
|
||||
|
||||
## readCertificateInfo(cert) ⇒ <code>Promise.<object></code>
|
||||
Read information from a certificate
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<object></code> - Certificate info
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| cert | <code>buffer</code> \| <code>string</code> | PEM encoded certificate |
|
||||
|
||||
**Example**
|
||||
Read certificate information
|
||||
```js
|
||||
const info = await acme.forge.readCertificateInfo(certificate);
|
||||
const { commonName, altNames } = info.domains;
|
||||
|
||||
console.log(`Not after: ${info.notAfter}`);
|
||||
console.log(`Not before: ${info.notBefore}`);
|
||||
|
||||
console.log(`Common name: ${commonName}`);
|
||||
console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
```
|
||||
<a name="createCsr"></a>
|
||||
|
||||
## createCsr(data, [key]) ⇒ <code>Promise.<Array.<buffer>></code>
|
||||
Create a Certificate Signing Request
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<Array.<buffer>></code> - [privateKey, certificateSigningRequest]
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>object</code> | |
|
||||
| [data.keySize] | <code>number</code> | Size of newly created private key, default: `2048` |
|
||||
| [data.commonName] | <code>string</code> | |
|
||||
| [data.altNames] | <code>array</code> | default: `[]` |
|
||||
| [data.country] | <code>string</code> | |
|
||||
| [data.state] | <code>string</code> | |
|
||||
| [data.locality] | <code>string</code> | |
|
||||
| [data.organization] | <code>string</code> | |
|
||||
| [data.organizationUnit] | <code>string</code> | |
|
||||
| [data.emailAddress] | <code>string</code> | |
|
||||
| [key] | <code>buffer</code> \| <code>string</code> | CSR private key |
|
||||
|
||||
**Example**
|
||||
Create a Certificate Signing Request
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with both common and alternative names
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
keySize: 4096,
|
||||
commonName: 'test.example.com',
|
||||
altNames: ['foo.example.com', 'bar.example.com']
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with additional information
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
commonName: 'test.example.com',
|
||||
country: 'US',
|
||||
state: 'California',
|
||||
locality: 'Los Angeles',
|
||||
organization: 'The Company Inc.',
|
||||
organizationUnit: 'IT Department',
|
||||
emailAddress: 'contact@example.com'
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with predefined private key
|
||||
```js
|
||||
const certificateKey = await acme.forge.createPrivateKey();
|
||||
|
||||
const [, certificateRequest] = await acme.forge.createCsr({
|
||||
commonName: 'test.example.com'
|
||||
}, certificateKey);
|
||||
98
packages/core/acme-client/docs/upgrade-v5.md
Normal file
98
packages/core/acme-client/docs/upgrade-v5.md
Normal file
@@ -0,0 +1,98 @@
|
||||
# Upgrading to v5 of `acme-client`
|
||||
|
||||
This document outlines the breaking changes introduced in v5 of `acme-client`, why they were introduced and what you should look out for when upgrading your application.
|
||||
|
||||
First off this release drops support for Node LTS v10, v12 and v14, and the reason for that is a new native crypto interface - more on that below. Since Node v14 is still currently in maintenance mode, `acme-client` v4 will continue to receive security updates and bugfixes until (at least) Node v14 reaches its end-of-line.
|
||||
|
||||
|
||||
## New native crypto interface
|
||||
|
||||
A new crypto interface has been introduced with v5, which you can find under `acme.crypto`. It uses native Node.js cryptography APIs to generate private keys, JSON Web Keys and signatures, and finally enables support for ECC/ECDSA (P-256, P384 and P521), both for account private keys and certificates. The [jsrsasign](https://www.npmjs.com/package/jsrsasign) module is used to handle generation and parsing of Certificate Signing Requests.
|
||||
|
||||
Full documentation of `acme.crypto` can be [found here](crypto.md).
|
||||
|
||||
Since the release of `acme-client` v1.0.0 the crypto interface API has remained mostly unaltered. Back then an OpenSSL CLI wrapper was used to generate keys, and very much has changed since. This has naturally resulted in a buildup of technical debt and slight API inconsistencies over time. The introduction of a new interface was a good opportunity to finally clean up these APIs.
|
||||
|
||||
Below you will find a table summarizing the current `acme.forge` methods, and their new `acme.crypto` replacements. A summary of the changes for each method, including examples on how to migrate, can be found following the table.
|
||||
|
||||
*Note: The now deprecated `acme.forge` interface is still available for use in v5, and will not be removed until a future major version, most likely v6. Should you not wish to change to the new interface right away, the following breaking changes will not immediately affect you.*
|
||||
|
||||
- :green_circle: = API functionality unchanged between `acme.forge` and `acme.crypto`
|
||||
- :orange_circle: = Slight API changes, like depromising or renaming, action may be required
|
||||
- :red_circle: = Breaking API changes or removal, action required if using these methods
|
||||
|
||||
| Deprecated `.forge` API | New `.crypto` API | State |
|
||||
| ----------------------------- | ----------------------------- | --------------------- |
|
||||
| `await createPrivateKey()` | `await createPrivateKey()` | :green_circle: |
|
||||
| `await createPublicKey()` | `getPublicKey()` | :orange_circle: (1) |
|
||||
| `getPemBody()` | `getPemBodyAsB64u()` | :red_circle: (2) |
|
||||
| `splitPemChain()` | `splitPemChain()` | :green_circle: |
|
||||
| `await getModulus()` | `getJwk()` | :red_circle: (3) |
|
||||
| `await getPublicExponent()` | `getJwk()` | :red_circle: (3) |
|
||||
| `await readCsrDomains()` | `readCsrDomains()` | :orange_circle: (4) |
|
||||
| `await readCertificateInfo()` | `readCertificateInfo()` | :orange_circle: (4) |
|
||||
| `await createCsr()` | `await createCsr()` | :green_circle: |
|
||||
|
||||
|
||||
### 1. `createPublicKey` renamed and depromised
|
||||
|
||||
* The method `createPublicKey()` has been renamed to `getPublicKey()`
|
||||
* No longer returns a promise, but the resulting public key directly
|
||||
* This is non-breaking if called with `await`, since `await` does not require its operand to be a promise
|
||||
* :orange_circle: **This is a breaking change if used with `.then()` or `.catch()`**
|
||||
|
||||
```js
|
||||
// Before
|
||||
const publicKey = await acme.forge.createPublicKey(privateKey);
|
||||
|
||||
// After
|
||||
const publicKey = acme.crypto.getPublicKey(privateKey);
|
||||
```
|
||||
|
||||
|
||||
### 2. `getPemBody` renamed, now returns Base64URL
|
||||
|
||||
* Method `getPemBody()` has been renamed to `getPemBodyAsB64u()`
|
||||
* Instead of a Base64-encoded PEM body, now returns a Base64URL-encoded PEM body
|
||||
* :red_circle: **This is a breaking change**
|
||||
|
||||
```js
|
||||
// Before
|
||||
const body = acme.forge.getPemBody(pem);
|
||||
|
||||
// After
|
||||
const body = acme.crypto.getPemBodyAsB64u(pem);
|
||||
```
|
||||
|
||||
|
||||
### 3. `getModulus` and `getPublicExponent` merged into `getJwk`
|
||||
|
||||
* Methods `getModulus()` and `getPublicExponent()` have been removed
|
||||
* Replaced by new method `getJwk()`
|
||||
* :red_circle: **This is a breaking change**
|
||||
|
||||
```js
|
||||
// Before
|
||||
const mod = await acme.forge.getModulus(key);
|
||||
const exp = await acme.forge.getPublicExponent(key);
|
||||
|
||||
// After
|
||||
const { e, n } = acme.crypto.getJwk(key);
|
||||
```
|
||||
|
||||
|
||||
### 4. `readCsrDomains` and `readCertificateInfo` depromised
|
||||
|
||||
* Methods `readCsrDomains()` and `readCertificateInfo()` no longer return promises, but their resulting payloads directly
|
||||
* This is non-breaking if called with `await`, since `await` does not require its operand to be a promise
|
||||
* :orange_circle: **This is a breaking change if used with `.then()` or `.catch()`**
|
||||
|
||||
```js
|
||||
// Before
|
||||
const domains = await acme.forge.readCsrDomains(csr);
|
||||
const info = await acme.forge.readCertificateInfo(certificate);
|
||||
|
||||
// After
|
||||
const domains = acme.crypto.readCsrDomains(csr);
|
||||
const info = acme.crypto.readCertificateInfo(certificate);
|
||||
```
|
||||
153
packages/core/acme-client/examples/api.js
Normal file
153
packages/core/acme-client/examples/api.js
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Example of acme.Client API
|
||||
*/
|
||||
|
||||
const acme = require('./../');
|
||||
|
||||
|
||||
function log(m) {
|
||||
process.stdout.write(`${m}\n`);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Function used to satisfy an ACME challenge
|
||||
*
|
||||
* @param {object} authz Authorization object
|
||||
* @param {object} challenge Selected challenge
|
||||
* @param {string} keyAuthorization Authorization key
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async function challengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
/* Do something here */
|
||||
log(JSON.stringify(authz));
|
||||
log(JSON.stringify(challenge));
|
||||
log(keyAuthorization);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Function used to remove an ACME challenge response
|
||||
*
|
||||
* @param {object} authz Authorization object
|
||||
* @param {object} challenge Selected challenge
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
|
||||
/* Do something here */
|
||||
log(JSON.stringify(authz));
|
||||
log(JSON.stringify(challenge));
|
||||
log(keyAuthorization);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
module.exports = async function() {
|
||||
/* Init client */
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: await acme.crypto.createPrivateKey()
|
||||
});
|
||||
|
||||
/* Register account */
|
||||
await client.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: ['mailto:test@example.com']
|
||||
});
|
||||
|
||||
/* Place new order */
|
||||
const order = await client.createOrder({
|
||||
identifiers: [
|
||||
{ type: 'dns', value: 'example.com' },
|
||||
{ type: 'dns', value: '*.example.com' }
|
||||
]
|
||||
});
|
||||
|
||||
/**
|
||||
* authorizations / client.getAuthorizations(order);
|
||||
* An array with one item per DNS name in the certificate order.
|
||||
* All items require at least one satisfied challenge before order can be completed.
|
||||
*/
|
||||
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
|
||||
const promises = authorizations.map(async (authz) => {
|
||||
let challengeCompleted = false;
|
||||
|
||||
try {
|
||||
/**
|
||||
* challenges / authz.challenges
|
||||
* An array of all available challenge types for a single DNS name.
|
||||
* One of these challenges needs to be satisfied.
|
||||
*/
|
||||
|
||||
const { challenges } = authz;
|
||||
|
||||
/* Just select any challenge */
|
||||
const challenge = challenges.pop();
|
||||
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
||||
|
||||
try {
|
||||
/* Satisfy challenge */
|
||||
await challengeCreateFn(authz, challenge, keyAuthorization);
|
||||
|
||||
/* Verify that challenge is satisfied */
|
||||
await client.verifyChallenge(authz, challenge);
|
||||
|
||||
/* Notify ACME provider that challenge is satisfied */
|
||||
await client.completeChallenge(challenge);
|
||||
challengeCompleted = true;
|
||||
|
||||
/* Wait for ACME provider to respond with valid status */
|
||||
await client.waitForValidStatus(challenge);
|
||||
}
|
||||
finally {
|
||||
/* Clean up challenge response */
|
||||
try {
|
||||
await challengeRemoveFn(authz, challenge, keyAuthorization);
|
||||
}
|
||||
catch (e) {
|
||||
/**
|
||||
* Catch errors thrown by challengeRemoveFn() so the order can
|
||||
* be finalized, even though something went wrong during cleanup
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
/* Deactivate pending authz when unable to complete challenge */
|
||||
if (!challengeCompleted) {
|
||||
try {
|
||||
await client.deactivateAuthorization(authz);
|
||||
}
|
||||
catch (f) {
|
||||
/* Catch and suppress deactivateAuthorization() errors */
|
||||
}
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
/* Wait for challenges to complete */
|
||||
await Promise.all(promises);
|
||||
|
||||
/* Finalize order */
|
||||
const [key, csr] = await acme.crypto.createCsr({
|
||||
commonName: '*.example.com',
|
||||
altNames: ['example.com']
|
||||
});
|
||||
|
||||
const finalized = await client.finalizeOrder(order, csr);
|
||||
const cert = await client.getCertificate(finalized);
|
||||
|
||||
/* Done */
|
||||
log(`CSR:\n${csr.toString()}`);
|
||||
log(`Private key:\n${key.toString()}`);
|
||||
log(`Certificate:\n${cert.toString()}`);
|
||||
};
|
||||
118
packages/core/acme-client/examples/auto.js
Normal file
118
packages/core/acme-client/examples/auto.js
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Example of acme.Client.auto()
|
||||
*/
|
||||
|
||||
// const fs = require('fs').promises;
|
||||
const acme = require('./../');
|
||||
|
||||
|
||||
function log(m) {
|
||||
process.stdout.write(`${m}\n`);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Function used to satisfy an ACME challenge
|
||||
*
|
||||
* @param {object} authz Authorization object
|
||||
* @param {object} challenge Selected challenge
|
||||
* @param {string} keyAuthorization Authorization key
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async function challengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
log('Triggered challengeCreateFn()');
|
||||
|
||||
/* http-01 */
|
||||
if (challenge.type === 'http-01') {
|
||||
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`;
|
||||
const fileContents = keyAuthorization;
|
||||
|
||||
log(`Creating challenge response for ${authz.identifier.value} at path: ${filePath}`);
|
||||
|
||||
/* Replace this */
|
||||
log(`Would write "${fileContents}" to path "${filePath}"`);
|
||||
// await fs.writeFile(filePath, fileContents);
|
||||
}
|
||||
|
||||
/* dns-01 */
|
||||
else if (challenge.type === 'dns-01') {
|
||||
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
|
||||
const recordValue = keyAuthorization;
|
||||
|
||||
log(`Creating TXT record for ${authz.identifier.value}: ${dnsRecord}`);
|
||||
|
||||
/* Replace this */
|
||||
log(`Would create TXT record "${dnsRecord}" with value "${recordValue}"`);
|
||||
// await dnsProvider.createRecord(dnsRecord, 'TXT', recordValue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Function used to remove an ACME challenge response
|
||||
*
|
||||
* @param {object} authz Authorization object
|
||||
* @param {object} challenge Selected challenge
|
||||
* @param {string} keyAuthorization Authorization key
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
|
||||
log('Triggered challengeRemoveFn()');
|
||||
|
||||
/* http-01 */
|
||||
if (challenge.type === 'http-01') {
|
||||
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`;
|
||||
|
||||
log(`Removing challenge response for ${authz.identifier.value} at path: ${filePath}`);
|
||||
|
||||
/* Replace this */
|
||||
log(`Would remove file on path "${filePath}"`);
|
||||
// await fs.unlink(filePath);
|
||||
}
|
||||
|
||||
/* dns-01 */
|
||||
else if (challenge.type === 'dns-01') {
|
||||
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
|
||||
const recordValue = keyAuthorization;
|
||||
|
||||
log(`Removing TXT record for ${authz.identifier.value}: ${dnsRecord}`);
|
||||
|
||||
/* Replace this */
|
||||
log(`Would remove TXT record "${dnsRecord}" with value "${recordValue}"`);
|
||||
// await dnsProvider.removeRecord(dnsRecord, 'TXT');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
module.exports = async function() {
|
||||
/* Init client */
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: await acme.crypto.createPrivateKey()
|
||||
});
|
||||
|
||||
/* Create CSR */
|
||||
const [key, csr] = await acme.crypto.createCsr({
|
||||
commonName: 'example.com'
|
||||
});
|
||||
|
||||
/* Certificate */
|
||||
const cert = await client.auto({
|
||||
csr,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn,
|
||||
challengeRemoveFn
|
||||
});
|
||||
|
||||
/* Done */
|
||||
log(`CSR:\n${csr.toString()}`);
|
||||
log(`Private key:\n${key.toString()}`);
|
||||
log(`Certificate:\n${cert.toString()}`);
|
||||
};
|
||||
62
packages/core/acme-client/package.json
Normal file
62
packages/core/acme-client/package.json
Normal file
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "@certd/acme-client",
|
||||
"description": "Simple and unopinionated ACME client",
|
||||
"private": false,
|
||||
"author": "nmorsman",
|
||||
"version": "1.0.6",
|
||||
"main": "src/index.js",
|
||||
"types": "types",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/publishlab/node-acme-client",
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"types"
|
||||
],
|
||||
"dependencies": {
|
||||
"axios": "0.27.2",
|
||||
"debug": "^4.1.1",
|
||||
"jsrsasign": "^10.5.26",
|
||||
"node-forge": "^1.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.6.1",
|
||||
"chai": "^4.3.6",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"dtslint": "^4.2.1",
|
||||
"eslint": "^8.11.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-plugin-import": "^2.25.4",
|
||||
"jsdoc-to-markdown": "^7.1.1",
|
||||
"mocha": "^10.0.0",
|
||||
"nock": "^13.2.4",
|
||||
"typescript": "^4.8.4",
|
||||
"uuid": "^8.3.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build-docs": "jsdoc2md src/client.js > docs/client.md && jsdoc2md src/crypto/index.js > docs/crypto.md && jsdoc2md src/crypto/forge.js > docs/forge.md",
|
||||
"lint": "eslint .",
|
||||
"lint-types": "dtslint types",
|
||||
"prepublishOnly": "npm run build-docs",
|
||||
"test": "mocha -t 60000 \"test/setup.js\" \"test/**/*.spec.js\"",
|
||||
"test-local": "/bin/bash scripts/run-tests.sh"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/publishlab/node-acme-client"
|
||||
},
|
||||
"keywords": [
|
||||
"acme",
|
||||
"client",
|
||||
"lets",
|
||||
"encrypt",
|
||||
"acmev2",
|
||||
"boulder"
|
||||
],
|
||||
"bugs": {
|
||||
"url": "https://github.com/publishlab/node-acme-client/issues"
|
||||
},
|
||||
"gitHead": "5950e1cae7cf30ebfc5128c15c7d1b0d101cbbb8"
|
||||
}
|
||||
56
packages/core/acme-client/scripts/run-tests.sh
Normal file
56
packages/core/acme-client/scripts/run-tests.sh
Normal file
@@ -0,0 +1,56 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Run test suite locally using CircleCI CLI.
|
||||
#
|
||||
set -eu
|
||||
|
||||
JOBS=("$@")
|
||||
|
||||
CIRCLECI_CLI_URL="https://github.com/CircleCI-Public/circleci-cli/releases/download/v0.1.16947/circleci-cli_0.1.16947_linux_amd64.tar.gz"
|
||||
CIRCLECI_CLI_SHASUM="c6f9a3276445c69ae40439acfed07e2c53502216a96bfacc4556e1d862d1019a"
|
||||
CIRCLECI_CLI_PATH="/tmp/circleci-cli"
|
||||
CIRCLECI_CLI_BIN="${CIRCLECI_CLI_PATH}/circleci"
|
||||
|
||||
PROJECT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && cd .. && pwd )"
|
||||
CONFIG_PATH="${PROJECT_DIR}/.circleci/.temp.yml"
|
||||
|
||||
# Run all jobs by default
|
||||
if [[ ${#JOBS[@]} -eq 0 ]]; then
|
||||
JOBS=(
|
||||
"v16"
|
||||
"v18"
|
||||
"eab-v16"
|
||||
"eab-v18"
|
||||
)
|
||||
fi
|
||||
|
||||
# Download CircleCI CLI
|
||||
if [[ ! -f "${CIRCLECI_CLI_BIN}" ]]; then
|
||||
echo "[-] Downloading CircleCI cli"
|
||||
mkdir -p "${CIRCLECI_CLI_PATH}"
|
||||
wget -nv "${CIRCLECI_CLI_URL}" -O "${CIRCLECI_CLI_PATH}/circleci-cli.tar.gz"
|
||||
echo "${CIRCLECI_CLI_SHASUM} *${CIRCLECI_CLI_PATH}/circleci-cli.tar.gz" | sha256sum -c
|
||||
tar zxvf "${CIRCLECI_CLI_PATH}/circleci-cli.tar.gz" -C "${CIRCLECI_CLI_PATH}" --strip-components=1
|
||||
fi
|
||||
|
||||
# Skip CircleCI update checks
|
||||
export CIRCLECI_CLI_SKIP_UPDATE_CHECK="true"
|
||||
|
||||
# Run test suite
|
||||
echo "[-] Running test suite"
|
||||
$CIRCLECI_CLI_BIN config process "${PROJECT_DIR}/.circleci/config.yml" > "${CONFIG_PATH}"
|
||||
$CIRCLECI_CLI_BIN config validate -c "${CONFIG_PATH}"
|
||||
|
||||
for job in "${JOBS[@]}"; do
|
||||
echo "[-] Running job: ${job}"
|
||||
$CIRCLECI_CLI_BIN local execute -c "${CONFIG_PATH}" --job "${job}" --skip-checkout
|
||||
echo "[+] ${job} completed successfully"
|
||||
done
|
||||
|
||||
# Clean up
|
||||
if [[ -f "${CONFIG_PATH}" ]]; then
|
||||
rm "${CONFIG_PATH}"
|
||||
fi
|
||||
|
||||
echo "[+] Test suite ran successfully!"
|
||||
exit 0
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install CoreDNS for testing.
|
||||
#
|
||||
set -eu
|
||||
|
||||
# Download and install
|
||||
wget -nv "https://github.com/coredns/coredns/releases/download/v${COREDNS_VERSION}/coredns_${COREDNS_VERSION}_linux_amd64.tgz" -O /tmp/coredns.tgz
|
||||
|
||||
tar zxvf /tmp/coredns.tgz -C /usr/local/bin
|
||||
chown root:root /usr/local/bin/coredns
|
||||
chmod 0755 /usr/local/bin/coredns
|
||||
|
||||
mkdir -p /etc/coredns
|
||||
|
||||
# Zones
|
||||
tee /etc/coredns/db.example.com << EOF
|
||||
\$ORIGIN example.com.
|
||||
@ 3600 IN SOA ns.coredns.invalid. master.coredns.invalid. (
|
||||
2017042745 ; serial
|
||||
7200 ; refresh
|
||||
3600 ; retry
|
||||
1209600 ; expire
|
||||
3600 ; minimum
|
||||
)
|
||||
|
||||
3600 IN NS ns1.example.com.
|
||||
3600 IN NS ns2.example.com.
|
||||
|
||||
ns1 3600 IN A 127.0.0.1
|
||||
ns2 3600 IN A 127.0.0.1
|
||||
|
||||
@ 3600 IN A 127.0.0.1
|
||||
www 3600 IN CNAME example.com.
|
||||
EOF
|
||||
|
||||
# Config
|
||||
tee /etc/coredns/Corefile << EOF
|
||||
example.com {
|
||||
errors
|
||||
log
|
||||
file /etc/coredns/db.example.com
|
||||
}
|
||||
|
||||
test.example.com {
|
||||
errors
|
||||
log
|
||||
forward . 127.0.0.1:${PEBBLECTS_DNS_PORT}
|
||||
}
|
||||
|
||||
. {
|
||||
errors
|
||||
log
|
||||
forward . 8.8.8.8
|
||||
}
|
||||
EOF
|
||||
|
||||
exit 0
|
||||
13
packages/core/acme-client/scripts/test-suite-install-cts.sh
Normal file
13
packages/core/acme-client/scripts/test-suite-install-cts.sh
Normal file
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install Pebble Challenge Test Server for testing.
|
||||
#
|
||||
set -eu
|
||||
|
||||
# Download and install
|
||||
wget -nv "https://github.com/letsencrypt/pebble/releases/download/v${PEBBLECTS_VERSION}/pebble-challtestsrv_linux-amd64" -O /usr/local/bin/pebble-challtestsrv
|
||||
|
||||
chown root:root /usr/local/bin/pebble-challtestsrv
|
||||
chmod 0755 /usr/local/bin/pebble-challtestsrv
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install Pebble for testing.
|
||||
#
|
||||
set -eu
|
||||
|
||||
config_name="pebble-config.json"
|
||||
|
||||
# Use Pebble EAB config if enabled
|
||||
set +u
|
||||
if [[ ! -z $ACME_CAP_EAB_ENABLED ]] && [[ $ACME_CAP_EAB_ENABLED -eq 1 ]]; then
|
||||
config_name="pebble-config-external-account-bindings.json"
|
||||
fi
|
||||
set -u
|
||||
|
||||
# Download certs and config
|
||||
mkdir -p /etc/pebble
|
||||
|
||||
wget -nv "https://raw.githubusercontent.com/letsencrypt/pebble/v${PEBBLE_VERSION}/test/certs/pebble.minica.pem" -O /etc/pebble/ca.cert.pem
|
||||
wget -nv "https://raw.githubusercontent.com/letsencrypt/pebble/v${PEBBLE_VERSION}/test/certs/localhost/cert.pem" -O /etc/pebble/cert.pem
|
||||
wget -nv "https://raw.githubusercontent.com/letsencrypt/pebble/v${PEBBLE_VERSION}/test/certs/localhost/key.pem" -O /etc/pebble/key.pem
|
||||
wget -nv "https://raw.githubusercontent.com/letsencrypt/pebble/v${PEBBLE_VERSION}/test/config/${config_name}" -O /etc/pebble/pebble.json
|
||||
|
||||
# Download and install Pebble
|
||||
wget -nv "https://github.com/letsencrypt/pebble/releases/download/v${PEBBLE_VERSION}/pebble_linux-amd64" -O /usr/local/bin/pebble
|
||||
|
||||
chown root:root /usr/local/bin/pebble
|
||||
chmod 0755 /usr/local/bin/pebble
|
||||
|
||||
# Config
|
||||
sed -i 's/test\/certs\/localhost/\/etc\/pebble/' /etc/pebble/pebble.json
|
||||
|
||||
exit 0
|
||||
20
packages/core/acme-client/scripts/test-suite-install-step.sh
Normal file
20
packages/core/acme-client/scripts/test-suite-install-step.sh
Normal file
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install and init step-ca for testing.
|
||||
#
|
||||
set -eu
|
||||
|
||||
# Download and install
|
||||
wget -nv "https://dl.step.sm/gh-release/certificates/gh-release-header/v${STEPCA_VERSION}/step-ca_${STEPCA_VERSION}_amd64.deb" -O /tmp/step-ca.deb
|
||||
wget -nv "https://dl.step.sm/gh-release/cli/gh-release-header/v${STEPCLI_VERSION}/step-cli_${STEPCLI_VERSION}_amd64.deb" -O /tmp/step-cli.deb
|
||||
|
||||
sudo dpkg -i /tmp/step-ca.deb
|
||||
sudo dpkg -i /tmp/step-cli.deb
|
||||
|
||||
# Initialize
|
||||
echo "hunter2" > /tmp/password
|
||||
|
||||
step ca init --name="Example Inc." --dns="localhost" --address="127.0.0.1:8443" --provisioner="test@example.com" --password-file="/tmp/password"
|
||||
step ca provisioner add acme --type ACME
|
||||
|
||||
exit 0
|
||||
27
packages/core/acme-client/scripts/test-suite-wait-for-ca.sh
Normal file
27
packages/core/acme-client/scripts/test-suite-wait-for-ca.sh
Normal file
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Wait for ACME server to accept connections.
|
||||
#
|
||||
set -eu
|
||||
|
||||
MAX_ATTEMPTS=15
|
||||
ATTEMPT=0
|
||||
|
||||
# Loop until ready
|
||||
while ! $(curl --cacert "${ACME_CA_CERT_PATH}" -s -D - "${ACME_DIRECTORY_URL}" | grep '^HTTP.*200' > /dev/null 2>&1); do
|
||||
ATTEMPT=$((ATTEMPT + 1))
|
||||
|
||||
# Max attempts
|
||||
if [[ $ATTEMPT -gt $MAX_ATTEMPTS ]]; then
|
||||
echo "[!] Waited ${ATTEMPT} attempts for server to become ready, exit 1"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Retry
|
||||
echo "[-] Waiting 1 second for server to become ready, attempt: ${ATTEMPT}/${MAX_ATTEMPTS}, check: ${ACME_DIRECTORY_URL}, cert: ${ACME_CA_CERT_PATH}"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Ready
|
||||
echo "[+] Server ready!"
|
||||
exit 0
|
||||
250
packages/core/acme-client/src/api.js
Normal file
250
packages/core/acme-client/src/api.js
Normal file
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* ACME API client
|
||||
*/
|
||||
|
||||
const util = require('./util');
|
||||
|
||||
|
||||
/**
|
||||
* AcmeApi
|
||||
*
|
||||
* @class
|
||||
* @param {HttpClient} httpClient
|
||||
*/
|
||||
|
||||
class AcmeApi {
|
||||
constructor(httpClient, accountUrl = null) {
|
||||
this.http = httpClient;
|
||||
this.accountUrl = accountUrl;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get account URL
|
||||
*
|
||||
* @private
|
||||
* @returns {string} Account URL
|
||||
*/
|
||||
|
||||
getAccountUrl() {
|
||||
if (!this.accountUrl) {
|
||||
throw new Error('No account URL found, register account first');
|
||||
}
|
||||
|
||||
return this.accountUrl;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ACME API request
|
||||
*
|
||||
* @private
|
||||
* @param {string} url Request URL
|
||||
* @param {object} [payload] Request payload, default: `null`
|
||||
* @param {array} [validStatusCodes] Array of valid HTTP response status codes, default: `[]`
|
||||
* @param {object} [opts]
|
||||
* @param {boolean} [opts.includeJwsKid] Include KID instead of JWK in JWS header, default: `true`
|
||||
* @param {boolean} [opts.includeExternalAccountBinding] Include EAB in request, default: `false`
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
async apiRequest(url, payload = null, validStatusCodes = [], { includeJwsKid = true, includeExternalAccountBinding = false } = {}) {
|
||||
const kid = includeJwsKid ? this.getAccountUrl() : null;
|
||||
const resp = await this.http.signedRequest(url, payload, { kid, includeExternalAccountBinding });
|
||||
|
||||
if (validStatusCodes.length && (validStatusCodes.indexOf(resp.status) === -1)) {
|
||||
throw new Error(util.formatResponseError(resp));
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ACME API request by resource name helper
|
||||
*
|
||||
* @private
|
||||
* @param {string} resource Request resource name
|
||||
* @param {object} [payload] Request payload, default: `null`
|
||||
* @param {array} [validStatusCodes] Array of valid HTTP response status codes, default: `[]`
|
||||
* @param {object} [opts]
|
||||
* @param {boolean} [opts.includeJwsKid] Include KID instead of JWK in JWS header, default: `true`
|
||||
* @param {boolean} [opts.includeExternalAccountBinding] Include EAB in request, default: `false`
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
async apiResourceRequest(resource, payload = null, validStatusCodes = [], { includeJwsKid = true, includeExternalAccountBinding = false } = {}) {
|
||||
const resourceUrl = await this.http.getResourceUrl(resource);
|
||||
return this.apiRequest(resourceUrl, payload, validStatusCodes, { includeJwsKid, includeExternalAccountBinding });
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get Terms of Service URL if available
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.1.1
|
||||
*
|
||||
* @returns {Promise<string|null>} ToS URL
|
||||
*/
|
||||
|
||||
async getTermsOfServiceUrl() {
|
||||
return this.http.getMetaField('termsOfService');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create new account
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3
|
||||
*
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
async createAccount(data) {
|
||||
const resp = await this.apiResourceRequest('newAccount', data, [200, 201], {
|
||||
includeJwsKid: false,
|
||||
includeExternalAccountBinding: (data.onlyReturnExisting !== true)
|
||||
});
|
||||
|
||||
/* Set account URL */
|
||||
if (resp.headers.location) {
|
||||
this.accountUrl = resp.headers.location;
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update account
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3.2
|
||||
*
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
updateAccount(data) {
|
||||
return this.apiRequest(this.getAccountUrl(), data, [200, 202]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update account key
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3.5
|
||||
*
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
updateAccountKey(data) {
|
||||
return this.apiResourceRequest('keyChange', data, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create new order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
createOrder(data) {
|
||||
return this.apiResourceRequest('newOrder', data, [201]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {string} url Order URL
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
getOrder(url) {
|
||||
return this.apiRequest(url, null, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Finalize order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {string} url Finalization URL
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
finalizeOrder(url, data) {
|
||||
return this.apiRequest(url, data, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get identifier authorization
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5
|
||||
*
|
||||
* @param {string} url Authorization URL
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
getAuthorization(url) {
|
||||
return this.apiRequest(url, null, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update identifier authorization
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5.2
|
||||
*
|
||||
* @param {string} url Authorization URL
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
updateAuthorization(url, data) {
|
||||
return this.apiRequest(url, data, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Complete challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5.1
|
||||
*
|
||||
* @param {string} url Challenge URL
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
completeChallenge(url, data) {
|
||||
return this.apiRequest(url, data, [200]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Revoke certificate
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.6
|
||||
*
|
||||
* @param {object} data Request payload
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
revokeCert(data) {
|
||||
return this.apiResourceRequest('revokeCert', data, [200]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Export API */
|
||||
module.exports = AcmeApi;
|
||||
199
packages/core/acme-client/src/auto.js
Normal file
199
packages/core/acme-client/src/auto.js
Normal file
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* ACME auto helper
|
||||
*/
|
||||
|
||||
const { readCsrDomains } = require('./crypto');
|
||||
const { log } = require('./logger');
|
||||
|
||||
const defaultOpts = {
|
||||
csr: null,
|
||||
email: null,
|
||||
preferredChain: null,
|
||||
termsOfServiceAgreed: false,
|
||||
skipChallengeVerification: false,
|
||||
challengePriority: ['http-01', 'dns-01'],
|
||||
challengeCreateFn: async () => { throw new Error('Missing challengeCreateFn()'); },
|
||||
challengeRemoveFn: async () => { throw new Error('Missing challengeRemoveFn()'); }
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* ACME client auto mode
|
||||
*
|
||||
* @param {AcmeClient} client ACME client
|
||||
* @param {object} userOpts Options
|
||||
* @returns {Promise<buffer>} Certificate
|
||||
*/
|
||||
|
||||
module.exports = async function(client, userOpts) {
|
||||
const opts = Object.assign({}, defaultOpts, userOpts);
|
||||
const accountPayload = { termsOfServiceAgreed: opts.termsOfServiceAgreed };
|
||||
|
||||
if (!Buffer.isBuffer(opts.csr)) {
|
||||
opts.csr = Buffer.from(opts.csr);
|
||||
}
|
||||
|
||||
if (opts.email) {
|
||||
accountPayload.contact = [`mailto:${opts.email}`];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register account
|
||||
*/
|
||||
|
||||
log('[auto] Checking account');
|
||||
|
||||
try {
|
||||
client.getAccountUrl();
|
||||
log('[auto] Account URL already exists, skipping account registration');
|
||||
}
|
||||
catch (e) {
|
||||
log('[auto] Registering account');
|
||||
await client.createAccount(accountPayload);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse domains from CSR
|
||||
*/
|
||||
|
||||
log('[auto] Parsing domains from Certificate Signing Request');
|
||||
const csrDomains = readCsrDomains(opts.csr);
|
||||
const domains = [csrDomains.commonName].concat(csrDomains.altNames);
|
||||
const uniqueDomains = Array.from(new Set(domains));
|
||||
|
||||
log(`[auto] Resolved ${uniqueDomains.length} unique domains from parsing the Certificate Signing Request`);
|
||||
|
||||
|
||||
/**
|
||||
* Place order
|
||||
*/
|
||||
|
||||
log('[auto] Placing new certificate order with ACME provider');
|
||||
const orderPayload = { identifiers: uniqueDomains.map((d) => ({ type: 'dns', value: d })) };
|
||||
const order = await client.createOrder(orderPayload);
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
|
||||
log(`[auto] Placed certificate order successfully, received ${authorizations.length} identity authorizations`);
|
||||
|
||||
|
||||
/**
|
||||
* Resolve and satisfy challenges
|
||||
*/
|
||||
|
||||
log('[auto] Resolving and satisfying authorization challenges');
|
||||
|
||||
const challengeFunc = async (authz) => {
|
||||
const d = authz.identifier.value;
|
||||
let challengeCompleted = false;
|
||||
|
||||
/* Skip authz that already has valid status */
|
||||
if (authz.status === 'valid') {
|
||||
log(`[auto] [${d}] Authorization already has valid status, no need to complete challenges`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
/* Select challenge based on priority */
|
||||
const challenge = authz.challenges.sort((a, b) => {
|
||||
const aidx = opts.challengePriority.indexOf(a.type);
|
||||
const bidx = opts.challengePriority.indexOf(b.type);
|
||||
|
||||
if (aidx === -1) return 1;
|
||||
if (bidx === -1) return -1;
|
||||
return aidx - bidx;
|
||||
}).slice(0, 1)[0];
|
||||
|
||||
if (!challenge) {
|
||||
throw new Error(`Unable to select challenge for ${d}, no challenge found`);
|
||||
}
|
||||
|
||||
log(`[auto] [${d}] Found ${authz.challenges.length} challenges, selected type: ${challenge.type}`);
|
||||
|
||||
/* Trigger challengeCreateFn() */
|
||||
log(`[auto] [${d}] Trigger challengeCreateFn()`);
|
||||
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
||||
let recordItem = null;
|
||||
try {
|
||||
recordItem = await opts.challengeCreateFn(authz, challenge, keyAuthorization);
|
||||
|
||||
/* Challenge verification */
|
||||
if (opts.skipChallengeVerification === true) {
|
||||
log(`[auto] [${d}] Skipping challenge verification since skipChallengeVerification=true`);
|
||||
}
|
||||
else {
|
||||
log(`[auto] [${d}] Running challenge verification`);
|
||||
await client.verifyChallenge(authz, challenge);
|
||||
}
|
||||
|
||||
/* Complete challenge and wait for valid status */
|
||||
log(`[auto] [${d}] Completing challenge with ACME provider and waiting for valid status`);
|
||||
await client.completeChallenge(challenge);
|
||||
challengeCompleted = true;
|
||||
|
||||
await client.waitForValidStatus(challenge);
|
||||
}
|
||||
catch (e) {
|
||||
log(`[auto] [${d}] challengeCreateFn threw error: ${e.message}`);
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
/* Trigger challengeRemoveFn(), suppress errors */
|
||||
log(`[auto] [${d}] Trigger challengeRemoveFn()`);
|
||||
|
||||
try {
|
||||
await opts.challengeRemoveFn(authz, challenge, keyAuthorization, recordItem);
|
||||
}
|
||||
catch (e) {
|
||||
log(`[auto] [${d}] challengeRemoveFn threw error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
/* Deactivate pending authz when unable to complete challenge */
|
||||
if (!challengeCompleted) {
|
||||
log(`[auto] [${d}] Unable to complete challenge: ${e.message}`);
|
||||
|
||||
try {
|
||||
log(`[auto] [${d}] Deactivating failed authorization`);
|
||||
await client.deactivateAuthorization(authz);
|
||||
}
|
||||
catch (f) {
|
||||
/* Suppress deactivateAuthorization() errors */
|
||||
log(`[auto] [${d}] Authorization deactivation threw error: ${f.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
const challengePromises = authorizations.map((authz) => async () => {
|
||||
await challengeFunc(authz);
|
||||
});
|
||||
|
||||
log('开始challenge');
|
||||
let promise = Promise.resolve();
|
||||
function runPromisesSerially(tasks) {
|
||||
tasks.forEach((task) => {
|
||||
promise = promise.then(task);
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
await runPromisesSerially(challengePromises);
|
||||
log('challenge结束');
|
||||
|
||||
// log('[auto] Waiting for challenge valid status');
|
||||
// await Promise.all(challengePromises);
|
||||
|
||||
|
||||
/**
|
||||
* Finalize order and download certificate
|
||||
*/
|
||||
|
||||
log('[auto] Finalizing order and downloading certificate');
|
||||
const finalized = await client.finalizeOrder(order, opts.csr);
|
||||
return client.getCertificate(finalized, opts.preferredChain);
|
||||
};
|
||||
40
packages/core/acme-client/src/axios.js
Normal file
40
packages/core/acme-client/src/axios.js
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Axios instance
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const adapter = require('axios/lib/adapters/http');
|
||||
const pkg = require('./../package.json');
|
||||
|
||||
|
||||
/**
|
||||
* Instance
|
||||
*/
|
||||
|
||||
const instance = axios.create();
|
||||
|
||||
/* Default User-Agent */
|
||||
instance.defaults.headers.common['User-Agent'] = `node-${pkg.name}/${pkg.version}`;
|
||||
|
||||
/* Default ACME settings */
|
||||
instance.defaults.acmeSettings = {
|
||||
httpChallengePort: 80,
|
||||
bypassCustomDnsResolver: false
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Explicitly set Node as default HTTP adapter
|
||||
*
|
||||
* https://github.com/axios/axios/issues/1180
|
||||
* https://stackoverflow.com/questions/42677387
|
||||
*/
|
||||
|
||||
instance.defaults.adapter = adapter;
|
||||
|
||||
|
||||
/**
|
||||
* Export instance
|
||||
*/
|
||||
|
||||
module.exports = instance;
|
||||
735
packages/core/acme-client/src/client.js
Normal file
735
packages/core/acme-client/src/client.js
Normal file
@@ -0,0 +1,735 @@
|
||||
/**
|
||||
* ACME client
|
||||
*
|
||||
* @namespace Client
|
||||
*/
|
||||
|
||||
const { createHash } = require('crypto');
|
||||
const { getPemBodyAsB64u } = require('./crypto');
|
||||
const { log } = require('./logger');
|
||||
const HttpClient = require('./http');
|
||||
const AcmeApi = require('./api');
|
||||
const verify = require('./verify');
|
||||
const util = require('./util');
|
||||
const auto = require('./auto');
|
||||
|
||||
|
||||
/**
|
||||
* ACME states
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
|
||||
const validStates = ['ready', 'valid'];
|
||||
const pendingStates = ['pending', 'processing'];
|
||||
const invalidStates = ['invalid'];
|
||||
|
||||
|
||||
/**
|
||||
* Default options
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
|
||||
const defaultOpts = {
|
||||
directoryUrl: undefined,
|
||||
accountKey: undefined,
|
||||
accountUrl: null,
|
||||
externalAccountBinding: {},
|
||||
backoffAttempts: 10,
|
||||
backoffMin: 5000,
|
||||
backoffMax: 30000
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* AcmeClient
|
||||
*
|
||||
* @class
|
||||
* @param {object} opts
|
||||
* @param {string} opts.directoryUrl ACME directory URL
|
||||
* @param {buffer|string} opts.accountKey PEM encoded account private key
|
||||
* @param {string} [opts.accountUrl] Account URL, default: `null`
|
||||
* @param {object} [opts.externalAccountBinding]
|
||||
* @param {string} [opts.externalAccountBinding.kid] External account binding KID
|
||||
* @param {string} [opts.externalAccountBinding.hmacKey] External account binding HMAC key
|
||||
* @param {number} [opts.backoffAttempts] Maximum number of backoff attempts, default: `10`
|
||||
* @param {number} [opts.backoffMin] Minimum backoff attempt delay in milliseconds, default: `5000`
|
||||
* @param {number} [opts.backoffMax] Maximum backoff attempt delay in milliseconds, default: `30000`
|
||||
*
|
||||
* @example Create ACME client instance
|
||||
* ```js
|
||||
* const client = new acme.Client({
|
||||
* directoryUrl: acme.directory.letsencrypt.staging,
|
||||
* accountKey: 'Private key goes here'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Create ACME client instance
|
||||
* ```js
|
||||
* const client = new acme.Client({
|
||||
* directoryUrl: acme.directory.letsencrypt.staging,
|
||||
* accountKey: 'Private key goes here',
|
||||
* accountUrl: 'Optional account URL goes here',
|
||||
* backoffAttempts: 10,
|
||||
* backoffMin: 5000,
|
||||
* backoffMax: 30000
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Create ACME client with external account binding
|
||||
* ```js
|
||||
* const client = new acme.Client({
|
||||
* directoryUrl: 'https://acme-provider.example.com/directory-url',
|
||||
* accountKey: 'Private key goes here',
|
||||
* externalAccountBinding: {
|
||||
* kid: 'YOUR-EAB-KID',
|
||||
* hmacKey: 'YOUR-EAB-HMAC-KEY'
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
class AcmeClient {
|
||||
constructor(opts) {
|
||||
if (!Buffer.isBuffer(opts.accountKey)) {
|
||||
opts.accountKey = Buffer.from(opts.accountKey);
|
||||
}
|
||||
|
||||
this.opts = Object.assign({}, defaultOpts, opts);
|
||||
|
||||
this.backoffOpts = {
|
||||
attempts: this.opts.backoffAttempts,
|
||||
min: this.opts.backoffMin,
|
||||
max: this.opts.backoffMax
|
||||
};
|
||||
|
||||
this.http = new HttpClient(this.opts.directoryUrl, this.opts.accountKey, this.opts.externalAccountBinding);
|
||||
this.api = new AcmeApi(this.http, this.opts.accountUrl);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get Terms of Service URL if available
|
||||
*
|
||||
* @returns {Promise<string|null>} ToS URL
|
||||
*
|
||||
* @example Get Terms of Service URL
|
||||
* ```js
|
||||
* const termsOfService = client.getTermsOfServiceUrl();
|
||||
*
|
||||
* if (!termsOfService) {
|
||||
* // CA did not provide Terms of Service
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
getTermsOfServiceUrl() {
|
||||
return this.api.getTermsOfServiceUrl();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get current account URL
|
||||
*
|
||||
* @returns {string} Account URL
|
||||
* @throws {Error} No account URL found
|
||||
*
|
||||
* @example Get current account URL
|
||||
* ```js
|
||||
* try {
|
||||
* const accountUrl = client.getAccountUrl();
|
||||
* }
|
||||
* catch (e) {
|
||||
* // No account URL exists, need to create account first
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
getAccountUrl() {
|
||||
return this.api.getAccountUrl();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new account
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3
|
||||
*
|
||||
* @param {object} [data] Request data
|
||||
* @returns {Promise<object>} Account
|
||||
*
|
||||
* @example Create a new account
|
||||
* ```js
|
||||
* const account = await client.createAccount({
|
||||
* termsOfServiceAgreed: true
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Create a new account with contact info
|
||||
* ```js
|
||||
* const account = await client.createAccount({
|
||||
* termsOfServiceAgreed: true,
|
||||
* contact: ['mailto:test@example.com']
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
async createAccount(data = {}) {
|
||||
try {
|
||||
this.getAccountUrl();
|
||||
|
||||
/* Account URL exists */
|
||||
log('Account URL exists, returning updateAccount()');
|
||||
return this.updateAccount(data);
|
||||
}
|
||||
catch (e) {
|
||||
const resp = await this.api.createAccount(data);
|
||||
|
||||
/* HTTP 200: Account exists */
|
||||
if (resp.status === 200) {
|
||||
log('Account already exists (HTTP 200), returning updateAccount()');
|
||||
return this.updateAccount(data);
|
||||
}
|
||||
|
||||
return resp.data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update existing account
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3.2
|
||||
*
|
||||
* @param {object} [data] Request data
|
||||
* @returns {Promise<object>} Account
|
||||
*
|
||||
* @example Update existing account
|
||||
* ```js
|
||||
* const account = await client.updateAccount({
|
||||
* contact: ['mailto:foo@example.com']
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
async updateAccount(data = {}) {
|
||||
try {
|
||||
this.api.getAccountUrl();
|
||||
}
|
||||
catch (e) {
|
||||
log('No account URL found, returning createAccount()');
|
||||
return this.createAccount(data);
|
||||
}
|
||||
|
||||
/* Remove data only applicable to createAccount() */
|
||||
if ('onlyReturnExisting' in data) {
|
||||
delete data.onlyReturnExisting;
|
||||
}
|
||||
|
||||
/* POST-as-GET */
|
||||
if (Object.keys(data).length === 0) {
|
||||
data = null;
|
||||
}
|
||||
|
||||
const resp = await this.api.updateAccount(data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update account private key
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3.5
|
||||
*
|
||||
* @param {buffer|string} newAccountKey New PEM encoded private key
|
||||
* @param {object} [data] Additional request data
|
||||
* @returns {Promise<object>} Account
|
||||
*
|
||||
* @example Update account private key
|
||||
* ```js
|
||||
* const newAccountKey = 'New private key goes here';
|
||||
* const result = await client.updateAccountKey(newAccountKey);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async updateAccountKey(newAccountKey, data = {}) {
|
||||
if (!Buffer.isBuffer(newAccountKey)) {
|
||||
newAccountKey = Buffer.from(newAccountKey);
|
||||
}
|
||||
|
||||
const accountUrl = this.api.getAccountUrl();
|
||||
|
||||
/* Create new HTTP and API clients using new key */
|
||||
const newHttpClient = new HttpClient(this.opts.directoryUrl, newAccountKey);
|
||||
const newApiClient = new AcmeApi(newHttpClient, accountUrl);
|
||||
|
||||
/* Get old JWK */
|
||||
data.account = accountUrl;
|
||||
data.oldKey = this.http.getJwk();
|
||||
|
||||
/* Get signed request body from new client */
|
||||
const url = await newHttpClient.getResourceUrl('keyChange');
|
||||
const body = newHttpClient.createSignedBody(url, data);
|
||||
|
||||
/* Change key using old client */
|
||||
const resp = await this.api.updateAccountKey(body);
|
||||
|
||||
/* Replace existing HTTP and API client */
|
||||
this.http = newHttpClient;
|
||||
this.api = newApiClient;
|
||||
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {object} data Request data
|
||||
* @returns {Promise<object>} Order
|
||||
*
|
||||
* @example Create a new order
|
||||
* ```js
|
||||
* const order = await client.createOrder({
|
||||
* identifiers: [
|
||||
* { type: 'dns', value: 'example.com' },
|
||||
* { type: 'dns', value: 'test.example.com' }
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
async createOrder(data) {
|
||||
const resp = await this.api.createOrder(data);
|
||||
|
||||
if (!resp.headers.location) {
|
||||
throw new Error('Creating a new order did not return an order link');
|
||||
}
|
||||
|
||||
/* Add URL to response */
|
||||
resp.data.url = resp.headers.location;
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Refresh order object from CA
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {object} order Order object
|
||||
* @returns {Promise<object>} Order
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* const order = { ... }; // Previously created order object
|
||||
* const result = await client.getOrder(order);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async getOrder(order) {
|
||||
if (!order.url) {
|
||||
throw new Error('Unable to get order, URL not found');
|
||||
}
|
||||
|
||||
const resp = await this.api.getOrder(order.url);
|
||||
|
||||
/* Add URL to response */
|
||||
resp.data.url = order.url;
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*
|
||||
* @param {object} order Order object
|
||||
* @param {buffer|string} csr PEM encoded Certificate Signing Request
|
||||
* @returns {Promise<object>} Order
|
||||
*
|
||||
* @example Finalize order
|
||||
* ```js
|
||||
* const order = { ... }; // Previously created order object
|
||||
* const csr = { ... }; // Previously created Certificate Signing Request
|
||||
* const result = await client.finalizeOrder(order, csr);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async finalizeOrder(order, csr) {
|
||||
if (!order.finalize) {
|
||||
throw new Error('Unable to finalize order, URL not found');
|
||||
}
|
||||
|
||||
if (!Buffer.isBuffer(csr)) {
|
||||
csr = Buffer.from(csr);
|
||||
}
|
||||
|
||||
const data = { csr: getPemBodyAsB64u(csr) };
|
||||
const resp = await this.api.finalizeOrder(order.finalize, data);
|
||||
|
||||
/* Add URL to response */
|
||||
resp.data.url = order.url;
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get identifier authorizations from order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5
|
||||
*
|
||||
* @param {object} order Order
|
||||
* @returns {Promise<object[]>} Authorizations
|
||||
*
|
||||
* @example Get identifier authorizations
|
||||
* ```js
|
||||
* const order = { ... }; // Previously created order object
|
||||
* const authorizations = await client.getAuthorizations(order);
|
||||
*
|
||||
* authorizations.forEach((authz) => {
|
||||
* const { challenges } = authz;
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
async getAuthorizations(order) {
|
||||
return Promise.all((order.authorizations || []).map(async (url) => {
|
||||
const resp = await this.api.getAuthorization(url);
|
||||
|
||||
/* Add URL to response */
|
||||
resp.data.url = url;
|
||||
return resp.data;
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deactivate identifier authorization
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5.2
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @returns {Promise<object>} Authorization
|
||||
*
|
||||
* @example Deactivate identifier authorization
|
||||
* ```js
|
||||
* const authz = { ... }; // Identifier authorization resolved from previously created order
|
||||
* const result = await client.deactivateAuthorization(authz);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async deactivateAuthorization(authz) {
|
||||
if (!authz.url) {
|
||||
throw new Error('Unable to deactivate identifier authorization, URL not found');
|
||||
}
|
||||
|
||||
const data = {
|
||||
status: 'deactivated'
|
||||
};
|
||||
|
||||
const resp = await this.api.updateAuthorization(authz.url, data);
|
||||
|
||||
/* Add URL to response */
|
||||
resp.data.url = authz.url;
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get key authorization for ACME challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.1
|
||||
*
|
||||
* @param {object} challenge Challenge object returned by API
|
||||
* @returns {Promise<string>} Key authorization
|
||||
*
|
||||
* @example Get challenge key authorization
|
||||
* ```js
|
||||
* const challenge = { ... }; // Challenge from previously resolved identifier authorization
|
||||
* const key = await client.getChallengeKeyAuthorization(challenge);
|
||||
*
|
||||
* // Write key somewhere to satisfy challenge
|
||||
* ```
|
||||
*/
|
||||
|
||||
async getChallengeKeyAuthorization(challenge) {
|
||||
const jwk = this.http.getJwk();
|
||||
const keysum = createHash('sha256').update(JSON.stringify(jwk));
|
||||
const thumbprint = keysum.digest('base64url');
|
||||
const result = `${challenge.token}.${thumbprint}`;
|
||||
|
||||
/**
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.3
|
||||
*/
|
||||
|
||||
if (challenge.type === 'http-01') {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.4
|
||||
* https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-01
|
||||
*/
|
||||
|
||||
if ((challenge.type === 'dns-01') || (challenge.type === 'tls-alpn-01')) {
|
||||
const shasum = createHash('sha256').update(result);
|
||||
return shasum.digest('base64url');
|
||||
}
|
||||
|
||||
throw new Error(`Unable to produce key authorization, unknown challenge type: ${challenge.type}`);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Verify that ACME challenge is satisfied
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @param {object} challenge Authorization challenge
|
||||
* @returns {Promise}
|
||||
*
|
||||
* @example Verify satisfied ACME challenge
|
||||
* ```js
|
||||
* const authz = { ... }; // Identifier authorization
|
||||
* const challenge = { ... }; // Satisfied challenge
|
||||
* await client.verifyChallenge(authz, challenge);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async verifyChallenge(authz, challenge) {
|
||||
if (!authz.url || !challenge.url) {
|
||||
throw new Error('Unable to verify ACME challenge, URL not found');
|
||||
}
|
||||
|
||||
if (typeof verify[challenge.type] === 'undefined') {
|
||||
throw new Error(`Unable to verify ACME challenge, unknown type: ${challenge.type}`);
|
||||
}
|
||||
|
||||
const keyAuthorization = await this.getChallengeKeyAuthorization(challenge);
|
||||
|
||||
const verifyFn = async () => {
|
||||
await verify[challenge.type](authz, challenge, keyAuthorization);
|
||||
};
|
||||
|
||||
log('Waiting for ACME challenge verification', this.backoffOpts);
|
||||
return util.retry(verifyFn, this.backoffOpts);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Notify CA that challenge has been completed
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5.1
|
||||
*
|
||||
* @param {object} challenge Challenge object returned by API
|
||||
* @returns {Promise<object>} Challenge
|
||||
*
|
||||
* @example Notify CA that challenge has been completed
|
||||
* ```js
|
||||
* const challenge = { ... }; // Satisfied challenge
|
||||
* const result = await client.completeChallenge(challenge);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async completeChallenge(challenge) {
|
||||
const resp = await this.api.completeChallenge(challenge.url, {});
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Wait for ACME provider to verify status on a order, authorization or challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.5.1
|
||||
*
|
||||
* @param {object} item An order, authorization or challenge object
|
||||
* @returns {Promise<object>} Valid order, authorization or challenge
|
||||
*
|
||||
* @example Wait for valid challenge status
|
||||
* ```js
|
||||
* const challenge = { ... };
|
||||
* await client.waitForValidStatus(challenge);
|
||||
* ```
|
||||
*
|
||||
* @example Wait for valid authoriation status
|
||||
* ```js
|
||||
* const authz = { ... };
|
||||
* await client.waitForValidStatus(authz);
|
||||
* ```
|
||||
*
|
||||
* @example Wait for valid order status
|
||||
* ```js
|
||||
* const order = { ... };
|
||||
* await client.waitForValidStatus(order);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async waitForValidStatus(item) {
|
||||
if (!item.url) {
|
||||
throw new Error('Unable to verify status of item, URL not found');
|
||||
}
|
||||
|
||||
const verifyFn = async (abort) => {
|
||||
const resp = await this.api.apiRequest(item.url, null, [200]);
|
||||
|
||||
/* Verify status */
|
||||
log(`Item has status: ${resp.data.status}`);
|
||||
|
||||
if (invalidStates.includes(resp.data.status)) {
|
||||
abort();
|
||||
throw new Error(util.formatResponseError(resp));
|
||||
}
|
||||
else if (pendingStates.includes(resp.data.status)) {
|
||||
throw new Error('Operation is pending or processing');
|
||||
}
|
||||
else if (validStates.includes(resp.data.status)) {
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected item status: ${resp.data.status}`);
|
||||
};
|
||||
|
||||
log(`Waiting for valid status from: ${item.url}`, this.backoffOpts);
|
||||
return util.retry(verifyFn, this.backoffOpts);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get certificate from ACME order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4.2
|
||||
*
|
||||
* @param {object} order Order object
|
||||
* @param {string} [preferredChain] Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null`
|
||||
* @returns {Promise<string>} Certificate
|
||||
*
|
||||
* @example Get certificate
|
||||
* ```js
|
||||
* const order = { ... }; // Previously created order
|
||||
* const certificate = await client.getCertificate(order);
|
||||
* ```
|
||||
*
|
||||
* @example Get certificate with preferred chain
|
||||
* ```js
|
||||
* const order = { ... }; // Previously created order
|
||||
* const certificate = await client.getCertificate(order, 'DST Root CA X3');
|
||||
* ```
|
||||
*/
|
||||
|
||||
async getCertificate(order, preferredChain = null) {
|
||||
if (!validStates.includes(order.status)) {
|
||||
order = await this.waitForValidStatus(order);
|
||||
}
|
||||
|
||||
if (!order.certificate) {
|
||||
throw new Error('Unable to download certificate, URL not found');
|
||||
}
|
||||
|
||||
const resp = await this.api.apiRequest(order.certificate, null, [200]);
|
||||
|
||||
/* Handle alternate certificate chains */
|
||||
if (preferredChain && resp.headers.link) {
|
||||
const alternateLinks = util.parseLinkHeader(resp.headers.link);
|
||||
const alternates = await Promise.all(alternateLinks.map(async (link) => this.api.apiRequest(link, null, [200])));
|
||||
const certificates = [resp].concat(alternates).map((c) => c.data);
|
||||
|
||||
return util.findCertificateChainForIssuer(certificates, preferredChain);
|
||||
}
|
||||
|
||||
/* Return default certificate chain */
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Revoke certificate
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.6
|
||||
*
|
||||
* @param {buffer|string} cert PEM encoded certificate
|
||||
* @param {object} [data] Additional request data
|
||||
* @returns {Promise}
|
||||
*
|
||||
* @example Revoke certificate
|
||||
* ```js
|
||||
* const certificate = { ... }; // Previously created certificate
|
||||
* const result = await client.revokeCertificate(certificate);
|
||||
* ```
|
||||
*
|
||||
* @example Revoke certificate with reason
|
||||
* ```js
|
||||
* const certificate = { ... }; // Previously created certificate
|
||||
* const result = await client.revokeCertificate(certificate, {
|
||||
* reason: 4
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
async revokeCertificate(cert, data = {}) {
|
||||
data.certificate = getPemBodyAsB64u(cert);
|
||||
const resp = await this.api.revokeCert(data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Auto mode
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {buffer|string} opts.csr Certificate Signing Request
|
||||
* @param {function} opts.challengeCreateFn Function returning Promise triggered before completing ACME challenge
|
||||
* @param {function} opts.challengeRemoveFn Function returning Promise triggered after completing ACME challenge
|
||||
* @param {string} [opts.email] Account email address
|
||||
* @param {boolean} [opts.termsOfServiceAgreed] Agree to Terms of Service, default: `false`
|
||||
* @param {boolean} [opts.skipChallengeVerification] Skip internal challenge verification before notifying ACME provider, default: `false`
|
||||
* @param {string[]} [opts.challengePriority] Array defining challenge type priority, default: `['http-01', 'dns-01']`
|
||||
* @param {string} [opts.preferredChain] Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null`
|
||||
* @returns {Promise<string>} Certificate
|
||||
*
|
||||
* @example Order a certificate using auto mode
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* });
|
||||
*
|
||||
* const certificate = await client.auto({
|
||||
* csr: certificateRequest,
|
||||
* email: 'test@example.com',
|
||||
* termsOfServiceAgreed: true,
|
||||
* challengeCreateFn: async (authz, challenge, keyAuthorization) => {
|
||||
* // Satisfy challenge here
|
||||
* },
|
||||
* challengeRemoveFn: async (authz, challenge, keyAuthorization) => {
|
||||
* // Clean up challenge here
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Order a certificate using auto mode with preferred chain
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* });
|
||||
*
|
||||
* const certificate = await client.auto({
|
||||
* csr: certificateRequest,
|
||||
* email: 'test@example.com',
|
||||
* termsOfServiceAgreed: true,
|
||||
* preferredChain: 'DST Root CA X3',
|
||||
* challengeCreateFn: async () => {},
|
||||
* challengeRemoveFn: async () => {}
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
auto(opts) {
|
||||
return auto(this, opts);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Export client */
|
||||
module.exports = AcmeClient;
|
||||
448
packages/core/acme-client/src/crypto/forge.js
Normal file
448
packages/core/acme-client/src/crypto/forge.js
Normal file
@@ -0,0 +1,448 @@
|
||||
/**
|
||||
* Legacy node-forge crypto interface
|
||||
*
|
||||
* DEPRECATION WARNING: This crypto interface is deprecated and will be removed from acme-client in a future
|
||||
* major release. Please migrate to the new `acme.crypto` interface at your earliest convenience.
|
||||
*
|
||||
* @namespace forge
|
||||
*/
|
||||
|
||||
const net = require('net');
|
||||
const { promisify } = require('util');
|
||||
const forge = require('node-forge');
|
||||
|
||||
const generateKeyPair = promisify(forge.pki.rsa.generateKeyPair);
|
||||
|
||||
|
||||
/**
|
||||
* Attempt to parse forge object from PEM encoded string
|
||||
*
|
||||
* @private
|
||||
* @param {string} input PEM string
|
||||
* @return {object}
|
||||
*/
|
||||
|
||||
function forgeObjectFromPem(input) {
|
||||
const msg = forge.pem.decode(input)[0];
|
||||
let result;
|
||||
|
||||
switch (msg.type) {
|
||||
case 'PRIVATE KEY':
|
||||
case 'RSA PRIVATE KEY':
|
||||
result = forge.pki.privateKeyFromPem(input);
|
||||
break;
|
||||
|
||||
case 'PUBLIC KEY':
|
||||
case 'RSA PUBLIC KEY':
|
||||
result = forge.pki.publicKeyFromPem(input);
|
||||
break;
|
||||
|
||||
case 'CERTIFICATE':
|
||||
case 'X509 CERTIFICATE':
|
||||
case 'TRUSTED CERTIFICATE':
|
||||
result = forge.pki.certificateFromPem(input).publicKey;
|
||||
break;
|
||||
|
||||
case 'CERTIFICATE REQUEST':
|
||||
result = forge.pki.certificationRequestFromPem(input).publicKey;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error('Unable to detect forge message type');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse domain names from a certificate or CSR
|
||||
*
|
||||
* @private
|
||||
* @param {object} obj Forge certificate or CSR
|
||||
* @returns {object} {commonName, altNames}
|
||||
*/
|
||||
|
||||
function parseDomains(obj) {
|
||||
let commonName = null;
|
||||
let altNames = [];
|
||||
let altNamesDict = [];
|
||||
|
||||
const commonNameObject = (obj.subject.attributes || []).find((a) => a.name === 'commonName');
|
||||
const rootAltNames = (obj.extensions || []).find((e) => 'altNames' in e);
|
||||
const rootExtensions = (obj.attributes || []).find((a) => 'extensions' in a);
|
||||
|
||||
if (rootAltNames && rootAltNames.altNames && rootAltNames.altNames.length) {
|
||||
altNamesDict = rootAltNames.altNames;
|
||||
}
|
||||
else if (rootExtensions && rootExtensions.extensions && rootExtensions.extensions.length) {
|
||||
const extAltNames = rootExtensions.extensions.find((e) => 'altNames' in e);
|
||||
|
||||
if (extAltNames && extAltNames.altNames && extAltNames.altNames.length) {
|
||||
altNamesDict = extAltNames.altNames;
|
||||
}
|
||||
}
|
||||
|
||||
if (commonNameObject) {
|
||||
commonName = commonNameObject.value;
|
||||
}
|
||||
|
||||
if (altNamesDict) {
|
||||
altNames = altNamesDict.map((a) => a.value);
|
||||
}
|
||||
|
||||
return {
|
||||
commonName,
|
||||
altNames
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generate a private RSA key
|
||||
*
|
||||
* @param {number} [size] Size of the key, default: `2048`
|
||||
* @returns {Promise<buffer>} PEM encoded private RSA key
|
||||
*
|
||||
* @example Generate private RSA key
|
||||
* ```js
|
||||
* const privateKey = await acme.forge.createPrivateKey();
|
||||
* ```
|
||||
*
|
||||
* @example Private RSA key with defined size
|
||||
* ```js
|
||||
* const privateKey = await acme.forge.createPrivateKey(4096);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async function createPrivateKey(size = 2048) {
|
||||
const keyPair = await generateKeyPair({ bits: size });
|
||||
const pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
|
||||
return Buffer.from(pemKey);
|
||||
}
|
||||
|
||||
exports.createPrivateKey = createPrivateKey;
|
||||
|
||||
|
||||
/**
|
||||
* Create public key from a private RSA key
|
||||
*
|
||||
* @param {buffer|string} key PEM encoded private RSA key
|
||||
* @returns {Promise<buffer>} PEM encoded public RSA key
|
||||
*
|
||||
* @example Create public key
|
||||
* ```js
|
||||
* const publicKey = await acme.forge.createPublicKey(privateKey);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.createPublicKey = async function(key) {
|
||||
const privateKey = forge.pki.privateKeyFromPem(key);
|
||||
const publicKey = forge.pki.rsa.setPublicKey(privateKey.n, privateKey.e);
|
||||
const pemKey = forge.pki.publicKeyToPem(publicKey);
|
||||
return Buffer.from(pemKey);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Parse body of PEM encoded object from buffer or string
|
||||
* If multiple objects are chained, the first body will be returned
|
||||
*
|
||||
* @param {buffer|string} str PEM encoded buffer or string
|
||||
* @returns {string} PEM body
|
||||
*/
|
||||
|
||||
exports.getPemBody = (str) => {
|
||||
const msg = forge.pem.decode(str)[0];
|
||||
return forge.util.encode64(msg.body);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Split chain of PEM encoded objects from buffer or string into array
|
||||
*
|
||||
* @param {buffer|string} str PEM encoded buffer or string
|
||||
* @returns {string[]} Array of PEM bodies
|
||||
*/
|
||||
|
||||
exports.splitPemChain = (str) => forge.pem.decode(str).map(forge.pem.encode);
|
||||
|
||||
|
||||
/**
|
||||
* Get modulus
|
||||
*
|
||||
* @param {buffer|string} input PEM encoded private key, certificate or CSR
|
||||
* @returns {Promise<buffer>} Modulus
|
||||
*
|
||||
* @example Get modulus
|
||||
* ```js
|
||||
* const m1 = await acme.forge.getModulus(privateKey);
|
||||
* const m2 = await acme.forge.getModulus(certificate);
|
||||
* const m3 = await acme.forge.getModulus(certificateRequest);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.getModulus = async function(input) {
|
||||
if (!Buffer.isBuffer(input)) {
|
||||
input = Buffer.from(input);
|
||||
}
|
||||
|
||||
const obj = forgeObjectFromPem(input);
|
||||
return Buffer.from(forge.util.hexToBytes(obj.n.toString(16)), 'binary');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get public exponent
|
||||
*
|
||||
* @param {buffer|string} input PEM encoded private key, certificate or CSR
|
||||
* @returns {Promise<buffer>} Exponent
|
||||
*
|
||||
* @example Get public exponent
|
||||
* ```js
|
||||
* const e1 = await acme.forge.getPublicExponent(privateKey);
|
||||
* const e2 = await acme.forge.getPublicExponent(certificate);
|
||||
* const e3 = await acme.forge.getPublicExponent(certificateRequest);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.getPublicExponent = async function(input) {
|
||||
if (!Buffer.isBuffer(input)) {
|
||||
input = Buffer.from(input);
|
||||
}
|
||||
|
||||
const obj = forgeObjectFromPem(input);
|
||||
return Buffer.from(forge.util.hexToBytes(obj.e.toString(16)), 'binary');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Read domains from a Certificate Signing Request
|
||||
*
|
||||
* @param {buffer|string} csr PEM encoded Certificate Signing Request
|
||||
* @returns {Promise<object>} {commonName, altNames}
|
||||
*
|
||||
* @example Read Certificate Signing Request domains
|
||||
* ```js
|
||||
* const { commonName, altNames } = await acme.forge.readCsrDomains(certificateRequest);
|
||||
*
|
||||
* console.log(`Common name: ${commonName}`);
|
||||
* console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.readCsrDomains = async function(csr) {
|
||||
if (!Buffer.isBuffer(csr)) {
|
||||
csr = Buffer.from(csr);
|
||||
}
|
||||
|
||||
const obj = forge.pki.certificationRequestFromPem(csr);
|
||||
return parseDomains(obj);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Read information from a certificate
|
||||
*
|
||||
* @param {buffer|string} cert PEM encoded certificate
|
||||
* @returns {Promise<object>} Certificate info
|
||||
*
|
||||
* @example Read certificate information
|
||||
* ```js
|
||||
* const info = await acme.forge.readCertificateInfo(certificate);
|
||||
* const { commonName, altNames } = info.domains;
|
||||
*
|
||||
* console.log(`Not after: ${info.notAfter}`);
|
||||
* console.log(`Not before: ${info.notBefore}`);
|
||||
*
|
||||
* console.log(`Common name: ${commonName}`);
|
||||
* console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.readCertificateInfo = async function(cert) {
|
||||
if (!Buffer.isBuffer(cert)) {
|
||||
cert = Buffer.from(cert);
|
||||
}
|
||||
|
||||
const obj = forge.pki.certificateFromPem(cert);
|
||||
const issuerCn = (obj.issuer.attributes || []).find((a) => a.name === 'commonName');
|
||||
|
||||
return {
|
||||
issuer: {
|
||||
commonName: issuerCn ? issuerCn.value : null
|
||||
},
|
||||
domains: parseDomains(obj),
|
||||
notAfter: obj.validity.notAfter,
|
||||
notBefore: obj.validity.notBefore
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Determine ASN.1 type for CSR subject short name
|
||||
* Note: https://tools.ietf.org/html/rfc5280
|
||||
*
|
||||
* @private
|
||||
* @param {string} shortName CSR subject short name
|
||||
* @returns {forge.asn1.Type} ASN.1 type
|
||||
*/
|
||||
|
||||
function getCsrValueTagClass(shortName) {
|
||||
switch (shortName) {
|
||||
case 'C':
|
||||
return forge.asn1.Type.PRINTABLESTRING;
|
||||
case 'E':
|
||||
return forge.asn1.Type.IA5STRING;
|
||||
default:
|
||||
return forge.asn1.Type.UTF8;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create array of short names and values for Certificate Signing Request subjects
|
||||
*
|
||||
* @private
|
||||
* @param {object} subjectObj Key-value of short names and values
|
||||
* @returns {object[]} Certificate Signing Request subject array
|
||||
*/
|
||||
|
||||
function createCsrSubject(subjectObj) {
|
||||
return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
|
||||
if (value) {
|
||||
const valueTagClass = getCsrValueTagClass(shortName);
|
||||
result.push({ shortName, value, valueTagClass });
|
||||
}
|
||||
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create array of alt names for Certificate Signing Requests
|
||||
* Note: https://github.com/digitalbazaar/forge/blob/dfdde475677a8a25c851e33e8f81dca60d90cfb9/lib/x509.js#L1444-L1454
|
||||
*
|
||||
* @private
|
||||
* @param {string[]} altNames Alt names
|
||||
* @returns {object[]} Certificate Signing Request alt names array
|
||||
*/
|
||||
|
||||
function formatCsrAltNames(altNames) {
|
||||
return altNames.map((value) => {
|
||||
const type = net.isIP(value) ? 7 : 2;
|
||||
return { type, value };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a Certificate Signing Request
|
||||
*
|
||||
* @param {object} data
|
||||
* @param {number} [data.keySize] Size of newly created private key, default: `2048`
|
||||
* @param {string} [data.commonName]
|
||||
* @param {array} [data.altNames] default: `[]`
|
||||
* @param {string} [data.country]
|
||||
* @param {string} [data.state]
|
||||
* @param {string} [data.locality]
|
||||
* @param {string} [data.organization]
|
||||
* @param {string} [data.organizationUnit]
|
||||
* @param {string} [data.emailAddress]
|
||||
* @param {buffer|string} [key] CSR private key
|
||||
* @returns {Promise<buffer[]>} [privateKey, certificateSigningRequest]
|
||||
*
|
||||
* @example Create a Certificate Signing Request
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with both common and alternative names
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
* keySize: 4096,
|
||||
* commonName: 'test.example.com',
|
||||
* altNames: ['foo.example.com', 'bar.example.com']
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with additional information
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.forge.createCsr({
|
||||
* commonName: 'test.example.com',
|
||||
* country: 'US',
|
||||
* state: 'California',
|
||||
* locality: 'Los Angeles',
|
||||
* organization: 'The Company Inc.',
|
||||
* organizationUnit: 'IT Department',
|
||||
* emailAddress: 'contact@example.com'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with predefined private key
|
||||
* ```js
|
||||
* const certificateKey = await acme.forge.createPrivateKey();
|
||||
*
|
||||
* const [, certificateRequest] = await acme.forge.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* }, certificateKey);
|
||||
*/
|
||||
|
||||
exports.createCsr = async function(data, key = null) {
|
||||
if (!key) {
|
||||
key = await createPrivateKey(data.keySize);
|
||||
}
|
||||
else if (!Buffer.isBuffer(key)) {
|
||||
key = Buffer.from(key);
|
||||
}
|
||||
|
||||
if (typeof data.altNames === 'undefined') {
|
||||
data.altNames = [];
|
||||
}
|
||||
|
||||
const csr = forge.pki.createCertificationRequest();
|
||||
|
||||
/* Public key */
|
||||
const privateKey = forge.pki.privateKeyFromPem(key);
|
||||
const publicKey = forge.pki.rsa.setPublicKey(privateKey.n, privateKey.e);
|
||||
csr.publicKey = publicKey;
|
||||
|
||||
/* Ensure subject common name is present in SAN - https://cabforum.org/wp-content/uploads/BRv1.2.3.pdf */
|
||||
if (data.commonName && !data.altNames.includes(data.commonName)) {
|
||||
data.altNames.unshift(data.commonName);
|
||||
}
|
||||
|
||||
/* Subject */
|
||||
const subject = createCsrSubject({
|
||||
CN: data.commonName,
|
||||
C: data.country,
|
||||
ST: data.state,
|
||||
L: data.locality,
|
||||
O: data.organization,
|
||||
OU: data.organizationUnit,
|
||||
E: data.emailAddress
|
||||
});
|
||||
|
||||
csr.setSubject(subject);
|
||||
|
||||
/* SAN extension */
|
||||
if (data.altNames.length) {
|
||||
csr.setAttributes([{
|
||||
name: 'extensionRequest',
|
||||
extensions: [{
|
||||
name: 'subjectAltName',
|
||||
altNames: formatCsrAltNames(data.altNames)
|
||||
}]
|
||||
}]);
|
||||
}
|
||||
|
||||
/* Sign CSR using SHA-256 */
|
||||
csr.sign(privateKey, forge.md.sha256.create());
|
||||
|
||||
/* Done */
|
||||
const pemCsr = forge.pki.certificationRequestToPem(csr);
|
||||
return [key, Buffer.from(pemCsr)];
|
||||
};
|
||||
526
packages/core/acme-client/src/crypto/index.js
Normal file
526
packages/core/acme-client/src/crypto/index.js
Normal file
@@ -0,0 +1,526 @@
|
||||
/**
|
||||
* Native Node.js crypto interface
|
||||
*
|
||||
* @namespace crypto
|
||||
*/
|
||||
|
||||
const net = require('net');
|
||||
const { promisify } = require('util');
|
||||
const crypto = require('crypto');
|
||||
const jsrsasign = require('jsrsasign');
|
||||
|
||||
const generateKeyPair = promisify(crypto.generateKeyPair);
|
||||
|
||||
|
||||
/**
|
||||
* Determine key type and info by attempting to derive public key
|
||||
*
|
||||
* @private
|
||||
* @param {buffer|string} keyPem PEM encoded private or public key
|
||||
* @returns {object}
|
||||
*/
|
||||
|
||||
function getKeyInfo(keyPem) {
|
||||
const result = {
|
||||
isRSA: false,
|
||||
isECDSA: false,
|
||||
signatureAlgorithm: null,
|
||||
publicKey: crypto.createPublicKey(keyPem)
|
||||
};
|
||||
|
||||
if (result.publicKey.asymmetricKeyType === 'rsa') {
|
||||
result.isRSA = true;
|
||||
result.signatureAlgorithm = 'SHA256withRSA';
|
||||
}
|
||||
else if (result.publicKey.asymmetricKeyType === 'ec') {
|
||||
result.isECDSA = true;
|
||||
result.signatureAlgorithm = 'SHA256withECDSA';
|
||||
}
|
||||
else {
|
||||
throw new Error('Unable to parse key information, unknown format');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generate a private RSA key
|
||||
*
|
||||
* @param {number} [modulusLength] Size of the keys modulus in bits, default: `2048`
|
||||
* @returns {Promise<buffer>} PEM encoded private RSA key
|
||||
*
|
||||
* @example Generate private RSA key
|
||||
* ```js
|
||||
* const privateKey = await acme.crypto.createPrivateRsaKey();
|
||||
* ```
|
||||
*
|
||||
* @example Private RSA key with modulus size 4096
|
||||
* ```js
|
||||
* const privateKey = await acme.crypto.createPrivateRsaKey(4096);
|
||||
* ```
|
||||
*/
|
||||
|
||||
async function createPrivateRsaKey(modulusLength = 2048) {
|
||||
const pair = await generateKeyPair('rsa', {
|
||||
modulusLength,
|
||||
privateKeyEncoding: {
|
||||
type: 'pkcs8',
|
||||
format: 'pem'
|
||||
}
|
||||
});
|
||||
|
||||
return Buffer.from(pair.privateKey);
|
||||
}
|
||||
|
||||
exports.createPrivateRsaKey = createPrivateRsaKey;
|
||||
|
||||
|
||||
/**
|
||||
* Alias of `createPrivateRsaKey()`
|
||||
*
|
||||
* @function
|
||||
*/
|
||||
|
||||
exports.createPrivateKey = createPrivateRsaKey;
|
||||
|
||||
|
||||
/**
|
||||
* Generate a private ECDSA key
|
||||
*
|
||||
* @param {string} [namedCurve] ECDSA curve name (P-256, P-384 or P-521), default `P-256`
|
||||
* @returns {Promise<buffer>} PEM encoded private ECDSA key
|
||||
*
|
||||
* @example Generate private ECDSA key
|
||||
* ```js
|
||||
* const privateKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
* ```
|
||||
*
|
||||
* @example Private ECDSA key using P-384 curve
|
||||
* ```js
|
||||
* const privateKey = await acme.crypto.createPrivateEcdsaKey('P-384');
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.createPrivateEcdsaKey = async (namedCurve = 'P-256') => {
|
||||
const pair = await generateKeyPair('ec', {
|
||||
namedCurve,
|
||||
privateKeyEncoding: {
|
||||
type: 'pkcs8',
|
||||
format: 'pem'
|
||||
}
|
||||
});
|
||||
|
||||
return Buffer.from(pair.privateKey);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get a public key derived from a RSA or ECDSA key
|
||||
*
|
||||
* @param {buffer|string} keyPem PEM encoded private or public key
|
||||
* @returns {buffer} PEM encoded public key
|
||||
*
|
||||
* @example Get public key
|
||||
* ```js
|
||||
* const publicKey = acme.crypto.getPublicKey(privateKey);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.getPublicKey = (keyPem) => {
|
||||
const info = getKeyInfo(keyPem);
|
||||
|
||||
const publicKey = info.publicKey.export({
|
||||
type: info.isECDSA ? 'spki' : 'pkcs1',
|
||||
format: 'pem'
|
||||
});
|
||||
|
||||
return Buffer.from(publicKey);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get a JSON Web Key derived from a RSA or ECDSA key
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc7517
|
||||
*
|
||||
* @param {buffer|string} keyPem PEM encoded private or public key
|
||||
* @returns {object} JSON Web Key
|
||||
*
|
||||
* @example Get JWK
|
||||
* ```js
|
||||
* const jwk = acme.crypto.getJwk(privateKey);
|
||||
* ```
|
||||
*/
|
||||
|
||||
function getJwk(keyPem) {
|
||||
const jwk = crypto.createPublicKey(keyPem).export({
|
||||
format: 'jwk'
|
||||
});
|
||||
|
||||
/* Sort keys */
|
||||
return Object.keys(jwk).sort().reduce((result, k) => {
|
||||
result[k] = jwk[k];
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
exports.getJwk = getJwk;
|
||||
|
||||
|
||||
/**
|
||||
* Fix missing support for NIST curve names in jsrsasign
|
||||
*
|
||||
* @private
|
||||
* @param {string} crv NIST curve name
|
||||
* @returns {string} SECG curve name
|
||||
*/
|
||||
|
||||
function convertNistCurveNameToSecg(nistName) {
|
||||
switch (nistName) {
|
||||
case 'P-256':
|
||||
return 'secp256r1';
|
||||
case 'P-384':
|
||||
return 'secp384r1';
|
||||
case 'P-521':
|
||||
return 'secp521r1';
|
||||
default:
|
||||
return nistName;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Split chain of PEM encoded objects from string into array
|
||||
*
|
||||
* @param {buffer|string} chainPem PEM encoded object chain
|
||||
* @returns {array} Array of PEM objects including headers
|
||||
*/
|
||||
|
||||
function splitPemChain(chainPem) {
|
||||
if (Buffer.isBuffer(chainPem)) {
|
||||
chainPem = chainPem.toString();
|
||||
}
|
||||
|
||||
return chainPem
|
||||
/* Split chain into chunks, starting at every header */
|
||||
.split(/\s*(?=-----BEGIN [A-Z0-9- ]+-----\r?\n?)/g)
|
||||
/* Match header, PEM body and footer */
|
||||
.map((pem) => pem.match(/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\S\s]+)\r?\n?-----END \1-----/))
|
||||
/* Filter out non-matches or empty bodies */
|
||||
.filter((pem) => pem && pem[2] && pem[2].replace(/[\r\n]+/g, '').trim())
|
||||
/* Decode to hex, and back to PEM for formatting etc */
|
||||
.map(([pem, header]) => jsrsasign.hextopem(jsrsasign.pemtohex(pem, header), header));
|
||||
}
|
||||
|
||||
exports.splitPemChain = splitPemChain;
|
||||
|
||||
|
||||
/**
|
||||
* Parse body of PEM encoded object and return a Base64URL string
|
||||
* If multiple objects are chained, the first body will be returned
|
||||
*
|
||||
* @param {buffer|string} pem PEM encoded chain or object
|
||||
* @returns {string} Base64URL-encoded body
|
||||
*/
|
||||
|
||||
exports.getPemBodyAsB64u = (pem) => {
|
||||
const chain = splitPemChain(pem);
|
||||
|
||||
if (!chain.length) {
|
||||
throw new Error('Unable to parse PEM body from string');
|
||||
}
|
||||
|
||||
/* First object, hex and back to b64 without new lines */
|
||||
return jsrsasign.hextob64u(jsrsasign.pemtohex(chain[0]));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Parse common name from a subject object
|
||||
*
|
||||
* @private
|
||||
* @param {object} subj Subject returned from jsrsasign
|
||||
* @returns {string} Common name value
|
||||
*/
|
||||
|
||||
function parseCommonName(subj) {
|
||||
const subjectArr = (subj && subj.array) ? subj.array : [];
|
||||
const cnArr = subjectArr.find((s) => (s[0] && s[0].type && s[0].value && (s[0].type === 'CN')));
|
||||
return (cnArr && cnArr.length && cnArr[0].value) ? cnArr[0].value : null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse domains from a certificate or CSR
|
||||
*
|
||||
* @private
|
||||
* @param {object} params Certificate or CSR params returned from jsrsasign
|
||||
* @returns {object} {commonName, altNames}
|
||||
*/
|
||||
|
||||
function parseDomains(params) {
|
||||
const commonName = parseCommonName(params.subject);
|
||||
const extensionArr = (params.ext || params.extreq || []);
|
||||
let altNames = [];
|
||||
|
||||
if (extensionArr && extensionArr.length) {
|
||||
const altNameExt = extensionArr.find((e) => (e.extname && (e.extname === 'subjectAltName')));
|
||||
const altNameArr = (altNameExt && altNameExt.array && altNameExt.array.length) ? altNameExt.array : [];
|
||||
altNames = altNameArr.map((a) => Object.values(a)[0] || null).filter((a) => a);
|
||||
}
|
||||
|
||||
return {
|
||||
commonName,
|
||||
altNames
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Read domains from a Certificate Signing Request
|
||||
*
|
||||
* @param {buffer|string} csrPem PEM encoded Certificate Signing Request
|
||||
* @returns {object} {commonName, altNames}
|
||||
*
|
||||
* @example Read Certificate Signing Request domains
|
||||
* ```js
|
||||
* const { commonName, altNames } = acme.crypto.readCsrDomains(certificateRequest);
|
||||
*
|
||||
* console.log(`Common name: ${commonName}`);
|
||||
* console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.readCsrDomains = (csrPem) => {
|
||||
if (Buffer.isBuffer(csrPem)) {
|
||||
csrPem = csrPem.toString();
|
||||
}
|
||||
|
||||
/* Parse CSR */
|
||||
const params = jsrsasign.KJUR.asn1.csr.CSRUtil.getParam(csrPem);
|
||||
return parseDomains(params);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Read information from a certificate
|
||||
* If multiple certificates are chained, the first will be read
|
||||
*
|
||||
* @param {buffer|string} certPem PEM encoded certificate or chain
|
||||
* @returns {object} Certificate info
|
||||
*
|
||||
* @example Read certificate information
|
||||
* ```js
|
||||
* const info = acme.crypto.readCertificateInfo(certificate);
|
||||
* const { commonName, altNames } = info.domains;
|
||||
*
|
||||
* console.log(`Not after: ${info.notAfter}`);
|
||||
* console.log(`Not before: ${info.notBefore}`);
|
||||
*
|
||||
* console.log(`Common name: ${commonName}`);
|
||||
* console.log(`Alt names: ${altNames.join(', ')}`);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.readCertificateInfo = (certPem) => {
|
||||
const chain = splitPemChain(certPem);
|
||||
|
||||
if (!chain.length) {
|
||||
throw new Error('Unable to parse PEM body from string');
|
||||
}
|
||||
|
||||
/* Parse certificate */
|
||||
const obj = new jsrsasign.X509();
|
||||
obj.readCertPEM(chain[0]);
|
||||
const params = obj.getParam();
|
||||
|
||||
return {
|
||||
issuer: {
|
||||
commonName: parseCommonName(params.issuer)
|
||||
},
|
||||
domains: parseDomains(params),
|
||||
notBefore: jsrsasign.zulutodate(params.notbefore),
|
||||
notAfter: jsrsasign.zulutodate(params.notafter)
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Determine ASN.1 character string type for CSR subject field
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc5280
|
||||
* https://github.com/kjur/jsrsasign/blob/2613c64559768b91dde9793dfa318feacb7c3b8a/src/x509-1.1.js#L2404-L2412
|
||||
* https://github.com/kjur/jsrsasign/blob/2613c64559768b91dde9793dfa318feacb7c3b8a/src/asn1x509-1.0.js#L3526-L3535
|
||||
*
|
||||
* @private
|
||||
* @param {string} field CSR subject field
|
||||
* @returns {string} ASN.1 jsrsasign character string type
|
||||
*/
|
||||
|
||||
function getCsrAsn1CharStringType(field) {
|
||||
switch (field) {
|
||||
case 'C':
|
||||
return 'prn';
|
||||
case 'E':
|
||||
return 'ia5';
|
||||
default:
|
||||
return 'utf8';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create array of subject fields for a Certificate Signing Request
|
||||
*
|
||||
* @private
|
||||
* @param {object} input Key-value of subject fields
|
||||
* @returns {object[]} Certificate Signing Request subject array
|
||||
*/
|
||||
|
||||
function createCsrSubject(input) {
|
||||
return Object.entries(input).reduce((result, [type, value]) => {
|
||||
if (value) {
|
||||
const ds = getCsrAsn1CharStringType(type);
|
||||
result.push([{ type, value, ds }]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create array of alt names for Certificate Signing Requests
|
||||
*
|
||||
* https://github.com/kjur/jsrsasign/blob/3edc0070846922daea98d9588978e91d855577ec/src/x509-1.1.js#L1355-L1410
|
||||
*
|
||||
* @private
|
||||
* @param {string[]} altNames Array of alt names
|
||||
* @returns {object[]} Certificate Signing Request alt names array
|
||||
*/
|
||||
|
||||
function formatCsrAltNames(altNames) {
|
||||
return altNames.map((value) => {
|
||||
const key = net.isIP(value) ? 'ip' : 'dns';
|
||||
return { [key]: value };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a Certificate Signing Request
|
||||
*
|
||||
* @param {object} data
|
||||
* @param {number} [data.keySize] Size of newly created RSA private key modulus in bits, default: `2048`
|
||||
* @param {string} [data.commonName] FQDN of your server
|
||||
* @param {array} [data.altNames] SAN (Subject Alternative Names), default: `[]`
|
||||
* @param {string} [data.country] 2 letter country code
|
||||
* @param {string} [data.state] State or province
|
||||
* @param {string} [data.locality] City
|
||||
* @param {string} [data.organization] Organization name
|
||||
* @param {string} [data.organizationUnit] Organizational unit name
|
||||
* @param {string} [data.emailAddress] Email address
|
||||
* @param {string} [keyPem] PEM encoded CSR private key
|
||||
* @returns {Promise<buffer[]>} [privateKey, certificateSigningRequest]
|
||||
*
|
||||
* @example Create a Certificate Signing Request
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with both common and alternative names
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
* keySize: 4096,
|
||||
* commonName: 'test.example.com',
|
||||
* altNames: ['foo.example.com', 'bar.example.com']
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with additional information
|
||||
* ```js
|
||||
* const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
* commonName: 'test.example.com',
|
||||
* country: 'US',
|
||||
* state: 'California',
|
||||
* locality: 'Los Angeles',
|
||||
* organization: 'The Company Inc.',
|
||||
* organizationUnit: 'IT Department',
|
||||
* emailAddress: 'contact@example.com'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with ECDSA private key
|
||||
* ```js
|
||||
* const certificateKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
*
|
||||
* const [, certificateRequest] = await acme.crypto.createCsr({
|
||||
* commonName: 'test.example.com'
|
||||
* }, certificateKey);
|
||||
*/
|
||||
|
||||
exports.createCsr = async (data, keyPem = null) => {
|
||||
if (!keyPem) {
|
||||
keyPem = await createPrivateRsaKey(data.keySize);
|
||||
}
|
||||
else if (!Buffer.isBuffer(keyPem)) {
|
||||
keyPem = Buffer.from(keyPem);
|
||||
}
|
||||
|
||||
if (typeof data.altNames === 'undefined') {
|
||||
data.altNames = [];
|
||||
}
|
||||
|
||||
/* Get key info and JWK */
|
||||
const info = getKeyInfo(keyPem);
|
||||
const jwk = getJwk(keyPem);
|
||||
const extensionRequests = [];
|
||||
|
||||
/* Missing support for NIST curve names in jsrsasign - https://github.com/kjur/jsrsasign/blob/master/src/asn1x509-1.0.js#L4388-L4393 */
|
||||
if (jwk.crv && (jwk.kty === 'EC')) {
|
||||
jwk.crv = convertNistCurveNameToSecg(jwk.crv);
|
||||
}
|
||||
|
||||
/* Ensure subject common name is present in SAN - https://cabforum.org/wp-content/uploads/BRv1.2.3.pdf */
|
||||
if (data.commonName && !data.altNames.includes(data.commonName)) {
|
||||
data.altNames.unshift(data.commonName);
|
||||
}
|
||||
|
||||
/* Subject */
|
||||
const subject = createCsrSubject({
|
||||
CN: data.commonName,
|
||||
C: data.country,
|
||||
ST: data.state,
|
||||
L: data.locality,
|
||||
O: data.organization,
|
||||
OU: data.organizationUnit,
|
||||
E: data.emailAddress
|
||||
});
|
||||
|
||||
/* SAN extension */
|
||||
if (data.altNames.length) {
|
||||
extensionRequests.push({
|
||||
extname: 'subjectAltName',
|
||||
array: formatCsrAltNames(data.altNames)
|
||||
});
|
||||
}
|
||||
|
||||
/* Create CSR */
|
||||
const csr = new jsrsasign.KJUR.asn1.csr.CertificationRequest({
|
||||
subject: { array: subject },
|
||||
sigalg: info.signatureAlgorithm,
|
||||
sbjprvkey: keyPem.toString(),
|
||||
sbjpubkey: jwk,
|
||||
extreq: extensionRequests
|
||||
});
|
||||
|
||||
/* Sign CSR, get PEM */
|
||||
csr.sign();
|
||||
const pem = csr.getPEM();
|
||||
|
||||
/* Done */
|
||||
return [keyPem, Buffer.from(pem)];
|
||||
};
|
||||
318
packages/core/acme-client/src/http.js
Normal file
318
packages/core/acme-client/src/http.js
Normal file
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* ACME HTTP client
|
||||
*/
|
||||
|
||||
const { createHmac, createSign, constants: { RSA_PKCS1_PADDING } } = require('crypto');
|
||||
const { getJwk } = require('./crypto');
|
||||
const { log } = require('./logger');
|
||||
const axios = require('./axios');
|
||||
|
||||
|
||||
/**
|
||||
* ACME HTTP client
|
||||
*
|
||||
* @class
|
||||
* @param {string} directoryUrl ACME directory URL
|
||||
* @param {buffer} accountKey PEM encoded account private key
|
||||
* @param {object} [opts.externalAccountBinding]
|
||||
* @param {string} [opts.externalAccountBinding.kid] External account binding KID
|
||||
* @param {string} [opts.externalAccountBinding.hmacKey] External account binding HMAC key
|
||||
*/
|
||||
|
||||
class HttpClient {
|
||||
constructor(directoryUrl, accountKey, externalAccountBinding = {}) {
|
||||
this.directoryUrl = directoryUrl;
|
||||
this.accountKey = accountKey;
|
||||
this.externalAccountBinding = externalAccountBinding;
|
||||
|
||||
this.maxBadNonceRetries = 5;
|
||||
this.directory = null;
|
||||
this.jwk = null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* HTTP request
|
||||
*
|
||||
* @param {string} url HTTP URL
|
||||
* @param {string} method HTTP method
|
||||
* @param {object} [opts] Request options
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
async request(url, method, opts = {}) {
|
||||
opts.url = url;
|
||||
opts.method = method;
|
||||
opts.validateStatus = null;
|
||||
|
||||
/* Headers */
|
||||
if (typeof opts.headers === 'undefined') {
|
||||
opts.headers = {};
|
||||
}
|
||||
|
||||
opts.headers['Content-Type'] = 'application/jose+json';
|
||||
|
||||
/* Request */
|
||||
log(`HTTP request: ${method} ${url}`);
|
||||
const resp = await axios.request(opts);
|
||||
|
||||
log(`RESP ${resp.status} ${method} ${url}`);
|
||||
return resp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Ensure provider directory exists
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.1.1
|
||||
*
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async getDirectory() {
|
||||
if (!this.directory) {
|
||||
const resp = await this.request(this.directoryUrl, 'get');
|
||||
|
||||
if (resp.status >= 400) {
|
||||
throw new Error(`Attempting to read ACME directory returned error ${resp.status}: ${this.directoryUrl}`);
|
||||
}
|
||||
|
||||
if (!resp.data) {
|
||||
throw new Error('Attempting to read ACME directory returned no data');
|
||||
}
|
||||
|
||||
this.directory = resp.data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get JSON Web Key
|
||||
*
|
||||
* @returns {object} JSON Web Key
|
||||
*/
|
||||
|
||||
getJwk() {
|
||||
if (!this.jwk) {
|
||||
this.jwk = getJwk(this.accountKey);
|
||||
}
|
||||
|
||||
return this.jwk;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get nonce from directory API endpoint
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.2
|
||||
*
|
||||
* @returns {Promise<string>} nonce
|
||||
*/
|
||||
|
||||
async getNonce() {
|
||||
const url = await this.getResourceUrl('newNonce');
|
||||
const resp = await this.request(url, 'head');
|
||||
|
||||
if (!resp.headers['replay-nonce']) {
|
||||
throw new Error('Failed to get nonce from ACME provider');
|
||||
}
|
||||
|
||||
return resp.headers['replay-nonce'];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get URL for a directory resource
|
||||
*
|
||||
* @param {string} resource API resource name
|
||||
* @returns {Promise<string>} URL
|
||||
*/
|
||||
|
||||
async getResourceUrl(resource) {
|
||||
await this.getDirectory();
|
||||
|
||||
if (!this.directory[resource]) {
|
||||
throw new Error(`Unable to locate API resource URL in ACME directory: "${resource}"`);
|
||||
}
|
||||
|
||||
return this.directory[resource];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get directory meta field
|
||||
*
|
||||
* @param {string} field Meta field name
|
||||
* @returns {Promise<string|null>} Meta field value
|
||||
*/
|
||||
|
||||
async getMetaField(field) {
|
||||
await this.getDirectory();
|
||||
|
||||
if (('meta' in this.directory) && (field in this.directory.meta)) {
|
||||
return this.directory.meta[field];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prepare HTTP request body for signature
|
||||
*
|
||||
* @param {string} alg JWS algorithm
|
||||
* @param {string} url Request URL
|
||||
* @param {object} [payload] Request payload
|
||||
* @param {object} [opts]
|
||||
* @param {string} [opts.nonce] JWS anti-replay nonce
|
||||
* @param {string} [opts.kid] JWS KID
|
||||
* @returns {object} Signed HTTP request body
|
||||
*/
|
||||
|
||||
prepareSignedBody(alg, url, payload = null, { nonce = null, kid = null } = {}) {
|
||||
const header = { alg, url };
|
||||
|
||||
/* Nonce */
|
||||
if (nonce) {
|
||||
log(`Using nonce: ${nonce}`);
|
||||
header.nonce = nonce;
|
||||
}
|
||||
|
||||
/* KID or JWK */
|
||||
if (kid) {
|
||||
header.kid = kid;
|
||||
}
|
||||
else {
|
||||
header.jwk = this.getJwk();
|
||||
}
|
||||
|
||||
/* Body */
|
||||
return {
|
||||
payload: payload ? Buffer.from(JSON.stringify(payload)).toString('base64url') : '',
|
||||
protected: Buffer.from(JSON.stringify(header)).toString('base64url')
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create JWS HTTP request body using HMAC
|
||||
*
|
||||
* @param {string} hmacKey HMAC key
|
||||
* @param {string} url Request URL
|
||||
* @param {object} [payload] Request payload
|
||||
* @param {object} [opts]
|
||||
* @param {string} [opts.nonce] JWS anti-replay nonce
|
||||
* @param {string} [opts.kid] JWS KID
|
||||
* @returns {object} Signed HMAC request body
|
||||
*/
|
||||
|
||||
createSignedHmacBody(hmacKey, url, payload = null, { nonce = null, kid = null } = {}) {
|
||||
const result = this.prepareSignedBody('HS256', url, payload, { nonce, kid });
|
||||
|
||||
/* Signature */
|
||||
const signer = createHmac('SHA256', Buffer.from(hmacKey, 'base64')).update(`${result.protected}.${result.payload}`, 'utf8');
|
||||
result.signature = signer.digest().toString('base64url');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create JWS HTTP request body using RSA or ECC
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc7515
|
||||
*
|
||||
* @param {string} url Request URL
|
||||
* @param {object} [payload] Request payload
|
||||
* @param {object} [opts]
|
||||
* @param {string} [opts.nonce] JWS nonce
|
||||
* @param {string} [opts.kid] JWS KID
|
||||
* @returns {object} JWS request body
|
||||
*/
|
||||
|
||||
createSignedBody(url, payload = null, { nonce = null, kid = null } = {}) {
|
||||
const jwk = this.getJwk();
|
||||
let headerAlg = 'RS256';
|
||||
let signerAlg = 'SHA256';
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc7518#section-3.1 */
|
||||
if (jwk.crv && (jwk.kty === 'EC')) {
|
||||
headerAlg = 'ES256';
|
||||
|
||||
if (jwk.crv === 'P-384') {
|
||||
headerAlg = 'ES384';
|
||||
signerAlg = 'SHA384';
|
||||
}
|
||||
else if (jwk.crv === 'P-521') {
|
||||
headerAlg = 'ES512';
|
||||
signerAlg = 'SHA512';
|
||||
}
|
||||
}
|
||||
|
||||
/* Prepare body and signer */
|
||||
const result = this.prepareSignedBody(headerAlg, url, payload, { nonce, kid });
|
||||
const signer = createSign(signerAlg).update(`${result.protected}.${result.payload}`, 'utf8');
|
||||
|
||||
/* Signature - https://stackoverflow.com/questions/39554165 */
|
||||
result.signature = signer.sign({
|
||||
key: this.accountKey,
|
||||
padding: RSA_PKCS1_PADDING,
|
||||
dsaEncoding: 'ieee-p1363'
|
||||
}, 'base64url');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Signed HTTP request
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-6.2
|
||||
*
|
||||
* @param {string} url Request URL
|
||||
* @param {object} payload Request payload
|
||||
* @param {object} [opts]
|
||||
* @param {string} [opts.kid] JWS KID
|
||||
* @param {string} [opts.nonce] JWS anti-replay nonce
|
||||
* @param {boolean} [opts.includeExternalAccountBinding] Include EAB in request
|
||||
* @param {number} [attempts] Request attempt counter
|
||||
* @returns {Promise<object>} HTTP response
|
||||
*/
|
||||
|
||||
async signedRequest(url, payload, { kid = null, nonce = null, includeExternalAccountBinding = false } = {}, attempts = 0) {
|
||||
if (!nonce) {
|
||||
nonce = await this.getNonce();
|
||||
}
|
||||
|
||||
/* External account binding */
|
||||
if (includeExternalAccountBinding && this.externalAccountBinding) {
|
||||
if (this.externalAccountBinding.kid && this.externalAccountBinding.hmacKey) {
|
||||
const jwk = this.getJwk();
|
||||
const eabKid = this.externalAccountBinding.kid;
|
||||
const eabHmacKey = this.externalAccountBinding.hmacKey;
|
||||
|
||||
payload.externalAccountBinding = this.createSignedHmacBody(eabHmacKey, url, jwk, { kid: eabKid });
|
||||
}
|
||||
}
|
||||
|
||||
/* Sign body and send request */
|
||||
const data = this.createSignedBody(url, payload, { nonce, kid });
|
||||
const resp = await this.request(url, 'post', { data });
|
||||
|
||||
/* Retry on bad nonce - https://tools.ietf.org/html/draft-ietf-acme-acme-10#section-6.4 */
|
||||
if (resp.data && resp.data.type && (resp.status === 400) && (resp.data.type === 'urn:ietf:params:acme:error:badNonce') && (attempts < this.maxBadNonceRetries)) {
|
||||
nonce = resp.headers['replay-nonce'] || null;
|
||||
attempts += 1;
|
||||
|
||||
log(`Caught invalid nonce error, retrying (${attempts}/${this.maxBadNonceRetries}) signed request to: ${url}`);
|
||||
return this.signedRequest(url, payload, { kid, nonce, includeExternalAccountBinding }, attempts);
|
||||
}
|
||||
|
||||
/* Return response */
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Export client */
|
||||
module.exports = HttpClient;
|
||||
46
packages/core/acme-client/src/index.js
Normal file
46
packages/core/acme-client/src/index.js
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* acme-client
|
||||
*/
|
||||
|
||||
exports.Client = require('./client');
|
||||
|
||||
|
||||
/**
|
||||
* Directory URLs
|
||||
*/
|
||||
|
||||
exports.directory = {
|
||||
buypass: {
|
||||
staging: 'https://api.test4.buypass.no/acme/directory',
|
||||
production: 'https://api.buypass.com/acme/directory'
|
||||
},
|
||||
letsencrypt: {
|
||||
staging: 'https://acme-staging-v02.api.letsencrypt.org/directory',
|
||||
production: 'https://acme-v02.api.letsencrypt.org/directory'
|
||||
},
|
||||
zerossl: {
|
||||
production: 'https://acme.zerossl.com/v2/DV90'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Crypto
|
||||
*/
|
||||
|
||||
exports.crypto = require('./crypto');
|
||||
exports.forge = require('./crypto/forge');
|
||||
|
||||
|
||||
/**
|
||||
* Axios
|
||||
*/
|
||||
|
||||
exports.axios = require('./axios');
|
||||
|
||||
|
||||
/**
|
||||
* Logger
|
||||
*/
|
||||
|
||||
exports.setLogger = require('./logger').setLogger;
|
||||
30
packages/core/acme-client/src/logger.js
Normal file
30
packages/core/acme-client/src/logger.js
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* ACME logger
|
||||
*/
|
||||
|
||||
const debug = require('debug')('acme-client');
|
||||
|
||||
let logger = () => {};
|
||||
|
||||
|
||||
/**
|
||||
* Set logger function
|
||||
*
|
||||
* @param {function} fn Logger function
|
||||
*/
|
||||
|
||||
exports.setLogger = (fn) => {
|
||||
logger = fn;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Log message
|
||||
*
|
||||
* @param {string} Message
|
||||
*/
|
||||
|
||||
exports.log = (msg) => {
|
||||
debug(msg);
|
||||
logger(msg);
|
||||
};
|
||||
258
packages/core/acme-client/src/util.js
Normal file
258
packages/core/acme-client/src/util.js
Normal file
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* Utility methods
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const { readCertificateInfo, splitPemChain } = require('./crypto');
|
||||
const { log } = require('./logger');
|
||||
|
||||
|
||||
/**
|
||||
* Exponential backoff
|
||||
*
|
||||
* https://github.com/mokesmokes/backo
|
||||
*
|
||||
* @class
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.min] Minimum backoff duration in ms
|
||||
* @param {number} [opts.max] Maximum backoff duration in ms
|
||||
*/
|
||||
|
||||
class Backoff {
|
||||
constructor({ min = 100, max = 10000 } = {}) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
this.attempts = 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get backoff duration
|
||||
*
|
||||
* @returns {number} Backoff duration in ms
|
||||
*/
|
||||
|
||||
duration() {
|
||||
const ms = this.min * (2 ** this.attempts);
|
||||
this.attempts += 1;
|
||||
return Math.min(ms, this.max);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retry promise
|
||||
*
|
||||
* @param {function} fn Function returning promise that should be retried
|
||||
* @param {number} attempts Maximum number of attempts
|
||||
* @param {Backoff} backoff Backoff instance
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async function retryPromise(fn, attempts, backoff) {
|
||||
let aborted = false;
|
||||
|
||||
try {
|
||||
const data = await fn(() => { aborted = true; });
|
||||
return data;
|
||||
}
|
||||
catch (e) {
|
||||
if (aborted || ((backoff.attempts + 1) >= attempts)) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
const duration = backoff.duration();
|
||||
log(`Promise rejected attempt #${backoff.attempts}, retrying in ${duration}ms: ${e.message}`);
|
||||
|
||||
await new Promise((resolve) => { setTimeout(resolve, duration); });
|
||||
return retryPromise(fn, attempts, backoff);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retry promise
|
||||
*
|
||||
* @param {function} fn Function returning promise that should be retried
|
||||
* @param {object} [backoffOpts] Backoff options
|
||||
* @param {number} [backoffOpts.attempts] Maximum number of attempts, default: `5`
|
||||
* @param {number} [backoffOpts.min] Minimum attempt delay in milliseconds, default: `5000`
|
||||
* @param {number} [backoffOpts.max] Maximum attempt delay in milliseconds, default: `30000`
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
function retry(fn, { attempts = 5, min = 5000, max = 30000 } = {}) {
|
||||
const backoff = new Backoff({ min, max });
|
||||
return retryPromise(fn, attempts, backoff);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse URLs from link header
|
||||
*
|
||||
* @param {string} header Link header contents
|
||||
* @param {string} rel Link relation, default: `alternate`
|
||||
* @returns {array} Array of URLs
|
||||
*/
|
||||
|
||||
function parseLinkHeader(header, rel = 'alternate') {
|
||||
const relRe = new RegExp(`\\s*rel\\s*=\\s*"?${rel}"?`, 'i');
|
||||
|
||||
const results = (header || '').split(/,\s*</).map((link) => {
|
||||
const [, linkUrl, linkParts] = link.match(/<?([^>]*)>;(.*)/) || [];
|
||||
return (linkUrl && linkParts && linkParts.match(relRe)) ? linkUrl : null;
|
||||
});
|
||||
|
||||
return results.filter((r) => r);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find certificate chain with preferred issuer common name
|
||||
* - If issuer is found in multiple chains, the closest to root wins
|
||||
* - If issuer can not be located, the first chain will be returned
|
||||
*
|
||||
* @param {array} certificates Array of PEM encoded certificate chains
|
||||
* @param {string} issuer Preferred certificate issuer
|
||||
* @returns {string} PEM encoded certificate chain
|
||||
*/
|
||||
|
||||
function findCertificateChainForIssuer(chains, issuer) {
|
||||
log(`Attempting to find match for issuer="${issuer}" in ${chains.length} certificate chains`);
|
||||
let bestMatch = null;
|
||||
let bestDistance = null;
|
||||
|
||||
chains.forEach((chain) => {
|
||||
/* Look up all issuers */
|
||||
const certs = splitPemChain(chain);
|
||||
const infoCollection = certs.map((c) => readCertificateInfo(c));
|
||||
const issuerCollection = infoCollection.map((i) => i.issuer.commonName);
|
||||
|
||||
/* Found issuer match, get distance from root - lower is better */
|
||||
if (issuerCollection.includes(issuer)) {
|
||||
const distance = (issuerCollection.length - issuerCollection.indexOf(issuer));
|
||||
log(`Found matching chain for preferred issuer="${issuer}" distance=${distance} issuers=${JSON.stringify(issuerCollection)}`);
|
||||
|
||||
/* Chain wins, use it */
|
||||
if (!bestDistance || (distance < bestDistance)) {
|
||||
log(`Issuer is closer to root than previous match, using it (${distance} < ${bestDistance || 'undefined'})`);
|
||||
bestMatch = chain;
|
||||
bestDistance = distance;
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* No match */
|
||||
log(`Unable to match certificate for preferred issuer="${issuer}", issuers=${JSON.stringify(issuerCollection)}`);
|
||||
}
|
||||
});
|
||||
|
||||
/* Return found match */
|
||||
if (bestMatch) {
|
||||
return bestMatch;
|
||||
}
|
||||
|
||||
/* No chains matched, return default */
|
||||
log(`Found no match in ${chains.length} certificate chains for preferred issuer="${issuer}", returning default certificate chain`);
|
||||
return chains[0];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find and format error in response object
|
||||
*
|
||||
* @param {object} resp HTTP response
|
||||
* @returns {string} Error message
|
||||
*/
|
||||
|
||||
function formatResponseError(resp) {
|
||||
let result;
|
||||
|
||||
if (resp.data.error) {
|
||||
result = resp.data.error.detail || resp.data.error;
|
||||
}
|
||||
else {
|
||||
result = resp.data.detail || JSON.stringify(resp.data);
|
||||
}
|
||||
|
||||
return result.replace(/\n/g, '');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Resolve root domain name by looking for SOA record
|
||||
*
|
||||
* @param {string} recordName DNS record name
|
||||
* @returns {Promise<string>} Root domain name
|
||||
*/
|
||||
|
||||
async function resolveDomainBySoaRecord(recordName) {
|
||||
try {
|
||||
await dns.resolveSoa(recordName);
|
||||
log(`Found SOA record, considering domain to be: ${recordName}`);
|
||||
return recordName;
|
||||
}
|
||||
catch (e) {
|
||||
log(`Unable to locate SOA record for name: ${recordName}`);
|
||||
const parentRecordName = recordName.split('.').slice(1).join('.');
|
||||
|
||||
if (!parentRecordName.includes('.')) {
|
||||
throw new Error('Unable to resolve domain by SOA record');
|
||||
}
|
||||
|
||||
return resolveDomainBySoaRecord(parentRecordName);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get DNS resolver using domains authoritative NS records
|
||||
*
|
||||
* @param {string} recordName DNS record name
|
||||
* @returns {Promise<dns.Resolver>} DNS resolver
|
||||
*/
|
||||
|
||||
async function getAuthoritativeDnsResolver(recordName) {
|
||||
log(`Locating authoritative NS records for name: ${recordName}`);
|
||||
const resolver = new dns.Resolver();
|
||||
|
||||
try {
|
||||
/* Resolve root domain by SOA */
|
||||
const domain = await resolveDomainBySoaRecord(recordName);
|
||||
|
||||
/* Resolve authoritative NS addresses */
|
||||
log(`Looking up authoritative NS records for domain: ${domain}`);
|
||||
const nsRecords = await dns.resolveNs(domain);
|
||||
const nsAddrArray = await Promise.all(nsRecords.map(async (r) => dns.resolve4(r)));
|
||||
const nsAddresses = [].concat(...nsAddrArray).filter((a) => a);
|
||||
|
||||
if (!nsAddresses.length) {
|
||||
throw new Error(`Unable to locate any valid authoritative NS addresses for domain: ${domain}`);
|
||||
}
|
||||
|
||||
/* Authoritative NS success */
|
||||
log(`Found ${nsAddresses.length} authoritative NS addresses for domain: ${domain}`);
|
||||
resolver.setServers(nsAddresses);
|
||||
}
|
||||
catch (e) {
|
||||
log(`Authoritative NS lookup error: ${e.message}`);
|
||||
}
|
||||
|
||||
/* Return resolver */
|
||||
const addresses = resolver.getServers();
|
||||
log(`DNS resolver addresses: ${addresses.join(', ')}`);
|
||||
|
||||
return resolver;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Export utils
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
retry,
|
||||
parseLinkHeader,
|
||||
findCertificateChainForIssuer,
|
||||
formatResponseError,
|
||||
getAuthoritativeDnsResolver
|
||||
};
|
||||
127
packages/core/acme-client/src/verify.js
Normal file
127
packages/core/acme-client/src/verify.js
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* ACME challenge verification
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const { log } = require('./logger');
|
||||
const axios = require('./axios');
|
||||
const util = require('./util');
|
||||
|
||||
|
||||
/**
|
||||
* Verify ACME HTTP challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.3
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @param {object} challenge Authorization challenge
|
||||
* @param {string} keyAuthorization Challenge key authorization
|
||||
* @param {string} [suffix] URL suffix
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
|
||||
async function verifyHttpChallenge(authz, challenge, keyAuthorization, suffix = `/.well-known/acme-challenge/${challenge.token}`) {
|
||||
const httpPort = axios.defaults.acmeSettings.httpChallengePort || 80;
|
||||
const challengeUrl = `http://${authz.identifier.value}:${httpPort}${suffix}`;
|
||||
|
||||
log(`Sending HTTP query to ${authz.identifier.value}, suffix: ${suffix}, port: ${httpPort}`);
|
||||
const resp = await axios.get(challengeUrl);
|
||||
const data = (resp.data || '').replace(/\s+$/, '');
|
||||
|
||||
log(`Query successful, HTTP status code: ${resp.status}`);
|
||||
|
||||
if (!data || (data !== keyAuthorization)) {
|
||||
throw new Error(`Authorization not found in HTTP response from ${authz.identifier.value}`);
|
||||
}
|
||||
|
||||
log(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Walk DNS until TXT records are found
|
||||
*/
|
||||
|
||||
async function walkDnsChallengeRecord(recordName, resolver = dns) {
|
||||
/* Resolve CNAME record first */
|
||||
try {
|
||||
log(`Checking name for CNAME records: ${recordName}`);
|
||||
const cnameRecords = await resolver.resolveCname(recordName);
|
||||
|
||||
if (cnameRecords.length) {
|
||||
log(`CNAME record found at ${recordName}, new challenge record name: ${cnameRecords[0]}`);
|
||||
return walkDnsChallengeRecord(cnameRecords[0]);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
log(`No CNAME records found for name: ${recordName}`);
|
||||
}
|
||||
|
||||
/* Resolve TXT records */
|
||||
try {
|
||||
log(`Checking name for TXT records: ${recordName}`);
|
||||
const txtRecords = await resolver.resolveTxt(recordName);
|
||||
|
||||
if (txtRecords.length) {
|
||||
log(`Found ${txtRecords.length} TXT records at ${recordName}`);
|
||||
return [].concat(...txtRecords);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
log(`No TXT records found for name: ${recordName}`);
|
||||
}
|
||||
|
||||
/* Found nothing */
|
||||
throw new Error(`No TXT records found for name: ${recordName}`);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Verify ACME DNS challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.4
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @param {object} challenge Authorization challenge
|
||||
* @param {string} keyAuthorization Challenge key authorization
|
||||
* @param {string} [prefix] DNS prefix
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
|
||||
async function verifyDnsChallenge(authz, challenge, keyAuthorization, prefix = '_acme-challenge.') {
|
||||
let recordValues = [];
|
||||
const recordName = `${prefix}${authz.identifier.value}`;
|
||||
log(`Resolving DNS TXT from record: ${recordName}`);
|
||||
|
||||
try {
|
||||
/* Default DNS resolver first */
|
||||
log('Attempting to resolve TXT with default DNS resolver first');
|
||||
recordValues = await walkDnsChallengeRecord(recordName);
|
||||
}
|
||||
catch (e) {
|
||||
/* Authoritative DNS resolver */
|
||||
log(`Error using default resolver, attempting to resolve TXT with authoritative NS: ${e.message}`);
|
||||
const authoritativeResolver = await util.getAuthoritativeDnsResolver(recordName);
|
||||
recordValues = await walkDnsChallengeRecord(recordName, authoritativeResolver);
|
||||
}
|
||||
|
||||
log(`DNS query finished successfully, found ${recordValues.length} TXT records`);
|
||||
|
||||
if (!recordValues.length || !recordValues.includes(keyAuthorization)) {
|
||||
throw new Error(`Authorization not found in DNS TXT record: ${recordName}`);
|
||||
}
|
||||
|
||||
log(`Key authorization match for ${challenge.type}/${recordName}, ACME challenge verified`);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Export API
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
'http-01': verifyHttpChallenge,
|
||||
'dns-01': verifyDnsChallenge
|
||||
};
|
||||
121
packages/core/acme-client/test/00-pebble.spec.js
Normal file
121
packages/core/acme-client/test/00-pebble.spec.js
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Pebble Challenge Test Server tests
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const { assert } = require('chai');
|
||||
const { v4: uuid } = require('uuid');
|
||||
const cts = require('./challtestsrv');
|
||||
const axios = require('./../src/axios');
|
||||
|
||||
const domainName = process.env.ACME_DOMAIN_NAME || 'example.com';
|
||||
const httpPort = axios.defaults.acmeSettings.httpChallengePort || 80;
|
||||
|
||||
|
||||
describe('pebble', () => {
|
||||
const testAHost = `${uuid()}.${domainName}`;
|
||||
const testARecords = ['1.1.1.1', '2.2.2.2'];
|
||||
const testCnameHost = `${uuid()}.${domainName}`;
|
||||
const testCnameRecord = `${uuid()}.${domainName}`;
|
||||
|
||||
const testHttp01ChallengeHost = `${uuid()}.${domainName}`;
|
||||
const testHttp01ChallengeToken = uuid();
|
||||
const testHttp01ChallengeContent = uuid();
|
||||
const testDns01ChallengeHost = `_acme-challenge.${uuid()}.${domainName}.`;
|
||||
const testDns01ChallengeValue = uuid();
|
||||
|
||||
|
||||
/**
|
||||
* Pebble CTS required
|
||||
*/
|
||||
|
||||
before(function() {
|
||||
if (!cts.isEnabled()) {
|
||||
this.skip();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* DNS mocking
|
||||
*/
|
||||
|
||||
describe('dns', () => {
|
||||
it('should not locate a records', async () => {
|
||||
const resp = await dns.resolve4(testAHost);
|
||||
|
||||
assert.isArray(resp);
|
||||
assert.notDeepEqual(resp, testARecords);
|
||||
});
|
||||
|
||||
it('should add dns a records', async () => {
|
||||
const resp = await cts.addDnsARecord(testAHost, testARecords);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate a records', async () => {
|
||||
const resp = await dns.resolve4(testAHost);
|
||||
|
||||
assert.isArray(resp);
|
||||
assert.deepStrictEqual(resp, testARecords);
|
||||
});
|
||||
|
||||
it('should not locate cname records', async () => {
|
||||
await assert.isRejected(dns.resolveCname(testCnameHost));
|
||||
});
|
||||
|
||||
it('should set dns cname record', async () => {
|
||||
const resp = await cts.setDnsCnameRecord(testCnameHost, testCnameRecord);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate cname record', async () => {
|
||||
const resp = await dns.resolveCname(testCnameHost);
|
||||
|
||||
assert.isArray(resp);
|
||||
assert.deepStrictEqual(resp, [testCnameRecord]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Challenge response
|
||||
*/
|
||||
|
||||
describe('challenges', () => {
|
||||
it('should not locate http-01 challenge response', async () => {
|
||||
const resp = await axios.get(`http://${testHttp01ChallengeHost}:${httpPort}/.well-known/acme-challenge/${testHttp01ChallengeToken}`);
|
||||
|
||||
assert.isString(resp.data);
|
||||
assert.notEqual(resp.data, testHttp01ChallengeContent);
|
||||
});
|
||||
|
||||
it('should add http-01 challenge response', async () => {
|
||||
const resp = await cts.addHttp01ChallengeResponse(testHttp01ChallengeToken, testHttp01ChallengeContent);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate http-01 challenge response', async () => {
|
||||
const resp = await axios.get(`http://${testHttp01ChallengeHost}:${httpPort}/.well-known/acme-challenge/${testHttp01ChallengeToken}`);
|
||||
|
||||
assert.isString(resp.data);
|
||||
assert.strictEqual(resp.data, testHttp01ChallengeContent);
|
||||
});
|
||||
|
||||
it('should not locate dns-01 challenge response', async () => {
|
||||
await assert.isRejected(dns.resolveTxt(testDns01ChallengeHost));
|
||||
});
|
||||
|
||||
it('should add dns-01 challenge response', async () => {
|
||||
const resp = await cts.addDns01ChallengeResponse(testDns01ChallengeHost, testDns01ChallengeValue);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate dns-01 challenge response', async () => {
|
||||
const resp = await dns.resolveTxt(testDns01ChallengeHost);
|
||||
|
||||
assert.isArray(resp);
|
||||
assert.deepStrictEqual(resp, [[testDns01ChallengeValue]]);
|
||||
});
|
||||
});
|
||||
});
|
||||
101
packages/core/acme-client/test/10-http.spec.js
Normal file
101
packages/core/acme-client/test/10-http.spec.js
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* HTTP client tests
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const { v4: uuid } = require('uuid');
|
||||
const nock = require('nock');
|
||||
const axios = require('./../src/axios');
|
||||
const HttpClient = require('./../src/http');
|
||||
const pkg = require('./../package.json');
|
||||
|
||||
|
||||
describe('http', () => {
|
||||
let testClient;
|
||||
|
||||
const defaultUserAgent = `node-${pkg.name}/${pkg.version}`;
|
||||
const customUserAgent = 'custom-ua-123';
|
||||
|
||||
const primaryEndpoint = `http://${uuid()}.example.com`;
|
||||
const defaultUaEndpoint = `http://${uuid()}.example.com`;
|
||||
const customUaEndpoint = `http://${uuid()}.example.com`;
|
||||
|
||||
|
||||
/**
|
||||
* HTTP mocking
|
||||
*/
|
||||
|
||||
before(() => {
|
||||
axios.defaults.acmeSettings.bypassCustomDnsResolver = true;
|
||||
|
||||
const defaultUaOpts = { reqheaders: { 'User-Agent': defaultUserAgent } };
|
||||
const customUaOpts = { reqheaders: { 'User-Agent': customUserAgent } };
|
||||
|
||||
nock(primaryEndpoint)
|
||||
.persist().get('/').reply(200, 'ok');
|
||||
|
||||
nock(defaultUaEndpoint, defaultUaOpts)
|
||||
.persist().get('/').reply(200, 'ok');
|
||||
|
||||
nock(customUaEndpoint, customUaOpts)
|
||||
.persist().get('/').reply(200, 'ok');
|
||||
});
|
||||
|
||||
after(() => {
|
||||
axios.defaults.headers.common['User-Agent'] = defaultUserAgent;
|
||||
axios.defaults.acmeSettings.bypassCustomDnsResolver = false;
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
|
||||
it('should initialize clients', () => {
|
||||
testClient = new HttpClient();
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* HTTP verbs
|
||||
*/
|
||||
|
||||
it('should http get', async () => {
|
||||
const resp = await testClient.request(primaryEndpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* User-Agent
|
||||
*/
|
||||
|
||||
it('should request using default user-agent', async () => {
|
||||
const resp = await testClient.request(defaultUaEndpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
it('should not request using custom user-agent', async () => {
|
||||
await assert.isRejected(testClient.request(customUaEndpoint, 'get'));
|
||||
});
|
||||
|
||||
it('should request using custom user-agent', async () => {
|
||||
axios.defaults.headers.common['User-Agent'] = customUserAgent;
|
||||
const resp = await testClient.request(customUaEndpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
it('should not request using default user-agent', async () => {
|
||||
axios.defaults.headers.common['User-Agent'] = customUserAgent;
|
||||
await assert.isRejected(testClient.request(defaultUaEndpoint, 'get'));
|
||||
});
|
||||
});
|
||||
35
packages/core/acme-client/test/10-logger.spec.js
Normal file
35
packages/core/acme-client/test/10-logger.spec.js
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Logger tests
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const logger = require('./../src/logger');
|
||||
|
||||
|
||||
describe('logger', () => {
|
||||
let lastLogMessage = null;
|
||||
|
||||
function customLoggerFn(msg) {
|
||||
lastLogMessage = msg;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Logger
|
||||
*/
|
||||
|
||||
it('should log without custom logger', () => {
|
||||
logger.log('something');
|
||||
assert.isNull(lastLogMessage);
|
||||
});
|
||||
|
||||
|
||||
it('should log with custom logger', () => {
|
||||
logger.setLogger(customLoggerFn);
|
||||
|
||||
['abc123', 'def456', 'ghi789'].forEach((m) => {
|
||||
logger.log(m);
|
||||
assert.strictEqual(lastLogMessage, m);
|
||||
});
|
||||
});
|
||||
});
|
||||
106
packages/core/acme-client/test/10-verify.spec.js
Normal file
106
packages/core/acme-client/test/10-verify.spec.js
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Challenge verification tests
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const { v4: uuid } = require('uuid');
|
||||
const cts = require('./challtestsrv');
|
||||
const verify = require('./../src/verify');
|
||||
|
||||
const domainName = process.env.ACME_DOMAIN_NAME || 'example.com';
|
||||
|
||||
|
||||
describe('verify', () => {
|
||||
const challengeTypes = ['http-01', 'dns-01'];
|
||||
|
||||
const testHttp01Authz = { identifier: { type: 'dns', value: `${uuid()}.${domainName}` } };
|
||||
const testHttp01Challenge = { type: 'http-01', status: 'pending', token: uuid() };
|
||||
const testHttp01Key = uuid();
|
||||
|
||||
const testDns01Authz = { identifier: { type: 'dns', value: `${uuid()}.${domainName}` } };
|
||||
const testDns01Challenge = { type: 'dns-01', status: 'pending', token: uuid() };
|
||||
const testDns01Key = uuid();
|
||||
const testDns01Cname = `${uuid()}.${domainName}`;
|
||||
|
||||
|
||||
/**
|
||||
* Pebble CTS required
|
||||
*/
|
||||
|
||||
before(function() {
|
||||
if (!cts.isEnabled()) {
|
||||
this.skip();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* API
|
||||
*/
|
||||
|
||||
it('should expose verification api', async () => {
|
||||
assert.containsAllKeys(verify, challengeTypes);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* http-01
|
||||
*/
|
||||
|
||||
describe('http-01', () => {
|
||||
it('should reject challenge', async () => {
|
||||
await assert.isRejected(verify['http-01'](testHttp01Authz, testHttp01Challenge, testHttp01Key));
|
||||
});
|
||||
|
||||
it('should mock challenge response', async () => {
|
||||
const resp = await cts.addHttp01ChallengeResponse(testHttp01Challenge.token, testHttp01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge', async () => {
|
||||
const resp = await verify['http-01'](testHttp01Authz, testHttp01Challenge, testHttp01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should mock challenge response with trailing newline', async () => {
|
||||
const resp = await cts.addHttp01ChallengeResponse(testHttp01Challenge.token, `${testHttp01Key}\n`);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge with trailing newline', async () => {
|
||||
const resp = await verify['http-01'](testHttp01Authz, testHttp01Challenge, testHttp01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* dns-01
|
||||
*/
|
||||
|
||||
describe('dns-01', () => {
|
||||
it('should reject challenge', async () => {
|
||||
await assert.isRejected(verify['dns-01'](testDns01Authz, testDns01Challenge, testDns01Key));
|
||||
});
|
||||
|
||||
it('should mock challenge response', async () => {
|
||||
const resp = await cts.addDns01ChallengeResponse(`_acme-challenge.${testDns01Authz.identifier.value}.`, testDns01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should add cname to challenge response', async () => {
|
||||
const resp = await cts.setDnsCnameRecord(testDns01Cname, `_acme-challenge.${testDns01Authz.identifier.value}.`);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge', async () => {
|
||||
const resp = await verify['dns-01'](testDns01Authz, testDns01Challenge, testDns01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge using cname', async () => {
|
||||
const resp = await verify['dns-01'](testDns01Authz, testDns01Challenge, testDns01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
});
|
||||
});
|
||||
276
packages/core/acme-client/test/20-crypto-legacy.spec.js
Normal file
276
packages/core/acme-client/test/20-crypto-legacy.spec.js
Normal file
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* Legacy crypto tests
|
||||
*/
|
||||
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { assert } = require('chai');
|
||||
const spec = require('./spec');
|
||||
const forge = require('./../src/crypto/forge');
|
||||
|
||||
const cryptoEngines = {
|
||||
forge
|
||||
};
|
||||
|
||||
|
||||
describe('crypto-legacy', () => {
|
||||
let testPemKey;
|
||||
let testCert;
|
||||
let testSanCert;
|
||||
|
||||
const modulusStore = [];
|
||||
const exponentStore = [];
|
||||
const publicKeyStore = [];
|
||||
|
||||
const testCsrDomain = 'example.com';
|
||||
const testSanCsrDomains = ['example.com', 'test.example.com', 'abc.example.com'];
|
||||
const testKeyPath = path.join(__dirname, 'fixtures', 'private.key');
|
||||
const testCertPath = path.join(__dirname, 'fixtures', 'certificate.crt');
|
||||
const testSanCertPath = path.join(__dirname, 'fixtures', 'san-certificate.crt');
|
||||
|
||||
|
||||
/**
|
||||
* Fixtures
|
||||
*/
|
||||
|
||||
describe('fixtures', () => {
|
||||
it('should read private key fixture', async () => {
|
||||
testPemKey = await fs.readFile(testKeyPath);
|
||||
assert.isTrue(Buffer.isBuffer(testPemKey));
|
||||
});
|
||||
|
||||
it('should read certificate fixture', async () => {
|
||||
testCert = await fs.readFile(testCertPath);
|
||||
assert.isTrue(Buffer.isBuffer(testCert));
|
||||
});
|
||||
|
||||
it('should read san certificate fixture', async () => {
|
||||
testSanCert = await fs.readFile(testSanCertPath);
|
||||
assert.isTrue(Buffer.isBuffer(testSanCert));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Engines
|
||||
*/
|
||||
|
||||
Object.entries(cryptoEngines).forEach(([name, engine]) => {
|
||||
describe(`engine/${name}`, () => {
|
||||
let testCsr;
|
||||
let testSanCsr;
|
||||
let testNonCnCsr;
|
||||
let testNonAsciiCsr;
|
||||
|
||||
|
||||
/**
|
||||
* Key generation
|
||||
*/
|
||||
|
||||
it('should generate a private key', async () => {
|
||||
const key = await engine.createPrivateKey();
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
});
|
||||
|
||||
it('should generate a private key with size=1024', async () => {
|
||||
const key = await engine.createPrivateKey(1024);
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
});
|
||||
|
||||
it('should generate a public key', async () => {
|
||||
const key = await engine.createPublicKey(testPemKey);
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
publicKeyStore.push(key.toString().replace(/[\r\n]/gm, ''));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Certificate Signing Request
|
||||
*/
|
||||
|
||||
it('should generate a csr', async () => {
|
||||
const [key, csr] = await engine.createCsr({
|
||||
commonName: testCsrDomain
|
||||
});
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testCsr = csr;
|
||||
});
|
||||
|
||||
it('should generate a san csr', async () => {
|
||||
const [key, csr] = await engine.createCsr({
|
||||
commonName: testSanCsrDomains[0],
|
||||
altNames: testSanCsrDomains.slice(1, testSanCsrDomains.length)
|
||||
});
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testSanCsr = csr;
|
||||
});
|
||||
|
||||
it('should generate a csr without common name', async () => {
|
||||
const [key, csr] = await engine.createCsr({
|
||||
altNames: testSanCsrDomains
|
||||
});
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testNonCnCsr = csr;
|
||||
});
|
||||
|
||||
it('should generate a non-ascii csr', async () => {
|
||||
const [key, csr] = await engine.createCsr({
|
||||
commonName: testCsrDomain,
|
||||
organization: '大安區',
|
||||
organizationUnit: '中文部門'
|
||||
});
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testNonAsciiCsr = csr;
|
||||
});
|
||||
|
||||
it('should resolve domains from csr', async () => {
|
||||
const result = await engine.readCsrDomains(testCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testCsrDomain);
|
||||
assert.deepStrictEqual(result.altNames, [testCsrDomain]);
|
||||
});
|
||||
|
||||
it('should resolve domains from san csr', async () => {
|
||||
const result = await engine.readCsrDomains(testSanCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testSanCsrDomains[0]);
|
||||
assert.deepStrictEqual(result.altNames, testSanCsrDomains);
|
||||
});
|
||||
|
||||
it('should resolve domains from san without common name', async () => {
|
||||
const result = await engine.readCsrDomains(testNonCnCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.isNull(result.commonName);
|
||||
assert.deepStrictEqual(result.altNames, testSanCsrDomains);
|
||||
});
|
||||
|
||||
it('should resolve domains from non-ascii csr', async () => {
|
||||
const result = await engine.readCsrDomains(testNonAsciiCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testCsrDomain);
|
||||
assert.deepStrictEqual(result.altNames, [testCsrDomain]);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Certificate
|
||||
*/
|
||||
|
||||
it('should read info from certificate', async () => {
|
||||
const info = await engine.readCertificateInfo(testCert);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testCsrDomain);
|
||||
assert.strictEqual(info.domains.altNames.length, 0);
|
||||
});
|
||||
|
||||
it('should read info from san certificate', async () => {
|
||||
const info = await engine.readCertificateInfo(testSanCert);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testSanCsrDomains[0]);
|
||||
assert.deepEqual(info.domains.altNames, testSanCsrDomains.slice(1, testSanCsrDomains.length));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* PEM utils
|
||||
*/
|
||||
|
||||
it('should get pem body', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const body = engine.getPemBody(pem);
|
||||
|
||||
assert.isString(body);
|
||||
assert.notInclude(body, '\r');
|
||||
assert.notInclude(body, '\n');
|
||||
assert.notInclude(body, '\r\n');
|
||||
});
|
||||
});
|
||||
|
||||
it('should split pem chain', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const chain = engine.splitPemChain(pem);
|
||||
|
||||
assert.isArray(chain);
|
||||
assert.isNotEmpty(chain);
|
||||
chain.forEach((c) => assert.isString(c));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Modulus and exponent
|
||||
*/
|
||||
|
||||
it('should get modulus', async () => {
|
||||
const result = await Promise.all([testPemKey, testCert, testSanCert].map(async (item) => {
|
||||
const mod = await engine.getModulus(item);
|
||||
assert.isTrue(Buffer.isBuffer(mod));
|
||||
|
||||
return mod;
|
||||
}));
|
||||
|
||||
modulusStore.push(result);
|
||||
});
|
||||
|
||||
it('should get public exponent', async () => {
|
||||
const result = await Promise.all([testPemKey, testCert, testSanCert].map(async (item) => {
|
||||
const exp = await engine.getPublicExponent(item);
|
||||
assert.isTrue(Buffer.isBuffer(exp));
|
||||
|
||||
const b64exp = exp.toString('base64');
|
||||
assert.strictEqual(b64exp, 'AQAB');
|
||||
|
||||
return b64exp;
|
||||
}));
|
||||
|
||||
exponentStore.push(result);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Verify identical results
|
||||
*/
|
||||
|
||||
describe('verification', () => {
|
||||
it('should have identical public keys', () => {
|
||||
if (publicKeyStore.length > 1) {
|
||||
const reference = publicKeyStore.shift();
|
||||
publicKeyStore.forEach((item) => assert.strictEqual(reference, item));
|
||||
}
|
||||
});
|
||||
|
||||
it('should have identical moduli', () => {
|
||||
if (modulusStore.length > 1) {
|
||||
const reference = modulusStore.shift();
|
||||
modulusStore.forEach((item) => assert.deepStrictEqual(reference, item));
|
||||
}
|
||||
});
|
||||
|
||||
it('should have identical public exponents', () => {
|
||||
if (exponentStore.length > 1) {
|
||||
const reference = exponentStore.shift();
|
||||
exponentStore.forEach((item) => assert.deepStrictEqual(reference, item));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
317
packages/core/acme-client/test/20-crypto.spec.js
Normal file
317
packages/core/acme-client/test/20-crypto.spec.js
Normal file
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* Crypto tests
|
||||
*/
|
||||
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { assert } = require('chai');
|
||||
const spec = require('./spec');
|
||||
const { crypto } = require('./../');
|
||||
|
||||
const emptyBodyChain1 = `
|
||||
-----BEGIN TEST-----
|
||||
a
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
b
|
||||
-----END TEST-----
|
||||
|
||||
-----BEGIN TEST-----
|
||||
|
||||
-----END TEST-----
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
c
|
||||
-----END TEST-----
|
||||
`;
|
||||
|
||||
const emptyBodyChain2 = `
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
|
||||
|
||||
|
||||
-----END TEST-----
|
||||
|
||||
-----BEGIN TEST-----
|
||||
a
|
||||
-----END TEST-----
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
b
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
c
|
||||
-----END TEST-----
|
||||
`;
|
||||
|
||||
|
||||
describe('crypto', () => {
|
||||
const testCsrDomain = 'example.com';
|
||||
const testSanCsrDomains = ['example.com', 'test.example.com', 'abc.example.com'];
|
||||
const testKeyPath = path.join(__dirname, 'fixtures', 'private.key');
|
||||
const testCertPath = path.join(__dirname, 'fixtures', 'certificate.crt');
|
||||
const testSanCertPath = path.join(__dirname, 'fixtures', 'san-certificate.crt');
|
||||
|
||||
|
||||
/**
|
||||
* Key types
|
||||
*/
|
||||
|
||||
Object.entries({
|
||||
rsa: {
|
||||
createKeyFns: {
|
||||
s1024: () => crypto.createPrivateRsaKey(1024),
|
||||
s2048: () => crypto.createPrivateRsaKey(),
|
||||
s4096: () => crypto.createPrivateRsaKey(4096)
|
||||
},
|
||||
jwkSpecFn: spec.jwk.rsa
|
||||
},
|
||||
ecdsa: {
|
||||
createKeyFns: {
|
||||
p256: () => crypto.createPrivateEcdsaKey(),
|
||||
p384: () => crypto.createPrivateEcdsaKey('P-384'),
|
||||
p521: () => crypto.createPrivateEcdsaKey('P-521')
|
||||
},
|
||||
jwkSpecFn: spec.jwk.ecdsa
|
||||
}
|
||||
}).forEach(([name, { createKeyFns, jwkSpecFn }]) => {
|
||||
describe(name, () => {
|
||||
const testPrivateKeys = {};
|
||||
const testPublicKeys = {};
|
||||
|
||||
|
||||
/**
|
||||
* Iterate through all generator variations
|
||||
*/
|
||||
|
||||
Object.entries(createKeyFns).forEach(([n, createFn]) => {
|
||||
let testCsr;
|
||||
let testSanCsr;
|
||||
let testNonCnCsr;
|
||||
let testNonAsciiCsr;
|
||||
|
||||
|
||||
/**
|
||||
* Keys and JWK
|
||||
*/
|
||||
|
||||
it(`${n}/should generate private key`, async () => {
|
||||
testPrivateKeys[n] = await createFn();
|
||||
assert.isTrue(Buffer.isBuffer(testPrivateKeys[n]));
|
||||
});
|
||||
|
||||
it(`${n}/should get public key`, () => {
|
||||
testPublicKeys[n] = crypto.getPublicKey(testPrivateKeys[n]);
|
||||
assert.isTrue(Buffer.isBuffer(testPublicKeys[n]));
|
||||
});
|
||||
|
||||
it(`${n}/should get jwk from private key`, () => {
|
||||
const jwk = crypto.getJwk(testPrivateKeys[n]);
|
||||
jwkSpecFn(jwk);
|
||||
});
|
||||
|
||||
it(`${n}/should get jwk from public key`, () => {
|
||||
const jwk = crypto.getJwk(testPublicKeys[n]);
|
||||
jwkSpecFn(jwk);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Certificate Signing Request
|
||||
*/
|
||||
|
||||
it(`${n}/should generate a csr`, async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
commonName: testCsrDomain
|
||||
}, testPrivateKeys[n]);
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testCsr = csr;
|
||||
});
|
||||
|
||||
it(`${n}/should generate a san csr`, async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
commonName: testSanCsrDomains[0],
|
||||
altNames: testSanCsrDomains.slice(1, testSanCsrDomains.length)
|
||||
}, testPrivateKeys[n]);
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testSanCsr = csr;
|
||||
});
|
||||
|
||||
it(`${n}/should generate a csr without common name`, async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
altNames: testSanCsrDomains
|
||||
}, testPrivateKeys[n]);
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testNonCnCsr = csr;
|
||||
});
|
||||
|
||||
it(`${n}/should generate a non-ascii csr`, async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
commonName: testCsrDomain,
|
||||
organization: '大安區',
|
||||
organizationUnit: '中文部門'
|
||||
}, testPrivateKeys[n]);
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
|
||||
testNonAsciiCsr = csr;
|
||||
});
|
||||
|
||||
it(`${n}/should throw with invalid key`, async () => {
|
||||
await assert.isRejected(crypto.createCsr({
|
||||
commonName: testCsrDomain
|
||||
}, testPublicKeys[n]));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Domain and info resolver
|
||||
*/
|
||||
|
||||
it(`${n}/should resolve domains from csr`, () => {
|
||||
const result = crypto.readCsrDomains(testCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testCsrDomain);
|
||||
assert.deepStrictEqual(result.altNames, [testCsrDomain]);
|
||||
});
|
||||
|
||||
it(`${n}/should resolve domains from san csr`, () => {
|
||||
const result = crypto.readCsrDomains(testSanCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testSanCsrDomains[0]);
|
||||
assert.deepStrictEqual(result.altNames, testSanCsrDomains);
|
||||
});
|
||||
|
||||
it(`${n}/should resolve domains from csr without common name`, () => {
|
||||
const result = crypto.readCsrDomains(testNonCnCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.isNull(result.commonName);
|
||||
assert.deepStrictEqual(result.altNames, testSanCsrDomains);
|
||||
});
|
||||
|
||||
it(`${n}/should resolve domains from non-ascii csr`, () => {
|
||||
const result = crypto.readCsrDomains(testNonAsciiCsr);
|
||||
|
||||
spec.crypto.csrDomains(result);
|
||||
assert.strictEqual(result.commonName, testCsrDomain);
|
||||
assert.deepStrictEqual(result.altNames, [testCsrDomain]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Common functionality
|
||||
*/
|
||||
|
||||
describe('common', () => {
|
||||
let testPemKey;
|
||||
let testCert;
|
||||
let testSanCert;
|
||||
|
||||
|
||||
it('should read private key fixture', async () => {
|
||||
testPemKey = await fs.readFile(testKeyPath);
|
||||
assert.isTrue(Buffer.isBuffer(testPemKey));
|
||||
});
|
||||
|
||||
it('should read certificate fixture', async () => {
|
||||
testCert = await fs.readFile(testCertPath);
|
||||
assert.isTrue(Buffer.isBuffer(testCert));
|
||||
});
|
||||
|
||||
it('should read san certificate fixture', async () => {
|
||||
testSanCert = await fs.readFile(testSanCertPath);
|
||||
assert.isTrue(Buffer.isBuffer(testSanCert));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* CSR with auto-generated key
|
||||
*/
|
||||
|
||||
it('should generate a csr with auto-generated key', async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
commonName: testCsrDomain
|
||||
});
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(csr));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Certificate
|
||||
*/
|
||||
|
||||
it('should read certificate info', () => {
|
||||
const info = crypto.readCertificateInfo(testCert);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testCsrDomain);
|
||||
assert.strictEqual(info.domains.altNames.length, 0);
|
||||
});
|
||||
|
||||
it('should read certificate info with san', () => {
|
||||
const info = crypto.readCertificateInfo(testSanCert);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testSanCsrDomains[0]);
|
||||
assert.deepEqual(info.domains.altNames, testSanCsrDomains.slice(1, testSanCsrDomains.length));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* PEM utils
|
||||
*/
|
||||
|
||||
it('should get pem body as b64u', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const body = crypto.getPemBodyAsB64u(pem);
|
||||
|
||||
assert.isString(body);
|
||||
assert.notInclude(body, '\r');
|
||||
assert.notInclude(body, '\n');
|
||||
assert.notInclude(body, '\r\n');
|
||||
});
|
||||
});
|
||||
|
||||
it('should split pem chain', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const chain = crypto.splitPemChain(pem);
|
||||
|
||||
assert.isArray(chain);
|
||||
assert.isNotEmpty(chain);
|
||||
chain.forEach((c) => assert.isString(c));
|
||||
});
|
||||
});
|
||||
|
||||
it('should split pem chain with empty bodies', () => {
|
||||
const c1 = crypto.splitPemChain(emptyBodyChain1);
|
||||
const c2 = crypto.splitPemChain(emptyBodyChain2);
|
||||
|
||||
assert.strictEqual(c1.length, 3);
|
||||
assert.strictEqual(c2.length, 3);
|
||||
});
|
||||
});
|
||||
});
|
||||
574
packages/core/acme-client/test/50-client.spec.js
Normal file
574
packages/core/acme-client/test/50-client.spec.js
Normal file
@@ -0,0 +1,574 @@
|
||||
/**
|
||||
* ACME client tests
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const { v4: uuid } = require('uuid');
|
||||
const cts = require('./challtestsrv');
|
||||
const getCertIssuers = require('./get-cert-issuers');
|
||||
const spec = require('./spec');
|
||||
const acme = require('./../');
|
||||
|
||||
const domainName = process.env.ACME_DOMAIN_NAME || 'example.com';
|
||||
const directoryUrl = process.env.ACME_DIRECTORY_URL || acme.directory.letsencrypt.staging;
|
||||
const capEabEnabled = (('ACME_CAP_EAB_ENABLED' in process.env) && (process.env.ACME_CAP_EAB_ENABLED === '1'));
|
||||
const capMetaTosField = !(('ACME_CAP_META_TOS_FIELD' in process.env) && (process.env.ACME_CAP_META_TOS_FIELD === '0'));
|
||||
const capUpdateAccountKey = !(('ACME_CAP_UPDATE_ACCOUNT_KEY' in process.env) && (process.env.ACME_CAP_UPDATE_ACCOUNT_KEY === '0'));
|
||||
const capAlternateCertRoots = !(('ACME_CAP_ALTERNATE_CERT_ROOTS' in process.env) && (process.env.ACME_CAP_ALTERNATE_CERT_ROOTS === '0'));
|
||||
|
||||
const clientOpts = {
|
||||
directoryUrl,
|
||||
backoffAttempts: 5,
|
||||
backoffMin: 1000,
|
||||
backoffMax: 5000
|
||||
};
|
||||
|
||||
if (capEabEnabled && process.env.ACME_EAB_KID && process.env.ACME_EAB_HMAC_KEY) {
|
||||
clientOpts.externalAccountBinding = {
|
||||
kid: process.env.ACME_EAB_KID,
|
||||
hmacKey: process.env.ACME_EAB_HMAC_KEY
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
describe('client', () => {
|
||||
const testDomain = `${uuid()}.${domainName}`;
|
||||
const testDomainWildcard = `*.${testDomain}`;
|
||||
const testContact = `mailto:test-${uuid()}@nope.com`;
|
||||
|
||||
|
||||
/**
|
||||
* Pebble CTS required
|
||||
*/
|
||||
|
||||
before(function() {
|
||||
if (!cts.isEnabled()) {
|
||||
this.skip();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Key types
|
||||
*/
|
||||
|
||||
Object.entries({
|
||||
rsa: {
|
||||
createKeyFn: () => acme.crypto.createPrivateRsaKey(),
|
||||
createKeyAltFns: {
|
||||
s1024: () => acme.crypto.createPrivateRsaKey(1024),
|
||||
s4096: () => acme.crypto.createPrivateRsaKey(4096)
|
||||
},
|
||||
jwkSpecFn: spec.jwk.rsa
|
||||
},
|
||||
ecdsa: {
|
||||
createKeyFn: () => acme.crypto.createPrivateEcdsaKey(),
|
||||
createKeyAltFns: {
|
||||
p384: () => acme.crypto.createPrivateEcdsaKey('P-384'),
|
||||
p521: () => acme.crypto.createPrivateEcdsaKey('P-521')
|
||||
},
|
||||
jwkSpecFn: spec.jwk.ecdsa
|
||||
}
|
||||
}).forEach(([name, { createKeyFn, createKeyAltFns, jwkSpecFn }]) => {
|
||||
describe(name, () => {
|
||||
let testIssuers;
|
||||
let testAccountKey;
|
||||
let testAccountSecondaryKey;
|
||||
let testClient;
|
||||
let testAccount;
|
||||
let testAccountUrl;
|
||||
let testOrder;
|
||||
let testOrderWildcard;
|
||||
let testAuthz;
|
||||
let testAuthzWildcard;
|
||||
let testChallenge;
|
||||
let testChallengeWildcard;
|
||||
let testKeyAuthorization;
|
||||
let testKeyAuthorizationWildcard;
|
||||
let testCsr;
|
||||
let testCsrWildcard;
|
||||
let testCertificate;
|
||||
let testCertificateWildcard;
|
||||
|
||||
|
||||
/**
|
||||
* Fixtures
|
||||
*/
|
||||
|
||||
it('should generate a private key', async () => {
|
||||
testAccountKey = await createKeyFn();
|
||||
assert.isTrue(Buffer.isBuffer(testAccountKey));
|
||||
});
|
||||
|
||||
it('should create a second private key', async () => {
|
||||
testAccountSecondaryKey = await createKeyFn();
|
||||
assert.isTrue(Buffer.isBuffer(testAccountSecondaryKey));
|
||||
});
|
||||
|
||||
it('should generate certificate signing request', async () => {
|
||||
[, testCsr] = await acme.crypto.createCsr({ commonName: testDomain }, await createKeyFn());
|
||||
[, testCsrWildcard] = await acme.crypto.createCsr({ commonName: testDomainWildcard }, await createKeyFn());
|
||||
});
|
||||
|
||||
it('should resolve certificate issuers [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
testIssuers = await getCertIssuers();
|
||||
|
||||
assert.isArray(testIssuers);
|
||||
assert.isTrue(testIssuers.length > 1);
|
||||
|
||||
testIssuers.forEach((i) => {
|
||||
assert.isString(i);
|
||||
assert.strictEqual(1, testIssuers.filter((c) => (c === i)).length);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Initialize clients
|
||||
*/
|
||||
|
||||
it('should initialize client', () => {
|
||||
testClient = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountKey
|
||||
});
|
||||
});
|
||||
|
||||
it('should produce a valid jwk', () => {
|
||||
const jwk = testClient.http.getJwk();
|
||||
jwkSpecFn(jwk);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Terms of Service
|
||||
*/
|
||||
|
||||
it('should produce tos url [ACME_CAP_META_TOS_FIELD]', async function() {
|
||||
if (!capMetaTosField) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const tos = await testClient.getTermsOfServiceUrl();
|
||||
assert.isString(tos);
|
||||
});
|
||||
|
||||
it('should not produce tos url [!ACME_CAP_META_TOS_FIELD]', async function() {
|
||||
if (capMetaTosField) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const tos = await testClient.getTermsOfServiceUrl();
|
||||
assert.isNull(tos);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Create account
|
||||
*/
|
||||
|
||||
it('should refuse account creation without tos [ACME_CAP_META_TOS_FIELD]', async function() {
|
||||
if (!capMetaTosField) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
await assert.isRejected(testClient.createAccount());
|
||||
});
|
||||
|
||||
it('should refuse account creation without eab [ACME_CAP_EAB_ENABLED]', async function() {
|
||||
if (!capEabEnabled) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountKey,
|
||||
externalAccountBinding: null
|
||||
});
|
||||
|
||||
await assert.isRejected(client.createAccount({
|
||||
termsOfServiceAgreed: true
|
||||
}));
|
||||
});
|
||||
|
||||
it('should create an account', async () => {
|
||||
testAccount = await testClient.createAccount({
|
||||
termsOfServiceAgreed: true
|
||||
});
|
||||
|
||||
spec.rfc8555.account(testAccount);
|
||||
assert.strictEqual(testAccount.status, 'valid');
|
||||
});
|
||||
|
||||
it('should produce an account url', () => {
|
||||
testAccountUrl = testClient.getAccountUrl();
|
||||
assert.isString(testAccountUrl);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Create account with alternate key sizes
|
||||
*/
|
||||
|
||||
Object.entries(createKeyAltFns).forEach(([k, altKeyFn]) => {
|
||||
it(`should create account with key=${k}`, async () => {
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: await altKeyFn()
|
||||
});
|
||||
|
||||
const account = await client.createAccount({
|
||||
termsOfServiceAgreed: true
|
||||
});
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'valid');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Find existing account using secondary client
|
||||
*/
|
||||
|
||||
it('should throw when trying to find account using invalid account key', async () => {
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountSecondaryKey
|
||||
});
|
||||
|
||||
await assert.isRejected(client.createAccount({
|
||||
onlyReturnExisting: true
|
||||
}));
|
||||
});
|
||||
|
||||
it('should find existing account using account key', async () => {
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountKey
|
||||
});
|
||||
|
||||
const account = await client.createAccount({
|
||||
onlyReturnExisting: true
|
||||
});
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'valid');
|
||||
assert.deepStrictEqual(account.key, testAccount.key);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Account URL
|
||||
*/
|
||||
|
||||
it('should refuse invalid account url', async () => {
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountKey,
|
||||
accountUrl: 'https://acme-staging-v02.api.letsencrypt.org/acme/acct/1'
|
||||
});
|
||||
|
||||
await assert.isRejected(client.updateAccount());
|
||||
});
|
||||
|
||||
it('should find existing account using account url', async () => {
|
||||
const client = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: testAccountKey,
|
||||
accountUrl: testAccountUrl
|
||||
});
|
||||
|
||||
const account = await client.createAccount({
|
||||
onlyReturnExisting: true
|
||||
});
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'valid');
|
||||
assert.deepStrictEqual(account.key, testAccount.key);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Update account contact info
|
||||
*/
|
||||
|
||||
it('should update account contact info', async () => {
|
||||
const data = { contact: [testContact] };
|
||||
const account = await testClient.updateAccount(data);
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'valid');
|
||||
assert.deepStrictEqual(account.key, testAccount.key);
|
||||
assert.isArray(account.contact);
|
||||
assert.include(account.contact, testContact);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Change account private key
|
||||
*/
|
||||
|
||||
it('should change account private key [ACME_CAP_UPDATE_ACCOUNT_KEY]', async function() {
|
||||
if (!capUpdateAccountKey) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
await testClient.updateAccountKey(testAccountSecondaryKey);
|
||||
|
||||
const account = await testClient.createAccount({
|
||||
onlyReturnExisting: true
|
||||
});
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'valid');
|
||||
assert.notDeepEqual(account.key, testAccount.key);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Create new certificate order
|
||||
*/
|
||||
|
||||
it('should create new order', async () => {
|
||||
const data1 = { identifiers: [{ type: 'dns', value: testDomain }] };
|
||||
const data2 = { identifiers: [{ type: 'dns', value: testDomainWildcard }] };
|
||||
|
||||
testOrder = await testClient.createOrder(data1);
|
||||
testOrderWildcard = await testClient.createOrder(data2);
|
||||
|
||||
[testOrder, testOrderWildcard].forEach((item) => {
|
||||
spec.rfc8555.order(item);
|
||||
assert.strictEqual(item.status, 'pending');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Get status of existing certificate order
|
||||
*/
|
||||
|
||||
it('should get existing order', async () => {
|
||||
await Promise.all([testOrder, testOrderWildcard].map(async (existing) => {
|
||||
const result = await testClient.getOrder(existing);
|
||||
|
||||
spec.rfc8555.order(result);
|
||||
assert.deepStrictEqual(existing, result);
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Get identifier authorization
|
||||
*/
|
||||
|
||||
it('should get identifier authorization', async () => {
|
||||
const orderAuthzCollection = await testClient.getAuthorizations(testOrder);
|
||||
const wildcardAuthzCollection = await testClient.getAuthorizations(testOrderWildcard);
|
||||
|
||||
[orderAuthzCollection, wildcardAuthzCollection].forEach((collection) => {
|
||||
assert.isArray(collection);
|
||||
assert.isNotEmpty(collection);
|
||||
|
||||
collection.forEach((authz) => {
|
||||
spec.rfc8555.authorization(authz);
|
||||
assert.strictEqual(authz.status, 'pending');
|
||||
});
|
||||
});
|
||||
|
||||
testAuthz = orderAuthzCollection.pop();
|
||||
testAuthzWildcard = wildcardAuthzCollection.pop();
|
||||
|
||||
testAuthz.challenges.concat(testAuthzWildcard.challenges).forEach((item) => {
|
||||
spec.rfc8555.challenge(item);
|
||||
assert.strictEqual(item.status, 'pending');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Generate challenge key authorization
|
||||
*/
|
||||
|
||||
it('should get challenge key authorization', async () => {
|
||||
testChallenge = testAuthz.challenges.find((c) => (c.type === 'http-01'));
|
||||
testChallengeWildcard = testAuthzWildcard.challenges.find((c) => (c.type === 'dns-01'));
|
||||
|
||||
testKeyAuthorization = await testClient.getChallengeKeyAuthorization(testChallenge);
|
||||
testKeyAuthorizationWildcard = await testClient.getChallengeKeyAuthorization(testChallengeWildcard);
|
||||
|
||||
[testKeyAuthorization, testKeyAuthorizationWildcard].forEach((k) => assert.isString(k));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Deactivate identifier authorization
|
||||
*/
|
||||
|
||||
it('should deactivate identifier authorization', async () => {
|
||||
const order = await testClient.createOrder({
|
||||
identifiers: [
|
||||
{ type: 'dns', value: `${uuid()}.${domainName}` },
|
||||
{ type: 'dns', value: `${uuid()}.${domainName}` }
|
||||
]
|
||||
});
|
||||
|
||||
const authzCollection = await testClient.getAuthorizations(order);
|
||||
|
||||
const results = await Promise.all(authzCollection.map(async (authz) => {
|
||||
spec.rfc8555.authorization(authz);
|
||||
assert.strictEqual(authz.status, 'pending');
|
||||
return testClient.deactivateAuthorization(authz);
|
||||
}));
|
||||
|
||||
results.forEach((authz) => {
|
||||
spec.rfc8555.authorization(authz);
|
||||
assert.strictEqual(authz.status, 'deactivated');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Verify satisfied challenge
|
||||
*/
|
||||
|
||||
it('should verify challenge', async () => {
|
||||
await cts.assertHttpChallengeCreateFn(testAuthz, testChallenge, testKeyAuthorization);
|
||||
await cts.assertDnsChallengeCreateFn(testAuthzWildcard, testChallengeWildcard, testKeyAuthorizationWildcard);
|
||||
|
||||
await testClient.verifyChallenge(testAuthz, testChallenge);
|
||||
await testClient.verifyChallenge(testAuthzWildcard, testChallengeWildcard);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Complete challenge
|
||||
*/
|
||||
|
||||
it('should complete challenge', async () => {
|
||||
await Promise.all([testChallenge, testChallengeWildcard].map(async (challenge) => {
|
||||
const result = await testClient.completeChallenge(challenge);
|
||||
|
||||
spec.rfc8555.challenge(result);
|
||||
assert.strictEqual(challenge.url, result.url);
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Wait for valid challenge
|
||||
*/
|
||||
|
||||
it('should wait for valid challenge status', async () => {
|
||||
await Promise.all([testChallenge, testChallengeWildcard].map(async (c) => testClient.waitForValidStatus(c)));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Finalize order
|
||||
*/
|
||||
|
||||
it('should finalize order', async () => {
|
||||
const finalize = await testClient.finalizeOrder(testOrder, testCsr);
|
||||
const finalizeWildcard = await testClient.finalizeOrder(testOrderWildcard, testCsrWildcard);
|
||||
|
||||
[finalize, finalizeWildcard].forEach((f) => spec.rfc8555.order(f));
|
||||
|
||||
assert.strictEqual(testOrder.url, finalize.url);
|
||||
assert.strictEqual(testOrderWildcard.url, finalizeWildcard.url);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Wait for valid order
|
||||
*/
|
||||
|
||||
it('should wait for valid order status', async () => {
|
||||
await Promise.all([testOrder, testOrderWildcard].map(async (o) => testClient.waitForValidStatus(o)));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Get certificate
|
||||
*/
|
||||
|
||||
it('should get certificate', async () => {
|
||||
testCertificate = await testClient.getCertificate(testOrder);
|
||||
testCertificateWildcard = await testClient.getCertificate(testOrderWildcard);
|
||||
|
||||
[testCertificate, testCertificateWildcard].forEach((cert) => {
|
||||
assert.isString(cert);
|
||||
acme.crypto.readCertificateInfo(cert);
|
||||
});
|
||||
});
|
||||
|
||||
it('should get alternate certificate chain [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
await Promise.all(testIssuers.map(async (issuer) => {
|
||||
const cert = await testClient.getCertificate(testOrder, issuer);
|
||||
const rootCert = acme.crypto.splitPemChain(cert).pop();
|
||||
const info = acme.crypto.readCertificateInfo(rootCert);
|
||||
|
||||
assert.strictEqual(issuer, info.issuer.commonName);
|
||||
}));
|
||||
});
|
||||
|
||||
it('should get default chain with invalid preference [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const cert = await testClient.getCertificate(testOrder, uuid());
|
||||
const rootCert = acme.crypto.splitPemChain(cert).pop();
|
||||
const info = acme.crypto.readCertificateInfo(rootCert);
|
||||
|
||||
assert.strictEqual(testIssuers[0], info.issuer.commonName);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Revoke certificate
|
||||
*/
|
||||
|
||||
it('should revoke certificate', async () => {
|
||||
await testClient.revokeCertificate(testCertificate);
|
||||
await testClient.revokeCertificate(testCertificateWildcard, { reason: 4 });
|
||||
});
|
||||
|
||||
it('should not allow getting revoked certificate', async () => {
|
||||
await assert.isRejected(testClient.getCertificate(testOrder));
|
||||
await assert.isRejected(testClient.getCertificate(testOrderWildcard));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Deactivate account
|
||||
*/
|
||||
|
||||
it('should deactivate account', async () => {
|
||||
const data = { status: 'deactivated' };
|
||||
const account = await testClient.updateAccount(data);
|
||||
|
||||
spec.rfc8555.account(account);
|
||||
assert.strictEqual(account.status, 'deactivated');
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Verify that no new orders can be made
|
||||
*/
|
||||
|
||||
it('should not allow new orders from deactivated account', async () => {
|
||||
const data = { identifiers: [{ type: 'dns', value: 'nope.com' }] };
|
||||
await assert.isRejected(testClient.createOrder(data));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
384
packages/core/acme-client/test/70-auto.spec.js
Normal file
384
packages/core/acme-client/test/70-auto.spec.js
Normal file
@@ -0,0 +1,384 @@
|
||||
/**
|
||||
* ACME client.auto tests
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const { v4: uuid } = require('uuid');
|
||||
const cts = require('./challtestsrv');
|
||||
const getCertIssuers = require('./get-cert-issuers');
|
||||
const spec = require('./spec');
|
||||
const acme = require('./../');
|
||||
|
||||
const domainName = process.env.ACME_DOMAIN_NAME || 'example.com';
|
||||
const directoryUrl = process.env.ACME_DIRECTORY_URL || acme.directory.letsencrypt.staging;
|
||||
const capEabEnabled = (('ACME_CAP_EAB_ENABLED' in process.env) && (process.env.ACME_CAP_EAB_ENABLED === '1'));
|
||||
const capAlternateCertRoots = !(('ACME_CAP_ALTERNATE_CERT_ROOTS' in process.env) && (process.env.ACME_CAP_ALTERNATE_CERT_ROOTS === '0'));
|
||||
|
||||
const clientOpts = {
|
||||
directoryUrl,
|
||||
backoffAttempts: 5,
|
||||
backoffMin: 1000,
|
||||
backoffMax: 5000
|
||||
};
|
||||
|
||||
if (capEabEnabled && process.env.ACME_EAB_KID && process.env.ACME_EAB_HMAC_KEY) {
|
||||
clientOpts.externalAccountBinding = {
|
||||
kid: process.env.ACME_EAB_KID,
|
||||
hmacKey: process.env.ACME_EAB_HMAC_KEY
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
describe('client.auto', () => {
|
||||
const testDomain = `${uuid()}.${domainName}`;
|
||||
const testHttpDomain = `${uuid()}.${domainName}`;
|
||||
const testDnsDomain = `${uuid()}.${domainName}`;
|
||||
const testWildcardDomain = `${uuid()}.${domainName}`;
|
||||
|
||||
const testSanDomains = [
|
||||
`${uuid()}.${domainName}`,
|
||||
`${uuid()}.${domainName}`,
|
||||
`${uuid()}.${domainName}`
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Pebble CTS required
|
||||
*/
|
||||
|
||||
before(function() {
|
||||
if (!cts.isEnabled()) {
|
||||
this.skip();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Key types
|
||||
*/
|
||||
|
||||
Object.entries({
|
||||
rsa: {
|
||||
createKeyFn: () => acme.crypto.createPrivateRsaKey(),
|
||||
createKeyAltFns: {
|
||||
s1024: () => acme.crypto.createPrivateRsaKey(1024),
|
||||
s4096: () => acme.crypto.createPrivateRsaKey(4096)
|
||||
}
|
||||
},
|
||||
ecdsa: {
|
||||
createKeyFn: () => acme.crypto.createPrivateEcdsaKey(),
|
||||
createKeyAltFns: {
|
||||
p384: () => acme.crypto.createPrivateEcdsaKey('P-384'),
|
||||
p521: () => acme.crypto.createPrivateEcdsaKey('P-521')
|
||||
}
|
||||
}
|
||||
}).forEach(([name, { createKeyFn, createKeyAltFns }]) => {
|
||||
describe(name, () => {
|
||||
let testIssuers;
|
||||
let testClient;
|
||||
let testCertificate;
|
||||
let testSanCertificate;
|
||||
let testWildcardCertificate;
|
||||
|
||||
|
||||
/**
|
||||
* Fixtures
|
||||
*/
|
||||
|
||||
it('should resolve certificate issuers [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
testIssuers = await getCertIssuers();
|
||||
|
||||
assert.isArray(testIssuers);
|
||||
assert.isTrue(testIssuers.length > 1);
|
||||
|
||||
testIssuers.forEach((i) => {
|
||||
assert.isString(i);
|
||||
assert.strictEqual(1, testIssuers.filter((c) => (c === i)).length);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Initialize client
|
||||
*/
|
||||
|
||||
it('should initialize client', async () => {
|
||||
testClient = new acme.Client({
|
||||
...clientOpts,
|
||||
accountKey: await createKeyFn()
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Invalid challenge response
|
||||
*/
|
||||
|
||||
it('should throw on invalid challenge response', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
await assert.isRejected(testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeNoopFn,
|
||||
challengeRemoveFn: cts.challengeNoopFn
|
||||
}), /^authorization not found/i);
|
||||
});
|
||||
|
||||
it('should throw on invalid challenge response with opts.skipChallengeVerification=true', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
await assert.isRejected(testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
skipChallengeVerification: true,
|
||||
challengeCreateFn: cts.challengeNoopFn,
|
||||
challengeRemoveFn: cts.challengeNoopFn
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Challenge function exceptions
|
||||
*/
|
||||
|
||||
it('should throw on challengeCreate exception', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
await assert.isRejected(testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeThrowFn,
|
||||
challengeRemoveFn: cts.challengeNoopFn
|
||||
}), /^oops$/);
|
||||
});
|
||||
|
||||
it('should not throw on challengeRemove exception', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeThrowFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Order certificates
|
||||
*/
|
||||
|
||||
it('should order certificate', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testDomain
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
testCertificate = cert;
|
||||
});
|
||||
|
||||
it('should order certificate using http-01', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testHttpDomain
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.assertHttpChallengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn,
|
||||
challengePriority: ['http-01']
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
|
||||
it('should order certificate using dns-01', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testDnsDomain
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.assertDnsChallengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn,
|
||||
challengePriority: ['dns-01']
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
|
||||
it('should order san certificate', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testSanDomains[0],
|
||||
altNames: testSanDomains
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
testSanCertificate = cert;
|
||||
});
|
||||
|
||||
it('should order wildcard certificate', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testWildcardDomain,
|
||||
altNames: [`*.${testWildcardDomain}`]
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
testWildcardCertificate = cert;
|
||||
});
|
||||
|
||||
it('should order certificate with opts.skipChallengeVerification=true', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
skipChallengeVerification: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
|
||||
it('should order alternate certificate chain [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
await Promise.all(testIssuers.map(async (issuer) => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
preferredChain: issuer,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
const rootCert = acme.crypto.splitPemChain(cert).pop();
|
||||
const info = acme.crypto.readCertificateInfo(rootCert);
|
||||
|
||||
assert.strictEqual(issuer, info.issuer.commonName);
|
||||
}));
|
||||
});
|
||||
|
||||
it('should get default chain with invalid preference [ACME_CAP_ALTERNATE_CERT_ROOTS]', async function() {
|
||||
if (!capAlternateCertRoots) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
preferredChain: uuid(),
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
const rootCert = acme.crypto.splitPemChain(cert).pop();
|
||||
const info = acme.crypto.readCertificateInfo(rootCert);
|
||||
|
||||
assert.strictEqual(testIssuers[0], info.issuer.commonName);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Order certificate with alternate key sizes
|
||||
*/
|
||||
|
||||
Object.entries(createKeyAltFns).forEach(([k, altKeyFn]) => {
|
||||
it(`should order certificate with key=${k}`, async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testDomain
|
||||
}, await altKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.challengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Read certificates
|
||||
*/
|
||||
|
||||
it('should read certificate info', () => {
|
||||
const info = acme.crypto.readCertificateInfo(testCertificate);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testDomain);
|
||||
assert.deepStrictEqual(info.domains.altNames, [testDomain]);
|
||||
});
|
||||
|
||||
it('should read san certificate info', () => {
|
||||
const info = acme.crypto.readCertificateInfo(testSanCertificate);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testSanDomains[0]);
|
||||
assert.deepStrictEqual(info.domains.altNames, testSanDomains);
|
||||
});
|
||||
|
||||
it('should read wildcard certificate info', () => {
|
||||
const info = acme.crypto.readCertificateInfo(testWildcardCertificate);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.strictEqual(info.domains.commonName, testWildcardDomain);
|
||||
assert.deepStrictEqual(info.domains.altNames, [testWildcardDomain, `*.${testWildcardDomain}`]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
93
packages/core/acme-client/test/challtestsrv.js
Normal file
93
packages/core/acme-client/test/challtestsrv.js
Normal file
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Pebble Challenge Test Server integration
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const axios = require('./../src/axios');
|
||||
|
||||
const apiBaseUrl = process.env.ACME_CHALLTESTSRV_URL || null;
|
||||
|
||||
|
||||
/**
|
||||
* Send request
|
||||
*/
|
||||
|
||||
async function request(apiPath, data = {}) {
|
||||
if (!apiBaseUrl) {
|
||||
throw new Error('No Pebble Challenge Test Server URL found');
|
||||
}
|
||||
|
||||
await axios.request({
|
||||
url: `${apiBaseUrl}/${apiPath}`,
|
||||
method: 'post',
|
||||
data
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* State
|
||||
*/
|
||||
|
||||
exports.isEnabled = () => !!apiBaseUrl;
|
||||
|
||||
|
||||
/**
|
||||
* DNS
|
||||
*/
|
||||
|
||||
exports.addDnsARecord = async (host, addresses) => request('add-a', { host, addresses });
|
||||
exports.setDnsCnameRecord = async (host, target) => request('set-cname', { host, target });
|
||||
|
||||
|
||||
/**
|
||||
* Challenge response
|
||||
*/
|
||||
|
||||
async function addHttp01ChallengeResponse(token, content) {
|
||||
return request('add-http01', { token, content });
|
||||
}
|
||||
|
||||
async function addDns01ChallengeResponse(host, value) {
|
||||
return request('set-txt', { host, value });
|
||||
}
|
||||
|
||||
exports.addHttp01ChallengeResponse = addHttp01ChallengeResponse;
|
||||
exports.addDns01ChallengeResponse = addDns01ChallengeResponse;
|
||||
|
||||
|
||||
/**
|
||||
* Challenge response mock functions
|
||||
*/
|
||||
|
||||
async function assertHttpChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'http-01');
|
||||
return addHttp01ChallengeResponse(challenge.token, keyAuthorization);
|
||||
}
|
||||
|
||||
async function assertDnsChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'dns-01');
|
||||
return addDns01ChallengeResponse(`_acme-challenge.${authz.identifier.value}.`, keyAuthorization);
|
||||
}
|
||||
|
||||
async function challengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
if (challenge.type === 'http-01') {
|
||||
return assertHttpChallengeCreateFn(authz, challenge, keyAuthorization);
|
||||
}
|
||||
|
||||
if (challenge.type === 'dns-01') {
|
||||
return assertDnsChallengeCreateFn(authz, challenge, keyAuthorization);
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported challenge type ${challenge.type}`);
|
||||
}
|
||||
|
||||
exports.challengeRemoveFn = async () => true;
|
||||
exports.challengeNoopFn = async () => true;
|
||||
exports.challengeThrowFn = async () => { throw new Error('oops'); };
|
||||
|
||||
exports.assertHttpChallengeCreateFn = assertHttpChallengeCreateFn;
|
||||
exports.assertDnsChallengeCreateFn = assertDnsChallengeCreateFn;
|
||||
exports.challengeCreateFn = challengeCreateFn;
|
||||
30
packages/core/acme-client/test/fixtures/certificate.crt
vendored
Normal file
30
packages/core/acme-client/test/fixtures/certificate.crt
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIFMjCCAxoCCQCVordquLnq8TANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQGEwJB
|
||||
VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0
|
||||
cyBQdHkgTHRkMRQwEgYDVQQDEwtleGFtcGxlLmNvbTAeFw0xNzA5MTQxNDMzMTRa
|
||||
Fw0xODA5MTQxNDMzMTRaMFsxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0
|
||||
YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxFDASBgNVBAMT
|
||||
C2V4YW1wbGUuY29tMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwi2P
|
||||
YBNGl1n78niRGDKgcsWK03TcTeVbQ1HztA57Rr1iDHAZNx3Mv4E/Sha8VKbKoshc
|
||||
mUcOS3AlmbIZX+7+9c7lL2oD+vtUZF1YUR/69fWuO72wk6fKj/eofxH9Ud5KFje8
|
||||
qrYZdJWKkPMdWlYgjD6qpA5wl60NiuxmUr44ADZDytqHzNThN3wrFruz74PcMfak
|
||||
cSUMxkh98LuNeGtqHpEAw+wliko3oDD4PanvDvp5mRgiQVKHEGT7dm85Up+W1iJK
|
||||
J65fkc/j940MaLbdISZYYCT5dtPgCGKCHgVuVrY+OXFJrD3TTm94ILsR/BkS/VSK
|
||||
NigGVPXg3q8tgIS++k13CzLUO0PNRMuod1RD9j5NEc2CVic9rcH06ugZyHlOcuVv
|
||||
vRsPGd52BPn+Jf1aePKPPQHxT9i5GOs80CJw0eduZCDZB32biRYNwUtjFkHbu8ii
|
||||
2IGkvhnWonjd4w5wOldG+RPr+XoFCIaHp5TszQ+HnUTLIXKtBgzzCKjK4eZqrck7
|
||||
xpo5B5m5V7EUxBze2LYVky+GsDsqL8CggQqJL4ZKuZVoxgPwhnDy5nMs057NCU9E
|
||||
nXcauMW9UEqEHu5NXnmGJrCvQ56wjYN3lgvCHEtmIpsRjCCWaBJYiawu1J5ZAf1y
|
||||
GTVNh8pEvO//zL9ImUxrSfOGUeFiN1tzSFlTfbcCAwEAATANBgkqhkiG9w0BAQUF
|
||||
AAOCAgEAdZZpgWv79CgF5ny6HmMaYgsXJKJyQE9RhJ1cmzDY8KAF+nzT7q4Pgt3W
|
||||
bA9bpdji7C0WqKjX7hLipqhgFnqb8qZcodEKhX788qBj4X45+4nT6QipyJlz5x6K
|
||||
cCn/v9gQNKks7U+dBlqquiVfbXaa1EAKMeGtqinf+Y51nR/fBcr/P9TBnSJqH61K
|
||||
DO3qrE5KGTwHQ9VXoeKyeppGt5sYf8G0vwoHhtPTOO8TuLEIlFcXtzbC3zAtmQj6
|
||||
Su//fI5yjuYTkiayxMx8nCGrQhQSXdC8gYpYd0os7UY01DVu4BTCXEvf0GYXtiGJ
|
||||
eG8lQT/eu7WdK83uJ93U/BMYzoq4lSVcqY4LNxlfAQXKhaAbioA5XyT7co7FQ0g+
|
||||
s2CGBUKa11wPDe8M2GVLPsxT2bXDQap5DQyVIuTwjtgL0tykGxPJPAnL2zuUy6T3
|
||||
/YzrWaJ9Os+6mUCVdLnXtDgZ10Ujel7mq6wo9Ns+u07grXZkXpmJYnJXBrwOsY8K
|
||||
Za5vFwgJrDXhWe+Fmgt1EP5VIqRCQAxH2iYvAaELi8udbN/ZiUU3K9t79MP/M3U/
|
||||
tEWAubHXsaAv03jRy43X0VjlZHmagU/4dU7RBWfyuwRarYIXLNT2FCd2z4kd3fsL
|
||||
3rB5iI+RH0uoNuOa1+UApfFCv0O65TYkp5jEWSlU8PhKYD43nXA=
|
||||
-----END CERTIFICATE-----
|
||||
27
packages/core/acme-client/test/fixtures/private.key
vendored
Normal file
27
packages/core/acme-client/test/fixtures/private.key
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEAo0nBEFBeo2XnR1kx0jV00W9EszE5Ei/zuJKLXXwTeUGMhy9h
|
||||
CqPFWQnTOD5PQUcja98p96LCdRZpfsfoL1RewksD6BCJN+9hZucImBASpmg2M432
|
||||
wsF7fa3/FMtICrEmQh+LJ48zOottr93YcipY1fNxHWzFr8Hvv+OZCMmQvL4W5u5U
|
||||
rxdi7jptbAbFvv470TN8lpVwneG7kG3cemPhW6RmfTTUQ2Qp/QP6fptpWIIy5kQe
|
||||
zvgpql2xRPBjqb4VDy1kVTTCe/Lpt7bNGe2eZOzXJcjrU+d5LEOrfQoX5ZO4H5UC
|
||||
9YlT6wqyPv9VZ5g2slz198LGV8hdGEVix8XPiQIDAQABAoIBAQCaoo4jVPlK5IZS
|
||||
GzYDTHyEmksFJ+hUQPUeJim1LnuCqYDbxRKxcMbDu3o8GUYVG7l/vqePzKM7Hy5o
|
||||
0gggSlYyybe5XW+VeS1UthZ9azs+PBKYYCj/5xt7ufuHRbvD5F/G3vh5TjPFjaUi
|
||||
l4UTGOdoNlM4+nl8KL1Ti8axe7GGCztxmjJL7VnN4RWc5yzBrU6oiQED0BM/6KFx
|
||||
nJHPuwzRemRRjz8Lk1ryMsCymtZx70slxVJeHPdoMc9vkseOulooBMZtXqOixoHO
|
||||
UtFuKGgIkg6KA9qI+8RmqSPUeXrbrPeRZtu3N9NcsPUYVptNo1ZjLpa9Eigd0tkq
|
||||
1+/TyGDBAoGBANCnK/+uXIZWt4QoF+7AUGeckOmRAbJnWf8KrScSa/TSGNObGP00
|
||||
LpeM10eNDqvfY9RepM6RH5R75vDWltJd4+fyQPaHqG4AhlMk1JglZn71F91FWstx
|
||||
K/qrPfnBQP7qq4yuQ0zavPkgIUWzryLk0JnQ4wPNLiXFAfQYDt+F8Vg3AoGBAMhX
|
||||
S+sej87zRHbV/wj7zLa/QwnDLiU7wswv9zUf2Ot+49pfwEzzSGuLHFHoIXVrGo2y
|
||||
QQl6sovJ6dFi7GFPikiwj9em/EF4JgTmWZhoYH1HmThTUeziLa2/VT4eIZn7Viwb
|
||||
/goxKAvGvHkcdQIeNPPFaEi0m7vDkTAv/WG/prY/AoGAcKWwVWuXPFfY4BqdQSLG
|
||||
xgl7Gv5UgjLWHaFv9iY17oj3KlcT2K+xb9Rz7Yc0IoqKZP9rzrH+8LUr616PMqfK
|
||||
AVGCzRZUUn8qBf1eYX3fpi9AYQ+ugyNocP6+iPZS1s1vLJZwcy+s0nsMO4tUxGvw
|
||||
SvrBdS3y+iUwds3+SaMQt2UCgYAg0BuBIPpQ3QtDo30oDYXUELN8L9mpA4a+RsTo
|
||||
kJTIzXmoVLJ8aAReiORUjf6c6rPorV91nAEOYD3Jq7gnoA14JmMI4TLDzlf7yXa3
|
||||
PbFAE7AGx67Na6YrpQDjMbAzNjVA+Dy9kpuKgjxwYbbQZ/4oRxbzgZFYSYnIKLQJ
|
||||
hIhbpQKBgEc8fYYc3UqyNIGNupYBZhb0pF7FPMwldzv4UufMjkYzKREaCT2D3HIC
|
||||
FEKiJxatIhOtCW5oa5sXK/mGR9EEzW1ltlljymu0u+slIoWvWWGfQU9DxFBnZ2x5
|
||||
4/nzeq4zI+qYt8qXZTnhY/bpZI0pdQqWT9+AoFJJn8Bfdk1mLuIs
|
||||
-----END RSA PRIVATE KEY-----
|
||||
18
packages/core/acme-client/test/fixtures/san-certificate.crt
vendored
Normal file
18
packages/core/acme-client/test/fixtures/san-certificate.crt
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIC3zCCAcegAwIBAgIJAPZkD9qD+FX8MA0GCSqGSIb3DQEBBQUAMBYxFDASBgNV
|
||||
BAMMC2V4YW1wbGUuY29tMB4XDTE3MDkyMTIwMzY1MFoXDTE4MDkyMTIwMzY1MFow
|
||||
FjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
|
||||
ggEKAoIBAQDNygRzPEyGP90Q3ms1DzUIj597u4t22TU08TQywMTt+/Sd+LNDvgwI
|
||||
yhCbbwetVq+rvEayAMaQjFzqgoQOxY8GDrrqfPfQ50ED79vu5VPaqVSTN5FwK7hq
|
||||
6Bl+kT2MUMIwhhGTfrn7inGhxB1hhYtAaUJDuLN2JjB6Ax9BfVv5NJLPeN1V6qdV
|
||||
edtmNrUV5eWwEPfl4kCJ8Ytes6YttN2UDnet/B19po3/JEdy5YgPmeAfW1wbA+kl
|
||||
oU475uPpKPV79M+6hrKNlS2hPFcGOiL/7glKgXURg7Ih+e53Qx6tgqKrgmjRM8Jq
|
||||
0bLwM1+xY0O/2C9wbkpElBLU9CKS9I+PAgMBAAGjMDAuMCwGA1UdEQQlMCOCEHRl
|
||||
c3QuZXhhbXBsZS5jb22CD2FiYy5leGFtcGxlLmNvbTANBgkqhkiG9w0BAQUFAAOC
|
||||
AQEAGCVsiJZOe0LVYQ40a/N/PaVVs1zj1KXmVDrKEWW8fhjEMao/j/Bb4rXuKCkC
|
||||
DQIZR1jsFC4IWyL4eOpUp4SPFn6kbdzhxjl+42kuzQLqTc1EiEobwEbroQSoUJpT
|
||||
xj2j0YnrFn/9hVBHUgsA3tONNXL5McEtiHOQ+iXUmoPw9sRvs0DEshS1XeYvTuzY
|
||||
Jua6uev1QBXxll3+pw7i2Wbt9ifeX6NBe+MOGIYxn6aMwwmgtoLbxDMThtVJJGCH
|
||||
V0JrSBhEkVlfK1LukSUeSO1RpCsV+97Xx2jEsNwbiji/xKnXk44sVJhJ/yQnWkiC
|
||||
wZLUm/SNOOtPT68U5RopRC0IXA==
|
||||
-----END CERTIFICATE-----
|
||||
40
packages/core/acme-client/test/get-cert-issuers.js
Normal file
40
packages/core/acme-client/test/get-cert-issuers.js
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Get ACME certificate issuers
|
||||
*/
|
||||
|
||||
const acme = require('./../');
|
||||
const util = require('./../src/util');
|
||||
|
||||
const pebbleManagementUrl = process.env.ACME_PEBBLE_MANAGEMENT_URL || null;
|
||||
|
||||
|
||||
/**
|
||||
* Pebble
|
||||
*/
|
||||
|
||||
async function getPebbleCertIssuers() {
|
||||
/* Get intermediate certificate and resolve alternates */
|
||||
const root = await acme.axios.get(`${pebbleManagementUrl}/intermediates/0`);
|
||||
const links = util.parseLinkHeader(root.headers.link || '');
|
||||
const alternates = await Promise.all(links.map(async (link) => acme.axios.get(link)));
|
||||
|
||||
/* Get certificate info */
|
||||
const certs = [root].concat(alternates).map((c) => c.data);
|
||||
const info = certs.map((c) => acme.crypto.readCertificateInfo(c));
|
||||
|
||||
/* Return issuers */
|
||||
return info.map((i) => i.issuer.commonName);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get certificate issuers
|
||||
*/
|
||||
|
||||
module.exports = async () => {
|
||||
if (pebbleManagementUrl) {
|
||||
return getPebbleCertIssuers();
|
||||
}
|
||||
|
||||
throw new Error('Unable to resolve list of certificate issuers');
|
||||
};
|
||||
59
packages/core/acme-client/test/retry.js
Normal file
59
packages/core/acme-client/test/retry.js
Normal file
@@ -0,0 +1,59 @@
|
||||
const { assert } = require('chai');
|
||||
const Promise = require('bluebird');
|
||||
const util = require('../src/util');
|
||||
|
||||
let count = 0;
|
||||
async function apiRequest() {
|
||||
count += 1;
|
||||
console.log(new Date(), 'retry count:', count);
|
||||
await Promise.delay(2000);
|
||||
return count;
|
||||
}
|
||||
|
||||
async function waitForValidStatus() {
|
||||
const verifyFn = async (abort) => {
|
||||
const resp = await apiRequest();
|
||||
|
||||
/* Verify status */
|
||||
console.log(new Date(), 'Item has status', resp);
|
||||
if (count < 3) {
|
||||
abort();
|
||||
throw new Error(`${new Date()}error`, count);
|
||||
}
|
||||
|
||||
console.log(new Date(), 'success');
|
||||
return 'success';
|
||||
|
||||
// if (resp.data.status === 'invalid') {
|
||||
// abort();
|
||||
// throw new Error(util.formatResponseError(resp));
|
||||
// }
|
||||
// else if (resp.data.status === 'pending') {
|
||||
// throw new Error('Operation is pending');
|
||||
// }
|
||||
// else if (resp.data.status === 'valid') {
|
||||
// return resp.data;
|
||||
// }
|
||||
//
|
||||
// throw new Error(`Unexpected item status: ${resp.data.status}`);
|
||||
};
|
||||
|
||||
console.log(new Date(), 'Waiting for valid status from', this.backoffOpts);
|
||||
return util.retry(verifyFn, this.backoffOpts);
|
||||
}
|
||||
/**
|
||||
*/
|
||||
describe('util', () => {
|
||||
it('retry', async function() {
|
||||
this.timeout(100000);
|
||||
try {
|
||||
await waitForValidStatus();
|
||||
}
|
||||
catch (e) {
|
||||
console.error('1111', e);
|
||||
}
|
||||
|
||||
|
||||
// await Promise.delay(100000);
|
||||
});
|
||||
});
|
||||
87
packages/core/acme-client/test/setup.js
Normal file
87
packages/core/acme-client/test/setup.js
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Setup testing
|
||||
*/
|
||||
|
||||
const url = require('url');
|
||||
const net = require('net');
|
||||
const fs = require('fs');
|
||||
const dns = require('dns').promises;
|
||||
const chai = require('chai');
|
||||
const chaiAsPromised = require('chai-as-promised');
|
||||
const axios = require('./../src/axios');
|
||||
|
||||
|
||||
/**
|
||||
* Add promise support to Chai
|
||||
*/
|
||||
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
|
||||
/**
|
||||
* HTTP challenge port
|
||||
*/
|
||||
|
||||
if (process.env.ACME_HTTP_PORT) {
|
||||
axios.defaults.acmeSettings.httpChallengePort = process.env.ACME_HTTP_PORT;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* External account binding
|
||||
*/
|
||||
|
||||
if (('ACME_CAP_EAB_ENABLED' in process.env) && (process.env.ACME_CAP_EAB_ENABLED === '1')) {
|
||||
const pebbleConfig = JSON.parse(fs.readFileSync('/etc/pebble/pebble.json').toString());
|
||||
const [kid, hmacKey] = Object.entries(pebbleConfig.pebble.externalAccountMACKeys)[0];
|
||||
|
||||
process.env.ACME_EAB_KID = kid;
|
||||
process.env.ACME_EAB_HMAC_KEY = hmacKey;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Custom DNS resolver
|
||||
*/
|
||||
|
||||
if (process.env.ACME_DNS_RESOLVER) {
|
||||
dns.setServers([process.env.ACME_DNS_RESOLVER]);
|
||||
|
||||
|
||||
/**
|
||||
* Axios DNS resolver
|
||||
*/
|
||||
|
||||
axios.interceptors.request.use(async (config) => {
|
||||
const urlObj = url.parse(config.url);
|
||||
|
||||
/* Bypass */
|
||||
if (axios.defaults.acmeSettings.bypassCustomDnsResolver === true) {
|
||||
return config;
|
||||
}
|
||||
|
||||
/* Skip IP addresses and localhost */
|
||||
if (net.isIP(urlObj.hostname) || (urlObj.hostname === 'localhost')) {
|
||||
return config;
|
||||
}
|
||||
|
||||
/* Lookup hostname */
|
||||
const result = await dns.resolve4(urlObj.hostname);
|
||||
|
||||
if (!result.length) {
|
||||
throw new Error(`Unable to lookup address: ${urlObj.hostname}`);
|
||||
}
|
||||
|
||||
/* Place hostname in header */
|
||||
config.headers = config.headers || {};
|
||||
config.headers.Host = urlObj.hostname;
|
||||
|
||||
/* Inject address into URL */
|
||||
delete urlObj.host;
|
||||
urlObj.hostname = result[0];
|
||||
config.url = url.format(urlObj);
|
||||
|
||||
/* Done */
|
||||
return config;
|
||||
});
|
||||
}
|
||||
178
packages/core/acme-client/test/spec.js
Normal file
178
packages/core/acme-client/test/spec.js
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Assertions
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
|
||||
const spec = {};
|
||||
module.exports = spec;
|
||||
|
||||
|
||||
/**
|
||||
* ACME
|
||||
*/
|
||||
|
||||
spec.rfc8555 = {};
|
||||
|
||||
spec.rfc8555.account = (obj) => {
|
||||
assert.isObject(obj);
|
||||
|
||||
assert.isString(obj.status);
|
||||
assert.include(['valid', 'deactivated', 'revoked'], obj.status);
|
||||
|
||||
assert.isString(obj.orders);
|
||||
|
||||
if ('contact' in obj) {
|
||||
assert.isArray(obj.contact);
|
||||
obj.contact.forEach((c) => assert.isString(c));
|
||||
}
|
||||
|
||||
if ('termsOfServiceAgreed' in obj) {
|
||||
assert.isBoolean(obj.termsOfServiceAgreed);
|
||||
}
|
||||
|
||||
if ('externalAccountBinding' in obj) {
|
||||
assert.isObject(obj.externalAccountBinding);
|
||||
}
|
||||
};
|
||||
|
||||
spec.rfc8555.order = (obj) => {
|
||||
assert.isObject(obj);
|
||||
|
||||
assert.isString(obj.status);
|
||||
assert.include(['pending', 'ready', 'processing', 'valid', 'invalid'], obj.status);
|
||||
|
||||
assert.isArray(obj.identifiers);
|
||||
obj.identifiers.forEach((i) => spec.rfc8555.identifier(i));
|
||||
|
||||
assert.isArray(obj.authorizations);
|
||||
obj.authorizations.forEach((a) => assert.isString(a));
|
||||
|
||||
assert.isString(obj.finalize);
|
||||
|
||||
if ('expires' in obj) {
|
||||
assert.isString(obj.expires);
|
||||
}
|
||||
|
||||
if ('notBefore' in obj) {
|
||||
assert.isString(obj.notBefore);
|
||||
}
|
||||
|
||||
if ('notAfter' in obj) {
|
||||
assert.isString(obj.notAfter);
|
||||
}
|
||||
|
||||
if ('error' in obj) {
|
||||
assert.isObject(obj.error);
|
||||
}
|
||||
|
||||
if ('certificate' in obj) {
|
||||
assert.isString(obj.certificate);
|
||||
}
|
||||
|
||||
/* Augmentations */
|
||||
assert.isString(obj.url);
|
||||
};
|
||||
|
||||
spec.rfc8555.authorization = (obj) => {
|
||||
assert.isObject(obj);
|
||||
|
||||
spec.rfc8555.identifier(obj.identifier);
|
||||
|
||||
assert.isString(obj.status);
|
||||
assert.include(['pending', 'valid', 'invalid', 'deactivated', 'expires', 'revoked'], obj.status);
|
||||
|
||||
assert.isArray(obj.challenges);
|
||||
obj.challenges.forEach((c) => spec.rfc8555.challenge(c));
|
||||
|
||||
if ('expires' in obj) {
|
||||
assert.isString(obj.expires);
|
||||
}
|
||||
|
||||
if ('wildcard' in obj) {
|
||||
assert.isBoolean(obj.wildcard);
|
||||
}
|
||||
|
||||
/* Augmentations */
|
||||
assert.isString(obj.url);
|
||||
};
|
||||
|
||||
spec.rfc8555.identifier = (obj) => {
|
||||
assert.isObject(obj);
|
||||
assert.isString(obj.type);
|
||||
assert.isString(obj.value);
|
||||
};
|
||||
|
||||
spec.rfc8555.challenge = (obj) => {
|
||||
assert.isObject(obj);
|
||||
assert.isString(obj.type);
|
||||
assert.isString(obj.url);
|
||||
|
||||
assert.isString(obj.status);
|
||||
assert.include(['pending', 'processing', 'valid', 'invalid'], obj.status);
|
||||
|
||||
if ('validated' in obj) {
|
||||
assert.isString(obj.validated);
|
||||
}
|
||||
|
||||
if ('error' in obj) {
|
||||
assert.isObject(obj.error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Crypto
|
||||
*/
|
||||
|
||||
spec.crypto = {};
|
||||
|
||||
spec.crypto.csrDomains = (obj) => {
|
||||
assert.isObject(obj);
|
||||
|
||||
assert.isDefined(obj.commonName);
|
||||
assert.isArray(obj.altNames);
|
||||
obj.altNames.forEach((a) => assert.isString(a));
|
||||
};
|
||||
|
||||
spec.crypto.certificateInfo = (obj) => {
|
||||
assert.isObject(obj);
|
||||
|
||||
assert.isObject(obj.issuer);
|
||||
assert.isDefined(obj.issuer.commonName);
|
||||
|
||||
assert.isObject(obj.domains);
|
||||
assert.isDefined(obj.domains.commonName);
|
||||
assert.isArray(obj.domains.altNames);
|
||||
obj.domains.altNames.forEach((a) => assert.isString(a));
|
||||
|
||||
assert.strictEqual(Object.prototype.toString.call(obj.notBefore), '[object Date]');
|
||||
assert.strictEqual(Object.prototype.toString.call(obj.notAfter), '[object Date]');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* JWK
|
||||
*/
|
||||
|
||||
spec.jwk = {};
|
||||
|
||||
spec.jwk.rsa = (obj) => {
|
||||
assert.isObject(obj);
|
||||
assert.isString(obj.e);
|
||||
assert.isString(obj.kty);
|
||||
assert.isString(obj.n);
|
||||
|
||||
assert.strictEqual(obj.e, 'AQAB');
|
||||
assert.strictEqual(obj.kty, 'RSA');
|
||||
};
|
||||
|
||||
spec.jwk.ecdsa = (obj) => {
|
||||
assert.isObject(obj);
|
||||
assert.isString(obj.crv);
|
||||
assert.isString(obj.kty);
|
||||
assert.isString(obj.x);
|
||||
assert.isString(obj.y);
|
||||
|
||||
assert.strictEqual(obj.kty, 'EC');
|
||||
};
|
||||
190
packages/core/acme-client/types/index.d.ts
vendored
Normal file
190
packages/core/acme-client/types/index.d.ts
vendored
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* acme-client type definitions
|
||||
*/
|
||||
|
||||
import { AxiosInstance } from 'axios';
|
||||
import * as rfc8555 from './rfc8555';
|
||||
|
||||
export type PrivateKeyBuffer = Buffer;
|
||||
export type PublicKeyBuffer = Buffer;
|
||||
export type CertificateBuffer = Buffer;
|
||||
export type CsrBuffer = Buffer;
|
||||
|
||||
export type PrivateKeyString = string;
|
||||
export type PublicKeyString = string;
|
||||
export type CertificateString = string;
|
||||
export type CsrString = string;
|
||||
|
||||
|
||||
/**
|
||||
* Augmented ACME interfaces
|
||||
*/
|
||||
|
||||
export interface Order extends rfc8555.Order {
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface Authorization extends rfc8555.Authorization {
|
||||
url: string;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Client
|
||||
*/
|
||||
|
||||
export interface ClientOptions {
|
||||
directoryUrl: string;
|
||||
accountKey: PrivateKeyBuffer | PrivateKeyString;
|
||||
accountUrl?: string;
|
||||
externalAccountBinding?: ClientExternalAccountBindingOptions;
|
||||
backoffAttempts?: number;
|
||||
backoffMin?: number;
|
||||
backoffMax?: number;
|
||||
}
|
||||
|
||||
export interface ClientExternalAccountBindingOptions {
|
||||
kid: string;
|
||||
hmacKey: string;
|
||||
}
|
||||
|
||||
export interface ClientAutoOptions {
|
||||
csr: CsrBuffer | CsrString;
|
||||
challengeCreateFn: (authz: Authorization, challenge: rfc8555.Challenge, keyAuthorization: string) => Promise<any>;
|
||||
challengeRemoveFn: (authz: Authorization, challenge: rfc8555.Challenge, keyAuthorization: string, recordRes:any) => Promise<any>;
|
||||
email?: string;
|
||||
termsOfServiceAgreed?: boolean;
|
||||
skipChallengeVerification?: boolean;
|
||||
challengePriority?: string[];
|
||||
preferredChain?: string;
|
||||
}
|
||||
|
||||
export class Client {
|
||||
constructor(opts: ClientOptions);
|
||||
getTermsOfServiceUrl(): Promise<string>;
|
||||
getAccountUrl(): string;
|
||||
createAccount(data?: rfc8555.AccountCreateRequest): Promise<rfc8555.Account>;
|
||||
updateAccount(data?: rfc8555.AccountUpdateRequest): Promise<rfc8555.Account>;
|
||||
updateAccountKey(newAccountKey: PrivateKeyBuffer | PrivateKeyString, data?: object): Promise<rfc8555.Account>;
|
||||
createOrder(data: rfc8555.OrderCreateRequest): Promise<Order>;
|
||||
getOrder(order: Order): Promise<Order>;
|
||||
finalizeOrder(order: Order, csr: CsrBuffer | CsrString): Promise<Order>;
|
||||
getAuthorizations(order: Order): Promise<Authorization[]>;
|
||||
deactivateAuthorization(authz: Authorization): Promise<Authorization>;
|
||||
getChallengeKeyAuthorization(challenge: rfc8555.Challenge): Promise<string>;
|
||||
verifyChallenge(authz: Authorization, challenge: rfc8555.Challenge): Promise<boolean>;
|
||||
completeChallenge(challenge: rfc8555.Challenge): Promise<rfc8555.Challenge>;
|
||||
waitForValidStatus<T = Order | Authorization | rfc8555.Challenge>(item: T): Promise<T>;
|
||||
getCertificate(order: Order, preferredChain?: string): Promise<string>;
|
||||
revokeCertificate(cert: CertificateBuffer | CertificateString, data?: rfc8555.CertificateRevocationRequest): Promise<void>;
|
||||
auto(opts: ClientAutoOptions): Promise<string>;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Directory URLs
|
||||
*/
|
||||
|
||||
export const directory: {
|
||||
buypass: {
|
||||
staging: string,
|
||||
production: string
|
||||
},
|
||||
letsencrypt: {
|
||||
staging: string,
|
||||
production: string
|
||||
},
|
||||
zerossl: {
|
||||
production: string
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Crypto
|
||||
*/
|
||||
|
||||
export interface CertificateDomains {
|
||||
commonName: string;
|
||||
altNames: string[];
|
||||
}
|
||||
|
||||
export interface CertificateIssuer {
|
||||
commonName: string;
|
||||
}
|
||||
|
||||
export interface CertificateInfo {
|
||||
issuer: CertificateIssuer;
|
||||
domains: CertificateDomains;
|
||||
notAfter: Date;
|
||||
notBefore: Date;
|
||||
}
|
||||
|
||||
export interface CsrOptions {
|
||||
keySize?: number;
|
||||
commonName?: string;
|
||||
altNames?: string[];
|
||||
country?: string;
|
||||
state?: string;
|
||||
locality?: string;
|
||||
organization?: string;
|
||||
organizationUnit?: string;
|
||||
emailAddress?: string;
|
||||
}
|
||||
|
||||
export interface RsaPublicJwk {
|
||||
e: string;
|
||||
kty: string;
|
||||
n: string;
|
||||
}
|
||||
|
||||
export interface EcdsaPublicJwk {
|
||||
crv: string;
|
||||
kty: string;
|
||||
x: string;
|
||||
y: string;
|
||||
}
|
||||
|
||||
export interface CryptoInterface {
|
||||
createPrivateKey(keySize?: number): Promise<PrivateKeyBuffer>;
|
||||
createPrivateRsaKey(keySize?: number): Promise<PrivateKeyBuffer>;
|
||||
createPrivateEcdsaKey(namedCurve?: 'P-256' | 'P-384' | 'P-521'): Promise<PrivateKeyBuffer>;
|
||||
getPublicKey(keyPem: PrivateKeyBuffer | PrivateKeyString | PublicKeyBuffer | PublicKeyString): PublicKeyBuffer;
|
||||
getJwk(keyPem: PrivateKeyBuffer | PrivateKeyString | PublicKeyBuffer | PublicKeyString): RsaPublicJwk | EcdsaPublicJwk;
|
||||
splitPemChain(chainPem: CertificateBuffer | CertificateString): string[];
|
||||
getPemBodyAsB64u(pem: CertificateBuffer | CertificateString): string;
|
||||
readCsrDomains(csrPem: CsrBuffer | CsrString): CertificateDomains;
|
||||
readCertificateInfo(certPem: CertificateBuffer | CertificateString): CertificateInfo;
|
||||
createCsr(data: CsrOptions, keyPem?: PrivateKeyBuffer | PrivateKeyString): Promise<[PrivateKeyBuffer, CsrBuffer]>;
|
||||
}
|
||||
|
||||
export const crypto: CryptoInterface;
|
||||
|
||||
/* TODO: LEGACY */
|
||||
export interface CryptoLegacyInterface {
|
||||
createPrivateKey(size?: number): Promise<PrivateKeyBuffer>;
|
||||
createPublicKey(key: PrivateKeyBuffer | PrivateKeyString): Promise<PublicKeyBuffer>;
|
||||
getPemBody(str: string): string;
|
||||
splitPemChain(str: string): string[];
|
||||
getModulus(input: PrivateKeyBuffer | PrivateKeyString | PublicKeyBuffer | PublicKeyString | CertificateBuffer | CertificateString | CsrBuffer | CsrString): Promise<Buffer>;
|
||||
getPublicExponent(input: PrivateKeyBuffer | PrivateKeyString | PublicKeyBuffer | PublicKeyString | CertificateBuffer | CertificateString | CsrBuffer | CsrString): Promise<Buffer>;
|
||||
readCsrDomains(csr: CsrBuffer | CsrString): Promise<CertificateDomains>;
|
||||
readCertificateInfo(cert: CertificateBuffer | CertificateString): Promise<CertificateInfo>;
|
||||
createCsr(data: CsrOptions, key?: PrivateKeyBuffer | PrivateKeyString): Promise<[PrivateKeyBuffer, CsrBuffer]>;
|
||||
}
|
||||
|
||||
export const forge: CryptoLegacyInterface;
|
||||
|
||||
|
||||
/**
|
||||
* Axios
|
||||
*/
|
||||
|
||||
export const axios: AxiosInstance;
|
||||
|
||||
|
||||
/**
|
||||
* Logger
|
||||
*/
|
||||
|
||||
export function setLogger(fn: (msg: string) => void): void;
|
||||
127
packages/core/acme-client/types/rfc8555.d.ts
vendored
Normal file
127
packages/core/acme-client/types/rfc8555.d.ts
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Account
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.1.2
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.3.2
|
||||
*/
|
||||
|
||||
export interface Account {
|
||||
status: 'valid' | 'deactivated' | 'revoked';
|
||||
orders: string;
|
||||
contact?: string[];
|
||||
termsOfServiceAgreed?: boolean;
|
||||
externalAccountBinding?: object;
|
||||
}
|
||||
|
||||
export interface AccountCreateRequest {
|
||||
contact?: string[];
|
||||
termsOfServiceAgreed?: boolean;
|
||||
onlyReturnExisting?: boolean;
|
||||
externalAccountBinding?: object;
|
||||
}
|
||||
|
||||
export interface AccountUpdateRequest {
|
||||
status?: string;
|
||||
contact?: string[];
|
||||
termsOfServiceAgreed?: boolean;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Order
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.1.3
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.4
|
||||
*/
|
||||
|
||||
export interface Order {
|
||||
status: 'pending' | 'ready' | 'processing' | 'valid' | 'invalid';
|
||||
identifiers: Identifier[];
|
||||
authorizations: string[];
|
||||
finalize: string;
|
||||
expires?: string;
|
||||
notBefore?: string;
|
||||
notAfter?: string;
|
||||
error?: object;
|
||||
certificate?: string;
|
||||
}
|
||||
|
||||
export interface OrderCreateRequest {
|
||||
identifiers: Identifier[];
|
||||
notBefore?: string;
|
||||
notAfter?: string;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Authorization
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.1.4
|
||||
*/
|
||||
|
||||
export interface Authorization {
|
||||
identifier: Identifier;
|
||||
status: 'pending' | 'valid' | 'invalid' | 'deactivated' | 'expired' | 'revoked';
|
||||
challenges: Challenge[];
|
||||
expires?: string;
|
||||
wildcard?: boolean;
|
||||
}
|
||||
|
||||
export interface Identifier {
|
||||
type: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Challenge
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-8
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.3
|
||||
* https://tools.ietf.org/html/rfc8555#section-8.4
|
||||
*/
|
||||
|
||||
export interface ChallengeAbstract {
|
||||
type: string;
|
||||
url: string;
|
||||
status: 'pending' | 'processing' | 'valid' | 'invalid';
|
||||
validated?: string;
|
||||
error?: object;
|
||||
}
|
||||
|
||||
export interface HttpChallenge extends ChallengeAbstract {
|
||||
type: 'http-01';
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface DnsChallenge extends ChallengeAbstract {
|
||||
type: 'dns-01';
|
||||
token: string;
|
||||
}
|
||||
|
||||
export type Challenge = HttpChallenge | DnsChallenge;
|
||||
|
||||
|
||||
/**
|
||||
* Certificate
|
||||
*
|
||||
* https://tools.ietf.org/html/rfc8555#section-7.6
|
||||
*/
|
||||
|
||||
export enum CertificateRevocationReason {
|
||||
Unspecified = 0,
|
||||
KeyCompromise = 1,
|
||||
CACompromise = 2,
|
||||
AffiliationChanged = 3,
|
||||
Superseded = 4,
|
||||
CessationOfOperation = 5,
|
||||
CertificateHold = 6,
|
||||
RemoveFromCRL = 8,
|
||||
PrivilegeWithdrawn = 9,
|
||||
AACompromise = 10,
|
||||
}
|
||||
|
||||
export interface CertificateRevocationRequest {
|
||||
reason?: CertificateRevocationReason;
|
||||
}
|
||||
70
packages/core/acme-client/types/test.ts
Normal file
70
packages/core/acme-client/types/test.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* acme-client type definition tests
|
||||
*/
|
||||
|
||||
import * as acme from 'acme-client';
|
||||
|
||||
|
||||
(async () => {
|
||||
/* Client */
|
||||
const accountKey = await acme.crypto.createPrivateKey();
|
||||
|
||||
const client = new acme.Client({
|
||||
accountKey,
|
||||
directoryUrl: acme.directory.letsencrypt.staging
|
||||
});
|
||||
|
||||
/* Account */
|
||||
await client.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: ['mailto:test@example.com']
|
||||
});
|
||||
|
||||
/* Order */
|
||||
const order = await client.createOrder({
|
||||
identifiers: [
|
||||
{ type: 'dns', value: 'example.com' },
|
||||
{ type: 'dns', value: '*.example.com' },
|
||||
]
|
||||
});
|
||||
|
||||
await client.getOrder(order);
|
||||
|
||||
/* Authorizations / Challenges */
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
const authorization = authorizations[0];
|
||||
const challenge = authorization.challenges[0];
|
||||
|
||||
await client.getChallengeKeyAuthorization(challenge);
|
||||
await client.verifyChallenge(authorization, challenge);
|
||||
await client.completeChallenge(challenge);
|
||||
await client.waitForValidStatus(challenge);
|
||||
|
||||
/* Finalize */
|
||||
const [certKey, certCsr] = await acme.crypto.createCsr({
|
||||
commonName: 'example.com',
|
||||
altNames: ['example.com', '*.example.com']
|
||||
});
|
||||
|
||||
await client.finalizeOrder(order, certCsr);
|
||||
await client.getCertificate(order);
|
||||
await client.getCertificate(order, 'DST Root CA X3');
|
||||
|
||||
/* Auto */
|
||||
await client.auto({
|
||||
csr: certCsr,
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {},
|
||||
challengeRemoveFn: async (authz, challenge, keyAuthorization) => {}
|
||||
});
|
||||
|
||||
await client.auto({
|
||||
csr: certCsr,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: false,
|
||||
skipChallengeVerification: false,
|
||||
challengePriority: ['http-01', 'dns-01'],
|
||||
preferredChain: 'DST Root CA X3',
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {},
|
||||
challengeRemoveFn: async (authz, challenge, keyAuthorization) => {}
|
||||
});
|
||||
})();
|
||||
11
packages/core/acme-client/types/tsconfig.json
Normal file
11
packages/core/acme-client/types/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": ["es6"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"baseUrl": ".",
|
||||
"paths": { "acme-client": ["."] }
|
||||
}
|
||||
}
|
||||
6
packages/core/acme-client/types/tslint.json
Normal file
6
packages/core/acme-client/types/tslint.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "dtslint/dtslint.json",
|
||||
"rules": {
|
||||
"no-consecutive-blank-lines": [true, 2]
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"extends": "standard",
|
||||
"env": {
|
||||
"mocha": true
|
||||
},
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2020
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.test.js", "*.spec.js"],
|
||||
"rules": {
|
||||
"no-unused-expressions": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@certd/api",
|
||||
"version": "0.3.0",
|
||||
"description": "",
|
||||
"main": "src/index.js",
|
||||
"type": "module",
|
||||
"author": "Greper",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"axios": "^0.21.1",
|
||||
"dayjs": "^1.9.7",
|
||||
"lodash-es": "^4.17.20",
|
||||
"log4js": "^6.3.0",
|
||||
"qs": "^6.9.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "^4.2.0",
|
||||
"eslint": "^7.15.0",
|
||||
"eslint-config-standard": "^16.0.2",
|
||||
"eslint-plugin-import": "^2.22.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"mocha": "^8.2.1"
|
||||
},
|
||||
"gitHead": "5fbd7742665c0a949333d805153e9b6af91c0a71"
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
import { Registry } from '../registry/registry.js'
|
||||
export const accessProviderRegistry = new Registry()
|
||||
@@ -1,47 +0,0 @@
|
||||
import _ from 'lodash-es'
|
||||
import logger from '../utils/util.log.js'
|
||||
import commonUtil from '../utils/util.common.js'
|
||||
export class AbstractDnsProvider {
|
||||
constructor ({ accessProviders }) {
|
||||
this.logger = logger
|
||||
this.accessProviders = commonUtil.arrayToMap(accessProviders)
|
||||
}
|
||||
|
||||
async createRecord ({ fullRecord, type, value }) {
|
||||
throw new Error('请实现 createRecord 方法')
|
||||
}
|
||||
|
||||
async removeRecord ({ fullRecord, type, value, record }) {
|
||||
throw new Error('请实现 removeRecord 方法')
|
||||
}
|
||||
|
||||
async getDomainList () {
|
||||
throw new Error('请实现 getDomainList 方法')
|
||||
}
|
||||
|
||||
async matchDomain (dnsRecord, domainPropName) {
|
||||
const list = await this.getDomainList()
|
||||
let domain = null
|
||||
for (const item of list) {
|
||||
if (_.endsWith(dnsRecord, item[domainPropName])) {
|
||||
domain = item
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!domain) {
|
||||
throw new Error('找不到域名,请检查域名是否正确:' + dnsRecord)
|
||||
}
|
||||
return domain
|
||||
}
|
||||
|
||||
getAccessProvider (accessProvider, accessProviders = this.accessProviders) {
|
||||
let access = accessProvider
|
||||
if (typeof accessProvider === 'string' && accessProviders) {
|
||||
access = accessProviders[accessProvider]
|
||||
}
|
||||
if (access == null) {
|
||||
throw new Error(`accessProvider :${accessProvider}不存在`)
|
||||
}
|
||||
return access
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { Registry } from '../registry/registry.js'
|
||||
export { AbstractDnsProvider } from './abstract-dns-provider.js'
|
||||
|
||||
export const dnsProviderRegistry = new Registry()
|
||||
@@ -1,6 +0,0 @@
|
||||
export * from './dns-provider/index.js'
|
||||
export * from './plugin/index.js'
|
||||
export * from './access-provider/index.js'
|
||||
export { Store } from './store/store.js'
|
||||
export { util } from './utils/index.js'
|
||||
// module.createRequireFromPath()
|
||||
@@ -1,81 +0,0 @@
|
||||
import fs from 'fs'
|
||||
import logger from '../utils/util.log.js'
|
||||
import dayjs from 'dayjs'
|
||||
import Sleep from '../utils/util.sleep.js'
|
||||
import commonUtil from '../utils/util.common.js'
|
||||
export class AbstractPlugin {
|
||||
constructor (options) {
|
||||
if (options == null) {
|
||||
throw new Error('插件安装失败:参数不允许为空')
|
||||
}
|
||||
const { accessProviders } = options
|
||||
this.logger = logger
|
||||
this.accessProviders = commonUtil.arrayToMap(accessProviders)
|
||||
}
|
||||
|
||||
appendTimeSuffix (name) {
|
||||
if (name == null) {
|
||||
name = 'certd'
|
||||
}
|
||||
return name + '-' + dayjs().format('YYYYMMDD-HHmmss')
|
||||
}
|
||||
|
||||
async executeFromContextFile (options = {}) {
|
||||
const { contextPath } = options
|
||||
const contextJson = fs.readFileSync(contextPath)
|
||||
const context = JSON.parse(contextJson)
|
||||
options.context = context
|
||||
await this.doExecute(options)
|
||||
fs.writeFileSync(JSON.stringify(context))
|
||||
}
|
||||
|
||||
async doExecute (options) {
|
||||
try {
|
||||
return await this.execute(options)
|
||||
} catch (e) {
|
||||
logger.error('插件执行出错:', e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行
|
||||
* @param options
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async execute (options) {
|
||||
console.error('请实现此方法,context:', options.context)
|
||||
}
|
||||
|
||||
async doRollback (options) {
|
||||
try {
|
||||
return await this.rollback(options)
|
||||
} catch (e) {
|
||||
logger.error('插件rollback出错:', e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回退,用于单元测试
|
||||
* @param options
|
||||
*/
|
||||
async rollback (options) {
|
||||
console.error('请实现此方法,rollback:', options.context)
|
||||
}
|
||||
|
||||
getAccessProvider (accessProvider, accessProviders = this.accessProviders) {
|
||||
let access = accessProvider
|
||||
if (typeof accessProvider === 'string' && accessProviders) {
|
||||
access = accessProviders[accessProvider]
|
||||
}
|
||||
if (access == null) {
|
||||
throw new Error(`accessProvider :${accessProvider}不存在`)
|
||||
}
|
||||
return access
|
||||
}
|
||||
|
||||
async sleep (time) {
|
||||
await Sleep(time)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import { Registry } from '../registry/registry.js'
|
||||
export { AbstractPlugin } from './abstract-plugin.js'
|
||||
export const pluginRegistry = new Registry()
|
||||
@@ -1,46 +0,0 @@
|
||||
export class Registry {
|
||||
constructor () {
|
||||
this.collection = {}
|
||||
}
|
||||
|
||||
install (target) {
|
||||
if (target == null) {
|
||||
return
|
||||
}
|
||||
if (this.collection == null) {
|
||||
this.collection = {}
|
||||
}
|
||||
let defineName = target.define ? target.define().name : null
|
||||
if (defineName == null) {
|
||||
defineName = target.name
|
||||
}
|
||||
|
||||
this.register(defineName, target)
|
||||
}
|
||||
|
||||
register (key, value) {
|
||||
if (!key || value == null) {
|
||||
return
|
||||
}
|
||||
this.collection[key] = value
|
||||
}
|
||||
|
||||
get (name) {
|
||||
if (!name) {
|
||||
throw new Error('插件名称不能为空')
|
||||
}
|
||||
|
||||
if (!this.collection) {
|
||||
this.collection = {}
|
||||
}
|
||||
const plugin = this.collection[name]
|
||||
if (!plugin) {
|
||||
throw new Error(`插件${name}还未注册`)
|
||||
}
|
||||
return plugin
|
||||
}
|
||||
|
||||
getCollection () {
|
||||
return this.collection
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
export class Store {
|
||||
set (key, value) {
|
||||
|
||||
}
|
||||
|
||||
get (key) {
|
||||
|
||||
}
|
||||
|
||||
buildKey (...keyItem) {
|
||||
|
||||
}
|
||||
|
||||
linkExists (linkPath) {
|
||||
|
||||
}
|
||||
|
||||
link (targetPath, linkPath) {
|
||||
|
||||
}
|
||||
|
||||
unlink (linkPath) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 全路径
|
||||
* @param key
|
||||
*/
|
||||
getActualKey (key) {
|
||||
// return 前缀+key
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import logger from './util.log.js'
|
||||
import path from './util.path.js'
|
||||
import { request } from './util.request.js'
|
||||
import sleep from './util.sleep.js'
|
||||
import common from './util.common.js'
|
||||
export const util = {
|
||||
logger, path, request, sleep, common
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import _ from 'lodash-es'
|
||||
export default {
|
||||
arrayToMap (array) {
|
||||
if (!array) {
|
||||
return {}
|
||||
}
|
||||
if (!_.isArray(array)) {
|
||||
return array
|
||||
}
|
||||
const map = {}
|
||||
for (const item of array) {
|
||||
if (item.key) {
|
||||
map[item.key] = item
|
||||
}
|
||||
}
|
||||
return map
|
||||
},
|
||||
mapToArray (map) {
|
||||
if (!map) {
|
||||
return []
|
||||
}
|
||||
if (_.isArray(map)) {
|
||||
return map
|
||||
}
|
||||
const array = []
|
||||
for (const key in map) {
|
||||
const item = map[key]
|
||||
item.key = key
|
||||
array.push(item)
|
||||
}
|
||||
return array
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import log4js from 'log4js'
|
||||
log4js.configure({
|
||||
appenders: { std: { type: 'stdout' } },
|
||||
categories: { default: { appenders: ['std'], level: 'info' } }
|
||||
})
|
||||
const logger = log4js.getLogger('certd')
|
||||
export default logger
|
||||
@@ -1,9 +0,0 @@
|
||||
import path from 'path'
|
||||
|
||||
function getUserBasePath () {
|
||||
const userHome = process.env.USERPROFILE || process.env.HOME
|
||||
return path.resolve(userHome, './.certd')
|
||||
}
|
||||
export default {
|
||||
getUserBasePath
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export default function (timeout) {
|
||||
return new Promise(resolve => {
|
||||
setTimeout(() => {
|
||||
resolve()
|
||||
}, timeout)
|
||||
})
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"extends": "standard",
|
||||
"env": {
|
||||
"mocha": true
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.test.js", "*.spec.js"],
|
||||
"rules": {
|
||||
"no-unused-expressions": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
7
packages/core/certd/.gitignore
vendored
7
packages/core/certd/.gitignore
vendored
@@ -1,7 +0,0 @@
|
||||
.vscode/
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
yarn.lock
|
||||
package-lock.json
|
||||
/.idea/
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@certd/certd",
|
||||
"version": "0.3.0",
|
||||
"description": "a ssl cert keeper",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
"test": "echo \\\"Error: no test specified\\\" && exit 1"
|
||||
},
|
||||
"type": "module",
|
||||
"author": "Greper",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@certd/acme-client": "^0.3.0",
|
||||
"@certd/api": "^0.3.0",
|
||||
"dayjs": "^1.9.7",
|
||||
"lodash-es": "^4.17.20",
|
||||
"node-forge": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "^4.2.0",
|
||||
"eslint": "^7.15.0",
|
||||
"eslint-config-standard": "^16.0.2",
|
||||
"eslint-plugin-import": "^2.22.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"mocha": "^8.2.1"
|
||||
},
|
||||
"gitHead": "5fbd7742665c0a949333d805153e9b6af91c0a71"
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import acme from '@certd/acme-client'
|
||||
import _ from 'lodash-es'
|
||||
import { util } from '@certd/api'
|
||||
const logger = util.logger
|
||||
export class AcmeService {
|
||||
constructor (store) {
|
||||
this.store = store
|
||||
acme.setLogger((text) => {
|
||||
logger.info(text)
|
||||
})
|
||||
}
|
||||
|
||||
async getAccountConfig (email) {
|
||||
let conf = this.store.get(this.buildAccountPath(email))
|
||||
if (conf == null) {
|
||||
conf = {}
|
||||
} else {
|
||||
conf = JSON.parse(conf)
|
||||
}
|
||||
return conf
|
||||
}
|
||||
|
||||
buildAccountPath (email) {
|
||||
return this.store.buildKey(email, 'account.json')
|
||||
}
|
||||
|
||||
saveAccountConfig (email, conf) {
|
||||
this.store.set(this.buildAccountPath(email), JSON.stringify(conf))
|
||||
}
|
||||
|
||||
async getAcmeClient (email, isTest) {
|
||||
const conf = await this.getAccountConfig(email)
|
||||
if (conf.key == null) {
|
||||
conf.key = await this.createNewKey()
|
||||
this.saveAccountConfig(email, conf)
|
||||
}
|
||||
if (isTest == null) {
|
||||
isTest = process.env.CERTD_MODE === 'test'
|
||||
}
|
||||
const client = new acme.Client({
|
||||
directoryUrl: isTest ? acme.directory.letsencrypt.staging : acme.directory.letsencrypt.production,
|
||||
accountKey: conf.key,
|
||||
accountUrl: conf.accountUrl,
|
||||
backoffAttempts: 20,
|
||||
backoffMin: 5000,
|
||||
backoffMax: 10000
|
||||
})
|
||||
|
||||
if (conf.accountUrl == null) {
|
||||
const accountPayload = { termsOfServiceAgreed: true, contact: [`mailto:${email}`] }
|
||||
await client.createAccount(accountPayload)
|
||||
conf.accountUrl = client.getAccountUrl()
|
||||
this.saveAccountConfig(email, conf)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
async createNewKey () {
|
||||
const key = await acme.forge.createPrivateKey()
|
||||
return key.toString()
|
||||
}
|
||||
|
||||
async challengeCreateFn (authz, challenge, keyAuthorization, dnsProvider) {
|
||||
logger.info('Triggered challengeCreateFn()')
|
||||
|
||||
/* http-01 */
|
||||
if (challenge.type === 'http-01') {
|
||||
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`
|
||||
const fileContents = keyAuthorization
|
||||
|
||||
logger.info(`Creating challenge response for ${authz.identifier.value} at path: ${filePath}`)
|
||||
|
||||
/* Replace this */
|
||||
logger.info(`Would write "${fileContents}" to path "${filePath}"`)
|
||||
// await fs.writeFileAsync(filePath, fileContents);
|
||||
} else if (challenge.type === 'dns-01') {
|
||||
/* dns-01 */
|
||||
const dnsRecord = `_acme-challenge.${authz.identifier.value}`
|
||||
const recordValue = keyAuthorization
|
||||
|
||||
logger.info(`Creating TXT record for ${authz.identifier.value}: ${dnsRecord}`)
|
||||
|
||||
/* Replace this */
|
||||
logger.info(`Would create TXT record "${dnsRecord}" with value "${recordValue}"`)
|
||||
|
||||
return await dnsProvider.createRecord({
|
||||
fullRecord: dnsRecord,
|
||||
type: 'TXT',
|
||||
value: recordValue
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function used to remove an ACME challenge response
|
||||
*
|
||||
* @param {object} authz Authorization object
|
||||
* @param {object} challenge Selected challenge
|
||||
* @param {string} keyAuthorization Authorization key
|
||||
* @param recordItem challengeCreateFn create record item
|
||||
* @param dnsProvider dnsProvider
|
||||
* @returns {Promise}
|
||||
*/
|
||||
|
||||
async challengeRemoveFn (authz, challenge, keyAuthorization, recordItem, dnsProvider) {
|
||||
logger.info('Triggered challengeRemoveFn()')
|
||||
|
||||
/* http-01 */
|
||||
if (challenge.type === 'http-01') {
|
||||
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`
|
||||
|
||||
logger.info(`Removing challenge response for ${authz.identifier.value} at path: ${filePath}`)
|
||||
|
||||
/* Replace this */
|
||||
logger.info(`Would remove file on path "${filePath}"`)
|
||||
// await fs.unlinkAsync(filePath);
|
||||
} else if (challenge.type === 'dns-01') {
|
||||
const dnsRecord = `_acme-challenge.${authz.identifier.value}`
|
||||
const recordValue = keyAuthorization
|
||||
|
||||
logger.info(`Removing TXT record for ${authz.identifier.value}: ${dnsRecord}`)
|
||||
|
||||
/* Replace this */
|
||||
logger.info(`Would remove TXT record "${dnsRecord}" with value "${recordValue}"`)
|
||||
await dnsProvider.removeRecord({
|
||||
fullRecord: dnsRecord,
|
||||
type: 'TXT',
|
||||
value: keyAuthorization,
|
||||
record: recordItem
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async order ({ email, domains, dnsProvider, dnsProviderCreator, csrInfo, isTest }) {
|
||||
const client = await this.getAcmeClient(email, isTest)
|
||||
|
||||
let accountUrl
|
||||
try {
|
||||
accountUrl = client.getAccountUrl()
|
||||
} catch (e) {
|
||||
}
|
||||
|
||||
/* Create CSR */
|
||||
const { commonName, altNames } = this.buildCommonNameByDomains(domains)
|
||||
|
||||
const [key, csr] = await acme.forge.createCsr({
|
||||
commonName,
|
||||
...csrInfo,
|
||||
altNames
|
||||
})
|
||||
if (dnsProvider == null && dnsProviderCreator) {
|
||||
dnsProvider = await dnsProviderCreator()
|
||||
}
|
||||
if (dnsProvider == null) {
|
||||
throw new Error('dnsProvider 不能为空')
|
||||
}
|
||||
/* 自动申请证书 */
|
||||
const crt = await client.auto({
|
||||
csr,
|
||||
email: email,
|
||||
termsOfServiceAgreed: true,
|
||||
challengePriority: ['dns-01'],
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
|
||||
return await this.challengeCreateFn(authz, challenge, keyAuthorization, dnsProvider)
|
||||
},
|
||||
challengeRemoveFn: async (authz, challenge, keyAuthorization, recordItem) => {
|
||||
return await this.challengeRemoveFn(authz, challenge, keyAuthorization, recordItem, dnsProvider)
|
||||
}
|
||||
})
|
||||
|
||||
// 保存账号url
|
||||
if (!accountUrl) {
|
||||
try {
|
||||
accountUrl = client.getAccountUrl()
|
||||
this.setAccountUrl(email, accountUrl)
|
||||
} catch (e) {
|
||||
logger.warn('保存accountUrl出错', e)
|
||||
}
|
||||
}
|
||||
/* Done */
|
||||
logger.debug(`CSR:\n${csr.toString()}`)
|
||||
logger.debug(`Certificate:\n${crt.toString()}`)
|
||||
logger.info('证书申请成功')
|
||||
return { key, crt, csr }
|
||||
}
|
||||
|
||||
buildCommonNameByDomains (domains) {
|
||||
if (typeof domains === 'string') {
|
||||
domains = domains.split(',')
|
||||
}
|
||||
if (domains.length === 0) {
|
||||
throw new Error('domain can not be empty')
|
||||
}
|
||||
const ret = {
|
||||
commonName: domains[0]
|
||||
}
|
||||
if (domains.length > 1) {
|
||||
ret.altNames = _.slice(domains, 1)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import { util, Store, dnsProviderRegistry } from '@certd/api'
|
||||
import { AcmeService } from './acme.js'
|
||||
import { FileStore } from './store/file-store.js'
|
||||
import { CertStore } from './store/cert-store.js'
|
||||
import dayjs from 'dayjs'
|
||||
import forge from 'node-forge'
|
||||
|
||||
const logger = util.logger
|
||||
export class Certd {
|
||||
constructor (options) {
|
||||
this.options = options
|
||||
this.email = options.cert.email
|
||||
this.domains = options.cert.domains
|
||||
|
||||
if (!(options.store instanceof Store)) {
|
||||
this.store = new FileStore(options.store || {})
|
||||
}
|
||||
this.certStore = new CertStore({
|
||||
store: this.store,
|
||||
email: options.cert.email,
|
||||
domains: this.domains
|
||||
})
|
||||
this.acme = new AcmeService(this.store)
|
||||
}
|
||||
|
||||
async certApply () {
|
||||
let oldCert
|
||||
try {
|
||||
oldCert = await this.readCurrentCert()
|
||||
} catch (e) {
|
||||
logger.warn('读取cert失败:', e)
|
||||
}
|
||||
|
||||
if (oldCert == null) {
|
||||
logger.info('还未申请过,准备申请新证书')
|
||||
} else {
|
||||
const ret = this.isWillExpire(oldCert.expires, this.options.cert.renewDays)
|
||||
if (!ret.isWillExpire) {
|
||||
logger.info('证书还未过期:', oldCert.expires, ',剩余', ret.leftDays, '天')
|
||||
if (this.options.args.forceCert) {
|
||||
logger.info('准备强制更新证书')
|
||||
} else {
|
||||
logger.info('暂不更新证书')
|
||||
|
||||
oldCert.isNew = false
|
||||
return oldCert
|
||||
}
|
||||
} else {
|
||||
logger.info('即将过期,准备更新证书')
|
||||
}
|
||||
}
|
||||
|
||||
// 执行证书申请步骤
|
||||
return await this.doCertApply()
|
||||
}
|
||||
|
||||
async doCertApply () {
|
||||
const options = this.options
|
||||
const dnsProvider = this.createDnsProvider(options)
|
||||
const cert = await this.acme.order({
|
||||
email: options.cert.email,
|
||||
domains: options.cert.domains,
|
||||
dnsProvider,
|
||||
csrInfo: options.cert.csrInfo,
|
||||
isTest: options.args.test
|
||||
})
|
||||
|
||||
await this.writeCert(cert)
|
||||
const certRet = await this.readCurrentCert()
|
||||
certRet.isNew = true
|
||||
return certRet
|
||||
}
|
||||
|
||||
createDnsProvider (options) {
|
||||
return this.createProviderByType(options.cert.dnsProvider, options.accessProviders)
|
||||
}
|
||||
|
||||
async writeCert (cert) {
|
||||
const newPath = await this.certStore.writeCert(cert)
|
||||
return {
|
||||
realPath: this.certStore.store.getActualKey(newPath),
|
||||
currentPath: this.certStore.store.getActualKey(this.certStore.currentMarkPath)
|
||||
}
|
||||
}
|
||||
|
||||
async readCurrentCert () {
|
||||
const cert = await this.certStore.readCert()
|
||||
if (cert == null) {
|
||||
return null
|
||||
}
|
||||
const { detail, expires } = this.getCrtDetail(cert.crt)
|
||||
const domain = this.certStore.getMainDomain(this.options.cert.domains)
|
||||
return {
|
||||
...cert, detail, expires, domain, domains: this.domains, email: this.email
|
||||
}
|
||||
}
|
||||
|
||||
getCrtDetail (crt) {
|
||||
const pki = forge.pki
|
||||
const detail = pki.certificateFromPem(crt.toString())
|
||||
const expires = detail.validity.notAfter
|
||||
return { detail, expires }
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否过期,默认提前20天
|
||||
* @param expires
|
||||
* @param maxDays
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isWillExpire (expires, maxDays = 20) {
|
||||
if (expires == null) {
|
||||
throw new Error('过期时间不能为空')
|
||||
}
|
||||
// 检查有效期
|
||||
const leftDays = dayjs(expires).diff(dayjs(), 'day')
|
||||
return {
|
||||
isWillExpire: leftDays < maxDays,
|
||||
leftDays
|
||||
}
|
||||
}
|
||||
|
||||
createProviderByType (props, accessProviders) {
|
||||
const { type } = props
|
||||
const Provider = dnsProviderRegistry.get(type)
|
||||
if (Provider == null) {
|
||||
throw new Error('暂不支持此dnsProvider,请先注册该provider:' + type)
|
||||
}
|
||||
return new Provider({ accessProviders, props })
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import dayjs from 'dayjs'
|
||||
import crypto from 'crypto'
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function md5 (content) {
|
||||
return crypto.createHash('md5').update(content).digest('hex')
|
||||
}
|
||||
export class CertStore {
|
||||
constructor ({ store, email, domains }) {
|
||||
this.store = store
|
||||
this.email = email
|
||||
this.domains = domains
|
||||
this.domain = this.getMainDomain(this.domains)
|
||||
this.safetyDomain = this.getSafetyDomain(this.domain)
|
||||
this.domainDir = this.safetyDomain + '-' + md5(this.getDomainStr(this.domains))
|
||||
// this.domainDir = this.safetyDomain
|
||||
this.certsRootPath = this.store.buildKey(this.email, 'certs')
|
||||
|
||||
this.currentMarkPath = this.store.buildKey(this.certsRootPath, this.domainDir, 'current.json')
|
||||
}
|
||||
|
||||
getMainDomain (domains) {
|
||||
if (domains == null) {
|
||||
return null
|
||||
}
|
||||
if (typeof domains === 'string') {
|
||||
return domains
|
||||
}
|
||||
if (domains.length > 0) {
|
||||
return domains[0]
|
||||
}
|
||||
}
|
||||
|
||||
getDomainStr (domains) {
|
||||
if (domains == null) {
|
||||
return null
|
||||
}
|
||||
if (typeof domains === 'string') {
|
||||
return domains
|
||||
}
|
||||
return domains.join(',')
|
||||
}
|
||||
|
||||
buildNewCertRootPath (dir) {
|
||||
if (dir == null) {
|
||||
dir = dayjs().format('YYYY.MM.DD.HHmmss')
|
||||
}
|
||||
return this.store.buildKey(this.certsRootPath, this.domainDir, dir)
|
||||
}
|
||||
|
||||
formatCert (pem) {
|
||||
pem = pem.replace(/\r/g, '')
|
||||
pem = pem.replace(/\n\n/g, '\n')
|
||||
pem = pem.replace(/\n$/g, '')
|
||||
return pem
|
||||
}
|
||||
|
||||
async writeCert (cert) {
|
||||
const newDir = this.buildNewCertRootPath()
|
||||
|
||||
const crtKey = this.buildKey(newDir, this.safetyDomain + '.crt')
|
||||
const priKey = this.buildKey(newDir, this.safetyDomain + '.key')
|
||||
const csrKey = this.buildKey(newDir, this.safetyDomain + '.csr')
|
||||
await this.store.set(crtKey, this.formatCert(cert.crt.toString()))
|
||||
await this.store.set(priKey, this.formatCert(cert.key.toString()))
|
||||
await this.store.set(csrKey, cert.csr.toString())
|
||||
|
||||
await this.store.set(this.currentMarkPath, JSON.stringify({ latest: newDir }))
|
||||
|
||||
return newDir
|
||||
}
|
||||
|
||||
async readCert (dir) {
|
||||
if (dir == null) {
|
||||
dir = await this.getCurrentDir()
|
||||
}
|
||||
if (dir == null) {
|
||||
return
|
||||
}
|
||||
|
||||
const crtKey = this.buildKey(dir, this.safetyDomain + '.crt')
|
||||
const priKey = this.buildKey(dir, this.safetyDomain + '.key')
|
||||
const csrKey = this.buildKey(dir, this.safetyDomain + '.csr')
|
||||
const crt = await this.store.get(crtKey)
|
||||
if (crt == null) {
|
||||
return null
|
||||
}
|
||||
const key = await this.store.get(priKey)
|
||||
const csr = await this.store.get(csrKey)
|
||||
|
||||
return {
|
||||
crt: this.formatCert(crt),
|
||||
key: this.formatCert(key),
|
||||
csr,
|
||||
crtPath: this.store.getActualKey(crtKey),
|
||||
keyPath: this.store.getActualKey(priKey),
|
||||
certDir: this.store.getActualKey(dir)
|
||||
}
|
||||
}
|
||||
|
||||
buildKey (...keyItem) {
|
||||
return this.store.buildKey(...keyItem)
|
||||
}
|
||||
|
||||
getSafetyDomain (domain) {
|
||||
return domain.replace(/\*/g, '_')
|
||||
}
|
||||
|
||||
async getCurrentDir () {
|
||||
const current = await this.store.get(this.currentMarkPath)
|
||||
if (current == null) {
|
||||
return null
|
||||
}
|
||||
return JSON.parse(current).latest
|
||||
}
|
||||
|
||||
async getCurrentFile (file) {
|
||||
const currentDir = await this.getCurrentDir()
|
||||
const key = this.buildKey(currentDir, file)
|
||||
return this.store.get(key)
|
||||
}
|
||||
|
||||
async setCurrentFile (file, value) {
|
||||
const currentDir = await this.getCurrentDir()
|
||||
const key = this.buildKey(currentDir, file)
|
||||
return this.store.set(key, value)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { Store, util } from '@certd/api'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
const logger = util.logger
|
||||
export class FileStore extends Store {
|
||||
constructor (opts) {
|
||||
super()
|
||||
if (opts.rootDir != null) {
|
||||
this.rootDir = opts.rootDir
|
||||
} else {
|
||||
this.rootDir = util.path.getUserBasePath()
|
||||
}
|
||||
if (opts.test) {
|
||||
this.rootDir = path.join(this.rootDir, '/test/')
|
||||
}
|
||||
}
|
||||
|
||||
getActualKey (key) {
|
||||
// return 前缀+key
|
||||
return this.getPathByKey(key)
|
||||
}
|
||||
|
||||
buildKey (...keyItem) {
|
||||
return path.join(...keyItem)
|
||||
}
|
||||
|
||||
getPathByKey (key) {
|
||||
return path.join(this.rootDir, key)
|
||||
}
|
||||
|
||||
set (key, value) {
|
||||
const filePath = this.getPathByKey(key)
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
fs.writeFileSync(filePath, value)
|
||||
return filePath
|
||||
}
|
||||
|
||||
get (key) {
|
||||
const filePath = this.getPathByKey(key)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return null
|
||||
}
|
||||
return fs.readFileSync(filePath).toString()
|
||||
}
|
||||
|
||||
link (targetPath, linkPath) {
|
||||
targetPath = this.getPathByKey(targetPath)
|
||||
linkPath = this.getPathByKey(linkPath)
|
||||
if (fs.existsSync(linkPath)) {
|
||||
try {
|
||||
fs.unlinkSync(linkPath)
|
||||
} catch (e) {
|
||||
logger.error('unlink error:', e)
|
||||
}
|
||||
}
|
||||
fs.symlinkSync(targetPath, linkPath, 'dir')
|
||||
}
|
||||
|
||||
unlink (linkPath) {
|
||||
linkPath = this.getPathByKey(linkPath)
|
||||
fs.unlinkSync(linkPath)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"extends": "standard",
|
||||
"env": {
|
||||
"mocha": true
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.test.js", "*.spec.js"],
|
||||
"rules": {
|
||||
"no-unused-expressions": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
7
packages/core/executor/.gitignore
vendored
7
packages/core/executor/.gitignore
vendored
@@ -1,7 +0,0 @@
|
||||
.vscode/
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
yarn.lock
|
||||
package-lock.json
|
||||
/.idea/
|
||||
@@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "@certd/executor",
|
||||
"version": "0.3.0",
|
||||
"description": "",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
"test": "echo \\\"Error: no test specified\\\" && exit 1",
|
||||
"build": "webpack --config webpack.config.cjs ",
|
||||
"rollup": "rollup --config rollup.config.js"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@certd/api": "^0.3.0",
|
||||
"@certd/certd": "^0.3.0",
|
||||
"dayjs": "^1.9.7",
|
||||
"lodash-es": "^4.17.20"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@certd/plugin-aliyun": "^0.3.0",
|
||||
"@certd/plugin-host": "^0.3.0",
|
||||
"@certd/plugin-tencent": "^0.3.0",
|
||||
"@rollup/plugin-commonjs": "^17.0.0",
|
||||
"@rollup/plugin-json": "^4.1.0",
|
||||
"@rollup/plugin-node-resolve": "^11.0.1",
|
||||
"chai": "^4.2.0",
|
||||
"eslint": "^7.15.0",
|
||||
"eslint-config-standard": "^16.0.2",
|
||||
"eslint-plugin-import": "^2.22.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"mocha": "^8.2.1",
|
||||
"rollup": "^2.35.1",
|
||||
"rollup-plugin-terser": "^7.0.2"
|
||||
},
|
||||
"author": "Greper",
|
||||
"license": "MIT",
|
||||
"sideEffects": false,
|
||||
"gitHead": "5fbd7742665c0a949333d805153e9b6af91c0a71"
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import json from '@rollup/plugin-json'
|
||||
import { terser } from 'rollup-plugin-terser'
|
||||
import commonjs from '@rollup/plugin-commonjs'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
|
||||
export default {
|
||||
input: 'src/index.js',
|
||||
output: [
|
||||
{
|
||||
file: 'bundle.js',
|
||||
format: 'es'
|
||||
},
|
||||
{
|
||||
file: 'bundle.min.js',
|
||||
format: 'iife',
|
||||
name: 'version',
|
||||
plugins: [terser()]
|
||||
}
|
||||
],
|
||||
plugins: [json(), commonjs(), nodeResolve()]
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { Certd } from '@certd/certd'
|
||||
import { pluginRegistry, util } from '@certd/api'
|
||||
import _ from 'lodash-es'
|
||||
import dayjs from 'dayjs'
|
||||
import { Trace } from './trace.js'
|
||||
const logger = util.logger
|
||||
|
||||
function createDefaultOptions () {
|
||||
return {
|
||||
args: {
|
||||
forceCert: false,
|
||||
forceDeploy: true,
|
||||
forceRedeploy: false,
|
||||
doNotThrowError: false // 部署流程执行有错误时,不抛异常,此时整个任务执行完毕后,可以返回结果,你可以在返回结果中处理
|
||||
}
|
||||
}
|
||||
}
|
||||
export class Executor {
|
||||
constructor () {
|
||||
this.trace = new Trace()
|
||||
}
|
||||
|
||||
async run (options) {
|
||||
logger.info('------------------- Cert-D ---------------------')
|
||||
try {
|
||||
this.transfer(options)
|
||||
options = _.merge(createDefaultOptions(), options)
|
||||
return await this.doRun(options)
|
||||
} catch (e) {
|
||||
logger.error('任务执行出错', e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
transfer (options) {
|
||||
const providers = options.accessProviders
|
||||
if (_.isArray(providers)) {
|
||||
const map = {}
|
||||
for (const provider of providers) {
|
||||
if (provider.key) {
|
||||
map[provider.key] = provider
|
||||
}
|
||||
}
|
||||
options.accessProviders = map
|
||||
}
|
||||
}
|
||||
|
||||
async doRun (options) {
|
||||
// 申请证书
|
||||
logger.info('任务开始')
|
||||
const certd = new Certd(options)
|
||||
const cert = await this.runCertd(certd)
|
||||
if (cert == null) {
|
||||
throw new Error('申请证书失败')
|
||||
}
|
||||
logger.info('证书保存路径:', cert.certDir)
|
||||
|
||||
logger.info('----------------------')
|
||||
if (!cert.isNew) {
|
||||
// 如果没有更新
|
||||
if (options.args.forceRedeploy) {
|
||||
// 强制重新部署,清空保存的状态
|
||||
await certd.certStore.setCurrentFile('context.json', '{}')
|
||||
} else if (!options.args.forceDeploy) {
|
||||
// 且不需要强制deploy
|
||||
logger.info('证书无更新,无需重新部署')
|
||||
logger.info('任务完成')
|
||||
return { cert }
|
||||
}
|
||||
}
|
||||
// 读取上次执行进度
|
||||
let context = {}
|
||||
const contextJson = await certd.certStore.getCurrentFile('context.json')
|
||||
if (contextJson) {
|
||||
context = JSON.parse(contextJson)
|
||||
}
|
||||
|
||||
context.certIsNew = !!cert.isNew
|
||||
|
||||
const trace = new Trace(context)
|
||||
const resultTrace = trace.getInstance({ type: 'result' })
|
||||
// 运行部署任务
|
||||
try {
|
||||
await this.runDeploys({ options, cert, context, trace })
|
||||
} finally {
|
||||
await certd.certStore.setCurrentFile('context.json', JSON.stringify(context))
|
||||
}
|
||||
logger.info('任务完成')
|
||||
trace.print()
|
||||
const result = resultTrace.get({ })
|
||||
if (result) {
|
||||
if (result.status === 'error' && options.args.doNotThrowError === false) {
|
||||
throw new Error(result.remark)
|
||||
}
|
||||
}
|
||||
return {
|
||||
cert,
|
||||
context,
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
async runCertd (certd) {
|
||||
logger.info(`证书任务 ${JSON.stringify(certd.options.cert.domains)} 开始`)
|
||||
const cert = await certd.certApply()
|
||||
logger.info(`证书任务 ${JSON.stringify(certd.options.cert.domains)} 完成`)
|
||||
return cert
|
||||
}
|
||||
|
||||
async runDeploys ({ options, cert, context, trace }) {
|
||||
if (cert == null) {
|
||||
const certd = new Certd(options)
|
||||
cert = await certd.readCurrentCert()
|
||||
}
|
||||
logger.info('部署任务开始')
|
||||
for (const deploy of options.deploy) {
|
||||
const deployName = deploy.deployName
|
||||
logger.info(`------------【${deployName}】-----------`)
|
||||
|
||||
const deployTrace = trace.getInstance({ type: 'deploy', deployName })
|
||||
if (deploy.disabled === true) {
|
||||
logger.info('此流程已被禁用,跳过')
|
||||
logger.info('')
|
||||
deployTrace.set({ value: { current: 'skip', status: 'disabled', remark: '流程禁用' } })
|
||||
deployTrace.set({ tasks: null })
|
||||
continue
|
||||
}
|
||||
try {
|
||||
for (const task of deploy.tasks) {
|
||||
if (context[deployName] == null) {
|
||||
context[deployName] = {}
|
||||
}
|
||||
const taskContext = context[deployName]
|
||||
// 开始执行任务列表
|
||||
await this.runTask({ options, cert, task, context: taskContext, deploy, trace })
|
||||
}
|
||||
|
||||
deployTrace.set({ value: { status: 'success', remark: '执行成功' } })
|
||||
trace.set({ type: 'result', value: { status: 'success', remark: '执行成功' } })
|
||||
} catch (e) {
|
||||
deployTrace.set({ value: { status: 'error', remark: '执行失败:' + e.message } })
|
||||
trace.set({ type: 'result', value: { status: 'error', remark: deployName + '执行失败:' + e.message } })
|
||||
logger.error('流程执行失败', e)
|
||||
}
|
||||
|
||||
logger.info('')
|
||||
}
|
||||
}
|
||||
|
||||
async runTask ({ options, task, cert, context, deploy, trace }) {
|
||||
const taskType = task.type
|
||||
const Plugin = pluginRegistry.get(taskType)
|
||||
const deployName = deploy.deployName
|
||||
const taskName = task.taskName
|
||||
if (Plugin == null) {
|
||||
throw new Error(`插件:${taskType}还未安装`)
|
||||
}
|
||||
|
||||
let instance = Plugin
|
||||
if (Plugin instanceof Function) {
|
||||
instance = new Plugin({ accessProviders: options.accessProviders })
|
||||
}
|
||||
const taskTrace = trace.getInstance({ type: 'deploy', deployName, taskName })
|
||||
const traceStatus = taskTrace.get({})
|
||||
if (traceStatus && traceStatus.status === 'success' && !options.args.forceRedeploy) {
|
||||
logger.info(`----【${taskName}】已经执行完成,跳过此任务`)
|
||||
taskTrace.set({ value: { current: 'skip', status: 'success', remark: '已执行成功过,本次跳过' } })
|
||||
return
|
||||
}
|
||||
logger.info(`----【${taskName}】开始执行`)
|
||||
try {
|
||||
// 执行任务
|
||||
await instance.execute({ cert, props: task.props, context })
|
||||
taskTrace.set({ value: { current: 'success', status: 'success', remark: '执行成功', time: dayjs().format() } })
|
||||
} catch (e) {
|
||||
taskTrace.set({ value: { current: 'error', status: 'error', remark: e.message, time: dayjs().format() } })
|
||||
throw e
|
||||
}
|
||||
logger.info(`----任务【${taskName}】执行完成`)
|
||||
logger.info('')
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
import { util } from '@certd/api'
|
||||
import _ from 'lodash-es'
|
||||
const logger = util.logger
|
||||
export class Trace {
|
||||
constructor (context) {
|
||||
this.context = context
|
||||
}
|
||||
|
||||
getInstance ({ type, deployName, taskName }) {
|
||||
return {
|
||||
get: ({ prop }) => {
|
||||
return this.get({ type, deployName, taskName, prop })
|
||||
},
|
||||
set: ({ prop, value }) => {
|
||||
this.set({ type, deployName, taskName, prop, value })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set ({ type, deployName, taskName, prop, value }) {
|
||||
const key = this.buildTraceKey({ type, deployName, taskName, prop })
|
||||
const oldValue = _.get(this.context, key) || {}
|
||||
_.merge(oldValue, value)
|
||||
_.set(this.context, key, oldValue)
|
||||
}
|
||||
|
||||
get ({ type, deployName, taskName, prop }) {
|
||||
return _.get(this.context, this.buildTraceKey({ type, deployName, taskName, prop }))
|
||||
}
|
||||
|
||||
buildTraceKey ({ type = 'default', deployName, taskName, prop }) {
|
||||
let key = '__trace__.' + type
|
||||
if (deployName) {
|
||||
key += '.'
|
||||
key += deployName.replace(/\./g, '_')
|
||||
}
|
||||
if (taskName) {
|
||||
key += '.tasks.'
|
||||
key += taskName.replace(/\./g, '_')
|
||||
}
|
||||
if (prop) {
|
||||
key += '.' + prop
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
getStringLength (str) {
|
||||
const enLength = str.replace(/[\u0391-\uFFE5]/g, '').length // 先把中文替换成两个字节的英文,再计算长度
|
||||
return Math.floor((str.length - enLength) * 1.5) + enLength
|
||||
}
|
||||
|
||||
print () {
|
||||
const context = this.context
|
||||
logger.info('---------------------------任务结果总览--------------------------')
|
||||
if (context.certIsNew) {
|
||||
this.printTraceLine({ current: 'success', remark: '证书更新成功' }, '更新证书')
|
||||
} else {
|
||||
this.printTraceLine({ current: 'skip', remark: '还未到过期时间,跳过' }, '更新证书')
|
||||
}
|
||||
const trace = this.get({ type: 'deploy' })
|
||||
// logger.info('trace', trace)
|
||||
for (const deployName in trace) {
|
||||
if (trace[deployName] == null) {
|
||||
trace[deployName] = {}
|
||||
}
|
||||
const traceStatus = this.printTraceLine(trace[deployName], deployName)
|
||||
|
||||
const tasks = traceStatus.tasks
|
||||
if (tasks) {
|
||||
for (const taskName in tasks) {
|
||||
if (tasks[taskName] == null) {
|
||||
tasks[taskName] = {}
|
||||
}
|
||||
this.printTraceLine(tasks[taskName], taskName, ' └')
|
||||
}
|
||||
}
|
||||
}
|
||||
const result = this.get({ type: 'result' })
|
||||
if (result) {
|
||||
this.printTraceLine(result, 'result', '')
|
||||
}
|
||||
const mainContext = {}
|
||||
_.merge(mainContext, context)
|
||||
delete mainContext.__trace__
|
||||
logger.info('【context】', JSON.stringify(mainContext))
|
||||
}
|
||||
|
||||
printTraceLine (traceStatus, name, prefix = '') {
|
||||
const length = this.getStringLength(name)
|
||||
const endPad = _.repeat('-', 45 - prefix.length - length) + '\t'
|
||||
const status = traceStatus.current || traceStatus.status || ''
|
||||
const remark = traceStatus.remark || ''
|
||||
logger.info(`${prefix}【${name}】${endPad}[${status}] \t${remark}`)
|
||||
return traceStatus
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import pkg from 'chai'
|
||||
import { Executor } from '../src/index.js'
|
||||
import { createOptions } from '../../../../test/options.js'
|
||||
import PluginAliyun from '@certd/plugin-aliyun'
|
||||
import PluginTencent from '@certd/plugin-tencent'
|
||||
import PluginHost from '@certd/plugin-host'
|
||||
const { expect } = pkg
|
||||
|
||||
// 安装默认插件和授权提供者
|
||||
PluginAliyun.install()
|
||||
PluginTencent.install()
|
||||
PluginHost.install()
|
||||
|
||||
describe('AutoDeploy', function () {
|
||||
it('#run', async function () {
|
||||
this.timeout(120000)
|
||||
const options = createOptions()
|
||||
const executor = new Executor()
|
||||
const ret = await executor.run(options)
|
||||
expect(ret).ok
|
||||
expect(ret.cert).ok
|
||||
})
|
||||
it('#forceCert', async function () {
|
||||
this.timeout(120000)
|
||||
const executor = new Executor()
|
||||
const options = createOptions()
|
||||
options.args.forceCert = true
|
||||
options.args.forceDeploy = true
|
||||
|
||||
const ret = await executor.run(options)
|
||||
expect(ret).ok
|
||||
expect(ret.cert).ok
|
||||
})
|
||||
it('#forceDeploy', async function () {
|
||||
this.timeout(120000)
|
||||
const executor = new Executor()
|
||||
const options = createOptions()
|
||||
const ret = await executor.run(options, { forceCert: false, forceDeploy: true, forceRedeploy: true })
|
||||
expect(ret).ok
|
||||
expect(ret.cert).ok
|
||||
})
|
||||
})
|
||||
@@ -1,23 +0,0 @@
|
||||
const path = require('path')
|
||||
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
|
||||
console.log(CleanWebpackPlugin)
|
||||
|
||||
module.exports = {
|
||||
devtool: 'source-map',
|
||||
target: 'node',
|
||||
entry: './src/index.js',
|
||||
output: {
|
||||
filename: 'executor.js',
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
library: 'certdExecutor',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new CleanWebpackPlugin()
|
||||
],
|
||||
mode: 'production'
|
||||
// mode: 'development',
|
||||
// optimization: {
|
||||
// usedExports: true
|
||||
// }
|
||||
}
|
||||
22
packages/core/pipeline/.eslintrc
Normal file
22
packages/core/pipeline/.eslintrc
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": [
|
||||
"@typescript-eslint"
|
||||
],
|
||||
"extends": [
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:prettier/recommended",
|
||||
"prettier"
|
||||
],
|
||||
"env": {
|
||||
"mocha": true
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/no-var-requires": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/ban-ts-ignore": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
// "no-unused-expressions": "off",
|
||||
"max-len": [0, 160, 2, { "ignoreUrls": true }]
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user