BREAKING CHANGE(acme): Replace external acme-client with a built-in RFC8555-compliant ACME implementation and update public APIs accordingly

This commit is contained in:
2026-02-15 20:20:46 +00:00
parent 3fa34fa373
commit cf4b758800
31 changed files with 4717 additions and 3530 deletions

532
readme.md
View File

@@ -1,361 +1,299 @@
# @push.rocks/smartacme
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power. 🔒
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
Using pnpm as the package manager:
```bash
pnpm add @push.rocks/smartacme
```
Ensure your project is set up to use TypeScript and ECMAScript Modules (ESM).
## Running Tests
Tests are written using `@push.rocks/tapbundle` and can be run with:
```bash
pnpm test
```
To run a specific test file:
```bash
tsx test/<test-file>.ts
```
Ensure your project uses TypeScript and ECMAScript Modules (ESM).
## Usage
This guide will walk you through using `@push.rocks/smartacme` to set up and manage ACME (Automated Certificate Management Environment) certificates with a focus on the Let's Encrypt service, which provides free SSL certificates. The library provides an easy yet powerful TypeScript interface to automate the process of obtaining, renewing, and installing your SSL certificates.
`@push.rocks/smartacme` automates the full ACME certificate lifecycle — obtaining, renewing, and storing SSL/TLS certificates from Let's Encrypt. It supports pluggable challenge handlers (DNS-01, HTTP-01) and pluggable certificate storage backends (MongoDB, in-memory, or your own).
### Table of Contents
1. [Setting Up Your Project](#setting-up-your-project)
2. [Creating a SmartAcme Instance](#creating-a-smartacme-instance)
3. [Initializing SmartAcme](#initializing-smartacme)
4. [Obtaining a Certificate for a Domain](#obtaining-a-certificate-for-a-domain)
5. [Automating DNS Challenges](#automating-dns-challenges)
6. [Managing Certificates](#managing-certificates)
7. [Environmental Considerations](#environmental-considerations)
8. [Complete Example](#complete-example)
### Setting Up Your Project
Ensure your project includes the necessary TypeScript configuration and dependencies. You'll need to have TypeScript installed and configured for ECMAScript Modules. If you are new to TypeScript, review its [documentation](https://www.typescriptlang.org/docs/) to get started.
### Creating a SmartAcme Instance
Start by importing the `SmartAcme` class and any built-in handlers you plan to use. For example, to use DNS-01 via Cloudflare:
### Quick Start
```typescript
import { SmartAcme, MongoCertManager } from '@push.rocks/smartacme';
import { SmartAcme, certmanagers, handlers } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
// Create a Cloudflare account client with your API token
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
// Initialize a certificate manager (e.g., MongoDB)
const certManager = new MongoCertManager({
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
// 1. Set up a certificate manager (MongoDB or in-memory)
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
});
// Instantiate SmartAcme with the certManager and challenge handlers
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
certManager,
environment: 'integration', // 'production' to request real certificates
retryOptions: {}, // optional retry/backoff settings
challengeHandlers: [ // pluggable ACME challenge handlers
new Dns01Handler(cfAccount),
// add more handlers as needed (e.g., Http01Webroot, Http01MemoryHandler)
],
challengePriority: ['dns-01'], // optional challenge ordering
});
```
// 2. Set up challenge handlers
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_API_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
### Initializing SmartAcme
Before proceeding to request certificates, start your SmartAcme instance:
```typescript
await smartAcmeInstance.start();
```
### Obtaining a Certificate for a Domain
To obtain a certificate for a specific domain, use the `getCertificateForDomain` method. This function ensures that if a valid certificate is already present, it will be reused; otherwise, a new certificate is obtained:
```typescript
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
```
### Automating DNS Challenges
SmartAcme uses pluggable ACME challenge handlers (see built-in handlers below) to automate domain validation. You configure handlers via the `challengeHandlers` array when creating the instance, and SmartAcme will invoke each handlers `prepare`, optional `verify`, and `cleanup` methods during the ACME order flow.
### Managing Certificates
The library automatically handles fetching, renewing, and storing your certificates in a MongoDB database specified via a certificate manager. Ensure your MongoDB instance is accessible and properly configured for use with SmartAcme.
```typescript
import { MongoCertManager } from '@push.rocks/smartacme';
const certManager = new MongoCertManager({
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
});
```
SmartAcme uses the `ICertManager` interface for certificate storage. Two built-in implementations are available:
- **MemoryCertManager**
- In-memory storage, suitable for testing or ephemeral use.
- Import example:
```typescript
import { MemoryCertManager } from '@push.rocks/smartacme';
const certManager = new MemoryCertManager();
```
- **MongoCertManager**
- Persistent storage in MongoDB (collection: `SmartacmeCert`).
- Import example:
```typescript
import { MongoCertManager } from '@push.rocks/smartacme';
const certManager = new MongoCertManager({
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
});
```
#### Custom Certificate Managers
To implement a custom certificate manager, implement the `ICertManager` interface and pass it to `SmartAcme`:
```typescript
import type { ICertManager, Cert as SmartacmeCert } from '@push.rocks/smartacme';
import { SmartAcme } from '@push.rocks/smartacme';
class MyCustomCertManager implements ICertManager {
async init(): Promise<void> { /* setup storage */ }
async get(domainName: string): Promise<SmartacmeCert | null> { /* lookup cert */ }
async put(cert: SmartacmeCert): Promise<SmartacmeCert> { /* store cert */ }
async delete(domainName: string): Promise<void> { /* remove cert */ }
async close?(): Promise<void> { /* optional cleanup */ }
}
// Use your custom manager:
const customManager = new MyCustomCertManager();
// 3. Create and start SmartAcme
const smartAcme = new SmartAcme({
accountEmail: 'youremail@example.com',
certManager: customManager,
environment: 'integration',
challengeHandlers: [], // add your handlers
accountEmail: 'admin@example.com',
certManager,
environment: 'production', // or 'integration' for staging
challengeHandlers: [dnsHandler],
});
await smartAcme.start();
// 4. Get a certificate
const cert = await smartAcme.getCertificateForDomain('example.com');
console.log(cert.publicKey); // PEM certificate
console.log(cert.privateKey); // PEM private key
// 5. Clean up
await smartAcme.stop();
```
### Environmental Considerations
When creating an instance of `SmartAcme`, you can specify an `environment` option. This is particularly useful for testing, as you can use the `integration` environment to avoid hitting rate limits and for testing your setup without issuing real certificates. Switch to `production` when you are ready to obtain actual certificates.
### Complete Example
Below is a complete example demonstrating how to use `@push.rocks/smartacme` to obtain and manage an ACME certificate with Let's Encrypt using a DNS-01 handler:
### SmartAcme Options
```typescript
import { SmartAcme, MongoCertManager } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Qenv } from '@push.rocks/qenv';
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
const qenv = new Qenv('./', './.nogit/');
const cloudflareAccount = new cloudflare.CloudflareAccount(qenv.getEnvVarOnDemand('CF_TOKEN'));
async function main() {
// Initialize MongoDB certificate manager
const certManager = new MongoCertManager({
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
});
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
certManager,
environment: 'integration',
challengeHandlers: [new Dns01Handler(cloudflareAccount)],
});
await smartAcmeInstance.start();
const myDomain = 'example.com';
// Get certificate for domain (no wildcard)
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
// Get certificate with wildcard (requires DNS-01 handler)
const certWithWildcard = await smartAcmeInstance.getCertificateForDomain(myDomain, { includeWildcard: true });
console.log('Certificate with wildcard:', certWithWildcard);
await smartAcmeInstance.stop();
interface ISmartAcmeOptions {
accountEmail: string; // ACME account email
accountPrivateKey?: string; // Optional account key (auto-generated if omitted)
certManager: ICertManager; // Certificate storage backend
environment: 'production' | 'integration'; // LetsEncrypt environment
challengeHandlers: IChallengeHandler[]; // At least one handler required
challengePriority?: string[]; // e.g. ['dns-01', 'http-01']
retryOptions?: { // Optional retry/backoff config
retries?: number;
factor?: number;
minTimeoutMs?: number;
maxTimeoutMs?: number;
};
}
main().catch(console.error);
```
## Built-in Challenge Handlers
This module includes three out-of-the-box ACME challenge handlers:
- **Dns01Handler**
- Uses a Cloudflare account (from `@apiclient.xyz/cloudflare`) and Smartdns client to set and remove DNS TXT records, then wait for propagation.
- Import path:
```typescript
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
```
- Example:
```typescript
import * as cloudflare from '@apiclient.xyz/cloudflare';
const cfAccount = new cloudflare.CloudflareAccount('CF_TOKEN');
const dnsHandler = new Dns01Handler(cfAccount);
```
- **Http01Webroot**
- Writes ACME HTTP-01 challenge files under a file-system webroot (`/.well-known/acme-challenge/`), and removes them on cleanup.
- Import path:
```typescript
import { Http01Webroot } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
```
- Example:
```typescript
const httpHandler = new Http01Webroot({ webroot: '/var/www/html' });
```
- **Http01MemoryHandler**
- In-memory HTTP-01 challenge handler that stores and serves ACME tokens without disk I/O.
- Import path:
```typescript
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
```
- Example (Express integration):
```typescript
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
const memoryHandler = new Http01MemoryHandler();
app.use((req, res, next) => memoryHandler.handleRequest(req, res, next));
```
All handlers implement the `IChallengeHandler<T>` interface and can be combined in the `challengeHandlers` array.
## Creating Custom Handlers
To support additional challenge types or custom validation flows, implement the `IChallengeHandler<T>` interface:
```typescript
import type { IChallengeHandler } from '@push.rocks/smartacme/ts/handlers/IChallengeHandler.js';
// Define your custom challenge payload type
interface MyChallenge { type: string; /* ... */ }
class MyCustomHandler implements IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] {
return ['my-01'];
}
// Prepare the challenge (set DNS records, start servers, etc.)
async prepare(ch: MyChallenge): Promise<void> {
// preparation logic
}
// Optional verify step after prepare
async verify?(ch: MyChallenge): Promise<void> {
// verification logic
}
// Cleanup after challenge (remove records, stop servers)
async cleanup(ch: MyChallenge): Promise<void> {
// cleanup logic
}
}
// Then register your handler:
const customInstance = new SmartAcme({
/* other options */,
challengeHandlers: [ new MyCustomHandler() ],
challengePriority: ['my-01'],
});
In this example, `Qenv` is used to manage environment variables, and the Cloudflare library is used to handle DNS challenges through the built-in `Dns01Handler` plugin.
### Getting Certificates
## Additional Details
```typescript
// Standard certificate for a single domain
const cert = await smartAcme.getCertificateForDomain('example.com');
// Include wildcard certificate (requires DNS-01 handler)
const certWithWildcard = await smartAcme.getCertificateForDomain('example.com', {
includeWildcard: true,
});
// Request wildcard only
const wildcardCert = await smartAcme.getCertificateForDomain('*.example.com');
```
Certificates are automatically cached and reused when still valid. Renewal happens automatically when a certificate is within 10 days of expiration.
### Certificate Object
The certificate object obtained from the `getCertificateForDomain` method has the following properties:
The returned `SmartacmeCert` object has these 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.
| Property | Type | Description |
|-------------|----------|--------------------------------------|
| `id` | `string` | Unique certificate identifier |
| `domainName`| `string` | Domain the cert is issued for |
| `publicKey` | `string` | PEM-encoded certificate |
| `privateKey`| `string` | PEM-encoded private key |
| `csr` | `string` | Certificate Signing Request |
| `created` | `number` | Timestamp of creation |
| `validUntil`| `number` | Timestamp of expiration |
### Methods Summary
## Certificate Managers
- **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, options?: { includeWildcard?: boolean })**: 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.
- By default, only a certificate for the exact domain is requested
- Set `includeWildcard: true` to also request a wildcard certificate (requires DNS-01 handler)
- When requesting a wildcard directly (e.g., `*.example.com`), only the wildcard certificate is requested
SmartAcme uses the `ICertManager` interface for pluggable certificate storage.
### Handling Domain Matching
### MongoCertManager
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.
Persistent storage backed by MongoDB using `@push.rocks/smartdata`:
```typescript
import { SmartacmeCertMatcher } from '@push.rocks/smartacme';
import { certmanagers } from '@push.rocks/smartacme';
const certMatcher = new SmartacmeCertMatcher();
const certDomainName = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
console.log('Certificate Domain Name:', certDomainName); // Output: example.com
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
});
```
### Testing
### MemoryCertManager
Sample tests are provided in the `test` directory. They demonstrate core functionality using the `MemoryCertManager` and built-in challenge handlers. To run all tests, use:
In-memory storage, ideal for testing or ephemeral workloads:
```typescript
import { certmanagers } from '@push.rocks/smartacme';
const certManager = new certmanagers.MemoryCertManager();
```
### Custom Certificate Manager
Implement the `ICertManager` interface for your own storage backend:
```typescript
import type { ICertManager } from '@push.rocks/smartacme';
import { Cert } from '@push.rocks/smartacme';
class RedisCertManager implements ICertManager {
async init(): Promise<void> { /* connect */ }
async retrieveCertificate(domainName: string): Promise<Cert | null> { /* lookup */ }
async storeCertificate(cert: Cert): Promise<void> { /* save */ }
async deleteCertificate(domainName: string): Promise<void> { /* remove */ }
async close(): Promise<void> { /* disconnect */ }
async wipe(): Promise<void> { /* clear all */ }
}
```
## Challenge Handlers
SmartAcme ships with three built-in ACME challenge handlers. All implement `IChallengeHandler<T>`.
### 🌐 Dns01Handler
Uses Cloudflare (or any `IConvenientDnsProvider`) to set and remove DNS TXT records for `dns-01` challenges:
```typescript
import { handlers } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
```
DNS-01 is required for wildcard certificates and works regardless of server accessibility.
### 📁 Http01Webroot
Writes challenge response files to a filesystem webroot for `http-01` validation:
```typescript
import { handlers } from '@push.rocks/smartacme';
const httpHandler = new handlers.Http01Webroot({
webroot: '/var/www/html',
});
```
The handler writes to `<webroot>/.well-known/acme-challenge/<token>` and cleans up after validation.
### 🧠 Http01MemoryHandler
In-memory HTTP-01 handler — stores challenge tokens in memory and serves them via `handleRequest()`:
```typescript
import { handlers } from '@push.rocks/smartacme';
const memHandler = new handlers.Http01MemoryHandler();
// Integrate with any HTTP server (Express, Koa, raw http, etc.)
app.use((req, res, next) => memHandler.handleRequest(req, res, next));
```
Perfect for serverless or container environments where filesystem access is limited.
### Custom Challenge Handler
Implement `IChallengeHandler<T>` for custom challenge types:
```typescript
import type { IChallengeHandler } from '@push.rocks/smartacme';
interface MyChallenge {
type: string;
token: string;
keyAuthorization: string;
}
class MyHandler implements IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] { return ['http-01']; }
async prepare(ch: MyChallenge): Promise<void> { /* ... */ }
async cleanup(ch: MyChallenge): Promise<void> { /* ... */ }
async checkWetherDomainIsSupported(domain: string): Promise<boolean> { return true; }
}
```
## Domain Matching
SmartAcme automatically maps subdomains to their base domain for certificate lookups:
```typescript
// subdomain.example.com → certificate for example.com
// *.example.com → certificate for example.com
// a.b.example.com → not supported (4+ level domains)
```
## Environment
- **`production`** — Uses LetsEncrypt production servers. Rate limits apply.
- **`integration`** — Uses LetsEncrypt staging servers. No rate limits, but certificates are not trusted by browsers. Use for testing.
## Complete Example with HTTP-01
```typescript
import { SmartAcme, certmanagers, handlers } from '@push.rocks/smartacme';
import * as http from 'http';
// In-memory handler for HTTP-01 challenges
const memHandler = new handlers.Http01MemoryHandler();
// Create HTTP server that serves ACME challenges
const server = http.createServer((req, res) => {
memHandler.handleRequest(req, res, () => {
res.statusCode = 200;
res.end('OK');
});
});
server.listen(80);
// Set up SmartAcme with in-memory storage and HTTP-01
const smartAcme = new SmartAcme({
accountEmail: 'admin@example.com',
certManager: new certmanagers.MemoryCertManager(),
environment: 'production',
challengeHandlers: [memHandler],
challengePriority: ['http-01'],
});
await smartAcme.start();
const cert = await smartAcme.getCertificateForDomain('example.com');
// Use cert.publicKey and cert.privateKey with your HTTPS server
await smartAcme.stop();
server.close();
```
## Testing
```bash
pnpm test
```
This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using `@push.rocks/smartacme`.
---
Tests use `@git.zone/tstest` with the tapbundle assertion library.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license.md](license.md) file within this repository.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**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.
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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
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.
For any legal inquiries or 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.