Compare commits

..

19 Commits

Author SHA1 Message Date
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
19 changed files with 9399 additions and 4524 deletions

View File

@ -6,8 +6,8 @@ on:
- '**' - '**'
env: env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}} NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}} NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}} NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
@ -26,7 +26,7 @@ jobs:
- name: Install pnpm and npmci - name: Install pnpm and npmci
run: | run: |
pnpm install -g pnpm pnpm install -g pnpm
pnpm install -g @shipzone/npmci pnpm install -g @ship.zone/npmci
- name: Run npm prepare - name: Run npm prepare
run: npmci npm prepare run: npmci npm prepare

View File

@ -6,8 +6,8 @@ on:
- '*' - '*'
env: env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}} NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}} NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}} NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
@ -26,7 +26,7 @@ jobs:
- name: Prepare - name: Prepare
run: | run: |
pnpm install -g pnpm pnpm install -g pnpm
pnpm install -g @shipzone/npmci pnpm install -g @ship.zone/npmci
npmci npm prepare npmci npm prepare
- name: Audit production dependencies - name: Audit production dependencies
@ -54,7 +54,7 @@ jobs:
- name: Prepare - name: Prepare
run: | run: |
pnpm install -g pnpm pnpm install -g pnpm
pnpm install -g @shipzone/npmci pnpm install -g @ship.zone/npmci
npmci npm prepare npmci npm prepare
- name: Test stable - name: Test stable
@ -82,7 +82,7 @@ jobs:
- name: Prepare - name: Prepare
run: | run: |
pnpm install -g pnpm pnpm install -g pnpm
pnpm install -g @shipzone/npmci pnpm install -g @ship.zone/npmci
npmci npm prepare npmci npm prepare
- name: Release - name: Release
@ -104,7 +104,7 @@ jobs:
- name: Prepare - name: Prepare
run: | run: |
pnpm install -g pnpm pnpm install -g pnpm
pnpm install -g @shipzone/npmci pnpm install -g @ship.zone/npmci
npmci npm prepare npmci npm prepare
- name: Code quality - name: Code quality
@ -119,6 +119,6 @@ jobs:
run: | run: |
npmci node install stable npmci node install stable
npmci npm install npmci npm install
pnpm install -g @gitzone/tsdoc pnpm install -g @git.zone/tsdoc
npmci command tsdoc npmci command tsdoc
continue-on-error: true continue-on-error: true

3
.gitignore vendored
View File

@ -3,7 +3,6 @@
# artifacts # artifacts
coverage/ coverage/
public/ public/
pages/
# installs # installs
node_modules/ node_modules/
@ -17,4 +16,4 @@ node_modules/
dist/ dist/
dist_*/ dist_*/
# custom #------# custom

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 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 this software and associated documentation files (the "Software"), to deal in

124
changelog.md Normal file
View File

@ -0,0 +1,124 @@
# Changelog
## 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

View File

