|
|
也可以加作者好友
| 加作者好友 | 微信 QQ |
|---------|-------------------------------------------------------------|
| 二维码 |
|
## 八、捐赠
************************
支持开源,为爱发电,我已入驻爱发电
https://afdian.com/a/greper
发电权益:
1. 可加入发电专属群,可以获得作者一对一技术支持
2. 您的需求我们将优先实现,并且将作为专业版功能提供
3. 一年期专业版激活码
专业版特权对比
| 功能 | 免费版 | 专业版 |
|---------|---------------------------------------|--------------------------------|
| 免费证书申请 | 免费无限制 | 免费无限制 |
| 域名数量 | 无限制 | 无限制 |
| 证书流水线条数 | 无限制 | 无限制 |
| 站点证书监控 | 限制1条 | 无限制 |
| 自动部署插件 | 阿里云CDN、腾讯云、七牛CDN、主机部署、宝塔、1Panel等大部分插件 | 群晖 |
| 通知 | 邮件通知、自定义webhook | 邮件免配置、企微、钉钉、飞书、anpush、server酱等 |
************************
## 九、贡献代码
1. 本地开发请参考 [贡献插件向导](https://certd.docmirror.cn/guide/development/)
2. 作为贡献者,代表您同意您贡献的代码如下许可:
1. 可以调整开源协议以使其更严格或更宽松。
2. 可以用于商业用途。
感谢以下贡献者做出的贡献。
|
|
You can also add the author as a friend.
| Add Author as Friend | WeChat QQ |
|---------|-------|-------|
| QR Code |
|
## 8. Donation
************************
Support open-source projects and contribute with love. I've joined Afdian.
https://afdian.com/a/greper
Benefits of Contribution:
1. Join the exclusive contributor group and get one-on-one technical support from the author.
2. Your requests will be prioritized and implemented as professional edition features.
3. Receive a one-year professional edition activation code.
Comparison of Professional Edition Privileges:
| Feature | Free Edition | Professional Edition |
|---------|---------------------------------------|--------------------------------|
| Free Certificate Application | Unlimited for free | Unlimited for free |
| Number of Domains | Unlimited | Unlimited |
| Number of Certificate Pipelines | Unlimited | Unlimited |
| Site Certificate Monitoring | Limited to 1 | Unlimited |
| Automatic Deployment Plugins | Most plugins such as Alibaba Cloud CDN, Tencent Cloud, QiNiu CDN, Host Deployment, Baota, 1Panel | Synology |
| Notifications | Email, Custom Webhook | Email without configuration, WeChat Work, DingTalk, Lark, anpush, ServerChan, etc. |
************************
## 9. Contribute Code
1. For local development, please refer to the [Plugin Contribution Guide](https://certd.docmirror.cn/guide/development/).
2. As a contributor, you agree that your contributed code is subject to the following license:
1. The open-source license can be adjusted to be more or less restrictive.
2. It can be used for commercial purposes.
Thank you to the following contributors.
|
|
## 2. 加作者好友
| 加作者好友 | 微信 QQ |
|---------|-------------------------------------------------------------|
| 二维码 |
|
================================================
FILE: docs/guide/development/demo/access.md
================================================
# 授权插件Demo
```ts
import { AccessInput, BaseAccess, IsAccess } from '@certd/pipeline';
import { isDev } from '../../utils/env.js';
/**
* 这个注解将注册一个授权配置
* 在certd的后台管理系统中,用户可以选择添加此类型的授权
*/
@IsAccess({
name: 'demo',
title: '授权插件示例',
icon: 'clarity:plugin-line',
desc: '',
})
export class DemoAccess extends BaseAccess {
/**
* 授权属性配置
*/
@AccessInput({
title: '密钥Id',
component: {
placeholder: 'demoKeyId',
},
required: true,
})
demoKeyId = '';
/**
* 授权属性配置
*/
@AccessInput({
//标题
title: '密钥串',
component: {
//input组件的placeholder
placeholder: 'demoKeySecret',
},
//是否必填
required: true,
//改属性是否需要加密
encrypt: true,
})
//属性名称
demoKeySecret = '';
}
new DemoAccess();
```
# 阿里云授权
```ts
import { IsAccess, AccessInput, BaseAccess } from "@certd/pipeline";
@IsAccess({
name: "aliyun",
title: "阿里云授权",
desc: "",
icon: "ant-design:aliyun-outlined",
order: 0,
})
export class AliyunAccess extends BaseAccess {
@AccessInput({
title: "accessKeyId",
component: {
placeholder: "accessKeyId",
},
helper: "登录阿里云控制台->AccessKey管理页面获取。",
required: true,
})
accessKeyId = "";
@AccessInput({
title: "accessKeySecret",
component: {
placeholder: "accessKeySecret",
},
required: true,
encrypt: true,
helper: "注意:证书申请需要dns解析权限;其他阿里云插件,需要对应的权限,比如证书上传需要证书管理权限;嫌麻烦就用主账号的全量权限的accessKey",
})
accessKeySecret = "";
}
new AliyunAccess();
```
================================================
FILE: docs/guide/development/index.md
================================================
# 本地开发
欢迎贡献插件
建议nodejs版本 `20.x` 及以上
## 一、本地调试运行
### 克隆代码
```shell
# 克隆代码
git clone https://github.com/certd/certd --depth=1
#进入项目目录
cd certd
```
### 修改pnpm-workspace.yaml文件
重要:否则无法正确加载专业版的access和plugin
```yaml
# pnpm-workspace.yaml
packages:
- 'packages/**' # <--------------注释掉这一行,PR时不要提交此修改
- 'packages/ui/**'
```
### 安装依赖和初始化:
```shell
# 安装pnpm,如果提示npm命令不存在,就需要先安装nodejs
npm install -g pnpm--registry=https://registry.npmmirror.com
# 使用国内镜像源,如果有代理,就不需要
pnpm config set registry https://registry.npmmirror.com
# 安装依赖
pnpm install
# 初始化构建
pnpm init
```
### 启动 server:
```shell
cd packages/ui/certd-server
pnpm dev
```
### 启动 client:
```shell
cd packages/ui/certd-client
pnpm dev
# 会自动打开浏览器,确认正常运行
```
## 二、开发插件
进入 `packages/ui/certd-server/src/plugins`
### 1.复制`plugin-demo`目录作为你的插件目录
比如你想做`cloudflare`的插件,那么你可以复制`plugin-demo`目录,将其命名成`plugin-cloudflare`。
以下均以`plugin-cloudflare`为例进行说明,你需要将其替换成你的插件名称
### 2. access授权
如果这是一个新的平台,它应该有授权方式,比如accessKey accessSecret之类的
参考`plugin-cloudflare/access.ts` 修改为你要做的平台的`access`
这样用户就可以在`certd`后台中创建这种授权凭证了
### 3. dns-provider
如果域名是这个平台进行解析的,那么你需要实现dns-provider,(申请证书需要)
参考`plugin-cloudflare/dns-provider.ts` 修改为你要做的平台的`dns-provider`
### 4. plugin-deploy
如果这个平台有需要部署证书的地方
参考`plugin-cloudflare/plugins/plugin-deploy-to-xx.ts` 修改为你要做的平台的`plugin-deploy-to-xx`
### 5. 增加导入
在`plugin-cloudflare/index.ts`中增加你的插件的`import`
```ts
export * from './dns-provider'
export * from './access'
export * from './plugins/plugin-deploy-to-xx'
````
在`./src/plugins/index.ts`中增加`import`
```ts
export * from "./plugin-cloudflare.js"
```
### 6. 重启服务进行调试
刷新浏览器,检查你的插件是否工作正常, 确保能够正常进行证书申请和部署
## 三、提交PR
我们将尽快审核PR
## 四、 注意事项
### 1. 如何让任务报错停止
```js
// 抛出异常即可使任务停止,否则会判定为成功
throw new Error("错误信息")
```
## 五、贡献插件送激活码
- PR要求,插件功能完整,代码规范
- PR通过后,联系我们,送您一个半年期专业版激活码
================================================
FILE: docs/guide/donate/index.md
================================================
# 捐赠
************************
支持开源,为爱发电,我已入驻爱发电
https://afdian.com/a/greper
## 发电权益:
1. 可加入发电专属群,可以获得作者一对一技术支持
2. 您的需求我们将优先实现,并且将作为专业版功能提供
3. 一年期专业版激活码
## 专业版特权对比
| 功能 | 免费版 | 专业版 |
|---------|------------------------|-----------------------------|
| 免费证书申请 | 免费无限制 | 免费无限制 |
| 自动部署插件 | 阿里云CDN、腾讯云、七牛CDN、主机部署等 | 支持群晖、宝塔、1Panel等,持续开发中 |
| 证书流水线条数 | 无限制 | 无限制 |
| 站点证书监控 | 限制1条 | 无限制 |
| 通知 | 邮件通知、自定义webhook | 邮件免配置、企微、飞书、anpush、server酱等 |
## 专业版激活方式

发电后,在私信中获取激活码
************************
================================================
FILE: docs/guide/feature/cname/index.md
================================================
# CNAME代理校验方式
通过CNAME代理校验方式,可以给`Certd`不支持的域名服务商的域名申请证书。
## 1. 前言
* 申请证书是需要`校验域名所有权`的。
* `DNS校验方式`需要开发适配DNS服务商的接口
* 目前`Certd`已实现`主流域名注册商`的接口(阿里云、腾讯云、华为云、Cloudflare、西数)
* 如果域名不在这几家,`DNS校验方式`就行不通
* 那么就只能通过`CNAME代理校验方式`来实现`证书自动申请`
## 2. 原理
* 假设你要申请证书的域名叫:`cert.com` ,它是在`Certd`不支持的服务商注册的
* 假设我们还有另外一个域名叫:`proxy.com`,它是在`Certd`支持的服务商注册的。
* 当我们按照如下进行配置时
```
CNAME记录(手动、固定) TXT记录(自动、随机)
_acme-challenge.cert.com ---> xxxxx.cname.proxy.com ----> txt-record-abcdefg
```
* 证书颁发机构就可以从`_acme-challenge.cert.com`查到TXT记录 `txt-record-abcdefg`,从而完成域名所有权校验。
* 以上可以看出 `xxxxx.cname.proxy.com ----> txt-record-abcdefg` 这一段`Certd` 是可以自动添加的。
* 剩下的只需要在你的`cert.com`域名中手动添加一条固定的`CNAME解析`即可
## 3. Certd CNAME使用步骤
1. 创建证书流水线,输入你要申请证书的域名,假设就是`cert.com`,然后选择`CNAME`校验方式
2. 此时需要配置验证计划,Certd会生成一个随机的CNAME记录模版,例如:`_acme-challenge`->`xxxxxx.cname.proxy.com`

3. 您需要手动在你的`cert.com`域名中添加CNAME解析,点击验证,校验成功后就可以开始申请证书了 (此操作每个域名只需要做一次,后续可以重复使用,注意不要删除添加的CNAME记录)


4. 申请过程中,Certd会在`xxxxxx.cname.proxy.com`下自动添加TXT记录。
5. 到此即可自动化申请证书了
================================================
FILE: docs/guide/feature/safe/hidden/index.md
================================================
# 站点隐藏
* 一般来说Certd设置好之后,很少需要访问。
* 所以我们`平时`可以把`站点访问关闭`,需要的时候再打开,减少站点被攻击的风险
## 1、开启站点隐藏
`系统管理->系统设置->安全设置->站点隐藏 `

:::warning
注意保存好`解除地址`和`解除密码`
:::
## 2、临时关闭站点隐藏
访问上面的`解除地址`,输入`解除密码`,`临时解除`站点隐藏

## 3、忘记解除地址和解除密码怎么办
登录服务器,在数据库平级的目录下创建`.unhidden`命名的空白文件,即可临时解除站点隐藏
临时解除后会自动删除`.unhidden`文件,请尽快设置好新的`解除地址`和`解除密码`,并记住
================================================
FILE: docs/guide/feature/safe/index.md
================================================
# 安全特性
Certd 存储了证书以及授权等敏感数据,所以需要严格保障安全。
我们提供了以下安全特性,以及安全生产建议(请遵照建议进行生产部署以保障数据安全)
## 一、站点安全特性
### 1、 授权数据加密存储【默认开启】
* 所有的授权敏感字段会加密后存储
* 每个用户独立维护授权数据,连管理员都无权查看

星号部分为加密数据
### 2、 密码防爆破【默认开启】
* 登录失败次数过多,账号将被锁定,最高24小时(重启服务可解除锁定)
* 用户登录密码加密hash后存储,无法计算出密码明文

### 3、站点隐藏【建议开启】
* 一般来说Certd设置好之后,后续很少需要访问修改。
* 所以我们平时可以把站点访问关闭,需要的时候再打开,减少站点被攻击的风险
* 请前往 `系统管理->系统设置->安全设置->开启站点隐藏`

点击查看 [站点隐藏功能详细使用说明](./hidden/)
### 4、登录双重验证
支持2FA双重认证

### 5、数据库自动备份【建议开启】
* [自动备份设置说明](../../use/backup/)
## 二、安全生产建议
尽管`Cert`本身实现了很多安全特性,但`外部环境的安全`仍需要您来确保。
请`务必`遵循如下建议做好安全防护
* 请`务必`使用`HTTPS协议`访问本应用,避免被中间人攻击
* 请`务必`使用`web应用防火墙`防护本应用,防止XSS、SQL注入等攻击
* 请`务必`做好`服务器本身`的安全防护,防止数据库泄露
* 请`务必`做好[`数据备份`](../../use/backup/),避免数据丢失
* 请`务必`修改管理员账号用户名,且建议将admin注册为普通用户,且设置为禁用。
* 建议开启[`站点隐藏`](./hidden/)功能
================================================
FILE: docs/guide/image.md
================================================
# 镜像说明
## 国内镜像地址:
* `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest`
* `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:armv7`、`[version]-armv7`
## DockerHub地址:
* `https://hub.docker.com/r/greper/certd`
* `greper/certd:latest`
* `greper/certd:armv7`、`greper/certd:[version]-armv7`
## GitHub Packages地址:
* `ghcr.io/certd/certd:latest`
* `ghcr.io/certd/certd:armv7`、`ghcr.io/certd/certd:[version]-armv7`
*
## 镜像构建公开
镜像构建通过`Actions`自动执行,过程公开透明,请放心使用
* [点我查看镜像构建日志](https://github.com/certd/certd/actions/workflows/build-image.yml)

================================================
FILE: docs/guide/index.md
================================================
# Certd
Certd 是一款开源、免费、全自动申请和部署更新SSL证书的工具。
后缀d取自linux守护进程的命名风格,意为证书守护进程。
关键字:证书自动申请、证书自动更新、证书自动续期、证书自动续签、证书管理工具
## 1、关于证书续期
>* 实际上没有办法不改变证书文件本身情况下直接续期或者续签。
>* 我们所说的续期,其实就是按照全套流程重新申请一份新证书,然后重新部署上去。
>* 免费证书过期时间90天,以后可能还会缩短,所以自动化部署必不可少
## 2、项目特性
本项目不仅支持证书申请过程自动化,还可以自动化部署更新证书,让你的证书永不过期。
* 全自动申请证书(支持所有注册商注册的域名,支持DNS-01、HTTP-01、CNAME代理等多种域名验证方式)
* 全自动部署更新证书(目前支持部署到主机、阿里云、腾讯云等70+部署插件)
* 支持通配符域名/泛域名,支持多个域名打到一个证书上,支持pem、pfx、der、jks等多种证书格式
* 邮件通知、webhook通知、企微、钉钉、飞书、anpush等多种通知方式
* 私有化部署,数据保存本地,安装升级非常简单快捷
* 镜像由Github Actions构建,过程公开透明
* 授权加密,站点隐藏,2FA,密码防爆破等多重安全保障
* 支持SQLite,PostgreSQL、MySQL多种数据库
* 开放接口支持
* 站点证书监控
* 多用户管理

================================================
FILE: docs/guide/install/1panel/index.md
================================================
# 部署到1Panel面板
## 一、安装1Panel
https://1panel.cn/docs/installation/online_installation/
## 二、部署certd
1. 打开`docker-compose.yaml`,整个内容复制下来
https://gitee.com/certd/certd/raw/v2/docker/run/docker-compose.yaml
2. 然后到 `1Panel->容器->编排->新建编排`
输入名称,粘贴`docker-compose.yaml`原文内容

3. 点击确定,启动容器

> 默认使用sqlite数据库,数据保存在`/data/certd`目录下,您可以手动备份该目录
> certd还支持`mysql`和`postgresql`数据库,[点我了解如何切换其他数据库](../database)
3. 访问测试
http://ip:7001
https://ip:7002
默认账号密码
admin/123456
登录后请及时修改密码
## 三、升级
1. 找到容器,点击更多->升级

2. 选择强制拉取镜像,点击确认即可

## 四、数据备份
> 默认数据保存在`/data/certd`目录下,可以手动备份
> 建议配置一条 [数据库备份流水线](../../use/backup/),自动备份
## 五、备份恢复
将备份的`db.sqlite`及同目录下的其他文件一起覆盖到原来的位置,重启certd即可
================================================
FILE: docs/guide/install/baota/index.md
================================================
# 部署到宝塔面板
## 一、安装
宝塔面板支持两种方式安装Certd,请选择其中一种方式
### 1、安装宝塔面板
* 安装宝塔面板,前往 [宝塔面板](https://www.bt.cn/u/CL3JHS) 官网,选择`9.2.0`以上正式版的脚本下载安装
* 登录宝塔面板,在菜单栏中点击 Docker,首次进入会提示安装Docker服务,点击立即安装,按提示完成安装
### 2、部署certd
以下两种方式人选一种:
#### 2.1 应用商店方式一键部署【推荐】
* 在宝塔Docker应用商店中找到`certd`(要先点右上角更新应用)
* 点击安装,配置域名等基本信息即可完成安装
> 需要宝塔9.2.0及以上版本才支持
#### 2.2 容器编排方式部署
1. 打开`docker-compose.yaml`,整个内容复制下来
https://gitee.com/certd/certd/raw/v2/docker/run/docker-compose.yaml
然后到宝塔里面进到docker->容器编排->添加容器编排

点击确定,等待启动完成

> certd默认使用sqlite数据库,另外支持`mysql`和`postgresql`数据库,[点我了解如何切换其他数据库](../database)
## 二、访问应用
http://ip:7001
https://ip:7002
默认账号密码
admin/123456
登录后请及时修改密码
## 三、如何升级
宝塔升级certd非常简单
打开容器页面: `docker`->`容器编排`->`左侧选择Certd`->`更新镜像`

## 四、数据备份
部署方式不同,数据保存位置不同
### 4.1 应用商店部署方式
点击进入安装路径,数据保存在`./data`目录下,可以手动备份


### 4.2 容器编排部署方式
数据默认保存在`/data/certd`目录下,可以手动备份
### 4.3 自动备份
> 建议配置一条 [数据库备份流水线](../../use/backup/),自动备份
## 五、备份恢复
将备份的`db.sqlite`及同目录下的其他文件一起覆盖到原来的位置,重启certd即可
## 六、宝塔部署相关问题排查
### 1. 无法访问Certd
1. 确认服务器的安全规则,是否放开了对应端口
2. 确认宝塔防火墙是否放开对应端口
3. 尝试将Certd容器加入宝塔的`bridge`网络

================================================
FILE: docs/guide/install/database.md
================================================
# 切换数据库
certd支持如下几种数据库:
1. sqlite3 (默认)
2. mysql
3. postgresql
您可以按如下两种方式切换数据库
## 一、全新安装
::: tip
以下按照`docker-compose`安装方式介绍如何使用mysql或postgresql数据库
如果您使用其他方式部署,请自行修改对应的环境变量即可。
:::
### 1.1、使用mysql数据库
1. 安装mysql,创建数据库 `(注意:charset=utf8mb4, collation=utf8mb4_bin)`
2. 下载最新的docker-compose.yaml
3. 修改环境变量配置
```yaml
services:
certd:
environment:
# 使用mysql数据库,需要提前创建数据库 charset=utf8mb4, collation=utf8mb4_bin
- certd_flyway_scriptDir=./db/migration-mysql # 升级脚本目录 【照抄】
- certd_typeorm_dataSource_default_type=mysql # 数据库类型, 或者 mariadb
- certd_typeorm_dataSource_default_host=localhost # 数据库地址
- certd_typeorm_dataSource_default_port=3306 # 数据库端口
- certd_typeorm_dataSource_default_username=root # 用户名
- certd_typeorm_dataSource_default_password=yourpasswd # 密码
- certd_typeorm_dataSource_default_database=certd # 数据库名
```
4. 启动certd
```shell
docker-compose up -d
```
### 1.2、使用Postgresql数据库
1. 安装postgresql,创建数据库
2. 下载最新的docker-compose.yaml
3. 修改环境变量配置
```yaml
services:
certd:
environment:
# 使用postgresql数据库,需要提前创建数据库
- certd_flyway_scriptDir=./db/migration-pg # 升级脚本目录 【照抄】
- certd_typeorm_dataSource_default_type=postgres # 数据库类型 【照抄】
- certd_typeorm_dataSource_default_host=localhost # 数据库地址
- certd_typeorm_dataSource_default_port=5433 # 数据库端口
- certd_typeorm_dataSource_default_username=postgres # 用户名
- certd_typeorm_dataSource_default_password=yourpasswd # 密码
- certd_typeorm_dataSource_default_database=certd # 数据库名
```
4. 启动certd
```shell
docker-compose up -d
```
## 二、从旧版的sqlite切换数据库
1. 先将`旧certd`升级到最新版 (`建议:备份sqlite数据库` )
2. 按照上面全新安装方式部署一套`新的certd` (`注意:新旧版本的certd要一致`)
3. 使用数据库工具将数据从sqlite导入到mysql或postgresql (`注意:flyway_history数据表不要导入`)
4. 重启新certd
5. 确认没有问题之后,删除旧版certd
================================================
FILE: docs/guide/install/docker/index.md
================================================
# Docker方式部署
## 一、安装
### 1. 环境准备
1.1 准备一台云服务器
* 【阿里云】云服务器2核2G,新老用户同享,99元/年,续费同价!【 [立即购买](https://www.aliyun.com/benefit?scm=20140722.M_10244282._.V_1&source=5176.11533457&userCode=qya11txb )】
* 【腾讯云】云服务器2核2G,新老用户同享,99元/年,续费同价!【 [立即购买](https://cloud.tencent.com/act/cps/redirect?redirect=6094&cps_key=b3ef73330335d7a6efa4a4bbeeb6b2c9&from=console)】
1.2 安装docker、docker-compose
https://docs.docker.com/engine/install/
选择对应的操作系统,按照官方文档执行命令即可
### 2. 部署certd容器
```bash
# 随便创建一个目录
mkdir certd
# 进入目录
cd certd
# 下载docker-compose.yaml文件,或者手动下载放到certd目录下
wget https://gitee.com/certd/certd/raw/v2/docker/run/docker-compose.yaml
# 可以根据需要修改里面的配置
# 1.修改镜像版本号【可选】
# 2.配置数据保存路径【可选】
# 3.修改端口号【可选】
vi docker-compose.yaml # 【可选】
# 启动certd
docker compose up -d
```
> [手动下载docker-compose.yaml ](https://gitee.com/certd/certd/raw/v2/docker/run/docker-compose.yaml)
> 当前版本号: 
> 如果提示 没有docker compose命令,请安装docker-compose
> https://docs.docker.com/compose/install/linux/
> certd默认使用sqlite数据库,另外还支持`mysql`和`postgresql`数据库,[点我了解如何切换其他数据库](../database)
### 3. 访问测试
http://your_server_ip:7001
https://your_server_ip:7002
默认账号密码:admin/123456
记得修改密码
## 二、升级
::: warning
如果您是第一次升级certd版本,切记切记先备份一下数据
:::
### 如果使用固定版本号
1. 修改`docker-compose.yaml`中的镜像版本号
2. 运行`docker compose up -d` 即可
### 如果使用`latest`版本
```shell
#重新拉取镜像
docker pull registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest
# 重新启动容器
docker compose down
docker compose up -d
```
## 三、数据备份
> 数据默认存在`/data/certd`目录下,不用担心数据丢失
> 建议配置一条[数据库备份流水线](../../use/backup/) 自动备份
## 四、备份恢复
将备份的`db.sqlite`及同目录下的其他文件一起覆盖到原来的位置,重启certd即可
================================================
FILE: docs/guide/install/source/index.md
================================================
# 源码部署
如果没有开发基础、没有运维基础、没有`git`和`nodejs`基础,强烈不推荐此方式
## 一、源码安装
### 环境要求
- nodejs 20 及以上
### 源码启动
```shell
# 克隆代码
git clone https://github.com/certd/certd --depth=1
# git checkout v1.x.x # 当v2主干分支代码无法正常启动时,可以尝试此命令,1.x.x换成最新版本号
cd certd
# 启动服务
./start.sh
```
>如果是windows,请先安装`git for windows` ,然后右键,选择`open git bash here`打开终端,再执行`./start.sh`命令
> 数据默认保存在 `./packages/ui/certd-server/data` 目录下,注意数据备份
### 访问测试
http://your_server_ip:7001
https://your_server_ip:7002
默认账号密码:admin/123456
记得修改密码
## 二、升级
```shell
cd certd
# 确保数据安全,备份一下数据
cp -rf ./packages/ui/certd-server/data ../certd-data-backup
git pull
# 如果提示pull失败,可以尝试强制更新
# git checkout v2 -f && git pull
# 先停止旧的服务,7001是certd的默认端口
kill -9 $(lsof -t -i:7001)
# 重新编译启动
./start.sh
```
::: warning
升级certd版本前,切记切记先备份一下数据
:::
## 三、数据备份
> 数据默认保存在 `./packages/ui/certd-server/data` 目录下
> 建议配置一条[数据库备份流水线](../../use/backup/) 自动备份
## 四、备份恢复
将备份的`db.sqlite`及同目录下的其他文件覆盖到原来的位置,重启certd即可
================================================
FILE: docs/guide/install/upgrade.md
================================================
# 版本升级
## 升级方法
根据不同部署方式查看升级方法
1. [Docker方式部署升级](./docker/#二、升级)
2. [宝塔面板方式部署升级](./baota/#三、如何升级)
3. [1Panel面板方式部署升级](./1panel/#三、升级)
4. [源码方式部署](./source/#二、升级)
::: warning
如果您是第一次升级certd版本,切记切记先备份一下数据
:::
## 升级日志
可以查看最新版本号,以及所有版本的更新日志
[CHANGELOG](../changelogs/CHANGELOG.md)
## 自动升级配置
### 1. 方法一:使用watchtower监控
修改docker-compose.yaml文件增加如下配置, 使用watchtower监控自动升级
```yaml
services:
certd:
...
labels:
com.centurylinklabs.watchtower.enable: "true"
# ↓↓↓↓ --------------------------------------------------------- 自动升级,上面certd的版本号要保持为latest
certd-updater: # 添加 Watchtower 服务
image: containrrr/watchtower:latest
container_name: certd-updater
restart: unless-stopped
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# 配置 自动更新
environment:
- WATCHTOWER_CLEANUP=true # 自动清理旧版本容器
- WATCHTOWER_INCLUDE_STOPPED=false # 不更新已停止的容器
- WATCHTOWER_LABEL_ENABLE=true # 根据容器标签进行更新
- WATCHTOWER_POLL_INTERVAL=600 # 每 10 分钟检查一次更新
```
### 2. 方法二:使用Certd版本监控功能
选择Github-检查Release版本插件

按如下图填写配置

检测到新版本后执行宿主机升级命令:
```shell
# 拉取最新镜像
docker pull registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest
# 升级容器命令, 替换成你自己的certd更新命令
export RESTART_CERT='sleep 10; cd ~/deploy/certd/ ; docker compose down; docker compose up -d'
# 构造一个脚本10s后在后台执行,避免容器销毁时执行太快,导致流水线任务无法结束
nohup sh -c '$RESTART_CERT' >/dev/null 2>&1 & echo '10秒后重启' && exit
```
================================================
FILE: docs/guide/license/index.md
================================================
# 开源协议
* 本项目遵循 GNU Affero General Public License(AGPL)开源协议。
* 允许个人和公司使用、复制、修改和分发本项目,禁止任何形式的商业用途
* 未获得商业授权情况下,禁止任何对logo、版权信息及授权许可相关代码的修改。
* 如需商业授权,请联系作者。
================================================
FILE: docs/guide/link/index.md
================================================
# 我的其他项目
| 项目名称 | stars | 项目描述 |
|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------|-----------------------------------|
| [袖手AI](https://ai.handsfree.work/) | | 袖手GPT,国内可用,无需FQ,每日免费额度 |
| [fast-crud](https://gitee.com/fast-crud/fast-crud/) | AcmeClient
objectACME client
Promise.<(string\|null)>
* [.getAccountUrl()](#AcmeClient+getAccountUrl) ⇒ string
* [.createAccount([data])](#AcmeClient+createAccount) ⇒ Promise.<object>
* [.updateAccount([data])](#AcmeClient+updateAccount) ⇒ Promise.<object>
* [.updateAccountKey(newAccountKey, [data])](#AcmeClient+updateAccountKey) ⇒ Promise.<object>
* [.createOrder(data)](#AcmeClient+createOrder) ⇒ Promise.<object>
* [.getOrder(order)](#AcmeClient+getOrder) ⇒ Promise.<object>
* [.finalizeOrder(order, csr)](#AcmeClient+finalizeOrder) ⇒ Promise.<object>
* [.getAuthorizations(order)](#AcmeClient+getAuthorizations) ⇒ Promise.<Array.<object>>
* [.deactivateAuthorization(authz)](#AcmeClient+deactivateAuthorization) ⇒ Promise.<object>
* [.getChallengeKeyAuthorization(challenge)](#AcmeClient+getChallengeKeyAuthorization) ⇒ Promise.<string>
* [.verifyChallenge(authz, challenge)](#AcmeClient+verifyChallenge) ⇒ Promise
* [.completeChallenge(challenge)](#AcmeClient+completeChallenge) ⇒ Promise.<object>
* [.waitForValidStatus(item)](#AcmeClient+waitForValidStatus) ⇒ Promise.<object>
* [.getCertificate(order, [preferredChain])](#AcmeClient+getCertificate) ⇒ Promise.<string>
* [.revokeCertificate(cert, [data])](#AcmeClient+revokeCertificate) ⇒ Promise
* [.auto(opts)](#AcmeClient+auto) ⇒ Promise.<string>
### new AcmeClient(opts)
| Param | Type | Description |
| --- | --- | --- |
| opts | object | |
| opts.directoryUrl | string | ACME directory URL |
| opts.accountKey | buffer \| string | PEM encoded account private key |
| [opts.accountUrl] | string | Account URL, default: `null` |
| [opts.externalAccountBinding] | object | |
| [opts.externalAccountBinding.kid] | string | External account binding KID |
| [opts.externalAccountBinding.hmacKey] | string | External account binding HMAC key |
| [opts.backoffAttempts] | number | Maximum number of backoff attempts, default: `10` |
| [opts.backoffMin] | number | Minimum backoff attempt delay in milliseconds, default: `5000` |
| [opts.backoffMax] | number | Maximum backoff attempt delay in milliseconds, default: `30000` |
**Example**
Create ACME client instance
```js
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: 'Private key goes here',
});
```
**Example**
Create ACME client instance
```js
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: 'Private key goes here',
accountUrl: 'Optional account URL goes here',
backoffAttempts: 10,
backoffMin: 5000,
backoffMax: 30000,
});
```
**Example**
Create ACME client with external account binding
```js
const client = new acme.Client({
directoryUrl: 'https://acme-provider.example.com/directory-url',
accountKey: 'Private key goes here',
externalAccountBinding: {
kid: 'YOUR-EAB-KID',
hmacKey: 'YOUR-EAB-HMAC-KEY',
},
});
```
### acmeClient.getTermsOfServiceUrl() ⇒ Promise.<(string\|null)>
Get Terms of Service URL if available
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<(string\|null)> - ToS URL
**Example**
Get Terms of Service URL
```js
const termsOfService = client.getTermsOfServiceUrl();
if (!termsOfService) {
// CA did not provide Terms of Service
}
```
### acmeClient.getAccountUrl() ⇒ string
Get current account URL
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: string - Account URL
**Throws**:
- Error No account URL found
**Example**
Get current account URL
```js
try {
const accountUrl = client.getAccountUrl();
}
catch (e) {
// No account URL exists, need to create account first
}
```
### acmeClient.createAccount([data]) ⇒ Promise.<object>
Create a new account
https://datatracker.ietf.org/doc/html/rfc8555#section-7.3
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Account
| Param | Type | Description |
| --- | --- | --- |
| [data] | object | Request data |
**Example**
Create a new account
```js
const account = await client.createAccount({
termsOfServiceAgreed: true,
});
```
**Example**
Create a new account with contact info
```js
const account = await client.createAccount({
termsOfServiceAgreed: true,
contact: ['mailto:test@example.com'],
});
```
### acmeClient.updateAccount([data]) ⇒ Promise.<object>
Update existing account
https://datatracker.ietf.org/doc/html/rfc8555#section-7.3.2
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Account
| Param | Type | Description |
| --- | --- | --- |
| [data] | object | Request data |
**Example**
Update existing account
```js
const account = await client.updateAccount({
contact: ['mailto:foo@example.com'],
});
```
### acmeClient.updateAccountKey(newAccountKey, [data]) ⇒ Promise.<object>
Update account private key
https://datatracker.ietf.org/doc/html/rfc8555#section-7.3.5
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Account
| Param | Type | Description |
| --- | --- | --- |
| newAccountKey | buffer \| string | New PEM encoded private key |
| [data] | object | Additional request data |
**Example**
Update account private key
```js
const newAccountKey = 'New private key goes here';
const result = await client.updateAccountKey(newAccountKey);
```
### acmeClient.createOrder(data) ⇒ Promise.<object>
Create a new order
https://datatracker.ietf.org/doc/html/rfc8555#section-7.4
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Order
| Param | Type | Description |
| --- | --- | --- |
| data | object | Request data |
**Example**
Create a new order
```js
const order = await client.createOrder({
identifiers: [
{ type: 'dns', value: 'example.com' },
{ type: 'dns', value: 'test.example.com' },
],
});
```
### acmeClient.getOrder(order) ⇒ Promise.<object>
Refresh order object from CA
https://datatracker.ietf.org/doc/html/rfc8555#section-7.4
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Order
| Param | Type | Description |
| --- | --- | --- |
| order | object | Order object |
**Example**
```js
const order = { ... }; // Previously created order object
const result = await client.getOrder(order);
```
### acmeClient.finalizeOrder(order, csr) ⇒ Promise.<object>
Finalize order
https://datatracker.ietf.org/doc/html/rfc8555#section-7.4
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Order
| Param | Type | Description |
| --- | --- | --- |
| order | object | Order object |
| csr | buffer \| string | PEM encoded Certificate Signing Request |
**Example**
Finalize order
```js
const order = { ... }; // Previously created order object
const csr = { ... }; // Previously created Certificate Signing Request
const result = await client.finalizeOrder(order, csr);
```
### acmeClient.getAuthorizations(order) ⇒ Promise.<Array.<object>>
Get identifier authorizations from order
https://datatracker.ietf.org/doc/html/rfc8555#section-7.5
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<Array.<object>> - Authorizations
| Param | Type | Description |
| --- | --- | --- |
| order | object | Order |
**Example**
Get identifier authorizations
```js
const order = { ... }; // Previously created order object
const authorizations = await client.getAuthorizations(order);
authorizations.forEach((authz) => {
const { challenges } = authz;
});
```
### acmeClient.deactivateAuthorization(authz) ⇒ Promise.<object>
Deactivate identifier authorization
https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.2
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Authorization
| Param | Type | Description |
| --- | --- | --- |
| authz | object | Identifier authorization |
**Example**
Deactivate identifier authorization
```js
const authz = { ... }; // Identifier authorization resolved from previously created order
const result = await client.deactivateAuthorization(authz);
```
### acmeClient.getChallengeKeyAuthorization(challenge) ⇒ Promise.<string>
Get key authorization for ACME challenge
https://datatracker.ietf.org/doc/html/rfc8555#section-8.1
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<string> - Key authorization
| Param | Type | Description |
| --- | --- | --- |
| challenge | object | Challenge object returned by API |
**Example**
Get challenge key authorization
```js
const challenge = { ... }; // Challenge from previously resolved identifier authorization
const key = await client.getChallengeKeyAuthorization(challenge);
// Write key somewhere to satisfy challenge
```
### acmeClient.verifyChallenge(authz, challenge) ⇒ Promise
Verify that ACME challenge is satisfied
**Kind**: instance method of [AcmeClient](#AcmeClient)
| Param | Type | Description |
| --- | --- | --- |
| authz | object | Identifier authorization |
| challenge | object | Authorization challenge |
**Example**
Verify satisfied ACME challenge
```js
const authz = { ... }; // Identifier authorization
const challenge = { ... }; // Satisfied challenge
await client.verifyChallenge(authz, challenge);
```
### acmeClient.completeChallenge(challenge) ⇒ Promise.<object>
Notify CA that challenge has been completed
https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.1
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Challenge
| Param | Type | Description |
| --- | --- | --- |
| challenge | object | Challenge object returned by API |
**Example**
Notify CA that challenge has been completed
```js
const challenge = { ... }; // Satisfied challenge
const result = await client.completeChallenge(challenge);
```
### acmeClient.waitForValidStatus(item) ⇒ Promise.<object>
Wait for ACME provider to verify status on a order, authorization or challenge
https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.1
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<object> - Valid order, authorization or challenge
| Param | Type | Description |
| --- | --- | --- |
| item | object | An order, authorization or challenge object |
**Example**
Wait for valid challenge status
```js
const challenge = { ... };
await client.waitForValidStatus(challenge);
```
**Example**
Wait for valid authorization status
```js
const authz = { ... };
await client.waitForValidStatus(authz);
```
**Example**
Wait for valid order status
```js
const order = { ... };
await client.waitForValidStatus(order);
```
### acmeClient.getCertificate(order, [preferredChain]) ⇒ Promise.<string>
Get certificate from ACME order
https://datatracker.ietf.org/doc/html/rfc8555#section-7.4.2
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<string> - Certificate
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| order | object | | Order object |
| [preferredChain] | string | null | Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null` |
**Example**
Get certificate
```js
const order = { ... }; // Previously created order
const certificate = await client.getCertificate(order);
```
**Example**
Get certificate with preferred chain
```js
const order = { ... }; // Previously created order
const certificate = await client.getCertificate(order, 'DST Root CA X3');
```
### acmeClient.revokeCertificate(cert, [data]) ⇒ Promise
Revoke certificate
https://datatracker.ietf.org/doc/html/rfc8555#section-7.6
**Kind**: instance method of [AcmeClient](#AcmeClient)
| Param | Type | Description |
| --- | --- | --- |
| cert | buffer \| string | PEM encoded certificate |
| [data] | object | Additional request data |
**Example**
Revoke certificate
```js
const certificate = { ... }; // Previously created certificate
const result = await client.revokeCertificate(certificate);
```
**Example**
Revoke certificate with reason
```js
const certificate = { ... }; // Previously created certificate
const result = await client.revokeCertificate(certificate, {
reason: 4,
});
```
### acmeClient.auto(opts) ⇒ Promise.<string>
Auto mode
**Kind**: instance method of [AcmeClient](#AcmeClient)
**Returns**: Promise.<string> - Certificate
| Param | Type | Description |
| --- | --- | --- |
| opts | object | |
| opts.csr | buffer \| string | Certificate Signing Request |
| opts.challengeCreateFn | function | Function returning Promise triggered before completing ACME challenge |
| opts.challengeRemoveFn | function | Function returning Promise triggered after completing ACME challenge |
| [opts.email] | string | Account email address |
| [opts.termsOfServiceAgreed] | boolean | Agree to Terms of Service, default: `false` |
| [opts.skipChallengeVerification] | boolean | Skip internal challenge verification before notifying ACME provider, default: `false` |
| [opts.challengePriority] | Array.<string> | Array defining challenge type priority, default: `['http-01', 'dns-01']` |
| [opts.preferredChain] | string | Indicate which certificate chain is preferred if a CA offers multiple, by exact issuer common name, default: `null` |
**Example**
Order a certificate using auto mode
```js
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
altNames: ['test.example.com'],
});
const certificate = await client.auto({
csr: certificateRequest,
email: 'test@example.com',
termsOfServiceAgreed: true,
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
// Satisfy challenge here
},
challengeRemoveFn: async (authz, challenge, keyAuthorization) => {
// Clean up challenge here
},
});
```
**Example**
Order a certificate using auto mode with preferred chain
```js
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
altNames: ['test.example.com'],
});
const certificate = await client.auto({
csr: certificateRequest,
email: 'test@example.com',
termsOfServiceAgreed: true,
preferredChain: 'DST Root CA X3',
challengeCreateFn: async () => {},
challengeRemoveFn: async () => {},
});
```
## Client : object
ACME client
**Kind**: global namespace
================================================
FILE: packages/core/acme-client/docs/crypto.md
================================================
## Objects
objectNative Node.js crypto interface
Promise.<buffer>Generate a private ECDSA key
bufferGet a public key derived from a RSA or ECDSA key
stringParse body of PEM encoded object and return a Base64URL string If multiple objects are chained, the first body will be returned
objectRead domains from a Certificate Signing Request
objectRead information from a certificate If multiple certificates are chained, the first will be read
Promise.<Array.<buffer>>Create a Certificate Signing Request
Promise.<Array.<buffer>>Create a self-signed ALPN certificate for TLS-ALPN-01 challenges
booleanValidate that a ALPN certificate contains the expected key authorization
Promise.<buffer>Generate a private RSA key
Alias of createPrivateRsaKey()
objectGet a JSON Web Key derived from a RSA or ECDSA key
Array.<string>Split chain of PEM encoded objects from string into array
object
Native Node.js crypto interface
**Kind**: global namespace
## createPrivateEcdsaKey ⇒ Promise.<buffer>
Generate a private ECDSA key
**Kind**: global constant
**Returns**: Promise.<buffer> - PEM encoded private ECDSA key
| Param | Type | Description |
| --- | --- | --- |
| [namedCurve] | string | ECDSA curve name (P-256, P-384 or P-521), default `P-256` |
**Example**
Generate private ECDSA key
```js
const privateKey = await acme.crypto.createPrivateEcdsaKey();
```
**Example**
Private ECDSA key using P-384 curve
```js
const privateKey = await acme.crypto.createPrivateEcdsaKey('P-384');
```
## getPublicKey ⇒ buffer
Get a public key derived from a RSA or ECDSA key
**Kind**: global constant
**Returns**: buffer - PEM encoded public key
| Param | Type | Description |
| --- | --- | --- |
| keyPem | buffer \| string | PEM encoded private or public key |
**Example**
Get public key
```js
const publicKey = acme.crypto.getPublicKey(privateKey);
```
## getPemBodyAsB64u ⇒ string
Parse body of PEM encoded object and return a Base64URL string
If multiple objects are chained, the first body will be returned
**Kind**: global constant
**Returns**: string - Base64URL-encoded body
| Param | Type | Description |
| --- | --- | --- |
| pem | buffer \| string | PEM encoded chain or object |
## readCsrDomains ⇒ object
Read domains from a Certificate Signing Request
**Kind**: global constant
**Returns**: object - {commonName, altNames}
| Param | Type | Description |
| --- | --- | --- |
| csrPem | buffer \| string | PEM encoded Certificate Signing Request |
**Example**
Read Certificate Signing Request domains
```js
const { commonName, altNames } = acme.crypto.readCsrDomains(certificateRequest);
console.log(`Common name: ${commonName}`);
console.log(`Alt names: ${altNames.join(', ')}`);
```
## readCertificateInfo ⇒ object
Read information from a certificate
If multiple certificates are chained, the first will be read
**Kind**: global constant
**Returns**: object - Certificate info
| Param | Type | Description |
| --- | --- | --- |
| certPem | buffer \| string | PEM encoded certificate or chain |
**Example**
Read certificate information
```js
const info = acme.crypto.readCertificateInfo(certificate);
const { commonName, altNames } = info.domains;
console.log(`Not after: ${info.notAfter}`);
console.log(`Not before: ${info.notBefore}`);
console.log(`Common name: ${commonName}`);
console.log(`Alt names: ${altNames.join(', ')}`);
```
## createCsr ⇒ Promise.<Array.<buffer>>
Create a Certificate Signing Request
**Kind**: global constant
**Returns**: Promise.<Array.<buffer>> - [privateKey, certificateSigningRequest]
| Param | Type | Description |
| --- | --- | --- |
| data | object | |
| [data.keySize] | number | Size of newly created RSA private key modulus in bits, default: `2048` |
| [data.commonName] | string | FQDN of your server |
| [data.altNames] | Array.<string> | SAN (Subject Alternative Names), default: `[]` |
| [data.country] | string | 2 letter country code |
| [data.state] | string | State or province |
| [data.locality] | string | City |
| [data.organization] | string | Organization name |
| [data.organizationUnit] | string | Organizational unit name |
| [data.emailAddress] | string | Email address |
| [keyPem] | buffer \| string | PEM encoded CSR private key |
**Example**
Create a Certificate Signing Request
```js
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
altNames: ['test.example.com'],
});
```
**Example**
Certificate Signing Request with both common and alternative names
> *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
```js
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
keySize: 4096,
commonName: 'test.example.com',
altNames: ['foo.example.com', 'bar.example.com'],
});
```
**Example**
Certificate Signing Request with additional information
```js
const [certificateKey, certificateRequest] = await acme.crypto.createCsr({
altNames: ['test.example.com'],
country: 'US',
state: 'California',
locality: 'Los Angeles',
organization: 'The Company Inc.',
organizationUnit: 'IT Department',
emailAddress: 'contact@example.com',
});
```
**Example**
Certificate Signing Request with ECDSA private key
```js
const certificateKey = await acme.crypto.createPrivateEcdsaKey();
const [, certificateRequest] = await acme.crypto.createCsr({
altNames: ['test.example.com'],
}, certificateKey);
```
## createAlpnCertificate ⇒ Promise.<Array.<buffer>>
Create a self-signed ALPN certificate for TLS-ALPN-01 challenges
https://datatracker.ietf.org/doc/html/rfc8737
**Kind**: global constant
**Returns**: Promise.<Array.<buffer>> - [privateKey, certificate]
| Param | Type | Description |
| --- | --- | --- |
| authz | object | Identifier authorization |
| keyAuthorization | string | Challenge key authorization |
| [keyPem] | buffer \| string | PEM encoded CSR private key |
**Example**
Create a ALPN certificate
```js
const [alpnKey, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization);
```
**Example**
Create a ALPN certificate with ECDSA private key
```js
const alpnKey = await acme.crypto.createPrivateEcdsaKey();
const [, alpnCertificate] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization, alpnKey);
```
## isAlpnCertificateAuthorizationValid ⇒ boolean
Validate that a ALPN certificate contains the expected key authorization
**Kind**: global constant
**Returns**: boolean - True when valid
| Param | Type | Description |
| --- | --- | --- |
| certPem | buffer \| string | PEM encoded certificate |
| keyAuthorization | string | Expected challenge key authorization |
## createPrivateRsaKey([modulusLength]) ⇒ Promise.<buffer>
Generate a private RSA key
**Kind**: global function
**Returns**: Promise.<buffer> - PEM encoded private RSA key
| Param | Type | Description |
| --- | --- | --- |
| [modulusLength] | number | Size of the keys modulus in bits, default: `2048` |
**Example**
Generate private RSA key
```js
const privateKey = await acme.crypto.createPrivateRsaKey();
```
**Example**
Private RSA key with modulus size 4096
```js
const privateKey = await acme.crypto.createPrivateRsaKey(4096);
```
## createPrivateKey()
Alias of `createPrivateRsaKey()`
**Kind**: global function
## getJwk(keyPem) ⇒ object
Get a JSON Web Key derived from a RSA or ECDSA key
https://datatracker.ietf.org/doc/html/rfc7517
**Kind**: global function
**Returns**: object - JSON Web Key
| Param | Type | Description |
| --- | --- | --- |
| keyPem | buffer \| string | PEM encoded private or public key |
**Example**
Get JWK
```js
const jwk = acme.crypto.getJwk(privateKey);
```
## splitPemChain(chainPem) ⇒ Array.<string>
Split chain of PEM encoded objects from string into array
**Kind**: global function
**Returns**: Array.<string> - Array of PEM objects including headers
| Param | Type | Description |
| --- | --- | --- |
| chainPem | buffer \| string | PEM encoded object chain |
================================================
FILE: packages/core/acme-client/docs/forge.md
================================================
## Objects
objectLegacy node-forge crypto interface
DEPRECATION WARNING: This crypto interface is deprecated and will be removed from acme-client in a future
major release. Please migrate to the new acme.crypto interface at your earliest convenience.
Promise.<buffer>Create public key from a private RSA key
stringParse body of PEM encoded object from buffer or string If multiple objects are chained, the first body will be returned
Array.<string>Split chain of PEM encoded objects from buffer or string into array
Promise.<buffer>Get modulus
Promise.<buffer>Get public exponent
Promise.<object>Read domains from a Certificate Signing Request
Promise.<object>Read information from a certificate
Promise.<Array.<buffer>>Create a Certificate Signing Request
Promise.<buffer>Generate a private RSA key
object
Legacy node-forge crypto interface
DEPRECATION WARNING: This crypto interface is deprecated and will be removed from acme-client in a future
major release. Please migrate to the new `acme.crypto` interface at your earliest convenience.
**Kind**: global namespace
## createPublicKey ⇒ Promise.<buffer>
Create public key from a private RSA key
**Kind**: global constant
**Returns**: Promise.<buffer> - PEM encoded public RSA key
| Param | Type | Description |
| --- | --- | --- |
| key | buffer \| string | PEM encoded private RSA key |
**Example**
Create public key
```js
const publicKey = await acme.forge.createPublicKey(privateKey);
```
## getPemBody ⇒ string
Parse body of PEM encoded object from buffer or string
If multiple objects are chained, the first body will be returned
**Kind**: global constant
**Returns**: string - PEM body
| Param | Type | Description |
| --- | --- | --- |
| str | buffer \| string | PEM encoded buffer or string |
## splitPemChain ⇒ Array.<string>
Split chain of PEM encoded objects from buffer or string into array
**Kind**: global constant
**Returns**: Array.<string> - Array of PEM bodies
| Param | Type | Description |
| --- | --- | --- |
| str | buffer \| string | PEM encoded buffer or string |
## getModulus ⇒ Promise.<buffer>
Get modulus
**Kind**: global constant
**Returns**: Promise.<buffer> - Modulus
| Param | Type | Description |
| --- | --- | --- |
| input | buffer \| string | PEM encoded private key, certificate or CSR |
**Example**
Get modulus
```js
const m1 = await acme.forge.getModulus(privateKey);
const m2 = await acme.forge.getModulus(certificate);
const m3 = await acme.forge.getModulus(certificateRequest);
```
## getPublicExponent ⇒ Promise.<buffer>
Get public exponent
**Kind**: global constant
**Returns**: Promise.<buffer> - Exponent
| Param | Type | Description |
| --- | --- | --- |
| input | buffer \| string | PEM encoded private key, certificate or CSR |
**Example**
Get public exponent
```js
const e1 = await acme.forge.getPublicExponent(privateKey);
const e2 = await acme.forge.getPublicExponent(certificate);
const e3 = await acme.forge.getPublicExponent(certificateRequest);
```
## readCsrDomains ⇒ Promise.<object>
Read domains from a Certificate Signing Request
**Kind**: global constant
**Returns**: Promise.<object> - {commonName, altNames}
| Param | Type | Description |
| --- | --- | --- |
| csr | buffer \| string | PEM encoded Certificate Signing Request |
**Example**
Read Certificate Signing Request domains
```js
const { commonName, altNames } = await acme.forge.readCsrDomains(certificateRequest);
console.log(`Common name: ${commonName}`);
console.log(`Alt names: ${altNames.join(', ')}`);
```
## readCertificateInfo ⇒ Promise.<object>
Read information from a certificate
**Kind**: global constant
**Returns**: Promise.<object> - Certificate info
| Param | Type | Description |
| --- | --- | --- |
| cert | buffer \| string | PEM encoded certificate |
**Example**
Read certificate information
```js
const info = await acme.forge.readCertificateInfo(certificate);
const { commonName, altNames } = info.domains;
console.log(`Not after: ${info.notAfter}`);
console.log(`Not before: ${info.notBefore}`);
console.log(`Common name: ${commonName}`);
console.log(`Alt names: ${altNames.join(', ')}`);
```
## createCsr ⇒ Promise.<Array.<buffer>>
Create a Certificate Signing Request
**Kind**: global constant
**Returns**: Promise.<Array.<buffer>> - [privateKey, certificateSigningRequest]
| Param | Type | Description |
| --- | --- | --- |
| data | object | |
| [data.keySize] | number | Size of newly created private key, default: `2048` |
| [data.commonName] | string | |
| [data.altNames] | Array.<string> | default: `[]` |
| [data.country] | string | |
| [data.state] | string | |
| [data.locality] | string | |
| [data.organization] | string | |
| [data.organizationUnit] | string | |
| [data.emailAddress] | string | |
| [key] | buffer \| string | CSR private key |
**Example**
Create a Certificate Signing Request
```js
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
altNames: ['test.example.com'],
});
```
**Example**
Certificate Signing Request with both common and alternative names
> *Warning*: Certificate subject common name has been [deprecated](https://letsencrypt.org/docs/glossary/#def-CN) and its use is [discouraged](https://cabforum.org/uploads/BRv1.2.3.pdf).
```js
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
keySize: 4096,
commonName: 'test.example.com',
altNames: ['foo.example.com', 'bar.example.com'],
});
```
**Example**
Certificate Signing Request with additional information
```js
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
altNames: ['test.example.com'],
country: 'US',
state: 'California',
locality: 'Los Angeles',
organization: 'The Company Inc.',
organizationUnit: 'IT Department',
emailAddress: 'contact@example.com',
});
```
**Example**
Certificate Signing Request with predefined private key
```js
const certificateKey = await acme.forge.createPrivateKey();
const [, certificateRequest] = await acme.forge.createCsr({
altNames: ['test.example.com'],
}, certificateKey);
## createPrivateKey([size]) ⇒ Promise.<buffer>
Generate a private RSA key
**Kind**: global function
**Returns**: Promise.<buffer> - PEM encoded private RSA key
| Param | Type | Description |
| --- | --- | --- |
| [size] | number | Size of the key, default: `2048` |
**Example**
Generate private RSA key
```js
const privateKey = await acme.forge.createPrivateKey();
```
**Example**
Private RSA key with defined size
```js
const privateKey = await acme.forge.createPrivateKey(4096);
```
================================================
FILE: packages/core/acme-client/docs/upgrade-v5.md
================================================
# Upgrading to v5 of `acme-client`
This document outlines the breaking changes introduced in v5 of `acme-client`, why they were introduced and what you should look out for when upgrading your application.
First off this release drops support for Node LTS v10, v12 and v14, and the reason for that is a new native crypto interface - more on that below. Since Node v14 is still currently in maintenance mode, `acme-client` v4 will continue to receive security updates and bugfixes until (at least) Node v14 reaches its end-of-line.
## New native crypto interface
A new crypto interface has been introduced with v5, which you can find under `acme.crypto`. It uses native Node.js cryptography APIs to generate private keys, JSON Web Keys and signatures, and finally enables support for ECC/ECDSA (P-256, P384 and P521), both for account private keys and certificates. The [@peculiar/x509](https://www.npmjs.com/package/@peculiar/x509) module is used to handle generation and parsing of Certificate Signing Requests.
Full documentation of `acme.crypto` can be [found here](crypto.md).
Since the release of `acme-client` v1.0.0 the crypto interface API has remained mostly unaltered. Back then an OpenSSL CLI wrapper was used to generate keys, and very much has changed since. This has naturally resulted in a buildup of technical debt and slight API inconsistencies over time. The introduction of a new interface was a good opportunity to finally clean up these APIs.
Below you will find a table summarizing the current `acme.forge` methods, and their new `acme.crypto` replacements. A summary of the changes for each method, including examples on how to migrate, can be found following the table.
*Note: The now deprecated `acme.forge` interface is still available for use in v5, and will not be removed until a future major version, most likely v6. Should you not wish to change to the new interface right away, the following breaking changes will not immediately affect you.*
* :green_circle: = API functionality unchanged between `acme.forge` and `acme.crypto`
* :orange_circle: = Slight API changes, like depromising or renaming, action may be required
* :red_circle: = Breaking API changes or removal, action required if using these methods
| Deprecated `.forge` API | New `.crypto` API | State |
| ----------------------------- | ----------------------------- | --------------------- |
| `await createPrivateKey()` | `await createPrivateKey()` | :green_circle: |
| `await createPublicKey()` | `getPublicKey()` | :orange_circle: (1) |
| `getPemBody()` | `getPemBodyAsB64u()` | :red_circle: (2) |
| `splitPemChain()` | `splitPemChain()` | :green_circle: |
| `await getModulus()` | `getJwk()` | :red_circle: (3) |
| `await getPublicExponent()` | `getJwk()` | :red_circle: (3) |
| `await readCsrDomains()` | `readCsrDomains()` | :orange_circle: (4) |
| `await readCertificateInfo()` | `readCertificateInfo()` | :orange_circle: (4) |
| `await createCsr()` | `await createCsr()` | :green_circle: |
### 1. `createPublicKey` renamed and depromised
* The method `createPublicKey()` has been renamed to `getPublicKey()`
* No longer returns a promise, but the resulting public key directly
* This is non-breaking if called with `await`, since `await` does not require its operand to be a promise
* :orange_circle: **This is a breaking change if used with `.then()` or `.catch()`**
```js
// Before
const publicKey = await acme.forge.createPublicKey(privateKey);
// After
const publicKey = acme.crypto.getPublicKey(privateKey);
```
### 2. `getPemBody` renamed, now returns Base64URL
* Method `getPemBody()` has been renamed to `getPemBodyAsB64u()`
* Instead of a Base64-encoded PEM body, now returns a Base64URL-encoded PEM body
* :red_circle: **This is a breaking change**
```js
// Before
const body = acme.forge.getPemBody(pem);
// After
const body = acme.crypto.getPemBodyAsB64u(pem);
```
### 3. `getModulus` and `getPublicExponent` merged into `getJwk`
* Methods `getModulus()` and `getPublicExponent()` have been removed
* Replaced by new method `getJwk()`
* :red_circle: **This is a breaking change**
```js
// Before
const mod = await acme.forge.getModulus(key);
const exp = await acme.forge.getPublicExponent(key);
// After
const { e, n } = acme.crypto.getJwk(key);
```
### 4. `readCsrDomains` and `readCertificateInfo` depromised
* Methods `readCsrDomains()` and `readCertificateInfo()` no longer return promises, but their resulting payloads directly
* This is non-breaking if called with `await`, since `await` does not require its operand to be a promise
* :orange_circle: **This is a breaking change if used with `.then()` or `.catch()`**
```js
// Before
const domains = await acme.forge.readCsrDomains(csr);
const info = await acme.forge.readCertificateInfo(certificate);
// After
const domains = acme.crypto.readCsrDomains(csr);
const info = acme.crypto.readCertificateInfo(certificate);
```
================================================
FILE: packages/core/acme-client/examples/README.md
================================================
# Disclaimer
These examples should not be used as is for any production environment, as they are just proof of concepts meant for testing and to get you started. The examples are naively written and purposefully avoids important topics since they will be specific to your application and how you choose to use `acme-client`, like for example:
1. **Concurrency control**
* If implementing on-demand certificate generation
* What happens when multiple requests hit your domain at the same time?
* Ensure your application does not place multiple cert orders for the same domain at the same time by implementing some sort of exclusive lock
2. **Domain allow lists**
* If implementing on-demand certificate generation
* What happens when someone manipulates the `ServerName` or `Host` header to your service?
* Ensure your application is unable to place certificate orders for domains you do not intend, as this can quickly rate limit your account and cause a DoS
3. **Clustering**
* If using `acme-client` across a cluster of servers
* Ensure challenge responses are known to all servers in your cluster, perhaps using a database or shared storage
4. **Certificate and key storage**
* Where and how should the account key be stored and read?
* Where and how should certificates and cert keys be stored and read?
* How and when should they be renewed?
================================================
FILE: packages/core/acme-client/examples/api.js
================================================
/**
* Example of acme.Client API
*/
const acme = require('./../');
function log(m) {
process.stdout.write(`${m}\n`);
}
/**
* Function used to satisfy an ACME challenge
*
* @param {object} authz Authorization object
* @param {object} challenge Selected challenge
* @param {string} keyAuthorization Authorization key
* @returns {Promise}
*/
async function challengeCreateFn(authz, challenge, keyAuthorization) {
/* Do something here */
log(JSON.stringify(authz));
log(JSON.stringify(challenge));
log(keyAuthorization);
}
/**
* Function used to remove an ACME challenge response
*
* @param {object} authz Authorization object
* @param {object} challenge Selected challenge
* @returns {Promise}
*/
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
/* Do something here */
log(JSON.stringify(authz));
log(JSON.stringify(challenge));
log(keyAuthorization);
}
/**
* Main
*/
module.exports = async () => {
/* Init client */
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: await acme.crypto.createPrivateKey(),
});
/* Register account */
await client.createAccount({
termsOfServiceAgreed: true,
contact: ['mailto:test@example.com'],
});
/* Place new order */
const order = await client.createOrder({
identifiers: [
{ type: 'dns', value: 'example.com' },
{ type: 'dns', value: '*.example.com' },
],
});
/**
* authorizations / client.getAuthorizations(order);
* An array with one item per DNS name in the certificate order.
* All items require at least one satisfied challenge before order can be completed.
*/
const authorizations = await client.getAuthorizations(order);
const promises = authorizations.map(async (authz) => {
let challengeCompleted = false;
try {
/**
* challenges / authz.challenges
* An array of all available challenge types for a single DNS name.
* One of these challenges needs to be satisfied.
*/
const { challenges } = authz;
/* Just select any challenge */
const challenge = challenges.pop();
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
try {
/* Satisfy challenge */
await challengeCreateFn(authz, challenge, keyAuthorization);
/* Verify that challenge is satisfied */
await client.verifyChallenge(authz, challenge);
/* Notify ACME provider that challenge is satisfied */
await client.completeChallenge(challenge);
challengeCompleted = true;
/* Wait for ACME provider to respond with valid status */
await client.waitForValidStatus(challenge);
}
finally {
/* Clean up challenge response */
try {
await challengeRemoveFn(authz, challenge, keyAuthorization);
}
catch (e) {
/**
* Catch errors thrown by challengeRemoveFn() so the order can
* be finalized, even though something went wrong during cleanup
*/
}
}
}
catch (e) {
/* Deactivate pending authz when unable to complete challenge */
if (!challengeCompleted) {
try {
await client.deactivateAuthorization(authz);
}
catch (f) {
/* Catch and suppress deactivateAuthorization() errors */
}
}
throw e;
}
});
/* Wait for challenges to complete */
await Promise.all(promises);
/* Finalize order */
const [key, csr] = await acme.crypto.createCsr({
altNames: ['example.com', '*.example.com'],
});
const finalized = await client.finalizeOrder(order, csr);
const cert = await client.getCertificate(finalized);
/* Done */
log(`CSR:\n${csr.toString()}`);
log(`Private key:\n${key.toString()}`);
log(`Certificate:\n${cert.toString()}`);
};
================================================
FILE: packages/core/acme-client/examples/auto.js
================================================
/**
* Example of acme.Client.auto()
*/
// const fs = require('fs').promises;
const acme = require('./../');
function log(m) {
process.stdout.write(`${m}\n`);
}
/**
* Function used to satisfy an ACME challenge
*
* @param {object} authz Authorization object
* @param {object} challenge Selected challenge
* @param {string} keyAuthorization Authorization key
* @returns {Promise}
*/
async function challengeCreateFn(authz, challenge, keyAuthorization) {
log('Triggered challengeCreateFn()');
/* http-01 */
if (challenge.type === 'http-01') {
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`;
const fileContents = keyAuthorization;
log(`Creating challenge response for ${authz.identifier.value} at path: ${filePath}`);
/* Replace this */
log(`Would write "${fileContents}" to path "${filePath}"`);
// await fs.writeFile(filePath, fileContents);
}
/* dns-01 */
else if (challenge.type === 'dns-01') {
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
const recordValue = keyAuthorization;
log(`Creating TXT record for ${authz.identifier.value}: ${dnsRecord}`);
/* Replace this */
log(`Would create TXT record "${dnsRecord}" with value "${recordValue}"`);
// await dnsProvider.createRecord(dnsRecord, 'TXT', recordValue);
}
}
/**
* Function used to remove an ACME challenge response
*
* @param {object} authz Authorization object
* @param {object} challenge Selected challenge
* @param {string} keyAuthorization Authorization key
* @returns {Promise}
*/
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
log('Triggered challengeRemoveFn()');
/* http-01 */
if (challenge.type === 'http-01') {
const filePath = `/var/www/html/.well-known/acme-challenge/${challenge.token}`;
log(`Removing challenge response for ${authz.identifier.value} at path: ${filePath}`);
/* Replace this */
log(`Would remove file on path "${filePath}"`);
// await fs.unlink(filePath);
}
/* dns-01 */
else if (challenge.type === 'dns-01') {
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
const recordValue = keyAuthorization;
log(`Removing TXT record for ${authz.identifier.value}: ${dnsRecord}`);
/* Replace this */
log(`Would remove TXT record "${dnsRecord}" with value "${recordValue}"`);
// await dnsProvider.removeRecord(dnsRecord, 'TXT', recordValue);
}
}
/**
* Main
*/
module.exports = async () => {
/* Init client */
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: await acme.crypto.createPrivateKey(),
});
/* Create CSR */
const [key, csr] = await acme.crypto.createCsr({
altNames: ['example.com'],
});
/* Certificate */
const cert = await client.auto({
csr,
email: 'test@example.com',
termsOfServiceAgreed: true,
challengeCreateFn,
challengeRemoveFn,
});
/* Done */
log(`CSR:\n${csr.toString()}`);
log(`Private key:\n${key.toString()}`);
log(`Certificate:\n${cert.toString()}`);
};
================================================
FILE: packages/core/acme-client/examples/dns-01/README.md
================================================
# dns-01
The greatest benefit of `dns-01` is that it is the only challenge type that can be used to issue ACME wildcard certificates, however it also has a few downsides. Your DNS provider needs to offer some sort of API you can use to automate adding and removing the required `TXT` DNS records. Additionally, solving DNS challenges will be much slower than the other challenge types because of DNS propagation delays.
## How it works
When solving `dns-01` challenges, you prove ownership of a domain by serving a specific payload within a specific DNS `TXT` record from the domains authoritative nameservers. The ACME authority provides the client with a token that, along with a thumbprint of your account key, is used to generate a `base64url` encoded `SHA256` digest. This payload is then placed as a `TXT` record under DNS name `_acme-challenge.$YOUR_DOMAIN`.
Once the order is finalized, the ACME authority will lookup your domains DNS record to verify that the payload is correct. `CNAME` and `NS` records are followed, should you wish to delegate challenge response to another DNS zone or record.
## Pros and cons
* Only challenge type that can be used to issue wildcard certificates
* Your DNS provider needs to supply an API that can be used
* DNS propagation time may be slow
* Useful in instances where both port 80 and 443 are unavailable
## External links
* [https://letsencrypt.org/docs/challenge-types/#dns-01-challenge](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
* [https://datatracker.ietf.org/doc/html/rfc8555#section-8.4](https://datatracker.ietf.org/doc/html/rfc8555#section-8.4)
================================================
FILE: packages/core/acme-client/examples/dns-01/dns-01.js
================================================
/**
* Example using dns-01 challenge to generate certificates
*
* NOTE: This example is incomplete as the DNS challenge response implementation
* will be specific to your DNS providers API.
*
* NOTE: This example does not order certificates on-demand, as solving dns-01
* will likely be too slow for it to make sense. Instead, it orders a wildcard
* certificate on init before starting the HTTPS server as a demonstration.
*/
const https = require('https');
const acme = require('./../../');
const HTTPS_SERVER_PORT = 443;
const WILDCARD_DOMAIN = 'example.com';
function log(m) {
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
}
/**
* Main
*/
(async () => {
try {
/**
* Initialize ACME client
*/
log('Initializing ACME client');
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: await acme.crypto.createPrivateKey(),
});
/**
* Order wildcard certificate
*/
log(`Creating CSR for ${WILDCARD_DOMAIN}`);
const [key, csr] = await acme.crypto.createCsr({
altNames: [WILDCARD_DOMAIN, `*.${WILDCARD_DOMAIN}`],
});
log(`Ordering certificate for ${WILDCARD_DOMAIN}`);
const cert = await client.auto({
csr,
email: 'test@example.com',
termsOfServiceAgreed: true,
challengePriority: ['dns-01'],
challengeCreateFn: (authz, challenge, keyAuthorization) => {
/* TODO: Implement this */
log(`[TODO] Add TXT record key=_acme-challenge.${authz.identifier.value} value=${keyAuthorization}`);
},
challengeRemoveFn: (authz, challenge, keyAuthorization) => {
/* TODO: Implement this */
log(`[TODO] Remove TXT record key=_acme-challenge.${authz.identifier.value} value=${keyAuthorization}`);
},
});
log(`Certificate for ${WILDCARD_DOMAIN} created successfully`);
/**
* HTTPS server
*/
const requestListener = (req, res) => {
log(`HTTP 200 ${req.headers.host}${req.url}`);
res.writeHead(200);
res.end('Hello world\n');
};
const httpsServer = https.createServer({
key,
cert,
}, requestListener);
httpsServer.listen(HTTPS_SERVER_PORT, () => {
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
});
}
catch (e) {
log(`[FATAL] ${e.message}`);
process.exit(1);
}
})();
================================================
FILE: packages/core/acme-client/examples/fallback.crt
================================================
-----BEGIN CERTIFICATE-----
MIIDCTCCAfGgAwIBAgIUGwI6ZLE3HN7oRZ9BvWLde0Tsu7EwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIyMDgwMTAwNTMzMVoXDTIyMDgz
MTAwNTMzMVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEA4c7zSiY6OEp9xYZHY42FUfOLREm03NstZhd9IxFFePwe
CTTirJjmi5teKQwzBmEok0SJkanJUaMsMlOHjEykWSc4SBO4QjD349Q60044i9WS
7KHzeSqpWTG+V9jF3HOJPw843VG9hXy3ulXKcysTXzumTVQwfatCODBNkpWqMju2
N33biLgmpqwLbDSfKXS3uSVTfoHAKGT/oRepko7/0Hwr5oEmjXEbpRWRhU09KYjH
7jokRaiQRn0h216a0r4AKzSNGihNQtKJZIuwJvLFPMQYafsu9qBaCLPqDBXCwQWG
aYh6Cm3kTkADKzG1LVPB/7/Uh2d4Fck/ejR9qXRK3QIDAQABo1MwUTAdBgNVHQ4E
FgQUvyceAVDMPbW7wHwNF9px5dWfgd4wHwYDVR0jBBgwFoAUvyceAVDMPbW7wHwN
F9px5dWfgd4wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAaYkz
AOHrRirPwfkwjb+uMliGHfANrmak8r5VDQA73RLTQLRhMpf1yrb1uhH7p/CUYKap
x1C8RGQAXujoQbQOslyZA7cVLA9ASSZS6Noq7NerfGBiqxeuye+x3lIIk1EOL/rH
aBu9rrYGmlU49PlGAQSfFHkwzXti2Mp1VQv8eMOBLR49ezZIXHiPE8S3gjNymZ0G
UA13wzZCT7SG1BLmQ/cBVASG2wvhlC8IG/4vF0Xe+boSOb1vGWUtHS+MnvvRK4n5
TMUtrnxSQ/LA8AtobvzqgvQVKBSPLK6RzLE7I+Q9pWsbKTBqfyStuQrQFqafBOqN
eYfPUgiID9uvfrxLvA==
-----END CERTIFICATE-----
================================================
FILE: packages/core/acme-client/examples/fallback.key
================================================
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDhzvNKJjo4Sn3F
hkdjjYVR84tESbTc2y1mF30jEUV4/B4JNOKsmOaLm14pDDMGYSiTRImRqclRoywy
U4eMTKRZJzhIE7hCMPfj1DrTTjiL1ZLsofN5KqlZMb5X2MXcc4k/DzjdUb2FfLe6
VcpzKxNfO6ZNVDB9q0I4ME2SlaoyO7Y3fduIuCamrAtsNJ8pdLe5JVN+gcAoZP+h
F6mSjv/QfCvmgSaNcRulFZGFTT0piMfuOiRFqJBGfSHbXprSvgArNI0aKE1C0olk
i7Am8sU8xBhp+y72oFoIs+oMFcLBBYZpiHoKbeROQAMrMbUtU8H/v9SHZ3gVyT96
NH2pdErdAgMBAAECggEBAImI0FxQblOM45AkmmTDdPmWWjPspNGEWeF92wU55tOq
0+yNnqa7tmg/6JkdyhJPqTQRoazr+ifUN/4rLDtDDzMSFVCpWihOxR2qTW4YjY52
NjgU6EPbvSwLhUDiUplUcbrL3bnHqKSecxV2XYnKKdFudntRFPvmDL5GhWkL6Y8P
9KiQaYuPf4av8PR0NlWBMiZs+CBjLlnSTMAWRYj5mRSyFSEOMT7+Lvr3TqrO2/nh
0H30LXxrXXXuCbQXnVy3oSNf7TrathT2ADIrUUTdRHsLscvkEA35VtFQtWdJLtEg
sso1J7viV9YDU4niPSdHPj3ubBjAExej4qCOzatsIQ0CgYEA8L5S3ojy89g7q6vB
QuusIrjGkyM1yebDWqhEnjvlMpfrU1hCS90BM1ozZ28bjz/7PBimKL+A8BO+W0m4
2s9YbZP5aGwo18Iq86XEdtDgWtQ3NXbYkb8F8LNtyevC/UlAI/xyIRr7hDYlr/1v
jJg16DXiNLyk+uj4Q3EuwzNl8n8CgYEA8B5UUkOiufPtm+ZOq9AlBpIa+NYaahZM
h52jzMTKsFB18xsZU/ufvpKvXEu1sTeCDRo3JAHmiA6AG292Zc7W+uWRtMtlmQWE
wnoZ6hKvEkFnArLCY6Nm5Qqm1wipLwDVO3dD/CDL86siHrXK4wU7Q+bp6xbt8lDi
itz5F7p7HKMCgYAoj8iimexlTU9wczXSsqaECyHZ9JrBc9ICWkuFZY4OYi5SEpLI
+WmUX2Q9zyiTkDIiQ/zq7KkqygjOlLNCmqDJhZ8GCwMupxZZitp5MmQ6qXrL1URT
+h1kGrcqyEBIMKlP5t7L2SH7eqwK5OaAh7y9bSa5v/cEF3CM3GsGlIhevQKBgBGU
RtwW84zlnNmzDMNrY6qNe8gH9LsbktLC6cEOD0DFQz1fGIWbgGB1YL1DFbQ5uh23
c54BPZ1sYlif2m0trXOE5xvzYCbJzqRmSAto/sQ5YY9DAxREXD4cf4ZyreAxEWtf
Ge0VgZj/SGozKP1h3qrj9vAtJ5J79XnxH5NrJaQ9AoGBAM2rQrt8H2kizg4wMGRZ
0G3709W7xxlbPdm+i/jFVDayJswCr0+eMm4gGyyZL3135D0fcijxytKgg3/OpOJF
jC9vsHsE2K1ATp6eYvYjrhqJHI1m44aq/h46SfajytZQjwMT/jaApULDP2/fCBm5
6eS2WCyHyrYJyrgoYQF56nsT
-----END PRIVATE KEY-----
================================================
FILE: packages/core/acme-client/examples/http-01/README.md
================================================
# http-01
The `http-01` challenge type is the simplest to implement and should likely be your default choice, unless you either require wildcard certificates or if port 80 is unavailable for use.
## How it works
When solving `http-01` challenges, you prove ownership of a domain name by serving a specific payload from a specific URL. The ACME authority provides the client with a token that is used to generate the URL and file contents. The file must exist at `http://$YOUR_DOMAIN/.well-known/acme-challenge/$TOKEN` and contain the token and a thumbprint of your account key.
Once the order is finalized, the ACME authority will verify that the URL responds with the correct payload by sending HTTP requests before the challenge is valid. HTTP redirects are followed, and Let's Encrypt allows redirecting to HTTPS although this diverges from the ACME spec.
## Pros and cons
* Challenge must be satisfied using port 80 (HTTP)
* The simplest challenge type to implement
* Can not be used to issue wildcard certificates
* If using multiple web servers, all of them need to respond with the correct token
## External links
* [https://letsencrypt.org/docs/challenge-types/#http-01-challenge](https://letsencrypt.org/docs/challenge-types/#http-01-challenge)
* [https://datatracker.ietf.org/doc/html/rfc8555#section-8.3](https://datatracker.ietf.org/doc/html/rfc8555#section-8.3)
================================================
FILE: packages/core/acme-client/examples/http-01/http-01.js
================================================
/**
* Example using http-01 challenge to generate certificates on-demand
*/
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const tls = require('tls');
const acme = require('./../../');
const HTTP_SERVER_PORT = 80;
const HTTPS_SERVER_PORT = 443;
const VALID_DOMAINS = ['example.com', 'example.org'];
const FALLBACK_KEY = fs.readFileSync(path.join(__dirname, '..', 'fallback.key'));
const FALLBACK_CERT = fs.readFileSync(path.join(__dirname, '..', 'fallback.crt'));
const pendingDomains = {};
const challengeResponses = {};
const certificateStore = {};
function log(m) {
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
}
/**
* On-demand certificate generation using http-01
*/
async function getCertOnDemand(client, servername, attempt = 0) {
/* Invalid domain */
if (!VALID_DOMAINS.includes(servername)) {
throw new Error(`Invalid domain: ${servername}`);
}
/* Certificate exists */
if (servername in certificateStore) {
return certificateStore[servername];
}
/* Waiting on certificate order to go through */
if (servername in pendingDomains) {
if (attempt >= 10) {
throw new Error(`Gave up waiting on certificate for ${servername}`);
}
await new Promise((resolve) => { setTimeout(resolve, 1000); });
return getCertOnDemand(client, servername, (attempt + 1));
}
/* Create CSR */
log(`Creating CSR for ${servername}`);
const [key, csr] = await acme.crypto.createCsr({
altNames: [servername],
});
/* Order certificate */
log(`Ordering certificate for ${servername}`);
const cert = await client.auto({
csr,
email: 'test@example.com',
termsOfServiceAgreed: true,
challengePriority: ['http-01'],
challengeCreateFn: (authz, challenge, keyAuthorization) => {
challengeResponses[challenge.token] = keyAuthorization;
},
challengeRemoveFn: (authz, challenge) => {
delete challengeResponses[challenge.token];
},
});
/* Done, store certificate */
log(`Certificate for ${servername} created successfully`);
certificateStore[servername] = [key, cert];
delete pendingDomains[servername];
return certificateStore[servername];
}
/**
* Main
*/
(async () => {
try {
/**
* Initialize ACME client
*/
log('Initializing ACME client');
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: await acme.crypto.createPrivateKey(),
});
/**
* HTTP server
*/
const httpServer = http.createServer((req, res) => {
if (req.url.match(/\/\.well-known\/acme-challenge\/.+/)) {
const token = req.url.split('/').pop();
log(`Received challenge request for token=${token}`);
/* ACME challenge response */
if (token in challengeResponses) {
log(`Serving challenge response HTTP 200 token=${token}`);
res.writeHead(200);
res.end(challengeResponses[token]);
return;
}
/* Challenge response not found */
log(`Oops, challenge response not found for token=${token}`);
res.writeHead(404);
res.end();
return;
}
/* HTTP 302 redirect */
log(`HTTP 302 ${req.headers.host}${req.url}`);
res.writeHead(302, { Location: `https://${req.headers.host}${req.url}` });
res.end();
});
httpServer.listen(HTTP_SERVER_PORT, () => {
log(`HTTP server listening on port ${HTTP_SERVER_PORT}`);
});
/**
* HTTPS server
*/
const requestListener = (req, res) => {
log(`HTTP 200 ${req.headers.host}${req.url}`);
res.writeHead(200);
res.end('Hello world\n');
};
const httpsServer = https.createServer({
/* Fallback certificate */
key: FALLBACK_KEY,
cert: FALLBACK_CERT,
/* Serve certificate based on servername */
SNICallback: async (servername, cb) => {
try {
log(`Handling SNI request for ${servername}`);
const [key, cert] = await getCertOnDemand(client, servername);
log(`Found certificate for ${servername}, serving secure context`);
cb(null, tls.createSecureContext({ key, cert }));
}
catch (e) {
log(`[ERROR] ${e.message}`);
cb(e.message);
}
},
}, requestListener);
httpsServer.listen(HTTPS_SERVER_PORT, () => {
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
});
}
catch (e) {
log(`[FATAL] ${e.message}`);
process.exit(1);
}
})();
================================================
FILE: packages/core/acme-client/examples/tls-alpn-01/README.md
================================================
# tls-alpn-01
Responding to `tls-alpn-01` challenges using Node.js is a bit more involved than the other two challenge types, and requires a proxy (f.ex. [Nginx](https://nginx.org) or [HAProxy](https://www.haproxy.org)) in front of the Node.js service. The reason for this is that `tls-alpn-01` is solved by responding to the ACME challenge using self-signed certificates with an ALPN extension containing the challenge response.
Since we don't want users of our application to be served with these self-signed certificates, we need to split the HTTPS traffic into two different Node.js backends - one that only serves ALPN certificates for challenge responses, and the other for actual end-user traffic that serves certificates retrieved from the ACME provider. As far as I *(library author)* know, routing HTTPS traffic based on ALPN protocol can not be done purely using Node.js.
The end result should look something like this:
```text
Nginx or HAProxy (0.0.0.0:443)
*inspect requests SSL ALPN protocol*
If ALPN == acme-tls/1
-> Node.js ALPN responder (127.0.0.1:4444)
Else
-> Node.js HTTPS server (127.0.0.1:4443)
```
Example proxy configuration:
* [haproxy.cfg](haproxy.cfg) *(requires HAProxy >= v1.9.1)*
* [nginx.conf](nginx.conf) *(requires [ngx_stream_ssl_preread_module](https://nginx.org/en/docs/stream/ngx_stream_ssl_preread_module.html))*
Big thanks to [acme.sh](https://github.com/acmesh-official/acme.sh) and [dehydrated](https://github.com/dehydrated-io/dehydrated) for doing the legwork and providing Nginx and HAProxy config examples.
## How it works
When solving `tls-alpn-01` challenges, you prove ownership of a domain name by serving a specially crafted certificate over HTTPS. The ACME authority provides the client with a token that is placed into the certificates `id-pe-acmeIdentifier` extension along with a thumbprint of your account key.
Once the order is finalized, the ACME authority will verify by sending HTTPS requests to your domain with the `acme-tls/1` ALPN protocol, indicating to the server that it should serve the challenge response certificate. If the `id-pe-acmeIdentifier` extension contains the correct payload, the challenge is valid.
## Pros and cons
* Challenge must be satisfied using port 443 (HTTPS)
* Useful in instances where port 80 is unavailable
* Can not be used to issue wildcard certificates
* More complex than `http-01`, can not be solved purely using Node.js
* If using multiple web servers, all of them need to respond with the correct certificate
## External links
* [https://letsencrypt.org/docs/challenge-types/#tls-alpn-01](https://letsencrypt.org/docs/challenge-types/#tls-alpn-01)
* [https://github.com/dehydrated-io/dehydrated/blob/master/docs/tls-alpn.md](https://github.com/dehydrated-io/dehydrated/blob/master/docs/tls-alpn.md)
* [https://github.com/acmesh-official/acme.sh/wiki/TLS-ALPN-without-downtime](https://github.com/acmesh-official/acme.sh/wiki/TLS-ALPN-without-downtime)
* [https://datatracker.ietf.org/doc/html/rfc8737](https://datatracker.ietf.org/doc/html/rfc8737)
================================================
FILE: packages/core/acme-client/examples/tls-alpn-01/haproxy.cfg
================================================
##
# HTTPS listener
# - Send to ALPN responder port 4444 if protocol is acme-tls/1
# - Default to HTTPS backend port 4443
##
frontend https
mode tcp
bind :443
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
use_backend alpnresp if { req.ssl_alpn acme-tls/1 }
default_backend https
# Default HTTPS backend
backend https
mode tcp
server https 127.0.0.1:4443
# ACME tls-alpn-01 responder backend
backend alpnresp
mode tcp
server acmesh 127.0.0.1:4444
================================================
FILE: packages/core/acme-client/examples/tls-alpn-01/nginx.conf
================================================
##
# HTTPS server
# - Send to ALPN responder port 4444 if protocol is acme-tls/1
# - Default to HTTPS backend port 4443
##
stream {
map $ssl_preread_alpn_protocols $tls_port {
~\bacme-tls/1\b 4444;
default 4443;
}
server {
listen 443;
listen [::]:443;
proxy_pass 127.0.0.1:$tls_port;
ssl_preread on;
}
}
================================================
FILE: packages/core/acme-client/examples/tls-alpn-01/tls-alpn-01.js
================================================
/**
* Example using tls-alpn-01 challenge to generate certificates on-demand
*/
const fs = require('fs');
const path = require('path');
const https = require('https');
const tls = require('tls');
const acme = require('./../../');
const HTTPS_SERVER_PORT = 4443;
const ALPN_RESPONDER_PORT = 4444;
const VALID_DOMAINS = ['example.com', 'example.org'];
const FALLBACK_KEY = fs.readFileSync(path.join(__dirname, '..', 'fallback.key'));
const FALLBACK_CERT = fs.readFileSync(path.join(__dirname, '..', 'fallback.crt'));
const pendingDomains = {};
const alpnResponses = {};
const certificateStore = {};
function log(m) {
process.stdout.write(`${(new Date()).toISOString()} ${m}\n`);
}
/**
* On-demand certificate generation using tls-alpn-01
*/
async function getCertOnDemand(client, servername, attempt = 0) {
/* Invalid domain */
if (!VALID_DOMAINS.includes(servername)) {
throw new Error(`Invalid domain: ${servername}`);
}
/* Certificate exists */
if (servername in certificateStore) {
return certificateStore[servername];
}
/* Waiting on certificate order to go through */
if (servername in pendingDomains) {
if (attempt >= 10) {
throw new Error(`Gave up waiting on certificate for ${servername}`);
}
await new Promise((resolve) => { setTimeout(resolve, 1000); });
return getCertOnDemand(client, servername, (attempt + 1));
}
/* Create CSR */
log(`Creating CSR for ${servername}`);
const [key, csr] = await acme.crypto.createCsr({
altNames: [servername],
});
/* Order certificate */
log(`Ordering certificate for ${servername}`);
const cert = await client.auto({
csr,
email: 'test@example.com',
termsOfServiceAgreed: true,
challengePriority: ['tls-alpn-01'],
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
alpnResponses[authz.identifier.value] = await acme.crypto.createAlpnCertificate(authz, keyAuthorization);
},
challengeRemoveFn: (authz) => {
delete alpnResponses[authz.identifier.value];
},
});
/* Done, store certificate */
log(`Certificate for ${servername} created successfully`);
certificateStore[servername] = [key, cert];
delete pendingDomains[servername];
return certificateStore[servername];
}
/**
* Main
*/
(async () => {
try {
/**
* Initialize ACME client
*/
log('Initializing ACME client');
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.staging,
accountKey: await acme.crypto.createPrivateKey(),
});
/**
* ALPN responder
*/
const alpnResponder = https.createServer({
/* Fallback cert */
key: FALLBACK_KEY,
cert: FALLBACK_CERT,
/* Allow acme-tls/1 ALPN protocol */
ALPNProtocols: ['acme-tls/1'],
/* Serve ALPN certificate based on servername */
SNICallback: async (servername, cb) => {
try {
log(`Handling ALPN SNI request for ${servername}`);
if (!Object.keys(alpnResponses).includes(servername)) {
throw new Error(`No ALPN certificate found for ${servername}`);
}
/* Serve ALPN challenge response */
log(`Found ALPN certificate for ${servername}, serving secure context`);
cb(null, tls.createSecureContext({
key: alpnResponses[servername][0],
cert: alpnResponses[servername][1],
}));
}
catch (e) {
log(`[ERROR] ${e.message}`);
cb(e.message);
}
},
});
/* Terminate once TLS handshake has been established */
alpnResponder.on('secureConnection', (socket) => {
socket.end();
});
alpnResponder.listen(ALPN_RESPONDER_PORT, () => {
log(`ALPN responder listening on port ${ALPN_RESPONDER_PORT}`);
});
/**
* HTTPS server
*/
const requestListener = (req, res) => {
log(`HTTP 200 ${req.headers.host}${req.url}`);
res.writeHead(200);
res.end('Hello world\n');
};
const httpsServer = https.createServer({
/* Fallback cert */
key: FALLBACK_KEY,
cert: FALLBACK_CERT,
/* Serve certificate based on servername */
SNICallback: async (servername, cb) => {
try {
log(`Handling SNI request for ${servername}`);
const [key, cert] = await getCertOnDemand(client, servername);
log(`Found certificate for ${servername}, serving secure context`);
cb(null, tls.createSecureContext({ key, cert }));
}
catch (e) {
log(`[ERROR] ${e.message}`);
cb(e.message);
}
},
}, requestListener);
httpsServer.listen(HTTPS_SERVER_PORT, () => {
log(`HTTPS server listening on port ${HTTPS_SERVER_PORT}`);
});
}
catch (e) {
log(`[FATAL] ${e.message}`);
process.exit(1);
}
})();
================================================
FILE: packages/core/acme-client/package.json
================================================
{
"name": "@certd/acme-client",
"description": "Simple and unopinionated ACME client",
"private": false,
"author": "nmorsman",
"version": "1.36.10",
"type": "module",
"module": "scr/index.js",
"main": "src/index.js",
"types": "types/index.d.ts",
"license": "MIT",
"homepage": "https://github.com/publishlab/node-acme-client",
"engines": {
"node": ">= 18"
},
"files": [
"src",
"types"
],
"dependencies": {
"@certd/basic": "^1.36.10",
"@peculiar/x509": "^1.11.0",
"asn1js": "^3.0.5",
"axios": "^1.7.2",
"debug": "^4.3.5",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"lodash-es": "^4.17.21",
"node-forge": "^1.3.1",
"punycode.js": "^2.3.1"
},
"devDependencies": {
"@types/node": "^20.14.10",
"@typescript-eslint/eslint-plugin": "^8.26.1",
"@typescript-eslint/parser": "^8.26.1",
"chai": "^4.4.1",
"chai-as-promised": "^7.1.2",
"eslint": "^8.57.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^4.2.1",
"jsdoc-to-markdown": "^8.0.1",
"mocha": "^10.6.0",
"nock": "^13.5.4",
"prettier": "^2.8.8",
"tsd": "^0.31.1",
"typescript": "^5.4.2"
},
"scripts": {
"build-docs": "jsdoc2md src/client.js > docs/client.md && jsdoc2md src/crypto/index.js > docs/crypto.md && jsdoc2md src/crypto/forge.js > docs/forge.md",
"lint": "eslint .",
"lint-types": "tsd",
"prepublishOnly": "npm run build-docs",
"test": "mocha -t 60000 \"test/setup.js\" \"test/**/*.spec.js\"",
"pub": "npm publish"
},
"repository": {
"type": "git",
"url": "https://github.com/publishlab/node-acme-client"
},
"keywords": [
"acme",
"client",
"lets",
"encrypt",
"acmev2",
"boulder"
],
"bugs": {
"url": "https://github.com/publishlab/node-acme-client/issues"
},
"gitHead": "085bdf5cfa9140903611aa12cdd2542d05aba321"
}
================================================
FILE: packages/core/acme-client/src/api.js
================================================
/**
* ACME API client
*/
import * as util from './util.js';
/**
* AcmeApi
*
* @class
* @param {HttpClient} httpClient
*/
class AcmeApi {
constructor(httpClient, accountUrl = null) {
this.http = httpClient;
this.accountUrl = accountUrl;
}
getLocationFromHeader(resp) {
let locationUrl = resp.headers.location;
const mapping = this.http.urlMapping;
if (mapping.mappings) {
// eslint-disable-next-line guard-for-in,no-restricted-syntax
for (const key in mapping.mappings) {
const url = mapping.mappings[key];
if (locationUrl.indexOf(url) > -1) {
locationUrl = locationUrl.replace(url, key);
}
}
}
console.log(locationUrl, mapping);
return locationUrl;
}
/**
* Get account URL
*
* @private
* @returns {string} Account URL
*/
getAccountUrl() {
if (!this.accountUrl) {
throw new Error('No account URL found, register account first');
}
return this.accountUrl;
}
/**
* ACME API request
*
* @private
* @param {string} url Request URL
* @param {object} [payload] Request payload, default: `null`
* @param {number[]} [validStatusCodes] Array of valid HTTP response status codes, default: `[]`
* @param {object} [opts]
* @param {boolean} [opts.includeJwsKid] Include KID instead of JWK in JWS header, default: `true`
* @param {boolean} [opts.includeExternalAccountBinding] Include EAB in request, default: `false`
* @returns {Promise