npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@push.rocks/smartacme

v5.0.0

Published

A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.

Downloads

13

Readme

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

```bash
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

  1. Setting Up Your Project
  2. Creating a SmartAcme Instance
  3. Initializing SmartAcme
  4. Obtaining a Certificate for a Domain
  5. Automating DNS Challenges
  6. Managing Certificates
  7. Environmental Considerations
  8. 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 from the @push.rocks/smartacme package. You'll also need to import or define interfaces for your setup options:

import { SmartAcme } from '@push.rocks/smartacme';

const smartAcmeInstance = new SmartAcme({
  accountEmail: '[email protected]', // 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: {
    mongoDbUrl: 'mongodb://yourmongoURL',
    mongoDbName: 'yourDbName',
    mongoDbPass: 'yourDbPassword',
  },
  removeChallenge: async (dnsChallenge) => {
    // Implement logic here to remove DNS challenge records
  },
  setChallenge: async (dnsChallenge) => {
    // Implement logic here to create DNS challenge records
  },
  environment: 'integration', // Use 'production' for actual certificates
});

Initializing SmartAcme

Before proceeding to request certificates, initialize your SmartAcme instance:

await smartAcmeInstance.init();

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

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.

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: '[email protected]',
  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.

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:

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: '[email protected]',
    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.

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: '[email protected]',
    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](license) 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 [email protected].

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.