Compare commits

...

51 Commits

Author SHA1 Message Date
e830cb6252 v9.3.1
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-03-27 22:21:16 +00:00
75def30b0a fix(acme): parse issued certificate expiry from X.509 metadata and update build compatibility for dependency upgrades 2026-03-27 22:21:16 +00:00
ab0ca6ccc3 v9.3.0
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-03-19 09:29:13 +00:00
e570ac6db0 feat(readme): document built-in ACME directory server and CA capabilities 2026-03-19 09:29:13 +00:00
47168408cc v9.2.0
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-03-19 09:19:15 +00:00
74ad7cd6c4 feat(server): add an embedded ACME directory server and certificate authority with challenge, order, and certificate endpoints 2026-03-19 09:19:15 +00:00
77d40985f3 v9.1.3
Some checks failed
Default (tags) / security (push) Successful in 1m49s
Default (tags) / test (push) Failing after 1m20s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-16 02:46:54 +00:00
adf9262ded fix(smartacme): Include base domain alongside wildcard when building identifiers for wildcard certificate requests 2026-02-16 02:46:54 +00:00
e2d182ca03 v9.1.2
Some checks failed
Default (tags) / security (push) Successful in 45s
Default (tags) / test (push) Failing after 2m38s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-15 23:31:42 +00:00
8cd713447e fix(docs): document built-in concurrency control, rate limiting, and request deduplication in README 2026-02-15 23:31:42 +00:00
2cf3dbdd95 v9.1.1
Some checks failed
Default (tags) / security (push) Successful in 1m44s
Default (tags) / test (push) Failing after 1m38s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-15 23:23:54 +00:00
1c75bac44f fix(deps): bump @push.rocks/smarttime to ^4.2.3 and @push.rocks/taskbuffer to ^6.1.2 2026-02-15 23:23:54 +00:00
a865fb89e0 v9.1.0
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Failing after 1m25s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-15 22:22:12 +00:00
cfc0695c8a 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. 2026-02-15 22:22:12 +00:00
68178366d5 v9.0.1
Some checks failed
Default (tags) / security (push) Successful in 1m48s
Default (tags) / test (push) Failing after 1m40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-15 20:43:06 +00:00
52e1295fd2 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). 2026-02-15 20:43:06 +00:00
e968f8a039 v9.0.0
Some checks failed
Default (tags) / security (push) Successful in 1m49s
Default (tags) / test (push) Failing after 1m38s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-15 20:20:46 +00:00
cf4b758800 BREAKING CHANGE(acme): Replace external acme-client with a built-in RFC8555-compliant ACME implementation and update public APIs accordingly 2026-02-15 20:20:46 +00:00
3fa34fa373 8.0.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 45m30s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-19 10:01:32 +00:00
086eea1aa2 BREAKING CHANGE(smartacme): Make wildcard certificates opt-in to fix HTTP-01 only configurations 2025-05-19 10:01:31 +00:00
dcc89f0088 7.3.4
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 45m22s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-18 15:47:43 +00:00
695a515990 fix(smartacme): Refine documentation and tests for improved clarity in ACME certificate management 2025-05-18 15:47:42 +00:00
01f7018540 7.3.3
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 45m22s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-05 17:29:17 +00:00
3cee6c534a fix(SmartAcme): Remove duplicate challengeHandlers declaration from SmartAcme class 2025-05-05 17:29:16 +00:00
47d1609a49 7.3.2
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 45m21s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-05 14:39:23 +00:00
d69eb73afc fix(test): Add missing checkWetherDomainIsSupported implementation to DummyHandler for interface compliance in tests 2025-05-05 14:39:23 +00:00
0a1d617ce3 7.3.1
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 45m20s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-05 14:06:23 +00:00
f78b50757c fix(core): Refactor import paths and update dependency references 2025-05-05 14:06:23 +00:00
0e6bbc5be6 7.3.0
Some checks failed
Default (tags) / security (push) Successful in 35s
Default (tags) / test (push) Failing after 45m11s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-05 12:02:04 +00:00
10511b4293 feat(index): Bump @tsclass/tsclass to 9.2.0 and update module exports to include handlers 2025-05-05 12:02:04 +00:00
d456876de7 7.2.5
Some checks failed
Default (tags) / security (push) Successful in 24s
Default (tags) / test (push) Failing after 45m11s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-05 10:50:23 +00:00
fe495a5f03 fix(smartacme): Refactor module exports and update wildcard certificate support documentation 2025-05-05 10:50:23 +00:00
88ba970494 7.2.4
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 45m13s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-04 11:40:01 +00:00
1e7e1739b8 fix(test): Refactor wildcard certificate test to properly stub SmartAcme.start and getCertificateForDomain for robust integration. 2025-05-04 11:40:01 +00:00
0c6da9ff74 update 2025-05-04 10:29:33 +00:00
1698abef16 7.2.3
Some checks failed
Default (tags) / security (push) Successful in 23s
Default (tags) / test (push) Failing after 1m2s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-01 11:38:36 +00:00
a0f6a14b63 fix(docs): Improve certificate manager documentation with detailed examples and custom implementation guide 2025-05-01 11:38:35 +00:00
876d876661 7.2.2
Some checks failed
Default (tags) / security (push) Successful in 39s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-01 11:33:55 +00:00
ae212c53d5 fix(readme): Update readme documentation: switch installation instructions to pnpm and clarify usage with MongoCertManager and updated SmartAcme options 2025-05-01 11:33:55 +00:00
b9866c2ced 7.2.1
Some checks failed
Default (tags) / security (push) Successful in 33s
Default (tags) / test (push) Failing after 53s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-01 09:28:10 +00:00
c863c7295d fix(smartacme): Centralize interest map coordination and remove redundant interestMap from cert managers 2025-05-01 09:28:10 +00:00
b8bb4af184 7.2.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-01 09:15:19 +00:00
6fedf0505e feat(core): Refactor SmartAcme core to centralize interest coordination and update dependencies 2025-05-01 09:15:19 +00:00
f814038a6a 7.1.0
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 18:18:45 +00:00
9dc8c1d8a3 feat(certmanagers/integration): Add optional wipe methods to certificate managers and update integration tests, plus bump tapbundle dependency 2025-04-30 18:18:45 +00:00
758c6c6b5d 7.0.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 17:27:17 +00:00
6363ec4be6 BREAKING CHANGE(SmartAcme (Cert Management)): Refactor certificate management and challenge handling API to use a unified certManager interface, remove legacy storage, and update challenge workflows. 2025-04-30 17:27:17 +00:00
6a53346d14 6.2.0
Some checks failed
Default (tags) / security (push) Successful in 37s
Default (tags) / test (push) Failing after 54s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 14:55:03 +00:00
fc420eb615 feat(handlers): Add in-memory HTTP-01 challenge handler and rename file-based handler to Http01Webroot 2025-04-30 14:55:03 +00:00
9f66a0487f 6.1.3
Some checks failed
Default (tags) / security (push) Successful in 36s
Default (tags) / test (push) Failing after 53s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-04-30 12:59:20 +00:00
40cae220d0 fix(Dns01Handler): Update dependency versions and refine Dns01Handler implementation 2025-04-30 12:59:20 +00:00
66 changed files with 15515 additions and 6478 deletions

View File

@@ -1,5 +1,5 @@
{
"gitzone": {
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
@@ -26,13 +26,19 @@
"certificate renewal",
"wildcard certificates"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"@git.zone/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"
},
"@ship.zone/szci": {
"npmGlobalTools": []
}
}

View File

