Compare commits

..

32 Commits

Author SHA1 Message Date
746fbb15e6 v12.6.2
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-03 10:48:26 +00:00
415065b246 fix(deps): bump @design.estate/dees-catalog to ^3.51.1 2026-04-03 10:48:26 +00:00
30aeef7bbd v12.6.1
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-03 10:15:10 +00:00
dba1c70fa7 fix(repo): no changes to commit 2026-04-03 10:15:10 +00:00
f9cfb3d36b v12.6.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-03 10:14:52 +00:00
43b92b784d feat(certificates): add confirmation before force renewing valid certificates from the certificate actions menu 2026-04-03 10:14:52 +00:00
b62a322c54 v12.5.2
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-03 08:19:02 +00:00
a3a64e9a02 fix(repo): no changes to commit 2026-04-03 08:19:02 +00:00
491e51f40b v12.5.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-03 08:18:28 +00:00
b46247d9cb fix(ops-view-network): centralize traffic chart timing constants for consistent rolling window updates 2026-04-03 08:18:28 +00:00
9c0e46ff4e v12.5.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-02 22:55:57 +00:00
f62bc4a526 feat(ops-view-routes): add priority support and list-based domain editing for routes 2026-04-02 22:55:57 +00:00
8f23600ec1 v12.4.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-02 22:37:49 +00:00
141f185fbf feat(routes): add route edit and delete actions to the ops routes view 2026-04-02 22:37:49 +00:00
6f4a5f19e7 v12.3.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-02 20:31:08 +00:00
9d8354e58f feat(docs,ops-dashboard): document unified database and reusable security profile and network target management 2026-04-02 20:31:08 +00:00
947637eed7 v12.2.6
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-02 18:49:52 +00:00
5202c2ea27 fix(ops-ui): improve operations table actions and modal form handling for profiles and network targets 2026-04-02 18:49:52 +00:00
6684dc43da v12.2.5
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-02 17:59:51 +00:00
04ec387ce5 fix(dcrouter): sync allowed tunnel edges when merged routes change 2026-04-02 17:59:51 +00:00
f145798f39 v12.2.4
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-02 17:27:05 +00:00
55f5465a9a fix(routes): support profile and target metadata in route creation and refresh remote ingress routes after config initialization 2026-04-02 17:27:05 +00:00
0577f45ced v12.2.3
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-02 16:27:35 +00:00
7d23617f15 fix(repo): no changes to commit 2026-04-02 16:27:35 +00:00
02415f8c53 v12.2.2
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-02 16:26:24 +00:00
73a47e5a97 fix(route-config): sync applied routes to remote ingress manager after route updates 2026-04-02 16:26:24 +00:00
5e980812b0 v12.2.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-02 16:10:35 +00:00
76e9735cde fix(web-ui): align dees-table props and action handlers in security profile and network target views 2026-04-02 16:10:35 +00:00
8bfc0c2fa2 v12.2.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-02 15:44:36 +00:00
55699f6618 feat(config): add reusable security profiles and network targets with route reference resolution 2026-04-02 15:44:36 +00:00
6344c2deae v12.1.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-01 05:13:02 +00:00
c1452131fa feat(vpn): add per-client routing controls and bridge forwarding support for VPN clients 2026-04-01 05:13:01 +00:00
47 changed files with 3991 additions and 220 deletions

View File

@@ -1 +1,7 @@
node_modules/
.nogit/
.git/
.playwright-mcp/
.vscode/
test/
test_watch/

View File

@@ -1,5 +1,110 @@
# Changelog
## 2026-04-03 - 12.6.2 - fix(deps)
bump @design.estate/dees-catalog to ^3.51.1
- Updates @design.estate/dees-catalog from ^3.51.0 to ^3.51.1 in package.json
## 2026-04-03 - 12.6.1 - fix(repo)
no changes to commit
## 2026-04-03 - 12.6.0 - feat(certificates)
add confirmation before force renewing valid certificates from the certificate actions menu
- Expose the Reprovision action in the certificate context menu
- Prompt for confirmation when reprovisioning a certificate that is still valid
- Update dees-catalog and @types/node dependencies
## 2026-04-03 - 12.5.2 - fix(repo)
no changes to commit
## 2026-04-03 - 12.5.1 - fix(ops-view-network)
centralize traffic chart timing constants for consistent rolling window updates
- Defines shared constants for the chart window, update interval, and maximum buffered data points
- Replaces hardcoded traffic history sizes and timer intervals with derived values across initialization, history loading, and live updates
- Keeps the chart rolling window configuration aligned with the in-memory traffic buffer
## 2026-04-02 - 12.5.0 - feat(ops-view-routes)
add priority support and list-based domain editing for routes
- Adds a priority field to route create and edit forms so route matching order can be configured.
- Replaces comma-separated domain text input with a list-based domain editor and updates form handling to persist domains as arrays.
## 2026-04-02 - 12.4.0 - feat(routes)
add route edit and delete actions to the ops routes view
- introduces an update route action in web app state and refreshes merged routes after changes
- adds edit and delete handlers with modal-based confirmation and route form inputs for programmatic routes
- enables realtime chart window configuration in network and overview dashboards
- bumps @serve.zone/catalog to ^2.11.0
## 2026-04-02 - 12.3.0 - feat(docs,ops-dashboard)
document unified database and reusable security profile and network target management
- Update project and interface documentation to replace separate storage/cache configuration with a unified database model
- Document new security profile and network target APIs, data models, and dashboard capabilities
- Add a global dashboard warning when the database is disabled so unavailable management features are clearly indicated
- Bump @design.estate/dees-catalog and @serve.zone/catalog to support the updated dashboard experience
## 2026-04-02 - 12.2.6 - fix(ops-ui)
improve operations table actions and modal form handling for profiles and network targets
- adds section headings for the Security Profiles and Network Targets views
- updates edit and delete actions to support in-row table actions in addition to context menus
- makes create and edit dialogs query forms safely from modal content and adds early returns when forms are unavailable
- enables the database configuration in the development watch server
## 2026-04-02 - 12.2.5 - fix(dcrouter)
sync allowed tunnel edges when merged routes change
- Triggers tunnelManager.syncAllowedEdges() after route updates are applied
- Keeps derived ports in the Rust hub binary aligned with merged route changes
## 2026-04-02 - 12.2.4 - fix(routes)
support profile and target metadata in route creation and refresh remote ingress routes after config initialization
- Re-applies routes to the remote ingress manager after config managers finish to avoid missing DB-backed routes during initialization
- Fetches profiles and targets when opening or authenticating into the routes view so route creation dropdowns are populated
- Includes selected security profile and network target metadata when creating programmatic routes and displays that metadata in route details
- Improves security profile forms by switching IP allow/block lists to list inputs instead of comma-separated text fields
- Updates UI dependencies including smartdb, dees-catalog, and serve.zone catalog
## 2026-04-02 - 12.2.3 - fix(repo)
no changes to commit
## 2026-04-02 - 12.2.2 - fix(route-config)
sync applied routes to remote ingress manager after route updates
- add an optional route-applied callback to RouteConfigManager
- forward merged SmartProxy routes to RemoteIngressManager whenever routes are updated
## 2026-04-02 - 12.2.1 - fix(web-ui)
align dees-table props and action handlers in security profile and network target views
- replace deprecated table heading prop with heading1 and heading2 in both admin views
- rename table action callbacks from action to actionFunc for create, refresh, edit, and delete actions
## 2026-04-02 - 12.2.0 - feat(config)
add reusable security profiles and network targets with route reference resolution
- introduces persisted security profile and network target models plus typed OpsServer CRUD and usage endpoints
- adds route metadata support so routes can reference profiles and targets and be re-resolved after updates
- supports optional seeding of default profiles and targets when the database is empty
- adds dashboard views and state management for managing security profiles and network targets
- includes tests for reference resolver behavior and API fallback/auth handling
## 2026-04-01 - 12.1.0 - feat(vpn)
add per-client routing controls and bridge forwarding support for VPN clients
- adds persisted per-client VPN settings for SmartProxy enforcement, destination allow/block lists, host IP assignment, DHCP/static IP selection, and VLAN options
- passes new VPN routing and bridge configuration through request handlers, app state, and the ops UI for creating, editing, and viewing clients
- supports bridge and hybrid forwarding modes in the VPN manager, including auto-upgrading to hybrid when clients request host IP access
- updates smartvpn and dees-catalog dependencies to support the new VPN forwarding capabilities
## 2026-03-31 - 12.0.0 - BREAKING CHANGE(db)
replace StorageManager and CacheDb with a unified smartdata-backed database layer

View File

