2023-07-21 18:49:18 +02:00
# @push.rocks/smartacme
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
A TypeScript-based ACME client for Let's Encrypt certificate management with a focus on simplicity and power. 🔒
2020-05-17 16:21:25 +00:00
2026-02-15 20:20:46 +00:00
## 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.
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
## Install
2024-04-14 17:18:13 +02:00
```bash
2025-05-01 11:33:55 +00:00
pnpm add @push .rocks/smartacme
2024-04-14 17:18:13 +02:00
```
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
Ensure your project uses TypeScript and ECMAScript Modules (ESM).
2025-05-01 11:33:55 +00:00
2026-02-15 20:20:46 +00:00
## Usage
2024-06-16 13:56:30 +02:00
2026-02-15 23:31:42 +00:00
`@push.rocks/smartacme` automates the full ACME certificate lifecycle — obtaining, renewing, and storing SSL/TLS certificates from Let's Encrypt. It features a built-in RFC 8555-compliant ACME protocol implementation, pluggable challenge handlers (DNS-01, HTTP-01), pluggable certificate storage backends (MongoDB, in-memory, or your own), structured error handling with smart retry logic, and built-in concurrency control with rate limiting to keep you safely within Let's Encrypt limits.
2026-02-15 20:20:46 +00:00
2026-02-15 20:43:06 +00:00
### 🚀 Quick Start
2026-02-15 20:20:46 +00:00
```typescript
import { SmartAcme, certmanagers, handlers } from '@push .rocks/smartacme';
import * as cloudflare from '@apiclient .xyz/cloudflare';
// 1. Set up a certificate manager (MongoDB or in-memory)
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
});
// 2. Set up challenge handlers
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_API_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
// 3. Create and start SmartAcme
const smartAcme = new SmartAcme({
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');
2026-02-15 20:43:06 +00:00
console.log(cert.publicKey); // PEM certificate chain
2026-02-15 20:20:46 +00:00
console.log(cert.privateKey); // PEM private key
// 5. Clean up
await smartAcme.stop();
2024-04-14 17:18:13 +02:00
```
2026-02-15 20:43:06 +00:00
### ⚙️ SmartAcme Options
2025-05-01 11:33:55 +00:00
2026-02-15 20:20:46 +00:00
```typescript
interface ISmartAcmeOptions {
2026-02-15 23:31:42 +00:00
accountEmail: string; // ACME account email
accountPrivateKey?: string; // Optional account key (auto-generated if omitted)
certManager: ICertManager; // Certificate storage backend
2026-02-15 20:43:06 +00:00
environment: 'production' | 'integration'; // Let's Encrypt environment
2026-02-15 23:31:42 +00:00
challengeHandlers: IChallengeHandler[]; // At least one handler required
challengePriority?: string[]; // e.g. ['dns-01', 'http-01']
retryOptions?: { // Optional retry/backoff config
retries?: number; // Default: 10
factor?: number; // Default: 4
minTimeoutMs?: number; // Default: 1000
maxTimeoutMs?: number; // Default: 60000
2026-02-15 20:20:46 +00:00
};
2026-02-15 23:31:42 +00:00
// Concurrency & rate limiting
maxConcurrentIssuances?: number; // Global cap on parallel ACME ops (default: 5)
maxOrdersPerWindow?: number; // Max orders in sliding window (default: 250)
orderWindowMs?: number; // Sliding window duration in ms (default: 3 hours)
2026-02-15 20:20:46 +00:00
}
2025-05-01 11:33:55 +00:00
```
2020-05-17 16:21:25 +00:00
2026-02-15 20:43:06 +00:00
### 📜 Getting Certificates
2026-02-15 20:20:46 +00:00
```typescript
// Standard certificate for a single domain
const cert = await smartAcme.getCertificateForDomain('example.com');
2026-02-15 20:43:06 +00:00
// Include wildcard coverage (requires DNS-01 handler)
// Issues a single cert covering example.com AND *.example.com
2026-02-15 20:20:46 +00:00
const certWithWildcard = await smartAcme.getCertificateForDomain('example.com', {
includeWildcard: true,
});
2020-05-17 16:21:25 +00:00
2026-02-15 20:20:46 +00:00
// Request wildcard only
const wildcardCert = await smartAcme.getCertificateForDomain('*.example.com');
```
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
Certificates are automatically cached and reused when still valid. Renewal happens automatically when a certificate is within 10 days of expiration.
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
### 📦 Certificate Object
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
The returned `SmartacmeCert` (also exported as `Cert` ) object has these properties:
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
| Property | Type | Description |
|-------------|----------|--------------------------------------|
| `id` | `string` | Unique certificate identifier |
| `domainName` | `string` | Domain the cert is issued for |
2026-02-15 20:43:06 +00:00
| `publicKey` | `string` | PEM-encoded certificate chain |
2026-02-15 20:20:46 +00:00
| `privateKey` | `string` | PEM-encoded private key |
| `csr` | `string` | Certificate Signing Request |
| `created` | `number` | Timestamp of creation |
| `validUntil` | `number` | Timestamp of expiration |
2024-04-14 17:18:13 +02:00
2026-02-15 20:43:06 +00:00
Useful methods:
```typescript
cert.isStillValid(); // true if not expired
cert.shouldBeRenewed(); // true if expires within 10 days
```
2026-02-15 23:31:42 +00:00
## 🔀 Concurrency Control & Rate Limiting
When many callers request certificates concurrently (e.g., hundreds of subdomains under the same TLD), SmartAcme automatically handles deduplication, concurrency, and rate limiting using a built-in task manager powered by `@push.rocks/taskbuffer` .
### How It Works
Three constraint layers protect your ACME account:
| Layer | What It Does | Default |
|-------|-------------|---------|
| **Per-domain mutex ** | Only one issuance runs per base domain at a time. Concurrent requests for the same domain automatically wait and receive the same certificate result. | 1 concurrent per domain |
| **Global concurrency cap ** | Limits total parallel ACME operations across all domains. | 5 concurrent |
| **Account rate limit ** | Sliding-window rate limiter that keeps you under Let's Encrypt's 300 orders/3h account limit. | 250 per 3 hours |
### 🛡️ Automatic Request Deduplication
If 100 requests come in for subdomains of `example.com` simultaneously, only **one ** ACME issuance runs. All other callers automatically wait and receive the same certificate — no duplicate orders, no wasted rate limit budget.
```typescript
// These all resolve to the same certificate with a single ACME order:
const results = await Promise.all([
smartAcme.getCertificateForDomain('app.example.com'),
smartAcme.getCertificateForDomain('api.example.com'),
smartAcme.getCertificateForDomain('cdn.example.com'),
]);
```
### ⚡ Configuring Limits
```typescript
const smartAcme = new SmartAcme({
accountEmail: 'admin@example .com',
certManager,
environment: 'production',
challengeHandlers: [dnsHandler],
maxConcurrentIssuances: 10, // Allow up to 10 parallel ACME issuances
maxOrdersPerWindow: 200, // Cap at 200 orders per window
orderWindowMs: 2 * 60 * 60_000, // 2-hour sliding window
});
```
### 📊 Observing Issuance Progress
Subscribe to the `certIssuanceEvents` stream to observe certificate issuance progress in real-time:
```typescript
smartAcme.certIssuanceEvents.subscribe((event) => {
switch (event.type) {
case 'started':
console.log(`🔄 Issuance started: ${event.task.name}` );
break;
case 'step':
console.log(`📍 Step: ${event.stepName} (${event.task.currentProgress}%)` );
break;
case 'completed':
console.log(`✅ Issuance completed: ${event.task.name}` );
break;
case 'failed':
console.log(`❌ Issuance failed: ${event.error}` );
break;
}
});
```
Each issuance goes through four steps: **prepare ** (10%) → **authorize ** (40%) → **finalize ** (30%) → **store ** (20%).
2026-02-15 20:20:46 +00:00
## Certificate Managers
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
SmartAcme uses the `ICertManager` interface for pluggable certificate storage.
2024-04-14 17:18:13 +02:00
2026-02-15 20:43:06 +00:00
### 🗄️ MongoCertManager
2025-04-27 14:28:05 +00:00
2026-02-15 20:20:46 +00:00
Persistent storage backed by MongoDB using `@push.rocks/smartdata` :
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
```typescript
import { certmanagers } from '@push .rocks/smartacme';
2025-05-01 11:33:55 +00:00
2026-02-15 20:20:46 +00:00
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
2024-04-14 17:18:13 +02:00
});
```
2026-02-15 20:43:06 +00:00
### 🧪 MemoryCertManager
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
In-memory storage, ideal for testing or ephemeral workloads:
2024-04-14 17:18:13 +02:00
```typescript
2026-02-15 20:20:46 +00:00
import { certmanagers } from '@push .rocks/smartacme';
const certManager = new certmanagers.MemoryCertManager();
2024-04-14 17:18:13 +02:00
```
2026-02-15 20:43:06 +00:00
### 🔧 Custom Certificate Manager
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
Implement the `ICertManager` interface for your own storage backend:
2024-04-14 17:18:13 +02:00
```typescript
2026-02-15 20:43:06 +00:00
import type { ICertManager, Cert } from '@push .rocks/smartacme';
2026-02-15 20:20:46 +00:00
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 */ }
}
2024-04-14 17:18:13 +02:00
```
2026-02-15 20:20:46 +00:00
## Challenge Handlers
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
SmartAcme ships with three built-in ACME challenge handlers. All implement `IChallengeHandler<T>` .
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
### 🌐 Dns01Handler
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
Uses Cloudflare (or any `IConvenientDnsProvider` ) to set and remove DNS TXT records for `dns-01` challenges:
2024-04-14 17:18:13 +02:00
```typescript
2026-02-15 20:20:46 +00:00
import { handlers } from '@push .rocks/smartacme';
import * as cloudflare from '@apiclient .xyz/cloudflare';
2025-05-01 11:33:55 +00:00
2026-02-15 20:20:46 +00:00
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
2020-05-17 16:21:25 +00:00
```
2026-02-15 20:43:06 +00:00
DNS-01 is **required ** for wildcard certificates and works regardless of server accessibility.
2025-05-01 11:38:35 +00:00
2026-02-15 20:20:46 +00:00
### 📁 Http01Webroot
2025-05-01 11:38:35 +00:00
2026-02-15 20:20:46 +00:00
Writes challenge response files to a filesystem webroot for `http-01` validation:
2025-05-01 11:38:35 +00:00
```typescript
2026-02-15 20:20:46 +00:00
import { handlers } from '@push .rocks/smartacme';
2025-05-01 11:38:35 +00:00
2026-02-15 20:20:46 +00:00
const httpHandler = new handlers.Http01Webroot({
webroot: '/var/www/html',
2025-05-01 11:38:35 +00:00
});
```
2026-02-15 20:20:46 +00:00
The handler writes to `<webroot>/.well-known/acme-challenge/<token>` and cleans up after validation.
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
### 🧠 Http01MemoryHandler
2024-04-14 17:18:13 +02:00
2026-02-15 20:20:46 +00:00
In-memory HTTP-01 handler — stores challenge tokens in memory and serves them via `handleRequest()` :
2024-06-16 13:56:30 +02:00
```typescript
2026-02-15 20:20:46 +00:00
import { handlers } from '@push .rocks/smartacme';
2025-05-01 11:33:55 +00:00
2026-02-15 20:20:46 +00:00
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.
2026-02-15 20:43:06 +00:00
### 🔧 Custom Challenge Handler
2026-02-15 20:20:46 +00:00
Implement `IChallengeHandler<T>` for custom challenge types:
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
```typescript
2026-02-15 20:43:06 +00:00
import type { handlers } from '@push .rocks/smartacme';
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
interface MyChallenge {
type: string;
token: string;
keyAuthorization: string;
}
2024-04-14 17:18:13 +02:00
2026-02-15 20:43:06 +00:00
class MyHandler implements handlers.IChallengeHandler<MyChallenge> {
2026-02-15 20:20:46 +00:00
getSupportedTypes(): string[] { return ['http-01']; }
2026-02-15 20:43:06 +00:00
async prepare(ch: MyChallenge): Promise<void> { /* set up challenge response */ }
async cleanup(ch: MyChallenge): Promise<void> { /* tear down */ }
2026-02-15 20:20:46 +00:00
async checkWetherDomainIsSupported(domain: string): Promise<boolean> { return true; }
2024-06-16 13:56:30 +02:00
}
2026-02-15 20:20:46 +00:00
```
2026-02-15 20:43:06 +00:00
## Error Handling
SmartAcme provides structured ACME error handling via the `AcmeError` class, which carries full RFC 8555 error information:
```typescript
import { AcmeError } from '@push .rocks/smartacme/ts/acme/acme.classes.error.js';
try {
const cert = await smartAcme.getCertificateForDomain('example.com');
} catch (err) {
if (err instanceof AcmeError) {
console.log(err.status); // HTTP status code (e.g. 429)
console.log(err.type); // ACME error URN (e.g. 'urn:ietf:params:acme:error:rateLimited')
console.log(err.detail); // Human-readable message
console.log(err.subproblems); // Per-identifier sub-errors (RFC 8555 §6.7.1)
console.log(err.retryAfter); // Retry-After value in seconds
console.log(err.isRateLimited); // true for 429 or rateLimited type
console.log(err.isRetryable); // true for 429, 503, 5xx, badNonce; false for 403/404/409
}
}
```
The built-in retry logic is **error-aware ** : non-retryable errors (403, 404, 409) are thrown immediately without wasting retry attempts, and rate-limited responses respect the server's `Retry-After` header instead of using blind exponential backoff.
2026-02-15 20:20:46 +00:00
## Domain Matching
SmartAcme automatically maps subdomains to their base domain for certificate lookups:
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
```
subdomain.example.com → certificate for example.com ✅
*.example.com → certificate for example.com ✅
a.b.example.com → not supported (4+ levels) ❌
2025-05-01 11:33:55 +00:00
```
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
## Environment
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
| Environment | Description |
|----------------|-------------|
| `production` | Let's Encrypt production servers. Certificates are browser-trusted. [Rate limits ](https://letsencrypt.org/docs/rate-limits/ ) apply. |
| `integration` | Let's Encrypt staging servers. No rate limits, but certificates are **not ** browser-trusted. Use for testing. |
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
## Complete Example with HTTP-01
```typescript
import { SmartAcme, certmanagers, handlers } from '@push .rocks/smartacme';
import * as http from 'http';
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
// In-memory handler for HTTP-01 challenges
const memHandler = new handlers.Http01MemoryHandler();
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
// 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);
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
// 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'],
});
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
await smartAcme.start();
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
const cert = await smartAcme.getCertificateForDomain('example.com');
// Use cert.publicKey and cert.privateKey with your HTTPS server
2024-06-16 13:56:30 +02:00
2026-02-15 20:20:46 +00:00
await smartAcme.stop();
server.close();
2024-06-16 13:56:30 +02:00
```
2026-02-15 20:43:06 +00:00
## Architecture
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
Under the hood, SmartAcme uses a fully custom RFC 8555-compliant ACME protocol implementation (no external ACME libraries). Key internal modules:
| Module | Purpose |
|--------|---------|
| `AcmeClient` | Top-level ACME facade — orders, authorizations, finalization |
| `AcmeCrypto` | RSA key generation, JWK/JWS (RFC 7515/7638), CSR via `@peculiar/x509` |
| `AcmeHttpClient` | JWS-signed HTTP transport with nonce management and structured logging |
| `AcmeError` | Structured error class with type URN, subproblems, Retry-After, retryability |
| `AcmeOrderManager` | Order lifecycle — create, poll, finalize, download certificate |
| `AcmeChallengeManager` | Key authorization computation and challenge completion |
2026-02-15 23:31:42 +00:00
| `TaskManager` | Constraint-based concurrency control, rate limiting, and request deduplication via `@push.rocks/taskbuffer` |
2024-06-16 13:56:30 +02:00
2026-02-15 20:43:06 +00:00
All cryptographic operations use `node:crypto` . The only external crypto dependency is `@peculiar/x509` for CSR generation.
2025-04-26 12:48:38 +00:00
2024-04-14 17:18:13 +02:00
## License and Legal Information
2026-02-15 20:20:46 +00:00
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE ](./LICENSE ) file.
2024-04-14 17:18:13 +02:00
**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
2026-02-15 20:20:46 +00:00
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.
2024-04-14 17:18:13 +02:00
### Company Information
2020-05-17 16:21:25 +00:00
2025-04-26 12:48:38 +00:00
Task Venture Capital GmbH
2026-02-15 20:20:46 +00:00
Registered at District Court Bremen HRB 35230 HB, Germany
2020-05-17 16:21:25 +00:00
2026-02-15 20:20:46 +00:00
For any legal inquiries or further information, please contact us via email at hello@task .vc.
2020-05-17 16:21:25 +00:00
2024-04-14 17:18:13 +02:00
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.