@@ -1,7 +1,7 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"fileMatch": ["/.smartconfig.json"],
"schema": {
"type": "object",
"properties": {

View File

@@ -1,5 +1,205 @@
# Changelog
## 2026-03-27 - 9.3.1 - fix(acme)
parse issued certificate expiry from X.509 metadata and update build compatibility for dependency upgrades
- Store certificate validity using the actual X.509 expiration date instead of a fixed 90-day estimate, with a fallback if PEM parsing fails.
- Add reflect-metadata imports and declare it as a direct dependency to support @peculiar/x509 v2.
- Update TypeScript and build configuration for newer toolchain requirements, including Node types and renamed project config file.
## 2026-03-19 - 9.3.0 - feat(readme)
document built-in ACME directory server and CA capabilities
- Update package metadata to describe client and server support, including built-in CA functionality
- Add README sections for ACME server quick start, configuration, endpoints, challenge verification, and trust setup
- Expand architecture notes and project hints to cover ts_server modules and tsbuild tsfolders usage
## 2026-03-19 - 9.2.0 - feat(server)
add an embedded ACME directory server and certificate authority with challenge, order, and certificate endpoints
- exports a new server module with AcmeServer, AcmeServerCA, server error types, and related interfaces
- implements in-memory account and order storage, nonce management, JWS verification, routing, challenge validation, and CSR signing for RFC 8555 style flows
- adds end-to-end tests for account creation, order processing, challenge handling, certificate issuance, and error scenarios
- updates the build configuration to include tsfolders and package file patterns for ts_* sources
## 2026-02-16 - 9.1.3 - fix(smartacme)
Include base domain alongside wildcard when building identifiers for wildcard certificate requests
- When isWildcardRequest is true, the base domain (e.g. example.com) is now added in addition to the wildcard (*.example.com) so the issued certificate covers both apex and wildcard entries.
- Prevents missing SAN for the apex domain when requesting wildcard certificates.
## 2026-02-15 - 9.1.2 - fix(docs)
document built-in concurrency control, rate limiting, and request deduplication in README
- Added a new 'Concurrency Control & Rate Limiting' section to the README describing per-domain mutex, global concurrency cap, and sliding-window account rate limiting (defaults: 1 per domain, 5 global, 250 per 3 hours).
- Documented new SmartAcme options in the interface: maxConcurrentIssuances, maxOrdersPerWindow, and orderWindowMs.
- Added example code showing configuration of the limits and an example of request deduplication behavior (multiple subdomain requests resolving to a single ACME order).
- Added an example subscription to certIssuanceEvents and updated the components table with TaskManager entry.
- Change is documentation-only (README) — no code changes; safe patch release.
## 2026-02-15 - 9.1.1 - fix(deps)
bump @push.rocks/smarttime to ^4.2.3 and @push.rocks/taskbuffer to ^6.1.2
- @push.rocks/smarttime: ^4.1.1 -> ^4.2.3
- @push.rocks/taskbuffer: ^6.1.0 -> ^6.1.2
- Only package.json dependency version updates; no code changes
## 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 (Lets 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)
Improve certificate manager documentation with detailed examples and custom implementation guide
- Added usage examples for MemoryCertManager and MongoCertManager
- Provided a custom ICertManager implementation guide
- Enhanced overall documentation clarity for certificate storage configuration
## 2025-05-01 - 7.2.2 - fix(readme)
Update readme documentation: switch installation instructions to pnpm and clarify usage with MongoCertManager and updated SmartAcme options
- Replaced npm/yarn commands with pnpm commands for installation and testing.
- Added guidance to ensure the project is set up for TypeScript and ECMAScript Modules.
- Updated usage examples to include initialization of MongoCertManager instead of legacy mongoDescriptor.
- Revised challenge handlers examples to reference the current API signatures.
## 2025-05-01 - 7.2.1 - fix(smartacme)
Centralize interest map coordination and remove redundant interestMap from cert managers
- Removed interestMap property and related logic from MemoryCertManager and MongoCertManager
- Refactored SmartAcme to instantiate its own interestMap for coordinating certificate requests
- Updated getCertificateForDomain to use the new interestMap for checking and adding certificate interests
## 2025-05-01 - 7.2.0 - feat(core)
Refactor SmartAcme core to centralize interest coordination and update dependencies
- Moved interest coordination mechanism out of ICertManager implementations and into SmartAcme core
- Updated certificate managers (MemoryCertManager and MongoCertManager) to remove redundant interestMap handling
- Upgraded @push.rocks/tapbundle from 6.0.1 to 6.0.3 in package.json
- Revised readme.plan.md to reflect the new interest coordination approach
## 2025-04-30 - 7.1.0 - feat(certmanagers/integration)
Add optional wipe methods to certificate managers and update integration tests, plus bump tapbundle dependency
- Introduce wipe() in ICertManager to support integration testing by clearing stored certificates
- Implement wipe() in MemoryCertManager and MongoCertManager for resetting internal state
- Refactor SmartAcme constructor to consider wiping certificates in integration mode (commented out for now)
- Update integration test assertions and add console logging for domain certificate retrieval
- Upgrade @push.rocks/tapbundle from ^6.0.0 to ^6.0.1
## 2025-04-30 - 7.0.0 - BREAKING CHANGE(SmartAcme (Cert Management))
Refactor certificate management and challenge handling API to use a unified certManager interface, remove legacy storage, and update challenge workflows.
- Introduce ICertManager interface with MemoryCertManager and MongoCertManager implementations.
- Remove the legacy SmartacmeCertManager and update SmartAcme to require a certManager option instead of mongoDescriptor.
- Adjust certificate renewal logic to delete and store certificates through the new certManager API.
- Refine DNS-01 challenge handling by removing in-handler DNS propagation waiting and relying on external checks.
- Increase retry settings for robustness during challenge verification and certificate issuance.
- Update integration and unit tests to use the new certManager configuration.
## 2025-04-30 - 6.2.0 - feat(handlers)
Add in-memory HTTP-01 challenge handler and rename file-based handler to Http01Webroot
- Renamed Http01Handler to Http01Webroot in both implementation and documentation
- Introduced Http01MemoryHandler for diskless HTTP-01 challenges
- Updated tests and README examples to reflect handler name changes and new feature
## 2025-04-30 - 6.1.3 - fix(Dns01Handler)
Update dependency versions and refine Dns01Handler implementation
- Bump '@apiclient.xyz/cloudflare' to ^6.4.1 and '@tsclass/tsclass' to ^9.1.0 in package.json
- Remove duplicate Cloudflare import in smartacme.plugins.ts
- Refactor Dns01Handler to use IConvenientDnsProvider and add checkWetherDomainIsSupported method
- Align devDependencies versions for improved consistency
## 2025-04-27 - 6.1.2 - fix(repo)
Update repository metadata by replacing the LICENSE file with a license.md file for improved consistency.

6827
deno.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,14 @@
{
"name": "@push.rocks/smartacme",
"version": "6.1.2",
"version": "9.3.1",
"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 and server for certificate management with built-in CA, supporting LetsEncrypt and custom ACME authorities.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild --web --allowimplicitany)",
"test": "(tstest test/ --verbose --logfile --timeout 600)",
"build": "(tsbuild tsfolders)",
"buildDocs": "tsdoc"
},
"repository": {
@@ -20,6 +20,9 @@
"LetsEncrypt",
"TypeScript",
"certificate management",
"certificate authority",
"ACME server",
"PKI",
"DNS challenges",
"SSL/TLS",
"secure communication",
@@ -28,9 +31,11 @@
"crypto",
"MongoDB",
"dns-01 challenge",
"http-01 challenge",
"token-based challenges",
"certificate renewal",
"wildcard certificates"
"wildcard certificates",
"RFC 8555"
],
"author": "Task Venture Capital GmbH",
"license": "MIT",
@@ -39,39 +44,38 @@
},
"homepage": "https://code.foss.global/push.rocks/smartacme#readme",
"dependencies": {
"@api.global/typedserver": "^3.0.74",
"@push.rocks/lik": "^6.2.2",
"@push.rocks/smartdata": "^5.15.1",
"@apiclient.xyz/cloudflare": "^7.1.0",
"@peculiar/x509": "^2.0.0",
"@push.rocks/lik": "^6.4.0",
"@push.rocks/smartdata": "^7.1.3",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartdns": "^6.2.2",
"@push.rocks/smartlog": "^3.0.7",
"@push.rocks/smartpromise": "^4.2.3",
"@push.rocks/smartrequest": "^2.1.0",
"@push.rocks/smartstring": "^4.0.15",
"@push.rocks/smarttime": "^4.1.1",
"@push.rocks/smartdns": "^7.9.0",
"@push.rocks/smartlog": "^3.2.1",
"@push.rocks/smartnetwork": "^4.5.2",
"@push.rocks/smartstring": "^4.1.0",
"@push.rocks/smarttime": "^4.2.3",
"@push.rocks/smartunique": "^3.0.9",
"@tsclass/tsclass": "^9.0.0",
"acme-client": "^5.4.0"
"@push.rocks/taskbuffer": "^8.0.2",
"@tsclass/tsclass": "^9.5.0",
"reflect-metadata": "^0.2.2"
},
"devDependencies": {
"@apiclient.xyz/cloudflare": "^6.3.2",
"@git.zone/tsbuild": "^2.3.2",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.96",
"@push.rocks/qenv": "^6.1.0",
"@push.rocks/tapbundle": "^5.6.3",
"@types/node": "^22.15.2"
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tsrun": "^2.0.2",
"@git.zone/tstest": "^3.6.3",
"@push.rocks/qenv": "^6.1.3",
"@types/node": "^25.5.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"ts_*/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
".smartconfig.json",
"readme.md"
],
"browserslist": [

9692
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +1,81 @@
- 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'.
- 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'.
## 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.
## ACME Directory Server (ts_server/)
As of v9.2.0, a built-in ACME Directory Server lives under `ts_server/`. This is a full RFC 8555-compliant CA server that allows running your own Certificate Authority.
Key files:
- `ts_server/server.classes.acmeserver.ts` — Top-level `AcmeServer` facade (start/stop/config)
- `ts_server/server.classes.ca.ts` — Self-signed root CA generation + certificate signing via `@peculiar/x509`
- `ts_server/server.classes.jws.verifier.ts` — JWS signature verification (inverse of `AcmeCrypto.createJws`)
- `ts_server/server.classes.router.ts` — Minimal HTTP router with `:param` support using raw `node:http`
- `ts_server/server.classes.nonce.ts` — Single-use replay nonce management
- `ts_server/server.classes.challenge.verifier.ts` — HTTP-01/DNS-01 verification (with bypass mode)
- `ts_server/server.classes.account.store.ts` — In-memory account storage
- `ts_server/server.classes.order.store.ts` — In-memory order/authz/challenge/cert storage
- `ts_server/server.handlers.*.ts` — Route handlers for each ACME endpoint
Design decisions:
- Uses raw `node:http` (no framework dependency — `@api.global/typedserver` was explicitly removed in v8.1.0)
- Zero new dependencies: uses `node:crypto`, `@peculiar/x509`, and existing project deps
- Reuses `AcmeCrypto` for JWK thumbprint/base64url, ACME interfaces for response types, `AcmeError` patterns
- `AcmeCrypto.getAlg()` was made public (was private) for use by the JWS verifier
- Storage interfaces (`IServerAccountStore`, `IServerOrderStore`) are pluggable, with in-memory defaults
- `challengeVerification: false` option auto-approves challenges for testing
- `tsbuild tsfolders` automatically compiles `ts_server/` to `dist_ts_server/`
## 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 tsfolders` (v4.4.0+) — auto-discovers and compiles `ts/` and `ts_server/` directories
- `@peculiar/x509` v2.0.0 removed `reflect-metadata` from its dependencies. Since `tsyringe` (used internally by `@peculiar/x509`) requires the Reflect polyfill, `reflect-metadata` is now a direct dependency and imported in `ts/acme/acme.classes.crypto.ts` and `ts_server/server.classes.ca.ts`.
- `@push.rocks/taskbuffer` upgraded from v6 to v8 (required by smartdata 7.1.3). API surface is backward-compatible.
- TypeScript 6 (via tsbuild 4.4.0) requires `"types": ["node"]` in tsconfig.json for `ts_server/` compilation to resolve `@types/node`.
- TypeScript 6 deprecated `baseUrl` in tsconfig — removed it since `paths` was empty.
- Config file renamed from `npmextra.json` to `.smartconfig.json` (ecosystem convention change).

704
readme.md
View File

@@ -1,325 +1,533 @@
# @push.rocks/smartacme
A TypeScript-based ACME client with an easy yet powerful interface for LetsEncrypt certificate management.
A TypeScript-based ACME client and server for certificate management with a focus on simplicity and power. Includes a full RFC 8555-compliant ACME client for Let's Encrypt and a built-in ACME Directory Server for running your own Certificate Authority.
## 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
To install `@push.rocks/smartacme`, you can use npm or yarn. Run one of the following commands in your project directory:
```bash
npm install @push.rocks/smartacme --save
pnpm add @push.rocks/smartacme
```
or
```bash
yarn add @push.rocks/smartacme
```
Make sure your project is set up to use TypeScript and supports ECMAScript Modules (ESM).
Ensure your project uses TypeScript and ECMAScript Modules (ESM).
## Usage
This guide will walk you through using `@push.rocks/smartacme` to set up and manage ACME (Automated Certificate Management Environment) certificates with a focus on the Let's Encrypt service, which provides free SSL certificates. The library provides an easy yet powerful TypeScript interface to automate the process of obtaining, renewing, and installing your SSL certificates.
`@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), structured error handling with smart retry logic, and built-in concurrency control with rate limiting to keep you safely within Let's Encrypt limits.
### Table of Contents
1. [Setting Up Your Project](#setting-up-your-project)
2. [Creating a SmartAcme Instance](#creating-a-smartacme-instance)
3. [Initializing SmartAcme](#initializing-smartacme)
4. [Obtaining a Certificate for a Domain](#obtaining-a-certificate-for-a-domain)
5. [Automating DNS Challenges](#automating-dns-challenges)
6. [Managing Certificates](#managing-certificates)
7. [Environmental Considerations](#environmental-considerations)
8. [Complete Example](#complete-example)
### Setting Up Your Project
Ensure your project includes the necessary TypeScript configuration and dependencies. You'll need to have TypeScript installed and configured for ECMAScript Modules. If you are new to TypeScript, review its [documentation](https://www.typescriptlang.org/docs/) to get started.
### 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:
### 🚀 Quick Start
```typescript
import { SmartAcme } from '@push.rocks/smartacme';
import { SmartAcme, certmanagers, handlers } from '@push.rocks/smartacme';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
// Create a Cloudflare account client with your API token
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
// 1. Set up a certificate manager (MongoDB or in-memory)
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
});
// Instantiate SmartAcme with one or more ACME challenge handlers
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
},
environment: 'integration', // 'production' to request real certificates
retryOptions: {}, // optional retry/backoff settings
challengeHandlers: [
new Dns01Handler(cfAccount),
// you can add more handlers, e.g. Http01Handler
],
challengePriority: ['dns-01'], // optional ordering of challenge types
// 2. Set up challenge handlers
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_API_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
// 3. Create and start SmartAcme
const smartAcme = new SmartAcme({
accountEmail: 'admin@example.com',
certManager,
environment: 'production', // or 'integration' for staging
challengeHandlers: [dnsHandler],
});
await smartAcme.start();
// 4. Get a certificate
const cert = await smartAcme.getCertificateForDomain('example.com');
console.log(cert.publicKey); // PEM certificate chain
console.log(cert.privateKey); // PEM private key
// 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
};
// Concurrency & rate limiting
maxConcurrentIssuances?: number; // Global cap on parallel ACME ops (default: 5)
maxOrdersPerWindow?: number; // Max orders in sliding window (default: 250)
orderWindowMs?: number; // Sliding window duration in ms (default: 3 hours)
}
```
### 📜 Getting Certificates
```typescript
// 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');
```
Certificates are automatically cached and reused when still valid. Renewal happens automatically when a certificate is within 10 days of expiration. The actual X.509 expiry date is parsed from the issued certificate, ensuring renewal timing is precise.
### 📦 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
cert.isStillValid(); // true if not expired
cert.shouldBeRenewed(); // true if expires within 10 days
```
## 🔀 Concurrency Control & Rate Limiting
When many callers request certificates concurrently (e.g., hundreds of subdomains under the same TLD), SmartAcme automatically handles deduplication, concurrency, and rate limiting using a built-in task manager powered by `@push.rocks/taskbuffer`.
### How It Works
Three constraint layers protect your ACME account:
| Layer | What It Does | Default |
|-------|-------------|---------|
| **Per-domain mutex** | Only one issuance runs per base domain at a time. Concurrent requests for the same domain automatically wait and receive the same certificate result. | 1 concurrent per domain |
| **Global concurrency cap** | Limits total parallel ACME operations across all domains. | 5 concurrent |
| **Account rate limit** | Sliding-window rate limiter that keeps you under Let's Encrypt's 300 orders/3h account limit. | 250 per 3 hours |
### 🛡️ Automatic Request Deduplication
If 100 requests come in for subdomains of `example.com` simultaneously, only **one** ACME issuance runs. All other callers automatically wait and receive the same certificate — no duplicate orders, no wasted rate limit budget.
```typescript
// These all resolve to the same certificate with a single ACME order:
const results = await Promise.all([
smartAcme.getCertificateForDomain('app.example.com'),
smartAcme.getCertificateForDomain('api.example.com'),
smartAcme.getCertificateForDomain('cdn.example.com'),
]);
```
### ⚡ Configuring Limits
```typescript
const smartAcme = new SmartAcme({
accountEmail: 'admin@example.com',
certManager,
environment: 'production',
challengeHandlers: [dnsHandler],
maxConcurrentIssuances: 10, // Allow up to 10 parallel ACME issuances
maxOrdersPerWindow: 200, // Cap at 200 orders per window
orderWindowMs: 2 * 60 * 60_000, // 2-hour sliding window
});
```
### Initializing SmartAcme
### 📊 Observing Issuance Progress
Before proceeding to request certificates, start your SmartAcme instance:
Subscribe to the `certIssuanceEvents` stream to observe certificate issuance progress in real-time:
```typescript
await smartAcmeInstance.start();
smartAcme.certIssuanceEvents.subscribe((event) => {
switch (event.type) {
case 'started':
console.log(`🔄 Issuance started: ${event.task.name}`);
break;
case 'step':
console.log(`📍 Step: ${event.stepName} (${event.task.currentProgress}%)`);
break;
case 'completed':
console.log(`✅ Issuance completed: ${event.task.name}`);
break;
case 'failed':
console.log(`❌ Issuance failed: ${event.error}`);
break;
}
});
```
### Obtaining a Certificate for a Domain
Each issuance goes through four steps: **prepare** (10%) → **authorize** (40%) → **finalize** (30%) → **store** (20%).
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:
## Certificate Managers
SmartAcme uses the `ICertManager` interface for pluggable certificate storage.
### 🗄️ MongoCertManager
Persistent storage backed by MongoDB using `@push.rocks/smartdata`:
```typescript
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
import { certmanagers } from '@push.rocks/smartacme';
const certManager = new certmanagers.MongoCertManager({
mongoDbUrl: 'mongodb://localhost:27017',
mongoDbName: 'myapp',
mongoDbPass: 'secret',
});
```
### Automating DNS Challenges
### 🧪 MemoryCertManager
SmartAcme uses pluggable ACME challenge handlers (see built-in handlers below) to automate domain validation. You configure handlers via the `challengeHandlers` array when creating the instance, and SmartAcme will invoke each handlers `prepare`, optional `verify`, and `cleanup` methods during the ACME order flow.
### Managing Certificates
The library automatically handles fetching, renewing, and storing your certificates in a MongoDB database specified in your configuration. Ensure your MongoDB instance is accessible and properly configured for use with SmartAcme.
In-memory storage, ideal for testing or ephemeral workloads:
```typescript
const mongoDescriptor = {
mongoDbUrl: 'mongodb://yourmongoURL',
mongoDbName: 'yourDbName',
mongoDbPass: 'yourDbPassword',
};
import { certmanagers } from '@push.rocks/smartacme';
const certManager = new certmanagers.MemoryCertManager();
```
### Environmental Considerations
### 🔧 Custom Certificate Manager
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:
Implement the `ICertManager` interface for your own storage backend:
```typescript
import { SmartAcme } from '@push.rocks/smartacme';
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 { Qenv } from '@push.rocks/qenv';
const qenv = new Qenv('./', './.nogit/');
const cloudflareAccount = new cloudflare.CloudflareAccount(qenv.getEnvVarOnDemand('CF_TOKEN'));
const cfAccount = new cloudflare.CloudflareAccount('YOUR_CF_TOKEN');
const dnsHandler = new handlers.Dns01Handler(cfAccount);
```
async function main() {
const smartAcmeInstance = new SmartAcme({
accountEmail: 'youremail@example.com',
mongoDescriptor: {
mongoDbUrl: qenv.getEnvVarRequired('MONGODB_URL'),
mongoDbName: qenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: qenv.getEnvVarRequired('MONGODB_PASSWORD'),
},
environment: 'integration',
challengeHandlers: [ new Dns01Handler(cloudflareAccount) ],
});
DNS-01 is **required** for wildcard certificates and works regardless of server accessibility.
await smartAcmeInstance.start();
### 📁 Http01Webroot
const myDomain = 'example.com';
const myCert = await smartAcmeInstance.getCertificateForDomain(myDomain);
console.log('Certificate:', myCert);
Writes challenge response files to a filesystem webroot for `http-01` validation:
await smartAcmeInstance.stop();
```typescript
import { handlers } from '@push.rocks/smartacme';
const httpHandler = new handlers.Http01Webroot({
webroot: '/var/www/html',
});
```
The handler writes to `<webroot>/.well-known/acme-challenge/<token>` and cleans up after validation.
### 🧠 Http01MemoryHandler
In-memory HTTP-01 handler — stores challenge tokens in memory and serves them via `handleRequest()`:
```typescript
import { handlers } from '@push.rocks/smartacme';
const memHandler = new handlers.Http01MemoryHandler();
// Integrate with any HTTP server (Express, Koa, raw http, etc.)
app.use((req, res, next) => memHandler.handleRequest(req, res, next));
```
Perfect for serverless or container environments where filesystem access is limited.
### 🔧 Custom Challenge Handler
Implement `IChallengeHandler<T>` for custom challenge types:
```typescript
import type { handlers } from '@push.rocks/smartacme';
interface MyChallenge {
type: string;
token: string;
keyAuthorization: string;
}
main().catch(console.error);
```
## Built-in Challenge Handlers
This module includes two out-of-the-box ACME challenge handlers:
- **Dns01Handler**
- Uses a Cloudflare account (from `@apiclient.xyz/cloudflare`) and Smartdns client to set and remove DNS TXT records, then wait for propagation.
- Import path:
```typescript
import { Dns01Handler } from '@push.rocks/smartacme/ts/handlers/Dns01Handler.js';
```
- Example:
```typescript
import * as cloudflare from '@apiclient.xyz/cloudflare';
const cfAccount = new cloudflare.CloudflareAccount('CF_TOKEN');
const dnsHandler = new Dns01Handler(cfAccount);
```
- **Http01Handler**
- Writes ACME HTTP-01 challenge files under a file-system webroot (`/.well-known/acme-challenge/`), and removes them on cleanup.
- Import path:
```typescript
import { Http01Handler } from '@push.rocks/smartacme/ts/handlers/Http01Handler.js';
```
- Example:
```typescript
const httpHandler = new Http01Handler({ webroot: '/var/www/html' });
```
Both handlers implement the `IChallengeHandler<T>` interface and can be combined in the `challengeHandlers` array.
## Creating Custom Handlers
To support additional challenge types or custom validation flows, implement the `IChallengeHandler<T>` interface:
```typescript
import type { IChallengeHandler } from '@push.rocks/smartacme/ts/handlers/IChallengeHandler.js';
// Define your custom challenge payload type
interface MyChallenge { type: string; /* ... */ }
class MyCustomHandler implements IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] {
return ['my-01'];
}
// Prepare the challenge (set DNS records, start servers, etc.)
async prepare(ch: MyChallenge): Promise<void> {
// preparation logic
}
// Optional verify step after prepare
async verify?(ch: MyChallenge): Promise<void> {
// verification logic
}
// Cleanup after challenge (remove records, stop servers)
async cleanup(ch: MyChallenge): Promise<void> {
// cleanup logic
}
}
// Then register your handler:
const customInstance = new SmartAcme({
/* other options */,
challengeHandlers: [ new MyCustomHandler() ],
challengePriority: ['my-01'],
});
In this example, `Qenv` is used to manage environment variables, and `cloudflare` library is used to handle DNS challenges required by Let's Encrypt ACME protocol. The `setChallenge` and `removeChallenge` methods are essential for automating the DNS challenge process, which is a key part of domain validation.
## Additional Details
### Certificate Object
The certificate object obtained from the `getCertificateForDomain` method has the following properties:
- `id`: Unique identifier for the certificate.
- `domainName`: The domain name for which the certificate is issued.
- `created`: Timestamp of when the certificate was created.
- `privateKey`: The private key associated with the certificate.
- `publicKey`: The public key or certificate itself.
- `csr`: Certificate Signing Request (CSR) used to obtain the certificate.
- `validUntil`: Timestamp indicating the expiration date of the certificate.
### Methods Summary
- **start()**: Initializes the SmartAcme instance, sets up the ACME client, and registers the account with Let's Encrypt.
- **stop()**: Closes the MongoDB connection and performs any necessary cleanup.
- **getCertificateForDomain(domainArg: string)**: Retrieves or obtains a certificate for the specified domain name. If a valid certificate exists in the database, it is returned. Otherwise, a new certificate is requested and stored.
- **setChallenge(dnsChallenge: any)**: Automates the process of setting DNS challenge records.
- **removeChallenge(dnsChallenge: any)**: Automates the process of removing DNS challenge records.
### Handling Domain Matching
The `SmartacmeCertMatcher` class is responsible for matching certificates with the broadest scope for wildcard certificates. The `getCertificateDomainNameByDomainName` method ensures that domains at various levels are correctly matched.
```typescript
import { SmartacmeCertMatcher } from '@push.rocks/smartacme';
const certMatcher = new SmartacmeCertMatcher();
const certDomainName = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
console.log('Certificate Domain Name:', certDomainName); // Output: example.com
class MyHandler implements handlers.IChallengeHandler<MyChallenge> {
getSupportedTypes(): string[] { return ['http-01']; }
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; }
}
```
### Testing
## Error Handling
Automated tests can be added to ensure that the setup and functions work as expected. Using a testing framework such as `tap` and mock services for DNS providers (e.g., Cloudflare), you can simulate the process of obtaining and managing certificates without the need for actual domain ownership.
SmartAcme provides structured ACME error handling via the `AcmeError` class, which carries full RFC 8555 error information:
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { Qenv } from '@push.rocks/qenv';
import * as cloudflare from '@apiclient.xyz/cloudflare';
import * as smartacme from '@push.rocks/smartacme';
import { AcmeError } from '@push.rocks/smartacme/ts/acme/acme.classes.error.js';
const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN'));
try {
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
}
}
```
let smartAcmeInstance: smartacme.SmartAcme;
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.
tap.test('should create a valid instance of SmartAcme', async () => {
smartAcmeInstance = new smartacme.SmartAcme({
accountEmail: 'domains@lossless.org',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
setChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
removeChallenge: async (dnsChallenge) => {
await testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
environment: 'integration',
## 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');
});
await smartAcmeInstance.init();
expect(smartAcmeInstance).toBeInstanceOf(smartacme.SmartAcme);
});
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'],
});
tap.test('should get a domain certificate', async () => {
const certificate = await smartAcmeInstance.getCertificateForDomain('example.com');
console.log('Certificate:', certificate);
expect(certificate).toHaveProperty('domainName', 'example.com');
});
await smartAcme.start();
tap.test('certmatcher should correctly match domains', async () => {
const certMatcher = new smartacme.SmartacmeCertMatcher();
const matchedCert = certMatcher.getCertificateDomainNameByDomainName('subdomain.example.com');
expect(matchedCert).toBe('example.com');
});
const cert = await smartAcme.getCertificateForDomain('example.com');
// Use cert.publicKey and cert.privateKey with your HTTPS server
tap.test('should stop correctly', async () => {
await smartAcmeInstance.stop();
expect(smartAcmeInstance).toHaveProperty('client', null);
});
tap.start();
await smartAcme.stop();
server.close();
```
This comprehensive guide ensures you can set up, manage, and test ACME certificates efficiently and effectively using `@push.rocks/smartacme`.
## 🏗️ ACME Directory Server (Built-in CA)
---
SmartAcme includes a full RFC 8555-compliant ACME Directory Server, allowing you to run your own Certificate Authority. This is useful for internal PKI, development/testing environments, and air-gapped networks.
### Quick Start — ACME Server
```typescript
import { server } from '@push.rocks/smartacme';
const acmeServer = new server.AcmeServer({
port: 14000,
challengeVerification: false, // Auto-approve challenges (for testing)
caOptions: {
commonName: 'My Internal CA',
certValidityDays: 365,
},
});
await acmeServer.start();
console.log(acmeServer.getDirectoryUrl()); // http://localhost:14000/directory
console.log(acmeServer.getCaCertPem()); // Root CA certificate in PEM format
// ... use it, then shut down
await acmeServer.stop();
```
### Server Options
```typescript
interface IAcmeServerOptions {
port?: number; // Default: 14000
hostname?: string; // Default: '0.0.0.0'
baseUrl?: string; // Auto-built from hostname:port if not provided
challengeVerification?: boolean; // Default: true. Set false to auto-approve challenges
caOptions?: {
commonName?: string; // CA subject CN (default: 'SmartACME Test CA')
validityDays?: number; // Root cert validity in days (default: 3650)
certValidityDays?: number; // Issued cert validity in days (default: 90)
};
}
```
### Using the Server with the Low-Level ACME Client
The `SmartAcme` class connects to Let's Encrypt by default. To use a custom ACME directory (like your own server), use the lower-level `AcmeClient` directly:
```typescript
import { server } from '@push.rocks/smartacme';
import { AcmeCrypto, AcmeClient } from '@push.rocks/smartacme/ts/acme/index.js';
// 1. Start your own CA
const acmeServer = new server.AcmeServer({
port: 14000,
challengeVerification: false, // auto-approve for testing
});
await acmeServer.start();
// 2. Create an ACME client pointing at your CA
const accountKey = AcmeCrypto.createRsaPrivateKey();
const client = new AcmeClient({
directoryUrl: acmeServer.getDirectoryUrl(),
accountKeyPem: accountKey,
});
// 3. Register an account
await client.createAccount({ termsOfServiceAgreed: true, contact: ['mailto:admin@internal.example.com'] });
// 4. Create an order and issue a certificate
const order = await client.createOrder({
identifiers: [{ type: 'dns', value: 'myapp.internal' }],
});
// ... complete challenges, finalize, and download cert
// (challenges auto-approved since challengeVerification is false)
await acmeServer.stop();
```
### Server Endpoints
The ACME server implements all RFC 8555 endpoints:
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/directory` | GET | ACME directory with all endpoint URLs |
| `/new-nonce` | HEAD/GET | Fresh replay nonce |
| `/new-account` | POST | Account registration/lookup |
| `/new-order` | POST | Create certificate order |
| `/order/:id` | POST | Poll order status |
| `/authz/:id` | POST | Get authorization with challenges |
| `/challenge/:id` | POST | Trigger or poll challenge validation |
| `/finalize/:id` | POST | Submit CSR and issue certificate |
| `/cert/:id` | POST | Download PEM certificate chain |
### Challenge Verification
By default, the server performs real challenge verification (HTTP-01 fetches the token, DNS-01 queries TXT records). Set `challengeVerification: false` to auto-approve all challenges — useful for testing or internal environments where domain validation isn't needed.
### Root CA Certificate
Use `getCaCertPem()` to retrieve the root CA certificate for trust configuration:
```typescript
import * as fs from 'fs';
fs.writeFileSync('/usr/local/share/ca-certificates/my-ca.crt', acmeServer.getCaCertPem());
// Then: sudo update-ca-certificates
```
## 🏛️ Architecture
Under the hood, SmartAcme uses a fully custom RFC 8555-compliant ACME protocol implementation (no external ACME libraries). Key internal modules:
### Client Modules (`ts/acme/`)
| Module | Purpose |
|--------|---------|
| `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 |
| `TaskManager` | Constraint-based concurrency control, rate limiting, and request deduplication via `@push.rocks/taskbuffer` |
### Server Modules (`ts_server/`)
| Module | Purpose |
|--------|---------|
| `AcmeServer` | Top-level server facade — start, stop, configuration |
| `AcmeServerCA` | Self-signed root CA generation and certificate signing via `@peculiar/x509` |
| `JwsVerifier` | JWS signature verification (inverse of `AcmeCrypto.createJws`) |
| `NonceManager` | Single-use replay nonce generation and validation |
| `ChallengeVerifier` | HTTP-01 and DNS-01 challenge verification (with bypass mode) |
| `AcmeRouter` | Minimal HTTP router with parameterized path support |
| `MemoryAccountStore` | In-memory ACME account storage |
| `MemoryOrderStore` | In-memory order, authorization, challenge, and certificate storage |
All cryptographic operations use `node:crypto`. The only external crypto dependency is `@peculiar/x509` for CSR generation and certificate signing.
## 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.md) 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
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
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.

3
readme.plan.md Normal file
View File

@@ -0,0 +1,3 @@
## Plan
Move the

View 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
View 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
View 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();

View File

@@ -0,0 +1,336 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as http from 'node:http';
import * as crypto from 'node:crypto';
import { AcmeServer } from '../ts_server/index.js';
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
const TEST_PORT = 14567;
const BASE_URL = `http://localhost:${TEST_PORT}`;
let server: AcmeServer;
let accountKeyPem: string;
let accountUrl: string;
let nonce: string;
// Helper: simple HTTP request
function httpRequest(
url: string,
method: string,
body?: string,
headers?: Record<string, string>,
): Promise<{ status: number; headers: Record<string, string>; data: any }> {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const options: http.RequestOptions = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method,
headers: {
...headers,
...(body ? { 'Content-Length': Buffer.byteLength(body).toString() } : {}),
},
};
const req = http.request(options, (res) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf-8');
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];
}
}
let data: any;
const ct = responseHeaders['content-type'] || '';
if (ct.includes('json') || ct.includes('problem')) {
try { data = JSON.parse(raw); } catch { data = raw; }
} else {
data = raw;
}
resolve({ status: res.statusCode || 0, headers: responseHeaders, data });
});
});
req.on('error', reject);
req.setTimeout(10000, () => req.destroy(new Error('Timeout')));
if (body) req.write(body);
req.end();
});
}
// Helper: signed ACME request
async function signedRequest(
url: string,
payload: any | null,
options?: { useJwk?: boolean },
): Promise<{ status: number; headers: Record<string, string>; data: any }> {
const jwsOptions: { nonce: string; kid?: string; jwk?: Record<string, string> } = { nonce };
if (options?.useJwk) {
jwsOptions.jwk = AcmeCrypto.getJwk(accountKeyPem);
} else if (accountUrl) {
jwsOptions.kid = accountUrl;
} else {
jwsOptions.jwk = AcmeCrypto.getJwk(accountKeyPem);
}
const jws = AcmeCrypto.createJws(accountKeyPem, url, payload, jwsOptions);
const body = JSON.stringify(jws);
const response = await httpRequest(url, 'POST', body, {
'Content-Type': 'application/jose+json',
});
// Save nonce from response
if (response.headers['replay-nonce']) {
nonce = response.headers['replay-nonce'];
}
return response;
}
// Helper: get a fresh nonce
async function fetchNonce(): Promise<string> {
const res = await httpRequest(`${BASE_URL}/new-nonce`, 'HEAD');
return res.headers['replay-nonce'];
}
// ============================================================================
// Tests
// ============================================================================
tap.test('server: start ACME server', async () => {
server = new AcmeServer({
port: TEST_PORT,
baseUrl: BASE_URL,
challengeVerification: false, // Auto-approve challenges for testing
caOptions: {
commonName: 'Test ACME CA',
certValidityDays: 30,
},
});
await server.start();
});
tap.test('server: GET /directory returns valid directory', async () => {
const res = await httpRequest(`${BASE_URL}/directory`, 'GET');
expect(res.status).toEqual(200);
expect(res.data.newNonce).toEqual(`${BASE_URL}/new-nonce`);
expect(res.data.newAccount).toEqual(`${BASE_URL}/new-account`);
expect(res.data.newOrder).toEqual(`${BASE_URL}/new-order`);
expect(res.data.meta).toBeTruthy();
});
tap.test('server: HEAD /new-nonce returns Replay-Nonce header', async () => {
const res = await httpRequest(`${BASE_URL}/new-nonce`, 'HEAD');
expect(res.status).toEqual(200);
expect(res.headers['replay-nonce']).toBeTruthy();
});
tap.test('server: GET /new-nonce returns 204 with Replay-Nonce header', async () => {
const res = await httpRequest(`${BASE_URL}/new-nonce`, 'GET');
expect(res.status).toEqual(204);
expect(res.headers['replay-nonce']).toBeTruthy();
});
tap.test('server: POST /new-account registers an account', async () => {
accountKeyPem = AcmeCrypto.createRsaPrivateKey();
nonce = await fetchNonce();
const res = await signedRequest(`${BASE_URL}/new-account`, {
termsOfServiceAgreed: true,
contact: ['mailto:test@example.com'],
}, { useJwk: true });
expect(res.status).toEqual(201);
expect(res.headers['location']).toBeTruthy();
expect(res.data.status).toEqual('valid');
accountUrl = res.headers['location'];
});
tap.test('server: POST /new-account returns existing account', async () => {
const res = await signedRequest(`${BASE_URL}/new-account`, {
termsOfServiceAgreed: true,
contact: ['mailto:test@example.com'],
}, { useJwk: true });
expect(res.status).toEqual(200);
expect(res.headers['location']).toEqual(accountUrl);
});
tap.test('server: full certificate issuance flow', async () => {
// 1. Create order
const orderRes = await signedRequest(`${BASE_URL}/new-order`, {
identifiers: [{ type: 'dns', value: 'example.com' }],
});
expect(orderRes.status).toEqual(201);
expect(orderRes.data.status).toEqual('pending');
expect(orderRes.data.authorizations).toBeTypeOf('object');
expect(orderRes.data.finalize).toBeTruthy();
const orderUrl = orderRes.headers['location'];
const authzUrl = orderRes.data.authorizations[0];
const finalizeUrl = orderRes.data.finalize;
// 2. Get authorization
const authzRes = await signedRequest(authzUrl, null);
expect(authzRes.status).toEqual(200);
expect(authzRes.data.identifier.value).toEqual('example.com');
expect(authzRes.data.challenges.length).toBeGreaterThan(0);
// Pick a challenge (prefer dns-01 since it's always available)
const challenge = authzRes.data.challenges.find((c: any) => c.type === 'dns-01') || authzRes.data.challenges[0];
expect(challenge.status).toEqual('pending');
// 3. Trigger challenge (auto-approved since challengeVerification is false)
const challengeRes = await signedRequest(challenge.url, {});
expect(challengeRes.status).toEqual(200);
expect(challengeRes.data.status).toEqual('valid');
// 4. Poll order — should now be ready
const orderPollRes = await signedRequest(orderUrl, null);
expect(orderPollRes.status).toEqual(200);
expect(orderPollRes.data.status).toEqual('ready');
// 5. Create CSR and finalize
const [keyPem, csrPem] = await AcmeCrypto.createCsr({
commonName: 'example.com',
altNames: ['example.com'],
});
const csrDer = AcmeCrypto.pemToBuffer(csrPem);
const csrB64url = csrDer.toString('base64url');
const finalizeRes = await signedRequest(finalizeUrl, { csr: csrB64url });
expect(finalizeRes.status).toEqual(200);
expect(finalizeRes.data.status).toEqual('valid');
expect(finalizeRes.data.certificate).toBeTruthy();
// 6. Download certificate
const certUrl = finalizeRes.data.certificate;
const certRes = await signedRequest(certUrl, null);
expect(certRes.status).toEqual(200);
expect(certRes.headers['content-type']).toEqual('application/pem-certificate-chain');
expect(certRes.data).toInclude('BEGIN CERTIFICATE');
// Verify it's a valid PEM chain (at least 2 certs: end-entity + CA)
const certMatches = (certRes.data as string).match(/-----BEGIN CERTIFICATE-----/g);
expect(certMatches!.length).toBeGreaterThan(1);
});
tap.test('server: wildcard certificate issuance', async () => {
// Create order with wildcard
const orderRes = await signedRequest(`${BASE_URL}/new-order`, {
identifiers: [
{ type: 'dns', value: 'test.org' },
{ type: 'dns', value: '*.test.org' },
],
});
expect(orderRes.status).toEqual(201);
expect(orderRes.data.authorizations.length).toEqual(2);
const orderUrl = orderRes.headers['location'];
// Complete all challenges
for (const authzUrl of orderRes.data.authorizations) {
const authzRes = await signedRequest(authzUrl, null);
// For wildcard, only dns-01 should be available
const challenge = authzRes.data.challenges.find((c: any) => c.type === 'dns-01');
expect(challenge).toBeTruthy();
await signedRequest(challenge.url, {});
}
// Poll order
const orderPollRes = await signedRequest(orderUrl, null);
expect(orderPollRes.data.status).toEqual('ready');
// Finalize
const [keyPem, csrPem] = await AcmeCrypto.createCsr({
commonName: 'test.org',
altNames: ['test.org', '*.test.org'],
});
const csrDer = AcmeCrypto.pemToBuffer(csrPem);
const finalizeRes = await signedRequest(orderPollRes.data.finalize, {
csr: csrDer.toString('base64url'),
});
expect(finalizeRes.data.status).toEqual('valid');
// Download cert
const certRes = await signedRequest(finalizeRes.data.certificate, null);
expect(certRes.data).toInclude('BEGIN CERTIFICATE');
});
tap.test('server: rejects invalid JWS signature', async () => {
// Create JWS with one key but sign URL intended for a different key
const otherKey = AcmeCrypto.createRsaPrivateKey();
const otherNonce = await fetchNonce();
const jws = AcmeCrypto.createJws(otherKey, `${BASE_URL}/new-order`, { identifiers: [] }, {
nonce: otherNonce,
kid: accountUrl, // Use our account URL but sign with a different key
});
const res = await httpRequest(`${BASE_URL}/new-order`, 'POST', JSON.stringify(jws), {
'Content-Type': 'application/jose+json',
});
// Save nonce for next request
if (res.headers['replay-nonce']) {
nonce = res.headers['replay-nonce'];
}
expect(res.status).toEqual(403);
});
tap.test('server: rejects expired/bad nonce', async () => {
const jws = AcmeCrypto.createJws(
accountKeyPem,
`${BASE_URL}/new-order`,
{ identifiers: [{ type: 'dns', value: 'example.com' }] },
{ nonce: 'definitely-not-a-valid-nonce', kid: accountUrl },
);
const res = await httpRequest(`${BASE_URL}/new-order`, 'POST', JSON.stringify(jws), {
'Content-Type': 'application/jose+json',
});
if (res.headers['replay-nonce']) {
nonce = res.headers['replay-nonce'];
}
expect(res.status).toEqual(400);
expect(res.data.type).toEqual('urn:ietf:params:acme:error:badNonce');
});
tap.test('server: finalize rejects order not in ready state', async () => {
// Create a new order but don't complete challenges
const orderRes = await signedRequest(`${BASE_URL}/new-order`, {
identifiers: [{ type: 'dns', value: 'pending.example.com' }],
});
const [keyPem, csrPem] = await AcmeCrypto.createCsr({
commonName: 'pending.example.com',
});
const csrDer = AcmeCrypto.pemToBuffer(csrPem);
const finalizeRes = await signedRequest(orderRes.data.finalize, {
csr: csrDer.toString('base64url'),
});
expect(finalizeRes.status).toEqual(403);
expect(finalizeRes.data.type).toEqual('urn:ietf:params:acme:error:orderNotReady');
});
tap.test('server: getCaCertPem returns root CA certificate', async () => {
const caPem = server.getCaCertPem();
expect(caPem).toInclude('BEGIN CERTIFICATE');
});
tap.test('server: stop ACME server', async () => {
await server.stop();
});
export default tap.start();