@@ -1,7 +1,7 @@
{
"name": "@serve.zone/dcrouter",
"private": false,
"version": "12.0.0",
"version": "12.6.2",
"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.0"
"@types/node": "^25.5.1"
},
"dependencies": {
"@api.global/typedrequest": "^3.3.0",
@@ -35,14 +35,14 @@
"@api.global/typedserver": "^8.4.6",
"@api.global/typedsocket": "^4.1.2",
"@apiclient.xyz/cloudflare": "^7.1.0",
"@design.estate/dees-catalog": "^3.49.0",
"@design.estate/dees-catalog": "^3.51.1",
"@design.estate/dees-element": "^2.2.4",
"@push.rocks/lik": "^6.4.0",
"@push.rocks/projectinfo": "^5.1.0",
"@push.rocks/qenv": "^6.1.3",
"@push.rocks/smartacme": "^9.3.1",
"@push.rocks/smartdata": "^7.1.3",
"@push.rocks/smartdb": "^2.0.0",
"@push.rocks/smartdb": "^2.1.1",
"@push.rocks/smartdns": "^7.9.0",
"@push.rocks/smartfs": "^1.5.0",
"@push.rocks/smartguard": "^3.1.0",
@@ -59,9 +59,9 @@
"@push.rocks/smartrx": "^3.0.10",
"@push.rocks/smartstate": "^2.3.0",
"@push.rocks/smartunique": "^3.0.9",
"@push.rocks/smartvpn": "1.17.1",
"@push.rocks/smartvpn": "1.19.1",
"@push.rocks/taskbuffer": "^8.0.2",
"@serve.zone/catalog": "^2.9.0",
"@serve.zone/catalog": "^2.11.0",
"@serve.zone/interfaces": "^5.3.0",
"@serve.zone/remoteingress": "^4.15.3",
"@tsclass/tsclass": "^9.5.0",

200
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.49.0
version: 3.49.0(@tiptap/pm@2.27.2)
specifier: ^3.51.1
version: 3.51.1(@tiptap/pm@2.27.2)
'@design.estate/dees-element':
specifier: ^2.2.4
version: 2.2.4
@@ -45,8 +45,8 @@ importers:
specifier: ^7.1.3
version: 7.1.3(socks@2.8.7)
'@push.rocks/smartdb':
specifier: ^2.0.0
version: 2.0.0
specifier: ^2.1.1
version: 2.1.1(@tiptap/pm@2.27.2)
'@push.rocks/smartdns':
specifier: ^7.9.0
version: 7.9.0
@@ -96,14 +96,14 @@ importers:
specifier: ^3.0.9
version: 3.0.9
'@push.rocks/smartvpn':
specifier: 1.17.1
version: 1.17.1
specifier: 1.19.1
version: 1.19.1
'@push.rocks/taskbuffer':
specifier: ^8.0.2
version: 8.0.2
'@serve.zone/catalog':
specifier: ^2.9.0
version: 2.9.0(@tiptap/pm@2.27.2)
specifier: ^2.11.0
version: 2.11.0(@tiptap/pm@2.27.2)
'@serve.zone/interfaces':
specifier: ^5.3.0
version: 5.3.0
@@ -142,8 +142,8 @@ importers:
specifier: ^3.3.2
version: 3.3.2(@tiptap/pm@2.27.2)
'@types/node':
specifier: ^25.5.0
version: 25.5.0
specifier: ^25.5.1
version: 25.5.1
packages:
@@ -350,8 +350,8 @@ packages:
'@configvault.io/interfaces@1.0.17':
resolution: {integrity: sha512-bEcCUR2VBDJsTin8HQh8Uw/mlYl2v8A3jMIaQ+MTB9Hrqd6CZL2dL7iJdWyFl/3EIX+LDxWFR+Oq7liIq7w+1Q==}
'@design.estate/dees-catalog@3.49.0':
resolution: {integrity: sha512-ZtHroyBZekv+jVSDmtGOzoGVI+EA55kd5EcSsNmUByxN3UMcFFeg62QRNzm3RHpz01u1Zfynm0bN9E44pk6FDQ==}
'@design.estate/dees-catalog@3.51.1':
resolution: {integrity: sha512-kBg5W9IuAaGau7LnrP2DN0RMDCcN78ttAA6h3MMDcG3P0247TVCKbxC1vxQjIaQYyYwcRebruJJx2e7VaMuwqQ==}
'@design.estate/dees-comms@1.0.30':
resolution: {integrity: sha512-KchMlklJfKAjQiJiR0xmofXtQ27VgZtBIxcMwPE9d+h3jJRv+lPZxzBQVOM0eyM0uS44S5vJMZ11IeV4uDXSHg==}
@@ -359,6 +359,9 @@ packages:
'@design.estate/dees-domtools@2.5.3':
resolution: {integrity: sha512-E30vu4Cl49nSQAFlazT2Eo9VVR3VG3RGc2NLmVe7i8NMC/Sm2HQisXlpKMZYBOoY8YwdG8W2MiXaD0lbGyibCw==}
'@design.estate/dees-domtools@2.5.4':
resolution: {integrity: sha512-IGyVKl1XMXHVCpPQXX6wSnGbD4S2Q1XkJCuuXZotu4Q86HTiALyfyZi0RouCKv3zxCSMvZHpFWVoh2DgF/3R3g==}
'@design.estate/dees-element@2.2.4':
resolution: {integrity: sha512-O9cA6flBMMd+pBwMQrZXwAWel9yVxgokolb+Em6gvkXxPJ0P/B5UDn4Vc2d4ts3ta55PTBm+l2dPeDVGx/bl7Q==}
@@ -1138,8 +1141,8 @@ packages:
'@push.rocks/smartdata@7.1.3':
resolution: {integrity: sha512-7vQJ9pdRk450yn2m9tmGPdSRlQVmxFPZjHD4sGYsfqCQPg+GLFusu+H16zpf+jKzAq4F2ZBMPaYymJHXvXiVcw==}
'@push.rocks/smartdb@2.0.0':
resolution: {integrity: sha512-RGaXGOS+5c7Hru2XwoyavQuoZqrfIzUfF/AnnVA0GYOrj4P2S89fngp8QDczVyZq/IbkByYXz59foQmN/WDlWA==}
'@push.rocks/smartdb@2.1.1':
resolution: {integrity: sha512-bm+xYpuzSgS+EacNP3NppwNvpw9OZN3gmtVUgBdqyLLKYX0329bDN5X63V6vdrglFBV/+MKox43l8BQBwVdfjw==}
'@push.rocks/smartdelay@3.0.5':
resolution: {integrity: sha512-mUuI7kj2f7ztjpic96FvRIlf2RsKBa5arw81AHNsndbxO6asRcxuWL8dTVxouEIK8YsBUlj0AsrCkHhMbLQdHw==}
@@ -1339,8 +1342,8 @@ packages:
'@push.rocks/smartversion@3.0.5':
resolution: {integrity: sha512-8MZSo1yqyaKxKq0Q5N188l4un++9GFWVbhCAX5mXJwewZHn97ujffTeL+eOQYpWFTEpUhaq1QhL4NhqObBCt1Q==}
'@push.rocks/smartvpn@1.17.1':
resolution: {integrity: sha512-oTOxNUrh+doL9AocgPnMbcYZKrWJhCeuqNotu1RfiteIV9DDdznvA+cl3nOgxD/ImUYrFPz6PUp5BEMogWcS8Q==}
'@push.rocks/smartvpn@1.19.1':
resolution: {integrity: sha512-zvC/rrba1tZcXzzzrhX97BEUN6smo1KcqcULu6ZAGpDNhR7c5PU8oWwFxIy33UdDf5NLActkS0L3dq42sGB8nw==}
'@push.rocks/smartwatch@6.4.0':
resolution: {integrity: sha512-KDswRgE/siBmZRCsRA07MtW5oF4c9uQEBkwTGPIWneHzksbCDsvs/7agKFEL7WnNifLNwo8w1K1qoiVWkX1fvw==}
@@ -1580,8 +1583,8 @@ packages:
'@selderee/plugin-htmlparser2@0.11.0':
resolution: {integrity: sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==}
'@serve.zone/catalog@2.9.0':
resolution: {integrity: sha512-7FgwS44pD/DFVj29jS0Kwwyn1i5h8cf4/yWMBEY8+8GO70ab3QctbcKMu+BVa1G3gIrpLqhpmxLFDoeL/zDnQA==}
'@serve.zone/catalog@2.11.0':
resolution: {integrity: sha512-4DFDewp1PFRhw5P+yQAoAw+i6gG2lfR3h+uPgbNxB5jCfW14eNDXi3nuwTMBQWRHL9jv8o0BokASjV9A0+q66g==}
'@serve.zone/interfaces@5.3.0':
resolution: {integrity: sha512-venO7wtDR9ixzD9NhdERBGjNKbFA5LL0yHw4eqGh0UpmvtXVc3SFG0uuHDilOKMZqZ8bttV88qVsFy1aSTJrtA==}
@@ -2047,11 +2050,11 @@ packages:
'@types/node@18.19.130':
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
'@types/node@22.19.15':
resolution: {integrity: sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==}
'@types/node@22.19.16':
resolution: {integrity: sha512-K6csxIjY+9RoDxdP6/wzaJzXaCf4znBz0/y0rrQDsbqmzQ5QFsOjubbsYWZhj6ZCgz3mjlyDZS+EJkhA9jWl9Q==}
'@types/node@25.5.0':
resolution: {integrity: sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==}
'@types/node@25.5.1':
resolution: {integrity: sha512-lgrR3HRNQdTEeeXBnLURFO4JIIbpcVcMlLM9IG0jsNRTRNSbMkm9S2hyhxhnokke1NM25Dr9QghgeB5PQKolrw==}
'@types/qrcode@1.5.6':
resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
@@ -2148,9 +2151,6 @@ packages:
any-base@1.1.0:
resolution: {integrity: sha512-uMgjozySS8adZZYePpaWs8cxB9/kdzmpX6SgJZ+wbz1K5eYk5QMYDVJaZKhxyIHUdnnJkfR7SVgStgH7LkGUyg==}
apexcharts@5.10.4:
resolution: {integrity: sha512-gt0VUqZ2+mr25ScbUcKZgJr96jKYm4vjOcxEWCEh/E5F4dWqhyo3dBhPRvNNnkKiWxkMd2cBwj3ZYH3rK39fkA==}
argparse@1.0.10:
resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==}
@@ -2625,6 +2625,9 @@ packages:
resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}
engines: {node: '>=18'}
fancy-canvas@2.1.0:
resolution: {integrity: sha512-nifxXJ95JNLFR2NgRV4/MxVP45G9909wJTEKz5fg/TZS20JJZA6hfgRVh/bC9bwl2zBtBNcYPjiBE4njQHVBwQ==}
fast-deep-equal@3.1.3:
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
@@ -3022,6 +3025,9 @@ packages:
libqp@2.1.1:
resolution: {integrity: sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==}
lightweight-charts@5.1.0:
resolution: {integrity: sha512-jEAYR4ODYeyNZcWUigsoLTl52rbPmgXnvd5FLIv/ZoA/2sSDw63YKnef8n4yhzum7W926yHeFwlm7ididKb7YQ==}
lines-and-columns@1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
@@ -3691,11 +3697,11 @@ packages:
prosemirror-state: ^1.4.2
prosemirror-view: ^1.33.8
prosemirror-transform@1.11.0:
resolution: {integrity: sha512-4I7Ce4KpygXb9bkiPS3hTEk4dSHorfRw8uI0pE8IhxlK2GXsqv5tIA7JUSxtSu7u8APVOTtbUBxTmnHIxVkIJw==}
prosemirror-transform@1.12.0:
resolution: {integrity: sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==}
prosemirror-view@1.41.7:
resolution: {integrity: sha512-jUwKNCEIGiqdvhlS91/2QAg21e4dfU5bH2iwmSDQeosXJgKF7smG0YSplOWK0cjSNgIqXe7VXqo7EIfUFJdt3w==}
prosemirror-view@1.41.8:
resolution: {integrity: sha512-TnKDdohEatgyZNGCDWIdccOHXhYloJwbwU+phw/a23KBvJIR9lWQWW7WHHK3vBdOLDNuF7TaX98GObUZOWkOnA==}
proto-list@1.2.4:
resolution: {integrity: sha1-IS1b/hMYMGpCD2QCuOJv85ZHqEk=}
@@ -4336,7 +4342,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.20260317.1
'@design.estate/dees-catalog': 3.49.0(@tiptap/pm@2.27.2)
'@design.estate/dees-catalog': 3.51.1(@tiptap/pm@2.27.2)
'@design.estate/dees-comms': 1.0.30
'@push.rocks/lik': 6.4.0
'@push.rocks/smartdelay': 3.0.5
@@ -4865,9 +4871,9 @@ snapshots:
dependencies:
'@api.global/typedrequest-interfaces': 3.0.19
'@design.estate/dees-catalog@3.49.0(@tiptap/pm@2.27.2)':
'@design.estate/dees-catalog@3.51.1(@tiptap/pm@2.27.2)':
dependencies:
'@design.estate/dees-domtools': 2.5.3
'@design.estate/dees-domtools': 2.5.4
'@design.estate/dees-element': 2.2.4
'@design.estate/dees-wcctools': 3.8.0
'@fortawesome/fontawesome-svg-core': 7.2.0
@@ -4885,9 +4891,9 @@ snapshots:
'@tiptap/extension-underline': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
'@tiptap/starter-kit': 2.27.2
'@tsclass/tsclass': 9.5.0
apexcharts: 5.10.4
highlight.js: 11.11.1
ibantools: 4.5.1
lightweight-charts: 5.1.0
lucide: 0.577.0
monaco-editor: 0.55.1
pdfjs-dist: 4.10.38
@@ -4933,6 +4939,32 @@ snapshots:
- supports-color
- vue
'@design.estate/dees-domtools@2.5.4':
dependencies:
'@api.global/typedrequest': 3.3.0
'@design.estate/dees-comms': 1.0.30
'@push.rocks/lik': 6.4.0
'@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartjson': 6.0.0
'@push.rocks/smartmarkdown': 3.0.3
'@push.rocks/smartpromise': 4.2.3
'@push.rocks/smartrouter': 1.3.3
'@push.rocks/smartrx': 3.0.10
'@push.rocks/smartstate': 2.3.0
'@push.rocks/smartstring': 4.1.0
'@push.rocks/smarturl': 3.1.0
'@push.rocks/webrequest': 4.0.5
'@push.rocks/websetup': 3.0.19
'@push.rocks/webstore': 2.0.21
'@tempfix/lenis': 1.3.20
lit: 3.3.2
sweet-scroll: 4.0.0
transitivePeerDependencies:
- '@nuxt/kit'
- react
- supports-color
- vue
'@design.estate/dees-element@2.2.4':
dependencies:
'@design.estate/dees-domtools': 2.5.3
@@ -4947,7 +4979,7 @@ snapshots:
'@design.estate/dees-wcctools@3.8.0':
dependencies:
'@design.estate/dees-domtools': 2.5.3
'@design.estate/dees-domtools': 2.5.4
'@design.estate/dees-element': 2.2.4
'@push.rocks/smartdelay': 3.0.5
lit: 3.3.2
@@ -5340,7 +5372,7 @@ snapshots:
'@inquirer/figures': 1.0.15
'@inquirer/type': 2.0.0
'@types/mute-stream': 0.0.4
'@types/node': 22.19.15
'@types/node': 22.19.16
'@types/wrap-ansi': 3.0.0
ansi-escapes: 4.3.2
cli-width: 4.1.0
@@ -6098,9 +6130,19 @@ snapshots:
- supports-color
- vue
'@push.rocks/smartdb@2.0.0':
'@push.rocks/smartdb@2.1.1(@tiptap/pm@2.27.2)':
dependencies:
'@api.global/typedserver': 8.4.6(@tiptap/pm@2.27.2)
'@design.estate/dees-element': 2.2.4
'@push.rocks/smartrust': 1.3.2
transitivePeerDependencies:
- '@nuxt/kit'
- '@tiptap/pm'
- bufferutil
- react
- supports-color
- utf-8-validate
- vue
'@push.rocks/smartdelay@3.0.5':
dependencies:
@@ -6622,7 +6664,7 @@ snapshots:
'@types/semver': 7.7.1
semver: 7.7.4
'@push.rocks/smartvpn@1.17.1':
'@push.rocks/smartvpn@1.19.1':
dependencies:
'@push.rocks/smartnftables': 1.1.0
'@push.rocks/smartpath': 6.0.0
@@ -6865,10 +6907,10 @@ snapshots:
domhandler: 5.0.3
selderee: 0.11.0
'@serve.zone/catalog@2.9.0(@tiptap/pm@2.27.2)':
'@serve.zone/catalog@2.11.0(@tiptap/pm@2.27.2)':
dependencies:
'@design.estate/dees-catalog': 3.49.0(@tiptap/pm@2.27.2)
'@design.estate/dees-domtools': 2.5.3
'@design.estate/dees-catalog': 3.51.1(@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
transitivePeerDependencies:
@@ -7359,9 +7401,9 @@ snapshots:
prosemirror-schema-list: 1.5.1
prosemirror-state: 1.4.4
prosemirror-tables: 1.8.5
prosemirror-trailing-node: 3.0.0(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-view@1.41.7)
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.7
prosemirror-trailing-node: 3.0.0(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-view@1.41.8)
prosemirror-transform: 1.12.0
prosemirror-view: 1.41.8
'@tiptap/starter-kit@2.27.2':
dependencies:
@@ -7415,7 +7457,7 @@ snapshots:
'@types/clean-css@4.2.11':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
source-map: 0.6.1
'@types/debug@4.1.13':
@@ -7425,7 +7467,7 @@ snapshots:
'@types/fs-extra@11.0.4':
dependencies:
'@types/jsonfile': 6.1.4
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/hast@3.0.4':
dependencies:
@@ -7445,12 +7487,12 @@ snapshots:
'@types/jsonfile@6.1.4':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/jsonwebtoken@9.0.10':
dependencies:
'@types/ms': 2.1.0
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/linkify-it@5.0.0': {}
@@ -7471,16 +7513,16 @@ snapshots:
'@types/mute-stream@0.0.4':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/node-fetch@2.6.13':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
form-data: 4.0.5
'@types/node-forge@1.3.14':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/node@16.9.1': {}
@@ -7488,17 +7530,17 @@ snapshots:
dependencies:
undici-types: 5.26.5
'@types/node@22.19.15':
'@types/node@22.19.16':
dependencies:
undici-types: 6.21.0
'@types/node@25.5.0':
'@types/node@25.5.1':
dependencies:
undici-types: 7.18.2
'@types/qrcode@1.5.6':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/randomatic@3.1.5': {}
@@ -7508,11 +7550,11 @@ snapshots:
'@types/tar-stream@3.1.4':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/through2@2.0.41':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/trusted-types@2.0.7': {}
@@ -7542,11 +7584,11 @@ snapshots:
'@types/ws@8.18.1':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
'@types/yauzl@2.10.3':
dependencies:
'@types/node': 25.5.0
'@types/node': 25.5.1
optional: true
'@ungap/structured-clone@1.3.0': {}
@@ -7591,8 +7633,6 @@ snapshots:
any-base@1.1.0: {}
apexcharts@5.10.4: {}
argparse@1.0.10:
dependencies:
sprintf-js: 1.0.3
@@ -8054,6 +8094,8 @@ snapshots:
fake-indexeddb@6.2.5: {}
fancy-canvas@2.1.0: {}
fast-deep-equal@3.1.3: {}
fast-fifo@1.3.2: {}
@@ -8550,6 +8592,10 @@ snapshots:
libqp@2.1.1: {}
lightweight-charts@5.1.0:
dependencies:
fancy-canvas: 2.1.0
lines-and-columns@1.2.4: {}
linkify-it@5.0.0:
@@ -9302,7 +9348,7 @@ snapshots:
prosemirror-changeset@2.4.0:
dependencies:
prosemirror-transform: 1.11.0
prosemirror-transform: 1.12.0
prosemirror-collab@1.3.1:
dependencies:
@@ -9312,32 +9358,32 @@ snapshots:
dependencies:
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-transform: 1.12.0
prosemirror-dropcursor@1.8.2:
dependencies:
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.7
prosemirror-transform: 1.12.0
prosemirror-view: 1.41.8
prosemirror-gapcursor@1.4.1:
dependencies:
prosemirror-keymap: 1.2.3
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-view: 1.41.7
prosemirror-view: 1.41.8
prosemirror-history@1.5.0:
dependencies:
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.7
prosemirror-transform: 1.12.0
prosemirror-view: 1.41.8
rope-sequence: 1.3.4
prosemirror-inputrules@1.5.1:
dependencies:
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-transform: 1.12.0
prosemirror-keymap@1.2.3:
dependencies:
@@ -9369,39 +9415,39 @@ snapshots:
dependencies:
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-transform: 1.12.0
prosemirror-state@1.4.4:
dependencies:
prosemirror-model: 1.25.4
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.7
prosemirror-transform: 1.12.0
prosemirror-view: 1.41.8
prosemirror-tables@1.8.5:
dependencies:
prosemirror-keymap: 1.2.3
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.7
prosemirror-transform: 1.12.0
prosemirror-view: 1.41.8
prosemirror-trailing-node@3.0.0(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-view@1.41.7):
prosemirror-trailing-node@3.0.0(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-view@1.41.8):
dependencies:
'@remirror/core-constants': 3.0.0
escape-string-regexp: 4.0.0
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-view: 1.41.7
prosemirror-view: 1.41.8
prosemirror-transform@1.11.0:
prosemirror-transform@1.12.0:
dependencies:
prosemirror-model: 1.25.4
prosemirror-view@1.41.7:
prosemirror-view@1.41.8:
dependencies:
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
prosemirror-transform: 1.12.0
proto-list@1.2.4: {}

140
readme.md
View File

@@ -93,10 +93,11 @@ For reporting bugs, issues, or security vulnerabilities, please visit [community
- **Socket-handler mode** — direct socket passing eliminates internal port hops
- **Real-time metrics** via SmartMetrics (CPU, memory, connections, throughput)
### 💾 Persistent Storage & Caching
- **Multiple storage backends**: filesystem, custom functions, or in-memory
- **Embedded cache database** via smartdata + smartdb (MongoDB-compatible)
### 💾 Unified Database
- **Two deployment modes**: embedded LocalSmartDb (zero-config) or external MongoDB
- **15 document classes** covering routes, certs, VPN, RADIUS, security profiles, network targets, and caches
- **Automatic TTL-based cleanup** for cached emails and IP reputation data
- **Reusable references** — security profiles and network targets that propagate changes to all referencing routes
### 🖥️ OpsServer Dashboard
- **Web-based management interface** with real-time monitoring
@@ -104,7 +105,9 @@ For reporting bugs, issues, or security vulnerabilities, please visit [community
- **Live views** for connections, email queues, DNS queries, RADIUS sessions, certificates, remote ingress edges, VPN clients, and security events
- **Domain-centric certificate overview** with backoff status and one-click reprovisioning
- **Remote ingress management** with connection token generation and one-click copy
- **Read-only configuration display** — DcRouter is configured through code
- **Security profiles & network targets** — reusable security configurations and host:port targets with propagation to referencing routes
- **Global warning banners** when database is disabled (management features unavailable)
- **Read-only configuration display** for system overview
- **Smart tab visibility handling** — auto-pauses all polling, WebSocket connections, and chart updates when the browser tab is hidden, preventing resource waste and tab freezing
### 🔧 Programmatic API Client
@@ -269,11 +272,8 @@ const router = new DcRouter({
],
},
// Persistent storage
storage: { fsPath: '/var/lib/dcrouter/data' },
// Cache database
cacheConfig: { enabled: true, storagePath: '~/.serve.zone/dcrouter/tsmdb' },
// Unified database (embedded LocalSmartDb or external MongoDB)
dbConfig: { enabled: true },
// TLS & ACME
tls: { contactEmail: 'admin@example.com' },
@@ -311,8 +311,7 @@ graph TB
CM[Certificate Manager<br/><i>smartacme v9</i>]
OS[OpsServer Dashboard]
MM[Metrics Manager]
SM[Storage Manager]
CD[Cache Database]
DB2[DcRouterDb<br/><i>smartdata + smartdb</i>]
end
subgraph "Backend Services"
@@ -339,8 +338,7 @@ graph TB
DC --> CM
DC --> OS
DC --> MM
DC --> SM
DC --> CD
DC --> DB2
SP --> WEB
SP --> API
@@ -365,8 +363,7 @@ graph TB
| **RemoteIngress** | `@serve.zone/remoteingress` | Distributed edge tunneling with Rust data plane and TS management |
| **OpsServer** | `@api.global/typedserver` | Web dashboard + TypedRequest API for monitoring and management |
| **MetricsManager** | `@push.rocks/smartmetrics` | Real-time metrics collection (CPU, memory, email, DNS, security) |
| **StorageManager** | built-in | Pluggable key-value storage (filesystem, custom, or in-memory) |
| **CacheDb** | `@push.rocks/smartdb` | Embedded MongoDB-compatible database (LocalSmartDb) for persistent caching |
| **DcRouterDb** | `@push.rocks/smartdata` + `@push.rocks/smartdb` | Unified database — embedded LocalSmartDb or external MongoDB for all persistence |
### How It Works
@@ -509,24 +506,16 @@ interface IDcRouterOptions {
};
dnsChallenge?: { cloudflareApiKey?: string };
// ── Storage & Caching ─────────────────────────────────────────
storage?: {
fsPath?: string;
readFunction?: (key: string) => Promise<string>;
writeFunction?: (key: string, value: string) => Promise<void>;
};
cacheConfig?: {
// ── Database ────────────────────────────────────────────────────
/** Unified database for all persistence (routes, certs, VPN, RADIUS, etc.) */
dbConfig?: {
enabled?: boolean; // default: true
mongoDbUrl?: string; // External MongoDB URL (omit for embedded LocalSmartDb)
storagePath?: string; // default: '~/.serve.zone/dcrouter/tsmdb'
dbName?: string; // default: 'dcrouter'
cleanupIntervalHours?: number; // default: 1
ttlConfig?: {
emails?: number; // default: 30 days
ipReputation?: number; // default: 1 day
bounces?: number; // default: 30 days
dkimKeys?: number; // default: 90 days
suppression?: number; // default: 30 days
};
seedOnEmpty?: boolean; // Seed default profiles/targets if DB is empty
seedData?: object; // Custom seed data
};
}
```
@@ -1213,49 +1202,55 @@ The OpsServer includes a **Certificates** view showing:
- One-click reprovisioning per domain
- Certificate import and export
## Storage & Caching
## Storage & Database
### StorageManager
DcRouter uses a **unified database** (`DcRouterDb`) powered by [`@push.rocks/smartdata`](https://code.foss.global/push.rocks/smartdata) + [`@push.rocks/smartdb`](https://code.foss.global/push.rocks/smartdb) for all persistence. It supports two modes:
Provides a unified key-value interface with three backends:
### Embedded LocalSmartDb (Default)
Zero-config, file-based MongoDB-compatible database — no external services needed:
```typescript
// Filesystem backend
storage: { fsPath: '/var/lib/dcrouter/data' }
// Custom backend (Redis, S3, etc.)
storage: {
readFunction: async (key) => await redis.get(key),
writeFunction: async (key, value) => await redis.set(key, value)
}
// In-memory (development only — data lost on restart)
// Simply omit the storage config
dbConfig: { enabled: true }
// Data stored at ~/.serve.zone/dcrouter/tsmdb by default
```
Used for: TLS certificates, DKIM keys, email routes, bounce/suppression lists, IP reputation data, domain configs, cert backoff state, remote ingress edge registrations.
### External MongoDB
### Cache Database
An embedded MongoDB-compatible database (via smartdata + smartdb) for persistent caching with automatic TTL cleanup:
Connect to an existing MongoDB instance:
```typescript
cacheConfig: {
dbConfig: {
enabled: true,
storagePath: '~/.serve.zone/dcrouter/tsmdb',
mongoDbUrl: 'mongodb://localhost:27017',
dbName: 'dcrouter',
cleanupIntervalHours: 1,
ttlConfig: {
emails: 30, // days
ipReputation: 1, // days
bounces: 30, // days
dkimKeys: 90, // days
suppression: 30 // days
}
}
```
Cached document types: `CachedEmail`, `CachedIPReputation`.
### Disabling the Database
For static, constructor-only deployments where no runtime management is needed:
```typescript
dbConfig: { enabled: false }
// Routes come exclusively from constructor config — no CRUD, no persistence
// OpsServer still runs but management features are disabled
```
### What's Stored
DcRouterDb persists all runtime state across 15 document classes:
| Category | Documents | Purpose |
|----------|-----------|---------|
| **Routes** | `StoredRouteDoc`, `RouteOverrideDoc` | Programmatic routes and hardcoded route overrides |
| **Certificates** | `ProxyCertDoc`, `AcmeCertDoc`, `CertBackoffDoc` | TLS certs, ACME state, per-domain backoff |
| **Auth** | `ApiTokenDoc` | API token storage |
| **Remote Ingress** | `RemoteIngressEdgeDoc` | Edge node registrations |
| **VPN** | `VpnServerKeysDoc`, `VpnClientDoc` | Server keys and client registrations |
| **RADIUS** | `VlanMappingsDoc`, `AccountingSessionDoc` | VLAN mappings and accounting sessions |
| **References** | `SecurityProfileDoc`, `NetworkTargetDoc` | Reusable security profiles and network targets |
| **Cache** | `CachedEmailDoc`, `CachedIpReputationDoc` | TTL-based caches with automatic cleanup |
## Security Features
@@ -1324,6 +1319,8 @@ The OpsServer provides a web-based management interface served on port 3000 by d
| 🔐 **Certificates** | Domain-centric certificate overview, status, backoff info, reprovisioning, import/export |
| 🌍 **RemoteIngress** | Edge node management, connection status, token generation, enable/disable |
| 🔐 **VPN** | VPN client management, server status, create/toggle/export/rotate/delete clients |
| 🛡️ **Security Profiles** | Reusable security configurations (IP allow/block lists, rate limits) |
| 🎯 **Network Targets** | Reusable host:port destinations for route references |
| 📡 **RADIUS** | NAS client management, VLAN mappings, session monitoring, accounting |
| 📜 **Logs** | Real-time log viewer with level filtering and search |
| ⚙️ **Configuration** | Read-only view of current system configuration |
@@ -1410,6 +1407,22 @@ All management is done via TypedRequest over HTTP POST to `/typedrequest`:
'setVlanMapping' // Add/update VLAN mapping
'removeVlanMapping' // Remove VLAN mapping
'testVlanAssignment' // Test what VLAN a MAC gets
// Security Profiles
'getSecurityProfiles' // List all security profiles
'getSecurityProfile' // Get a single profile by ID
'createSecurityProfile' // Create a reusable security profile
'updateSecurityProfile' // Update a profile (propagates to referencing routes)
'deleteSecurityProfile' // Delete a profile (with optional force)
'getSecurityProfileUsage' // Get routes referencing a profile
// Network Targets
'getNetworkTargets' // List all network targets
'getNetworkTarget' // Get a single target by ID
'createNetworkTarget' // Create a reusable host:port target
'updateNetworkTarget' // Update a target (propagates to referencing routes)
'deleteNetworkTarget' // Delete a target (with optional force)
'getNetworkTargetUsage' // Get routes referencing a target
```
## API Client
@@ -1518,12 +1531,12 @@ const router = new DcRouter(options: IDcRouterOptions);
| `remoteIngressManager` | `RemoteIngressManager` | Edge registration CRUD manager |
| `tunnelManager` | `TunnelManager` | Tunnel lifecycle and status manager |
| `vpnManager` | `VpnManager` | VPN server lifecycle and client CRUD manager |
| `storageManager` | `StorageManager` | Storage backend |
| `opsServer` | `OpsServer` | OpsServer/dashboard instance |
| `metricsManager` | `MetricsManager` | Metrics collector |
| `cacheDb` | `CacheDb` | Cache database instance |
| `certProvisionScheduler` | `CertProvisionScheduler` | Per-domain backoff scheduler for cert provisioning |
| `certificateStatusMap` | `Map<string, ...>` | Domain-keyed certificate status from SmartProxy events |
| `dcRouterDb` | `DcRouterDb` | Unified database instance (smartdata + smartdb) |
| `routeConfigManager` | `RouteConfigManager` | Programmatic route CRUD manager |
| `apiTokenManager` | `ApiTokenManager` | API token management |
| `referenceResolver` | `ReferenceResolver` | Security profile and network target resolver |
### Re-exported Types
@@ -1589,7 +1602,8 @@ tstest test/test.opsserver-api.ts --verbose --timeout 60
| `test.jwt-auth.ts` | JWT login, verification, logout, invalid credentials | 8 |
| `test.opsserver-api.ts` | Health, statistics, configuration, log APIs | 8 |
| `test.protected-endpoint.ts` | Admin auth, identity verification, public endpoints | 8 |
| `test.storagemanager.ts` | Memory, filesystem, custom backends, concurrency | 8 |
| `test.reference-resolver.ts` | Security profiles, network targets, route resolution | 20 |
| `test.security-profiles-api.ts` | Profile/target API endpoints, auth enforcement | 13 |
## Docker / OCI Container Deployment

View File

@@ -0,0 +1,371 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ReferenceResolver } from '../ts/config/classes.reference-resolver.js';
import type { ISecurityProfile, INetworkTarget, IRouteMetadata } from '../ts_interfaces/data/route-management.js';
import type { IRouteConfig } from '@push.rocks/smartproxy';
// ============================================================================
// Helpers: access private maps for direct unit testing without DB
// ============================================================================
function injectProfile(resolver: ReferenceResolver, profile: ISecurityProfile): void {
(resolver as any).profiles.set(profile.id, profile);
}
function injectTarget(resolver: ReferenceResolver, target: INetworkTarget): void {
(resolver as any).targets.set(target.id, target);
}
function makeProfile(overrides: Partial<ISecurityProfile> = {}): ISecurityProfile {
return {
id: 'profile-1',
name: 'STANDARD',
description: 'Test profile',
security: {
ipAllowList: ['192.168.0.0/16', '10.0.0.0/8'],
maxConnections: 1000,
},
createdAt: Date.now(),
updatedAt: Date.now(),
createdBy: 'test',
...overrides,
};
}
function makeTarget(overrides: Partial<INetworkTarget> = {}): INetworkTarget {
return {
id: 'target-1',
name: 'INFRA',
description: 'Test target',
host: '192.168.5.247',
port: 443,
createdAt: Date.now(),
updatedAt: Date.now(),
createdBy: 'test',
...overrides,
};
}
function makeRoute(overrides: Partial<IRouteConfig> = {}): IRouteConfig {
return {
name: 'test-route',
match: { ports: 443, domains: 'test.example.com' },
action: { type: 'forward', targets: [{ host: 'placeholder', port: 80 }] },
...overrides,
} as IRouteConfig;
}
// ============================================================================
// Resolution tests
// ============================================================================
let resolver: ReferenceResolver;
tap.test('should create ReferenceResolver instance', async () => {
resolver = new ReferenceResolver();
expect(resolver).toBeTruthy();
});
tap.test('should list empty profiles and targets initially', async () => {
expect(resolver.listProfiles()).toBeArray();
expect(resolver.listProfiles().length).toEqual(0);
expect(resolver.listTargets()).toBeArray();
expect(resolver.listTargets().length).toEqual(0);
});
// ---- Security profile resolution ----
tap.test('should resolve security profile onto a route', async () => {
const profile = makeProfile();
injectProfile(resolver, profile);
const route = makeRoute();
const metadata: IRouteMetadata = { securityProfileRef: 'profile-1' };
const result = resolver.resolveRoute(route, metadata);
expect(result.route.security).toBeTruthy();
expect(result.route.security!.ipAllowList).toContain('192.168.0.0/16');
expect(result.route.security!.ipAllowList).toContain('10.0.0.0/8');
expect(result.route.security!.maxConnections).toEqual(1000);
expect(result.metadata.securityProfileName).toEqual('STANDARD');
expect(result.metadata.lastResolvedAt).toBeTruthy();
});
tap.test('should merge inline route security with profile security', async () => {
const route = makeRoute({
security: {
ipAllowList: ['127.0.0.1'],
maxConnections: 5000,
},
});
const metadata: IRouteMetadata = { securityProfileRef: 'profile-1' };
const result = resolver.resolveRoute(route, metadata);
// IP lists are unioned
expect(result.route.security!.ipAllowList).toContain('192.168.0.0/16');
expect(result.route.security!.ipAllowList).toContain('10.0.0.0/8');
expect(result.route.security!.ipAllowList).toContain('127.0.0.1');
// Inline maxConnections overrides profile
expect(result.route.security!.maxConnections).toEqual(5000);
});
tap.test('should deduplicate IP lists during merge', async () => {
const route = makeRoute({
security: {
ipAllowList: ['192.168.0.0/16', '127.0.0.1'],
},
});
const metadata: IRouteMetadata = { securityProfileRef: 'profile-1' };
const result = resolver.resolveRoute(route, metadata);
// 192.168.0.0/16 appears in both profile and route, should be deduplicated
const count = result.route.security!.ipAllowList!.filter(ip => ip === '192.168.0.0/16').length;
expect(count).toEqual(1);
});
tap.test('should handle missing profile gracefully', async () => {
const route = makeRoute();
const metadata: IRouteMetadata = { securityProfileRef: 'nonexistent-profile' };
const result = resolver.resolveRoute(route, metadata);
// Route should be unchanged
expect(result.route.security).toBeUndefined();
expect(result.metadata.securityProfileName).toBeUndefined();
});
// ---- Profile inheritance ----
tap.test('should resolve profile inheritance (extendsProfiles)', async () => {
const baseProfile = makeProfile({
id: 'base-profile',
name: 'BASE',
security: {
ipAllowList: ['10.0.0.0/8'],
maxConnections: 500,
},
});
injectProfile(resolver, baseProfile);
const extendedProfile = makeProfile({
id: 'extended-profile',
name: 'EXTENDED',
security: {
ipAllowList: ['160.79.104.0/21'],
},
extendsProfiles: ['base-profile'],
});
injectProfile(resolver, extendedProfile);
const route = makeRoute();
const metadata: IRouteMetadata = { securityProfileRef: 'extended-profile' };
const result = resolver.resolveRoute(route, metadata);
// Should have IPs from both base and extended profiles
expect(result.route.security!.ipAllowList).toContain('10.0.0.0/8');
expect(result.route.security!.ipAllowList).toContain('160.79.104.0/21');
// maxConnections from base (extended doesn't override)
expect(result.route.security!.maxConnections).toEqual(500);
expect(result.metadata.securityProfileName).toEqual('EXTENDED');
});
tap.test('should detect circular profile inheritance', async () => {
const profileA = makeProfile({
id: 'circular-a',
name: 'A',
security: { ipAllowList: ['1.1.1.1'] },
extendsProfiles: ['circular-b'],
});
const profileB = makeProfile({
id: 'circular-b',
name: 'B',
security: { ipAllowList: ['2.2.2.2'] },
extendsProfiles: ['circular-a'],
});
injectProfile(resolver, profileA);
injectProfile(resolver, profileB);
const route = makeRoute();
const metadata: IRouteMetadata = { securityProfileRef: 'circular-a' };
// Should not infinite loop — resolves what it can
const result = resolver.resolveRoute(route, metadata);
expect(result.route.security).toBeTruthy();
expect(result.route.security!.ipAllowList).toContain('1.1.1.1');
});
// ---- Network target resolution ----
tap.test('should resolve network target onto a route', async () => {
const target = makeTarget();
injectTarget(resolver, target);
const route = makeRoute();
const metadata: IRouteMetadata = { networkTargetRef: 'target-1' };
const result = resolver.resolveRoute(route, metadata);
expect(result.route.action.targets).toBeTruthy();
expect(result.route.action.targets![0].host).toEqual('192.168.5.247');
expect(result.route.action.targets![0].port).toEqual(443);
expect(result.metadata.networkTargetName).toEqual('INFRA');
expect(result.metadata.lastResolvedAt).toBeTruthy();
});
tap.test('should handle missing target gracefully', async () => {
const route = makeRoute();
const metadata: IRouteMetadata = { networkTargetRef: 'nonexistent-target' };
const result = resolver.resolveRoute(route, metadata);
// Route targets should be unchanged (still the placeholder)
expect(result.route.action.targets![0].host).toEqual('placeholder');
expect(result.metadata.networkTargetName).toBeUndefined();
});
// ---- Combined resolution ----
tap.test('should resolve both profile and target simultaneously', async () => {
const route = makeRoute();
const metadata: IRouteMetadata = {
securityProfileRef: 'profile-1',
networkTargetRef: 'target-1',
};
const result = resolver.resolveRoute(route, metadata);
// Security from profile
expect(result.route.security!.ipAllowList).toContain('192.168.0.0/16');
expect(result.route.security!.maxConnections).toEqual(1000);
// Target from network target
expect(result.route.action.targets![0].host).toEqual('192.168.5.247');
expect(result.route.action.targets![0].port).toEqual(443);
// Both names recorded
expect(result.metadata.securityProfileName).toEqual('STANDARD');
expect(result.metadata.networkTargetName).toEqual('INFRA');
});
tap.test('should skip resolution when no metadata refs', async () => {
const route = makeRoute({
security: { ipAllowList: ['1.2.3.4'] },
});
const metadata: IRouteMetadata = {};
const result = resolver.resolveRoute(route, metadata);
// Route should be completely unchanged
expect(result.route.security!.ipAllowList).toContain('1.2.3.4');
expect(result.route.security!.ipAllowList!.length).toEqual(1);
expect(result.route.action.targets![0].host).toEqual('placeholder');
});
tap.test('should be idempotent — resolving twice gives same result', async () => {
const route = makeRoute();
const metadata: IRouteMetadata = {
securityProfileRef: 'profile-1',
networkTargetRef: 'target-1',
};
const first = resolver.resolveRoute(route, metadata);
const second = resolver.resolveRoute(first.route, first.metadata);
expect(second.route.security!.ipAllowList!.length).toEqual(first.route.security!.ipAllowList!.length);
expect(second.route.action.targets![0].host).toEqual(first.route.action.targets![0].host);
expect(second.route.action.targets![0].port).toEqual(first.route.action.targets![0].port);
});
// ---- Lookup helpers ----
tap.test('should find routes by profile ref (sync)', async () => {
const storedRoutes = new Map<string, any>();
storedRoutes.set('route-a', {
id: 'route-a',
route: makeRoute({ name: 'route-a' }),
enabled: true,
metadata: { securityProfileRef: 'profile-1' },
});
storedRoutes.set('route-b', {
id: 'route-b',
route: makeRoute({ name: 'route-b' }),
enabled: true,
metadata: { networkTargetRef: 'target-1' },
});
storedRoutes.set('route-c', {
id: 'route-c',
route: makeRoute({ name: 'route-c' }),
enabled: true,
metadata: { securityProfileRef: 'profile-1', networkTargetRef: 'target-1' },
});
const profileRefs = resolver.findRoutesByProfileRefSync('profile-1', storedRoutes);
expect(profileRefs.length).toEqual(2);
expect(profileRefs).toContain('route-a');
expect(profileRefs).toContain('route-c');
const targetRefs = resolver.findRoutesByTargetRefSync('target-1', storedRoutes);
expect(targetRefs.length).toEqual(2);
expect(targetRefs).toContain('route-b');
expect(targetRefs).toContain('route-c');
});
tap.test('should get profile usage for a specific profile ID', async () => {
const storedRoutes = new Map<string, any>();
storedRoutes.set('route-x', {
id: 'route-x',
route: makeRoute({ name: 'my-route' }),
enabled: true,
metadata: { securityProfileRef: 'profile-1' },
});
const usage = resolver.getProfileUsageForId('profile-1', storedRoutes);
expect(usage.length).toEqual(1);
expect(usage[0].id).toEqual('route-x');
expect(usage[0].routeName).toEqual('my-route');
});
tap.test('should get target usage for a specific target ID', async () => {
const storedRoutes = new Map<string, any>();
storedRoutes.set('route-y', {
id: 'route-y',
route: makeRoute({ name: 'other-route' }),
enabled: true,
metadata: { networkTargetRef: 'target-1' },
});
const usage = resolver.getTargetUsageForId('target-1', storedRoutes);
expect(usage.length).toEqual(1);
expect(usage[0].id).toEqual('route-y');
expect(usage[0].routeName).toEqual('other-route');
});
// ---- Profile/target getters ----
tap.test('should get profile by name', async () => {
const profile = resolver.getProfileByName('STANDARD');
expect(profile).toBeTruthy();
expect(profile!.id).toEqual('profile-1');
});
tap.test('should get target by name', async () => {
const target = resolver.getTargetByName('INFRA');
expect(target).toBeTruthy();
expect(target!.id).toEqual('target-1');
});
tap.test('should return undefined for nonexistent profile name', async () => {
const profile = resolver.getProfileByName('NONEXISTENT');
expect(profile).toBeUndefined();
});
tap.test('should return undefined for nonexistent target name', async () => {
const target = resolver.getTargetByName('NONEXISTENT');
expect(target).toBeUndefined();
});
export default tap.start();

View File

@@ -0,0 +1,208 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DcRouter } from '../ts/index.js';
import { TypedRequest } from '@api.global/typedrequest';
import * as interfaces from '../ts_interfaces/index.js';
const TEST_PORT = 3200;
const TEST_URL = `http://localhost:${TEST_PORT}/typedrequest`;
let testDcRouter: DcRouter;
let adminIdentity: interfaces.data.IIdentity;
// ============================================================================
// Setup — db disabled, handlers return graceful fallbacks
// ============================================================================
tap.test('should start DCRouter with OpsServer', async () => {
testDcRouter = new DcRouter({
opsServerPort: TEST_PORT,
dbConfig: { enabled: false },
});
await testDcRouter.start();
expect(testDcRouter.opsServer).toBeInstanceOf(Object);
});
tap.test('should login as admin', async () => {
const loginRequest = new TypedRequest<interfaces.requests.IReq_AdminLoginWithUsernameAndPassword>(
TEST_URL,
'adminLoginWithUsernameAndPassword'
);
const response = await loginRequest.fire({
username: 'admin',
password: 'admin',
});
expect(response).toHaveProperty('identity');
adminIdentity = response.identity;
});
// ============================================================================
// Security Profile endpoints (graceful fallbacks when resolver unavailable)
// ============================================================================
tap.test('should return empty profiles list when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetSecurityProfiles>(
TEST_URL,
'getSecurityProfiles'
);
const response = await req.fire({
identity: adminIdentity,
});
expect(response.profiles).toBeArray();
expect(response.profiles.length).toEqual(0);
});
tap.test('should return null for single profile when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetSecurityProfile>(
TEST_URL,
'getSecurityProfile'
);
const response = await req.fire({
identity: adminIdentity,
id: 'nonexistent',
});
expect(response.profile).toEqual(null);
});
tap.test('should return failure for create profile when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_CreateSecurityProfile>(
TEST_URL,
'createSecurityProfile'
);
const response = await req.fire({
identity: adminIdentity,
name: 'TEST',
security: { ipAllowList: ['*'] },
});
expect(response.success).toBeFalse();
expect(response.message).toBeTruthy();
});
tap.test('should return empty profile usage when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetSecurityProfileUsage>(
TEST_URL,
'getSecurityProfileUsage'
);
const response = await req.fire({
identity: adminIdentity,
id: 'nonexistent',
});
expect(response.routes).toBeArray();
expect(response.routes.length).toEqual(0);
});
// ============================================================================
// Network Target endpoints (graceful fallbacks when resolver unavailable)
// ============================================================================
tap.test('should return empty targets list when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetNetworkTargets>(
TEST_URL,
'getNetworkTargets'
);
const response = await req.fire({
identity: adminIdentity,
});
expect(response.targets).toBeArray();
expect(response.targets.length).toEqual(0);
});
tap.test('should return null for single target when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetNetworkTarget>(
TEST_URL,
'getNetworkTarget'
);
const response = await req.fire({
identity: adminIdentity,
id: 'nonexistent',
});
expect(response.target).toEqual(null);
});
tap.test('should return failure for create target when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_CreateNetworkTarget>(
TEST_URL,
'createNetworkTarget'
);
const response = await req.fire({
identity: adminIdentity,
name: 'TEST',
host: '127.0.0.1',
port: 443,
});
expect(response.success).toBeFalse();
expect(response.message).toBeTruthy();
});
tap.test('should return empty target usage when resolver not initialized', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetNetworkTargetUsage>(
TEST_URL,
'getNetworkTargetUsage'
);
const response = await req.fire({
identity: adminIdentity,
id: 'nonexistent',
});
expect(response.routes).toBeArray();
expect(response.routes.length).toEqual(0);
});
// ============================================================================
// Auth rejection
// ============================================================================
tap.test('should reject unauthenticated profile requests', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetSecurityProfiles>(
TEST_URL,
'getSecurityProfiles'
);
try {
await req.fire({} as any);
expect(true).toBeFalse();
} catch (error) {
expect(error).toBeTruthy();
}
});
tap.test('should reject unauthenticated target requests', async () => {
const req = new TypedRequest<interfaces.requests.IReq_GetNetworkTargets>(
TEST_URL,
'getNetworkTargets'
);
try {
await req.fire({} as any);
expect(true).toBeFalse();
} catch (error) {
expect(error).toBeTruthy();
}
});
// ============================================================================
// Cleanup
// ============================================================================
tap.test('should stop DCRouter', async () => {
await testDcRouter.stop();
});
export default tap.start();

