Compare commits

...

16 Commits

Author SHA1 Message Date
07a3365496 v13.13.0
Some checks failed
Docker (tags) / security (push) Failing after 3s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-13 09:47:19 +00:00
1c4f7dbb11 feat(dns): add domain migration between dcrouter and provider-managed DNS with unified ACME managed-domain handling 2026-04-13 09:47:19 +00:00
1fdff79dd0 v13.12.0
Some checks failed
Docker (tags) / security (push) Failing after 2s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-12 23:46:31 +00:00
59b52d08fa feat(email-domains): support creating email domains on optional subdomains 2026-04-12 23:46:31 +00:00
2cdc392a40 v13.11.0
Some checks failed
Docker (tags) / security (push) Failing after 2s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-12 22:09:20 +00:00
433047bbf1 feat(email-domains): add email domain management with DNS provisioning, validation, and ops dashboard support 2026-04-12 22:09:20 +00:00
0b81c95de2 v13.10.0
Some checks failed
Docker (tags) / security (push) Failing after 3s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-12 20:43:57 +00:00
196e5dfc1b feat(web-ui): standardize settings views for ACME and email security panels 2026-04-12 20:43:57 +00:00
60d095cd78 v13.9.2
Some checks failed
Docker (tags) / security (push) Failing after 2m58s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-12 19:42:07 +00:00
2861511d20 fix(web-ui): improve form field descriptions and align certificate settings with tile components 2026-04-12 19:42:07 +00:00
b582d44502 v13.9.1
Some checks failed
Docker (tags) / security (push) Failing after 3s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-08 15:26:12 +00:00
36a2ebc94e fix(network-ui): enable flashing table updates for network activity, remote ingress, and VPN views 2026-04-08 15:26:12 +00:00
ed52a3188d v13.9.0
Some checks failed
Docker (tags) / security (push) Failing after 2s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-08 14:54:49 +00:00
93cc5c7b06 feat(dns): add built-in dcrouter DNS provider support and rename manual domains to dcrouter-hosted/local 2026-04-08 14:54:49 +00:00
5689e93665 v13.8.0
Some checks failed
Docker (tags) / security (push) Failing after 2s
Docker (tags) / test (push) Has been skipped
Docker (tags) / release (push) Has been skipped
Docker (tags) / metadata (push) Has been skipped
2026-04-08 13:12:20 +00:00
c224028495 feat(acme): add DB-backed ACME configuration management and OpsServer certificate settings UI 2026-04-08 13:12:20 +00:00
52 changed files with 2942 additions and 342 deletions

View File

@@ -1,5 +1,64 @@
# Changelog
## 2026-04-13 - 13.13.0 - feat(dns)
add domain migration between dcrouter and provider-managed DNS with unified ACME managed-domain handling
- adds domain migration support in DnsManager, API handlers, request interfaces, app state, and domains UI
- routes ACME DNS-01 challenges through managed domains using createRecord/deleteRecord for both dcrouter-hosted and provider-managed zones
- enables immediate unregister of deleted dcrouter-hosted DNS records from the embedded DNS server
## 2026-04-12 - 13.12.0 - feat(email-domains)
support creating email domains on optional subdomains
- Add optional subdomain support to email domain creation, persistence, and API interfaces.
- Update the ops UI to collect and submit a subdomain prefix when creating an email domain.
- Bump @design.estate/dees-catalog from ^3.78.0 to ^3.78.2.
## 2026-04-12 - 13.11.0 - feat(email-domains)
add email domain management with DNS provisioning, validation, and ops dashboard support
- Introduce EmailDomainManager with persisted email domain records, DKIM configuration, DNS record generation, provisioning, and validation.
- Add opsserver typed request handlers and shared interfaces for listing, creating, updating, deleting, validating, and provisioning email domains.
- Add ops dashboard email domains view and app state integration for managing domains and inspecting required DNS records.
## 2026-04-12 - 13.10.0 - feat(web-ui)
standardize settings views for ACME and email security panels
- replace custom ACME settings layouts with the reusable dees-settings component for configured and empty states
- update the email security view to present settings through dees-settings and open a modal-based read-only edit dialog
- bump @design.estate/dees-catalog to ^3.78.0 to support the updated UI components
## 2026-04-12 - 13.9.2 - fix(web-ui)
improve form field descriptions and align certificate settings with tile components
- Refines labels and adds descriptive helper text across API token, DNS, domain, route, edge, target profile, and VPN forms for clearer operator input
- Updates the DNS provider form to surface provider and credential guidance through built-in input metadata instead of custom help blocks
- Restyles the certificates ACME settings section to use tile-based layout and improves related form wording and file upload metadata
- Refreshes the Cloudflare DNS provider description and bumps UI-related dependencies
## 2026-04-08 - 13.9.1 - fix(network-ui)
enable flashing table updates for network activity, remote ingress, and VPN views
- adds stable row keys to dees-table instances so existing rows can be diffed correctly
- enables flash highlighting for changed rows and cells across network activity, top IPs, backends, remote ingress edges, and VPN clients
- updates network activity request data on every refresh so live metrics like duration and byte counts visibly refresh
## 2026-04-08 - 13.9.0 - feat(dns)
add built-in dcrouter DNS provider support and rename manual domains to dcrouter-hosted/local
- Expose a synthetic built-in "DcRouter" provider in provider listings and block create, edit, delete, test, and external domain listing operations for it
- Rename domain and record source semantics from "manual" to "dcrouter" and "local" across backend, interfaces, and UI
- Add database migrations to convert existing DomainDoc.source and DnsRecordDoc.source values to the new naming
- Update domain creation flows and provider UI labels to reflect dcrouter-hosted authoritative domains
## 2026-04-08 - 13.8.0 - feat(acme)
add DB-backed ACME configuration management and OpsServer certificate settings UI
- introduces a singleton AcmeConfig manager and document persisted in the database, with first-boot seeding from legacy tls.contactEmail and smartProxyConfig.acme options
- updates SmartProxy startup to read live ACME settings from the database and only enable DNS-01 challenge wiring when ACME is configured and enabled
- adds authenticated OpsServer typed request endpoints and API token scopes for reading and updating ACME configuration
- adds web app state and a certificates view card/modal for viewing and editing ACME settings from the Domains certificate UI
## 2026-04-08 - 13.7.1 - fix(repo)
no changes to commit

View File

@@ -1,7 +1,7 @@
{
"name": "@serve.zone/dcrouter",
"private": false,
"version": "13.7.1",
"version": "13.13.0",
"description": "A multifaceted routing service handling mail and SMS delivery functions.",
"type": "module",
"exports": {
@@ -27,7 +27,7 @@
"@git.zone/tsrun": "^2.0.2",
"@git.zone/tstest": "^3.6.3",
"@git.zone/tswatch": "^3.3.2",
"@types/node": "^25.5.2"
"@types/node": "^25.6.0"
},
"dependencies": {
"@api.global/typedrequest": "^3.3.0",
@@ -35,7 +35,7 @@
"@api.global/typedserver": "^8.4.6",
"@api.global/typedsocket": "^4.1.2",
"@apiclient.xyz/cloudflare": "^7.1.0",
"@design.estate/dees-catalog": "^3.69.1",
"@design.estate/dees-catalog": "^3.78.2",
"@design.estate/dees-element": "^2.2.4",
"@push.rocks/lik": "^6.4.0",
"@push.rocks/projectinfo": "^5.1.0",
@@ -49,7 +49,7 @@
"@push.rocks/smartjwt": "^2.2.1",
"@push.rocks/smartlog": "^3.2.2",
"@push.rocks/smartmetrics": "^3.0.3",
"@push.rocks/smartmigration": "1.1.1",
"@push.rocks/smartmigration": "1.2.0",
"@push.rocks/smartmta": "^5.3.1",
"@push.rocks/smartnetwork": "^4.5.2",
"@push.rocks/smartpath": "^6.0.0",
@@ -67,7 +67,7 @@
"@serve.zone/remoteingress": "^4.15.3",
"@tsclass/tsclass": "^9.5.0",
"@types/qrcode": "^1.5.6",
"lru-cache": "^11.3.2",
"lru-cache": "^11.3.3",
"qrcode": "^1.5.4",
"uuid": "^13.0.0"
},

134
pnpm-lock.yaml generated
View File

@@ -24,8 +24,8 @@ importers:
specifier: ^7.1.0
version: 7.1.0
'@design.estate/dees-catalog':
specifier: ^3.69.1
version: 3.69.1(@tiptap/pm@2.27.2)
specifier: ^3.78.2
version: 3.78.2(@tiptap/pm@2.27.2)
'@design.estate/dees-element':
specifier: ^2.2.4
version: 2.2.4
@@ -66,8 +66,8 @@ importers:
specifier: ^3.0.3
version: 3.0.3
'@push.rocks/smartmigration':
specifier: 1.1.1
version: 1.1.1(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))
specifier: 1.2.0
version: 1.2.0(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))
'@push.rocks/smartmta':
specifier: ^5.3.1
version: 5.3.1
@@ -120,8 +120,8 @@ importers:
specifier: ^1.5.6
version: 1.5.6
lru-cache:
specifier: ^11.3.2
version: 11.3.2
specifier: ^11.3.3
version: 11.3.3
qrcode:
specifier: ^1.5.4
version: 1.5.4
@@ -145,8 +145,8 @@ importers:
specifier: ^3.3.2
version: 3.3.2(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@tiptap/pm@2.27.2)
'@types/node':
specifier: ^25.5.2
version: 25.5.2
specifier: ^25.6.0
version: 25.6.0
packages:
@@ -353,8 +353,8 @@ packages:
'@configvault.io/interfaces@1.0.17':
resolution: {integrity: sha512-bEcCUR2VBDJsTin8HQh8Uw/mlYl2v8A3jMIaQ+MTB9Hrqd6CZL2dL7iJdWyFl/3EIX+LDxWFR+Oq7liIq7w+1Q==}
'@design.estate/dees-catalog@3.69.1':
resolution: {integrity: sha512-OSpHB/hfOrL2mkAfF50TqTKJ2hvPd7Cj1WklAmFckyjloE4fd7DRDeXdI/Bziq9152gExipX5VoofTAOr4rF5w==}
'@design.estate/dees-catalog@3.78.2':
resolution: {integrity: sha512-9MKKCvx+vxoIp6UpqVQklreokdg7ZSSODz4FlKyNFqjfZiDDme6pjwxWoMSA+Tn4bkboYyCBosUrVfc0nxa1HA==}
'@design.estate/dees-comms@1.0.30':
resolution: {integrity: sha512-KchMlklJfKAjQiJiR0xmofXtQ27VgZtBIxcMwPE9d+h3jJRv+lPZxzBQVOM0eyM0uS44S5vJMZ11IeV4uDXSHg==}
@@ -368,6 +368,9 @@ packages:
'@design.estate/dees-wcctools@3.8.0':
resolution: {integrity: sha512-CC14iVKUrguzD9jIrdPBd9fZ4egVJEZMxl5y8iy0l7WLumeoYvGsoXj5INVkRPLRVLqziIdi4Je1hXqHt2NU+g==}
'@design.estate/dees-wcctools@3.9.0':
resolution: {integrity: sha512-0vZBaGBEGIbl8hx+8BezIIea3U5T7iSHHF9VqlJZGf+nOFIW4zBAxcCljH8YzZ1Yayp6BEjxp/pQXjHN2YB3Jg==}
'@emnapi/core@1.9.2':
resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==}
@@ -1231,8 +1234,8 @@ packages:
'@push.rocks/smartmetrics@3.0.3':
resolution: {integrity: sha512-RYY4NOla3kraZYVF9TBHgIz4/hSkqVDVNP7tLwhLK5mGBPBy8I/9NWXX6txZKQw6QihP85YD8mWUuUu2xS4D6Q==}
'@push.rocks/smartmigration@1.1.1':
resolution: {integrity: sha512-K/eLN9cNy+CLOT73rhI93vOy/vGwpV46iJpjRUyPwHsMcQcV6po2idk5+XZQzeuq2x7KpKuUPtZ6gXMtf5Y/ig==}
'@push.rocks/smartmigration@1.2.0':
resolution: {integrity: sha512-H2diE1UbZm4cXjxgxkt2YQW3aUQ3QVVU/e8Ws30hzIep0xIqL1BH6//WawA5ZBQhnAOBssZpVOuWOd3GIeBq+Q==}
peerDependencies:
'@push.rocks/smartbucket': ^4.6.0
'@push.rocks/smartdata': ^7.1.7
@@ -1994,6 +1997,12 @@ packages:
'@types/debug@4.1.13':
resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
'@types/dom-mediacapture-transform@0.1.11':
resolution: {integrity: sha512-Y2p+nGf1bF2XMttBnsVPHUWzRRZzqUoJAKmiP10b5umnO6DDrWI0BrGDJy1pOHoOULVmGSfFNkQrAlC5dcj6nQ==}
'@types/dom-webcodecs@0.1.13':
resolution: {integrity: sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==}
'@types/fs-extra@11.0.4':
resolution: {integrity: sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==}
@@ -2054,8 +2063,8 @@ packages:
'@types/node@22.19.17':
resolution: {integrity: sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==}
'@types/node@25.5.2':
resolution: {integrity: sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg==}
'@types/node@25.6.0':
resolution: {integrity: sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==}
'@types/qrcode@1.5.6':
resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
@@ -2858,8 +2867,8 @@ packages:
humanize-ms@1.2.1:
resolution: {integrity: sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0=}
ibantools@4.5.2:
resolution: {integrity: sha512-is+8TgZcKS/AMv/z9nW1zz0bhjhoyjpA1p0nc3A6GkW/InOdcQiUZpkufADzh/aO/LY/TOD/P3oPWncNRn5QMA==}
ibantools@4.5.4:
resolution: {integrity: sha512-6jX1gh4aH6XH+o0ey+wtkMTzkcvsEta7DakIOZSng9voZYpMw3U+gK1+tZChk3aRcPcloEt0NOzksjaRZiqXbw==}
iconv-lite@0.4.24:
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
@@ -3076,16 +3085,16 @@ packages:
resolution: {integrity: sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
lru-cache@11.3.2:
resolution: {integrity: sha512-wgWa6FWQ3QRRJbIjbsldRJZxdxYngT/dO0I5Ynmlnin8qy7tC6xYzbcJjtN4wHLXtkbVwHzk0C+OejVw1XM+DQ==}
lru-cache@11.3.3:
resolution: {integrity: sha512-JvNw9Y81y33E+BEYPr0U7omo+U9AySnsMsEiXgwT6yqd31VQWTLNQqmT4ou5eqPFUrTfIDFta2wKhB1hyohtAQ==}
engines: {node: 20 || >=22}
lru-cache@7.18.3:
resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==}
engines: {node: '>=12'}
lucide@0.577.0:
resolution: {integrity: sha512-PpC/m5eOItp/WU/GlQPFBXDOhq6HibL73KzYP37OX3LM7VmzWQF8voEj8QRWUFvy9FIKfeDQkWYoyS1D/MdWFA==}
lucide@1.8.0:
resolution: {integrity: sha512-JjV/QnadgFLj1Pyu9IKl0lknrolFEzo04B64QcYLLeRzZl/iEHpdbSrRRKbyXcv45SZNv+WGjIUCT33e7xHO6Q==}
mailparser@3.9.6:
resolution: {integrity: sha512-EJYTDWMrOS1kddK1mTsRkrx2Ngh2nYsg54SRMWVVWGVEGbHH4tod8tqqU9hIRPgGQVboSjFubDn9cboSitbM3Q==}
@@ -3163,6 +3172,9 @@ packages:
mdurl@2.0.0:
resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==}
mediabunny@1.40.1:
resolution: {integrity: sha512-HU/stGzAkdWaJIly6ypbUVgAUvT9kt39DIg0IaErR7/1fwtTmgUYs4i8uEPYcgcjPjbB9gtBmUXOLnXi6J2LDw==}
memory-pager@1.5.0:
resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==}
@@ -4098,8 +4110,8 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
undici-types@7.18.2:
resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}
undici-types@7.19.2:
resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==}
unified@11.0.5:
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
@@ -4315,7 +4327,7 @@ snapshots:
'@api.global/typedrequest-interfaces': 3.0.19
'@api.global/typedsocket': 4.1.2(@push.rocks/smartserve@2.0.3)
'@cloudflare/workers-types': 4.20260405.1
'@design.estate/dees-catalog': 3.69.1(@tiptap/pm@2.27.2)
'@design.estate/dees-catalog': 3.78.2(@tiptap/pm@2.27.2)
'@design.estate/dees-comms': 1.0.30
'@push.rocks/lik': 6.4.0
'@push.rocks/smartdelay': 3.0.5
@@ -4844,11 +4856,11 @@ snapshots:
dependencies:
'@api.global/typedrequest-interfaces': 3.0.19
'@design.estate/dees-catalog@3.69.1(@tiptap/pm@2.27.2)':
'@design.estate/dees-catalog@3.78.2(@tiptap/pm@2.27.2)':
dependencies:
'@design.estate/dees-domtools': 2.5.4
'@design.estate/dees-element': 2.2.4
'@design.estate/dees-wcctools': 3.8.0
'@design.estate/dees-wcctools': 3.9.0
'@fortawesome/fontawesome-svg-core': 7.2.0
'@fortawesome/free-brands-svg-icons': 7.2.0
'@fortawesome/free-regular-svg-icons': 7.2.0
@@ -4866,9 +4878,9 @@ snapshots:
'@tsclass/tsclass': 9.5.0
echarts: 5.6.0
highlight.js: 11.11.1
ibantools: 4.5.2
ibantools: 4.5.4
lightweight-charts: 5.1.0
lucide: 0.577.0
lucide: 1.8.0
monaco-editor: 0.55.1
pdfjs-dist: 4.10.38
xterm: 5.3.0
@@ -4937,6 +4949,19 @@ snapshots:
- supports-color
- vue
'@design.estate/dees-wcctools@3.9.0':
dependencies:
'@design.estate/dees-domtools': 2.5.4
'@design.estate/dees-element': 2.2.4
'@push.rocks/smartdelay': 3.0.5
lit: 3.3.2
mediabunny: 1.40.1
transitivePeerDependencies:
- '@nuxt/kit'
- react
- supports-color
- vue
'@emnapi/core@1.9.2':
dependencies:
'@emnapi/wasi-threads': 1.2.1
@@ -6354,7 +6379,7 @@ snapshots:
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartlog': 3.2.2
'@push.rocks/smartmigration@1.1.1(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))':
'@push.rocks/smartmigration@1.2.0(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))':
dependencies:
'@push.rocks/smartlog': 3.2.2
'@push.rocks/smartversion': 3.1.0
@@ -6404,7 +6429,7 @@ snapshots:
'@push.rocks/smartpath': 6.0.0
'@push.rocks/smartrust': 1.3.2
'@tsclass/tsclass': 9.5.0
lru-cache: 11.3.2
lru-cache: 11.3.3
mailparser: 3.9.6
uuid: 13.0.0
transitivePeerDependencies:
@@ -6900,7 +6925,7 @@ snapshots:
'@serve.zone/catalog@2.12.3(@tiptap/pm@2.27.2)':
dependencies:
'@design.estate/dees-catalog': 3.69.1(@tiptap/pm@2.27.2)
'@design.estate/dees-catalog': 3.78.2(@tiptap/pm@2.27.2)
'@design.estate/dees-domtools': 2.5.4
'@design.estate/dees-element': 2.2.4
'@design.estate/dees-wcctools': 3.8.0
@@ -7442,17 +7467,23 @@ snapshots:
'@types/clean-css@4.2.11':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
source-map: 0.6.1
'@types/debug@4.1.13':
dependencies:
'@types/ms': 2.1.0
'@types/dom-mediacapture-transform@0.1.11':
dependencies:
'@types/dom-webcodecs': 0.1.13
'@types/dom-webcodecs@0.1.13': {}
'@types/fs-extra@11.0.4':
dependencies:
'@types/jsonfile': 6.1.4
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/hast@3.0.4':
dependencies:
@@ -7472,12 +7503,12 @@ snapshots:
'@types/jsonfile@6.1.4':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/jsonwebtoken@9.0.10':
dependencies:
'@types/ms': 2.1.0
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/linkify-it@5.0.0': {}
@@ -7498,16 +7529,16 @@ snapshots:
'@types/mute-stream@0.0.4':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/node-fetch@2.6.13':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
form-data: 4.0.5
'@types/node-forge@1.3.14':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/node@16.9.1': {}
@@ -7519,13 +7550,13 @@ snapshots:
dependencies:
undici-types: 6.21.0
'@types/node@25.5.2':
'@types/node@25.6.0':
dependencies:
undici-types: 7.18.2
undici-types: 7.19.2
'@types/qrcode@1.5.6':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/randomatic@3.1.5': {}
@@ -7535,11 +7566,11 @@ snapshots:
'@types/tar-stream@3.1.4':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/through2@2.0.41':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/trusted-types@2.0.7': {}
@@ -7569,11 +7600,11 @@ snapshots:
'@types/ws@8.18.1':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
'@types/yauzl@2.10.3':
dependencies:
'@types/node': 25.5.2
'@types/node': 25.6.0
optional: true
'@ungap/structured-clone@1.3.0': {}
@@ -8390,7 +8421,7 @@ snapshots:
dependencies:
ms: 2.1.3
ibantools@4.5.2: {}
ibantools@4.5.4: {}
iconv-lite@0.4.24:
dependencies:
@@ -8628,11 +8659,11 @@ snapshots:
lowercase-keys@3.0.0: {}
lru-cache@11.3.2: {}
lru-cache@11.3.3: {}
lru-cache@7.18.3: {}
lucide@0.577.0: {}
lucide@1.8.0: {}
mailparser@3.9.6:
dependencies:
@@ -8804,6 +8835,11 @@ snapshots:
mdurl@2.0.0: {}
mediabunny@1.40.1:
dependencies:
'@types/dom-mediacapture-transform': 0.1.11
'@types/dom-webcodecs': 0.1.13
memory-pager@1.5.0: {}
micromark-core-commonmark@2.0.3:
@@ -9268,7 +9304,7 @@ snapshots:
path-scurry@2.0.2:
dependencies:
lru-cache: 11.3.2
lru-cache: 11.3.3
minipass: 7.1.3
path-to-regexp@8.4.2: {}
@@ -9942,7 +9978,7 @@ snapshots:
undici-types@6.21.0: {}
undici-types@7.18.2: {}
undici-types@7.19.2: {}
unified@11.0.5:
dependencies:

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@serve.zone/dcrouter',
version: '13.7.1',
version: '13.13.0',
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
}

