Compare commits

..

194 Commits

Author SHA1 Message Date
758c6c6b5d 7.0.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 17:27:17 +00:00
6363ec4be6 BREAKING CHANGE(SmartAcme (Cert Management)): Refactor certificate management and challenge handling API to use a unified certManager interface, remove legacy storage, and update challenge workflows. 2025-04-30 17:27:17 +00:00
6a53346d14 6.2.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 14:55:03 +00:00
fc420eb615 feat(handlers): Add in-memory HTTP-01 challenge handler and rename file-based handler to Http01Webroot 2025-04-30 14:55:03 +00:00
9f66a0487f 6.1.3
Some checks failed
Default (tags) / security (push) Successful in 36s
Default (tags) / test (push) Failing after 53s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 12:59:20 +00:00
40cae220d0 fix(Dns01Handler): Update dependency versions and refine Dns01Handler implementation 2025-04-30 12:59:20 +00:00
f7dccb25e4 6.1.2
Some checks failed
Default (tags) / security (push) Successful in 22s
Default (tags) / test (push) Failing after 51s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-27 14:51:22 +00:00
da75c52c09 fix(repo): Update repository metadata by replacing the LICENSE file with a license.md file for improved consistency. 2025-04-27 14:51:22 +00:00
708145c550 6.1.1
Some checks failed
Default (tags) / security (push) Successful in 32s
Default (tags) / test (push) Failing after 51s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-27 14:50:28 +00:00
0de2178eb5 fix(readme): Fix license link reference in documentation 2025-04-27 14:50:28 +00:00
5183d88b69 6.1.0
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 50s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-27 14:39:59 +00:00
d5e7e11256 feat(readme): Update documentation with detailed built-in challenge handlers and custom handler examples 2025-04-27 14:39:59 +00:00
916ac9ff8c 6.0.1 2025-04-27 14:30:53 +00:00
b7005f360c fix(readme): Remove extraneous code fence markers from license section in readme 2025-04-27 14:30:53 +00:00
49f5d344a4 6.0.0 2025-04-27 14:28:06 +00:00
58015f0b58 BREAKING CHANGE(SmartAcme): Refactor challenge handling by removing legacy setChallenge/removeChallenge in favor of pluggable challengeHandlers and update documentation and tests accordingly 2025-04-27 14:28:05 +00:00
48018b8955 5.1.0 2025-04-27 13:21:41 +00:00
56a440660b feat(smartacme): Implement exponential backoff retry logic and graceful shutdown handling in SmartAcme; update acme-client dependency to v5.4.0 2025-04-27 13:21:41 +00:00
82bfc20a6d 5.0.1 2025-04-26 12:48:38 +00:00
b84714b208 fix(build): Update CI workflows, bump dependency versions, and refine import and TypeScript configuration 2025-04-26 12:48:38 +00:00
6425e4a93f 5.0.0 2024-06-16 13:56:31 +02:00
55fa1215ae BREAKING CHANGE(structure): renamed classes to avoid confusion 2024-06-16 13:56:30 +02:00
3769468b01 update description 2024-05-29 14:11:35 +02:00
6ea919780c update tsconfig 2024-04-14 17:18:13 +02:00
b5afe8e842 update npmextra.json: githost 2024-04-01 21:33:37 +02:00
942e444d41 update npmextra.json: githost 2024-04-01 19:57:35 +02:00
1ab15c0b72 update npmextra.json: githost 2024-03-30 21:46:32 +01:00
f1db9c1c5d 4.0.8 2024-01-28 16:08:33 +01:00
e3974b3bb1 fix(core): update 2024-01-28 16:08:32 +01:00
016b93ea3a 4.0.7 2024-01-28 02:50:42 +01:00
ab870af0bb fix(core): update 2024-01-28 02:50:41 +01:00
8cda69b3c2 4.0.6 2023-07-21 19:01:26 +02:00
3641d75e2f fix(core): update 2023-07-21 19:01:26 +02:00
fd343c1558 4.0.5 2023-07-21 18:59:18 +02:00
76650ac199 fix(core): update 2023-07-21 18:59:17 +02:00
d9ba5f20b1 4.0.4 2023-07-21 18:49:19 +02:00
941923e90f fix(core): update 2023-07-21 18:49:18 +02:00
e38b4c1215 switch to new org scheme 2023-07-11 00:09:13 +02:00
d405bf63a3 switch to new org scheme 2023-07-10 02:41:58 +02:00
737f5bf5cc 4.0.3 2023-01-06 14:08:18 +01:00
149cdf67bb fix(core): update 2023-01-06 14:08:18 +01:00
c35ff8d711 4.0.2 2022-09-27 19:55:38 +02:00
f2bd9b65aa fix(core): update 2022-09-27 19:55:38 +02:00
018a25ba6a 4.0.1 2022-09-27 15:44:06 +02:00
3c052df1e7 fix(core): update 2022-09-27 15:44:06 +02:00
17c85eb8b9 4.0.0 2022-09-27 15:40:55 +02:00
2bcb31e4d6 BREAKING CHANGE(core): update 2022-09-27 15:40:55 +02:00
70aef3fe7e 3.0.15 2021-01-22 23:43:22 +00:00
734bde4a98 fix(core): update 2021-01-22 23:43:21 +00:00
c7d9a42feb 3.0.14 2021-01-22 23:32:34 +00:00
f20bc72abb fix(core): update 2021-01-22 23:32:34 +00:00
cd2cfce683 3.0.13 2021-01-22 22:59:28 +00:00
44ab180474 fix(core): update 2021-01-22 22:59:27 +00:00
15557dfdd6 3.0.12 2021-01-22 20:31:56 +00:00
488f616d34 fix(core): update 2021-01-22 20:31:55 +00:00
e920406ce9 3.0.11 2021-01-22 18:47:02 +00:00
e044fd81bd fix(core): update 2021-01-22 18:47:01 +00:00
edaccc357d 3.0.10 2021-01-22 18:33:53 +00:00
67f645ad50 fix(core): update 2021-01-22 18:33:53 +00:00
bfeced5f34 3.0.9 2020-11-18 16:52:50 +00:00
24b9794a18 fix(core): update 2020-11-18 16:52:49 +00:00
a781329a47 3.0.8 2020-08-13 03:10:38 +00:00
6b5e0a1207 fix(core): update 2020-08-13 03:10:37 +00:00
2455adfbca 3.0.7 2020-08-12 16:36:06 +00:00
a2cf86b62f fix(core): update 2020-08-12 16:36:06 +00:00
7277906851 3.0.6 2020-05-17 16:21:26 +00:00
9da9ebb01e fix(core): update 2020-05-17 16:21:25 +00:00
f70684b773 3.0.5 2020-02-21 10:48:09 +00:00
8b19b206a4 fix(core): update 2020-02-21 10:48:08 +00:00
6be2866ddd 3.0.4 2020-02-19 19:17:59 +00:00
ab55d3c91a fix(core): update 2020-02-19 19:17:58 +00:00
c7ee7eb774 3.0.3 2020-02-19 18:48:50 +00:00
02daa13a2f fix(core): update 2020-02-19 18:48:49 +00:00
28944b1100 3.0.2 2020-02-10 20:36:02 +00:00
7ec04d6d3d fix(core): update 2020-02-10 20:36:01 +00:00
595d4d8894 3.0.1 2020-02-10 20:16:50 +00:00
04ed28f7d1 fix(core): update 2020-02-10 20:16:49 +00:00
6c95cec709 3.0.0 2020-02-10 20:13:07 +00:00
59173b3ca8 BREAKING CHANGE(core): streamline scope to certificate retrieval using dns challenge 2020-02-10 20:13:06 +00:00
c2036bba90 2.1.2 2020-02-10 11:15:48 +00:00
83afea95e6 fix(core): update 2020-02-10 11:15:47 +00:00
ac515f5e80 2.1.1 2020-01-19 11:09:32 +00:00
6abbf58b83 fix(core): update 2020-01-19 11:09:32 +00:00
9c25ecdc02 2.1.0 2019-02-06 14:37:01 +01:00
81a15da2d0 feat(Cert): now has validity check 2019-02-06 14:37:00 +01:00
86929251ba update 2019-02-06 09:47:33 +01:00
1d8fb2b296 2.0.36 2019-01-18 01:35:00 +01:00
9d5f0d7a5d fix(core): update 2019-01-18 01:34:59 +01:00
82b1d68576 2.0.35 2019-01-17 22:50:22 +01:00
e04b23aceb fix(core): update 2019-01-17 22:50:21 +01:00
8e255938b5 2.0.34 2019-01-17 22:47:58 +01:00
f2eb9666a7 fix(core): update 2019-01-17 22:47:58 +01:00
cbdb0c8b08 2.0.33 2019-01-17 22:13:10 +01:00
f821f4d9cc fix(core): update 2019-01-17 22:13:10 +01:00
6cfcf21d95 2.0.32 2019-01-17 01:15:22 +01:00
a33090bb5e fix(core): update 2019-01-17 01:15:22 +01:00
3151829f85 2.0.31 2019-01-16 22:34:38 +01:00
eca63e588c fix(core): update 2019-01-16 22:34:38 +01:00
9d23e205d8 2.0.30 2019-01-16 02:34:48 +01:00
5ecdf7c9fd fix(core): update 2019-01-16 02:34:47 +01:00
2817a65e21 2.0.29 2019-01-15 23:59:21 +01:00
09a8bc5cb5 fix(core): update 2019-01-15 23:59:21 +01:00
a1134cf227 2.0.28 2019-01-15 23:39:31 +01:00
4ee1c4b08c fix(core): update 2019-01-15 23:39:31 +01:00
08c3eaa65f 2.0.27 2019-01-14 02:46:36 +01:00
2717f08476 fix(core): update 2019-01-14 02:46:36 +01:00
f16dbeea32 2.0.26 2019-01-13 21:40:40 +01:00
a0c0230419 fix(core): update 2019-01-13 21:40:40 +01:00
0d1ebf2d1a 2.0.25 2019-01-13 19:40:32 +01:00
6edbf3cb46 fix(core): update 2019-01-13 19:40:32 +01:00
b26f7ac3e9 2.0.24 2019-01-13 19:15:04 +01:00
5129c5d601 fix(core): update 2019-01-13 19:15:03 +01:00
d09b3fd1bc 2.0.23 2019-01-13 02:11:56 +01:00
14fccd40d8 fix(core): update 2019-01-13 02:11:56 +01:00
c0f45a10e0 2.0.22 2019-01-13 02:10:00 +01:00
f9db3d28fe fix(core): update 2019-01-13 02:10:00 +01:00
c3fd8750b2 2.0.21 2019-01-13 00:50:44 +01:00
2b3c28c7a1 fix(core): update 2019-01-13 00:50:43 +01:00
d6b1f942b3 2.0.20 2019-01-13 00:24:40 +01:00
7eff6ea36a fix(core): update 2019-01-13 00:24:39 +01:00
1ef3615a49 2.0.19 2019-01-13 00:06:00 +01:00
3653cdc797 fix(core): update 2019-01-13 00:06:00 +01:00
c0271648fc 2.0.18 2019-01-12 21:06:29 +01:00
5546fa5f49 fix(core): update 2019-01-12 21:06:29 +01:00
54fe89860e 2.0.17 2019-01-12 19:12:53 +01:00
d1edf75f6f fix(core): update 2019-01-12 19:12:52 +01:00
6f9c644221 2.0.16 2019-01-12 19:11:39 +01:00
0b26054687 fix(core): update 2019-01-12 19:11:39 +01:00
e3323ed4ef 2.0.15 2019-01-12 13:52:21 +01:00
24f692636c fix(core): update 2019-01-12 13:52:21 +01:00
a9f709ee7b 2.0.14 2019-01-12 13:44:18 +01:00
1b11b637a5 fix(core): update 2019-01-12 13:44:18 +01:00
ad54bf41ea 2.0.13 2019-01-09 00:01:02 +01:00
060ebf1b29 fix(core): update 2019-01-09 00:01:01 +01:00
a87c6acb8a 2.0.12 2019-01-08 20:45:36 +01:00
62d27619f4 fix(core): update 2019-01-08 20:45:35 +01:00
0faebf2a79 2.0.11 2019-01-07 12:29:11 +01:00
29ea50796c fix(core): update 2019-01-07 12:29:10 +01:00
26d1b7cbf0 2.0.10 2019-01-07 01:08:50 +01:00
c0c97835ea fix(core): update 2019-01-07 01:08:50 +01:00
d4d50b7dcf 2.0.9 2019-01-07 01:00:58 +01:00
2492fd4de2 fix(core): update 2019-01-07 01:00:58 +01:00
bef54799b6 2.0.8 2019-01-07 00:36:51 +01:00
dbe09f320a fix(core): update 2019-01-07 00:36:51 +01:00
18045dadaf 2.0.7 2019-01-06 23:54:47 +01:00
ee300c3e12 fix(core): update 2019-01-06 23:54:46 +01:00
ed4ba0cb61 2.0.6 2019-01-06 23:30:39 +01:00
a8ab27045d fix(core): update 2019-01-06 23:30:38 +01:00
975c3ed190 2.0.5 2019-01-06 20:41:43 +01:00
a99dea549b fix(core): update 2019-01-06 20:41:42 +01:00
f8b78c433a 2.0.4 2019-01-06 20:41:22 +01:00
6c33111074 fix(core): update 2019-01-06 20:41:21 +01:00
280335f6f6 2.0.3 2019-01-04 23:30:37 +01:00
b90092c043 fix(core): update 2019-01-04 23:30:37 +01:00
9e1c73febf 2.0.2 2018-10-07 21:06:28 +02:00
dcf1915816 2.0.1 2018-10-07 21:05:46 +02:00
748c911168 fix(core): update 2018-10-07 21:05:45 +02:00
3a48cb4ea8 2.0.0 2018-10-07 21:02:18 +02:00
a035c5c0b0 BREAKING CHANGE(scope): change to @pushrocks 2018-10-07 21:02:17 +02:00
f9c521b7b3 1.1.4 2018-08-12 21:45:21 +02:00
19cfe8bdc5 fix(core): update 2018-08-12 21:45:21 +02:00
601d6b30d3 1.1.3 2018-08-12 20:59:56 +02:00
57ffc82c43 1.1.2 2018-08-12 20:59:00 +02:00
312d3c01cd fix(npm publishing): update 2018-08-12 20:58:59 +02:00
8814c1fc62 1.1.1 2018-08-12 01:35:14 +02:00
223a47c997 fix(core): now creating certs all right 2018-08-12 01:35:14 +02:00
651ef6d281 1.1.0 2018-08-12 00:29:02 +02:00
9eda0da9a7 feat(swaitch to acme-v2): switch to letsencrypt v2 2018-08-12 00:29:02 +02:00
3e350dfed5 1.0.11 2017-04-28 19:01:04 +02:00
6fc280e168 add updated ci config 2017-04-28 19:00:56 +02:00
a9efae65d6 1.0.10 2017-04-28 18:59:45 +02:00
0f09bdaf9f update to latest standards 2017-04-28 18:59:43 +02:00
84177cd575 update 2017-04-28 18:56:55 +02:00
7d16ada760 1.0.9 2017-01-27 01:09:48 +01:00
b4de8cc2be basic functionality 2017-01-27 01:09:38 +01:00
68e570c32a 1.0.8 2017-01-25 02:45:52 +01:00
20ea599f9d now getting a valid response 2017-01-25 02:45:48 +01:00
5fa530456b update validation 2017-01-22 21:50:04 +01:00
2cd1794e7e improve README 2017-01-15 23:19:48 +01:00
1f38e12bd3 1.0.7 2017-01-15 23:11:54 +01:00
1c777f6f05 improve README 2017-01-15 23:11:51 +01:00
aad113a8ea add async checkDNS 2017-01-15 22:59:58 +01:00
fff63839d1 1.0.6 2017-01-15 22:30:43 +01:00
c8d2cfd4ce update to new standards 2017-01-15 22:30:33 +01:00
dfd7edd330 now has working requestValidation method 2017-01-15 13:33:55 +01:00
4dadcf227c fix som things 2017-01-15 12:21:29 +01:00
fce25c60ed start better segregation of concerns 2017-01-14 18:36:33 +01:00
98cc70dbfb start with certificate signing process 2017-01-14 14:14:50 +01:00
89d628bd37 1.0.5 2017-01-02 00:18:57 +01:00
0056c8508c now getting certificates 2017-01-02 00:18:51 +01:00
96e0c4f905 can now agree to TOS 2017-01-01 21:20:12 +01:00
2f844dd78d remove test keys 2017-01-01 18:15:48 +01:00
ab82ac0c83 1.0.4 2017-01-01 18:09:48 +01:00
5b925e3d1b add npmextra.json 2017-01-01 18:09:45 +01:00
56 changed files with 12394 additions and 409 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