View File

@@ -49,8 +49,7 @@ const devRouter = new DcRouter({
{ clientId: 'admin-desktop', serverDefinedClientTags: ['admin'], description: 'Admin workstation' },
],
},
// Disable db/mongo for dev
dbConfig: { enabled: false },
dbConfig: { enabled: true },
});
console.log('Starting DcRouter in development mode...');

View File

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

View File

@@ -21,7 +21,7 @@ import { MetricsManager } from './monitoring/index.js';
import { RadiusServer, type IRadiusServerConfig } from './radius/index.js';
import { RemoteIngressManager, TunnelManager } from './remoteingress/index.js';
import { VpnManager, type IVpnManagerConfig } from './vpn/index.js';
import { RouteConfigManager, ApiTokenManager } from './config/index.js';
import { RouteConfigManager, ApiTokenManager, ReferenceResolver, DbSeeder } from './config/index.js';
import { SecurityLogger, ContentScanner, IPReputationChecker } from './security/index.js';
import { type IHttp3Config, augmentRoutesWithHttp3 } from './http3/index.js';
@@ -137,6 +137,10 @@ export interface IDcRouterOptions {
dbName?: string;
/** Cache cleanup interval in hours (default: 1) */
cleanupIntervalHours?: number;
/** Seed default security profiles and network targets when DB is empty on first startup. */
seedOnEmpty?: boolean;
/** Custom seed data for profiles and targets (overrides built-in defaults). */
seedData?: import('./config/classes.db-seeder.js').ISeedData;
};
/**
@@ -205,6 +209,17 @@ export interface IDcRouterOptions {
allowList?: string[];
blockList?: string[];
};
/** Forwarding mode: 'socket' (default, userspace NAT), 'bridge' (L2 bridge to host LAN),
* or 'hybrid' (socket default, bridge for clients with useHostIp=true) */
forwardingMode?: 'socket' | 'bridge' | 'hybrid';
/** LAN subnet CIDR for bridge mode (e.g., '192.168.1.0/24') */
bridgeLanSubnet?: string;
/** Physical network interface for bridge mode (auto-detected if omitted) */
bridgePhysicalInterface?: string;
/** Start of VPN client IP range in LAN subnet (host offset, default: 200) */
bridgeIpRangeStart?: number;
/** End of VPN client IP range in LAN subnet (host offset, default: 250) */
bridgeIpRangeEnd?: number;
};
}
@@ -258,6 +273,7 @@ export class DcRouter {
// Programmatic config API
public routeConfigManager?: RouteConfigManager;
public apiTokenManager?: ApiTokenManager;
public referenceResolver?: ReferenceResolver;
// Auto-discovered public IP (populated by generateAuthoritativeRecords)
public detectedPublicIp: string | null = null;
@@ -445,6 +461,10 @@ export class DcRouter {
.optional()
.dependsOn('SmartProxy', 'DcRouterDb')
.withStart(async () => {
// Initialize reference resolver first (profiles + targets)
this.referenceResolver = new ReferenceResolver();
await this.referenceResolver.initialize();
this.routeConfigManager = new RouteConfigManager(
() => this.getConstructorRoutes(),
() => this.smartProxy,
@@ -457,14 +477,33 @@ export class DcRouter {
return [this.options.vpnConfig?.subnet || '10.8.0.0/24'];
}
: undefined,
this.referenceResolver,
// Sync merged routes to RemoteIngressManager whenever routes change,
// then push updated derived ports to the Rust hub binary
(routes) => {
if (this.remoteIngressManager) {
this.remoteIngressManager.setRoutes(routes as any[]);
}
if (this.tunnelManager) {
this.tunnelManager.syncAllowedEdges();
}
},
);
this.apiTokenManager = new ApiTokenManager();
await this.apiTokenManager.initialize();
await this.routeConfigManager.initialize();
// Seed default profiles/targets if DB is empty and seeding is enabled
const seeder = new DbSeeder(this.referenceResolver);
await seeder.seedIfEmpty(
this.options.dbConfig?.seedOnEmpty,
this.options.dbConfig?.seedData,
);
})
.withStop(async () => {
this.routeConfigManager = undefined;
this.apiTokenManager = undefined;
this.referenceResolver = undefined;
})
.withRetry({ maxRetries: 2, baseDelayMs: 1000 }),
);
@@ -2025,6 +2064,13 @@ export class DcRouter {
const currentRoutes = this.constructorRoutes;
this.remoteIngressManager.setRoutes(currentRoutes as any[]);
// Race-condition fix: if ConfigManagers finished before us, re-apply routes
// so the callback delivers the full merged set (including DB-stored routes)
// to our newly-created remoteIngressManager.
if (this.routeConfigManager) {
await this.routeConfigManager.applyRoutes();
}
// Resolve TLS certs for tunnel: explicit paths > ACME for hubDomain > self-signed (Rust default)
const riCfg = this.options.remoteIngressConfig;
let tlsConfig: { certPem: string; keyPem: string } | undefined;
@@ -2085,6 +2131,11 @@ export class DcRouter {
serverEndpoint: this.options.vpnConfig.serverEndpoint,
initialClients: this.options.vpnConfig.clients,
destinationPolicy: this.options.vpnConfig.destinationPolicy,
forwardingMode: this.options.vpnConfig.forwardingMode,
bridgeLanSubnet: this.options.vpnConfig.bridgeLanSubnet,
bridgePhysicalInterface: this.options.vpnConfig.bridgePhysicalInterface,
bridgeIpRangeStart: this.options.vpnConfig.bridgeIpRangeStart,
bridgeIpRangeEnd: this.options.vpnConfig.bridgeIpRangeEnd,
onClientChanged: () => {
// Re-apply routes so tag-based ipAllowLists get updated
this.routeConfigManager?.applyRoutes();

View File

@@ -0,0 +1,95 @@
import { logger } from '../logger.js';
import type { ReferenceResolver } from './classes.reference-resolver.js';
import type { IRouteSecurity } from '../../ts_interfaces/data/route-management.js';
export interface ISeedData {
profiles?: Array<{
name: string;
description?: string;
security: IRouteSecurity;
extendsProfiles?: string[];
}>;
targets?: Array<{
name: string;
description?: string;
host: string | string[];
port: number;
}>;
}
export class DbSeeder {
constructor(private referenceResolver: ReferenceResolver) {}
/**
* Check if DB is empty and seed if configured.
* Called once during ConfigManagers service startup, after initialize().
*/
public async seedIfEmpty(
seedOnEmpty?: boolean,
seedData?: ISeedData,
): Promise<void> {
if (!seedOnEmpty) return;
const existingProfiles = this.referenceResolver.listProfiles();
const existingTargets = this.referenceResolver.listTargets();
if (existingProfiles.length > 0 || existingTargets.length > 0) {
logger.log('info', 'DB already contains profiles/targets, skipping seed');
return;
}
logger.log('info', 'Seeding database with initial profiles and targets...');
const profilesToSeed: NonNullable<ISeedData['profiles']> = seedData?.profiles ?? DEFAULT_PROFILES;
const targetsToSeed: NonNullable<ISeedData['targets']> = seedData?.targets ?? DEFAULT_TARGETS;
for (const p of profilesToSeed) {
await this.referenceResolver.createProfile({
name: p.name,
description: p.description,
security: p.security,
extendsProfiles: p.extendsProfiles,
createdBy: 'system-seed',
});
}
for (const t of targetsToSeed) {
await this.referenceResolver.createTarget({
name: t.name,
description: t.description,
host: t.host,
port: t.port,
createdBy: 'system-seed',
});
}
logger.log('info', `Seeded ${profilesToSeed.length} profile(s) and ${targetsToSeed.length} target(s)`);
}
}
const DEFAULT_PROFILES: Array<NonNullable<ISeedData['profiles']>[number]> = [
{
name: 'PUBLIC',
description: 'Allow all traffic — no IP restrictions',
security: {
ipAllowList: ['*'],
},
},
{
name: 'STANDARD',
description: 'Standard internal access with common private subnets',
security: {
ipAllowList: ['192.168.0.0/16', '10.0.0.0/8', '127.0.0.1', '::1'],
maxConnections: 1000,
},
},
];
const DEFAULT_TARGETS: Array<NonNullable<ISeedData['targets']>[number]> = [
{
name: 'LOCALHOST',
description: 'Local machine on port 443',
host: '127.0.0.1',
port: 443,
},
];

View File

@@ -0,0 +1,576 @@
import * as plugins from '../plugins.js';
import { logger } from '../logger.js';
import { SecurityProfileDoc, NetworkTargetDoc, StoredRouteDoc } from '../db/index.js';
import type {
ISecurityProfile,
INetworkTarget,
IRouteMetadata,
IStoredRoute,
IRouteSecurity,
} from '../../ts_interfaces/data/route-management.js';
const MAX_INHERITANCE_DEPTH = 5;
export class ReferenceResolver {
private profiles = new Map<string, ISecurityProfile>();
private targets = new Map<string, INetworkTarget>();
// =========================================================================
// Lifecycle
// =========================================================================
public async initialize(): Promise<void> {
await this.loadProfiles();
await this.loadTargets();
}
// =========================================================================
// Profile CRUD
// =========================================================================
public async createProfile(data: {
name: string;
description?: string;
security: IRouteSecurity;
extendsProfiles?: string[];
createdBy: string;
}): Promise<string> {
const id = plugins.uuid.v4();
const now = Date.now();
const profile: ISecurityProfile = {
id,
name: data.name,
description: data.description,
security: data.security,
extendsProfiles: data.extendsProfiles,
createdAt: now,
updatedAt: now,
createdBy: data.createdBy,
};
this.profiles.set(id, profile);
await this.persistProfile(profile);
logger.log('info', `Created security profile '${profile.name}' (${id})`);
return id;
}
public async updateProfile(
id: string,
patch: Partial<Omit<ISecurityProfile, 'id' | 'createdAt' | 'createdBy'>>,
): Promise<{ affectedRouteIds: string[] }> {
const profile = this.profiles.get(id);
if (!profile) {
throw new Error(`Security profile '${id}' not found`);
}
if (patch.name !== undefined) profile.name = patch.name;
if (patch.description !== undefined) profile.description = patch.description;
if (patch.security !== undefined) profile.security = patch.security;
if (patch.extendsProfiles !== undefined) profile.extendsProfiles = patch.extendsProfiles;
profile.updatedAt = Date.now();
await this.persistProfile(profile);
logger.log('info', `Updated security profile '${profile.name}' (${id})`);
// Find routes referencing this profile
const affectedRouteIds = await this.findRoutesByProfileRef(id);
return { affectedRouteIds };
}
public async deleteProfile(
id: string,
force: boolean,
storedRoutes?: Map<string, IStoredRoute>,
): Promise<{ success: boolean; message?: string }> {
const profile = this.profiles.get(id);
if (!profile) {
return { success: false, message: `Security profile '${id}' not found` };
}
// Check usage
const affectedIds = storedRoutes
? this.findRoutesByProfileRefSync(id, storedRoutes)
: await this.findRoutesByProfileRef(id);
if (affectedIds.length > 0 && !force) {
return {
success: false,
message: `Profile '${profile.name}' is in use by ${affectedIds.length} route(s). Use force=true to delete.`,
};
}
// Delete from DB
const doc = await SecurityProfileDoc.findById(id);
if (doc) await doc.delete();
this.profiles.delete(id);
// If force-deleting with referencing routes, clear refs but keep resolved values
if (affectedIds.length > 0) {
await this.clearProfileRefsOnRoutes(affectedIds);
logger.log('warn', `Force-deleted profile '${profile.name}'; cleared refs on ${affectedIds.length} route(s)`);
} else {
logger.log('info', `Deleted security profile '${profile.name}' (${id})`);
}
return { success: true };
}
public getProfile(id: string): ISecurityProfile | undefined {
return this.profiles.get(id);
}
public getProfileByName(name: string): ISecurityProfile | undefined {
for (const profile of this.profiles.values()) {
if (profile.name === name) return profile;
}
return undefined;
}
public listProfiles(): ISecurityProfile[] {
return [...this.profiles.values()];
}
public getProfileUsage(storedRoutes: Map<string, IStoredRoute>): Map<string, Array<{ id: string; routeName: string }>> {
const usage = new Map<string, Array<{ id: string; routeName: string }>>();
for (const profile of this.profiles.values()) {
usage.set(profile.id, []);
}
for (const [routeId, stored] of storedRoutes) {
const ref = stored.metadata?.securityProfileRef;
if (ref && usage.has(ref)) {
usage.get(ref)!.push({ id: routeId, routeName: stored.route.name || routeId });
}
}
return usage;
}
public getProfileUsageForId(
profileId: string,
storedRoutes: Map<string, IStoredRoute>,
): Array<{ id: string; routeName: string }> {
const routes: Array<{ id: string; routeName: string }> = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.securityProfileRef === profileId) {
routes.push({ id: routeId, routeName: stored.route.name || routeId });
}
}
return routes;
}
// =========================================================================
// Target CRUD
// =========================================================================
public async createTarget(data: {
name: string;
description?: string;
host: string | string[];
port: number;
createdBy: string;
}): Promise<string> {
const id = plugins.uuid.v4();
const now = Date.now();
const target: INetworkTarget = {
id,
name: data.name,
description: data.description,
host: data.host,
port: data.port,
createdAt: now,
updatedAt: now,
createdBy: data.createdBy,
};
this.targets.set(id, target);
await this.persistTarget(target);
logger.log('info', `Created network target '${target.name}' (${id})`);
return id;
}
public async updateTarget(
id: string,
patch: Partial<Omit<INetworkTarget, 'id' | 'createdAt' | 'createdBy'>>,
): Promise<{ affectedRouteIds: string[] }> {
const target = this.targets.get(id);
if (!target) {
throw new Error(`Network target '${id}' not found`);
}
if (patch.name !== undefined) target.name = patch.name;
if (patch.description !== undefined) target.description = patch.description;
if (patch.host !== undefined) target.host = patch.host;
if (patch.port !== undefined) target.port = patch.port;
target.updatedAt = Date.now();
await this.persistTarget(target);
logger.log('info', `Updated network target '${target.name}' (${id})`);
const affectedRouteIds = await this.findRoutesByTargetRef(id);
return { affectedRouteIds };
}
public async deleteTarget(
id: string,
force: boolean,
storedRoutes?: Map<string, IStoredRoute>,
): Promise<{ success: boolean; message?: string }> {
const target = this.targets.get(id);
if (!target) {
return { success: false, message: `Network target '${id}' not found` };
}
const affectedIds = storedRoutes
? this.findRoutesByTargetRefSync(id, storedRoutes)
: await this.findRoutesByTargetRef(id);
if (affectedIds.length > 0 && !force) {
return {
success: false,
message: `Target '${target.name}' is in use by ${affectedIds.length} route(s). Use force=true to delete.`,
};
}
const doc = await NetworkTargetDoc.findById(id);
if (doc) await doc.delete();
this.targets.delete(id);
if (affectedIds.length > 0) {
await this.clearTargetRefsOnRoutes(affectedIds);
logger.log('warn', `Force-deleted target '${target.name}'; cleared refs on ${affectedIds.length} route(s)`);
} else {
logger.log('info', `Deleted network target '${target.name}' (${id})`);
}
return { success: true };
}
public getTarget(id: string): INetworkTarget | undefined {
return this.targets.get(id);
}
public getTargetByName(name: string): INetworkTarget | undefined {
for (const target of this.targets.values()) {
if (target.name === name) return target;
}
return undefined;
}
public listTargets(): INetworkTarget[] {
return [...this.targets.values()];
}
public getTargetUsageForId(
targetId: string,
storedRoutes: Map<string, IStoredRoute>,
): Array<{ id: string; routeName: string }> {
const routes: Array<{ id: string; routeName: string }> = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.networkTargetRef === targetId) {
routes.push({ id: routeId, routeName: stored.route.name || routeId });
}
}
return routes;
}
// =========================================================================
// Resolution
// =========================================================================
/**
* Resolve references for a single route.
* Materializes security profile and/or network target into the route's fields.
* Returns the resolved route and updated metadata.
*/
public resolveRoute(
route: plugins.smartproxy.IRouteConfig,
metadata?: IRouteMetadata,
): { route: plugins.smartproxy.IRouteConfig; metadata: IRouteMetadata } {
const resolvedMetadata: IRouteMetadata = { ...metadata };
if (resolvedMetadata.securityProfileRef) {
const resolvedSecurity = this.resolveSecurityProfile(resolvedMetadata.securityProfileRef);
if (resolvedSecurity) {
const profile = this.profiles.get(resolvedMetadata.securityProfileRef);
// Merge: profile provides base, route's inline values override
route = {
...route,
security: this.mergeSecurityFields(resolvedSecurity, route.security),
};
resolvedMetadata.securityProfileName = profile?.name;
resolvedMetadata.lastResolvedAt = Date.now();
} else {
logger.log('warn', `Security profile '${resolvedMetadata.securityProfileRef}' not found during resolution`);
}
}
if (resolvedMetadata.networkTargetRef) {
const target = this.targets.get(resolvedMetadata.networkTargetRef);
if (target) {
route = {
...route,
action: {
...route.action,
targets: [{
host: target.host as string,
port: target.port,
}],
},
};
resolvedMetadata.networkTargetName = target.name;
resolvedMetadata.lastResolvedAt = Date.now();
} else {
logger.log('warn', `Network target '${resolvedMetadata.networkTargetRef}' not found during resolution`);
}
}
return { route, metadata: resolvedMetadata };
}
// =========================================================================
// Reference lookup helpers
// =========================================================================
public async findRoutesByProfileRef(profileId: string): Promise<string[]> {
const docs = await StoredRouteDoc.findAll();
return docs
.filter((doc) => doc.metadata?.securityProfileRef === profileId)
.map((doc) => doc.id);
}
public async findRoutesByTargetRef(targetId: string): Promise<string[]> {
const docs = await StoredRouteDoc.findAll();
return docs
.filter((doc) => doc.metadata?.networkTargetRef === targetId)
.map((doc) => doc.id);
}
public findRoutesByProfileRefSync(profileId: string, storedRoutes: Map<string, IStoredRoute>): string[] {
const ids: string[] = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.securityProfileRef === profileId) {
ids.push(routeId);
}
}
return ids;
}
public findRoutesByTargetRefSync(targetId: string, storedRoutes: Map<string, IStoredRoute>): string[] {
const ids: string[] = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.networkTargetRef === targetId) {
ids.push(routeId);
}
}
return ids;
}
// =========================================================================
// Private: security profile resolution with inheritance
// =========================================================================
private resolveSecurityProfile(
profileId: string,
visited: Set<string> = new Set(),
depth: number = 0,
): IRouteSecurity | null {
if (depth > MAX_INHERITANCE_DEPTH) {
logger.log('warn', `Max inheritance depth (${MAX_INHERITANCE_DEPTH}) exceeded resolving profile '${profileId}'`);
return null;
}
if (visited.has(profileId)) {
logger.log('warn', `Circular inheritance detected for profile '${profileId}'`);
return null;
}
const profile = this.profiles.get(profileId);
if (!profile) return null;
visited.add(profileId);
// Start with an empty base
let baseSecurity: IRouteSecurity = {};
// Resolve parent profiles first (top-down, later overrides earlier)
if (profile.extendsProfiles?.length) {
for (const parentId of profile.extendsProfiles) {
const parentSecurity = this.resolveSecurityProfile(parentId, new Set(visited), depth + 1);
if (parentSecurity) {
baseSecurity = this.mergeSecurityFields(baseSecurity, parentSecurity);
}
}
}
// Apply this profile's security on top
return this.mergeSecurityFields(baseSecurity, profile.security);
}
/**
* Merge two IRouteSecurity objects.
* `override` values take precedence over `base` values.
* For ipAllowList/ipBlockList: union arrays and deduplicate.
* For scalar/object fields: override wins if present.
*/
private mergeSecurityFields(
base: IRouteSecurity | undefined,
override: IRouteSecurity | undefined,
): IRouteSecurity {
if (!base && !override) return {};
if (!base) return { ...override };
if (!override) return { ...base };
const merged: IRouteSecurity = { ...base };
// IP lists: union
if (override.ipAllowList || base.ipAllowList) {
merged.ipAllowList = [...new Set([
...(base.ipAllowList || []),
...(override.ipAllowList || []),
])];
}
if (override.ipBlockList || base.ipBlockList) {
merged.ipBlockList = [...new Set([
...(base.ipBlockList || []),
...(override.ipBlockList || []),
])];
}
// Scalar/object fields: override wins
if (override.maxConnections !== undefined) merged.maxConnections = override.maxConnections;
if (override.rateLimit !== undefined) merged.rateLimit = override.rateLimit;
if (override.authentication !== undefined) merged.authentication = override.authentication;
if (override.basicAuth !== undefined) merged.basicAuth = override.basicAuth;
if (override.jwtAuth !== undefined) merged.jwtAuth = override.jwtAuth;
return merged;
}
// =========================================================================
// Private: persistence
// =========================================================================
private async loadProfiles(): Promise<void> {
const docs = await SecurityProfileDoc.findAll();
for (const doc of docs) {
if (doc.id) {
this.profiles.set(doc.id, {
id: doc.id,
name: doc.name,
description: doc.description,
security: doc.security,
extendsProfiles: doc.extendsProfiles,
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
createdBy: doc.createdBy,
});
}
}
if (this.profiles.size > 0) {
logger.log('info', `Loaded ${this.profiles.size} security profile(s) from storage`);
}
}
private async loadTargets(): Promise<void> {
const docs = await NetworkTargetDoc.findAll();
for (const doc of docs) {
if (doc.id) {
this.targets.set(doc.id, {
id: doc.id,
name: doc.name,
description: doc.description,
host: doc.host,
port: doc.port,
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
createdBy: doc.createdBy,
});
}
}
if (this.targets.size > 0) {
logger.log('info', `Loaded ${this.targets.size} network target(s) from storage`);
}
}
private async persistProfile(profile: ISecurityProfile): Promise<void> {
const existingDoc = await SecurityProfileDoc.findById(profile.id);
if (existingDoc) {
existingDoc.name = profile.name;
existingDoc.description = profile.description;
existingDoc.security = profile.security;
existingDoc.extendsProfiles = profile.extendsProfiles;
existingDoc.updatedAt = profile.updatedAt;
await existingDoc.save();
} else {
const doc = new SecurityProfileDoc();
doc.id = profile.id;
doc.name = profile.name;
doc.description = profile.description;
doc.security = profile.security;
doc.extendsProfiles = profile.extendsProfiles;
doc.createdAt = profile.createdAt;
doc.updatedAt = profile.updatedAt;
doc.createdBy = profile.createdBy;
await doc.save();
}
}
private async persistTarget(target: INetworkTarget): Promise<void> {
const existingDoc = await NetworkTargetDoc.findById(target.id);
if (existingDoc) {
existingDoc.name = target.name;
existingDoc.description = target.description;
existingDoc.host = target.host;
existingDoc.port = target.port;
existingDoc.updatedAt = target.updatedAt;
await existingDoc.save();
} else {
const doc = new NetworkTargetDoc();
doc.id = target.id;
doc.name = target.name;
doc.description = target.description;
doc.host = target.host;
doc.port = target.port;
doc.createdAt = target.createdAt;
doc.updatedAt = target.updatedAt;
doc.createdBy = target.createdBy;
await doc.save();
}
}
// =========================================================================
// Private: ref cleanup on force-delete
// =========================================================================
private async clearProfileRefsOnRoutes(routeIds: string[]): Promise<void> {
for (const routeId of routeIds) {
const doc = await StoredRouteDoc.findById(routeId);
if (doc?.metadata) {
doc.metadata = {
...doc.metadata,
securityProfileRef: undefined,
securityProfileName: undefined,
};
doc.updatedAt = Date.now();
await doc.save();
}
}
}
private async clearTargetRefsOnRoutes(routeIds: string[]): Promise<void> {
for (const routeId of routeIds) {
const doc = await StoredRouteDoc.findById(routeId);
if (doc?.metadata) {
doc.metadata = {
...doc.metadata,
networkTargetRef: undefined,
networkTargetName: undefined,
};
doc.updatedAt = Date.now();
await doc.save();
}
}
}
}