@ -2,17 +2,37 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "push.rocks", "gitscope": "push.rocks",
"gitrepo": "smartacme", "gitrepo": "smartacme",
"description": "acme with an easy yet powerful interface in TypeScript", "description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
"npmPackagename": "@push.rocks/smartacme", "npmPackagename": "@push.rocks/smartacme",
"license": "MIT", "license": "MIT",
"projectDomain": "push.rocks" "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": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "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,8 +1,8 @@
{ {
"name": "@push.rocks/smartacme", "name": "@push.rocks/smartacme",
"version": "4.0.4", "version": "5.1.0",
"private": false, "private": false,
"description": "acme with an easy yet powerful interface in TypeScript", "description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module", "type": "module",
@ -13,42 +13,54 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+ssh://git@gitlab.com/umbrellazone/smartacme.git" "url": "https://code.foss.global/push.rocks/smartacme.git"
}, },
"keywords": [ "keywords": [
"ACME",
"LetsEncrypt",
"TypeScript", "TypeScript",
"acme", "certificate management",
"letsencrypt" "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", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/umbrellazone/smartacme/issues" "url": "https://code.foss.global/push.rocks/smartacme/issues"
}, },
"homepage": "https://gitlab.com/umbrellazone/smartacme#README", "homepage": "https://code.foss.global/push.rocks/smartacme#readme",
"dependencies": { "dependencies": {
"@apiglobal/typedserver": "^2.0.65", "@api.global/typedserver": "^3.0.74",
"@push.rocks/lik": "^6.0.3", "@push.rocks/lik": "^6.2.2",
"@push.rocks/smartdata": "^5.0.8", "@push.rocks/smartdata": "^5.15.1",
"@push.rocks/smartdelay": "^3.0.5", "@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartdns": "^5.0.2", "@push.rocks/smartdns": "^6.2.2",
"@push.rocks/smartlog": "^3.0.3", "@push.rocks/smartlog": "^3.0.7",
"@push.rocks/smartpromise": "^4.0.3", "@push.rocks/smartpromise": "^4.2.3",
"@push.rocks/smartrequest": "^2.0.18", "@push.rocks/smartrequest": "^2.1.0",
"@push.rocks/smartstring": "^4.0.5", "@push.rocks/smartstring": "^4.0.15",
"@push.rocks/smarttime": "^4.0.4", "@push.rocks/smarttime": "^4.1.1",
"@push.rocks/smartunique": "^3.0.3", "@push.rocks/smartunique": "^3.0.9",
"@tsclass/tsclass": "^4.0.42", "@tsclass/tsclass": "^9.0.0",
"acme-client": "^4.2.5" "acme-client": "^5.4.0"
}, },
"devDependencies": { "devDependencies": {
"@apiclient.xyz/cloudflare": "^6.0.3", "@apiclient.xyz/cloudflare": "^6.3.2",
"@gitzone/tsbuild": "^2.1.66", "@git.zone/tsbuild": "^2.3.2",
"@gitzone/tsrun": "^1.2.44", "@git.zone/tsrun": "^1.3.3",
"@gitzone/tstest": "^1.0.77", "@git.zone/tstest": "^1.0.96",
"@push.rocks/qenv": "^5.0.2", "@push.rocks/qenv": "^6.1.0",
"@push.rocks/tapbundle": "^5.0.12", "@push.rocks/tapbundle": "^5.6.3",
"@types/node": "^20.4.2" "@types/node": "^22.15.2"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@ -64,5 +76,9 @@
], ],
"browserslist": [ "browserslist": [
"last 1 chrome versions" "last 1 chrome versions"
] ],
"packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6",
"pnpm": {
"overrides": {}
}
} }

13152
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

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'.

298
readme.md
View File