View File

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

View File

@@ -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';
tap.test('Dns01Handler prepare and cleanup calls Cloudflare and DNS functions', async () => {
@@ -7,15 +7,11 @@ tap.test('Dns01Handler prepare and cleanup calls Cloudflare and DNS functions',
// fake Cloudflare API
const fakeCF: any = {
convenience: {
acmeSetDnsChallenge: async (ch: any) => {
acmeSetDnsChallenge: async (_ch: any) => {
setCalled = true;
expect(ch).toHaveProperty('hostName');
expect(ch).toHaveProperty('challenge');
},
acmeRemoveDnsChallenge: async (ch: any) => {
acmeRemoveDnsChallenge: async (_ch: any) => {
removeCalled = true;
expect(ch).toHaveProperty('hostName');
expect(ch).toHaveProperty('challenge');
},
},
};

View File

@@ -0,0 +1,58 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import { Http01MemoryHandler } from '../ts/handlers/Http01MemoryHandler.js';
tap.test('Http01MemoryHandler serves in-memory challenges and cleans up', async () => {
const handler = new Http01MemoryHandler();
const token = 'testtoken';
const keyAuth = 'keyAuthValue';
const webPath = `/.well-known/acme-challenge/${token}`;
const challenge = { type: 'http-01', token, keyAuthorization: keyAuth, webPath };
// Prepare challenge (store in memory)
await handler.prepare(challenge);
// Serve existing challenge without next()
const req1: any = { url: webPath };
const res1: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req1, res1);
expect(res1.statusCode).toEqual(200);
expect(res1.body).toEqual(keyAuth);
expect(res1.headers['content-type']).toEqual('text/plain');
// Cleanup challenge (remove from memory)
await handler.cleanup(challenge);
// Serve after cleanup without next() should give 404
const req2: any = { url: webPath };
const res2: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req2, res2);
expect(res2.statusCode).toEqual(404);
// Serve after cleanup with next() should call next
const req3: any = { url: webPath };
let nextCalled = false;
const next = () => { nextCalled = true; };
const res3: any = {
statusCode: 0,
headers: {} as Record<string, string>,
body: '',
setHeader(name: string, value: string) { this.headers[name] = value; },
end(body?: string) { this.body = body || ''; },
};
handler.handleRequest(req3, res3, next);
expect(nextCalled).toEqual(true);
});
export default tap.start();

View File

@@ -1,13 +1,13 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { Http01Handler } from '../ts/handlers/Http01Handler.js';
import { tap, expect } from '@git.zone/tstest/tapbundle';
import { Http01Webroot } from '../ts/handlers/Http01Handler.js';
import { promises as fs } from 'fs';
import * as path from 'path';
import os from 'os';
tap.test('Http01Handler writes challenge file and removes it on cleanup', async () => {
tap.test('Http01Webroot writes challenge file and removes it on cleanup', async () => {
// create temporary webroot directory
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'http01-'));
const handler = new Http01Handler({ webroot: tmpDir });
const handler = new Http01Webroot({ webroot: tmpDir });
const token = 'testtoken';
const keyAuth = 'keyAuthValue';
const webPath = `/.well-known/acme-challenge/${token}`;

172
test/test.http01-only.ts Normal file
View 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();

View File

@@ -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 * as cloudflare from '@apiclient.xyz/cloudflare';
import { SmartAcme } from '../ts/index.js';
import { SmartAcme, certmanagers } from '../ts/index.js';
import { Dns01Handler } from '../ts/handlers/Dns01Handler.js';
// Load environment variables for credentials (stored under .nogit/)
@@ -14,12 +14,14 @@ const mongoDbName = (await testQenv.getEnvVarOnDemand('MONGODB_DATABASE'))!;
const mongoDbPass = (await testQenv.getEnvVarOnDemand('MONGODB_PASSWORD'))!;
const mongoDbUrl = (await testQenv.getEnvVarOnDemand('MONGODB_URL'))!;
let smartAcmeInstance: SmartAcme;
tap.test('create SmartAcme instance with DNS-01 handler and start', async () => {
smartAcmeInstance = new SmartAcme({
accountEmail: 'domains@lossless.org',
mongoDescriptor: { mongoDbName, mongoDbPass, mongoDbUrl },
// certManager: new MongoCertManager({ mongoDbName, mongoDbPass, mongoDbUrl }),
certManager: new certmanagers.MemoryCertManager(),
environment: 'integration',
retryOptions: {},
challengeHandlers: [new Dns01Handler(cfAccount)],
@@ -29,10 +31,13 @@ tap.test('create SmartAcme instance with DNS-01 handler and start', async () =>
expect(smartAcmeInstance).toBeInstanceOf(SmartAcme);
});
tap.test('get a domain certificate via DNS-01 challenge', async () => {
// Replace 'bleu.de' with your test domain if different
tap.test('should wipe the certmanager for this test', async () => {
await smartAcmeInstance.certmanager.wipe();
});
tap.test('get a domain certificate covering bleu.de and *.bleu.de via DNS-01 challenge', async () => {
const domain = 'bleu.de';
const cert = await smartAcmeInstance.getCertificateForDomain(domain);
const cert = await smartAcmeInstance.getCertificateForDomain(domain, { includeWildcard: true });
expect(cert).toHaveProperty('domainName');
expect(cert.domainName).toEqual(domain);
expect(cert).toHaveProperty('publicKey');

View File

@@ -1,5 +1,6 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { SmartAcme } from '../ts/index.js';
import { tap, expect } from '@git.zone/tstest/tapbundle';
import { SmartAcme, certmanagers } from '../ts/index.js';
import { Cert } from '../ts/index.js';
import type { IChallengeHandler } from '../ts/handlers/IChallengeHandler.js';
// Dummy handler for testing
@@ -7,12 +8,13 @@ class DummyHandler implements IChallengeHandler<any> {
getSupportedTypes(): string[] { return ['dns-01']; }
async prepare(_: 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 () => {
expect(() => new SmartAcme({
accountEmail: 'test@example.com',
mongoDescriptor: { mongoDbName: 'db', mongoDbPass: 'pass', mongoDbUrl: 'url' },
certManager: new certmanagers.MemoryCertManager(),
environment: 'integration',
retryOptions: {},
} as any)).toThrow();
@@ -21,12 +23,39 @@ tap.test('constructor throws without challengeHandlers', async () => {
tap.test('constructor accepts valid challengeHandlers', async () => {
const sa = new SmartAcme({
accountEmail: 'test@example.com',
mongoDescriptor: { mongoDbName: 'db', mongoDbPass: 'pass', mongoDbUrl: 'url' },
certManager: new certmanagers.MemoryCertManager(),
environment: 'integration',
retryOptions: {},
challengeHandlers: [new DummyHandler()],
});
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();

View 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();

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartacme',
version: '6.1.2',
description: 'A TypeScript-based ACME client for LetsEncrypt certificate management with a focus on simplicity and power.'
version: '9.3.1',
description: 'A TypeScript-based ACME client and server for certificate management with built-in CA, supporting LetsEncrypt and custom ACME authorities.'
}

View 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;
}
}

View 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, {});
}
}

View 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();
}
}

View File

@@ -0,0 +1,221 @@
import 'reflect-metadata';
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
*/
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 };
}
}

View 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;

View 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;
}
}

View 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();
});
}
}

View 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`);
}
}

View 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
View 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';

2
ts/certmanagers/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export * from './memory.js';
export * from './mongo.js';

38
ts/certmanagers/memory.ts Normal file
View File

@@ -0,0 +1,38 @@
import * as plugins from '../plugins.js';
import type { ICertManager } from '../interfaces/certmanager.js';
import { SmartacmeCert } from '../smartacme.classes.cert.js';
/**
* In-memory certificate manager for mongoless mode.
* Stores certificates in memory only and does not connect to MongoDB.
*/
export class MemoryCertManager implements ICertManager {
private certs: Map<string, SmartacmeCert> = new Map();
public async init(): Promise<void> {
// no-op for in-memory store
}
public async retrieveCertificate(domainName: string): Promise<SmartacmeCert | null> {
return this.certs.get(domainName) ?? null;
}
public async storeCertificate(cert: SmartacmeCert): Promise<void> {
this.certs.set(cert.domainName, cert);
}
public async deleteCertificate(domainName: string): Promise<void> {
this.certs.delete(domainName);
}
public async close(): Promise<void> {
// no-op
}
/**
* Wipe all certificates from the in-memory store (for testing)
*/
public async wipe(): Promise<void> {
this.certs.clear();
}
}

51
ts/certmanagers/mongo.ts Normal file
View File

@@ -0,0 +1,51 @@
import * as plugins from '../plugins.js';
import type { ICertManager } from '../interfaces/certmanager.js';
import { SmartacmeCert } from '../smartacme.classes.cert.js';
/**
* MongoDB-backed certificate manager using EasyStore from smartdata.
*/
export class MongoCertManager implements ICertManager {
private db: plugins.smartdata.SmartdataDb;
private store: plugins.smartdata.EasyStore<Record<string, any>>;
/**
* @param mongoDescriptor MongoDB connection settings
*/
constructor(mongoDescriptor: plugins.smartdata.IMongoDescriptor) {
this.db = new plugins.smartdata.SmartdataDb(mongoDescriptor);
this.store = new plugins.smartdata.EasyStore<Record<string, any>>(
'smartacme-certs',
this.db,
);
}
public async init(): Promise<void> {
await this.db.init();
}
public async retrieveCertificate(domainName: string): Promise<SmartacmeCert | null> {
const data = await this.store.readKey(domainName);
return data ? new SmartacmeCert(data) : null;
}
public async storeCertificate(cert: SmartacmeCert): Promise<void> {
// write plain object for persistence
await this.store.writeKey(cert.domainName, { ...cert });
}
public async deleteCertificate(domainName: string): Promise<void> {
await this.store.deleteKey(domainName);
}
public async close(): Promise<void> {
await this.db.close();
}
/**
* Wipe all certificates from the persistent store (for integration testing)
*/
public async wipe(): Promise<void> {
// clear all keys in the easy store
await this.store.wipe();
}
}

View File

@@ -1,18 +1,18 @@
import * as plugins from '../smartacme.plugins.js';
import * as plugins from '../plugins.js';
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* DNS-01 challenge handler using CloudflareAccount and Smartdns.
*/
export class Dns01Handler implements IChallengeHandler<plugins.tsclass.network.IDnsChallenge> {
private cf: any;
private cf: plugins.tsclass.network.IConvenientDnsProvider;
private smartdns: plugins.smartdnsClient.Smartdns;
constructor(
cloudflareAccount: any,
convenientDnsProvider: plugins.tsclass.network.IConvenientDnsProvider,
smartdnsInstance?: plugins.smartdnsClient.Smartdns,
) {
this.cf = cloudflareAccount;
this.cf = convenientDnsProvider;
this.smartdns = smartdnsInstance ?? new plugins.smartdnsClient.Smartdns({});
}
@@ -23,18 +23,14 @@ export class Dns01Handler implements IChallengeHandler<plugins.tsclass.network.I
public async prepare(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
// set DNS TXT record
await this.cf.convenience.acmeSetDnsChallenge(ch);
// wait for DNS propagation
await this.smartdns.checkUntilAvailable(
ch.hostName,
'TXT',
ch.challenge,
100,
5000,
);
}
public async cleanup(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
// remove DNS TXT record
await this.cf.convenience.acmeRemoveDnsChallenge(ch);
}
public async checkWetherDomainIsSupported(domainArg: string): Promise<boolean> {
return this.cf.convenience.isDomainSupported(domainArg);
}
}

View File

@@ -1,27 +1,29 @@
import { promises as fs } from 'fs';
import * as path from 'path';
import * as plugins from '../plugins.js';
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* HTTP-01 ACME challenge handler using file-system webroot.
* Writes and removes the challenge file under <webroot>/.well-known/acme-challenge/.
*/
export interface Http01HandlerOptions {
export interface Http01WebrootOptions {
/**
* Directory that serves HTTP requests for /.well-known/acme-challenge
*/
webroot: string;
}
export class Http01Handler implements IChallengeHandler<{
export class Http01Webroot implements IChallengeHandler<{
type: string;
token: string;
keyAuthorization: string;
webPath: string;
}> {
private smartnetworkInstance = new plugins.smartnetwork.SmartNetwork();
private smartdnsClient = new plugins.smartdnsClient.Smartdns({});
private webroot: string;
constructor(options: Http01HandlerOptions) {
constructor(options: Http01WebrootOptions) {
this.webroot = options.webroot;
}
@@ -31,10 +33,10 @@ export class Http01Handler implements IChallengeHandler<{
public async prepare(ch: { token: string; keyAuthorization: string; webPath: string }): Promise<void> {
const relWebPath = ch.webPath.replace(/^\/+/, '');
const filePath = path.join(this.webroot, relWebPath);
const dir = path.dirname(filePath);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(filePath, ch.keyAuthorization, 'utf8');
const filePath = plugins.path.join(this.webroot, relWebPath);
const dir = plugins.path.dirname(filePath);
await plugins.fs.promises.mkdir(dir, { recursive: true });
await plugins.fs.promises.writeFile(filePath, ch.keyAuthorization, 'utf8');
}
public async verify(ch: { webPath: string; keyAuthorization: string }): Promise<void> {
@@ -44,11 +46,24 @@ export class Http01Handler implements IChallengeHandler<{
public async cleanup(ch: { token: string; webPath: string }): Promise<void> {
const relWebPath = ch.webPath.replace(/^\/+/, '');
const filePath = path.join(this.webroot, relWebPath);
const filePath = plugins.path.join(this.webroot, relWebPath);
try {
await fs.unlink(filePath);
await plugins.fs.promises.unlink(filePath);
} catch {
// 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;
}
}

View File

@@ -0,0 +1,83 @@
import * as plugins from '../plugins.js';
import type { IChallengeHandler } from './IChallengeHandler.js';
/**
* HTTP-01 ACME challenge handler using in-memory storage.
* Stores challenge tokens and key authorizations in memory
* and serves them via handleRequest for arbitrary HTTP servers.
*/
export interface Http01MemoryHandlerChallenge {
type: string;
token: string;
keyAuthorization: string;
webPath: string;
}
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();
public getSupportedTypes(): string[] {
return ['http-01'];
}
public async prepare(ch: Http01MemoryHandlerChallenge): Promise<void> {
this.store.set(ch.token, ch.keyAuthorization);
}
public async verify(_ch: Http01MemoryHandlerChallenge): Promise<void> {
// No-op
return;
}
public async cleanup(ch: Http01MemoryHandlerChallenge): Promise<void> {
this.store.delete(ch.token);
}
/**
* HTTP request handler for serving ACME HTTP-01 challenges.
* @param req HTTP request object (should have url property)
* @param res HTTP response object
* @param next Optional next() callback for Express-style fallthrough
*/
public handleRequest(req: any, res: any, next?: () => void): void {
const url = req.url || '';
const prefix = '/.well-known/acme-challenge/';
if (!url.startsWith(prefix)) {
if (next) {
return next();
}
res.statusCode = 404;
return res.end();
}
const token = url.slice(prefix.length);
const keyAuth = this.store.get(token);
if (keyAuth !== undefined) {
if (typeof res.status === 'function' && typeof res.send === 'function') {
return res.status(200).send(keyAuth);
}
res.statusCode = 200;
res.setHeader('content-type', 'text/plain');
return res.end(keyAuth);
}
if (next) {
return next();
}
res.statusCode = 404;
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;
}
}

View File

@@ -19,4 +19,6 @@ export interface IChallengeHandler<T> {
* Clean up resources: remove DNS record, stop server.
*/
cleanup(ch: T): Promise<void>;
checkWetherDomainIsSupported(domainArg: string): Promise<boolean>;
}

View File

@@ -1,4 +1,5 @@
export type { IChallengeHandler } from './IChallengeHandler.js';
// Removed legacy handler adapter
export { Dns01Handler } from './Dns01Handler.js';
export { Http01Handler } from './Http01Handler.js';
export { Http01Webroot } from './Http01Handler.js';
export { Http01MemoryHandler } from './Http01MemoryHandler.js';

View File

@@ -1,2 +1,18 @@
export * from './smartacme.classes.smartacme.js';
export { SmartacmeCert as Cert } from './smartacme.classes.cert.js';
export type { ICertManager } from './interfaces/certmanager.js';
// certmanagers
import * as certmanagers from './certmanagers/index.js';
export { certmanagers };
// handlers
import * as handlers from './handlers/index.js';
export { handlers };
// server (ACME Directory Server / CA)
import * as server from '../ts_server/index.js';
export { server };
// re-export taskbuffer event types for consumers
export type { ITaskEvent, ITaskMetadata } from '@push.rocks/taskbuffer';

View File

@@ -0,0 +1,36 @@
import type { SmartacmeCert } from '../smartacme.classes.cert.js';
// (ICertRecord removed; use SmartacmeCert directly)
/**
* Interface for certificate storage managers.
* Users can implement this to provide custom persistence (in-memory,
* file-based, Redis, etc.).
*/
export interface ICertManager {
/**
* Initialize the store (e.g., connect to database).
*/
init(): Promise<void>;
/**
* Retrieve a certificate record by domain name.
* Returns null if none found.
*/
retrieveCertificate(domainName: string): Promise<SmartacmeCert | null>;
/**
* Store a certificate record. Fulfills any pending interests.
*/
storeCertificate(cert: SmartacmeCert): Promise<void>;
/**
* Delete a certificate record by domain name.
*/
deleteCertificate(domainName: string): Promise<void>;
/**
* Close the store (e.g., disconnect database).
*/
close(): Promise<void>;
/**
* Optional: wipe all stored certificates (e.g., for integration testing)
*/
wipe(): Promise<void>;
}

View File

@@ -1,19 +1,29 @@
// @apiglobal scope
import * as typedserver from '@api.global/typedserver';
// reflect-metadata polyfill (required by @peculiar/x509 v2 via tsyringe)
import 'reflect-metadata';
export { typedserver };
// node native
import * as crypto from 'node:crypto';
import * as fs from 'fs';
import * as path from 'path';
// @pushrocks scope
export { crypto, fs, path };
// @apiclient.xyz scope
import * as cloudflare from '@apiclient.xyz/cloudflare';
export { cloudflare };
// @push.rocks scope
import * as lik from '@push.rocks/lik';
import * as smartdata from '@push.rocks/smartdata';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartdnsClient from '@push.rocks/smartdns/client';
import * as smartlog from '@push.rocks/smartlog';
import * as smartpromise from '@push.rocks/smartpromise';
import * as smartrequest from '@push.rocks/smartrequest';
import * as smartnetwork from '@push.rocks/smartnetwork';
import * as smartunique from '@push.rocks/smartunique';
import * as smartstring from '@push.rocks/smartstring';
import * as smarttime from '@push.rocks/smarttime';
import * as taskbuffer from '@push.rocks/taskbuffer';
export {
lik,
@@ -21,11 +31,11 @@ export {
smartdelay,
smartdnsClient,
smartlog,
smartpromise,
smartrequest,
smartnetwork,
smartunique,
smartstring,
smarttime,
taskbuffer,
};
// @tsclass scope
@@ -33,8 +43,8 @@ import * as tsclass from '@tsclass/tsclass';
export { tsclass };
// third party scope
import * as acme from 'acme-client';
// acme protocol (custom implementation)
import * as acme from './acme/index.js';
export { acme };
// local handlers for challenge types

View File

@@ -1,64 +1,39 @@
import * as plugins from './smartacme.plugins.js';
import * as plugins from './plugins.js';
import * as interfaces from './interfaces/index.js';
import { SmartacmeCertManager } from './smartacme.classes.certmanager.js';
import { Collection, svDb, unI } from '@push.rocks/smartdata';
@plugins.smartdata.Collection(() => {
return SmartacmeCertManager.activeDB;
})
export class SmartacmeCert
extends plugins.smartdata.SmartDataDbDoc<SmartacmeCert, plugins.tsclass.network.ICert>
implements plugins.tsclass.network.ICert
{
@unI()
/**
* Plain certificate record.
*/
export class SmartacmeCert {
public id: string;
@svDb()
public domainName: string;
@svDb()
public created: number;
@svDb()
public privateKey: string;
@svDb()
public publicKey: string;
@svDb()
public csr: string;
@svDb()
public validUntil: number;
constructor(data: Partial<SmartacmeCert> = {}) {
this.id = data.id || '';
this.domainName = data.domainName || '';
this.created = data.created || Date.now();
this.privateKey = data.privateKey || '';
this.publicKey = data.publicKey || '';
this.csr = data.csr || '';
this.validUntil = data.validUntil || 0;
}
/**
* Check if certificate is still valid.
*/
public isStillValid(): boolean {
return this.validUntil >= Date.now();
}
/**
* Check if certificate needs renewal (e.g., expires in <10 days).
*/
public shouldBeRenewed(): boolean {
const shouldBeValidAtLeastUntil =
Date.now() +
plugins.smarttime.getMilliSecondsFromUnits({
days: 10,
});
return !(this.validUntil >= shouldBeValidAtLeastUntil);
}
public update(certDataArg: plugins.tsclass.network.ICert) {
Object.keys(certDataArg).forEach((key) => {
this[key] = certDataArg[key];
});
}
constructor(optionsArg: plugins.tsclass.network.ICert) {
super();
if (optionsArg) {
Object.keys(optionsArg).forEach((key) => {
this[key] = optionsArg[key];
});
}
const threshold = Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 10 });
return this.validUntil < threshold;
}
}

View File

@@ -1,77 +0,0 @@
import * as plugins from './smartacme.plugins.js';
import { SmartacmeCert } from './smartacme.classes.cert.js';
import { SmartAcme } from './smartacme.classes.smartacme.js';
import * as interfaces from './interfaces/index.js';
export class SmartacmeCertManager {
// =========
// STATIC
// =========
public static activeDB: plugins.smartdata.SmartdataDb;
// =========
// INSTANCE
// =========
private mongoDescriptor: plugins.smartdata.IMongoDescriptor;
public smartdataDb: plugins.smartdata.SmartdataDb;
public interestMap: plugins.lik.InterestMap<string, SmartacmeCert>;
constructor(
smartAcmeArg: SmartAcme,
optionsArg: {
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
},
) {
this.mongoDescriptor = optionsArg.mongoDescriptor;
}
public async init() {
// Smartdata DB
this.smartdataDb = new plugins.smartdata.SmartdataDb(this.mongoDescriptor);
await this.smartdataDb.init();
SmartacmeCertManager.activeDB = this.smartdataDb;
// Pending Map
this.interestMap = new plugins.lik.InterestMap((certName) => certName);
}
/**
* retrieves a certificate
* @returns the Cert class or null
* @param certDomainNameArg the domain Name to retrieve the vcertificate for
*/
public async retrieveCertificate(certDomainNameArg: string): Promise<SmartacmeCert> {
const existingCertificate: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
domainName: certDomainNameArg,
});
if (existingCertificate) {
return existingCertificate;
} else {
return null;
}
}
/**
* stores the certificate
* @param optionsArg
*/
public async storeCertificate(optionsArg: plugins.tsclass.network.ICert) {
const cert = new SmartacmeCert(optionsArg);
await cert.save();
const interest = this.interestMap.findInterest(cert.domainName);
if (interest) {
interest.fullfillInterest(cert);
interest.markLost();
}
}
public async deleteCertificate(certDomainNameArg: string) {
const cert: SmartacmeCert = await SmartacmeCert.getInstance<SmartacmeCert>({
domainName: certDomainNameArg,
});
await cert.delete();
}
}

View File

@@ -1,4 +1,4 @@
import * as plugins from './smartacme.plugins.js';
import * as plugins from './plugins.js';
import * as interfaces from './interfaces/index.js';
/**
@@ -10,10 +10,17 @@ export class SmartacmeCertMatcher {
* for wild card certificates
* @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);
// For domains with up to 3 levels (no level4), return base domain.
if (!originalDomain.level4) {
return `${originalDomain.level2}.${originalDomain.level1}`;
}
// Deeper domains (4+ levels) are not supported.
return undefined;
}
}

View File

@@ -1,16 +1,35 @@
import * as plugins from './smartacme.plugins.js';
import { SmartacmeCert } from './smartacme.classes.cert.js';
import { SmartacmeCertManager } from './smartacme.classes.certmanager.js';
import * as plugins from './plugins.js';
import type { ICertManager } from './interfaces/certmanager.js';
import { SmartacmeCertMatcher } from './smartacme.classes.certmatcher.js';
import { commitinfo } from './00_commitinfo_data.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
*/
export interface ISmartAcmeOptions {
accountPrivateKey?: string;
accountEmail: string;
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
accountPrivateKey?: string;
/**
* Certificate storage manager (e.g., Mongo or in-memory).
*/
certManager: ICertManager;
// Removed legacy setChallenge/removeChallenge in favor of `challengeHandlers`
environment: 'production' | 'integration';
/**
@@ -35,6 +54,21 @@ export interface ISmartAcmeOptions {
* Defaults to ['dns-01'] or first supported type from handlers.
*/
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;
}
/**
@@ -51,25 +85,41 @@ export class SmartAcme {
private options: ISmartAcmeOptions;
// the acme client
private client: plugins.acme.Client;
private client!: plugins.acme.AcmeClient;
private smartdns = new plugins.smartdnsClient.Smartdns({});
public logger: plugins.smartlog.Smartlog;
// the account private key
private privateKey: string;
private privateKey!: string;
// certmanager
private certmanager: SmartacmeCertManager;
private certmatcher: SmartacmeCertMatcher;
// certificate manager for persistence (implements ICertManager)
public certmanager!: ICertManager;
// configured pluggable ACME challenge handlers
public challengeHandlers: plugins.handlers.IChallengeHandler<any>[];
private certmatcher!: SmartacmeCertMatcher;
// retry/backoff configuration (resolved with defaults)
private retryOptions: { retries: number; factor: number; minTimeoutMs: number; maxTimeoutMs: number };
// track pending DNS challenges for graceful shutdown
private pendingChallenges: plugins.tsclass.network.IDnsChallenge[] = [];
// configured pluggable ACME challenge handlers
private challengeHandlers: plugins.handlers.IChallengeHandler<any>[];
// priority order of challenge types
private challengePriority: string[];
// TaskManager for coordinating concurrent certificate requests
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) {
this.options = optionsArg;
@@ -78,10 +128,10 @@ export class SmartAcme {
this.logger.enableConsole();
// initialize retry/backoff options
this.retryOptions = {
retries: optionsArg.retryOptions?.retries ?? 3,
factor: optionsArg.retryOptions?.factor ?? 2,
retries: optionsArg.retryOptions?.retries ?? 10,
factor: optionsArg.retryOptions?.factor ?? 4,
minTimeoutMs: optionsArg.retryOptions?.minTimeoutMs ?? 1000,
maxTimeoutMs: optionsArg.retryOptions?.maxTimeoutMs ?? 30000,
maxTimeoutMs: optionsArg.retryOptions?.maxTimeoutMs ?? 60000,
};
// initialize challenge handlers (must provide at least one)
if (!optionsArg.challengeHandlers || optionsArg.challengeHandlers.length === 0) {
@@ -95,6 +145,60 @@ export class SmartAcme {
optionsArg.challengePriority && optionsArg.challengePriority.length > 0
? optionsArg.challengePriority
: this.challengeHandlers.map((h) => h.getSupportedTypes()[0]);
// ── 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);
}
/**
@@ -105,27 +209,31 @@ export class SmartAcme {
*/
public async start() {
this.privateKey =
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
this.options.accountPrivateKey || plugins.acme.AcmeCrypto.createRsaPrivateKey();
// CertMangaer
this.certmanager = new SmartacmeCertManager(this, {
mongoDescriptor: this.options.mongoDescriptor,
});
// Initialize certificate manager
if (!this.options.certManager) {
throw new Error('You must provide a certManager via options.certManager');
}
this.certmanager = this.options.certManager;
await this.certmanager.init();
// CertMatcher
this.certmatcher = new SmartacmeCertMatcher();
// ACME Client
this.client = new plugins.acme.Client({
this.client = new plugins.acme.AcmeClient({
directoryUrl: (() => {
if (this.options.environment === 'production') {
return plugins.acme.directory.letsencrypt.production;
return plugins.acme.ACME_DIRECTORY_URLS.letsencrypt.production;
} 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 */
@@ -133,15 +241,45 @@ export class SmartAcme {
termsOfServiceAgreed: true,
contact: [`mailto:${this.options.accountEmail}`],
});
// Setup graceful shutdown handlers
process.on('SIGINT', () => this.handleSignal('SIGINT'));
process.on('SIGTERM', () => this.handleSignal('SIGTERM'));
// Start the task manager
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);
}
public async stop() {
await this.certmanager.smartdataDb.close();
/**
* Stops the SmartAcme instance and closes certificate store connections.
*/
public async stop() {
// Remove signal handlers so the process can exit cleanly
if (this.boundSigintHandler) {
process.removeListener('SIGINT', this.boundSigintHandler);
this.boundSigintHandler = null;
}
/** Retry helper with exponential backoff */
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') {
await (this.certmanager as any).close();
}
}
/** Retry helper with exponential backoff and AcmeError awareness */
private async retry<T>(operation: () => Promise<T>, operationName: string = 'operation'): Promise<T> {
let attempt = 0;
let delay = this.retryOptions.minTimeoutMs;
@@ -149,6 +287,19 @@ export class SmartAcme {
try {
return await operation();
} 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++;
if (attempt > this.retryOptions.retries) {
await this.logger.log('error', `Operation ${operationName} failed after ${attempt} attempts`, err);
@@ -202,39 +353,107 @@ export class SmartAcme {
* * if not in the database announce it
* * then get it from letsencrypt
* * store it
* * remove it from the pending map (which it go onto by announcing it)
* * retrieve it from the databse and return it
* * retrieve it from the database and return it
*
* @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);
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);
if (
!retrievedCertificate &&
(await this.certmanager.interestMap.checkInterest(certDomainName))
) {
const existingCertificateInterest = this.certmanager.interestMap.findInterest(certDomainName);
const certificate = existingCertificateInterest.interestFullfilled;
return certificate;
} else if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
return retrievedCertificate;
} else if (retrievedCertificate && retrievedCertificate.shouldBeRenewed()) {
await retrievedCertificate.delete();
// Remove old certificate via certManager
await this.certmanager.deleteCertificate(certDomainName);
}
// lets make sure others get the same interest
const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName);
// Build issuance input and trigger the constrained task
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}` });
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 */
const order = await this.retry(() => this.client.createOrder({
identifiers: [
{ type: 'dns', value: certDomainName },
{ type: 'dns', value: `*.${certDomainName}` },
],
identifiers,
}), 'createOrder');
// ── Step: authorize ───────────────────────────────────────────────────
this.certIssuanceTask.notifyStep('authorize');
/* Get authorizations and select challenges */
const authorizations = await this.retry(() => this.client.getAuthorizations(order), 'getAuthorizations');
@@ -258,76 +477,110 @@ export class SmartAcme {
}
const { type, handler } = selectedHandler;
// build handler input with keyAuthorization
let input: any;
let challengeInput: any;
// retrieve keyAuthorization for challenge
const keyAuth = await this.client.getChallengeKeyAuthorization(selectedChallengeArg);
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') {
// HTTP-01 requires serving token at webPath
input = {
challengeInput = {
type,
token: (selectedChallengeArg as any).token,
keyAuthorization: keyAuth,
webPath: `/.well-known/acme-challenge/${(selectedChallengeArg as any).token}`,
};
} else {
// generic challenge input: include raw challenge properties
input = { type, keyAuthorization: keyAuth, ...selectedChallengeArg };
challengeInput = { type, keyAuthorization: keyAuth, ...selectedChallengeArg };
}
this.pendingChallenges.push(input);
this.pendingChallenges.push(challengeInput);
try {
await this.retry(() => handler.prepare(input), `${type}.prepare`);
if (handler.verify) {
await this.retry(() => handler.verify!(input), `${type}.verify`);
} else {
await this.retry(() => this.client.verifyChallenge(authz, selectedChallengeArg), `${type}.verifyChallenge`);
await this.retry(() => handler.prepare(challengeInput), `${type}.prepare`);
if (type === 'dns-01') {
const dnsInput = challengeInput as { hostName: string; challenge: string };
await this.retry(
() => this.smartdns.checkUntilAvailable(dnsInput.hostName, 'TXT', dnsInput.challenge, 100, 5000),
`${type}.propagation`,
);
this.logger.log('info', 'Cooling down for 1 minute before ACME verification');
await plugins.smartdelay.delayFor(60000);
}
await this.retry(
() => this.client.completeChallenge(selectedChallengeArg),
`${type}.completeChallenge`,
);
try {
await this.retry(
() => this.client.waitForValidStatus(selectedChallengeArg),
`${type}.waitForValidStatus`,
);
} catch (err) {
await this.logger.log(
'warn',
`Challenge ${type} did not reach valid status in time, proceeding to finalize`,
err,
);
}
await this.retry(() => this.client.completeChallenge(selectedChallengeArg), `${type}.completeChallenge`);
await this.retry(() => this.client.waitForValidStatus(selectedChallengeArg), `${type}.waitForValidStatus`);
} finally {
try {
await this.retry(() => handler.cleanup(input), `${type}.cleanup`);
await this.retry(() => handler.cleanup(challengeInput), `${type}.cleanup`);
} catch (err) {
await this.logger.log('error', `Error during ${type}.cleanup`, err);
} finally {
this.pendingChallenges = this.pendingChallenges.filter((c) => c !== input);
this.pendingChallenges = this.pendingChallenges.filter((c) => c !== challengeInput);
}
}
}
/* Finalize order */
const [key, csr] = await plugins.acme.forge.createCsr({
commonName: `*.${certDomainName}`,
altNames: [certDomainName],
// ── Step: finalize ────────────────────────────────────────────────────
this.certIssuanceTask.notifyStep('finalize');
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');
const cert = await this.retry(() => this.client.getCertificate(order), 'getCertificate');
/* Done */
// ── Step: store ───────────────────────────────────────────────────────
this.certIssuanceTask.notifyStep('store');
await this.certmanager.storeCertificate({
// Parse real X509 expiry from the issued PEM certificate
let validUntil: number;
try {
const x509 = new plugins.crypto.X509Certificate(cert.toString());
validUntil = new Date(x509.validTo).getTime();
} catch {
// Fallback to 90-day estimate if PEM parsing fails
validUntil = Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 90 });
}
const certRecord = new SmartacmeCert({
id: plugins.smartunique.shortId(),
domainName: certDomainName,
privateKey: key.toString(),
publicKey: cert.toString(),
csr: csr.toString(),
created: Date.now(),
validUntil:
Date.now() +
plugins.smarttime.getMilliSecondsFromUnits({
days: 90,
}),
validUntil,
});
await this.certmanager.storeCertificate(certRecord);
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
currentDomainInterst.fullfillInterest(newCertificate);
currentDomainInterst.destroy();
return newCertificate;
return newCertificate ?? certRecord;
}
public async getAllCertificates(): Promise<SmartacmeCert[]> {
return SmartacmeCert.getInstances({});
}
}