View File

@@ -6,9 +6,11 @@ import type {
IRouteOverride,
IMergedRoute,
IRouteWarning,
IRouteMetadata,
} from '../../ts_interfaces/data/route-management.js';
import type { IDcRouterRouteConfig } from '../../ts_interfaces/data/remoteingress.js';
import { type IHttp3Config, augmentRouteWithHttp3 } from '../http3/index.js';
import type { ReferenceResolver } from './classes.reference-resolver.js';
export class RouteConfigManager {
private storedRoutes = new Map<string, IStoredRoute>();
@@ -20,8 +22,15 @@ export class RouteConfigManager {
private getSmartProxy: () => plugins.smartproxy.SmartProxy | undefined,
private getHttp3Config?: () => IHttp3Config | undefined,
private getVpnAllowList?: (tags?: string[]) => string[],
private referenceResolver?: ReferenceResolver,
private onRoutesApplied?: (routes: plugins.smartproxy.IRouteConfig[]) => void,
) {}
/** Expose stored routes map for reference resolution lookups. */
public getStoredRoutes(): Map<string, IStoredRoute> {
return this.storedRoutes;
}
/**
* Load persisted routes and overrides, compute warnings, apply to SmartProxy.
*/
@@ -62,6 +71,7 @@ export class RouteConfigManager {
storedRouteId: stored.id,
createdAt: stored.createdAt,
updatedAt: stored.updatedAt,
metadata: stored.metadata,
});
}
@@ -76,6 +86,7 @@ export class RouteConfigManager {
route: plugins.smartproxy.IRouteConfig,
createdBy: string,
enabled = true,
metadata?: IRouteMetadata,
): Promise<string> {
const id = plugins.uuid.v4();
const now = Date.now();
@@ -85,6 +96,14 @@ export class RouteConfigManager {
route.name = `programmatic-${id.slice(0, 8)}`;
}
// Resolve references if metadata has refs and resolver is available
let resolvedMetadata = metadata;
if (metadata && this.referenceResolver) {
const resolved = this.referenceResolver.resolveRoute(route, metadata);
route = resolved.route;
resolvedMetadata = resolved.metadata;
}
const stored: IStoredRoute = {
id,
route,
@@ -92,6 +111,7 @@ export class RouteConfigManager {
createdAt: now,
updatedAt: now,
createdBy,
metadata: resolvedMetadata,
};
this.storedRoutes.set(id, stored);
@@ -102,7 +122,11 @@ export class RouteConfigManager {
public async updateRoute(
id: string,
patch: { route?: Partial<plugins.smartproxy.IRouteConfig>; enabled?: boolean },
patch: {
route?: Partial<plugins.smartproxy.IRouteConfig>;
enabled?: boolean;
metadata?: Partial<IRouteMetadata>;
},
): Promise<boolean> {
const stored = this.storedRoutes.get(id);
if (!stored) return false;
@@ -113,6 +137,17 @@ export class RouteConfigManager {
if (patch.enabled !== undefined) {
stored.enabled = patch.enabled;
}
if (patch.metadata !== undefined) {
stored.metadata = { ...stored.metadata, ...patch.metadata };
}
// Re-resolve if metadata refs exist and resolver is available
if (stored.metadata && this.referenceResolver) {
const resolved = this.referenceResolver.resolveRoute(stored.route, stored.metadata);
stored.route = resolved.route;
stored.metadata = resolved.metadata;
}
stored.updatedAt = Date.now();
await this.persistRoute(stored);
@@ -188,6 +223,7 @@ export class RouteConfigManager {
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
createdBy: doc.createdBy,
metadata: doc.metadata,
});
}
}
@@ -220,6 +256,7 @@ export class RouteConfigManager {
existingDoc.enabled = stored.enabled;
existingDoc.updatedAt = stored.updatedAt;
existingDoc.createdBy = stored.createdBy;
existingDoc.metadata = stored.metadata;
await existingDoc.save();
} else {
const doc = new StoredRouteDoc();
@@ -229,6 +266,7 @@ export class RouteConfigManager {
doc.createdAt = stored.createdAt;
doc.updatedAt = stored.updatedAt;
doc.createdBy = stored.createdBy;
doc.metadata = stored.metadata;
await doc.save();
}
}
@@ -277,6 +315,32 @@ export class RouteConfigManager {
}
}
// =========================================================================
// Re-resolve routes after profile/target changes
// =========================================================================
/**
* Re-resolve specific routes by ID (after a profile or target is updated).
* Persists each route and calls applyRoutes() once at the end.
*/
public async reResolveRoutes(routeIds: string[]): Promise<void> {
if (!this.referenceResolver || routeIds.length === 0) return;
for (const routeId of routeIds) {
const stored = this.storedRoutes.get(routeId);
if (!stored?.metadata) continue;
const resolved = this.referenceResolver.resolveRoute(stored.route, stored.metadata);
stored.route = resolved.route;
stored.metadata = resolved.metadata;
stored.updatedAt = Date.now();
await this.persistRoute(stored);
}
await this.applyRoutes();
logger.log('info', `Re-resolved ${routeIds.length} route(s) after profile/target change`);
}
// =========================================================================
// Private: apply merged routes to SmartProxy
// =========================================================================
@@ -330,6 +394,12 @@ export class RouteConfigManager {
}
await smartProxy.updateRoutes(enabledRoutes);
// Notify listeners (e.g. RemoteIngressManager) of the merged route set
if (this.onRoutesApplied) {
this.onRoutesApplied(enabledRoutes);
}
logger.log('info', `Applied ${enabledRoutes.length} routes to SmartProxy (${this.storedRoutes.size} programmatic, ${this.overrides.size} overrides)`);
}
}