1
ts/acme/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './manager.acme-config.js';

View File

@@ -0,0 +1,182 @@
import { logger } from '../logger.js';
import { AcmeConfigDoc } from '../db/documents/index.js';
import type { IDcRouterOptions } from '../classes.dcrouter.js';
import type { IAcmeConfig } from '../../ts_interfaces/data/acme-config.js';
/**
* AcmeConfigManager — owns the singleton ACME configuration in the DB.
*
* Lifecycle:
* - `start()` — loads from the DB; if empty, seeds from legacy constructor
* fields (`tls.contactEmail`, `smartProxyConfig.acme.*`) on first boot.
* - `getConfig()` — returns the in-memory cached `IAcmeConfig` (or null)
* - `updateConfig(args, updatedBy)` — upserts and refreshes the cache
*
* Reload semantics: updates take effect on the next dcrouter restart because
* `SmartAcme` is instantiated once in `setupSmartProxy()`. `renewThresholdDays`
* applies immediately to the next renewal check. See
* `ts_web/elements/domains/ops-view-certificates.ts` for the UI warning.
*/
export class AcmeConfigManager {
private cached: IAcmeConfig | null = null;
constructor(private options: IDcRouterOptions) {}
public async start(): Promise<void> {
logger.log('info', 'AcmeConfigManager: starting');
let doc = await AcmeConfigDoc.load();
if (!doc) {
// First-boot path: seed from legacy constructor fields if present.
const seed = this.deriveSeedFromOptions();
if (seed) {
doc = await this.createSeedDoc(seed);
logger.log(
'info',
`AcmeConfigManager: seeded from constructor legacy fields (accountEmail=${seed.accountEmail}, useProduction=${seed.useProduction})`,
);
} else {
logger.log(
'info',
'AcmeConfigManager: no AcmeConfig in DB and no legacy constructor fields — ACME disabled until configured via Domains > Certificates > Settings.',
);
}
} else if (this.deriveSeedFromOptions()) {
logger.log(
'warn',
'AcmeConfigManager: ignoring constructor tls.contactEmail / smartProxyConfig.acme — DB already has AcmeConfigDoc. Manage via Domains > Certificates > Settings.',
);
}
this.cached = doc ? this.toPlain(doc) : null;
if (this.cached) {
logger.log(
'info',
`AcmeConfigManager: loaded ACME config (accountEmail=${this.cached.accountEmail}, enabled=${this.cached.enabled}, useProduction=${this.cached.useProduction})`,
);
}
}
public async stop(): Promise<void> {
this.cached = null;
}
/**
* Returns the current ACME config, or null if not configured.
* In-memory — does not hit the DB.
*/
public getConfig(): IAcmeConfig | null {
return this.cached;
}
/**
* True if there is an enabled ACME config. Used by `setupSmartProxy()` to
* decide whether to instantiate SmartAcme.
*/
public hasEnabledConfig(): boolean {
return this.cached !== null && this.cached.enabled;
}
/**
* Upsert the ACME config. All fields are optional; missing fields are
* preserved from the existing row (or defaulted if there is no row yet).
*/
public async updateConfig(
args: Partial<Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'>>,
updatedBy: string,
): Promise<IAcmeConfig> {
let doc = await AcmeConfigDoc.load();
const now = Date.now();
if (!doc) {
doc = new AcmeConfigDoc();
doc.configId = 'acme-config';
doc.accountEmail = args.accountEmail ?? '';
doc.enabled = args.enabled ?? true;
doc.useProduction = args.useProduction ?? true;
doc.autoRenew = args.autoRenew ?? true;
doc.renewThresholdDays = args.renewThresholdDays ?? 30;
} else {
if (args.accountEmail !== undefined) doc.accountEmail = args.accountEmail;
if (args.enabled !== undefined) doc.enabled = args.enabled;
if (args.useProduction !== undefined) doc.useProduction = args.useProduction;
if (args.autoRenew !== undefined) doc.autoRenew = args.autoRenew;
if (args.renewThresholdDays !== undefined) doc.renewThresholdDays = args.renewThresholdDays;
}
doc.updatedAt = now;
doc.updatedBy = updatedBy;
await doc.save();
this.cached = this.toPlain(doc);
return this.cached;
}
// ==========================================================================
// Internal helpers
// ==========================================================================
/**
* Build a seed object from the legacy constructor fields. Returns null
* if the user has not provided any of them.
*
* Supports BOTH `tls.contactEmail` (short form) and `smartProxyConfig.acme`
* (full form). `smartProxyConfig.acme` wins when both are present.
*/
private deriveSeedFromOptions(): Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'> | null {
const acme = this.options.smartProxyConfig?.acme;
const tls = this.options.tls;
// Prefer the explicit smartProxyConfig.acme block if present.
if (acme?.accountEmail) {
return {
accountEmail: acme.accountEmail,
enabled: acme.enabled !== false,
useProduction: acme.useProduction !== false,
autoRenew: acme.autoRenew !== false,
renewThresholdDays: acme.renewThresholdDays ?? 30,
};
}
// Fall back to the short tls.contactEmail form.
if (tls?.contactEmail) {
return {
accountEmail: tls.contactEmail,
enabled: true,
useProduction: true,
autoRenew: true,
renewThresholdDays: 30,
};
}
return null;
}
private async createSeedDoc(
seed: Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'>,
): Promise<AcmeConfigDoc> {
const doc = new AcmeConfigDoc();
doc.configId = 'acme-config';
doc.accountEmail = seed.accountEmail;
doc.enabled = seed.enabled;
doc.useProduction = seed.useProduction;
doc.autoRenew = seed.autoRenew;
doc.renewThresholdDays = seed.renewThresholdDays;
doc.updatedAt = Date.now();
doc.updatedBy = 'seed';
await doc.save();
return doc;
}
private toPlain(doc: AcmeConfigDoc): IAcmeConfig {
return {
accountEmail: doc.accountEmail,
enabled: doc.enabled,
useProduction: doc.useProduction,
autoRenew: doc.autoRenew,
renewThresholdDays: doc.renewThresholdDays,
updatedAt: doc.updatedAt,
updatedBy: doc.updatedBy,
};
}
}

View File