12
ts_server/index.ts Normal file
View File

@@ -0,0 +1,12 @@
export { AcmeServer } from './server.classes.acmeserver.js';
export { AcmeServerError } from './server.classes.jws.verifier.js';
export { AcmeServerCA } from './server.classes.ca.js';
export type {
IAcmeServerOptions,
IServerAccountStore,
IServerOrderStore,
IServerAccount,
IServerOrder,
IServerAuthorization,
IServerChallenge,
} from './server.interfaces.js';

View File

@@ -0,0 +1,27 @@
import type { IServerAccountStore, IServerAccount } from './server.interfaces.js';
/**
* In-memory account storage for the ACME server.
*/
export class MemoryAccountStore implements IServerAccountStore {
private accounts = new Map<string, IServerAccount>();
private byThumbprint = new Map<string, string>();
private byUrl = new Map<string, string>();
async create(account: IServerAccount): Promise<IServerAccount> {
this.accounts.set(account.id, account);
this.byThumbprint.set(account.thumbprint, account.id);
this.byUrl.set(account.url, account.id);
return account;
}
async getByThumbprint(thumbprint: string): Promise<IServerAccount | null> {
const id = this.byThumbprint.get(thumbprint);
return id ? this.accounts.get(id) || null : null;
}
async getByUrl(url: string): Promise<IServerAccount | null> {
const id = this.byUrl.get(url);
return id ? this.accounts.get(id) || null : null;
}
}