View File

@@ -1,4 +1,6 @@
// Export validation tools only
export * from './validator.js';
export { RouteConfigManager } from './classes.route-config-manager.js';
export { ApiTokenManager } from './classes.api-token-manager.js';
export { ApiTokenManager } from './classes.api-token-manager.js';
export { ReferenceResolver } from './classes.reference-resolver.js';
export { DbSeeder } from './classes.db-seeder.js';

View File

@@ -0,0 +1,48 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
const getDb = () => DcRouterDb.getInstance().getDb();
@plugins.smartdata.Collection(() => getDb())
export class NetworkTargetDoc extends plugins.smartdata.SmartDataDbDoc<NetworkTargetDoc, NetworkTargetDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public id!: string;
@plugins.smartdata.svDb()
public name: string = '';
@plugins.smartdata.svDb()
public description?: string;
@plugins.smartdata.svDb()
public host!: string | string[];
@plugins.smartdata.svDb()
public port!: number;
@plugins.smartdata.svDb()
public createdAt!: number;
@plugins.smartdata.svDb()
public updatedAt!: number;
@plugins.smartdata.svDb()
public createdBy!: string;
constructor() {
super();
}
public static async findById(id: string): Promise<NetworkTargetDoc | null> {
return await NetworkTargetDoc.getInstance({ id });
}
public static async findByName(name: string): Promise<NetworkTargetDoc | null> {
return await NetworkTargetDoc.getInstance({ name });
}
public static async findAll(): Promise<NetworkTargetDoc[]> {
return await NetworkTargetDoc.getInstances({});
}
}

View File

@@ -0,0 +1,49 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
import type { IRouteSecurity } from '../../../ts_interfaces/data/route-management.js';
const getDb = () => DcRouterDb.getInstance().getDb();
@plugins.smartdata.Collection(() => getDb())
export class SecurityProfileDoc extends plugins.smartdata.SmartDataDbDoc<SecurityProfileDoc, SecurityProfileDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public id!: string;
@plugins.smartdata.svDb()
public name: string = '';
@plugins.smartdata.svDb()
public description?: string;
@plugins.smartdata.svDb()
public security!: IRouteSecurity;
@plugins.smartdata.svDb()
public extendsProfiles?: string[];
@plugins.smartdata.svDb()
public createdAt!: number;
@plugins.smartdata.svDb()
public updatedAt!: number;
@plugins.smartdata.svDb()
public createdBy!: string;
constructor() {
super();
}
public static async findById(id: string): Promise<SecurityProfileDoc | null> {
return await SecurityProfileDoc.getInstance({ id });
}
public static async findByName(name: string): Promise<SecurityProfileDoc | null> {
return await SecurityProfileDoc.getInstance({ name });
}
public static async findAll(): Promise<SecurityProfileDoc[]> {
return await SecurityProfileDoc.getInstances({});
}
}

View File

@@ -1,5 +1,6 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
import type { IRouteMetadata } from '../../../ts_interfaces/data/route-management.js';
const getDb = () => DcRouterDb.getInstance().getDb();
@@ -24,6 +25,9 @@ export class StoredRouteDoc extends plugins.smartdata.SmartDataDbDoc<StoredRoute
@plugins.smartdata.svDb()
public createdBy!: string;
@plugins.smartdata.svDb()
public metadata?: IRouteMetadata;
constructor() {
super();
}

View File

@@ -39,6 +39,30 @@ export class VpnClientDoc extends plugins.smartdata.SmartDataDbDoc<VpnClientDoc,
@plugins.smartdata.svDb()
public expiresAt?: string;
@plugins.smartdata.svDb()
public forceDestinationSmartproxy: boolean = true;
@plugins.smartdata.svDb()
public destinationAllowList?: string[];
@plugins.smartdata.svDb()
public destinationBlockList?: string[];
@plugins.smartdata.svDb()
public useHostIp?: boolean;
@plugins.smartdata.svDb()
public useDhcp?: boolean;
@plugins.smartdata.svDb()
public staticIp?: string;
@plugins.smartdata.svDb()
public forceVlan?: boolean;
@plugins.smartdata.svDb()
public vlanId?: number;
constructor() {
super();
}

View File

@@ -6,6 +6,8 @@ export * from './classes.cached.ip.reputation.js';
export * from './classes.stored-route.doc.js';
export * from './classes.route-override.doc.js';
export * from './classes.api-token.doc.js';
export * from './classes.security-profile.doc.js';
export * from './classes.network-target.doc.js';
// VPN document classes
export * from './classes.vpn-server-keys.doc.js';

View File

@@ -29,6 +29,8 @@ export class OpsServer {
private routeManagementHandler!: handlers.RouteManagementHandler;
private apiTokenHandler!: handlers.ApiTokenHandler;
private vpnHandler!: handlers.VpnHandler;
private securityProfileHandler!: handlers.SecurityProfileHandler;
private networkTargetHandler!: handlers.NetworkTargetHandler;
constructor(dcRouterRefArg: DcRouter) {
this.dcRouterRef = dcRouterRefArg;
@@ -88,6 +90,8 @@ export class OpsServer {
this.routeManagementHandler = new handlers.RouteManagementHandler(this);
this.apiTokenHandler = new handlers.ApiTokenHandler(this);
this.vpnHandler = new handlers.VpnHandler(this);
this.securityProfileHandler = new handlers.SecurityProfileHandler(this);
this.networkTargetHandler = new handlers.NetworkTargetHandler(this);
console.log('✅ OpsServer TypedRequest handlers initialized');
}

View File

@@ -9,4 +9,6 @@ export * from './certificate.handler.js';
export * from './remoteingress.handler.js';
export * from './route-management.handler.js';
export * from './api-token.handler.js';
export * from './vpn.handler.js';
export * from './vpn.handler.js';
export * from './security-profile.handler.js';
export * from './network-target.handler.js';

View File

@@ -0,0 +1,167 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
export class NetworkTargetHandler {
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 all network targets
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTargets>(
'getNetworkTargets',
async (dataArg) => {
await this.requireAuth(dataArg, 'targets:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { targets: [] };
}
return { targets: resolver.listTargets() };
},
),
);
// Get a single network target
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTarget>(
'getNetworkTarget',
async (dataArg) => {
await this.requireAuth(dataArg, 'targets:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { target: null };
}
return { target: resolver.getTarget(dataArg.id) || null };
},
),
);
// Create a network target
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateNetworkTarget>(
'createNetworkTarget',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'targets:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { success: false, message: 'Reference resolver not initialized' };
}
const id = await resolver.createTarget({
name: dataArg.name,
description: dataArg.description,
host: dataArg.host,
port: dataArg.port,
createdBy: userId,
});
return { success: true, id };
},
),
);
// Update a network target
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateNetworkTarget>(
'updateNetworkTarget',
async (dataArg) => {
await this.requireAuth(dataArg, 'targets:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { success: false, message: 'Not initialized' };
}
const { affectedRouteIds } = await resolver.updateTarget(dataArg.id, {
name: dataArg.name,
description: dataArg.description,
host: dataArg.host,
port: dataArg.port,
});
if (affectedRouteIds.length > 0) {
await manager.reResolveRoutes(affectedRouteIds);
}
return { success: true, affectedRouteCount: affectedRouteIds.length };
},
),
);
// Delete a network target
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteNetworkTarget>(
'deleteNetworkTarget',
async (dataArg) => {
await this.requireAuth(dataArg, 'targets:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { success: false, message: 'Not initialized' };
}
const result = await resolver.deleteTarget(
dataArg.id,
dataArg.force ?? false,
manager.getStoredRoutes(),
);
if (result.success && dataArg.force) {
await manager.applyRoutes();
}
return result;
},
),
);
// Get routes using a network target
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTargetUsage>(
'getNetworkTargetUsage',
async (dataArg) => {
await this.requireAuth(dataArg, 'targets:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { routes: [] };
}
const usage = resolver.getTargetUsageForId(dataArg.id, manager.getStoredRoutes());
return { routes: usage.map((u) => ({ id: u.id, name: u.routeName })) };
},
),
);
}
}

View File

@@ -71,7 +71,7 @@ export class RouteManagementHandler {
if (!manager) {
return { success: false, message: 'Route management not initialized' };
}
const id = await manager.createRoute(dataArg.route, userId, dataArg.enabled ?? true);
const id = await manager.createRoute(dataArg.route, userId, dataArg.enabled ?? true, dataArg.metadata);
return { success: true, storedRouteId: id };
},
),
@@ -90,6 +90,7 @@ export class RouteManagementHandler {
const ok = await manager.updateRoute(dataArg.id, {
route: dataArg.route as any,
enabled: dataArg.enabled,
metadata: dataArg.metadata,
});
return { success: ok, message: ok ? undefined : 'Route not found' };
},

View File

@@ -0,0 +1,169 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
export class SecurityProfileHandler {
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 all security profiles
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfiles>(
'getSecurityProfiles',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { profiles: [] };
}
return { profiles: resolver.listProfiles() };
},
),
);
// Get a single security profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfile>(
'getSecurityProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { profile: null };
}
return { profile: resolver.getProfile(dataArg.id) || null };
},
),
);
// Create a security profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSecurityProfile>(
'createSecurityProfile',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { success: false, message: 'Reference resolver not initialized' };
}
const id = await resolver.createProfile({
name: dataArg.name,
description: dataArg.description,
security: dataArg.security,
extendsProfiles: dataArg.extendsProfiles,
createdBy: userId,
});
return { success: true, id };
},
),
);
// Update a security profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSecurityProfile>(
'updateSecurityProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { success: false, message: 'Not initialized' };
}
const { affectedRouteIds } = await resolver.updateProfile(dataArg.id, {
name: dataArg.name,
description: dataArg.description,
security: dataArg.security,
extendsProfiles: dataArg.extendsProfiles,
});
// Propagate to affected routes
if (affectedRouteIds.length > 0) {
await manager.reResolveRoutes(affectedRouteIds);
}
return { success: true, affectedRouteCount: affectedRouteIds.length };
},
),
);
// Delete a security profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSecurityProfile>(
'deleteSecurityProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { success: false, message: 'Not initialized' };
}
const result = await resolver.deleteProfile(
dataArg.id,
dataArg.force ?? false,
manager.getStoredRoutes(),
);
// If force-deleted with affected routes, re-apply
if (result.success && dataArg.force) {
await manager.applyRoutes();
}
return result;
},
),
);
// Get routes using a security profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfileUsage>(
'getSecurityProfileUsage',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
return { routes: [] };
}
const usage = resolver.getProfileUsageForId(dataArg.id, manager.getStoredRoutes());
return { routes: usage.map((u) => ({ id: u.id, name: u.routeName })) };
},
),
);
}
}

View File

@@ -31,6 +31,14 @@ export class VpnHandler {
createdAt: c.createdAt,
updatedAt: c.updatedAt,
expiresAt: c.expiresAt,
forceDestinationSmartproxy: c.forceDestinationSmartproxy ?? true,
destinationAllowList: c.destinationAllowList,
destinationBlockList: c.destinationBlockList,
useHostIp: c.useHostIp,
useDhcp: c.useDhcp,
staticIp: c.staticIp,
forceVlan: c.forceVlan,
vlanId: c.vlanId,
}));
return { clients };
},
@@ -114,8 +122,21 @@ export class VpnHandler {
clientId: dataArg.clientId,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
description: dataArg.description,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
destinationBlockList: dataArg.destinationBlockList,
useHostIp: dataArg.useHostIp,
useDhcp: dataArg.useDhcp,
staticIp: dataArg.staticIp,
forceVlan: dataArg.forceVlan,
vlanId: dataArg.vlanId,
});
// Retrieve the persisted doc to get dcrouter-level fields
const persistedClient = manager.listClients().find(
(c) => c.clientId === bundle.entry.clientId,
);
return {
success: true,
client: {
@@ -127,6 +148,14 @@ export class VpnHandler {
createdAt: Date.now(),
updatedAt: Date.now(),
expiresAt: bundle.entry.expiresAt,
forceDestinationSmartproxy: persistedClient?.forceDestinationSmartproxy ?? true,
destinationAllowList: persistedClient?.destinationAllowList,
destinationBlockList: persistedClient?.destinationBlockList,
useHostIp: persistedClient?.useHostIp,
useDhcp: persistedClient?.useDhcp,
staticIp: persistedClient?.staticIp,
forceVlan: persistedClient?.forceVlan,
vlanId: persistedClient?.vlanId,
},
wireguardConfig: bundle.wireguardConfig,
};
@@ -151,6 +180,14 @@ export class VpnHandler {
await manager.updateClient(dataArg.clientId, {
description: dataArg.description,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
destinationBlockList: dataArg.destinationBlockList,
useHostIp: dataArg.useHostIp,
useDhcp: dataArg.useDhcp,
staticIp: dataArg.staticIp,
forceVlan: dataArg.forceVlan,
vlanId: dataArg.vlanId,
});
return { success: true };
} catch (err: unknown) {

View File

@@ -30,6 +30,17 @@ export interface IVpnManagerConfig {
* Called at config generation time (create/export). Returns CIDRs for WireGuard AllowedIPs.
* When not set, defaults to [subnet]. */
getClientAllowedIPs?: (clientTags: string[]) => Promise<string[]>;
/** Forwarding mode: 'socket' (default, userspace NAT), 'bridge' (L2 bridge to host LAN),
* or 'hybrid' (socket default, bridge for clients with useHostIp=true) */
forwardingMode?: 'socket' | 'bridge' | 'hybrid';
/** LAN subnet CIDR for bridge mode (e.g., '192.168.1.0/24') */
bridgeLanSubnet?: string;
/** Physical network interface for bridge mode (auto-detected if omitted) */
bridgePhysicalInterface?: string;
/** Start of VPN client IP range in LAN subnet (host offset, default: 200) */
bridgeIpRangeStart?: number;
/** End of VPN client IP range in LAN subnet (host offset, default: 250) */
bridgeIpRangeEnd?: number;
}
/**
@@ -69,8 +80,12 @@ export class VpnManager {
// Build client entries for the daemon
const clientEntries: plugins.smartvpn.IClientEntry[] = [];
let anyClientUsesHostIp = false;
for (const client of this.clients.values()) {
clientEntries.push({
if (client.useHostIp) {
anyClientUsesHostIp = true;
}
const entry: plugins.smartvpn.IClientEntry = {
clientId: client.clientId,
publicKey: client.noisePublicKey,
wgPublicKey: client.wgPublicKey,
@@ -79,35 +94,65 @@ export class VpnManager {
description: client.description,
assignedIp: client.assignedIp,
expiresAt: client.expiresAt,
});
security: this.buildClientSecurity(client),
};
// Pass per-client bridge fields if present (for hybrid/bridge mode)
if (client.useHostIp !== undefined) (entry as any).useHostIp = client.useHostIp;
if (client.useDhcp !== undefined) (entry as any).useDhcp = client.useDhcp;
if (client.staticIp !== undefined) (entry as any).staticIp = client.staticIp;
if (client.forceVlan !== undefined) (entry as any).forceVlan = client.forceVlan;
if (client.vlanId !== undefined) (entry as any).vlanId = client.vlanId;
clientEntries.push(entry);
}
const subnet = this.getSubnet();
const wgListenPort = this.config.wgListenPort ?? 51820;
// Auto-detect hybrid mode: if any persisted client uses host IP and mode is
// 'socket' (or unset), upgrade to 'hybrid' so the daemon can handle both
let configuredMode = this.config.forwardingMode ?? 'socket';
if (anyClientUsesHostIp && configuredMode === 'socket') {
configuredMode = 'hybrid';
logger.log('info', 'VPN: Auto-upgrading forwarding mode to hybrid (client with useHostIp detected)');
}
const forwardingMode = configuredMode === 'hybrid' ? 'hybrid' : configuredMode;
const isBridge = forwardingMode === 'bridge';
// Create and start VpnServer
this.vpnServer = new plugins.smartvpn.VpnServer({
transport: { transport: 'stdio' },
});
// Default destination policy: bridge mode allows traffic through directly,
// socket mode forces traffic to SmartProxy on 127.0.0.1
const defaultDestinationPolicy: plugins.smartvpn.IDestinationPolicy = isBridge
? { default: 'allow' as const }
: { default: 'forceTarget' as const, target: '127.0.0.1' };
const serverConfig: plugins.smartvpn.IVpnServerConfig = {
listenAddr: '0.0.0.0:0', // WS listener not strictly needed but required field
privateKey: this.serverKeys.noisePrivateKey,
publicKey: this.serverKeys.noisePublicKey,
subnet,
dns: this.config.dns,
forwardingMode: 'socket',
forwardingMode: forwardingMode as any,
transportMode: 'all',
wgPrivateKey: this.serverKeys.wgPrivateKey,
wgListenPort,
clients: clientEntries,
socketForwardProxyProtocol: true,
destinationPolicy: this.config.destinationPolicy
?? { default: 'forceTarget' as const, target: '127.0.0.1' },
socketForwardProxyProtocol: !isBridge,
destinationPolicy: this.config.destinationPolicy ?? defaultDestinationPolicy,
serverEndpoint: this.config.serverEndpoint
? `${this.config.serverEndpoint}:${wgListenPort}`
: undefined,
clientAllowedIPs: [subnet],
// Bridge-specific config
...(isBridge ? {
bridgeLanSubnet: this.config.bridgeLanSubnet,
bridgePhysicalInterface: this.config.bridgePhysicalInterface,
bridgeIpRangeStart: this.config.bridgeIpRangeStart,
bridgeIpRangeEnd: this.config.bridgeIpRangeEnd,
} : {}),
};
await this.vpnServer.start(serverConfig);
@@ -154,6 +199,14 @@ export class VpnManager {
clientId: string;
serverDefinedClientTags?: string[];
description?: string;
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
}): Promise<plugins.smartvpn.IClientConfigBundle> {
if (!this.vpnServer) {
throw new Error('VPN server not running');
@@ -188,9 +241,39 @@ export class VpnManager {
doc.createdAt = Date.now();
doc.updatedAt = Date.now();
doc.expiresAt = bundle.entry.expiresAt;
if (opts.forceDestinationSmartproxy !== undefined) {
doc.forceDestinationSmartproxy = opts.forceDestinationSmartproxy;
}
if (opts.destinationAllowList !== undefined) {
doc.destinationAllowList = opts.destinationAllowList;
}
if (opts.destinationBlockList !== undefined) {
doc.destinationBlockList = opts.destinationBlockList;
}
if (opts.useHostIp !== undefined) {
doc.useHostIp = opts.useHostIp;
}
if (opts.useDhcp !== undefined) {
doc.useDhcp = opts.useDhcp;
}
if (opts.staticIp !== undefined) {
doc.staticIp = opts.staticIp;
}
if (opts.forceVlan !== undefined) {
doc.forceVlan = opts.forceVlan;
}
if (opts.vlanId !== undefined) {
doc.vlanId = opts.vlanId;
}
this.clients.set(doc.clientId, doc);
await this.persistClient(doc);
// Sync per-client security to the running daemon
const security = this.buildClientSecurity(doc);
if (security.destinationPolicy) {
await this.vpnServer!.updateClient(doc.clientId, { security });
}
this.config.onClientChanged?.();
return bundle;
}
@@ -254,13 +337,36 @@ export class VpnManager {
public async updateClient(clientId: string, update: {
description?: string;
serverDefinedClientTags?: string[];
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
}): Promise<void> {
const client = this.clients.get(clientId);
if (!client) throw new Error(`Client not found: ${clientId}`);
if (update.description !== undefined) client.description = update.description;
if (update.serverDefinedClientTags !== undefined) client.serverDefinedClientTags = update.serverDefinedClientTags;
if (update.forceDestinationSmartproxy !== undefined) client.forceDestinationSmartproxy = update.forceDestinationSmartproxy;
if (update.destinationAllowList !== undefined) client.destinationAllowList = update.destinationAllowList;
if (update.destinationBlockList !== undefined) client.destinationBlockList = update.destinationBlockList;
if (update.useHostIp !== undefined) client.useHostIp = update.useHostIp;
if (update.useDhcp !== undefined) client.useDhcp = update.useDhcp;
if (update.staticIp !== undefined) client.staticIp = update.staticIp;
if (update.forceVlan !== undefined) client.forceVlan = update.forceVlan;
if (update.vlanId !== undefined) client.vlanId = update.vlanId;
client.updatedAt = Date.now();
await this.persistClient(client);
// Sync per-client security to the running daemon
if (this.vpnServer) {
const security = this.buildClientSecurity(client);
await this.vpnServer.updateClient(clientId, { security });
}
this.config.onClientChanged?.();
}
@@ -378,6 +484,37 @@ export class VpnManager {
};
}
// ── Per-client security ────────────────────────────────────────────────
/**
* Build per-client security settings for the smartvpn daemon.
* Maps dcrouter-level fields (forceDestinationSmartproxy, allow/block lists)
* to smartvpn's IClientSecurity with a destinationPolicy.
*/
private buildClientSecurity(client: VpnClientDoc): plugins.smartvpn.IClientSecurity {
const security: plugins.smartvpn.IClientSecurity = {};
const forceSmartproxy = client.forceDestinationSmartproxy ?? true;
if (!forceSmartproxy) {
// Client traffic goes directly — not forced to SmartProxy
security.destinationPolicy = {
default: 'allow' as const,
blockList: client.destinationBlockList,
};
} else if (client.destinationAllowList?.length || client.destinationBlockList?.length) {
// Client is forced to SmartProxy, but with per-client allow/block overrides
security.destinationPolicy = {
default: 'forceTarget' as const,
target: '127.0.0.1',
allowList: client.destinationAllowList,
blockList: client.destinationBlockList,
};
}
// else: no per-client policy, server-wide applies
return security;
}
// ── Private helpers ────────────────────────────────────────────────────
private async loadOrGenerateServerKeys(): Promise<VpnServerKeysDoc> {

View File

@@ -1,10 +1,77 @@
import type { IRouteConfig } from '@push.rocks/smartproxy';
// Derive IRouteSecurity from IRouteConfig since it's not directly exported
export type IRouteSecurity = NonNullable<IRouteConfig['security']>;
// ============================================================================
// Route Management Data Types
// ============================================================================
export type TApiTokenScope = 'routes:read' | 'routes:write' | 'config:read' | 'tokens:read' | 'tokens:manage';
export type TApiTokenScope =
| 'routes:read' | 'routes:write'
| 'config:read'
| 'tokens:read' | 'tokens:manage'
| 'profiles:read' | 'profiles:write'
| 'targets:read' | 'targets:write';
// ============================================================================
// Security Profile Types
// ============================================================================
/**
* A reusable, named security profile that can be referenced by routes.
* Stores the full IRouteSecurity shape from SmartProxy.
*/
export interface ISecurityProfile {
id: string;
name: string;
description?: string;
/** The security configuration — mirrors SmartProxy's IRouteSecurity. */
security: IRouteSecurity;
/** IDs of profiles this one extends (resolved top-down, later overrides earlier). */
extendsProfiles?: string[];
createdAt: number;
updatedAt: number;
createdBy: string;
}
// ============================================================================
// Network Target Types
// ============================================================================
/**
* A reusable, named network target (host + port) that can be referenced by routes.
*/
export interface INetworkTarget {
id: string;
name: string;
description?: string;
host: string | string[];
port: number;
createdAt: number;
updatedAt: number;
createdBy: string;
}
// ============================================================================
// Route Metadata Types
// ============================================================================
/**
* Metadata on a stored route tracking where its resolved values came from.
*/
export interface IRouteMetadata {
/** ID of the SecurityProfileDoc used to resolve this route's security. */
securityProfileRef?: string;
/** ID of the NetworkTargetDoc used to resolve this route's targets. */
networkTargetRef?: string;
/** Snapshot of the profile name at resolution time, for display. */
securityProfileName?: string;
/** Snapshot of the target name at resolution time, for display. */
networkTargetName?: string;
/** Timestamp of last reference resolution. */
lastResolvedAt?: number;
}
/**
* A merged route combining hardcoded and programmatic sources.
@@ -17,6 +84,7 @@ export interface IMergedRoute {
storedRouteId?: string;
createdAt?: number;
updatedAt?: number;
metadata?: IRouteMetadata;
}
/**
@@ -55,6 +123,7 @@ export interface IStoredRoute {
createdAt: number;
updatedAt: number;
createdBy: string;
metadata?: IRouteMetadata;
}
/**

View File

@@ -10,6 +10,14 @@ export interface IVpnClient {
createdAt: number;
updatedAt: number;
expiresAt?: string;
forceDestinationSmartproxy: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
}
/**

View File

@@ -90,6 +90,13 @@ interface IIdentity {
| `IApiTokenInfo` | Token info: id, name, scopes, createdAt, expiresAt, enabled |
| `TApiTokenScope` | Token scopes: `routes:read`, `routes:write`, `config:read`, `tokens:read`, `tokens:manage` |
#### Security & Reference Interfaces
| Interface | Description |
|-----------|-------------|
| `ISecurityProfile` | Reusable security config: id, name, description, security (ipAllowList, ipBlockList, maxConnections, rateLimit, etc.), extendsProfiles |
| `INetworkTarget` | Reusable host:port destination: id, name, description, host (string or string[]), port |
| `IRouteMetadata` | Route-to-reference links: securityProfileRef, networkTargetRef, snapshot names, lastResolvedAt |
#### Remote Ingress Interfaces
| Interface | Description |
|-----------|-------------|
@@ -241,6 +248,26 @@ interface ICertificateInfo {
| `IReq_GetRadiusStatistics` | `getRadiusStatistics` | RADIUS stats |
| `IReq_GetRadiusAccountingSummary` | `getRadiusAccountingSummary` | Accounting summary |
#### 🛡️ Security Profiles
| Interface | Method | Description |
|-----------|--------|-------------|
| `IReq_GetSecurityProfiles` | `getSecurityProfiles` | List all security profiles |
| `IReq_GetSecurityProfile` | `getSecurityProfile` | Get a single profile by ID |
| `IReq_CreateSecurityProfile` | `createSecurityProfile` | Create a reusable security profile |
| `IReq_UpdateSecurityProfile` | `updateSecurityProfile` | Update a profile (propagates to routes) |
| `IReq_DeleteSecurityProfile` | `deleteSecurityProfile` | Delete a profile (with optional force) |
| `IReq_GetSecurityProfileUsage` | `getSecurityProfileUsage` | Get routes referencing a profile |
#### 🎯 Network Targets
| Interface | Method | Description |
|-----------|--------|-------------|
| `IReq_GetNetworkTargets` | `getNetworkTargets` | List all network targets |
| `IReq_GetNetworkTarget` | `getNetworkTarget` | Get a single target by ID |
| `IReq_CreateNetworkTarget` | `createNetworkTarget` | Create a reusable host:port target |
| `IReq_UpdateNetworkTarget` | `updateNetworkTarget` | Update a target (propagates to routes) |
| `IReq_DeleteNetworkTarget` | `deleteNetworkTarget` | Delete a target (with optional force) |
| `IReq_GetNetworkTargetUsage` | `getNetworkTargetUsage` | Get routes referencing a target |
## Example: Full API Integration
> 💡 **Tip:** For a higher-level, object-oriented API, use [`@serve.zone/dcrouter-apiclient`](https://www.npmjs.com/package/@serve.zone/dcrouter-apiclient) which wraps these interfaces with resource classes and builder patterns.

View File

@@ -9,4 +9,6 @@ export * from './certificate.js';
export * from './remoteingress.js';
export * from './route-management.js';
export * from './api-tokens.js';
export * from './vpn.js';
export * from './vpn.js';
export * from './security-profiles.js';
export * from './network-targets.js';

View File

@@ -0,0 +1,127 @@
import * as plugins from '../plugins.js';
import type * as authInterfaces from '../data/auth.js';
import type { INetworkTarget } from '../data/route-management.js';
// ============================================================================
// Network Target Endpoints
// ============================================================================
/**
* Get all network targets.
*/
export interface IReq_GetNetworkTargets extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetNetworkTargets
> {
method: 'getNetworkTargets';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
targets: INetworkTarget[];
};
}
/**
* Get a single network target by ID.
*/
export interface IReq_GetNetworkTarget extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetNetworkTarget
> {
method: 'getNetworkTarget';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
target: INetworkTarget | null;
};
}
/**
* Create a new network target.
*/
export interface IReq_CreateNetworkTarget extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_CreateNetworkTarget
> {
method: 'createNetworkTarget';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
name: string;
description?: string;
host: string | string[];
port: number;
};
response: {
success: boolean;
id?: string;
message?: string;
};
}
/**
* Update a network target.
*/
export interface IReq_UpdateNetworkTarget extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_UpdateNetworkTarget
> {
method: 'updateNetworkTarget';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
name?: string;
description?: string;
host?: string | string[];
port?: number;
};
response: {
success: boolean;
affectedRouteCount?: number;
message?: string;
};
}
/**
* Delete a network target.
*/
export interface IReq_DeleteNetworkTarget extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_DeleteNetworkTarget
> {
method: 'deleteNetworkTarget';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
force?: boolean;
};
response: {
success: boolean;
message?: string;
};
}
/**
* Get which routes reference a network target.
*/
export interface IReq_GetNetworkTargetUsage extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetNetworkTargetUsage
> {
method: 'getNetworkTargetUsage';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
routes: Array<{ id: string; name: string }>;
};
}