19
.gitignore vendored
View File

@ -1,4 +1,19 @@
node_modules/
.nogit/
# artifacts
coverage/
public/
pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
#------# custom

View File

@ -1,59 +0,0 @@
image: hosttoday/ht-docker-node:npmts
stages:
- test
- release
- trigger
- pages
testLEGACY:
stage: test
script:
- npmci test legacy
tags:
- docker
allow_failure: true
testLTS:
stage: test
script:
- npmci test lts
tags:
- docker
testSTABLE:
stage: test
script:
- npmci test stable
tags:
- docker
release:
stage: release
script:
- npmci publish
only:
- tags
tags:
- docker
trigger:
stage: trigger
script:
- npmci trigger
only:
- tags
tags:
- docker
pages:
image: hosttoday/ht-docker-node:npmpage
stage: pages
script:
- npmci command npmpage --host gitlab
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public

4
.npmignore Normal file
View File

@ -0,0 +1,4 @@
node_modules/
coverage/
public/
pages/

11
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,24 +0,0 @@
# smartacme
acme implementation in TypeScript
## Availabililty
[![npm](https://push.rocks/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartacme)
[![git](https://push.rocks/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/smartacme)
[![git](https://push.rocks/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartacme)
[![docs](https://push.rocks/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartacme/)
## Status for master
[![build status](https://GitLab.com/pushrocks/smartacme/badges/master/build.svg)](https://GitLab.com/pushrocks/smartacme/commits/master)
[![coverage report](https://GitLab.com/pushrocks/smartacme/badges/master/coverage.svg)](https://GitLab.com/pushrocks/smartacme/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/smartacme.svg)](https://www.npmjs.com/package/smartacme)
[![Dependency Status](https://david-dm.org/pushrocks/smartacme.svg)](https://david-dm.org/pushrocks/smartacme)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartacme/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartacme/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartacme/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartacme)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
[![npm](https://push.rocks/assets/repo-header.svg)](https://push.rocks)

View File

@ -1,27 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAyocFq3vvbiRNCsEcXtsqimIi6UM1OmxiYVQ0NoLvBtpaWk+E
TvNIjmUgh5QQaQfRyRGoWvhskp+E8p6go4GsbRtzx0TvL8uINTcC3SHHo6Qvl599
4QUUPUrioHdh+lX1oj+zIPVUOaL4dl0US1Ebs5vrZVbCfNXSm86vBaPIj6IkWEkj
4S5xGsYlVaQUI8Tvv2fbPziIivbkxS1v/EEMnfk6i5PWgCsnMupYxz58WaVp9xyu
+v/DMPB09mqo4DzchtUNF/b5eOWh3pDJoewYyRVMDDPJoQiTKkJn3kt64EaQuZK2
nUXcihlmaKIx5ayxirsgfvIvxidHnkQcluvciQIDAQABAoIBAQCTPUKz/3B8pMuW
C/syQyhUXzB+YawrA20q0Wr8Toi0dL7HdZP9SgXv8DmMF+suUM8F3V6GdKGKn4qq
UQT8mmPfFtw/fTBfkRs/hPUCC3L214D6PKvpkiW6wdytSN3kf+YKxUDXr0RCeuck
NltwvlDjbXHfxQm0dEefms3HzeEb+jwCyyLVLv+cDly7w7Qqq+67A6mduV/hb53p
92VFm36r7njr+1CYHq+ixV+oyUrEue7yW7w1SjZRkii3AY8Tbvk1f0lVw+XkyYf7
bQvmGSGJh1FmBi7Lytc2hKnqBLTn+iWx3S5pdPhcKTMwC/OD8p+r/DfyqThW/KVa
aaXdoY/5AoGBAO4uAcmHOhR+M/Jnue4srZJ82EkNOQy+zaFlg9KCU9R4qZ59/klH
fp0PkOw3bDFT4/1i12nm4XXqhI9Z7nsKdAoajOYpnifJVEAwQh9MlRBM7Lw+ZS0q
IcH7dvvP1XQ7E2U4C0cWUMcpWNpnmwV67gtqy0KZwk5i+WlFuugQzmhbAoGBANmu
JX6bPKUx0kBJLWhJeAxsk0OoHJ4uGihs1zxT6gl6s+AKQG4db9vU2w99lJ0nR3Aw
MLA4evSMFa5Od96W4KnoiMNHS4c5QiiVKsRSU1losWfwq0jyg406oyTh8rd0eOQn
LDOKP7nDTij8A6l0/t5a2MCu4bLQQXTedPrX+wPrAoGBAM/XO94Fb+xUGLaOR1SM
jkaHRSGyNTdnBP+zGy5GZirBxJo2rgB6MAWUgM1wq6v73bbOWtXiEJqaNGT3gEDE
ZXAvrQZoCMgFSszcj8bKSEW6Ktc1x4p6+oxRCIpC2aycpJcuKcE1uvWgohWsVT2a
AUHbRlXu4P0QJz7zB1/c0pGDAoGAbIvSVpfCXf3CAhx7cA1yt39Mz+f8nUQP9yiP
C54sjh2JpKZ4CnDTXqN9uPO+L79ueBsPrE/9wAQ6q3ilfXFvBkrWJ8pdd0iuHN6F
PPBwb50tGc+BGhcUUlBzGekxxxllTx/ZgrnlnRQu3XENwmp8zRQwEaUjFq+SdFyZ
qJwap5ECgYEA7UGxxRXAjfStTLnsrnr9svvr3QhwnZBg5JAjeR6FKC0cGFzdBrJ5
rV/Zy4mGbTBBVh5oU3MplB3AUHejuFv+8eCik2mJug8k3G8KQAk9mB8oV97k0cp+
bdlu9vlutIoCG9RXxCHdgRVLiLK+OkLv6p7hQOIY7fsIRaAuI+vPKSk=
-----END RSA PRIVATE KEY-----

View File

@ -1,9 +0,0 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyocFq3vvbiRNCsEcXtsq
imIi6UM1OmxiYVQ0NoLvBtpaWk+ETvNIjmUgh5QQaQfRyRGoWvhskp+E8p6go4Gs
bRtzx0TvL8uINTcC3SHHo6Qvl5994QUUPUrioHdh+lX1oj+zIPVUOaL4dl0US1Eb
s5vrZVbCfNXSm86vBaPIj6IkWEkj4S5xGsYlVaQUI8Tvv2fbPziIivbkxS1v/EEM
nfk6i5PWgCsnMupYxz58WaVp9xyu+v/DMPB09mqo4DzchtUNF/b5eOWh3pDJoewY
yRVMDDPJoQiTKkJn3kt64EaQuZK2nUXcihlmaKIx5ayxirsgfvIvxidHnkQcluvc
iQIDAQAB
-----END PUBLIC KEY-----

181
changelog.md Normal file
View File

@ -0,0 +1,181 @@
# Changelog
## 2025-04-30 - 7.0.0 - BREAKING CHANGE(SmartAcme (Cert Management))
Refactor certificate management and challenge handling API to use a unified certManager interface, remove legacy storage, and update challenge workflows.
- Introduce ICertManager interface with MemoryCertManager and MongoCertManager implementations.
- Remove the legacy SmartacmeCertManager and update SmartAcme to require a certManager option instead of mongoDescriptor.
- Adjust certificate renewal logic to delete and store certificates through the new certManager API.
- Refine DNS-01 challenge handling by removing in-handler DNS propagation waiting and relying on external checks.
- Increase retry settings for robustness during challenge verification and certificate issuance.
- Update integration and unit tests to use the new certManager configuration.
## 2025-04-30 - 6.2.0 - feat(handlers)
Add in-memory HTTP-01 challenge handler and rename file-based handler to Http01Webroot
- Renamed Http01Handler to Http01Webroot in both implementation and documentation
- Introduced Http01MemoryHandler for diskless HTTP-01 challenges
- Updated tests and README examples to reflect handler name changes and new feature
## 2025-04-30 - 6.1.3 - fix(Dns01Handler)
Update dependency versions and refine Dns01Handler implementation
- Bump '@apiclient.xyz/cloudflare' to ^6.4.1 and '@tsclass/tsclass' to ^9.1.0 in package.json
- Remove duplicate Cloudflare import in smartacme.plugins.ts
- Refactor Dns01Handler to use IConvenientDnsProvider and add checkWetherDomainIsSupported method
- Align devDependencies versions for improved consistency
## 2025-04-27 - 6.1.2 - fix(repo)
Update repository metadata by replacing the LICENSE file with a license.md file for improved consistency.
- Removed the old LICENSE file.
- Introduced license.md as the new license documentation file.
## 2025-04-27 - 6.1.1 - fix(readme)
Fix license link reference in documentation
- Updated the license link from [license](license) to [license.md](license.md) in the License and Legal Information section
## 2025-04-27 - 6.1.0 - feat(readme)
Update documentation with detailed built-in challenge handlers and custom handler examples
- Expanded readme to include sections on Dns01Handler and Http01Handler usage
- Added examples for creating and registering custom ACME challenge handlers
- Improved clarity of ACME certificate management instructions using SmartAcme
## 2025-04-27 - 6.0.1 - fix(readme)
Remove extraneous code fence markers from license section in readme
- Removed unnecessary triple backticks wrapping the license information
- Improved clarity of the license section in the documentation
## 2025-04-27 - 6.0.0 - BREAKING CHANGE(SmartAcme)
Refactor challenge handling by removing legacy setChallenge/removeChallenge in favor of pluggable challengeHandlers and update documentation and tests accordingly
- Removed legacy challenge methods and introduced new 'challengeHandlers' and 'challengePriority' options
- Updated readme examples to demonstrate usage with DNS-01 (and HTTP-01) handlers
- Refactored internal SmartAcme flow to select and process challenges via the new handler interface
- Adjusted tests (including integration tests) to align with the updated challenge handling mechanism
## 2025-04-27 - 5.1.0 - feat(smartacme)
Implement exponential backoff retry logic and graceful shutdown handling in SmartAcme; update acme-client dependency to v5.4.0
- Added retry helper with exponential backoff for ACME client operations
- Introduced retryOptions in ISmartAcmeOptions for configurable retry parameters
- Enhanced graceful shutdown handling by cleaning up pending DNS challenges on signal
- Updated acme-client dependency from v4.2.5 to v5.4.0
## 2025-04-26 - 5.0.1 - fix(build)
Update CI workflows, bump dependency versions, and refine import and TypeScript configuration
- Changed CI workflow image and npmci package from '@shipzone/npmci' to '@ship.zone/npmci', and updated repository URLs
- Bumped several dependency versions in package.json (e.g. @api.global/typedserver, @push.rocks/lik, @push.rocks/smartdata, @push.rocks/smartdns, @tsclass/tsclass) to newer releases
- Adjusted smartdns import to use the smartdnsClient module for proper module resolution
- Updated tsconfig.json to add emitDecoratorMetadata and baseUrl settings
- Minor markdown and formatting tweaks in readme and gitignore files, and slight improvements in test async handling
## 2024-06-16 - 5.0.0 - No significant changes
This release contains no userfacing changes.
## 2024-06-16 - 4.0.8 - Structure and configuration updates
- BREAKING CHANGE(structure): renamed classes to avoid confusion
- update description
- update tsconfig
- update npmextra.json: githost
## 2024-01-28 - 4.0.74.0.6 - Internal fixes and updates
- A series of releases with routine bug fixes and maintenance updates.
## 2023-07-21 - 4.0.54.0.4 - Internal fixes and updates
- Multiple releases addressing internal issues and maintenance improvements.
## 2023-07-10 - 4.0.3 - Organizational changes
- switch to new org scheme
## 2022-09-27 - 4.0.04.0.2 - Internal fixes and updates
- Routine maintenance and internal bug fixes.
## 2022-09-27 - 3.0.15 - Breaking changes
- BREAKING CHANGE(core): update
## 2021-01-22 - 3.0.93.0.14 - Internal fixes and updates
- A range of releases focused on routine internal updates.
## 2020-11-18 - 3.0.03.0.8 - Internal fixes and updates
- Routine maintenance and internal bug fixes.
## 2020-02-10 - 2.1.2 - Breaking changes
- BREAKING CHANGE(core): streamline scope to certificate retrieval using dns challenge
## 2020-02-10 - 2.1.02.1.1 - Internal fixes and updates
- Routine fixes and updates.
## 2019-02-06 - 2.0.36 - New feature
- feat(Cert): now has validity check
## 2019-01-18 - 2.0.22.0.35 - Internal fixes and updates
- Routine internal updates and maintenance.
## 2018-10-07 - 2.0.02.0.1 - Internal fixes and updates
- Routine internal updates and maintenance.
## 2018-10-07 - 1.1.4 - Breaking changes
- BREAKING CHANGE(scope): change to @pushrocks
## 2018-08-12 - 1.1.1 - NPM publishing fix
- fix(npm publishing): update
## 2018-08-11 - 1.1.0 - Certificate issuance update
- fix(core): now creating certs all right
## 2018-08-11 - 1.0.11 - Feature update
- feat(swaitch to acme-v2): switch to letsencrypt v2
## 2017-04-28 - 1.0.10 - CI improvements
- add updated ci config
## 2017-04-28 - 1.0.9 - Standards update
- update to latest standards
## 2017-01-27 - 1.0.8 - Basic functionality
- basic functionality
## 2017-01-25 - 1.0.7 - Response and validation improvements
- now getting a valid response
- update validation
- improve README
## 2017-01-15 - 1.0.6 - Async and documentation improvements
- improve README
- add async checkDNS
## 2017-01-15 - 1.0.5 - Standards and process updates
- update to new standards
- now has working requestValidation method
- fix som things
- start better segregation of concerns
- start with certificate signing process
## 2017-01-01 - 1.0.4 - Certificate acquisition improvements
- now getting certificates
- can now agree to TOS
- remove test keys
## 2017-01-01 - 1.0.3 - NPM extra configuration
- add npmextra.json
## 2017-01-01 - 1.0.2 - README and integration update
- add better readme
- switch to rawacme for more basic letsencrypt access
## 2016-11-17 - 1.0.1 - Promise fix
- fix promise
## 2016-11-17 - 1.0.0 - Major initial release changes
- remove superflouous key creation
- switch to acme core
- prepare switch to leacmecore
- improve upon keyCreation
- update to use more promises
- add README
- first version

1
dist/index.d.ts vendored
View File

@ -1 +0,0 @@
export * from './smartacme.classes.smartacme';

6
dist/index.js vendored
View File

@ -1,6 +0,0 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require("./smartacme.classes.smartacme"));
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O0FBQUEsbURBQTZDIn0=

View File

@ -1,8 +0,0 @@
import 'typings-global';
export interface IRsaKeypair {
publicKey: string;
privateKey: string;
}
export declare class SmartacmeHelper {
createKeypair(bit?: number): IRsaKeypair;
}

View File

@ -1,14 +0,0 @@
"use strict";
require("typings-global");
let rsaKeygen = require('rsa-keygen');
class SmartacmeHelper {
createKeypair(bit = 2048) {
let result = rsaKeygen.generate(bit);
return {
publicKey: result.public_key,
privateKey: result.private_key
};
}
}
exports.SmartacmeHelper = SmartacmeHelper;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRhY21lLmNsYXNzZXMuaGVscGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRhY21lLmNsYXNzZXMuaGVscGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSwwQkFBdUI7QUFDdkIsSUFBSSxTQUFTLEdBQUcsT0FBTyxDQUFDLFlBQVksQ0FBQyxDQUFBO0FBT3JDO0lBQ0ksYUFBYSxDQUFDLEdBQUcsR0FBRyxJQUFJO1FBQ3BCLElBQUksTUFBTSxHQUFHLFNBQVMsQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLENBQUE7UUFDbkMsTUFBTSxDQUFDO1lBQ0osU0FBUyxFQUFHLE1BQU0sQ0FBQyxVQUFVO1lBQzdCLFVBQVUsRUFBRSxNQUFNLENBQUMsV0FBVztTQUNoQyxDQUFBO0lBQ04sQ0FBQztDQUNKO0FBUkQsMENBUUMifQ==

View File

@ -1,23 +0,0 @@
/// <reference types="q" />
import 'typings-global';
import * as q from 'q';
import { SmartacmeHelper, IRsaKeypair } from './smartacme.classes.helper';
/**
* class SmartAcme exports methods for maintaining SSL Certificates
*/
export declare class SmartAcme {
helper: SmartacmeHelper;
acmeUrl: string;
productionBool: boolean;
keyPair: IRsaKeypair;
JWK: any;
/**
* the constructor for class SmartAcme
*/
constructor(productionArg?: boolean);
/**
* creates an account if not currently present in module
* @executes ASYNC
*/
createAccount(): q.Promise<{}>;
}

View File

@ -1,60 +0,0 @@
"use strict";
require("typings-global");
const q = require("q");
let rsaKeygen = require('rsa-keygen');
let rawacme = require('rawacme');
const smartacme_classes_helper_1 = require("./smartacme.classes.helper");
/**
* class SmartAcme exports methods for maintaining SSL Certificates
*/
class SmartAcme {
/**
* the constructor for class SmartAcme
*/
constructor(productionArg = false) {
this.productionBool = productionArg;
this.helper = new smartacme_classes_helper_1.SmartacmeHelper();
this.keyPair = this.helper.createKeypair();
if (this.productionBool) {
this.acmeUrl = rawacme.LETSENCRYPT_STAGING_URL;
}
else {
this.acmeUrl = rawacme.LETSENCRYPT_URL;
}
}
/**
* creates an account if not currently present in module
* @executes ASYNC
*/
createAccount() {
let done = q.defer();
rawacme.createClient({
url: this.acmeUrl,
publicKey: this.keyPair.publicKey,
privateKey: this.keyPair.privateKey
}, (err, client) => {
if (err) {
console.error('smartacme: something went wrong:');
console.log(err);
done.reject(err);
return;
}
client.newReg({
contact: ['mailto:domains@lossless.org']
}, (err, res) => {
if (err) {
console.error('smartacme: something went wrong:');
console.log(err);
done.reject(err);
return;
}
this.JWK = res.body.key;
console.log(this.JWK);
done.resolve();
});
});
return done.promise;
}
}
exports.SmartAcme = SmartAcme;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRhY21lLmNsYXNzZXMuc21hcnRhY21lLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRhY21lLmNsYXNzZXMuc21hcnRhY21lLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSwwQkFBdUI7QUFDdkIsdUJBQXNCO0FBRXRCLElBQUksU0FBUyxHQUFHLE9BQU8sQ0FBQyxZQUFZLENBQUMsQ0FBQTtBQUdyQyxJQUFJLE9BQU8sR0FBRyxPQUFPLENBQUMsU0FBUyxDQUFDLENBQUE7QUFHaEMseUVBQXlFO0FBRXpFOztHQUVHO0FBQ0g7SUFPSTs7T0FFRztJQUNILFlBQVksZ0JBQXlCLEtBQUs7UUFDdEMsSUFBSSxDQUFDLGNBQWMsR0FBRyxhQUFhLENBQUE7UUFDbkMsSUFBSSxDQUFDLE1BQU0sR0FBRyxJQUFJLDBDQUFlLEVBQUUsQ0FBQTtRQUNuQyxJQUFJLENBQUMsT0FBTyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxFQUFFLENBQUE7UUFDMUMsRUFBRSxDQUFDLENBQUMsSUFBSSxDQUFDLGNBQWMsQ0FBQyxDQUFDLENBQUM7WUFDdEIsSUFBSSxDQUFDLE9BQU8sR0FBRyxPQUFPLENBQUMsdUJBQXVCLENBQUE7UUFDbEQsQ0FBQztRQUFDLElBQUksQ0FBQyxDQUFDO1lBQ0osSUFBSSxDQUFDLE9BQU8sR0FBRyxPQUFPLENBQUMsZUFBZSxDQUFBO1FBQzFDLENBQUM7SUFDTCxDQUFDO0lBRUQ7OztPQUdHO0lBQ0gsYUFBYTtRQUNULElBQUksSUFBSSxHQUFHLENBQUMsQ0FBQyxLQUFLLEVBQUUsQ0FBQTtRQUNwQixPQUFPLENBQUMsWUFBWSxDQUNoQjtZQUNJLEdBQUcsRUFBRSxJQUFJLENBQUMsT0FBTztZQUNqQixTQUFTLEVBQUUsSUFBSSxDQUFDLE9BQU8sQ0FBQyxTQUFTO1lBQ2pDLFVBQVUsRUFBRSxJQUFJLENBQUMsT0FBTyxDQUFDLFVBQVU7U0FDdEMsRUFDRCxDQUFDLEdBQUcsRUFBRSxNQUFNO1lBQ1IsRUFBRSxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQztnQkFDTixPQUFPLENBQUMsS0FBSyxDQUFDLGtDQUFrQyxDQUFDLENBQUE7Z0JBQ2pELE9BQU8sQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUE7Z0JBQ2hCLElBQUksQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLENBQUE7Z0JBQ2hCLE1BQU0sQ0FBQTtZQUNWLENBQUM7WUFFRCxNQUFNLENBQUMsTUFBTSxDQUNUO2dCQUNJLE9BQU8sRUFBRSxDQUFDLDZCQUE2QixDQUFDO2FBQzNDLEVBQ0QsQ0FBQyxHQUFHLEVBQUUsR0FBRztnQkFDTCxFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO29CQUNOLE9BQU8sQ0FBQyxLQUFLLENBQUMsa0NBQWtDLENBQUMsQ0FBQTtvQkFDakQsT0FBTyxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQTtvQkFDaEIsSUFBSSxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQTtvQkFDaEIsTUFBTSxDQUFBO2dCQUNWLENBQUM7Z0JBQ0QsSUFBSSxDQUFDLEdBQUcsR0FBRyxHQUFHLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQTtnQkFDdkIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUE7Z0JBQ3JCLElBQUksQ0FBQyxPQUFPLEVBQUUsQ0FBQTtZQUNsQixDQUFDLENBQUMsQ0FBQTtRQUVWLENBQUMsQ0FDSixDQUFBO1FBQ0QsTUFBTSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUE7SUFDdkIsQ0FBQztDQUNKO0FBN0RELDhCQTZEQyJ9

View File

@ -1,2 +0,0 @@
export declare let packageDir: string;
export declare let assetDir: string;

View File

@ -1,7 +0,0 @@
"use strict";
const path = require("path");
const smartfile = require("smartfile");
exports.packageDir = path.join(__dirname, '../');
exports.assetDir = path.join(exports.packageDir, 'assets/');
smartfile.fs.ensureDirSync(exports.assetDir);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRhY21lLnBhdGhzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRhY21lLnBhdGhzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSw2QkFBNEI7QUFDNUIsdUNBQXNDO0FBRTNCLFFBQUEsVUFBVSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsU0FBUyxFQUFDLEtBQUssQ0FBQyxDQUFBO0FBQ3ZDLFFBQUEsUUFBUSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsa0JBQVUsRUFBQyxTQUFTLENBQUMsQ0FBQTtBQUNyRCxTQUFTLENBQUMsRUFBRSxDQUFDLGFBQWEsQ0FBQyxnQkFBUSxDQUFDLENBQUEifQ==

View File

@ -1,4 +1,4 @@
Copyright (C) 2016, Lossless GmbH
Copyright (C) 2016, Task Venture Capital GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in

38
npmextra.json Normal file
View File

@ -0,0 +1,38 @@
{
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartacme",
"description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
"npmPackagename": "@push.rocks/smartacme",
"license": "MIT",
"projectDomain": "push.rocks",
"keywords": [
"ACME",
"LetsEncrypt",
"TypeScript",
"certificate management",
"DNS challenges",
"SSL/TLS",
"secure communication",
"domain validation",
"automation",
"crypto",
"MongoDB",
"dns-01 challenge",
"token-based challenges",
"certificate renewal",
"wildcard certificates"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

View File

@ -1,39 +1,84 @@
{
"name": "smartacme",
"version": "1.0.3",
"description": "acme implementation in TypeScript",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"name": "@push.rocks/smartacme",
"version": "7.0.0",
"private": false,
"description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(npmts --nodocs)"
"test": "(tstest test/)",
"build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/pushrocks/smartacme.git"
"url": "https://code.foss.global/push.rocks/smartacme.git"
},
"keywords": [
"ACME",
"LetsEncrypt",
"TypeScript",
"acme",
"letsencrypt"
"certificate management",
"DNS challenges",
"SSL/TLS",
"secure communication",
"domain validation",
"automation",
"crypto",
"MongoDB",
"dns-01 challenge",
"token-based challenges",
"certificate renewal",
"wildcard certificates"
],
"author": "Lossless GmbH",
"author": "Task Venture Capital GmbH",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartacme/issues"
"url": "https://code.foss.global/push.rocks/smartacme/issues"
},
"homepage": "https://gitlab.com/pushrocks/smartacme#README",
"homepage": "https://code.foss.global/push.rocks/smartacme#readme",
"dependencies": {
"@types/q": "0.x.x",
"q": "^1.4.1",
"rawacme": "^0.2.1",
"rsa-keygen": "^1.0.6",
"smartfile": "^4.1.0",
"smartstring": "^2.0.20",
"typings-global": "^1.0.14"
"@api.global/typedserver": "^3.0.74",
"@apiclient.xyz/cloudflare": "^6.4.1",
"@push.rocks/lik": "^6.2.2",
"@push.rocks/smartdata": "^5.15.1",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartdns": "^6.2.2",
"@push.rocks/smartlog": "^3.0.7",
"@push.rocks/smartpromise": "^4.2.3",
"@push.rocks/smartrequest": "^2.1.0",
"@push.rocks/smartstring": "^4.0.15",
"@push.rocks/smarttime": "^4.1.1",
"@push.rocks/smartunique": "^3.0.9",
"@tsclass/tsclass": "^9.1.0",
"acme-client": "^5.4.0"
},
"devDependencies": {
"@types/should": "^8.1.30",
"should": "^11.1.1",
"typings-test": "^1.0.3"
"@git.zone/tsbuild": "^2.3.2",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.96",
"@push.rocks/qenv": "^6.1.0",
"@push.rocks/tapbundle": "^6.0.0",
"@types/node": "^22.15.3"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6",
"pnpm": {
"overrides": {}
}
}

10437
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

5
qenv.yml Normal file
View File

@ -0,0 +1,5 @@
required:
- CF_TOKEN
- MONGODB_URL
- MONGODB_PASSWORD
- MONGODB_DATABASE

2
readme.hints.md Normal file
View File

@ -0,0 +1,2 @@
- this repo is dependent on letsencrypt and its limits
- to simpify the outside API, smartacme is stateful, meaning it works with a mongodb and a collection called 'SmartacmeCert'.

338
readme.md Normal file
View File

@ -0,0 +1,338 @@
# @push.rocks/smartacme
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
## Install
To install `@push.rocks/smartacme`, you can use npm or yarn. Run one of the following commands in your project directory:
```bash
npm install @push.rocks/smartacme --save
```
or
```bash
yarn add @push.rocks/smartacme
```
Make sure your project is set up to use TypeScript and supports ECMAScript Modules (ESM).
## Usage
This guide will walk you through using `@push.rocks/smartacme` to set up and manage ACME (Automated Certificate Management Environment) certificates with a focus on the Let's Encrypt service, which provides free SSL certificates. The library provides an easy yet powerful TypeScript interface to automate the process of obtaining, renewing, and installing your SSL certificates.
### Table of Contents
1. [Setting Up Your Project](#setting-up-your-project)
2. [Creating a SmartAcme Instance](#creating-a-smartacme-instance)
3. [Initializing SmartAcme](#initializing-smartacme)
4. [Obtaining a Certificate for a Domain](#obtaining-a-certificate-for-a-domain)
5. [Automating DNS Challenges](#automating-dns-challenges)
6. [Managing Certificates](#managing-certificates)
7. [Environmental Considerations](#environmental-considerations)
8. [Complete Example](#complete-example)
### Setting Up Your Project
Ensure your project includes the necessary TypeScript configuration and dependencies. You'll need to have TypeScript installed and configured for ECMAScript Modules. If you are new to TypeScript, review its [documentation](https://www.typescriptlang.org/docs/) to get started.
### Creating a SmartAcme Instance
Start by importing the `SmartAcme` class and any built-in handlers you plan to use. For example, to use DNS-01 via Cloudflare:
```typescript
import { SmartAcme } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
// Create a Cloudflare account client with your API token
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
// Instantiate SmartAcme with one or more ACME challenge handlers
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
},
environment: 'integration', // 'production' to request real certificates
retryOptions: {}, // optional retry/backoff settings
challengeHandlers: [
new Dns01Handler(cfAccount),
// you can add more handlers, e.g. Http01Webroot
],
challengePriority: ['dns-01'], // optional ordering of challenge types
});
```
### Initializing SmartAcme
Before proceeding to request certificates, start your SmartAcme instance:
```typescript
await smartAcmeInstance.start();
```
### Obtaining a Certificate for a Domain
To obtain a certificate for a specific domain, use the `getCertificateForDomain` method. This function ensures that if a valid certificate is already present, it will be reused; otherwise, a new certificate is obtained:
```typescript
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
```
### Automating DNS Challenges
SmartAcme uses pluggable ACME challenge handlers (see built-in handlers below) to automate domain validation. You configure handlers via the `challengeHandlers` array when creating the instance, and SmartAcme will invoke each handlers `prepare`, optional `verify`, and `cleanup` methods during the ACME order flow.
### Managing Certificates
The library automatically handles fetching, renewing, and storing your certificates in a MongoDB database specified in your configuration. Ensure your MongoDB instance is accessible and properly configured for use with SmartAcme.
```typescript
const mongoDescriptor = {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
};
```
### Environmental Considerations
When creating an instance of `SmartAcme`, you can specify an `environment` option. This is particularly useful for testing, as you can use the `integration` environment to avoid hitting rate limits and for testing your setup without issuing real certificates. Switch to `production` when you are ready to obtain actual certificates.
### Complete Example
Below is a complete example demonstrating how to use `@push.rocks/smartacme` to obtain and manage an ACME certificate with Let's Encrypt using a DNS-01 handler:
```typescript
import { SmartAcme } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Qenv } from '@push.rocks/qenv';
const qenv = new Qenv('./', './.nogit/');
const cloudflareAccount = new cloudflare.CloudflareAccount(qenv.getEnvVarOnDemand('CF_TOKEN'));
async function main() {
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
},
environment: 'integration',
challengeHandlers: [ new Dns01Handler(cloudflareAccount) ],
});
await smartAcmeInstance.start();
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
await smartAcmeInstance.stop();
}
main().catch(console.error);
```
## Built-in Challenge Handlers
This module includes three out-of-the-box ACME challenge handlers:
- **Dns01Handler**
- Uses a Cloudflare account (from `@apiclient.xyz/cloudflare`) and Smartdns client to set and remove DNS TXT records, then wait for propagation.
- Import path:
```typescript
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
```
- Example:
```typescript
import * as cloudflare from '@apiclient.xyz/cloudflare';
const cfAccount = new cloudflare.CloudflareAccount('CF_TOKEN');
const dnsHandler = new Dns01Handler(cfAccount);
```
- **Http01Webroot**
- Writes ACME HTTP-01 challenge files under a file-system webroot (`/.well-known/acme-challenge/`), and removes them on cleanup.
- Import path:
```typescript
import { Http01Webroot } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
```
- Example:
```typescript
const httpHandler = new Http01Webroot({ webroot: '/var/www/html' });
```
- **Http01MemoryHandler**
- In-memory HTTP-01 challenge handler that stores and serves ACME tokens without disk I/O.
- Import path:
```typescript
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
```
- Example (Express integration):
```typescript
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
const memoryHandler = new Http01MemoryHandler();
app.use((req, res, next) => memoryHandler.handleRequest(req, res, next));
```
All handlers implement the `IChallengeHandler<T>` interface and can be combined in the `challengeHandlers` array.
## Creating Custom Handlers
To support additional challenge types or custom validation flows, implement the `IChallengeHandler<T>` interface:
```typescript
import type { IChallengeHandler } from '@push.rocks/smartacme/ts/handlers/IChallengeHandler.js';
// Define your custom challenge payload type
interface MyChallenge { type: string; /* ... */ }
class MyCustomHandler implements IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] {
return ['my-01'];
}
// Prepare the challenge (set DNS records, start servers, etc.)
async prepare(ch: MyChallenge): Promise<void> {
// preparation logic
}
// Optional verify step after prepare
async verify?(ch: MyChallenge): Promise<void> {
// verification logic
}
// Cleanup after challenge (remove records, stop servers)
async cleanup(ch: MyChallenge): Promise<void> {
// cleanup logic
}
}
// Then register your handler:
const customInstance = new SmartAcme({
/* other options */,
challengeHandlers: [ new MyCustomHandler() ],
challengePriority: ['my-01'],
});
In this example, `Qenv` is used to manage environment variables, and `cloudflare` library is used to handle DNS challenges required by Let's Encrypt ACME protocol. The `setChallenge` and `removeChallenge` methods are essential for automating the DNS challenge process, which is a key part of domain validation.
## Additional Details
### Certificate Object
The certificate object obtained from the `getCertificateForDomain` method has the following properties:
- `id`: Unique identifier for the certificate.
- `domainName`: The domain name for which the certificate is issued.
- `created`: Timestamp of when the certificate was created.
- `privateKey`: The private key associated with the certificate.
- `publicKey`: The public key or certificate itself.
- `csr`: Certificate Signing Request (CSR) used to obtain the certificate.
- `validUntil`: Timestamp indicating the expiration date of the certificate.
### Methods Summary
- **start()**: Initializes the SmartAcme instance, sets up the ACME client, and registers the account with Let's Encrypt.
- **stop()**: Closes the MongoDB connection and performs any necessary cleanup.
- **getCertificateForDomain(domainArg: string)**: Retrieves or obtains a certificate for the specified domain name. If a valid certificate exists in the database, it is returned. Otherwise, a new certificate is requested and stored.
- **setChallenge(dnsChallenge: any)**: Automates the process of setting DNS challenge records.
- **removeChallenge(dnsChallenge: any)**: Automates the process of removing DNS challenge records.
### Handling Domain Matching
The `SmartacmeCertMatcher` class is responsible for matching certificates with the broadest scope for wildcard certificates. The `getCertificateDomainNameByDomainName` method ensures that domains at various levels are correctly matched.
```typescript
import { SmartacmeCertMatcher } from '@push.rocks/smartacme';
const certMatcher = new SmartacmeCertMatcher();
const certDomainName = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
console.log('Certificate Domain Name:', certDomainName); // Output: example.com
```
### Testing
Automated tests can be added to ensure that the setup and functions work as expected. Using a testing framework such as `tap` and mock services for DNS providers (e.g., Cloudflare), you can simulate the process of obtaining and managing certificates without the need for actual domain ownership.
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { Qenv } from '@push.rocks/qenv';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import * as smartacme from '@push.rocks/smartacme';
const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN'));
let smartAcmeInstance: smartacme.SmartAcme;
tap.test('should create a valid instance of SmartAcme', async () => {
smartAcmeInstance = new smartacme.SmartAcme({
accountEmail: 'domains@lossless.org',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
setChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
removeChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
environment: 'integration',
});
await smartAcmeInstance.init();
expect(smartAcmeInstance).toBeInstanceOf(smartacme.SmartAcme);
});
tap.test('should get a domain certificate', async () => {
const certificate = await smartAcmeInstance.getCertificateForDomain('example.com');
console.log('Certificate:', certificate);
expect(certificate).toHaveProperty('domainName', 'example.com');
});
tap.test('certmatcher should correctly match domains', async () => {
const certMatcher = new smartacme.SmartacmeCertMatcher();
const matchedCert = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
expect(matchedCert).toBe('example.com');
});
tap.test('should stop correctly', async () => {
await smartAcmeInstance.stop();
expect(smartAcmeInstance).toHaveProperty('client', null);
});
tap.start();
```
This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using `@push.rocks/smartacme`.
---
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license.md](license.md) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

44
readme.plan.md Normal file
View File

@ -0,0 +1,44 @@
# Plan: Diskless HTTP-01 Handler and Renaming Existing Handler
This plan outlines steps to rename the existing filesystem-based HTTP-01 handler to `Http01Webroot`
and introduce a new diskless (in-memory) HTTP-01 handler for integration with arbitrary HTTP servers
(e.g., Express).
## 1. Rename existing handler to Http01Webroot
- In `ts/handlers/Http01Handler.ts`:
- Rename `Http01HandlerOptions` to `Http01WebrootOptions`.
- Rename class `Http01Handler` to `Http01Webroot`.
- Remove the legacy alias; rename the handler directly.
- In `ts/handlers/index.ts`:
- Export `Http01Webroot` under its new name.
- Remove any `Http01Handler` export.
- Update existing tests (e.g., `test.handlers-http01.ts`) to import `Http01Webroot` instead of `Http01Handler`.
## 2. Add new diskless (in-memory) HTTP-01 handler
- Create `ts/handlers/Http01MemoryHandler.ts`:
- Implement `IChallengeHandler<{ token: string; keyAuthorization: string; webPath: string }>`, storing challenges in a private `Map<string, string>`.
- `prepare()`: add token→keyAuthorization mapping.
- `verify()`: no-op.
- `cleanup()`: remove mapping.
- Add `handleRequest(req, res, next?)` method:
- Parse `/.well-known/acme-challenge/:token` from `req.url`.
- If token exists, respond with the key authorization and status 200.
- If missing and `next` provided, call `next()`, otherwise respond 404.
- Export `Http01MemoryHandler` in `ts/handlers/index.ts`.
## 3. Write tests for Http01MemoryHandler
- Create `test/test.handlers-http01-memory.ts`:
- Use `tap` and `expect` to:
1. `prepare()` a challenge.
2. Invoke `handleRequest()` with a fake `req`/`res` to confirm 200 and correct body.
3. `cleanup()` the challenge.
4. Confirm `handleRequest()` now yields 404.
## 4. Update documentation
- Add examples in `readme.md` showing how to use both `Http01Webroot` and the new `Http01MemoryHandler`:
- Sample code for Express integration using `handleRequest`.
## 5. Build and test
- Run `pnpm build` and `pnpm test`, ensuring existing tests are updated for `Http01Webroot` and new tests pass.
Please review and let me know if this plan makes sense before proceeding with implementation.

21
test/test.certmatcher.ts Normal file
View File

@ -0,0 +1,21 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { SmartacmeCertMatcher } from '../ts/smartacme.classes.certmatcher.js';
tap.test('should match 2-level domain', async () => {
const matcher = new SmartacmeCertMatcher();
expect(matcher.getCertificateDomainNameByDomainName('example.com')).toEqual('example.com');
});
tap.test('should match 3-level domain', async () => {
const matcher = new SmartacmeCertMatcher();
expect(matcher.getCertificateDomainNameByDomainName('subdomain.example.com')).toEqual('example.com');
});
tap.test('should return undefined for deeper domain', async () => {
const matcher = new SmartacmeCertMatcher();
// domain with 4 or more levels
const result = matcher.getCertificateDomainNameByDomainName('a.b.example.com');
expect(result).toEqual(undefined);
});
export default tap.start();

1
test/test.d.ts vendored
View File

@ -1 +0,0 @@
import 'typings-test';

View File

@ -0,0 +1,34 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
tap.test('Dns01Handler prepare and cleanup calls Cloudflare and DNS functions', async () => {
let setCalled = false;
let removeCalled = false;
// fake Cloudflare API
const fakeCF: any = {
convenience: {
acmeSetDnsChallenge: async (_ch: any) => {
setCalled = true;
},
acmeRemoveDnsChallenge: async (_ch: any) => {
removeCalled = true;
},
},
};
// fake DNS checker
const fakeDNS: any = {
checkUntilAvailable: async (host: string, rr: string, val: string, count: number, interval: number) => {
expect(host).toEqual('test.host');
expect(rr).toEqual('TXT');
expect(val).toEqual('token');
},
};
const handler = new Dns01Handler(fakeCF, fakeDNS);
const input = { hostName: 'test.host', challenge: 'token' };
await handler.prepare(input);
expect(setCalled).toEqual(true);
await handler.cleanup(input);
expect(removeCalled).toEqual(true);
});
export default tap.start();

View File

@ -0,0 +1,58 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { Http01MemoryHandler } from '../ts/handlers/Http01MemoryHandler.js';
tap.test('Http01MemoryHandler serves in-memory challenges and cleans up', async () => {
const handler = new Http01MemoryHandler();
const token = 'testtoken';
const keyAuth = 'keyAuthValue';
const webPath = `/.well-known/acme-challenge/${token}`;
const challenge = { type: 'http-01', token, keyAuthorization: keyAuth, webPath };
// Prepare challenge (store in memory)
await handler.prepare(challenge);
// Serve existing challenge without next()
const req1: any = { url: webPath };
const res1: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req1, res1);
expect(res1.statusCode).toEqual(200);
expect(res1.body).toEqual(keyAuth);
expect(res1.headers['content-type']).toEqual('text/plain');
// Cleanup challenge (remove from memory)
await handler.cleanup(challenge);
// Serve after cleanup without next() should give 404
const req2: any = { url: webPath };
const res2: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req2, res2);
expect(res2.statusCode).toEqual(404);
// Serve after cleanup with next() should call next
const req3: any = { url: webPath };
let nextCalled = false;
const next = () => { nextCalled = true; };
const res3: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req3, res3, next);
expect(nextCalled).toEqual(true);
});
export default tap.start();

View File

@ -0,0 +1,26 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { Http01Webroot } from '../ts/handlers/Http01Handler.js';
import { promises as fs } from 'fs';
import * as path from 'path';
import os from 'os';
tap.test('Http01Webroot writes challenge file and removes it on cleanup', async () => {
// create temporary webroot directory
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'http01-'));
const handler = new Http01Webroot({ webroot: tmpDir });
const token = 'testtoken';
const keyAuth = 'keyAuthValue';
const webPath = `/.well-known/acme-challenge/${token}`;
const input = { type: 'http-01', token, keyAuthorization: keyAuth, webPath };
// prepare should write the file
await handler.prepare(input);
const filePath = path.join(tmpDir, webPath);
const content = await fs.readFile(filePath, 'utf8');
expect(content).toEqual(keyAuth);
// cleanup should remove the file
await handler.cleanup(input);
const exists = await fs.stat(filePath).then(() => true).catch(() => false);
expect(exists).toEqual(false);
});
export default tap.start();

View File

@ -1,26 +0,0 @@
"use strict";
require("typings-test");
const should = require("should");
// import the module to test
const smartacme = require("../dist/index");
describe('smartacme', function () {
let testAcme;
it('should create a valid instance', function () {
this.timeout(10000);
testAcme = new smartacme.SmartAcme();
should(testAcme).be.instanceOf(smartacme.SmartAcme);
});
it('should have created keyPair', function () {
should(testAcme.acmeUrl).be.of.type('string');
});
it('should register a new account', function (done) {
this.timeout(40000);
testAcme.createAccount().then(x => {
done();
}).catch(err => {
console.log(err);
done(err);
});
});
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLHdCQUFxQjtBQUNyQixpQ0FBZ0M7QUFFaEMsNEJBQTRCO0FBQzVCLDJDQUEwQztBQUUxQyxRQUFRLENBQUMsV0FBVyxFQUFFO0lBQ2xCLElBQUksUUFBNkIsQ0FBQTtJQUNqQyxFQUFFLENBQUMsZ0NBQWdDLEVBQUU7UUFDakMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxLQUFLLENBQUMsQ0FBQTtRQUNuQixRQUFRLEdBQUcsSUFBSSxTQUFTLENBQUMsU0FBUyxFQUFFLENBQUE7UUFDcEMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxVQUFVLENBQUMsU0FBUyxDQUFDLFNBQVMsQ0FBQyxDQUFBO0lBQ3ZELENBQUMsQ0FBQyxDQUFBO0lBQ0YsRUFBRSxDQUFDLDZCQUE2QixFQUFFO1FBQzlCLE1BQU0sQ0FBQyxRQUFRLENBQUMsT0FBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUE7SUFDakQsQ0FBQyxDQUFDLENBQUE7SUFDRixFQUFFLENBQUMsK0JBQStCLEVBQUUsVUFBVSxJQUFJO1FBQzlDLElBQUksQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLENBQUE7UUFDbkIsUUFBUSxDQUFDLGFBQWEsRUFBRSxDQUFDLElBQUksQ0FBQyxDQUFDO1lBQzNCLElBQUksRUFBRSxDQUFBO1FBQ1YsQ0FBQyxDQUFDLENBQUMsS0FBSyxDQUFDLEdBQUc7WUFDUixPQUFPLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFBO1lBQ2hCLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQTtRQUNiLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQyxDQUFDLENBQUE7QUFDTixDQUFDLENBQUMsQ0FBQSJ9

View File

@ -0,0 +1,47 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { Qenv } from '@push.rocks/qenv';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { SmartAcme, MongoCertManager } from '../ts/index.js';
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
// Load environment variables for credentials (stored under .nogit/)
const testQenv = new Qenv('./', './.nogit/');
// Cloudflare API token for DNS-01 challenge (must be set in .nogit/ or env)
const cfToken = (await testQenv.getEnvVarOnDemand('CF_TOKEN'))!;
const cfAccount = new cloudflare.CloudflareAccount(cfToken);
// MongoDB connection settings for certificate storage (must be set in .nogit/ or env)
const mongoDbName = (await testQenv.getEnvVarOnDemand('MONGODB_DATABASE'))!;
const mongoDbPass = (await testQenv.getEnvVarOnDemand('MONGODB_PASSWORD'))!;
const mongoDbUrl = (await testQenv.getEnvVarOnDemand('MONGODB_URL'))!;
let smartAcmeInstance: SmartAcme;
tap.test('create SmartAcme instance with DNS-01 handler and start', async () => {
smartAcmeInstance = new SmartAcme({
accountEmail: 'domains@lossless.org',
certManager: new MongoCertManager({ mongoDbName, mongoDbPass, mongoDbUrl }),
environment: 'integration',
retryOptions: {},
challengeHandlers: [new Dns01Handler(cfAccount)],
challengePriority: ['dns-01'],
});
await smartAcmeInstance.start();
expect(smartAcmeInstance).toBeInstanceOf(SmartAcme);
});
tap.test('get a domain certificate via DNS-01 challenge', async () => {
// Replace 'bleu.de' with your test domain if different
const domain = 'bleu.de';
const cert = await smartAcmeInstance.getCertificateForDomain(domain);
expect(cert).toHaveProperty('domainName');
expect(cert).toEqual(domain);
expect(cert).toHaveProperty('publicKey');
expect(typeof cert.publicKey).toEqual('string');
expect(cert.publicKey.length).toBeGreaterThan(0);
});
tap.test('stop SmartAcme instance', async () => {
await smartAcmeInstance.stop();
});
export default tap.start();

32
test/test.smartacme.ts Normal file
View File

@ -0,0 +1,32 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { SmartAcme, MemoryCertManager } from '../ts/index.js';
import type { IChallengeHandler } from '../ts/handlers/IChallengeHandler.js';
// Dummy handler for testing
class DummyHandler implements IChallengeHandler<any> {
getSupportedTypes(): string[] { return ['dns-01']; }
async prepare(_: any): Promise<void> { /* no-op */ }
async cleanup(_: any): Promise<void> { /* no-op */ }
}
tap.test('constructor throws without challengeHandlers', async () => {
expect(() => new SmartAcme({
accountEmail: 'test@example.com',
certManager: new MemoryCertManager(),
environment: 'integration',
retryOptions: {},
} as any)).toThrow();
});
tap.test('constructor accepts valid challengeHandlers', async () => {
const sa = new SmartAcme({
accountEmail: 'test@example.com',
certManager: new MemoryCertManager(),
environment: 'integration',
retryOptions: {},
challengeHandlers: [new DummyHandler()],
});
expect(sa).toBeInstanceOf(SmartAcme);
});
export default tap.start();

View File

@ -1,26 +0,0 @@
import 'typings-test'
import * as should from 'should'
// import the module to test
import * as smartacme from '../dist/index'
describe('smartacme', function () {
let testAcme: smartacme.SmartAcme
it('should create a valid instance', function () {
this.timeout(10000)
testAcme = new smartacme.SmartAcme()
should(testAcme).be.instanceOf(smartacme.SmartAcme)
})
it('should have created keyPair', function () {
should(testAcme.acmeUrl).be.of.type('string')
})
it('should register a new account', function (done) {
this.timeout(40000)
testAcme.createAccount().then(x => {
done()
}).catch(err => {
console.log(err)
done(err)
})
})
})

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartacme',
version: '7.0.0',
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
}

90
ts/certmanagers.ts Normal file
View File

@ -0,0 +1,90 @@
import * as plugins from './smartacme.plugins.js';
import type { ICertManager } from './interfaces/certmanager.js';
import { SmartacmeCert } from './smartacme.classes.cert.js';
/**
* In-memory certificate manager for mongoless mode.
* Stores certificates in memory only and does not connect to MongoDB.
*/
export class MemoryCertManager implements ICertManager {
public interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
private certs: Map<string, SmartacmeCert> = new Map();
constructor() {
this.interestMap = new plugins.lik.InterestMap((domain) => domain);
}
public async init(): Promise<void> {
// no-op for in-memory store
}
public async retrieveCertificate(domainName: string): Promise<SmartacmeCert | null> {
return this.certs.get(domainName) ?? null;
}
public async storeCertificate(cert: SmartacmeCert): Promise<void> {
this.certs.set(cert.domainName, cert);
const interest = this.interestMap.findInterest(cert.domainName);
if (interest) {
interest.fullfillInterest(cert);
interest.markLost();
}
}
public async deleteCertificate(domainName: string): Promise<void> {
this.certs.delete(domainName);
}
public async close(): Promise<void> {
// no-op
}
}
/**
* MongoDB-backed certificate manager using EasyStore from smartdata.
*/
export class MongoCertManager implements ICertManager {
public interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
private db: plugins.smartdata.SmartdataDb;
private store: plugins.smartdata.EasyStore<Record<string, any>>;
/**
* @param mongoDescriptor MongoDB connection settings
*/
constructor(mongoDescriptor: plugins.smartdata.IMongoDescriptor) {
this.db = new plugins.smartdata.SmartdataDb(mongoDescriptor);
// Use a single EasyStore document to hold all certs keyed by domainName
this.store = new plugins.smartdata.EasyStore<Record<string, any>>(
'smartacme-certs',
this.db,
);
this.interestMap = new plugins.lik.InterestMap((domain) => domain);
}
public async init(): Promise<void> {
await this.db.init();
}
public async retrieveCertificate(domainName: string): Promise<SmartacmeCert | null> {
const data = await this.store.readKey(domainName);
return data ? new SmartacmeCert(data) : null;
}
public async storeCertificate(cert: SmartacmeCert): Promise<void> {
// write plain object for persistence
await this.store.writeKey(cert.domainName, { ...cert });
const interest = this.interestMap.findInterest(cert.domainName);
if (interest) {
interest.fullfillInterest(cert);
interest.markLost();
}
}
public async deleteCertificate(domainName: string): Promise<void> {
await this.store.deleteKey(domainName);
}
public async close(): Promise<void> {
await this.db.close();
}
}

View File

@ -0,0 +1,36 @@
import * as plugins from '../smartacme.plugins.js';
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* DNS-01 challenge handler using CloudflareAccount and Smartdns.
*/
export class Dns01Handler implements IChallengeHandler<plugins.tsclass.network.IDnsChallenge> {
private cf: plugins.tsclass.network.IConvenientDnsProvider;
private smartdns: plugins.smartdnsClient.Smartdns;
constructor(
convenientDnsProvider: plugins.tsclass.network.IConvenientDnsProvider,
smartdnsInstance?: plugins.smartdnsClient.Smartdns,
) {
this.cf = convenientDnsProvider;
this.smartdns = smartdnsInstance ?? new plugins.smartdnsClient.Smartdns({});
}
public getSupportedTypes(): string[] {
return ['dns-01'];
}
public async prepare(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
// set DNS TXT record
await this.cf.convenience.acmeSetDnsChallenge(ch);
}
public async cleanup(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
// remove DNS TXT record
await this.cf.convenience.acmeRemoveDnsChallenge(ch);
}
public async checkWetherDomainIsSupported(domainArg: string): Promise<boolean> {
return this.cf.convenience.isDomainSupported(domainArg);
}
}

View File

@ -0,0 +1,54 @@
import { promises as fs } from 'fs';
import * as path from 'path';
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* HTTP-01 ACME challenge handler using file-system webroot.
* Writes and removes the challenge file under <webroot>/.well-known/acme-challenge/.
*/
export interface Http01WebrootOptions {
/**
* Directory that serves HTTP requests for /.well-known/acme-challenge
*/
webroot: string;
}
export class Http01Webroot implements IChallengeHandler<{
type: string;
token: string;
keyAuthorization: string;
webPath: string;
}> {
private webroot: string;
constructor(options: Http01WebrootOptions) {
this.webroot = options.webroot;
}
public getSupportedTypes(): string[] {
return ['http-01'];
}
public async prepare(ch: { token: string; keyAuthorization: string; webPath: string }): Promise<void> {
const relWebPath = ch.webPath.replace(/^\/+/, '');
const filePath = path.join(this.webroot, relWebPath);
const dir = path.dirname(filePath);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(filePath, ch.keyAuthorization, 'utf8');
}
public async verify(ch: { webPath: string; keyAuthorization: string }): Promise<void> {
// Optional: implement HTTP polling if desired
return;
}
public async cleanup(ch: { token: string; webPath: string }): Promise<void> {
const relWebPath = ch.webPath.replace(/^\/+/, '');
const filePath = path.join(this.webroot, relWebPath);
try {
await fs.unlink(filePath);
} catch {
// ignore missing file
}
}
}

View File

@ -0,0 +1,67 @@
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* HTTP-01 ACME challenge handler using in-memory storage.
* Stores challenge tokens and key authorizations in memory
* and serves them via handleRequest for arbitrary HTTP servers.
*/
export interface Http01MemoryHandlerChallenge {
type: string;
token: string;
keyAuthorization: string;
webPath: string;
}
export class Http01MemoryHandler implements IChallengeHandler<Http01MemoryHandlerChallenge> {
private store: Map<string, string> = new Map();
public getSupportedTypes(): string[] {
return ['http-01'];
}
public async prepare(ch: Http01MemoryHandlerChallenge): Promise<void> {
this.store.set(ch.token, ch.keyAuthorization);
}
public async verify(_ch: Http01MemoryHandlerChallenge): Promise<void> {
// No-op
return;
}
public async cleanup(ch: Http01MemoryHandlerChallenge): Promise<void> {
this.store.delete(ch.token);
}
/**
* HTTP request handler for serving ACME HTTP-01 challenges.
* @param req HTTP request object (should have url property)
* @param res HTTP response object
* @param next Optional next() callback for Express-style fallthrough
*/
public handleRequest(req: any, res: any, next?: () => void): void {
const url = req.url || '';
const prefix = '/.well-known/acme-challenge/';
if (!url.startsWith(prefix)) {
if (next) {
return next();
}
res.statusCode = 404;
return res.end();
}
const token = url.slice(prefix.length);
const keyAuth = this.store.get(token);
if (keyAuth !== undefined) {
if (typeof res.status === 'function' && typeof res.send === 'function') {
return res.status(200).send(keyAuth);
}
res.statusCode = 200;
res.setHeader('content-type', 'text/plain');
return res.end(keyAuth);
}
if (next) {
return next();
}
res.statusCode = 404;
return res.end();
}
}

View File

@ -0,0 +1,22 @@
/**
* Pluggable interface for ACME challenge handlers.
* Supports DNS-01, HTTP-01, TLS-ALPN-01, or custom challenge types.
*/
export interface IChallengeHandler<T> {
/**
* ACME challenge types this handler supports (e.g. ['dns-01']).
*/
getSupportedTypes(): string[];
/**
* Prepare the challenge: set DNS record, start HTTP/TLS server, etc.
*/
prepare(ch: T): Promise<void>;
/**
* Optional extra verify step (HTTP GET, ALPN handshake).
*/
verify?(ch: T): Promise<void>;
/**
* Clean up resources: remove DNS record, stop server.
*/
cleanup(ch: T): Promise<void>;
}

5
ts/handlers/index.ts Normal file
View File

@ -0,0 +1,5 @@
export type { IChallengeHandler } from './IChallengeHandler.js';
// Removed legacy handler adapter
export { Dns01Handler } from './Dns01Handler.js';
export { Http01Webroot } from './Http01Handler.js';
export { Http01MemoryHandler } from './Http01MemoryHandler.js';

View File

@ -1 +1,4 @@
export * from './smartacme.classes.smartacme'
export * from './smartacme.classes.smartacme.js';
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';
export type { ICertManager } from './interfaces/certmanager.js';
export { MemoryCertManager, MongoCertManager } from './certmanagers.js';

View File

@ -0,0 +1,8 @@
export interface IAccountData {
id: number;
key: { kty: 'RSA'; n: string; e: string; kid: string };
contact: string[];
initialIp: string;
createdAt: string;
status: string;
}

View File

@ -0,0 +1,37 @@
import type { InterestMap } from '@push.rocks/lik';
import type { SmartacmeCert } from '../smartacme.classes.cert.js';
// (ICertRecord removed; use SmartacmeCert directly)
/**
* Interface for certificate storage managers.
* Users can implement this to provide custom persistence (in-memory,
* file-based, Redis, etc.).
*/
export interface ICertManager {
/**
* Map for coordinating concurrent certificate requests.
*/
interestMap: InterestMap<string, SmartacmeCert>;
/**
* Initialize the store (e.g., connect to database).
*/
init(): Promise<void>;
/**
* Retrieve a certificate record by domain name.
* Returns null if none found.
*/
retrieveCertificate(domainName: string): Promise<SmartacmeCert | null>;
/**
* Store a certificate record. Fulfills any pending interests.
*/
storeCertificate(cert: SmartacmeCert): Promise<void>;
/**
* Delete a certificate record by domain name.
*/
deleteCertificate(domainName: string): Promise<void>;
/**
* Close the store (e.g., disconnect database).
*/
close(): Promise<void>;
}

1
ts/interfaces/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './accountdata.js';

View File

@ -0,0 +1,39 @@
import * as plugins from './smartacme.plugins.js';
/**
* Plain certificate record.
*/
export class SmartacmeCert {
public id: string;
public domainName: string;
public created: number;
public privateKey: string;
public publicKey: string;
public csr: string;
public validUntil: number;
constructor(data: Partial<SmartacmeCert> = {}) {
this.id = data.id || '';
this.domainName = data.domainName || '';
this.created = data.created || Date.now();
this.privateKey = data.privateKey || '';
this.publicKey = data.publicKey || '';
this.csr = data.csr || '';
this.validUntil = data.validUntil || 0;
}
/**
* Check if certificate is still valid.
*/
public isStillValid(): boolean {
return this.validUntil >= Date.now();
}
/**
* Check if certificate needs renewal (e.g., expires in <10 days).
*/
public shouldBeRenewed(): boolean {
const threshold = Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 10 });
return this.validUntil < threshold;
}
}

View File

@ -0,0 +1,19 @@
import * as plugins from './smartacme.plugins.js';
import * as interfaces from './interfaces/index.js';
/**
* certmatcher is responsible for matching certificates
*/
export class SmartacmeCertMatcher {
/**
* creates a domainName for the certificate that will include the broadest scope
* for wild card certificates
* @param domainNameArg the domainNameArg to create the scope from
*/
public getCertificateDomainNameByDomainName(domainNameArg: string): string {
const originalDomain = new plugins.smartstring.Domain(domainNameArg);
if (!originalDomain.level4) {
return `${originalDomain.level2}.${originalDomain.level1}`;
}
}
}

View File

@ -1,17 +0,0 @@
import 'typings-global'
let rsaKeygen = require('rsa-keygen')
export interface IRsaKeypair {
publicKey: string
privateKey: string
}
export class SmartacmeHelper {
createKeypair(bit = 2048): IRsaKeypair {
let result = rsaKeygen.generate(bit)
return {
publicKey: result.public_key,
privateKey: result.private_key
}
}
}

View File

@ -1,76 +1,368 @@
import 'typings-global'
import * as q from 'q'
import * as path from 'path'
let rsaKeygen = require('rsa-keygen')
import * as smartfile from 'smartfile'
import * as smartstring from 'smartstring'
let rawacme = require('rawacme')
import * as paths from './smartacme.paths'
import { SmartacmeHelper, IRsaKeypair } from './smartacme.classes.helper'
import * as plugins from './smartacme.plugins.js';
import type { ICertManager } from './interfaces/certmanager.js';
import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
import { commitinfo } from './00_commitinfo_data.js';
import { SmartacmeCert } from './smartacme.classes.cert.js';
/**
* class SmartAcme exports methods for maintaining SSL Certificates
* the options for the class @see SmartAcme
*/
export interface ISmartAcmeOptions {
accountPrivateKey?: string;
accountEmail: string;
/**
* Certificate storage manager (e.g., Mongo or in-memory).
*/
certManager: ICertManager;
// Removed legacy setChallenge/removeChallenge in favor of `challengeHandlers`
environment: 'production' | 'integration';
/**
* Optional retry/backoff configuration for transient failures
*/
retryOptions?: {
/** number of retry attempts */
retries?: number;
/** backoff multiplier */
factor?: number;
/** initial delay in milliseconds */
minTimeoutMs?: number;
/** maximum delay cap in milliseconds */
maxTimeoutMs?: number;
};
/**
* Pluggable ACME challenge handlers (DNS-01, HTTP-01, TLS-ALPN-01, etc.)
*/
challengeHandlers?: plugins.handlers.IChallengeHandler<any>[];
/**
* Order of challenge types to try (e.g. ['http-01','dns-01']).
* Defaults to ['dns-01'] or first supported type from handlers.
*/
challengePriority?: string[];
}
/**
* class SmartAcme
* can be used for setting up communication with an ACME authority
*
* ```ts
* const mySmartAcmeInstance = new SmartAcme({
* // see ISmartAcmeOptions for options
* })
* ```
*/
export class SmartAcme {
helper: SmartacmeHelper // bundles helper methods that would clutter the main SmartAcme class
acmeUrl: string // the acme url to use
productionBool: boolean // a boolean to quickly know wether we are in production or not
keyPair: IRsaKeypair // the keyPair needed for account creation
JWK
private options: ISmartAcmeOptions;
/**
* the constructor for class SmartAcme
*/
constructor(productionArg: boolean = false) {
this.productionBool = productionArg
this.helper = new SmartacmeHelper()
this.keyPair = this.helper.createKeypair()
if (this.productionBool) {
this.acmeUrl = rawacme.LETSENCRYPT_STAGING_URL
// the acme client
private client: plugins.acme.Client;
private smartdns = new plugins.smartdnsClient.Smartdns({});
public logger: plugins.smartlog.Smartlog;
// the account private key
private privateKey: string;
// certificate manager for persistence (implements ICertManager)
private certmanager: ICertManager;
private certmatcher: SmartacmeCertMatcher;
// retry/backoff configuration (resolved with defaults)
private retryOptions: { retries: number; factor: number; minTimeoutMs: number; maxTimeoutMs: number };
// track pending DNS challenges for graceful shutdown
private pendingChallenges: plugins.tsclass.network.IDnsChallenge[] = [];
// configured pluggable ACME challenge handlers
private challengeHandlers: plugins.handlers.IChallengeHandler<any>[];
// priority order of challenge types
private challengePriority: string[];
constructor(optionsArg: ISmartAcmeOptions) {
this.options = optionsArg;
this.logger = plugins.smartlog.Smartlog.createForCommitinfo(commitinfo);
// enable console output for structured logging
this.logger.enableConsole();
// initialize retry/backoff options
this.retryOptions = {
retries: optionsArg.retryOptions?.retries ?? 10,
factor: optionsArg.retryOptions?.factor ?? 4,
minTimeoutMs: optionsArg.retryOptions?.minTimeoutMs ?? 1000,
maxTimeoutMs: optionsArg.retryOptions?.maxTimeoutMs ?? 60000,
};
// initialize challenge handlers (must provide at least one)
if (!optionsArg.challengeHandlers || optionsArg.challengeHandlers.length === 0) {
throw new Error(
'You must provide at least one ACME challenge handler via options.challengeHandlers',
);
}
this.challengeHandlers = optionsArg.challengeHandlers;
// initialize challenge priority
this.challengePriority =
optionsArg.challengePriority && optionsArg.challengePriority.length > 0
? optionsArg.challengePriority
: this.challengeHandlers.map((h) => h.getSupportedTypes()[0]);
}
/**
* starts the instance
* ```ts
* await myCloudlyInstance.start() // does not support options
* ```
*/
public async start() {
this.privateKey =
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
// Initialize certificate manager
if (!this.options.certManager) {
throw new Error('You must provide a certManager via options.certManager');
}
this.certmanager = this.options.certManager;
await this.certmanager.init();
// CertMatcher
this.certmatcher = new SmartacmeCertMatcher();
// ACME Client
this.client = new plugins.acme.Client({
directoryUrl: (() => {
if (this.options.environment === 'production') {
return plugins.acme.directory.letsencrypt.production;
} else {
this.acmeUrl = rawacme.LETSENCRYPT_URL
return plugins.acme.directory.letsencrypt.staging;
}
})(),
accountKey: this.privateKey,
});
/* Register account */
await this.client.createAccount({
termsOfServiceAgreed: true,
contact: [`mailto:${this.options.accountEmail}`],
});
// Setup graceful shutdown handlers
process.on('SIGINT', () => this.handleSignal('SIGINT'));
process.on('SIGTERM', () => this.handleSignal('SIGTERM'));
}
/**
* Stops the SmartAcme instance and closes certificate store connections.
*/
public async stop() {
if (this.certmanager && typeof (this.certmanager as any).close === 'function') {
await (this.certmanager as any).close();
}
}
/** Retry helper with exponential backoff */
private async retry<T>(operation: () => Promise<T>, operationName: string = 'operation'): Promise<T> {
let attempt = 0;
let delay = this.retryOptions.minTimeoutMs;
while (true) {
try {
return await operation();
} catch (err) {
attempt++;
if (attempt > this.retryOptions.retries) {
await this.logger.log('error', `Operation ${operationName} failed after ${attempt} attempts`, err);
throw err;
}
await this.logger.log('warn', `Operation ${operationName} failed on attempt ${attempt}, retrying in ${delay}ms`, err);
await plugins.smartdelay.delayFor(delay);
delay = Math.min(delay * this.retryOptions.factor, this.retryOptions.maxTimeoutMs);
}
}
}
/** Clean up pending challenges and shut down */
private async handleShutdown(): Promise<void> {
for (const input of [...this.pendingChallenges]) {
const type: string = (input as any).type;
const handler = this.challengeHandlers.find((h) => h.getSupportedTypes().includes(type));
if (handler) {
try {
await handler.cleanup(input);
await this.logger.log('info', `Removed pending ${type} challenge during shutdown`, input);
} catch (err) {
await this.logger.log('error', `Failed to remove pending ${type} challenge during shutdown`, err);
}
} else {
await this.logger.log(
'warn',
`No handler for pending challenge type '${type}' during shutdown; skipping cleanup`,
input,
);
}
}
this.pendingChallenges = [];
await this.stop();
}
/** Handle process signals for graceful shutdown */
private handleSignal(sig: string): void {
this.logger.log('info', `Received signal ${sig}, shutting down gracefully`);
this.handleShutdown()
.then(() => process.exit(0))
.catch((err) => {
this.logger.log('error', 'Error during shutdown', err).then(() => process.exit(1));
});
}
/**
* creates an account if not currently present in module
* @executes ASYNC
*/
createAccount() {
let done = q.defer()
rawacme.createClient(
{
url: this.acmeUrl,
publicKey: this.keyPair.publicKey,
privateKey: this.keyPair.privateKey
},
(err, client) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
/**
* gets a certificate
* it runs through the following steps
*
* * look in the database
* * if in the database and still valid return it
* * if not in the database announce it
* * then get it from letsencrypt
* * store it
* * remove it from the pending map (which it go onto by announcing it)
* * retrieve it from the databse and return it
*
* @param domainArg
*/
public async getCertificateForDomain(domainArg: string): Promise<SmartacmeCert> {
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
client.newReg(
{
contact: ['mailto:domains@lossless.org']
},
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
this.JWK = res.body.key
console.log(this.JWK)
done.resolve()
})
}
)
return done.promise
if (
!retrievedCertificate &&
(await this.certmanager.interestMap.checkInterest(certDomainName))
) {
const existingCertificateInterest = this.certmanager.interestMap.findInterest(certDomainName);
const certificate = existingCertificateInterest.interestFullfilled;
return certificate;
} else if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
return retrievedCertificate;
} else if (retrievedCertificate && retrievedCertificate.shouldBeRenewed()) {
// Remove old certificate via certManager
await this.certmanager.deleteCertificate(certDomainName);
}
// lets make sure others get the same interest
const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName);
/* Place new order with retry */
const order = await this.retry(() => this.client.createOrder({
identifiers: [
{ type: 'dns', value: certDomainName },
{ type: 'dns', value: `*.${certDomainName}` },
],
}), 'createOrder');
/* Get authorizations and select challenges */
const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
for (const authz of authorizations) {
await this.logger.log('debug', 'Authorization received', authz);
// select a handler based on configured priority
let selectedHandler: { type: string; handler: plugins.handlers.IChallengeHandler<any> } | null = null;
let selectedChallengeArg: any = null;
for (const type of this.challengePriority) {
const candidate = authz.challenges.find((c: any) => c.type === type);
if (!candidate) continue;
const handler = this.challengeHandlers.find((h) => h.getSupportedTypes().includes(type));
if (handler) {
selectedHandler = { type, handler };
selectedChallengeArg = candidate;
break;
}
}
if (!selectedHandler) {
throw new Error(`No challenge handler for domain ${authz.identifier.value}: supported types [${this.challengePriority.join(',')}]`);
}
const { type, handler } = selectedHandler;
// build handler input with keyAuthorization
let input: any;
// retrieve keyAuthorization for challenge
const keyAuth = await this.client.getChallengeKeyAuthorization(selectedChallengeArg);
if (type === 'dns-01') {
input = { type, hostName: `_acme-challenge.${authz.identifier.value}`, challenge: keyAuth };
} else if (type === 'http-01') {
// HTTP-01 requires serving token at webPath
input = {
type,
token: (selectedChallengeArg as any).token,
keyAuthorization: keyAuth,
webPath: `/.well-known/acme-challenge/${(selectedChallengeArg as any).token}`,
};
} else {
// generic challenge input: include raw challenge properties
input = { type, keyAuthorization: keyAuth, ...selectedChallengeArg };
}
this.pendingChallenges.push(input);
try {
// Prepare the challenge (set DNS record, write file, etc.)
await this.retry(() => handler.prepare(input), `${type}.prepare`);
// For DNS-01, wait for propagation before verification
if (type === 'dns-01') {
const dnsInput = input as { hostName: string; challenge: string };
// Wait for authoritative DNS propagation before ACME verify
await this.retry(
() => this.smartdns.checkUntilAvailable(dnsInput.hostName, 'TXT', dnsInput.challenge, 100, 5000),
`${type}.propagation`,
);
// Extra cool-down to ensure ACME server sees the new TXT record
this.logger.log('info', 'Cooling down for 1 minute before ACME verification');
await plugins.smartdelay.delayFor(60000);
}
// Official ACME verification (ensures challenge is publicly reachable)
await this.retry(
() => this.client.verifyChallenge(authz, selectedChallengeArg),
`${type}.verifyChallenge`,
);
// Notify ACME server to complete the challenge
await this.retry(
() => this.client.completeChallenge(selectedChallengeArg),
`${type}.completeChallenge`,
);
// Wait for valid status (warnings on staging timeouts)
try {
await this.retry(
() => this.client.waitForValidStatus(selectedChallengeArg),
`${type}.waitForValidStatus`,
);
} catch (err) {
await this.logger.log(
'warn',
`Challenge ${type} did not reach valid status in time, proceeding to finalize`,
err,
);
}
} finally {
// Always cleanup resource
try {
await this.retry(() => handler.cleanup(input), `${type}.cleanup`);
} catch (err) {
await this.logger.log('error', `Error during ${type}.cleanup`, err);
} finally {
this.pendingChallenges = this.pendingChallenges.filter((c) => c !== input);
}
}
}
/* Finalize order */
const [key, csr] = await plugins.acme.forge.createCsr({
commonName: `*.${certDomainName}`,
altNames: [certDomainName],
});
await this.retry(() => this.client.finalizeOrder(order, csr), 'finalizeOrder');
const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
/* Done */
// Store the new certificate record
const certRecord = new SmartacmeCert({
id: plugins.smartunique.shortId(),
domainName: certDomainName,
privateKey: key.toString(),
publicKey: cert.toString(),
csr: csr.toString(),
created: Date.now(),
validUntil: Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 90 }),
});
await this.certmanager.storeCertificate(certRecord);
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
currentDomainInterst.fullfillInterest(newCertificate);
currentDomainInterst.destroy();
return newCertificate;
}
}

View File

@ -1,6 +0,0 @@
import * as path from 'path'
import * as smartfile from 'smartfile'
export let packageDir = path.join(__dirname,'../')
export let assetDir = path.join(packageDir,'assets/')
smartfile.fs.ensureDirSync(assetDir)

47
ts/smartacme.plugins.ts Normal file
View File

@ -0,0 +1,47 @@
// @apiclient.xyz scope
import * as cloudflare from '@apiclient.xyz/cloudflare';
export { cloudflare };
// @apiglobal scope
import * as typedserver from '@api.global/typedserver';
export { typedserver };
// @pushrocks scope
import * as lik from '@push.rocks/lik';
import * as smartdata from '@push.rocks/smartdata';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartdnsClient from '@push.rocks/smartdns/client';
import * as smartlog from '@push.rocks/smartlog';
import * as smartpromise from '@push.rocks/smartpromise';
import * as smartrequest from '@push.rocks/smartrequest';
import * as smartunique from '@push.rocks/smartunique';
import * as smartstring from '@push.rocks/smartstring';
import * as smarttime from '@push.rocks/smarttime';
export {
lik,
smartdata,
smartdelay,
smartdnsClient,
smartlog,
smartpromise,
smartrequest,
smartunique,
smartstring,
smarttime,
};
// @tsclass scope
import * as tsclass from '@tsclass/tsclass';
export { tsclass };
// third party scope
import * as acme from 'acme-client';
export { acme };
// local handlers for challenge types
import * as handlers from './handlers/index.js';
export { handlers };

View File

22
tsconfig.json Normal file
View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"include": [
"ts/**/*.ts"
],
"exclude": [
"node_modules",
"test",
"dist_*/**/*.d.ts"
]
}

View File

@ -1,3 +0,0 @@
{
"extends": "tslint-config-standard"
}