View File

@@ -0,0 +1,128 @@
import * as http from 'node:http';
import type { IAcmeServerOptions } from './server.interfaces.js';
import { NonceManager } from './server.classes.nonce.js';
import { JwsVerifier } from './server.classes.jws.verifier.js';
import { MemoryAccountStore } from './server.classes.account.store.js';
import { MemoryOrderStore } from './server.classes.order.store.js';
import { AcmeServerCA } from './server.classes.ca.js';
import { ChallengeVerifier } from './server.classes.challenge.verifier.js';
import { AcmeRouter } from './server.classes.router.js';
import { createDirectoryHandler } from './server.handlers.directory.js';
import { createNonceHeadHandler, createNonceGetHandler } from './server.handlers.nonce.js';
import { createAccountHandler } from './server.handlers.account.js';
import { createNewOrderHandler, createOrderPollHandler } from './server.handlers.order.js';
import { createAuthzHandler } from './server.handlers.authz.js';
import { createChallengeHandler } from './server.handlers.challenge.js';
import { createFinalizeHandler } from './server.handlers.finalize.js';
import { createCertHandler } from './server.handlers.cert.js';
/**
* ACME Directory Server — a self-contained RFC 8555 Certificate Authority.
*
* Usage:
* ```ts
* const server = new AcmeServer({ port: 14000 });
* await server.start();
* console.log(server.getDirectoryUrl()); // http://localhost:14000/directory
* ```
*/
export class AcmeServer {
private options: Required<Pick<IAcmeServerOptions, 'port' | 'hostname'>> & IAcmeServerOptions;
private httpServer: http.Server | null = null;
private ca: AcmeServerCA;
private baseUrl: string;
constructor(options: IAcmeServerOptions = {}) {
this.options = {
port: options.port ?? 14000,
hostname: options.hostname ?? '0.0.0.0',
...options,
};
this.baseUrl = options.baseUrl ?? `http://localhost:${this.options.port}`;
this.ca = new AcmeServerCA(options.caOptions);
}
async start(): Promise<void> {
// Initialize CA
await this.ca.init();
// Create stores
const accountStore = new MemoryAccountStore();
const orderStore = new MemoryOrderStore();
// Create managers
const nonceManager = new NonceManager();
const jwsVerifier = new JwsVerifier(nonceManager, accountStore);
const challengeVerifier = new ChallengeVerifier(this.options.challengeVerification ?? true);
// Create router and register routes
const router = new AcmeRouter(nonceManager);
// Directory
router.addRoute('GET', '/directory', createDirectoryHandler(this.baseUrl));
// Nonce
router.addRoute('HEAD', '/new-nonce', createNonceHeadHandler());
router.addRoute('GET', '/new-nonce', createNonceGetHandler());
// Account
router.addRoute('POST', '/new-account', createAccountHandler(this.baseUrl, jwsVerifier, accountStore));
// Order
router.addRoute('POST', '/new-order', createNewOrderHandler(this.baseUrl, jwsVerifier, orderStore));
router.addRoute('POST', '/order/:id', createOrderPollHandler(this.baseUrl, jwsVerifier, orderStore));
// Authorization
router.addRoute('POST', '/authz/:id', createAuthzHandler(this.baseUrl, jwsVerifier, orderStore));
// Challenge
router.addRoute('POST', '/challenge/:id', createChallengeHandler(
this.baseUrl,
jwsVerifier,
orderStore,
accountStore,
challengeVerifier,
));
// Finalize
router.addRoute('POST', '/finalize/:id', createFinalizeHandler(this.baseUrl, jwsVerifier, orderStore, this.ca));
// Certificate
router.addRoute('POST', '/cert/:id', createCertHandler(this.baseUrl, jwsVerifier, orderStore));
// Start HTTP server
this.httpServer = http.createServer((req, res) => {
router.handle(req, res).catch((err) => {
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'application/problem+json' });
res.end(JSON.stringify({
type: 'urn:ietf:params:acme:error:serverInternal',
detail: err instanceof Error ? err.message : 'Unknown error',
status: 500,
}));
}
});
});
await new Promise<void>((resolve) => {
this.httpServer!.listen(this.options.port, this.options.hostname, () => resolve());
});
}
async stop(): Promise<void> {
if (this.httpServer) {
await new Promise<void>((resolve, reject) => {
this.httpServer!.close((err) => (err ? reject(err) : resolve()));
});
this.httpServer = null;
}
}
getDirectoryUrl(): string {
return `${this.baseUrl}/directory`;
}
getCaCertPem(): string {
return this.ca.getCaCertPem();
}
}