View File

@@ -1,6 +1,6 @@
import * as plugins from '../plugins.js';
import type * as authInterfaces from '../data/auth.js';
import type { IMergedRoute, IRouteWarning } from '../data/route-management.js';
import type { IMergedRoute, IRouteWarning, IRouteMetadata } from '../data/route-management.js';
import type { IRouteConfig } from '@push.rocks/smartproxy';
// ============================================================================
@@ -38,6 +38,7 @@ export interface IReq_CreateRoute extends plugins.typedrequestInterfaces.impleme
apiToken?: string;
route: IRouteConfig;
enabled?: boolean;
metadata?: IRouteMetadata;
};
response: {
success: boolean;
@@ -60,6 +61,7 @@ export interface IReq_UpdateRoute extends plugins.typedrequestInterfaces.impleme
id: string;
route?: Partial<IRouteConfig>;
enabled?: boolean;
metadata?: Partial<IRouteMetadata>;
};
response: {
success: boolean;

View File

@@ -0,0 +1,127 @@
import * as plugins from '../plugins.js';
import type * as authInterfaces from '../data/auth.js';
import type { ISecurityProfile, IRouteSecurity } from '../data/route-management.js';
// ============================================================================
// Security Profile Endpoints
// ============================================================================
/**
* Get all security profiles.
*/
export interface IReq_GetSecurityProfiles extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetSecurityProfiles
> {
method: 'getSecurityProfiles';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
profiles: ISecurityProfile[];
};
}
/**
* Get a single security profile by ID.
*/
export interface IReq_GetSecurityProfile extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetSecurityProfile
> {
method: 'getSecurityProfile';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
profile: ISecurityProfile | null;
};
}
/**
* Create a new security profile.
*/
export interface IReq_CreateSecurityProfile extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_CreateSecurityProfile
> {
method: 'createSecurityProfile';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
name: string;
description?: string;
security: IRouteSecurity;
extendsProfiles?: string[];
};
response: {
success: boolean;
id?: string;
message?: string;
};
}
/**
* Update a security profile.
*/
export interface IReq_UpdateSecurityProfile extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_UpdateSecurityProfile
> {
method: 'updateSecurityProfile';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
name?: string;
description?: string;
security?: IRouteSecurity;
extendsProfiles?: string[];
};
response: {
success: boolean;
affectedRouteCount?: number;
message?: string;
};
}
/**
* Delete a security profile.
*/
export interface IReq_DeleteSecurityProfile extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_DeleteSecurityProfile
> {
method: 'deleteSecurityProfile';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
force?: boolean;
};
response: {
success: boolean;
message?: string;
};
}
/**
* Get which routes reference a security profile.
*/
export interface IReq_GetSecurityProfileUsage extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetSecurityProfileUsage
> {
method: 'getSecurityProfileUsage';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
routes: Array<{ id: string; name: string }>;
};
}

View File