@ -1,35 +1,228 @@
````markdown
# @push.rocks/smartacme # @push.rocks/smartacme
acme with an easy yet powerful interface in TypeScript
## Availabililty and Links A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartacme)
* [gitlab.com (source)](https://gitlab.com/push.rocks/smartacme)
* [github.com (source mirror)](https://github.com/push.rocks/smartacme)
* [docs (typedoc)](https://push.rocks.gitlab.io/smartacme/)
## Status for master ## Install
Status Category | Status Badge To install `@push.rocks/smartacme`, you can use npm or yarn. Run one of the following commands in your project directory:
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartacme/badges/master/pipeline.svg)](https://lossless.cloud) ```bash
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartacme/badges/master/coverage.svg)](https://lossless.cloud) npm install @push.rocks/smartacme --save
npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartacme)](https://lossless.cloud) ```
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartacme)](https://lossless.cloud) ````
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) or
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartacme)](https://lossless.cloud) ```bash
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartacme)](https://lossless.cloud) yarn add @push.rocks/smartacme
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartacme)](https://lossless.cloud) ```
Make sure your project is set up to use TypeScript and supports ECMAScript Modules (ESM).
## Usage ## Usage
Use TypeScript for best in class instellisense. 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.
```javascript ### Table of Contents
import { SmartAcme } from 'smartacme';
const run = async () => { 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 from the `@push.rocks/smartacme` package. You'll also need to import or define interfaces for your setup options:
```typescript
import { SmartAcme } from '@push.rocks/smartacme';
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com', // Email used for Let's Encrypt registration and recovery
accountPrivateKey: null, // Private key for the account (optional, if not provided it will be generated)
mongoDescriptor: {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
},
removeChallenge: async (dnsChallenge) => {
// Implement logic here to remove DNS challenge records
},
setChallenge: async (dnsChallenge) => {
// Implement logic here to create DNS challenge records
},
environment: 'integration', // Use 'production' for actual certificates
});
```
### Initializing SmartAcme
Before proceeding to request certificates, initialize your SmartAcme instance:
```typescript
await smartAcmeInstance.init();
```
### 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
Part of the ACME protocol involves responding to DNS challenges issued by the certificate authority to prove control over a domain. Implement the `setChallenge` and `removeChallenge` functions in your SmartAcme configuration to automate this process. These functions receive a `dnsChallenge` argument containing details needed to create or remove the necessary DNS records.
```typescript
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Qenv } from '@push.rocks/qenv';
const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN'));
const smartAcmeInstance = new SmartAcme({
accountEmail: 'domains@example.com',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
removeChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
setChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
environment: 'integration',
});
await smartAcmeInstance.init();
```
### 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:
```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',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
},
setChallenge: async (dnsChallenge) => {
await cloudflareAccount.convenience.acmeSetDnsChallenge(dnsChallenge);
},
removeChallenge: async (dnsChallenge) => {
await cloudflareAccount.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
environment: 'integration',
});
await smartAcmeInstance.init();
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
await smartAcmeInstance.stop();
}
main().catch(console.error);
```
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({ smartAcmeInstance = new smartacme.SmartAcme({
accountEmail: 'domains@lossless.org', accountEmail: 'domains@lossless.org',
accountPrivateKey: null, accountPrivateKey: null,
@ -38,27 +231,60 @@ const run = async () => {
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'), mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'), mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
}, },
removeChallenge: async (dnsChallenge) => {
// somehow provide a function that is able to remove the dns challenge
},
setChallenge: async (dnsChallenge) => { setChallenge: async (dnsChallenge) => {
// somehow provide a function that is able to the dns challenge await testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
removeChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
}, },
environment: 'integration', environment: 'integration',
}); });
await smartAcmeInstance.init(); await smartAcmeInstance.init();
expect(smartAcmeInstance).toBeInstanceOf(smartacme.SmartAcme);
});
// myCert has properties for public/private keys and csr ;) tap.test('should get a domain certificate', async () => {
const myCert = await smartAcmeInstance.getCertificateForDomain('bleu.de'); 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();
``` ```
## Contribution This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using `@push.rocks/smartacme`.
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) ---
For further information read the linked docs at the top of this readme. ```
## Legal ## License and Legal Information
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) 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](license) 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.
```

View File

@ -3,7 +3,7 @@ import { Qenv } from '@push.rocks/qenv';
import * as cloudflare from '@apiclient.xyz/cloudflare'; import * as cloudflare from '@apiclient.xyz/cloudflare';
const testQenv = new Qenv('./', './.nogit/'); const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN')); const testCloudflare = new cloudflare.CloudflareAccount(await testQenv.getEnvVarOnDemand('CF_TOKEN'));
import * as smartacme from '../ts/index.js'; import * as smartacme from '../ts/index.js';
@ -14,9 +14,9 @@ tap.test('should create a valid instance of SmartAcme', async () => {
accountEmail: 'domains@lossless.org', accountEmail: 'domains@lossless.org',
accountPrivateKey: null, accountPrivateKey: null,
mongoDescriptor: { mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'), mongoDbName: await testQenv.getEnvVarOnDemand('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'), mongoDbPass: await testQenv.getEnvVarOnDemand('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'), mongoDbUrl: await testQenv.getEnvVarOnDemand('MONGODB_URL'),
}, },
removeChallenge: async (dnsChallenge) => { removeChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge); testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
@ -26,7 +26,7 @@ tap.test('should create a valid instance of SmartAcme', async () => {
}, },
environment: 'integration', environment: 'integration',
}); });
await smartAcmeInstance.init(); await smartAcmeInstance.start();
}); });
tap.test('should get a domain certificate', async () => { tap.test('should get a domain certificate', async () => {
@ -36,7 +36,7 @@ tap.test('should get a domain certificate', async () => {
tap.test('certmatcher should correctly match domains', async () => { tap.test('certmatcher should correctly match domains', async () => {
const certMatcherMod = await import('../ts/smartacme.classes.certmatcher.js'); const certMatcherMod = await import('../ts/smartacme.classes.certmatcher.js');
const certMatcher = new certMatcherMod.CertMatcher(); const certMatcher = new certMatcherMod.SmartacmeCertMatcher();
const matchedCert = certMatcher.getCertificateDomainNameByDomainName('level3.level2.level1'); const matchedCert = certMatcher.getCertificateDomainNameByDomainName('level3.level2.level1');
expect(matchedCert).toEqual('level2.level1'); expect(matchedCert).toEqual('level2.level1');
}); });

View File

@ -1,8 +1,8 @@
/** /**
* autocreated commitinfo by @pushrocks/commitinfo * autocreated commitinfo by @push.rocks/commitinfo
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartacme', name: '@push.rocks/smartacme',
version: '4.0.4', version: '5.1.0',
description: 'acme with an easy yet powerful interface in TypeScript' description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
} }

View File

@ -1 +1,2 @@
export * from './smartacme.classes.smartacme.js'; export * from './smartacme.classes.smartacme.js';
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';

View File

@ -2,15 +2,15 @@ import * as plugins from './smartacme.plugins.js';
import * as interfaces from './interfaces/index.js'; import * as interfaces from './interfaces/index.js';
import { CertManager } from './smartacme.classes.certmanager.js'; import { SmartacmeCertManager } from './smartacme.classes.certmanager.js';
import { Collection, svDb, unI } from '@push.rocks/smartdata'; import { Collection, svDb, unI } from '@push.rocks/smartdata';
@plugins.smartdata.Collection(() => { @plugins.smartdata.Collection(() => {
return CertManager.activeDB; return SmartacmeCertManager.activeDB;
}) })
export class Cert export class SmartacmeCert
extends plugins.smartdata.SmartDataDbDoc<Cert, plugins.tsclass.network.ICert> extends plugins.smartdata.SmartDataDbDoc<SmartacmeCert, plugins.tsclass.network.ICert>
implements plugins.tsclass.network.ICert implements plugins.tsclass.network.ICert
{ {
@unI() @unI()

View File

@ -1,10 +1,10 @@
import * as plugins from './smartacme.plugins.js'; import * as plugins from './smartacme.plugins.js';
import { Cert } from './smartacme.classes.cert.js'; import { SmartacmeCert } from './smartacme.classes.cert.js';
import { SmartAcme } from './smartacme.classes.smartacme.js'; import { SmartAcme } from './smartacme.classes.smartacme.js';
import * as interfaces from './interfaces/index.js'; import * as interfaces from './interfaces/index.js';
export class CertManager { export class SmartacmeCertManager {
// ========= // =========
// STATIC // STATIC
// ========= // =========
@ -16,13 +16,13 @@ export class CertManager {
private mongoDescriptor: plugins.smartdata.IMongoDescriptor; private mongoDescriptor: plugins.smartdata.IMongoDescriptor;
public smartdataDb: plugins.smartdata.SmartdataDb; public smartdataDb: plugins.smartdata.SmartdataDb;
public interestMap: plugins.lik.InterestMap<string, Cert>; public interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
constructor( constructor(
smartAcmeArg: SmartAcme, smartAcmeArg: SmartAcme,
optionsArg: { optionsArg: {
mongoDescriptor: plugins.smartdata.IMongoDescriptor; mongoDescriptor: plugins.smartdata.IMongoDescriptor;
} },
) { ) {
this.mongoDescriptor = optionsArg.mongoDescriptor; this.mongoDescriptor = optionsArg.mongoDescriptor;
} }
@ -31,7 +31,7 @@ export class CertManager {
// Smartdata DB // Smartdata DB
this.smartdataDb = new plugins.smartdata.SmartdataDb(this.mongoDescriptor); this.smartdataDb = new plugins.smartdata.SmartdataDb(this.mongoDescriptor);
await this.smartdataDb.init(); await this.smartdataDb.init();
CertManager.activeDB = this.smartdataDb; SmartacmeCertManager.activeDB = this.smartdataDb;
// Pending Map // Pending Map
this.interestMap = new plugins.lik.InterestMap((certName) => certName); this.interestMap = new plugins.lik.InterestMap((certName) => certName);
@ -42,8 +42,8 @@ export class CertManager {
* @returns the Cert class or null * @returns the Cert class or null
* @param certDomainNameArg the domain Name to retrieve the vcertificate for * @param certDomainNameArg the domain Name to retrieve the vcertificate for
*/ */
public async retrieveCertificate(certDomainNameArg: string): Promise<Cert> { public async retrieveCertificate(certDomainNameArg: string): Promise<SmartacmeCert> {
const existingCertificate: Cert = await Cert.getInstance<Cert>({ const existingCertificate: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
domainName: certDomainNameArg, domainName: certDomainNameArg,
}); });
@ -59,7 +59,7 @@ export class CertManager {
* @param optionsArg * @param optionsArg
*/ */
public async storeCertificate(optionsArg: plugins.tsclass.network.ICert) { public async storeCertificate(optionsArg: plugins.tsclass.network.ICert) {
const cert = new Cert(optionsArg); const cert = new SmartacmeCert(optionsArg);
await cert.save(); await cert.save();
const interest = this.interestMap.findInterest(cert.domainName); const interest = this.interestMap.findInterest(cert.domainName);
if (interest) { if (interest) {
@ -69,7 +69,7 @@ export class CertManager {
} }
public async deleteCertificate(certDomainNameArg: string) { public async deleteCertificate(certDomainNameArg: string) {
const cert: Cert = await Cert.getInstance<Cert>({ const cert: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
domainName: certDomainNameArg, domainName: certDomainNameArg,
}); });
await cert.delete(); await cert.delete();

View File

@ -4,7 +4,7 @@ import * as interfaces from './interfaces/index.js';
/** /**
* certmatcher is responsible for matching certificates * certmatcher is responsible for matching certificates
*/ */
export class CertMatcher { export class SmartacmeCertMatcher {
/** /**
* creates a domainName for the certificate that will include the broadest scope * creates a domainName for the certificate that will include the broadest scope
* for wild card certificates * for wild card certificates

View File

@ -1,7 +1,8 @@
import * as plugins from './smartacme.plugins.js'; import * as plugins from './smartacme.plugins.js';
import { Cert } from './smartacme.classes.cert.js'; import { SmartacmeCert } from './smartacme.classes.cert.js';
import { CertManager } from './smartacme.classes.certmanager.js'; import { SmartacmeCertManager } from './smartacme.classes.certmanager.js';
import { CertMatcher } from './smartacme.classes.certmatcher.js'; import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
import { commitinfo } from './00_commitinfo_data.js';
/** /**
* the options for the class @see SmartAcme * the options for the class @see SmartAcme
@ -13,6 +14,19 @@ export interface ISmartAcmeOptions {
setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>; setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>; removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
environment: 'production' | 'integration'; 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;
};
} }
/** /**
@ -29,9 +43,9 @@ export class SmartAcme {
private options: ISmartAcmeOptions; private options: ISmartAcmeOptions;
// the acme client // the acme client
private client: any; private client: plugins.acme.Client;
private smartdns = new plugins.smartdns.Smartdns({}); private smartdns = new plugins.smartdnsClient.Smartdns({});
public logger: plugins.smartlog.ConsoleLog; public logger: plugins.smartlog.Smartlog;
// the account private key // the account private key
private privateKey: string; private privateKey: string;
@ -41,34 +55,47 @@ export class SmartAcme {
private removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>; private removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
// certmanager // certmanager
private certmanager: CertManager; private certmanager: SmartacmeCertManager;
private certmatcher: CertMatcher; 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[] = [];
constructor(optionsArg: ISmartAcmeOptions) { constructor(optionsArg: ISmartAcmeOptions) {
this.options = optionsArg; this.options = optionsArg;
this.logger = new plugins.smartlog.ConsoleLog(); 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 ?? 3,
factor: optionsArg.retryOptions?.factor ?? 2,
minTimeoutMs: optionsArg.retryOptions?.minTimeoutMs ?? 1000,
maxTimeoutMs: optionsArg.retryOptions?.maxTimeoutMs ?? 30000,
};
} }
/** /**
* inits the instance * starts the instance
* ```ts * ```ts
* await myCloudlyInstance.init() // does not support options * await myCloudlyInstance.start() // does not support options
* ``` * ```
*/ */
public async init() { public async start() {
this.privateKey = this.privateKey =
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString(); this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
this.setChallenge = this.options.setChallenge; this.setChallenge = this.options.setChallenge;
this.removeChallenge = this.options.removeChallenge; this.removeChallenge = this.options.removeChallenge;
// CertMangaer // CertMangaer
this.certmanager = new CertManager(this, { this.certmanager = new SmartacmeCertManager(this, {
mongoDescriptor: this.options.mongoDescriptor, mongoDescriptor: this.options.mongoDescriptor,
}); });
await this.certmanager.init(); await this.certmanager.init();
// CertMatcher // CertMatcher
this.certmatcher = new CertMatcher(); this.certmatcher = new SmartacmeCertMatcher();
// ACME Client // ACME Client
this.client = new plugins.acme.Client({ this.client = new plugins.acme.Client({
@ -87,11 +114,55 @@ export class SmartAcme {
termsOfServiceAgreed: true, termsOfServiceAgreed: true,
contact: [`mailto:${this.options.accountEmail}`], contact: [`mailto:${this.options.accountEmail}`],
}); });
// Setup graceful shutdown handlers
process.on('SIGINT', () => this.handleSignal('SIGINT'));
process.on('SIGTERM', () => this.handleSignal('SIGTERM'));
} }
public async stop() { public async stop() {
await this.certmanager.smartdataDb.close(); await this.certmanager.smartdataDb.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 challenge of [...this.pendingChallenges]) {
try {
await this.removeChallenge(challenge);
await this.logger.log('info', 'Removed pending challenge during shutdown', challenge);
} catch (err) {
await this.logger.log('error', 'Failed to remove pending challenge during shutdown', err);
}
}
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));
});
}
/** /**
* gets a certificate * gets a certificate
@ -107,7 +178,7 @@ export class SmartAcme {
* *
* @param domainArg * @param domainArg
*/ */
public async getCertificateForDomain(domainArg: string): Promise<Cert> { public async getCertificateForDomain(domainArg: string): Promise<SmartacmeCert> {
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg); const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName); const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
@ -127,54 +198,54 @@ export class SmartAcme {
// lets make sure others get the same interest // lets make sure others get the same interest
const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName); const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName);
/* Place new order */ /* Place new order with retry */
const order = await this.client.createOrder({ const order = await this.retry(() => this.client.createOrder({
identifiers: [ identifiers: [
{ type: 'dns', value: certDomainName }, { type: 'dns', value: certDomainName },
{ type: 'dns', value: `*.${certDomainName}` }, { type: 'dns', value: `*.${certDomainName}` },
], ],
}); }), 'createOrder');
/* Get authorizations and select challenges */ /* Get authorizations and select challenges */
const authorizations = await this.client.getAuthorizations(order); const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
for (const authz of authorizations) { for (const authz of authorizations) {
console.log(authz); await this.logger.log('debug', 'Authorization received', authz);
const fullHostName: string = `_acme-challenge.${authz.identifier.value}`; const fullHostName: string = `_acme-challenge.${authz.identifier.value}`;
const dnsChallenge: string = authz.challenges.find((challengeArg) => { const dnsChallenge = authz.challenges.find((challengeArg) => {
return challengeArg.type === 'dns-01'; return challengeArg.type === 'dns-01';
}); });
// process.exit(1); // process.exit(1);
const keyAuthorization: string = await this.client.getChallengeKeyAuthorization(dnsChallenge); const keyAuthorization: string = await this.client.getChallengeKeyAuthorization(dnsChallenge);
// prepare DNS challenge record and track for cleanup
const challengeRecord: plugins.tsclass.network.IDnsChallenge = { hostName: fullHostName, challenge: keyAuthorization };
this.pendingChallenges.push(challengeRecord);
try { try {
/* Satisfy challenge */ /* Satisfy challenge */
await this.setChallenge({ await this.retry(() => this.setChallenge(challengeRecord), 'setChallenge');
hostName: fullHostName,
challenge: keyAuthorization,
});
await plugins.smartdelay.delayFor(30000); await plugins.smartdelay.delayFor(30000);
await this.smartdns.checkUntilAvailable(fullHostName, 'TXT', keyAuthorization, 100, 5000); await this.retry(() => this.smartdns.checkUntilAvailable(fullHostName, 'TXT', keyAuthorization, 100, 5000), 'dnsCheckUntilAvailable');
console.log('Cool down an extra 60 second for region availability'); await this.logger.log('info', 'Cooling down extra 60 seconds for DNS regional propagation');
await plugins.smartdelay.delayFor(60000); await plugins.smartdelay.delayFor(60000);
/* Verify that challenge is satisfied */ /* Verify that challenge is satisfied */
await this.client.verifyChallenge(authz, dnsChallenge); await this.retry(() => this.client.verifyChallenge(authz, dnsChallenge), 'verifyChallenge');
/* Notify ACME provider that challenge is satisfied */ /* Notify ACME provider that challenge is satisfied */
await this.client.completeChallenge(dnsChallenge); await this.retry(() => this.client.completeChallenge(dnsChallenge), 'completeChallenge');
/* Wait for ACME provider to respond with valid status */ /* Wait for ACME provider to respond with valid status */
await this.client.waitForValidStatus(dnsChallenge); await this.retry(() => this.client.waitForValidStatus(dnsChallenge), 'waitForValidStatus');
} finally { } finally {
/* Clean up challenge response */ /* Clean up challenge response */
try { try {
await this.removeChallenge({ await this.retry(() => this.removeChallenge(challengeRecord), 'removeChallenge');
hostName: fullHostName, } catch (err) {
challenge: keyAuthorization, await this.logger.log('error', 'Error removing DNS challenge', err);
}); } finally {
} catch (e) { // remove from pending list
console.log(e); this.pendingChallenges = this.pendingChallenges.filter(c => c !== challengeRecord);
} }
} }
} }
@ -185,8 +256,8 @@ export class SmartAcme {
altNames: [certDomainName], altNames: [certDomainName],
}); });
await this.client.finalizeOrder(order, csr); await this.retry(() => this.client.finalizeOrder(order, csr), 'finalizeOrder');
const cert = await this.client.getCertificate(order); const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
/* Done */ /* Done */
@ -209,4 +280,8 @@ export class SmartAcme {
currentDomainInterst.destroy(); currentDomainInterst.destroy();
return newCertificate; return newCertificate;
} }
public async getAllCertificates(): Promise<SmartacmeCert[]> {
return SmartacmeCert.getInstances({});
}
} }

View File

@ -1,5 +1,5 @@
// @apiglobal scope // @apiglobal scope
import * as typedserver from '@apiglobal/typedserver'; import * as typedserver from '@api.global/typedserver';
export { typedserver }; export { typedserver };
@ -7,7 +7,7 @@ export { typedserver };
import * as lik from '@push.rocks/lik'; import * as lik from '@push.rocks/lik';
import * as smartdata from '@push.rocks/smartdata'; import * as smartdata from '@push.rocks/smartdata';
import * as smartdelay from '@push.rocks/smartdelay'; import * as smartdelay from '@push.rocks/smartdelay';
import * as smartdns from '@push.rocks/smartdns'; import * as smartdnsClient from '@push.rocks/smartdns/client';
import * as smartlog from '@push.rocks/smartlog'; import * as smartlog from '@push.rocks/smartlog';
import * as smartpromise from '@push.rocks/smartpromise'; import * as smartpromise from '@push.rocks/smartpromise';
import * as smartrequest from '@push.rocks/smartrequest'; import * as smartrequest from '@push.rocks/smartrequest';
@ -19,7 +19,7 @@ export {
lik, lik,
smartdata, smartdata,
smartdelay, smartdelay,
smartdns, smartdnsClient,
smartlog, smartlog,
smartpromise, smartpromise,
smartrequest, smartrequest,

View File

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