Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a865fb89e0 | |||
| cfc0695c8a | |||
| 68178366d5 | |||
| 52e1295fd2 | |||
| e968f8a039 | |||
| cf4b758800 | |||
| 3fa34fa373 | |||
| 086eea1aa2 | |||
| dcc89f0088 | |||
| 695a515990 | |||
| 01f7018540 | |||
| 3cee6c534a | |||
| 47d1609a49 | |||
| d69eb73afc | |||
| 0a1d617ce3 | |||
| f78b50757c | |||
| 0e6bbc5be6 | |||
| 10511b4293 | |||
| d456876de7 | |||
| fe495a5f03 | |||
| 88ba970494 | |||
| 1e7e1739b8 | |||
| 0c6da9ff74 |
92
changelog.md
92
changelog.md
@@ -1,5 +1,97 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2026-02-15 - 9.1.0 - feat(smartacme)
|
||||||
|
Integrate @push.rocks/taskbuffer TaskManager to coordinate ACME certificate issuance with per-domain mutex, global concurrency cap, and account-level rate limiting; refactor issuance flow into a single reusable cert-issuance task, expose issuance events, and update lifecycle to start/stop the TaskManager. Add configuration for concurrent issuances and sliding-window order limits, export taskbuffer types/plugins, and update tests and docs accordingly.
|
||||||
|
|
||||||
|
- Added dependency @push.rocks/taskbuffer and re-exported ITaskEvent/ITaskMetadata in ts/index.ts; also imported/exported taskbuffer in ts/plugins.ts.
|
||||||
|
- Replaced interestMap coordination with TaskManager + TaskConstraintGroup(s): 'cert-domain-mutex' (per-domain mutex, resultSharingMode: 'share-latest'), 'acme-global-concurrency' (global concurrency cap), and 'acme-account-rate-limit' (sliding-window rate limiter).
|
||||||
|
- Introduced a single reusable Task named 'cert-issuance' and moved the ACME issuance flow into performCertificateIssuance(), splitting progress into named steps (prepare/authorize/finalize/store) and using notifyStep() for observable progress.
|
||||||
|
- Exposed certIssuanceEvents via SmartAcme.certIssuanceEvents and wired TaskManager.start()/stop() into SmartAcme.start()/stop().
|
||||||
|
- Added new ISmartAcmeOptions: maxConcurrentIssuances, maxOrdersPerWindow, orderWindowMs to control concurrency and rate limiting.
|
||||||
|
- Updated tests to remove interestMap stubs and adapt to the taskbuffer-based flow; cleaned up client/retry stubbing in tests.
|
||||||
|
- Updated readme.hints.md with guidance on concurrency, rate limiting, and taskbuffer integration.
|
||||||
|
|
||||||
|
## 2026-02-15 - 9.0.1 - fix(acme-http-client)
|
||||||
|
Destroy keep-alive HTTP agents and DNS client on shutdown to allow process exit; add destroy() on AcmeHttpClient and AcmeClient, wire agents into requests, and call client/smartdns destroy during SmartAcme.stop; documentation clarifications and expanded README (error handling, examples, default retry values).
|
||||||
|
|
||||||
|
- ts/acme/acme.classes.http-client.ts: added per-protocol http/https agents (keepAlive: false), use agent for outgoing requests, and added destroy() to explicitly destroy agents and free sockets.
|
||||||
|
- ts/acme/acme.classes.client.ts: added destroy() that forwards to the HTTP client to allow transport cleanup.
|
||||||
|
- ts/smartacme.classes.smartacme.ts: SmartAcme.stop now calls client.destroy() and smartdns.destroy() (when present) to ensure child processes and sockets are terminated before exit; also ensures certmanager.close() is awaited.
|
||||||
|
- readme.md: documentation improvements and clarifications (Let’s Encrypt spelling, added RFC 8555 compliance note, error handling / AcmeError usage examples, default retry parameter docs, UI/emoji improvements, and other wording/formatting updates).
|
||||||
|
|
||||||
|
## 2026-02-15 - 9.0.0 - BREAKING CHANGE(acme)
|
||||||
|
Replace external acme-client with a built-in RFC8555-compliant ACME implementation and update public APIs accordingly
|
||||||
|
|
||||||
|
- Add complete TypeScript ACME implementation under ts/acme (AcmeClient, AcmeCrypto, AcmeHttpClient, AcmeAccount, AcmeOrderManager, AcmeChallengeManager, AcmeError, interfaces, ACME_DIRECTORY_URLS).
|
||||||
|
- Implement JWK/JWK-thumbprint, JWS creation, nonce management, bad-nonce retries, Retry-After handling, CSR generation via @peculiar/x509 and node:crypto.
|
||||||
|
- Update SmartAcme to use the new AcmeClient/AcmeCrypto API (e.g. plugins.acme.AcmeClient, accountKeyPem) and add AcmeError-aware retry/backoff logic.
|
||||||
|
- Remove dependency on the external acme-client and other unused packages; add @peculiar/x509 and bump multiple dependency/devDependency versions.
|
||||||
|
- Add/adjust tests (unit tests for crypto, challenge, error handling) and update test imports to @git.zone/tstest; update README/readme.hints and npmextra.json to reflect implementation and publishing changes.
|
||||||
|
|
||||||
|
## 2025-05-19 - 8.0.0 - BREAKING CHANGE(smartacme)
|
||||||
|
Make wildcard certificates opt-in to fix HTTP-01 only configurations
|
||||||
|
|
||||||
|
- BREAKING CHANGE: Wildcard certificates are no longer automatically requested for all domains
|
||||||
|
- Added 'includeWildcard' option to getCertificateForDomain() to explicitly request wildcard certificates
|
||||||
|
- HTTP-01 only configurations now work correctly as they do not try to request wildcard certificates automatically
|
||||||
|
- Updated certificate CSR generation to match the requested domain configuration
|
||||||
|
|
||||||
|
## 2025-05-19 - 7.4.0 - feat(smartacme)
|
||||||
|
Make wildcard certificates opt-in to fix HTTP-01 only configurations
|
||||||
|
|
||||||
|
- BREAKING CHANGE: Wildcard certificates are no longer automatically requested for all domains
|
||||||
|
- Added `includeWildcard` option to `getCertificateForDomain()` to explicitly request wildcards
|
||||||
|
- HTTP-01 only configurations now work correctly as they no longer attempt wildcard certificates
|
||||||
|
- Wildcard certificates require DNS-01 handler and must be explicitly requested
|
||||||
|
- Updated certificate CSR generation to match the requested domain configuration
|
||||||
|
|
||||||
|
## 2025-05-18 - 7.3.4 - fix(smartacme)
|
||||||
|
Refine documentation and tests for improved clarity in ACME certificate management
|
||||||
|
|
||||||
|
- Enhanced the README with detailed usage, configuration, and example sections
|
||||||
|
- Refined test cases for certificate matching and challenge handlers across DNS-01 and HTTP-01
|
||||||
|
- Updated TypeScript definitions and inline comments for better developer experience
|
||||||
|
|
||||||
|
## 2025-05-05 - 7.3.3 - fix(SmartAcme)
|
||||||
|
Remove duplicate challengeHandlers declaration from SmartAcme class
|
||||||
|
|
||||||
|
- Eliminated the redundant private declaration of challengeHandlers since it is already defined as a public property
|
||||||
|
- Ensures a single source of truth and clearer interface for challenge handler configuration
|
||||||
|
|
||||||
|
## 2025-05-05 - 7.3.2 - fix(test)
|
||||||
|
Add missing checkWetherDomainIsSupported implementation to DummyHandler for interface compliance in tests
|
||||||
|
|
||||||
|
- Implemented the missing checkWetherDomainIsSupported method in the DummyHandler to satisfy IChallengeHandler interface requirements
|
||||||
|
- Ensured that tests now correctly instantiate the DummyHandler without interface errors
|
||||||
|
|
||||||
|
## 2025-05-05 - 7.3.1 - fix(core)
|
||||||
|
Refactor import paths and update dependency references
|
||||||
|
|
||||||
|
- Replaced deprecated 'smartacme.plugins.js' with the new 'plugins.js' across cert managers, handlers, and core classes
|
||||||
|
- Added missing dependencies (@push.rocks/smartfile and @push.rocks/smartnetwork) in package.json
|
||||||
|
- Updated HTTP challenge handlers to include domain support checks via checkWetherDomainIsSupported
|
||||||
|
- Adjusted import paths in MongoCertManager, MemoryCertManager, and DNS-01 handler for consistency
|
||||||
|
|
||||||
|
## 2025-05-05 - 7.3.0 - feat(index)
|
||||||
|
Bump @tsclass/tsclass to 9.2.0 and update module exports to include handlers
|
||||||
|
|
||||||
|
- Upgrade @tsclass/tsclass dependency from 9.1.0 to 9.2.0 in package.json
|
||||||
|
- Add explicit export of handlers in ts/index.ts to improve module accessibility
|
||||||
|
|
||||||
|
## 2025-05-05 - 7.2.5 - fix(smartacme)
|
||||||
|
Refactor module exports and update wildcard certificate support documentation
|
||||||
|
|
||||||
|
- Updated readme.plan.md to streamline and remove obsolete wildcard plan details
|
||||||
|
- Normalized certmanager imports by consolidating exports in ts/index.ts and updating tests accordingly
|
||||||
|
- Reordered ISmartAcmeOptions interface properties for clarity (accountEmail moved to the top)
|
||||||
|
|
||||||
|
## 2025-05-04 - 7.2.4 - fix(test)
|
||||||
|
Refactor wildcard certificate test to properly stub SmartAcme.start and getCertificateForDomain for robust integration.
|
||||||
|
|
||||||
|
- Temporarily override SmartAcme.start and getCertificateForDomain to simulate wildcard certificate behavior.
|
||||||
|
- Restore original prototype methods post-test to prevent side effects.
|
||||||
|
- Improve test clarity for wildcard certificate integration.
|
||||||
|
|
||||||
## 2025-05-01 - 7.2.3 - fix(docs)
|
## 2025-05-01 - 7.2.3 - fix(docs)
|
||||||
Improve certificate manager documentation with detailed examples and custom implementation guide
|
Improve certificate manager documentation with detailed examples and custom implementation guide
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"gitzone": {
|
"@git.zone/cli": {
|
||||||
"projectType": "npm",
|
"projectType": "npm",
|
||||||
"module": {
|
"module": {
|
||||||
"githost": "code.foss.global",
|
"githost": "code.foss.global",
|
||||||
@@ -26,13 +26,19 @@
|
|||||||
"certificate renewal",
|
"certificate renewal",
|
||||||
"wildcard certificates"
|
"wildcard certificates"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
"release": {
|
||||||
|
"registries": [
|
||||||
|
"https://verdaccio.lossless.digital",
|
||||||
|
"https://registry.npmjs.org"
|
||||||
|
],
|
||||||
|
"accessLevel": "public"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"npmci": {
|
"@git.zone/tsdoc": {
|
||||||
"npmGlobalTools": [],
|
|
||||||
"npmAccessLevel": "public"
|
|
||||||
},
|
|
||||||
"tsdoc": {
|
|
||||||
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
|
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
|
||||||
|
},
|
||||||
|
"@ship.zone/szci": {
|
||||||
|
"npmGlobalTools": []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
36
package.json
36
package.json
@@ -1,14 +1,14 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartacme",
|
"name": "@push.rocks/smartacme",
|
||||||
"version": "7.2.3",
|
"version": "9.1.0",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
|
"description": "A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
"typings": "dist_ts/index.d.ts",
|
"typings": "dist_ts/index.d.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/ --verbose --logfile --timeout 600)",
|
||||||
"build": "(tsbuild --web --allowimplicitany)",
|
"build": "(tsbuild)",
|
||||||
"buildDocs": "tsdoc"
|
"buildDocs": "tsdoc"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -39,28 +39,26 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://code.foss.global/push.rocks/smartacme#readme",
|
"homepage": "https://code.foss.global/push.rocks/smartacme#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@api.global/typedserver": "^3.0.74",
|
"@apiclient.xyz/cloudflare": "^7.1.0",
|
||||||
"@apiclient.xyz/cloudflare": "^6.4.1",
|
"@peculiar/x509": "^1.14.3",
|
||||||
"@push.rocks/lik": "^6.2.2",
|
"@push.rocks/lik": "^6.2.2",
|
||||||
"@push.rocks/smartdata": "^5.15.1",
|
"@push.rocks/smartdata": "^7.0.15",
|
||||||
|
"@push.rocks/taskbuffer": "^6.1.0",
|
||||||
"@push.rocks/smartdelay": "^3.0.5",
|
"@push.rocks/smartdelay": "^3.0.5",
|
||||||
"@push.rocks/smartdns": "^6.2.2",
|
"@push.rocks/smartdns": "^7.8.1",
|
||||||
"@push.rocks/smartlog": "^3.0.7",
|
"@push.rocks/smartlog": "^3.1.10",
|
||||||
"@push.rocks/smartpromise": "^4.2.3",
|
"@push.rocks/smartnetwork": "^4.4.0",
|
||||||
"@push.rocks/smartrequest": "^2.1.0",
|
"@push.rocks/smartstring": "^4.1.0",
|
||||||
"@push.rocks/smartstring": "^4.0.15",
|
|
||||||
"@push.rocks/smarttime": "^4.1.1",
|
"@push.rocks/smarttime": "^4.1.1",
|
||||||
"@push.rocks/smartunique": "^3.0.9",
|
"@push.rocks/smartunique": "^3.0.9",
|
||||||
"@tsclass/tsclass": "^9.1.0",
|
"@tsclass/tsclass": "^9.3.0"
|
||||||
"acme-client": "^5.4.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@git.zone/tsbuild": "^2.3.2",
|
"@git.zone/tsbuild": "^4.1.2",
|
||||||
"@git.zone/tsrun": "^1.3.3",
|
"@git.zone/tsrun": "^2.0.1",
|
||||||
"@git.zone/tstest": "^1.0.96",
|
"@git.zone/tstest": "^3.1.8",
|
||||||
"@push.rocks/qenv": "^6.1.0",
|
"@push.rocks/qenv": "^6.1.3",
|
||||||
"@push.rocks/tapbundle": "^6.0.3",
|
"@types/node": "^25.2.3"
|
||||||
"@types/node": "^22.15.3"
|
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"ts/**/*",
|
"ts/**/*",
|
||||||
|
|||||||
6202
pnpm-lock.yaml
generated
6202
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,52 @@
|
|||||||
- this repo is dependent on letsencrypt and its limits
|
- this repo is dependent on letsencrypt and its limits
|
||||||
- to simpify the outside API, smartacme is stateful, meaning it works with a mongodb and a collection called 'SmartacmeCert'.
|
- to simpify the outside API, smartacme is stateful, meaning it works with a mongodb and a collection called 'SmartacmeCert'.
|
||||||
|
|
||||||
|
## Certificate Request Behavior
|
||||||
|
|
||||||
|
As of v7.4.0, SmartAcme no longer automatically requests wildcard certificates for all domain requests. This change was made to fix issues with HTTP-01 only configurations which cannot validate wildcard domains.
|
||||||
|
|
||||||
|
- By default, `getCertificateForDomain('example.com')` only requests a certificate for `example.com`
|
||||||
|
- To request both regular and wildcard certificates, use `getCertificateForDomain('example.com', { includeWildcard: true })`
|
||||||
|
- Wildcard certificates require a DNS-01 challenge handler to be configured
|
||||||
|
- Direct wildcard requests like `getCertificateForDomain('*.example.com')` only request the wildcard certificate
|
||||||
|
|
||||||
|
This change ensures HTTP-01 only configurations work properly while still allowing wildcard certificates when needed and supported.
|
||||||
|
|
||||||
|
## ACME Protocol Implementation
|
||||||
|
|
||||||
|
As of v8.1.0, the `acme-client` npm package has been replaced with a custom OOP implementation under `ts/acme/`. This uses `node:crypto` for all cryptographic operations and `@peculiar/x509` solely for CSR generation. The implementation follows RFC 8555.
|
||||||
|
|
||||||
|
Key files:
|
||||||
|
- `ts/acme/acme.classes.client.ts` — Top-level facade (`AcmeClient`), accepts optional `logger` callback
|
||||||
|
- `ts/acme/acme.classes.crypto.ts` — Key gen, JWK, JWS signing, CSR (`AcmeCrypto`)
|
||||||
|
- `ts/acme/acme.classes.http-client.ts` — JWS-signed HTTP transport with nonce management and logging
|
||||||
|
- `ts/acme/acme.classes.error.ts` — Structured `AcmeError` with type URN, subproblems, Retry-After, `isRetryable`/`isRateLimited`
|
||||||
|
- `ts/acme/acme.classes.account.ts` — Account registration
|
||||||
|
- `ts/acme/acme.classes.order.ts` — Order lifecycle + polling
|
||||||
|
- `ts/acme/acme.classes.challenge.ts` — Key authorization + challenge completion
|
||||||
|
- `ts/acme/acme.classes.directory.ts` — CA directory URL constants (`ACME_DIRECTORY_URLS`)
|
||||||
|
|
||||||
|
Usage in `ts/plugins.ts`: `import * as acme from './acme/index.js'` (replaces `acme-client`)
|
||||||
|
|
||||||
|
## Concurrency & Rate Limiting (taskbuffer integration)
|
||||||
|
|
||||||
|
As of v9.1.0, `@push.rocks/lik.InterestMap` was replaced with `@push.rocks/taskbuffer.TaskManager` for coordinating concurrent certificate requests. This provides:
|
||||||
|
|
||||||
|
- **Per-domain mutex** (`cert-domain-mutex`): Only one ACME issuance per TLD at a time, with `resultSharingMode: 'share-latest'` so queued callers get the same result without re-issuing.
|
||||||
|
- **Global concurrency cap** (`acme-global-concurrency`): Limits total parallel ACME operations (default 5, configurable via `maxConcurrentIssuances`).
|
||||||
|
- **Account-level rate limiting** (`acme-account-rate-limit`): Sliding-window rate limit (default 250 orders per 3 hours, configurable via `maxOrdersPerWindow`/`orderWindowMs`) to stay under Let's Encrypt limits.
|
||||||
|
- **Step-based progress**: The cert issuance task uses `notifyStep()` for prepare/authorize/finalize/store phases, observable via `smartAcme.certIssuanceEvents`.
|
||||||
|
|
||||||
|
Key implementation details:
|
||||||
|
- A single reusable `Task` named `cert-issuance` handles all domains via `triggerTaskConstrained()` with different inputs.
|
||||||
|
- The `shouldExecute` callback on the domain mutex checks the certmanager cache as a safety net.
|
||||||
|
- `TaskManager.start()` is called in `SmartAcme.start()` and `TaskManager.stop()` in `SmartAcme.stop()`.
|
||||||
|
- The "no cronjobs specified" log messages during tests come from taskbuffer's internal CronManager polling — harmless noise when no cron tasks are scheduled.
|
||||||
|
|
||||||
|
## Dependency Notes
|
||||||
|
|
||||||
|
- `acme-client` was replaced with custom implementation in `ts/acme/` + `@peculiar/x509` for CSR generation
|
||||||
|
- `@push.rocks/smartfile`, `@api.global/typedserver`, `@push.rocks/smartrequest`, `@push.rocks/smartpromise` were removed as unused dependencies in v8.1.0
|
||||||
|
- The `@apiclient.xyz/cloudflare` `convenience` namespace is deprecated but still functional. The `Dns01Handler` accepts an `IConvenientDnsProvider` interface which remains stable.
|
||||||
|
- Test imports use `@git.zone/tstest/tapbundle` (not `@push.rocks/tapbundle`)
|
||||||
|
- Build uses `tsbuild` (no flags needed, v4+)
|
||||||
|
|||||||
538
readme.md
538
readme.md
@@ -1,353 +1,339 @@
|
|||||||
# @push.rocks/smartacme
|
# @push.rocks/smartacme
|
||||||
|
|
||||||
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
|
A TypeScript-based ACME client for Let's Encrypt certificate management with a focus on simplicity and power. 🔒
|
||||||
|
|
||||||
|
## Issue Reporting and Security
|
||||||
|
|
||||||
|
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
Using pnpm as the package manager:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm add @push.rocks/smartacme
|
pnpm add @push.rocks/smartacme
|
||||||
```
|
```
|
||||||
|
|
||||||
Ensure your project is set up to use TypeScript and ECMAScript Modules (ESM).
|
Ensure your project uses TypeScript and ECMAScript Modules (ESM).
|
||||||
## Running Tests
|
|
||||||
|
|
||||||
Tests are written using `@push.rocks/tapbundle` and can be run with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm test
|
|
||||||
```
|
|
||||||
|
|
||||||
To run a specific test file:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
tsx test/<test-file>.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage
|
## 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.
|
`@push.rocks/smartacme` automates the full ACME certificate lifecycle — obtaining, renewing, and storing SSL/TLS certificates from Let's Encrypt. It features a built-in RFC 8555-compliant ACME protocol implementation, pluggable challenge handlers (DNS-01, HTTP-01), pluggable certificate storage backends (MongoDB, in-memory, or your own), and structured error handling with smart retry logic.
|
||||||
|
|
||||||
### Table of Contents
|
### 🚀 Quick Start
|
||||||
|
|
||||||
1. [Setting Up Your Project](#setting-up-your-project)
|
|
||||||
2. [Creating a SmartAcme Instance](#creating-a-smartacme-instance)
|
|
||||||
3. [Initializing SmartAcme](#initializing-smartacme)
|
|
||||||
4. [Obtaining a Certificate for a Domain](#obtaining-a-certificate-for-a-domain)
|
|
||||||
5. [Automating DNS Challenges](#automating-dns-challenges)
|
|
||||||
6. [Managing Certificates](#managing-certificates)
|
|
||||||
7. [Environmental Considerations](#environmental-considerations)
|
|
||||||
8. [Complete Example](#complete-example)
|
|
||||||
|
|
||||||
### Setting Up Your Project
|
|
||||||
|
|
||||||
Ensure your project includes the necessary TypeScript configuration and dependencies. You'll need to have TypeScript installed and configured for ECMAScript Modules. If you are new to TypeScript, review its [documentation](https://www.typescriptlang.org/docs/) to get started.
|
|
||||||
|
|
||||||
### Creating a SmartAcme Instance
|
|
||||||
|
|
||||||
Start by importing the `SmartAcme` class and any built-in handlers you plan to use. For example, to use DNS-01 via Cloudflare:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { SmartAcme, MongoCertManager } from '@push.rocks/smartacme';
|
import { SmartAcme, certmanagers, handlers } from '@push.rocks/smartacme';
|
||||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
||||||
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
|
|
||||||
|
|
||||||
// Create a Cloudflare account client with your API token
|
// 1. Set up a certificate manager (MongoDB or in-memory)
|
||||||
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
|
const certManager = new certmanagers.MongoCertManager({
|
||||||
|
mongoDbUrl: 'mongodb://localhost:27017',
|
||||||
// Initialize a certificate manager (e.g., MongoDB)
|
mongoDbName: 'myapp',
|
||||||
const certManager = new MongoCertManager({
|
mongoDbPass: 'secret',
|
||||||
mongoDbUrl: 'mongodb://yourmongoURL',
|
|
||||||
mongoDbName: 'yourDbName',
|
|
||||||
mongoDbPass: 'yourDbPassword',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Instantiate SmartAcme with the certManager and challenge handlers
|
// 2. Set up challenge handlers
|
||||||
const smartAcmeInstance = new SmartAcme({
|
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_API_TOKEN');
|
||||||
accountEmail: 'youremail@example.com',
|
const dnsHandler = new handlers.Dns01Handler(cfAccount);
|
||||||
certManager,
|
|
||||||
environment: 'integration', // 'production' to request real certificates
|
|
||||||
retryOptions: {}, // optional retry/backoff settings
|
|
||||||
challengeHandlers: [ // pluggable ACME challenge handlers
|
|
||||||
new Dns01Handler(cfAccount),
|
|
||||||
// add more handlers as needed (e.g., Http01Webroot, Http01MemoryHandler)
|
|
||||||
],
|
|
||||||
challengePriority: ['dns-01'], // optional challenge ordering
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Initializing SmartAcme
|
// 3. Create and start SmartAcme
|
||||||
|
|
||||||
Before proceeding to request certificates, start your SmartAcme instance:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await smartAcmeInstance.start();
|
|
||||||
```
|
|
||||||
|
|
||||||
### Obtaining a Certificate for a Domain
|
|
||||||
|
|
||||||
To obtain a certificate for a specific domain, use the `getCertificateForDomain` method. This function ensures that if a valid certificate is already present, it will be reused; otherwise, a new certificate is obtained:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const myDomain = 'example.com';
|
|
||||||
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
|
|
||||||
console.log('Certificate:', myCert);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Automating DNS Challenges
|
|
||||||
|
|
||||||
SmartAcme uses pluggable ACME challenge handlers (see built-in handlers below) to automate domain validation. You configure handlers via the `challengeHandlers` array when creating the instance, and SmartAcme will invoke each handler’s `prepare`, optional `verify`, and `cleanup` methods during the ACME order flow.
|
|
||||||
|
|
||||||
### Managing Certificates
|
|
||||||
|
|
||||||
The library automatically handles fetching, renewing, and storing your certificates in a MongoDB database specified via a certificate manager. Ensure your MongoDB instance is accessible and properly configured for use with SmartAcme.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { MongoCertManager } from '@push.rocks/smartacme';
|
|
||||||
|
|
||||||
const certManager = new MongoCertManager({
|
|
||||||
mongoDbUrl: 'mongodb://yourmongoURL',
|
|
||||||
mongoDbName: 'yourDbName',
|
|
||||||
mongoDbPass: 'yourDbPassword',
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
SmartAcme uses the `ICertManager` interface for certificate storage. Two built-in implementations are available:
|
|
||||||
|
|
||||||
- **MemoryCertManager**
|
|
||||||
- In-memory storage, suitable for testing or ephemeral use.
|
|
||||||
- Import example:
|
|
||||||
```typescript
|
|
||||||
import { MemoryCertManager } from '@push.rocks/smartacme';
|
|
||||||
const certManager = new MemoryCertManager();
|
|
||||||
```
|
|
||||||
|
|
||||||
- **MongoCertManager**
|
|
||||||
- Persistent storage in MongoDB (collection: `SmartacmeCert`).
|
|
||||||
- Import example:
|
|
||||||
```typescript
|
|
||||||
import { MongoCertManager } from '@push.rocks/smartacme';
|
|
||||||
const certManager = new MongoCertManager({
|
|
||||||
mongoDbUrl: 'mongodb://yourmongoURL',
|
|
||||||
mongoDbName: 'yourDbName',
|
|
||||||
mongoDbPass: 'yourDbPassword',
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Custom Certificate Managers
|
|
||||||
|
|
||||||
To implement a custom certificate manager, implement the `ICertManager` interface and pass it to `SmartAcme`:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import type { ICertManager, Cert as SmartacmeCert } from '@push.rocks/smartacme';
|
|
||||||
import { SmartAcme } from '@push.rocks/smartacme';
|
|
||||||
|
|
||||||
class MyCustomCertManager implements ICertManager {
|
|
||||||
async init(): Promise<void> { /* setup storage */ }
|
|
||||||
async get(domainName: string): Promise<SmartacmeCert | null> { /* lookup cert */ }
|
|
||||||
async put(cert: SmartacmeCert): Promise<SmartacmeCert> { /* store cert */ }
|
|
||||||
async delete(domainName: string): Promise<void> { /* remove cert */ }
|
|
||||||
async close?(): Promise<void> { /* optional cleanup */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use your custom manager:
|
|
||||||
const customManager = new MyCustomCertManager();
|
|
||||||
const smartAcme = new SmartAcme({
|
const smartAcme = new SmartAcme({
|
||||||
accountEmail: 'youremail@example.com',
|
accountEmail: 'admin@example.com',
|
||||||
certManager: customManager,
|
|
||||||
environment: 'integration',
|
|
||||||
challengeHandlers: [], // add your handlers
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Environmental Considerations
|
|
||||||
|
|
||||||
When creating an instance of `SmartAcme`, you can specify an `environment` option. This is particularly useful for testing, as you can use the `integration` environment to avoid hitting rate limits and for testing your setup without issuing real certificates. Switch to `production` when you are ready to obtain actual certificates.
|
|
||||||
|
|
||||||
### Complete Example
|
|
||||||
|
|
||||||
Below is a complete example demonstrating how to use `@push.rocks/smartacme` to obtain and manage an ACME certificate with Let's Encrypt using a DNS-01 handler:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { SmartAcme, MongoCertManager } from '@push.rocks/smartacme';
|
|
||||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
|
||||||
import { Qenv } from '@push.rocks/qenv';
|
|
||||||
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
|
|
||||||
|
|
||||||
const qenv = new Qenv('./', './.nogit/');
|
|
||||||
const cloudflareAccount = new cloudflare.CloudflareAccount(qenv.getEnvVarOnDemand('CF_TOKEN'));
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
// Initialize MongoDB certificate manager
|
|
||||||
const certManager = new MongoCertManager({
|
|
||||||
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
|
|
||||||
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
|
|
||||||
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
|
|
||||||
});
|
|
||||||
|
|
||||||
const smartAcmeInstance = new SmartAcme({
|
|
||||||
accountEmail: 'youremail@example.com',
|
|
||||||
certManager,
|
certManager,
|
||||||
environment: 'integration',
|
environment: 'production', // or 'integration' for staging
|
||||||
challengeHandlers: [new Dns01Handler(cloudflareAccount)],
|
challengeHandlers: [dnsHandler],
|
||||||
});
|
});
|
||||||
|
|
||||||
await smartAcmeInstance.start();
|
await smartAcme.start();
|
||||||
|
|
||||||
const myDomain = 'example.com';
|
// 4. Get a certificate
|
||||||
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
|
const cert = await smartAcme.getCertificateForDomain('example.com');
|
||||||
console.log('Certificate:', myCert);
|
console.log(cert.publicKey); // PEM certificate chain
|
||||||
|
console.log(cert.privateKey); // PEM private key
|
||||||
|
|
||||||
await smartAcmeInstance.stop();
|
// 5. Clean up
|
||||||
|
await smartAcme.stop();
|
||||||
|
```
|
||||||
|
|
||||||
|
### ⚙️ SmartAcme Options
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface ISmartAcmeOptions {
|
||||||
|
accountEmail: string; // ACME account email
|
||||||
|
accountPrivateKey?: string; // Optional account key (auto-generated if omitted)
|
||||||
|
certManager: ICertManager; // Certificate storage backend
|
||||||
|
environment: 'production' | 'integration'; // Let's Encrypt environment
|
||||||
|
challengeHandlers: IChallengeHandler[]; // At least one handler required
|
||||||
|
challengePriority?: string[]; // e.g. ['dns-01', 'http-01']
|
||||||
|
retryOptions?: { // Optional retry/backoff config
|
||||||
|
retries?: number; // Default: 10
|
||||||
|
factor?: number; // Default: 4
|
||||||
|
minTimeoutMs?: number; // Default: 1000
|
||||||
|
maxTimeoutMs?: number; // Default: 60000
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch(console.error);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Built-in Challenge Handlers
|
### 📜 Getting Certificates
|
||||||
|
|
||||||
This module includes three out-of-the-box ACME challenge handlers:
|
|
||||||
|
|
||||||
- **Dns01Handler**
|
|
||||||
- Uses a Cloudflare account (from `@apiclient.xyz/cloudflare`) and Smartdns client to set and remove DNS TXT records, then wait for propagation.
|
|
||||||
- Import path:
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
|
// Standard certificate for a single domain
|
||||||
|
const cert = await smartAcme.getCertificateForDomain('example.com');
|
||||||
|
|
||||||
|
// Include wildcard coverage (requires DNS-01 handler)
|
||||||
|
// Issues a single cert covering example.com AND *.example.com
|
||||||
|
const certWithWildcard = await smartAcme.getCertificateForDomain('example.com', {
|
||||||
|
includeWildcard: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Request wildcard only
|
||||||
|
const wildcardCert = await smartAcme.getCertificateForDomain('*.example.com');
|
||||||
```
|
```
|
||||||
- Example:
|
|
||||||
|
Certificates are automatically cached and reused when still valid. Renewal happens automatically when a certificate is within 10 days of expiration.
|
||||||
|
|
||||||
|
### 📦 Certificate Object
|
||||||
|
|
||||||
|
The returned `SmartacmeCert` (also exported as `Cert`) object has these properties:
|
||||||
|
|
||||||
|
| Property | Type | Description |
|
||||||
|
|-------------|----------|--------------------------------------|
|
||||||
|
| `id` | `string` | Unique certificate identifier |
|
||||||
|
| `domainName`| `string` | Domain the cert is issued for |
|
||||||
|
| `publicKey` | `string` | PEM-encoded certificate chain |
|
||||||
|
| `privateKey`| `string` | PEM-encoded private key |
|
||||||
|
| `csr` | `string` | Certificate Signing Request |
|
||||||
|
| `created` | `number` | Timestamp of creation |
|
||||||
|
| `validUntil`| `number` | Timestamp of expiration |
|
||||||
|
|
||||||
|
Useful methods:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
cert.isStillValid(); // true if not expired
|
||||||
|
cert.shouldBeRenewed(); // true if expires within 10 days
|
||||||
|
```
|
||||||
|
|
||||||
|
## Certificate Managers
|
||||||
|
|
||||||
|
SmartAcme uses the `ICertManager` interface for pluggable certificate storage.
|
||||||
|
|
||||||
|
### 🗄️ MongoCertManager
|
||||||
|
|
||||||
|
Persistent storage backed by MongoDB using `@push.rocks/smartdata`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { certmanagers } from '@push.rocks/smartacme';
|
||||||
|
|
||||||
|
const certManager = new certmanagers.MongoCertManager({
|
||||||
|
mongoDbUrl: 'mongodb://localhost:27017',
|
||||||
|
mongoDbName: 'myapp',
|
||||||
|
mongoDbPass: 'secret',
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🧪 MemoryCertManager
|
||||||
|
|
||||||
|
In-memory storage, ideal for testing or ephemeral workloads:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { certmanagers } from '@push.rocks/smartacme';
|
||||||
|
|
||||||
|
const certManager = new certmanagers.MemoryCertManager();
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔧 Custom Certificate Manager
|
||||||
|
|
||||||
|
Implement the `ICertManager` interface for your own storage backend:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { ICertManager, Cert } from '@push.rocks/smartacme';
|
||||||
|
|
||||||
|
class RedisCertManager implements ICertManager {
|
||||||
|
async init(): Promise<void> { /* connect */ }
|
||||||
|
async retrieveCertificate(domainName: string): Promise<Cert | null> { /* lookup */ }
|
||||||
|
async storeCertificate(cert: Cert): Promise<void> { /* save */ }
|
||||||
|
async deleteCertificate(domainName: string): Promise<void> { /* remove */ }
|
||||||
|
async close(): Promise<void> { /* disconnect */ }
|
||||||
|
async wipe(): Promise<void> { /* clear all */ }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Challenge Handlers
|
||||||
|
|
||||||
|
SmartAcme ships with three built-in ACME challenge handlers. All implement `IChallengeHandler<T>`.
|
||||||
|
|
||||||
|
### 🌐 Dns01Handler
|
||||||
|
|
||||||
|
Uses Cloudflare (or any `IConvenientDnsProvider`) to set and remove DNS TXT records for `dns-01` challenges:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { handlers } from '@push.rocks/smartacme';
|
||||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
||||||
const cfAccount = new cloudflare.CloudflareAccount('CF_TOKEN');
|
|
||||||
const dnsHandler = new Dns01Handler(cfAccount);
|
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
|
||||||
|
const dnsHandler = new handlers.Dns01Handler(cfAccount);
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Http01Webroot**
|
DNS-01 is **required** for wildcard certificates and works regardless of server accessibility.
|
||||||
- Writes ACME HTTP-01 challenge files under a file-system webroot (`/.well-known/acme-challenge/`), and removes them on cleanup.
|
|
||||||
- Import path:
|
### 📁 Http01Webroot
|
||||||
|
|
||||||
|
Writes challenge response files to a filesystem webroot for `http-01` validation:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Http01Webroot } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
|
import { handlers } from '@push.rocks/smartacme';
|
||||||
```
|
|
||||||
- Example:
|
const httpHandler = new handlers.Http01Webroot({
|
||||||
```typescript
|
webroot: '/var/www/html',
|
||||||
const httpHandler = new Http01Webroot({ webroot: '/var/www/html' });
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Http01MemoryHandler**
|
The handler writes to `<webroot>/.well-known/acme-challenge/<token>` and cleans up after validation.
|
||||||
- In-memory HTTP-01 challenge handler that stores and serves ACME tokens without disk I/O.
|
|
||||||
- Import path:
|
### 🧠 Http01MemoryHandler
|
||||||
|
|
||||||
|
In-memory HTTP-01 handler — stores challenge tokens in memory and serves them via `handleRequest()`:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
|
import { handlers } from '@push.rocks/smartacme';
|
||||||
```
|
|
||||||
- Example (Express integration):
|
const memHandler = new handlers.Http01MemoryHandler();
|
||||||
```typescript
|
|
||||||
import { Http01MemoryHandler } from '@push.rocks/smartacme/ts/handlers/Http01MemoryHandler.js';
|
// Integrate with any HTTP server (Express, Koa, raw http, etc.)
|
||||||
const memoryHandler = new Http01MemoryHandler();
|
app.use((req, res, next) => memHandler.handleRequest(req, res, next));
|
||||||
app.use((req, res, next) => memoryHandler.handleRequest(req, res, next));
|
|
||||||
```
|
```
|
||||||
|
|
||||||
All handlers implement the `IChallengeHandler<T>` interface and can be combined in the `challengeHandlers` array.
|
Perfect for serverless or container environments where filesystem access is limited.
|
||||||
|
|
||||||
## Creating Custom Handlers
|
### 🔧 Custom Challenge Handler
|
||||||
|
|
||||||
To support additional challenge types or custom validation flows, implement the `IChallengeHandler<T>` interface:
|
Implement `IChallengeHandler<T>` for custom challenge types:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import type { IChallengeHandler } from '@push.rocks/smartacme/ts/handlers/IChallengeHandler.js';
|
import type { handlers } from '@push.rocks/smartacme';
|
||||||
|
|
||||||
// Define your custom challenge payload type
|
interface MyChallenge {
|
||||||
interface MyChallenge { type: string; /* ... */ }
|
type: string;
|
||||||
|
token: string;
|
||||||
class MyCustomHandler implements IChallengeHandler<MyChallenge> {
|
keyAuthorization: string;
|
||||||
getSupportedTypes(): string[] {
|
|
||||||
return ['my-01'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare the challenge (set DNS records, start servers, etc.)
|
class MyHandler implements handlers.IChallengeHandler<MyChallenge> {
|
||||||
async prepare(ch: MyChallenge): Promise<void> {
|
getSupportedTypes(): string[] { return ['http-01']; }
|
||||||
// preparation logic
|
async prepare(ch: MyChallenge): Promise<void> { /* set up challenge response */ }
|
||||||
|
async cleanup(ch: MyChallenge): Promise<void> { /* tear down */ }
|
||||||
|
async checkWetherDomainIsSupported(domain: string): Promise<boolean> { return true; }
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
// Optional verify step after prepare
|
## Error Handling
|
||||||
async verify?(ch: MyChallenge): Promise<void> {
|
|
||||||
// verification logic
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cleanup after challenge (remove records, stop servers)
|
SmartAcme provides structured ACME error handling via the `AcmeError` class, which carries full RFC 8555 error information:
|
||||||
async cleanup(ch: MyChallenge): Promise<void> {
|
|
||||||
// cleanup logic
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then register your handler:
|
```typescript
|
||||||
const customInstance = new SmartAcme({
|
import { AcmeError } from '@push.rocks/smartacme/ts/acme/acme.classes.error.js';
|
||||||
/* other options */,
|
|
||||||
challengeHandlers: [ new MyCustomHandler() ],
|
try {
|
||||||
challengePriority: ['my-01'],
|
const cert = await smartAcme.getCertificateForDomain('example.com');
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof AcmeError) {
|
||||||
|
console.log(err.status); // HTTP status code (e.g. 429)
|
||||||
|
console.log(err.type); // ACME error URN (e.g. 'urn:ietf:params:acme:error:rateLimited')
|
||||||
|
console.log(err.detail); // Human-readable message
|
||||||
|
console.log(err.subproblems); // Per-identifier sub-errors (RFC 8555 §6.7.1)
|
||||||
|
console.log(err.retryAfter); // Retry-After value in seconds
|
||||||
|
console.log(err.isRateLimited); // true for 429 or rateLimited type
|
||||||
|
console.log(err.isRetryable); // true for 429, 503, 5xx, badNonce; false for 403/404/409
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The built-in retry logic is **error-aware**: non-retryable errors (403, 404, 409) are thrown immediately without wasting retry attempts, and rate-limited responses respect the server's `Retry-After` header instead of using blind exponential backoff.
|
||||||
|
|
||||||
|
## Domain Matching
|
||||||
|
|
||||||
|
SmartAcme automatically maps subdomains to their base domain for certificate lookups:
|
||||||
|
|
||||||
|
```
|
||||||
|
subdomain.example.com → certificate for example.com ✅
|
||||||
|
*.example.com → certificate for example.com ✅
|
||||||
|
a.b.example.com → not supported (4+ levels) ❌
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment
|
||||||
|
|
||||||
|
| Environment | Description |
|
||||||
|
|----------------|-------------|
|
||||||
|
| `production` | Let's Encrypt production servers. Certificates are browser-trusted. [Rate limits](https://letsencrypt.org/docs/rate-limits/) apply. |
|
||||||
|
| `integration` | Let's Encrypt staging servers. No rate limits, but certificates are **not** browser-trusted. Use for testing. |
|
||||||
|
|
||||||
|
## Complete Example with HTTP-01
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { SmartAcme, certmanagers, handlers } from '@push.rocks/smartacme';
|
||||||
|
import * as http from 'http';
|
||||||
|
|
||||||
|
// In-memory handler for HTTP-01 challenges
|
||||||
|
const memHandler = new handlers.Http01MemoryHandler();
|
||||||
|
|
||||||
|
// Create HTTP server that serves ACME challenges
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
memHandler.handleRequest(req, res, () => {
|
||||||
|
res.statusCode = 200;
|
||||||
|
res.end('OK');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
server.listen(80);
|
||||||
|
|
||||||
|
// Set up SmartAcme with in-memory storage and HTTP-01
|
||||||
|
const smartAcme = new SmartAcme({
|
||||||
|
accountEmail: 'admin@example.com',
|
||||||
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
|
environment: 'production',
|
||||||
|
challengeHandlers: [memHandler],
|
||||||
|
challengePriority: ['http-01'],
|
||||||
});
|
});
|
||||||
|
|
||||||
In this example, `Qenv` is used to manage environment variables, and the Cloudflare library is used to handle DNS challenges through the built-in `Dns01Handler` plugin.
|
await smartAcme.start();
|
||||||
|
|
||||||
## Additional Details
|
const cert = await smartAcme.getCertificateForDomain('example.com');
|
||||||
|
// Use cert.publicKey and cert.privateKey with your HTTPS server
|
||||||
|
|
||||||
### Certificate Object
|
await smartAcme.stop();
|
||||||
|
server.close();
|
||||||
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.
|
|
||||||
|
|
||||||
### Handling Domain Matching
|
|
||||||
|
|
||||||
The `SmartacmeCertMatcher` class is responsible for matching certificates with the broadest scope for wildcard certificates. The `getCertificateDomainNameByDomainName` method ensures that domains at various levels are correctly matched.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { SmartacmeCertMatcher } from '@push.rocks/smartacme';
|
|
||||||
|
|
||||||
const certMatcher = new SmartacmeCertMatcher();
|
|
||||||
const certDomainName = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
|
|
||||||
console.log('Certificate Domain Name:', certDomainName); // Output: example.com
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Testing
|
## Architecture
|
||||||
|
|
||||||
Sample tests are provided in the `test` directory. They demonstrate core functionality using the `MemoryCertManager` and built-in challenge handlers. To run all tests, use:
|
Under the hood, SmartAcme uses a fully custom RFC 8555-compliant ACME protocol implementation (no external ACME libraries). Key internal modules:
|
||||||
|
|
||||||
```bash
|
| Module | Purpose |
|
||||||
pnpm test
|
|--------|---------|
|
||||||
```
|
| `AcmeClient` | Top-level ACME facade — orders, authorizations, finalization |
|
||||||
|
| `AcmeCrypto` | RSA key generation, JWK/JWS (RFC 7515/7638), CSR via `@peculiar/x509` |
|
||||||
|
| `AcmeHttpClient` | JWS-signed HTTP transport with nonce management and structured logging |
|
||||||
|
| `AcmeError` | Structured error class with type URN, subproblems, Retry-After, retryability |
|
||||||
|
| `AcmeOrderManager` | Order lifecycle — create, poll, finalize, download certificate |
|
||||||
|
| `AcmeChallengeManager` | Key authorization computation and challenge completion |
|
||||||
|
|
||||||
|
All cryptographic operations use `node:crypto`. The only external crypto dependency is `@peculiar/x509` for CSR generation.
|
||||||
This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using `@push.rocks/smartacme`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## License and Legal Information
|
## License and Legal Information
|
||||||
|
|
||||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license.md](license.md) file within this repository.
|
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||||
|
|
||||||
**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.
|
**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
|
### 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.
|
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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||||
|
|
||||||
### Company Information
|
### Company Information
|
||||||
|
|
||||||
Task Venture Capital GmbH
|
Task Venture Capital GmbH
|
||||||
Registered at District court Bremen HRB 35230 HB, Germany
|
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||||
|
|
||||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
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.
|
||||||
|
|||||||
@@ -1,16 +1,3 @@
|
|||||||
# Plan: Move interestMap from certmanager to smartacme core
|
## Plan
|
||||||
|
|
||||||
## Goal
|
Move the
|
||||||
- Pull the interest coordination mechanism out of the ICertManager implementations and into the SmartAcme class.
|
|
||||||
|
|
||||||
## Steps
|
|
||||||
1. Remove `interestMap` from `ICertManager` interface (`ts/interfaces/certmanager.ts`) and its import of `InterestMap`.
|
|
||||||
2. Strip out `interestMap` property, initialization, and usage from `MemoryCertManager` and `MongoCertManager` (`ts/certmanagers/*.ts`).
|
|
||||||
3. In `Smartacme` class (`ts/smartacme.classes.smartacme.ts`):
|
|
||||||
- Add a private `interestMap: plugins.lik.InterestMap<string, SmartacmeCert>` property.
|
|
||||||
- Initialize it in the constructor: `this.interestMap = new plugins.lik.InterestMap((domain) => domain);`.
|
|
||||||
- Update `getCertificateForDomain()` and any other consumers to reference `this.interestMap` instead of `this.certmanager.interestMap`.
|
|
||||||
4. Remove any tests or code that reference the old `interestMap` on `ICertManager` (if any).
|
|
||||||
5. Run CI (`pnpm build` and `pnpm test`) and fix any regressions.
|
|
||||||
|
|
||||||
Please review and confirm before we begin the refactor.
|
|
||||||
64
test/test.acme-challenge.ts
Normal file
64
test/test.acme-challenge.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
import * as crypto from 'node:crypto';
|
||||||
|
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
|
||||||
|
import { AcmeChallengeManager } from '../ts/acme/acme.classes.challenge.js';
|
||||||
|
|
||||||
|
// Create a shared key and fake httpClient for all tests
|
||||||
|
let accountKeyPem: string;
|
||||||
|
let challengeManager: AcmeChallengeManager;
|
||||||
|
|
||||||
|
tap.test('setup: create key and challenge manager', async () => {
|
||||||
|
accountKeyPem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
// AcmeChallengeManager only needs httpClient for complete(), not for getKeyAuthorization()
|
||||||
|
// Pass null since we only test the sync crypto method
|
||||||
|
challengeManager = new AcmeChallengeManager(null as any, accountKeyPem);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- http-01 ---
|
||||||
|
|
||||||
|
tap.test('http-01 returns token.thumbprint', async () => {
|
||||||
|
const challenge = { type: 'http-01', url: 'https://acme.example/chall/1', status: 'pending', token: 'test-token-abc' };
|
||||||
|
const result = challengeManager.getKeyAuthorization(challenge);
|
||||||
|
|
||||||
|
const jwk = AcmeCrypto.getJwk(accountKeyPem);
|
||||||
|
const thumbprint = AcmeCrypto.getJwkThumbprint(jwk);
|
||||||
|
expect(result).toEqual(`test-token-abc.${thumbprint}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- dns-01 ---
|
||||||
|
|
||||||
|
tap.test('dns-01 returns base64url(sha256(token.thumbprint))', async () => {
|
||||||
|
const challenge = { type: 'dns-01', url: 'https://acme.example/chall/2', status: 'pending', token: 'dns-token-xyz' };
|
||||||
|
const result = challengeManager.getKeyAuthorization(challenge);
|
||||||
|
|
||||||
|
// Manual computation
|
||||||
|
const jwk = AcmeCrypto.getJwk(accountKeyPem);
|
||||||
|
const thumbprint = AcmeCrypto.getJwkThumbprint(jwk);
|
||||||
|
const keyAuth = `dns-token-xyz.${thumbprint}`;
|
||||||
|
const expected = crypto.createHash('sha256').update(keyAuth).digest().toString('base64url');
|
||||||
|
expect(result).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('dns-01 output is base64url (no +, /, =)', async () => {
|
||||||
|
const challenge = { type: 'dns-01', url: 'https://acme.example/chall/3', status: 'pending', token: 'another-token' };
|
||||||
|
const result = challengeManager.getKeyAuthorization(challenge);
|
||||||
|
expect(result).not.toInclude('+');
|
||||||
|
expect(result).not.toInclude('/');
|
||||||
|
expect(result).not.toInclude('=');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('http-01 and dns-01 differ for same token', async () => {
|
||||||
|
const token = 'shared-token-123';
|
||||||
|
const httpResult = challengeManager.getKeyAuthorization({ type: 'http-01', url: 'https://acme.example/c/1', status: 'pending', token });
|
||||||
|
const dnsResult = challengeManager.getKeyAuthorization({ type: 'dns-01', url: 'https://acme.example/c/2', status: 'pending', token });
|
||||||
|
expect(httpResult).not.toEqual(dnsResult);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('deterministic across calls', async () => {
|
||||||
|
const challenge = { type: 'http-01', url: 'https://acme.example/c/x', status: 'pending', token: 'stable-token' };
|
||||||
|
const r1 = challengeManager.getKeyAuthorization(challenge);
|
||||||
|
const r2 = challengeManager.getKeyAuthorization(challenge);
|
||||||
|
expect(r1).toEqual(r2);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
161
test/test.acme-crypto.ts
Normal file
161
test/test.acme-crypto.ts
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
import * as crypto from 'node:crypto';
|
||||||
|
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
|
||||||
|
|
||||||
|
// --- createRsaPrivateKey ---
|
||||||
|
|
||||||
|
tap.test('createRsaPrivateKey returns valid PEM', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
expect(pem).toStartWith('-----BEGIN PRIVATE KEY-----');
|
||||||
|
expect(pem).toInclude('-----END PRIVATE KEY-----');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createRsaPrivateKey creates RSA key type', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const keyObj = crypto.createPrivateKey(pem);
|
||||||
|
expect(keyObj.asymmetricKeyType).toEqual('rsa');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createRsaPrivateKey respects modulusLength', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey(4096);
|
||||||
|
const keyObj = crypto.createPrivateKey(pem);
|
||||||
|
expect(keyObj.asymmetricKeyDetails!.modulusLength).toEqual(4096);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- getJwk ---
|
||||||
|
|
||||||
|
tap.test('getJwk returns sorted keys {e, kty, n}', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const keys = Object.keys(jwk);
|
||||||
|
expect(keys).toEqual(['e', 'kty', 'n']);
|
||||||
|
expect(jwk.kty).toEqual('RSA');
|
||||||
|
expect(typeof jwk.e).toEqual('string');
|
||||||
|
expect(typeof jwk.n).toEqual('string');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('getJwk is deterministic for same key', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk1 = AcmeCrypto.getJwk(pem);
|
||||||
|
const jwk2 = AcmeCrypto.getJwk(pem);
|
||||||
|
expect(JSON.stringify(jwk1)).toEqual(JSON.stringify(jwk2));
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- getJwkThumbprint ---
|
||||||
|
|
||||||
|
tap.test('getJwkThumbprint matches manual SHA-256 computation', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const thumbprint = AcmeCrypto.getJwkThumbprint(jwk);
|
||||||
|
|
||||||
|
// Manual computation
|
||||||
|
const canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
|
||||||
|
const expected = crypto.createHash('sha256').update(canonical).digest().toString('base64url');
|
||||||
|
expect(thumbprint).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('getJwkThumbprint is base64url format (no +, /, =)', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const thumbprint = AcmeCrypto.getJwkThumbprint(jwk);
|
||||||
|
expect(thumbprint).not.toInclude('+');
|
||||||
|
expect(thumbprint).not.toInclude('/');
|
||||||
|
expect(thumbprint).not.toInclude('=');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- createJws ---
|
||||||
|
|
||||||
|
tap.test('createJws returns correct structure', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const jws = AcmeCrypto.createJws(pem, 'https://acme.example/new-acct', { foo: 'bar' }, {
|
||||||
|
nonce: 'test-nonce',
|
||||||
|
jwk,
|
||||||
|
});
|
||||||
|
expect(typeof jws.protected).toEqual('string');
|
||||||
|
expect(typeof jws.payload).toEqual('string');
|
||||||
|
expect(typeof jws.signature).toEqual('string');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createJws protected header contains alg, nonce, url, jwk', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const jws = AcmeCrypto.createJws(pem, 'https://acme.example/new-acct', { foo: 'bar' }, {
|
||||||
|
nonce: 'test-nonce',
|
||||||
|
jwk,
|
||||||
|
});
|
||||||
|
const header = JSON.parse(Buffer.from(jws.protected, 'base64url').toString());
|
||||||
|
expect(header.alg).toEqual('RS256');
|
||||||
|
expect(header.nonce).toEqual('test-nonce');
|
||||||
|
expect(header.url).toEqual('https://acme.example/new-acct');
|
||||||
|
expect(header.jwk).toBeTruthy();
|
||||||
|
expect(header.kid).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createJws uses kid when provided instead of jwk', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jws = AcmeCrypto.createJws(pem, 'https://acme.example/order', { test: 1 }, {
|
||||||
|
nonce: 'nonce-2',
|
||||||
|
kid: 'https://acme.example/acct/1',
|
||||||
|
});
|
||||||
|
const header = JSON.parse(Buffer.from(jws.protected, 'base64url').toString());
|
||||||
|
expect(header.kid).toEqual('https://acme.example/acct/1');
|
||||||
|
expect(header.jwk).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createJws POST-as-GET produces empty payload', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jws = AcmeCrypto.createJws(pem, 'https://acme.example/order/1', null, {
|
||||||
|
nonce: 'nonce-3',
|
||||||
|
kid: 'https://acme.example/acct/1',
|
||||||
|
});
|
||||||
|
expect(jws.payload).toEqual('');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createJws signature is verifiable', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const jwk = AcmeCrypto.getJwk(pem);
|
||||||
|
const jws = AcmeCrypto.createJws(pem, 'https://acme.example/test', { val: 1 }, {
|
||||||
|
nonce: 'nonce-v',
|
||||||
|
jwk,
|
||||||
|
});
|
||||||
|
|
||||||
|
const sigInput = `${jws.protected}.${jws.payload}`;
|
||||||
|
const pubKey = crypto.createPublicKey(pem);
|
||||||
|
const verified = crypto.verify(
|
||||||
|
'sha256',
|
||||||
|
Buffer.from(sigInput),
|
||||||
|
pubKey,
|
||||||
|
Buffer.from(jws.signature, 'base64url'),
|
||||||
|
);
|
||||||
|
expect(verified).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- createCsr ---
|
||||||
|
|
||||||
|
tap.test('createCsr returns [keyPem, csrPem] with valid PEM formats', async () => {
|
||||||
|
const [keyPem, csrPem] = await AcmeCrypto.createCsr({ commonName: 'example.com' });
|
||||||
|
expect(keyPem).toStartWith('-----BEGIN PRIVATE KEY-----');
|
||||||
|
expect(csrPem).toInclude('CERTIFICATE REQUEST');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('createCsr uses existing key when provided', async () => {
|
||||||
|
const existingKey = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const [keyPem, csrPem] = await AcmeCrypto.createCsr({ commonName: 'example.com' }, existingKey);
|
||||||
|
expect(keyPem).toEqual(existingKey);
|
||||||
|
expect(csrPem).toInclude('CERTIFICATE REQUEST');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- pemToBuffer ---
|
||||||
|
|
||||||
|
tap.test('pemToBuffer strips headers and returns Buffer', async () => {
|
||||||
|
const pem = AcmeCrypto.createRsaPrivateKey();
|
||||||
|
const buf = AcmeCrypto.pemToBuffer(pem);
|
||||||
|
expect(buf).toBeInstanceOf(Buffer);
|
||||||
|
expect(buf.length).toBeGreaterThan(0);
|
||||||
|
// Verify it doesn't contain PEM header text
|
||||||
|
const str = buf.toString('utf-8');
|
||||||
|
expect(str).not.toInclude('-----BEGIN');
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
103
test/test.acme-error.ts
Normal file
103
test/test.acme-error.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
import { AcmeError } from '../ts/acme/acme.classes.error.js';
|
||||||
|
|
||||||
|
// --- Basic error properties ---
|
||||||
|
|
||||||
|
tap.test('AcmeError extends Error', async () => {
|
||||||
|
const err = new AcmeError({ status: 400 });
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err).toBeInstanceOf(AcmeError);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('AcmeError has correct name', async () => {
|
||||||
|
const err = new AcmeError({ status: 400 });
|
||||||
|
expect(err.name).toEqual('AcmeError');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('message includes type, status, url, and detail', async () => {
|
||||||
|
const err = new AcmeError({
|
||||||
|
status: 403,
|
||||||
|
type: 'urn:ietf:params:acme:error:unauthorized',
|
||||||
|
detail: 'Account is deactivated',
|
||||||
|
url: 'https://acme.example/order/1',
|
||||||
|
});
|
||||||
|
expect(err.message).toInclude('403');
|
||||||
|
expect(err.message).toInclude('urn:ietf:params:acme:error:unauthorized');
|
||||||
|
expect(err.message).toInclude('https://acme.example/order/1');
|
||||||
|
expect(err.message).toInclude('Account is deactivated');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('preserves all properties including subproblems', async () => {
|
||||||
|
const subproblems = [
|
||||||
|
{ type: 'urn:ietf:params:acme:error:caa', detail: 'CAA record prevents issuance', identifier: { type: 'dns', value: 'example.com' } },
|
||||||
|
];
|
||||||
|
const err = new AcmeError({
|
||||||
|
status: 403,
|
||||||
|
type: 'urn:ietf:params:acme:error:unauthorized',
|
||||||
|
detail: 'Forbidden',
|
||||||
|
subproblems,
|
||||||
|
url: 'https://acme.example/chall/1',
|
||||||
|
retryAfter: 30,
|
||||||
|
});
|
||||||
|
expect(err.status).toEqual(403);
|
||||||
|
expect(err.type).toEqual('urn:ietf:params:acme:error:unauthorized');
|
||||||
|
expect(err.detail).toEqual('Forbidden');
|
||||||
|
expect(err.subproblems.length).toEqual(1);
|
||||||
|
expect(err.subproblems[0].type).toEqual('urn:ietf:params:acme:error:caa');
|
||||||
|
expect(err.url).toEqual('https://acme.example/chall/1');
|
||||||
|
expect(err.retryAfter).toEqual(30);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('default values for optional fields', async () => {
|
||||||
|
const err = new AcmeError({ status: 500 });
|
||||||
|
expect(err.type).toEqual('');
|
||||||
|
expect(err.detail).toEqual('');
|
||||||
|
expect(err.subproblems).toEqual([]);
|
||||||
|
expect(err.url).toEqual('');
|
||||||
|
expect(err.retryAfter).toEqual(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- isRateLimited ---
|
||||||
|
|
||||||
|
tap.test('isRateLimited is true for status 429', async () => {
|
||||||
|
const err = new AcmeError({ status: 429 });
|
||||||
|
expect(err.isRateLimited).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('isRateLimited is true for rateLimited type URN', async () => {
|
||||||
|
const err = new AcmeError({
|
||||||
|
status: 403,
|
||||||
|
type: 'urn:ietf:params:acme:error:rateLimited',
|
||||||
|
});
|
||||||
|
expect(err.isRateLimited).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('isRateLimited is false for regular 400', async () => {
|
||||||
|
const err = new AcmeError({ status: 400, type: 'urn:ietf:params:acme:error:malformed' });
|
||||||
|
expect(err.isRateLimited).toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- isRetryable ---
|
||||||
|
|
||||||
|
tap.test('isRetryable is true for 429', async () => {
|
||||||
|
const err = new AcmeError({ status: 429 });
|
||||||
|
expect(err.isRetryable).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('isRetryable is true for 503 and 500', async () => {
|
||||||
|
expect(new AcmeError({ status: 503 }).isRetryable).toBeTrue();
|
||||||
|
expect(new AcmeError({ status: 500 }).isRetryable).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('isRetryable is true for badNonce type', async () => {
|
||||||
|
const err = new AcmeError({ status: 400, type: 'urn:ietf:params:acme:error:badNonce' });
|
||||||
|
expect(err.isRetryable).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('isRetryable is false for 403, 404, 409', async () => {
|
||||||
|
expect(new AcmeError({ status: 403 }).isRetryable).toBeFalse();
|
||||||
|
expect(new AcmeError({ status: 404 }).isRetryable).toBeFalse();
|
||||||
|
expect(new AcmeError({ status: 409 }).isRetryable).toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { SmartacmeCertMatcher } from '../ts/smartacme.classes.certmatcher.js';
|
import { SmartacmeCertMatcher } from '../ts/smartacme.classes.certmatcher.js';
|
||||||
|
|
||||||
tap.test('should match 2-level domain', async () => {
|
tap.test('should match 2-level domain', async () => {
|
||||||
@@ -18,4 +18,12 @@ tap.test('should return undefined for deeper domain', async () => {
|
|||||||
expect(result).toEqual(undefined);
|
expect(result).toEqual(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Wildcard domain handling
|
||||||
|
tap.test('should strip wildcard prefix and return base domain', async () => {
|
||||||
|
const matcher = new SmartacmeCertMatcher();
|
||||||
|
expect(matcher.getCertificateDomainNameByDomainName('*.example.com')).toEqual('example.com');
|
||||||
|
expect(matcher.getCertificateDomainNameByDomainName('*.sub.example.com')).toEqual('sub.example.com');
|
||||||
|
expect(matcher.getCertificateDomainNameByDomainName('*.a.b.example.com')).toEqual('a.b.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
export default tap.start();
|
export default tap.start();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
|
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
|
||||||
|
|
||||||
tap.test('Dns01Handler prepare and cleanup calls Cloudflare and DNS functions', async () => {
|
tap.test('Dns01Handler prepare and cleanup calls Cloudflare and DNS functions', async () => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { Http01MemoryHandler } from '../ts/handlers/Http01MemoryHandler.js';
|
import { Http01MemoryHandler } from '../ts/handlers/Http01MemoryHandler.js';
|
||||||
|
|
||||||
tap.test('Http01MemoryHandler serves in-memory challenges and cleans up', async () => {
|
tap.test('Http01MemoryHandler serves in-memory challenges and cleans up', async () => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { Http01Webroot } from '../ts/handlers/Http01Handler.js';
|
import { Http01Webroot } from '../ts/handlers/Http01Handler.js';
|
||||||
import { promises as fs } from 'fs';
|
import { promises as fs } from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
|
|||||||
172
test/test.http01-only.ts
Normal file
172
test/test.http01-only.ts
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
import { SmartAcme, certmanagers } from '../ts/index.js';
|
||||||
|
import { Http01MemoryHandler } from '../ts/handlers/Http01MemoryHandler.js';
|
||||||
|
|
||||||
|
// Test that HTTP-01 only configuration works without wildcard certificates
|
||||||
|
tap.test('HTTP-01 only configuration should work for regular domains', async () => {
|
||||||
|
const memHandler = new Http01MemoryHandler();
|
||||||
|
|
||||||
|
// Stub the domain support check to always return true for testing
|
||||||
|
memHandler.checkWetherDomainIsSupported = async () => true;
|
||||||
|
|
||||||
|
const certManager = new certmanagers.MemoryCertManager();
|
||||||
|
const smartAcmeInstance = new SmartAcme({
|
||||||
|
accountEmail: 'test@example.com',
|
||||||
|
certManager,
|
||||||
|
environment: 'integration',
|
||||||
|
retryOptions: {},
|
||||||
|
challengeHandlers: [memHandler],
|
||||||
|
challengePriority: ['http-01'],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stub the start method to avoid actual ACME connections
|
||||||
|
smartAcmeInstance.start = async () => {
|
||||||
|
smartAcmeInstance.certmanager = certManager;
|
||||||
|
smartAcmeInstance.certmatcher = {
|
||||||
|
getCertificateDomainNameByDomainName: (domain: string) => domain.replace('*.', '')
|
||||||
|
} as any;
|
||||||
|
await smartAcmeInstance.certmanager.init();
|
||||||
|
};
|
||||||
|
await smartAcmeInstance.start();
|
||||||
|
|
||||||
|
// Stub the core certificate methods to avoid actual ACME calls
|
||||||
|
(smartAcmeInstance as any).client = {
|
||||||
|
createOrder: async (orderPayload: any) => {
|
||||||
|
// Verify no wildcard is included in default request
|
||||||
|
const identifiers = orderPayload.identifiers;
|
||||||
|
expect(identifiers.length).toEqual(1);
|
||||||
|
expect(identifiers[0].value).toEqual('example.com');
|
||||||
|
expect(identifiers.find((id: any) => id.value.startsWith('*.'))).toBeUndefined();
|
||||||
|
return { status: 'pending', authorizations: [], finalize: '', certificate: '' };
|
||||||
|
},
|
||||||
|
getAuthorizations: async () => [],
|
||||||
|
finalizeOrder: async () => {},
|
||||||
|
getCertificate: async () => '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----',
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
(smartAcmeInstance as any).retry = async (fn: () => Promise<any>) => fn();
|
||||||
|
|
||||||
|
// Mock certmanager methods
|
||||||
|
smartAcmeInstance.certmanager.retrieveCertificate = async () => null;
|
||||||
|
smartAcmeInstance.certmanager.storeCertificate = async (cert: any) => cert;
|
||||||
|
|
||||||
|
// Request certificate without wildcard
|
||||||
|
const cert = await smartAcmeInstance.getCertificateForDomain('example.com');
|
||||||
|
expect(cert).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should only include wildcard when explicitly requested with DNS-01', async () => {
|
||||||
|
const dnsHandler = {
|
||||||
|
getSupportedTypes: () => ['dns-01'],
|
||||||
|
prepare: async () => {},
|
||||||
|
cleanup: async () => {},
|
||||||
|
checkWetherDomainIsSupported: async () => true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const certManager2 = new certmanagers.MemoryCertManager();
|
||||||
|
const smartAcmeInstance = new SmartAcme({
|
||||||
|
accountEmail: 'test@example.com',
|
||||||
|
certManager: certManager2,
|
||||||
|
environment: 'integration',
|
||||||
|
retryOptions: {},
|
||||||
|
challengeHandlers: [dnsHandler],
|
||||||
|
challengePriority: ['dns-01'],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stub the start method to avoid actual ACME connections
|
||||||
|
smartAcmeInstance.start = async () => {
|
||||||
|
smartAcmeInstance.certmanager = certManager2;
|
||||||
|
smartAcmeInstance.certmatcher = {
|
||||||
|
getCertificateDomainNameByDomainName: (domain: string) => domain.replace('*.', '')
|
||||||
|
} as any;
|
||||||
|
await smartAcmeInstance.certmanager.init();
|
||||||
|
};
|
||||||
|
await smartAcmeInstance.start();
|
||||||
|
|
||||||
|
// Stub the core certificate methods
|
||||||
|
(smartAcmeInstance as any).client = {
|
||||||
|
createOrder: async (orderPayload: any) => {
|
||||||
|
const identifiers = orderPayload.identifiers;
|
||||||
|
expect(identifiers.length).toEqual(2);
|
||||||
|
expect(identifiers[0].value).toEqual('example.com');
|
||||||
|
expect(identifiers[1].value).toEqual('*.example.com');
|
||||||
|
return { status: 'pending', authorizations: [], finalize: '', certificate: '' };
|
||||||
|
},
|
||||||
|
getAuthorizations: async () => [],
|
||||||
|
finalizeOrder: async () => {},
|
||||||
|
getCertificate: async () => '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----',
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
(smartAcmeInstance as any).retry = async (fn: () => Promise<any>) => fn();
|
||||||
|
|
||||||
|
// Mock certmanager methods
|
||||||
|
smartAcmeInstance.certmanager.retrieveCertificate = async () => null;
|
||||||
|
smartAcmeInstance.certmanager.storeCertificate = async (cert: any) => cert;
|
||||||
|
|
||||||
|
// Request certificate with wildcard
|
||||||
|
const cert = await smartAcmeInstance.getCertificateForDomain('example.com', { includeWildcard: true });
|
||||||
|
expect(cert).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should skip wildcard if requested but no DNS-01 handler available', async () => {
|
||||||
|
const httpHandler = new Http01MemoryHandler();
|
||||||
|
httpHandler.checkWetherDomainIsSupported = async () => true;
|
||||||
|
|
||||||
|
const certManager3 = new certmanagers.MemoryCertManager();
|
||||||
|
const smartAcmeInstance = new SmartAcme({
|
||||||
|
accountEmail: 'test@example.com',
|
||||||
|
certManager: certManager3,
|
||||||
|
environment: 'integration',
|
||||||
|
retryOptions: {},
|
||||||
|
challengeHandlers: [httpHandler],
|
||||||
|
challengePriority: ['http-01'],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stub the start method to avoid actual ACME connections
|
||||||
|
smartAcmeInstance.start = async () => {
|
||||||
|
smartAcmeInstance.certmanager = certManager3;
|
||||||
|
smartAcmeInstance.certmatcher = {
|
||||||
|
getCertificateDomainNameByDomainName: (domain: string) => domain.replace('*.', '')
|
||||||
|
} as any;
|
||||||
|
await smartAcmeInstance.certmanager.init();
|
||||||
|
};
|
||||||
|
await smartAcmeInstance.start();
|
||||||
|
|
||||||
|
// Mock logger to capture warning
|
||||||
|
const logSpy = { called: false, message: '' };
|
||||||
|
smartAcmeInstance.logger.log = async (level: string, message: string) => {
|
||||||
|
if (level === 'warn') {
|
||||||
|
logSpy.called = true;
|
||||||
|
logSpy.message = message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Stub the core certificate methods
|
||||||
|
(smartAcmeInstance as any).client = {
|
||||||
|
createOrder: async (orderPayload: any) => {
|
||||||
|
const identifiers = orderPayload.identifiers;
|
||||||
|
// Should only have regular domain, no wildcard
|
||||||
|
expect(identifiers.length).toEqual(1);
|
||||||
|
expect(identifiers[0].value).toEqual('example.com');
|
||||||
|
return { status: 'pending', authorizations: [], finalize: '', certificate: '' };
|
||||||
|
},
|
||||||
|
getAuthorizations: async () => [],
|
||||||
|
finalizeOrder: async () => {},
|
||||||
|
getCertificate: async () => '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----',
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
(smartAcmeInstance as any).retry = async (fn: () => Promise<any>) => fn();
|
||||||
|
|
||||||
|
// Mock certmanager methods
|
||||||
|
smartAcmeInstance.certmanager.retrieveCertificate = async () => null;
|
||||||
|
smartAcmeInstance.certmanager.storeCertificate = async (cert: any) => cert;
|
||||||
|
|
||||||
|
// Request certificate with wildcard (should be skipped)
|
||||||
|
const cert = await smartAcmeInstance.getCertificateForDomain('example.com', { includeWildcard: true });
|
||||||
|
|
||||||
|
expect(cert).toBeDefined();
|
||||||
|
expect(logSpy.called).toBeTrue();
|
||||||
|
expect(logSpy.message).toContain('Wildcard certificate requested but no DNS-01 handler available');
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { Qenv } from '@push.rocks/qenv';
|
import { Qenv } from '@push.rocks/qenv';
|
||||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
||||||
import { SmartAcme, MongoCertManager } from '../ts/index.js';
|
import { SmartAcme, certmanagers } from '../ts/index.js';
|
||||||
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
|
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
|
||||||
|
|
||||||
// Load environment variables for credentials (stored under .nogit/)
|
// Load environment variables for credentials (stored under .nogit/)
|
||||||
@@ -20,7 +20,8 @@ let smartAcmeInstance: SmartAcme;
|
|||||||
tap.test('create SmartAcme instance with DNS-01 handler and start', async () => {
|
tap.test('create SmartAcme instance with DNS-01 handler and start', async () => {
|
||||||
smartAcmeInstance = new SmartAcme({
|
smartAcmeInstance = new SmartAcme({
|
||||||
accountEmail: 'domains@lossless.org',
|
accountEmail: 'domains@lossless.org',
|
||||||
certManager: new MongoCertManager({ mongoDbName, mongoDbPass, mongoDbUrl }),
|
// certManager: new MongoCertManager({ mongoDbName, mongoDbPass, mongoDbUrl }),
|
||||||
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
environment: 'integration',
|
environment: 'integration',
|
||||||
retryOptions: {},
|
retryOptions: {},
|
||||||
challengeHandlers: [new Dns01Handler(cfAccount)],
|
challengeHandlers: [new Dns01Handler(cfAccount)],
|
||||||
@@ -34,10 +35,9 @@ tap.test('should wipe the certmanager for this test', async () => {
|
|||||||
await smartAcmeInstance.certmanager.wipe();
|
await smartAcmeInstance.certmanager.wipe();
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('get a domain certificate via DNS-01 challenge', async () => {
|
tap.test('get a domain certificate covering bleu.de and *.bleu.de via DNS-01 challenge', async () => {
|
||||||
// Replace 'bleu.de' with your test domain if different
|
|
||||||
const domain = 'bleu.de';
|
const domain = 'bleu.de';
|
||||||
const cert = await smartAcmeInstance.getCertificateForDomain(domain);
|
const cert = await smartAcmeInstance.getCertificateForDomain(domain, { includeWildcard: true });
|
||||||
expect(cert).toHaveProperty('domainName');
|
expect(cert).toHaveProperty('domainName');
|
||||||
expect(cert.domainName).toEqual(domain);
|
expect(cert.domainName).toEqual(domain);
|
||||||
expect(cert).toHaveProperty('publicKey');
|
expect(cert).toHaveProperty('publicKey');
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
import { SmartAcme, MemoryCertManager } from '../ts/index.js';
|
import { SmartAcme, certmanagers } from '../ts/index.js';
|
||||||
|
import { Cert } from '../ts/index.js';
|
||||||
import type { IChallengeHandler } from '../ts/handlers/IChallengeHandler.js';
|
import type { IChallengeHandler } from '../ts/handlers/IChallengeHandler.js';
|
||||||
|
|
||||||
// Dummy handler for testing
|
// Dummy handler for testing
|
||||||
@@ -7,12 +8,13 @@ class DummyHandler implements IChallengeHandler<any> {
|
|||||||
getSupportedTypes(): string[] { return ['dns-01']; }
|
getSupportedTypes(): string[] { return ['dns-01']; }
|
||||||
async prepare(_: any): Promise<void> { /* no-op */ }
|
async prepare(_: any): Promise<void> { /* no-op */ }
|
||||||
async cleanup(_: any): Promise<void> { /* no-op */ }
|
async cleanup(_: any): Promise<void> { /* no-op */ }
|
||||||
|
async checkWetherDomainIsSupported(_: string): Promise<boolean> { return true; }
|
||||||
}
|
}
|
||||||
|
|
||||||
tap.test('constructor throws without challengeHandlers', async () => {
|
tap.test('constructor throws without challengeHandlers', async () => {
|
||||||
expect(() => new SmartAcme({
|
expect(() => new SmartAcme({
|
||||||
accountEmail: 'test@example.com',
|
accountEmail: 'test@example.com',
|
||||||
certManager: new MemoryCertManager(),
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
environment: 'integration',
|
environment: 'integration',
|
||||||
retryOptions: {},
|
retryOptions: {},
|
||||||
} as any)).toThrow();
|
} as any)).toThrow();
|
||||||
@@ -21,12 +23,39 @@ tap.test('constructor throws without challengeHandlers', async () => {
|
|||||||
tap.test('constructor accepts valid challengeHandlers', async () => {
|
tap.test('constructor accepts valid challengeHandlers', async () => {
|
||||||
const sa = new SmartAcme({
|
const sa = new SmartAcme({
|
||||||
accountEmail: 'test@example.com',
|
accountEmail: 'test@example.com',
|
||||||
certManager: new MemoryCertManager(),
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
environment: 'integration',
|
environment: 'integration',
|
||||||
retryOptions: {},
|
retryOptions: {},
|
||||||
challengeHandlers: [new DummyHandler()],
|
challengeHandlers: [new DummyHandler()],
|
||||||
});
|
});
|
||||||
expect(sa).toBeInstanceOf(SmartAcme);
|
expect(sa).toBeInstanceOf(SmartAcme);
|
||||||
});
|
});
|
||||||
|
// Wildcard certificate stub for integration mode (unit test override)
|
||||||
|
tap.test('get wildcard certificate stub in integration mode', async () => {
|
||||||
|
// Temporarily stub SmartAcme.start and getCertificateForDomain for wildcard
|
||||||
|
const origStart = SmartAcme.prototype.start;
|
||||||
|
const origGetCert = SmartAcme.prototype.getCertificateForDomain;
|
||||||
|
try {
|
||||||
|
SmartAcme.prototype.start = async function(): Promise<void> { /* no-op */ };
|
||||||
|
SmartAcme.prototype.getCertificateForDomain = async function(domain: string) {
|
||||||
|
return new Cert({ domainName: domain });
|
||||||
|
};
|
||||||
|
const sa = new SmartAcme({
|
||||||
|
accountEmail: 'domains@lossless.org',
|
||||||
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
|
environment: 'integration',
|
||||||
|
retryOptions: {},
|
||||||
|
challengeHandlers: [new DummyHandler()],
|
||||||
|
});
|
||||||
|
await sa.start();
|
||||||
|
const domainWildcard = '*.example.com';
|
||||||
|
const cert = await sa.getCertificateForDomain(domainWildcard);
|
||||||
|
expect(cert.domainName).toEqual(domainWildcard);
|
||||||
|
await sa.stop();
|
||||||
|
} finally {
|
||||||
|
SmartAcme.prototype.start = origStart;
|
||||||
|
SmartAcme.prototype.getCertificateForDomain = origGetCert;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
export default tap.start();
|
export default tap.start();
|
||||||
94
test/test.wildcard-options.ts
Normal file
94
test/test.wildcard-options.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
import { SmartAcme, certmanagers } from '../ts/index.js';
|
||||||
|
import { SmartacmeCert as Cert } from '../ts/smartacme.classes.cert.js';
|
||||||
|
|
||||||
|
// Simple test to verify wildcard options are correctly processed
|
||||||
|
tap.test('should not include wildcard by default for regular domain', async () => {
|
||||||
|
let orderPayload: any = null;
|
||||||
|
|
||||||
|
// Override the SmartAcme prototype methods for testing
|
||||||
|
const origGetCert = SmartAcme.prototype.getCertificateForDomain;
|
||||||
|
|
||||||
|
// Create a minimal test version of getCertificateForDomain
|
||||||
|
SmartAcme.prototype.getCertificateForDomain = async function(
|
||||||
|
domainArg: string,
|
||||||
|
options?: { includeWildcard?: boolean }
|
||||||
|
) {
|
||||||
|
const certDomainName = domainArg.replace('*.', '');
|
||||||
|
const identifiers = [];
|
||||||
|
|
||||||
|
if (domainArg.startsWith('*.')) {
|
||||||
|
identifiers.push({ type: 'dns', value: domainArg });
|
||||||
|
} else {
|
||||||
|
identifiers.push({ type: 'dns', value: certDomainName });
|
||||||
|
|
||||||
|
if (options?.includeWildcard) {
|
||||||
|
const hasDnsHandler = this.challengeHandlers.some((h) =>
|
||||||
|
h.getSupportedTypes().includes('dns-01')
|
||||||
|
);
|
||||||
|
|
||||||
|
if (hasDnsHandler) {
|
||||||
|
identifiers.push({ type: 'dns', value: `*.${certDomainName}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
orderPayload = { identifiers };
|
||||||
|
return new Cert({ domainName: certDomainName });
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create instance with HTTP-01 only
|
||||||
|
const smartAcme = new SmartAcme({
|
||||||
|
accountEmail: 'test@example.com',
|
||||||
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
|
environment: 'integration',
|
||||||
|
challengeHandlers: [{
|
||||||
|
getSupportedTypes: () => ['http-01'],
|
||||||
|
prepare: async () => {},
|
||||||
|
cleanup: async () => {},
|
||||||
|
checkWetherDomainIsSupported: async () => true,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test 1: Regular domain without wildcard option
|
||||||
|
await smartAcme.getCertificateForDomain('example.com');
|
||||||
|
expect(orderPayload.identifiers.length).toEqual(1);
|
||||||
|
expect(orderPayload.identifiers[0].value).toEqual('example.com');
|
||||||
|
|
||||||
|
// Test 2: Regular domain with wildcard option (but no DNS-01 handler)
|
||||||
|
await smartAcme.getCertificateForDomain('example.com', { includeWildcard: true });
|
||||||
|
expect(orderPayload.identifiers.length).toEqual(1);
|
||||||
|
expect(orderPayload.identifiers[0].value).toEqual('example.com');
|
||||||
|
|
||||||
|
// Create instance with DNS-01
|
||||||
|
const smartAcmeDns = new SmartAcme({
|
||||||
|
accountEmail: 'test@example.com',
|
||||||
|
certManager: new certmanagers.MemoryCertManager(),
|
||||||
|
environment: 'integration',
|
||||||
|
challengeHandlers: [{
|
||||||
|
getSupportedTypes: () => ['dns-01'],
|
||||||
|
prepare: async () => {},
|
||||||
|
cleanup: async () => {},
|
||||||
|
checkWetherDomainIsSupported: async () => true,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test 3: Regular domain with wildcard option and DNS-01 handler
|
||||||
|
await smartAcmeDns.getCertificateForDomain('example.com', { includeWildcard: true });
|
||||||
|
expect(orderPayload.identifiers.length).toEqual(2);
|
||||||
|
expect(orderPayload.identifiers[0].value).toEqual('example.com');
|
||||||
|
expect(orderPayload.identifiers[1].value).toEqual('*.example.com');
|
||||||
|
|
||||||
|
// Test 4: Direct wildcard request
|
||||||
|
await smartAcmeDns.getCertificateForDomain('*.example.com');
|
||||||
|
expect(orderPayload.identifiers.length).toEqual(1);
|
||||||
|
expect(orderPayload.identifiers[0].value).toEqual('*.example.com');
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// Restore original method
|
||||||
|
SmartAcme.prototype.getCertificateForDomain = origGetCert;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartacme',
|
name: '@push.rocks/smartacme',
|
||||||
version: '7.2.3',
|
version: '9.1.0',
|
||||||
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
|
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
|
||||||
}
|
}
|
||||||
|
|||||||
45
ts/acme/acme.classes.account.ts
Normal file
45
ts/acme/acme.classes.account.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import type { AcmeHttpClient } from './acme.classes.http-client.js';
|
||||||
|
import type { IAcmeAccount, IAcmeAccountCreateRequest } from './acme.interfaces.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ACME account management - registration and key management
|
||||||
|
*/
|
||||||
|
export class AcmeAccount {
|
||||||
|
private httpClient: AcmeHttpClient;
|
||||||
|
private accountUrl: string | null = null;
|
||||||
|
|
||||||
|
constructor(httpClient: AcmeHttpClient) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register or retrieve an ACME account.
|
||||||
|
* Uses JWK (not kid) since account URL is not yet known.
|
||||||
|
* Captures account URL from Location header for subsequent requests.
|
||||||
|
*/
|
||||||
|
async create(request: IAcmeAccountCreateRequest): Promise<IAcmeAccount> {
|
||||||
|
const dir = await this.httpClient.getDirectory();
|
||||||
|
const response = await this.httpClient.signedRequest(dir.newAccount, request, {
|
||||||
|
useJwk: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Capture account URL from Location header (used as kid for future requests)
|
||||||
|
const location = response.headers['location'];
|
||||||
|
if (location) {
|
||||||
|
this.accountUrl = location;
|
||||||
|
this.httpClient.kid = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.data as IAcmeAccount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the account URL (kid) for use in JWS headers
|
||||||
|
*/
|
||||||
|
getAccountUrl(): string {
|
||||||
|
if (!this.accountUrl) {
|
||||||
|
throw new Error('Account not yet created - call create() first');
|
||||||
|
}
|
||||||
|
return this.accountUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
45
ts/acme/acme.classes.challenge.ts
Normal file
45
ts/acme/acme.classes.challenge.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import * as crypto from 'node:crypto';
|
||||||
|
import { AcmeCrypto } from './acme.classes.crypto.js';
|
||||||
|
import type { AcmeHttpClient } from './acme.classes.http-client.js';
|
||||||
|
import type { IAcmeChallenge } from './acme.interfaces.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ACME challenge operations - key authorization computation and challenge completion
|
||||||
|
*/
|
||||||
|
export class AcmeChallengeManager {
|
||||||
|
private httpClient: AcmeHttpClient;
|
||||||
|
private accountKeyPem: string;
|
||||||
|
|
||||||
|
constructor(httpClient: AcmeHttpClient, accountKeyPem: string) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.accountKeyPem = accountKeyPem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the key authorization for a challenge.
|
||||||
|
* For http-01: returns `token.thumbprint`
|
||||||
|
* For dns-01: returns `base64url(sha256(token.thumbprint))`
|
||||||
|
*
|
||||||
|
* This is a synchronous, pure-crypto computation.
|
||||||
|
*/
|
||||||
|
getKeyAuthorization(challenge: IAcmeChallenge): string {
|
||||||
|
const jwk = AcmeCrypto.getJwk(this.accountKeyPem);
|
||||||
|
const thumbprint = AcmeCrypto.getJwkThumbprint(jwk);
|
||||||
|
const keyAuth = `${challenge.token}.${thumbprint}`;
|
||||||
|
|
||||||
|
if (challenge.type === 'dns-01') {
|
||||||
|
// DNS-01 uses base64url(SHA-256(keyAuthorization))
|
||||||
|
return crypto.createHash('sha256').update(keyAuth).digest().toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTP-01 and others use the raw key authorization
|
||||||
|
return keyAuth;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify the ACME server to validate a challenge (POST {} to challenge URL)
|
||||||
|
*/
|
||||||
|
async complete(challenge: IAcmeChallenge): Promise<void> {
|
||||||
|
await this.httpClient.signedRequest(challenge.url, {});
|
||||||
|
}
|
||||||
|
}
|
||||||
106
ts/acme/acme.classes.client.ts
Normal file
106
ts/acme/acme.classes.client.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { AcmeCrypto } from './acme.classes.crypto.js';
|
||||||
|
import { ACME_DIRECTORY_URLS } from './acme.classes.directory.js';
|
||||||
|
import { AcmeHttpClient, type TAcmeLogger } from './acme.classes.http-client.js';
|
||||||
|
import { AcmeAccount } from './acme.classes.account.js';
|
||||||
|
import { AcmeOrderManager } from './acme.classes.order.js';
|
||||||
|
import { AcmeChallengeManager } from './acme.classes.challenge.js';
|
||||||
|
import type {
|
||||||
|
IAcmeAccount,
|
||||||
|
IAcmeAccountCreateRequest,
|
||||||
|
IAcmeAuthorization,
|
||||||
|
IAcmeChallenge,
|
||||||
|
IAcmeIdentifier,
|
||||||
|
IAcmeOrder,
|
||||||
|
} from './acme.interfaces.js';
|
||||||
|
|
||||||
|
export interface IAcmeClientOptions {
|
||||||
|
directoryUrl: string;
|
||||||
|
accountKeyPem: string;
|
||||||
|
logger?: TAcmeLogger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Top-level ACME client facade.
|
||||||
|
* Composes HTTP transport, account management, order lifecycle, and challenge handling.
|
||||||
|
*/
|
||||||
|
export class AcmeClient {
|
||||||
|
private httpClient: AcmeHttpClient;
|
||||||
|
private account: AcmeAccount;
|
||||||
|
private orderManager: AcmeOrderManager;
|
||||||
|
private challengeManager: AcmeChallengeManager;
|
||||||
|
|
||||||
|
/** Well-known CA directory URLs */
|
||||||
|
static directory = ACME_DIRECTORY_URLS;
|
||||||
|
/** Crypto utilities */
|
||||||
|
static crypto = AcmeCrypto;
|
||||||
|
|
||||||
|
constructor(options: IAcmeClientOptions) {
|
||||||
|
this.httpClient = new AcmeHttpClient(options.directoryUrl, options.accountKeyPem, options.logger);
|
||||||
|
this.account = new AcmeAccount(this.httpClient);
|
||||||
|
this.orderManager = new AcmeOrderManager(this.httpClient);
|
||||||
|
this.challengeManager = new AcmeChallengeManager(this.httpClient, options.accountKeyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register or retrieve an ACME account
|
||||||
|
*/
|
||||||
|
async createAccount(request: IAcmeAccountCreateRequest): Promise<IAcmeAccount> {
|
||||||
|
return this.account.create(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new certificate order
|
||||||
|
*/
|
||||||
|
async createOrder(opts: { identifiers: IAcmeIdentifier[] }): Promise<IAcmeOrder> {
|
||||||
|
return this.orderManager.create(opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all authorizations for an order
|
||||||
|
*/
|
||||||
|
async getAuthorizations(order: IAcmeOrder): Promise<IAcmeAuthorization[]> {
|
||||||
|
return this.orderManager.getAuthorizations(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the key authorization string for a challenge (sync)
|
||||||
|
*/
|
||||||
|
getChallengeKeyAuthorization(challenge: IAcmeChallenge): string {
|
||||||
|
return this.challengeManager.getKeyAuthorization(challenge);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify the ACME server to validate a challenge
|
||||||
|
*/
|
||||||
|
async completeChallenge(challenge: IAcmeChallenge): Promise<void> {
|
||||||
|
return this.challengeManager.complete(challenge);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Poll an ACME resource until it reaches valid/ready status
|
||||||
|
*/
|
||||||
|
async waitForValidStatus(item: { url: string }): Promise<any> {
|
||||||
|
return this.orderManager.waitForValidStatus(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finalize an order by submitting the CSR
|
||||||
|
*/
|
||||||
|
async finalizeOrder(order: IAcmeOrder, csrPem: string): Promise<void> {
|
||||||
|
return this.orderManager.finalize(order, csrPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download the certificate chain (PEM)
|
||||||
|
*/
|
||||||
|
async getCertificate(order: IAcmeOrder): Promise<string> {
|
||||||
|
return this.orderManager.getCertificate(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy HTTP transport to release sockets and allow process exit.
|
||||||
|
*/
|
||||||
|
destroy(): void {
|
||||||
|
this.httpClient.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
220
ts/acme/acme.classes.crypto.ts
Normal file
220
ts/acme/acme.classes.crypto.ts
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
import * as crypto from 'node:crypto';
|
||||||
|
import type { IAcmeCsrOptions } from './acme.interfaces.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All cryptographic operations for the ACME protocol.
|
||||||
|
* Uses node:crypto for key gen, JWK, JWS signing.
|
||||||
|
* Uses @peculiar/x509 for CSR generation (no native Node.js CSR API).
|
||||||
|
*/
|
||||||
|
export class AcmeCrypto {
|
||||||
|
/**
|
||||||
|
* Generate an RSA private key in PEM format
|
||||||
|
*/
|
||||||
|
static createRsaPrivateKey(modulusLength = 2048): string {
|
||||||
|
const { privateKey } = crypto.generateKeyPairSync('rsa', {
|
||||||
|
modulusLength,
|
||||||
|
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
||||||
|
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
||||||
|
});
|
||||||
|
return privateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export public JWK from PEM private key, keys sorted alphabetically per RFC 7638
|
||||||
|
*/
|
||||||
|
static getJwk(keyPem: string): Record<string, string> {
|
||||||
|
const keyObj = crypto.createPublicKey(keyPem);
|
||||||
|
const jwk = keyObj.export({ format: 'jwk' }) as Record<string, any>;
|
||||||
|
if (jwk.kty === 'RSA') {
|
||||||
|
return { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
||||||
|
} else if (jwk.kty === 'EC') {
|
||||||
|
return { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
||||||
|
}
|
||||||
|
throw new Error(`Unsupported key type: ${jwk.kty}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute JWK Thumbprint (SHA-256, base64url) per RFC 7638
|
||||||
|
*/
|
||||||
|
static getJwkThumbprint(jwk: Record<string, string>): string {
|
||||||
|
let canonical: string;
|
||||||
|
if (jwk.kty === 'RSA') {
|
||||||
|
canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
|
||||||
|
} else if (jwk.kty === 'EC') {
|
||||||
|
canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unsupported key type: ${jwk.kty}`);
|
||||||
|
}
|
||||||
|
const hash = crypto.createHash('sha256').update(canonical).digest();
|
||||||
|
return hash.toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a flattened JWS for ACME requests (RFC 7515)
|
||||||
|
* payload=null means POST-as-GET (empty string payload)
|
||||||
|
*/
|
||||||
|
static createJws(
|
||||||
|
keyPem: string,
|
||||||
|
url: string,
|
||||||
|
payload: any | null,
|
||||||
|
options: { nonce: string; kid?: string; jwk?: Record<string, string> },
|
||||||
|
): { protected: string; payload: string; signature: string } {
|
||||||
|
const header: Record<string, any> = {
|
||||||
|
alg: AcmeCrypto.getAlg(keyPem),
|
||||||
|
nonce: options.nonce,
|
||||||
|
url,
|
||||||
|
};
|
||||||
|
if (options.kid) {
|
||||||
|
header.kid = options.kid;
|
||||||
|
} else if (options.jwk) {
|
||||||
|
header.jwk = options.jwk;
|
||||||
|
} else {
|
||||||
|
header.jwk = AcmeCrypto.getJwk(keyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
const protectedB64 = Buffer.from(JSON.stringify(header)).toString('base64url');
|
||||||
|
const payloadB64 =
|
||||||
|
payload !== null ? Buffer.from(JSON.stringify(payload)).toString('base64url') : '';
|
||||||
|
|
||||||
|
const signingInput = `${protectedB64}.${payloadB64}`;
|
||||||
|
const keyObj = crypto.createPrivateKey(keyPem);
|
||||||
|
const alg = AcmeCrypto.getAlg(keyPem);
|
||||||
|
|
||||||
|
let signature: Buffer;
|
||||||
|
if (alg.startsWith('RS')) {
|
||||||
|
signature = crypto.sign('sha256', Buffer.from(signingInput), keyObj);
|
||||||
|
} else if (alg.startsWith('ES')) {
|
||||||
|
signature = crypto.sign('sha256', Buffer.from(signingInput), {
|
||||||
|
key: keyObj,
|
||||||
|
dsaEncoding: 'ieee-p1363',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unsupported algorithm: ${alg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
protected: protectedB64,
|
||||||
|
payload: payloadB64,
|
||||||
|
signature: signature.toString('base64url'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a CSR (PKCS#10) via @peculiar/x509
|
||||||
|
* Returns [privateKeyPem, csrPem]
|
||||||
|
*/
|
||||||
|
static async createCsr(
|
||||||
|
options: IAcmeCsrOptions,
|
||||||
|
existingKeyPem?: string,
|
||||||
|
): Promise<[string, string]> {
|
||||||
|
const x509 = await import('@peculiar/x509');
|
||||||
|
const { webcrypto } = crypto;
|
||||||
|
x509.cryptoProvider.set(webcrypto as any);
|
||||||
|
|
||||||
|
let keys: CryptoKeyPair;
|
||||||
|
let keyPem: string;
|
||||||
|
|
||||||
|
if (existingKeyPem) {
|
||||||
|
keys = await AcmeCrypto.importKeyPairToWebCrypto(existingKeyPem, webcrypto);
|
||||||
|
keyPem = existingKeyPem;
|
||||||
|
} else {
|
||||||
|
keys = (await webcrypto.subtle.generateKey(
|
||||||
|
{
|
||||||
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
|
modulusLength: 2048,
|
||||||
|
publicExponent: new Uint8Array([1, 0, 1]),
|
||||||
|
hash: 'SHA-256',
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
)) as CryptoKeyPair;
|
||||||
|
|
||||||
|
const pkcs8 = await webcrypto.subtle.exportKey('pkcs8', keys.privateKey);
|
||||||
|
const b64 = Buffer.from(pkcs8).toString('base64');
|
||||||
|
const lines = b64.match(/.{1,64}/g)!;
|
||||||
|
keyPem = `-----BEGIN PRIVATE KEY-----\n${lines.join('\n')}\n-----END PRIVATE KEY-----\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect all DNS names for SAN (CN is always included)
|
||||||
|
const sanNames: string[] = [options.commonName];
|
||||||
|
if (options.altNames) {
|
||||||
|
for (const name of options.altNames) {
|
||||||
|
if (!sanNames.includes(name)) {
|
||||||
|
sanNames.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const csr = await x509.Pkcs10CertificateRequestGenerator.create({
|
||||||
|
name: `CN=${options.commonName}`,
|
||||||
|
keys,
|
||||||
|
signingAlgorithm: { name: 'RSASSA-PKCS1-v1_5' },
|
||||||
|
extensions: [
|
||||||
|
new x509.SubjectAlternativeNameExtension(
|
||||||
|
sanNames.map((name) => ({ type: 'dns' as const, value: name })),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Convert to PEM
|
||||||
|
const csrPem = csr.toString('pem');
|
||||||
|
|
||||||
|
return [keyPem, csrPem];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert PEM to raw DER Buffer (strip headers, decode base64)
|
||||||
|
*/
|
||||||
|
static pemToBuffer(pem: string): Buffer {
|
||||||
|
const lines = pem
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => !line.startsWith('-----') && line.trim().length > 0);
|
||||||
|
return Buffer.from(lines.join(''), 'base64');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine JWS algorithm from key type
|
||||||
|
*/
|
||||||
|
private static getAlg(keyPem: string): string {
|
||||||
|
const keyObj = crypto.createPrivateKey(keyPem);
|
||||||
|
const keyType = keyObj.asymmetricKeyType;
|
||||||
|
if (keyType === 'rsa') return 'RS256';
|
||||||
|
if (keyType === 'ec') {
|
||||||
|
const details = keyObj.asymmetricKeyDetails;
|
||||||
|
if (details?.namedCurve === 'prime256v1' || details?.namedCurve === 'P-256') return 'ES256';
|
||||||
|
if (details?.namedCurve === 'secp384r1' || details?.namedCurve === 'P-384') return 'ES384';
|
||||||
|
return 'ES256';
|
||||||
|
}
|
||||||
|
throw new Error(`Unsupported key type: ${keyType}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import a PEM private key into WebCrypto as a CryptoKeyPair
|
||||||
|
*/
|
||||||
|
private static async importKeyPairToWebCrypto(
|
||||||
|
keyPem: string,
|
||||||
|
wc: typeof crypto.webcrypto,
|
||||||
|
): Promise<CryptoKeyPair> {
|
||||||
|
const keyObj = crypto.createPrivateKey(keyPem);
|
||||||
|
const pkcs8Der = keyObj.export({ type: 'pkcs8', format: 'der' });
|
||||||
|
const privateKey = await wc.subtle.importKey(
|
||||||
|
'pkcs8',
|
||||||
|
pkcs8Der,
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['sign'],
|
||||||
|
);
|
||||||
|
|
||||||
|
const pubKeyObj = crypto.createPublicKey(keyPem);
|
||||||
|
const spkiDer = pubKeyObj.export({ type: 'spki', format: 'der' });
|
||||||
|
const publicKey = await wc.subtle.importKey(
|
||||||
|
'spki',
|
||||||
|
spkiDer,
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['verify'],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { privateKey: privateKey as unknown as CryptoKey, publicKey: publicKey as unknown as CryptoKey };
|
||||||
|
}
|
||||||
|
}
|
||||||
13
ts/acme/acme.classes.directory.ts
Normal file
13
ts/acme/acme.classes.directory.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* ACME directory URL constants for well-known CAs
|
||||||
|
*/
|
||||||
|
export const ACME_DIRECTORY_URLS = {
|
||||||
|
letsencrypt: {
|
||||||
|
production: 'https://acme-v02.api.letsencrypt.org/directory',
|
||||||
|
staging: 'https://acme-staging-v02.api.letsencrypt.org/directory',
|
||||||
|
},
|
||||||
|
buypass: {
|
||||||
|
production: 'https://api.buypass.com/acme/directory',
|
||||||
|
staging: 'https://api.test4.buypass.no/acme/directory',
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
55
ts/acme/acme.classes.error.ts
Normal file
55
ts/acme/acme.classes.error.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Structured ACME protocol error with RFC 8555 fields.
|
||||||
|
* Provides type URN, subproblems, Retry-After, and retryability classification.
|
||||||
|
*/
|
||||||
|
export class AcmeError extends Error {
|
||||||
|
public readonly status: number;
|
||||||
|
public readonly type: string;
|
||||||
|
public readonly detail: string;
|
||||||
|
public readonly subproblems: Array<{ type: string; detail: string; identifier?: { type: string; value: string } }>;
|
||||||
|
public readonly url: string;
|
||||||
|
public readonly retryAfter: number;
|
||||||
|
|
||||||
|
constructor(options: {
|
||||||
|
message?: string;
|
||||||
|
status: number;
|
||||||
|
type?: string;
|
||||||
|
detail?: string;
|
||||||
|
subproblems?: Array<{ type: string; detail: string; identifier?: { type: string; value: string } }>;
|
||||||
|
url?: string;
|
||||||
|
retryAfter?: number;
|
||||||
|
}) {
|
||||||
|
const type = options.type || '';
|
||||||
|
const detail = options.detail || '';
|
||||||
|
const url = options.url || '';
|
||||||
|
const msg =
|
||||||
|
options.message ||
|
||||||
|
`ACME error: ${type || 'unknown'} (HTTP ${options.status}) at ${url || 'unknown'} - ${detail || 'no detail'}`;
|
||||||
|
super(msg);
|
||||||
|
this.name = 'AcmeError';
|
||||||
|
this.status = options.status;
|
||||||
|
this.type = type;
|
||||||
|
this.detail = detail;
|
||||||
|
this.subproblems = options.subproblems || [];
|
||||||
|
this.url = url;
|
||||||
|
this.retryAfter = options.retryAfter || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True for HTTP 429 or ACME rateLimited type URN
|
||||||
|
*/
|
||||||
|
get isRateLimited(): boolean {
|
||||||
|
return this.status === 429 || this.type === 'urn:ietf:params:acme:error:rateLimited';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True for transient/retryable errors: 429, 503, 5xx, badNonce.
|
||||||
|
* False for definitive client errors: 400 (non-badNonce), 403, 404, 409.
|
||||||
|
*/
|
||||||
|
get isRetryable(): boolean {
|
||||||
|
if (this.type === 'urn:ietf:params:acme:error:badNonce') return true;
|
||||||
|
if (this.status === 429 || this.status === 503) return true;
|
||||||
|
if (this.status >= 500) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
249
ts/acme/acme.classes.http-client.ts
Normal file
249
ts/acme/acme.classes.http-client.ts
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
import * as https from 'node:https';
|
||||||
|
import * as http from 'node:http';
|
||||||
|
import { AcmeCrypto } from './acme.classes.crypto.js';
|
||||||
|
import { AcmeError } from './acme.classes.error.js';
|
||||||
|
import type { IAcmeDirectory, IAcmeHttpResponse } from './acme.interfaces.js';
|
||||||
|
|
||||||
|
export type TAcmeLogger = (level: string, message: string, data?: any) => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JWS-signed HTTP transport for ACME protocol.
|
||||||
|
* Handles nonce management, bad-nonce retries, and signed requests.
|
||||||
|
*/
|
||||||
|
export class AcmeHttpClient {
|
||||||
|
private directoryUrl: string;
|
||||||
|
private accountKeyPem: string;
|
||||||
|
private directory: IAcmeDirectory | null = null;
|
||||||
|
private nonce: string | null = null;
|
||||||
|
public kid: string | null = null;
|
||||||
|
private logger?: TAcmeLogger;
|
||||||
|
private httpsAgent: https.Agent;
|
||||||
|
private httpAgent: http.Agent;
|
||||||
|
|
||||||
|
constructor(directoryUrl: string, accountKeyPem: string, logger?: TAcmeLogger) {
|
||||||
|
this.directoryUrl = directoryUrl;
|
||||||
|
this.accountKeyPem = accountKeyPem;
|
||||||
|
this.logger = logger;
|
||||||
|
this.httpsAgent = new https.Agent({ keepAlive: false });
|
||||||
|
this.httpAgent = new http.Agent({ keepAlive: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy HTTP agents to release sockets and allow process exit.
|
||||||
|
*/
|
||||||
|
destroy(): void {
|
||||||
|
this.httpsAgent.destroy();
|
||||||
|
this.httpAgent.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
private log(level: string, message: string, data?: any): void {
|
||||||
|
if (this.logger) {
|
||||||
|
this.logger(level, message, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET the ACME directory (cached after first call)
|
||||||
|
*/
|
||||||
|
async getDirectory(): Promise<IAcmeDirectory> {
|
||||||
|
if (this.directory) return this.directory;
|
||||||
|
const response = await this.httpRequest(this.directoryUrl, 'GET');
|
||||||
|
if (response.status !== 200) {
|
||||||
|
throw new AcmeError({
|
||||||
|
status: response.status,
|
||||||
|
type: response.data?.type || '',
|
||||||
|
detail: `Failed to fetch ACME directory`,
|
||||||
|
url: this.directoryUrl,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.directory = response.data as IAcmeDirectory;
|
||||||
|
return this.directory;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch a fresh nonce via HEAD to newNonce
|
||||||
|
*/
|
||||||
|
async getNonce(): Promise<string> {
|
||||||
|
if (this.nonce) {
|
||||||
|
const n = this.nonce;
|
||||||
|
this.nonce = null;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
const dir = await this.getDirectory();
|
||||||
|
const response = await this.httpRequest(dir.newNonce, 'HEAD');
|
||||||
|
const nonce = response.headers['replay-nonce'];
|
||||||
|
if (!nonce) {
|
||||||
|
throw new Error('No replay-nonce header in newNonce response');
|
||||||
|
}
|
||||||
|
return nonce;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a JWS-signed POST request to an ACME endpoint.
|
||||||
|
* Handles nonce rotation and bad-nonce retries (up to 5).
|
||||||
|
* payload=null means POST-as-GET.
|
||||||
|
*/
|
||||||
|
async signedRequest(
|
||||||
|
url: string,
|
||||||
|
payload: any | null,
|
||||||
|
options?: { useJwk?: boolean },
|
||||||
|
): Promise<IAcmeHttpResponse> {
|
||||||
|
const maxRetries = 5;
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||||
|
const nonce = await this.getNonce();
|
||||||
|
|
||||||
|
const jwsOptions: { nonce: string; kid?: string; jwk?: Record<string, string> } = { nonce };
|
||||||
|
if (options?.useJwk) {
|
||||||
|
jwsOptions.jwk = AcmeCrypto.getJwk(this.accountKeyPem);
|
||||||
|
} else if (this.kid) {
|
||||||
|
jwsOptions.kid = this.kid;
|
||||||
|
} else {
|
||||||
|
jwsOptions.jwk = AcmeCrypto.getJwk(this.accountKeyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
const jws = AcmeCrypto.createJws(this.accountKeyPem, url, payload, jwsOptions);
|
||||||
|
const body = JSON.stringify(jws);
|
||||||
|
|
||||||
|
const response = await this.httpRequest(url, 'POST', body, {
|
||||||
|
'Content-Type': 'application/jose+json',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save nonce from response for reuse
|
||||||
|
if (response.headers['replay-nonce']) {
|
||||||
|
this.nonce = response.headers['replay-nonce'];
|
||||||
|
}
|
||||||
|
|
||||||
|
this.log('debug', `ACME request: POST ${url} → ${response.status}`);
|
||||||
|
|
||||||
|
// Retry on bad-nonce
|
||||||
|
if (
|
||||||
|
response.status === 400 &&
|
||||||
|
response.data?.type === 'urn:ietf:params:acme:error:badNonce'
|
||||||
|
) {
|
||||||
|
this.log('debug', `Bad nonce on attempt ${attempt + 1}, retrying`);
|
||||||
|
if (attempt < maxRetries) {
|
||||||
|
this.nonce = null; // Force fresh nonce
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Throw on error responses
|
||||||
|
if (response.status >= 400) {
|
||||||
|
const retryAfterRaw = response.headers['retry-after'];
|
||||||
|
let retryAfter = 0;
|
||||||
|
if (retryAfterRaw) {
|
||||||
|
const parsed = parseInt(retryAfterRaw, 10);
|
||||||
|
if (!isNaN(parsed)) {
|
||||||
|
retryAfter = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const acmeError = new AcmeError({
|
||||||
|
status: response.status,
|
||||||
|
type: response.data?.type || '',
|
||||||
|
detail: response.data?.detail || JSON.stringify(response.data),
|
||||||
|
subproblems: response.data?.subproblems,
|
||||||
|
url,
|
||||||
|
retryAfter,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (acmeError.isRateLimited) {
|
||||||
|
this.log('warn', `RATE LIMITED: ${url} (HTTP ${response.status}), Retry-After: ${retryAfter}s`, {
|
||||||
|
type: acmeError.type,
|
||||||
|
detail: acmeError.detail,
|
||||||
|
retryAfter,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.log('warn', `ACME error: ${url} (HTTP ${response.status})`, {
|
||||||
|
type: acmeError.type,
|
||||||
|
detail: acmeError.detail,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
throw acmeError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Max bad-nonce retries exceeded');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw HTTP request using native node:https
|
||||||
|
*/
|
||||||
|
private httpRequest(
|
||||||
|
url: string,
|
||||||
|
method: string,
|
||||||
|
body?: string,
|
||||||
|
headers?: Record<string, string>,
|
||||||
|
): Promise<IAcmeHttpResponse> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const urlObj = new URL(url);
|
||||||
|
const isHttps = urlObj.protocol === 'https:';
|
||||||
|
const lib = isHttps ? https : http;
|
||||||
|
|
||||||
|
const requestHeaders: Record<string, string | number> = {
|
||||||
|
...headers,
|
||||||
|
'User-Agent': 'smartacme-acme-client/1.0',
|
||||||
|
};
|
||||||
|
if (body) {
|
||||||
|
requestHeaders['Content-Length'] = Buffer.byteLength(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
const options: https.RequestOptions = {
|
||||||
|
hostname: urlObj.hostname,
|
||||||
|
port: urlObj.port || (isHttps ? 443 : 80),
|
||||||
|
path: urlObj.pathname + urlObj.search,
|
||||||
|
method,
|
||||||
|
headers: requestHeaders,
|
||||||
|
agent: isHttps ? this.httpsAgent : this.httpAgent,
|
||||||
|
};
|
||||||
|
|
||||||
|
const req = lib.request(options, (res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
res.on('end', () => {
|
||||||
|
const responseBody = Buffer.concat(chunks).toString('utf-8');
|
||||||
|
|
||||||
|
// Normalize headers to lowercase single-value
|
||||||
|
const responseHeaders: Record<string, string> = {};
|
||||||
|
for (const [key, value] of Object.entries(res.headers)) {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
responseHeaders[key.toLowerCase()] = value;
|
||||||
|
} else if (Array.isArray(value)) {
|
||||||
|
responseHeaders[key.toLowerCase()] = value[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse JSON if applicable, otherwise return raw string
|
||||||
|
let data: any;
|
||||||
|
const contentType = responseHeaders['content-type'] || '';
|
||||||
|
if (contentType.includes('json')) {
|
||||||
|
try {
|
||||||
|
data = JSON.parse(responseBody);
|
||||||
|
} catch {
|
||||||
|
data = responseBody;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
data = responseBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve({
|
||||||
|
status: res.statusCode || 0,
|
||||||
|
headers: responseHeaders,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', reject);
|
||||||
|
req.setTimeout(30000, () => {
|
||||||
|
req.destroy(new Error('Request timeout'));
|
||||||
|
});
|
||||||
|
if (body) req.write(body);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
125
ts/acme/acme.classes.order.ts
Normal file
125
ts/acme/acme.classes.order.ts
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import { AcmeCrypto } from './acme.classes.crypto.js';
|
||||||
|
import { AcmeError } from './acme.classes.error.js';
|
||||||
|
import type { AcmeHttpClient } from './acme.classes.http-client.js';
|
||||||
|
import type {
|
||||||
|
IAcmeAuthorization,
|
||||||
|
IAcmeIdentifier,
|
||||||
|
IAcmeOrder,
|
||||||
|
} from './acme.interfaces.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ACME order lifecycle management.
|
||||||
|
* Handles order creation, authorization retrieval, finalization, and certificate download.
|
||||||
|
*/
|
||||||
|
export class AcmeOrderManager {
|
||||||
|
private httpClient: AcmeHttpClient;
|
||||||
|
|
||||||
|
constructor(httpClient: AcmeHttpClient) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new ACME order for the given identifiers
|
||||||
|
*/
|
||||||
|
async create(opts: { identifiers: IAcmeIdentifier[] }): Promise<IAcmeOrder> {
|
||||||
|
const dir = await this.httpClient.getDirectory();
|
||||||
|
const response = await this.httpClient.signedRequest(dir.newOrder, {
|
||||||
|
identifiers: opts.identifiers,
|
||||||
|
});
|
||||||
|
|
||||||
|
const order = response.data as IAcmeOrder;
|
||||||
|
// Capture order URL from Location header
|
||||||
|
order.url = response.headers['location'] || '';
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve all authorizations for an order (POST-as-GET each authorization URL)
|
||||||
|
*/
|
||||||
|
async getAuthorizations(order: IAcmeOrder): Promise<IAcmeAuthorization[]> {
|
||||||
|
const authorizations: IAcmeAuthorization[] = [];
|
||||||
|
for (const authzUrl of order.authorizations) {
|
||||||
|
const response = await this.httpClient.signedRequest(authzUrl, null);
|
||||||
|
authorizations.push(response.data as IAcmeAuthorization);
|
||||||
|
}
|
||||||
|
return authorizations;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finalize an order by submitting the CSR.
|
||||||
|
* Waits for the order to reach 'valid' status.
|
||||||
|
* Mutates the order object with updated status and certificate URL.
|
||||||
|
*/
|
||||||
|
async finalize(order: IAcmeOrder, csrPem: string): Promise<void> {
|
||||||
|
// Convert PEM CSR to base64url DER for ACME
|
||||||
|
const csrDer = AcmeCrypto.pemToBuffer(csrPem);
|
||||||
|
const csrB64url = csrDer.toString('base64url');
|
||||||
|
|
||||||
|
const response = await this.httpClient.signedRequest(order.finalize, { csr: csrB64url });
|
||||||
|
|
||||||
|
// Update order with response data
|
||||||
|
const updatedOrder = response.data;
|
||||||
|
order.status = updatedOrder.status;
|
||||||
|
if (updatedOrder.certificate) {
|
||||||
|
order.certificate = updatedOrder.certificate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If not yet valid, poll until it is
|
||||||
|
if (order.status !== 'valid' && order.url) {
|
||||||
|
const finalOrder = await this.waitForValidStatus({ url: order.url });
|
||||||
|
order.status = finalOrder.status;
|
||||||
|
order.certificate = finalOrder.certificate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download the certificate chain (PEM) from the order's certificate URL
|
||||||
|
*/
|
||||||
|
async getCertificate(order: IAcmeOrder): Promise<string> {
|
||||||
|
if (!order.certificate) {
|
||||||
|
throw new Error('Order does not have a certificate URL - finalize first');
|
||||||
|
}
|
||||||
|
const response = await this.httpClient.signedRequest(order.certificate, null);
|
||||||
|
// Certificate chain is returned as PEM text
|
||||||
|
return typeof response.data === 'string' ? response.data : response.data.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Poll an ACME resource (order or challenge) until it reaches 'valid' or 'ready' status.
|
||||||
|
* Uses exponential backoff with Retry-After header support.
|
||||||
|
*/
|
||||||
|
async waitForValidStatus(
|
||||||
|
item: { url: string },
|
||||||
|
opts?: { maxAttempts?: number; initialDelayMs?: number },
|
||||||
|
): Promise<any> {
|
||||||
|
const maxAttempts = opts?.maxAttempts ?? 30;
|
||||||
|
const initialDelay = opts?.initialDelayMs ?? 1000;
|
||||||
|
|
||||||
|
for (let i = 0; i < maxAttempts; i++) {
|
||||||
|
const response = await this.httpClient.signedRequest(item.url, null);
|
||||||
|
const body = response.data;
|
||||||
|
|
||||||
|
if (body.status === 'valid' || body.status === 'ready') {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
if (body.status === 'invalid') {
|
||||||
|
const challengeError = body.challenges?.find((c: any) => c.error)?.error;
|
||||||
|
throw new AcmeError({
|
||||||
|
status: 0,
|
||||||
|
type: challengeError?.type || 'urn:ietf:params:acme:error:rejectedIdentifier',
|
||||||
|
detail: challengeError?.detail || JSON.stringify(body),
|
||||||
|
subproblems: challengeError?.subproblems,
|
||||||
|
url: item.url,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Respect Retry-After header, otherwise exponential backoff
|
||||||
|
const retryAfter = parseInt(response.headers['retry-after'] || '0', 10);
|
||||||
|
const delay =
|
||||||
|
retryAfter > 0 ? retryAfter * 1000 : Math.min(initialDelay * Math.pow(2, i), 30000);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Timeout waiting for valid status after ${maxAttempts} attempts`);
|
||||||
|
}
|
||||||
|
}
|
||||||
74
ts/acme/acme.interfaces.ts
Normal file
74
ts/acme/acme.interfaces.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* ACME Protocol interfaces per RFC 8555
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface IAcmeDirectory {
|
||||||
|
newNonce: string;
|
||||||
|
newAccount: string;
|
||||||
|
newOrder: string;
|
||||||
|
newAuthz?: string;
|
||||||
|
revokeCert?: string;
|
||||||
|
keyChange?: string;
|
||||||
|
meta?: IAcmeDirectoryMeta;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeDirectoryMeta {
|
||||||
|
termsOfService?: string;
|
||||||
|
website?: string;
|
||||||
|
caaIdentities?: string[];
|
||||||
|
externalAccountRequired?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeIdentifier {
|
||||||
|
type: 'dns';
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeAccount {
|
||||||
|
status: string;
|
||||||
|
contact?: string[];
|
||||||
|
termsOfServiceAgreed?: boolean;
|
||||||
|
orders?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeAccountCreateRequest {
|
||||||
|
termsOfServiceAgreed: boolean;
|
||||||
|
contact?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeOrder {
|
||||||
|
url: string;
|
||||||
|
status: string;
|
||||||
|
expires?: string;
|
||||||
|
identifiers: IAcmeIdentifier[];
|
||||||
|
authorizations: string[];
|
||||||
|
finalize: string;
|
||||||
|
certificate?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeAuthorization {
|
||||||
|
identifier: IAcmeIdentifier;
|
||||||
|
status: string;
|
||||||
|
expires?: string;
|
||||||
|
challenges: IAcmeChallenge[];
|
||||||
|
wildcard?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeChallenge {
|
||||||
|
type: string;
|
||||||
|
url: string;
|
||||||
|
status: string;
|
||||||
|
token: string;
|
||||||
|
validated?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeCsrOptions {
|
||||||
|
commonName: string;
|
||||||
|
altNames?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAcmeHttpResponse {
|
||||||
|
status: number;
|
||||||
|
headers: Record<string, string>;
|
||||||
|
data: any;
|
||||||
|
}
|
||||||
16
ts/acme/index.ts
Normal file
16
ts/acme/index.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export { AcmeClient, type IAcmeClientOptions } from './acme.classes.client.js';
|
||||||
|
export { AcmeCrypto } from './acme.classes.crypto.js';
|
||||||
|
export { AcmeError } from './acme.classes.error.js';
|
||||||
|
export { ACME_DIRECTORY_URLS } from './acme.classes.directory.js';
|
||||||
|
export type {
|
||||||
|
IAcmeDirectory,
|
||||||
|
IAcmeDirectoryMeta,
|
||||||
|
IAcmeIdentifier,
|
||||||
|
IAcmeAccount,
|
||||||
|
IAcmeAccountCreateRequest,
|
||||||
|
IAcmeOrder,
|
||||||
|
IAcmeAuthorization,
|
||||||
|
IAcmeChallenge,
|
||||||
|
IAcmeCsrOptions,
|
||||||
|
IAcmeHttpResponse,
|
||||||
|
} from './acme.interfaces.js';
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as plugins from '../smartacme.plugins.js';
|
import * as plugins from '../plugins.js';
|
||||||
import type { ICertManager } from '../interfaces/certmanager.js';
|
import type { ICertManager } from '../interfaces/certmanager.js';
|
||||||
import { SmartacmeCert } from '../smartacme.classes.cert.js';
|
import { SmartacmeCert } from '../smartacme.classes.cert.js';
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as plugins from '../smartacme.plugins.js';
|
import * as plugins from '../plugins.js';
|
||||||
import type { ICertManager } from '../interfaces/certmanager.js';
|
import type { ICertManager } from '../interfaces/certmanager.js';
|
||||||
import { SmartacmeCert } from '../smartacme.classes.cert.js';
|
import { SmartacmeCert } from '../smartacme.classes.cert.js';
|
||||||
|
|
||||||
@@ -14,7 +14,6 @@ export class MongoCertManager implements ICertManager {
|
|||||||
*/
|
*/
|
||||||
constructor(mongoDescriptor: plugins.smartdata.IMongoDescriptor) {
|
constructor(mongoDescriptor: plugins.smartdata.IMongoDescriptor) {
|
||||||
this.db = new plugins.smartdata.SmartdataDb(mongoDescriptor);
|
this.db = new plugins.smartdata.SmartdataDb(mongoDescriptor);
|
||||||
// Use a single EasyStore document to hold all certs keyed by domainName
|
|
||||||
this.store = new plugins.smartdata.EasyStore<Record<string, any>>(
|
this.store = new plugins.smartdata.EasyStore<Record<string, any>>(
|
||||||
'smartacme-certs',
|
'smartacme-certs',
|
||||||
this.db,
|
this.db,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as plugins from '../smartacme.plugins.js';
|
import * as plugins from '../plugins.js';
|
||||||
import type { IChallengeHandler } from './IChallengeHandler.js';
|
import type { IChallengeHandler } from './IChallengeHandler.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { promises as fs } from 'fs';
|
import * as plugins from '../plugins.js';
|
||||||
import * as path from 'path';
|
|
||||||
import type { IChallengeHandler } from './IChallengeHandler.js';
|
import type { IChallengeHandler } from './IChallengeHandler.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +18,9 @@ export class Http01Webroot implements IChallengeHandler<{
|
|||||||
keyAuthorization: string;
|
keyAuthorization: string;
|
||||||
webPath: string;
|
webPath: string;
|
||||||
}> {
|
}> {
|
||||||
|
private smartnetworkInstance = new plugins.smartnetwork.SmartNetwork();
|
||||||
|
private smartdnsClient = new plugins.smartdnsClient.Smartdns({});
|
||||||
|
|
||||||
private webroot: string;
|
private webroot: string;
|
||||||
|
|
||||||
constructor(options: Http01WebrootOptions) {
|
constructor(options: Http01WebrootOptions) {
|
||||||
@@ -31,10 +33,10 @@ export class Http01Webroot implements IChallengeHandler<{
|
|||||||
|
|
||||||
public async prepare(ch: { token: string; keyAuthorization: string; webPath: string }): Promise<void> {
|
public async prepare(ch: { token: string; keyAuthorization: string; webPath: string }): Promise<void> {
|
||||||
const relWebPath = ch.webPath.replace(/^\/+/, '');
|
const relWebPath = ch.webPath.replace(/^\/+/, '');
|
||||||
const filePath = path.join(this.webroot, relWebPath);
|
const filePath = plugins.path.join(this.webroot, relWebPath);
|
||||||
const dir = path.dirname(filePath);
|
const dir = plugins.path.dirname(filePath);
|
||||||
await fs.mkdir(dir, { recursive: true });
|
await plugins.fs.promises.mkdir(dir, { recursive: true });
|
||||||
await fs.writeFile(filePath, ch.keyAuthorization, 'utf8');
|
await plugins.fs.promises.writeFile(filePath, ch.keyAuthorization, 'utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
public async verify(ch: { webPath: string; keyAuthorization: string }): Promise<void> {
|
public async verify(ch: { webPath: string; keyAuthorization: string }): Promise<void> {
|
||||||
@@ -44,11 +46,24 @@ export class Http01Webroot implements IChallengeHandler<{
|
|||||||
|
|
||||||
public async cleanup(ch: { token: string; webPath: string }): Promise<void> {
|
public async cleanup(ch: { token: string; webPath: string }): Promise<void> {
|
||||||
const relWebPath = ch.webPath.replace(/^\/+/, '');
|
const relWebPath = ch.webPath.replace(/^\/+/, '');
|
||||||
const filePath = path.join(this.webroot, relWebPath);
|
const filePath = plugins.path.join(this.webroot, relWebPath);
|
||||||
try {
|
try {
|
||||||
await fs.unlink(filePath);
|
await plugins.fs.promises.unlink(filePath);
|
||||||
} catch {
|
} catch {
|
||||||
// ignore missing file
|
// ignore missing file
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async checkWetherDomainIsSupported(domainArg: string): Promise<boolean> {
|
||||||
|
const publicIps = await this.smartnetworkInstance.getPublicIps();
|
||||||
|
const aRecords = await this.smartdnsClient.getRecordsA(domainArg);
|
||||||
|
const aaaaRecords = await this.smartdnsClient.getRecordsAAAA(domainArg);
|
||||||
|
if (aRecords.length && aRecords.some(record => record.value !== publicIps.v4)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (aaaaRecords.length && aaaaRecords.some(record => record.value !== publicIps.v6)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import * as plugins from '../plugins.js';
|
||||||
import type { IChallengeHandler } from './IChallengeHandler.js';
|
import type { IChallengeHandler } from './IChallengeHandler.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -13,6 +14,8 @@ export interface Http01MemoryHandlerChallenge {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class Http01MemoryHandler implements IChallengeHandler<Http01MemoryHandlerChallenge> {
|
export class Http01MemoryHandler implements IChallengeHandler<Http01MemoryHandlerChallenge> {
|
||||||
|
private smartnetworkInstance = new plugins.smartnetwork.SmartNetwork();
|
||||||
|
private smartdnsClient = new plugins.smartdnsClient.Smartdns({});
|
||||||
private store: Map<string, string> = new Map();
|
private store: Map<string, string> = new Map();
|
||||||
|
|
||||||
public getSupportedTypes(): string[] {
|
public getSupportedTypes(): string[] {
|
||||||
@@ -64,4 +67,17 @@ export class Http01MemoryHandler implements IChallengeHandler<Http01MemoryHandle
|
|||||||
res.statusCode = 404;
|
res.statusCode = 404;
|
||||||
return res.end();
|
return res.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async checkWetherDomainIsSupported(domainArg: string): Promise<boolean> {
|
||||||
|
const publicIps = await this.smartnetworkInstance.getPublicIps();
|
||||||
|
const aRecords = await this.smartdnsClient.getRecordsA(domainArg);
|
||||||
|
const aaaaRecords = await this.smartdnsClient.getRecordsAAAA(domainArg);
|
||||||
|
if (aRecords.length && aRecords.some((record) => record.value !== publicIps.v4)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (aaaaRecords.length && aaaaRecords.some((record) => record.value !== publicIps.v6)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -19,4 +19,6 @@ export interface IChallengeHandler<T> {
|
|||||||
* Clean up resources: remove DNS record, stop server.
|
* Clean up resources: remove DNS record, stop server.
|
||||||
*/
|
*/
|
||||||
cleanup(ch: T): Promise<void>;
|
cleanup(ch: T): Promise<void>;
|
||||||
|
|
||||||
|
checkWetherDomainIsSupported(domainArg: string): Promise<boolean>;
|
||||||
}
|
}
|
||||||
12
ts/index.ts
12
ts/index.ts
@@ -1,4 +1,14 @@
|
|||||||
export * from './smartacme.classes.smartacme.js';
|
export * from './smartacme.classes.smartacme.js';
|
||||||
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';
|
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';
|
||||||
export type { ICertManager } from './interfaces/certmanager.js';
|
export type { ICertManager } from './interfaces/certmanager.js';
|
||||||
export { MemoryCertManager, MongoCertManager } from './certmanagers/index.js';
|
|
||||||
|
// certmanagers
|
||||||
|
import * as certmanagers from './certmanagers/index.js';
|
||||||
|
export { certmanagers };
|
||||||
|
|
||||||
|
// handlers
|
||||||
|
import * as handlers from './handlers/index.js';
|
||||||
|
export { handlers };
|
||||||
|
|
||||||
|
// re-export taskbuffer event types for consumers
|
||||||
|
export type { ITaskEvent, ITaskMetadata } from '@push.rocks/taskbuffer';
|
||||||
|
|||||||
@@ -1,24 +1,25 @@
|
|||||||
|
// node native
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
export { fs, path };
|
||||||
|
|
||||||
// @apiclient.xyz scope
|
// @apiclient.xyz scope
|
||||||
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
import * as cloudflare from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
export { cloudflare };
|
export { cloudflare };
|
||||||
|
|
||||||
// @apiglobal scope
|
// @push.rocks scope
|
||||||
import * as typedserver from '@api.global/typedserver';
|
|
||||||
|
|
||||||
export { typedserver };
|
|
||||||
|
|
||||||
// @pushrocks scope
|
|
||||||
import * as lik from '@push.rocks/lik';
|
import * as lik from '@push.rocks/lik';
|
||||||
import * as smartdata from '@push.rocks/smartdata';
|
import * as smartdata from '@push.rocks/smartdata';
|
||||||
import * as smartdelay from '@push.rocks/smartdelay';
|
import * as smartdelay from '@push.rocks/smartdelay';
|
||||||
import * as smartdnsClient from '@push.rocks/smartdns/client';
|
import * as smartdnsClient from '@push.rocks/smartdns/client';
|
||||||
import * as smartlog from '@push.rocks/smartlog';
|
import * as smartlog from '@push.rocks/smartlog';
|
||||||
import * as smartpromise from '@push.rocks/smartpromise';
|
import * as smartnetwork from '@push.rocks/smartnetwork';
|
||||||
import * as smartrequest from '@push.rocks/smartrequest';
|
|
||||||
import * as smartunique from '@push.rocks/smartunique';
|
import * as smartunique from '@push.rocks/smartunique';
|
||||||
import * as smartstring from '@push.rocks/smartstring';
|
import * as smartstring from '@push.rocks/smartstring';
|
||||||
import * as smarttime from '@push.rocks/smarttime';
|
import * as smarttime from '@push.rocks/smarttime';
|
||||||
|
import * as taskbuffer from '@push.rocks/taskbuffer';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
lik,
|
lik,
|
||||||
@@ -26,11 +27,11 @@ export {
|
|||||||
smartdelay,
|
smartdelay,
|
||||||
smartdnsClient,
|
smartdnsClient,
|
||||||
smartlog,
|
smartlog,
|
||||||
smartpromise,
|
smartnetwork,
|
||||||
smartrequest,
|
|
||||||
smartunique,
|
smartunique,
|
||||||
smartstring,
|
smartstring,
|
||||||
smarttime,
|
smarttime,
|
||||||
|
taskbuffer,
|
||||||
};
|
};
|
||||||
|
|
||||||
// @tsclass scope
|
// @tsclass scope
|
||||||
@@ -38,8 +39,8 @@ import * as tsclass from '@tsclass/tsclass';
|
|||||||
|
|
||||||
export { tsclass };
|
export { tsclass };
|
||||||
|
|
||||||
// third party scope
|
// acme protocol (custom implementation)
|
||||||
import * as acme from 'acme-client';
|
import * as acme from './acme/index.js';
|
||||||
|
|
||||||
export { acme };
|
export { acme };
|
||||||
// local handlers for challenge types
|
// local handlers for challenge types
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as plugins from './smartacme.plugins.js';
|
import * as plugins from './plugins.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plain certificate record.
|
* Plain certificate record.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import * as plugins from './smartacme.plugins.js';
|
import * as plugins from './plugins.js';
|
||||||
import * as interfaces from './interfaces/index.js';
|
import * as interfaces from './interfaces/index.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -10,10 +10,17 @@ export class SmartacmeCertMatcher {
|
|||||||
* for wild card certificates
|
* for wild card certificates
|
||||||
* @param domainNameArg the domainNameArg to create the scope from
|
* @param domainNameArg the domainNameArg to create the scope from
|
||||||
*/
|
*/
|
||||||
public getCertificateDomainNameByDomainName(domainNameArg: string): string {
|
public getCertificateDomainNameByDomainName(domainNameArg: string): string | undefined {
|
||||||
|
// Handle wildcard domains by stripping the '*.' prefix.
|
||||||
|
if (domainNameArg.startsWith('*.')) {
|
||||||
|
return domainNameArg.slice(2);
|
||||||
|
}
|
||||||
const originalDomain = new plugins.smartstring.Domain(domainNameArg);
|
const originalDomain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
// For domains with up to 3 levels (no level4), return base domain.
|
||||||
if (!originalDomain.level4) {
|
if (!originalDomain.level4) {
|
||||||
return `${originalDomain.level2}.${originalDomain.level1}`;
|
return `${originalDomain.level2}.${originalDomain.level1}`;
|
||||||
}
|
}
|
||||||
|
// Deeper domains (4+ levels) are not supported.
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,31 @@
|
|||||||
import * as plugins from './smartacme.plugins.js';
|
import * as plugins from './plugins.js';
|
||||||
import type { ICertManager } from './interfaces/certmanager.js';
|
import type { ICertManager } from './interfaces/certmanager.js';
|
||||||
import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
|
import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
|
||||||
import { commitinfo } from './00_commitinfo_data.js';
|
import { commitinfo } from './00_commitinfo_data.js';
|
||||||
import { SmartacmeCert } from './smartacme.classes.cert.js';
|
import { SmartacmeCert } from './smartacme.classes.cert.js';
|
||||||
|
|
||||||
|
// ── Types & constants for certificate issuance task ──────────────────────────
|
||||||
|
|
||||||
|
interface ICertIssuanceInput {
|
||||||
|
certDomainName: string;
|
||||||
|
domainArg: string;
|
||||||
|
isWildcardRequest: boolean;
|
||||||
|
includeWildcard: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CERT_ISSUANCE_STEPS = [
|
||||||
|
{ name: 'prepare', description: 'Creating ACME order', percentage: 10 },
|
||||||
|
{ name: 'authorize', description: 'Solving ACME challenges', percentage: 40 },
|
||||||
|
{ name: 'finalize', description: 'Finalizing and getting cert', percentage: 30 },
|
||||||
|
{ name: 'store', description: 'Storing certificate', percentage: 20 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* the options for the class @see SmartAcme
|
* the options for the class @see SmartAcme
|
||||||
*/
|
*/
|
||||||
export interface ISmartAcmeOptions {
|
export interface ISmartAcmeOptions {
|
||||||
accountPrivateKey?: string;
|
|
||||||
accountEmail: string;
|
accountEmail: string;
|
||||||
|
accountPrivateKey?: string;
|
||||||
/**
|
/**
|
||||||
* Certificate storage manager (e.g., Mongo or in-memory).
|
* Certificate storage manager (e.g., Mongo or in-memory).
|
||||||
*/
|
*/
|
||||||
@@ -38,6 +54,21 @@ export interface ISmartAcmeOptions {
|
|||||||
* Defaults to ['dns-01'] or first supported type from handlers.
|
* Defaults to ['dns-01'] or first supported type from handlers.
|
||||||
*/
|
*/
|
||||||
challengePriority?: string[];
|
challengePriority?: string[];
|
||||||
|
/**
|
||||||
|
* Maximum number of concurrent ACME issuances across all domains.
|
||||||
|
* Defaults to 5.
|
||||||
|
*/
|
||||||
|
maxConcurrentIssuances?: number;
|
||||||
|
/**
|
||||||
|
* Maximum ACME orders allowed within the sliding window.
|
||||||
|
* Defaults to 250 (conservative limit under Let's Encrypt's 300/3h).
|
||||||
|
*/
|
||||||
|
maxOrdersPerWindow?: number;
|
||||||
|
/**
|
||||||
|
* Sliding window duration in milliseconds for rate limiting.
|
||||||
|
* Defaults to 3 hours (10_800_000 ms).
|
||||||
|
*/
|
||||||
|
orderWindowMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,7 +85,7 @@ export class SmartAcme {
|
|||||||
private options: ISmartAcmeOptions;
|
private options: ISmartAcmeOptions;
|
||||||
|
|
||||||
// the acme client
|
// the acme client
|
||||||
private client: plugins.acme.Client;
|
private client: plugins.acme.AcmeClient;
|
||||||
private smartdns = new plugins.smartdnsClient.Smartdns({});
|
private smartdns = new plugins.smartdnsClient.Smartdns({});
|
||||||
public logger: plugins.smartlog.Smartlog;
|
public logger: plugins.smartlog.Smartlog;
|
||||||
|
|
||||||
@@ -64,17 +95,31 @@ export class SmartAcme {
|
|||||||
|
|
||||||
// certificate manager for persistence (implements ICertManager)
|
// certificate manager for persistence (implements ICertManager)
|
||||||
public certmanager: ICertManager;
|
public certmanager: ICertManager;
|
||||||
|
// configured pluggable ACME challenge handlers
|
||||||
|
public challengeHandlers: plugins.handlers.IChallengeHandler<any>[];
|
||||||
|
|
||||||
|
|
||||||
private certmatcher: SmartacmeCertMatcher;
|
private certmatcher: SmartacmeCertMatcher;
|
||||||
// retry/backoff configuration (resolved with defaults)
|
// retry/backoff configuration (resolved with defaults)
|
||||||
private retryOptions: { retries: number; factor: number; minTimeoutMs: number; maxTimeoutMs: number };
|
private retryOptions: { retries: number; factor: number; minTimeoutMs: number; maxTimeoutMs: number };
|
||||||
// track pending DNS challenges for graceful shutdown
|
// track pending DNS challenges for graceful shutdown
|
||||||
private pendingChallenges: plugins.tsclass.network.IDnsChallenge[] = [];
|
private pendingChallenges: plugins.tsclass.network.IDnsChallenge[] = [];
|
||||||
// configured pluggable ACME challenge handlers
|
|
||||||
private challengeHandlers: plugins.handlers.IChallengeHandler<any>[];
|
|
||||||
// priority order of challenge types
|
// priority order of challenge types
|
||||||
private challengePriority: string[];
|
private challengePriority: string[];
|
||||||
// Map for coordinating concurrent certificate requests
|
// TaskManager for coordinating concurrent certificate requests
|
||||||
private interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
|
private taskManager: plugins.taskbuffer.TaskManager;
|
||||||
|
// Single reusable task for certificate issuance
|
||||||
|
private certIssuanceTask: plugins.taskbuffer.Task<undefined, typeof CERT_ISSUANCE_STEPS>;
|
||||||
|
// bound signal handlers so they can be removed on stop()
|
||||||
|
private boundSigintHandler: (() => void) | null = null;
|
||||||
|
private boundSigtermHandler: (() => void) | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exposes the aggregated task event stream for observing certificate issuance progress.
|
||||||
|
*/
|
||||||
|
public get certIssuanceEvents(): plugins.taskbuffer.TaskManager['taskSubject'] {
|
||||||
|
return this.taskManager.taskSubject;
|
||||||
|
}
|
||||||
|
|
||||||
constructor(optionsArg: ISmartAcmeOptions) {
|
constructor(optionsArg: ISmartAcmeOptions) {
|
||||||
this.options = optionsArg;
|
this.options = optionsArg;
|
||||||
@@ -100,8 +145,60 @@ export class SmartAcme {
|
|||||||
optionsArg.challengePriority && optionsArg.challengePriority.length > 0
|
optionsArg.challengePriority && optionsArg.challengePriority.length > 0
|
||||||
? optionsArg.challengePriority
|
? optionsArg.challengePriority
|
||||||
: this.challengeHandlers.map((h) => h.getSupportedTypes()[0]);
|
: this.challengeHandlers.map((h) => h.getSupportedTypes()[0]);
|
||||||
// initialize interest coordination
|
|
||||||
this.interestMap = new plugins.lik.InterestMap((domain) => domain);
|
// ── TaskManager setup ──────────────────────────────────────────────────
|
||||||
|
this.taskManager = new plugins.taskbuffer.TaskManager();
|
||||||
|
|
||||||
|
// Constraint 1: Per-domain mutex — one issuance at a time per TLD, with result sharing
|
||||||
|
const certDomainMutex = new plugins.taskbuffer.TaskConstraintGroup({
|
||||||
|
name: 'cert-domain-mutex',
|
||||||
|
maxConcurrent: 1,
|
||||||
|
resultSharingMode: 'share-latest',
|
||||||
|
constraintKeyForExecution: (_task, input?: ICertIssuanceInput) => {
|
||||||
|
return input?.certDomainName ?? null;
|
||||||
|
},
|
||||||
|
shouldExecute: async (_task, input?: ICertIssuanceInput) => {
|
||||||
|
if (!input?.certDomainName || !this.certmanager) return true;
|
||||||
|
// Safety net: if a valid cert is already cached, skip re-issuance
|
||||||
|
const existing = await this.certmanager.retrieveCertificate(input.certDomainName);
|
||||||
|
if (existing && !existing.shouldBeRenewed()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Constraint 2: Global concurrency cap
|
||||||
|
const acmeGlobalConcurrency = new plugins.taskbuffer.TaskConstraintGroup({
|
||||||
|
name: 'acme-global-concurrency',
|
||||||
|
maxConcurrent: optionsArg.maxConcurrentIssuances ?? 5,
|
||||||
|
constraintKeyForExecution: () => 'global',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Constraint 3: Account-level rate limiting
|
||||||
|
const acmeAccountRateLimit = new plugins.taskbuffer.TaskConstraintGroup({
|
||||||
|
name: 'acme-account-rate-limit',
|
||||||
|
rateLimit: {
|
||||||
|
maxPerWindow: optionsArg.maxOrdersPerWindow ?? 250,
|
||||||
|
windowMs: optionsArg.orderWindowMs ?? 10_800_000,
|
||||||
|
},
|
||||||
|
constraintKeyForExecution: () => 'account',
|
||||||
|
});
|
||||||
|
|
||||||
|
this.taskManager.addConstraintGroup(certDomainMutex);
|
||||||
|
this.taskManager.addConstraintGroup(acmeGlobalConcurrency);
|
||||||
|
this.taskManager.addConstraintGroup(acmeAccountRateLimit);
|
||||||
|
|
||||||
|
// Create the single reusable certificate issuance task
|
||||||
|
this.certIssuanceTask = new plugins.taskbuffer.Task({
|
||||||
|
name: 'cert-issuance',
|
||||||
|
steps: CERT_ISSUANCE_STEPS,
|
||||||
|
taskFunction: async (input: ICertIssuanceInput) => {
|
||||||
|
return this.performCertificateIssuance(input);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.taskManager.addTask(this.certIssuanceTask);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -112,7 +209,7 @@ export class SmartAcme {
|
|||||||
*/
|
*/
|
||||||
public async start() {
|
public async start() {
|
||||||
this.privateKey =
|
this.privateKey =
|
||||||
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
|
this.options.accountPrivateKey || plugins.acme.AcmeCrypto.createRsaPrivateKey();
|
||||||
|
|
||||||
// Initialize certificate manager
|
// Initialize certificate manager
|
||||||
if (!this.options.certManager) {
|
if (!this.options.certManager) {
|
||||||
@@ -125,15 +222,18 @@ export class SmartAcme {
|
|||||||
this.certmatcher = new SmartacmeCertMatcher();
|
this.certmatcher = new SmartacmeCertMatcher();
|
||||||
|
|
||||||
// ACME Client
|
// ACME Client
|
||||||
this.client = new plugins.acme.Client({
|
this.client = new plugins.acme.AcmeClient({
|
||||||
directoryUrl: (() => {
|
directoryUrl: (() => {
|
||||||
if (this.options.environment === 'production') {
|
if (this.options.environment === 'production') {
|
||||||
return plugins.acme.directory.letsencrypt.production;
|
return plugins.acme.ACME_DIRECTORY_URLS.letsencrypt.production;
|
||||||
} else {
|
} else {
|
||||||
return plugins.acme.directory.letsencrypt.staging;
|
return plugins.acme.ACME_DIRECTORY_URLS.letsencrypt.staging;
|
||||||
}
|
}
|
||||||
})(),
|
})(),
|
||||||
accountKey: this.privateKey,
|
accountKeyPem: this.privateKey,
|
||||||
|
logger: (level, message, data) => {
|
||||||
|
this.logger.log(level as any, message, data);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
/* Register account */
|
/* Register account */
|
||||||
@@ -141,20 +241,45 @@ export class SmartAcme {
|
|||||||
termsOfServiceAgreed: true,
|
termsOfServiceAgreed: true,
|
||||||
contact: [`mailto:${this.options.accountEmail}`],
|
contact: [`mailto:${this.options.accountEmail}`],
|
||||||
});
|
});
|
||||||
// Setup graceful shutdown handlers
|
|
||||||
process.on('SIGINT', () => this.handleSignal('SIGINT'));
|
// Start the task manager
|
||||||
process.on('SIGTERM', () => this.handleSignal('SIGTERM'));
|
await this.taskManager.start();
|
||||||
|
|
||||||
|
// Setup graceful shutdown handlers (store references for removal in stop())
|
||||||
|
this.boundSigintHandler = () => this.handleSignal('SIGINT');
|
||||||
|
this.boundSigtermHandler = () => this.handleSignal('SIGTERM');
|
||||||
|
process.on('SIGINT', this.boundSigintHandler);
|
||||||
|
process.on('SIGTERM', this.boundSigtermHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the SmartAcme instance and closes certificate store connections.
|
* Stops the SmartAcme instance and closes certificate store connections.
|
||||||
*/
|
*/
|
||||||
public async stop() {
|
public async stop() {
|
||||||
|
// Remove signal handlers so the process can exit cleanly
|
||||||
|
if (this.boundSigintHandler) {
|
||||||
|
process.removeListener('SIGINT', this.boundSigintHandler);
|
||||||
|
this.boundSigintHandler = null;
|
||||||
|
}
|
||||||
|
if (this.boundSigtermHandler) {
|
||||||
|
process.removeListener('SIGTERM', this.boundSigtermHandler);
|
||||||
|
this.boundSigtermHandler = null;
|
||||||
|
}
|
||||||
|
// Stop the task manager
|
||||||
|
await this.taskManager.stop();
|
||||||
|
// Destroy ACME HTTP transport (closes keep-alive sockets)
|
||||||
|
if (this.client) {
|
||||||
|
this.client.destroy();
|
||||||
|
}
|
||||||
|
// Destroy DNS client (kills Rust bridge child process if spawned)
|
||||||
|
if (this.smartdns) {
|
||||||
|
this.smartdns.destroy();
|
||||||
|
}
|
||||||
if (this.certmanager && typeof (this.certmanager as any).close === 'function') {
|
if (this.certmanager && typeof (this.certmanager as any).close === 'function') {
|
||||||
await (this.certmanager as any).close();
|
await (this.certmanager as any).close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Retry helper with exponential backoff */
|
/** Retry helper with exponential backoff and AcmeError awareness */
|
||||||
private async retry<T>(operation: () => Promise<T>, operationName: string = 'operation'): Promise<T> {
|
private async retry<T>(operation: () => Promise<T>, operationName: string = 'operation'): Promise<T> {
|
||||||
let attempt = 0;
|
let attempt = 0;
|
||||||
let delay = this.retryOptions.minTimeoutMs;
|
let delay = this.retryOptions.minTimeoutMs;
|
||||||
@@ -162,6 +287,19 @@ export class SmartAcme {
|
|||||||
try {
|
try {
|
||||||
return await operation();
|
return await operation();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Check if it's a non-retryable ACME error — throw immediately
|
||||||
|
if (err instanceof plugins.acme.AcmeError) {
|
||||||
|
if (!err.isRetryable) {
|
||||||
|
await this.logger.log('error', `Operation ${operationName} failed with non-retryable error (${err.type}, HTTP ${err.status}) at ${err.url}`, err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
// For rate-limited errors, use server-specified Retry-After delay
|
||||||
|
if (err.isRateLimited && err.retryAfter > 0) {
|
||||||
|
delay = err.retryAfter * 1000;
|
||||||
|
await this.logger.log('warn', `Operation ${operationName} rate-limited, Retry-After: ${err.retryAfter}s`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
attempt++;
|
attempt++;
|
||||||
if (attempt > this.retryOptions.retries) {
|
if (attempt > this.retryOptions.retries) {
|
||||||
await this.logger.log('error', `Operation ${operationName} failed after ${attempt} attempts`, err);
|
await this.logger.log('error', `Operation ${operationName} failed after ${attempt} attempts`, err);
|
||||||
@@ -215,58 +353,106 @@ export class SmartAcme {
|
|||||||
* * if not in the database announce it
|
* * if not in the database announce it
|
||||||
* * then get it from letsencrypt
|
* * then get it from letsencrypt
|
||||||
* * store it
|
* * store it
|
||||||
* * remove it from the pending map (which it go onto by announcing it)
|
* * retrieve it from the database and return it
|
||||||
* * retrieve it from the databse and return it
|
|
||||||
*
|
*
|
||||||
* @param domainArg
|
* @param domainArg
|
||||||
|
* @param options Optional configuration for certificate generation
|
||||||
*/
|
*/
|
||||||
public async getCertificateForDomain(domainArg: string): Promise<SmartacmeCert> {
|
public async getCertificateForDomain(
|
||||||
|
domainArg: string,
|
||||||
|
options?: { includeWildcard?: boolean }
|
||||||
|
): Promise<SmartacmeCert> {
|
||||||
|
// Determine if this is a wildcard request (e.g., '*.example.com').
|
||||||
|
const isWildcardRequest = domainArg.startsWith('*.');
|
||||||
|
// Determine the base domain for certificate retrieval/issuance.
|
||||||
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
|
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
|
||||||
|
if (!certDomainName) {
|
||||||
|
throw new Error(`Cannot determine certificate domain for ${domainArg}`);
|
||||||
|
}
|
||||||
|
// Wildcard certificates require DNS-01 challenge support.
|
||||||
|
if (isWildcardRequest) {
|
||||||
|
const hasDnsHandler = this.challengeHandlers.some((h) =>
|
||||||
|
h.getSupportedTypes().includes('dns-01'),
|
||||||
|
);
|
||||||
|
if (!hasDnsHandler) {
|
||||||
|
throw new Error('Wildcard certificate requests require a DNS-01 challenge handler');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Retrieve any existing certificate record by base domain.
|
||||||
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
|
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
|
||||||
// integration test stub: bypass ACME and return a dummy certificate
|
|
||||||
if (this.options.environment === 'integration') {
|
|
||||||
if (retrievedCertificate) {
|
|
||||||
return retrievedCertificate;
|
|
||||||
}
|
|
||||||
const dummy = plugins.smartunique.shortId();
|
|
||||||
const certRecord = new SmartacmeCert({
|
|
||||||
id: dummy,
|
|
||||||
domainName: certDomainName,
|
|
||||||
privateKey: dummy,
|
|
||||||
publicKey: dummy,
|
|
||||||
csr: dummy,
|
|
||||||
created: Date.now(),
|
|
||||||
validUntil: Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 90 }),
|
|
||||||
});
|
|
||||||
await this.certmanager.storeCertificate(certRecord);
|
|
||||||
return certRecord;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
|
||||||
!retrievedCertificate &&
|
|
||||||
(await this.interestMap.checkInterest(certDomainName))
|
|
||||||
) {
|
|
||||||
const existingCertificateInterest = this.interestMap.findInterest(certDomainName);
|
|
||||||
const certificate = existingCertificateInterest.interestFullfilled;
|
|
||||||
return certificate;
|
|
||||||
} else if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
|
|
||||||
return retrievedCertificate;
|
return retrievedCertificate;
|
||||||
} else if (retrievedCertificate && retrievedCertificate.shouldBeRenewed()) {
|
} else if (retrievedCertificate && retrievedCertificate.shouldBeRenewed()) {
|
||||||
// Remove old certificate via certManager
|
// Remove old certificate via certManager
|
||||||
await this.certmanager.deleteCertificate(certDomainName);
|
await this.certmanager.deleteCertificate(certDomainName);
|
||||||
}
|
}
|
||||||
|
|
||||||
// lets make sure others get the same interest
|
// Build issuance input and trigger the constrained task
|
||||||
const currentDomainInterst = await this.interestMap.addInterest(certDomainName);
|
const issuanceInput: ICertIssuanceInput = {
|
||||||
|
certDomainName,
|
||||||
|
domainArg,
|
||||||
|
isWildcardRequest,
|
||||||
|
includeWildcard: options?.includeWildcard ?? false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await this.taskManager.triggerTaskConstrained(
|
||||||
|
this.certIssuanceTask,
|
||||||
|
issuanceInput,
|
||||||
|
);
|
||||||
|
|
||||||
|
// If we got a cert directly (either from execution or result sharing), return it
|
||||||
|
if (result != null) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If shouldExecute returned false (cert appeared in cache), read from cache
|
||||||
|
const cachedCert = await this.certmanager.retrieveCertificate(certDomainName);
|
||||||
|
if (cachedCert) {
|
||||||
|
return cachedCert;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Certificate issuance failed for ${certDomainName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs the actual ACME certificate issuance flow.
|
||||||
|
* Called by the certIssuanceTask's taskFunction.
|
||||||
|
*/
|
||||||
|
private async performCertificateIssuance(input: ICertIssuanceInput): Promise<SmartacmeCert> {
|
||||||
|
const { certDomainName, isWildcardRequest, includeWildcard } = input;
|
||||||
|
|
||||||
|
// ── Step: prepare ─────────────────────────────────────────────────────
|
||||||
|
this.certIssuanceTask.notifyStep('prepare');
|
||||||
|
|
||||||
|
// Build identifiers array based on request
|
||||||
|
const identifiers: Array<{ type: 'dns'; value: string }> = [];
|
||||||
|
|
||||||
|
if (isWildcardRequest) {
|
||||||
|
identifiers.push({ type: 'dns', value: `*.${certDomainName}` });
|
||||||
|
} else {
|
||||||
|
identifiers.push({ type: 'dns', value: certDomainName });
|
||||||
|
|
||||||
|
if (includeWildcard) {
|
||||||
|
const hasDnsHandler = this.challengeHandlers.some((h) =>
|
||||||
|
h.getSupportedTypes().includes('dns-01'),
|
||||||
|
);
|
||||||
|
if (!hasDnsHandler) {
|
||||||
|
this.logger.log('warn', 'Wildcard certificate requested but no DNS-01 handler available. Skipping wildcard.');
|
||||||
|
} else {
|
||||||
|
identifiers.push({ type: 'dns', value: `*.${certDomainName}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Place new order with retry */
|
/* Place new order with retry */
|
||||||
const order = await this.retry(() => this.client.createOrder({
|
const order = await this.retry(() => this.client.createOrder({
|
||||||
identifiers: [
|
identifiers,
|
||||||
{ type: 'dns', value: certDomainName },
|
|
||||||
{ type: 'dns', value: `*.${certDomainName}` },
|
|
||||||
],
|
|
||||||
}), 'createOrder');
|
}), 'createOrder');
|
||||||
|
|
||||||
|
// ── Step: authorize ───────────────────────────────────────────────────
|
||||||
|
this.certIssuanceTask.notifyStep('authorize');
|
||||||
|
|
||||||
/* Get authorizations and select challenges */
|
/* Get authorizations and select challenges */
|
||||||
const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
|
const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
|
||||||
|
|
||||||
@@ -290,50 +476,37 @@ export class SmartAcme {
|
|||||||
}
|
}
|
||||||
const { type, handler } = selectedHandler;
|
const { type, handler } = selectedHandler;
|
||||||
// build handler input with keyAuthorization
|
// build handler input with keyAuthorization
|
||||||
let input: any;
|
let challengeInput: any;
|
||||||
// retrieve keyAuthorization for challenge
|
// retrieve keyAuthorization for challenge
|
||||||
const keyAuth = await this.client.getChallengeKeyAuthorization(selectedChallengeArg);
|
const keyAuth = await this.client.getChallengeKeyAuthorization(selectedChallengeArg);
|
||||||
if (type === 'dns-01') {
|
if (type === 'dns-01') {
|
||||||
input = { type, hostName: `_acme-challenge.${authz.identifier.value}`, challenge: keyAuth };
|
challengeInput = { type, hostName: `_acme-challenge.${authz.identifier.value}`, challenge: keyAuth };
|
||||||
} else if (type === 'http-01') {
|
} else if (type === 'http-01') {
|
||||||
// HTTP-01 requires serving token at webPath
|
challengeInput = {
|
||||||
input = {
|
|
||||||
type,
|
type,
|
||||||
token: (selectedChallengeArg as any).token,
|
token: (selectedChallengeArg as any).token,
|
||||||
keyAuthorization: keyAuth,
|
keyAuthorization: keyAuth,
|
||||||
webPath: `/.well-known/acme-challenge/${(selectedChallengeArg as any).token}`,
|
webPath: `/.well-known/acme-challenge/${(selectedChallengeArg as any).token}`,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// generic challenge input: include raw challenge properties
|
challengeInput = { type, keyAuthorization: keyAuth, ...selectedChallengeArg };
|
||||||
input = { type, keyAuthorization: keyAuth, ...selectedChallengeArg };
|
|
||||||
}
|
}
|
||||||
this.pendingChallenges.push(input);
|
this.pendingChallenges.push(challengeInput);
|
||||||
try {
|
try {
|
||||||
// Prepare the challenge (set DNS record, write file, etc.)
|
await this.retry(() => handler.prepare(challengeInput), `${type}.prepare`);
|
||||||
await this.retry(() => handler.prepare(input), `${type}.prepare`);
|
|
||||||
// For DNS-01, wait for propagation before verification
|
|
||||||
if (type === 'dns-01') {
|
if (type === 'dns-01') {
|
||||||
const dnsInput = input as { hostName: string; challenge: string };
|
const dnsInput = challengeInput as { hostName: string; challenge: string };
|
||||||
// Wait for authoritative DNS propagation before ACME verify
|
|
||||||
await this.retry(
|
await this.retry(
|
||||||
() => this.smartdns.checkUntilAvailable(dnsInput.hostName, 'TXT', dnsInput.challenge, 100, 5000),
|
() => this.smartdns.checkUntilAvailable(dnsInput.hostName, 'TXT', dnsInput.challenge, 100, 5000),
|
||||||
`${type}.propagation`,
|
`${type}.propagation`,
|
||||||
);
|
);
|
||||||
// Extra cool-down to ensure ACME server sees the new TXT record
|
|
||||||
this.logger.log('info', 'Cooling down for 1 minute before ACME verification');
|
this.logger.log('info', 'Cooling down for 1 minute before ACME verification');
|
||||||
await plugins.smartdelay.delayFor(60000);
|
await plugins.smartdelay.delayFor(60000);
|
||||||
}
|
}
|
||||||
// Official ACME verification (ensures challenge is publicly reachable)
|
|
||||||
await this.retry(
|
|
||||||
() => this.client.verifyChallenge(authz, selectedChallengeArg),
|
|
||||||
`${type}.verifyChallenge`,
|
|
||||||
);
|
|
||||||
// Notify ACME server to complete the challenge
|
|
||||||
await this.retry(
|
await this.retry(
|
||||||
() => this.client.completeChallenge(selectedChallengeArg),
|
() => this.client.completeChallenge(selectedChallengeArg),
|
||||||
`${type}.completeChallenge`,
|
`${type}.completeChallenge`,
|
||||||
);
|
);
|
||||||
// Wait for valid status (warnings on staging timeouts)
|
|
||||||
try {
|
try {
|
||||||
await this.retry(
|
await this.retry(
|
||||||
() => this.client.waitForValidStatus(selectedChallengeArg),
|
() => this.client.waitForValidStatus(selectedChallengeArg),
|
||||||
@@ -347,29 +520,43 @@ export class SmartAcme {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// Always cleanup resource
|
|
||||||
try {
|
try {
|
||||||
await this.retry(() => handler.cleanup(input), `${type}.cleanup`);
|
await this.retry(() => handler.cleanup(challengeInput), `${type}.cleanup`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.logger.log('error', `Error during ${type}.cleanup`, err);
|
await this.logger.log('error', `Error during ${type}.cleanup`, err);
|
||||||
} finally {
|
} finally {
|
||||||
this.pendingChallenges = this.pendingChallenges.filter((c) => c !== input);
|
this.pendingChallenges = this.pendingChallenges.filter((c) => c !== challengeInput);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Finalize order */
|
// ── Step: finalize ────────────────────────────────────────────────────
|
||||||
const [key, csr] = await plugins.acme.forge.createCsr({
|
this.certIssuanceTask.notifyStep('finalize');
|
||||||
commonName: `*.${certDomainName}`,
|
|
||||||
altNames: [certDomainName],
|
const csrDomains: string[] = [];
|
||||||
|
let commonName: string;
|
||||||
|
|
||||||
|
if (isWildcardRequest) {
|
||||||
|
commonName = `*.${certDomainName}`;
|
||||||
|
csrDomains.push(certDomainName);
|
||||||
|
} else {
|
||||||
|
commonName = certDomainName;
|
||||||
|
if (includeWildcard && identifiers.some(id => id.value === `*.${certDomainName}`)) {
|
||||||
|
csrDomains.push(`*.${certDomainName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const [key, csr] = await plugins.acme.AcmeCrypto.createCsr({
|
||||||
|
commonName,
|
||||||
|
altNames: csrDomains,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.retry(() => this.client.finalizeOrder(order, csr), 'finalizeOrder');
|
await this.retry(() => this.client.finalizeOrder(order, csr), 'finalizeOrder');
|
||||||
const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
|
const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
|
||||||
|
|
||||||
/* Done */
|
// ── Step: store ───────────────────────────────────────────────────────
|
||||||
|
this.certIssuanceTask.notifyStep('store');
|
||||||
|
|
||||||
// Store the new certificate record
|
|
||||||
const certRecord = new SmartacmeCert({
|
const certRecord = new SmartacmeCert({
|
||||||
id: plugins.smartunique.shortId(),
|
id: plugins.smartunique.shortId(),
|
||||||
domainName: certDomainName,
|
domainName: certDomainName,
|
||||||
@@ -382,9 +569,7 @@ export class SmartAcme {
|
|||||||
await this.certmanager.storeCertificate(certRecord);
|
await this.certmanager.storeCertificate(certRecord);
|
||||||
|
|
||||||
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
|
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
|
||||||
currentDomainInterst.fullfillInterest(newCertificate);
|
return newCertificate ?? certRecord;
|
||||||
currentDomainInterst.destroy();
|
|
||||||
return newCertificate;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user