@@ -51,6 +51,14 @@ export interface IReq_CreateVpnClient extends plugins.typedrequestInterfaces.imp
clientId: string;
serverDefinedClientTags?: string[];
description?: string;
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
};
response: {
success: boolean;
@@ -74,6 +82,14 @@ export interface IReq_UpdateVpnClient extends plugins.typedrequestInterfaces.imp
clientId: string;
description?: string;
serverDefinedClientTags?: string[];
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
};
response: {
success: boolean;

View File

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

View File

@@ -110,7 +110,7 @@ export const configStatePart = await appState.getStatePart<IConfigState>(
// Determine initial view from URL path
const getInitialView = (): string => {
const path = typeof window !== 'undefined' ? window.location.pathname : '/';
const validViews = ['overview', 'network', 'emails', 'logs', 'routes', 'apitokens', 'configuration', 'security', 'certificates', 'remoteingress'];
const validViews = ['overview', 'network', 'emails', 'logs', 'routes', 'apitokens', 'configuration', 'security', 'certificates', 'remoteingress', 'securityprofiles', 'networktargets'];
const segments = path.split('/').filter(Boolean);
const view = segments[0];
return validViews.includes(view) ? view : 'overview';
@@ -427,6 +427,8 @@ export const setActiveViewAction = uiStatePart.createAction<string>(async (state
if (viewName === 'routes' && currentState.activeView !== 'routes') {
setTimeout(() => {
routeManagementStatePart.dispatchAction(fetchMergedRoutesAction, null);
// Also fetch profiles/targets for the Create Route dropdowns
profilesTargetsStatePart.dispatchAction(fetchProfilesAndTargetsAction, null);
}, 100);
}
@@ -444,6 +446,13 @@ export const setActiveViewAction = uiStatePart.createAction<string>(async (state
}, 100);
}
// If switching to security profiles or network targets views, fetch profiles/targets data
if ((viewName === 'securityprofiles' || viewName === 'networktargets') && currentState.activeView !== viewName) {
setTimeout(() => {
profilesTargetsStatePart.dispatchAction(fetchProfilesAndTargetsAction, null);
}, 100);
}
return {
...currentState,
activeView: viewName,
@@ -984,6 +993,14 @@ export const createVpnClientAction = vpnStatePart.createAction<{
clientId: string;
serverDefinedClientTags?: string[];
description?: string;
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
}>(async (statePartArg, dataArg, actionContext): Promise<IVpnState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
@@ -998,6 +1015,14 @@ export const createVpnClientAction = vpnStatePart.createAction<{
clientId: dataArg.clientId,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
description: dataArg.description,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
destinationBlockList: dataArg.destinationBlockList,
useHostIp: dataArg.useHostIp,
useDhcp: dataArg.useDhcp,
staticIp: dataArg.staticIp,
forceVlan: dataArg.forceVlan,
vlanId: dataArg.vlanId,
});
if (!response.success) {
@@ -1066,6 +1091,14 @@ export const updateVpnClientAction = vpnStatePart.createAction<{
clientId: string;
description?: string;
serverDefinedClientTags?: string[];
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
useHostIp?: boolean;
useDhcp?: boolean;
staticIp?: string;
forceVlan?: boolean;
vlanId?: number;
}>(async (statePartArg, dataArg, actionContext): Promise<IVpnState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
@@ -1080,6 +1113,14 @@ export const updateVpnClientAction = vpnStatePart.createAction<{
clientId: dataArg.clientId,
description: dataArg.description,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
destinationBlockList: dataArg.destinationBlockList,
useHostIp: dataArg.useHostIp,
useDhcp: dataArg.useDhcp,
staticIp: dataArg.staticIp,
forceVlan: dataArg.forceVlan,
vlanId: dataArg.vlanId,
});
if (!response.success) {
@@ -1101,6 +1142,241 @@ export const clearNewClientConfigAction = vpnStatePart.createAction(
},
);
// ============================================================================
// Security Profiles & Network Targets State
// ============================================================================
export interface IProfilesTargetsState {
profiles: interfaces.data.ISecurityProfile[];
targets: interfaces.data.INetworkTarget[];
isLoading: boolean;
error: string | null;
lastUpdated: number;
}
export const profilesTargetsStatePart = await appState.getStatePart<IProfilesTargetsState>(
'profilesTargets',
{
profiles: [],
targets: [],
isLoading: false,
error: null,
lastUpdated: 0,
},
'soft'
);
// ============================================================================
// Security Profiles & Network Targets Actions
// ============================================================================
export const fetchProfilesAndTargetsAction = profilesTargetsStatePart.createAction(
async (statePartArg): Promise<IProfilesTargetsState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
if (!context.identity) return currentState;
try {
const profilesRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetSecurityProfiles
>('/typedrequest', 'getSecurityProfiles');
const targetsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetNetworkTargets
>('/typedrequest', 'getNetworkTargets');
const [profilesResponse, targetsResponse] = await Promise.all([
profilesRequest.fire({ identity: context.identity }),
targetsRequest.fire({ identity: context.identity }),
]);
return {
profiles: profilesResponse.profiles,
targets: targetsResponse.targets,
isLoading: false,
error: null,
lastUpdated: Date.now(),
};
} catch (error) {
return {
...currentState,
isLoading: false,
error: error instanceof Error ? error.message : 'Failed to fetch profiles/targets',
};
}
}
);
export const createProfileAction = profilesTargetsStatePart.createAction<{
name: string;
description?: string;
security: any;
extendsProfiles?: string[];
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_CreateSecurityProfile
>('/typedrequest', 'createSecurityProfile');
await request.fire({
identity: context.identity!,
name: dataArg.name,
description: dataArg.description,
security: dataArg.security,
extendsProfiles: dataArg.extendsProfiles,
});
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to create profile',
};
}
});
export const updateProfileAction = profilesTargetsStatePart.createAction<{
id: string;
name?: string;
description?: string;
security?: any;
extendsProfiles?: string[];
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_UpdateSecurityProfile
>('/typedrequest', 'updateSecurityProfile');
await request.fire({
identity: context.identity!,
id: dataArg.id,
name: dataArg.name,
description: dataArg.description,
security: dataArg.security,
extendsProfiles: dataArg.extendsProfiles,
});
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to update profile',
};
}
});
export const deleteProfileAction = profilesTargetsStatePart.createAction<{
id: string;
force?: boolean;
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_DeleteSecurityProfile
>('/typedrequest', 'deleteSecurityProfile');
const response = await request.fire({
identity: context.identity!,
id: dataArg.id,
force: dataArg.force,
});
if (!response.success) {
return {
...statePartArg.getState()!,
error: response.message || 'Failed to delete profile',
};
}
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to delete profile',
};
}
});
export const createTargetAction = profilesTargetsStatePart.createAction<{
name: string;
description?: string;
host: string | string[];
port: number;
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_CreateNetworkTarget
>('/typedrequest', 'createNetworkTarget');
await request.fire({
identity: context.identity!,
name: dataArg.name,
description: dataArg.description,
host: dataArg.host,
port: dataArg.port,
});
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to create target',
};
}
});
export const updateTargetAction = profilesTargetsStatePart.createAction<{
id: string;
name?: string;
description?: string;
host?: string | string[];
port?: number;
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_UpdateNetworkTarget
>('/typedrequest', 'updateNetworkTarget');
await request.fire({
identity: context.identity!,
id: dataArg.id,
name: dataArg.name,
description: dataArg.description,
host: dataArg.host,
port: dataArg.port,
});
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to update target',
};
}
});
export const deleteTargetAction = profilesTargetsStatePart.createAction<{
id: string;
force?: boolean;
}>(async (statePartArg, dataArg, actionContext): Promise<IProfilesTargetsState> => {
const context = getActionContext();
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_DeleteNetworkTarget
>('/typedrequest', 'deleteNetworkTarget');
const response = await request.fire({
identity: context.identity!,
id: dataArg.id,
force: dataArg.force,
});
if (!response.success) {
return {
...statePartArg.getState()!,
error: response.message || 'Failed to delete target',
};
}
return await actionContext!.dispatch(fetchProfilesAndTargetsAction, null);
} catch (error: unknown) {
return {
...statePartArg.getState()!,
error: error instanceof Error ? error.message : 'Failed to delete target',
};
}
});
// ============================================================================
// Route Management Actions
// ============================================================================
@@ -1139,6 +1415,7 @@ export const fetchMergedRoutesAction = routeManagementStatePart.createAction(asy
export const createRouteAction = routeManagementStatePart.createAction<{
route: any;
enabled?: boolean;
metadata?: any;
}>(async (statePartArg, dataArg, actionContext): Promise<IRouteManagementState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
@@ -1152,6 +1429,7 @@ export const createRouteAction = routeManagementStatePart.createAction<{
identity: context.identity!,
route: dataArg.route,
enabled: dataArg.enabled,
metadata: dataArg.metadata,
});
return await actionContext!.dispatch(fetchMergedRoutesAction, null);
@@ -1163,6 +1441,37 @@ export const createRouteAction = routeManagementStatePart.createAction<{
}
});
export const updateRouteAction = routeManagementStatePart.createAction<{
id: string;
route?: any;
enabled?: boolean;
metadata?: any;
}>(async (statePartArg, dataArg, actionContext): Promise<IRouteManagementState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_UpdateRoute
>('/typedrequest', 'updateRoute');
await request.fire({
identity: context.identity!,
id: dataArg.id,
route: dataArg.route,
enabled: dataArg.enabled,
metadata: dataArg.metadata,
});
return await actionContext!.dispatch(fetchMergedRoutesAction, null);
} catch (error: unknown) {
return {
...currentState,
error: error instanceof Error ? error.message : 'Failed to update route',
};
}
});
export const deleteRouteAction = routeManagementStatePart.createAction<string>(
async (statePartArg, routeId, actionContext): Promise<IRouteManagementState> => {
const context = getActionContext();

View File

@@ -10,4 +10,6 @@ export * from './ops-view-security.js';
export * from './ops-view-certificates.js';
export * from './ops-view-remoteingress.js';
export * from './ops-view-vpn.js';
export * from './ops-view-securityprofiles.js';
export * from './ops-view-networktargets.js';
export * from './shared/index.js';

View File

@@ -2,7 +2,6 @@ import * as plugins from '../plugins.js';
import * as appstate from '../appstate.js';
import * as interfaces from '../../dist_ts_interfaces/index.js';
import { appRouter } from '../router.js';
import {
DeesElement,
css,
@@ -25,6 +24,8 @@ import { OpsViewSecurity } from './ops-view-security.js';
import { OpsViewCertificates } from './ops-view-certificates.js';
import { OpsViewRemoteIngress } from './ops-view-remoteingress.js';
import { OpsViewVpn } from './ops-view-vpn.js';
import { OpsViewSecurityProfiles } from './ops-view-securityprofiles.js';
import { OpsViewNetworkTargets } from './ops-view-networktargets.js';
@customElement('ops-dashboard')
export class OpsDashboard extends DeesElement {
@@ -41,6 +42,12 @@ export class OpsDashboard extends DeesElement {
theme: 'light',
};
@state() accessor configState: appstate.IConfigState = {
config: null,
isLoading: false,
error: null,
};
// Store viewTabs as a property to maintain object references
private viewTabs = [
{
@@ -73,6 +80,16 @@ export class OpsDashboard extends DeesElement {
iconName: 'lucide:route',
element: OpsViewRoutes,
},
{
name: 'SecurityProfiles',
iconName: 'lucide:shieldCheck',
element: OpsViewSecurityProfiles,
},
{
name: 'NetworkTargets',
iconName: 'lucide:server',
element: OpsViewNetworkTargets,
},
{
name: 'ApiTokens',
iconName: 'lucide:key',
@@ -100,6 +117,20 @@ export class OpsDashboard extends DeesElement {
},
];
private get globalMessages() {
const messages: Array<{ id: string; type: string; message: string; dismissible?: boolean }> = [];
const config = this.configState.config;
if (config && !config.cache.enabled) {
messages.push({
id: 'db-disabled',
type: 'warning',
message: 'Database is disabled. Creating and editing routes, profiles, targets, and API tokens is not available.',
dismissible: false,
});
}
return messages;
}
/**
* Get the current view tab based on the UI state's activeView.
* Used to pass the correct selectedView to dees-simple-appdash on initial render.
@@ -125,6 +156,14 @@ export class OpsDashboard extends DeesElement {
});
this.rxSubscriptions.push(loginSubscription);
// Subscribe to config state (for global warnings)
const configSubscription = appstate.configStatePart
.select((stateArg) => stateArg)
.subscribe((configState) => {
this.configState = configState;
});
this.rxSubscriptions.push(configSubscription);
// Subscribe to UI state
const uiSubscription = appstate.uiStatePart
.select((stateArg) => stateArg)
@@ -193,6 +232,7 @@ export class OpsDashboard extends DeesElement {
name="DCRouter OpsServer"
.viewTabs=${this.viewTabs}
.selectedView=${this.currentViewTab}
.globalMessages=${this.globalMessages}
>
</dees-simple-appdash>
</dees-simple-login>

View File

@@ -299,7 +299,7 @@ export class OpsViewCertificates extends DeesElement {
{
name: 'Reprovision',
iconName: 'lucide:RefreshCw',
type: ['inRow'],
type: ['inRow', 'contextmenu'],
actionFunc: async (actionData: { item: interfaces.requests.ICertificateInfo }) => {
const cert = actionData.item;
if (!cert.canReprovision) {
@@ -311,16 +311,39 @@ export class OpsViewCertificates extends DeesElement {
});
return;
}
await appstate.certificateStatePart.dispatchAction(
appstate.reprovisionCertificateAction,
cert.domain,
);
const { DeesToast } = await import('@design.estate/dees-catalog');
DeesToast.show({
message: `Reprovisioning triggered for ${cert.domain}`,
type: 'success',
duration: 3000,
});
const doReprovision = async () => {
await appstate.certificateStatePart.dispatchAction(
appstate.reprovisionCertificateAction,
cert.domain,
);
const { DeesToast } = await import('@design.estate/dees-catalog');
DeesToast.show({
message: `Reprovisioning triggered for ${cert.domain}`,
type: 'success',
duration: 3000,
});
};
if (cert.status === 'valid') {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Certificate Still Valid',
content: html`<p style="margin: 0; line-height: 1.5;">The certificate for <strong>${cert.domain}</strong> is still valid${cert.expiryDate ? ` until ${new Date(cert.expiryDate).toLocaleDateString()}` : ''}. Do you want to force renew it now?</p>`,
menuOptions: [
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
{
name: 'Force Renew',
action: async (modalArg: any) => {
await modalArg.destroy();
await doReprovision();
},
},
],
});
} else {
await doReprovision();
}
},
},
{

View File

@@ -28,6 +28,13 @@ interface INetworkRequest {
@customElement('ops-view-network')
export class OpsViewNetwork extends DeesElement {
/** How far back the traffic chart shows */
private static readonly CHART_WINDOW_MS = 5 * 60 * 1000; // 5 minutes
/** How often a new data point is added */
private static readonly UPDATE_INTERVAL_MS = 1000; // 1 second
/** Derived: max data points the buffer holds */
private static readonly MAX_DATA_POINTS = OpsViewNetwork.CHART_WINDOW_MS / OpsViewNetwork.UPDATE_INTERVAL_MS;
@state()
accessor statsState = appstate.statsStatePart.getState()!;
@@ -46,7 +53,7 @@ export class OpsViewNetwork extends DeesElement {
// Track if we need to update the chart to avoid unnecessary re-renders
private lastChartUpdate = 0;
private chartUpdateThreshold = 1000; // Minimum ms between chart updates
private chartUpdateThreshold = OpsViewNetwork.UPDATE_INTERVAL_MS; // Minimum ms between chart updates
private trafficUpdateTimer: any = null;
private requestsPerSecHistory: number[] = []; // Track requests/sec over time for trend
@@ -104,13 +111,11 @@ export class OpsViewNetwork extends DeesElement {
private initializeTrafficData() {
const now = Date.now();
// Fixed 5 minute time range
const range = 5 * 60 * 1000; // 5 minutes
const bucketSize = range / 60; // 60 data points
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetwork;
// Initialize with empty data points for both in and out
const emptyData = Array.from({ length: 60 }, (_, i) => {
const time = now - ((59 - i) * bucketSize);
const emptyData = Array.from({ length: MAX_DATA_POINTS }, (_, i) => {
const time = now - ((MAX_DATA_POINTS - 1 - i) * UPDATE_INTERVAL_MS);
return {
x: new Date(time).toISOString(),
y: 0,
@@ -143,23 +148,23 @@ export class OpsViewNetwork extends DeesElement {
y: Math.round((p.out * 8) / 1000000 * 10) / 10,
}));
// Use history as the chart data, keeping the most recent 60 points (5 min window)
const sliceStart = Math.max(0, historyIn.length - 60);
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetwork;
// Use history as the chart data, keeping the most recent points within the window
const sliceStart = Math.max(0, historyIn.length - MAX_DATA_POINTS);
this.trafficDataIn = historyIn.slice(sliceStart);
this.trafficDataOut = historyOut.slice(sliceStart);
// If fewer than 60 points, pad the front with zeros
if (this.trafficDataIn.length < 60) {
// If fewer than MAX_DATA_POINTS, pad the front with zeros
if (this.trafficDataIn.length < MAX_DATA_POINTS) {
const now = Date.now();
const range = 5 * 60 * 1000;
const bucketSize = range / 60;
const padCount = 60 - this.trafficDataIn.length;
const padCount = MAX_DATA_POINTS - this.trafficDataIn.length;
const firstTimestamp = this.trafficDataIn.length > 0
? new Date(this.trafficDataIn[0].x).getTime()
: now;
const padIn = Array.from({ length: padCount }, (_, i) => ({
x: new Date(firstTimestamp - ((padCount - i) * bucketSize)).toISOString(),
x: new Date(firstTimestamp - ((padCount - i) * UPDATE_INTERVAL_MS)).toISOString(),
y: 0,
}));
const padOut = padIn.map(p => ({ ...p }));
@@ -287,27 +292,17 @@ export class OpsViewNetwork extends DeesElement {
{
name: 'Inbound',
data: this.trafficDataIn,
color: '#22c55e', // Green for download
color: '#22c55e',
},
{
name: 'Outbound',
data: this.trafficDataOut,
color: '#8b5cf6', // Purple for upload
color: '#8b5cf6',
}
]}
.stacked=${false}
.realtimeMode=${true}
.rollingWindow=${OpsViewNetwork.CHART_WINDOW_MS}
.yAxisFormatter=${(val: number) => `${val} Mbit/s`}
.tooltipFormatter=${(point: any) => {
const mbps = point.y || 0;
const seriesName = point.series?.name || 'Throughput';
const timestamp = new Date(point.x).toLocaleTimeString();
return `
<div style="padding: 8px;">
<div style="font-weight: bold; margin-bottom: 4px;">${timestamp}</div>
<div>${seriesName}: ${mbps.toFixed(2)} Mbit/s</div>
</div>
`;
}}
></dees-chart-area>
<!-- Top IPs Section -->
@@ -719,9 +714,8 @@ export class OpsViewNetwork extends DeesElement {
private startTrafficUpdateTimer() {
this.stopTrafficUpdateTimer(); // Clear any existing timer
this.trafficUpdateTimer = setInterval(() => {
// Add a new data point every second
this.addTrafficDataPoint();
}, 1000); // Update every second
}, OpsViewNetwork.UPDATE_INTERVAL_MS);
}
private addTrafficDataPoint() {
@@ -752,7 +746,7 @@ export class OpsViewNetwork extends DeesElement {
};
// In-place mutation then reassign for Lit reactivity (avoids 4 intermediate arrays)
if (this.trafficDataIn.length >= 60) {
if (this.trafficDataIn.length >= OpsViewNetwork.MAX_DATA_POINTS) {
this.trafficDataIn.shift();
this.trafficDataOut.shift();
}

View File

@@ -0,0 +1,220 @@
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-networktargets': OpsViewNetworkTargets;
}
}
@customElement('ops-view-networktargets')
export class OpsViewNetworkTargets extends DeesElement {
@state()
accessor profilesState: appstate.IProfilesTargetsState = appstate.profilesTargetsStatePart.getState()!;
constructor() {
super();
const sub = appstate.profilesTargetsStatePart.select().subscribe((newState) => {
this.profilesState = newState;
});
this.rxSubscriptions.push(sub);
}
async connectedCallback() {
await super.connectedCallback();
await appstate.profilesTargetsStatePart.dispatchAction(appstate.fetchProfilesAndTargetsAction, null);
}
public static styles = [
cssManager.defaultStyles,
viewHostCss,
css`
.targetsContainer {
display: flex;
flex-direction: column;
gap: 24px;
}
`,
];
public render(): TemplateResult {
const targets = this.profilesState.targets;
const statsTiles: IStatsTile[] = [
{
id: 'totalTargets',
title: 'Total Targets',
type: 'number',
value: targets.length,
icon: 'lucide:server',
description: 'Reusable network targets',
color: '#8b5cf6',
},
];
return html`
<ops-sectionheading>Network Targets</ops-sectionheading>
<div class="targetsContainer">
<dees-statsgrid .tiles=${statsTiles}></dees-statsgrid>
<dees-table
.heading1=${'Network Targets'}
.heading2=${'Reusable host:port destinations for routes'}
.data=${targets}
.displayFunction=${(target: interfaces.data.INetworkTarget) => ({
Name: target.name,
Host: Array.isArray(target.host) ? target.host.join(', ') : target.host,
Port: target.port,
Description: target.description || '-',
})}
.dataActions=${[
{
name: 'Create Target',
iconName: 'lucide:plus',
type: ['header' as const],
actionFunc: async () => {
await this.showCreateTargetDialog();
},
},
{
name: 'Refresh',
iconName: 'lucide:rotateCw',
type: ['header' as const],
actionFunc: async () => {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.fetchProfilesAndTargetsAction, null);
},
},
{
name: 'Edit',
iconName: 'lucide:pencil',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const target = actionData.item as interfaces.data.INetworkTarget;
await this.showEditTargetDialog(target);
},
},
{
name: 'Delete',
iconName: 'lucide:trash2',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const target = actionData.item as interfaces.data.INetworkTarget;
await this.deleteTarget(target);
},
},
]}
></dees-table>
</div>
`;
}
private async showCreateTargetDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Create Network Target',
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name'} .required=${true}></dees-input-text>
<dees-input-text .key=${'host'} .label=${'Host'} .required=${true}></dees-input-text>
<dees-input-text .key=${'port'} .label=${'Port'} .required=${true} .value=${'443'}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'}></dees-input-text>
</dees-form>
`,
menuOptions: [
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
{
name: 'Create',
action: async (modalArg: any) => {
const form = modalArg.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
await appstate.profilesTargetsStatePart.dispatchAction(appstate.createTargetAction, {
name: String(data.name),
description: data.description ? String(data.description) : undefined,
host: String(data.host),
port: parseInt(String(data.port)) || 443,
});
modalArg.destroy();
},
},
],
});
}
private async showEditTargetDialog(target: interfaces.data.INetworkTarget) {
const hostStr = Array.isArray(target.host) ? target.host.join(', ') : target.host;
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: `Edit Target: ${target.name}`,
content: html`
<dees-form>
<dees-input-text .key=${'name'} .label=${'Name'} .value=${target.name}></dees-input-text>
<dees-input-text .key=${'host'} .label=${'Host'} .value=${hostStr}></dees-input-text>
<dees-input-text .key=${'port'} .label=${'Port'} .value=${String(target.port)}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'} .value=${target.description || ''}></dees-input-text>
</dees-form>
`,
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();
await appstate.profilesTargetsStatePart.dispatchAction(appstate.updateTargetAction, {
id: target.id,
name: String(data.name),
description: data.description ? String(data.description) : undefined,
host: String(data.host),
port: parseInt(String(data.port)) || 443,
});
modalArg.destroy();
},
},
],
});
}
private async deleteTarget(target: interfaces.data.INetworkTarget) {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.deleteTargetAction, {
id: target.id,
force: false,
});
const currentState = appstate.profilesTargetsStatePart.getState()!;
if (currentState.error?.includes('in use')) {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Target In Use',
content: html`<p>${currentState.error} Force delete?</p>`,
menuOptions: [
{
name: 'Force Delete',
action: async (modalArg: any) => {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.deleteTargetAction, {
id: target.id,
force: true,
});
modalArg.destroy();
},
},
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
],
});
}
}
}

View File

@@ -121,11 +121,15 @@ export class OpsViewOverview extends DeesElement {
<dees-chart-area
.label=${'Email Traffic (24h)'}
.series=${this.getEmailTrafficSeries()}
.realtimeMode=${true}
.rollingWindow=${86400000}
.yAxisFormatter=${(val: number) => `${val}`}
></dees-chart-area>
<dees-chart-area
.label=${'DNS Queries (24h)'}
.series=${this.getDnsQuerySeries()}
.realtimeMode=${true}
.rollingWindow=${86400000}
.yAxisFormatter=${(val: number) => `${val}`}
></dees-chart-area>
<dees-chart-log

View File

@@ -24,6 +24,14 @@ export class OpsViewRoutes extends DeesElement {
lastUpdated: 0,
};
@state() accessor profilesTargetsState: appstate.IProfilesTargetsState = {
profiles: [],
targets: [],
isLoading: false,
error: null,
lastUpdated: 0,
};
constructor() {
super();
const sub = appstate.routeManagementStatePart
@@ -33,6 +41,13 @@ export class OpsViewRoutes extends DeesElement {
});
this.rxSubscriptions.push(sub);
const ptSub = appstate.profilesTargetsStatePart
.select((s) => s)
.subscribe((ptState) => {
this.profilesTargetsState = ptState;
});
this.rxSubscriptions.push(ptSub);
// Re-fetch routes when user logs in (fixes race condition where
// the view is created before authentication completes)
const loginSub = appstate.loginStatePart
@@ -40,6 +55,7 @@ export class OpsViewRoutes extends DeesElement {
.subscribe((isLoggedIn) => {
if (isLoggedIn) {
appstate.routeManagementStatePart.dispatchAction(appstate.fetchMergedRoutesAction, null);
appstate.profilesTargetsStatePart.dispatchAction(appstate.fetchProfilesAndTargetsAction, null);
}
});
this.rxSubscriptions.push(loginSub);
@@ -145,6 +161,7 @@ export class OpsViewRoutes extends DeesElement {
enabled: mr.enabled,
tags,
id: mr.storedRouteId || mr.route.name || undefined,
metadata: mr.metadata,
};
});
@@ -187,7 +204,10 @@ export class OpsViewRoutes extends DeesElement {
? html`
<sz-route-list-view
.routes=${szRoutes}
.showActionsFilter=${(route: any) => route.tags?.includes('programmatic') ?? false}
@route-click=${(e: CustomEvent) => this.handleRouteClick(e)}
@route-edit=${(e: CustomEvent) => this.handleRouteEdit(e)}
@route-delete=${(e: CustomEvent) => this.handleRouteDelete(e)}
></sz-route-list-view>
`
: html`
@@ -275,6 +295,7 @@ export class OpsViewRoutes extends DeesElement {
});
} else {
// Programmatic route
const meta = merged.metadata;
await DeesModal.createAndShow({
heading: `Route: ${merged.route.name}`,
content: html`
@@ -282,6 +303,8 @@ export class OpsViewRoutes extends DeesElement {
<p>Source: <strong style="color: #0af;">programmatic</strong></p>
<p>Status: <strong>${merged.enabled ? 'Enabled' : 'Disabled'}</strong></p>
<p>ID: <code style="color: #888;">${merged.storedRouteId}</code></p>
${meta?.securityProfileName ? html`<p>Security Profile: <strong style="color: #a78bfa;">${meta.securityProfileName}</strong></p>` : ''}
${meta?.networkTargetName ? html`<p>Network Target: <strong style="color: #a78bfa;">${meta.networkTargetName}</strong></p>` : ''}
</div>
`,
menuOptions: [
@@ -317,8 +340,185 @@ export class OpsViewRoutes extends DeesElement {
}
}
private async handleRouteEdit(e: CustomEvent) {
const clickedRoute = e.detail;
if (!clickedRoute) return;
const merged = this.routeState.mergedRoutes.find(
(mr) => mr.route.name === clickedRoute.name,
);
if (!merged || !merged.storedRouteId) return;
this.showEditRouteDialog(merged);
}
private async handleRouteDelete(e: CustomEvent) {
const clickedRoute = e.detail;
if (!clickedRoute) return;
const merged = this.routeState.mergedRoutes.find(
(mr) => mr.route.name === clickedRoute.name,
);
if (!merged || !merged.storedRouteId) return;
const { DeesModal } = await import('@design.estate/dees-catalog');
await DeesModal.createAndShow({
heading: `Delete Route: ${merged.route.name}`,
content: html`
<div style="color: #ccc; padding: 8px 0;">
<p>Are you sure you want to delete this route? This action cannot be undone.</p>
</div>
`,
menuOptions: [
{
name: 'Cancel',
iconName: 'lucide:x',
action: async (modalArg: any) => await modalArg.destroy(),
},
{
name: 'Delete',
iconName: 'lucide:trash-2',
action: async (modalArg: any) => {
await appstate.routeManagementStatePart.dispatchAction(
appstate.deleteRouteAction,
merged.storedRouteId!,
);
await modalArg.destroy();
},
},
],
});
}
private async showEditRouteDialog(merged: interfaces.data.IMergedRoute) {
const { DeesModal } = await import('@design.estate/dees-catalog');
const profiles = this.profilesTargetsState.profiles;
const targets = this.profilesTargetsState.targets;
const profileOptions = [
{ key: '', option: '(none — inline security)' },
...profiles.map((p) => ({
key: p.id,
option: `${p.name}${p.description ? ' — ' + p.description : ''}`,
})),
];
const targetOptions = [
{ key: '', option: '(none — inline target)' },
...targets.map((t) => ({
key: t.id,
option: `${t.name} (${Array.isArray(t.host) ? t.host.join(',') : t.host}:${t.port})`,
})),
];
const route = merged.route;
const currentPorts = Array.isArray(route.match.ports)
? route.match.ports.map((p: any) => typeof p === 'number' ? String(p) : `${p.from}-${p.to}`).join(', ')
: String(route.match.ports);
const currentDomains: string[] = route.match.domains
? (Array.isArray(route.match.domains) ? route.match.domains : [route.match.domains])
: [];
const firstTarget = route.action.targets?.[0];
const currentTargetHost = firstTarget
? (Array.isArray(firstTarget.host) ? firstTarget.host[0] : firstTarget.host)
: '';
const currentTargetPort = firstTarget?.port != null ? String(firstTarget.port) : '';
await DeesModal.createAndShow({
heading: `Edit Route: ${route.name}`,
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-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-dropdown .key=${'securityProfileRef'} .label=${'Security Profile'} .options=${profileOptions} .selectedKey=${merged.metadata?.securityProfileRef || ''}></dees-input-dropdown>
<dees-input-dropdown .key=${'networkTargetRef'} .label=${'Network Target'} .options=${targetOptions} .selectedKey=${merged.metadata?.networkTargetRef || ''}></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-form>
`,
menuOptions: [
{
name: 'Cancel',
iconName: 'lucide:x',
action: async (modalArg: any) => await modalArg.destroy(),
},
{
name: 'Save',
iconName: 'lucide:check',
action: async (modalArg: any) => {
const form = modalArg.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
if (!form) return;
const formData = await form.collectFormData();
if (!formData.name || !formData.ports) return;
const ports = formData.ports.split(',').map((p: string) => parseInt(p.trim(), 10)).filter((p: number) => !isNaN(p));
const domains: string[] = Array.isArray(formData.domains)
? formData.domains.filter(Boolean)
: [];
const priority = formData.priority ? parseInt(formData.priority, 10) : undefined;
const updatedRoute: any = {
name: formData.name,
match: {
ports,
...(domains.length > 0 ? { domains } : {}),
},
action: {
type: 'forward',
targets: [
{
host: formData.targetHost || 'localhost',
port: parseInt(formData.targetPort, 10) || 443,
},
],
},
...(priority != null && !isNaN(priority) ? { priority } : {}),
};
const metadata: any = {};
if (formData.securityProfileRef) {
metadata.securityProfileRef = formData.securityProfileRef;
}
if (formData.networkTargetRef) {
metadata.networkTargetRef = formData.networkTargetRef;
}
await appstate.routeManagementStatePart.dispatchAction(
appstate.updateRouteAction,
{
id: merged.storedRouteId!,
route: updatedRoute,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
},
);
await modalArg.destroy();
},
},
],
});
}
private async showCreateRouteDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
const profiles = this.profilesTargetsState.profiles;
const targets = this.profilesTargetsState.targets;
// Build dropdown options for profiles and targets
const profileOptions = [
{ key: '', option: '(none — inline security)' },
...profiles.map((p) => ({
key: p.id,
option: `${p.name}${p.description ? ' — ' + p.description : ''}`,
})),
];
const targetOptions = [
{ key: '', option: '(none — inline target)' },
...targets.map((t) => ({
key: t.id,
option: `${t.name} (${Array.isArray(t.host) ? t.host.join(',') : t.host}:${t.port})`,
})),
];
await DeesModal.createAndShow({
heading: 'Add Programmatic Route',
@@ -326,9 +526,12 @@ export class OpsViewRoutes extends DeesElement {
<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=${'domains'} .label=${'Domains (comma-separated, optional)'}></dees-input-text>
<dees-input-text .key=${'targetHost'} .label=${'Target Host'} .value=${'localhost'} .required=${true}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port'} .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-dropdown .key=${'securityProfileRef'} .label=${'Security Profile'} .options=${profileOptions} .selectedKey=${''}></dees-input-dropdown>
<dees-input-dropdown .key=${'networkTargetRef'} .label=${'Network Target'} .options=${targetOptions} .selectedKey=${''}></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-form>
`,
menuOptions: [
@@ -347,30 +550,44 @@ export class OpsViewRoutes extends DeesElement {
if (!formData.name || !formData.ports) return;
const ports = formData.ports.split(',').map((p: string) => parseInt(p.trim(), 10)).filter((p: number) => !isNaN(p));
const domains = formData.domains
? formData.domains.split(',').map((d: string) => d.trim()).filter(Boolean)
: undefined;
const domains: string[] = Array.isArray(formData.domains)
? formData.domains.filter(Boolean)
: [];
const priority = formData.priority ? parseInt(formData.priority, 10) : undefined;
const route: any = {
name: formData.name,
match: {
ports,
...(domains && domains.length > 0 ? { domains } : {}),
...(domains.length > 0 ? { domains } : {}),
},
action: {
type: 'forward',
targets: [
{
host: formData.targetHost || 'localhost',
port: parseInt(formData.targetPort, 10),
port: parseInt(formData.targetPort, 10) || 443,
},
],
},
...(priority != null && !isNaN(priority) ? { priority } : {}),
};
// Build metadata if profile/target selected
const metadata: any = {};
if (formData.securityProfileRef) {
metadata.securityProfileRef = formData.securityProfileRef;
}
if (formData.networkTargetRef) {
metadata.networkTargetRef = formData.networkTargetRef;
}
await appstate.routeManagementStatePart.dispatchAction(
appstate.createRouteAction,
{ route },
{
route,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
},
);
await modalArg.destroy();
},

View File

@@ -0,0 +1,240 @@
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-securityprofiles': OpsViewSecurityProfiles;
}
}
@customElement('ops-view-securityprofiles')
export class OpsViewSecurityProfiles extends DeesElement {
@state()
accessor profilesState: appstate.IProfilesTargetsState = appstate.profilesTargetsStatePart.getState()!;
constructor() {
super();
const sub = appstate.profilesTargetsStatePart.select().subscribe((newState) => {
this.profilesState = newState;
});
this.rxSubscriptions.push(sub);
}
async connectedCallback() {
await super.connectedCallback();
await appstate.profilesTargetsStatePart.dispatchAction(appstate.fetchProfilesAndTargetsAction, null);
}
public static styles = [
cssManager.defaultStyles,
viewHostCss,
css`
.profilesContainer {
display: flex;
flex-direction: column;
gap: 24px;
}
`,
];
public render(): TemplateResult {
const profiles = this.profilesState.profiles;
const statsTiles: IStatsTile[] = [
{
id: 'totalProfiles',
title: 'Total Profiles',
type: 'number',
value: profiles.length,
icon: 'lucide:shieldCheck',
description: 'Reusable security profiles',
color: '#3b82f6',
},
];
return html`
<ops-sectionheading>Security Profiles</ops-sectionheading>
<div class="profilesContainer">
<dees-statsgrid .tiles=${statsTiles}></dees-statsgrid>
<dees-table
.heading1=${'Security Profiles'}
.heading2=${'Reusable security configurations for routes'}
.data=${profiles}
.displayFunction=${(profile: interfaces.data.ISecurityProfile) => ({
Name: profile.name,
Description: profile.description || '-',
'IP Allow List': (profile.security?.ipAllowList || []).join(', ') || '-',
'IP Block List': (profile.security?.ipBlockList || []).join(', ') || '-',
'Max Connections': profile.security?.maxConnections ?? '-',
'Rate Limit': profile.security?.rateLimit?.enabled ? `${profile.security.rateLimit.maxRequests}/${profile.security.rateLimit.window}s` : '-',
Extends: (profile.extendsProfiles || []).length > 0
? profile.extendsProfiles!.map(id => {
const p = profiles.find(pp => pp.id === id);
return p ? p.name : id.slice(0, 8);
}).join(', ')
: '-',
})}
.dataActions=${[
{
name: 'Create Profile',
iconName: 'lucide:plus',
type: ['header' as const],
actionFunc: async () => {
await this.showCreateProfileDialog();
},
},
{
name: 'Refresh',
iconName: 'lucide:rotateCw',
type: ['header' as const],
actionFunc: async () => {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.fetchProfilesAndTargetsAction, null);
},
},
{
name: 'Edit',
iconName: 'lucide:pencil',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const profile = actionData.item as interfaces.data.ISecurityProfile;
await this.showEditProfileDialog(profile);
},
},
{
name: 'Delete',
iconName: 'lucide:trash2',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
const profile = actionData.item as interfaces.data.ISecurityProfile;
await this.deleteProfile(profile);
},
},
]}
></dees-table>
</div>
`;
}
private async showCreateProfileDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Create Security Profile',
content: html`
<dees-form>
<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=${'ipAllowList'} .label=${'IP Allow List'} .placeholder=${'Add IP or CIDR...'}></dees-input-list>
<dees-input-list .key=${'ipBlockList'} .label=${'IP Block List'} .placeholder=${'Add IP or CIDR...'}></dees-input-list>
<dees-input-text .key=${'maxConnections'} .label=${'Max Connections'}></dees-input-text>
</dees-form>
`,
menuOptions: [
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
{
name: 'Create',
action: async (modalArg: any) => {
const form = modalArg.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
if (!form) return;
const data = await form.collectFormData();
const ipAllowList: string[] = Array.isArray(data.ipAllowList) ? data.ipAllowList : [];
const ipBlockList: string[] = Array.isArray(data.ipBlockList) ? data.ipBlockList : [];
const maxConnections = data.maxConnections ? parseInt(String(data.maxConnections)) : undefined;
await appstate.profilesTargetsStatePart.dispatchAction(appstate.createProfileAction, {
name: String(data.name),
description: data.description ? String(data.description) : undefined,
security: {
...(ipAllowList.length > 0 ? { ipAllowList } : {}),
...(ipBlockList.length > 0 ? { ipBlockList } : {}),
...(maxConnections ? { maxConnections } : {}),
},
});
modalArg.destroy();
},
},
],
});
}
private async showEditProfileDialog(profile: interfaces.data.ISecurityProfile) {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: `Edit Profile: ${profile.name}`,
content: html`
<dees-form>
<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=${'ipAllowList'} .label=${'IP Allow List'} .placeholder=${'Add IP or CIDR...'} .value=${profile.security?.ipAllowList || []}></dees-input-list>
<dees-input-list .key=${'ipBlockList'} .label=${'IP Block List'} .placeholder=${'Add IP or CIDR...'} .value=${profile.security?.ipBlockList || []}></dees-input-list>
<dees-input-text .key=${'maxConnections'} .label=${'Max Connections'} .value=${String(profile.security?.maxConnections || '')}></dees-input-text>
</dees-form>
`,
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 ipAllowList: string[] = Array.isArray(data.ipAllowList) ? data.ipAllowList : [];
const ipBlockList: string[] = Array.isArray(data.ipBlockList) ? data.ipBlockList : [];
const maxConnections = data.maxConnections ? parseInt(String(data.maxConnections)) : undefined;
await appstate.profilesTargetsStatePart.dispatchAction(appstate.updateProfileAction, {
id: profile.id,
name: String(data.name),
description: data.description ? String(data.description) : undefined,
security: {
ipAllowList,
ipBlockList,
...(maxConnections ? { maxConnections } : {}),
},
});
modalArg.destroy();
},
},
],
});
}
private async deleteProfile(profile: interfaces.data.ISecurityProfile) {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.deleteProfileAction, {
id: profile.id,
force: false,
});
const currentState = appstate.profilesTargetsStatePart.getState()!;
if (currentState.error?.includes('in use')) {
const { DeesModal } = await import('@design.estate/dees-catalog');
DeesModal.createAndShow({
heading: 'Profile In Use',
content: html`<p>${currentState.error} Force delete?</p>`,
menuOptions: [
{
name: 'Force Delete',
action: async (modalArg: any) => {
await appstate.profilesTargetsStatePart.dispatchAction(appstate.deleteProfileAction, {
id: profile.id,
force: true,
});
modalArg.destroy();
},
},
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
],
});
}
}
}

View File

@@ -13,6 +13,31 @@ import * as interfaces from '../../dist_ts_interfaces/index.js';
import { viewHostCss } from './shared/css.js';
import { type IStatsTile } from '@design.estate/dees-catalog';
/**
* Toggle form field visibility based on checkbox states.
* Used in Create and Edit VPN client dialogs.
*/
function setupFormVisibility(formEl: any) {
const show = 'flex'; // match dees-form's flex layout
const updateVisibility = async () => {
const data = await formEl.collectFormData();
const contentEl = formEl.closest('.content') || formEl.parentElement;
if (!contentEl) return;
const hostIpGroup = contentEl.querySelector('.hostIpGroup') as HTMLElement;
const hostIpDetails = contentEl.querySelector('.hostIpDetails') as HTMLElement;
const staticIpGroup = contentEl.querySelector('.staticIpGroup') as HTMLElement;
const vlanIdGroup = contentEl.querySelector('.vlanIdGroup') as HTMLElement;
const aclGroup = contentEl.querySelector('.aclGroup') as HTMLElement;
if (hostIpGroup) hostIpGroup.style.display = data.forceDestinationSmartproxy ? 'none' : show;
if (hostIpDetails) hostIpDetails.style.display = data.useHostIp ? show : 'none';
if (staticIpGroup) staticIpGroup.style.display = data.useDhcp ? 'none' : show;
if (vlanIdGroup) vlanIdGroup.style.display = data.forceVlan ? show : 'none';
if (aclGroup) aclGroup.style.display = data.allowAdditionalAcls ? show : 'none';
};
formEl.changeSubject.subscribe(() => updateVisibility());
updateVisibility();
}
declare global {
interface HTMLElementTagNameMap {
'ops-view-vpn': OpsViewVpn;
@@ -289,9 +314,18 @@ export class OpsViewVpn extends DeesElement {
} else {
statusHtml = html`<span class="statusBadge enabled" style="background: ${cssManager.bdTheme('#eff6ff', '#172554')}; color: ${cssManager.bdTheme('#1e40af', '#60a5fa')};">offline</span>`;
}
let routingHtml;
if (client.forceDestinationSmartproxy !== false) {
routingHtml = html`<span class="statusBadge enabled">SmartProxy</span>`;
} else if (client.useHostIp) {
routingHtml = html`<span class="statusBadge" style="background: ${cssManager.bdTheme('#f3e8ff', '#3b0764')}; color: ${cssManager.bdTheme('#7c3aed', '#c084fc')};">Host IP</span>`;
} else {
routingHtml = html`<span class="statusBadge" style="background: ${cssManager.bdTheme('#eff6ff', '#172554')}; color: ${cssManager.bdTheme('#1e40af', '#60a5fa')};">Direct</span>`;
}
return {
'Client ID': client.clientId,
'Status': statusHtml,
'Routing': routingHtml,
'VPN IP': client.assignedIp || '-',
'Tags': client.serverDefinedClientTags?.length
? html`${client.serverDefinedClientTags.map(t => html`<span class="tagBadge">${t}</span>`)}`
@@ -307,13 +341,32 @@ export class OpsViewVpn extends DeesElement {
type: ['header'],
actionFunc: async () => {
const { DeesModal } = await import('@design.estate/dees-catalog');
await DeesModal.createAndShow({
const createModal = await DeesModal.createAndShow({
heading: 'Create VPN Client',
content: html`
<dees-form>
<dees-input-text .key=${'clientId'} .label=${'Client ID'} .required=${true}></dees-input-text>
<dees-input-text .key=${'description'} .label=${'Description'}></dees-input-text>
<dees-input-text .key=${'tags'} .label=${'Server-Defined Tags (comma-separated)'}></dees-input-text>
<dees-input-checkbox .key=${'forceDestinationSmartproxy'} .label=${'Force traffic through SmartProxy'} .value=${true}></dees-input-checkbox>
<div class="hostIpGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-checkbox .key=${'useHostIp'} .label=${'Get Host IP'} .value=${false}></dees-input-checkbox>
<div class="hostIpDetails" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-checkbox .key=${'useDhcp'} .label=${'Get IP through DHCP'} .value=${false}></dees-input-checkbox>
<div class="staticIpGroup" style="display: flex; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'staticIp'} .label=${'Static IP'}></dees-input-text>
</div>
<dees-input-checkbox .key=${'forceVlan'} .label=${'Force VLAN'} .value=${false}></dees-input-checkbox>
<div class="vlanIdGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'vlanId'} .label=${'VLAN ID'}></dees-input-text>
</div>
</div>
</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>
</div>
</dees-form>
`,
menuOptions: [
@@ -333,16 +386,47 @@ export class OpsViewVpn extends DeesElement {
const serverDefinedClientTags = data.tags
? data.tags.split(',').map((t: string) => t.trim()).filter(Boolean)
: undefined;
// Apply conditional logic based on checkbox states
const forceSmartproxy = data.forceDestinationSmartproxy ?? true;
const useHostIp = !forceSmartproxy && (data.useHostIp ?? false);
const useDhcp = useHostIp && (data.useDhcp ?? false);
const staticIp = useHostIp && !useDhcp && data.staticIp ? data.staticIp : undefined;
const forceVlan = useHostIp && (data.forceVlan ?? false);
const vlanId = forceVlan && data.vlanId ? parseInt(data.vlanId, 10) : undefined;
const allowAcls = data.allowAdditionalAcls ?? false;
const destinationAllowList = allowAcls && data.destinationAllowList
? data.destinationAllowList.split(',').map((s: string) => s.trim()).filter(Boolean)
: undefined;
const destinationBlockList = allowAcls && data.destinationBlockList
? data.destinationBlockList.split(',').map((s: string) => s.trim()).filter(Boolean)
: undefined;
await appstate.vpnStatePart.dispatchAction(appstate.createVpnClientAction, {
clientId: data.clientId,
description: data.description || undefined,
serverDefinedClientTags,
forceDestinationSmartproxy: forceSmartproxy,
useHostIp: useHostIp || undefined,
useDhcp: useDhcp || undefined,
staticIp,
forceVlan: forceVlan || undefined,
vlanId,
destinationAllowList,
destinationBlockList,
});
await modalArg.destroy();
},
},
],
});
// Setup conditional form visibility after modal renders
const createForm = createModal?.shadowRoot?.querySelector('.content')?.querySelector('dees-form') as any;
if (createForm) {
await createForm.updateComplete;
setupFormVisibility(createForm);
}
},
},
{
@@ -396,6 +480,13 @@ export class OpsViewVpn extends DeesElement {
` : ''}
<div class="infoItem"><span class="infoLabel">Description</span><span class="infoValue">${client.description || '-'}</span></div>
<div class="infoItem"><span class="infoLabel">Tags</span><span class="infoValue">${client.serverDefinedClientTags?.join(', ') || '-'}</span></div>
<div class="infoItem"><span class="infoLabel">Routing</span><span class="infoValue">${client.forceDestinationSmartproxy !== false ? 'SmartProxy' : client.useHostIp ? 'Host IP' : 'Direct'}</span></div>
${client.useHostIp ? html`
<div class="infoItem"><span class="infoLabel">Host IP</span><span class="infoValue">${client.useDhcp ? 'DHCP' : client.staticIp ? `Static: ${client.staticIp}` : 'Not configured'}</span></div>
<div class="infoItem"><span class="infoLabel">VLAN</span><span class="infoValue">${client.forceVlan && client.vlanId != null ? `VLAN ${client.vlanId}` : 'No VLAN'}</span></div>
` : ''}
<div class="infoItem"><span class="infoLabel">Allow List</span><span class="infoValue">${client.destinationAllowList?.length ? client.destinationAllowList.join(', ') : 'None'}</span></div>
<div class="infoItem"><span class="infoLabel">Block List</span><span class="infoValue">${client.destinationBlockList?.length ? client.destinationBlockList.join(', ') : 'None'}</span></div>
<div class="infoItem"><span class="infoLabel">Created</span><span class="infoValue">${new Date(client.createdAt).toLocaleString()}</span></div>
<div class="infoItem"><span class="infoLabel">Updated</span><span class="infoValue">${new Date(client.updatedAt).toLocaleString()}</span></div>
</div>
@@ -553,12 +644,41 @@ export class OpsViewVpn extends DeesElement {
const { DeesModal } = await import('@design.estate/dees-catalog');
const currentDescription = client.description ?? '';
const currentTags = client.serverDefinedClientTags?.join(', ') ?? '';
DeesModal.createAndShow({
const currentForceSmartproxy = client.forceDestinationSmartproxy ?? true;
const currentUseHostIp = client.useHostIp ?? false;
const currentUseDhcp = client.useDhcp ?? false;
const currentStaticIp = client.staticIp ?? '';
const currentForceVlan = client.forceVlan ?? false;
const currentVlanId = client.vlanId != null ? String(client.vlanId) : '';
const currentAllowList = client.destinationAllowList?.join(', ') ?? '';
const currentBlockList = client.destinationBlockList?.join(', ') ?? '';
const currentAllowAcls = (client.destinationAllowList?.length ?? 0) > 0
|| (client.destinationBlockList?.length ?? 0) > 0;
const editModal = await DeesModal.createAndShow({
heading: `Edit: ${client.clientId}`,
content: html`
<dees-form>
<dees-input-text .key=${'description'} .label=${'Description'} .value=${currentDescription}></dees-input-text>
<dees-input-text .key=${'tags'} .label=${'Server-Defined Tags (comma-separated)'} .value=${currentTags}></dees-input-text>
<dees-input-checkbox .key=${'forceDestinationSmartproxy'} .label=${'Force traffic through SmartProxy'} .value=${currentForceSmartproxy}></dees-input-checkbox>
<div class="hostIpGroup" style="display: ${currentForceSmartproxy ? 'none' : 'flex'}; flex-direction: column; gap: 16px;">
<dees-input-checkbox .key=${'useHostIp'} .label=${'Get Host IP'} .value=${currentUseHostIp}></dees-input-checkbox>
<div class="hostIpDetails" style="display: ${currentUseHostIp ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-checkbox .key=${'useDhcp'} .label=${'Get IP through DHCP'} .value=${currentUseDhcp}></dees-input-checkbox>
<div class="staticIpGroup" style="display: ${currentUseDhcp ? 'none' : 'flex'}; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'staticIp'} .label=${'Static IP'} .value=${currentStaticIp}></dees-input-text>
</div>
<dees-input-checkbox .key=${'forceVlan'} .label=${'Force VLAN'} .value=${currentForceVlan}></dees-input-checkbox>
<div class="vlanIdGroup" style="display: ${currentForceVlan ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-text .key=${'vlanId'} .label=${'VLAN ID'} .value=${currentVlanId}></dees-input-text>
</div>
</div>
</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>
</div>
</dees-form>
`,
menuOptions: [
@@ -573,16 +693,47 @@ export class OpsViewVpn extends DeesElement {
const serverDefinedClientTags = data.tags
? data.tags.split(',').map((t: string) => t.trim()).filter(Boolean)
: [];
// Apply conditional logic based on checkbox states
const forceSmartproxy = data.forceDestinationSmartproxy ?? true;
const useHostIp = !forceSmartproxy && (data.useHostIp ?? false);
const useDhcp = useHostIp && (data.useDhcp ?? false);
const staticIp = useHostIp && !useDhcp && data.staticIp ? data.staticIp : undefined;
const forceVlan = useHostIp && (data.forceVlan ?? false);
const vlanId = forceVlan && data.vlanId ? parseInt(data.vlanId, 10) : undefined;
const allowAcls = data.allowAdditionalAcls ?? false;
const destinationAllowList = allowAcls && data.destinationAllowList
? data.destinationAllowList.split(',').map((s: string) => s.trim()).filter(Boolean)
: [];
const destinationBlockList = allowAcls && data.destinationBlockList
? data.destinationBlockList.split(',').map((s: string) => s.trim()).filter(Boolean)
: [];
await appstate.vpnStatePart.dispatchAction(appstate.updateVpnClientAction, {
clientId: client.clientId,
description: data.description || undefined,
serverDefinedClientTags,
forceDestinationSmartproxy: forceSmartproxy,
useHostIp: useHostIp || undefined,
useDhcp: useDhcp || undefined,
staticIp,
forceVlan: forceVlan || undefined,
vlanId,
destinationAllowList,
destinationBlockList,
});
await modalArg.destroy();
},
},
],
});
// Setup conditional form visibility for edit dialog
const editForm = editModal?.shadowRoot?.querySelector('.content')?.querySelector('dees-form') as any;
if (editForm) {
await editForm.updateComplete;
setupFormVisibility(editForm);
}
},
},
{

View File

@@ -68,6 +68,12 @@ For reporting bugs, issues, or security vulnerabilities, please visit [community
- API token creation, revocation, and scope management
- Routes tab and API Tokens tab in unified view
### 🛡️ Security Profiles & Network Targets
- Create, edit, and delete reusable security profiles (IP allow/block lists, rate limits, max connections)
- Create, edit, and delete reusable network targets (host:port destinations)
- In-row and context menu actions for quick editing
- Changes propagate automatically to all referencing routes
### ⚙️ Configuration
- Read-only display of current system configuration
- Status badges for boolean values (enabled/disabled)

View File

@@ -3,7 +3,7 @@ import * as appstate from './appstate.js';
const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;
export const validViews = ['overview', 'network', 'emails', 'logs', 'routes', 'apitokens', 'configuration', 'security', 'certificates', 'remoteingress', 'vpn'] as const;
export const validViews = ['overview', 'network', 'emails', 'logs', 'routes', 'apitokens', 'configuration', 'security', 'certificates', 'remoteingress', 'vpn', 'securityprofiles', 'networktargets'] as const;
export type TValidView = typeof validViews[number];