@@ -28,6 +28,8 @@ import { RouteConfigManager, ApiTokenManager, ReferenceResolver, DbSeeder, Targe
import { SecurityLogger, ContentScanner, IPReputationChecker } from './security/index.js';
import { type IHttp3Config, augmentRoutesWithHttp3 } from './http3/index.js';
import { DnsManager } from './dns/manager.dns.js';
import { AcmeConfigManager } from './acme/manager.acme-config.js';
import { EmailDomainManager } from './email/classes.email-domain.manager.js';
export interface IDcRouterOptions {
/** Base directory for all dcrouter data. Defaults to ~/.serve.zone/dcrouter */
@@ -276,6 +278,10 @@ export class DcRouter {
// Domain / DNS management (DB-backed providers, domains, records)
public dnsManager?: DnsManager;
// ACME configuration (DB-backed singleton, replaces tls.contactEmail)
public acmeConfigManager?: AcmeConfigManager;
public emailDomainManager?: EmailDomainManager;
// Auto-discovered public IP (populated by generateAuthoritativeRecords)
public detectedPublicIp: string | null = null;
@@ -412,11 +418,50 @@ export class DcRouter {
);
}
// SmartProxy: critical, depends on DcRouterDb + DnsManager (if enabled)
// AcmeConfigManager: optional, depends on DcRouterDb — owns the singleton
// ACME configuration (accountEmail, useProduction, etc.). Must run before
// SmartProxy so setupSmartProxy() can read the ACME config from the DB.
// On first boot, seeds from legacy `tls.contactEmail` / `smartProxyConfig.acme`.
if (this.options.dbConfig?.enabled !== false) {
this.serviceManager.addService(
new plugins.taskbuffer.Service('AcmeConfigManager')
.optional()
.dependsOn('DcRouterDb')
.withStart(async () => {
this.acmeConfigManager = new AcmeConfigManager(this.options);
await this.acmeConfigManager.start();
})
.withStop(async () => {
if (this.acmeConfigManager) {
await this.acmeConfigManager.stop();
this.acmeConfigManager = undefined;
}
})
.withRetry({ maxRetries: 1, baseDelayMs: 500 }),
);
}
// Email Domain Manager: optional, depends on DcRouterDb
if (this.options.dbConfig?.enabled !== false) {
this.serviceManager.addService(
new plugins.taskbuffer.Service('EmailDomainManager')
.optional()
.dependsOn('DcRouterDb')
.withStart(async () => {
this.emailDomainManager = new EmailDomainManager(this);
})
.withStop(async () => {
this.emailDomainManager = undefined;
}),
);
}
// SmartProxy: critical, depends on DcRouterDb + DnsManager + AcmeConfigManager (if enabled)
const smartProxyDeps: string[] = [];
if (this.options.dbConfig?.enabled !== false) {
smartProxyDeps.push('DcRouterDb');
smartProxyDeps.push('DnsManager');
smartProxyDeps.push('AcmeConfigManager');
}
this.serviceManager.addService(
new plugins.taskbuffer.Service('SmartProxy')
@@ -837,46 +882,64 @@ export class DcRouter {
}
let routes: plugins.smartproxy.IRouteConfig[] = [];
let acmeConfig: plugins.smartproxy.IAcmeOptions | undefined;
// If user provides full SmartProxy config, use it directly
// If user provides full SmartProxy config, use its routes.
// NOTE: `smartProxyConfig.acme` is now seed-only — consumed by
// AcmeConfigManager on first boot. The live ACME config always comes
// from the DB via `this.acmeConfigManager.getConfig()`.
if (this.options.smartProxyConfig) {
routes = this.options.smartProxyConfig.routes || [];
acmeConfig = this.options.smartProxyConfig.acme;
logger.log('info', `Found ${routes.length} routes in config, ACME config present: ${!!acmeConfig}`);
logger.log('info', `Found ${routes.length} routes in config`);
}
// If email config exists, automatically add email routes
if (this.options.emailConfig) {
const emailRoutes = this.generateEmailRoutes(this.options.emailConfig);
logger.log('debug', 'Email routes generated', { routes: JSON.stringify(emailRoutes) });
routes = [...routes, ...emailRoutes]; // Enable email routing through SmartProxy
}
// If DNS is configured, add DNS routes
if (this.options.dnsNsDomains && this.options.dnsNsDomains.length > 0) {
const dnsRoutes = this.generateDnsRoutes();
logger.log('debug', `DNS routes for nameservers ${this.options.dnsNsDomains.join(', ')}`, { routes: JSON.stringify(dnsRoutes) });
routes = [...routes, ...dnsRoutes];
}
// Merge TLS/ACME configuration if provided at root level
if (this.options.tls && !acmeConfig) {
acmeConfig = {
accountEmail: this.options.tls.contactEmail,
enabled: true,
useProduction: true,
autoRenew: true,
renewThresholdDays: 30
};
// Build the ACME options for SmartProxy from the DB-backed AcmeConfigManager.
// If no config exists or it's disabled, SmartProxy's own ACME is turned off
// and dcrouter's SmartAcme / certProvisionFunction are not wired.
const dbAcme = this.acmeConfigManager?.getConfig();
const acmeConfig: plugins.smartproxy.IAcmeOptions | undefined =
dbAcme && dbAcme.enabled
? {
accountEmail: dbAcme.accountEmail,
enabled: true,
useProduction: dbAcme.useProduction,
autoRenew: dbAcme.autoRenew,
renewThresholdDays: dbAcme.renewThresholdDays,
}
: undefined;
if (acmeConfig) {
logger.log(
'info',
`ACME config: accountEmail=${acmeConfig.accountEmail}, useProduction=${acmeConfig.useProduction}, autoRenew=${acmeConfig.autoRenew}`,
);
} else {
logger.log('info', 'ACME config: disabled or not yet configured in DB');
}
// Configure DNS-01 challenge if any DnsProviderDoc exists in the DB.
// The DnsManager dispatches each challenge to the right provider client
// based on the FQDN being certificated.
// Configure DNS-01 challenge if any DnsProviderDoc exists in the DB AND
// ACME is enabled. The DnsManager dispatches each challenge through the
// unified createRecord()/deleteRecord() path — works for both dcrouter-hosted
// zones and provider-managed zones. Only domains under management get certs.
let challengeHandlers: any[] = [];
if (this.dnsManager && (await this.dnsManager.hasAcmeCapableProvider())) {
logger.log('info', 'Configuring DNS-01 challenge for ACME via DnsManager (DB providers)');
if (
acmeConfig &&
this.dnsManager &&
(await this.dnsManager.hasAnyManagedDomain())
) {
logger.log('info', 'Configuring DNS-01 challenge for ACME via DnsManager (managed domains)');
const convenientDnsProvider = this.dnsManager.buildAcmeConvenientDnsProvider();
const dns01Handler = new plugins.smartacme.handlers.Dns01Handler(convenientDnsProvider);
challengeHandlers.push(dns01Handler);
@@ -977,10 +1040,12 @@ export class DcRouter {
logger.log('error', 'Error stopping old SmartAcme', { error: String(err) })
);
}
// Safe non-null: challengeHandlers.length > 0 implies both dnsManager
// and acmeConfig exist (enforced above).
this.smartAcme = new plugins.smartacme.SmartAcme({
accountEmail: acmeConfig?.accountEmail || this.options.tls?.contactEmail || 'admin@example.com',
accountEmail: dbAcme!.accountEmail,
certManager: new StorageBackedCertManager(),
environment: 'production',
environment: dbAcme!.useProduction ? 'production' : 'integration',
challengeHandlers: challengeHandlers,
challengePriority: ['dns-01'],
});
@@ -1745,7 +1810,8 @@ export class DcRouter {
logger.log('info', `Registered ${allRecords.length} DNS records (${authoritativeRecords.length} authoritative, ${emailDnsRecords.length} email, ${dkimRecords.length} DKIM, ${this.options.dnsRecords?.length || 0} user-defined)`);
}
// Hand the DnsServer to DnsManager so DB-backed manual records get registered too.
// Hand the DnsServer to DnsManager so DB-backed local records on
// dcrouter-hosted domains get registered too.
if (this.dnsManager && this.dnsServer) {
await this.dnsManager.attachDnsServer(this.dnsServer);
}

View File

@@ -0,0 +1,49 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
const getDb = () => DcRouterDb.getInstance().getDb();
/**
* Singleton ACME configuration document. One row per dcrouter instance,
* keyed on the fixed `configId = 'acme-config'` following the
* `VpnServerKeysDoc` pattern.
*
* Replaces the legacy `tls.contactEmail` and `smartProxyConfig.acme.*`
* constructor fields. Managed via the OpsServer UI at
* **Domains > Certificates > Settings**.
*/
@plugins.smartdata.Collection(() => getDb())
export class AcmeConfigDoc extends plugins.smartdata.SmartDataDbDoc<AcmeConfigDoc, AcmeConfigDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public configId: string = 'acme-config';
@plugins.smartdata.svDb()
public accountEmail: string = '';
@plugins.smartdata.svDb()
public enabled: boolean = true;
@plugins.smartdata.svDb()
public useProduction: boolean = true;
@plugins.smartdata.svDb()
public autoRenew: boolean = true;
@plugins.smartdata.svDb()
public renewThresholdDays: number = 30;
@plugins.smartdata.svDb()
public updatedAt: number = 0;
@plugins.smartdata.svDb()
public updatedBy: string = '';
constructor() {
super();
}
public static async load(): Promise<AcmeConfigDoc | null> {
return await AcmeConfigDoc.getInstance({ configId: 'acme-config' });
}
}

View File

@@ -0,0 +1,56 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
import type {
IEmailDomainDkim,
IEmailDomainRateLimits,
IEmailDomainDnsStatus,
} from '../../../ts_interfaces/data/email-domain.js';
const getDb = () => DcRouterDb.getInstance().getDb();
@plugins.smartdata.Collection(() => getDb())
export class EmailDomainDoc extends plugins.smartdata.SmartDataDbDoc<EmailDomainDoc, EmailDomainDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public id!: string;
@plugins.smartdata.svDb()
public domain: string = '';
@plugins.smartdata.svDb()
public linkedDomainId: string = '';
@plugins.smartdata.svDb()
public subdomain?: string;
@plugins.smartdata.svDb()
public dkim!: IEmailDomainDkim;
@plugins.smartdata.svDb()
public rateLimits?: IEmailDomainRateLimits;
@plugins.smartdata.svDb()
public dnsStatus!: IEmailDomainDnsStatus;
@plugins.smartdata.svDb()
public createdAt!: string;
@plugins.smartdata.svDb()
public updatedAt!: string;
constructor() {
super();
}
public static async findById(id: string): Promise<EmailDomainDoc | null> {
return await EmailDomainDoc.getInstance({ id });
}
public static async findByDomain(domain: string): Promise<EmailDomainDoc | null> {
return await EmailDomainDoc.getInstance({ domain: domain.toLowerCase() });
}
public static async findAll(): Promise<EmailDomainDoc[]> {
return await EmailDomainDoc.getInstances({});
}
}

View File

@@ -30,3 +30,9 @@ export * from './classes.accounting-session.doc.js';
export * from './classes.dns-provider.doc.js';
export * from './classes.domain.doc.js';
export * from './classes.dns-record.doc.js';
// ACME configuration (singleton)
export * from './classes.acme-config.doc.js';
// Email domain management
export * from './classes.email-domain.doc.js';

View File

@@ -25,9 +25,9 @@ import type {
* Responsibilities:
* - Load Domain/DnsRecord docs from the DB on start
* - First-boot seeding from legacy constructor config (dnsScopes/dnsRecords/dnsNsDomains)
* - Register manual-domain records with smartdns.DnsServer at startup
* - Provide CRUD methods used by OpsServer handlers (manual domains hit smartdns,
* provider domains hit the provider API)
* - Register dcrouter-hosted domain records with smartdns.DnsServer at startup
* - Provide CRUD methods used by OpsServer handlers (dcrouter-hosted domains hit
* smartdns, provider domains hit the provider API)
* - Expose a provider lookup used by the ACME DNS-01 wiring in setupSmartProxy()
*
* Provider-managed domains are NEVER served from the embedded DnsServer — the
@@ -69,12 +69,12 @@ export class DnsManager {
/**
* Wire the embedded DnsServer instance after it has been created by
* DcRouter.setupDnsWithSocketHandler(). After this, manual records loaded
* from the DB are registered with the server.
* DcRouter.setupDnsWithSocketHandler(). After this, local records on
* dcrouter-hosted domains loaded from the DB are registered with the server.
*/
public async attachDnsServer(dnsServer: plugins.smartdns.dnsServerMod.DnsServer): Promise<void> {
this.dnsServer = dnsServer;
await this.applyManualDomainsToDnsServer();
await this.applyDcrouterDomainsToDnsServer();
}
// ==========================================================================
@@ -83,7 +83,8 @@ export class DnsManager {
/**
* If no DomainDocs exist yet but the constructor has legacy DNS fields,
* seed them as `source: 'manual'` records. On subsequent boots (DB has
* seed them as dcrouter-hosted (`domain.source: 'dcrouter'`) zones with
* local (`record.source: 'local'`) records. On subsequent boots (DB has
* entries), constructor config is ignored with a warning.
*/
private async seedFromConstructorConfigIfEmpty(): Promise<void> {
@@ -117,7 +118,7 @@ export class DnsManager {
const domain = new DomainDoc();
domain.id = plugins.uuid.v4();
domain.name = scope.toLowerCase();
domain.source = 'manual';
domain.source = 'dcrouter';
domain.authoritative = true;
domain.createdAt = now;
domain.updatedAt = now;
@@ -144,7 +145,7 @@ export class DnsManager {
record.type = rec.type as TDnsRecordType;
record.value = rec.value;
record.ttl = rec.ttl ?? 300;
record.source = 'manual';
record.source = 'local';
record.createdAt = now;
record.updatedAt = now;
record.createdBy = 'seed';
@@ -174,28 +175,31 @@ export class DnsManager {
}
// ==========================================================================
// Manual-domain DnsServer wiring
// DcRouter-hosted domain DnsServer wiring
// ==========================================================================
/**
* Register all manual-domain records from the DB with the embedded DnsServer.
* Called once after attachDnsServer().
* Register all records from dcrouter-hosted domains in the DB with the
* embedded DnsServer. Called once after attachDnsServer().
*/
private async applyManualDomainsToDnsServer(): Promise<void> {
private async applyDcrouterDomainsToDnsServer(): Promise<void> {
if (!this.dnsServer) {
return;
}
const allDomains = await DomainDoc.findAll();
const manualDomains = allDomains.filter((d) => d.source === 'manual');
const dcrouterDomains = allDomains.filter((d) => d.source === 'dcrouter');
let registered = 0;
for (const domain of manualDomains) {
for (const domain of dcrouterDomains) {
const records = await DnsRecordDoc.findByDomainId(domain.id);
for (const rec of records) {
this.registerRecordWithDnsServer(rec);
registered++;
}
}
logger.log('info', `DnsManager: registered ${registered} manual DNS record(s) from DB`);
logger.log(
'info',
`DnsManager: registered ${registered} dcrouter-hosted DNS record(s) from DB`,
);
}
/**
@@ -292,70 +296,99 @@ export class DnsManager {
}
/**
* True if any cloudflare provider exists in the DB. Used by setupSmartProxy()
* to decide whether to wire SmartAcme with a DNS-01 handler.
* Find the DomainDoc that covers a given FQDN, regardless of source
* (dcrouter-hosted or provider-managed). Uses longest-suffix match.
*/
public async hasAcmeCapableProvider(): Promise<boolean> {
const providers = await DnsProviderDoc.findAll();
return providers.length > 0;
public async findDomainForFqdn(fqdn: string): Promise<DomainDoc | null> {
const lower = fqdn.toLowerCase().replace(/^\*\./, '').replace(/\.$/, '');
const allDomains = await DomainDoc.findAll();
// Sort by name length descending for longest-match-wins
allDomains.sort((a, b) => b.name.length - a.name.length);
for (const domain of allDomains) {
if (lower === domain.name || lower.endsWith(`.${domain.name}`)) {
return domain;
}
}
return null;
}
/**
* Build an IConvenientDnsProvider that dispatches each ACME challenge to
* the right provider client (whichever provider type owns the parent zone),
* based on the challenge's hostName. Provider-agnostic — uses the IDnsProviderClient
* interface, so any registered provider implementation works.
* Returned object plugs directly into smartacme's Dns01Handler.
* Delete all DNS records matching a name and type under a domain.
* Used for ACME challenge cleanup (may have multiple TXT records at the same name).
*/
public async deleteRecordsByNameAndType(
domainId: string,
name: string,
type: TDnsRecordType,
): Promise<void> {
const records = await DnsRecordDoc.findByDomainId(domainId);
for (const rec of records) {
if (rec.name.toLowerCase() === name.toLowerCase() && rec.type === type) {
await this.deleteRecord(rec.id);
}
}
}
/**
* True if any domain is under management (dcrouter-hosted or provider-managed).
* Used by setupSmartProxy() to decide whether to wire SmartAcme with a DNS-01 handler.
*/
public async hasAnyManagedDomain(): Promise<boolean> {
const domains = await DomainDoc.findAll();
return domains.length > 0;
}
/**
* Build an IConvenientDnsProvider that routes ACME DNS-01 challenges through
* the DnsManager abstraction. Challenges are dispatched via createRecord() /
* deleteRecord(), which transparently handle both dcrouter-hosted zones
* (embedded DnsServer) and provider-managed zones (e.g. Cloudflare API).
*
* Only domains under management (with a DomainDoc in DB) are supported —
* this acts as the management gate for certificate issuance.
*/
public buildAcmeConvenientDnsProvider(): plugins.tsclass.network.IConvenientDnsProvider {
const self = this;
const adapter = {
async acmeSetDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
if (!client) {
const domainDoc = await self.findDomainForFqdn(dnsChallenge.hostName);
if (!domainDoc) {
throw new Error(
`DnsManager: no DNS provider configured for ${dnsChallenge.hostName}. ` +
'Add one in the Domains > Providers UI before issuing certificates.',
`DnsManager: no managed domain found for ${dnsChallenge.hostName}. ` +
'Add the domain in Domains before issuing certificates.',
);
}
// Clean any leftover challenge records first to avoid duplicates.
// Clean leftover challenge records first to avoid duplicates.
try {
const existing = await client.listRecords(dnsChallenge.hostName);
for (const r of existing) {
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId).catch(() => {});
}
}
await self.deleteRecordsByNameAndType(domainDoc.id, dnsChallenge.hostName, 'TXT');
} catch (err: unknown) {
logger.log('warn', `DnsManager: failed to clean existing TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
}
await client.createRecord(dnsChallenge.hostName, {
// Create the challenge TXT record via the unified path
await self.createRecord({
domainId: domainDoc.id,
name: dnsChallenge.hostName,
type: 'TXT',
value: dnsChallenge.challenge,
ttl: 120,
createdBy: 'acme-dns01',
});
},
async acmeRemoveDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
if (!client) {
const domainDoc = await self.findDomainForFqdn(dnsChallenge.hostName);
if (!domainDoc) {
// The domain may have been removed; nothing to clean up.
return;
}
try {
const existing = await client.listRecords(dnsChallenge.hostName);
for (const r of existing) {
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId);
}
}
await self.deleteRecordsByNameAndType(domainDoc.id, dnsChallenge.hostName, 'TXT');
} catch (err: unknown) {
logger.log('warn', `DnsManager: failed to remove TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
}
},
async isDomainSupported(domain: string): Promise<boolean> {
const client = await self.getProviderClientForDomain(domain);
return !!client;
const domainDoc = await self.findDomainForFqdn(domain);
return !!domainDoc;
},
};
return { convenience: adapter } as plugins.tsclass.network.IConvenientDnsProvider;
@@ -381,6 +414,12 @@ export class DnsManager {
credentials: TDnsProviderCredentials;
createdBy: string;
}): Promise<string> {
if (args.type === 'dcrouter') {
throw new Error(
'createProvider: cannot create a DnsProviderDoc with type "dcrouter" — ' +
'that type is reserved for the built-in pseudo-provider surfaced at read time.',
);
}
const now = Date.now();
const doc = new DnsProviderDoc();
doc.id = plugins.uuid.v4();
@@ -473,10 +512,10 @@ export class DnsManager {
}
/**
* Create a manual (authoritative) domain. dcrouter will serve DNS records
* for this domain via the embedded smartdns.DnsServer.
* Create a dcrouter-hosted (authoritative) domain. dcrouter will serve
* DNS records for this domain via the embedded smartdns.DnsServer.
*/
public async createManualDomain(args: {
public async createDcrouterDomain(args: {
name: string;
description?: string;
createdBy: string;
@@ -485,7 +524,7 @@ export class DnsManager {
const doc = new DomainDoc();
doc.id = plugins.uuid.v4();
doc.name = args.name.toLowerCase();
doc.source = 'manual';
doc.source = 'dcrouter';
doc.authoritative = true;
doc.description = args.description;
doc.createdAt = now;
@@ -571,10 +610,11 @@ export class DnsManager {
/**
* Delete a domain and all of its DNS records. For provider domains, only
* removes the local mirror — does NOT touch the provider.
* For manual domains, also unregisters records from the embedded DnsServer.
* For dcrouter-hosted domains, also unregisters records from the embedded
* DnsServer.
*
* Note: smartdns has no public unregister-by-name API in the version pinned
* here, so manual record deletes only take effect after a restart. The DB
* here, so local record deletes only take effect after a restart. The DB
* is the source of truth and the next start will not register the deleted
* record.
*/
@@ -631,6 +671,151 @@ export class DnsManager {
return await DnsRecordDoc.findById(id);
}
// ==========================================================================
// Domain migration
// ==========================================================================
/**
* Migrate a domain between dcrouter-hosted and provider-managed.
* Transfers all records to the target and updates domain metadata.
*/
public async migrateDomain(args: {
id: string;
targetSource: 'dcrouter' | 'provider';
targetProviderId?: string;
deleteExistingProviderRecords?: boolean;
}): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
const domain = await DomainDoc.findById(args.id);
if (!domain) return { success: false, message: 'Domain not found' };
if (domain.source === args.targetSource && domain.providerId === args.targetProviderId) {
return { success: false, message: 'Domain is already in the target configuration' };
}
const records = await DnsRecordDoc.findByDomainId(domain.id);
if (args.targetSource === 'provider') {
return this.migrateToDnsProvider(domain, records, args.targetProviderId!, args.deleteExistingProviderRecords ?? false);
} else {
return this.migrateToDcrouter(domain, records);
}
}
/**
* Migrate domain from dcrouter-hosted (or another provider) to an external DNS provider.
*/
private async migrateToDnsProvider(
domain: DomainDoc,
records: DnsRecordDoc[],
targetProviderId: string,
deleteExistingProviderRecords: boolean,
): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
// Validate the target provider exists
const client = await this.getProviderClientById(targetProviderId);
if (!client) {
return { success: false, message: 'Target DNS provider not found' };
}
// Find the zone at the provider
const providerDomains = await client.listDomains();
const zone = providerDomains.find(
(z) => z.name.toLowerCase() === domain.name.toLowerCase(),
);
if (!zone) {
return { success: false, message: `Zone "${domain.name}" not found at the target provider` };
}
// Optionally delete existing records at the provider
if (deleteExistingProviderRecords) {
try {
const existingProviderRecords = await client.listRecords(domain.name);
for (const pr of existingProviderRecords) {
await client.deleteRecord(domain.name, pr.providerRecordId).catch(() => {});
}
logger.log('info', `Deleted ${existingProviderRecords.length} existing records at provider for ${domain.name}`);
} catch (err: unknown) {
logger.log('warn', `Failed to clean existing provider records for ${domain.name}: ${(err as Error).message}`);
}
}
// Push each local record to the provider
let migrated = 0;
for (const rec of records) {
try {
const providerRecord = await client.createRecord(domain.name, {
name: rec.name,
type: rec.type as any,
value: rec.value,
ttl: rec.ttl,
});
// Unregister from embedded DnsServer if it was dcrouter-hosted
if (domain.source === 'dcrouter') {
this.unregisterRecordFromDnsServer(rec);
}
// Update the record doc to synced
rec.source = 'synced' as TDnsRecordSource;
rec.providerRecordId = providerRecord.providerRecordId;
await rec.save();
migrated++;
} catch (err: unknown) {
logger.log('warn', `Failed to migrate record ${rec.name} ${rec.type} to provider: ${(err as Error).message}`);
}
}
// Update domain metadata
domain.source = 'provider';
domain.authoritative = false;
domain.providerId = targetProviderId;
domain.externalZoneId = zone.externalId;
domain.nameservers = zone.nameservers;
domain.lastSyncedAt = Date.now();
domain.updatedAt = Date.now();
await domain.save();
logger.log('info', `Domain ${domain.name} migrated to provider (${migrated} records)`);
return { success: true, recordsMigrated: migrated };
}
/**
* Migrate domain from provider-managed to dcrouter-hosted (authoritative).
*/
private async migrateToDcrouter(
domain: DomainDoc,
records: DnsRecordDoc[],
): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
// Register each record with the embedded DnsServer
let migrated = 0;
for (const rec of records) {
try {
this.registerRecordWithDnsServer(rec);
// Update the record doc to local
rec.source = 'local' as TDnsRecordSource;
rec.providerRecordId = undefined;
await rec.save();
migrated++;
} catch (err: unknown) {
logger.log('warn', `Failed to register record ${rec.name} ${rec.type} with DnsServer: ${(err as Error).message}`);
}
}
// Update domain metadata
domain.source = 'dcrouter';
domain.authoritative = true;
domain.providerId = undefined;
domain.externalZoneId = undefined;
domain.nameservers = undefined;
domain.lastSyncedAt = undefined;
domain.updatedAt = Date.now();
await domain.save();
logger.log('info', `Domain ${domain.name} migrated to dcrouter (${migrated} records)`);
return { success: true, recordsMigrated: migrated };
}
// ==========================================================================
// Record CRUD
// ==========================================================================
public async createRecord(args: {
domainId: string;
name: string;
@@ -652,7 +837,7 @@ export class DnsManager {
doc.value = args.value;
doc.ttl = args.ttl ?? 300;
if (args.proxied !== undefined) doc.proxied = args.proxied;
doc.source = 'manual';
doc.source = 'local';
doc.createdAt = now;
doc.updatedAt = now;
doc.createdBy = args.createdBy;
@@ -678,7 +863,7 @@ export class DnsManager {
return { success: false, message: `Provider rejected record: ${(err as Error).message}` };
}
} else {
// Manual / authoritative — register with embedded DnsServer immediately
// dcrouter-hosted / authoritative — register with embedded DnsServer immediately
this.registerRecordWithDnsServer(doc);
}
@@ -722,7 +907,7 @@ export class DnsManager {
return { success: false, message: `Provider rejected update: ${(err as Error).message}` };
}
} else {
// Re-register the manual record so the new closure picks up the updated fields
// Re-register the local record so the new closure picks up the updated fields
this.registerRecordWithDnsServer(doc);
}
@@ -748,14 +933,24 @@ export class DnsManager {
}
}
}
// For manual records: smartdns has no unregister API in the pinned version,
// so the record stays served until the next restart. The DB delete still
// takes effect — on restart, the record will not be re-registered.
// For dcrouter-hosted records: unregister the handler from the embedded DnsServer
// so the record stops being served immediately (not just after restart).
if (domain.source === 'dcrouter' && this.dnsServer) {
this.unregisterRecordFromDnsServer(doc);
}
await doc.delete();
return { success: true };
}
/**
* Unregister a record's handler from the embedded DnsServer.
*/
public unregisterRecordFromDnsServer(rec: DnsRecordDoc): void {
if (!this.dnsServer) return;
this.dnsServer.unregisterHandler(rec.name, [rec.type]);
}
// ==========================================================================
// Internal helpers
// ==========================================================================
@@ -807,7 +1002,7 @@ export class DnsManager {
public toPublicDomain(doc: DomainDoc): {
id: string;
name: string;
source: 'manual' | 'provider';
source: 'dcrouter' | 'provider';
providerId?: string;
authoritative: boolean;
nameservers?: string[];

View File

@@ -38,6 +38,17 @@ export function createDnsProvider(
}
return new CloudflareDnsProvider(credentials.apiToken);
}
case 'dcrouter': {
// The built-in DcRouter pseudo-provider has no runtime client — dcrouter
// itself serves the records via the embedded smartdns.DnsServer. This
// case exists only to satisfy the exhaustive switch; it should never
// actually run because the handler layer rejects any CRUD that would
// result in a DnsProviderDoc with type: 'dcrouter'.
throw new Error(
`createDnsProvider: 'dcrouter' is a built-in pseudo-provider — no runtime client exists. ` +
`This call indicates a DnsProviderDoc with type: 'dcrouter' was persisted, which should never happen.`,
);
}
default: {
// If you see a TypeScript error here after extending TDnsProviderType,
// add a `case` for the new type above. The `never` enforces exhaustiveness.

View File

@@ -0,0 +1,321 @@
import * as plugins from '../plugins.js';
import { logger } from '../logger.js';
import { EmailDomainDoc } from '../db/documents/classes.email-domain.doc.js';
import { DomainDoc } from '../db/documents/classes.domain.doc.js';
import { DnsRecordDoc } from '../db/documents/classes.dns-record.doc.js';
import type { DnsManager } from '../dns/manager.dns.js';
import type { IEmailDomain, IEmailDnsRecord, TDnsRecordStatus } from '../../ts_interfaces/data/email-domain.js';
/**
* EmailDomainManager — orchestrates email domain setup.
*
* Wires smartmta's DKIMCreator (key generation) with dcrouter's DnsManager
* (record creation for dcrouter-hosted and provider-managed zones) to provide
* a single entry point for setting up an email domain from A to Z.
*/
export class EmailDomainManager {
private dcRouter: any; // DcRouter — avoids circular import
constructor(dcRouterRef: any) {
this.dcRouter = dcRouterRef;
}
private get dnsManager(): DnsManager | undefined {
return this.dcRouter.dnsManager;
}
private get dkimCreator(): any | undefined {
return this.dcRouter.emailServer?.dkimCreator;
}
private get emailHostname(): string {
return this.dcRouter.options?.emailConfig?.hostname || this.dcRouter.options?.tls?.domain || 'localhost';
}
// ---------------------------------------------------------------------------
// CRUD
// ---------------------------------------------------------------------------
public async getAll(): Promise<IEmailDomain[]> {
const docs = await EmailDomainDoc.findAll();
return docs.map((d) => this.docToInterface(d));
}
public async getById(id: string): Promise<IEmailDomain | null> {
const doc = await EmailDomainDoc.findById(id);
return doc ? this.docToInterface(doc) : null;
}
public async createEmailDomain(opts: {
linkedDomainId: string;
subdomain?: string;
dkimSelector?: string;
dkimKeySize?: number;
rotateKeys?: boolean;
rotationIntervalDays?: number;
}): Promise<IEmailDomain> {
// Resolve the linked DNS domain
const domainDoc = await DomainDoc.findById(opts.linkedDomainId);
if (!domainDoc) {
throw new Error(`DNS domain not found: ${opts.linkedDomainId}`);
}
const baseDomain = domainDoc.name;
const subdomain = opts.subdomain?.trim() || undefined;
const domainName = subdomain ? `${subdomain}.${baseDomain}` : baseDomain;
// Check for duplicates
const existing = await EmailDomainDoc.findByDomain(domainName);
if (existing) {
throw new Error(`Email domain already exists for ${domainName}`);
}
const selector = opts.dkimSelector || 'default';
const keySize = opts.dkimKeySize || 2048;
const now = new Date().toISOString();
// Generate DKIM keys
let publicKey: string | undefined;
if (this.dkimCreator) {
try {
await this.dkimCreator.handleDKIMKeysForDomain(domainName);
const dnsRecord = await this.dkimCreator.getDNSRecordForSelector(domainName, selector);
// Extract public key from the DNS record value
const match = dnsRecord?.value?.match(/p=([A-Za-z0-9+/=]+)/);
publicKey = match ? match[1] : undefined;
logger.log('info', `DKIM keys generated for ${domainName} (selector: ${selector})`);
} catch (err: unknown) {
logger.log('warn', `DKIM key generation failed for ${domainName}: ${(err as Error).message}`);
}
}
// Create the document
const doc = new EmailDomainDoc();
doc.id = plugins.smartunique.shortId();
doc.domain = domainName.toLowerCase();
doc.linkedDomainId = opts.linkedDomainId;
doc.subdomain = subdomain;
doc.dkim = {
selector,
keySize,
publicKey,
rotateKeys: opts.rotateKeys ?? false,
rotationIntervalDays: opts.rotationIntervalDays ?? 90,
};
doc.dnsStatus = {
mx: 'unchecked',
spf: 'unchecked',
dkim: 'unchecked',
dmarc: 'unchecked',
};
doc.createdAt = now;
doc.updatedAt = now;
await doc.save();
logger.log('info', `Email domain created: ${domainName}`);
return this.docToInterface(doc);
}
public async updateEmailDomain(
id: string,
changes: {
rotateKeys?: boolean;
rotationIntervalDays?: number;
rateLimits?: IEmailDomain['rateLimits'];
},
): Promise<void> {
const doc = await EmailDomainDoc.findById(id);
if (!doc) throw new Error(`Email domain not found: ${id}`);
if (changes.rotateKeys !== undefined) doc.dkim.rotateKeys = changes.rotateKeys;
if (changes.rotationIntervalDays !== undefined) doc.dkim.rotationIntervalDays = changes.rotationIntervalDays;
if (changes.rateLimits !== undefined) doc.rateLimits = changes.rateLimits;
doc.updatedAt = new Date().toISOString();
await doc.save();
}
public async deleteEmailDomain(id: string): Promise<void> {
const doc = await EmailDomainDoc.findById(id);
if (!doc) throw new Error(`Email domain not found: ${id}`);
await doc.delete();
logger.log('info', `Email domain deleted: ${doc.domain}`);
}
// ---------------------------------------------------------------------------
// DNS record computation
// ---------------------------------------------------------------------------
/**
* Compute the 4 required DNS records for an email domain.
*/
public async getRequiredDnsRecords(id: string): Promise<IEmailDnsRecord[]> {
const doc = await EmailDomainDoc.findById(id);
if (!doc) throw new Error(`Email domain not found: ${id}`);
const domain = doc.domain;
const selector = doc.dkim.selector;
const publicKey = doc.dkim.publicKey || '';
const hostname = this.emailHostname;
const records: IEmailDnsRecord[] = [
{
type: 'MX',
name: domain,
value: `10 ${hostname}`,
status: doc.dnsStatus.mx,
},
{
type: 'TXT',
name: domain,
value: 'v=spf1 a mx ~all',
status: doc.dnsStatus.spf,
},
{
type: 'TXT',
name: `${selector}._domainkey.${domain}`,
value: `v=DKIM1; h=sha256; k=rsa; p=${publicKey}`,
status: doc.dnsStatus.dkim,
},
{
type: 'TXT',
name: `_dmarc.${domain}`,
value: `v=DMARC1; p=none; rua=mailto:dmarc@${domain}`,
status: doc.dnsStatus.dmarc,
},
];
return records;
}
// ---------------------------------------------------------------------------
// DNS provisioning
// ---------------------------------------------------------------------------
/**
* Auto-create missing DNS records via the linked domain's DNS path.
*/
public async provisionDnsRecords(id: string): Promise<number> {
const doc = await EmailDomainDoc.findById(id);
if (!doc) throw new Error(`Email domain not found: ${id}`);
if (!this.dnsManager) throw new Error('DnsManager not available');
const requiredRecords = await this.getRequiredDnsRecords(id);
const domainId = doc.linkedDomainId;
// Get existing DNS records for the linked domain
const existingRecords = await DnsRecordDoc.findByDomainId(domainId);
let provisioned = 0;
for (const required of requiredRecords) {
// Check if a matching record already exists
const exists = existingRecords.some((r) => {
if (required.type === 'MX') {
return r.type === 'MX' && r.name.toLowerCase() === required.name.toLowerCase();
}
// For TXT records, match by name AND check value prefix (v=spf1, v=DKIM1, v=DMARC1)
if (r.type !== 'TXT' || r.name.toLowerCase() !== required.name.toLowerCase()) return false;
if (required.value.startsWith('v=spf1')) return r.value.includes('v=spf1');
if (required.value.startsWith('v=DKIM1')) return r.value.includes('v=DKIM1');
if (required.value.startsWith('v=DMARC1')) return r.value.includes('v=DMARC1');
return false;
});
if (!exists) {
try {
await this.dnsManager.createRecord({
domainId,
name: required.name,
type: required.type as any,
value: required.value,
ttl: 3600,
createdBy: 'email-domain-manager',
});
provisioned++;
logger.log('info', `Provisioned ${required.type} record for ${required.name}`);
} catch (err: unknown) {
logger.log('warn', `Failed to provision ${required.type} for ${required.name}: ${(err as Error).message}`);
}
}
}
// Re-validate after provisioning
await this.validateDns(id);
return provisioned;
}
// ---------------------------------------------------------------------------
// DNS validation
// ---------------------------------------------------------------------------
/**
* Validate DNS records via live lookups.
*/
public async validateDns(id: string): Promise<IEmailDnsRecord[]> {
const doc = await EmailDomainDoc.findById(id);
if (!doc) throw new Error(`Email domain not found: ${id}`);
const domain = doc.domain;
const selector = doc.dkim.selector;
const resolver = new plugins.dns.promises.Resolver();
// MX check
doc.dnsStatus.mx = await this.checkMx(resolver, domain);
// SPF check
doc.dnsStatus.spf = await this.checkTxtRecord(resolver, domain, 'v=spf1');
// DKIM check
doc.dnsStatus.dkim = await this.checkTxtRecord(resolver, `${selector}._domainkey.${domain}`, 'v=DKIM1');
// DMARC check
doc.dnsStatus.dmarc = await this.checkTxtRecord(resolver, `_dmarc.${domain}`, 'v=DMARC1');
doc.dnsStatus.lastCheckedAt = new Date().toISOString();
doc.updatedAt = new Date().toISOString();
await doc.save();
return this.getRequiredDnsRecords(id);
}
private async checkMx(resolver: plugins.dns.promises.Resolver, domain: string): Promise<TDnsRecordStatus> {
try {
const records = await resolver.resolveMx(domain);
return records && records.length > 0 ? 'valid' : 'missing';
} catch {
return 'missing';
}
}
private async checkTxtRecord(
resolver: plugins.dns.promises.Resolver,
name: string,
prefix: string,
): Promise<TDnsRecordStatus> {
try {
const records = await resolver.resolveTxt(name);
const flat = records.map((r) => r.join(''));
const found = flat.some((r) => r.startsWith(prefix));
return found ? 'valid' : 'missing';
} catch {
return 'missing';
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
private docToInterface(doc: EmailDomainDoc): IEmailDomain {
return {
id: doc.id,
domain: doc.domain,
linkedDomainId: doc.linkedDomainId,
subdomain: doc.subdomain,
dkim: doc.dkim,
rateLimits: doc.rateLimits,
dnsStatus: doc.dnsStatus,
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
};
}
}

1
ts/email/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './classes.email-domain.manager.js';

View File

@@ -36,6 +36,8 @@ export class OpsServer {
private dnsProviderHandler!: handlers.DnsProviderHandler;
private domainHandler!: handlers.DomainHandler;
private dnsRecordHandler!: handlers.DnsRecordHandler;
private acmeConfigHandler!: handlers.AcmeConfigHandler;
private emailDomainHandler!: handlers.EmailDomainHandler;
constructor(dcRouterRefArg: DcRouter) {
this.dcRouterRef = dcRouterRefArg;
@@ -102,6 +104,8 @@ export class OpsServer {
this.dnsProviderHandler = new handlers.DnsProviderHandler(this);
this.domainHandler = new handlers.DomainHandler(this);
this.dnsRecordHandler = new handlers.DnsRecordHandler(this);
this.acmeConfigHandler = new handlers.AcmeConfigHandler(this);
this.emailDomainHandler = new handlers.EmailDomainHandler(this);
console.log('✅ OpsServer TypedRequest handlers initialized');
}

View File

@@ -0,0 +1,94 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
/**
* CRUD handler for the singleton `AcmeConfigDoc`.
*
* Auth: same dual-mode pattern as other handlers — admin JWT or API token
* with `acme-config:read` / `acme-config:write` scope.
*/
export class AcmeConfigHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
constructor(private opsServerRef: OpsServer) {
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
this.registerHandlers();
}
private async requireAuth(
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
requiredScope?: interfaces.data.TApiTokenScope,
): Promise<string> {
if (request.identity?.jwt) {
try {
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
identity: request.identity,
});
if (isAdmin) return request.identity.userId;
} catch { /* fall through */ }
}
if (request.apiToken) {
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (tokenManager) {
const token = await tokenManager.validateToken(request.apiToken);
if (token) {
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
return token.createdBy;
}
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
}
}
}
throw new plugins.typedrequest.TypedResponseError('unauthorized');
}
private registerHandlers(): void {
// Get current ACME config
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAcmeConfig>(
'getAcmeConfig',
async (dataArg) => {
await this.requireAuth(dataArg, 'acme-config:read');
const mgr = this.opsServerRef.dcRouterRef.acmeConfigManager;
if (!mgr) return { config: null };
return { config: mgr.getConfig() };
},
),
);
// Update (upsert) the ACME config
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateAcmeConfig>(
'updateAcmeConfig',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'acme-config:write');
const mgr = this.opsServerRef.dcRouterRef.acmeConfigManager;
if (!mgr) {
return {
success: false,
message: 'AcmeConfigManager not initialized (DB disabled?)',
};
}
try {
const updated = await mgr.updateConfig(
{
accountEmail: dataArg.accountEmail,
enabled: dataArg.enabled,
useProduction: dataArg.useProduction,
autoRenew: dataArg.autoRenew,
renewThresholdDays: dataArg.renewThresholdDays,
},
userId,
);
return { success: true, config: updated };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
}
}

View File

@@ -127,7 +127,7 @@ export class ConfigHandler {
// (replaces the legacy `dnsChallenge.cloudflareApiKey` constructor field).
let dnsChallengeEnabled = false;
try {
dnsChallengeEnabled = (await dcRouter.dnsManager?.hasAcmeCapableProvider()) ?? false;
dnsChallengeEnabled = (await dcRouter.dnsManager?.hasAnyManagedDomain()) ?? false;
} catch {
dnsChallengeEnabled = false;
}

View File

@@ -46,15 +46,28 @@ export class DnsProviderHandler {
}
private registerHandlers(): void {
// Get all providers
// Get all providers — prepends the built-in DcRouter pseudo-provider
// so operators see a uniform "who serves this?" list that includes the
// authoritative dcrouter alongside external accounts.
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsProviders>(
'getDnsProviders',
async (dataArg) => {
await this.requireAuth(dataArg, 'dns-providers:read');
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { providers: [] };
return { providers: await dnsManager.listProviders() };
const synthetic: interfaces.data.IDnsProviderPublic = {
id: interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID,
name: 'DcRouter',
type: 'dcrouter',
status: 'ok',
createdAt: 0,
updatedAt: 0,
createdBy: 'system',
hasCredentials: false,
builtIn: true,
};
const real = dnsManager ? await dnsManager.listProviders() : [];
return { providers: [synthetic, ...real] };
},
),
);
@@ -78,6 +91,12 @@ export class DnsProviderHandler {
'createDnsProvider',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'dns-providers:write');
if (dataArg.type === 'dcrouter') {
return {
success: false,
message: 'cannot create built-in provider',
};
}
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) {
return { success: false, message: 'DnsManager not initialized (DB disabled?)' };
@@ -99,6 +118,9 @@ export class DnsProviderHandler {
'updateDnsProvider',
async (dataArg) => {
await this.requireAuth(dataArg, 'dns-providers:write');
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
return { success: false, message: 'cannot edit built-in provider' };
}
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
const ok = await dnsManager.updateProvider(dataArg.id, {
@@ -116,6 +138,9 @@ export class DnsProviderHandler {
'deleteDnsProvider',
async (dataArg) => {
await this.requireAuth(dataArg, 'dns-providers:write');
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
return { success: false, message: 'cannot delete built-in provider' };
}
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
return await dnsManager.deleteProvider(dataArg.id, dataArg.force ?? false);
@@ -129,6 +154,13 @@ export class DnsProviderHandler {
'testDnsProvider',
async (dataArg) => {
await this.requireAuth(dataArg, 'dns-providers:read');
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
return {
ok: false,
error: 'built-in provider has no external connection to test',
testedAt: Date.now(),
};
}
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) {
return { ok: false, error: 'DnsManager not initialized', testedAt: Date.now() };
@@ -144,6 +176,12 @@ export class DnsProviderHandler {
'listProviderDomains',
async (dataArg) => {
await this.requireAuth(dataArg, 'dns-providers:read');
if (dataArg.providerId === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
return {
success: false,
message: 'built-in provider has no external domain listing — use "Add DcRouter Domain" instead',
};
}
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
try {

View File

@@ -71,7 +71,7 @@ export class DomainHandler {
),
);
// Create manual domain
// Create dcrouter-hosted domain
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateDomain>(
'createDomain',
@@ -80,7 +80,7 @@ export class DomainHandler {
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
try {
const id = await dnsManager.createManualDomain({
const id = await dnsManager.createDcrouterDomain({
name: dataArg.name,
description: dataArg.description,
createdBy: userId,
@@ -157,5 +157,23 @@ export class DomainHandler {
},
),
);
// Migrate domain between dcrouter-hosted and provider-managed
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_MigrateDomain>(
'migrateDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'domains:write');
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
return await dnsManager.migrateDomain({
id: dataArg.id,
targetSource: dataArg.targetSource,
targetProviderId: dataArg.targetProviderId,
deleteExistingProviderRecords: dataArg.deleteExistingProviderRecords,
});
},
),
);
}
}

View File

@@ -0,0 +1,195 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
/**
* CRUD + DNS provisioning handler for email domains.
*
* Auth: admin JWT or API token with `email-domains:read` / `email-domains:write` scope.
*/
export class EmailDomainHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
constructor(private opsServerRef: OpsServer) {
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
this.registerHandlers();
}
private async requireAuth(
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
requiredScope?: interfaces.data.TApiTokenScope,
): Promise<string> {
if (request.identity?.jwt) {
try {
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
identity: request.identity,
});
if (isAdmin) return request.identity.userId;
} catch { /* fall through */ }
}
if (request.apiToken) {
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (tokenManager) {
const token = await tokenManager.validateToken(request.apiToken);
if (token) {
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
return token.createdBy;
}
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
}
}
}
throw new plugins.typedrequest.TypedResponseError('unauthorized');
}
private get manager() {
return this.opsServerRef.dcRouterRef.emailDomainManager;
}
private registerHandlers(): void {
// List all email domains
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetEmailDomains>(
'getEmailDomains',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:read' as any);
if (!this.manager) return { domains: [] };
return { domains: await this.manager.getAll() };
},
),
);
// Get single email domain
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetEmailDomain>(
'getEmailDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:read' as any);
if (!this.manager) return { domain: null };
return { domain: await this.manager.getById(dataArg.id) };
},
),
);
// Create email domain
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateEmailDomain>(
'createEmailDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:write' as any);
if (!this.manager) {
return { success: false, message: 'EmailDomainManager not initialized' };
}
try {
const domain = await this.manager.createEmailDomain({
linkedDomainId: dataArg.linkedDomainId,
subdomain: dataArg.subdomain,
dkimSelector: dataArg.dkimSelector,
dkimKeySize: dataArg.dkimKeySize,
rotateKeys: dataArg.rotateKeys,
rotationIntervalDays: dataArg.rotationIntervalDays,
});
return { success: true, domain };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
// Update email domain
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateEmailDomain>(
'updateEmailDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:write' as any);
if (!this.manager) {
return { success: false, message: 'EmailDomainManager not initialized' };
}
try {
await this.manager.updateEmailDomain(dataArg.id, {
rotateKeys: dataArg.rotateKeys,
rotationIntervalDays: dataArg.rotationIntervalDays,
rateLimits: dataArg.rateLimits,
});
return { success: true };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
// Delete email domain
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteEmailDomain>(
'deleteEmailDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:write' as any);
if (!this.manager) {
return { success: false, message: 'EmailDomainManager not initialized' };
}
try {
await this.manager.deleteEmailDomain(dataArg.id);
return { success: true };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
// Validate DNS records
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ValidateEmailDomain>(
'validateEmailDomain',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:read' as any);
if (!this.manager) {
return { success: false, message: 'EmailDomainManager not initialized' };
}
try {
const records = await this.manager.validateDns(dataArg.id);
const domain = await this.manager.getById(dataArg.id);
return { success: true, domain: domain ?? undefined, records };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
// Get required DNS records
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetEmailDomainDnsRecords>(
'getEmailDomainDnsRecords',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:read' as any);
if (!this.manager) return { records: [] };
return { records: await this.manager.getRequiredDnsRecords(dataArg.id) };
},
),
);
// Auto-provision DNS records
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ProvisionEmailDomainDns>(
'provisionEmailDomainDns',
async (dataArg) => {
await this.requireAuth(dataArg, 'email-domains:write' as any);
if (!this.manager) {
return { success: false, message: 'EmailDomainManager not initialized' };
}
try {
const provisioned = await this.manager.provisionDnsRecords(dataArg.id);
return { success: true, provisioned };
} catch (err: unknown) {
return { success: false, message: (err as Error).message };
}
},
),
);
}
}

View File

@@ -16,4 +16,6 @@ export * from './network-target.handler.js';
export * from './users.handler.js';
export * from './dns-provider.handler.js';
export * from './domain.handler.js';
export * from './dns-record.handler.js';
export * from './dns-record.handler.js';
export * from './acme-config.handler.js';
export * from './email-domain.handler.js';

View File

@@ -0,0 +1,25 @@
/**
* ACME configuration for automated TLS certificate issuance via Let's Encrypt.
*
* Persisted as a singleton `AcmeConfigDoc` in the DcRouterDb. Replaces the
* legacy constructor fields `tls.contactEmail` / `smartProxyConfig.acme.*`
* which are now seed-only (used once on first boot if the DB is empty).
*
* Managed via the OpsServer UI at **Domains > Certificates > Settings**.
*/
export interface IAcmeConfig {
/** Contact email used for Let's Encrypt account registration. */
accountEmail: string;
/** Whether ACME is enabled. If false, no certs are issued via ACME. */
enabled: boolean;
/** True = Let's Encrypt production, false = staging. */
useProduction: boolean;
/** Whether to automatically renew certs before expiry. */
autoRenew: boolean;
/** Renew when a cert has fewer than this many days of validity left. */
renewThresholdDays: number;
/** Unix ms timestamp of last config change. */
updatedAt: number;
/** Who last updated the config (userId or 'seed' / 'system'). */
updatedBy: string;
}

View File

@@ -1,9 +1,28 @@
/**
* Supported DNS provider types. Initially Cloudflare; the abstraction is
* designed so additional providers (Route53, Gandi, DigitalOcean…) can be
* added by implementing the IDnsProvider class interface in ts/dns/providers/.
* Stable ID for the built-in DcRouter pseudo-provider. The Providers list
* surfaces this as the first, non-deletable row so operators see a uniform
* "who serves this?" answer for every domain. The ID is magic — it never
* exists in the DnsProviderDoc collection; handlers inject it at read time
* and reject any mutation that targets it.
*/
export type TDnsProviderType = 'cloudflare';
export const DCROUTER_BUILTIN_PROVIDER_ID = '__dcrouter__';
/**
* Supported DNS provider types.
*
* - 'cloudflare' → Cloudflare account (API token-based). Provider stays
* authoritative; dcrouter pushes record changes via API.
* - 'dcrouter' → Built-in pseudo-provider for dcrouter-hosted zones.
* dcrouter itself is the authoritative DNS server. No
* credentials, cannot be created/edited/deleted through
* the provider CRUD — the Providers view renders it from
* a handler-level synthetic row.
*
* The abstraction is designed so additional providers (Route53, Gandi,
* DigitalOcean, foreign dcrouters…) can be added by implementing the
* IDnsProvider class interface in ts/dns/providers/.
*/
export type TDnsProviderType = 'cloudflare' | 'dcrouter';
/**
* Status of the last connection test against a provider.
@@ -58,6 +77,12 @@ export interface IDnsProviderPublic {
createdBy: string;
/** Whether credentials are configured (true after creation). Never the secret itself. */
hasCredentials: boolean;
/**
* True for the built-in DcRouter pseudo-provider — read-only, cannot be
* created / edited / deleted. Injected by the handler layer, never
* persisted in the DnsProviderDoc collection.
*/
builtIn?: boolean;
}
/**
@@ -114,11 +139,18 @@ export interface IDnsProviderTypeDescriptor {
* credentials each one needs. Used by both backend and frontend.
*/
export const dnsProviderTypeDescriptors: ReadonlyArray<IDnsProviderTypeDescriptor> = [
{
type: 'dcrouter',
displayName: 'DcRouter (built-in)',
description:
'Built-in authoritative DNS. Records are served directly by dcrouter — delegate the domain\'s NS records to make this effective.',
credentialFields: [],
},
{
type: 'cloudflare',
displayName: 'Cloudflare',
description:
'Manages records via the Cloudflare API. Provider stays authoritative; dcrouter pushes record changes.',
'External DNS provider. The provider stays authoritative; dcrouter pushes record changes via its API.',
credentialFields: [
{
key: 'apiToken',

View File

@@ -6,16 +6,18 @@ export type TDnsRecordType = 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' | 'NS' | 'SOA
/**
* Where a DNS record came from.
*
* - 'manual' → created in the dcrouter UI / API
* - 'synced' → pulled from a provider during a sync operation
* - 'local' originated in this dcrouter (created via UI / API)
* - 'synced' → pulled from an upstream provider (Cloudflare, foreign
* dcrouter, …) during a sync operation
*/
export type TDnsRecordSource = 'manual' | 'synced';
export type TDnsRecordSource = 'local' | 'synced';
/**
* A DNS record. For manual (authoritative) domains, the record is registered
* with the embedded smartdns.DnsServer. For provider-managed domains, the
* record is mirrored from / pushed to the provider API and `providerRecordId`
* holds the provider's internal record id (for updates and deletes).
* A DNS record. For dcrouter-hosted (authoritative) domains, the record is
* registered with the embedded smartdns.DnsServer. For provider-managed
* domains, the record is mirrored from / pushed to the provider API and
* `providerRecordId` holds the provider's internal record id (for updates
* and deletes).
*/
export interface IDnsRecord {
id: string;

View File

@@ -1,14 +1,15 @@
/**
* Where a domain came from / how it is managed.
*
* - 'manual' → operator added the domain manually. dcrouter is the
* authoritative DNS server for it; records are served by
* the embedded smartdns.DnsServer.
* - 'dcrouter' → dcrouter is the authoritative DNS server for this domain;
* records are served by the embedded smartdns.DnsServer.
* Operators delegate the domain's NS records to make this
* effective.
* - 'provider' → domain was imported from an external DNS provider
* (e.g. Cloudflare). The provider stays authoritative;
* dcrouter only reads/writes records via the provider API.
* (e.g. Cloudflare). The provider stays authoritative;
* dcrouter only reads/writes records via the provider API.
*/
export type TDomainSource = 'manual' | 'provider';
export type TDomainSource = 'dcrouter' | 'provider';
/**
* A domain under management by dcrouter.
@@ -20,7 +21,7 @@ export interface IDomain {
source: TDomainSource;
/** ID of the DnsProvider that owns this domain — only set when source === 'provider'. */
providerId?: string;
/** True when dcrouter is the authoritative DNS server for this domain (source === 'manual'). */
/** True when dcrouter is the authoritative DNS server for this domain (source === 'dcrouter'). */
authoritative: boolean;
/** Authoritative nameservers (display only — populated from provider for imported domains). */
nameservers?: string[];

View File

@@ -0,0 +1,75 @@
/**
* DNS record validation status for a single email-related record (MX, SPF, DKIM, DMARC).
*/
export type TDnsRecordStatus = 'valid' | 'missing' | 'invalid' | 'unchecked';
/**
* An email domain managed by dcrouter.
*
* Each email domain is linked to an existing dcrouter DNS domain (dcrouter-hosted
* or provider-managed). The DNS management path is inherited from the linked domain
* — no separate DNS mode is needed.
*/
export interface IEmailDomain {
id: string;
/** Fully qualified email domain name (e.g. 'example.com' or 'mail.example.com'). */
domain: string;
/** ID of the linked dcrouter DNS domain — determines how DNS records are managed. */
linkedDomainId: string;
/** Optional subdomain prefix (e.g. 'mail' for mail.example.com). Empty/undefined = bare domain. */
subdomain?: string;
/** DKIM configuration and key state. */
dkim: IEmailDomainDkim;
/** Optional per-domain rate limits. */
rateLimits?: IEmailDomainRateLimits;
/** DNS record validation status — populated by validateDns(). */
dnsStatus: IEmailDomainDnsStatus;
createdAt: string;
updatedAt: string;
}
export interface IEmailDomainDkim {
/** DKIM selector (default: 'default'). */
selector: string;
/** RSA key size in bits (default: 2048). */
keySize: number;
/** Base64-encoded public key — populated after key generation. */
publicKey?: string;
/** Whether automatic key rotation is enabled. */
rotateKeys: boolean;
/** Days between key rotations (default: 90). */
rotationIntervalDays: number;
/** ISO date of last key rotation. */
lastRotatedAt?: string;
}
export interface IEmailDomainRateLimits {
outbound?: {
messagesPerMinute?: number;
messagesPerHour?: number;
messagesPerDay?: number;
};
inbound?: {
messagesPerMinute?: number;
connectionsPerIp?: number;
recipientsPerMessage?: number;
};
}
export interface IEmailDomainDnsStatus {
mx: TDnsRecordStatus;
spf: TDnsRecordStatus;
dkim: TDnsRecordStatus;
dmarc: TDnsRecordStatus;
lastCheckedAt?: string;
}
/**
* A single required DNS record for an email domain — used for display / copy-paste.
*/
export interface IEmailDnsRecord {
type: 'MX' | 'TXT';
name: string;
value: string;
status: TDnsRecordStatus;
}

View File

@@ -6,4 +6,6 @@ export * from './target-profile.js';
export * from './vpn.js';
export * from './dns-provider.js';
export * from './domain.js';
export * from './dns-record.js';
export * from './dns-record.js';
export * from './acme-config.js';
export * from './email-domain.js';

View File

@@ -17,7 +17,8 @@ export type TApiTokenScope =
| 'targets:read' | 'targets:write'
| 'dns-providers:read' | 'dns-providers:write'
| 'domains:read' | 'domains:write'
| 'dns-records:read' | 'dns-records:write';
| 'dns-records:read' | 'dns-records:write'
| 'acme-config:read' | 'acme-config:write';
// ============================================================================
// Source Profile Types (source-side: who can access)

View File

@@ -0,0 +1,54 @@
import * as plugins from '../plugins.js';
import type * as authInterfaces from '../data/auth.js';
import type { IAcmeConfig } from '../data/acme-config.js';
// ============================================================================
// ACME Config Endpoints
// ============================================================================
/**
* Get the current ACME configuration. Returns null if no config has been
* set yet (neither from DB nor seeded from the constructor).
*/
export interface IReq_GetAcmeConfig extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetAcmeConfig
> {
method: 'getAcmeConfig';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
config: IAcmeConfig | null;
};
}
/**
* Update the ACME configuration (upsert). All fields are required on first
* create, optional on subsequent updates (partial update).
*
* NOTE: Most fields take effect on the next dcrouter restart — SmartAcme is
* instantiated once at startup. `renewThresholdDays` applies immediately to
* the next renewal check.
*/
export interface IReq_UpdateAcmeConfig extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_UpdateAcmeConfig
> {
method: 'updateAcmeConfig';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
accountEmail?: string;
enabled?: boolean;
useProduction?: boolean;
autoRenew?: boolean;
renewThresholdDays?: number;
};
response: {
success: boolean;
config?: IAcmeConfig;
message?: string;
};
}

View File

@@ -45,7 +45,7 @@ export interface IReq_GetDnsRecord extends plugins.typedrequestInterfaces.implem
/**
* Create a new DNS record.
*
* For manual domains: registers the record with the embedded DnsServer.
* For dcrouter-hosted domains: registers the record with the embedded DnsServer.
* For provider domains: pushes the record to the provider API.
*/
export interface IReq_CreateDnsRecord extends plugins.typedrequestInterfaces.implementsTR<

View File

@@ -42,8 +42,8 @@ export interface IReq_GetDomain extends plugins.typedrequestInterfaces.implement
}
/**
* Create a manual (authoritative) domain. dcrouter will serve DNS
* records for this domain via the embedded smartdns.DnsServer.
* Create a dcrouter-hosted (authoritative) domain. dcrouter will serve
* DNS records for this domain via the embedded smartdns.DnsServer.
*/
export interface IReq_CreateDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
@@ -130,7 +130,7 @@ export interface IReq_DeleteDomain extends plugins.typedrequestInterfaces.implem
/**
* Force-resync a provider-managed domain: re-pulls all records from the
* provider API, replacing the cached DnsRecordDocs.
* No-op for manual domains.
* No-op for dcrouter-hosted domains.
*/
export interface IReq_SyncDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
@@ -148,3 +148,31 @@ export interface IReq_SyncDomain extends plugins.typedrequestInterfaces.implemen
message?: string;
};
}
/**
* Migrate a domain between dcrouter-hosted and provider-managed (or between providers).
* Records are transferred to the target and the domain source/providerId are updated.
*/
export interface IReq_MigrateDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_MigrateDomain
> {
method: 'migrateDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
/** Target source type. */
targetSource: import('../data/domain.js').TDomainSource;
/** Required when targetSource is 'provider'. */
targetProviderId?: string;
/** When migrating to a provider: delete all existing records at the provider first. */
deleteExistingProviderRecords?: boolean;
};
response: {
success: boolean;
/** Number of records migrated. */
recordsMigrated?: number;
message?: string;
};
}

View File

@@ -0,0 +1,178 @@
import * as plugins from '../plugins.js';
import type * as authInterfaces from '../data/auth.js';
import type { IEmailDomain, IEmailDnsRecord } from '../data/email-domain.js';
// ============================================================================
// Email Domain Endpoints
// ============================================================================
/**
* List all email domains.
*/
export interface IReq_GetEmailDomains extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetEmailDomains
> {
method: 'getEmailDomains';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
domains: IEmailDomain[];
};
}
/**
* Get a single email domain by id.
*/
export interface IReq_GetEmailDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetEmailDomain
> {
method: 'getEmailDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
domain: IEmailDomain | null;
};
}
/**
* Create an email domain. Links to an existing dcrouter DNS domain.
* Generates DKIM keys and computes the required DNS records.
*/
export interface IReq_CreateEmailDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_CreateEmailDomain
> {
method: 'createEmailDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
/** ID of the existing dcrouter DNS domain to link to. */
linkedDomainId: string;
/** Optional subdomain prefix (e.g. 'mail' for mail.example.com). Leave empty for bare domain. */
subdomain?: string;
/** DKIM selector (default: 'default'). */
dkimSelector?: string;
/** RSA key size (default: 2048). */
dkimKeySize?: number;
/** Enable automatic key rotation (default: false). */
rotateKeys?: boolean;
/** Days between rotations (default: 90). */
rotationIntervalDays?: number;
};
response: {
success: boolean;
domain?: IEmailDomain;
message?: string;
};
}
/**
* Update an email domain's configuration.
*/
export interface IReq_UpdateEmailDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_UpdateEmailDomain
> {
method: 'updateEmailDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
rotateKeys?: boolean;
rotationIntervalDays?: number;
rateLimits?: IEmailDomain['rateLimits'];
};
response: {
success: boolean;
message?: string;
};
}
/**
* Delete an email domain.
*/
export interface IReq_DeleteEmailDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_DeleteEmailDomain
> {
method: 'deleteEmailDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
success: boolean;
message?: string;
};
}
/**
* Trigger DNS validation for an email domain.
* Performs live lookups for MX, SPF, DKIM, and DMARC records.
*/
export interface IReq_ValidateEmailDomain extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_ValidateEmailDomain
> {
method: 'validateEmailDomain';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
success: boolean;
domain?: IEmailDomain;
records?: IEmailDnsRecord[];
message?: string;
};
}
/**
* Get the required DNS records for an email domain (for display / copy-paste).
*/
export interface IReq_GetEmailDomainDnsRecords extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetEmailDomainDnsRecords
> {
method: 'getEmailDomainDnsRecords';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
records: IEmailDnsRecord[];
};
}
/**
* Auto-provision DNS records for an email domain.
* Creates any missing MX, SPF, DKIM, and DMARC records via the linked
* domain's DNS path (dcrouter zone or provider API).
*/
export interface IReq_ProvisionEmailDomainDns extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_ProvisionEmailDomainDns
> {
method: 'provisionEmailDomainDns';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
success: boolean;
/** Number of records created. */
provisioned?: number;
message?: string;
};
}

View File

@@ -16,4 +16,6 @@ export * from './network-targets.js';
export * from './users.js';
export * from './dns-providers.js';
export * from './domains.js';
export * from './dns-records.js';
export * from './dns-records.js';
export * from './acme-config.js';
export * from './email-domains.js';

View File

@@ -64,6 +64,34 @@ export async function createMigrationRunner(
migrated++;
}
ctx.log.log('info', `rename-target-profile-host-to-ip: migrated ${migrated} profile(s)`);
})
.step('rename-domain-source-manual-to-dcrouter')
.from('13.1.0').to('13.8.1')
.description('Rename DomainDoc.source value from "manual" to "dcrouter"')
.up(async (ctx) => {
const collection = ctx.mongo!.collection('domaindoc');
const result = await collection.updateMany(
{ source: 'manual' },
{ $set: { source: 'dcrouter' } },
);
ctx.log.log(
'info',
`rename-domain-source-manual-to-dcrouter: migrated ${result.modifiedCount} domain(s)`,
);
})
.step('rename-record-source-manual-to-local')
.from('13.8.1').to('13.8.2')
.description('Rename DnsRecordDoc.source value from "manual" to "local"')
.up(async (ctx) => {
const collection = ctx.mongo!.collection('dnsrecorddoc');
const result = await collection.updateMany(
{ source: 'manual' },
{ $set: { source: 'local' } },
);
ctx.log.log(
'info',
`rename-record-source-manual-to-local: migrated ${result.modifiedCount} record(s)`,
);
});
return migration;

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@serve.zone/dcrouter',
version: '13.7.1',
version: '13.13.0',
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
}

View File

@@ -197,6 +197,28 @@ export const certificateStatePart = await appState.getStatePart<ICertificateStat
'soft'
);
// ============================================================================
// ACME Config State (DB-backed singleton, managed via Domains > Certificates)
// ============================================================================
export interface IAcmeConfigState {
config: interfaces.data.IAcmeConfig | null;
isLoading: boolean;
error: string | null;
lastUpdated: number;
}
export const acmeConfigStatePart = await appState.getStatePart<IAcmeConfigState>(
'acmeConfig',
{
config: null,
isLoading: false,
error: null,
lastUpdated: 0,
},
'soft',
);
// ============================================================================
// Remote Ingress State
// ============================================================================
@@ -1771,7 +1793,7 @@ export async function fetchProviderDomains(
return await request.fire({ identity: context.identity, providerId });
}
export const createManualDomainAction = domainsStatePart.createAction<{
export const createDcrouterDomainAction = domainsStatePart.createAction<{
name: string;
description?: string;
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
@@ -1865,6 +1887,32 @@ export const syncDomainAction = domainsStatePart.createAction<{ id: string }>(
},
);
export const migrateDomainAction = domainsStatePart.createAction<{
id: string;
targetSource: interfaces.data.TDomainSource;
targetProviderId?: string;
deleteExistingProviderRecords?: boolean;
}>(
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_MigrateDomain
>('/typedrequest', 'migrateDomain');
const response = await request.fire({ identity: context.identity!, ...dataArg });
if (!response.success) {
return { ...statePartArg.getState()!, error: response.message || 'Migration failed' };
}
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Migration failed',
};
}
},
);
export const createDnsRecordAction = domainsStatePart.createAction<{
domainId: string;
name: string;
@@ -1953,6 +2001,72 @@ export const deleteDnsRecordAction = domainsStatePart.createAction<{ id: string;
},
);
// ============================================================================
// ACME Config Actions
// ============================================================================
export const fetchAcmeConfigAction = acmeConfigStatePart.createAction(
async (statePartArg): Promise<IAcmeConfigState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
if (!context.identity) return currentState;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetAcmeConfig
>('/typedrequest', 'getAcmeConfig');
const response = await request.fire({ identity: context.identity });
return {
config: response.config,
isLoading: false,
error: null,
lastUpdated: Date.now(),
};
} catch (error: unknown) {
return {
...currentState,
isLoading: false,
error: error instanceof Error ? error.message : 'Failed to fetch ACME config',
};
}
},
);
export const updateAcmeConfigAction = acmeConfigStatePart.createAction<{
accountEmail?: string;
enabled?: boolean;
useProduction?: boolean;
autoRenew?: boolean;
renewThresholdDays?: number;
}>(async (statePartArg, dataArg, actionContext): Promise<IAcmeConfigState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_UpdateAcmeConfig
>('/typedrequest', 'updateAcmeConfig');
const response = await request.fire({
identity: context.identity!,
accountEmail: dataArg.accountEmail,
enabled: dataArg.enabled,
useProduction: dataArg.useProduction,
autoRenew: dataArg.autoRenew,
renewThresholdDays: dataArg.renewThresholdDays,
});
if (!response.success) {
return {
...statePartArg.getState()!,
error: response.message || 'Failed to update ACME config',
};
}
return await actionContext!.dispatch(fetchAcmeConfigAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to update ACME config',
};
}
});
// ============================================================================
// Route Management Actions
// ============================================================================
@@ -2289,6 +2403,130 @@ export const toggleApiTokenAction = routeManagementStatePart.createAction<{
}
});
// ============================================================================
// Email Domains State
// ============================================================================
export interface IEmailDomainsState {
domains: interfaces.data.IEmailDomain[];
isLoading: boolean;
lastUpdated: number;
}
export const emailDomainsStatePart = await appState.getStatePart<IEmailDomainsState>(
'emailDomains',
{
domains: [],
isLoading: false,
lastUpdated: 0,
},
'soft',
);
export const fetchEmailDomainsAction = emailDomainsStatePart.createAction(
async (statePartArg): Promise<IEmailDomainsState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
if (!context.identity) return currentState;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetEmailDomains
>('/typedrequest', 'getEmailDomains');
const response = await request.fire({ identity: context.identity });
return {
...currentState,
domains: response.domains,
isLoading: false,
lastUpdated: Date.now(),
};
} catch {
return { ...currentState, isLoading: false };
}
},
);
export const createEmailDomainAction = emailDomainsStatePart.createAction<{
linkedDomainId: string;
subdomain?: string;
dkimSelector?: string;
dkimKeySize?: number;
rotateKeys?: boolean;
rotationIntervalDays?: number;
}>(async (statePartArg, args, actionContext) => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_CreateEmailDomain
>('/typedrequest', 'createEmailDomain');
await request.fire({ identity: context.identity!, ...args });
return await actionContext!.dispatch(fetchEmailDomainsAction, null);
} catch {
return currentState;
}
});
export const deleteEmailDomainAction = emailDomainsStatePart.createAction<string>(
async (statePartArg, id, actionContext) => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_DeleteEmailDomain
>('/typedrequest', 'deleteEmailDomain');
await request.fire({ identity: context.identity!, id });
return await actionContext!.dispatch(fetchEmailDomainsAction, null);
} catch {
return currentState;
}
},
);
export const validateEmailDomainAction = emailDomainsStatePart.createAction<string>(
async (statePartArg, id, actionContext) => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_ValidateEmailDomain
>('/typedrequest', 'validateEmailDomain');
await request.fire({ identity: context.identity!, id });
return await actionContext!.dispatch(fetchEmailDomainsAction, null);
} catch {
return currentState;
}
},
);
export const provisionEmailDomainDnsAction = emailDomainsStatePart.createAction<string>(
async (statePartArg, id, actionContext) => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_ProvisionEmailDomainDns
>('/typedrequest', 'provisionEmailDomainDns');
await request.fire({ identity: context.identity!, id });
return await actionContext!.dispatch(fetchEmailDomainsAction, null);
} catch {
return currentState;
}
},
);
// ============================================================================
// Email Domain Standalone Functions
// ============================================================================
export async function fetchEmailDomainDnsRecords(id: string) {
const context = getActionContext();
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetEmailDomainDnsRecords
>('/typedrequest', 'getEmailDomainDnsRecords');
return request.fire({ identity: context.identity!, id });
}
// ============================================================================
// TypedSocket Client for Real-time Log Streaming
// ============================================================================

