@push.rocks/smartacme
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
Install
To install @push.rocks/smartacme
, you can use npm or yarn. Run one of the following commands in your project directory:
npm install @push.rocks/smartacme --save
or
yarn add @push.rocks/smartacme
Make sure your project is set up to use TypeScript and supports ECMAScript Modules (ESM).
Usage
This guide will walk you through using @push.rocks/smartacme
to set up and manage ACME (Automated Certificate Management Environment) certificates with a focus on the Let's Encrypt service, which provides free SSL certificates. The library provides an easy yet powerful TypeScript interface to automate the process of obtaining, renewing, and installing your SSL certificates.
Table of Contents
- Setting Up Your Project
- Creating a SmartAcme Instance
- Initializing SmartAcme
- Obtaining a Certificate for a Domain
- Automating DNS Challenges
- Managing Certificates
- Environmental Considerations
- 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 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:
import { SmartAcme } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
// Create a Cloudflare account client with your API token
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
// Instantiate SmartAcme with one or more ACME challenge handlers
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
},
environment: 'integration', // 'production' to request real certificates
retryOptions: {}, // optional retry/backoff settings
challengeHandlers: [
new Dns01Handler(cfAccount),
// you can add more handlers, e.g. Http01Webroot
],
challengePriority: ['dns-01'], // optional ordering of challenge types
});
Initializing SmartAcme
Before proceeding to request certificates, start your SmartAcme instance:
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:
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 handler’s prepare
, optional verify
, and cleanup
methods during the ACME order flow.
Managing Certificates
The library automatically handles fetching, renewing, and storing your certificates in a MongoDB database specified in your configuration. Ensure your MongoDB instance is accessible and properly configured for use with SmartAcme.
const mongoDescriptor = {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
};
Environmental Considerations
When creating an instance of SmartAcme
, you can specify an environment
option. This is particularly useful for testing, as you can use the integration
environment to avoid hitting rate limits and for testing your setup without issuing real certificates. Switch to production
when you are ready to obtain actual certificates.
Complete Example
Below is a complete example demonstrating how to use @push.rocks/smartacme
to obtain and manage an ACME certificate with Let's Encrypt using a DNS-01 handler:
import { SmartAcme } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Qenv } from '@push.rocks/qenv';
const qenv = new Qenv('./', './.nogit/');
const cloudflareAccount = new cloudflare.CloudflareAccount(qenv.getEnvVarOnDemand('CF_TOKEN'));
async function main() {
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
},
environment: 'integration',
challengeHandlers: [ new Dns01Handler(cloudflareAccount) ],
});
await smartAcmeInstance.start();
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
await smartAcmeInstance.stop();
}
main().catch(console.error);
Built-in Challenge Handlers
This module includes three out-of-the-box ACME challenge handlers:
-
Dns01Handler
- Uses a Cloudflare account (from
@apiclient.xyz/cloudflare
) and Smartdns client to set and remove DNS TXT records, then wait for propagation. - Import path:
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
- Example:
import * as cloudflare from '@apiclient.xyz/cloudflare'; const cfAccount = new cloudflare.CloudflareAccount('CF_TOKEN'); const dnsHandler = new Dns01Handler(cfAccount);
- Uses a Cloudflare account (from
-
Http01Webroot
- Writes ACME HTTP-01 challenge files under a file-system webroot (
/.well-known/acme-challenge/
), and removes them on cleanup. - Import path:
import { Http01Webroot } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
- Example:
const httpHandler = new Http01Webroot({ webroot: '/var/www/html' });
- Writes ACME HTTP-01 challenge files under a file-system webroot (
-
Http01MemoryHandler
- In-memory HTTP-01 challenge handler that stores and serves ACME tokens without disk I/O.
- Import path:
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
- Example (Express integration):
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:
import type { IChallengeHandler } from '@push.rocks/smartacme/ts/handlers/IChallengeHandler.js';
// Define your custom challenge payload type
interface MyChallenge { type: string; /* ... */ }
class MyCustomHandler implements IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] {
return ['my-01'];
}
// Prepare the challenge (set DNS records, start servers, etc.)
async prepare(ch: MyChallenge): Promise<void> {
// preparation logic
}
// Optional verify step after prepare
async verify?(ch: MyChallenge): Promise<void> {
// verification logic
}
// Cleanup after challenge (remove records, stop servers)
async cleanup(ch: MyChallenge): Promise<void> {
// cleanup logic
}
}
// Then register your handler:
const customInstance = new SmartAcme({
/* other options */,
challengeHandlers: [ new MyCustomHandler() ],
challengePriority: ['my-01'],
});
In this example, `Qenv` is used to manage environment variables, and `cloudflare` library is used to handle DNS challenges required by Let's Encrypt ACME protocol. The `setChallenge` and `removeChallenge` methods are essential for automating the DNS challenge process, which is a key part of domain validation.
## Additional Details
### Certificate Object
The certificate object obtained from the `getCertificateForDomain` method has the following properties:
- `id`: Unique identifier for the certificate.
- `domainName`: The domain name for which the certificate is issued.
- `created`: Timestamp of when the certificate was created.
- `privateKey`: The private key associated with the certificate.
- `publicKey`: The public key or certificate itself.
- `csr`: Certificate Signing Request (CSR) used to obtain the certificate.
- `validUntil`: Timestamp indicating the expiration date of the certificate.
### Methods Summary
- **start()**: Initializes the SmartAcme instance, sets up the ACME client, and registers the account with Let's Encrypt.
- **stop()**: Closes the MongoDB connection and performs any necessary cleanup.
- **getCertificateForDomain(domainArg: string)**: Retrieves or obtains a certificate for the specified domain name. If a valid certificate exists in the database, it is returned. Otherwise, a new certificate is requested and stored.
- **setChallenge(dnsChallenge: any)**: Automates the process of setting DNS challenge records.
- **removeChallenge(dnsChallenge: any)**: Automates the process of removing DNS challenge records.
### Handling Domain Matching
The `SmartacmeCertMatcher` class is responsible for matching certificates with the broadest scope for wildcard certificates. The `getCertificateDomainNameByDomainName` method ensures that domains at various levels are correctly matched.
```typescript
import { SmartacmeCertMatcher } from '@push.rocks/smartacme';
const certMatcher = new SmartacmeCertMatcher();
const certDomainName = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
console.log('Certificate Domain Name:', certDomainName); // Output: example.com
Testing
Automated tests can be added to ensure that the setup and functions work as expected. Using a testing framework such as tap
and mock services for DNS providers (e.g., Cloudflare), you can simulate the process of obtaining and managing certificates without the need for actual domain ownership.
import { tap, expect } from '@push.rocks/tapbundle';
import { Qenv } from '@push.rocks/qenv';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import * as smartacme from '@push.rocks/smartacme';
const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN'));
let smartAcmeInstance: smartacme.SmartAcme;
tap.test('should create a valid instance of SmartAcme', async () => {
smartAcmeInstance = new smartacme.SmartAcme({
accountEmail: 'domains@lossless.org',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
setChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
removeChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
environment: 'integration',
});
await smartAcmeInstance.init();
expect(smartAcmeInstance).toBeInstanceOf(smartacme.SmartAcme);
});
tap.test('should get a domain certificate', async () => {
const certificate = await smartAcmeInstance.getCertificateForDomain('example.com');
console.log('Certificate:', certificate);
expect(certificate).toHaveProperty('domainName', 'example.com');
});
tap.test('certmatcher should correctly match domains', async () => {
const certMatcher = new smartacme.SmartacmeCertMatcher();
const matchedCert = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
expect(matchedCert).toBe('example.com');
});
tap.test('should stop correctly', async () => {
await smartAcmeInstance.stop();
expect(smartAcmeInstance).toHaveProperty('client', null);
});
tap.start();
This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using @push.rocks/smartacme
.
License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license.md 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.