mirror of
https://github.com/certd/certd.git
synced 2026-04-04 23:10:56 +08:00
Compare commits
14 Commits
client_syn
...
acme_sync
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5edfbfa6d | ||
|
|
86e64af35c | ||
|
|
162e10909b | ||
|
|
0f1ae6ccd9 | ||
|
|
c9d5cda953 | ||
|
|
960f61d158 | ||
|
|
80cd1bfc8e | ||
|
|
a6bf198604 | ||
|
|
7e8842b452 | ||
|
|
fc9e71bed2 | ||
|
|
08c1f338d5 | ||
|
|
18865f0931 | ||
|
|
d22a25d260 | ||
|
|
f64ea78c44 |
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 = space
|
||||
indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[{*.yml,*.yaml}]
|
||||
indent_size = 2
|
||||
16
packages/core/acme-client/.eslintrc.yml
Normal file
16
packages/core/acme-client/.eslintrc.yml
Normal file
@@ -0,0 +1,16 @@
|
||||
extends:
|
||||
- 'airbnb-base'
|
||||
|
||||
env:
|
||||
browser: false
|
||||
node: true
|
||||
mocha: true
|
||||
|
||||
rules:
|
||||
indent: [2, 4, { SwitchCase: 1, VariableDeclarator: 1 }]
|
||||
brace-style: [2, 'stroustrup', { allowSingleLine: true }]
|
||||
func-names: 0
|
||||
class-methods-use-this: 0
|
||||
no-param-reassign: 0
|
||||
max-len: [1, 200, 2, { ignoreUrls: true, ignoreComments: false }]
|
||||
import/no-useless-path-segments: 0
|
||||
61
packages/core/acme-client/.github/scripts/tests-install-coredns.sh
vendored
Normal file
61
packages/core/acme-client/.github/scripts/tests-install-coredns.sh
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install CoreDNS for testing.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
# 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
|
||||
bind 127.53.53.53
|
||||
file /etc/coredns/db.example.com
|
||||
}
|
||||
|
||||
test.example.com {
|
||||
errors
|
||||
log
|
||||
bind 127.53.53.53
|
||||
forward . 127.0.0.1:${PEBBLECTS_DNS_PORT}
|
||||
}
|
||||
|
||||
. {
|
||||
errors
|
||||
log
|
||||
bind 127.53.53.53
|
||||
forward . 8.8.8.8
|
||||
}
|
||||
EOF
|
||||
|
||||
exit 0
|
||||
15
packages/core/acme-client/.github/scripts/tests-install-cts.sh
vendored
Normal file
15
packages/core/acme-client/.github/scripts/tests-install-cts.sh
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install Pebble Challenge Test Server for testing.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
# Download and install
|
||||
wget -nv "https://github.com/letsencrypt/pebble/releases/download/v${PEBBLECTS_VERSION}/pebble-challtestsrv-linux-amd64.tar.gz" -O /tmp/pebble-challtestsrv.tar.gz
|
||||
tar zxvf /tmp/pebble-challtestsrv.tar.gz -C /tmp
|
||||
|
||||
mv /tmp/pebble-challtestsrv-linux-amd64/linux/amd64/pebble-challtestsrv /usr/local/bin/pebble-challtestsrv
|
||||
chown root:root /usr/local/bin/pebble-challtestsrv
|
||||
chmod 0755 /usr/local/bin/pebble-challtestsrv
|
||||
|
||||
exit 0
|
||||
35
packages/core/acme-client/.github/scripts/tests-install-pebble.sh
vendored
Normal file
35
packages/core/acme-client/.github/scripts/tests-install-pebble.sh
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Install Pebble for testing.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
CONFIG_NAME="pebble-config.json"
|
||||
|
||||
# Use Pebble EAB config if enabled
|
||||
set +u
|
||||
if [[ -n $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.tar.gz" -O /tmp/pebble.tar.gz
|
||||
tar zxvf /tmp/pebble.tar.gz -C /tmp
|
||||
|
||||
mv /tmp/pebble-linux-amd64/linux/amd64/pebble /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
|
||||
27
packages/core/acme-client/.github/scripts/tests-wait-for-ca.sh
vendored
Normal file
27
packages/core/acme-client/.github/scripts/tests-wait-for-ca.sh
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Wait for ACME server to accept connections.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
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
|
||||
91
packages/core/acme-client/.github/workflows/tests.yml
vendored
Normal file
91
packages/core/acme-client/.github/workflows/tests.yml
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
name: test
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: node=${{matrix.node}} eab=${{matrix.eab}}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node: [16, 18, 20]
|
||||
eab: [0, 1]
|
||||
|
||||
#
|
||||
# Environment
|
||||
#
|
||||
|
||||
env:
|
||||
FORCE_COLOR: 1
|
||||
NPM_CONFIG_COLOR: always
|
||||
|
||||
PEBBLE_VERSION: 2.6.0
|
||||
PEBBLE_ALTERNATE_ROOTS: 2
|
||||
PEBBLECTS_VERSION: 2.6.0
|
||||
PEBBLECTS_DNS_PORT: 8053
|
||||
COREDNS_VERSION: 1.11.1
|
||||
|
||||
NODE_EXTRA_CA_CERTS: /etc/pebble/ca.cert.pem
|
||||
ACME_CA_CERT_PATH: /etc/pebble/ca.cert.pem
|
||||
|
||||
ACME_DIRECTORY_URL: https://127.0.0.1:14000/dir
|
||||
ACME_CHALLTESTSRV_URL: http://127.0.0.1:8055
|
||||
ACME_PEBBLE_MANAGEMENT_URL: https://127.0.0.1:15000
|
||||
|
||||
ACME_DOMAIN_NAME: test.example.com
|
||||
ACME_CAP_EAB_ENABLED: ${{matrix.eab}}
|
||||
|
||||
ACME_TLSALPN_PORT: 5001
|
||||
ACME_HTTP_PORT: 5002
|
||||
ACME_HTTPS_PORT: 5003
|
||||
|
||||
#
|
||||
# Pipeline
|
||||
#
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{matrix.node}}
|
||||
|
||||
# Pebble Challenge Test Server
|
||||
- name: Install Pebble Challenge Test Server
|
||||
run: sudo -E /bin/bash ./.github/scripts/tests-install-cts.sh
|
||||
|
||||
- name: Start Pebble Challenge Test Server
|
||||
run: |-
|
||||
nohup bash -c "pebble-challtestsrv \
|
||||
-dns01 :${PEBBLECTS_DNS_PORT} \
|
||||
-tlsalpn01 :${ACME_TLSALPN_PORT} \
|
||||
-http01 :${ACME_HTTP_PORT} \
|
||||
-https01 :${ACME_HTTPS_PORT} \
|
||||
-defaultIPv4 127.0.0.1 \
|
||||
-defaultIPv6 \"\" &"
|
||||
|
||||
# Pebble
|
||||
- name: Install Pebble
|
||||
run: sudo -E /bin/bash ./.github/scripts/tests-install-pebble.sh
|
||||
|
||||
- name: Start Pebble
|
||||
run: nohup bash -c "pebble -strict -config /etc/pebble/pebble.json -dnsserver 127.53.53.53:53 &"
|
||||
|
||||
- name: Wait for Pebble
|
||||
run: /bin/bash ./.github/scripts/tests-wait-for-ca.sh
|
||||
|
||||
# CoreDNS
|
||||
- name: Install CoreDNS
|
||||
run: sudo -E /bin/bash ./.github/scripts/tests-install-coredns.sh
|
||||
|
||||
- name: Start CoreDNS
|
||||
run: nohup bash -c "sudo coredns -p 53 -conf /etc/coredns/Corefile &"
|
||||
|
||||
- name: Use CoreDNS for DNS resolution
|
||||
run: echo "nameserver 127.53.53.53" | sudo tee /etc/resolv.conf
|
||||
|
||||
# Run tests
|
||||
- run: npm i
|
||||
- run: npm run lint
|
||||
- run: npm run lint-types
|
||||
- run: npm run build-docs
|
||||
- run: npm run test
|
||||
5
packages/core/acme-client/.gitignore
vendored
Normal file
5
packages/core/acme-client/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
.actrc
|
||||
.vscode/
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
package-lock.json
|
||||
210
packages/core/acme-client/CHANGELOG.md
Normal file
210
packages/core/acme-client/CHANGELOG.md
Normal file
@@ -0,0 +1,210 @@
|
||||
# Changelog
|
||||
|
||||
## v5.4.0 (2024-07-16)
|
||||
|
||||
* `added` Directory URLs for [Google](https://cloud.google.com/certificate-manager/docs/overview) ACME provider
|
||||
* `fixed` Invalidate ACME provider directory cache after 24 hours
|
||||
* `fixed` Retry HTTP requests on server errors or when rate limited - [#89](https://github.com/publishlab/node-acme-client/issues/89)
|
||||
|
||||
## v5.3.1 (2024-05-22)
|
||||
|
||||
* `fixed` Allow `client.auto()` being called with an empty CSR common name
|
||||
* `fixed` Bug when calling `updateAccountKey()` with external account binding
|
||||
|
||||
## v5.3.0 (2024-02-05)
|
||||
|
||||
* `added` Support and tests for satisfying `tls-alpn-01` challenges
|
||||
* `changed` Replace `jsrsasign` with `@peculiar/x509` for certificate and CSR handling
|
||||
* `changed` Method `getChallengeKeyAuthorization()` now returns `$token.$thumbprint` when called with a `tls-alpn-01` challenge
|
||||
* Previously returned base64url encoded SHA256 digest of `$token.$thumbprint` erroneously
|
||||
* This change is not considered breaking since the previous behavior was incorrect
|
||||
|
||||
## v5.2.0 (2024-01-22)
|
||||
|
||||
* `fixed` Allow self-signed or invalid certs when validating `http-01` challenges that redirect to HTTPS - [#65](https://github.com/publishlab/node-acme-client/issues/65)
|
||||
* `fixed` Wait for all challenge promises to settle before rejecting `client.auto()` - [#75](https://github.com/publishlab/node-acme-client/issues/75)
|
||||
|
||||
## v5.1.0 (2024-01-20)
|
||||
|
||||
* `fixed` Upgrade `jsrsasign@11.0.0` - [GHSA-rh63-9qcf-83gf](https://github.com/kjur/jsrsasign/security/advisories/GHSA-rh63-9qcf-83gf)
|
||||
* `fixed` Upgrade `axios@1.6.5` - [CVE-2023-45857](https://cve.mitre.org/cgi-bin/cvename.cgi?name=2023-45857)
|
||||
|
||||
## 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)
|
||||
|
||||
## v4.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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/html/rfc5280)
|
||||
* `fixed` Implement `POST-as-GET` for all ACME API requests - [RFC 8555 Section 6.3](https://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 fast-crud
|
||||
Copyright (c) 2017-2024 Labrador CMS AS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
241
packages/core/acme-client/README.md
Normal file
241
packages/core/acme-client/README.md
Normal file
@@ -0,0 +1,241 @@
|
||||
# acme-client [](https://github.com/publishlab/node-acme-client/actions/workflows/tests.yml)
|
||||
|
||||
*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://datatracker.ietf.org/doc/html/rfc8555](https://datatracker.ietf.org/doc/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)
|
||||
|
||||
## 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.google.staging;
|
||||
acme.directory.google.production;
|
||||
|
||||
acme.directory.letsencrypt.staging;
|
||||
acme.directory.letsencrypt.production;
|
||||
|
||||
acme.directory.zerossl.production;
|
||||
```
|
||||
|
||||
### External account binding
|
||||
|
||||
To enable [external account binding](https://datatracker.ietf.org/doc/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 [@peculiar/x509](https://www.npmjs.com/package/@peculiar/x509) 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({
|
||||
altNames: ['example.com', '*.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)
|
||||
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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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 authorization 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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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({
|
||||
altNames: ['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({
|
||||
altNames: ['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
|
||||
316
packages/core/acme-client/docs/crypto.md
Normal file
316
packages/core/acme-client/docs/crypto.md
Normal file
@@ -0,0 +1,316 @@
|
||||
## 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.<string></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>
|
||||
<dt><a href="#createAlpnCertificate">createAlpnCertificate(authz, keyAuthorization, [keyPem])</a> ⇒ <code>Promise.<Array.<buffer>></code></dt>
|
||||
<dd><p>Create a self-signed ALPN certificate for TLS-ALPN-01 challenges</p>
|
||||
<p><a href="https://datatracker.ietf.org/doc/html/rfc8737">https://datatracker.ietf.org/doc/html/rfc8737</a></p>
|
||||
</dd>
|
||||
<dt><a href="#isAlpnCertificateAuthorizationValid">isAlpnCertificateAuthorizationValid(certPem, keyAuthorization)</a> ⇒ <code>boolean</code></dt>
|
||||
<dd><p>Validate that a ALPN certificate contains the expected key authorization</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.<string></code>
|
||||
Split chain of PEM encoded objects from string into array
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Array.<string></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.<string></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>buffer</code> \| <code>string</code> | PEM encoded CSR private key |
|
||||
|
||||
**Example**
|
||||
Create a Certificate Signing Request
|
||||
```js
|
||||
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
|
||||
altNames: ['test.example.com'],
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with both common and alternative names
|
||||
> *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
|
||||
```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({
|
||||
altNames: ['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({
|
||||
altNames: ['test.example.com'],
|
||||
}, certificateKey);
|
||||
```
|
||||
<a name="createAlpnCertificate"></a>
|
||||
|
||||
## createAlpnCertificate(authz, keyAuthorization, [keyPem]) ⇒ <code>Promise.<Array.<buffer>></code>
|
||||
Create a self-signed ALPN certificate for TLS-ALPN-01 challenges
|
||||
|
||||
https://datatracker.ietf.org/doc/html/rfc8737
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>Promise.<Array.<buffer>></code> - [privateKey, certificate]
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| authz | <code>object</code> | Identifier authorization |
|
||||
| keyAuthorization | <code>string</code> | Challenge key authorization |
|
||||
| [keyPem] | <code>buffer</code> \| <code>string</code> | PEM encoded CSR private key |
|
||||
|
||||
**Example**
|
||||
Create a ALPN certificate
|
||||
```js
|
||||
const [alpnKey, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization);
|
||||
```
|
||||
**Example**
|
||||
Create a ALPN certificate with ECDSA private key
|
||||
```js
|
||||
const alpnKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
const [, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization, alpnKey);
|
||||
```
|
||||
<a name="isAlpnCertificateAuthorizationValid"></a>
|
||||
|
||||
## isAlpnCertificateAuthorizationValid(certPem, keyAuthorization) ⇒ <code>boolean</code>
|
||||
Validate that a ALPN certificate contains the expected key authorization
|
||||
|
||||
**Kind**: global function
|
||||
**Returns**: <code>boolean</code> - True when valid
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| certPem | <code>buffer</code> \| <code>string</code> | PEM encoded certificate |
|
||||
| keyAuthorization | <code>string</code> | Expected challenge key authorization |
|
||||
|
||||
258
packages/core/acme-client/docs/forge.md
Normal file
258
packages/core/acme-client/docs/forge.md
Normal file
@@ -0,0 +1,258 @@
|
||||
## 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.<string></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({
|
||||
altNames: ['test.example.com'],
|
||||
});
|
||||
```
|
||||
**Example**
|
||||
Certificate Signing Request with both common and alternative names
|
||||
> *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
|
||||
```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({
|
||||
altNames: ['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({
|
||||
altNames: ['test.example.com'],
|
||||
}, certificateKey);
|
||||
93
packages/core/acme-client/docs/upgrade-v5.md
Normal file
93
packages/core/acme-client/docs/upgrade-v5.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# 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 [@peculiar/x509](https://www.npmjs.com/package/@peculiar/x509) 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);
|
||||
```
|
||||
19
packages/core/acme-client/examples/README.md
Normal file
19
packages/core/acme-client/examples/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Disclaimer
|
||||
|
||||
These examples should not be used as is for any production environment, as they are just proof of concepts meant for testing and to get you started. The examples are naively written and purposefully avoids important topics since they will be specific to your application and how you choose to use `acme-client`, like for example:
|
||||
|
||||
1. **Concurrency control**
|
||||
* If implementing on-demand certificate generation
|
||||
* What happens when multiple requests hit your domain at the same time?
|
||||
* Ensure your application does not place multiple cert orders for the same domain at the same time by implementing some sort of exclusive lock
|
||||
2. **Domain allow lists**
|
||||
* If implementing on-demand certificate generation
|
||||
* What happens when someone manipulates the `ServerName` or `Host` header to your service?
|
||||
* Ensure your application is unable to place certificate orders for domains you do not intend, as this can quickly rate limit your account and cause a DoS
|
||||
3. **Clustering**
|
||||
* If using `acme-client` across a cluster of servers
|
||||
* Ensure challenge responses are known to all servers in your cluster, perhaps using a database or shared storage
|
||||
4. **Certificate and key storage**
|
||||
* Where and how should the account key be stored and read?
|
||||
* Where and how should certificates and cert keys be stored and read?
|
||||
* How and when should they be renewed?
|
||||
148
packages/core/acme-client/examples/api.js
Normal file
148
packages/core/acme-client/examples/api.js
Normal file
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* 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 () => {
|
||||
/* 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({
|
||||
altNames: ['example.com', '*.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()}`);
|
||||
};
|
||||
114
packages/core/acme-client/examples/auto.js
Normal file
114
packages/core/acme-client/examples/auto.js
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 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', recordValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
module.exports = async () => {
|
||||
/* 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({
|
||||
altNames: ['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()}`);
|
||||
};
|
||||
21
packages/core/acme-client/examples/dns-01/README.md
Normal file
21
packages/core/acme-client/examples/dns-01/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# dns-01
|
||||
|
||||
The greatest benefit of `dns-01` is that it is the only challenge type that can be used to issue ACME wildcard certificates, however it also has a few downsides. Your DNS provider needs to offer some sort of API you can use to automate adding and removing the required `TXT` DNS records. Additionally, solving DNS challenges will be much slower than the other challenge types because of DNS propagation delays.
|
||||
|
||||
## How it works
|
||||
|
||||
When solving `dns-01` challenges, you prove ownership of a domain by serving a specific payload within a specific DNS `TXT` record from the domains authoritative nameservers. The ACME authority provides the client with a token that, along with a thumbprint of your account key, is used to generate a `base64url` encoded `SHA256` digest. This payload is then placed as a `TXT` record under DNS name `_acme-challenge.$YOUR_DOMAIN`.
|
||||
|
||||
Once the order is finalized, the ACME authority will lookup your domains DNS record to verify that the payload is correct. `CNAME` and `NS` records are followed, should you wish to delegate challenge response to another DNS zone or record.
|
||||
|
||||
## Pros and cons
|
||||
|
||||
* Only challenge type that can be used to issue wildcard certificates
|
||||
* Your DNS provider needs to supply an API that can be used
|
||||
* DNS propagation time may be slow
|
||||
* Useful in instances where both port 80 and 443 are unavailable
|
||||
|
||||
## External links
|
||||
|
||||
* [https://letsencrypt.org/docs/challenge-types/#dns-01-challenge](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
|
||||
* [https://datatracker.ietf.org/doc/html/rfc8555#section-8.4](https://datatracker.ietf.org/doc/html/rfc8555#section-8.4)
|
||||
88
packages/core/acme-client/examples/dns-01/dns-01.js
Normal file
88
packages/core/acme-client/examples/dns-01/dns-01.js
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Example using dns-01 challenge to generate certificates
|
||||
*
|
||||
* NOTE: This example is incomplete as the DNS challenge response implementation
|
||||
* will be specific to your DNS providers API.
|
||||
*
|
||||
* NOTE: This example does not order certificates on-demand, as solving dns-01
|
||||
* will likely be too slow for it to make sense. Instead, it orders a wildcard
|
||||
* certificate on init before starting the HTTPS server as a demonstration.
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const acme = require('./../../');
|
||||
|
||||
const HTTPS_SERVER_PORT = 443;
|
||||
const WILDCARD_DOMAIN = 'example.com';
|
||||
|
||||
function log(m) {
|
||||
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
/**
|
||||
* Initialize ACME client
|
||||
*/
|
||||
|
||||
log('Initializing ACME client');
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: await acme.crypto.createPrivateKey(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Order wildcard certificate
|
||||
*/
|
||||
|
||||
log(`Creating CSR for ${WILDCARD_DOMAIN}`);
|
||||
const [key, csr] = await acme.crypto.createCsr({
|
||||
altNames: [WILDCARD_DOMAIN, `*.${WILDCARD_DOMAIN}`],
|
||||
});
|
||||
|
||||
log(`Ordering certificate for ${WILDCARD_DOMAIN}`);
|
||||
const cert = await client.auto({
|
||||
csr,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengePriority: ['dns-01'],
|
||||
challengeCreateFn: (authz, challenge, keyAuthorization) => {
|
||||
/* TODO: Implement this */
|
||||
log(`[TODO] Add TXT record key=_acme-challenge.${authz.identifier.value} value=${keyAuthorization}`);
|
||||
},
|
||||
challengeRemoveFn: (authz, challenge, keyAuthorization) => {
|
||||
/* TODO: Implement this */
|
||||
log(`[TODO] Remove TXT record key=_acme-challenge.${authz.identifier.value} value=${keyAuthorization}`);
|
||||
},
|
||||
});
|
||||
|
||||
log(`Certificate for ${WILDCARD_DOMAIN} created successfully`);
|
||||
|
||||
/**
|
||||
* HTTPS server
|
||||
*/
|
||||
|
||||
const requestListener = (req, res) => {
|
||||
log(`HTTP 200 ${req.headers.host}${req.url}`);
|
||||
res.writeHead(200);
|
||||
res.end('Hello world\n');
|
||||
};
|
||||
|
||||
const httpsServer = https.createServer({
|
||||
key,
|
||||
cert,
|
||||
}, requestListener);
|
||||
|
||||
httpsServer.listen(HTTPS_SERVER_PORT, () => {
|
||||
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
log(`[FATAL] ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
})();
|
||||
19
packages/core/acme-client/examples/fallback.crt
Normal file
19
packages/core/acme-client/examples/fallback.crt
Normal file
@@ -0,0 +1,19 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDCTCCAfGgAwIBAgIUGwI6ZLE3HN7oRZ9BvWLde0Tsu7EwDQYJKoZIhvcNAQEL
|
||||
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIyMDgwMTAwNTMzMVoXDTIyMDgz
|
||||
MTAwNTMzMVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
|
||||
AAOCAQ8AMIIBCgKCAQEA4c7zSiY6OEp9xYZHY42FUfOLREm03NstZhd9IxFFePwe
|
||||
CTTirJjmi5teKQwzBmEok0SJkanJUaMsMlOHjEykWSc4SBO4QjD349Q60044i9WS
|
||||
7KHzeSqpWTG+V9jF3HOJPw843VG9hXy3ulXKcysTXzumTVQwfatCODBNkpWqMju2
|
||||
N33biLgmpqwLbDSfKXS3uSVTfoHAKGT/oRepko7/0Hwr5oEmjXEbpRWRhU09KYjH
|
||||
7jokRaiQRn0h216a0r4AKzSNGihNQtKJZIuwJvLFPMQYafsu9qBaCLPqDBXCwQWG
|
||||
aYh6Cm3kTkADKzG1LVPB/7/Uh2d4Fck/ejR9qXRK3QIDAQABo1MwUTAdBgNVHQ4E
|
||||
FgQUvyceAVDMPbW7wHwNF9px5dWfgd4wHwYDVR0jBBgwFoAUvyceAVDMPbW7wHwN
|
||||
F9px5dWfgd4wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAaYkz
|
||||
AOHrRirPwfkwjb+uMliGHfANrmak8r5VDQA73RLTQLRhMpf1yrb1uhH7p/CUYKap
|
||||
x1C8RGQAXujoQbQOslyZA7cVLA9ASSZS6Noq7NerfGBiqxeuye+x3lIIk1EOL/rH
|
||||
aBu9rrYGmlU49PlGAQSfFHkwzXti2Mp1VQv8eMOBLR49ezZIXHiPE8S3gjNymZ0G
|
||||
UA13wzZCT7SG1BLmQ/cBVASG2wvhlC8IG/4vF0Xe+boSOb1vGWUtHS+MnvvRK4n5
|
||||
TMUtrnxSQ/LA8AtobvzqgvQVKBSPLK6RzLE7I+Q9pWsbKTBqfyStuQrQFqafBOqN
|
||||
eYfPUgiID9uvfrxLvA==
|
||||
-----END CERTIFICATE-----
|
||||
28
packages/core/acme-client/examples/fallback.key
Normal file
28
packages/core/acme-client/examples/fallback.key
Normal file
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDhzvNKJjo4Sn3F
|
||||
hkdjjYVR84tESbTc2y1mF30jEUV4/B4JNOKsmOaLm14pDDMGYSiTRImRqclRoywy
|
||||
U4eMTKRZJzhIE7hCMPfj1DrTTjiL1ZLsofN5KqlZMb5X2MXcc4k/DzjdUb2FfLe6
|
||||
VcpzKxNfO6ZNVDB9q0I4ME2SlaoyO7Y3fduIuCamrAtsNJ8pdLe5JVN+gcAoZP+h
|
||||
F6mSjv/QfCvmgSaNcRulFZGFTT0piMfuOiRFqJBGfSHbXprSvgArNI0aKE1C0olk
|
||||
i7Am8sU8xBhp+y72oFoIs+oMFcLBBYZpiHoKbeROQAMrMbUtU8H/v9SHZ3gVyT96
|
||||
NH2pdErdAgMBAAECggEBAImI0FxQblOM45AkmmTDdPmWWjPspNGEWeF92wU55tOq
|
||||
0+yNnqa7tmg/6JkdyhJPqTQRoazr+ifUN/4rLDtDDzMSFVCpWihOxR2qTW4YjY52
|
||||
NjgU6EPbvSwLhUDiUplUcbrL3bnHqKSecxV2XYnKKdFudntRFPvmDL5GhWkL6Y8P
|
||||
9KiQaYuPf4av8PR0NlWBMiZs+CBjLlnSTMAWRYj5mRSyFSEOMT7+Lvr3TqrO2/nh
|
||||
0H30LXxrXXXuCbQXnVy3oSNf7TrathT2ADIrUUTdRHsLscvkEA35VtFQtWdJLtEg
|
||||
sso1J7viV9YDU4niPSdHPj3ubBjAExej4qCOzatsIQ0CgYEA8L5S3ojy89g7q6vB
|
||||
QuusIrjGkyM1yebDWqhEnjvlMpfrU1hCS90BM1ozZ28bjz/7PBimKL+A8BO+W0m4
|
||||
2s9YbZP5aGwo18Iq86XEdtDgWtQ3NXbYkb8F8LNtyevC/UlAI/xyIRr7hDYlr/1v
|
||||
jJg16DXiNLyk+uj4Q3EuwzNl8n8CgYEA8B5UUkOiufPtm+ZOq9AlBpIa+NYaahZM
|
||||
h52jzMTKsFB18xsZU/ufvpKvXEu1sTeCDRo3JAHmiA6AG292Zc7W+uWRtMtlmQWE
|
||||
wnoZ6hKvEkFnArLCY6Nm5Qqm1wipLwDVO3dD/CDL86siHrXK4wU7Q+bp6xbt8lDi
|
||||
itz5F7p7HKMCgYAoj8iimexlTU9wczXSsqaECyHZ9JrBc9ICWkuFZY4OYi5SEpLI
|
||||
+WmUX2Q9zyiTkDIiQ/zq7KkqygjOlLNCmqDJhZ8GCwMupxZZitp5MmQ6qXrL1URT
|
||||
+h1kGrcqyEBIMKlP5t7L2SH7eqwK5OaAh7y9bSa5v/cEF3CM3GsGlIhevQKBgBGU
|
||||
RtwW84zlnNmzDMNrY6qNe8gH9LsbktLC6cEOD0DFQz1fGIWbgGB1YL1DFbQ5uh23
|
||||
c54BPZ1sYlif2m0trXOE5xvzYCbJzqRmSAto/sQ5YY9DAxREXD4cf4ZyreAxEWtf
|
||||
Ge0VgZj/SGozKP1h3qrj9vAtJ5J79XnxH5NrJaQ9AoGBAM2rQrt8H2kizg4wMGRZ
|
||||
0G3709W7xxlbPdm+i/jFVDayJswCr0+eMm4gGyyZL3135D0fcijxytKgg3/OpOJF
|
||||
jC9vsHsE2K1ATp6eYvYjrhqJHI1m44aq/h46SfajytZQjwMT/jaApULDP2/fCBm5
|
||||
6eS2WCyHyrYJyrgoYQF56nsT
|
||||
-----END PRIVATE KEY-----
|
||||
21
packages/core/acme-client/examples/http-01/README.md
Normal file
21
packages/core/acme-client/examples/http-01/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# http-01
|
||||
|
||||
The `http-01` challenge type is the simplest to implement and should likely be your default choice, unless you either require wildcard certificates or if port 80 is unavailable for use.
|
||||
|
||||
## How it works
|
||||
|
||||
When solving `http-01` challenges, you prove ownership of a domain name by serving a specific payload from a specific URL. The ACME authority provides the client with a token that is used to generate the URL and file contents. The file must exist at `http://$YOUR_DOMAIN/.well-known/acme-challenge/$TOKEN` and contain the token and a thumbprint of your account key.
|
||||
|
||||
Once the order is finalized, the ACME authority will verify that the URL responds with the correct payload by sending HTTP requests before the challenge is valid. HTTP redirects are followed, and Let's Encrypt allows redirecting to HTTPS although this diverges from the ACME spec.
|
||||
|
||||
## Pros and cons
|
||||
|
||||
* Challenge must be satisfied using port 80 (HTTP)
|
||||
* The simplest challenge type to implement
|
||||
* Can not be used to issue wildcard certificates
|
||||
* If using multiple web servers, all of them need to respond with the correct token
|
||||
|
||||
## External links
|
||||
|
||||
* [https://letsencrypt.org/docs/challenge-types/#http-01-challenge](https://letsencrypt.org/docs/challenge-types/#http-01-challenge)
|
||||
* [https://datatracker.ietf.org/doc/html/rfc8555#section-8.3](https://datatracker.ietf.org/doc/html/rfc8555#section-8.3)
|
||||
168
packages/core/acme-client/examples/http-01/http-01.js
Normal file
168
packages/core/acme-client/examples/http-01/http-01.js
Normal file
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Example using http-01 challenge to generate certificates on-demand
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const tls = require('tls');
|
||||
const acme = require('./../../');
|
||||
|
||||
const HTTP_SERVER_PORT = 80;
|
||||
const HTTPS_SERVER_PORT = 443;
|
||||
const VALID_DOMAINS = ['example.com', 'example.org'];
|
||||
const FALLBACK_KEY = fs.readFileSync(path.join(__dirname, '..', 'fallback.key'));
|
||||
const FALLBACK_CERT = fs.readFileSync(path.join(__dirname, '..', 'fallback.crt'));
|
||||
|
||||
const pendingDomains = {};
|
||||
const challengeResponses = {};
|
||||
const certificateStore = {};
|
||||
|
||||
function log(m) {
|
||||
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* On-demand certificate generation using http-01
|
||||
*/
|
||||
|
||||
async function getCertOnDemand(client, servername, attempt = 0) {
|
||||
/* Invalid domain */
|
||||
if (!VALID_DOMAINS.includes(servername)) {
|
||||
throw new Error(`Invalid domain: ${servername}`);
|
||||
}
|
||||
|
||||
/* Certificate exists */
|
||||
if (servername in certificateStore) {
|
||||
return certificateStore[servername];
|
||||
}
|
||||
|
||||
/* Waiting on certificate order to go through */
|
||||
if (servername in pendingDomains) {
|
||||
if (attempt >= 10) {
|
||||
throw new Error(`Gave up waiting on certificate for ${servername}`);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => { setTimeout(resolve, 1000); });
|
||||
return getCertOnDemand(client, servername, (attempt + 1));
|
||||
}
|
||||
|
||||
/* Create CSR */
|
||||
log(`Creating CSR for ${servername}`);
|
||||
const [key, csr] = await acme.crypto.createCsr({
|
||||
altNames: [servername],
|
||||
});
|
||||
|
||||
/* Order certificate */
|
||||
log(`Ordering certificate for ${servername}`);
|
||||
const cert = await client.auto({
|
||||
csr,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengePriority: ['http-01'],
|
||||
challengeCreateFn: (authz, challenge, keyAuthorization) => {
|
||||
challengeResponses[challenge.token] = keyAuthorization;
|
||||
},
|
||||
challengeRemoveFn: (authz, challenge) => {
|
||||
delete challengeResponses[challenge.token];
|
||||
},
|
||||
});
|
||||
|
||||
/* Done, store certificate */
|
||||
log(`Certificate for ${servername} created successfully`);
|
||||
certificateStore[servername] = [key, cert];
|
||||
delete pendingDomains[servername];
|
||||
return certificateStore[servername];
|
||||
}
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
/**
|
||||
* Initialize ACME client
|
||||
*/
|
||||
|
||||
log('Initializing ACME client');
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: await acme.crypto.createPrivateKey(),
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTP server
|
||||
*/
|
||||
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
if (req.url.match(/\/\.well-known\/acme-challenge\/.+/)) {
|
||||
const token = req.url.split('/').pop();
|
||||
log(`Received challenge request for token=${token}`);
|
||||
|
||||
/* ACME challenge response */
|
||||
if (token in challengeResponses) {
|
||||
log(`Serving challenge response HTTP 200 token=${token}`);
|
||||
res.writeHead(200);
|
||||
res.end(challengeResponses[token]);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Challenge response not found */
|
||||
log(`Oops, challenge response not found for token=${token}`);
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
/* HTTP 302 redirect */
|
||||
log(`HTTP 302 ${req.headers.host}${req.url}`);
|
||||
res.writeHead(302, { Location: `https://${req.headers.host}${req.url}` });
|
||||
res.end();
|
||||
});
|
||||
|
||||
httpServer.listen(HTTP_SERVER_PORT, () => {
|
||||
log(`HTTP server listening on port ${HTTP_SERVER_PORT}`);
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTPS server
|
||||
*/
|
||||
|
||||
const requestListener = (req, res) => {
|
||||
log(`HTTP 200 ${req.headers.host}${req.url}`);
|
||||
res.writeHead(200);
|
||||
res.end('Hello world\n');
|
||||
};
|
||||
|
||||
const httpsServer = https.createServer({
|
||||
/* Fallback certificate */
|
||||
key: FALLBACK_KEY,
|
||||
cert: FALLBACK_CERT,
|
||||
|
||||
/* Serve certificate based on servername */
|
||||
SNICallback: async (servername, cb) => {
|
||||
try {
|
||||
log(`Handling SNI request for ${servername}`);
|
||||
const [key, cert] = await getCertOnDemand(client, servername);
|
||||
|
||||
log(`Found certificate for ${servername}, serving secure context`);
|
||||
cb(null, tls.createSecureContext({ key, cert }));
|
||||
}
|
||||
catch (e) {
|
||||
log(`[ERROR] ${e.message}`);
|
||||
cb(e.message);
|
||||
}
|
||||
},
|
||||
}, requestListener);
|
||||
|
||||
httpsServer.listen(HTTPS_SERVER_PORT, () => {
|
||||
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
log(`[FATAL] ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
})();
|
||||
44
packages/core/acme-client/examples/tls-alpn-01/README.md
Normal file
44
packages/core/acme-client/examples/tls-alpn-01/README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# tls-alpn-01
|
||||
|
||||
Responding to `tls-alpn-01` challenges using Node.js is a bit more involved than the other two challenge types, and requires a proxy (f.ex. [Nginx](https://nginx.org) or [HAProxy](https://www.haproxy.org)) in front of the Node.js service. The reason for this is that `tls-alpn-01` is solved by responding to the ACME challenge using self-signed certificates with an ALPN extension containing the challenge response.
|
||||
|
||||
Since we don't want users of our application to be served with these self-signed certificates, we need to split the HTTPS traffic into two different Node.js backends - one that only serves ALPN certificates for challenge responses, and the other for actual end-user traffic that serves certificates retrieved from the ACME provider. As far as I *(library author)* know, routing HTTPS traffic based on ALPN protocol can not be done purely using Node.js.
|
||||
|
||||
The end result should look something like this:
|
||||
|
||||
```text
|
||||
Nginx or HAProxy (0.0.0.0:443)
|
||||
*inspect requests SSL ALPN protocol*
|
||||
If ALPN == acme-tls/1
|
||||
-> Node.js ALPN responder (127.0.0.1:4444)
|
||||
Else
|
||||
-> Node.js HTTPS server (127.0.0.1:4443)
|
||||
```
|
||||
|
||||
Example proxy configuration:
|
||||
|
||||
* [haproxy.cfg](haproxy.cfg) *(requires HAProxy >= v1.9.1)*
|
||||
* [nginx.conf](nginx.conf) *(requires [ngx_stream_ssl_preread_module](https://nginx.org/en/docs/stream/ngx_stream_ssl_preread_module.html))*
|
||||
|
||||
Big thanks to [acme.sh](https://github.com/acmesh-official/acme.sh) and [dehydrated](https://github.com/dehydrated-io/dehydrated) for doing the legwork and providing Nginx and HAProxy config examples.
|
||||
|
||||
## How it works
|
||||
|
||||
When solving `tls-alpn-01` challenges, you prove ownership of a domain name by serving a specially crafted certificate over HTTPS. The ACME authority provides the client with a token that is placed into the certificates `id-pe-acmeIdentifier` extension along with a thumbprint of your account key.
|
||||
|
||||
Once the order is finalized, the ACME authority will verify by sending HTTPS requests to your domain with the `acme-tls/1` ALPN protocol, indicating to the server that it should serve the challenge response certificate. If the `id-pe-acmeIdentifier` extension contains the correct payload, the challenge is valid.
|
||||
|
||||
## Pros and cons
|
||||
|
||||
* Challenge must be satisfied using port 443 (HTTPS)
|
||||
* Useful in instances where port 80 is unavailable
|
||||
* Can not be used to issue wildcard certificates
|
||||
* More complex than `http-01`, can not be solved purely using Node.js
|
||||
* If using multiple web servers, all of them need to respond with the correct certificate
|
||||
|
||||
## External links
|
||||
|
||||
* [https://letsencrypt.org/docs/challenge-types/#tls-alpn-01](https://letsencrypt.org/docs/challenge-types/#tls-alpn-01)
|
||||
* [https://github.com/dehydrated-io/dehydrated/blob/master/docs/tls-alpn.md](https://github.com/dehydrated-io/dehydrated/blob/master/docs/tls-alpn.md)
|
||||
* [https://github.com/acmesh-official/acme.sh/wiki/TLS-ALPN-without-downtime](https://github.com/acmesh-official/acme.sh/wiki/TLS-ALPN-without-downtime)
|
||||
* [https://datatracker.ietf.org/doc/html/rfc8737](https://datatracker.ietf.org/doc/html/rfc8737)
|
||||
23
packages/core/acme-client/examples/tls-alpn-01/haproxy.cfg
Normal file
23
packages/core/acme-client/examples/tls-alpn-01/haproxy.cfg
Normal file
@@ -0,0 +1,23 @@
|
||||
##
|
||||
# HTTPS listener
|
||||
# - Send to ALPN responder port 4444 if protocol is acme-tls/1
|
||||
# - Default to HTTPS backend port 4443
|
||||
##
|
||||
|
||||
frontend https
|
||||
mode tcp
|
||||
bind :443
|
||||
tcp-request inspect-delay 5s
|
||||
tcp-request content accept if { req_ssl_hello_type 1 }
|
||||
use_backend alpnresp if { req.ssl_alpn acme-tls/1 }
|
||||
default_backend https
|
||||
|
||||
# Default HTTPS backend
|
||||
backend https
|
||||
mode tcp
|
||||
server https 127.0.0.1:4443
|
||||
|
||||
# ACME tls-alpn-01 responder backend
|
||||
backend alpnresp
|
||||
mode tcp
|
||||
server acmesh 127.0.0.1:4444
|
||||
19
packages/core/acme-client/examples/tls-alpn-01/nginx.conf
Normal file
19
packages/core/acme-client/examples/tls-alpn-01/nginx.conf
Normal file
@@ -0,0 +1,19 @@
|
||||
##
|
||||
# HTTPS server
|
||||
# - Send to ALPN responder port 4444 if protocol is acme-tls/1
|
||||
# - Default to HTTPS backend port 4443
|
||||
##
|
||||
|
||||
stream {
|
||||
map $ssl_preread_alpn_protocols $tls_port {
|
||||
~\bacme-tls/1\b 4444;
|
||||
default 4443;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443;
|
||||
listen [::]:443;
|
||||
proxy_pass 127.0.0.1:$tls_port;
|
||||
ssl_preread on;
|
||||
}
|
||||
}
|
||||
176
packages/core/acme-client/examples/tls-alpn-01/tls-alpn-01.js
Normal file
176
packages/core/acme-client/examples/tls-alpn-01/tls-alpn-01.js
Normal file
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Example using tls-alpn-01 challenge to generate certificates on-demand
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
const tls = require('tls');
|
||||
const acme = require('./../../');
|
||||
|
||||
const HTTPS_SERVER_PORT = 4443;
|
||||
const ALPN_RESPONDER_PORT = 4444;
|
||||
const VALID_DOMAINS = ['example.com', 'example.org'];
|
||||
const FALLBACK_KEY = fs.readFileSync(path.join(__dirname, '..', 'fallback.key'));
|
||||
const FALLBACK_CERT = fs.readFileSync(path.join(__dirname, '..', 'fallback.crt'));
|
||||
|
||||
const pendingDomains = {};
|
||||
const alpnResponses = {};
|
||||
const certificateStore = {};
|
||||
|
||||
function log(m) {
|
||||
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* On-demand certificate generation using tls-alpn-01
|
||||
*/
|
||||
|
||||
async function getCertOnDemand(client, servername, attempt = 0) {
|
||||
/* Invalid domain */
|
||||
if (!VALID_DOMAINS.includes(servername)) {
|
||||
throw new Error(`Invalid domain: ${servername}`);
|
||||
}
|
||||
|
||||
/* Certificate exists */
|
||||
if (servername in certificateStore) {
|
||||
return certificateStore[servername];
|
||||
}
|
||||
|
||||
/* Waiting on certificate order to go through */
|
||||
if (servername in pendingDomains) {
|
||||
if (attempt >= 10) {
|
||||
throw new Error(`Gave up waiting on certificate for ${servername}`);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => { setTimeout(resolve, 1000); });
|
||||
return getCertOnDemand(client, servername, (attempt + 1));
|
||||
}
|
||||
|
||||
/* Create CSR */
|
||||
log(`Creating CSR for ${servername}`);
|
||||
const [key, csr] = await acme.crypto.createCsr({
|
||||
altNames: [servername],
|
||||
});
|
||||
|
||||
/* Order certificate */
|
||||
log(`Ordering certificate for ${servername}`);
|
||||
const cert = await client.auto({
|
||||
csr,
|
||||
email: 'test@example.com',
|
||||
termsOfServiceAgreed: true,
|
||||
challengePriority: ['tls-alpn-01'],
|
||||
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
|
||||
alpnResponses[authz.identifier.value] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization);
|
||||
},
|
||||
challengeRemoveFn: (authz) => {
|
||||
delete alpnResponses[authz.identifier.value];
|
||||
},
|
||||
});
|
||||
|
||||
/* Done, store certificate */
|
||||
log(`Certificate for ${servername} created successfully`);
|
||||
certificateStore[servername] = [key, cert];
|
||||
delete pendingDomains[servername];
|
||||
return certificateStore[servername];
|
||||
}
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
/**
|
||||
* Initialize ACME client
|
||||
*/
|
||||
|
||||
log('Initializing ACME client');
|
||||
const client = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: await acme.crypto.createPrivateKey(),
|
||||
});
|
||||
|
||||
/**
|
||||
* ALPN responder
|
||||
*/
|
||||
|
||||
const alpnResponder = https.createServer({
|
||||
/* Fallback cert */
|
||||
key: FALLBACK_KEY,
|
||||
cert: FALLBACK_CERT,
|
||||
|
||||
/* Allow acme-tls/1 ALPN protocol */
|
||||
ALPNProtocols: ['acme-tls/1'],
|
||||
|
||||
/* Serve ALPN certificate based on servername */
|
||||
SNICallback: async (servername, cb) => {
|
||||
try {
|
||||
log(`Handling ALPN SNI request for ${servername}`);
|
||||
if (!Object.keys(alpnResponses).includes(servername)) {
|
||||
throw new Error(`No ALPN certificate found for ${servername}`);
|
||||
}
|
||||
|
||||
/* Serve ALPN challenge response */
|
||||
log(`Found ALPN certificate for ${servername}, serving secure context`);
|
||||
cb(null, tls.createSecureContext({
|
||||
key: alpnResponses[servername][0],
|
||||
cert: alpnResponses[servername][1],
|
||||
}));
|
||||
}
|
||||
catch (e) {
|
||||
log(`[ERROR] ${e.message}`);
|
||||
cb(e.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/* Terminate once TLS handshake has been established */
|
||||
alpnResponder.on('secureConnection', (socket) => {
|
||||
socket.end();
|
||||
});
|
||||
|
||||
alpnResponder.listen(ALPN_RESPONDER_PORT, () => {
|
||||
log(`ALPN responder listening on port ${ALPN_RESPONDER_PORT}`);
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTPS server
|
||||
*/
|
||||
|
||||
const requestListener = (req, res) => {
|
||||
log(`HTTP 200 ${req.headers.host}${req.url}`);
|
||||
res.writeHead(200);
|
||||
res.end('Hello world\n');
|
||||
};
|
||||
|
||||
const httpsServer = https.createServer({
|
||||
/* Fallback cert */
|
||||
key: FALLBACK_KEY,
|
||||
cert: FALLBACK_CERT,
|
||||
|
||||
/* Serve certificate based on servername */
|
||||
SNICallback: async (servername, cb) => {
|
||||
try {
|
||||
log(`Handling SNI request for ${servername}`);
|
||||
const [key, cert] = await getCertOnDemand(client, servername);
|
||||
|
||||
log(`Found certificate for ${servername}, serving secure context`);
|
||||
cb(null, tls.createSecureContext({ key, cert }));
|
||||
}
|
||||
catch (e) {
|
||||
log(`[ERROR] ${e.message}`);
|
||||
cb(e.message);
|
||||
}
|
||||
},
|
||||
}, requestListener);
|
||||
|
||||
httpsServer.listen(HTTPS_SERVER_PORT, () => {
|
||||
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
log(`[FATAL] ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
})();
|
||||
58
packages/core/acme-client/package.json
Normal file
58
packages/core/acme-client/package.json
Normal file
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "acme-client",
|
||||
"description": "Simple and unopinionated ACME client",
|
||||
"author": "nmorsman",
|
||||
"version": "5.4.0",
|
||||
"main": "src/index.js",
|
||||
"types": "types/index.d.ts",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/publishlab/node-acme-client",
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"types"
|
||||
],
|
||||
"dependencies": {
|
||||
"@peculiar/x509": "^1.11.0",
|
||||
"asn1js": "^3.0.5",
|
||||
"axios": "^1.7.2",
|
||||
"debug": "^4.3.5",
|
||||
"node-forge": "^1.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.10",
|
||||
"chai": "^4.4.1",
|
||||
"chai-as-promised": "^7.1.2",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"jsdoc-to-markdown": "^8.0.1",
|
||||
"mocha": "^10.6.0",
|
||||
"nock": "^13.5.4",
|
||||
"tsd": "^0.31.1"
|
||||
},
|
||||
"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": "tsd",
|
||||
"prepublishOnly": "npm run build-docs",
|
||||
"test": "mocha -t 60000 \"test/setup.js\" \"test/**/*.spec.js\""
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
234
packages/core/acme-client/src/api.js
Normal file
234
packages/core/acme-client/src/api.js
Normal file
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* 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 {number[]} [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 {number[]} [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://datatracker.ietf.org/doc/html/rfc8555#section-7.1.1
|
||||
*
|
||||
* @returns {Promise<string|null>} ToS URL
|
||||
*/
|
||||
|
||||
async getTermsOfServiceUrl() {
|
||||
return this.http.getMetaField('termsOfService');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new account
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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;
|
||||
182
packages/core/acme-client/src/auto.js
Normal file
182
packages/core/acme-client/src/auto.js
Normal file
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* 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 (client, userOpts) => {
|
||||
const opts = { ...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 { commonName, altNames } = readCsrDomains(opts.csr);
|
||||
const uniqueDomains = Array.from(new Set([commonName].concat(altNames).filter((d) => d)));
|
||||
|
||||
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 challengePromises = authorizations.map(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);
|
||||
|
||||
try {
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
/* Trigger challengeRemoveFn(), suppress errors */
|
||||
log(`[auto] [${d}] Trigger challengeRemoveFn()`);
|
||||
|
||||
try {
|
||||
await opts.challengeRemoveFn(authz, challenge, keyAuthorization);
|
||||
}
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Wait for all challenge promises to settle
|
||||
*/
|
||||
|
||||
try {
|
||||
log('[auto] Waiting for challenge valid status');
|
||||
await Promise.all(challengePromises);
|
||||
}
|
||||
catch (e) {
|
||||
await Promise.allSettled(challengePromises);
|
||||
throw e;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
};
|
||||
123
packages/core/acme-client/src/axios.js
Normal file
123
packages/core/acme-client/src/axios.js
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Axios instance
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const { parseRetryAfterHeader } = require('./util');
|
||||
const { log } = require('./logger');
|
||||
const pkg = require('./../package.json');
|
||||
|
||||
const { AxiosError } = axios;
|
||||
|
||||
/**
|
||||
* Defaults
|
||||
*/
|
||||
|
||||
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,
|
||||
httpsChallengePort: 443,
|
||||
tlsAlpnChallengePort: 443,
|
||||
|
||||
retryMaxAttempts: 5,
|
||||
retryDefaultDelay: 5,
|
||||
};
|
||||
|
||||
/**
|
||||
* Explicitly set Node as default HTTP adapter
|
||||
*
|
||||
* https://github.com/axios/axios/issues/1180
|
||||
* https://stackoverflow.com/questions/42677387
|
||||
*/
|
||||
|
||||
instance.defaults.adapter = 'http';
|
||||
|
||||
/**
|
||||
* Retry requests on server errors or when rate limited
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-6.6
|
||||
*/
|
||||
|
||||
function isRetryableError(error) {
|
||||
return (error.code !== 'ECONNABORTED')
|
||||
&& (error.code !== 'ERR_NOCK_NO_MATCH')
|
||||
&& (!error.response
|
||||
|| (error.response.status === 429)
|
||||
|| ((error.response.status >= 500) && (error.response.status <= 599)));
|
||||
}
|
||||
|
||||
/* https://github.com/axios/axios/blob/main/lib/core/settle.js */
|
||||
function validateStatus(response) {
|
||||
const validator = response.config.retryValidateStatus;
|
||||
|
||||
if (!response.status || !validator || validator(response.status)) {
|
||||
return response;
|
||||
}
|
||||
|
||||
throw new AxiosError(
|
||||
`Request failed with status code ${response.status}`,
|
||||
(Math.floor(response.status / 100) === 4) ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE,
|
||||
response.config,
|
||||
response.request,
|
||||
response,
|
||||
);
|
||||
}
|
||||
|
||||
/* Pass all responses through the error interceptor */
|
||||
instance.interceptors.request.use((config) => {
|
||||
if (!('retryValidateStatus' in config)) {
|
||||
config.retryValidateStatus = config.validateStatus;
|
||||
}
|
||||
|
||||
config.validateStatus = () => false;
|
||||
return config;
|
||||
});
|
||||
|
||||
/* Handle request retries if applicable */
|
||||
instance.interceptors.response.use(null, async (error) => {
|
||||
const { config, response } = error;
|
||||
|
||||
if (!config) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
/* Pick up errors we want to retry */
|
||||
if (isRetryableError(error)) {
|
||||
const { retryMaxAttempts, retryDefaultDelay } = instance.defaults.acmeSettings;
|
||||
config.retryAttempt = ('retryAttempt' in config) ? (config.retryAttempt + 1) : 1;
|
||||
|
||||
if (config.retryAttempt <= retryMaxAttempts) {
|
||||
const code = response ? `HTTP ${response.status}` : error.code;
|
||||
log(`Caught ${code}, retry attempt ${config.retryAttempt}/${retryMaxAttempts} to URL ${config.url}`);
|
||||
|
||||
/* Attempt to parse Retry-After header, fallback to default delay */
|
||||
let retryAfter = response ? parseRetryAfterHeader(response.headers['retry-after']) : 0;
|
||||
|
||||
if (retryAfter > 0) {
|
||||
log(`Found retry-after response header with value: ${response.headers['retry-after']}, waiting ${retryAfter} seconds`);
|
||||
}
|
||||
else {
|
||||
retryAfter = (retryDefaultDelay * config.retryAttempt);
|
||||
log(`Unable to locate or parse retry-after response header, waiting ${retryAfter} seconds`);
|
||||
}
|
||||
|
||||
/* Wait and retry the request */
|
||||
await new Promise((resolve) => { setTimeout(resolve, (retryAfter * 1000)); });
|
||||
return instance(config);
|
||||
}
|
||||
}
|
||||
|
||||
/* Validate and return response */
|
||||
return validateStatus(response);
|
||||
});
|
||||
|
||||
/**
|
||||
* Export instance
|
||||
*/
|
||||
|
||||
module.exports = instance;
|
||||
708
packages/core/acme-client/src/client.js
Normal file
708
packages/core/acme-client/src/client.js
Normal file
@@ -0,0 +1,708 @@
|
||||
/**
|
||||
* 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 = { ...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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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, this.opts.externalAccountBinding);
|
||||
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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/html/rfc8555#section-8.3 */
|
||||
if (challenge.type === 'http-01') {
|
||||
return result;
|
||||
}
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc8555#section-8.4 */
|
||||
if (challenge.type === 'dns-01') {
|
||||
return createHash('sha256').update(result).digest('base64url');
|
||||
}
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc8737 */
|
||||
if (challenge.type === 'tls-alpn-01') {
|
||||
return result;
|
||||
}
|
||||
|
||||
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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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 authorization 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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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({
|
||||
* altNames: ['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({
|
||||
* altNames: ['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;
|
||||
435
packages/core/acme-client/src/crypto/forge.js
Normal file
435
packages/core/acme-client/src/crypto/forge.js
Normal file
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* 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 (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 (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 (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 (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 (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://datatracker.ietf.org/doc/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 {string[]} [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({
|
||||
* altNames: ['test.example.com'],
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with both common and alternative names
|
||||
* > *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
|
||||
* ```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({
|
||||
* altNames: ['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({
|
||||
* altNames: ['test.example.com'],
|
||||
* }, certificateKey);
|
||||
*/
|
||||
|
||||
exports.createCsr = async (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)];
|
||||
};
|
||||
604
packages/core/acme-client/src/crypto/index.js
Normal file
604
packages/core/acme-client/src/crypto/index.js
Normal file
@@ -0,0 +1,604 @@
|
||||
/**
|
||||
* Native Node.js crypto interface
|
||||
*
|
||||
* @namespace crypto
|
||||
*/
|
||||
|
||||
const net = require('net');
|
||||
const { promisify } = require('util');
|
||||
const crypto = require('crypto');
|
||||
const asn1js = require('asn1js');
|
||||
const x509 = require('@peculiar/x509');
|
||||
|
||||
const randomInt = promisify(crypto.randomInt);
|
||||
const generateKeyPair = promisify(crypto.generateKeyPair);
|
||||
|
||||
/* Use Node.js Web Crypto API */
|
||||
x509.cryptoProvider.set(crypto.webcrypto);
|
||||
|
||||
/* id-ce-subjectAltName - https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6 */
|
||||
const subjectAltNameOID = '2.5.29.17';
|
||||
|
||||
/* id-pe-acmeIdentifier - https://datatracker.ietf.org/doc/html/rfc8737#section-6.1 */
|
||||
const alpnAcmeIdentifierOID = '1.3.6.1.5.5.7.1.31';
|
||||
|
||||
/**
|
||||
* 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,
|
||||
publicKey: crypto.createPublicKey(keyPem),
|
||||
};
|
||||
|
||||
if (result.publicKey.asymmetricKeyType === 'rsa') {
|
||||
result.isRSA = true;
|
||||
}
|
||||
else if (result.publicKey.asymmetricKeyType === 'ec') {
|
||||
result.isECDSA = true;
|
||||
}
|
||||
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;
|
||||
|
||||
/**
|
||||
* Produce CryptoKeyPair and signing algorithm from a PEM encoded private key
|
||||
*
|
||||
* @private
|
||||
* @param {buffer|string} keyPem PEM encoded private key
|
||||
* @returns {Promise<array>} [keyPair, signingAlgorithm]
|
||||
*/
|
||||
|
||||
async function getWebCryptoKeyPair(keyPem) {
|
||||
const info = getKeyInfo(keyPem);
|
||||
const jwk = getJwk(keyPem);
|
||||
|
||||
/* Signing algorithm */
|
||||
const sigalg = {
|
||||
name: 'RSASSA-PKCS1-v1_5',
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
|
||||
if (info.isECDSA) {
|
||||
sigalg.name = 'ECDSA';
|
||||
sigalg.namedCurve = jwk.crv;
|
||||
|
||||
if (jwk.crv === 'P-384') {
|
||||
sigalg.hash.name = 'SHA-384';
|
||||
}
|
||||
|
||||
if (jwk.crv === 'P-521') {
|
||||
sigalg.hash.name = 'SHA-512';
|
||||
}
|
||||
}
|
||||
|
||||
/* Decode PEM and import into CryptoKeyPair */
|
||||
const privateKeyDec = x509.PemConverter.decodeFirst(keyPem.toString());
|
||||
const privateKey = await crypto.webcrypto.subtle.importKey('pkcs8', privateKeyDec, sigalg, true, ['sign']);
|
||||
const publicKey = await crypto.webcrypto.subtle.importKey('jwk', jwk, sigalg, true, ['verify']);
|
||||
|
||||
return [{ privateKey, publicKey }, sigalg];
|
||||
}
|
||||
|
||||
/**
|
||||
* Split chain of PEM encoded objects from string into array
|
||||
*
|
||||
* @param {buffer|string} chainPem PEM encoded object chain
|
||||
* @returns {string[]} Array of PEM objects including headers
|
||||
*/
|
||||
|
||||
function splitPemChain(chainPem) {
|
||||
if (Buffer.isBuffer(chainPem)) {
|
||||
chainPem = chainPem.toString();
|
||||
}
|
||||
|
||||
/* Decode into array and re-encode */
|
||||
return x509.PemConverter.decodeWithHeaders(chainPem)
|
||||
.map((params) => x509.PemConverter.encode([params]));
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
/* Select first object, extract body and convert to b64u */
|
||||
const dec = x509.PemConverter.decodeFirst(chain[0]);
|
||||
return Buffer.from(dec).toString('base64url');
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse domains from a certificate or CSR
|
||||
*
|
||||
* @private
|
||||
* @param {object} input x509.Certificate or x509.Pkcs10CertificateRequest
|
||||
* @returns {object} {commonName, altNames}
|
||||
*/
|
||||
|
||||
function parseDomains(input) {
|
||||
const commonName = input.subjectName.getField('CN').pop() || null;
|
||||
const altNamesRaw = input.getExtension(subjectAltNameOID);
|
||||
let altNames = [];
|
||||
|
||||
if (altNamesRaw) {
|
||||
const altNamesExt = new x509.SubjectAlternativeNameExtension(altNamesRaw.rawData);
|
||||
altNames = altNames.concat(altNamesExt.names.items.map((i) => i.value));
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
const dec = x509.PemConverter.decodeFirst(csrPem);
|
||||
const csr = new x509.Pkcs10CertificateRequest(dec);
|
||||
return parseDomains(csr);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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) => {
|
||||
if (Buffer.isBuffer(certPem)) {
|
||||
certPem = certPem.toString();
|
||||
}
|
||||
|
||||
const dec = x509.PemConverter.decodeFirst(certPem);
|
||||
const cert = new x509.X509Certificate(dec);
|
||||
|
||||
return {
|
||||
issuer: {
|
||||
commonName: cert.issuerName.getField('CN').pop() || null,
|
||||
},
|
||||
domains: parseDomains(cert),
|
||||
notBefore: cert.notBefore,
|
||||
notAfter: cert.notAfter,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Determine ASN.1 character string type for CSR subject field name
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc5280
|
||||
* https://github.com/PeculiarVentures/x509/blob/ecf78224fd594abbc2fa83c41565d79874f88e00/src/name.ts#L65-L71
|
||||
*
|
||||
* @private
|
||||
* @param {string} field CSR subject field name
|
||||
* @returns {string} ASN.1 character string type
|
||||
*/
|
||||
|
||||
function getCsrAsn1CharStringType(field) {
|
||||
switch (field) {
|
||||
case 'C':
|
||||
return 'printableString';
|
||||
case 'E':
|
||||
return 'ia5String';
|
||||
default:
|
||||
return 'utf8String';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create array of subject fields for a Certificate Signing Request
|
||||
*
|
||||
* https://github.com/PeculiarVentures/x509/blob/ecf78224fd594abbc2fa83c41565d79874f88e00/src/name.ts#L65-L71
|
||||
*
|
||||
* @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]: [{ [ds]: value }] });
|
||||
}
|
||||
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create x509 subject alternate name extension
|
||||
*
|
||||
* https://github.com/PeculiarVentures/x509/blob/ecf78224fd594abbc2fa83c41565d79874f88e00/src/extensions/subject_alt_name.ts
|
||||
*
|
||||
* @private
|
||||
* @param {string[]} altNames Array of alt names
|
||||
* @returns {x509.SubjectAlternativeNameExtension} Subject alternate name extension
|
||||
*/
|
||||
|
||||
function createSubjectAltNameExtension(altNames) {
|
||||
return new x509.SubjectAlternativeNameExtension(altNames.map((value) => {
|
||||
const type = net.isIP(value) ? 'ip' : 'dns';
|
||||
return { type, 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 {string[]} [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 {buffer|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({
|
||||
* altNames: ['test.example.com'],
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example Certificate Signing Request with both common and alternative names
|
||||
* > *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
|
||||
* ```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({
|
||||
* altNames: ['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({
|
||||
* altNames: ['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 = [];
|
||||
}
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
/* CryptoKeyPair and signing algorithm from private key */
|
||||
const [keys, signingAlgorithm] = await getWebCryptoKeyPair(keyPem);
|
||||
|
||||
const extensions = [
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3 */
|
||||
new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment), // eslint-disable-line no-bitwise
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6 */
|
||||
createSubjectAltNameExtension(data.altNames),
|
||||
];
|
||||
|
||||
/* Create CSR */
|
||||
const csr = await x509.Pkcs10CertificateRequestGenerator.create({
|
||||
keys,
|
||||
extensions,
|
||||
signingAlgorithm,
|
||||
name: createCsrSubject({
|
||||
CN: data.commonName,
|
||||
C: data.country,
|
||||
ST: data.state,
|
||||
L: data.locality,
|
||||
O: data.organization,
|
||||
OU: data.organizationUnit,
|
||||
E: data.emailAddress,
|
||||
}),
|
||||
});
|
||||
|
||||
/* Done */
|
||||
const pem = csr.toString('pem');
|
||||
return [keyPem, Buffer.from(pem)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a self-signed ALPN certificate for TLS-ALPN-01 challenges
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8737
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @param {string} keyAuthorization Challenge key authorization
|
||||
* @param {buffer|string} [keyPem] PEM encoded CSR private key
|
||||
* @returns {Promise<buffer[]>} [privateKey, certificate]
|
||||
*
|
||||
* @example Create a ALPN certificate
|
||||
* ```js
|
||||
* const [alpnKey, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization);
|
||||
* ```
|
||||
*
|
||||
* @example Create a ALPN certificate with ECDSA private key
|
||||
* ```js
|
||||
* const alpnKey = await acme.crypto.createPrivateEcdsaKey();
|
||||
* const [, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization, alpnKey);
|
||||
* ```
|
||||
*/
|
||||
|
||||
exports.createAlpnCertificate = async (authz, keyAuthorization, keyPem = null) => {
|
||||
if (!keyPem) {
|
||||
keyPem = await createPrivateRsaKey();
|
||||
}
|
||||
else if (!Buffer.isBuffer(keyPem)) {
|
||||
keyPem = Buffer.from(keyPem);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const commonName = authz.identifier.value;
|
||||
|
||||
/* Pseudo-random serial - max 20 bytes, 11 for epoch (year 5138), 9 random */
|
||||
const random = await randomInt(1, 999999999);
|
||||
const serialNumber = `${Math.floor(now.getTime() / 1000)}${random}`;
|
||||
|
||||
/* CryptoKeyPair and signing algorithm from private key */
|
||||
const [keys, signingAlgorithm] = await getWebCryptoKeyPair(keyPem);
|
||||
|
||||
const extensions = [
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3 */
|
||||
new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), // eslint-disable-line no-bitwise
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.9 */
|
||||
new x509.BasicConstraintsExtension(true, 2, true),
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.2 */
|
||||
await x509.SubjectKeyIdentifierExtension.create(keys.publicKey),
|
||||
|
||||
/* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6 */
|
||||
createSubjectAltNameExtension([commonName]),
|
||||
];
|
||||
|
||||
/* ALPN extension */
|
||||
const payload = crypto.createHash('sha256').update(keyAuthorization).digest('hex');
|
||||
const octstr = new asn1js.OctetString({ valueHex: Buffer.from(payload, 'hex') });
|
||||
extensions.push(new x509.Extension(alpnAcmeIdentifierOID, true, octstr.toBER()));
|
||||
|
||||
/* Self-signed ALPN certificate */
|
||||
const cert = await x509.X509CertificateGenerator.createSelfSigned({
|
||||
keys,
|
||||
signingAlgorithm,
|
||||
extensions,
|
||||
serialNumber,
|
||||
notBefore: now,
|
||||
notAfter: now,
|
||||
name: createCsrSubject({
|
||||
CN: commonName,
|
||||
}),
|
||||
});
|
||||
|
||||
/* Done */
|
||||
const pem = cert.toString('pem');
|
||||
return [keyPem, Buffer.from(pem)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate that a ALPN certificate contains the expected key authorization
|
||||
*
|
||||
* @param {buffer|string} certPem PEM encoded certificate
|
||||
* @param {string} keyAuthorization Expected challenge key authorization
|
||||
* @returns {boolean} True when valid
|
||||
*/
|
||||
|
||||
exports.isAlpnCertificateAuthorizationValid = (certPem, keyAuthorization) => {
|
||||
const expected = crypto.createHash('sha256').update(keyAuthorization).digest('hex');
|
||||
|
||||
/* Attempt to locate ALPN extension */
|
||||
const cert = new x509.X509Certificate(certPem);
|
||||
const ext = cert.getExtension(alpnAcmeIdentifierOID);
|
||||
|
||||
if (!ext) {
|
||||
throw new Error('Unable to locate ALPN extension within parsed certificate');
|
||||
}
|
||||
|
||||
/* Decode extension value */
|
||||
const parsed = asn1js.fromBER(ext.value);
|
||||
const result = Buffer.from(parsed.result.valueBlock.valueHexView).toString('hex');
|
||||
|
||||
/* Return true if match */
|
||||
return (result === expected);
|
||||
};
|
||||
316
packages/core/acme-client/src/http.js
Normal file
316
packages/core/acme-client/src/http.js
Normal file
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* 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.jwk = null;
|
||||
|
||||
this.directoryCache = null;
|
||||
this.directoryMaxAge = 86400;
|
||||
this.directoryTimestamp = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ACME provider directory
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-7.1.1
|
||||
*
|
||||
* @returns {Promise<object>} ACME directory contents
|
||||
*/
|
||||
|
||||
async getDirectory() {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const age = (now - this.directoryTimestamp);
|
||||
|
||||
if (!this.directoryCache || (age > this.directoryMaxAge)) {
|
||||
log(`Refreshing ACME directory, age: ${age}`);
|
||||
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.directoryCache = resp.data;
|
||||
this.directoryTimestamp = now;
|
||||
}
|
||||
|
||||
return this.directoryCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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://datatracker.ietf.org/doc/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) {
|
||||
const dir = await this.getDirectory();
|
||||
|
||||
if (!dir[resource]) {
|
||||
throw new Error(`Unable to locate API resource URL in ACME directory: "${resource}"`);
|
||||
}
|
||||
|
||||
return dir[resource];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get directory meta field
|
||||
*
|
||||
* @param {string} field Meta field name
|
||||
* @returns {Promise<string|null>} Meta field value
|
||||
*/
|
||||
|
||||
async getMetaField(field) {
|
||||
const dir = await this.getDirectory();
|
||||
|
||||
if (('meta' in dir) && (field in dir.meta)) {
|
||||
return dir.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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/html/rfc8555#section-6.5 */
|
||||
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',
|
||||
},
|
||||
google: {
|
||||
staging: 'https://dv.acme-v02.test-api.pki.goog/directory',
|
||||
production: 'https://dv.acme-v02.api.pki.goog/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;
|
||||
28
packages/core/acme-client/src/logger.js
Normal file
28
packages/core/acme-client/src/logger.js
Normal file
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 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} msg Message
|
||||
*/
|
||||
|
||||
exports.log = (msg) => {
|
||||
debug(msg);
|
||||
logger(msg);
|
||||
};
|
||||
340
packages/core/acme-client/src/util.js
Normal file
340
packages/core/acme-client/src/util.js
Normal file
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* Utility methods
|
||||
*/
|
||||
|
||||
const tls = require('tls');
|
||||
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
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-7.4.2
|
||||
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
|
||||
*
|
||||
* @param {string} header Header contents
|
||||
* @param {string} rel Link relation, default: `alternate`
|
||||
* @returns {string[]} 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse date or duration from Retry-After header
|
||||
*
|
||||
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
||||
*
|
||||
* @param {string} header Header contents
|
||||
* @returns {number} Retry duration in seconds
|
||||
*/
|
||||
|
||||
function parseRetryAfterHeader(header) {
|
||||
const sec = parseInt(header, 10);
|
||||
const date = new Date(header);
|
||||
|
||||
/* Seconds into the future */
|
||||
if (Number.isSafeInteger(sec) && (sec > 0)) {
|
||||
return sec;
|
||||
}
|
||||
|
||||
/* Future date string */
|
||||
if (date instanceof Date && !Number.isNaN(date)) {
|
||||
const now = new Date();
|
||||
const diff = Math.ceil((date.getTime() - now.getTime()) / 1000);
|
||||
|
||||
if (diff > 0) {
|
||||
return diff;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {string[]} 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) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to retrieve TLS ALPN certificate from peer
|
||||
*
|
||||
* https://nodejs.org/api/tls.html#tlsconnectoptions-callback
|
||||
*
|
||||
* @param {string} host Host the TLS client should connect to
|
||||
* @param {number} port Port the client should connect to
|
||||
* @param {string} servername Server name for the SNI (Server Name Indication)
|
||||
* @returns {Promise<string>} PEM encoded certificate
|
||||
*/
|
||||
|
||||
async function retrieveTlsAlpnCertificate(host, port, timeout = 30000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let result;
|
||||
|
||||
/* TLS connection */
|
||||
const socket = tls.connect({
|
||||
host,
|
||||
port,
|
||||
servername: host,
|
||||
rejectUnauthorized: false,
|
||||
ALPNProtocols: ['acme-tls/1'],
|
||||
});
|
||||
|
||||
socket.setTimeout(timeout);
|
||||
socket.setEncoding('utf-8');
|
||||
|
||||
/* Grab certificate once connected and close */
|
||||
socket.on('secureConnect', () => {
|
||||
result = socket.getPeerX509Certificate();
|
||||
socket.end();
|
||||
});
|
||||
|
||||
/* Errors */
|
||||
socket.on('error', (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
socket.on('timeout', () => {
|
||||
socket.destroy(new Error('TLS ALPN certificate lookup request timed out'));
|
||||
});
|
||||
|
||||
/* Done, return cert as PEM if found */
|
||||
socket.on('end', () => {
|
||||
if (result) {
|
||||
return resolve(result.toString());
|
||||
}
|
||||
|
||||
return reject(new Error('TLS ALPN lookup failed to retrieve certificate'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Export utils
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
retry,
|
||||
parseLinkHeader,
|
||||
parseRetryAfterHeader,
|
||||
findCertificateChainForIssuer,
|
||||
formatResponseError,
|
||||
getAuthoritativeDnsResolver,
|
||||
retrieveTlsAlpnCertificate,
|
||||
};
|
||||
156
packages/core/acme-client/src/verify.js
Normal file
156
packages/core/acme-client/src/verify.js
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* ACME challenge verification
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const https = require('https');
|
||||
const { log } = require('./logger');
|
||||
const axios = require('./axios');
|
||||
const util = require('./util');
|
||||
const { isAlpnCertificateAuthorizationValid } = require('./crypto');
|
||||
|
||||
/**
|
||||
* Verify ACME HTTP challenge
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/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}`;
|
||||
|
||||
/* May redirect to HTTPS with invalid/self-signed cert - https://letsencrypt.org/docs/challenge-types/#http-01-challenge */
|
||||
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
||||
|
||||
log(`Sending HTTP query to ${authz.identifier.value}, suffix: ${suffix}, port: ${httpPort}`);
|
||||
const resp = await axios.get(challengeUrl, { httpsAgent });
|
||||
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://datatracker.ietf.org/doc/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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify ACME TLS ALPN challenge
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8737
|
||||
*
|
||||
* @param {object} authz Identifier authorization
|
||||
* @param {object} challenge Authorization challenge
|
||||
* @param {string} keyAuthorization Challenge key authorization
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
|
||||
async function verifyTlsAlpnChallenge(authz, challenge, keyAuthorization) {
|
||||
const tlsAlpnPort = axios.defaults.acmeSettings.tlsAlpnChallengePort || 443;
|
||||
const host = authz.identifier.value;
|
||||
log(`Establishing TLS connection with host: ${host}:${tlsAlpnPort}`);
|
||||
|
||||
const certificate = await util.retrieveTlsAlpnCertificate(host, tlsAlpnPort);
|
||||
log('Certificate received from server successfully, matching key authorization in ALPN');
|
||||
|
||||
if (!isAlpnCertificateAuthorizationValid(certificate, keyAuthorization)) {
|
||||
throw new Error(`Authorization not found in certificate from ${authz.identifier.value}`);
|
||||
}
|
||||
|
||||
log(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export API
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
'http-01': verifyHttpChallenge,
|
||||
'dns-01': verifyDnsChallenge,
|
||||
'tls-alpn-01': verifyTlsAlpnChallenge,
|
||||
};
|
||||
208
packages/core/acme-client/test/00-pebble.spec.js
Normal file
208
packages/core/acme-client/test/00-pebble.spec.js
Normal file
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Pebble Challenge Test Server tests
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const { randomUUID: uuid } = require('crypto');
|
||||
const https = require('https');
|
||||
const { assert } = require('chai');
|
||||
const cts = require('./challtestsrv');
|
||||
const axios = require('./../src/axios');
|
||||
const { retrieveTlsAlpnCertificate } = require('./../src/util');
|
||||
const { isAlpnCertificateAuthorizationValid } = require('./../src/crypto');
|
||||
|
||||
const domainName = process.env.ACME_DOMAIN_NAME || 'example.com';
|
||||
const httpPort = axios.defaults.acmeSettings.httpChallengePort || 80;
|
||||
const httpsPort = axios.defaults.acmeSettings.httpsChallengePort || 443;
|
||||
const tlsAlpnPort = axios.defaults.acmeSettings.tlsAlpnChallengePort || 443;
|
||||
|
||||
describe('pebble', () => {
|
||||
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
||||
|
||||
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 testHttps01ChallengeHost = `${uuid()}.${domainName}`;
|
||||
const testHttps01ChallengeToken = uuid();
|
||||
const testHttps01ChallengeContent = uuid();
|
||||
|
||||
const testDns01ChallengeHost = `_acme-challenge.${uuid()}.${domainName}.`;
|
||||
const testDns01ChallengeValue = uuid();
|
||||
|
||||
const testTlsAlpn01ChallengeHost = `${uuid()}.${domainName}`;
|
||||
const testTlsAlpn01ChallengeValue = 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]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTP-01 challenge response
|
||||
*/
|
||||
|
||||
describe('http-01', () => {
|
||||
it('should not locate 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 challenge response', async () => {
|
||||
const resp = await cts.addHttp01ChallengeResponse(testHttp01ChallengeToken, testHttp01ChallengeContent);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate 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);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTPS-01 challenge response
|
||||
*/
|
||||
|
||||
describe('https-01', () => {
|
||||
it('should not locate challenge response', async () => {
|
||||
const r1 = await axios.get(`http://${testHttps01ChallengeHost}:${httpPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, { httpsAgent });
|
||||
const r2 = await axios.get(`https://${testHttps01ChallengeHost}:${httpsPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, { httpsAgent });
|
||||
|
||||
[r1, r2].forEach((resp) => {
|
||||
assert.isString(resp.data);
|
||||
assert.notEqual(resp.data, testHttps01ChallengeContent);
|
||||
});
|
||||
});
|
||||
|
||||
it('should add challenge response', async () => {
|
||||
const resp = await cts.addHttps01ChallengeResponse(testHttps01ChallengeToken, testHttps01ChallengeContent, testHttps01ChallengeHost);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should 302 with self-signed cert', async () => {
|
||||
/* Assert HTTP 302 */
|
||||
const resp = await axios.get(`http://${testHttps01ChallengeHost}:${httpPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, {
|
||||
maxRedirects: 0,
|
||||
validateStatus: null,
|
||||
});
|
||||
|
||||
assert.strictEqual(resp.status, 302);
|
||||
assert.strictEqual(resp.headers.location, `https://${testHttps01ChallengeHost}:${httpsPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`);
|
||||
|
||||
/* Self-signed cert test */
|
||||
await assert.isRejected(axios.get(`https://${testHttps01ChallengeHost}:${httpsPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`));
|
||||
await assert.isFulfilled(axios.get(`https://${testHttps01ChallengeHost}:${httpsPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, { httpsAgent }));
|
||||
});
|
||||
|
||||
it('should locate challenge response', async () => {
|
||||
const r1 = await axios.get(`http://${testHttps01ChallengeHost}:${httpPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, { httpsAgent });
|
||||
const r2 = await axios.get(`https://${testHttps01ChallengeHost}:${httpsPort}/.well-known/acme-challenge/${testHttps01ChallengeToken}`, { httpsAgent });
|
||||
|
||||
[r1, r2].forEach((resp) => {
|
||||
assert.isString(resp.data);
|
||||
assert.strictEqual(resp.data, testHttps01ChallengeContent);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* DNS-01 challenge response
|
||||
*/
|
||||
|
||||
describe('dns-01', () => {
|
||||
it('should not locate challenge response', async () => {
|
||||
await assert.isRejected(dns.resolveTxt(testDns01ChallengeHost));
|
||||
});
|
||||
|
||||
it('should add challenge response', async () => {
|
||||
const resp = await cts.addDns01ChallengeResponse(testDns01ChallengeHost, testDns01ChallengeValue);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate challenge response', async () => {
|
||||
const resp = await dns.resolveTxt(testDns01ChallengeHost);
|
||||
|
||||
assert.isArray(resp);
|
||||
assert.deepStrictEqual(resp, [[testDns01ChallengeValue]]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* TLS-ALPN-01 challenge response
|
||||
*/
|
||||
|
||||
describe('tls-alpn-01', () => {
|
||||
it('should not locate challenge response', async () => {
|
||||
await assert.isRejected(retrieveTlsAlpnCertificate(testTlsAlpn01ChallengeHost, tlsAlpnPort), /(failed to retrieve)|(ssl3_read_bytes:tlsv1 alert internal error)/);
|
||||
});
|
||||
|
||||
it('should timeout challenge response', async () => {
|
||||
await assert.isRejected(retrieveTlsAlpnCertificate('example.org', tlsAlpnPort, 500));
|
||||
});
|
||||
|
||||
it('should add challenge response', async () => {
|
||||
const resp = await cts.addTlsAlpn01ChallengeResponse(testTlsAlpn01ChallengeHost, testTlsAlpn01ChallengeValue);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should locate challenge response', async () => {
|
||||
const resp = await retrieveTlsAlpnCertificate(testTlsAlpn01ChallengeHost, tlsAlpnPort);
|
||||
assert.isTrue(isAlpnCertificateAuthorizationValid(resp, testTlsAlpn01ChallengeValue));
|
||||
});
|
||||
});
|
||||
});
|
||||
121
packages/core/acme-client/test/10-http.spec.js
Normal file
121
packages/core/acme-client/test/10-http.spec.js
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* HTTP client tests
|
||||
*/
|
||||
|
||||
const { randomUUID: uuid } = require('crypto');
|
||||
const { assert } = require('chai');
|
||||
const nock = require('nock');
|
||||
const axios = require('./../src/axios');
|
||||
const HttpClient = require('./../src/http');
|
||||
const pkg = require('./../package.json');
|
||||
|
||||
describe('http', () => {
|
||||
let testClient;
|
||||
|
||||
const endpoint = `http://${uuid()}.example.com`;
|
||||
const defaultUserAgent = `node-${pkg.name}/${pkg.version}`;
|
||||
const customUserAgent = 'custom-ua-123';
|
||||
|
||||
afterEach(() => {
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
|
||||
it('should initialize clients', () => {
|
||||
testClient = new HttpClient();
|
||||
});
|
||||
|
||||
/**
|
||||
* HTTP verbs
|
||||
*/
|
||||
|
||||
it('should http get', async () => {
|
||||
nock(endpoint).get('/').reply(200, 'ok');
|
||||
const resp = await testClient.request(endpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
/**
|
||||
* User-Agent
|
||||
*/
|
||||
|
||||
it('should request using default user-agent', async () => {
|
||||
nock(endpoint).matchHeader('user-agent', defaultUserAgent).get('/').reply(200, 'ok');
|
||||
axios.defaults.headers.common['User-Agent'] = defaultUserAgent;
|
||||
const resp = await testClient.request(endpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
it('should reject using custom user-agent', async () => {
|
||||
nock(endpoint).matchHeader('user-agent', defaultUserAgent).get('/').reply(200, 'ok');
|
||||
axios.defaults.headers.common['User-Agent'] = customUserAgent;
|
||||
await assert.isRejected(testClient.request(endpoint, 'get'));
|
||||
});
|
||||
|
||||
it('should request using custom user-agent', async () => {
|
||||
nock(endpoint).matchHeader('user-agent', customUserAgent).get('/').reply(200, 'ok');
|
||||
axios.defaults.headers.common['User-Agent'] = customUserAgent;
|
||||
const resp = await testClient.request(endpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
});
|
||||
|
||||
it('should reject using default user-agent', async () => {
|
||||
nock(endpoint).matchHeader('user-agent', customUserAgent).get('/').reply(200, 'ok');
|
||||
axios.defaults.headers.common['User-Agent'] = defaultUserAgent;
|
||||
await assert.isRejected(testClient.request(endpoint, 'get'));
|
||||
});
|
||||
|
||||
/**
|
||||
* Retry on HTTP errors
|
||||
*/
|
||||
|
||||
it('should retry on 429 rate limit', async () => {
|
||||
let rateLimitCount = 0;
|
||||
|
||||
nock(endpoint).persist().get('/').reply(() => {
|
||||
rateLimitCount += 1;
|
||||
|
||||
if (rateLimitCount < 3) {
|
||||
return [429, 'Rate Limit Exceeded', { 'Retry-After': 1 }];
|
||||
}
|
||||
|
||||
return [200, 'ok'];
|
||||
});
|
||||
|
||||
assert.strictEqual(rateLimitCount, 0);
|
||||
const resp = await testClient.request(endpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 200);
|
||||
assert.strictEqual(resp.data, 'ok');
|
||||
assert.strictEqual(rateLimitCount, 3);
|
||||
});
|
||||
|
||||
it('should retry on 5xx server error', async () => {
|
||||
let serverErrorCount = 0;
|
||||
|
||||
nock(endpoint).persist().get('/').reply(() => {
|
||||
serverErrorCount += 1;
|
||||
return [500, 'Internal Server Error', { 'Retry-After': 1 }];
|
||||
});
|
||||
|
||||
assert.strictEqual(serverErrorCount, 0);
|
||||
const resp = await testClient.request(endpoint, 'get');
|
||||
|
||||
assert.isObject(resp);
|
||||
assert.strictEqual(resp.status, 500);
|
||||
assert.strictEqual(serverErrorCount, 4);
|
||||
});
|
||||
});
|
||||
32
packages/core/acme-client/test/10-logger.spec.js
Normal file
32
packages/core/acme-client/test/10-logger.spec.js
Normal file
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
145
packages/core/acme-client/test/10-util.spec.js
Normal file
145
packages/core/acme-client/test/10-util.spec.js
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Utility method tests
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { assert } = require('chai');
|
||||
const util = require('./../src/util');
|
||||
const { readCertificateInfo } = require('./../src/crypto');
|
||||
|
||||
describe('util', () => {
|
||||
const testCertPath1 = path.join(__dirname, 'fixtures', 'certificate.crt');
|
||||
const testCertPath2 = path.join(__dirname, 'fixtures', 'letsencrypt.crt');
|
||||
|
||||
it('retry()', async () => {
|
||||
let attempts = 0;
|
||||
const backoffOpts = {
|
||||
min: 100,
|
||||
max: 500,
|
||||
};
|
||||
|
||||
await assert.isRejected(util.retry(() => {
|
||||
throw new Error('oops');
|
||||
}, backoffOpts));
|
||||
|
||||
const r = await util.retry(() => {
|
||||
attempts += 1;
|
||||
|
||||
if (attempts < 3) {
|
||||
throw new Error('oops');
|
||||
}
|
||||
|
||||
return 'abc';
|
||||
}, backoffOpts);
|
||||
|
||||
assert.strictEqual(r, 'abc');
|
||||
assert.strictEqual(attempts, 3);
|
||||
});
|
||||
|
||||
it('parseLinkHeader()', () => {
|
||||
const r1 = util.parseLinkHeader('<https://example.com/a>;rel="alternate"');
|
||||
assert.isArray(r1);
|
||||
assert.strictEqual(r1.length, 1);
|
||||
assert.strictEqual(r1[0], 'https://example.com/a');
|
||||
|
||||
const r2 = util.parseLinkHeader('<https://example.com/b>;rel="test"');
|
||||
assert.isArray(r2);
|
||||
assert.strictEqual(r2.length, 0);
|
||||
|
||||
const r3 = util.parseLinkHeader('<http://example.com/c>; rel="test"', 'test');
|
||||
assert.isArray(r3);
|
||||
assert.strictEqual(r3.length, 1);
|
||||
assert.strictEqual(r3[0], 'http://example.com/c');
|
||||
|
||||
const r4 = util.parseLinkHeader(`<https://example.com/a>; rel="alternate",
|
||||
<https://example.com/x>; rel="nope",
|
||||
<https://example.com/b>;rel="alternate",
|
||||
<https://example.com/c>; rel="alternate"`);
|
||||
assert.isArray(r4);
|
||||
assert.strictEqual(r4.length, 3);
|
||||
assert.strictEqual(r4[0], 'https://example.com/a');
|
||||
assert.strictEqual(r4[1], 'https://example.com/b');
|
||||
assert.strictEqual(r4[2], 'https://example.com/c');
|
||||
});
|
||||
|
||||
it('parseRetryAfterHeader()', () => {
|
||||
const r1 = util.parseRetryAfterHeader('');
|
||||
assert.strictEqual(r1, 0);
|
||||
|
||||
const r2 = util.parseRetryAfterHeader('abcdef');
|
||||
assert.strictEqual(r2, 0);
|
||||
|
||||
const r3 = util.parseRetryAfterHeader('123');
|
||||
assert.strictEqual(r3, 123);
|
||||
|
||||
const r4 = util.parseRetryAfterHeader('123.456');
|
||||
assert.strictEqual(r4, 123);
|
||||
|
||||
const r5 = util.parseRetryAfterHeader('-555');
|
||||
assert.strictEqual(r5, 0);
|
||||
|
||||
const r6 = util.parseRetryAfterHeader('Wed, 21 Oct 2015 07:28:00 GMT');
|
||||
assert.strictEqual(r6, 0);
|
||||
|
||||
const now = new Date();
|
||||
const future = new Date(now.getTime() + 123000);
|
||||
const r7 = util.parseRetryAfterHeader(future.toUTCString());
|
||||
assert.isTrue(r7 > 100);
|
||||
});
|
||||
|
||||
it('findCertificateChainForIssuer()', async () => {
|
||||
const certs = [
|
||||
(await fs.readFile(testCertPath1)).toString(),
|
||||
(await fs.readFile(testCertPath2)).toString(),
|
||||
];
|
||||
|
||||
const r1 = util.findCertificateChainForIssuer(certs, 'abc123');
|
||||
const r2 = util.findCertificateChainForIssuer(certs, 'example.com');
|
||||
const r3 = util.findCertificateChainForIssuer(certs, 'E6');
|
||||
|
||||
[r1, r2, r3].forEach((r) => {
|
||||
assert.isString(r);
|
||||
assert.isNotEmpty(r);
|
||||
});
|
||||
|
||||
assert.strictEqual(readCertificateInfo(r1).issuer.commonName, 'example.com');
|
||||
assert.strictEqual(readCertificateInfo(r2).issuer.commonName, 'example.com');
|
||||
assert.strictEqual(readCertificateInfo(r3).issuer.commonName, 'E6');
|
||||
});
|
||||
|
||||
it('formatResponseError()', () => {
|
||||
const e1 = util.formatResponseError({ data: { error: 'aaa' } });
|
||||
assert.strictEqual(e1, 'aaa');
|
||||
|
||||
const e2 = util.formatResponseError({ data: { error: { detail: 'bbb' } } });
|
||||
assert.strictEqual(e2, 'bbb');
|
||||
|
||||
const e3 = util.formatResponseError({ data: { detail: 'ccc' } });
|
||||
assert.strictEqual(e3, 'ccc');
|
||||
|
||||
const e4 = util.formatResponseError({ data: { a: 123 } });
|
||||
assert.strictEqual(e4, '{"a":123}');
|
||||
|
||||
const e5 = util.formatResponseError({});
|
||||
assert.isString(e5);
|
||||
assert.isEmpty(e5);
|
||||
});
|
||||
|
||||
it('getAuthoritativeDnsResolver()', async () => {
|
||||
/* valid domain - should not use global default */
|
||||
const r1 = await util.getAuthoritativeDnsResolver('example.com');
|
||||
assert.instanceOf(r1, dns.Resolver);
|
||||
assert.isNotEmpty(r1.getServers());
|
||||
assert.notDeepEqual(r1.getServers(), dns.getServers());
|
||||
|
||||
/* invalid domain - fallback to global default */
|
||||
const r2 = await util.getAuthoritativeDnsResolver('invalid.xtldx');
|
||||
assert.instanceOf(r2, dns.Resolver);
|
||||
assert.deepStrictEqual(r2.getServers(), dns.getServers());
|
||||
});
|
||||
|
||||
/* TODO: Figure out how to test this */
|
||||
it('retrieveTlsAlpnCertificate()');
|
||||
});
|
||||
149
packages/core/acme-client/test/10-verify.spec.js
Normal file
149
packages/core/acme-client/test/10-verify.spec.js
Normal file
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Challenge verification tests
|
||||
*/
|
||||
|
||||
const { randomUUID: uuid } = require('crypto');
|
||||
const { assert } = require('chai');
|
||||
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 testHttps01Authz = { identifier: { type: 'dns', value: `${uuid()}.${domainName}` } };
|
||||
const testHttps01Challenge = { type: 'http-01', status: 'pending', token: uuid() };
|
||||
const testHttps01Key = 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}`;
|
||||
|
||||
const testTlsAlpn01Authz = { identifier: { type: 'dns', value: `${uuid()}.${domainName}` } };
|
||||
const testTlsAlpn01Challenge = { type: 'dns-01', status: 'pending', token: uuid() };
|
||||
const testTlsAlpn01Key = uuid();
|
||||
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* https-01
|
||||
*/
|
||||
|
||||
describe('https-01', () => {
|
||||
it('should reject challenge', async () => {
|
||||
await assert.isRejected(verify['http-01'](testHttps01Authz, testHttps01Challenge, testHttps01Key));
|
||||
});
|
||||
|
||||
it('should mock challenge response', async () => {
|
||||
const resp = await cts.addHttps01ChallengeResponse(testHttps01Challenge.token, testHttps01Key, testHttps01Authz.identifier.value);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge', async () => {
|
||||
const resp = await verify['http-01'](testHttps01Authz, testHttps01Challenge, testHttps01Key);
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* tls-alpn-01
|
||||
*/
|
||||
|
||||
describe('tls-alpn-01', () => {
|
||||
it('should reject challenge', async () => {
|
||||
await assert.isRejected(verify['tls-alpn-01'](testTlsAlpn01Authz, testTlsAlpn01Challenge, testTlsAlpn01Key));
|
||||
});
|
||||
|
||||
it('should mock challenge response', async () => {
|
||||
const resp = await cts.addTlsAlpn01ChallengeResponse(testTlsAlpn01Authz.identifier.value, testTlsAlpn01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
|
||||
it('should verify challenge', async () => {
|
||||
const resp = await verify['tls-alpn-01'](testTlsAlpn01Authz, testTlsAlpn01Challenge, testTlsAlpn01Key);
|
||||
assert.isTrue(resp);
|
||||
});
|
||||
});
|
||||
});
|
||||
267
packages/core/acme-client/test/20-crypto-legacy.spec.js
Normal file
267
packages/core/acme-client/test/20-crypto-legacy.spec.js
Normal file
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
410
packages/core/acme-client/test/20-crypto.spec.js
Normal file
410
packages/core/acme-client/test/20-crypto.spec.js
Normal file
@@ -0,0 +1,410 @@
|
||||
/**
|
||||
* 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-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----END TEST-----
|
||||
|
||||
-----BEGIN TEST-----
|
||||
|
||||
-----END TEST-----
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----END TEST-----
|
||||
`;
|
||||
|
||||
const emptyBodyChain2 = `
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
|
||||
|
||||
|
||||
-----END TEST-----
|
||||
|
||||
-----BEGIN TEST-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----END TEST-----
|
||||
|
||||
|
||||
-----BEGIN TEST-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----END TEST-----
|
||||
-----BEGIN TEST-----
|
||||
dGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZ3Rlc3Rpbmd0ZXN0aW5ndGVzdGluZw==
|
||||
-----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;
|
||||
let testAlpnCertificate;
|
||||
|
||||
/**
|
||||
* 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 public key from string`, () => {
|
||||
testPublicKeys[n] = crypto.getPublicKey(testPrivateKeys[n].toString());
|
||||
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);
|
||||
});
|
||||
|
||||
it(`${n}/should get jwk from string`, () => {
|
||||
const jwk = crypto.getJwk(testPrivateKeys[n].toString());
|
||||
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 generate a csr with key as string`, async () => {
|
||||
const [key, csr] = await crypto.createCsr({
|
||||
commonName: testCsrDomain,
|
||||
}, testPrivateKeys[n].toString());
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(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]);
|
||||
});
|
||||
|
||||
it(`${n}/should resolve domains from csr string`, () => {
|
||||
[testCsr, testSanCsr, testNonCnCsr, testNonAsciiCsr].forEach((csr) => {
|
||||
const result = crypto.readCsrDomains(csr.toString());
|
||||
spec.crypto.csrDomains(result);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* ALPN
|
||||
*/
|
||||
|
||||
it(`${n}/should generate alpn certificate`, async () => {
|
||||
const authz = { identifier: { value: 'test.example.com' } };
|
||||
const [key, cert] = await crypto.createAlpnCertificate(authz, 'super-secret.12345', await createFn());
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(cert));
|
||||
|
||||
testAlpnCertificate = cert;
|
||||
});
|
||||
|
||||
it(`${n}/should generate alpn certificate with key as string`, async () => {
|
||||
const k = await createFn();
|
||||
const authz = { identifier: { value: 'test.example.com' } };
|
||||
const [key, cert] = await crypto.createAlpnCertificate(authz, 'super-secret.12345', k.toString());
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(cert));
|
||||
});
|
||||
|
||||
it(`${n}/should not validate invalid alpn certificate key authorization`, () => {
|
||||
assert.isFalse(crypto.isAlpnCertificateAuthorizationValid(testAlpnCertificate, 'aaaaaaa'));
|
||||
assert.isFalse(crypto.isAlpnCertificateAuthorizationValid(testAlpnCertificate, 'bbbbbbb'));
|
||||
assert.isFalse(crypto.isAlpnCertificateAuthorizationValid(testAlpnCertificate, 'ccccccc'));
|
||||
});
|
||||
|
||||
it(`${n}/should validate valid alpn certificate key authorization`, () => {
|
||||
assert.isTrue(crypto.isAlpnCertificateAuthorizationValid(testAlpnCertificate, 'super-secret.12345'));
|
||||
});
|
||||
|
||||
it(`${n}/should validate valid alpn certificate with cert as string`, () => {
|
||||
assert.isTrue(crypto.isAlpnCertificateAuthorizationValid(testAlpnCertificate.toString(), 'super-secret.12345'));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 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 default 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));
|
||||
});
|
||||
|
||||
it('should read certificate info from string', () => {
|
||||
[testCert, testSanCert].forEach((cert) => {
|
||||
const info = crypto.readCertificateInfo(cert.toString());
|
||||
spec.crypto.certificateInfo(info);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* ALPN
|
||||
*/
|
||||
|
||||
it('should generate alpn certificate with default key', async () => {
|
||||
const authz = { identifier: { value: 'test.example.com' } };
|
||||
const [key, cert] = await crypto.createAlpnCertificate(authz, 'abc123');
|
||||
|
||||
assert.isTrue(Buffer.isBuffer(key));
|
||||
assert.isTrue(Buffer.isBuffer(cert));
|
||||
});
|
||||
|
||||
/**
|
||||
* 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 get pem body as b64u from string', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const body = crypto.getPemBodyAsB64u(pem.toString());
|
||||
|
||||
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 from string', () => {
|
||||
[testPemKey, testCert, testSanCert].forEach((pem) => {
|
||||
const chain = crypto.splitPemChain(pem.toString());
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
569
packages/core/acme-client/test/50-client.spec.js
Normal file
569
packages/core/acme-client/test/50-client.spec.js
Normal file
@@ -0,0 +1,569 @@
|
||||
/**
|
||||
* ACME client tests
|
||||
*/
|
||||
|
||||
const { randomUUID: uuid } = require('crypto');
|
||||
const { assert } = require('chai');
|
||||
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 testDomainAlpn = `${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 testOrderAlpn;
|
||||
let testOrderWildcard;
|
||||
let testAuthz;
|
||||
let testAuthzAlpn;
|
||||
let testAuthzWildcard;
|
||||
let testChallenge;
|
||||
let testChallengeAlpn;
|
||||
let testChallengeWildcard;
|
||||
let testKeyAuthorization;
|
||||
let testKeyAuthorizationAlpn;
|
||||
let testKeyAuthorizationWildcard;
|
||||
let testCsr;
|
||||
let testCsrAlpn;
|
||||
let testCsrWildcard;
|
||||
let testCertificate;
|
||||
let testCertificateAlpn;
|
||||
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());
|
||||
[, testCsrAlpn] = await acme.crypto.createCsr({ altNames: [testDomainAlpn] }, await createKeyFn());
|
||||
[, testCsrWildcard] = await acme.crypto.createCsr({ altNames: [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: testDomainAlpn }] };
|
||||
const data3 = { identifiers: [{ type: 'dns', value: testDomainWildcard }] };
|
||||
|
||||
testOrder = await testClient.createOrder(data1);
|
||||
testOrderAlpn = await testClient.createOrder(data2);
|
||||
testOrderWildcard = await testClient.createOrder(data3);
|
||||
|
||||
[testOrder, testOrderAlpn, 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, testOrderAlpn, 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 alpnAuthzCollection = await testClient.getAuthorizations(testOrderAlpn);
|
||||
const wildcardAuthzCollection = await testClient.getAuthorizations(testOrderWildcard);
|
||||
|
||||
[orderAuthzCollection, alpnAuthzCollection, wildcardAuthzCollection].forEach((collection) => {
|
||||
assert.isArray(collection);
|
||||
assert.isNotEmpty(collection);
|
||||
|
||||
collection.forEach((authz) => {
|
||||
spec.rfc8555.authorization(authz);
|
||||
assert.strictEqual(authz.status, 'pending');
|
||||
});
|
||||
});
|
||||
|
||||
testAuthz = orderAuthzCollection.pop();
|
||||
testAuthzAlpn = alpnAuthzCollection.pop();
|
||||
testAuthzWildcard = wildcardAuthzCollection.pop();
|
||||
|
||||
testAuthz.challenges.concat(testAuthzAlpn.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'));
|
||||
testChallengeAlpn = testAuthzAlpn.challenges.find((c) => (c.type === 'tls-alpn-01'));
|
||||
testChallengeWildcard = testAuthzWildcard.challenges.find((c) => (c.type === 'dns-01'));
|
||||
|
||||
testKeyAuthorization = await testClient.getChallengeKeyAuthorization(testChallenge);
|
||||
testKeyAuthorizationAlpn = await testClient.getChallengeKeyAuthorization(testChallengeAlpn);
|
||||
testKeyAuthorizationWildcard = await testClient.getChallengeKeyAuthorization(testChallengeWildcard);
|
||||
|
||||
[testKeyAuthorization, testKeyAuthorizationAlpn, 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.assertTlsAlpnChallengeCreateFn(testAuthzAlpn, testChallengeAlpn, testKeyAuthorizationAlpn);
|
||||
await cts.assertDnsChallengeCreateFn(testAuthzWildcard, testChallengeWildcard, testKeyAuthorizationWildcard);
|
||||
|
||||
await testClient.verifyChallenge(testAuthz, testChallenge);
|
||||
await testClient.verifyChallenge(testAuthzAlpn, testChallengeAlpn);
|
||||
await testClient.verifyChallenge(testAuthzWildcard, testChallengeWildcard);
|
||||
});
|
||||
|
||||
/**
|
||||
* Complete challenge
|
||||
*/
|
||||
|
||||
it('should complete challenge', async () => {
|
||||
await Promise.all([testChallenge, testChallengeAlpn, 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, testChallengeAlpn, testChallengeWildcard].map(async (c) => testClient.waitForValidStatus(c)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Finalize order
|
||||
*/
|
||||
|
||||
it('should finalize order', async () => {
|
||||
const finalize = await testClient.finalizeOrder(testOrder, testCsr);
|
||||
const finalizeAlpn = await testClient.finalizeOrder(testOrderAlpn, testCsrAlpn);
|
||||
const finalizeWildcard = await testClient.finalizeOrder(testOrderWildcard, testCsrWildcard);
|
||||
|
||||
[finalize, finalizeAlpn, finalizeWildcard].forEach((f) => spec.rfc8555.order(f));
|
||||
|
||||
assert.strictEqual(testOrder.url, finalize.url);
|
||||
assert.strictEqual(testOrderAlpn.url, finalizeAlpn.url);
|
||||
assert.strictEqual(testOrderWildcard.url, finalizeWildcard.url);
|
||||
});
|
||||
|
||||
/**
|
||||
* Wait for valid order
|
||||
*/
|
||||
|
||||
it('should wait for valid order status', async () => {
|
||||
await Promise.all([testOrder, testOrderAlpn, testOrderWildcard].map(async (o) => testClient.waitForValidStatus(o)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Get certificate
|
||||
*/
|
||||
|
||||
it('should get certificate', async () => {
|
||||
testCertificate = await testClient.getCertificate(testOrder);
|
||||
testCertificateAlpn = await testClient.getCertificate(testOrderAlpn);
|
||||
testCertificateWildcard = await testClient.getCertificate(testOrderWildcard);
|
||||
|
||||
[testCertificate, testCertificateAlpn, 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(testCertificateAlpn, { reason: 0 });
|
||||
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(testOrderAlpn));
|
||||
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));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
438
packages/core/acme-client/test/70-auto.spec.js
Normal file
438
packages/core/acme-client/test/70-auto.spec.js
Normal file
@@ -0,0 +1,438 @@
|
||||
/**
|
||||
* ACME client.auto tests
|
||||
*/
|
||||
|
||||
const { randomUUID: uuid } = require('crypto');
|
||||
const { assert } = require('chai');
|
||||
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 testHttpsDomain = `${uuid()}.${domainName}`;
|
||||
const testDnsDomain = `${uuid()}.${domainName}`;
|
||||
const testAlpnDomain = `${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);
|
||||
});
|
||||
|
||||
it('should settle all challenges before rejecting', async () => {
|
||||
const results = [];
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: `${uuid()}.${domainName}`,
|
||||
altNames: [
|
||||
`${uuid()}.${domainName}`,
|
||||
`${uuid()}.${domainName}`,
|
||||
`${uuid()}.${domainName}`,
|
||||
`${uuid()}.${domainName}`,
|
||||
],
|
||||
}, await createKeyFn());
|
||||
|
||||
await assert.isRejected(testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: async (...args) => {
|
||||
if ([0, 1, 2].includes(results.length)) {
|
||||
results.push(false);
|
||||
throw new Error('oops');
|
||||
}
|
||||
|
||||
await new Promise((resolve) => { setTimeout(resolve, 500); });
|
||||
results.push(true);
|
||||
return cts.challengeCreateFn(...args);
|
||||
},
|
||||
challengeRemoveFn: cts.challengeRemoveFn,
|
||||
}));
|
||||
|
||||
assert.strictEqual(results.length, 5);
|
||||
assert.deepStrictEqual(results, [false, false, false, true, true]);
|
||||
});
|
||||
|
||||
/**
|
||||
* 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 https-01', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testHttpsDomain,
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.assertHttpsChallengeCreateFn,
|
||||
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 certificate using tls-alpn-01', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
commonName: testAlpnDomain,
|
||||
}, await createKeyFn());
|
||||
|
||||
const cert = await testClient.auto({
|
||||
csr,
|
||||
termsOfServiceAgreed: true,
|
||||
challengeCreateFn: cts.assertTlsAlpnChallengeCreateFn,
|
||||
challengeRemoveFn: cts.challengeRemoveFn,
|
||||
challengePriority: ['tls-alpn-01'],
|
||||
});
|
||||
|
||||
assert.isString(cert);
|
||||
});
|
||||
|
||||
it('should order san certificate', async () => {
|
||||
const [, csr] = await acme.crypto.createCsr({
|
||||
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({
|
||||
altNames: [testWildcardDomain, `*.${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.isNull(info.domains.commonName);
|
||||
assert.deepStrictEqual(info.domains.altNames, [testDomain]);
|
||||
});
|
||||
|
||||
it('should read san certificate info', () => {
|
||||
const info = acme.crypto.readCertificateInfo(testSanCertificate);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.isNull(info.domains.commonName);
|
||||
assert.deepStrictEqual(info.domains.altNames, testSanDomains);
|
||||
});
|
||||
|
||||
it('should read wildcard certificate info', () => {
|
||||
const info = acme.crypto.readCertificateInfo(testWildcardCertificate);
|
||||
|
||||
spec.crypto.certificateInfo(info);
|
||||
assert.isNull(info.domains.commonName);
|
||||
assert.deepStrictEqual(info.domains.altNames, [testWildcardDomain, `*.${testWildcardDomain}`]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
119
packages/core/acme-client/test/challtestsrv.js
Normal file
119
packages/core/acme-client/test/challtestsrv.js
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Pebble Challenge Test Server integration
|
||||
*/
|
||||
|
||||
const { assert } = require('chai');
|
||||
const axios = require('./../src/axios');
|
||||
|
||||
const apiBaseUrl = process.env.ACME_CHALLTESTSRV_URL || null;
|
||||
const httpsPort = axios.defaults.acmeSettings.httpsChallengePort || 443;
|
||||
|
||||
/**
|
||||
* 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 addHttps01ChallengeResponse(token, content, targetHostname) {
|
||||
await addHttp01ChallengeResponse(token, content);
|
||||
return request('add-redirect', {
|
||||
path: `/.well-known/acme-challenge/${token}`,
|
||||
targetURL: `https://${targetHostname}:${httpsPort}/.well-known/acme-challenge/${token}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function addDns01ChallengeResponse(host, value) {
|
||||
return request('set-txt', { host, value });
|
||||
}
|
||||
|
||||
async function addTlsAlpn01ChallengeResponse(host, content) {
|
||||
return request('add-tlsalpn01', { host, content });
|
||||
}
|
||||
|
||||
exports.addHttp01ChallengeResponse = addHttp01ChallengeResponse;
|
||||
exports.addHttps01ChallengeResponse = addHttps01ChallengeResponse;
|
||||
exports.addDns01ChallengeResponse = addDns01ChallengeResponse;
|
||||
exports.addTlsAlpn01ChallengeResponse = addTlsAlpn01ChallengeResponse;
|
||||
|
||||
/**
|
||||
* Challenge response mock functions
|
||||
*/
|
||||
|
||||
async function assertHttpChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'http-01');
|
||||
return addHttp01ChallengeResponse(challenge.token, keyAuthorization);
|
||||
}
|
||||
|
||||
async function assertHttpsChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'http-01');
|
||||
return addHttps01ChallengeResponse(challenge.token, keyAuthorization, authz.identifier.value);
|
||||
}
|
||||
|
||||
async function assertDnsChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'dns-01');
|
||||
return addDns01ChallengeResponse(`_acme-challenge.${authz.identifier.value}.`, keyAuthorization);
|
||||
}
|
||||
|
||||
async function assertTlsAlpnChallengeCreateFn(authz, challenge, keyAuthorization) {
|
||||
assert.strictEqual(challenge.type, 'tls-alpn-01');
|
||||
return addTlsAlpn01ChallengeResponse(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);
|
||||
}
|
||||
|
||||
if (challenge.type === 'tls-alpn-01') {
|
||||
return assertTlsAlpnChallengeCreateFn(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.assertHttpsChallengeCreateFn = assertHttpsChallengeCreateFn;
|
||||
exports.assertDnsChallengeCreateFn = assertDnsChallengeCreateFn;
|
||||
exports.assertTlsAlpnChallengeCreateFn = assertTlsAlpnChallengeCreateFn;
|
||||
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-----
|
||||
23
packages/core/acme-client/test/fixtures/letsencrypt.crt
vendored
Normal file
23
packages/core/acme-client/test/fixtures/letsencrypt.crt
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDzzCCA1WgAwIBAgISA0ghDoSv5DpT3Pd3lqwjbVDDMAoGCCqGSM49BAMDMDIx
|
||||
CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQDEwJF
|
||||
NjAeFw0yNDA2MTAxNzEyMjZaFw0yNDA5MDgxNzEyMjVaMBQxEjAQBgNVBAMTCWxl
|
||||
bmNyLm9yZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEHJ3DjN7pYV3mftHzaP
|
||||
V/WI0RhOJnSI5AIFEPFHDi8UowOINRGIfm9FHGIDqrb4Rmyvr9JrrqBdFGDen8BW
|
||||
6OGjggJnMIICYzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwEG
|
||||
CCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFIdCTnxqmpOELDyzPaEM
|
||||
seB36lUOMB8GA1UdIwQYMBaAFJMnRpgDqVFojpjWxEJI2yO/WJTSMFUGCCsGAQUF
|
||||
BwEBBEkwRzAhBggrBgEFBQcwAYYVaHR0cDovL2U2Lm8ubGVuY3Iub3JnMCIGCCsG
|
||||
AQUFBzAChhZodHRwOi8vZTYuaS5sZW5jci5vcmcvMG8GA1UdEQRoMGaCCWxlbmNy
|
||||
Lm9yZ4IPbGV0c2VuY3J5cHQuY29tgg9sZXRzZW5jcnlwdC5vcmeCDXd3dy5sZW5j
|
||||
ci5vcmeCE3d3dy5sZXRzZW5jcnlwdC5jb22CE3d3dy5sZXRzZW5jcnlwdC5vcmcw
|
||||
EwYDVR0gBAwwCjAIBgZngQwBAgEwggEFBgorBgEEAdZ5AgQCBIH2BIHzAPEAdgA/
|
||||
F0tP1yJHWJQdZRyEvg0S7ZA3fx+FauvBvyiF7PhkbgAAAZADWfneAAAEAwBHMEUC
|
||||
IGlp+dPU2hLT2suTMYkYMlt/xbzSnKLZDA/wYSsPACP7AiEAxbAzx6mkzn0cs0hh
|
||||
ti6sLf0pcbmDhxHdlJRjuo6SQZEAdwDf4VbrqgWvtZwPhnGNqMAyTq5W2W6n9aVq
|
||||
AdHBO75SXAAAAZADWfqrAAAEAwBIMEYCIQCrAmDUrlX3oGhri1qCIb65Cuf8h2GR
|
||||
LC1VfXBenX7dCAIhALXwbhCQ1vO1WLv4CqyihMHOwFaICYqN/N6ylaBlVAM4MAoG
|
||||
CCqGSM49BAMDA2gAMGUCMFdgjOXGl+hE2ABDsAeuNq8wi34yTMUHk0KMTOjRAfy9
|
||||
rOCGQqvP0myoYlyzXOH9uQIxAMdkG1ZWBZS1dHavbPf1I/MjYpzX6gy0jVHIXXu5
|
||||
aYWylBi/Uf2RPj0LWFZh8tNa1Q==
|
||||
-----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-----
|
||||
38
packages/core/acme-client/test/get-cert-issuers.js
Normal file
38
packages/core/acme-client/test/get-cert-issuers.js
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 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');
|
||||
};
|
||||
49
packages/core/acme-client/test/setup.js
Normal file
49
packages/core/acme-client/test/setup.js
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Setup testing
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const chai = require('chai');
|
||||
const chaiAsPromised = require('chai-as-promised');
|
||||
const axios = require('./../src/axios');
|
||||
|
||||
/**
|
||||
* Add promise support to Chai
|
||||
*/
|
||||
|
||||
chai.use(chaiAsPromised);
|
||||
|
||||
/**
|
||||
* Challenge test server ports
|
||||
*/
|
||||
|
||||
if (process.env.ACME_HTTP_PORT) {
|
||||
axios.defaults.acmeSettings.httpChallengePort = process.env.ACME_HTTP_PORT;
|
||||
}
|
||||
|
||||
if (process.env.ACME_HTTPS_PORT) {
|
||||
axios.defaults.acmeSettings.httpsChallengePort = process.env.ACME_HTTPS_PORT;
|
||||
}
|
||||
|
||||
if (process.env.ACME_TLSALPN_PORT) {
|
||||
axios.defaults.acmeSettings.tlsAlpnChallengePort = process.env.ACME_TLSALPN_PORT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Greatly reduce retry duration while testing
|
||||
*/
|
||||
|
||||
axios.defaults.acmeSettings.retryMaxAttempts = 3;
|
||||
axios.defaults.acmeSettings.retryDefaultDelay = 1;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
175
packages/core/acme-client/test/spec.js
Normal file
175
packages/core/acme-client/test/spec.js
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 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');
|
||||
};
|
||||
11
packages/core/acme-client/tsconfig.json
Normal file
11
packages/core/acme-client/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": ["es6"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"baseUrl": ".",
|
||||
"paths": { "acme-client": ["."] }
|
||||
}
|
||||
}
|
||||
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) => 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
|
||||
},
|
||||
google: {
|
||||
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]>;
|
||||
createAlpnCertificate(authz: Authorization, keyAuthorization: string, keyPem?: PrivateKeyBuffer | PrivateKeyString): Promise<[PrivateKeyBuffer, CertificateBuffer]>;
|
||||
isAlpnCertificateAuthorizationValid(certPem: CertificateBuffer | CertificateString, keyAuthorization: string): boolean;
|
||||
}
|
||||
|
||||
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;
|
||||
69
packages/core/acme-client/types/index.test-d.ts
Normal file
69
packages/core/acme-client/types/index.test-d.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 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) => {}
|
||||
});
|
||||
})();
|
||||
123
packages/core/acme-client/types/rfc8555.d.ts
vendored
Normal file
123
packages/core/acme-client/types/rfc8555.d.ts
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Account
|
||||
*
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-7.1.2
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-7.3
|
||||
* https://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/html/rfc8555#section-7.1.3
|
||||
* https://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/html/rfc8555#section-8
|
||||
* https://datatracker.ietf.org/doc/html/rfc8555#section-8.3
|
||||
* https://datatracker.ietf.org/doc/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://datatracker.ietf.org/doc/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;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
> 1%
|
||||
last 2 versions
|
||||
not dead
|
||||
@@ -1,463 +0,0 @@
|
||||
/** @type {import('dependency-cruiser').IConfiguration} */
|
||||
module.exports = {
|
||||
forbidden: [
|
||||
/* rules from the 'recommended' preset: */
|
||||
{
|
||||
name: 'no-circular',
|
||||
severity: 'warn',
|
||||
comment:
|
||||
'This dependency is part of a circular relationship. You might want to revise ' +
|
||||
'your solution (i.e. use dependency inversion, make sure the modules have a single responsibility) ',
|
||||
from: {},
|
||||
to: {
|
||||
circular: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'no-orphans',
|
||||
comment:
|
||||
"This is an orphan module - it's likely not used (anymore?). Either use it or " +
|
||||
"remove it. If it's logical this module is an orphan (i.e. it's a config file), " +
|
||||
"add an exception for it in your dependency-cruiser configuration. By default " +
|
||||
"this rule does not scrutinize dot-files (e.g. .eslintrc.js), TypeScript declaration " +
|
||||
"files (.d.ts), tsconfig.json and some of the babel and webpack configs.",
|
||||
severity: 'warn',
|
||||
from: {
|
||||
orphan: true,
|
||||
pathNot: [
|
||||
'(^|/)\\.[^/]+\\.(js|cjs|mjs|ts|json)$', // dot files
|
||||
'\\.d\\.ts$', // TypeScript declaration files
|
||||
'(^|/)tsconfig\\.json$', // TypeScript config
|
||||
'(^|/)(babel|webpack)\\.config\\.(js|cjs|mjs|ts|json)$' // other configs
|
||||
]
|
||||
},
|
||||
to: {},
|
||||
},
|
||||
{
|
||||
name: 'no-deprecated-core',
|
||||
comment:
|
||||
'A module depends on a node core module that has been deprecated. Find an alternative - these are ' +
|
||||
"bound to exist - node doesn't deprecate lightly.",
|
||||
severity: 'warn',
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'core'
|
||||
],
|
||||
path: [
|
||||
'^(v8\/tools\/codemap)$',
|
||||
'^(v8\/tools\/consarray)$',
|
||||
'^(v8\/tools\/csvparser)$',
|
||||
'^(v8\/tools\/logreader)$',
|
||||
'^(v8\/tools\/profile_view)$',
|
||||
'^(v8\/tools\/profile)$',
|
||||
'^(v8\/tools\/SourceMap)$',
|
||||
'^(v8\/tools\/splaytree)$',
|
||||
'^(v8\/tools\/tickprocessor-driver)$',
|
||||
'^(v8\/tools\/tickprocessor)$',
|
||||
'^(node-inspect\/lib\/_inspect)$',
|
||||
'^(node-inspect\/lib\/internal\/inspect_client)$',
|
||||
'^(node-inspect\/lib\/internal\/inspect_repl)$',
|
||||
'^(async_hooks)$',
|
||||
'^(punycode)$',
|
||||
'^(domain)$',
|
||||
'^(constants)$',
|
||||
'^(sys)$',
|
||||
'^(_linklist)$',
|
||||
'^(_stream_wrap)$'
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'not-to-deprecated',
|
||||
comment:
|
||||
'This module uses a (version of an) npm module that has been deprecated. Either upgrade to a later ' +
|
||||
'version of that module, or find an alternative. Deprecated modules are a security risk.',
|
||||
severity: 'warn',
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'deprecated'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'no-non-package-json',
|
||||
severity: 'error',
|
||||
comment:
|
||||
"This module depends on an npm package that isn't in the 'dependencies' section of your package.json. " +
|
||||
"That's problematic as the package either (1) won't be available on live (2 - worse) will be " +
|
||||
"available on live with an non-guaranteed version. Fix it by adding the package to the dependencies " +
|
||||
"in your package.json.",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'npm-no-pkg',
|
||||
'npm-unknown'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'not-to-unresolvable',
|
||||
comment:
|
||||
"This module depends on a module that cannot be found ('resolved to disk'). If it's an npm " +
|
||||
'module: add it to your package.json. In all other cases you likely already know what to do.',
|
||||
severity: 'error',
|
||||
from: {},
|
||||
to: {
|
||||
couldNotResolve: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'no-duplicate-dep-types',
|
||||
comment:
|
||||
"Likely this module depends on an external ('npm') package that occurs more than once " +
|
||||
"in your package.json i.e. bot as a devDependencies and in dependencies. This will cause " +
|
||||
"maintenance problems later on.",
|
||||
severity: 'warn',
|
||||
from: {},
|
||||
to: {
|
||||
moreThanOneDependencyType: true,
|
||||
// as it's pretty common to have a type import be a type only import
|
||||
// _and_ (e.g.) a devDependency - don't consider type-only dependency
|
||||
// types for this rule
|
||||
dependencyTypesNot: ["type-only"]
|
||||
}
|
||||
},
|
||||
|
||||
/* rules you might want to tweak for your specific situation: */
|
||||
{
|
||||
name: 'not-to-test',
|
||||
comment:
|
||||
"This module depends on code within a folder that should only contain tests. As tests don't " +
|
||||
"implement functionality this is odd. Either you're writing a test outside the test folder " +
|
||||
"or there's something in the test folder that isn't a test.",
|
||||
severity: 'error',
|
||||
from: {
|
||||
pathNot: '^(tests)'
|
||||
},
|
||||
to: {
|
||||
path: '^(tests)'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'not-to-spec',
|
||||
comment:
|
||||
'This module depends on a spec (test) file. The sole responsibility of a spec file is to test code. ' +
|
||||
"If there's something in a spec that's of use to other modules, it doesn't have that single " +
|
||||
'responsibility anymore. Factor it out into (e.g.) a separate utility/ helper or a mock.',
|
||||
severity: 'error',
|
||||
from: {},
|
||||
to: {
|
||||
path: '\\.(spec|test)\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\.md)$'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'not-to-dev-dep',
|
||||
severity: 'error',
|
||||
comment:
|
||||
"This module depends on an npm package from the 'devDependencies' section of your " +
|
||||
'package.json. It looks like something that ships to production, though. To prevent problems ' +
|
||||
"with npm packages that aren't there on production declare it (only!) in the 'dependencies'" +
|
||||
'section of your package.json. If this module is development only - add it to the ' +
|
||||
'from.pathNot re of the not-to-dev-dep rule in the dependency-cruiser configuration',
|
||||
from: {
|
||||
path: '^(src)',
|
||||
pathNot: '\\.(spec|test)\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\.md)$'
|
||||
},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'npm-dev'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'optional-deps-used',
|
||||
severity: 'info',
|
||||
comment:
|
||||
"This module depends on an npm package that is declared as an optional dependency " +
|
||||
"in your package.json. As this makes sense in limited situations only, it's flagged here. " +
|
||||
"If you're using an optional dependency here by design - add an exception to your" +
|
||||
"dependency-cruiser configuration.",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'npm-optional'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'peer-deps-used',
|
||||
comment:
|
||||
"This module depends on an npm package that is declared as a peer dependency " +
|
||||
"in your package.json. This makes sense if your package is e.g. a plugin, but in " +
|
||||
"other cases - maybe not so much. If the use of a peer dependency is intentional " +
|
||||
"add an exception to your dependency-cruiser configuration.",
|
||||
severity: 'warn',
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: [
|
||||
'npm-peer'
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
options: {
|
||||
|
||||
/* conditions specifying which files not to follow further when encountered:
|
||||
- path: a regular expression to match
|
||||
- dependencyTypes: see https://github.com/sverweij/dependency-cruiser/blob/master/doc/rules-reference.md#dependencytypes-and-dependencytypesnot
|
||||
for a complete list
|
||||
*/
|
||||
doNotFollow: {
|
||||
path: 'node_modules'
|
||||
},
|
||||
|
||||
/* conditions specifying which dependencies to exclude
|
||||
- path: a regular expression to match
|
||||
- dynamic: a boolean indicating whether to ignore dynamic (true) or static (false) dependencies.
|
||||
leave out if you want to exclude neither (recommended!)
|
||||
*/
|
||||
// exclude : {
|
||||
// path: '',
|
||||
// dynamic: true
|
||||
// },
|
||||
|
||||
/* pattern specifying which files to include (regular expression)
|
||||
dependency-cruiser will skip everything not matching this pattern
|
||||
*/
|
||||
// includeOnly : '',
|
||||
|
||||
/* dependency-cruiser will include modules matching against the focus
|
||||
regular expression in its output, as well as their neighbours (direct
|
||||
dependencies and dependents)
|
||||
*/
|
||||
// focus : '',
|
||||
|
||||
/* list of module systems to cruise */
|
||||
// moduleSystems: ['amd', 'cjs', 'es6', 'tsd'],
|
||||
|
||||
/* prefix for links in html and svg output (e.g. 'https://github.com/you/yourrepo/blob/develop/'
|
||||
to open it on your online repo or `vscode://file/${process.cwd()}/` to
|
||||
open it in visual studio code),
|
||||
*/
|
||||
// prefix: '',
|
||||
|
||||
/* false (the default): ignore dependencies that only exist before typescript-to-javascript compilation
|
||||
true: also detect dependencies that only exist before typescript-to-javascript compilation
|
||||
"specify": for each dependency identify whether it only exists before compilation or also after
|
||||
*/
|
||||
tsPreCompilationDeps: true,
|
||||
|
||||
/*
|
||||
list of extensions to scan that aren't javascript or compile-to-javascript.
|
||||
Empty by default. Only put extensions in here that you want to take into
|
||||
account that are _not_ parsable.
|
||||
*/
|
||||
// extraExtensionsToScan: [".json", ".jpg", ".png", ".svg", ".webp"],
|
||||
|
||||
/* if true combines the package.jsons found from the module up to the base
|
||||
folder the cruise is initiated from. Useful for how (some) mono-repos
|
||||
manage dependencies & dependency definitions.
|
||||
*/
|
||||
// combinedDependencies: false,
|
||||
|
||||
/* if true leave symlinks untouched, otherwise use the realpath */
|
||||
// preserveSymlinks: false,
|
||||
|
||||
/* TypeScript project file ('tsconfig.json') to use for
|
||||
(1) compilation and
|
||||
(2) resolution (e.g. with the paths property)
|
||||
|
||||
The (optional) fileName attribute specifies which file to take (relative to
|
||||
dependency-cruiser's current working directory). When not provided
|
||||
defaults to './tsconfig.json'.
|
||||
*/
|
||||
tsConfig: {
|
||||
fileName: 'tsconfig.json'
|
||||
},
|
||||
|
||||
/* Webpack configuration to use to get resolve options from.
|
||||
|
||||
The (optional) fileName attribute specifies which file to take (relative
|
||||
to dependency-cruiser's current working directory. When not provided defaults
|
||||
to './webpack.conf.js'.
|
||||
|
||||
The (optional) `env` and `args` attributes contain the parameters to be passed if
|
||||
your webpack config is a function and takes them (see webpack documentation
|
||||
for details)
|
||||
*/
|
||||
// webpackConfig: {
|
||||
// fileName: './webpack.config.js',
|
||||
// env: {},
|
||||
// args: {},
|
||||
// },
|
||||
|
||||
/* Babel config ('.babelrc', '.babelrc.json', '.babelrc.json5', ...) to use
|
||||
for compilation (and whatever other naughty things babel plugins do to
|
||||
source code). This feature is well tested and usable, but might change
|
||||
behavior a bit over time (e.g. more precise results for used module
|
||||
systems) without dependency-cruiser getting a major version bump.
|
||||
*/
|
||||
// babelConfig: {
|
||||
// fileName: './.babelrc'
|
||||
// },
|
||||
|
||||
/* List of strings you have in use in addition to cjs/ es6 requires
|
||||
& imports to declare module dependencies. Use this e.g. if you've
|
||||
re-declared require, use a require-wrapper or use window.require as
|
||||
a hack.
|
||||
*/
|
||||
// exoticRequireStrings: [],
|
||||
/* options to pass on to enhanced-resolve, the package dependency-cruiser
|
||||
uses to resolve module references to disk. You can set most of these
|
||||
options in a webpack.conf.js - this section is here for those
|
||||
projects that don't have a separate webpack config file.
|
||||
|
||||
Note: settings in webpack.conf.js override the ones specified here.
|
||||
*/
|
||||
enhancedResolveOptions: {
|
||||
/* List of strings to consider as 'exports' fields in package.json. Use
|
||||
['exports'] when you use packages that use such a field and your environment
|
||||
supports it (e.g. node ^12.19 || >=14.7 or recent versions of webpack).
|
||||
|
||||
If you have an `exportsFields` attribute in your webpack config, that one
|
||||
will have precedence over the one specified here.
|
||||
*/
|
||||
exportsFields: ["exports"],
|
||||
/* List of conditions to check for in the exports field. e.g. use ['imports']
|
||||
if you're only interested in exposed es6 modules, ['require'] for commonjs,
|
||||
or all conditions at once `(['import', 'require', 'node', 'default']`)
|
||||
if anything goes for you. Only works when the 'exportsFields' array is
|
||||
non-empty.
|
||||
|
||||
If you have a 'conditionNames' attribute in your webpack config, that one will
|
||||
have precedence over the one specified here.
|
||||
*/
|
||||
conditionNames: ["import", "require", "node", "default"],
|
||||
/*
|
||||
The extensions, by default are the same as the ones dependency-cruiser
|
||||
can access (run `npx depcruise --info` to see which ones that are in
|
||||
_your_ environment. If that list is larger than what you need (e.g.
|
||||
it contains .js, .jsx, .ts, .tsx, .cts, .mts - but you don't use
|
||||
TypeScript you can pass just the extensions you actually use (e.g.
|
||||
[".js", ".jsx"]). This can speed up the most expensive step in
|
||||
dependency cruising (module resolution) quite a bit.
|
||||
*/
|
||||
// extensions: [".js", ".jsx", ".ts", ".tsx", ".d.ts"],
|
||||
/*
|
||||
If your TypeScript project makes use of types specified in 'types'
|
||||
fields in package.jsons of external dependencies, specify "types"
|
||||
in addition to "main" in here, so enhanced-resolve (the resolver
|
||||
dependency-cruiser uses) knows to also look there. You can also do
|
||||
this if you're not sure, but still use TypeScript. In a future version
|
||||
of dependency-cruiser this will likely become the default.
|
||||
*/
|
||||
mainFields: ["main", "types"],
|
||||
},
|
||||
reporterOptions: {
|
||||
dot: {
|
||||
/* pattern of modules that can be consolidated in the detailed
|
||||
graphical dependency graph. The default pattern in this configuration
|
||||
collapses everything in node_modules to one folder deep so you see
|
||||
the external modules, but not the innards your app depends upon.
|
||||
*/
|
||||
collapsePattern: 'node_modules/(@[^/]+/[^/]+|[^/]+)',
|
||||
|
||||
/* Options to tweak the appearance of your graph.See
|
||||
https://github.com/sverweij/dependency-cruiser/blob/master/doc/options-reference.md#reporteroptions
|
||||
for details and some examples. If you don't specify a theme
|
||||
don't worry - dependency-cruiser will fall back to the default one.
|
||||
*/
|
||||
// theme: {
|
||||
// graph: {
|
||||
// /* use splines: "ortho" for straight lines. Be aware though
|
||||
// graphviz might take a long time calculating ortho(gonal)
|
||||
// routings.
|
||||
// */
|
||||
// splines: "true"
|
||||
// },
|
||||
// modules: [
|
||||
// {
|
||||
// criteria: { matchesFocus: true },
|
||||
// attributes: {
|
||||
// fillcolor: "lime",
|
||||
// penwidth: 2,
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// criteria: { matchesFocus: false },
|
||||
// attributes: {
|
||||
// fillcolor: "lightgrey",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// criteria: { matchesReaches: true },
|
||||
// attributes: {
|
||||
// fillcolor: "lime",
|
||||
// penwidth: 2,
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// criteria: { matchesReaches: false },
|
||||
// attributes: {
|
||||
// fillcolor: "lightgrey",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// criteria: { source: "^src/model" },
|
||||
// attributes: { fillcolor: "#ccccff" }
|
||||
// },
|
||||
// {
|
||||
// criteria: { source: "^src/view" },
|
||||
// attributes: { fillcolor: "#ccffcc" }
|
||||
// },
|
||||
// ],
|
||||
// dependencies: [
|
||||
// {
|
||||
// criteria: { "rules[0].severity": "error" },
|
||||
// attributes: { fontcolor: "red", color: "red" }
|
||||
// },
|
||||
// {
|
||||
// criteria: { "rules[0].severity": "warn" },
|
||||
// attributes: { fontcolor: "orange", color: "orange" }
|
||||
// },
|
||||
// {
|
||||
// criteria: { "rules[0].severity": "info" },
|
||||
// attributes: { fontcolor: "blue", color: "blue" }
|
||||
// },
|
||||
// {
|
||||
// criteria: { resolved: "^src/model" },
|
||||
// attributes: { color: "#0000ff77" }
|
||||
// },
|
||||
// {
|
||||
// criteria: { resolved: "^src/view" },
|
||||
// attributes: { color: "#00770077" }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
},
|
||||
archi: {
|
||||
/* pattern of modules that can be consolidated in the high level
|
||||
graphical dependency graph. If you use the high level graphical
|
||||
dependency graph reporter (`archi`) you probably want to tweak
|
||||
this collapsePattern to your situation.
|
||||
*/
|
||||
collapsePattern: '^(packages|src|lib|app|bin|test(s?)|spec(s?))/[^/]+|node_modules/(@[^/]+/[^/]+|[^/]+)',
|
||||
|
||||
/* Options to tweak the appearance of your graph.See
|
||||
https://github.com/sverweij/dependency-cruiser/blob/master/doc/options-reference.md#reporteroptions
|
||||
for details and some examples. If you don't specify a theme
|
||||
for 'archi' dependency-cruiser will use the one specified in the
|
||||
dot section (see above), if any, and otherwise use the default one.
|
||||
*/
|
||||
// theme: {
|
||||
// },
|
||||
},
|
||||
"text": {
|
||||
"highlightFocused": true
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
// generated: dependency-cruiser@12.11.0 on 2023-03-24T14:11:38.647Z
|
||||
@@ -1,9 +0,0 @@
|
||||
VITE_APP_API=/api
|
||||
#登录与权限关闭
|
||||
VITE_APP_PM_ENABLED=false
|
||||
VITE_APP_TITLE=fs-admin-antdv4
|
||||
VITE_APP_SLOGAN=面向配置的CRUD开发,快如闪电
|
||||
VITE_APP_COPYRIGHT=Copyright © 2021 Greper
|
||||
VITE_APP_LOGO_PATH=./images/logo/logo.svg
|
||||
VITE_APP_PROJECT_PATH=https://github.com/fast-crud/fast-crud
|
||||
VITE_APP_NAMESPACE=fs
|
||||
@@ -1,2 +0,0 @@
|
||||
#登录与权限开启
|
||||
VITE_APP_PM_ENABLED=false
|
||||
@@ -1,2 +0,0 @@
|
||||
#登录与权限开启
|
||||
VITE_APP_PM_ENABLED=true
|
||||
@@ -1,2 +0,0 @@
|
||||
#登录与权限开启
|
||||
VITE_APP_PM_ENABLED=true
|
||||
@@ -1,3 +0,0 @@
|
||||
VITE_APP_API=http://www.docmirror.cn:7001/api
|
||||
#登录与权限开启
|
||||
VITE_APP_PM_ENABLED=true
|
||||
@@ -1,2 +0,0 @@
|
||||
node_modules
|
||||
.idea
|
||||
@@ -1,73 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: {
|
||||
browser: true,
|
||||
node: true,
|
||||
es6: true
|
||||
},
|
||||
parser: "vue-eslint-parser",
|
||||
parserOptions: {
|
||||
parser: "@typescript-eslint/parser",
|
||||
ecmaVersion: 2020,
|
||||
sourceType: "module",
|
||||
jsxPragma: "React",
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
tsx: true
|
||||
}
|
||||
},
|
||||
extends: ["plugin:vue/vue3-recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended", "prettier"],
|
||||
rules: {
|
||||
//"max-len": [0, 200, 2, { ignoreUrls: true }],
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/ban-ts-ignore": "off",
|
||||
"@typescript-eslint/explicit-function-return-type": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-var-requires": "off",
|
||||
"@typescript-eslint/no-empty-function": "off",
|
||||
"@typescript-eslint/no-use-before-define": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "off",
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off"
|
||||
// "@typescript-eslint/no-unused-vars": [
|
||||
// "error",
|
||||
// {
|
||||
// argsIgnorePattern: "^h$",
|
||||
// varsIgnorePattern: "^h$",
|
||||
// },
|
||||
// ],
|
||||
// "no-unused-vars": [
|
||||
// "error",
|
||||
// {
|
||||
// argsIgnorePattern: "^h$",
|
||||
// varsIgnorePattern: "^h$",
|
||||
// },
|
||||
// ],
|
||||
// "vue/custom-event-name-casing": "off",
|
||||
// "no-use-before-define": "off",
|
||||
// "space-before-function-paren": "off",
|
||||
|
||||
// "vue/attributes-order": "off",
|
||||
// "vue/one-component-per-file": "off",
|
||||
// "vue/html-closing-bracket-newline": "off",
|
||||
// "vue/max-attributes-per-line": "off",
|
||||
// "vue/multiline-html-element-content-newline": "off",
|
||||
// "vue/singleline-html-element-content-newline": "off",
|
||||
// "vue/attribute-hyphenation": "off",
|
||||
// "vue/require-default-prop": "off",
|
||||
// "vue/html-self-closing": [
|
||||
// "error",
|
||||
// {
|
||||
// html: {
|
||||
// void: "always",
|
||||
// normal: "never",
|
||||
// component: "always",
|
||||
// },
|
||||
// svg: "always",
|
||||
// math: "always",
|
||||
// },
|
||||
// ],
|
||||
}
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
> 感谢您支持fast-crud,请按如下规范提交issue
|
||||
> 如果有条件,请尽量在[github上提交](https://github.com/fast-crud/fast-crud/issues)
|
||||
|
||||
|
||||
## 一、问题描述
|
||||
`请在此处简要描述你所遇到的问题,必要时请贴出相关截图辅助理解和定位`
|
||||
|
||||
### 复现步骤
|
||||
`请描述复现问题的详细步骤`
|
||||
`如果非示例页面的问题,最好能提供最小复现示例的代码、或者仓库链接`
|
||||
|
||||
### 代码截图
|
||||
`请贴出出错的相关代码截图`
|
||||
|
||||
### 报错截图
|
||||
`请贴出报错日志截图`
|
||||
|
||||
### 效果截图
|
||||
`请贴出效果截图`
|
||||
#### 1. 期望效果
|
||||
|
||||
#### 2. 实际效果
|
||||
|
||||
|
||||
## 二、当前使用的库版本
|
||||
### 1. fast-crud版本:
|
||||
`请您填写fast-crud的版本`
|
||||
### 2. 使用的ui库以及版本
|
||||
`中括号中输入x即选中,或者删除其他,仅保留你正使用的ui库`
|
||||
- [x] Antdv (版本?)
|
||||
- [ ] ElementPlus(版本?)
|
||||
- [ ] NaiveUI(版本?)
|
||||
|
||||
### 3. 使用的admin框架
|
||||
`请您填写您当前使用的admin框架是哪一套`
|
||||
- [x] fs-admin-antdv
|
||||
- [ ] fs-admin-element
|
||||
- [ ] fs-admin-naive
|
||||
- [ ] fs-in-vben
|
||||
- [ ] vben-admin
|
||||
- [ ] cool-admin
|
||||
- [ ] 其他:`请注明`
|
||||
@@ -1,37 +0,0 @@
|
||||
name: sync-to-gitee
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
# 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:
|
||||
credentials: https://${{secrets.PUSH_TOKEN_GITEE}}@gitee.com
|
||||
|
||||
- name: push to gitee # 4. 执行同步
|
||||
run: |
|
||||
git remote add upstream https://gitee.com/fast-crud/fs-admin-antdv4
|
||||
git push --set-upstream upstream main
|
||||
|
||||
|
||||
|
||||
11
packages/ui/certd-client/.gitignore
vendored
11
packages/ui/certd-client/.gitignore
vendored
@@ -1,11 +0,0 @@
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
/stats.html
|
||||
yarn.lock
|
||||
.idea
|
||||
/.idea/
|
||||
yarn-error.log
|
||||
vite-profile.cpuprofile
|
||||
@@ -1,2 +0,0 @@
|
||||
node_modules
|
||||
/stats.html
|
||||
@@ -1,2 +0,0 @@
|
||||
link-workspace-packages=deep
|
||||
prefer-workspace-packages=true
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
|
||||
"trailingComma": "none",
|
||||
"printWidth": 220
|
||||
}
|
||||
@@ -1,689 +0,0 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [1.26.0](https://github.com/fast-crud/fast-crud/compare/v1.25.13...v1.26.0) (2025-07-28)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 独立使用form表单缺失mode的问题 ([9ed791a](https://github.com/fast-crud/fast-crud/commit/9ed791ad4bb9294f4b9380d858df89fbc32ca2a0))
|
||||
* 修复table-select 示例右上角自定义插槽无法设置的bug ([54a5d90](https://github.com/fast-crud/fast-crud/commit/54a5d90b86338036474657267de3bd7a74caf1eb))
|
||||
* card布局情况下,header-top header-bottom同时跟search显隐的bug ([3484232](https://github.com/fast-crud/fast-crud/commit/348423280f06f052fb16214e863ba03735ff9042))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* antdv示例背景设置为白色 ([3d74bf4](https://github.com/fast-crud/fast-crud/commit/3d74bf4e7ca76ecad286ec8f1b8fd2cbcb6428eb))
|
||||
|
||||
## [1.25.13](https://github.com/fast-crud/fast-crud/compare/v1.25.12...v1.25.13) (2025-06-10)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复fs-values-format组件某些值无法获取自动颜色的bug ([18169fc](https://github.com/fast-crud/fast-crud/commit/18169fc11f37595b8fba96467f0c741fe898ad21))
|
||||
|
||||
## [1.25.12](https://github.com/fast-crud/fast-crud/compare/v1.25.11...v1.25.12) (2025-05-26)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复cloneable模式下的dict 无法动态修改data的bug ([1dd5cd1](https://github.com/fast-crud/fast-crud/commit/1dd5cd1e1445b126451c6e1b68f453a70bf920de))
|
||||
|
||||
## [1.25.11](https://github.com/fast-crud/fast-crud/compare/v1.25.10...v1.25.11) (2025-05-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复naive-ui下 form-item 的label设置为render会报警告的问题 ([45e1bc6](https://github.com/fast-crud/fast-crud/commit/45e1bc6d9cfc408a98dfe628bf3b9bd14af4b2cf))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 单元格支持tooltip ([44d83ad](https://github.com/fast-crud/fast-crud/commit/44d83ad890589b2b64ff5e9f869fc04863576a3b))
|
||||
|
||||
## [1.25.10](https://github.com/fast-crud/fast-crud/compare/v1.25.9...v1.25.10) (2025-04-25)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 新增editable-select组件 ([8681285](https://github.com/fast-crud/fast-crud/commit/86812851de435cb2406d06898396c368d5eda414))
|
||||
* 优化antdv单元格合并示例,使用customCell方法,以及增加操作列合并演示 ([1068f9a](https://github.com/fast-crud/fast-crud/commit/1068f9aaa9b7732acb7082cc2ce3b1fadf1f8521))
|
||||
|
||||
## [1.25.9](https://github.com/fast-crud/fast-crud/compare/v1.25.8...v1.25.9) (2025-04-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复预览大图previewurl错误的bug ([cfb6554](https://github.com/fast-crud/fast-crud/commit/cfb6554c7c93297ddfcaa206168aceaf4ba2c2ef))
|
||||
* 修复yaml workers引入问题 ([1c90198](https://github.com/fast-crud/fast-crud/commit/1c90198f6f7df0ac0c9845d1c6af0592b1c34ae3))
|
||||
|
||||
## [1.25.8](https://github.com/fast-crud/fast-crud/compare/v1.25.7...v1.25.8) (2025-04-10)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复commonOptions无法覆盖某些参数的bug ([f2ecc03](https://github.com/fast-crud/fast-crud/commit/f2ecc034bf5b38d668ee8366c903a824af34302c))
|
||||
* fs-editor-code 支持配置schema校验 ([7d342cb](https://github.com/fast-crud/fast-crud/commit/7d342cbe8ebbaebb6ff5b3b80ce977d87aaa9ba5))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 添加代码编辑器示例 ([7217460](https://github.com/fast-crud/fast-crud/commit/72174604735b90fc57e0fb1ce40cc380b6c0c351))
|
||||
|
||||
## [1.25.7](https://github.com/fast-crud/fast-crud/compare/v1.25.6...v1.25.7) (2025-03-30)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复新页面编辑无法正确获取数据的bug ([e0df772](https://github.com/fast-crud/fast-crud/commit/e0df7729d0d8fff7a0bcd81477ec9379f6f23369))
|
||||
* 修复antdv4示例没有源码跳转按钮的bug ([a8f6486](https://github.com/fast-crud/fast-crud/commit/a8f6486bccc441bb394ae5fb8bbe515de78f83d3))
|
||||
|
||||
## [1.25.6](https://github.com/fast-crud/fast-crud/compare/v1.25.5...v1.25.6) (2025-03-19)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.25.5](https://github.com/fast-crud/fast-crud/compare/v1.25.4...v1.25.5) (2025-03-19)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复 antdv 弹出菜单边框过大的问题 ([fe4a044](https://github.com/fast-crud/fast-crud/commit/fe4a0442bf8fcdc3120b6de788ff318933b6bfab))
|
||||
* 修复 antdv懒加载后dropdown按钮无法点击的bug ([30ee067](https://github.com/fast-crud/fast-crud/commit/30ee067580fb663bbe550d50abf63c1fd89504a1))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* antdv示例增加保存列宽功能 ([a1218b0](https://github.com/fast-crud/fast-crud/commit/a1218b0451eb73fae8e337128e79b6e1fd4184eb))
|
||||
|
||||
## [1.25.4](https://github.com/fast-crud/fast-crud/compare/v1.25.3...v1.25.4) (2025-03-04)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 精简lodash ([21f59e8](https://github.com/fast-crud/fast-crud/commit/21f59e80db56cf0968b2739b9bc7ff1e8b7be4e4))
|
||||
* antdv 异步加载,加快首页打开速度 ([4eb4283](https://github.com/fast-crud/fast-crud/commit/4eb4283ad66e856814962ca2bde416dddbac0868))
|
||||
|
||||
## [1.25.3](https://github.com/fast-crud/fast-crud/compare/v1.25.2...v1.25.3) (2025-02-23)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.25.2](https://github.com/fast-crud/fast-crud/compare/v1.25.1...v1.25.2) (2025-02-22)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复4.2.x版本antdv导致modal全屏无效的bug ([9a26363](https://github.com/fast-crud/fast-crud/commit/9a26363d44faf6b0eb0809be4a8dd0fd14f2c309))
|
||||
|
||||
## [1.25.1](https://github.com/fast-crud/fast-crud/compare/v1.25.0...v1.25.1) (2025-02-12)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.25.0](https://github.com/fast-crud/fast-crud/compare/v1.24.2...v1.25.0) (2025-01-12)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 支持图标选择器 ([7dd8745](https://github.com/fast-crud/fast-crud/commit/7dd874534caa926ba63d6b8100116c032d794d51))
|
||||
|
||||
## [1.24.2](https://github.com/fast-crud/fast-crud/compare/v1.24.1...v1.24.2) (2024-12-31)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.24.1](https://github.com/fast-crud/fast-crud/compare/v1.24.0...v1.24.1) (2024-12-28)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.24.0](https://github.com/fast-crud/fast-crud/compare/v1.23.4...v1.24.0) (2024-12-28)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.23.4](https://github.com/fast-crud/fast-crud/compare/v1.23.3...v1.23.4) (2024-12-03)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复表单全屏的bug ([a25cff7](https://github.com/fast-crud/fast-crud/commit/a25cff725bef9d0dac063f7bd653844231c57b8d))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* rowHandle按钮支持render,删除按钮提供popcomfirm风格示例 ([b834db9](https://github.com/fast-crud/fast-crud/commit/b834db96e46e6b281d5c3a178a57c71aadf9bfd0))
|
||||
* table-select open支持context参数 ([492ee98](https://github.com/fast-crud/fast-crud/commit/492ee9862eee80ffcef81f42178a33484102213a))
|
||||
|
||||
## [1.23.3](https://github.com/fast-crud/fast-crud/compare/v1.23.2...v1.23.3) (2024-11-26)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复antdv4新页面打开示例不显示表单的bug ([34ab106](https://github.com/fast-crud/fast-crud/commit/34ab106d5e1cce918ce9745df141fda03f69331d))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 增加card列表示例 ([cfad8c8](https://github.com/fast-crud/fast-crud/commit/cfad8c87cb6f9588bb016c0595d03b34b0147c2a))
|
||||
|
||||
## [1.23.2](https://github.com/fast-crud/fast-crud/compare/v1.23.1...v1.23.2) (2024-11-18)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复dict-select多选情况下selected-change返回为空的bug ([181b167](https://github.com/fast-crud/fast-crud/commit/181b167d29536ffd8cd476e4744e322c5542b991))
|
||||
|
||||
## [1.23.1](https://github.com/fast-crud/fast-crud/compare/v1.23.0...v1.23.1) (2024-11-13)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复1.23.0 antdv下不显示pagination的bug ([9424dc1](https://github.com/fast-crud/fast-crud/commit/9424dc130505a5557042534acb976400b42ff483))
|
||||
|
||||
# [1.23.0](https://github.com/fast-crud/fast-crud/compare/v1.22.5...v1.23.0) (2024-11-11)
|
||||
|
||||
### Features
|
||||
|
||||
* 示例全面改成useFsAsync ([aa848a9](https://github.com/fast-crud/fast-crud/commit/aa848a9530af831247077620fa3ee0f605c19009))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 示例改成useFsAsync ([f7fac52](https://github.com/fast-crud/fast-crud/commit/f7fac52fcfaa4703bfebd8259007b235401b8357))
|
||||
|
||||
## [1.22.5](https://github.com/fast-crud/fast-crud/compare/v1.22.4...v1.22.5) (2024-11-04)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.22.4](https://github.com/fast-crud/fast-crud/compare/v1.22.3...v1.22.4) (2024-11-04)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复tab change后清空查询表单的bug ([8d7525a](https://github.com/fast-crud/fast-crud/commit/8d7525a747c41fe3fb1f14b92d0e353440ebc8ad))
|
||||
|
||||
## [1.22.3](https://github.com/fast-crud/fast-crud/compare/v1.22.2...v1.22.3) (2024-11-01)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复search.formItem配置无效的bug ([e112f03](https://github.com/fast-crud/fast-crud/commit/e112f033a60e142eced129e03b7c3cb96605b3fb))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* editable row 优化添加 ([9e0beb0](https://github.com/fast-crud/fast-crud/commit/9e0beb06470b564d490ec9393afe978f8a66c2fd))
|
||||
|
||||
## [1.22.2](https://github.com/fast-crud/fast-crud/compare/v1.22.1...v1.22.2) (2024-10-24)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.22.1](https://github.com/fast-crud/fast-crud/compare/v1.22.0...v1.22.1) (2024-10-23)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 表单支持左右插槽 ([e3a9e8b](https://github.com/fast-crud/fast-crud/commit/e3a9e8b985558f7cbff0acd580af242df56da8c4))
|
||||
* 独立使用表单支持插槽 ([095da7a](https://github.com/fast-crud/fast-crud/commit/095da7ac92996779f3b3c3885a8abd4de6c2fc0c))
|
||||
* editable支持单元格插槽 ([ae029de](https://github.com/fast-crud/fast-crud/commit/ae029de0f554f4cc4c4750e0af3b6f7bd1edaee5))
|
||||
* values-format option支持iconSpin ([cdaa4f5](https://github.com/fast-crud/fast-crud/commit/cdaa4f55a9384b95764443b4a7f4223ec787cce3))
|
||||
|
||||
# [1.22.0](https://github.com/fast-crud/fast-crud/compare/v1.21.5...v1.22.0) (2024-10-21)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.21.5](https://github.com/fast-crud/fast-crud/compare/v1.21.4...v1.21.5) (2024-10-21)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 列设置支持自定义storage ([298fb2f](https://github.com/fast-crud/fast-crud/commit/298fb2f9f2fff559567bedf6e977e7cb04024cdd))
|
||||
|
||||
## [1.21.4](https://github.com/fast-crud/fast-crud/compare/v1.21.3...v1.21.4) (2024-10-13)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化列设置多级表头支持级联勾选 ([a196922](https://github.com/fast-crud/fast-crud/commit/a196922630e9ef627dd548bb8d1c13acbe2eee28))
|
||||
* table-select支持destroyOnClose参数,以修复点击取消后,扔保留上一次选中值的bug ([5a70cec](https://github.com/fast-crud/fast-crud/commit/5a70cec7e5f45439a518fc2aadc40b29fad5c6f1))
|
||||
|
||||
## [1.21.3](https://github.com/fast-crud/fast-crud/compare/v1.21.2...v1.21.3) (2024-09-20)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化antdv search按钮组错位问题 ([0948650](https://github.com/fast-crud/fast-crud/commit/0948650747d725ffe84e4f357d81a3a9a331109e))
|
||||
|
||||
## [1.21.2](https://github.com/fast-crud/fast-crud/compare/v1.21.1...v1.21.2) (2024-07-15)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 增加示例,FsInDrawer ([777830f](https://github.com/fast-crud/fast-crud/commit/777830f860b6a9752ba24df5a99af5e7c62bdfb2))
|
||||
|
||||
## [1.21.1](https://github.com/fast-crud/fast-crud/compare/v1.21.0...v1.21.1) (2024-06-23)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复独立使用对话框 openDialog方法await无返回值的bug ([0cc22fd](https://github.com/fast-crud/fast-crud/commit/0cc22fd2ad57b8e3e85174ced1546bb6a90ed838))
|
||||
|
||||
# [1.21.0](https://github.com/fast-crud/fast-crud/compare/v1.20.2...v1.21.0) (2024-06-08)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复三级以上路由页面无法缓存的问题 ([9ce8c7a](https://github.com/fast-crud/fast-crud/commit/9ce8c7a6a5fc12f347351ca74213ff9c542820d3))
|
||||
* 修复提交表单只有一个输入框时点回车会刷新浏览器的问题 ([3d756ea](https://github.com/fast-crud/fast-crud/commit/3d756eaab6894355053e078424835d3edbd80025))
|
||||
* 修复fs-table.less中的颜色污染 ([a0b1de4](https://github.com/fast-crud/fast-crud/commit/a0b1de45668f882e13669c5aee484d3d2532ce25))
|
||||
* edit-wang 改成edit-wang5 ([7b994c1](https://github.com/fast-crud/fast-crud/commit/7b994c19637aa4b6399acbf362d4dc6a73c07ca4))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 富文本编辑器增加为空校验示例 ([3e51ac1](https://github.com/fast-crud/fast-crud/commit/3e51ac1c2c22f2dc5200134732fc0146a4a0fd2d))
|
||||
* 图片裁剪组件中英文支持 ([8b5b3f6](https://github.com/fast-crud/fast-crud/commit/8b5b3f61bc67e17ed13ded4a5519434249d5c4df))
|
||||
* alioss getAuthorization接口支持后台返回key ([75e5b14](https://github.com/fast-crud/fast-crud/commit/75e5b1449238fbae86f002c290771a6b9fd1f824))
|
||||
|
||||
## [1.20.2](https://github.com/fast-crud/fast-crud/compare/v1.20.1...v1.20.2) (2024-03-21)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复单元格valueChange 的value 改变滞后的问题 ([768c233](https://github.com/fast-crud/fast-crud/commit/768c233c915dc4277f3fb49106bf99f0bd1fb31c))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 升级依赖版本 ([42ae562](https://github.com/fast-crud/fast-crud/commit/42ae56289cc9d80ee1b3c1f9b7b2dd4656e9ba84))
|
||||
* table-select element增加radio列 ([b56b5df](https://github.com/fast-crud/fast-crud/commit/b56b5df79c6ce634bdac0545e83629f6f5587d42))
|
||||
|
||||
## [1.20.1](https://github.com/fast-crud/fast-crud/compare/v1.20.0...v1.20.1) (2024-02-27)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.20.0](https://github.com/fast-crud/fast-crud/compare/v1.19.3...v1.20.0) (2024-01-28)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复查询valueChange 修改form无效的bug ([054f8b4](https://github.com/fast-crud/fast-crud/commit/054f8b4b808a52f6d8daf2d19ee3adf43f693c0a))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化element 日期示例,格式化问题,输入数据格式告警问题,range样式问题 ([66fd07b](https://github.com/fast-crud/fast-crud/commit/66fd07b96143b77ed73b5e3b88182070ebdb4c80))
|
||||
* 优化form.wrapper.buttons的默认配置 ([61f2ae5](https://github.com/fast-crud/fast-crud/commit/61f2ae5600814a59e2eaad8933892c1ec9f57c69))
|
||||
* 优化free模式,支持默认不激活 ([aeaf0a6](https://github.com/fast-crud/fast-crud/commit/aeaf0a683ecc24dcb86036daea363f3019347299))
|
||||
* dict-tree组件无需手动配置labelName keyName ([c8b0ee1](https://github.com/fast-crud/fast-crud/commit/c8b0ee1ee5fa22e73b3a8ef77e1ad3335351dc70))
|
||||
|
||||
## [1.19.3](https://github.com/fast-crud/fast-crud/compare/v1.19.2...v1.19.3) (2023-12-15)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* antdv4 日期组件bug修复 ([a55b3e2](https://github.com/fast-crud/fast-crud/commit/a55b3e293a94396bbdfbd7d6dabb19d886cb8e16))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 增加表单label=0px示例 ([500d793](https://github.com/fast-crud/fast-crud/commit/500d793d72d727e8945cf7bca47aee684856bd80))
|
||||
|
||||
## [1.19.2](https://github.com/fast-crud/fast-crud/compare/v1.19.1...v1.19.2) (2023-11-22)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **editable:** 行编辑只能删除第一条数据的bug ([daf041f](https://github.com/fast-crud/fast-crud/commit/daf041f21cf531b4e32655248e522c96dd06f460))
|
||||
|
||||
## [1.19.1](https://github.com/fast-crud/fast-crud/compare/v1.19.0...v1.19.1) (2023-11-20)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复一些错误的类型定义 ([e098f51](https://github.com/fast-crud/fast-crud/commit/e098f511160148a824a1950bf4e85325c2ac50f0))
|
||||
|
||||
# [1.19.0](https://github.com/fast-crud/fast-crud/compare/v1.18.5...v1.19.0) (2023-11-20)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **editable:** 支持多级数据 ([89db59e](https://github.com/fast-crud/fast-crud/commit/89db59ea2b3dbe8227399086513e27aa7c2ab7aa))
|
||||
|
||||
## [1.18.5](https://github.com/fast-crud/fast-crud/compare/v1.18.4...v1.18.5) (2023-11-08)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复form.value会覆盖初始值的bug ([050f889](https://github.com/fast-crud/fast-crud/commit/050f889dfbdfb38debcd7c8e4a455acf07198530))
|
||||
|
||||
## [1.18.4](https://github.com/fast-crud/fast-crud/compare/v1.18.3...v1.18.4) (2023-11-07)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复afterSubmit返回false仍然关闭对话框的bug ([80337ff](https://github.com/fast-crud/fast-crud/commit/80337ffc46eda74d526562d9f27c43a2b6eb0534))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 新增国际手机号输入框 ([ebabee2](https://github.com/fast-crud/fast-crud/commit/ebabee2f61caed3678f0681330ed3cb044803a2f))
|
||||
* antdv 支持按钮组 ([cfdefdf](https://github.com/fast-crud/fast-crud/commit/cfdefdf89bfe7e037d1a8d3c6416cf38678074c9))
|
||||
|
||||
## [1.18.3](https://github.com/fast-crud/fast-crud/compare/v1.18.2...v1.18.3) (2023-10-26)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.18.2](https://github.com/fast-crud/fast-crud/compare/v1.18.1...v1.18.2) (2023-10-26)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 导出配置columns报错的bug ([d12f881](https://github.com/fast-crud/fast-crud/commit/d12f881f83e8c521673dc49d656e457a4fc67102))
|
||||
* 修复动态切换component.name报 resolveComponent 只能在setup和render中使用的问题 ([8792962](https://github.com/fast-crud/fast-crud/commit/8792962156346dbf05445d8f143b23296d60c781))
|
||||
|
||||
## [1.18.1](https://github.com/fast-crud/fast-crud/compare/v1.18.0...v1.18.1) (2023-10-26)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 取消 searchCopyFormProps valueResolve配置 ([ae55fda](https://github.com/fast-crud/fast-crud/commit/ae55fda1f9aa206d644f2e3da654201f0831f0be))
|
||||
|
||||
# [1.18.0](https://github.com/fast-crud/fast-crud/compare/v1.17.5...v1.18.0) (2023-10-25)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复antdv4,drawer弹窗过时的api ([9514db6](https://github.com/fast-crud/fast-crud/commit/9514db6768b5a5e1bef283b961438a6671f7df79))
|
||||
* 修复element下按钮图标异常问题 ([4959c2e](https://github.com/fast-crud/fast-crud/commit/4959c2e15b89f6d2fec50864f1453f2965a85159))
|
||||
* 增加文档链接 ([2b9f525](https://github.com/fast-crud/fast-crud/commit/2b9f525988c34ea322695b1a40de0628a627e50a))
|
||||
|
||||
### Features
|
||||
|
||||
* 新特性,CrudOptionsPlugin ([9e1ac6d](https://github.com/fast-crud/fast-crud/commit/9e1ac6df56622b3b75cd5a23ea565f5c722085de))
|
||||
* ui-demo,ui-interface独立 ([d78f040](https://github.com/fast-crud/fast-crud/commit/d78f040cd666d072937b0350edb2da11871206e6))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 导出增加loading ([6530c29](https://github.com/fast-crud/fast-crud/commit/6530c29615be9e1ff04029a962d521bed2df30a6))
|
||||
* 优化文档搜索 ([19fff41](https://github.com/fast-crud/fast-crud/commit/19fff41b3f431e2bd1c84274a7d17ad96a547b03))
|
||||
|
||||
## [1.17.5](https://github.com/fast-crud/fast-crud/compare/v1.17.4...v1.17.5) (2023-09-26)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.17.4](https://github.com/fast-crud/fast-crud/compare/v1.17.3...v1.17.4) (2023-09-26)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.17.3](https://github.com/fast-crud/fast-crud/compare/v1.17.2...v1.17.3) (2023-09-23)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.17.2](https://github.com/fast-crud/fast-crud/compare/v1.17.1...v1.17.2) (2023-09-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复naive 时间示例无法修改的bug ([6ab9218](https://github.com/fast-crud/fast-crud/commit/6ab92188fc19d792de8bed0190853c444784b009))
|
||||
* antdv 查询框label上置错位的bug ([00a35ad](https://github.com/fast-crud/fast-crud/commit/00a35ade86de3f2b9c3c336f3c8dda6f224e1abf))
|
||||
|
||||
## [1.17.1](https://github.com/fast-crud/fast-crud/compare/v1.17.0...v1.17.1) (2023-09-13)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.17.0](https://github.com/fast-crud/fast-crud/compare/v1.16.11...v1.17.0) (2023-09-12)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复element 图片裁剪组件无法横向排列的bug ([25fa258](https://github.com/fast-crud/fast-crud/commit/25fa25855e9750813d5a959a8b09ff6e90b04c1c))
|
||||
|
||||
### Features
|
||||
|
||||
* table-select支持 ([1c5b749](https://github.com/fast-crud/fast-crud/commit/1c5b7493a7782581a5f2a5bff843b135eb531f92))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 增加重置后清空排序设置演示 ([6a563ad](https://github.com/fast-crud/fast-crud/commit/6a563ad67b87f66e2765e47f72c5d4831cf06801))
|
||||
|
||||
## [1.16.11](https://github.com/fast-crud/fast-crud/compare/v1.16.10...v1.16.11) (2023-09-03)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.10](https://github.com/fast-crud/fast-crud/compare/v1.16.9...v1.16.10) (2023-09-03)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.9](https://github.com/fast-crud/fast-crud/compare/v1.16.8...v1.16.9) (2023-09-03)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 表单下所有组件优化为宽度100% ([da38460](https://github.com/fast-crud/fast-crud/commit/da384605f9c6bfc26359a369613dce4f48a3ba64))
|
||||
|
||||
## [1.16.8](https://github.com/fast-crud/fast-crud/compare/v1.16.7...v1.16.8) (2023-09-03)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 表单labelWidth演示 ([72f5372](https://github.com/fast-crud/fast-crud/commit/72f5372948f9aefebb0aba8671c277e8d80566bd))
|
||||
* 翻页后自动滚动到顶部 ([a6e5f67](https://github.com/fast-crud/fast-crud/commit/a6e5f6740a59780995283c7d787864fdd65f0d4b))
|
||||
|
||||
## [1.16.7](https://github.com/fast-crud/fast-crud/compare/v1.16.6...v1.16.7) (2023-08-21)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.6](https://github.com/fast-crud/fast-crud/compare/v1.16.5...v1.16.6) (2023-08-21)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.5](https://github.com/fast-crud/fast-crud/compare/v1.16.4...v1.16.5) (2023-08-20)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.4](https://github.com/fast-crud/fast-crud/compare/v1.16.3...v1.16.4) (2023-08-18)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.3](https://github.com/fast-crud/fast-crud/compare/v1.16.2...v1.16.3) (2023-08-18)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* fs-button增加buttonProps参数,当fs-button的属性与x-button属性名重复时使用 ([5ca5333](https://github.com/fast-crud/fast-crud/commit/5ca53330f8bcf8d7acf4eb921aa92b83c41de52a))
|
||||
|
||||
## [1.16.2](https://github.com/fast-crud/fast-crud/compare/v1.16.1...v1.16.2) (2023-08-10)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.16.1](https://github.com/fast-crud/fast-crud/compare/v1.16.0...v1.16.1) (2023-08-09)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.16.0](https://github.com/fast-crud/fast-crud/compare/v1.15.1...v1.16.0) (2023-08-07)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
## [1.15.1](https://github.com/fast-crud/fast-crud/compare/v1.15.0...v1.15.1) (2023-08-05)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv4
|
||||
|
||||
# [1.15.0](https://github.com/fast-crud/fast-crud/compare/v1.14.7...v1.15.0) (2023-08-05)
|
||||
|
||||
### Features
|
||||
|
||||
* antdv4 支持 ([1935614](https://github.com/fast-crud/fast-crud/commit/19356142cda925d1248fe7c84c18cb8324ce5f70))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 适配antdv4样式 ([1108f58](https://github.com/fast-crud/fast-crud/commit/1108f5874a5369cbdb6f015264327ea8a879da61))
|
||||
|
||||
## [1.14.7](https://github.com/fast-crud/fast-crud/compare/v1.14.6...v1.14.7) (2023-07-24)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.14.6](https://github.com/fast-crud/fast-crud/compare/v1.14.5...v1.14.6) (2023-07-23)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复element 版 search select组件右边超出显示的问题 ([ff11cf4](https://github.com/fast-crud/fast-crud/commit/ff11cf4f9c6ac63d997b5cad2067123c01cd299b))
|
||||
|
||||
## [1.14.5](https://github.com/fast-crud/fast-crud/compare/v1.14.4...v1.14.5) (2023-07-04)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复search.value第一次查询无效的bug ([d9a907a](https://github.com/fast-crud/fast-crud/commit/d9a907a477bae66662a8a8720a24ab3506772d30))
|
||||
|
||||
## [1.14.4](https://github.com/fast-crud/fast-crud/compare/v1.14.3...v1.14.4) (2023-07-02)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.14.3](https://github.com/fast-crud/fast-crud/compare/v1.14.2...v1.14.3) (2023-07-02)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.14.2](https://github.com/fast-crud/fast-crud/compare/v1.14.1...v1.14.2) (2023-07-02)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复多选导出csv,导致表格错位的bug ([4e0bf5b](https://github.com/fast-crud/fast-crud/commit/4e0bf5bae3bd39fd1654c5cf10991039eacf1acc))
|
||||
* 修复某些情况下fs-icon spin失效的bug ([2499a33](https://github.com/fast-crud/fast-crud/commit/2499a338def7436356c91a9b547e570c4204286d))
|
||||
* 修复行编辑模式下,render、conditionalRender无效的bug ([403fedc](https://github.com/fast-crud/fast-crud/commit/403fedc6e22817e33a1f4ac316a016e570127aa8))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 导出重构 ([e99dc7b](https://github.com/fast-crud/fast-crud/commit/e99dc7bb6b24d4456fc524a04e8787e16b07511e))
|
||||
* export 功能 ([2accdba](https://github.com/fast-crud/fast-crud/commit/2accdba5d087c01a87c6fd20b98c6510d0038f9d))
|
||||
|
||||
## [1.14.1](https://github.com/fast-crud/fast-crud/compare/v1.14.0...v1.14.1) (2023-06-16)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
# [1.14.0](https://github.com/fast-crud/fast-crud/compare/v1.13.12...v1.14.0) (2023-06-09)
|
||||
|
||||
### Features
|
||||
|
||||
* crudBinding.value.table.columns由array改成map ([8f89d2b](https://github.com/fast-crud/fast-crud/commit/8f89d2b26e12be0b3bcec2da8b4d7a2942395e8e))
|
||||
|
||||
## [1.13.12](https://github.com/fast-crud/fast-crud/compare/v1.13.11...v1.13.12) (2023-06-08)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.11](https://github.com/fast-crud/fast-crud/compare/v1.13.10...v1.13.11) (2023-06-08)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.10](https://github.com/fast-crud/fast-crud/compare/v1.13.9...v1.13.10) (2023-05-31)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.9](https://github.com/fast-crud/fast-crud/compare/v1.13.8...v1.13.9) (2023-05-31)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复antdv文件上传限制数量的bug ([8b14ba3](https://github.com/fast-crud/fast-crud/commit/8b14ba3a45f90a11222cc751b2ca173e212bc666))
|
||||
|
||||
## [1.13.8](https://github.com/fast-crud/fast-crud/compare/v1.13.7...v1.13.8) (2023-05-22)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.7](https://github.com/fast-crud/fast-crud/compare/v1.13.6...v1.13.7) (2023-05-19)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复rowhandle 排列不整齐的问题 ([ff644b1](https://github.com/fast-crud/fast-crud/commit/ff644b11b91c58295692fc0874dc4a3d743eb6df))
|
||||
|
||||
## [1.13.6](https://github.com/fast-crud/fast-crud/compare/v1.13.5...v1.13.6) (2023-05-13)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.5](https://github.com/fast-crud/fast-crud/compare/v1.13.4...v1.13.5) (2023-05-13)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.13.4](https://github.com/fast-crud/fast-crud/compare/v1.13.3...v1.13.4) (2023-05-06)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 1.13.3 ([451bd53](https://github.com/fast-crud/fast-crud/commit/451bd5390ce88fcbb875d39a39c88b3226f46b4e))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* naiveui sortable示例完善 ([dcd9e5b](https://github.com/fast-crud/fast-crud/commit/dcd9e5b04df7bda352878f4f1e30874ab9a6f452))
|
||||
|
||||
## [1.13.3](https://github.com/fast-crud/fast-crud/compare/v1.13.2...v1.13.3) (2023-05-04)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 升级cos sdk,修复windows报毒问题 ([352f8df](https://github.com/fast-crud/fast-crud/commit/352f8df76dfe093dd29c8778f3b33e3e3775b902))
|
||||
|
||||
## [1.13.2](https://github.com/fast-crud/fast-crud/compare/v1.13.1...v1.13.2) (2023-04-20)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* dict ts缺少cloneable参数 ([ab9528d](https://github.com/fast-crud/fast-crud/commit/ab9528d7ae2ab782cccc89d7530a22faa981ee74))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化fs-images-format 加载失败时的显示 ([7df6eab](https://github.com/fast-crud/fast-crud/commit/7df6eab4d653409de442eeef933177906a2ffc70))
|
||||
|
||||
## [1.13.1](https://github.com/fast-crud/fast-crud/compare/v1.13.0...v1.13.1) (2023-04-10)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
# [1.13.0](https://github.com/fast-crud/fast-crud/compare/v1.12.2...v1.13.0) (2023-04-07)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.12.2](https://github.com/fast-crud/fast-crud/compare/v1.12.1...v1.12.2) (2023-04-06)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.12.1](https://github.com/fast-crud/fast-crud/compare/v1.12.0...v1.12.1) (2023-04-04)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 增加自定义组件示例 ([c1f5b40](https://github.com/fast-crud/fast-crud/commit/c1f5b407d6137a0f5cbedb1ec2a56a18140e77a1))
|
||||
|
||||
# [1.12.0](https://github.com/fast-crud/fast-crud/compare/v1.11.10...v1.12.0) (2023-03-31)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化多行查询示例 ([95fa427](https://github.com/fast-crud/fast-crud/commit/95fa427043b29ef9590ce75fe91df9d5d686b196))
|
||||
|
||||
## [1.11.10](https://github.com/fast-crud/fast-crud/compare/v1.11.9...v1.11.10) (2023-03-29)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.9](https://github.com/fast-crud/fast-crud/compare/v1.11.8...v1.11.9) (2023-03-28)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.8](https://github.com/fast-crud/fast-crud/compare/v1.11.7...v1.11.8) (2023-03-24)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复当limit=1时,上传文件删光后,再选择文件上传第一次无效的bug ([d0a1ed9](https://github.com/fast-crud/fast-crud/commit/d0a1ed9c8a730d5eea19dc61f0dd6cf4031db1c3))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 优化翻页性能 ([d0a1db7](https://github.com/fast-crud/fast-crud/commit/d0a1db7bda08b49226739bba38e28b38c60c2b65))
|
||||
|
||||
## [1.11.7](https://github.com/fast-crud/fast-crud/compare/v1.11.6...v1.11.7) (2023-03-22)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.6](https://github.com/fast-crud/fast-crud/compare/v1.11.5...v1.11.6) (2023-03-22)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.5](https://github.com/fast-crud/fast-crud/compare/v1.11.4...v1.11.5) (2023-03-22)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.4](https://github.com/fast-crud/fast-crud/compare/v1.11.3...v1.11.4) (2023-03-22)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* doRefresh增加参数 ([a585604](https://github.com/fast-crud/fast-crud/commit/a5856045380f4a3fe2e657fd2ace1aea3473c6d7))
|
||||
|
||||
## [1.11.3](https://github.com/fast-crud/fast-crud/compare/v1.11.2...v1.11.3) (2023-03-21)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.2](https://github.com/fast-crud/fast-crud/compare/v1.11.1...v1.11.2) (2023-03-21)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.11.1](https://github.com/fast-crud/fast-crud/compare/v1.11.0...v1.11.1) (2023-03-17)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
# [1.11.0](https://github.com/fast-crud/fast-crud/compare/v1.10.0...v1.11.0) (2023-03-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 修复wangeditor无法上传视频的bug ([53ee51e](https://github.com/fast-crud/fast-crud/commit/53ee51e901956da9596600235632545bcf98746e))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 全面ts化 ([168d3a2](https://github.com/fast-crud/fast-crud/commit/168d3a240eb67548195c31a5fa4cb5aedb8a410c))
|
||||
|
||||
# [1.10.0](https://github.com/fast-crud/fast-crud/compare/v1.9.2...v1.10.0) (2023-03-11)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 行编辑支持多级表头 ([a547c99](https://github.com/fast-crud/fast-crud/commit/a547c99250f2d00b9d91c326364ccb81415c2772))
|
||||
|
||||
### Features
|
||||
|
||||
* fs-form-wrapper支持多实例 ([023cc1d](https://github.com/fast-crud/fast-crud/commit/023cc1d425d5b1fa618a3d13fe5c88c81671524d))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* 完善文档,完善部分types ([8fff02d](https://github.com/fast-crud/fast-crud/commit/8fff02d758530bbb1212d7475dc94bc8b562ef97))
|
||||
|
||||
* 优化d.ts类型 ([7a51aac](https://github.com/fast-crud/fast-crud/commit/7a51aace532ed6692f28a53332a2103a74f5827a))
|
||||
|
||||
* 增加s3示例 ([9060b03](https://github.com/fast-crud/fast-crud/commit/9060b036ce9e36ef8f2ddc50b1362682c7d3aa7f))
|
||||
|
||||
## [1.9.2](https://github.com/fast-crud/fast-crud/compare/v1.9.1...v1.9.2) (2023-03-01)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [1.9.1](https://github.com/fast-crud/fast-crud/compare/v1.9.0...v1.9.1) (2023-03-01)
|
||||
|
||||
**Note:** Version bump only for package @fast-crud/fs-admin-antdv
|
||||
|
||||
## [0.10.5](https://github.com/fast-crud/fast-crud/compare/v0.10.4...v0.10.5) (2021-07-01)
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* fs-admin 与crud demo ([4e6b20f](https://github.com/fast-crud/fast-crud/commit/4e6b20fe19434460853841f371b9fd5f16e5e2d3))
|
||||
|
||||
* fs-admin纳入子模块 ([2940d30](https://github.com/fast-crud/fast-crud/commit/2940d30f419bf4bde1e8e791f1fbdb9184818285))
|
||||
@@ -1,42 +0,0 @@
|
||||
# fs-admin-antdv
|
||||
|
||||
基于vue3、antdv 的 admin管理后台脚手架
|
||||
更多信息请参考: [fast-crud](https://github.com/fast-crud/fast-crud)
|
||||
# server端
|
||||
|
||||
## fs-server-js
|
||||
https://github.com/fast-crud/fs-server-js
|
||||
|
||||
# 其他相关项目
|
||||
* [fast-crud](https://github.com/fast-crud/fast-crud) crud主项目
|
||||
* [fs-admin-element](https://github.com/fast-crud/fs-admin-element) element版示例
|
||||
* [fs-admin-naive](https://github.com/fast-crud/fs-admin-naive-ui) naive版示例
|
||||
* [fs-in-vben-starter](https://github.com/fast-crud/fs-in-vben-starter) vben示例
|
||||
|
||||
# build
|
||||
|
||||
```sh
|
||||
set NODE_OPTIONS=--max-old-space-size=32768 && npm run build
|
||||
```
|
||||
# 感谢
|
||||
|
||||
### 依赖
|
||||
* [vue](https://github.com/vuejs/vue-next)
|
||||
* [vue-router](https://github.com/vuejs/vue-router-next)
|
||||
* [antdv 2x](https://github.com/vueComponent/ant-design-vue)
|
||||
* [vitejs](https://github.com/vitejs/vite)
|
||||
* [pinia](https://github.com/posva/pinia)
|
||||
* [purge-icons](https://github.com/antfu/purge-icons)
|
||||
|
||||
### 参考如下项目
|
||||
* [d2-admin](https://github.com/d2-projects/d2-admin)
|
||||
* [antdv-pro](https://github.com/vueComponent/ant-design-vue-pro)
|
||||
* [vben-admin](https://github.com/anncwb/vue-vben-admin)
|
||||
|
||||
感谢这些优秀的项目
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// import { getThemeVariables } from "ant-design-vue/dist/theme";
|
||||
// import path from "path";
|
||||
// const resolve = path.resolve;
|
||||
export function generateModifyVars(dark = false) {
|
||||
//const modifyVars = getThemeVariables({ dark });
|
||||
// const vars = `${resolve("src/style/theme/index.less")}`;
|
||||
return {
|
||||
//...modifyVars
|
||||
// hack: `true; @import (reference) "${vars}";`
|
||||
};
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { addDynamicIconSelectors } from "@iconify/tailwind";
|
||||
import { getPackagesSync } from "@manypkg/get-packages";
|
||||
import typographyPlugin from "@tailwindcss/typography";
|
||||
import animate from "tailwindcss-animate";
|
||||
|
||||
import { enterAnimationPlugin } from "./plugins/entry.mjs";
|
||||
|
||||
// import defaultTheme from 'tailwindcss/defaultTheme';
|
||||
|
||||
const { packages } = getPackagesSync(process.cwd());
|
||||
|
||||
const tailwindPackages = [];
|
||||
|
||||
packages.forEach((pkg) => {
|
||||
// apps目录下和 @vben-core/tailwind-ui 包需要使用到 tailwindcss ui
|
||||
// if (fs.existsSync(path.join(pkg.dir, 'tailwind.config.mjs'))) {
|
||||
tailwindPackages.push(pkg.dir);
|
||||
// }
|
||||
});
|
||||
|
||||
const shadcnUiColors = {
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
hover: "hsl(var(--accent-hover))",
|
||||
lighter: "has(val(--accent-lighter))"
|
||||
},
|
||||
background: {
|
||||
deep: "hsl(var(--background-deep))",
|
||||
DEFAULT: "hsl(var(--background))"
|
||||
},
|
||||
border: {
|
||||
DEFAULT: "hsl(var(--border))"
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))"
|
||||
},
|
||||
destructive: {
|
||||
...createColorsPalette("destructive"),
|
||||
DEFAULT: "hsl(var(--destructive))"
|
||||
},
|
||||
|
||||
foreground: {
|
||||
DEFAULT: "hsl(var(--foreground))"
|
||||
},
|
||||
|
||||
input: {
|
||||
background: "hsl(var(--input-background))",
|
||||
DEFAULT: "hsl(var(--input))"
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))"
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))"
|
||||
},
|
||||
primary: {
|
||||
...createColorsPalette("primary"),
|
||||
DEFAULT: "hsl(var(--primary))"
|
||||
},
|
||||
|
||||
ring: "hsl(var(--ring))",
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
desc: "hsl(var(--secondary-desc))",
|
||||
foreground: "hsl(var(--secondary-foreground))"
|
||||
}
|
||||
};
|
||||
|
||||
const customColors = {
|
||||
green: {
|
||||
...createColorsPalette("green"),
|
||||
foreground: "hsl(var(--success-foreground))"
|
||||
},
|
||||
header: {
|
||||
DEFAULT: "hsl(var(--header))"
|
||||
},
|
||||
heavy: {
|
||||
DEFAULT: "hsl(var(--heavy))",
|
||||
foreground: "hsl(var(--heavy-foreground))"
|
||||
},
|
||||
main: {
|
||||
DEFAULT: "hsl(var(--main))"
|
||||
},
|
||||
overlay: {
|
||||
content: "hsl(var(--overlay-content))",
|
||||
DEFAULT: "hsl(var(--overlay))"
|
||||
},
|
||||
red: {
|
||||
...createColorsPalette("red"),
|
||||
foreground: "hsl(var(--destructive-foreground))"
|
||||
},
|
||||
sidebar: {
|
||||
deep: "hsl(var(--sidebar-deep))",
|
||||
DEFAULT: "hsl(var(--sidebar))"
|
||||
},
|
||||
success: {
|
||||
...createColorsPalette("success"),
|
||||
DEFAULT: "hsl(var(--success))"
|
||||
},
|
||||
warning: {
|
||||
...createColorsPalette("warning"),
|
||||
DEFAULT: "hsl(var(--warning))"
|
||||
},
|
||||
yellow: {
|
||||
...createColorsPalette("yellow"),
|
||||
foreground: "hsl(var(--warning-foreground))"
|
||||
}
|
||||
};
|
||||
|
||||
export default {
|
||||
content: ["./index.html", ...tailwindPackages.map((item) => path.join(item, "src/**/*.{vue,js,ts,jsx,tsx,svelte,astro,html}"))],
|
||||
darkMode: "selector",
|
||||
plugins: [animate, typographyPlugin, addDynamicIconSelectors(), enterAnimationPlugin],
|
||||
prefix: "",
|
||||
theme: {
|
||||
container: {
|
||||
center: true,
|
||||
padding: "2rem",
|
||||
screens: {
|
||||
"2xl": "1400px"
|
||||
}
|
||||
},
|
||||
extend: {
|
||||
animation: {
|
||||
"accordion-down": "accordion-down 0.2s ease-out",
|
||||
"accordion-up": "accordion-up 0.2s ease-out",
|
||||
"collapsible-down": "collapsible-down 0.2s ease-in-out",
|
||||
"collapsible-up": "collapsible-up 0.2s ease-in-out",
|
||||
float: "float 5s linear 0ms infinite"
|
||||
},
|
||||
|
||||
animationDuration: {
|
||||
2000: "2000ms",
|
||||
3000: "3000ms"
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
xl: "calc(var(--radius) + 4px)"
|
||||
},
|
||||
boxShadow: {
|
||||
float: `0 6px 16px 0 rgb(0 0 0 / 8%),
|
||||
0 3px 6px -4px rgb(0 0 0 / 12%),
|
||||
0 9px 28px 8px rgb(0 0 0 / 5%)`
|
||||
},
|
||||
colors: {
|
||||
...customColors,
|
||||
...shadcnUiColors
|
||||
},
|
||||
fontFamily: {
|
||||
sans: [
|
||||
"var(--font-family)"
|
||||
// ...defaultTheme.fontFamily.sans
|
||||
]
|
||||
},
|
||||
keyframes: {
|
||||
"accordion-down": {
|
||||
from: { height: "0" },
|
||||
to: { height: "var(--radix-accordion-content-height)" }
|
||||
},
|
||||
"accordion-up": {
|
||||
from: { height: "var(--radix-accordion-content-height)" },
|
||||
to: { height: "0" }
|
||||
},
|
||||
"collapsible-down": {
|
||||
from: { height: "0" },
|
||||
to: { height: "var(--radix-collapsible-content-height)" }
|
||||
},
|
||||
"collapsible-up": {
|
||||
from: { height: "var(--radix-collapsible-content-height)" },
|
||||
to: { height: "0" }
|
||||
},
|
||||
float: {
|
||||
"0%": { transform: "translateY(0)" },
|
||||
"50%": { transform: "translateY(-20px)" },
|
||||
"100%": { transform: "translateY(0)" }
|
||||
}
|
||||
},
|
||||
zIndex: {
|
||||
100: "100",
|
||||
1000: "1000"
|
||||
}
|
||||
}
|
||||
},
|
||||
safelist: ["dark"]
|
||||
};
|
||||
|
||||
function createColorsPalette(name) {
|
||||
// backgroundLightest: '#EFF6FF', // Tailwind CSS 默认的 `blue-50`
|
||||
// backgroundLighter: '#DBEAFE', // Tailwind CSS 默认的 `blue-100`
|
||||
// backgroundLight: '#BFDBFE', // Tailwind CSS 默认的 `blue-200`
|
||||
// borderLight: '#93C5FD', // Tailwind CSS 默认的 `blue-300`
|
||||
// border: '#60A5FA', // Tailwind CSS 默认的 `blue-400`
|
||||
// main: '#3B82F6', // Tailwind CSS 默认的 `blue-500`
|
||||
// hover: '#2563EB', // Tailwind CSS 默认的 `blue-600`
|
||||
// active: '#1D4ED8', // Tailwind CSS 默认的 `blue-700`
|
||||
// backgroundDark: '#1E40AF', // Tailwind CSS 默认的 `blue-800`
|
||||
// backgroundDarker: '#1E3A8A', // Tailwind CSS 默认的 `blue-900`
|
||||
// backgroundDarkest: '#172554', // Tailwind CSS 默认的 `blue-950`
|
||||
|
||||
// • backgroundLightest (#EFF6FF): 适用于最浅的背景色,可能用于非常轻微的阴影或卡片的背景。
|
||||
// • backgroundLighter (#DBEAFE): 适用于略浅的背景色,通常用于次要背景或略浅的区域。
|
||||
// • backgroundLight (#BFDBFE): 适用于浅色背景,可能用于输入框或表单区域的背景。
|
||||
// • borderLight (#93C5FD): 适用于浅色边框,可能用于输入框或卡片的边框。
|
||||
// • border (#60A5FA): 适用于普通边框,可能用于按钮或卡片的边框。
|
||||
// • main (#3B82F6): 适用于主要的主题色,通常用于按钮、链接或主要的强调色。
|
||||
// • hover (#2563EB): 适用于鼠标悬停状态下的颜色,例如按钮悬停时的背景色或边框色。
|
||||
// • active (#1D4ED8): 适用于激活状态下的颜色,例如按钮按下时的背景色或边框色。
|
||||
// • backgroundDark (#1E40AF): 适用于深色背景,可能用于主要按钮或深色卡片背景。
|
||||
// • backgroundDarker (#1E3A8A): 适用于更深的背景,通常用于头部导航栏或页脚。
|
||||
// • backgroundDarkest (#172554): 适用于最深的背景,可能用于非常深色的区域或极端对比色。
|
||||
|
||||
return {
|
||||
50: `hsl(var(--${name}-50))`,
|
||||
100: `hsl(var(--${name}-100))`,
|
||||
200: `hsl(var(--${name}-200))`,
|
||||
300: `hsl(var(--${name}-300))`,
|
||||
400: `hsl(var(--${name}-400))`,
|
||||
500: `hsl(var(--${name}-500))`,
|
||||
600: `hsl(var(--${name}-600))`,
|
||||
700: `hsl(var(--${name}-700))`,
|
||||
// 800: `hsl(var(--${name}-800))`,
|
||||
// 900: `hsl(var(--${name}-900))`,
|
||||
// 950: `hsl(var(--${name}-950))`,
|
||||
// 激活状态下的颜色,适用于按钮按下时的背景色或边框色。
|
||||
active: `hsl(var(--${name}-700))`,
|
||||
// 浅色背景,适用于输入框或表单区域的背景。
|
||||
"background-light": `hsl(var(--${name}-200))`,
|
||||
// 适用于略浅的背景色,通常用于次要背景或略浅的区域。
|
||||
"background-lighter": `hsl(var(--${name}-100))`,
|
||||
// 最浅的背景色,适用于非常轻微的阴影或卡片的背景。
|
||||
"background-lightest": `hsl(var(--${name}-50))`,
|
||||
// 适用于普通边框,可能用于按钮或卡片的边框。
|
||||
border: `hsl(var(--${name}-400))`,
|
||||
// 浅色边框,适用于输入框或卡片的边框。
|
||||
"border-light": `hsl(var(--${name}-300))`,
|
||||
foreground: `hsl(var(--${name}-foreground))`,
|
||||
// 鼠标悬停状态下的颜色,适用于按钮悬停时的背景色或边框色。
|
||||
hover: `hsl(var(--${name}-600))`,
|
||||
// 主色文本
|
||||
text: `hsl(var(--${name}-500))`,
|
||||
// 主色文本激活态
|
||||
"text-active": `hsl(var(--${name}-700))`,
|
||||
// 主色文本悬浮态
|
||||
"text-hover": `hsl(var(--${name}-600))`
|
||||
};
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import plugin from "tailwindcss/plugin.js";
|
||||
|
||||
const enterAnimationPlugin = plugin(({ addUtilities }) => {
|
||||
const maxChild = 5;
|
||||
const utilities = {};
|
||||
for (let i = 1; i <= maxChild; i++) {
|
||||
const baseDelay = 0.1;
|
||||
const delay = `${baseDelay * i}s`;
|
||||
|
||||
utilities[`.enter-x:nth-child(${i})`] = {
|
||||
animation: `enter-x-animation 0.3s ease-in-out ${delay} forwards`,
|
||||
opacity: "0",
|
||||
transform: `translateX(50px)`
|
||||
};
|
||||
|
||||
utilities[`.enter-y:nth-child(${i})`] = {
|
||||
animation: `enter-y-animation 0.3s ease-in-out ${delay} forwards`,
|
||||
opacity: "0",
|
||||
transform: `translateY(50px)`
|
||||
};
|
||||
|
||||
utilities[`.-enter-x:nth-child(${i})`] = {
|
||||
animation: `enter-x-animation 0.3s ease-in-out ${delay} forwards`,
|
||||
opacity: "0",
|
||||
transform: `translateX(-50px)`
|
||||
};
|
||||
|
||||
utilities[`.-enter-y:nth-child(${i})`] = {
|
||||
animation: `enter-y-animation 0.3s ease-in-out ${delay} forwards`,
|
||||
opacity: "0",
|
||||
transform: `translateY(-50px)`
|
||||
};
|
||||
}
|
||||
|
||||
// 添加动画关键帧
|
||||
addUtilities(utilities);
|
||||
addUtilities({
|
||||
"@keyframes enter-x-animation": {
|
||||
to: {
|
||||
opacity: "1",
|
||||
transform: "translateX(0)"
|
||||
}
|
||||
},
|
||||
"@keyframes enter-y-animation": {
|
||||
to: {
|
||||
opacity: "1",
|
||||
transform: "translateY(0)"
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
export { enterAnimationPlugin };
|
||||
@@ -1,15 +0,0 @@
|
||||
import config from ".";
|
||||
|
||||
export default {
|
||||
plugins: {
|
||||
...(process.env.NODE_ENV === "production" ? { cssnano: {} } : {}),
|
||||
// Specifying the config is not necessary in most cases, but it is included
|
||||
autoprefixer: {},
|
||||
// 修复 element-plus 和 ant-design-vue 的样式和tailwindcss冲突问题
|
||||
"postcss-antd-fixes": { prefixes: ["ant", "el"] },
|
||||
"postcss-import": {},
|
||||
"postcss-preset-env": {},
|
||||
tailwindcss: { config },
|
||||
"tailwindcss/nesting": {}
|
||||
}
|
||||
};
|
||||
@@ -1,72 +0,0 @@
|
||||
import { generate } from "@ant-design/colors";
|
||||
|
||||
export const primaryColor = "#1890ff";
|
||||
|
||||
export const darkMode = "light";
|
||||
|
||||
type Fn = (...arg: any) => any;
|
||||
|
||||
export interface GenerateColorsParams {
|
||||
mixLighten: Fn;
|
||||
mixDarken: Fn;
|
||||
tinycolor: any;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export function generateAntColors(color: string) {
|
||||
return generate(color, {
|
||||
theme: "default"
|
||||
});
|
||||
}
|
||||
|
||||
export function getThemeColors(color?: string) {
|
||||
const tc = color || primaryColor;
|
||||
const colors = generateAntColors(tc);
|
||||
const primary = colors[5];
|
||||
const modeColors = generateAntColors(primary);
|
||||
|
||||
return [...colors, ...modeColors];
|
||||
}
|
||||
|
||||
export function generateColors({ color = primaryColor, mixLighten, mixDarken, tinycolor }: GenerateColorsParams) {
|
||||
const arr = new Array(19).fill(0);
|
||||
const lightens = arr.map((_t, i) => {
|
||||
return mixLighten(color, i / 5);
|
||||
});
|
||||
|
||||
const darkens = arr.map((_t, i) => {
|
||||
return mixDarken(color, i / 5);
|
||||
});
|
||||
|
||||
const alphaColors = arr.map((_t, i) => {
|
||||
return tinycolor(color)
|
||||
.setAlpha(i / 20)
|
||||
.toRgbString();
|
||||
});
|
||||
|
||||
const shortAlphaColors = alphaColors.map((item) => item.replace(/\s/g, "").replace(/0\./g, "."));
|
||||
|
||||
const tinycolorLightens = arr
|
||||
.map((_t, i) => {
|
||||
return tinycolor(color)
|
||||
.lighten(i * 5)
|
||||
.toHexString();
|
||||
})
|
||||
.filter((item) => item !== "#ffffff");
|
||||
|
||||
const tinycolorDarkens = arr
|
||||
.map((_t, i) => {
|
||||
return tinycolor(color)
|
||||
.darken(i * 5)
|
||||
.toHexString();
|
||||
})
|
||||
.filter((item) => item !== "#000000");
|
||||
return [
|
||||
...lightens,
|
||||
...darkens,
|
||||
...alphaColors,
|
||||
...shortAlphaColors,
|
||||
...tinycolorDarkens,
|
||||
...tinycolorLightens
|
||||
].filter((item) => !item.includes("-"));
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
/**
|
||||
* Vite plugin for website theme color switching
|
||||
* https://github.com/anncwb/vite-plugin-theme
|
||||
*/
|
||||
import type { Plugin } from "vite";
|
||||
import path from "path";
|
||||
import { viteThemePlugin, mixLighten, mixDarken, tinycolor, antdDarkThemePlugin } from "vite-plugin-theme";
|
||||
import { getThemeColors, generateColors } from "./theme-colors";
|
||||
import { generateModifyVars } from "./modify-vars";
|
||||
|
||||
export function configThemePlugin(isBuild: boolean): Plugin[] {
|
||||
const colors = generateColors({
|
||||
mixDarken,
|
||||
mixLighten,
|
||||
tinycolor
|
||||
});
|
||||
const colorVariables = [...getThemeColors(), ...colors];
|
||||
const plugin = [
|
||||
viteThemePlugin({
|
||||
// resolveSelector: (s) => {
|
||||
// s = s.trim();
|
||||
// switch (s) {
|
||||
// case ".ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon":
|
||||
// return ".ant-steps-item-icon > .ant-steps-icon";
|
||||
// case ".ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)":
|
||||
// case ".ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover":
|
||||
// case ".ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):active":
|
||||
// return s;
|
||||
// case ".ant-steps-item-icon > .ant-steps-icon":
|
||||
// return s;
|
||||
// }
|
||||
// return `[data-theme] ${s}`;
|
||||
// },
|
||||
resolveSelector: (s) => {
|
||||
s = s.trim();
|
||||
if (s === ".ant-btn:hover,.ant-btn:focus") {
|
||||
// console.log("ssss", s);
|
||||
return ".theme-discard-xxxxxxx";
|
||||
}
|
||||
return s;
|
||||
},
|
||||
colorVariables
|
||||
}),
|
||||
antdDarkThemePlugin({
|
||||
preloadFiles: [
|
||||
path.resolve(process.cwd(), "node_modules/ant-design-vue/dist/antd.less"),
|
||||
path.resolve(process.cwd(), "src/style/theme/index.less")
|
||||
],
|
||||
filter: (id) => (isBuild ? !id.endsWith("antd.less") : true),
|
||||
// extractCss: false,
|
||||
darkModifyVars: {
|
||||
...generateModifyVars(true),
|
||||
"text-color": "#c9d1d9",
|
||||
"text-color-base": "#c9d1d9",
|
||||
"component-background": "#151515",
|
||||
// black: '#0e1117',
|
||||
// #8b949e
|
||||
"text-color-secondary": "#8b949e",
|
||||
"border-color-base": "#303030",
|
||||
// 'border-color-split': '#30363d',
|
||||
"item-active-bg": "#111b26",
|
||||
"app-content-background": "rgb(255 255 255 / 4%)"
|
||||
}
|
||||
})
|
||||
];
|
||||
|
||||
return (plugin as unknown) as Plugin[];
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/logo.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title><%= title %></title>
|
||||
<link rel="stylesheet" type="text/css" href="/index.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<div class="fs-bootstrap">
|
||||
<div class="fs-bootstrap__main">
|
||||
<div class="fs-bootstrap__loading"></div>
|
||||
</div>
|
||||
<div class="fs-bootstrap__footer">
|
||||
<a href="<%= projectPath %>" target="_blank">
|
||||
<%= projectPath %>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,161 +0,0 @@
|
||||
{
|
||||
"name": "@fast-crud/fs-admin-antdv4",
|
||||
"version": "1.26.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:pm": "vite --mode pm",
|
||||
"dev:force": "vite --force",
|
||||
"debug": "vite --mode debug --open",
|
||||
"debug:pm": "vite --mode debugpm",
|
||||
"debug:force": "vite --force --mode debug",
|
||||
"build": "vite build ",
|
||||
"serve": "vite preview",
|
||||
"preview": "vite preview",
|
||||
"pretty-quick": "pretty-quick",
|
||||
"lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/",
|
||||
"upgrade": "yarn upgrade-interactive --latest",
|
||||
"tsc": "vue-tsc --noEmit --skipLibCheck",
|
||||
"circle:check": "pnpm dependency-cruise --validate --output-type err-html -f dependency-report.html src",
|
||||
"afterPubPush": "git add . && git commit -m \"build: publish success\" && git push"
|
||||
},
|
||||
"author": "greper",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@ant-design/colors": "^7.0.2",
|
||||
"@ant-design/icons-vue": "^7.0.1",
|
||||
"@aws-sdk/client-s3": "^3.535.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.535.0",
|
||||
"@ctrl/tinycolor": "^4.1.0",
|
||||
"@fast-crud/editor-code": "^1.26.0",
|
||||
"@fast-crud/fast-crud": "^1.26.0",
|
||||
"@fast-crud/fast-extends": "^1.26.0",
|
||||
"@fast-crud/ui-antdv4": "^1.26.0",
|
||||
"@fast-crud/ui-interface": "^1.26.0",
|
||||
"@iconify/tailwind": "^1.2.0",
|
||||
"@iconify/vue": "^4.1.1",
|
||||
"@manypkg/get-packages": "^2.2.2",
|
||||
"@soerenmartius/vue3-clipboard": "^0.1.2",
|
||||
"@tailwindcss/nesting": "0.0.0-insiders.565cd3e",
|
||||
"@tailwindcss/typography": "^0.5.16",
|
||||
"@tanstack/vue-store": "^0.7.0",
|
||||
"@vee-validate/zod": "^4.15.0",
|
||||
"@vue/shared": "^3.5.13",
|
||||
"@vueuse/core": "^10.11.0",
|
||||
"ant-design-vue": "^4.2.6",
|
||||
"axios": "^1.6.8",
|
||||
"axios-mock-adapter": "^1.22.0",
|
||||
"base64-js": "^1.5.1",
|
||||
"better-scroll": "^2.5.1",
|
||||
"china-division": "^2.7.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"core-js": "^3.36.0",
|
||||
"cos-js-sdk-v5": "^1.7.0",
|
||||
"cropperjs": "^1.6.1",
|
||||
"cssnano": "^7.0.6",
|
||||
"dayjs": "^1.11.10",
|
||||
"defu": "^6.1.4",
|
||||
"highlight.js": "^11.9.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lodash-es": "^4.17.21",
|
||||
"lucide-vue-next": "^0.477.0",
|
||||
"mitt": "^3.0.1",
|
||||
"monaco-editor": "^0.52.2",
|
||||
"monaco-yaml": "^5.3.1",
|
||||
"nprogress": "^0.2.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"pinia": "2.1.7",
|
||||
"pinia-plugin-persistedstate": "^4.2.0",
|
||||
"postcss-antd-fixes": "^0.2.0",
|
||||
"postcss-import": "^16.1.0",
|
||||
"postcss-preset-env": "^10.1.5",
|
||||
"qiniu-js": "^3.4.2",
|
||||
"radix-vue": "^1.9.16",
|
||||
"sortablejs": "^1.15.3",
|
||||
"tailwind-merge": "^3.0.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"theme-colors": "^0.1.0",
|
||||
"vee-validate": "^4.15.0",
|
||||
"vitest": "^0.34.6",
|
||||
"vue": "^3.4.21",
|
||||
"vue-cropperjs": "^5.0.0",
|
||||
"vue-i18n": "^9.10.2",
|
||||
"vue-router": "^4.3.0",
|
||||
"vuedraggable": "^2.24.3",
|
||||
"watermark-js-plus": "^1.5.8",
|
||||
"yaml-language-server": "^1.17.0",
|
||||
"zod": "^3.24.2",
|
||||
"zod-defaults": "^0.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^25.0.7",
|
||||
"@rollup/plugin-node-resolve": "^15.2.3",
|
||||
"@types/chai": "^4.3.12",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/mocha": "^10.0.6",
|
||||
"@types/node": "^20.11.28",
|
||||
"@types/nprogress": "^0.2.3",
|
||||
"@typescript-eslint/eslint-plugin": "^7.2.0",
|
||||
"@typescript-eslint/parser": "^7.2.0",
|
||||
"@vitejs/plugin-legacy": "^5.3.2",
|
||||
"@vitejs/plugin-vue": "^5.0.4",
|
||||
"@vitejs/plugin-vue-jsx": "^3.1.0",
|
||||
"@vue/compiler-sfc": "^3.4.21",
|
||||
"@vue/eslint-config-typescript": "^13.0.0",
|
||||
"@vue/test-utils": "^2.4.5",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"caller-path": "^4.0.0",
|
||||
"chai": "^5.1.0",
|
||||
"dependency-cruiser": "^16.2.3",
|
||||
"dot": "^1.1.3",
|
||||
"eslint": "8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"eslint-plugin-promise": "^6.1.1",
|
||||
"eslint-plugin-vue": "^9.23.0",
|
||||
"esno": "^4.7.0",
|
||||
"husky": "^9.0.11",
|
||||
"less": "^4.2.0",
|
||||
"less-loader": "^12.2.0",
|
||||
"lint-staged": "^15.2.2",
|
||||
"postcss": "^8.4.35",
|
||||
"prettier": "3.2.5",
|
||||
"pretty-quick": "^4.0.0",
|
||||
"rimraf": "^5.0.5",
|
||||
"rollup": "^4.13.0",
|
||||
"rollup-plugin-visualizer": "^5.12.0",
|
||||
"stylelint": "^16.2.1",
|
||||
"stylelint-config-prettier": "^9.0.5",
|
||||
"stylelint-order": "^6.0.4",
|
||||
"tailwindcss": "^3.4.14",
|
||||
"terser": "^5.29.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tslint": "^6.1.3",
|
||||
"typescript": "5.4.2",
|
||||
"unplugin-vue-define-options": "^1.4.2",
|
||||
"vite": "^5.1.6",
|
||||
"vite-plugin-compression": "^0.5.1",
|
||||
"vite-plugin-html": "^3.2.2",
|
||||
"vite-plugin-theme": "^0.8.6",
|
||||
"vite-plugin-windicss": "^1.9.3",
|
||||
"vue-eslint-parser": "^9.4.2",
|
||||
"vue-tsc": "^1.8.8",
|
||||
"windicss": "^3.5.6"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
},
|
||||
"gitHead": "9c2162697f3affea22c9a8cbc0ca74f4034ab27e",
|
||||
"vite": {
|
||||
"optimizeDeps": {
|
||||
"include": [
|
||||
"@iconify/iconify"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import config from "./build/tailwind-config/index.mjs";
|
||||
|
||||
export default {
|
||||
plugins: {
|
||||
...(process.env.NODE_ENV === "production" ? { cssnano: {} } : {}),
|
||||
// Specifying the config is not necessary in most cases, but it is included
|
||||
autoprefixer: {},
|
||||
// 修复 element-plus 和 ant-design-vue 的样式和tailwindcss冲突问题
|
||||
"postcss-antd-fixes": { prefixes: ["ant", "el"] },
|
||||
"postcss-import": {},
|
||||
"postcss-preset-env": {},
|
||||
tailwindcss: { config },
|
||||
"tailwindcss/nesting": {}
|
||||
}
|
||||
};
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
@@ -1,106 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="210mm"
|
||||
height="210mm"
|
||||
viewBox="0 0 210 210"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
>
|
||||
<g id="layer1" style="display:inline">
|
||||
<path
|
||||
style="fill:#002255;stroke:none;stroke-width:0.625348"
|
||||
d="M 35.587501,69.766667 V 59.766664 h 70.000109 69.99991 v 10.000003 9.999997 H 105.58761 35.587501 Z"
|
||||
id="path12" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-4"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8-3"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8-2"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-7"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-4-0"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-9"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8-37"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8-4"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-7-1"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="82.941666" />
|
||||
</g>
|
||||
<polygon
|
||||
points="75.3,174.4 103.1,103.6 79.8,103.6 112.6,41.3 156.4,41.3 129.9,90.5 148.1,90.5 "
|
||||
fill="#f6cc00"
|
||||
id="polygon276"
|
||||
transform="matrix(1.0930933,0,0,0.99853202,-17.517362,-0.52287941)" />
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.7 KiB |
@@ -1,12 +0,0 @@
|
||||
html, body, #app { height: 100%; margin: 0; padding: 0; width: 100%;}
|
||||
.fs-bootstrap { background-color: #474949; height: 100%; display: flex; flex-direction: column;position: fixed;width: 100% }
|
||||
.fs-bootstrap__main {flex:1; user-select: none; width: 100%; flex-grow: 1; display: flex; justify-content: center; align-items: center; flex-direction: column; }
|
||||
.fs-bootstrap__footer { width: 100%; flex-grow: 0; text-align: center; padding: 10px 0; }
|
||||
.fs-bootstrap__footer > a { font-size: 12px; color: #ABABAB; text-decoration: none; }
|
||||
.fs-bootstrap__loading {box-sizing: border-box; height: 50px; width: 50px; margin-bottom: 5px;border:5px solid #333333;border-bottom:#aaa 5px solid;
|
||||
border-radius:1000px; animation:load 1.1s infinite linear;-webkit-animation:load 1.1s infinite linear;-moz-animation:load 1.1s infinite linear; -o-animation:load 1.1s infinite linear;
|
||||
}
|
||||
@keyframes load {from {transform:rotate(0deg);-ms-transform:rotate(0deg);}to { transform:rotate(360deg);-ms-transform:rotate(360deg); }
|
||||
}@-webkit-keyframes load {from {-webkit-transform:rotate(0deg); }to { -webkit-transform:rotate(360deg);}
|
||||
}@-moz-keyframes load { from { -moz-transform:rotate(0deg); } to { -moz-transform:rotate(360deg);}
|
||||
}@-o-keyframes load { from { -o-transform:rotate(0deg);} to { -o-transform:rotate(360deg);}}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@@ -1,106 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="210mm"
|
||||
height="210mm"
|
||||
viewBox="0 0 210 210"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
>
|
||||
<g id="layer1" style="display:inline">
|
||||
<path
|
||||
style="fill:#002255;stroke:none;stroke-width:0.625348"
|
||||
d="M 35.587501,69.766667 V 59.766664 h 70.000109 69.99991 v 10.000003 9.999997 H 105.58761 35.587501 Z"
|
||||
id="path12" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-4"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8-3"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8-2"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-7"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="106.64581" />
|
||||
<rect
|
||||
style="fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-4-0"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="129.82079" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-9"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="71.506088"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-8-37"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="107.42467"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-8-5-8-4"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="143.34325"
|
||||
y="82.941666" />
|
||||
<rect
|
||||
style="display:inline;fill:#2a7fff;fill-rule:evenodd;stroke-width:0.214311"
|
||||
id="rect22-2-7-1"
|
||||
width="32.244232"
|
||||
height="20"
|
||||
x="35.587502"
|
||||
y="82.941666" />
|
||||
</g>
|
||||
<polygon
|
||||
points="75.3,174.4 103.1,103.6 79.8,103.6 112.6,41.3 156.4,41.3 129.9,90.5 148.1,90.5 "
|
||||
fill="#f6cc00"
|
||||
id="polygon276"
|
||||
transform="matrix(1.0930933,0,0,0.99853202,-17.517362,-0.52287941)" />
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.7 KiB |
@@ -1,6 +0,0 @@
|
||||
name,mobile
|
||||
张三,18603040102
|
||||
李四,18603040103
|
||||
王五,18603040104
|
||||
赵六,18603040105
|
||||
田七,18603040106
|
||||
|
@@ -1,69 +0,0 @@
|
||||
<template>
|
||||
<AConfigProvider :locale="locale" :theme="tokenTheme">
|
||||
<fs-form-provider>
|
||||
<router-view v-if="routerEnabled" />
|
||||
</fs-form-provider>
|
||||
</AConfigProvider>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import zhCN from "ant-design-vue/es/locale/zh_CN";
|
||||
import enUS from "ant-design-vue/es/locale/en_US";
|
||||
import { computed, provide, ref } from "vue";
|
||||
import "dayjs/locale/zh-cn";
|
||||
import "dayjs/locale/en";
|
||||
import dayjs from "dayjs";
|
||||
import { usePreferences, preferences } from "/@/vben/preferences";
|
||||
import { useAntdDesignTokens } from "/@/vben/hooks";
|
||||
import { theme } from "ant-design-vue";
|
||||
import AConfigProvider from "ant-design-vue/es/config-provider";
|
||||
defineOptions({
|
||||
name: "App"
|
||||
});
|
||||
|
||||
//刷新页面方法
|
||||
const routerEnabled = ref(true);
|
||||
const locale = ref(zhCN);
|
||||
async function reload() {
|
||||
// routerEnabled.value = false;
|
||||
// await nextTick();
|
||||
// routerEnabled.value = true;
|
||||
}
|
||||
function localeChanged(value: any) {
|
||||
console.log("locale changed:", value);
|
||||
if (value === "zh-cn") {
|
||||
locale.value = zhCN;
|
||||
dayjs.locale("zh-cn");
|
||||
} else if (value === "en") {
|
||||
locale.value = enUS;
|
||||
dayjs.locale("en");
|
||||
}
|
||||
}
|
||||
localeChanged("zh-cn");
|
||||
provide("fn:router.reload", reload);
|
||||
provide("fn:locale.changed", localeChanged);
|
||||
|
||||
const { isDark } = usePreferences();
|
||||
const { tokens } = useAntdDesignTokens();
|
||||
|
||||
const tokenTheme = computed(() => {
|
||||
const algorithm = isDark.value ? [theme.darkAlgorithm] : [theme.defaultAlgorithm];
|
||||
|
||||
// antd 紧凑模式算法
|
||||
if (preferences.app.compact) {
|
||||
algorithm.push(theme.compactAlgorithm);
|
||||
}
|
||||
|
||||
return {
|
||||
algorithm,
|
||||
token: tokens
|
||||
};
|
||||
});
|
||||
//其他初始化
|
||||
// const resourceStore = useResourceStore();
|
||||
// resourceStore.init();
|
||||
// const pageStore = usePageStore();
|
||||
// pageStore.init();
|
||||
// const settingStore = useSettingStore();
|
||||
// settingStore.init();
|
||||
</script>
|
||||
@@ -1,31 +0,0 @@
|
||||
export default [
|
||||
{
|
||||
path: "/login",
|
||||
method: "post",
|
||||
handle() {
|
||||
return {
|
||||
code: 0,
|
||||
msg: "success",
|
||||
data: {
|
||||
token: "faker token",
|
||||
expire: 10000
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
path: "/sys/authority/user/mine",
|
||||
method: "get",
|
||||
handle() {
|
||||
return {
|
||||
code: 0,
|
||||
msg: "success",
|
||||
data: {
|
||||
id: 1,
|
||||
username: "username",
|
||||
nickName: "admin"
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -1,52 +0,0 @@
|
||||
import { request, requestForMock } from "../service";
|
||||
import { env } from "/@/utils/util.env";
|
||||
/**
|
||||
* @description: Login interface parameters
|
||||
*/
|
||||
export interface LoginReq {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface UserInfoRes {
|
||||
id: string | number;
|
||||
username: string;
|
||||
nickName: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export interface LoginRes {
|
||||
token: string;
|
||||
expire: number;
|
||||
}
|
||||
|
||||
export async function login(data: LoginReq): Promise<LoginRes> {
|
||||
if (env.PM_ENABLED === "false") {
|
||||
//没有开启权限模块,模拟登录
|
||||
return await requestForMock({
|
||||
url: "/login",
|
||||
method: "post",
|
||||
data
|
||||
});
|
||||
}
|
||||
//如果开启了登录与权限模块,则真实登录
|
||||
return await request({
|
||||
url: "/login",
|
||||
method: "post",
|
||||
data
|
||||
});
|
||||
}
|
||||
|
||||
export async function mine(): Promise<UserInfoRes> {
|
||||
if (env.PM_ENABLED === "false") {
|
||||
//没有开启权限模块,模拟登录
|
||||
return await requestForMock({
|
||||
url: "/sys/authority/user/mine",
|
||||
method: "post"
|
||||
});
|
||||
}
|
||||
return await request({
|
||||
url: "/sys/authority/user/mine",
|
||||
method: "post"
|
||||
});
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import axios from "axios";
|
||||
import { get } from "lodash-es";
|
||||
import Adapter from "axios-mock-adapter";
|
||||
import { errorLog, errorCreate } from "./tools";
|
||||
import { env } from "/src/utils/util.env";
|
||||
import { useUserStore } from "../store/modules/user";
|
||||
/**
|
||||
* @description 创建请求实例
|
||||
*/
|
||||
function createService() {
|
||||
// 创建一个 axios 实例
|
||||
const service = axios.create();
|
||||
// 请求拦截
|
||||
service.interceptors.request.use(
|
||||
(config) => config,
|
||||
(error) => {
|
||||
// 发送失败
|
||||
console.log(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
// 响应拦截
|
||||
service.interceptors.response.use(
|
||||
(response) => {
|
||||
if (response.config.responseType === "blob") {
|
||||
return response;
|
||||
}
|
||||
// dataAxios 是 axios 返回数据中的 data
|
||||
const dataAxios = response.data;
|
||||
// 这个状态码是和后端约定的
|
||||
const { code } = dataAxios;
|
||||
// 根据 code 进行判断
|
||||
if (code === undefined) {
|
||||
// 如果没有 code 代表这不是项目后端开发的接口 比如可能是 D2Admin 请求最新版本
|
||||
errorCreate(`非标准返回:${dataAxios}, ${response.config.url}`);
|
||||
return dataAxios;
|
||||
} else {
|
||||
// 有 code 代表这是一个后端接口 可以进行进一步的判断
|
||||
switch (code) {
|
||||
case 0:
|
||||
// [ 示例 ] code === 0 代表没有错误
|
||||
// @ts-ignore
|
||||
if (response.config.unpack === false) {
|
||||
//如果不需要解包
|
||||
return dataAxios;
|
||||
}
|
||||
return dataAxios.data;
|
||||
default:
|
||||
// 不是正确的 code
|
||||
errorCreate(`${dataAxios.msg}: ${response.config.url}`);
|
||||
return dataAxios;
|
||||
}
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
const status = get(error, "response.status");
|
||||
switch (status) {
|
||||
case 400:
|
||||
error.message = "请求错误";
|
||||
break;
|
||||
case 401:
|
||||
error.message = "未授权,请登录";
|
||||
break;
|
||||
case 403:
|
||||
error.message = "拒绝访问";
|
||||
break;
|
||||
case 404:
|
||||
error.message = `请求地址出错: ${error.response.config.url}`;
|
||||
break;
|
||||
case 408:
|
||||
error.message = "请求超时";
|
||||
break;
|
||||
case 500:
|
||||
error.message = "服务器内部错误";
|
||||
break;
|
||||
case 501:
|
||||
error.message = "服务未实现";
|
||||
break;
|
||||
case 502:
|
||||
error.message = "网关错误";
|
||||
break;
|
||||
case 503:
|
||||
error.message = "服务不可用";
|
||||
break;
|
||||
case 504:
|
||||
error.message = "网关超时";
|
||||
break;
|
||||
case 505:
|
||||
error.message = "HTTP版本不受支持";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
errorLog(error);
|
||||
if (status === 401) {
|
||||
const userStore = useUserStore();
|
||||
userStore.logout();
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
return service;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建请求方法
|
||||
* @param {Object} service axios 实例
|
||||
*/
|
||||
function createRequestFunction(service: any) {
|
||||
return function (config: any) {
|
||||
const configDefault = {
|
||||
headers: {
|
||||
"Content-Type": get(config, "headers.Content-Type", "application/json")
|
||||
},
|
||||
timeout: 5000,
|
||||
baseURL: env.API,
|
||||
data: {}
|
||||
};
|
||||
const userStore = useUserStore();
|
||||
const token = userStore.getToken;
|
||||
if (token != null) {
|
||||
// @ts-ignore
|
||||
configDefault.headers.Authorization = token;
|
||||
}
|
||||
return service(Object.assign(configDefault, config));
|
||||
};
|
||||
}
|
||||
|
||||
// 用于真实网络请求的实例和请求方法
|
||||
export const service = createService();
|
||||
export const request = createRequestFunction(service);
|
||||
|
||||
// 用于模拟网络请求的实例和请求方法
|
||||
export const serviceForMock = createService();
|
||||
export const requestForMock = createRequestFunction(serviceForMock);
|
||||
|
||||
// 网络请求数据模拟工具
|
||||
export const mock = new Adapter(serviceForMock, { delayResponse: 200 });
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* @description 安全地解析 json 字符串
|
||||
* @param {String} jsonString 需要解析的 json 字符串
|
||||
* @param {String} defaultValue 默认值
|
||||
*/
|
||||
import { uiContext } from "@fast-crud/fast-crud";
|
||||
|
||||
export function parse(jsonString = "{}", defaultValue = {}) {
|
||||
let result = defaultValue;
|
||||
try {
|
||||
result = JSON.parse(jsonString);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
* @param {Number} code 状态码
|
||||
*/
|
||||
export function response(data = {}, msg = "", code = 0) {
|
||||
return [200, { code, msg, data }];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回 正确返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
*/
|
||||
export function responseSuccess(data = {}, msg = "成功") {
|
||||
return response(data, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回 错误返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
* @param {Number} code 状态码
|
||||
*/
|
||||
export function responseError(data = {}, msg = "请求失败", code = 500) {
|
||||
return response(data, msg, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 记录和显示错误
|
||||
* @param {Error} error 错误对象
|
||||
*/
|
||||
export function errorLog(error: any) {
|
||||
// 打印到控制台
|
||||
console.error(error);
|
||||
let message = error.message;
|
||||
if (error.response?.data?.message) {
|
||||
message = error.response.data.message;
|
||||
}
|
||||
// 显示提示
|
||||
uiContext.get().notification.error({ message });
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建一个错误
|
||||
* @param {String} msg 错误信息
|
||||
*/
|
||||
export function errorCreate(msg: any) {
|
||||
const error = new Error(msg);
|
||||
errorLog(error);
|
||||
throw error;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg width="1361px" height="609px" viewBox="0 0 1361 609" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>Group 21</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs></defs>
|
||||
<g id="Ant-Design-Pro-3.0" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="账户密码登录-校验" transform="translate(-79.000000, -82.000000)">
|
||||
<g id="Group-21" transform="translate(77.000000, 73.000000)">
|
||||
<g id="Group-18" opacity="0.8" transform="translate(74.901416, 569.699158) rotate(-7.000000) translate(-74.901416, -569.699158) translate(4.901416, 525.199158)">
|
||||
<ellipse id="Oval-11" fill="#CFDAE6" opacity="0.25" cx="63.5748792" cy="32.468367" rx="21.7830479" ry="21.766008"></ellipse>
|
||||
<ellipse id="Oval-3" fill="#CFDAE6" opacity="0.599999964" cx="5.98746479" cy="13.8668601" rx="5.2173913" ry="5.21330997"></ellipse>
|
||||
<path d="M38.1354514,88.3520215 C43.8984227,88.3520215 48.570234,83.6838647 48.570234,77.9254015 C48.570234,72.1669383 43.8984227,67.4987816 38.1354514,67.4987816 C32.3724801,67.4987816 27.7006688,72.1669383 27.7006688,77.9254015 C27.7006688,83.6838647 32.3724801,88.3520215 38.1354514,88.3520215 Z" id="Oval-3-Copy" fill="#CFDAE6" opacity="0.45"></path>
|
||||
<path d="M64.2775582,33.1704963 L119.185836,16.5654915" id="Path-12" stroke="#CFDAE6" stroke-width="1.73913043" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M42.1431708,26.5002681 L7.71190162,14.5640702" id="Path-16" stroke="#E0B4B7" stroke-width="0.702678964" opacity="0.7" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.405357899873153,2.108036953469981"></path>
|
||||
<path d="M63.9262187,33.521561 L43.6721326,69.3250951" id="Path-15" stroke="#BACAD9" stroke-width="0.702678964" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.405357899873153,2.108036953469981"></path>
|
||||
<g id="Group-17" transform="translate(126.850922, 13.543654) rotate(30.000000) translate(-126.850922, -13.543654) translate(117.285705, 4.381889)" fill="#CFDAE6">
|
||||
<ellipse id="Oval-4" opacity="0.45" cx="9.13482653" cy="9.12768076" rx="9.13482653" ry="9.12768076"></ellipse>
|
||||
<path d="M18.2696531,18.2553615 C18.2696531,13.2142826 14.1798519,9.12768076 9.13482653,9.12768076 C4.08980114,9.12768076 0,13.2142826 0,18.2553615 L18.2696531,18.2553615 Z" id="Oval-4" transform="translate(9.134827, 13.691521) scale(-1, -1) translate(-9.134827, -13.691521) "></path>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Group-14" transform="translate(216.294700, 123.725600) rotate(-5.000000) translate(-216.294700, -123.725600) translate(106.294700, 35.225600)">
|
||||
<ellipse id="Oval-2" fill="#CFDAE6" opacity="0.25" cx="29.1176471" cy="29.1402439" rx="29.1176471" ry="29.1402439"></ellipse>
|
||||
<ellipse id="Oval-2" fill="#CFDAE6" opacity="0.3" cx="29.1176471" cy="29.1402439" rx="21.5686275" ry="21.5853659"></ellipse>
|
||||
<ellipse id="Oval-2-Copy" stroke="#CFDAE6" opacity="0.4" cx="179.019608" cy="138.146341" rx="23.7254902" ry="23.7439024"></ellipse>
|
||||
<ellipse id="Oval-2" fill="#BACAD9" opacity="0.5" cx="29.1176471" cy="29.1402439" rx="10.7843137" ry="10.7926829"></ellipse>
|
||||
<path d="M29.1176471,39.9329268 L29.1176471,18.347561 C23.1616351,18.347561 18.3333333,23.1796097 18.3333333,29.1402439 C18.3333333,35.1008781 23.1616351,39.9329268 29.1176471,39.9329268 Z" id="Oval-2" fill="#BACAD9"></path>
|
||||
<g id="Group-9" opacity="0.45" transform="translate(172.000000, 131.000000)" fill="#E6A1A6">
|
||||
<ellipse id="Oval-2-Copy-2" cx="7.01960784" cy="7.14634146" rx="6.47058824" ry="6.47560976"></ellipse>
|
||||
<path d="M0.549019608,13.6219512 C4.12262681,13.6219512 7.01960784,10.722722 7.01960784,7.14634146 C7.01960784,3.56996095 4.12262681,0.670731707 0.549019608,0.670731707 L0.549019608,13.6219512 Z" id="Oval-2-Copy-2" transform="translate(3.784314, 7.146341) scale(-1, 1) translate(-3.784314, -7.146341) "></path>
|
||||
</g>
|
||||
<ellipse id="Oval-10" fill="#CFDAE6" cx="218.382353" cy="138.685976" rx="1.61764706" ry="1.61890244"></ellipse>
|
||||
<ellipse id="Oval-10-Copy-2" fill="#E0B4B7" opacity="0.35" cx="179.558824" cy="175.381098" rx="1.61764706" ry="1.61890244"></ellipse>
|
||||
<ellipse id="Oval-10-Copy" fill="#E0B4B7" opacity="0.35" cx="180.098039" cy="102.530488" rx="2.15686275" ry="2.15853659"></ellipse>
|
||||
<path d="M28.9985381,29.9671598 L171.151018,132.876024" id="Path-11" stroke="#CFDAE6" opacity="0.8"></path>
|
||||
</g>
|
||||
<g id="Group-10" opacity="0.799999952" transform="translate(1054.100635, 36.659317) rotate(-11.000000) translate(-1054.100635, -36.659317) translate(1026.600635, 4.659317)">
|
||||
<ellipse id="Oval-7" stroke="#CFDAE6" stroke-width="0.941176471" cx="43.8135593" cy="32" rx="11.1864407" ry="11.2941176"></ellipse>
|
||||
<g id="Group-12" transform="translate(34.596774, 23.111111)" fill="#BACAD9">
|
||||
<ellipse id="Oval-7" opacity="0.45" cx="9.18534718" cy="8.88888889" rx="8.47457627" ry="8.55614973"></ellipse>
|
||||
<path d="M9.18534718,17.4450386 C13.8657264,17.4450386 17.6599235,13.6143199 17.6599235,8.88888889 C17.6599235,4.16345787 13.8657264,0.332739156 9.18534718,0.332739156 L9.18534718,17.4450386 Z" id="Oval-7"></path>
|
||||
</g>
|
||||
<path d="M34.6597385,24.809694 L5.71666084,4.76878945" id="Path-2" stroke="#CFDAE6" stroke-width="0.941176471"></path>
|
||||
<ellipse id="Oval" stroke="#CFDAE6" stroke-width="0.941176471" cx="3.26271186" cy="3.29411765" rx="3.26271186" ry="3.29411765"></ellipse>
|
||||
<ellipse id="Oval-Copy" fill="#F7E1AD" cx="2.79661017" cy="61.1764706" rx="2.79661017" ry="2.82352941"></ellipse>
|
||||
<path d="M34.6312443,39.2922712 L5.06366663,59.785082" id="Path-10" stroke="#CFDAE6" stroke-width="0.941176471"></path>
|
||||
</g>
|
||||
<g id="Group-19" opacity="0.33" transform="translate(1282.537219, 446.502867) rotate(-10.000000) translate(-1282.537219, -446.502867) translate(1142.537219, 327.502867)">
|
||||
<g id="Group-17" transform="translate(141.333539, 104.502742) rotate(275.000000) translate(-141.333539, -104.502742) translate(129.333539, 92.502742)" fill="#BACAD9">
|
||||
<circle id="Oval-4" opacity="0.45" cx="11.6666667" cy="11.6666667" r="11.6666667"></circle>
|
||||
<path d="M23.3333333,23.3333333 C23.3333333,16.8900113 18.1099887,11.6666667 11.6666667,11.6666667 C5.22334459,11.6666667 0,16.8900113 0,23.3333333 L23.3333333,23.3333333 Z" id="Oval-4" transform="translate(11.666667, 17.500000) scale(-1, -1) translate(-11.666667, -17.500000) "></path>
|
||||
</g>
|
||||
<circle id="Oval-5-Copy-6" fill="#CFDAE6" cx="201.833333" cy="87.5" r="5.83333333"></circle>
|
||||
<path d="M143.5,88.8126685 L155.070501,17.6038544" id="Path-17" stroke="#BACAD9" stroke-width="1.16666667"></path>
|
||||
<path d="M17.5,37.3333333 L127.466252,97.6449735" id="Path-18" stroke="#BACAD9" stroke-width="1.16666667"></path>
|
||||
<polyline id="Path-19" stroke="#CFDAE6" stroke-width="1.16666667" points="143.902597 120.302281 174.935455 231.571342 38.5 147.510847 126.366941 110.833333"></polyline>
|
||||
<path d="M159.833333,99.7453842 L195.416667,89.25" id="Path-20" stroke="#E0B4B7" stroke-width="1.16666667" opacity="0.6"></path>
|
||||
<path d="M205.333333,82.1372105 L238.719406,36.1666667" id="Path-24" stroke="#BACAD9" stroke-width="1.16666667"></path>
|
||||
<path d="M266.723424,132.231988 L207.083333,90.4166667" id="Path-25" stroke="#CFDAE6" stroke-width="1.16666667"></path>
|
||||
<circle id="Oval-5" fill="#C1D1E0" cx="156.916667" cy="8.75" r="8.75"></circle>
|
||||
<circle id="Oval-5-Copy-3" fill="#C1D1E0" cx="39.0833333" cy="148.75" r="5.25"></circle>
|
||||
<circle id="Oval-5-Copy-2" fill-opacity="0.6" fill="#D1DEED" cx="8.75" cy="33.25" r="8.75"></circle>
|
||||
<circle id="Oval-5-Copy-4" fill-opacity="0.6" fill="#D1DEED" cx="243.833333" cy="30.3333333" r="5.83333333"></circle>
|
||||
<circle id="Oval-5-Copy-5" fill="#E0B4B7" cx="175.583333" cy="232.75" r="5.25"></circle>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.7 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user