smartacme/readme.md

326 lines
14 KiB
Markdown
Raw Normal View History

2023-07-21 18:49:18 +02:00
# @push.rocks/smartacme
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
2020-05-17 16:21:25 +00:00
2024-04-14 17:18:13 +02:00
## Install
2024-04-14 17:18:13 +02:00
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
```
2024-04-14 17:18:13 +02:00
or
2024-04-14 17:18:13 +02:00
```bash
yarn add @push.rocks/smartacme
```
Make sure your project is set up to use TypeScript and supports ECMAScript Modules (ESM).
2020-05-17 16:21:25 +00:00
## Usage
2024-04-14 17:18:13 +02:00
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
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)
2024-04-14 17:18:13 +02:00
### 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
2024-04-14 17:18:13 +02:00
Start by importing the `SmartAcme` class and any built-in handlers you plan to use. For example, to use DNS-01 via Cloudflare:
2024-04-14 17:18:13 +02:00
```typescript
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');
2024-04-14 17:18:13 +02:00
// Instantiate SmartAcme with one or more ACME challenge handlers
2024-04-14 17:18:13 +02:00
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
2024-04-14 17:18:13 +02:00
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. Http01Handler
],
challengePriority: ['dns-01'], // optional ordering of challenge types
2024-04-14 17:18:13 +02:00
});
```
### Initializing SmartAcme
Before proceeding to request certificates, start your SmartAcme instance:
2024-04-14 17:18:13 +02:00
```typescript
await smartAcmeInstance.start();
2024-04-14 17:18:13 +02:00
```
### 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.
2024-04-14 17:18:13 +02:00
### 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 = {
2024-04-14 17:18:13 +02:00
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
};
2020-05-17 16:21:25 +00:00
```
2024-04-14 17:18:13 +02:00
### 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:
```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',
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);
2024-04-14 17:18:13 +02:00
await smartAcmeInstance.stop();
}
main().catch(console.error);
```
## Built-in Challenge Handlers
This module includes two 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);
```
- **Http01Handler**
- Writes ACME HTTP-01 challenge files under a file-system webroot (`/.well-known/acme-challenge/`), and removes them on cleanup.
- Import path:
```typescript
import { Http01Handler } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
```
- Example:
```typescript
const httpHandler = new Http01Handler({ webroot: '/var/www/html' });
```
Both 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 `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,
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`.
---
2024-04-14 17:18:13 +02:00
## 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.
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
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
2020-05-17 16:21:25 +00:00
Task Venture Capital GmbH
2024-04-14 17:18:13 +02:00
Registered at District court Bremen HRB 35230 HB, Germany
2020-05-17 16:21:25 +00:00
2024-04-14 17:18:13 +02:00
For any legal inquiries or if you require 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.