View File

@@ -0,0 +1,143 @@
import 'reflect-metadata';
import * as crypto from 'node:crypto';
/**
* Certificate Authority for the ACME server.
* Generates a self-signed root CA and signs certificates from CSRs.
* Uses @peculiar/x509 (already a project dependency).
*/
export class AcmeServerCA {
private caKeyPair!: CryptoKeyPair;
private caCert!: InstanceType<typeof import('@peculiar/x509').X509Certificate>;
private caCertPem!: string;
private certValidityDays: number;
constructor(private options: { commonName?: string; validityDays?: number; certValidityDays?: number } = {}) {
this.certValidityDays = options.certValidityDays ?? 90;
}
async init(): Promise<void> {
const x509 = await import('@peculiar/x509');
const { webcrypto } = crypto;
x509.cryptoProvider.set(webcrypto as any);
// Generate RSA key pair for the CA
this.caKeyPair = 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 cn = this.options.commonName ?? 'SmartACME Test CA';
const validityDays = this.options.validityDays ?? 3650;
const notBefore = new Date();
const notAfter = new Date();
notAfter.setDate(notAfter.getDate() + validityDays);
// Create self-signed root CA certificate
this.caCert = await x509.X509CertificateGenerator.createSelfSigned({
serialNumber: this.randomSerialNumber(),
name: `CN=${cn}`,
notBefore,
notAfter,
signingAlgorithm: { name: 'RSASSA-PKCS1-v1_5' },
keys: this.caKeyPair,
extensions: [
new x509.BasicConstraintsExtension(true, undefined, true),
new x509.KeyUsagesExtension(
x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign,
true,
),
await x509.SubjectKeyIdentifierExtension.create(this.caKeyPair.publicKey),
],
});
this.caCertPem = this.caCert.toString('pem');
}
/**
* Sign a CSR and return a PEM certificate chain (end-entity + root CA).
* @param csrDerBase64url - The CSR in base64url-encoded DER format (as sent by ACME clients)
*/
async signCsr(csrDerBase64url: string): Promise<string> {
const x509 = await import('@peculiar/x509');
const { webcrypto } = crypto;
x509.cryptoProvider.set(webcrypto as any);
// Parse the CSR
const csrDer = Buffer.from(csrDerBase64url, 'base64url');
const csr = new x509.Pkcs10CertificateRequest(csrDer);
// Extract Subject Alternative Names from CSR extensions
const sanNames: { type: 'dns'; value: string }[] = [];
const sanExt = csr.extensions?.find(
(ext) => ext.type === '2.5.29.17', // OID for SubjectAlternativeName
);
if (sanExt) {
const san = new x509.SubjectAlternativeNameExtension(sanExt.rawData);
if (san.names) {
const jsonNames = san.names.toJSON();
for (const name of jsonNames) {
if (name.type === 'dns') {
sanNames.push({ type: 'dns', value: name.value });
}
}
}
}
// If no SAN found, use CN from subject
if (sanNames.length === 0) {
const cnMatch = csr.subject.match(/CN=([^,]+)/);
if (cnMatch) {
sanNames.push({ type: 'dns', value: cnMatch[1] });
}
}
const notBefore = new Date();
const notAfter = new Date();
notAfter.setDate(notAfter.getDate() + this.certValidityDays);
// Sign the certificate
const cert = await x509.X509CertificateGenerator.create({
serialNumber: this.randomSerialNumber(),
subject: csr.subject,
issuer: this.caCert.subject,
notBefore,
notAfter,
signingAlgorithm: { name: 'RSASSA-PKCS1-v1_5' },
publicKey: csr.publicKey,
signingKey: this.caKeyPair.privateKey,
extensions: [
new x509.BasicConstraintsExtension(false, undefined, true),
new x509.KeyUsagesExtension(
x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment,
true,
),
new x509.ExtendedKeyUsageExtension(
['1.3.6.1.5.5.7.3.1'], // serverAuth
true,
),
new x509.SubjectAlternativeNameExtension(sanNames),
await x509.AuthorityKeyIdentifierExtension.create(this.caKeyPair.publicKey),
],
});
// Return PEM chain: end-entity cert + root CA cert
const certPem = cert.toString('pem');
return `${certPem}\n${this.caCertPem}`;
}
getCaCertPem(): string {
return this.caCertPem;
}
private randomSerialNumber(): string {
return crypto.randomBytes(16).toString('hex');
}
}