View File

@@ -222,7 +222,7 @@ export class OpsViewApiTokens extends DeesElement {
.suggestions=${allScopes}
.required=${true}
></dees-input-tags>
<dees-input-text .key=${'expiresInDays'} .label=${'Expires in (days, blank = never)'}></dees-input-text>
<dees-input-text .key=${'expiresInDays'} .label=${'Expires in'} .description=${'Number of days; leave blank for no expiration'}></dees-input-text>
</dees-form>
`,
menuOptions: [

View File

@@ -44,12 +44,15 @@ export class DnsProviderForm extends DeesElement {
accessor providerName: string = '';
/**
* Currently selected provider type. Initialized to the first descriptor;
* caller can override before mounting (e.g. for edit dialogs).
* Currently selected provider type. Initialized to the first user-creatable
* descriptor; caller can override before mounting (e.g. for edit dialogs).
* The built-in 'dcrouter' pseudo-provider is excluded from the picker —
* operators cannot create another one.
*/
@state()
accessor selectedType: interfaces.data.TDnsProviderType =
interfaces.data.dnsProviderTypeDescriptors[0]?.type ?? 'cloudflare';
interfaces.data.dnsProviderTypeDescriptors.find((d) => d.type !== 'dcrouter')?.type ??
'cloudflare';
/** When true, hide the type picker — used in edit dialogs. */
@property({ type: Boolean })
@@ -77,22 +80,6 @@ export class DnsProviderForm extends DeesElement {
margin-bottom: 12px;
}
.helpText {
font-size: 12px;
opacity: 0.7;
margin-top: -6px;
margin-bottom: 8px;
}
.typeDescription {
font-size: 12px;
opacity: 0.8;
margin: 4px 0 16px;
padding: 8px 12px;
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
border-radius: 6px;
}
.credentialsHint {
font-size: 12px;
opacity: 0.7;
@@ -102,7 +89,12 @@ export class DnsProviderForm extends DeesElement {
];
public render(): TemplateResult {
const descriptors = interfaces.data.dnsProviderTypeDescriptors;
// Exclude the built-in 'dcrouter' pseudo-provider from the type picker —
// operators cannot create another one, it's surfaced at read time by the
// backend handler instead.
const descriptors = interfaces.data.dnsProviderTypeDescriptors.filter(
(d) => d.type !== 'dcrouter',
);
const descriptor = interfaces.data.getDnsProviderTypeDescriptor(this.selectedType);
return html`
@@ -122,6 +114,7 @@ export class DnsProviderForm extends DeesElement {
<dees-input-text
.key=${'__type_display'}
.label=${'Type'}
.infoText=${descriptor?.description || ''}
.value=${descriptor?.displayName ?? this.selectedType}
.disabled=${true}
></dees-input-text>
@@ -132,6 +125,7 @@ export class DnsProviderForm extends DeesElement {
<dees-input-dropdown
.key=${'__type'}
.label=${'Provider type'}
.infoText=${descriptor?.description || ''}
.options=${descriptors.map((d) => ({ option: d.displayName, key: d.type }))}
.selectedOption=${descriptor
? { option: descriptor.displayName, key: descriptor.type }
@@ -150,7 +144,6 @@ export class DnsProviderForm extends DeesElement {
`}
${descriptor
? html`
<div class="typeDescription">${descriptor.description}</div>
${this.credentialsHint
? html`<div class="credentialsHint">${this.credentialsHint}</div>`
: ''}
@@ -160,9 +153,9 @@ export class DnsProviderForm extends DeesElement {
<dees-input-text
.key=${f.key}
.label=${f.label}
.description=${f.helpText || ''}
.required=${f.required && !this.lockType}
></dees-input-text>
${f.helpText ? html`<div class="helpText">${f.helpText}</div>` : ''}
</div>
`,
)}

View File

@@ -23,17 +23,25 @@ export class OpsViewCertificates extends DeesElement {
@state()
accessor certState: appstate.ICertificateState = appstate.certificateStatePart.getState()!;
@state()
accessor acmeState: appstate.IAcmeConfigState = appstate.acmeConfigStatePart.getState()!;
constructor() {
super();
const sub = appstate.certificateStatePart.select().subscribe((newState) => {
const certSub = appstate.certificateStatePart.select().subscribe((newState) => {
this.certState = newState;
});
this.rxSubscriptions.push(sub);
this.rxSubscriptions.push(certSub);
const acmeSub = appstate.acmeConfigStatePart.select().subscribe((newState) => {
this.acmeState = newState;
});
this.rxSubscriptions.push(acmeSub);
}
async connectedCallback() {
await super.connectedCallback();
await appstate.certificateStatePart.dispatchAction(appstate.fetchCertificateOverviewAction, null);
await appstate.acmeConfigStatePart.dispatchAction(appstate.fetchAcmeConfigAction, null);
}
public static styles = [
@@ -163,11 +171,117 @@ export class OpsViewCertificates extends DeesElement {
<div class="certificatesContainer">
${this.renderStatsTiles(summary)}
${this.renderAcmeSettingsTile()}
${this.renderCertificateTable()}
</div>
`;
}
private renderAcmeSettingsTile(): TemplateResult {
const config = this.acmeState.config;
if (!config) {
return html`
<dees-settings
.heading=${'ACME Settings'}
.description=${'No ACME configuration yet. Click Configure to set up automated TLS certificate issuance via Let\'s Encrypt. You\'ll also need at least one DNS provider under Domains > Providers.'}
.actions=${[{ name: 'Configure', action: () => this.showEditAcmeDialog() }]}
></dees-settings>
`;
}
return html`
<dees-settings
.heading=${'ACME Settings'}
.settingsFields=${[
{ key: 'email', label: 'Account email', value: config.accountEmail || '(not set)' },
{ key: 'status', label: 'Status', value: config.enabled ? 'enabled' : 'disabled' },
{ key: 'mode', label: 'Mode', value: config.useProduction ? 'production' : 'staging' },
{ key: 'autoRenew', label: 'Auto-renew', value: config.autoRenew ? 'on' : 'off' },
{ key: 'threshold', label: 'Renewal threshold', value: `${config.renewThresholdDays} days` },
]}
.actions=${[{ name: 'Edit', action: () => this.showEditAcmeDialog() }]}
></dees-settings>
`;
}
private async showEditAcmeDialog() {
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
const current = this.acmeState.config;
DeesModal.createAndShow({
heading: current ? 'Edit ACME Settings' : 'Configure ACME',
content: html`
<dees-form>
<dees-input-text
.key=${'accountEmail'}
.label=${'Account email'}
.value=${current?.accountEmail ?? ''}
.required=${true}
></dees-input-text>
<dees-input-checkbox
.key=${'enabled'}
.label=${'Enabled'}
.value=${current?.enabled ?? true}
></dees-input-checkbox>
<dees-input-checkbox
.key=${'useProduction'}
.label=${"Use Let's Encrypt production"}
.description=${'Uncheck to use the staging environment'}
.value=${current?.useProduction ?? true}
></dees-input-checkbox>
<dees-input-checkbox
.key=${'autoRenew'}
.label=${'Auto-renew certificates'}
.value=${current?.autoRenew ?? true}
></dees-input-checkbox>
<dees-input-text
.key=${'renewThresholdDays'}
.label=${'Renewal threshold'}
.description=${'Number of days before expiry to trigger renewal'}
.value=${String(current?.renewThresholdDays ?? 30)}
></dees-input-text>
</dees-form>
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
Most fields take effect on the next dcrouter restart (SmartAcme is instantiated once at
startup). Changing the account email creates a new Let's Encrypt account — only do this
if you know what you're doing.
</p>
`,
menuOptions: [
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
{
name: 'Save',
action: async (modalArg: any) => {
const form = modalArg.shadowRoot
?.querySelector('.content')
?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
const email = String(data.accountEmail ?? '').trim();
if (!email) {
DeesToast.show({
message: 'Account email is required',
type: 'warning',
duration: 2500,
});
return;
}
const threshold = parseInt(String(data.renewThresholdDays ?? '30'), 10);
await appstate.acmeConfigStatePart.dispatchAction(appstate.updateAcmeConfigAction, {
accountEmail: email,
enabled: Boolean(data.enabled),
useProduction: Boolean(data.useProduction),
autoRenew: Boolean(data.autoRenew),
renewThresholdDays: Number.isFinite(threshold) ? threshold : 30,
});
modalArg.destroy();
},
},
],
});
}
private renderStatsTiles(summary: appstate.ICertificateState['summary']): TemplateResult {
const tiles: IStatsTile[] = [
{
@@ -253,11 +367,12 @@ export class OpsViewCertificates extends DeesElement {
content: html`
<dees-form>
<dees-input-fileupload
key="certJsonFile"
label="Certificate JSON (.tsclass.cert.json)"
accept=".json"
.key=${'certJsonFile'}
.label=${'Certificate JSON'}
.description=${'Upload a .tsclass.cert.json file'}
.accept=${'.json'}
.multiple=${false}
required
.required=${true}
></dees-input-fileupload>
</dees-form>
`,

View File

@@ -80,7 +80,7 @@ export class OpsViewDns extends DeesElement {
font-weight: 500;
}
.sourceBadge.manual {
.sourceBadge.local {
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
}
@@ -101,8 +101,8 @@ export class OpsViewDns extends DeesElement {
<dees-heading level="3">DNS Records</dees-heading>
<div class="dnsContainer">
<div class="domainPicker">
<span>Domain:</span>
<dees-input-dropdown
.label=${'Domain'}
.options=${domains.map((d) => ({ option: d.name, key: d.id }))}
.selectedOption=${selectedId
? { option: domains.find((d) => d.id === selectedId)?.name || '', key: selectedId }
@@ -184,7 +184,7 @@ export class OpsViewDns extends DeesElement {
private domainHint(domainId: string): string {
const domain = this.domainsState.domains.find((d) => d.id === domainId);
if (!domain) return '';
if (domain.source === 'manual') {
if (domain.source === 'dcrouter') {
return 'Records are served by dcrouter (authoritative).';
}
return 'Records are stored at the provider — changes here are pushed via the provider API.';
@@ -196,7 +196,7 @@ export class OpsViewDns extends DeesElement {
heading: 'Add DNS Record',
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name (FQDN)'} .required=${true}></dees-input-text>
<dees-input-text .key=${'name'} .label=${'Name'} .description=${'Fully qualified domain name'} .required=${true}></dees-input-text>
<dees-input-dropdown
.key=${'type'}
.label=${'Type'}
@@ -205,10 +205,11 @@ export class OpsViewDns extends DeesElement {
></dees-input-dropdown>
<dees-input-text
.key=${'value'}
.label=${'Value (for MX use "10 mail.example.com")'}
.label=${'Value'}
.description=${'For MX records use priority format, e.g. "10 mail.example.com"'}
.required=${true}
></dees-input-text>
<dees-input-text .key=${'ttl'} .label=${'TTL (seconds)'} .value=${'300'}></dees-input-text>
<dees-input-text .key=${'ttl'} .label=${'TTL'} .description=${'Time to live in seconds'} .value=${'300'}></dees-input-text>
</dees-form>
`,
menuOptions: [
@@ -242,9 +243,9 @@ export class OpsViewDns extends DeesElement {
heading: `Edit ${rec.type} ${rec.name}`,
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name (FQDN)'} .value=${rec.name}></dees-input-text>
<dees-input-text .key=${'name'} .label=${'Name'} .description=${'Fully qualified domain name'} .value=${rec.name}></dees-input-text>
<dees-input-text .key=${'value'} .label=${'Value'} .value=${rec.value}></dees-input-text>
<dees-input-text .key=${'ttl'} .label=${'TTL (seconds)'} .value=${String(rec.ttl)}></dees-input-text>
<dees-input-text .key=${'ttl'} .label=${'TTL'} .description=${'Time to live in seconds'} .value=${String(rec.ttl)}></dees-input-text>
</dees-form>
`,
menuOptions: [

View File

@@ -55,7 +55,7 @@ export class OpsViewDomains extends DeesElement {
font-weight: 500;
}
.sourceBadge.manual {
.sourceBadge.dcrouter {
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
}
@@ -76,7 +76,7 @@ export class OpsViewDomains extends DeesElement {
<div class="domainsContainer">
<dees-table
.heading1=${'Domains'}
.heading2=${'Domains under management — manual (authoritative) or imported from a provider'}
.heading2=${'Domains under management — served by dcrouter (authoritative) or imported from a provider'}
.data=${domains}
.showColumnFilters=${true}
.displayFunction=${(d: interfaces.data.IDomain) => ({
@@ -90,11 +90,11 @@ export class OpsViewDomains extends DeesElement {
})}
.dataActions=${[
{
name: 'Add Manual Domain',
name: 'Add DcRouter Domain',
iconName: 'lucide:plus',
type: ['header' as const],
actionFunc: async () => {
await this.showCreateManualDialog();
await this.showCreateDcrouterDialog();
},
},
{
@@ -149,6 +149,15 @@ export class OpsViewDomains extends DeesElement {
});
},
},
{
name: 'Migrate',
iconName: 'lucide:arrow-right-left',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const domain = actionData.item as interfaces.data.IDomain;
await this.showMigrateDialog(domain);
},
},
{
name: 'Delete',
iconName: 'lucide:trash2',
@@ -168,21 +177,21 @@ export class OpsViewDomains extends DeesElement {
d: interfaces.data.IDomain,
providersById: Map<string, interfaces.data.IDnsProviderPublic>,
): TemplateResult {
if (d.source === 'manual') {
return html`<span class="sourceBadge manual">Manual</span>`;
if (d.source === 'dcrouter') {
return html`<span class="sourceBadge dcrouter">DcRouter</span>`;
}
const provider = d.providerId ? providersById.get(d.providerId) : undefined;
return html`<span class="sourceBadge provider">${provider?.name || 'Provider'}</span>`;
}
private async showCreateManualDialog() {
private async showCreateDcrouterDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Add Manual Domain',
heading: 'Add DcRouter Domain',
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'FQDN (e.g. example.com)'} .required=${true}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description (optional)'}></dees-input-text>
<dees-input-text .key=${'name'} .label=${'FQDN'} .description=${'e.g. example.com'} .required=${true}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'}></dees-input-text>
</dees-form>
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
dcrouter will become the authoritative DNS server for this domain. You'll need to
@@ -199,7 +208,7 @@ export class OpsViewDomains extends DeesElement {
?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
await appstate.domainsStatePart.dispatchAction(appstate.createManualDomainAction, {
await appstate.domainsStatePart.dispatchAction(appstate.createDcrouterDomainAction, {
name: String(data.name),
description: data.description ? String(data.description) : undefined,
});
@@ -235,7 +244,8 @@ export class OpsViewDomains extends DeesElement {
></dees-input-dropdown>
<dees-input-text
.key=${'domainNames'}
.label=${'Comma-separated FQDNs to import (e.g. example.com, foo.com)'}
.label=${'Domain Names'}
.description=${'Comma-separated FQDNs, e.g. example.com, foo.com'}
.required=${true}
></dees-input-text>
</dees-form>
@@ -307,6 +317,96 @@ export class OpsViewDomains extends DeesElement {
});
}
private async showMigrateDialog(domain: interfaces.data.IDomain) {
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
const providers = this.domainsState.providers;
// Build target options based on current source
const targetOptions: { option: string; key: string }[] = [];
if (domain.source === 'provider') {
targetOptions.push({ option: 'DcRouter (authoritative)', key: 'dcrouter' });
}
// Add all providers (except the current one if already provider-managed)
for (const p of providers) {
if (domain.source === 'provider' && domain.providerId === p.id) continue;
targetOptions.push({ option: `${p.name} (${p.type})`, key: `provider:${p.id}` });
}
if (domain.source === 'dcrouter') {
targetOptions.unshift({ option: 'DcRouter (authoritative)', key: 'dcrouter' });
}
if (targetOptions.length === 0) {
DeesToast.show({
message: 'No migration targets available. Add a DNS provider first.',
type: 'warning',
duration: 3000,
});
return;
}
const currentLabel = domain.source === 'dcrouter'
? 'DcRouter (authoritative)'
: providers.find((p) => p.id === domain.providerId)?.name || 'Provider';
DeesModal.createAndShow({
heading: `Migrate: ${domain.name}`,
content: html`
<dees-form>
<dees-input-text
.key=${'currentSource'}
.label=${'Current source'}
.value=${currentLabel}
.disabled=${true}
></dees-input-text>
<dees-input-dropdown
.key=${'target'}
.label=${'Migrate to'}
.description=${'Select the target DNS management'}
.options=${targetOptions}
.required=${true}
></dees-input-dropdown>
<dees-input-checkbox
.key=${'deleteExisting'}
.label=${'Delete existing records at provider first'}
.description=${'Removes all records at the provider before pushing migrated records'}
.value=${true}
></dees-input-checkbox>
</dees-form>
`,
menuOptions: [
{ name: 'Cancel', action: async (m: any) => m.destroy() },
{
name: 'Migrate',
action: async (m: any) => {
const form = m.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
const targetKey = typeof data.target === 'object' ? data.target.key : data.target;
if (!targetKey) return;
let targetSource: interfaces.data.TDomainSource;
let targetProviderId: string | undefined;
if (targetKey === 'dcrouter') {
targetSource = 'dcrouter';
} else {
targetSource = 'provider';
targetProviderId = targetKey.replace('provider:', '');
}
await appstate.domainsStatePart.dispatchAction(appstate.migrateDomainAction, {
id: domain.id,
targetSource,
targetProviderId,
deleteExistingProviderRecords: targetSource === 'provider' ? Boolean(data.deleteExisting) : false,
});
DeesToast.show({ message: `Domain ${domain.name} migrated successfully`, type: 'success', duration: 3000 });
m.destroy();
},
},
],
});
}
private async deleteDomain(domain: interfaces.data.IDomain) {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({

View File

@@ -71,6 +71,11 @@ export class OpsViewProviders extends DeesElement {
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
color: ${cssManager.bdTheme('#4b5563', '#9ca3af')};
}
.statusBadge.builtin {
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
}
`,
];
@@ -82,15 +87,21 @@ export class OpsViewProviders extends DeesElement {
<div class="providersContainer">
<dees-table
.heading1=${'Providers'}
.heading2=${'External DNS provider accounts'}
.heading2=${'Built-in dcrouter + external DNS provider accounts'}
.data=${providers}
.showColumnFilters=${true}
.displayFunction=${(p: interfaces.data.IDnsProviderPublic) => ({
Name: p.name,
Type: this.providerTypeLabel(p.type),
Status: this.renderStatusBadge(p.status),
'Last Tested': p.lastTestedAt ? new Date(p.lastTestedAt).toLocaleString() : 'never',
Error: p.lastError || '-',
Status: p.builtIn
? html`<span class="statusBadge builtin">built-in</span>`
: this.renderStatusBadge(p.status),
'Last Tested': p.builtIn
? '—'
: p.lastTestedAt
? new Date(p.lastTestedAt).toLocaleString()
: 'never',
Error: p.builtIn ? '—' : p.lastError || '-',
})}
.dataActions=${[
{
@@ -116,6 +127,7 @@ export class OpsViewProviders extends DeesElement {
name: 'Test Connection',
iconName: 'lucide:plug',
type: ['inRow', 'contextmenu'] as any,
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
actionFunc: async (actionData: any) => {
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
await this.testProvider(provider);
@@ -125,6 +137,7 @@ export class OpsViewProviders extends DeesElement {
name: 'Edit',
iconName: 'lucide:pencil',
type: ['inRow', 'contextmenu'] as any,
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
actionFunc: async (actionData: any) => {
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
await this.showEditDialog(provider);
@@ -134,6 +147,7 @@ export class OpsViewProviders extends DeesElement {
name: 'Delete',
iconName: 'lucide:trash2',
type: ['inRow', 'contextmenu'] as any,
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
actionFunc: async (actionData: any) => {
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
await this.deleteProvider(provider);

View File

@@ -1,2 +1,3 @@
export * from './ops-view-emails.js';
export * from './ops-view-email-security.js';
export * from './ops-view-email-domains.js';

View File

@@ -0,0 +1,396 @@
import {
DeesElement,
html,
customElement,
type TemplateResult,
css,
state,
cssManager,
} from '@design.estate/dees-element';
import * as appstate from '../../appstate.js';
import * as interfaces from '../../../dist_ts_interfaces/index.js';
import { viewHostCss } from '../shared/css.js';
import { type IStatsTile } from '@design.estate/dees-catalog';
declare global {
interface HTMLElementTagNameMap {
'ops-view-email-domains': OpsViewEmailDomains;
}
}
@customElement('ops-view-email-domains')
export class OpsViewEmailDomains extends DeesElement {
@state()
accessor emailDomainsState: appstate.IEmailDomainsState =
appstate.emailDomainsStatePart.getState()!;
@state()
accessor domainsState: appstate.IDomainsState = appstate.domainsStatePart.getState()!;
constructor() {
super();
const sub = appstate.emailDomainsStatePart.select().subscribe((s) => {
this.emailDomainsState = s;
});
this.rxSubscriptions.push(sub);
const domSub = appstate.domainsStatePart.select().subscribe((s) => {
this.domainsState = s;
});
this.rxSubscriptions.push(domSub);
}
async connectedCallback() {
await super.connectedCallback();
await appstate.emailDomainsStatePart.dispatchAction(appstate.fetchEmailDomainsAction, null);
await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
}
public static styles = [
cssManager.defaultStyles,
viewHostCss,
css`
.emailDomainsContainer {
display: flex;
flex-direction: column;
gap: 24px;
}
.statusBadge {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.statusBadge.valid {
background: ${cssManager.bdTheme('#dcfce7', '#14532d')};
color: ${cssManager.bdTheme('#166534', '#4ade80')};
}
.statusBadge.missing {
background: ${cssManager.bdTheme('#fef2f2', '#450a0a')};
color: ${cssManager.bdTheme('#991b1b', '#f87171')};
}
.statusBadge.invalid {
background: ${cssManager.bdTheme('#fff7ed', '#431407')};
color: ${cssManager.bdTheme('#9a3412', '#fb923c')};
}
.statusBadge.unchecked {
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
color: ${cssManager.bdTheme('#4b5563', '#9ca3af')};
}
.sourceBadge {
display: inline-flex;
align-items: center;
padding: 3px 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 500;
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
color: ${cssManager.bdTheme('#374151', '#d1d5db')};
}
`,
];
public render(): TemplateResult {
const domains = this.emailDomainsState.domains;
const validCount = domains.filter(
(d) =>
d.dnsStatus.mx === 'valid' &&
d.dnsStatus.spf === 'valid' &&
d.dnsStatus.dkim === 'valid' &&
d.dnsStatus.dmarc === 'valid',
).length;
const issueCount = domains.length - validCount;
const tiles: IStatsTile[] = [
{
id: 'total',
title: 'Total Domains',
value: domains.length,
type: 'number',
icon: 'lucide:globe',
color: '#3b82f6',
},
{
id: 'valid',
title: 'Valid DNS',
value: validCount,
type: 'number',
icon: 'lucide:Check',
color: '#22c55e',
},
{
id: 'issues',
title: 'Issues',
value: issueCount,
type: 'number',
icon: 'lucide:TriangleAlert',
color: issueCount > 0 ? '#ef4444' : '#22c55e',
},
{
id: 'dkim',
title: 'DKIM Active',
value: domains.filter((d) => d.dkim.publicKey).length,
type: 'number',
icon: 'lucide:KeyRound',
color: '#8b5cf6',
},
];
return html`
<dees-heading level="3">Email Domains</dees-heading>
<div class="emailDomainsContainer">
<dees-statsgrid
.tiles=${tiles}
.minTileWidth=${200}
.gridActions=${[
{
name: 'Refresh',
iconName: 'lucide:RefreshCw',
action: async () => {
await appstate.emailDomainsStatePart.dispatchAction(
appstate.fetchEmailDomainsAction,
null,
);
},
},
]}
></dees-statsgrid>
<dees-table
.heading1=${'Email Domains'}
.heading2=${'DKIM, SPF, DMARC and MX management'}
.data=${domains}
.showColumnFilters=${true}
.displayFunction=${(d: interfaces.data.IEmailDomain) => ({
Domain: d.domain,
Source: this.renderSourceBadge(d.linkedDomainId),
MX: this.renderDnsStatus(d.dnsStatus.mx),
SPF: this.renderDnsStatus(d.dnsStatus.spf),
DKIM: this.renderDnsStatus(d.dnsStatus.dkim),
DMARC: this.renderDnsStatus(d.dnsStatus.dmarc),
})}
.dataActions=${[
{
name: 'Add Email Domain',
iconName: 'lucide:plus',
type: ['header'] as any,
actionFunc: async () => {
await this.showCreateDialog();
},
},
{
name: 'Validate DNS',
iconName: 'lucide:search-check',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const d = actionData.item as interfaces.data.IEmailDomain;
await appstate.emailDomainsStatePart.dispatchAction(
appstate.validateEmailDomainAction,
d.id,
);
const { DeesToast } = await import('@design.estate/dees-catalog');
DeesToast.show({ message: `DNS validated for ${d.domain}`, type: 'success', duration: 2500 });
},
},
{
name: 'Provision DNS',
iconName: 'lucide:wand-sparkles',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const d = actionData.item as interfaces.data.IEmailDomain;
await appstate.emailDomainsStatePart.dispatchAction(
appstate.provisionEmailDomainDnsAction,
d.id,
);
const { DeesToast } = await import('@design.estate/dees-catalog');
DeesToast.show({ message: `DNS records provisioned for ${d.domain}`, type: 'success', duration: 2500 });
},
},
{
name: 'View DNS Records',
iconName: 'lucide:list',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const d = actionData.item as interfaces.data.IEmailDomain;
await this.showDnsRecordsDialog(d);
},
},
{
name: 'Delete',
iconName: 'lucide:trash2',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const d = actionData.item as interfaces.data.IEmailDomain;
await appstate.emailDomainsStatePart.dispatchAction(
appstate.deleteEmailDomainAction,
d.id,
);
},
},
]}
dataName="email domain"
></dees-table>
</div>
`;
}
private renderDnsStatus(status: interfaces.data.TDnsRecordStatus): TemplateResult {
return html`<span class="statusBadge ${status}">${status}</span>`;
}
private renderSourceBadge(linkedDomainId: string): TemplateResult {
const domain = this.domainsState.domains.find((d) => d.id === linkedDomainId);
if (!domain) return html`<span class="sourceBadge">unknown</span>`;
const label =
domain.source === 'dcrouter'
? 'dcrouter'
: this.domainsState.providers.find((p) => p.id === domain.providerId)?.name || 'provider';
return html`<span class="sourceBadge">${label}</span>`;
}
private async showCreateDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
const domainOptions = this.domainsState.domains.map((d) => ({
option: `${d.name} (${d.source})`,
key: d.id,
}));
DeesModal.createAndShow({
heading: 'Add Email Domain',
content: html`
<dees-form>
<dees-input-dropdown
.key=${'linkedDomainId'}
.label=${'Domain'}
.description=${'Select an existing DNS domain'}
.options=${domainOptions}
.required=${true}
></dees-input-dropdown>
<dees-input-text
.key=${'subdomain'}
.label=${'Subdomain'}
.description=${'Leave empty for bare domain, e.g. "mail" for mail.example.com'}
></dees-input-text>
<dees-input-text
.key=${'dkimSelector'}
.label=${'DKIM Selector'}
.description=${'Identifier used in DNS record name'}
.value=${'default'}
></dees-input-text>
<dees-input-dropdown
.key=${'dkimKeySize'}
.label=${'DKIM Key Size'}
.options=${[
{ option: '2048 (recommended)', key: '2048' },
{ option: '1024', key: '1024' },
{ option: '4096', key: '4096' },
]}
.selectedOption=${{ option: '2048 (recommended)', key: '2048' }}
></dees-input-dropdown>
<dees-input-checkbox
.key=${'rotateKeys'}
.label=${'Auto-rotate DKIM keys'}
.value=${false}
></dees-input-checkbox>
</dees-form>
`,
menuOptions: [
{ name: 'Cancel', action: async (m: any) => m.destroy() },
{
name: 'Create',
action: async (m: any) => {
const form = m.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
const linkedDomainId =
typeof data.linkedDomainId === 'object'
? data.linkedDomainId.key
: data.linkedDomainId;
const keySize =
typeof data.dkimKeySize === 'object'
? parseInt(data.dkimKeySize.key, 10)
: parseInt(data.dkimKeySize || '2048', 10);
const subdomain = data.subdomain?.trim() || undefined;
await appstate.emailDomainsStatePart.dispatchAction(
appstate.createEmailDomainAction,
{
linkedDomainId,
subdomain,
dkimSelector: data.dkimSelector || 'default',
dkimKeySize: keySize,
rotateKeys: Boolean(data.rotateKeys),
},
);
m.destroy();
},
},
],
});
}
private async showDnsRecordsDialog(emailDomain: interfaces.data.IEmailDomain) {
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
// Fetch required DNS records
let records: interfaces.data.IEmailDnsRecord[] = [];
try {
const response = await appstate.fetchEmailDomainDnsRecords(emailDomain.id);
records = response.records;
} catch {
records = [];
}
DeesModal.createAndShow({
heading: `DNS Records: ${emailDomain.domain}`,
content: html`
<dees-table
.data=${records}
.displayFunction=${(r: interfaces.data.IEmailDnsRecord) => ({
Type: r.type,
Name: r.name,
Value: r.value,
Status: html`<span class="statusBadge ${r.status}">${r.status}</span>`,
})}
.dataActions=${[
{
name: 'Copy Value',
iconName: 'lucide:copy',
type: ['inRow'] as any,
actionFunc: async (actionData: any) => {
const rec = actionData.item as interfaces.data.IEmailDnsRecord;
await navigator.clipboard.writeText(rec.value);
DeesToast.show({ message: 'Copied to clipboard', type: 'success', duration: 1500 });
},
},
]}
dataName="DNS record"
></dees-table>
`,
menuOptions: [
{
name: 'Auto-Provision All',
action: async (m: any) => {
await appstate.emailDomainsStatePart.dispatchAction(
appstate.provisionEmailDomainDnsAction,
emailDomain.id,
);
DeesToast.show({ message: 'DNS records provisioned', type: 'success', duration: 2500 });
m.destroy();
},
},
{ name: 'Close', action: async (m: any) => m.destroy() },
],
});
}
}

View File

@@ -37,25 +37,10 @@ export class OpsViewEmailSecurity extends DeesElement {
cssManager.defaultStyles,
viewHostCss,
css`
h2 {
margin: 32px 0 16px 0;
font-size: 24px;
font-weight: 600;
color: ${cssManager.bdTheme('#333', '#ccc')};
}
dees-statsgrid {
margin-bottom: 32px;
}
.securityCard {
background: ${cssManager.bdTheme('#fff', '#222')};
border: 1px solid ${cssManager.bdTheme('#e9ecef', '#333')};
border-radius: 8px;
padding: 24px;
position: relative;
overflow: hidden;
}
.actionButton {
margin-top: 16px;
.securityContainer {
display: flex;
flex-direction: column;
gap: 24px;
}
`,
];
@@ -113,48 +98,44 @@ export class OpsViewEmailSecurity extends DeesElement {
return html`
<dees-heading level="3">Email Security</dees-heading>
<dees-statsgrid
.tiles=${tiles}
.minTileWidth=${200}
></dees-statsgrid>
<div class="securityContainer">
<dees-statsgrid
.tiles=${tiles}
.minTileWidth=${200}
></dees-statsgrid>
<h2>Email Security Configuration</h2>
<div class="securityCard">
<dees-form>
<dees-input-checkbox
.key=${'enableSPF'}
.label=${'Enable SPF checking'}
.value=${true}
></dees-input-checkbox>
<dees-input-checkbox
.key=${'enableDKIM'}
.label=${'Enable DKIM validation'}
.value=${true}
></dees-input-checkbox>
<dees-input-checkbox
.key=${'enableDMARC'}
.label=${'Enable DMARC policy enforcement'}
.value=${true}
></dees-input-checkbox>
<dees-input-checkbox
.key=${'enableSpamFilter'}
.label=${'Enable spam filtering'}
.value=${true}
></dees-input-checkbox>
</dees-form>
<dees-button
class="actionButton"
type="highlighted"
@click=${() => this.saveEmailSecuritySettings()}
>
Save Settings
</dees-button>
<dees-settings
.heading=${'Security Configuration'}
.settingsFields=${[
{ key: 'spf', label: 'SPF checking', value: 'enabled' },
{ key: 'dkim', label: 'DKIM validation', value: 'enabled' },
{ key: 'dmarc', label: 'DMARC policy', value: 'enabled' },
{ key: 'spam', label: 'Spam filtering', value: 'enabled' },
]}
.actions=${[{ name: 'Edit', action: () => this.showEditSecurityDialog() }]}
></dees-settings>
</div>
`;
}
private async saveEmailSecuritySettings() {
// Config is read-only from the UI for now
alert('Email security settings are read-only. Update the dcrouter configuration file to change these settings.');
private async showEditSecurityDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Edit Security Configuration',
content: html`
<dees-form>
<dees-input-checkbox .key=${'enableSPF'} .label=${'SPF checking'} .value=${true}></dees-input-checkbox>
<dees-input-checkbox .key=${'enableDKIM'} .label=${'DKIM validation'} .value=${true}></dees-input-checkbox>
<dees-input-checkbox .key=${'enableDMARC'} .label=${'DMARC policy enforcement'} .value=${true}></dees-input-checkbox>
<dees-input-checkbox .key=${'enableSpamFilter'} .label=${'Spam filtering'} .value=${true}></dees-input-checkbox>
</dees-form>
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
These settings are read-only for now. Update the dcrouter configuration to change them.
</p>
`,
menuOptions: [
{ name: 'Close', action: async (modalArg: any) => modalArg.destroy() },
],
});
}
}

View File

@@ -323,6 +323,8 @@ export class OpsViewNetworkActivity extends DeesElement {
<!-- Requests Table -->
<dees-table
.data=${this.networkRequests}
.rowKey=${'id'}
.highlightUpdates=${'flash'}
.displayFunction=${(req: INetworkRequest) => ({
Time: new Date(req.timestamp).toLocaleTimeString(),
Protocol: html`<span class="protocolBadge ${req.protocol}">${req.protocol.toUpperCase()}</span>`,
@@ -595,6 +597,8 @@ export class OpsViewNetworkActivity extends DeesElement {
return html`
<dees-table
.data=${this.networkState.topIPs}
.rowKey=${'ip'}
.highlightUpdates=${'flash'}
.displayFunction=${(ipData: { ip: string; count: number }) => {
const bw = bandwidthByIP.get(ipData.ip);
return {
@@ -624,6 +628,8 @@ export class OpsViewNetworkActivity extends DeesElement {
return html`
<dees-table
.data=${backends}
.rowKey=${'backend'}
.highlightUpdates=${'flash'}
.displayFunction=${(item: interfaces.data.IBackendInfo) => {
const totalErrors = item.connectErrors + item.handshakeErrors + item.requestErrors;
const protocolClass = item.protocol.toLowerCase().replace(/[^a-z0-9]/g, '');
@@ -724,37 +730,24 @@ export class OpsViewNetworkActivity extends DeesElement {
this.requestsPerSecHistory.shift();
}
// Only update if connections changed significantly
const newConnectionCount = this.networkState.connections.length;
const oldConnectionCount = this.networkRequests.length;
// Check if we need to update the network requests array
const shouldUpdate = newConnectionCount !== oldConnectionCount ||
newConnectionCount === 0 ||
(newConnectionCount > 0 && this.networkRequests.length === 0);
if (shouldUpdate) {
// Convert connection data to network requests format
if (newConnectionCount > 0) {
this.networkRequests = this.networkState.connections.map((conn, index) => ({
id: conn.id,
timestamp: conn.startTime,
method: 'GET', // Default method for proxy connections
url: '/',
hostname: conn.remoteAddress,
port: conn.protocol === 'https' ? 443 : 80,
protocol: conn.protocol === 'https' || conn.protocol === 'http' ? conn.protocol : 'tcp',
statusCode: conn.state === 'connected' ? 200 : undefined,
duration: Date.now() - conn.startTime,
bytesIn: conn.bytesReceived,
bytesOut: conn.bytesSent,
remoteIp: conn.remoteAddress,
route: 'proxy',
}));
} else {
this.networkRequests = [];
}
}
// Reassign unconditionally so dees-table's flash diff can compare per-cell
// values against the previous snapshot. Row identity is preserved via
// rowKey='id', so DOM nodes are reused across ticks.
this.networkRequests = this.networkState.connections.map((conn) => ({
id: conn.id,
timestamp: conn.startTime,
method: 'GET', // Default method for proxy connections
url: '/',
hostname: conn.remoteAddress,
port: conn.protocol === 'https' ? 443 : 80,
protocol: conn.protocol === 'https' || conn.protocol === 'http' ? conn.protocol : 'tcp',
statusCode: conn.state === 'connected' ? 200 : undefined,
duration: Date.now() - conn.startTime,
bytesIn: conn.bytesReceived,
bytesOut: conn.bytesSent,
remoteIp: conn.remoteAddress,
route: 'proxy',
}));
// Load server-side throughput history into chart (once)
if (!this.historyLoaded && this.networkState.throughputHistory && this.networkState.throughputHistory.length > 0) {

View File

@@ -220,6 +220,8 @@ export class OpsViewRemoteIngress extends DeesElement {
.heading1=${'Edge Nodes'}
.heading2=${'Manage remote ingress edge registrations'}
.data=${this.riState.edges}
.rowKey=${'id'}
.highlightUpdates=${'flash'}
.showColumnFilters=${true}
.displayFunction=${(edge: interfaces.data.IRemoteIngress) => ({
name: edge.name,
@@ -241,9 +243,9 @@ export class OpsViewRemoteIngress extends DeesElement {
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name'} .required=${true}></dees-input-text>
<dees-input-text .key=${'listenPorts'} .label=${'Additional Manual Ports (comma-separated, optional)'}></dees-input-text>
<dees-input-text .key=${'listenPorts'} .label=${'Manual Ports'} .description=${'Comma-separated port numbers, optional'}></dees-input-text>
<dees-input-checkbox .key=${'autoDerivePorts'} .label=${'Auto-derive ports from routes'} .value=${true}></dees-input-checkbox>
<dees-input-text .key=${'tags'} .label=${'Tags (comma-separated, optional)'}></dees-input-text>
<dees-input-text .key=${'tags'} .label=${'Tags'} .description=${'Comma-separated, optional'}></dees-input-text>
</dees-form>
`,
menuOptions: [
@@ -318,9 +320,9 @@ export class OpsViewRemoteIngress extends DeesElement {
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name'} .value=${edge.name}></dees-input-text>
<dees-input-text .key=${'listenPorts'} .label=${'Manual Ports (comma-separated)'} .value=${(edge.listenPorts || []).join(', ')}></dees-input-text>
<dees-input-text .key=${'listenPorts'} .label=${'Manual Ports'} .description=${'Comma-separated port numbers'} .value=${(edge.listenPorts || []).join(', ')}></dees-input-text>
<dees-input-checkbox .key=${'autoDerivePorts'} .label=${'Auto-derive ports from routes'} .value=${edge.autoDerivePorts !== false}></dees-input-checkbox>
<dees-input-text .key=${'tags'} .label=${'Tags (comma-separated)'} .value=${(edge.tags || []).join(', ')}></dees-input-text>
<dees-input-text .key=${'tags'} .label=${'Tags'} .description=${'Comma-separated'} .value=${(edge.tags || []).join(', ')}></dees-input-text>
</dees-form>
`,
menuOptions: [

View File

@@ -473,19 +473,19 @@ export class OpsViewRoutes extends DeesElement {
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Route Name'} .value=${route.name || ''} .required=${true}></dees-input-text>
<dees-input-text .key=${'ports'} .label=${'Ports (comma-separated)'} .value=${currentPorts} .required=${true}></dees-input-text>
<dees-input-text .key=${'ports'} .label=${'Ports'} .description=${'Comma-separated, e.g. 80, 443'} .value=${currentPorts} .required=${true}></dees-input-text>
<dees-input-list .key=${'domains'} .label=${'Domains'} .placeholder=${'Add domain...'} .value=${currentDomains}></dees-input-list>
<dees-input-text .key=${'priority'} .label=${'Priority (higher = matched first)'} .value=${route.priority != null ? String(route.priority) : ''}></dees-input-text>
<dees-input-text .key=${'priority'} .label=${'Priority'} .description=${'Higher values are matched first'} .value=${route.priority != null ? String(route.priority) : ''}></dees-input-text>
<dees-input-dropdown .key=${'sourceProfileRef'} .label=${'Source Profile'} .options=${profileOptions} .selectedOption=${profileOptions.find((o) => o.key === (merged.metadata?.sourceProfileRef || '')) || null}></dees-input-dropdown>
<dees-input-dropdown .key=${'networkTargetRef'} .label=${'Network Target'} .options=${targetOptions} .selectedOption=${targetOptions.find((o) => o.key === (merged.metadata?.networkTargetRef || '')) || null}></dees-input-dropdown>
<dees-input-text .key=${'targetHost'} .label=${'Target Host (if no target selected)'} .value=${currentTargetHost}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port (if no target selected)'} .value=${currentTargetPort}></dees-input-text>
<dees-input-text .key=${'targetHost'} .label=${'Target Host'} .description=${'Used when no network target is selected'} .value=${currentTargetHost}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port'} .description=${'Used when no network target is selected'} .value=${currentTargetPort}></dees-input-text>
<dees-input-dropdown .key=${'tlsMode'} .label=${'TLS Mode'} .options=${tlsModeOptions} .selectedOption=${tlsModeOptions.find((o) => o.key === currentTlsMode) || tlsModeOptions[0]}></dees-input-dropdown>
<div class="tlsCertificateGroup" style="display: ${needsCert ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-dropdown .key=${'tlsCertificate'} .label=${'Certificate'} .options=${tlsCertOptions} .selectedOption=${tlsCertOptions.find((o) => o.key === currentTlsCert) || tlsCertOptions[0]}></dees-input-dropdown>
<div class="tlsCustomCertGroup" style="display: ${needsCert && isCustom ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'tlsCertKey'} .label=${'Private Key (PEM)'} .value=${currentCustomKey}></dees-input-text>
<dees-input-text .key=${'tlsCertCert'} .label=${'Certificate (PEM)'} .value=${currentCustomCert}></dees-input-text>
<dees-input-text .key=${'tlsCertKey'} .label=${'Private Key'} .description=${'PEM-encoded private key'} .value=${currentCustomKey}></dees-input-text>
<dees-input-text .key=${'tlsCertCert'} .label=${'Certificate'} .description=${'PEM-encoded certificate'} .value=${currentCustomCert}></dees-input-text>
</div>
</div>
</dees-form>
@@ -607,19 +607,19 @@ export class OpsViewRoutes extends DeesElement {
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Route Name'} .required=${true}></dees-input-text>
<dees-input-text .key=${'ports'} .label=${'Ports (comma-separated)'} .required=${true}></dees-input-text>
<dees-input-text .key=${'ports'} .label=${'Ports'} .description=${'Comma-separated, e.g. 80, 443'} .required=${true}></dees-input-text>
<dees-input-list .key=${'domains'} .label=${'Domains'} .placeholder=${'Add domain...'}></dees-input-list>
<dees-input-text .key=${'priority'} .label=${'Priority (higher = matched first)'}></dees-input-text>
<dees-input-text .key=${'priority'} .label=${'Priority'} .description=${'Higher values are matched first'}></dees-input-text>
<dees-input-dropdown .key=${'sourceProfileRef'} .label=${'Source Profile'} .options=${profileOptions}></dees-input-dropdown>
<dees-input-dropdown .key=${'networkTargetRef'} .label=${'Network Target'} .options=${targetOptions}></dees-input-dropdown>
<dees-input-text .key=${'targetHost'} .label=${'Target Host (if no target selected)'} .value=${'localhost'}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port (if no target selected)'}></dees-input-text>
<dees-input-text .key=${'targetHost'} .label=${'Target Host'} .description=${'Used when no network target is selected'} .value=${'localhost'}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port'} .description=${'Used when no network target is selected'}></dees-input-text>
<dees-input-dropdown .key=${'tlsMode'} .label=${'TLS Mode'} .options=${tlsModeOptions} .selectedOption=${tlsModeOptions[0]}></dees-input-dropdown>
<div class="tlsCertificateGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-dropdown .key=${'tlsCertificate'} .label=${'Certificate'} .options=${tlsCertOptions} .selectedOption=${tlsCertOptions[0]}></dees-input-dropdown>
<div class="tlsCustomCertGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'tlsCertKey'} .label=${'Private Key (PEM)'}></dees-input-text>
<dees-input-text .key=${'tlsCertCert'} .label=${'Certificate (PEM)'}></dees-input-text>
<dees-input-text .key=${'tlsCertKey'} .label=${'Private Key'} .description=${'PEM-encoded private key'}></dees-input-text>
<dees-input-text .key=${'tlsCertCert'} .label=${'Certificate'} .description=${'PEM-encoded certificate'}></dees-input-text>
</div>
</div>
</dees-form>

View File

@@ -176,7 +176,7 @@ export class OpsViewTargetProfiles extends DeesElement {
<dees-input-text .key=${'name'} .label=${'Name'} .required=${true}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'}></dees-input-text>
<dees-input-list .key=${'domains'} .label=${'Domains'} .placeholder=${'e.g. *.example.com'} .allowFreeform=${true}></dees-input-list>
<dees-input-list .key=${'targets'} .label=${'Targets (ip:port)'} .placeholder=${'e.g. 10.0.0.1:443'} .allowFreeform=${true}></dees-input-list>
<dees-input-list .key=${'targets'} .label=${'Targets'} .description=${'Format: ip:port, e.g. 10.0.0.1:443'} .placeholder=${'e.g. 10.0.0.1:443'} .allowFreeform=${true}></dees-input-list>
<dees-input-list .key=${'routeRefs'} .label=${'Route Refs'} .placeholder=${'Type to search routes...'} .candidates=${routeCandidates} .allowFreeform=${true}></dees-input-list>
</dees-form>
`,
@@ -235,7 +235,7 @@ export class OpsViewTargetProfiles extends DeesElement {
<dees-input-text .key=${'name'} .label=${'Name'} .value=${profile.name}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'} .value=${profile.description || ''}></dees-input-text>
<dees-input-list .key=${'domains'} .label=${'Domains'} .placeholder=${'e.g. *.example.com'} .allowFreeform=${true} .value=${currentDomains}></dees-input-list>
<dees-input-list .key=${'targets'} .label=${'Targets (ip:port)'} .placeholder=${'e.g. 10.0.0.1:443'} .allowFreeform=${true} .value=${currentTargets}></dees-input-list>
<dees-input-list .key=${'targets'} .label=${'Targets'} .description=${'Format: ip:port, e.g. 10.0.0.1:443'} .placeholder=${'e.g. 10.0.0.1:443'} .allowFreeform=${true} .value=${currentTargets}></dees-input-list>
<dees-input-list .key=${'routeRefs'} .label=${'Route Refs'} .placeholder=${'Type to search routes...'} .candidates=${routeCandidates} .allowFreeform=${true} .value=${currentRouteRefs}></dees-input-list>
</dees-form>
`,

View File

@@ -305,6 +305,8 @@ export class OpsViewVpn extends DeesElement {
.heading1=${'VPN Clients'}
.heading2=${'Manage WireGuard and SmartVPN client registrations'}
.data=${clients}
.rowKey=${'clientId'}
.highlightUpdates=${'flash'}
.showColumnFilters=${true}
.displayFunction=${(client: interfaces.data.IVpnClient) => {
const conn = this.getConnectedInfo(client);
@@ -369,8 +371,8 @@ export class OpsViewVpn extends DeesElement {
</div>
<dees-input-checkbox .key=${'allowAdditionalAcls'} .label=${'Allow additional ACLs'} .value=${false}></dees-input-checkbox>
<div class="aclGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'destinationAllowList'} .label=${'Destination Allow List (comma-separated IPs/CIDRs)'}></dees-input-text>
<dees-input-text .key=${'destinationBlockList'} .label=${'Destination Block List (comma-separated IPs/CIDRs)'}></dees-input-text>
<dees-input-text .key=${'destinationAllowList'} .label=${'Destination Allow List'} .description=${'Comma-separated IPs or CIDRs'}></dees-input-text>
<dees-input-text .key=${'destinationBlockList'} .label=${'Destination Block List'} .description=${'Comma-separated IPs or CIDRs'}></dees-input-text>
</div>
</dees-form>
`,
@@ -679,8 +681,8 @@ export class OpsViewVpn extends DeesElement {
</div>
<dees-input-checkbox .key=${'allowAdditionalAcls'} .label=${'Allow additional ACLs'} .value=${currentAllowAcls}></dees-input-checkbox>
<div class="aclGroup" style="display: ${currentAllowAcls ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'destinationAllowList'} .label=${'Destination Allow List (comma-separated IPs/CIDRs)'} .value=${currentAllowList}></dees-input-text>
<dees-input-text .key=${'destinationBlockList'} .label=${'Destination Block List (comma-separated IPs/CIDRs)'} .value=${currentBlockList}></dees-input-text>
<dees-input-text .key=${'destinationAllowList'} .label=${'Destination Allow List'} .description=${'Comma-separated IPs or CIDRs'} .value=${currentAllowList}></dees-input-text>
<dees-input-text .key=${'destinationBlockList'} .label=${'Destination Block List'} .description=${'Comma-separated IPs or CIDRs'} .value=${currentBlockList}></dees-input-text>
</div>
</dees-form>
`,

View File

@@ -32,6 +32,7 @@ import { OpsViewVpn } from './network/ops-view-vpn.js';
// Email group
import { OpsViewEmails } from './email/ops-view-emails.js';
import { OpsViewEmailSecurity } from './email/ops-view-email-security.js';
import { OpsViewEmailDomains } from './email/ops-view-email-domains.js';
// Access group
import { OpsViewApiTokens } from './access/ops-view-apitokens.js';
@@ -108,6 +109,7 @@ export class OpsDashboard extends DeesElement {
subViews: [
{ slug: 'log', name: 'Email Log', iconName: 'lucide:scrollText', element: OpsViewEmails },
{ slug: 'security', name: 'Email Security', iconName: 'lucide:shieldCheck', element: OpsViewEmailSecurity },
{ slug: 'domains', name: 'Email Domains', iconName: 'lucide:globe', element: OpsViewEmailDomains },
],
},
{

View File

@@ -10,7 +10,7 @@ const flatViews = ['logs'] as const;
const subviewMap: Record<string, readonly string[]> = {
overview: ['stats', 'configuration'] as const,
network: ['activity', 'routes', 'sourceprofiles', 'networktargets', 'targetprofiles', 'remoteingress', 'vpn'] as const,
email: ['log', 'security'] as const,
email: ['log', 'security', 'domains'] as const,
access: ['apitokens', 'users'] as const,
security: ['overview', 'blocked', 'authentication'] as const,
domains: ['providers', 'domains', 'dns', 'certificates'] as const,