Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
48018b8955 | |||
56a440660b | |||
82bfc20a6d | |||
b84714b208 | |||
6425e4a93f | |||
55fa1215ae | |||
3769468b01 | |||
6ea919780c | |||
b5afe8e842 | |||
942e444d41 | |||
1ab15c0b72 | |||
f1db9c1c5d | |||
e3974b3bb1 | |||
016b93ea3a | |||
ab870af0bb |
@ -6,8 +6,8 @@ on:
|
||||
- '**'
|
||||
|
||||
env:
|
||||
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
|
||||
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}}
|
||||
@ -26,7 +26,7 @@ jobs:
|
||||
- name: Install pnpm and npmci
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @shipzone/npmci
|
||||
pnpm install -g @ship.zone/npmci
|
||||
|
||||
- name: Run npm prepare
|
||||
run: npmci npm prepare
|
||||
|
@ -6,8 +6,8 @@ on:
|
||||
- '*'
|
||||
|
||||
env:
|
||||
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
|
||||
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}}
|
||||
@ -26,7 +26,7 @@ jobs:
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @shipzone/npmci
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Audit production dependencies
|
||||
@ -54,7 +54,7 @@ jobs:
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @shipzone/npmci
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Test stable
|
||||
@ -82,7 +82,7 @@ jobs:
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @shipzone/npmci
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Release
|
||||
@ -104,7 +104,7 @@ jobs:
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @shipzone/npmci
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Code quality
|
||||
@ -119,6 +119,6 @@ jobs:
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
pnpm install -g @gitzone/tsdoc
|
||||
pnpm install -g @git.zone/tsdoc
|
||||
npmci command tsdoc
|
||||
continue-on-error: true
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,7 +3,6 @@
|
||||
# artifacts
|
||||
coverage/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
@ -17,4 +16,4 @@ node_modules/
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
# custom
|
||||
#------# custom
|
2
LICENSE
2
LICENSE
@ -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
|
||||
|
124
changelog.md
Normal file
124
changelog.md
Normal 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 user‑facing 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.7–4.0.6 - Internal fixes and updates
|
||||
- A series of releases with routine bug fixes and maintenance updates.
|
||||
|
||||
## 2023-07-21 - 4.0.5–4.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.0–4.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.9–3.0.14 - Internal fixes and updates
|
||||
- A range of releases focused on routine internal updates.
|
||||
|
||||
## 2020-11-18 - 3.0.0–3.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.0–2.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.2–2.0.35 - Internal fixes and updates
|
||||
- Routine internal updates and maintenance.
|
||||
|
||||
## 2018-10-07 - 2.0.0–2.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 le‑acme‑core
|
||||
- improve upon keyCreation
|
||||
- update to use more promises
|
||||
- add README
|
||||
- first version
|
@ -2,17 +2,37 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"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",
|
||||
"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": {
|
||||
"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"
|
||||
}
|
||||
}
|
72
package.json
72
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@push.rocks/smartacme",
|
||||
"version": "4.0.6",
|
||||
"version": "5.1.0",
|
||||
"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",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@ -13,42 +13,54 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@gitlab.com/umbrellazone/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/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": {
|
||||
"@apiglobal/typedserver": "^2.0.65",
|
||||
"@push.rocks/lik": "^6.0.3",
|
||||
"@push.rocks/smartdata": "^5.0.8",
|
||||
"@api.global/typedserver": "^3.0.74",
|
||||
"@push.rocks/lik": "^6.2.2",
|
||||
"@push.rocks/smartdata": "^5.15.1",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartdns": "^5.0.2",
|
||||
"@push.rocks/smartlog": "^3.0.3",
|
||||
"@push.rocks/smartpromise": "^4.0.3",
|
||||
"@push.rocks/smartrequest": "^2.0.18",
|
||||
"@push.rocks/smartstring": "^4.0.5",
|
||||
"@push.rocks/smarttime": "^4.0.4",
|
||||
"@push.rocks/smartunique": "^3.0.3",
|
||||
"@tsclass/tsclass": "^4.0.42",
|
||||
"acme-client": "^4.2.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.0.0",
|
||||
"acme-client": "^5.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apiclient.xyz/cloudflare": "^6.0.3",
|
||||
"@gitzone/tsbuild": "^2.1.66",
|
||||
"@gitzone/tsrun": "^1.2.44",
|
||||
"@gitzone/tstest": "^1.0.77",
|
||||
"@push.rocks/qenv": "^5.0.2",
|
||||
"@push.rocks/tapbundle": "^5.0.12",
|
||||
"@types/node": "^20.4.2"
|
||||
"@apiclient.xyz/cloudflare": "^6.3.2",
|
||||
"@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": "^5.6.3",
|
||||
"@types/node": "^22.15.2"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@ -64,5 +76,9 @@
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
]
|
||||
],
|
||||
"packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6",
|
||||
"pnpm": {
|
||||
"overrides": {}
|
||||
}
|
||||
}
|
||||
|
13118
pnpm-lock.yaml
generated
13118
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
2
readme.hints.md
Normal file
2
readme.hints.md
Normal 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
298
readme.md
@ -1,35 +1,228 @@
|
||||
````markdown
|
||||
# @push.rocks/smartacme
|
||||
acme with an easy yet powerful interface in TypeScript
|
||||
|
||||
## Availabililty and Links
|
||||
* [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/)
|
||||
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
|
||||
|
||||
## Status for master
|
||||
## Install
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
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
|
||||
|
||||
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
|
||||
import { SmartAcme } from 'smartacme';
|
||||
### Table of Contents
|
||||
|
||||
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({
|
||||
accountEmail: 'domains@lossless.org',
|
||||
accountPrivateKey: null,
|
||||
@ -38,27 +231,60 @@ const run = async () => {
|
||||
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
|
||||
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
|
||||
},
|
||||
removeChallenge: async (dnsChallenge) => {
|
||||
// somehow provide a function that is able to remove the dns challenge
|
||||
},
|
||||
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',
|
||||
});
|
||||
await smartAcmeInstance.init();
|
||||
expect(smartAcmeInstance).toBeInstanceOf(smartacme.SmartAcme);
|
||||
});
|
||||
|
||||
// myCert has properties for public/private keys and csr ;)
|
||||
const myCert = await smartAcmeInstance.getCertificateForDomain('bleu.de');
|
||||
};
|
||||
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();
|
||||
```
|
||||
|
||||
## 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
|
||||
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
## 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](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.
|
||||
```
|
||||
|
12
test/test.ts
12
test/test.ts
@ -3,7 +3,7 @@ import { Qenv } from '@push.rocks/qenv';
|
||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
||||
|
||||
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';
|
||||
|
||||
@ -14,9 +14,9 @@ tap.test('should create a valid instance of SmartAcme', async () => {
|
||||
accountEmail: 'domains@lossless.org',
|
||||
accountPrivateKey: null,
|
||||
mongoDescriptor: {
|
||||
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
|
||||
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
|
||||
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
|
||||
mongoDbName: await testQenv.getEnvVarOnDemand('MONGODB_DATABASE'),
|
||||
mongoDbPass: await testQenv.getEnvVarOnDemand('MONGODB_PASSWORD'),
|
||||
mongoDbUrl: await testQenv.getEnvVarOnDemand('MONGODB_URL'),
|
||||
},
|
||||
removeChallenge: async (dnsChallenge) => {
|
||||
testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
|
||||
@ -26,7 +26,7 @@ tap.test('should create a valid instance of SmartAcme', async () => {
|
||||
},
|
||||
environment: 'integration',
|
||||
});
|
||||
await smartAcmeInstance.init();
|
||||
await smartAcmeInstance.start();
|
||||
});
|
||||
|
||||
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 () => {
|
||||
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');
|
||||
expect(matchedCert).toEqual('level2.level1');
|
||||
});
|
||||
|
@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartacme',
|
||||
version: '4.0.6',
|
||||
description: 'acme with an easy yet powerful interface in TypeScript'
|
||||
version: '5.1.0',
|
||||
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
|
||||
}
|
||||
|
@ -1 +1,2 @@
|
||||
export * from './smartacme.classes.smartacme.js';
|
||||
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';
|
||||
|
@ -2,15 +2,15 @@ import * as plugins from './smartacme.plugins.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';
|
||||
|
||||
@plugins.smartdata.Collection(() => {
|
||||
return CertManager.activeDB;
|
||||
return SmartacmeCertManager.activeDB;
|
||||
})
|
||||
export class Cert
|
||||
extends plugins.smartdata.SmartDataDbDoc<Cert, plugins.tsclass.network.ICert>
|
||||
export class SmartacmeCert
|
||||
extends plugins.smartdata.SmartDataDbDoc<SmartacmeCert, plugins.tsclass.network.ICert>
|
||||
implements plugins.tsclass.network.ICert
|
||||
{
|
||||
@unI()
|
||||
|
@ -1,10 +1,10 @@
|
||||
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 * as interfaces from './interfaces/index.js';
|
||||
|
||||
export class CertManager {
|
||||
export class SmartacmeCertManager {
|
||||
// =========
|
||||
// STATIC
|
||||
// =========
|
||||
@ -16,13 +16,13 @@ export class CertManager {
|
||||
private mongoDescriptor: plugins.smartdata.IMongoDescriptor;
|
||||
public smartdataDb: plugins.smartdata.SmartdataDb;
|
||||
|
||||
public interestMap: plugins.lik.InterestMap<string, Cert>;
|
||||
public interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
|
||||
|
||||
constructor(
|
||||
smartAcmeArg: SmartAcme,
|
||||
optionsArg: {
|
||||
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
|
||||
}
|
||||
},
|
||||
) {
|
||||
this.mongoDescriptor = optionsArg.mongoDescriptor;
|
||||
}
|
||||
@ -31,7 +31,7 @@ export class CertManager {
|
||||
// Smartdata DB
|
||||
this.smartdataDb = new plugins.smartdata.SmartdataDb(this.mongoDescriptor);
|
||||
await this.smartdataDb.init();
|
||||
CertManager.activeDB = this.smartdataDb;
|
||||
SmartacmeCertManager.activeDB = this.smartdataDb;
|
||||
|
||||
// Pending Map
|
||||
this.interestMap = new plugins.lik.InterestMap((certName) => certName);
|
||||
@ -42,8 +42,8 @@ export class CertManager {
|
||||
* @returns the Cert class or null
|
||||
* @param certDomainNameArg the domain Name to retrieve the vcertificate for
|
||||
*/
|
||||
public async retrieveCertificate(certDomainNameArg: string): Promise<Cert> {
|
||||
const existingCertificate: Cert = await Cert.getInstance<Cert>({
|
||||
public async retrieveCertificate(certDomainNameArg: string): Promise<SmartacmeCert> {
|
||||
const existingCertificate: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
|
||||
domainName: certDomainNameArg,
|
||||
});
|
||||
|
||||
@ -59,7 +59,7 @@ export class CertManager {
|
||||
* @param optionsArg
|
||||
*/
|
||||
public async storeCertificate(optionsArg: plugins.tsclass.network.ICert) {
|
||||
const cert = new Cert(optionsArg);
|
||||
const cert = new SmartacmeCert(optionsArg);
|
||||
await cert.save();
|
||||
const interest = this.interestMap.findInterest(cert.domainName);
|
||||
if (interest) {
|
||||
@ -69,7 +69,7 @@ export class CertManager {
|
||||
}
|
||||
|
||||
public async deleteCertificate(certDomainNameArg: string) {
|
||||
const cert: Cert = await Cert.getInstance<Cert>({
|
||||
const cert: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
|
||||
domainName: certDomainNameArg,
|
||||
});
|
||||
await cert.delete();
|
||||
|
@ -4,7 +4,7 @@ import * as interfaces from './interfaces/index.js';
|
||||
/**
|
||||
* certmatcher is responsible for matching certificates
|
||||
*/
|
||||
export class CertMatcher {
|
||||
export class SmartacmeCertMatcher {
|
||||
/**
|
||||
* creates a domainName for the certificate that will include the broadest scope
|
||||
* for wild card certificates
|
||||
|
@ -1,7 +1,8 @@
|
||||
import * as plugins from './smartacme.plugins.js';
|
||||
import { Cert } from './smartacme.classes.cert.js';
|
||||
import { CertManager } from './smartacme.classes.certmanager.js';
|
||||
import { CertMatcher } from './smartacme.classes.certmatcher.js';
|
||||
import { SmartacmeCert } from './smartacme.classes.cert.js';
|
||||
import { SmartacmeCertManager } from './smartacme.classes.certmanager.js';
|
||||
import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
|
||||
import { commitinfo } from './00_commitinfo_data.js';
|
||||
|
||||
/**
|
||||
* the options for the class @see SmartAcme
|
||||
@ -13,6 +14,19 @@ export interface ISmartAcmeOptions {
|
||||
setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
|
||||
removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
|
||||
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;
|
||||
|
||||
// the acme client
|
||||
private client: any;
|
||||
private smartdns = new plugins.smartdns.Smartdns({});
|
||||
public logger: plugins.smartlog.ConsoleLog;
|
||||
private client: plugins.acme.Client;
|
||||
private smartdns = new plugins.smartdnsClient.Smartdns({});
|
||||
public logger: plugins.smartlog.Smartlog;
|
||||
|
||||
// the account private key
|
||||
private privateKey: string;
|
||||
@ -41,34 +55,47 @@ export class SmartAcme {
|
||||
private removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
|
||||
|
||||
// certmanager
|
||||
private certmanager: CertManager;
|
||||
private certmatcher: CertMatcher;
|
||||
private certmanager: SmartacmeCertManager;
|
||||
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) {
|
||||
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
|
||||
* await myCloudlyInstance.init() // does not support options
|
||||
* await myCloudlyInstance.start() // does not support options
|
||||
* ```
|
||||
*/
|
||||
public async init() {
|
||||
public async start() {
|
||||
this.privateKey =
|
||||
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
|
||||
this.setChallenge = this.options.setChallenge;
|
||||
this.removeChallenge = this.options.removeChallenge;
|
||||
|
||||
// CertMangaer
|
||||
this.certmanager = new CertManager(this, {
|
||||
this.certmanager = new SmartacmeCertManager(this, {
|
||||
mongoDescriptor: this.options.mongoDescriptor,
|
||||
});
|
||||
await this.certmanager.init();
|
||||
|
||||
// CertMatcher
|
||||
this.certmatcher = new CertMatcher();
|
||||
this.certmatcher = new SmartacmeCertMatcher();
|
||||
|
||||
// ACME Client
|
||||
this.client = new plugins.acme.Client({
|
||||
@ -87,11 +114,55 @@ export class SmartAcme {
|
||||
termsOfServiceAgreed: true,
|
||||
contact: [`mailto:${this.options.accountEmail}`],
|
||||
});
|
||||
// Setup graceful shutdown handlers
|
||||
process.on('SIGINT', () => this.handleSignal('SIGINT'));
|
||||
process.on('SIGTERM', () => this.handleSignal('SIGTERM'));
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
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
|
||||
@ -107,7 +178,7 @@ export class SmartAcme {
|
||||
*
|
||||
* @param domainArg
|
||||
*/
|
||||
public async getCertificateForDomain(domainArg: string): Promise<Cert> {
|
||||
public async getCertificateForDomain(domainArg: string): Promise<SmartacmeCert> {
|
||||
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
|
||||
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
|
||||
|
||||
@ -127,54 +198,54 @@ export class SmartAcme {
|
||||
// lets make sure others get the same interest
|
||||
const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName);
|
||||
|
||||
/* Place new order */
|
||||
const order = await this.client.createOrder({
|
||||
/* 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.client.getAuthorizations(order);
|
||||
const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
|
||||
|
||||
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 dnsChallenge: string = authz.challenges.find((challengeArg) => {
|
||||
const dnsChallenge = authz.challenges.find((challengeArg) => {
|
||||
return challengeArg.type === 'dns-01';
|
||||
});
|
||||
// process.exit(1);
|
||||
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 {
|
||||
/* Satisfy challenge */
|
||||
await this.setChallenge({
|
||||
hostName: fullHostName,
|
||||
challenge: keyAuthorization,
|
||||
});
|
||||
await this.retry(() => this.setChallenge(challengeRecord), 'setChallenge');
|
||||
await plugins.smartdelay.delayFor(30000);
|
||||
await this.smartdns.checkUntilAvailable(fullHostName, 'TXT', keyAuthorization, 100, 5000);
|
||||
console.log('Cool down an extra 60 second for region availability');
|
||||
await this.retry(() => this.smartdns.checkUntilAvailable(fullHostName, 'TXT', keyAuthorization, 100, 5000), 'dnsCheckUntilAvailable');
|
||||
await this.logger.log('info', 'Cooling down extra 60 seconds for DNS regional propagation');
|
||||
await plugins.smartdelay.delayFor(60000);
|
||||
|
||||
/* 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 */
|
||||
await this.client.completeChallenge(dnsChallenge);
|
||||
await this.retry(() => this.client.completeChallenge(dnsChallenge), 'completeChallenge');
|
||||
|
||||
/* Wait for ACME provider to respond with valid status */
|
||||
await this.client.waitForValidStatus(dnsChallenge);
|
||||
await this.retry(() => this.client.waitForValidStatus(dnsChallenge), 'waitForValidStatus');
|
||||
} finally {
|
||||
/* Clean up challenge response */
|
||||
try {
|
||||
await this.removeChallenge({
|
||||
hostName: fullHostName,
|
||||
challenge: keyAuthorization,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
await this.retry(() => this.removeChallenge(challengeRecord), 'removeChallenge');
|
||||
} catch (err) {
|
||||
await this.logger.log('error', 'Error removing DNS challenge', err);
|
||||
} finally {
|
||||
// remove from pending list
|
||||
this.pendingChallenges = this.pendingChallenges.filter(c => c !== challengeRecord);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -185,8 +256,8 @@ export class SmartAcme {
|
||||
altNames: [certDomainName],
|
||||
});
|
||||
|
||||
await this.client.finalizeOrder(order, csr);
|
||||
const cert = await this.client.getCertificate(order);
|
||||
await this.retry(() => this.client.finalizeOrder(order, csr), 'finalizeOrder');
|
||||
const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
|
||||
|
||||
/* Done */
|
||||
|
||||
@ -209,4 +280,8 @@ export class SmartAcme {
|
||||
currentDomainInterst.destroy();
|
||||
return newCertificate;
|
||||
}
|
||||
|
||||
public async getAllCertificates(): Promise<SmartacmeCert[]> {
|
||||
return SmartacmeCert.getInstances({});
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
// @apiglobal scope
|
||||
import * as typedserver from '@apiglobal/typedserver';
|
||||
import * as typedserver from '@api.global/typedserver';
|
||||
|
||||
export { typedserver };
|
||||
|
||||
@ -7,7 +7,7 @@ export { typedserver };
|
||||
import * as lik from '@push.rocks/lik';
|
||||
import * as smartdata from '@push.rocks/smartdata';
|
||||
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 smartpromise from '@push.rocks/smartpromise';
|
||||
import * as smartrequest from '@push.rocks/smartrequest';
|
||||
@ -19,7 +19,7 @@ export {
|
||||
lik,
|
||||
smartdata,
|
||||
smartdelay,
|
||||
smartdns,
|
||||
smartdnsClient,
|
||||
smartlog,
|
||||
smartpromise,
|
||||
smartrequest,
|
||||
|
@ -1,11 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "nodenext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
}
|
||||
"baseUrl": ".",
|
||||
"paths": {}
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
Reference in New Issue
Block a user