View File

@@ -0,0 +1,61 @@
import * as http from 'node:http';
/**
* Verifies ACME challenges by making HTTP requests or DNS lookups.
*/
export class ChallengeVerifier {
private verificationEnabled: boolean;
constructor(verificationEnabled = true) {
this.verificationEnabled = verificationEnabled;
}
/**
* Verify an HTTP-01 challenge by fetching the token from the domain.
*/
async verifyHttp01(domain: string, token: string, expectedKeyAuth: string): Promise<boolean> {
if (!this.verificationEnabled) {
return true;
}
try {
const url = `http://${domain}/.well-known/acme-challenge/${token}`;
const body = await this.httpGet(url);
return body.trim() === expectedKeyAuth.trim();
} catch {
return false;
}
}
/**
* Verify a DNS-01 challenge by looking up the TXT record.
*/
async verifyDns01(domain: string, expectedHash: string): Promise<boolean> {
if (!this.verificationEnabled) {
return true;
}
try {
const { promises: dns } = await import('node:dns');
const records = await dns.resolveTxt(`_acme-challenge.${domain}`);
const flatRecords = records.map((r) => r.join(''));
return flatRecords.some((r) => r === expectedHash);
} catch {
return false;
}
}
private httpGet(url: string): Promise<string> {
return new Promise((resolve, reject) => {
const req = http.get(url, { timeout: 10000 }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy(new Error('HTTP-01 verification timeout'));
});
});
}
}

View File

@@ -0,0 +1,153 @@
import * as crypto from 'node:crypto';
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
import type { NonceManager } from './server.classes.nonce.js';
import type { IServerAccountStore } from './server.interfaces.js';
export interface IJwsVerifyResult {
jwk: Record<string, string>;
kid: string | null;
thumbprint: string;
payload: any;
}
/**
* Verifies JWS-signed ACME requests.
* This is the inverse of AcmeCrypto.createJws().
*/
export class JwsVerifier {
private nonceManager: NonceManager;
private accountStore: IServerAccountStore;
constructor(nonceManager: NonceManager, accountStore: IServerAccountStore) {
this.nonceManager = nonceManager;
this.accountStore = accountStore;
}
async verify(
body: { protected: string; payload: string; signature: string },
expectedUrl: string,
): Promise<IJwsVerifyResult> {
if (!body || !body.protected || body.signature === undefined) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Invalid JWS structure');
}
// 1. Decode protected header
const headerJson = Buffer.from(body.protected, 'base64url').toString('utf-8');
let header: Record<string, any>;
try {
header = JSON.parse(headerJson);
} catch {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Invalid JWS protected header');
}
// 2. Validate required fields
const { alg, nonce, url, jwk, kid } = header;
if (!alg) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Missing alg in protected header');
}
if (!nonce) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:badNonce', 'Missing nonce in protected header');
}
if (!url) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Missing url in protected header');
}
// 3. Validate URL matches
if (url !== expectedUrl) {
throw new AcmeServerError(
400,
'urn:ietf:params:acme:error:malformed',
`URL mismatch: expected ${expectedUrl}, got ${url}`,
);
}
// 4. Validate and consume nonce
if (!this.nonceManager.consume(nonce)) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:badNonce', 'Invalid or expired nonce');
}
// 5. Must have exactly one of jwk or kid
if (jwk && kid) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'JWS must have jwk or kid, not both');
}
if (!jwk && !kid) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'JWS must have jwk or kid');
}
// 6. Resolve the public key
let resolvedJwk: Record<string, string>;
if (jwk) {
resolvedJwk = jwk;
} else {
// Look up account by kid (account URL)
const account = await this.accountStore.getByUrl(kid);
if (!account) {
throw new AcmeServerError(
400,
'urn:ietf:params:acme:error:accountDoesNotExist',
'Account not found for kid',
);
}
resolvedJwk = account.jwk;
}
// 7. Reconstruct public key and verify signature
const publicKey = crypto.createPublicKey({ key: resolvedJwk, format: 'jwk' });
const signingInput = `${body.protected}.${body.payload}`;
const signatureBuffer = Buffer.from(body.signature, 'base64url');
const supportedAlgs = ['RS256', 'ES256', 'ES384'];
if (!supportedAlgs.includes(alg)) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:badSignatureAlgorithm', `Unsupported algorithm: ${alg}`);
}
let valid: boolean;
if (alg.startsWith('RS')) {
valid = crypto.verify('sha256', Buffer.from(signingInput), publicKey, signatureBuffer);
} else {
valid = crypto.verify('sha256', Buffer.from(signingInput), { key: publicKey, dsaEncoding: 'ieee-p1363' }, signatureBuffer);
}
if (!valid) {
throw new AcmeServerError(403, 'urn:ietf:params:acme:error:unauthorized', 'Invalid JWS signature');
}
// 8. Decode payload
let payload: any;
if (body.payload === '') {
payload = null; // POST-as-GET
} else {
try {
payload = JSON.parse(Buffer.from(body.payload, 'base64url').toString('utf-8'));
} catch {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Invalid JWS payload');
}
}
const thumbprint = AcmeCrypto.getJwkThumbprint(resolvedJwk);
return {
jwk: resolvedJwk,
kid: kid || null,
thumbprint,
payload,
};
}
}
/**
* Simple error class for ACME server errors that maps to RFC 8555 problem responses.
*/
export class AcmeServerError extends Error {
public readonly status: number;
public readonly type: string;
public readonly detail: string;
constructor(status: number, type: string, detail: string) {
super(`${type}: ${detail}`);
this.name = 'AcmeServerError';
this.status = status;
this.type = type;
this.detail = detail;
}
}

View File

@@ -0,0 +1,36 @@
import * as crypto from 'node:crypto';
/**
* Manages ACME replay nonces.
* Each nonce is single-use: consumed on verification, fresh one issued with every response.
*/
export class NonceManager {
private nonces = new Set<string>();
private nonceQueue: string[] = [];
private maxSize: number;
constructor(maxSize = 10000) {
this.maxSize = maxSize;
}
generate(): string {
const nonce = crypto.randomBytes(16).toString('base64url');
if (this.nonces.size >= this.maxSize) {
const oldest = this.nonceQueue.shift();
if (oldest) {
this.nonces.delete(oldest);
}
}
this.nonces.add(nonce);
this.nonceQueue.push(nonce);
return nonce;
}
consume(nonce: string): boolean {
if (this.nonces.has(nonce)) {
this.nonces.delete(nonce);
return true;
}
return false;
}
}

View File

@@ -0,0 +1,72 @@
import type {
IServerOrderStore,
IServerOrder,
IServerAuthorization,
IServerChallenge,
} from './server.interfaces.js';
/**
* In-memory order/authorization/challenge/certificate storage for the ACME server.
*/
export class MemoryOrderStore implements IServerOrderStore {
private orders = new Map<string, IServerOrder>();
private authorizations = new Map<string, IServerAuthorization>();
private challenges = new Map<string, IServerChallenge>();
private certPems = new Map<string, string>();
async createOrder(order: IServerOrder): Promise<IServerOrder> {
this.orders.set(order.id, order);
return order;
}
async getOrder(id: string): Promise<IServerOrder | null> {
return this.orders.get(id) || null;
}
async updateOrder(id: string, updates: Partial<IServerOrder>): Promise<void> {
const order = this.orders.get(id);
if (order) {
Object.assign(order, updates);
}
}
async createAuthorization(authz: IServerAuthorization): Promise<IServerAuthorization> {
this.authorizations.set(authz.id, authz);
return authz;
}
async getAuthorization(id: string): Promise<IServerAuthorization | null> {
return this.authorizations.get(id) || null;
}
async updateAuthorization(id: string, updates: Partial<IServerAuthorization>): Promise<void> {
const authz = this.authorizations.get(id);
if (authz) {
Object.assign(authz, updates);
}
}
async createChallenge(challenge: IServerChallenge): Promise<IServerChallenge> {
this.challenges.set(challenge.id, challenge);
return challenge;
}
async getChallenge(id: string): Promise<IServerChallenge | null> {
return this.challenges.get(id) || null;
}
async updateChallenge(id: string, updates: Partial<IServerChallenge>): Promise<void> {
const challenge = this.challenges.get(id);
if (challenge) {
Object.assign(challenge, updates);
}
}
async storeCertPem(orderId: string, pem: string): Promise<void> {
this.certPems.set(orderId, pem);
}
async getCertPem(orderId: string): Promise<string | null> {
return this.certPems.get(orderId) || null;
}
}

View File

@@ -0,0 +1,116 @@
import type * as http from 'node:http';
import type { TRouteHandler } from './server.interfaces.js';
import type { NonceManager } from './server.classes.nonce.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
interface IRoute {
method: string;
pattern: string;
segments: string[];
handler: TRouteHandler;
}
/**
* Minimal HTTP router for the ACME server.
* Supports parameterized paths like /order/:id.
*/
export class AcmeRouter {
private routes: IRoute[] = [];
private nonceManager: NonceManager;
constructor(nonceManager: NonceManager) {
this.nonceManager = nonceManager;
}
addRoute(method: string, pattern: string, handler: TRouteHandler): void {
this.routes.push({
method: method.toUpperCase(),
pattern,
segments: pattern.split('/').filter(Boolean),
handler,
});
}
async handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const method = (req.method || 'GET').toUpperCase();
const pathSegments = url.pathname.split('/').filter(Boolean);
// Always add a fresh nonce to every response
res.setHeader('Replay-Nonce', this.nonceManager.generate());
res.setHeader('Cache-Control', 'no-store');
// Find matching route
for (const route of this.routes) {
if (route.method !== method) continue;
const params = this.matchPath(route.segments, pathSegments);
if (params === null) continue;
try {
const body = method === 'POST' ? await this.parseBody(req) : undefined;
await route.handler(req, res, params, body);
} catch (err) {
this.sendError(res, err);
}
return;
}
// No route found
this.sendError(res, new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Not found'));
}
private matchPath(
routeSegments: string[],
pathSegments: string[],
): Record<string, string> | null {
if (routeSegments.length !== pathSegments.length) return null;
const params: Record<string, string> = {};
for (let i = 0; i < routeSegments.length; i++) {
if (routeSegments[i].startsWith(':')) {
params[routeSegments[i].slice(1)] = pathSegments[i];
} else if (routeSegments[i] !== pathSegments[i]) {
return null;
}
}
return params;
}
private parseBody(req: http.IncomingMessage): Promise<any> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer) => chunks.push(chunk));
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf-8');
if (!raw) {
resolve(undefined);
return;
}
try {
resolve(JSON.parse(raw));
} catch {
reject(new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Invalid JSON body'));
}
});
req.on('error', reject);
});
}
private sendError(res: http.ServerResponse, err: unknown): void {
if (err instanceof AcmeServerError) {
res.writeHead(err.status, { 'Content-Type': 'application/problem+json' });
res.end(JSON.stringify({
type: err.type,
detail: err.detail,
status: err.status,
}));
} else {
const message = err instanceof Error ? err.message : 'Internal server error';
res.writeHead(500, { 'Content-Type': 'application/problem+json' });
res.end(JSON.stringify({
type: 'urn:ietf:params:acme:error:serverInternal',
detail: message,
status: 500,
}));
}
}
}

View File

@@ -0,0 +1,85 @@
import type * as http from 'node:http';
import * as crypto from 'node:crypto';
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerAccountStore } from './server.interfaces.js';
/**
* POST /new-account — Register or retrieve an ACME account.
* Expects JWS with JWK in protected header (not kid).
*/
export function createAccountHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
accountStore: IServerAccountStore,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
_params: Record<string, string>,
body: any,
): Promise<void> => {
const requestUrl = `${baseUrl}/new-account`;
const verified = await jwsVerifier.verify(body, requestUrl);
// Account creation must use JWK, not kid
if (verified.kid) {
throw new AcmeServerError(
400,
'urn:ietf:params:acme:error:malformed',
'newAccount requests must use JWK, not kid',
);
}
const { payload, jwk, thumbprint } = verified;
// Check if account already exists
const existing = await accountStore.getByThumbprint(thumbprint);
if (existing) {
// If onlyReturnExisting, or just returning the existing account
res.writeHead(200, {
'Content-Type': 'application/json',
'Location': existing.url,
});
res.end(JSON.stringify({
status: existing.status,
contact: existing.contact,
orders: `${baseUrl}/account/${existing.id}/orders`,
}));
return;
}
// onlyReturnExisting = true but no account found
if (payload?.onlyReturnExisting) {
throw new AcmeServerError(
400,
'urn:ietf:params:acme:error:accountDoesNotExist',
'Account does not exist',
);
}
// Create new account
const id = crypto.randomBytes(16).toString('hex');
const accountUrl = `${baseUrl}/account/${id}`;
const account = await accountStore.create({
id,
thumbprint,
url: accountUrl,
jwk,
status: 'valid',
contact: payload?.contact || [],
createdAt: new Date().toISOString(),
});
res.writeHead(201, {
'Content-Type': 'application/json',
'Location': accountUrl,
});
res.end(JSON.stringify({
status: account.status,
contact: account.contact,
orders: `${baseUrl}/account/${id}/orders`,
}));
};
}

View File

@@ -0,0 +1,58 @@
import type * as http from 'node:http';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerOrderStore } from './server.interfaces.js';
/**
* POST /authz/:id — Return authorization with embedded challenges (POST-as-GET).
*/
export function createAuthzHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
params: Record<string, string>,
body: any,
): Promise<void> => {
const authzId = params.id;
const requestUrl = `${baseUrl}/authz/${authzId}`;
await jwsVerifier.verify(body, requestUrl);
const authz = await orderStore.getAuthorization(authzId);
if (!authz) {
throw new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Authorization not found');
}
// Build challenge objects
const challenges: Array<{ type: string; url: string; status: string; token: string; validated?: string }> = [];
for (const challengeId of authz.challengeIds) {
const challenge = await orderStore.getChallenge(challengeId);
if (challenge) {
challenges.push({
type: challenge.type,
url: `${baseUrl}/challenge/${challenge.id}`,
status: challenge.status,
token: challenge.token,
...(challenge.validated ? { validated: challenge.validated } : {}),
});
}
}
const responseBody: Record<string, any> = {
identifier: authz.identifier,
status: authz.status,
expires: authz.expires,
challenges,
};
if (authz.wildcard) {
responseBody.wildcard = true;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(responseBody));
};
}

