BREAKING CHANGE(structure): renamed classes to avoid confusion

This commit is contained in:
Philipp Kunz 2024-06-16 13:56:30 +02:00
parent 3769468b01
commit 55fa1215ae
12 changed files with 6442 additions and 4530 deletions

View File

@ -5,7 +5,7 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartacme",
"description": "A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.",
"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",
@ -19,7 +19,12 @@
"secure communication",
"domain validation",
"automation",
"crypto"
"crypto",
"MongoDB",
"dns-01 challenge",
"token-based challenges",
"certificate renewal",
"wildcard certificates"
]
}
},

View File

@ -2,7 +2,7 @@
"name": "@push.rocks/smartacme",
"version": "4.0.8",
"private": false,
"description": "A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.",
"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",
@ -25,7 +25,12 @@
"secure communication",
"domain validation",
"automation",
"crypto"
"crypto",
"MongoDB",
"dns-01 challenge",
"token-based challenges",
"certificate renewal",
"wildcard certificates"
],
"author": "Lossless GmbH",
"license": "MIT",
@ -34,28 +39,28 @@
},
"homepage": "https://code.foss.global/push.rocks/smartacme",
"dependencies": {
"@api.global/typedserver": "^3.0.20",
"@push.rocks/lik": "^6.0.12",
"@push.rocks/smartdata": "^5.0.33",
"@api.global/typedserver": "^3.0.50",
"@push.rocks/lik": "^6.0.15",
"@push.rocks/smartdata": "^5.2.4",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartdns": "^5.0.2",
"@push.rocks/smartlog": "^3.0.3",
"@push.rocks/smartlog": "^3.0.7",
"@push.rocks/smartpromise": "^4.0.3",
"@push.rocks/smartrequest": "^2.0.21",
"@push.rocks/smartstring": "^4.0.13",
"@push.rocks/smartrequest": "^2.0.22",
"@push.rocks/smartstring": "^4.0.15",
"@push.rocks/smarttime": "^4.0.6",
"@push.rocks/smartunique": "^3.0.6",
"@tsclass/tsclass": "^4.0.46",
"@push.rocks/smartunique": "^3.0.9",
"@tsclass/tsclass": "^4.0.58",
"acme-client": "^4.2.5"
},
"devDependencies": {
"@apiclient.xyz/cloudflare": "^6.0.3",
"@git.zone/tsbuild": "^2.1.66",
"@git.zone/tsbuild": "^2.1.80",
"@git.zone/tsrun": "^1.2.44",
"@git.zone/tstest": "^1.0.77",
"@push.rocks/qenv": "^6.0.4",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.11.9"
"@git.zone/tstest": "^1.0.90",
"@push.rocks/qenv": "^6.0.5",
"@push.rocks/tapbundle": "^5.0.23",
"@types/node": "^20.14.2"
},
"files": [
"ts/**/*",

File diff suppressed because it is too large Load Diff

View File

@ -1 +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'.

199
readme.md
View File

@ -1,13 +1,18 @@
```markdown
# @push.rocks/smartacme
acme with an easy yet powerful interface in TypeScript
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:
```bash
npm install @push.rocks/smartacme --save
```
or
```bash
yarn add @push.rocks/smartacme
```
@ -18,27 +23,32 @@ Make sure your project is set up to use TypeScript and supports ECMAScript Modul
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)
### 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.
### Importing @push.rocks/smartacme
### 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';
```
### Creating a SmartAcme Instance
The `SmartAcme` class is central to interaction with the ACME service. Create an instance of `SmartAcme` with your configuration:
```typescript
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: { // MongoDB connection details for storing your certificates
mongoDescriptor: {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
@ -75,26 +85,187 @@ console.log('Certificate:', myCert);
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
// Example MongoDB configuration
{
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
This documentation covers the basic setup and operation of `@push.rocks/smartacme`. The library is designed to simplify interactions with ACME services and automate certificate management tasks, enabling secure communication for your applications with minimal hassle.
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,
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

View File

@ -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');
});

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartacme',
version: '4.0.8',
description: 'acme with an easy yet powerful interface in TypeScript'
version: '5.0.0',
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
}

View File

@ -1,2 +1,2 @@
export * from './smartacme.classes.smartacme.js';
export { Cert } from './smartacme.classes.cert.js';
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';

View File

@ -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()

View File

@ -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,7 +16,7 @@ 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,
@ -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();

View File

@ -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

View File

@ -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
@ -31,7 +32,7 @@ export class SmartAcme {
// the acme client
private client: any;
private smartdns = new plugins.smartdns.Smartdns({});
public logger: plugins.smartlog.ConsoleLog;
public logger: plugins.smartlog.Smartlog;
// the account private key
private privateKey: string;
@ -41,34 +42,34 @@ 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;
constructor(optionsArg: ISmartAcmeOptions) {
this.options = optionsArg;
this.logger = new plugins.smartlog.ConsoleLog();
this.logger = plugins.smartlog.Smartlog.createForCommitinfo(commitinfo);
}
/**
* 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({
@ -107,7 +108,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);
@ -209,4 +210,8 @@ export class SmartAcme {
currentDomainInterst.destroy();
return newCertificate;
}
public async getAllCertificates(): Promise<SmartacmeCert[]> {
return SmartacmeCert.getInstances({});
}
}