View File

@@ -0,0 +1,32 @@
import type * as http from 'node:http';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerOrderStore } from './server.interfaces.js';
/**
* POST /cert/:id — Download certificate chain (POST-as-GET).
*/
export function createCertHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
params: Record<string, string>,
body: any,
): Promise<void> => {
const orderId = params.id;
const requestUrl = `${baseUrl}/cert/${orderId}`;
await jwsVerifier.verify(body, requestUrl);
const certPem = await orderStore.getCertPem(orderId);
if (!certPem) {
throw new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Certificate not found');
}
res.writeHead(200, { 'Content-Type': 'application/pem-certificate-chain' });
res.end(certPem);
};
}

View File

@@ -0,0 +1,142 @@
import type * as http from 'node:http';
import * as crypto from 'node:crypto';
import { AcmeCrypto } from '../ts/acme/acme.classes.crypto.js';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerOrderStore, IServerAccountStore } from './server.interfaces.js';
import type { ChallengeVerifier } from './server.classes.challenge.verifier.js';
/**
* POST /challenge/:id — Trigger or poll an ACME challenge.
* - POST with `{}` payload: trigger challenge validation
* - POST-as-GET (null payload): return current challenge state
*/
export function createChallengeHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
accountStore: IServerAccountStore,
challengeVerifier: ChallengeVerifier,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
params: Record<string, string>,
body: any,
): Promise<void> => {
const challengeId = params.id;
const requestUrl = `${baseUrl}/challenge/${challengeId}`;
const verified = await jwsVerifier.verify(body, requestUrl);
const challenge = await orderStore.getChallenge(challengeId);
if (!challenge) {
throw new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Challenge not found');
}
// POST-as-GET: just return current state
if (verified.payload === null) {
sendChallengeResponse(res, challenge, baseUrl);
return;
}
// Trigger validation (payload should be `{}`)
if (challenge.status !== 'pending') {
// Already processing or completed
sendChallengeResponse(res, challenge, baseUrl);
return;
}
// Set to processing
await orderStore.updateChallenge(challengeId, { status: 'processing' });
// Get the authorization to find the domain
const authz = await orderStore.getAuthorization(challenge.authorizationId);
if (!authz) {
throw new AcmeServerError(500, 'urn:ietf:params:acme:error:serverInternal', 'Authorization not found');
}
// Resolve the account's JWK for key authorization computation
const account = await accountStore.getByUrl(verified.kid!);
if (!account) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:accountDoesNotExist', 'Account not found');
}
const thumbprint = AcmeCrypto.getJwkThumbprint(account.jwk);
const keyAuth = `${challenge.token}.${thumbprint}`;
// Verify the challenge
let valid = false;
const domain = authz.identifier.value;
if (challenge.type === 'http-01') {
valid = await challengeVerifier.verifyHttp01(domain, challenge.token, keyAuth);
} else if (challenge.type === 'dns-01') {
const hash = crypto.createHash('sha256').update(keyAuth).digest('base64url');
valid = await challengeVerifier.verifyDns01(domain, hash);
}
if (valid) {
await orderStore.updateChallenge(challengeId, {
status: 'valid',
validated: new Date().toISOString(),
});
challenge.status = 'valid';
challenge.validated = new Date().toISOString();
// Check if all challenges for this authorization's required type are valid
// One valid challenge is enough to validate the authorization
await orderStore.updateAuthorization(authz.id, { status: 'valid' });
// Check if all authorizations for the order are now valid
const order = await orderStore.getOrder(authz.orderId);
if (order && order.status === 'pending') {
let allValid = true;
for (const authzId of order.authorizationIds) {
const a = await orderStore.getAuthorization(authzId);
if (!a || a.status !== 'valid') {
allValid = false;
break;
}
}
if (allValid) {
await orderStore.updateOrder(order.id, { status: 'ready' });
}
}
} else {
await orderStore.updateChallenge(challengeId, {
status: 'invalid',
error: {
type: 'urn:ietf:params:acme:error:incorrectResponse',
detail: `Challenge verification failed for ${domain}`,
},
});
challenge.status = 'invalid';
// Mark authorization as invalid too
await orderStore.updateAuthorization(authz.id, { status: 'invalid' });
}
sendChallengeResponse(res, challenge, baseUrl);
};
}
function sendChallengeResponse(
res: http.ServerResponse,
challenge: { id: string; type: string; status: string; token: string; validated?: string },
baseUrl: string,
): void {
const responseBody: Record<string, any> = {
type: challenge.type,
url: `${baseUrl}/challenge/${challenge.id}`,
status: challenge.status,
token: challenge.token,
};
if (challenge.validated) {
responseBody.validated = challenge.validated;
}
res.writeHead(200, {
'Content-Type': 'application/json',
'Link': `<${baseUrl}/directory>;rel="index"`,
});
res.end(JSON.stringify(responseBody));
}

View File

@@ -0,0 +1,30 @@
import type * as http from 'node:http';
import type { IAcmeDirectory } from '../ts/acme/acme.interfaces.js';
/**
* GET /directory — Returns the ACME directory object with all endpoint URLs.
*/
export function createDirectoryHandler(baseUrl: string) {
return async (
_req: http.IncomingMessage,
res: http.ServerResponse,
_params: Record<string, string>,
_body: any,
): Promise<void> => {
const directory: IAcmeDirectory = {
newNonce: `${baseUrl}/new-nonce`,
newAccount: `${baseUrl}/new-account`,
newOrder: `${baseUrl}/new-order`,
revokeCert: `${baseUrl}/revoke-cert`,
keyChange: `${baseUrl}/key-change`,
meta: {
termsOfService: `${baseUrl}/terms`,
website: `${baseUrl}`,
caaIdentities: [],
externalAccountRequired: false,
},
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(directory));
};
}

View File

@@ -0,0 +1,93 @@
import type * as http from 'node:http';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerOrderStore } from './server.interfaces.js';
import type { AcmeServerCA } from './server.classes.ca.js';
/**
* POST /finalize/:id — Submit CSR and issue certificate.
*/
export function createFinalizeHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
ca: AcmeServerCA,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
params: Record<string, string>,
body: any,
): Promise<void> => {
const orderId = params.id;
const requestUrl = `${baseUrl}/finalize/${orderId}`;
const verified = await jwsVerifier.verify(body, requestUrl);
if (!verified.kid) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Finalize requires kid');
}
const order = await orderStore.getOrder(orderId);
if (!order) {
throw new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Order not found');
}
// Check all authorizations are valid and update order status if needed
if (order.status === 'pending') {
let allValid = true;
for (const authzId of order.authorizationIds) {
const authz = await orderStore.getAuthorization(authzId);
if (!authz || authz.status !== 'valid') {
allValid = false;
break;
}
}
if (allValid) {
await orderStore.updateOrder(orderId, { status: 'ready' });
order.status = 'ready';
}
}
if (order.status !== 'ready') {
throw new AcmeServerError(
403,
'urn:ietf:params:acme:error:orderNotReady',
`Order is in "${order.status}" state, expected "ready"`,
);
}
const { payload } = verified;
if (!payload?.csr) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'Missing CSR in finalize request');
}
// Transition to processing
await orderStore.updateOrder(orderId, { status: 'processing' });
// Sign the certificate
const certPem = await ca.signCsr(payload.csr);
// Store certificate and update order
const certUrl = `${baseUrl}/cert/${orderId}`;
await orderStore.storeCertPem(orderId, certPem);
await orderStore.updateOrder(orderId, {
status: 'valid',
certificate: certUrl,
});
const responseBody = {
status: 'valid',
expires: order.expires,
identifiers: order.identifiers,
authorizations: order.authorizationIds.map((id) => `${baseUrl}/authz/${id}`),
finalize: order.finalize,
certificate: certUrl,
};
res.writeHead(200, {
'Content-Type': 'application/json',
'Location': `${baseUrl}/order/${orderId}`,
});
res.end(JSON.stringify(responseBody));
};
}

View File

@@ -0,0 +1,29 @@
import type * as http from 'node:http';
/**
* HEAD /new-nonce — Returns 200 with Replay-Nonce header (added by router).
* GET /new-nonce — Returns 204 with Replay-Nonce header (added by router).
*/
export function createNonceHeadHandler() {
return async (
_req: http.IncomingMessage,
res: http.ServerResponse,
_params: Record<string, string>,
_body: any,
): Promise<void> => {
res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
res.end();
};
}
export function createNonceGetHandler() {
return async (
_req: http.IncomingMessage,
res: http.ServerResponse,
_params: Record<string, string>,
_body: any,
): Promise<void> => {
res.writeHead(204);
res.end();
};
}

View File

@@ -0,0 +1,177 @@
import type * as http from 'node:http';
import * as crypto from 'node:crypto';
import type { JwsVerifier } from './server.classes.jws.verifier.js';
import { AcmeServerError } from './server.classes.jws.verifier.js';
import type { IServerOrderStore, IServerAccountStore } from './server.interfaces.js';
import type { IAcmeIdentifier } from '../ts/acme/acme.interfaces.js';
/**
* POST /new-order — Create a new ACME order.
*/
export function createNewOrderHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
_params: Record<string, string>,
body: any,
): Promise<void> => {
const requestUrl = `${baseUrl}/new-order`;
const verified = await jwsVerifier.verify(body, requestUrl);
if (!verified.kid) {
throw new AcmeServerError(400, 'urn:ietf:params:acme:error:malformed', 'newOrder requires kid');
}
const { payload } = verified;
const identifiers: IAcmeIdentifier[] = payload?.identifiers;
if (!identifiers || !Array.isArray(identifiers) || identifiers.length === 0) {
throw new AcmeServerError(
400,
'urn:ietf:params:acme:error:malformed',
'Order must include at least one identifier',
);
}
const orderId = crypto.randomBytes(16).toString('hex');
const expires = new Date();
expires.setDate(expires.getDate() + 7);
// Create authorizations and challenges for each identifier
const authorizationIds: string[] = [];
for (const identifier of identifiers) {
const authzId = crypto.randomBytes(16).toString('hex');
const isWildcard = identifier.value.startsWith('*.');
const domain = isWildcard ? identifier.value.slice(2) : identifier.value;
// Create challenges for this authorization
const challengeIds: string[] = [];
// HTTP-01 challenge (not for wildcards)
if (!isWildcard) {
const http01Id = crypto.randomBytes(16).toString('hex');
const http01Token = crypto.randomBytes(32).toString('base64url');
await orderStore.createChallenge({
id: http01Id,
authorizationId: authzId,
type: 'http-01',
token: http01Token,
status: 'pending',
});
challengeIds.push(http01Id);
}
// DNS-01 challenge (always)
const dns01Id = crypto.randomBytes(16).toString('hex');
const dns01Token = crypto.randomBytes(32).toString('base64url');
await orderStore.createChallenge({
id: dns01Id,
authorizationId: authzId,
type: 'dns-01',
token: dns01Token,
status: 'pending',
});
challengeIds.push(dns01Id);
await orderStore.createAuthorization({
id: authzId,
orderId,
identifier: { type: 'dns', value: domain },
status: 'pending',
expires: expires.toISOString(),
challengeIds,
wildcard: isWildcard || undefined,
});
authorizationIds.push(authzId);
}
const order = await orderStore.createOrder({
id: orderId,
accountUrl: verified.kid,
status: 'pending',
identifiers,
authorizationIds,
expires: expires.toISOString(),
finalize: `${baseUrl}/finalize/${orderId}`,
});
const responseBody = {
status: order.status,
expires: order.expires,
identifiers: order.identifiers,
authorizations: order.authorizationIds.map((id) => `${baseUrl}/authz/${id}`),
finalize: order.finalize,
};
res.writeHead(201, {
'Content-Type': 'application/json',
'Location': `${baseUrl}/order/${orderId}`,
});
res.end(JSON.stringify(responseBody));
};
}
/**
* POST /order/:id — Poll order status (POST-as-GET).
*/
export function createOrderPollHandler(
baseUrl: string,
jwsVerifier: JwsVerifier,
orderStore: IServerOrderStore,
) {
return async (
req: http.IncomingMessage,
res: http.ServerResponse,
params: Record<string, string>,
body: any,
): Promise<void> => {
const orderId = params.id;
const requestUrl = `${baseUrl}/order/${orderId}`;
await jwsVerifier.verify(body, requestUrl);
const order = await orderStore.getOrder(orderId);
if (!order) {
throw new AcmeServerError(404, 'urn:ietf:params:acme:error:malformed', 'Order not found');
}
// Check if all authorizations are valid → transition to ready
if (order.status === 'pending') {
let allValid = true;
for (const authzId of order.authorizationIds) {
const authz = await orderStore.getAuthorization(authzId);
if (!authz || authz.status !== 'valid') {
allValid = false;
break;
}
}
if (allValid) {
await orderStore.updateOrder(orderId, { status: 'ready' });
order.status = 'ready';
}
}
const responseBody: Record<string, any> = {
status: order.status,
expires: order.expires,
identifiers: order.identifiers,
authorizations: order.authorizationIds.map((id) => `${baseUrl}/authz/${id}`),
finalize: order.finalize,
};
if (order.certificate) {
responseBody.certificate = order.certificate;
}
res.writeHead(200, {
'Content-Type': 'application/json',
'Location': requestUrl,
});
res.end(JSON.stringify(responseBody));
};
}

View File

@@ -0,0 +1,98 @@
import type { IAcmeIdentifier } from '../ts/acme/acme.interfaces.js';
// ============================================================================
// Server configuration
// ============================================================================
export interface IAcmeServerOptions {
port?: number;
hostname?: string;
baseUrl?: string;
/** When false, challenges auto-approve on trigger (useful for testing) */
challengeVerification?: boolean;
caOptions?: {
commonName?: string;
validityDays?: number;
certValidityDays?: number;
};
}
// ============================================================================
// Pluggable storage interfaces
// ============================================================================
export interface IServerAccountStore {
create(account: IServerAccount): Promise<IServerAccount>;
getByThumbprint(thumbprint: string): Promise<IServerAccount | null>;
getByUrl(url: string): Promise<IServerAccount | null>;
}
export interface IServerOrderStore {
createOrder(order: IServerOrder): Promise<IServerOrder>;
getOrder(id: string): Promise<IServerOrder | null>;
updateOrder(id: string, updates: Partial<IServerOrder>): Promise<void>;
createAuthorization(authz: IServerAuthorization): Promise<IServerAuthorization>;
getAuthorization(id: string): Promise<IServerAuthorization | null>;
updateAuthorization(id: string, updates: Partial<IServerAuthorization>): Promise<void>;
createChallenge(challenge: IServerChallenge): Promise<IServerChallenge>;
getChallenge(id: string): Promise<IServerChallenge | null>;
updateChallenge(id: string, updates: Partial<IServerChallenge>): Promise<void>;
storeCertPem(orderId: string, pem: string): Promise<void>;
getCertPem(orderId: string): Promise<string | null>;
}
// ============================================================================
// Internal server models
// ============================================================================
export interface IServerAccount {
id: string;
thumbprint: string;
url: string;
jwk: Record<string, string>;
status: string;
contact: string[];
createdAt: string;
}
export interface IServerOrder {
id: string;
accountUrl: string;
status: string;
identifiers: IAcmeIdentifier[];
authorizationIds: string[];
expires: string;
finalize: string;
certificate?: string;
}
export interface IServerAuthorization {
id: string;
orderId: string;
identifier: IAcmeIdentifier;
status: string;
expires: string;
challengeIds: string[];
wildcard?: boolean;
}
export interface IServerChallenge {
id: string;
authorizationId: string;
type: string;
token: string;
status: string;
validated?: string;
error?: { type: string; detail: string };
}
// ============================================================================
// Route handler type
// ============================================================================
export type TRouteHandler = (
req: import('node:http').IncomingMessage,
res: import('node:http').ServerResponse,
params: Record<string, string>,
body: any,
) => Promise<void>;

View File

@@ -8,8 +8,7 @@
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
"types": ["node"]
},
"include": [
"ts/**/*.ts"