Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ed52a3188d | |||
| 93cc5c7b06 | |||
| 5689e93665 | |||
| c224028495 | |||
| 4fbe01823b | |||
| 34ba2c9f02 | |||
| 52aed0e96e | |||
| ea2e618990 | |||
| 140637a307 | |||
| 21c80e173d | |||
| e77fe9451e | |||
| 7971bd249e | |||
| 6099563acd | |||
| bf4c181026 | |||
| d9d12427d3 | |||
| 91aa9a7228 | |||
| 877356b247 | |||
| 2325f01cde | |||
| 00fdadb088 | |||
| 2b76e05a40 | |||
| 1b37944aab | |||
| 35a01a6981 | |||
| 3058706d2a | |||
| 0e4d6a3c0c | |||
| 2bc2475878 | |||
| 37eab7c7b1 |
80
changelog.md
80
changelog.md
@@ -1,5 +1,85 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-04-08 - 13.9.0 - feat(dns)
|
||||
add built-in dcrouter DNS provider support and rename manual domains to dcrouter-hosted/local
|
||||
|
||||
- Expose a synthetic built-in "DcRouter" provider in provider listings and block create, edit, delete, test, and external domain listing operations for it
|
||||
- Rename domain and record source semantics from "manual" to "dcrouter" and "local" across backend, interfaces, and UI
|
||||
- Add database migrations to convert existing DomainDoc.source and DnsRecordDoc.source values to the new naming
|
||||
- Update domain creation flows and provider UI labels to reflect dcrouter-hosted authoritative domains
|
||||
|
||||
## 2026-04-08 - 13.8.0 - feat(acme)
|
||||
add DB-backed ACME configuration management and OpsServer certificate settings UI
|
||||
|
||||
- introduces a singleton AcmeConfig manager and document persisted in the database, with first-boot seeding from legacy tls.contactEmail and smartProxyConfig.acme options
|
||||
- updates SmartProxy startup to read live ACME settings from the database and only enable DNS-01 challenge wiring when ACME is configured and enabled
|
||||
- adds authenticated OpsServer typed request endpoints and API token scopes for reading and updating ACME configuration
|
||||
- adds web app state and a certificates view card/modal for viewing and editing ACME settings from the Domains certificate UI
|
||||
|
||||
## 2026-04-08 - 13.7.1 - fix(repo)
|
||||
no changes to commit
|
||||
|
||||
|
||||
## 2026-04-08 - 13.7.0 - feat(dns-providers)
|
||||
add provider-agnostic DNS provider form metadata and reusable UI for create/edit flows
|
||||
|
||||
- Introduce shared DNS provider type descriptors and credential field metadata to drive provider forms dynamically.
|
||||
- Add a reusable dns-provider-form component and update provider create/edit dialogs to use typed provider selection and credential handling.
|
||||
- Remove Cloudflare-specific ACME helper exposure and clarify provider-agnostic DNS manager and factory documentation for future provider implementations.
|
||||
|
||||
## 2026-04-08 - 13.6.0 - feat(dns)
|
||||
add db-backed DNS provider, domain, and record management with ops UI support
|
||||
|
||||
- introduce DnsManager-backed persistence for DNS providers, domains, and records with Cloudflare provider support
|
||||
- replace constructor-based ACME DNS challenge configuration with provider records stored in the database
|
||||
- add opsserver typed request handlers and API token scopes for managing DNS providers, domains, and records
|
||||
- add a new Domains section in the ops UI for providers, domains, DNS records, and certificates
|
||||
|
||||
## 2026-04-08 - 13.5.0 - feat(opsserver-access)
|
||||
add admin user listing to the access dashboard
|
||||
|
||||
- register a new admin-only typed request endpoint to list users with id, username, and role while excluding passwords
|
||||
- add users state management and a dedicated access dashboard view for browsing OpsServer user accounts
|
||||
- update access routing to include the new users subview and improve related table filtering and section headings
|
||||
|
||||
## 2026-04-08 - 13.4.2 - fix(repo)
|
||||
no changes to commit
|
||||
|
||||
|
||||
## 2026-04-08 - 13.4.1 - fix(repo)
|
||||
no changes to commit
|
||||
|
||||
|
||||
## 2026-04-08 - 13.4.0 - feat(web-ui)
|
||||
reorganize dashboard views into grouped navigation with new email, access, and network subviews
|
||||
|
||||
- Restructures the ops dashboard and router to use grouped top-level sections with subviews for overview, network, email, access, and security.
|
||||
- Adds dedicated Email Security and API Tokens views and exposes Remote Ingress and VPN under Network subnavigation.
|
||||
- Updates refresh and initial view handling to work with nested subviews, including remote ingress and VPN refresh behavior.
|
||||
- Moves overview, configuration, email, API token, and remote ingress components into feature directories and standardizes shared view styling.
|
||||
|
||||
## 2026-04-08 - 13.3.0 - feat(web-ui)
|
||||
reorganize network and security views into tabbed subviews with route-aware navigation
|
||||
|
||||
- add URL-based subview support in app state and router for network and security sections
|
||||
- group routes, source profiles, network targets, and target profiles under the network view with tab navigation
|
||||
- split security into dedicated overview, blocked IPs, authentication, and email security subviews
|
||||
- update configuration navigation to deep-link directly to the network routes subview
|
||||
|
||||
## 2026-04-08 - 13.2.2 - fix(project)
|
||||
no changes to commit
|
||||
|
||||
|
||||
## 2026-04-08 - 13.2.1 - fix(project)
|
||||
no changes to commit
|
||||
|
||||
|
||||
## 2026-04-08 - 13.2.0 - feat(ops-ui)
|
||||
add column filters to operations tables across admin views
|
||||
|
||||
- Enable table column filters for API tokens, certificates, network requests, top IPs, backends, network targets, remote ingress edges, security views, source profiles, target profiles, and VPN clients.
|
||||
- Improves filtering and exploration of operational data throughout the admin interface without changing backend behavior.
|
||||
|
||||
## 2026-04-08 - 13.1.3 - fix(certificate-handler)
|
||||
preserve wildcard coverage during forced certificate renewals and propagate renewed certs to sibling domains
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@serve.zone/dcrouter",
|
||||
"private": false,
|
||||
"version": "13.1.3",
|
||||
"version": "13.9.0",
|
||||
"description": "A multifaceted routing service handling mail and SMS delivery functions.",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -35,7 +35,7 @@
|
||||
"@api.global/typedserver": "^8.4.6",
|
||||
"@api.global/typedsocket": "^4.1.2",
|
||||
"@apiclient.xyz/cloudflare": "^7.1.0",
|
||||
"@design.estate/dees-catalog": "^3.67.1",
|
||||
"@design.estate/dees-catalog": "^3.70.0",
|
||||
"@design.estate/dees-element": "^2.2.4",
|
||||
"@push.rocks/lik": "^6.4.0",
|
||||
"@push.rocks/projectinfo": "^5.1.0",
|
||||
@@ -49,7 +49,7 @@
|
||||
"@push.rocks/smartjwt": "^2.2.1",
|
||||
"@push.rocks/smartlog": "^3.2.2",
|
||||
"@push.rocks/smartmetrics": "^3.0.3",
|
||||
"@push.rocks/smartmigration": "1.1.1",
|
||||
"@push.rocks/smartmigration": "1.2.0",
|
||||
"@push.rocks/smartmta": "^5.3.1",
|
||||
"@push.rocks/smartnetwork": "^4.5.2",
|
||||
"@push.rocks/smartpath": "^6.0.0",
|
||||
|
||||
24
pnpm-lock.yaml
generated
24
pnpm-lock.yaml
generated
@@ -24,8 +24,8 @@ importers:
|
||||
specifier: ^7.1.0
|
||||
version: 7.1.0
|
||||
'@design.estate/dees-catalog':
|
||||
specifier: ^3.67.1
|
||||
version: 3.67.1(@tiptap/pm@2.27.2)
|
||||
specifier: ^3.70.0
|
||||
version: 3.70.0(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-element':
|
||||
specifier: ^2.2.4
|
||||
version: 2.2.4
|
||||
@@ -66,8 +66,8 @@ importers:
|
||||
specifier: ^3.0.3
|
||||
version: 3.0.3
|
||||
'@push.rocks/smartmigration':
|
||||
specifier: 1.1.1
|
||||
version: 1.1.1(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))
|
||||
specifier: 1.2.0
|
||||
version: 1.2.0(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))
|
||||
'@push.rocks/smartmta':
|
||||
specifier: ^5.3.1
|
||||
version: 5.3.1
|
||||
@@ -353,8 +353,8 @@ packages:
|
||||
'@configvault.io/interfaces@1.0.17':
|
||||
resolution: {integrity: sha512-bEcCUR2VBDJsTin8HQh8Uw/mlYl2v8A3jMIaQ+MTB9Hrqd6CZL2dL7iJdWyFl/3EIX+LDxWFR+Oq7liIq7w+1Q==}
|
||||
|
||||
'@design.estate/dees-catalog@3.67.1':
|
||||
resolution: {integrity: sha512-8zaVNP70IbcB6pEmLoBxVA5WD0N5gQr12ylTdILtvds6rftKLCI1i2jx4RBztIy4FpZv0wIewJBtRvSUjK8Ysw==}
|
||||
'@design.estate/dees-catalog@3.70.0':
|
||||
resolution: {integrity: sha512-bNqOxxl83FNCCV+7QoUj6oeRC0VTExWOClrLrHNMoLIU0TCtzhcmQqiuJhdWrcCwZ5RBhXHGMSFsR62d2RcWpw==}
|
||||
|
||||
'@design.estate/dees-comms@1.0.30':
|
||||
resolution: {integrity: sha512-KchMlklJfKAjQiJiR0xmofXtQ27VgZtBIxcMwPE9d+h3jJRv+lPZxzBQVOM0eyM0uS44S5vJMZ11IeV4uDXSHg==}
|
||||
@@ -1231,8 +1231,8 @@ packages:
|
||||
'@push.rocks/smartmetrics@3.0.3':
|
||||
resolution: {integrity: sha512-RYY4NOla3kraZYVF9TBHgIz4/hSkqVDVNP7tLwhLK5mGBPBy8I/9NWXX6txZKQw6QihP85YD8mWUuUu2xS4D6Q==}
|
||||
|
||||
'@push.rocks/smartmigration@1.1.1':
|
||||
resolution: {integrity: sha512-K/eLN9cNy+CLOT73rhI93vOy/vGwpV46iJpjRUyPwHsMcQcV6po2idk5+XZQzeuq2x7KpKuUPtZ6gXMtf5Y/ig==}
|
||||
'@push.rocks/smartmigration@1.2.0':
|
||||
resolution: {integrity: sha512-H2diE1UbZm4cXjxgxkt2YQW3aUQ3QVVU/e8Ws30hzIep0xIqL1BH6//WawA5ZBQhnAOBssZpVOuWOd3GIeBq+Q==}
|
||||
peerDependencies:
|
||||
'@push.rocks/smartbucket': ^4.6.0
|
||||
'@push.rocks/smartdata': ^7.1.7
|
||||
@@ -4315,7 +4315,7 @@ snapshots:
|
||||
'@api.global/typedrequest-interfaces': 3.0.19
|
||||
'@api.global/typedsocket': 4.1.2(@push.rocks/smartserve@2.0.3)
|
||||
'@cloudflare/workers-types': 4.20260405.1
|
||||
'@design.estate/dees-catalog': 3.67.1(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-catalog': 3.70.0(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-comms': 1.0.30
|
||||
'@push.rocks/lik': 6.4.0
|
||||
'@push.rocks/smartdelay': 3.0.5
|
||||
@@ -4844,7 +4844,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@api.global/typedrequest-interfaces': 3.0.19
|
||||
|
||||
'@design.estate/dees-catalog@3.67.1(@tiptap/pm@2.27.2)':
|
||||
'@design.estate/dees-catalog@3.70.0(@tiptap/pm@2.27.2)':
|
||||
dependencies:
|
||||
'@design.estate/dees-domtools': 2.5.4
|
||||
'@design.estate/dees-element': 2.2.4
|
||||
@@ -6354,7 +6354,7 @@ snapshots:
|
||||
'@push.rocks/smartdelay': 3.0.5
|
||||
'@push.rocks/smartlog': 3.2.2
|
||||
|
||||
'@push.rocks/smartmigration@1.1.1(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))':
|
||||
'@push.rocks/smartmigration@1.2.0(@push.rocks/smartbucket@4.6.0)(@push.rocks/smartdata@7.1.7(socks@2.8.7))':
|
||||
dependencies:
|
||||
'@push.rocks/smartlog': 3.2.2
|
||||
'@push.rocks/smartversion': 3.1.0
|
||||
@@ -6900,7 +6900,7 @@ snapshots:
|
||||
|
||||
'@serve.zone/catalog@2.12.3(@tiptap/pm@2.27.2)':
|
||||
dependencies:
|
||||
'@design.estate/dees-catalog': 3.67.1(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-catalog': 3.70.0(@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
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/dcrouter',
|
||||
version: '13.1.3',
|
||||
version: '13.9.0',
|
||||
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
|
||||
}
|
||||
|
||||
1
ts/acme/index.ts
Normal file
1
ts/acme/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './manager.acme-config.js';
|
||||
182
ts/acme/manager.acme-config.ts
Normal file
182
ts/acme/manager.acme-config.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { logger } from '../logger.js';
|
||||
import { AcmeConfigDoc } from '../db/documents/index.js';
|
||||
import type { IDcRouterOptions } from '../classes.dcrouter.js';
|
||||
import type { IAcmeConfig } from '../../ts_interfaces/data/acme-config.js';
|
||||
|
||||
/**
|
||||
* AcmeConfigManager — owns the singleton ACME configuration in the DB.
|
||||
*
|
||||
* Lifecycle:
|
||||
* - `start()` — loads from the DB; if empty, seeds from legacy constructor
|
||||
* fields (`tls.contactEmail`, `smartProxyConfig.acme.*`) on first boot.
|
||||
* - `getConfig()` — returns the in-memory cached `IAcmeConfig` (or null)
|
||||
* - `updateConfig(args, updatedBy)` — upserts and refreshes the cache
|
||||
*
|
||||
* Reload semantics: updates take effect on the next dcrouter restart because
|
||||
* `SmartAcme` is instantiated once in `setupSmartProxy()`. `renewThresholdDays`
|
||||
* applies immediately to the next renewal check. See
|
||||
* `ts_web/elements/domains/ops-view-certificates.ts` for the UI warning.
|
||||
*/
|
||||
export class AcmeConfigManager {
|
||||
private cached: IAcmeConfig | null = null;
|
||||
|
||||
constructor(private options: IDcRouterOptions) {}
|
||||
|
||||
public async start(): Promise<void> {
|
||||
logger.log('info', 'AcmeConfigManager: starting');
|
||||
let doc = await AcmeConfigDoc.load();
|
||||
|
||||
if (!doc) {
|
||||
// First-boot path: seed from legacy constructor fields if present.
|
||||
const seed = this.deriveSeedFromOptions();
|
||||
if (seed) {
|
||||
doc = await this.createSeedDoc(seed);
|
||||
logger.log(
|
||||
'info',
|
||||
`AcmeConfigManager: seeded from constructor legacy fields (accountEmail=${seed.accountEmail}, useProduction=${seed.useProduction})`,
|
||||
);
|
||||
} else {
|
||||
logger.log(
|
||||
'info',
|
||||
'AcmeConfigManager: no AcmeConfig in DB and no legacy constructor fields — ACME disabled until configured via Domains > Certificates > Settings.',
|
||||
);
|
||||
}
|
||||
} else if (this.deriveSeedFromOptions()) {
|
||||
logger.log(
|
||||
'warn',
|
||||
'AcmeConfigManager: ignoring constructor tls.contactEmail / smartProxyConfig.acme — DB already has AcmeConfigDoc. Manage via Domains > Certificates > Settings.',
|
||||
);
|
||||
}
|
||||
|
||||
this.cached = doc ? this.toPlain(doc) : null;
|
||||
if (this.cached) {
|
||||
logger.log(
|
||||
'info',
|
||||
`AcmeConfigManager: loaded ACME config (accountEmail=${this.cached.accountEmail}, enabled=${this.cached.enabled}, useProduction=${this.cached.useProduction})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async stop(): Promise<void> {
|
||||
this.cached = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current ACME config, or null if not configured.
|
||||
* In-memory — does not hit the DB.
|
||||
*/
|
||||
public getConfig(): IAcmeConfig | null {
|
||||
return this.cached;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if there is an enabled ACME config. Used by `setupSmartProxy()` to
|
||||
* decide whether to instantiate SmartAcme.
|
||||
*/
|
||||
public hasEnabledConfig(): boolean {
|
||||
return this.cached !== null && this.cached.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upsert the ACME config. All fields are optional; missing fields are
|
||||
* preserved from the existing row (or defaulted if there is no row yet).
|
||||
*/
|
||||
public async updateConfig(
|
||||
args: Partial<Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'>>,
|
||||
updatedBy: string,
|
||||
): Promise<IAcmeConfig> {
|
||||
let doc = await AcmeConfigDoc.load();
|
||||
const now = Date.now();
|
||||
|
||||
if (!doc) {
|
||||
doc = new AcmeConfigDoc();
|
||||
doc.configId = 'acme-config';
|
||||
doc.accountEmail = args.accountEmail ?? '';
|
||||
doc.enabled = args.enabled ?? true;
|
||||
doc.useProduction = args.useProduction ?? true;
|
||||
doc.autoRenew = args.autoRenew ?? true;
|
||||
doc.renewThresholdDays = args.renewThresholdDays ?? 30;
|
||||
} else {
|
||||
if (args.accountEmail !== undefined) doc.accountEmail = args.accountEmail;
|
||||
if (args.enabled !== undefined) doc.enabled = args.enabled;
|
||||
if (args.useProduction !== undefined) doc.useProduction = args.useProduction;
|
||||
if (args.autoRenew !== undefined) doc.autoRenew = args.autoRenew;
|
||||
if (args.renewThresholdDays !== undefined) doc.renewThresholdDays = args.renewThresholdDays;
|
||||
}
|
||||
|
||||
doc.updatedAt = now;
|
||||
doc.updatedBy = updatedBy;
|
||||
await doc.save();
|
||||
|
||||
this.cached = this.toPlain(doc);
|
||||
return this.cached;
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Internal helpers
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* Build a seed object from the legacy constructor fields. Returns null
|
||||
* if the user has not provided any of them.
|
||||
*
|
||||
* Supports BOTH `tls.contactEmail` (short form) and `smartProxyConfig.acme`
|
||||
* (full form). `smartProxyConfig.acme` wins when both are present.
|
||||
*/
|
||||
private deriveSeedFromOptions(): Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'> | null {
|
||||
const acme = this.options.smartProxyConfig?.acme;
|
||||
const tls = this.options.tls;
|
||||
|
||||
// Prefer the explicit smartProxyConfig.acme block if present.
|
||||
if (acme?.accountEmail) {
|
||||
return {
|
||||
accountEmail: acme.accountEmail,
|
||||
enabled: acme.enabled !== false,
|
||||
useProduction: acme.useProduction !== false,
|
||||
autoRenew: acme.autoRenew !== false,
|
||||
renewThresholdDays: acme.renewThresholdDays ?? 30,
|
||||
};
|
||||
}
|
||||
|
||||
// Fall back to the short tls.contactEmail form.
|
||||
if (tls?.contactEmail) {
|
||||
return {
|
||||
accountEmail: tls.contactEmail,
|
||||
enabled: true,
|
||||
useProduction: true,
|
||||
autoRenew: true,
|
||||
renewThresholdDays: 30,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async createSeedDoc(
|
||||
seed: Omit<IAcmeConfig, 'updatedAt' | 'updatedBy'>,
|
||||
): Promise<AcmeConfigDoc> {
|
||||
const doc = new AcmeConfigDoc();
|
||||
doc.configId = 'acme-config';
|
||||
doc.accountEmail = seed.accountEmail;
|
||||
doc.enabled = seed.enabled;
|
||||
doc.useProduction = seed.useProduction;
|
||||
doc.autoRenew = seed.autoRenew;
|
||||
doc.renewThresholdDays = seed.renewThresholdDays;
|
||||
doc.updatedAt = Date.now();
|
||||
doc.updatedBy = 'seed';
|
||||
await doc.save();
|
||||
return doc;
|
||||
}
|
||||
|
||||
private toPlain(doc: AcmeConfigDoc): IAcmeConfig {
|
||||
return {
|
||||
accountEmail: doc.accountEmail,
|
||||
enabled: doc.enabled,
|
||||
useProduction: doc.useProduction,
|
||||
autoRenew: doc.autoRenew,
|
||||
renewThresholdDays: doc.renewThresholdDays,
|
||||
updatedAt: doc.updatedAt,
|
||||
updatedBy: doc.updatedBy,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import { VpnManager, type IVpnManagerConfig } from './vpn/index.js';
|
||||
import { RouteConfigManager, ApiTokenManager, ReferenceResolver, DbSeeder, TargetProfileManager } from './config/index.js';
|
||||
import { SecurityLogger, ContentScanner, IPReputationChecker } from './security/index.js';
|
||||
import { type IHttp3Config, augmentRoutesWithHttp3 } from './http3/index.js';
|
||||
import { DnsManager } from './dns/manager.dns.js';
|
||||
import { AcmeConfigManager } from './acme/manager.acme-config.js';
|
||||
|
||||
export interface IDcRouterOptions {
|
||||
/** Base directory for all dcrouter data. Defaults to ~/.serve.zone/dcrouter */
|
||||
@@ -116,13 +118,6 @@ export interface IDcRouterOptions {
|
||||
useIngressProxy?: boolean; // Whether to replace server IP with proxy IP (default: true)
|
||||
}>;
|
||||
|
||||
/** DNS challenge configuration for ACME (optional) */
|
||||
dnsChallenge?: {
|
||||
/** Cloudflare API key for DNS challenges */
|
||||
cloudflareApiKey?: string;
|
||||
/** Other DNS providers can be added here */
|
||||
};
|
||||
|
||||
/**
|
||||
* Unified database configuration.
|
||||
* All persistent data (config, certs, VPN, cache, etc.) is stored via smartdata.
|
||||
@@ -279,6 +274,12 @@ export class DcRouter {
|
||||
public referenceResolver?: ReferenceResolver;
|
||||
public targetProfileManager?: TargetProfileManager;
|
||||
|
||||
// Domain / DNS management (DB-backed providers, domains, records)
|
||||
public dnsManager?: DnsManager;
|
||||
|
||||
// ACME configuration (DB-backed singleton, replaces tls.contactEmail)
|
||||
public acmeConfigManager?: AcmeConfigManager;
|
||||
|
||||
// Auto-discovered public IP (populated by generateAuthoritativeRecords)
|
||||
public detectedPublicIp: string | null = null;
|
||||
|
||||
@@ -393,10 +394,57 @@ export class DcRouter {
|
||||
.withRetry({ maxRetries: 1, baseDelayMs: 1000 }),
|
||||
);
|
||||
|
||||
// SmartProxy: critical, depends on DcRouterDb (if enabled)
|
||||
// DnsManager: optional, depends on DcRouterDb — owns DB-backed DNS state
|
||||
// (providers, domains, records). Must run before SmartProxy so ACME DNS-01
|
||||
// wiring can look up providers.
|
||||
if (this.options.dbConfig?.enabled !== false) {
|
||||
this.serviceManager.addService(
|
||||
new plugins.taskbuffer.Service('DnsManager')
|
||||
.optional()
|
||||
.dependsOn('DcRouterDb')
|
||||
.withStart(async () => {
|
||||
this.dnsManager = new DnsManager(this.options);
|
||||
await this.dnsManager.start();
|
||||
})
|
||||
.withStop(async () => {
|
||||
if (this.dnsManager) {
|
||||
await this.dnsManager.stop();
|
||||
this.dnsManager = undefined;
|
||||
}
|
||||
})
|
||||
.withRetry({ maxRetries: 1, baseDelayMs: 500 }),
|
||||
);
|
||||
}
|
||||
|
||||
// AcmeConfigManager: optional, depends on DcRouterDb — owns the singleton
|
||||
// ACME configuration (accountEmail, useProduction, etc.). Must run before
|
||||
// SmartProxy so setupSmartProxy() can read the ACME config from the DB.
|
||||
// On first boot, seeds from legacy `tls.contactEmail` / `smartProxyConfig.acme`.
|
||||
if (this.options.dbConfig?.enabled !== false) {
|
||||
this.serviceManager.addService(
|
||||
new plugins.taskbuffer.Service('AcmeConfigManager')
|
||||
.optional()
|
||||
.dependsOn('DcRouterDb')
|
||||
.withStart(async () => {
|
||||
this.acmeConfigManager = new AcmeConfigManager(this.options);
|
||||
await this.acmeConfigManager.start();
|
||||
})
|
||||
.withStop(async () => {
|
||||
if (this.acmeConfigManager) {
|
||||
await this.acmeConfigManager.stop();
|
||||
this.acmeConfigManager = undefined;
|
||||
}
|
||||
})
|
||||
.withRetry({ maxRetries: 1, baseDelayMs: 500 }),
|
||||
);
|
||||
}
|
||||
|
||||
// SmartProxy: critical, depends on DcRouterDb + DnsManager + AcmeConfigManager (if enabled)
|
||||
const smartProxyDeps: string[] = [];
|
||||
if (this.options.dbConfig?.enabled !== false) {
|
||||
smartProxyDeps.push('DcRouterDb');
|
||||
smartProxyDeps.push('DnsManager');
|
||||
smartProxyDeps.push('AcmeConfigManager');
|
||||
}
|
||||
this.serviceManager.addService(
|
||||
new plugins.taskbuffer.Service('SmartProxy')
|
||||
@@ -415,9 +463,11 @@ export class DcRouter {
|
||||
.withRetry({ maxRetries: 0 }),
|
||||
);
|
||||
|
||||
// SmartAcme: optional, depends on SmartProxy — aggressive retry for rate limits
|
||||
// Only registered if DNS challenge is configured
|
||||
if (this.options.dnsChallenge?.cloudflareApiKey) {
|
||||
// SmartAcme: optional, depends on SmartProxy — aggressive retry for rate limits.
|
||||
// Always registered when the DB is enabled; setupSmartProxy() decides whether
|
||||
// to actually instantiate SmartAcme based on whether any DnsProviderDoc exists.
|
||||
// If `this.smartAcme` is unset by the time this service starts, withStart is a no-op.
|
||||
if (this.options.dbConfig?.enabled !== false) {
|
||||
this.serviceManager.addService(
|
||||
new plugins.taskbuffer.Service('SmartAcme')
|
||||
.optional()
|
||||
@@ -815,46 +865,65 @@ export class DcRouter {
|
||||
}
|
||||
|
||||
let routes: plugins.smartproxy.IRouteConfig[] = [];
|
||||
let acmeConfig: plugins.smartproxy.IAcmeOptions | undefined;
|
||||
|
||||
// If user provides full SmartProxy config, use it directly
|
||||
|
||||
// If user provides full SmartProxy config, use its routes.
|
||||
// NOTE: `smartProxyConfig.acme` is now seed-only — consumed by
|
||||
// AcmeConfigManager on first boot. The live ACME config always comes
|
||||
// from the DB via `this.acmeConfigManager.getConfig()`.
|
||||
if (this.options.smartProxyConfig) {
|
||||
routes = this.options.smartProxyConfig.routes || [];
|
||||
acmeConfig = this.options.smartProxyConfig.acme;
|
||||
logger.log('info', `Found ${routes.length} routes in config, ACME config present: ${!!acmeConfig}`);
|
||||
logger.log('info', `Found ${routes.length} routes in config`);
|
||||
}
|
||||
|
||||
|
||||
// If email config exists, automatically add email routes
|
||||
if (this.options.emailConfig) {
|
||||
const emailRoutes = this.generateEmailRoutes(this.options.emailConfig);
|
||||
logger.log('debug', 'Email routes generated', { routes: JSON.stringify(emailRoutes) });
|
||||
routes = [...routes, ...emailRoutes]; // Enable email routing through SmartProxy
|
||||
}
|
||||
|
||||
|
||||
// If DNS is configured, add DNS routes
|
||||
if (this.options.dnsNsDomains && this.options.dnsNsDomains.length > 0) {
|
||||
const dnsRoutes = this.generateDnsRoutes();
|
||||
logger.log('debug', `DNS routes for nameservers ${this.options.dnsNsDomains.join(', ')}`, { routes: JSON.stringify(dnsRoutes) });
|
||||
routes = [...routes, ...dnsRoutes];
|
||||
}
|
||||
|
||||
// Merge TLS/ACME configuration if provided at root level
|
||||
if (this.options.tls && !acmeConfig) {
|
||||
acmeConfig = {
|
||||
accountEmail: this.options.tls.contactEmail,
|
||||
enabled: true,
|
||||
useProduction: true,
|
||||
autoRenew: true,
|
||||
renewThresholdDays: 30
|
||||
};
|
||||
|
||||
// Build the ACME options for SmartProxy from the DB-backed AcmeConfigManager.
|
||||
// If no config exists or it's disabled, SmartProxy's own ACME is turned off
|
||||
// and dcrouter's SmartAcme / certProvisionFunction are not wired.
|
||||
const dbAcme = this.acmeConfigManager?.getConfig();
|
||||
const acmeConfig: plugins.smartproxy.IAcmeOptions | undefined =
|
||||
dbAcme && dbAcme.enabled
|
||||
? {
|
||||
accountEmail: dbAcme.accountEmail,
|
||||
enabled: true,
|
||||
useProduction: dbAcme.useProduction,
|
||||
autoRenew: dbAcme.autoRenew,
|
||||
renewThresholdDays: dbAcme.renewThresholdDays,
|
||||
}
|
||||
: undefined;
|
||||
if (acmeConfig) {
|
||||
logger.log(
|
||||
'info',
|
||||
`ACME config: accountEmail=${acmeConfig.accountEmail}, useProduction=${acmeConfig.useProduction}, autoRenew=${acmeConfig.autoRenew}`,
|
||||
);
|
||||
} else {
|
||||
logger.log('info', 'ACME config: disabled or not yet configured in DB');
|
||||
}
|
||||
|
||||
// Configure DNS challenge if available
|
||||
|
||||
// Configure DNS-01 challenge if any DnsProviderDoc exists in the DB AND
|
||||
// ACME is enabled. The DnsManager dispatches each challenge to the right
|
||||
// provider client based on the FQDN being certificated.
|
||||
let challengeHandlers: any[] = [];
|
||||
if (this.options.dnsChallenge?.cloudflareApiKey) {
|
||||
logger.log('info', 'Configuring Cloudflare DNS challenge for ACME');
|
||||
const cloudflareAccount = new plugins.cloudflare.CloudflareAccount(this.options.dnsChallenge.cloudflareApiKey);
|
||||
const dns01Handler = new plugins.smartacme.handlers.Dns01Handler(cloudflareAccount);
|
||||
if (
|
||||
acmeConfig &&
|
||||
this.dnsManager &&
|
||||
(await this.dnsManager.hasAcmeCapableProvider())
|
||||
) {
|
||||
logger.log('info', 'Configuring DNS-01 challenge for ACME via DnsManager (DB providers)');
|
||||
const convenientDnsProvider = this.dnsManager.buildAcmeConvenientDnsProvider();
|
||||
const dns01Handler = new plugins.smartacme.handlers.Dns01Handler(convenientDnsProvider);
|
||||
challengeHandlers.push(dns01Handler);
|
||||
}
|
||||
|
||||
@@ -953,10 +1022,12 @@ export class DcRouter {
|
||||
logger.log('error', 'Error stopping old SmartAcme', { error: String(err) })
|
||||
);
|
||||
}
|
||||
// Safe non-null: challengeHandlers.length > 0 implies both dnsManager
|
||||
// and acmeConfig exist (enforced above).
|
||||
this.smartAcme = new plugins.smartacme.SmartAcme({
|
||||
accountEmail: acmeConfig?.accountEmail || this.options.tls?.contactEmail || 'admin@example.com',
|
||||
accountEmail: dbAcme!.accountEmail,
|
||||
certManager: new StorageBackedCertManager(),
|
||||
environment: 'production',
|
||||
environment: dbAcme!.useProduction ? 'production' : 'integration',
|
||||
challengeHandlers: challengeHandlers,
|
||||
challengePriority: ['dns-01'],
|
||||
});
|
||||
@@ -1720,8 +1791,14 @@ export class DcRouter {
|
||||
this.registerDnsRecords(allRecords);
|
||||
logger.log('info', `Registered ${allRecords.length} DNS records (${authoritativeRecords.length} authoritative, ${emailDnsRecords.length} email, ${dkimRecords.length} DKIM, ${this.options.dnsRecords?.length || 0} user-defined)`);
|
||||
}
|
||||
|
||||
// Hand the DnsServer to DnsManager so DB-backed local records on
|
||||
// dcrouter-hosted domains get registered too.
|
||||
if (this.dnsManager && this.dnsServer) {
|
||||
await this.dnsManager.attachDnsServer(this.dnsServer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create DNS socket handler for DoH
|
||||
*/
|
||||
|
||||
49
ts/db/documents/classes.acme-config.doc.ts
Normal file
49
ts/db/documents/classes.acme-config.doc.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import { DcRouterDb } from '../classes.dcrouter-db.js';
|
||||
|
||||
const getDb = () => DcRouterDb.getInstance().getDb();
|
||||
|
||||
/**
|
||||
* Singleton ACME configuration document. One row per dcrouter instance,
|
||||
* keyed on the fixed `configId = 'acme-config'` following the
|
||||
* `VpnServerKeysDoc` pattern.
|
||||
*
|
||||
* Replaces the legacy `tls.contactEmail` and `smartProxyConfig.acme.*`
|
||||
* constructor fields. Managed via the OpsServer UI at
|
||||
* **Domains > Certificates > Settings**.
|
||||
*/
|
||||
@plugins.smartdata.Collection(() => getDb())
|
||||
export class AcmeConfigDoc extends plugins.smartdata.SmartDataDbDoc<AcmeConfigDoc, AcmeConfigDoc> {
|
||||
@plugins.smartdata.unI()
|
||||
@plugins.smartdata.svDb()
|
||||
public configId: string = 'acme-config';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public accountEmail: string = '';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public enabled: boolean = true;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public useProduction: boolean = true;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public autoRenew: boolean = true;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public renewThresholdDays: number = 30;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public updatedAt: number = 0;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public updatedBy: string = '';
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static async load(): Promise<AcmeConfigDoc | null> {
|
||||
return await AcmeConfigDoc.getInstance({ configId: 'acme-config' });
|
||||
}
|
||||
}
|
||||
63
ts/db/documents/classes.dns-provider.doc.ts
Normal file
63
ts/db/documents/classes.dns-provider.doc.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import { DcRouterDb } from '../classes.dcrouter-db.js';
|
||||
import type {
|
||||
TDnsProviderType,
|
||||
TDnsProviderStatus,
|
||||
TDnsProviderCredentials,
|
||||
} from '../../../ts_interfaces/data/dns-provider.js';
|
||||
|
||||
const getDb = () => DcRouterDb.getInstance().getDb();
|
||||
|
||||
@plugins.smartdata.Collection(() => getDb())
|
||||
export class DnsProviderDoc extends plugins.smartdata.SmartDataDbDoc<DnsProviderDoc, DnsProviderDoc> {
|
||||
@plugins.smartdata.unI()
|
||||
@plugins.smartdata.svDb()
|
||||
public id!: string;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public name: string = '';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public type!: TDnsProviderType;
|
||||
|
||||
/**
|
||||
* Provider credentials, persisted as an opaque object. Shape varies by `type`.
|
||||
* Never returned to the UI — handlers map to IDnsProviderPublic before sending.
|
||||
*/
|
||||
@plugins.smartdata.svDb()
|
||||
public credentials!: TDnsProviderCredentials;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public status: TDnsProviderStatus = 'untested';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public lastTestedAt?: number;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public lastError?: 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<DnsProviderDoc | null> {
|
||||
return await DnsProviderDoc.getInstance({ id });
|
||||
}
|
||||
|
||||
public static async findAll(): Promise<DnsProviderDoc[]> {
|
||||
return await DnsProviderDoc.getInstances({});
|
||||
}
|
||||
|
||||
public static async findByType(type: TDnsProviderType): Promise<DnsProviderDoc[]> {
|
||||
return await DnsProviderDoc.getInstances({ type });
|
||||
}
|
||||
}
|
||||
62
ts/db/documents/classes.dns-record.doc.ts
Normal file
62
ts/db/documents/classes.dns-record.doc.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import { DcRouterDb } from '../classes.dcrouter-db.js';
|
||||
import type { TDnsRecordType, TDnsRecordSource } from '../../../ts_interfaces/data/dns-record.js';
|
||||
|
||||
const getDb = () => DcRouterDb.getInstance().getDb();
|
||||
|
||||
@plugins.smartdata.Collection(() => getDb())
|
||||
export class DnsRecordDoc extends plugins.smartdata.SmartDataDbDoc<DnsRecordDoc, DnsRecordDoc> {
|
||||
@plugins.smartdata.unI()
|
||||
@plugins.smartdata.svDb()
|
||||
public id!: string;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public domainId!: string;
|
||||
|
||||
/** FQDN of the record (e.g. 'www.example.com'). */
|
||||
@plugins.smartdata.svDb()
|
||||
public name: string = '';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public type!: TDnsRecordType;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public value!: string;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public ttl: number = 300;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public proxied?: boolean;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public source!: TDnsRecordSource;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public providerRecordId?: 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<DnsRecordDoc | null> {
|
||||
return await DnsRecordDoc.getInstance({ id });
|
||||
}
|
||||
|
||||
public static async findAll(): Promise<DnsRecordDoc[]> {
|
||||
return await DnsRecordDoc.getInstances({});
|
||||
}
|
||||
|
||||
public static async findByDomainId(domainId: string): Promise<DnsRecordDoc[]> {
|
||||
return await DnsRecordDoc.getInstances({ domainId });
|
||||
}
|
||||
}
|
||||
66
ts/db/documents/classes.domain.doc.ts
Normal file
66
ts/db/documents/classes.domain.doc.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import { DcRouterDb } from '../classes.dcrouter-db.js';
|
||||
import type { TDomainSource } from '../../../ts_interfaces/data/domain.js';
|
||||
|
||||
const getDb = () => DcRouterDb.getInstance().getDb();
|
||||
|
||||
@plugins.smartdata.Collection(() => getDb())
|
||||
export class DomainDoc extends plugins.smartdata.SmartDataDbDoc<DomainDoc, DomainDoc> {
|
||||
@plugins.smartdata.unI()
|
||||
@plugins.smartdata.svDb()
|
||||
public id!: string;
|
||||
|
||||
/** FQDN — kept lowercased on save. */
|
||||
@plugins.smartdata.svDb()
|
||||
public name: string = '';
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public source!: TDomainSource;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public providerId?: string;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public authoritative: boolean = false;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public nameservers?: string[];
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public externalZoneId?: string;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public lastSyncedAt?: number;
|
||||
|
||||
@plugins.smartdata.svDb()
|
||||
public description?: 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<DomainDoc | null> {
|
||||
return await DomainDoc.getInstance({ id });
|
||||
}
|
||||
|
||||
public static async findByName(name: string): Promise<DomainDoc | null> {
|
||||
return await DomainDoc.getInstance({ name: name.toLowerCase() });
|
||||
}
|
||||
|
||||
public static async findAll(): Promise<DomainDoc[]> {
|
||||
return await DomainDoc.getInstances({});
|
||||
}
|
||||
|
||||
public static async findByProviderId(providerId: string): Promise<DomainDoc[]> {
|
||||
return await DomainDoc.getInstances({ providerId });
|
||||
}
|
||||
}
|
||||
@@ -25,3 +25,11 @@ export * from './classes.remote-ingress-edge.doc.js';
|
||||
// RADIUS document classes
|
||||
export * from './classes.vlan-mappings.doc.js';
|
||||
export * from './classes.accounting-session.doc.js';
|
||||
|
||||
// DNS / Domain management document classes
|
||||
export * from './classes.dns-provider.doc.js';
|
||||
export * from './classes.domain.doc.js';
|
||||
export * from './classes.dns-record.doc.js';
|
||||
|
||||
// ACME configuration (singleton)
|
||||
export * from './classes.acme-config.doc.js';
|
||||
|
||||
2
ts/dns/index.ts
Normal file
2
ts/dns/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './manager.dns.js';
|
||||
export * from './providers/index.js';
|
||||
880
ts/dns/manager.dns.ts
Normal file
880
ts/dns/manager.dns.ts
Normal file
@@ -0,0 +1,880 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import { logger } from '../logger.js';
|
||||
import {
|
||||
DnsProviderDoc,
|
||||
DomainDoc,
|
||||
DnsRecordDoc,
|
||||
} from '../db/documents/index.js';
|
||||
import type { IDcRouterOptions } from '../classes.dcrouter.js';
|
||||
import type { IDnsProviderClient, IProviderRecord } from './providers/interfaces.js';
|
||||
import { createDnsProvider } from './providers/factory.js';
|
||||
import type {
|
||||
TDnsRecordType,
|
||||
TDnsRecordSource,
|
||||
} from '../../ts_interfaces/data/dns-record.js';
|
||||
import type {
|
||||
TDnsProviderType,
|
||||
TDnsProviderCredentials,
|
||||
IDnsProviderPublic,
|
||||
IProviderDomainListing,
|
||||
} from '../../ts_interfaces/data/dns-provider.js';
|
||||
|
||||
/**
|
||||
* DnsManager — owns runtime DNS state on top of the embedded DnsServer.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Load Domain/DnsRecord docs from the DB on start
|
||||
* - First-boot seeding from legacy constructor config (dnsScopes/dnsRecords/dnsNsDomains)
|
||||
* - Register dcrouter-hosted domain records with smartdns.DnsServer at startup
|
||||
* - Provide CRUD methods used by OpsServer handlers (dcrouter-hosted domains hit
|
||||
* smartdns, provider domains hit the provider API)
|
||||
* - Expose a provider lookup used by the ACME DNS-01 wiring in setupSmartProxy()
|
||||
*
|
||||
* Provider-managed domains are NEVER served from the embedded DnsServer — the
|
||||
* provider stays authoritative. We only mirror their records locally for the UI
|
||||
* and to track providerRecordIds for updates / deletes.
|
||||
*/
|
||||
export class DnsManager {
|
||||
/**
|
||||
* Reference to the active smartdns DnsServer (set by DcRouter once it exists).
|
||||
* May be undefined if dnsScopes/dnsNsDomains aren't configured.
|
||||
*/
|
||||
public dnsServer?: plugins.smartdns.dnsServerMod.DnsServer;
|
||||
|
||||
/**
|
||||
* Cached provider clients, keyed by DnsProviderDoc.id.
|
||||
* Created lazily when a provider is first needed.
|
||||
*/
|
||||
private providerClients = new Map<string, IDnsProviderClient>();
|
||||
|
||||
constructor(private options: IDcRouterOptions) {}
|
||||
|
||||
// ==========================================================================
|
||||
// Lifecycle
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* Called from DcRouter after DcRouterDb is up. Performs first-boot seeding
|
||||
* from legacy constructor config if (and only if) the DB is empty.
|
||||
*/
|
||||
public async start(): Promise<void> {
|
||||
logger.log('info', 'DnsManager: starting');
|
||||
await this.seedFromConstructorConfigIfEmpty();
|
||||
}
|
||||
|
||||
public async stop(): Promise<void> {
|
||||
this.providerClients.clear();
|
||||
this.dnsServer = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the embedded DnsServer instance after it has been created by
|
||||
* DcRouter.setupDnsWithSocketHandler(). After this, local records on
|
||||
* dcrouter-hosted domains loaded from the DB are registered with the server.
|
||||
*/
|
||||
public async attachDnsServer(dnsServer: plugins.smartdns.dnsServerMod.DnsServer): Promise<void> {
|
||||
this.dnsServer = dnsServer;
|
||||
await this.applyDcrouterDomainsToDnsServer();
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// First-boot seeding
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* If no DomainDocs exist yet but the constructor has legacy DNS fields,
|
||||
* seed them as dcrouter-hosted (`domain.source: 'dcrouter'`) zones with
|
||||
* local (`record.source: 'local'`) records. On subsequent boots (DB has
|
||||
* entries), constructor config is ignored with a warning.
|
||||
*/
|
||||
private async seedFromConstructorConfigIfEmpty(): Promise<void> {
|
||||
const existingDomains = await DomainDoc.findAll();
|
||||
const hasLegacyConfig =
|
||||
(this.options.dnsScopes && this.options.dnsScopes.length > 0) ||
|
||||
(this.options.dnsRecords && this.options.dnsRecords.length > 0);
|
||||
|
||||
if (existingDomains.length > 0) {
|
||||
if (hasLegacyConfig) {
|
||||
logger.log(
|
||||
'warn',
|
||||
'DnsManager: DB has DomainDoc entries — ignoring legacy dnsScopes/dnsRecords/dnsNsDomains constructor config. ' +
|
||||
'Manage DNS via the Domains UI instead.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasLegacyConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.log('info', 'DnsManager: seeding DB from legacy constructor DNS config');
|
||||
|
||||
const now = Date.now();
|
||||
const seededDomains = new Map<string, DomainDoc>();
|
||||
|
||||
// Create one DomainDoc per dnsScope (these are the authoritative zones)
|
||||
for (const scope of this.options.dnsScopes ?? []) {
|
||||
const domain = new DomainDoc();
|
||||
domain.id = plugins.uuid.v4();
|
||||
domain.name = scope.toLowerCase();
|
||||
domain.source = 'dcrouter';
|
||||
domain.authoritative = true;
|
||||
domain.createdAt = now;
|
||||
domain.updatedAt = now;
|
||||
domain.createdBy = 'seed';
|
||||
await domain.save();
|
||||
seededDomains.set(domain.name, domain);
|
||||
logger.log('info', `DnsManager: seeded DomainDoc for ${domain.name}`);
|
||||
}
|
||||
|
||||
// Map each legacy dnsRecord to its parent DomainDoc
|
||||
for (const rec of this.options.dnsRecords ?? []) {
|
||||
const parent = this.findParentDomain(rec.name, seededDomains);
|
||||
if (!parent) {
|
||||
logger.log(
|
||||
'warn',
|
||||
`DnsManager: legacy dnsRecord '${rec.name}' has no matching dnsScope — skipping seed`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const record = new DnsRecordDoc();
|
||||
record.id = plugins.uuid.v4();
|
||||
record.domainId = parent.id;
|
||||
record.name = rec.name.toLowerCase();
|
||||
record.type = rec.type as TDnsRecordType;
|
||||
record.value = rec.value;
|
||||
record.ttl = rec.ttl ?? 300;
|
||||
record.source = 'local';
|
||||
record.createdAt = now;
|
||||
record.updatedAt = now;
|
||||
record.createdBy = 'seed';
|
||||
await record.save();
|
||||
}
|
||||
|
||||
logger.log(
|
||||
'info',
|
||||
`DnsManager: seeded ${seededDomains.size} domain(s) and ${this.options.dnsRecords?.length ?? 0} record(s) from legacy config`,
|
||||
);
|
||||
}
|
||||
|
||||
private findParentDomain(
|
||||
recordName: string,
|
||||
domains: Map<string, DomainDoc>,
|
||||
): DomainDoc | null {
|
||||
const lower = recordName.toLowerCase().replace(/^\*\./, '');
|
||||
let candidate: DomainDoc | null = null;
|
||||
for (const [name, doc] of domains) {
|
||||
if (lower === name || lower.endsWith(`.${name}`)) {
|
||||
if (!candidate || name.length > candidate.name.length) {
|
||||
candidate = doc;
|
||||
}
|
||||
}
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// DcRouter-hosted domain DnsServer wiring
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* Register all records from dcrouter-hosted domains in the DB with the
|
||||
* embedded DnsServer. Called once after attachDnsServer().
|
||||
*/
|
||||
private async applyDcrouterDomainsToDnsServer(): Promise<void> {
|
||||
if (!this.dnsServer) {
|
||||
return;
|
||||
}
|
||||
const allDomains = await DomainDoc.findAll();
|
||||
const dcrouterDomains = allDomains.filter((d) => d.source === 'dcrouter');
|
||||
let registered = 0;
|
||||
for (const domain of dcrouterDomains) {
|
||||
const records = await DnsRecordDoc.findByDomainId(domain.id);
|
||||
for (const rec of records) {
|
||||
this.registerRecordWithDnsServer(rec);
|
||||
registered++;
|
||||
}
|
||||
}
|
||||
logger.log(
|
||||
'info',
|
||||
`DnsManager: registered ${registered} dcrouter-hosted DNS record(s) from DB`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a single record with the embedded DnsServer. The handler closure
|
||||
* captures the record fields, so updates require a re-register cycle.
|
||||
*/
|
||||
private registerRecordWithDnsServer(rec: DnsRecordDoc): void {
|
||||
if (!this.dnsServer) return;
|
||||
this.dnsServer.registerHandler(rec.name, [rec.type], (question) => {
|
||||
if (question.name === rec.name && question.type === rec.type) {
|
||||
return {
|
||||
name: rec.name,
|
||||
type: rec.type,
|
||||
class: 'IN',
|
||||
ttl: rec.ttl,
|
||||
data: this.parseRecordData(rec.type, rec.value),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private parseRecordData(type: TDnsRecordType, value: string): any {
|
||||
switch (type) {
|
||||
case 'A':
|
||||
case 'AAAA':
|
||||
case 'CNAME':
|
||||
case 'TXT':
|
||||
case 'NS':
|
||||
case 'CAA':
|
||||
return value;
|
||||
case 'MX': {
|
||||
const [priorityStr, exchange] = value.split(' ');
|
||||
return { priority: parseInt(priorityStr, 10), exchange };
|
||||
}
|
||||
case 'SOA': {
|
||||
const parts = value.split(' ');
|
||||
return {
|
||||
mname: parts[0],
|
||||
rname: parts[1],
|
||||
serial: parseInt(parts[2], 10),
|
||||
refresh: parseInt(parts[3], 10),
|
||||
retry: parseInt(parts[4], 10),
|
||||
expire: parseInt(parts[5], 10),
|
||||
minimum: parseInt(parts[6], 10),
|
||||
};
|
||||
}
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Provider lookup (used by ACME DNS-01 + record CRUD)
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* Get the provider client for a given DnsProviderDoc id, instantiating
|
||||
* (and caching) it on first use.
|
||||
*/
|
||||
public async getProviderClientById(providerId: string): Promise<IDnsProviderClient | null> {
|
||||
const cached = this.providerClients.get(providerId);
|
||||
if (cached) return cached;
|
||||
const doc = await DnsProviderDoc.findById(providerId);
|
||||
if (!doc) return null;
|
||||
const client = createDnsProvider(doc.type, doc.credentials);
|
||||
this.providerClients.set(providerId, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the IDnsProviderClient that owns the given FQDN (by walking up its
|
||||
* labels to find a matching DomainDoc with `source === 'provider'`).
|
||||
* Returns null if no provider claims this FQDN.
|
||||
*
|
||||
* Used by:
|
||||
* - SmartAcme DNS-01 wiring in setupSmartProxy()
|
||||
* - DnsRecordHandler when creating provider records
|
||||
*/
|
||||
public async getProviderClientForDomain(fqdn: string): Promise<IDnsProviderClient | null> {
|
||||
const lower = fqdn.toLowerCase().replace(/^\*\./, '').replace(/\.$/, '');
|
||||
const allDomains = await DomainDoc.findAll();
|
||||
const providerDomains = allDomains
|
||||
.filter((d) => d.source === 'provider' && d.providerId)
|
||||
// longest-match wins
|
||||
.sort((a, b) => b.name.length - a.name.length);
|
||||
|
||||
for (const domain of providerDomains) {
|
||||
if (lower === domain.name || lower.endsWith(`.${domain.name}`)) {
|
||||
return this.getProviderClientById(domain.providerId!);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any cloudflare provider exists in the DB. Used by setupSmartProxy()
|
||||
* to decide whether to wire SmartAcme with a DNS-01 handler.
|
||||
*/
|
||||
public async hasAcmeCapableProvider(): Promise<boolean> {
|
||||
const providers = await DnsProviderDoc.findAll();
|
||||
return providers.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an IConvenientDnsProvider that dispatches each ACME challenge to
|
||||
* the right provider client (whichever provider type owns the parent zone),
|
||||
* based on the challenge's hostName. Provider-agnostic — uses the IDnsProviderClient
|
||||
* interface, so any registered provider implementation works.
|
||||
* Returned object plugs directly into smartacme's Dns01Handler.
|
||||
*/
|
||||
public buildAcmeConvenientDnsProvider(): plugins.tsclass.network.IConvenientDnsProvider {
|
||||
const self = this;
|
||||
const adapter = {
|
||||
async acmeSetDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
|
||||
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
|
||||
if (!client) {
|
||||
throw new Error(
|
||||
`DnsManager: no DNS provider configured for ${dnsChallenge.hostName}. ` +
|
||||
'Add one in the Domains > Providers UI before issuing certificates.',
|
||||
);
|
||||
}
|
||||
// Clean any leftover challenge records first to avoid duplicates.
|
||||
try {
|
||||
const existing = await client.listRecords(dnsChallenge.hostName);
|
||||
for (const r of existing) {
|
||||
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
|
||||
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId).catch(() => {});
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `DnsManager: failed to clean existing TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
|
||||
}
|
||||
await client.createRecord(dnsChallenge.hostName, {
|
||||
name: dnsChallenge.hostName,
|
||||
type: 'TXT',
|
||||
value: dnsChallenge.challenge,
|
||||
ttl: 120,
|
||||
});
|
||||
},
|
||||
async acmeRemoveDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
|
||||
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
|
||||
if (!client) {
|
||||
// The domain may have been removed; nothing to clean up.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const existing = await client.listRecords(dnsChallenge.hostName);
|
||||
for (const r of existing) {
|
||||
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
|
||||
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId);
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `DnsManager: failed to remove TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
|
||||
}
|
||||
},
|
||||
async isDomainSupported(domain: string): Promise<boolean> {
|
||||
const client = await self.getProviderClientForDomain(domain);
|
||||
return !!client;
|
||||
},
|
||||
};
|
||||
return { convenience: adapter } as plugins.tsclass.network.IConvenientDnsProvider;
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Provider CRUD (used by DnsProviderHandler)
|
||||
// ==========================================================================
|
||||
|
||||
public async listProviders(): Promise<IDnsProviderPublic[]> {
|
||||
const docs = await DnsProviderDoc.findAll();
|
||||
return docs.map((d) => this.toPublicProvider(d));
|
||||
}
|
||||
|
||||
public async getProvider(id: string): Promise<IDnsProviderPublic | null> {
|
||||
const doc = await DnsProviderDoc.findById(id);
|
||||
return doc ? this.toPublicProvider(doc) : null;
|
||||
}
|
||||
|
||||
public async createProvider(args: {
|
||||
name: string;
|
||||
type: TDnsProviderType;
|
||||
credentials: TDnsProviderCredentials;
|
||||
createdBy: string;
|
||||
}): Promise<string> {
|
||||
if (args.type === 'dcrouter') {
|
||||
throw new Error(
|
||||
'createProvider: cannot create a DnsProviderDoc with type "dcrouter" — ' +
|
||||
'that type is reserved for the built-in pseudo-provider surfaced at read time.',
|
||||
);
|
||||
}
|
||||
const now = Date.now();
|
||||
const doc = new DnsProviderDoc();
|
||||
doc.id = plugins.uuid.v4();
|
||||
doc.name = args.name;
|
||||
doc.type = args.type;
|
||||
doc.credentials = args.credentials;
|
||||
doc.status = 'untested';
|
||||
doc.createdAt = now;
|
||||
doc.updatedAt = now;
|
||||
doc.createdBy = args.createdBy;
|
||||
await doc.save();
|
||||
return doc.id;
|
||||
}
|
||||
|
||||
public async updateProvider(
|
||||
id: string,
|
||||
args: { name?: string; credentials?: TDnsProviderCredentials },
|
||||
): Promise<boolean> {
|
||||
const doc = await DnsProviderDoc.findById(id);
|
||||
if (!doc) return false;
|
||||
if (args.name !== undefined) doc.name = args.name;
|
||||
if (args.credentials !== undefined) {
|
||||
doc.credentials = args.credentials;
|
||||
doc.status = 'untested';
|
||||
doc.lastError = undefined;
|
||||
// Invalidate cached client so the next use re-instantiates with the new credentials.
|
||||
this.providerClients.delete(id);
|
||||
}
|
||||
doc.updatedAt = Date.now();
|
||||
await doc.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
public async deleteProvider(id: string, force: boolean): Promise<{ success: boolean; message?: string }> {
|
||||
const doc = await DnsProviderDoc.findById(id);
|
||||
if (!doc) return { success: false, message: 'Provider not found' };
|
||||
const linkedDomains = await DomainDoc.findByProviderId(id);
|
||||
if (linkedDomains.length > 0 && !force) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Provider is referenced by ${linkedDomains.length} domain(s). Pass force: true to delete anyway.`,
|
||||
};
|
||||
}
|
||||
// If forcing, also delete the linked domains and their records.
|
||||
if (force) {
|
||||
for (const domain of linkedDomains) {
|
||||
await this.deleteDomain(domain.id);
|
||||
}
|
||||
}
|
||||
await doc.delete();
|
||||
this.providerClients.delete(id);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
public async testProvider(id: string): Promise<{ ok: boolean; error?: string; testedAt: number }> {
|
||||
const doc = await DnsProviderDoc.findById(id);
|
||||
if (!doc) {
|
||||
return { ok: false, error: 'Provider not found', testedAt: Date.now() };
|
||||
}
|
||||
const client = createDnsProvider(doc.type, doc.credentials);
|
||||
const result = await client.testConnection();
|
||||
doc.status = result.ok ? 'ok' : 'error';
|
||||
doc.lastTestedAt = Date.now();
|
||||
doc.lastError = result.ok ? undefined : result.error;
|
||||
await doc.save();
|
||||
if (result.ok) {
|
||||
this.providerClients.set(id, client); // cache the working client
|
||||
}
|
||||
return { ok: result.ok, error: result.error, testedAt: doc.lastTestedAt };
|
||||
}
|
||||
|
||||
public async listProviderDomains(providerId: string): Promise<IProviderDomainListing[]> {
|
||||
const client = await this.getProviderClientById(providerId);
|
||||
if (!client) {
|
||||
throw new Error('Provider not found');
|
||||
}
|
||||
return await client.listDomains();
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Domain CRUD (used by DomainHandler)
|
||||
// ==========================================================================
|
||||
|
||||
public async listDomains(): Promise<DomainDoc[]> {
|
||||
return await DomainDoc.findAll();
|
||||
}
|
||||
|
||||
public async getDomain(id: string): Promise<DomainDoc | null> {
|
||||
return await DomainDoc.findById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a dcrouter-hosted (authoritative) domain. dcrouter will serve
|
||||
* DNS records for this domain via the embedded smartdns.DnsServer.
|
||||
*/
|
||||
public async createDcrouterDomain(args: {
|
||||
name: string;
|
||||
description?: string;
|
||||
createdBy: string;
|
||||
}): Promise<string> {
|
||||
const now = Date.now();
|
||||
const doc = new DomainDoc();
|
||||
doc.id = plugins.uuid.v4();
|
||||
doc.name = args.name.toLowerCase();
|
||||
doc.source = 'dcrouter';
|
||||
doc.authoritative = true;
|
||||
doc.description = args.description;
|
||||
doc.createdAt = now;
|
||||
doc.updatedAt = now;
|
||||
doc.createdBy = args.createdBy;
|
||||
await doc.save();
|
||||
return doc.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Import one or more domains from a provider, pulling all of their DNS
|
||||
* records into local DnsRecordDocs.
|
||||
*/
|
||||
public async importDomainsFromProvider(args: {
|
||||
providerId: string;
|
||||
domainNames: string[];
|
||||
createdBy: string;
|
||||
}): Promise<string[]> {
|
||||
const provider = await DnsProviderDoc.findById(args.providerId);
|
||||
if (!provider) {
|
||||
throw new Error('Provider not found');
|
||||
}
|
||||
const client = await this.getProviderClientById(args.providerId);
|
||||
if (!client) {
|
||||
throw new Error('Failed to instantiate provider client');
|
||||
}
|
||||
const allProviderDomains = await client.listDomains();
|
||||
const importedIds: string[] = [];
|
||||
const now = Date.now();
|
||||
|
||||
for (const wantedName of args.domainNames) {
|
||||
const lower = wantedName.toLowerCase();
|
||||
const listing = allProviderDomains.find((d) => d.name.toLowerCase() === lower);
|
||||
if (!listing) {
|
||||
logger.log('warn', `DnsManager: import skipped — provider does not list domain ${wantedName}`);
|
||||
continue;
|
||||
}
|
||||
// Skip if already imported
|
||||
const existing = await DomainDoc.findByName(lower);
|
||||
if (existing) {
|
||||
logger.log('warn', `DnsManager: domain ${wantedName} already imported — skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const domain = new DomainDoc();
|
||||
domain.id = plugins.uuid.v4();
|
||||
domain.name = lower;
|
||||
domain.source = 'provider';
|
||||
domain.providerId = args.providerId;
|
||||
domain.authoritative = false;
|
||||
domain.nameservers = listing.nameservers;
|
||||
domain.externalZoneId = listing.externalId;
|
||||
domain.lastSyncedAt = now;
|
||||
domain.createdAt = now;
|
||||
domain.updatedAt = now;
|
||||
domain.createdBy = args.createdBy;
|
||||
await domain.save();
|
||||
importedIds.push(domain.id);
|
||||
|
||||
// Pull records for the imported domain
|
||||
try {
|
||||
const providerRecords = await client.listRecords(lower);
|
||||
for (const pr of providerRecords) {
|
||||
await this.createSyncedRecord(domain.id, pr, args.createdBy);
|
||||
}
|
||||
logger.log('info', `DnsManager: imported ${providerRecords.length} record(s) for ${lower}`);
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `DnsManager: failed to import records for ${lower}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
return importedIds;
|
||||
}
|
||||
|
||||
public async updateDomain(id: string, args: { description?: string }): Promise<boolean> {
|
||||
const doc = await DomainDoc.findById(id);
|
||||
if (!doc) return false;
|
||||
if (args.description !== undefined) doc.description = args.description;
|
||||
doc.updatedAt = Date.now();
|
||||
await doc.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a domain and all of its DNS records. For provider domains, only
|
||||
* removes the local mirror — does NOT touch the provider.
|
||||
* For dcrouter-hosted domains, also unregisters records from the embedded
|
||||
* DnsServer.
|
||||
*
|
||||
* Note: smartdns has no public unregister-by-name API in the version pinned
|
||||
* here, so local record deletes only take effect after a restart. The DB
|
||||
* is the source of truth and the next start will not register the deleted
|
||||
* record.
|
||||
*/
|
||||
public async deleteDomain(id: string): Promise<boolean> {
|
||||
const doc = await DomainDoc.findById(id);
|
||||
if (!doc) return false;
|
||||
const records = await DnsRecordDoc.findByDomainId(id);
|
||||
for (const r of records) {
|
||||
await r.delete();
|
||||
}
|
||||
await doc.delete();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Force-resync a provider-managed domain: re-pull all records from the
|
||||
* provider API, replacing the cached DnsRecordDocs.
|
||||
*/
|
||||
public async syncDomain(id: string): Promise<{ success: boolean; recordCount?: number; message?: string }> {
|
||||
const doc = await DomainDoc.findById(id);
|
||||
if (!doc) return { success: false, message: 'Domain not found' };
|
||||
if (doc.source !== 'provider' || !doc.providerId) {
|
||||
return { success: false, message: 'Domain is not provider-managed' };
|
||||
}
|
||||
const client = await this.getProviderClientById(doc.providerId);
|
||||
if (!client) {
|
||||
return { success: false, message: 'Provider client unavailable' };
|
||||
}
|
||||
const providerRecords = await client.listRecords(doc.name);
|
||||
|
||||
// Drop existing records and replace
|
||||
const existing = await DnsRecordDoc.findByDomainId(id);
|
||||
for (const r of existing) {
|
||||
await r.delete();
|
||||
}
|
||||
for (const pr of providerRecords) {
|
||||
await this.createSyncedRecord(id, pr, doc.createdBy);
|
||||
}
|
||||
doc.lastSyncedAt = Date.now();
|
||||
doc.updatedAt = doc.lastSyncedAt;
|
||||
await doc.save();
|
||||
return { success: true, recordCount: providerRecords.length };
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Record CRUD (used by DnsRecordHandler)
|
||||
// ==========================================================================
|
||||
|
||||
public async listRecordsForDomain(domainId: string): Promise<DnsRecordDoc[]> {
|
||||
return await DnsRecordDoc.findByDomainId(domainId);
|
||||
}
|
||||
|
||||
public async getRecord(id: string): Promise<DnsRecordDoc | null> {
|
||||
return await DnsRecordDoc.findById(id);
|
||||
}
|
||||
|
||||
public async createRecord(args: {
|
||||
domainId: string;
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
value: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
createdBy: string;
|
||||
}): Promise<{ success: boolean; id?: string; message?: string }> {
|
||||
const domain = await DomainDoc.findById(args.domainId);
|
||||
if (!domain) return { success: false, message: 'Domain not found' };
|
||||
|
||||
const now = Date.now();
|
||||
const doc = new DnsRecordDoc();
|
||||
doc.id = plugins.uuid.v4();
|
||||
doc.domainId = args.domainId;
|
||||
doc.name = args.name.toLowerCase();
|
||||
doc.type = args.type;
|
||||
doc.value = args.value;
|
||||
doc.ttl = args.ttl ?? 300;
|
||||
if (args.proxied !== undefined) doc.proxied = args.proxied;
|
||||
doc.source = 'local';
|
||||
doc.createdAt = now;
|
||||
doc.updatedAt = now;
|
||||
doc.createdBy = args.createdBy;
|
||||
|
||||
if (domain.source === 'provider') {
|
||||
// Push to provider first; only persist locally on success
|
||||
if (!domain.providerId) {
|
||||
return { success: false, message: 'Provider domain has no providerId' };
|
||||
}
|
||||
const client = await this.getProviderClientById(domain.providerId);
|
||||
if (!client) return { success: false, message: 'Provider client unavailable' };
|
||||
try {
|
||||
const created = await client.createRecord(domain.name, {
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
value: doc.value,
|
||||
ttl: doc.ttl,
|
||||
proxied: doc.proxied,
|
||||
});
|
||||
doc.providerRecordId = created.providerRecordId;
|
||||
doc.source = 'synced';
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: `Provider rejected record: ${(err as Error).message}` };
|
||||
}
|
||||
} else {
|
||||
// dcrouter-hosted / authoritative — register with embedded DnsServer immediately
|
||||
this.registerRecordWithDnsServer(doc);
|
||||
}
|
||||
|
||||
await doc.save();
|
||||
return { success: true, id: doc.id };
|
||||
}
|
||||
|
||||
public async updateRecord(args: {
|
||||
id: string;
|
||||
name?: string;
|
||||
value?: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
}): Promise<{ success: boolean; message?: string }> {
|
||||
const doc = await DnsRecordDoc.findById(args.id);
|
||||
if (!doc) return { success: false, message: 'Record not found' };
|
||||
const domain = await DomainDoc.findById(doc.domainId);
|
||||
if (!domain) return { success: false, message: 'Parent domain not found' };
|
||||
|
||||
if (args.name !== undefined) doc.name = args.name.toLowerCase();
|
||||
if (args.value !== undefined) doc.value = args.value;
|
||||
if (args.ttl !== undefined) doc.ttl = args.ttl;
|
||||
if (args.proxied !== undefined) doc.proxied = args.proxied;
|
||||
doc.updatedAt = Date.now();
|
||||
|
||||
if (domain.source === 'provider') {
|
||||
if (!domain.providerId || !doc.providerRecordId) {
|
||||
return { success: false, message: 'Provider record metadata missing' };
|
||||
}
|
||||
const client = await this.getProviderClientById(domain.providerId);
|
||||
if (!client) return { success: false, message: 'Provider client unavailable' };
|
||||
try {
|
||||
await client.updateRecord(domain.name, doc.providerRecordId, {
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
value: doc.value,
|
||||
ttl: doc.ttl,
|
||||
proxied: doc.proxied,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: `Provider rejected update: ${(err as Error).message}` };
|
||||
}
|
||||
} else {
|
||||
// Re-register the local record so the new closure picks up the updated fields
|
||||
this.registerRecordWithDnsServer(doc);
|
||||
}
|
||||
|
||||
await doc.save();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
public async deleteRecord(id: string): Promise<{ success: boolean; message?: string }> {
|
||||
const doc = await DnsRecordDoc.findById(id);
|
||||
if (!doc) return { success: false, message: 'Record not found' };
|
||||
const domain = await DomainDoc.findById(doc.domainId);
|
||||
if (!domain) return { success: false, message: 'Parent domain not found' };
|
||||
|
||||
if (domain.source === 'provider') {
|
||||
if (domain.providerId && doc.providerRecordId) {
|
||||
const client = await this.getProviderClientById(domain.providerId);
|
||||
if (client) {
|
||||
try {
|
||||
await client.deleteRecord(domain.name, doc.providerRecordId);
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: `Provider rejected delete: ${(err as Error).message}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// For local records: smartdns has no unregister API in the pinned version,
|
||||
// so the record stays served until the next restart. The DB delete still
|
||||
// takes effect — on restart, the record will not be re-registered.
|
||||
|
||||
await doc.delete();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Internal helpers
|
||||
// ==========================================================================
|
||||
|
||||
private async createSyncedRecord(
|
||||
domainId: string,
|
||||
pr: IProviderRecord,
|
||||
createdBy: string,
|
||||
): Promise<void> {
|
||||
const now = Date.now();
|
||||
const doc = new DnsRecordDoc();
|
||||
doc.id = plugins.uuid.v4();
|
||||
doc.domainId = domainId;
|
||||
doc.name = pr.name.toLowerCase();
|
||||
doc.type = pr.type;
|
||||
doc.value = pr.value;
|
||||
doc.ttl = pr.ttl;
|
||||
if (pr.proxied !== undefined) doc.proxied = pr.proxied;
|
||||
doc.source = 'synced';
|
||||
doc.providerRecordId = pr.providerRecordId;
|
||||
doc.createdAt = now;
|
||||
doc.updatedAt = now;
|
||||
doc.createdBy = createdBy;
|
||||
await doc.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DnsProviderDoc to its public, secret-stripped representation
|
||||
* for the OpsServer API.
|
||||
*/
|
||||
public toPublicProvider(doc: DnsProviderDoc): IDnsProviderPublic {
|
||||
return {
|
||||
id: doc.id,
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
status: doc.status,
|
||||
lastTestedAt: doc.lastTestedAt,
|
||||
lastError: doc.lastError,
|
||||
createdAt: doc.createdAt,
|
||||
updatedAt: doc.updatedAt,
|
||||
createdBy: doc.createdBy,
|
||||
hasCredentials: !!doc.credentials,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DomainDoc to its plain interface representation.
|
||||
*/
|
||||
public toPublicDomain(doc: DomainDoc): {
|
||||
id: string;
|
||||
name: string;
|
||||
source: 'dcrouter' | 'provider';
|
||||
providerId?: string;
|
||||
authoritative: boolean;
|
||||
nameservers?: string[];
|
||||
externalZoneId?: string;
|
||||
lastSyncedAt?: number;
|
||||
description?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
} {
|
||||
return {
|
||||
id: doc.id,
|
||||
name: doc.name,
|
||||
source: doc.source,
|
||||
providerId: doc.providerId,
|
||||
authoritative: doc.authoritative,
|
||||
nameservers: doc.nameservers,
|
||||
externalZoneId: doc.externalZoneId,
|
||||
lastSyncedAt: doc.lastSyncedAt,
|
||||
description: doc.description,
|
||||
createdAt: doc.createdAt,
|
||||
updatedAt: doc.updatedAt,
|
||||
createdBy: doc.createdBy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DnsRecordDoc to its plain interface representation.
|
||||
*/
|
||||
public toPublicRecord(doc: DnsRecordDoc): {
|
||||
id: string;
|
||||
domainId: string;
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
value: string;
|
||||
ttl: number;
|
||||
proxied?: boolean;
|
||||
source: TDnsRecordSource;
|
||||
providerRecordId?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
} {
|
||||
return {
|
||||
id: doc.id,
|
||||
domainId: doc.domainId,
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
value: doc.value,
|
||||
ttl: doc.ttl,
|
||||
proxied: doc.proxied,
|
||||
source: doc.source,
|
||||
providerRecordId: doc.providerRecordId,
|
||||
createdAt: doc.createdAt,
|
||||
updatedAt: doc.updatedAt,
|
||||
createdBy: doc.createdBy,
|
||||
};
|
||||
}
|
||||
}
|
||||
131
ts/dns/providers/cloudflare.provider.ts
Normal file
131
ts/dns/providers/cloudflare.provider.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import { logger } from '../../logger.js';
|
||||
import type {
|
||||
IDnsProviderClient,
|
||||
IConnectionTestResult,
|
||||
IProviderRecord,
|
||||
IProviderRecordInput,
|
||||
} from './interfaces.js';
|
||||
import type { IProviderDomainListing } from '../../../ts_interfaces/data/dns-provider.js';
|
||||
import type { TDnsRecordType } from '../../../ts_interfaces/data/dns-record.js';
|
||||
|
||||
/**
|
||||
* Cloudflare implementation of IDnsProviderClient.
|
||||
*
|
||||
* Wraps `@apiclient.xyz/cloudflare`. Records at Cloudflare are addressed by
|
||||
* an internal record id, which we surface as `providerRecordId` so the rest
|
||||
* of the system can issue updates and deletes without ambiguity (Cloudflare
|
||||
* can have multiple records of the same name+type).
|
||||
*/
|
||||
export class CloudflareDnsProvider implements IDnsProviderClient {
|
||||
private cfAccount: plugins.cloudflare.CloudflareAccount;
|
||||
|
||||
constructor(apiToken: string) {
|
||||
if (!apiToken) {
|
||||
throw new Error('CloudflareDnsProvider: apiToken is required');
|
||||
}
|
||||
this.cfAccount = new plugins.cloudflare.CloudflareAccount(apiToken);
|
||||
}
|
||||
|
||||
public async testConnection(): Promise<IConnectionTestResult> {
|
||||
try {
|
||||
// Listing zones is the lightest-weight call that proves the token works.
|
||||
await this.cfAccount.zoneManager.listZones();
|
||||
return { ok: true };
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.log('warn', `CloudflareDnsProvider testConnection failed: ${message}`);
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
public async listDomains(): Promise<IProviderDomainListing[]> {
|
||||
const zones = await this.cfAccount.zoneManager.listZones();
|
||||
return zones.map((zone) => ({
|
||||
name: zone.name,
|
||||
externalId: zone.id,
|
||||
nameservers: zone.name_servers ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
public async listRecords(domain: string): Promise<IProviderRecord[]> {
|
||||
const records = await this.cfAccount.recordManager.listRecords(domain);
|
||||
return records
|
||||
.filter((r) => this.isSupportedType(r.type))
|
||||
.map((r) => ({
|
||||
providerRecordId: r.id,
|
||||
name: r.name,
|
||||
type: r.type as TDnsRecordType,
|
||||
value: r.content,
|
||||
ttl: r.ttl,
|
||||
proxied: r.proxied,
|
||||
}));
|
||||
}
|
||||
|
||||
public async createRecord(
|
||||
domain: string,
|
||||
record: IProviderRecordInput,
|
||||
): Promise<IProviderRecord> {
|
||||
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain);
|
||||
const apiRecord: any = {
|
||||
zone_id: zoneId,
|
||||
type: record.type,
|
||||
name: record.name,
|
||||
content: record.value,
|
||||
ttl: record.ttl ?? 1, // 1 = automatic
|
||||
};
|
||||
if (record.proxied !== undefined) {
|
||||
apiRecord.proxied = record.proxied;
|
||||
}
|
||||
const created = await (this.cfAccount as any).apiAccount.dns.records.create(apiRecord);
|
||||
return {
|
||||
providerRecordId: created.id,
|
||||
name: created.name,
|
||||
type: created.type as TDnsRecordType,
|
||||
value: created.content,
|
||||
ttl: created.ttl,
|
||||
proxied: created.proxied,
|
||||
};
|
||||
}
|
||||
|
||||
public async updateRecord(
|
||||
domain: string,
|
||||
providerRecordId: string,
|
||||
record: IProviderRecordInput,
|
||||
): Promise<IProviderRecord> {
|
||||
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain);
|
||||
const apiRecord: any = {
|
||||
zone_id: zoneId,
|
||||
type: record.type,
|
||||
name: record.name,
|
||||
content: record.value,
|
||||
ttl: record.ttl ?? 1,
|
||||
};
|
||||
if (record.proxied !== undefined) {
|
||||
apiRecord.proxied = record.proxied;
|
||||
}
|
||||
const updated = await (this.cfAccount as any).apiAccount.dns.records.edit(
|
||||
providerRecordId,
|
||||
apiRecord,
|
||||
);
|
||||
return {
|
||||
providerRecordId: updated.id,
|
||||
name: updated.name,
|
||||
type: updated.type as TDnsRecordType,
|
||||
value: updated.content,
|
||||
ttl: updated.ttl,
|
||||
proxied: updated.proxied,
|
||||
};
|
||||
}
|
||||
|
||||
public async deleteRecord(domain: string, providerRecordId: string): Promise<void> {
|
||||
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain);
|
||||
await (this.cfAccount as any).apiAccount.dns.records.delete(providerRecordId, {
|
||||
zone_id: zoneId,
|
||||
});
|
||||
}
|
||||
|
||||
private isSupportedType(type: string): boolean {
|
||||
return ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SOA', 'CAA'].includes(type);
|
||||
}
|
||||
}
|
||||
59
ts/dns/providers/factory.ts
Normal file
59
ts/dns/providers/factory.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { IDnsProviderClient } from './interfaces.js';
|
||||
import type {
|
||||
TDnsProviderType,
|
||||
TDnsProviderCredentials,
|
||||
} from '../../../ts_interfaces/data/dns-provider.js';
|
||||
import { CloudflareDnsProvider } from './cloudflare.provider.js';
|
||||
|
||||
/**
|
||||
* Instantiate a runtime DNS provider client from a stored DnsProviderDoc.
|
||||
*
|
||||
* @throws if the provider type is not supported.
|
||||
*
|
||||
* ## Adding a new provider (e.g. Route53)
|
||||
*
|
||||
* 1. **Type union** — extend `TDnsProviderType` in
|
||||
* `ts_interfaces/data/dns-provider.ts` (e.g. `'cloudflare' | 'route53'`).
|
||||
* 2. **Credentials interface** — add `IRoute53Credentials` and append it to
|
||||
* the `TDnsProviderCredentials` discriminated union.
|
||||
* 3. **Descriptor** — append a new entry to `dnsProviderTypeDescriptors` so
|
||||
* the OpsServer UI picks up the new type and renders the right credential
|
||||
* form fields automatically.
|
||||
* 4. **Provider class** — create `ts/dns/providers/route53.provider.ts`
|
||||
* implementing `IDnsProviderClient`.
|
||||
* 5. **Factory case** — add a new `case 'route53':` below. The
|
||||
* `_exhaustive: never` line will fail to compile until you do.
|
||||
* 6. **Index** — re-export the new class from `ts/dns/providers/index.ts`.
|
||||
*/
|
||||
export function createDnsProvider(
|
||||
type: TDnsProviderType,
|
||||
credentials: TDnsProviderCredentials,
|
||||
): IDnsProviderClient {
|
||||
switch (type) {
|
||||
case 'cloudflare': {
|
||||
if (credentials.type !== 'cloudflare') {
|
||||
throw new Error(
|
||||
`createDnsProvider: type mismatch — provider type is 'cloudflare' but credentials.type is '${credentials.type}'`,
|
||||
);
|
||||
}
|
||||
return new CloudflareDnsProvider(credentials.apiToken);
|
||||
}
|
||||
case 'dcrouter': {
|
||||
// The built-in DcRouter pseudo-provider has no runtime client — dcrouter
|
||||
// itself serves the records via the embedded smartdns.DnsServer. This
|
||||
// case exists only to satisfy the exhaustive switch; it should never
|
||||
// actually run because the handler layer rejects any CRUD that would
|
||||
// result in a DnsProviderDoc with type: 'dcrouter'.
|
||||
throw new Error(
|
||||
`createDnsProvider: 'dcrouter' is a built-in pseudo-provider — no runtime client exists. ` +
|
||||
`This call indicates a DnsProviderDoc with type: 'dcrouter' was persisted, which should never happen.`,
|
||||
);
|
||||
}
|
||||
default: {
|
||||
// If you see a TypeScript error here after extending TDnsProviderType,
|
||||
// add a `case` for the new type above. The `never` enforces exhaustiveness.
|
||||
const _exhaustive: never = type;
|
||||
throw new Error(`createDnsProvider: unsupported provider type: ${_exhaustive}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
3
ts/dns/providers/index.ts
Normal file
3
ts/dns/providers/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './interfaces.js';
|
||||
export * from './cloudflare.provider.js';
|
||||
export * from './factory.js';
|
||||
67
ts/dns/providers/interfaces.ts
Normal file
67
ts/dns/providers/interfaces.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import type { TDnsRecordType } from '../../../ts_interfaces/data/dns-record.js';
|
||||
import type { IProviderDomainListing } from '../../../ts_interfaces/data/dns-provider.js';
|
||||
|
||||
/**
|
||||
* A DNS record as seen at a provider's API. The `providerRecordId` field
|
||||
* is the provider's internal identifier, used for subsequent updates and
|
||||
* deletes (since providers can have multiple records of the same name+type).
|
||||
*/
|
||||
export interface IProviderRecord {
|
||||
providerRecordId: string;
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
value: string;
|
||||
ttl: number;
|
||||
proxied?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Input shape for creating / updating a DNS record at a provider.
|
||||
*/
|
||||
export interface IProviderRecordInput {
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
value: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outcome of a connection test against a provider's API.
|
||||
*/
|
||||
export interface IConnectionTestResult {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pluggable DNS provider client interface. One implementation per provider type
|
||||
* (Cloudflare, Route53, …). Implementations live in ts/dns/providers/ and are
|
||||
* instantiated by `createDnsProvider()` in factory.ts.
|
||||
*
|
||||
* NOT a smartdata interface — this is the *runtime* client. The persisted
|
||||
* representation is in `IDnsProvider` (ts_interfaces/data/dns-provider.ts).
|
||||
*/
|
||||
export interface IDnsProviderClient {
|
||||
/** Lightweight check that credentials are valid and the API is reachable. */
|
||||
testConnection(): Promise<IConnectionTestResult>;
|
||||
|
||||
/** List all DNS zones visible to this provider account. */
|
||||
listDomains(): Promise<IProviderDomainListing[]>;
|
||||
|
||||
/** List all DNS records for a zone (FQDN). */
|
||||
listRecords(domain: string): Promise<IProviderRecord[]>;
|
||||
|
||||
/** Create a new DNS record at the provider; returns the created record (with id). */
|
||||
createRecord(domain: string, record: IProviderRecordInput): Promise<IProviderRecord>;
|
||||
|
||||
/** Update an existing record by provider id; returns the updated record. */
|
||||
updateRecord(
|
||||
domain: string,
|
||||
providerRecordId: string,
|
||||
record: IProviderRecordInput,
|
||||
): Promise<IProviderRecord>;
|
||||
|
||||
/** Delete a record by provider id. */
|
||||
deleteRecord(domain: string, providerRecordId: string): Promise<void>;
|
||||
}
|
||||
@@ -32,6 +32,11 @@ export class OpsServer {
|
||||
private sourceProfileHandler!: handlers.SourceProfileHandler;
|
||||
private targetProfileHandler!: handlers.TargetProfileHandler;
|
||||
private networkTargetHandler!: handlers.NetworkTargetHandler;
|
||||
private usersHandler!: handlers.UsersHandler;
|
||||
private dnsProviderHandler!: handlers.DnsProviderHandler;
|
||||
private domainHandler!: handlers.DomainHandler;
|
||||
private dnsRecordHandler!: handlers.DnsRecordHandler;
|
||||
private acmeConfigHandler!: handlers.AcmeConfigHandler;
|
||||
|
||||
constructor(dcRouterRefArg: DcRouter) {
|
||||
this.dcRouterRef = dcRouterRefArg;
|
||||
@@ -94,6 +99,11 @@ export class OpsServer {
|
||||
this.sourceProfileHandler = new handlers.SourceProfileHandler(this);
|
||||
this.targetProfileHandler = new handlers.TargetProfileHandler(this);
|
||||
this.networkTargetHandler = new handlers.NetworkTargetHandler(this);
|
||||
this.usersHandler = new handlers.UsersHandler(this);
|
||||
this.dnsProviderHandler = new handlers.DnsProviderHandler(this);
|
||||
this.domainHandler = new handlers.DomainHandler(this);
|
||||
this.dnsRecordHandler = new handlers.DnsRecordHandler(this);
|
||||
this.acmeConfigHandler = new handlers.AcmeConfigHandler(this);
|
||||
|
||||
console.log('✅ OpsServer TypedRequest handlers initialized');
|
||||
}
|
||||
|
||||
94
ts/opsserver/handlers/acme-config.handler.ts
Normal file
94
ts/opsserver/handlers/acme-config.handler.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
/**
|
||||
* CRUD handler for the singleton `AcmeConfigDoc`.
|
||||
*
|
||||
* Auth: same dual-mode pattern as other handlers — admin JWT or API token
|
||||
* with `acme-config:read` / `acme-config:write` scope.
|
||||
*/
|
||||
export class AcmeConfigHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private async requireAuth(
|
||||
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
|
||||
requiredScope?: interfaces.data.TApiTokenScope,
|
||||
): Promise<string> {
|
||||
if (request.identity?.jwt) {
|
||||
try {
|
||||
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
|
||||
identity: request.identity,
|
||||
});
|
||||
if (isAdmin) return request.identity.userId;
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
|
||||
if (request.apiToken) {
|
||||
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
|
||||
if (tokenManager) {
|
||||
const token = await tokenManager.validateToken(request.apiToken);
|
||||
if (token) {
|
||||
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
|
||||
return token.createdBy;
|
||||
}
|
||||
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new plugins.typedrequest.TypedResponseError('unauthorized');
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Get current ACME config
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAcmeConfig>(
|
||||
'getAcmeConfig',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'acme-config:read');
|
||||
const mgr = this.opsServerRef.dcRouterRef.acmeConfigManager;
|
||||
if (!mgr) return { config: null };
|
||||
return { config: mgr.getConfig() };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update (upsert) the ACME config
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateAcmeConfig>(
|
||||
'updateAcmeConfig',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'acme-config:write');
|
||||
const mgr = this.opsServerRef.dcRouterRef.acmeConfigManager;
|
||||
if (!mgr) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'AcmeConfigManager not initialized (DB disabled?)',
|
||||
};
|
||||
}
|
||||
try {
|
||||
const updated = await mgr.updateConfig(
|
||||
{
|
||||
accountEmail: dataArg.accountEmail,
|
||||
enabled: dataArg.enabled,
|
||||
useProduction: dataArg.useProduction,
|
||||
autoRenew: dataArg.autoRenew,
|
||||
renewThresholdDays: dataArg.renewThresholdDays,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
return { success: true, config: updated };
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: (err as Error).message };
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,18 @@ export class AdminHandler {
|
||||
role: 'admin',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a safe projection of the users Map — excludes password fields.
|
||||
* Used by UsersHandler to serve the admin-only listUsers endpoint.
|
||||
*/
|
||||
public listUsers(): Array<{ id: string; username: string; role: string }> {
|
||||
return Array.from(this.users.values()).map((user) => ({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
}));
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Admin Login Handler
|
||||
|
||||
@@ -123,6 +123,15 @@ export class ConfigHandler {
|
||||
ttl: r.ttl,
|
||||
}));
|
||||
|
||||
// dnsChallenge: true when at least one DnsProviderDoc exists in the DB
|
||||
// (replaces the legacy `dnsChallenge.cloudflareApiKey` constructor field).
|
||||
let dnsChallengeEnabled = false;
|
||||
try {
|
||||
dnsChallengeEnabled = (await dcRouter.dnsManager?.hasAcmeCapableProvider()) ?? false;
|
||||
} catch {
|
||||
dnsChallengeEnabled = false;
|
||||
}
|
||||
|
||||
const dns: interfaces.requests.IConfigData['dns'] = {
|
||||
enabled: !!dcRouter.dnsServer,
|
||||
port: 53,
|
||||
@@ -130,7 +139,7 @@ export class ConfigHandler {
|
||||
scopes: opts.dnsScopes || [],
|
||||
recordCount: dnsRecords.length,
|
||||
records: dnsRecords,
|
||||
dnsChallenge: !!opts.dnsChallenge?.cloudflareApiKey,
|
||||
dnsChallenge: dnsChallengeEnabled,
|
||||
};
|
||||
|
||||
// --- TLS ---
|
||||
|
||||
197
ts/opsserver/handlers/dns-provider.handler.ts
Normal file
197
ts/opsserver/handlers/dns-provider.handler.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
/**
|
||||
* CRUD + connection-test handlers for DnsProviderDoc.
|
||||
*
|
||||
* Auth: same dual-mode pattern as TargetProfileHandler — admin JWT or
|
||||
* API token with the appropriate `dns-providers:read|write` scope.
|
||||
*/
|
||||
export class DnsProviderHandler {
|
||||
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 providers — prepends the built-in DcRouter pseudo-provider
|
||||
// so operators see a uniform "who serves this?" list that includes the
|
||||
// authoritative dcrouter alongside external accounts.
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsProviders>(
|
||||
'getDnsProviders',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
const synthetic: interfaces.data.IDnsProviderPublic = {
|
||||
id: interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID,
|
||||
name: 'DcRouter',
|
||||
type: 'dcrouter',
|
||||
status: 'ok',
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
createdBy: 'system',
|
||||
hasCredentials: false,
|
||||
builtIn: true,
|
||||
};
|
||||
const real = dnsManager ? await dnsManager.listProviders() : [];
|
||||
return { providers: [synthetic, ...real] };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Get single provider
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsProvider>(
|
||||
'getDnsProvider',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { provider: null };
|
||||
return { provider: await dnsManager.getProvider(dataArg.id) };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Create provider
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateDnsProvider>(
|
||||
'createDnsProvider',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'dns-providers:write');
|
||||
if (dataArg.type === 'dcrouter') {
|
||||
return {
|
||||
success: false,
|
||||
message: 'cannot create built-in provider',
|
||||
};
|
||||
}
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) {
|
||||
return { success: false, message: 'DnsManager not initialized (DB disabled?)' };
|
||||
}
|
||||
const id = await dnsManager.createProvider({
|
||||
name: dataArg.name,
|
||||
type: dataArg.type,
|
||||
credentials: dataArg.credentials,
|
||||
createdBy: userId,
|
||||
});
|
||||
return { success: true, id };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update provider
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateDnsProvider>(
|
||||
'updateDnsProvider',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:write');
|
||||
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
|
||||
return { success: false, message: 'cannot edit built-in provider' };
|
||||
}
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
const ok = await dnsManager.updateProvider(dataArg.id, {
|
||||
name: dataArg.name,
|
||||
credentials: dataArg.credentials,
|
||||
});
|
||||
return ok ? { success: true } : { success: false, message: 'Provider not found' };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Delete provider
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteDnsProvider>(
|
||||
'deleteDnsProvider',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:write');
|
||||
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
|
||||
return { success: false, message: 'cannot delete built-in provider' };
|
||||
}
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.deleteProvider(dataArg.id, dataArg.force ?? false);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Test provider connection
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_TestDnsProvider>(
|
||||
'testDnsProvider',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:read');
|
||||
if (dataArg.id === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'built-in provider has no external connection to test',
|
||||
testedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) {
|
||||
return { ok: false, error: 'DnsManager not initialized', testedAt: Date.now() };
|
||||
}
|
||||
return await dnsManager.testProvider(dataArg.id);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// List domains visible to a provider's account (without importing them)
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListProviderDomains>(
|
||||
'listProviderDomains',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-providers:read');
|
||||
if (dataArg.providerId === interfaces.data.DCROUTER_BUILTIN_PROVIDER_ID) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'built-in provider has no external domain listing — use "Add DcRouter Domain" instead',
|
||||
};
|
||||
}
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
try {
|
||||
const domains = await dnsManager.listProviderDomains(dataArg.providerId);
|
||||
return { success: true, domains };
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: (err as Error).message };
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
127
ts/opsserver/handlers/dns-record.handler.ts
Normal file
127
ts/opsserver/handlers/dns-record.handler.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
/**
|
||||
* CRUD handlers for DnsRecordDoc.
|
||||
*/
|
||||
export class DnsRecordHandler {
|
||||
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 records by domain
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsRecords>(
|
||||
'getDnsRecords',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-records:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { records: [] };
|
||||
const docs = await dnsManager.listRecordsForDomain(dataArg.domainId);
|
||||
return { records: docs.map((d) => dnsManager.toPublicRecord(d)) };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Get single record
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsRecord>(
|
||||
'getDnsRecord',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-records:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { record: null };
|
||||
const doc = await dnsManager.getRecord(dataArg.id);
|
||||
return { record: doc ? dnsManager.toPublicRecord(doc) : null };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Create record
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateDnsRecord>(
|
||||
'createDnsRecord',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'dns-records:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.createRecord({
|
||||
domainId: dataArg.domainId,
|
||||
name: dataArg.name,
|
||||
type: dataArg.type,
|
||||
value: dataArg.value,
|
||||
ttl: dataArg.ttl,
|
||||
proxied: dataArg.proxied,
|
||||
createdBy: userId,
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update record
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateDnsRecord>(
|
||||
'updateDnsRecord',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-records:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.updateRecord({
|
||||
id: dataArg.id,
|
||||
name: dataArg.name,
|
||||
value: dataArg.value,
|
||||
ttl: dataArg.ttl,
|
||||
proxied: dataArg.proxied,
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Delete record
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteDnsRecord>(
|
||||
'deleteDnsRecord',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'dns-records:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.deleteRecord(dataArg.id);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
161
ts/opsserver/handlers/domain.handler.ts
Normal file
161
ts/opsserver/handlers/domain.handler.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
/**
|
||||
* CRUD handlers for DomainDoc.
|
||||
*/
|
||||
export class DomainHandler {
|
||||
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 domains
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDomains>(
|
||||
'getDomains',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { domains: [] };
|
||||
const docs = await dnsManager.listDomains();
|
||||
return { domains: docs.map((d) => dnsManager.toPublicDomain(d)) };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Get single domain
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDomain>(
|
||||
'getDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { domain: null };
|
||||
const doc = await dnsManager.getDomain(dataArg.id);
|
||||
return { domain: doc ? dnsManager.toPublicDomain(doc) : null };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Create dcrouter-hosted domain
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateDomain>(
|
||||
'createDomain',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
try {
|
||||
const id = await dnsManager.createDcrouterDomain({
|
||||
name: dataArg.name,
|
||||
description: dataArg.description,
|
||||
createdBy: userId,
|
||||
});
|
||||
return { success: true, id };
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: (err as Error).message };
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Import domains from a provider
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ImportDomain>(
|
||||
'importDomain',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
try {
|
||||
const importedIds = await dnsManager.importDomainsFromProvider({
|
||||
providerId: dataArg.providerId,
|
||||
domainNames: dataArg.domainNames,
|
||||
createdBy: userId,
|
||||
});
|
||||
return { success: true, importedIds };
|
||||
} catch (err: unknown) {
|
||||
return { success: false, message: (err as Error).message };
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update domain metadata
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateDomain>(
|
||||
'updateDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
const ok = await dnsManager.updateDomain(dataArg.id, {
|
||||
description: dataArg.description,
|
||||
});
|
||||
return ok ? { success: true } : { success: false, message: 'Domain not found' };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Delete domain
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteDomain>(
|
||||
'deleteDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
const ok = await dnsManager.deleteDomain(dataArg.id);
|
||||
return ok ? { success: true } : { success: false, message: 'Domain not found' };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Force-resync provider domain
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SyncDomain>(
|
||||
'syncDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.syncDomain(dataArg.id);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,4 +12,9 @@ export * from './api-token.handler.js';
|
||||
export * from './vpn.handler.js';
|
||||
export * from './source-profile.handler.js';
|
||||
export * from './target-profile.handler.js';
|
||||
export * from './network-target.handler.js';
|
||||
export * from './network-target.handler.js';
|
||||
export * from './users.handler.js';
|
||||
export * from './dns-provider.handler.js';
|
||||
export * from './domain.handler.js';
|
||||
export * from './dns-record.handler.js';
|
||||
export * from './acme-config.handler.js';
|
||||
30
ts/opsserver/handlers/users.handler.ts
Normal file
30
ts/opsserver/handlers/users.handler.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
/**
|
||||
* Read-only handler for OpsServer user accounts. Registers on adminRouter,
|
||||
* so admin middleware enforces auth + role check before the handler runs.
|
||||
* User data is owned by AdminHandler; this handler just exposes a safe
|
||||
* projection of it via TypedRequest.
|
||||
*/
|
||||
export class UsersHandler {
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
const router = this.opsServerRef.adminRouter;
|
||||
|
||||
// List users (admin-only, read-only)
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListUsers>(
|
||||
'listUsers',
|
||||
async (_dataArg) => {
|
||||
const users = this.opsServerRef.adminHandler.listUsers();
|
||||
return { users };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
25
ts_interfaces/data/acme-config.ts
Normal file
25
ts_interfaces/data/acme-config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* ACME configuration for automated TLS certificate issuance via Let's Encrypt.
|
||||
*
|
||||
* Persisted as a singleton `AcmeConfigDoc` in the DcRouterDb. Replaces the
|
||||
* legacy constructor fields `tls.contactEmail` / `smartProxyConfig.acme.*`
|
||||
* which are now seed-only (used once on first boot if the DB is empty).
|
||||
*
|
||||
* Managed via the OpsServer UI at **Domains > Certificates > Settings**.
|
||||
*/
|
||||
export interface IAcmeConfig {
|
||||
/** Contact email used for Let's Encrypt account registration. */
|
||||
accountEmail: string;
|
||||
/** Whether ACME is enabled. If false, no certs are issued via ACME. */
|
||||
enabled: boolean;
|
||||
/** True = Let's Encrypt production, false = staging. */
|
||||
useProduction: boolean;
|
||||
/** Whether to automatically renew certs before expiry. */
|
||||
autoRenew: boolean;
|
||||
/** Renew when a cert has fewer than this many days of validity left. */
|
||||
renewThresholdDays: number;
|
||||
/** Unix ms timestamp of last config change. */
|
||||
updatedAt: number;
|
||||
/** Who last updated the config (userId or 'seed' / 'system'). */
|
||||
updatedBy: string;
|
||||
}
|
||||
174
ts_interfaces/data/dns-provider.ts
Normal file
174
ts_interfaces/data/dns-provider.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Stable ID for the built-in DcRouter pseudo-provider. The Providers list
|
||||
* surfaces this as the first, non-deletable row so operators see a uniform
|
||||
* "who serves this?" answer for every domain. The ID is magic — it never
|
||||
* exists in the DnsProviderDoc collection; handlers inject it at read time
|
||||
* and reject any mutation that targets it.
|
||||
*/
|
||||
export const DCROUTER_BUILTIN_PROVIDER_ID = '__dcrouter__';
|
||||
|
||||
/**
|
||||
* Supported DNS provider types.
|
||||
*
|
||||
* - 'cloudflare' → Cloudflare account (API token-based). Provider stays
|
||||
* authoritative; dcrouter pushes record changes via API.
|
||||
* - 'dcrouter' → Built-in pseudo-provider for dcrouter-hosted zones.
|
||||
* dcrouter itself is the authoritative DNS server. No
|
||||
* credentials, cannot be created/edited/deleted through
|
||||
* the provider CRUD — the Providers view renders it from
|
||||
* a handler-level synthetic row.
|
||||
*
|
||||
* The abstraction is designed so additional providers (Route53, Gandi,
|
||||
* DigitalOcean, foreign dcrouters…) can be added by implementing the
|
||||
* IDnsProvider class interface in ts/dns/providers/.
|
||||
*/
|
||||
export type TDnsProviderType = 'cloudflare' | 'dcrouter';
|
||||
|
||||
/**
|
||||
* Status of the last connection test against a provider.
|
||||
*/
|
||||
export type TDnsProviderStatus = 'untested' | 'ok' | 'error';
|
||||
|
||||
/**
|
||||
* Cloudflare-specific credential shape.
|
||||
*/
|
||||
export interface ICloudflareCredentials {
|
||||
apiToken: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated union of all supported provider credential shapes.
|
||||
* Persisted opaquely on `IDnsProvider.credentials`.
|
||||
*/
|
||||
export type TDnsProviderCredentials =
|
||||
| ({ type: 'cloudflare' } & ICloudflareCredentials);
|
||||
|
||||
/**
|
||||
* A registered DNS provider account. Holds the credentials needed to
|
||||
* call the provider's API and a snapshot of its last health check.
|
||||
*/
|
||||
export interface IDnsProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
type: TDnsProviderType;
|
||||
/** Opaque credentials object — shape depends on `type`. */
|
||||
credentials: TDnsProviderCredentials;
|
||||
status: TDnsProviderStatus;
|
||||
lastTestedAt?: number;
|
||||
lastError?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A redacted view of IDnsProvider safe to send to the UI / over the wire.
|
||||
* Strips secret fields from `credentials` while preserving the rest.
|
||||
*/
|
||||
export interface IDnsProviderPublic {
|
||||
id: string;
|
||||
name: string;
|
||||
type: TDnsProviderType;
|
||||
status: TDnsProviderStatus;
|
||||
lastTestedAt?: number;
|
||||
lastError?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
/** Whether credentials are configured (true after creation). Never the secret itself. */
|
||||
hasCredentials: boolean;
|
||||
/**
|
||||
* True for the built-in DcRouter pseudo-provider — read-only, cannot be
|
||||
* created / edited / deleted. Injected by the handler layer, never
|
||||
* persisted in the DnsProviderDoc collection.
|
||||
*/
|
||||
builtIn?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A domain reported by a provider's API (not yet imported into dcrouter).
|
||||
*/
|
||||
export interface IProviderDomainListing {
|
||||
/** FQDN of the zone (e.g. 'example.com'). */
|
||||
name: string;
|
||||
/** Provider's internal zone identifier (zone_id for Cloudflare). */
|
||||
externalId: string;
|
||||
/** Authoritative nameservers reported by the provider. */
|
||||
nameservers: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Schema entry for a single credential field, used by the OpsServer UI to
|
||||
* render a provider's credential form dynamically.
|
||||
*/
|
||||
export interface IDnsProviderCredentialField {
|
||||
/** Key under which the value is stored in the credentials object. */
|
||||
key: string;
|
||||
/** Label shown to the user. */
|
||||
label: string;
|
||||
/** Optional inline help text. */
|
||||
helpText?: string;
|
||||
/** Whether the field must be filled. */
|
||||
required: boolean;
|
||||
/** True for secret fields (rendered as password input, never echoed back). */
|
||||
secret: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata describing a DNS provider type. Drives:
|
||||
* - the OpsServer UI's provider type picker + credential form,
|
||||
* - documentation of which credentials each provider needs,
|
||||
* - end-to-end consistency between the type union, the discriminated
|
||||
* credentials union, the runtime factory, and the form rendering.
|
||||
*
|
||||
* To add a new provider, append a new entry to `dnsProviderTypeDescriptors`
|
||||
* below — and follow the checklist in `ts/dns/providers/factory.ts`.
|
||||
*/
|
||||
export interface IDnsProviderTypeDescriptor {
|
||||
type: TDnsProviderType;
|
||||
/** Human-readable name for the UI. */
|
||||
displayName: string;
|
||||
/** One-line description shown next to the type picker. */
|
||||
description: string;
|
||||
/** Schema for the credentials form. */
|
||||
credentialFields: IDnsProviderCredentialField[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for which DNS provider types exist and what
|
||||
* credentials each one needs. Used by both backend and frontend.
|
||||
*/
|
||||
export const dnsProviderTypeDescriptors: ReadonlyArray<IDnsProviderTypeDescriptor> = [
|
||||
{
|
||||
type: 'dcrouter',
|
||||
displayName: 'DcRouter (built-in)',
|
||||
description:
|
||||
'Built-in authoritative DNS. Records are served directly by dcrouter — delegate the domain\'s NS records to make this effective.',
|
||||
credentialFields: [],
|
||||
},
|
||||
{
|
||||
type: 'cloudflare',
|
||||
displayName: 'Cloudflare',
|
||||
description:
|
||||
'Manages records via the Cloudflare API. Provider stays authoritative; dcrouter pushes record changes.',
|
||||
credentialFields: [
|
||||
{
|
||||
key: 'apiToken',
|
||||
label: 'API Token',
|
||||
helpText:
|
||||
'A Cloudflare API token with Zone:Read and DNS:Edit permissions for the target zones.',
|
||||
required: true,
|
||||
secret: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Look up the descriptor for a given provider type.
|
||||
*/
|
||||
export function getDnsProviderTypeDescriptor(
|
||||
type: TDnsProviderType,
|
||||
): IDnsProviderTypeDescriptor | undefined {
|
||||
return dnsProviderTypeDescriptors.find((d) => d.type === type);
|
||||
}
|
||||
44
ts_interfaces/data/dns-record.ts
Normal file
44
ts_interfaces/data/dns-record.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Supported DNS record types.
|
||||
*/
|
||||
export type TDnsRecordType = 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' | 'NS' | 'SOA' | 'CAA';
|
||||
|
||||
/**
|
||||
* Where a DNS record came from.
|
||||
*
|
||||
* - 'local' → originated in this dcrouter (created via UI / API)
|
||||
* - 'synced' → pulled from an upstream provider (Cloudflare, foreign
|
||||
* dcrouter, …) during a sync operation
|
||||
*/
|
||||
export type TDnsRecordSource = 'local' | 'synced';
|
||||
|
||||
/**
|
||||
* A DNS record. For dcrouter-hosted (authoritative) domains, the record is
|
||||
* registered with the embedded smartdns.DnsServer. For provider-managed
|
||||
* domains, the record is mirrored from / pushed to the provider API and
|
||||
* `providerRecordId` holds the provider's internal record id (for updates
|
||||
* and deletes).
|
||||
*/
|
||||
export interface IDnsRecord {
|
||||
id: string;
|
||||
/** ID of the parent IDomain. */
|
||||
domainId: string;
|
||||
/** Fully qualified record name (e.g. 'www.example.com'). */
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
/**
|
||||
* Record value as a string. For MX records, formatted as
|
||||
* `<priority> <exchange>` (e.g. `10 mail.example.com`).
|
||||
*/
|
||||
value: string;
|
||||
/** TTL in seconds. */
|
||||
ttl: number;
|
||||
/** Cloudflare-specific: whether the record is proxied through Cloudflare. */
|
||||
proxied?: boolean;
|
||||
source: TDnsRecordSource;
|
||||
/** Provider's internal record id (for updates/deletes). Only set for provider records. */
|
||||
providerRecordId?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
}
|
||||
36
ts_interfaces/data/domain.ts
Normal file
36
ts_interfaces/data/domain.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Where a domain came from / how it is managed.
|
||||
*
|
||||
* - 'dcrouter' → dcrouter is the authoritative DNS server for this domain;
|
||||
* records are served by the embedded smartdns.DnsServer.
|
||||
* Operators delegate the domain's NS records to make this
|
||||
* effective.
|
||||
* - 'provider' → domain was imported from an external DNS provider
|
||||
* (e.g. Cloudflare). The provider stays authoritative;
|
||||
* dcrouter only reads/writes records via the provider API.
|
||||
*/
|
||||
export type TDomainSource = 'dcrouter' | 'provider';
|
||||
|
||||
/**
|
||||
* A domain under management by dcrouter.
|
||||
*/
|
||||
export interface IDomain {
|
||||
id: string;
|
||||
/** Fully qualified domain name (e.g. 'example.com'). */
|
||||
name: string;
|
||||
source: TDomainSource;
|
||||
/** ID of the DnsProvider that owns this domain — only set when source === 'provider'. */
|
||||
providerId?: string;
|
||||
/** True when dcrouter is the authoritative DNS server for this domain (source === 'dcrouter'). */
|
||||
authoritative: boolean;
|
||||
/** Authoritative nameservers (display only — populated from provider for imported domains). */
|
||||
nameservers?: string[];
|
||||
/** Provider's internal zone identifier — only set when source === 'provider'. */
|
||||
externalZoneId?: string;
|
||||
/** Last time records were synced from the provider — only set when source === 'provider'. */
|
||||
lastSyncedAt?: number;
|
||||
description?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
}
|
||||
@@ -3,4 +3,8 @@ export * from './stats.js';
|
||||
export * from './remoteingress.js';
|
||||
export * from './route-management.js';
|
||||
export * from './target-profile.js';
|
||||
export * from './vpn.js';
|
||||
export * from './vpn.js';
|
||||
export * from './dns-provider.js';
|
||||
export * from './domain.js';
|
||||
export * from './dns-record.js';
|
||||
export * from './acme-config.js';
|
||||
@@ -14,7 +14,11 @@ export type TApiTokenScope =
|
||||
| 'tokens:read' | 'tokens:manage'
|
||||
| 'source-profiles:read' | 'source-profiles:write'
|
||||
| 'target-profiles:read' | 'target-profiles:write'
|
||||
| 'targets:read' | 'targets:write';
|
||||
| 'targets:read' | 'targets:write'
|
||||
| 'dns-providers:read' | 'dns-providers:write'
|
||||
| 'domains:read' | 'domains:write'
|
||||
| 'dns-records:read' | 'dns-records:write'
|
||||
| 'acme-config:read' | 'acme-config:write';
|
||||
|
||||
// ============================================================================
|
||||
// Source Profile Types (source-side: who can access)
|
||||
|
||||
54
ts_interfaces/requests/acme-config.ts
Normal file
54
ts_interfaces/requests/acme-config.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import type * as authInterfaces from '../data/auth.js';
|
||||
import type { IAcmeConfig } from '../data/acme-config.js';
|
||||
|
||||
// ============================================================================
|
||||
// ACME Config Endpoints
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get the current ACME configuration. Returns null if no config has been
|
||||
* set yet (neither from DB nor seeded from the constructor).
|
||||
*/
|
||||
export interface IReq_GetAcmeConfig extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAcmeConfig
|
||||
> {
|
||||
method: 'getAcmeConfig';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
};
|
||||
response: {
|
||||
config: IAcmeConfig | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the ACME configuration (upsert). All fields are required on first
|
||||
* create, optional on subsequent updates (partial update).
|
||||
*
|
||||
* NOTE: Most fields take effect on the next dcrouter restart — SmartAcme is
|
||||
* instantiated once at startup. `renewThresholdDays` applies immediately to
|
||||
* the next renewal check.
|
||||
*/
|
||||
export interface IReq_UpdateAcmeConfig extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_UpdateAcmeConfig
|
||||
> {
|
||||
method: 'updateAcmeConfig';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
accountEmail?: string;
|
||||
enabled?: boolean;
|
||||
useProduction?: boolean;
|
||||
autoRenew?: boolean;
|
||||
renewThresholdDays?: number;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
config?: IAcmeConfig;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
154
ts_interfaces/requests/dns-providers.ts
Normal file
154
ts_interfaces/requests/dns-providers.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import type * as authInterfaces from '../data/auth.js';
|
||||
import type {
|
||||
IDnsProviderPublic,
|
||||
IProviderDomainListing,
|
||||
TDnsProviderType,
|
||||
TDnsProviderCredentials,
|
||||
} from '../data/dns-provider.js';
|
||||
|
||||
// ============================================================================
|
||||
// DNS Provider Endpoints
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get all DNS providers (public view, no secrets).
|
||||
*/
|
||||
export interface IReq_GetDnsProviders extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDnsProviders
|
||||
> {
|
||||
method: 'getDnsProviders';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
};
|
||||
response: {
|
||||
providers: IDnsProviderPublic[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single DNS provider by id.
|
||||
*/
|
||||
export interface IReq_GetDnsProvider extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDnsProvider
|
||||
> {
|
||||
method: 'getDnsProvider';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
provider: IDnsProviderPublic | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new DNS provider.
|
||||
*/
|
||||
export interface IReq_CreateDnsProvider extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_CreateDnsProvider
|
||||
> {
|
||||
method: 'createDnsProvider';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
name: string;
|
||||
type: TDnsProviderType;
|
||||
credentials: TDnsProviderCredentials;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
id?: string;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a DNS provider. Only supplied fields are updated.
|
||||
* Pass `credentials` to rotate the secret.
|
||||
*/
|
||||
export interface IReq_UpdateDnsProvider extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_UpdateDnsProvider
|
||||
> {
|
||||
method: 'updateDnsProvider';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
name?: string;
|
||||
credentials?: TDnsProviderCredentials;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a DNS provider. Fails if any IDomain still references it
|
||||
* unless `force: true` is set.
|
||||
*/
|
||||
export interface IReq_DeleteDnsProvider extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_DeleteDnsProvider
|
||||
> {
|
||||
method: 'deleteDnsProvider';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
force?: boolean;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the connection to a DNS provider. Used both for newly-saved
|
||||
* providers and on demand from the UI.
|
||||
*/
|
||||
export interface IReq_TestDnsProvider extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_TestDnsProvider
|
||||
> {
|
||||
method: 'testDnsProvider';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
testedAt: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* List the domains visible to a DNS provider's API account.
|
||||
* Used when importing — does NOT persist anything.
|
||||
*/
|
||||
export interface IReq_ListProviderDomains extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_ListProviderDomains
|
||||
> {
|
||||
method: 'listProviderDomains';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
providerId: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
domains?: IProviderDomainListing[];
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
113
ts_interfaces/requests/dns-records.ts
Normal file
113
ts_interfaces/requests/dns-records.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import type * as authInterfaces from '../data/auth.js';
|
||||
import type { IDnsRecord, TDnsRecordType } from '../data/dns-record.js';
|
||||
|
||||
// ============================================================================
|
||||
// DNS Record Endpoints
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get all DNS records for a domain.
|
||||
*/
|
||||
export interface IReq_GetDnsRecords extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDnsRecords
|
||||
> {
|
||||
method: 'getDnsRecords';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
domainId: string;
|
||||
};
|
||||
response: {
|
||||
records: IDnsRecord[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single DNS record by id.
|
||||
*/
|
||||
export interface IReq_GetDnsRecord extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDnsRecord
|
||||
> {
|
||||
method: 'getDnsRecord';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
record: IDnsRecord | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new DNS record.
|
||||
*
|
||||
* For dcrouter-hosted domains: registers the record with the embedded DnsServer.
|
||||
* For provider domains: pushes the record to the provider API.
|
||||
*/
|
||||
export interface IReq_CreateDnsRecord extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_CreateDnsRecord
|
||||
> {
|
||||
method: 'createDnsRecord';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
domainId: string;
|
||||
name: string;
|
||||
type: TDnsRecordType;
|
||||
value: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
id?: string;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a DNS record.
|
||||
*/
|
||||
export interface IReq_UpdateDnsRecord extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_UpdateDnsRecord
|
||||
> {
|
||||
method: 'updateDnsRecord';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
name?: string;
|
||||
value?: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a DNS record.
|
||||
*/
|
||||
export interface IReq_DeleteDnsRecord extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_DeleteDnsRecord
|
||||
> {
|
||||
method: 'deleteDnsRecord';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
150
ts_interfaces/requests/domains.ts
Normal file
150
ts_interfaces/requests/domains.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import type * as authInterfaces from '../data/auth.js';
|
||||
import type { IDomain } from '../data/domain.js';
|
||||
|
||||
// ============================================================================
|
||||
// Domain Endpoints
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get all domains under management.
|
||||
*/
|
||||
export interface IReq_GetDomains extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDomains
|
||||
> {
|
||||
method: 'getDomains';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
};
|
||||
response: {
|
||||
domains: IDomain[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single domain by id.
|
||||
*/
|
||||
export interface IReq_GetDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetDomain
|
||||
> {
|
||||
method: 'getDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
domain: IDomain | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a dcrouter-hosted (authoritative) domain. dcrouter will serve
|
||||
* DNS records for this domain via the embedded smartdns.DnsServer.
|
||||
*/
|
||||
export interface IReq_CreateDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_CreateDomain
|
||||
> {
|
||||
method: 'createDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
id?: string;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Import one or more domains from a DNS provider. For each imported
|
||||
* domain, records are pulled from the provider into DnsRecordDoc.
|
||||
*/
|
||||
export interface IReq_ImportDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_ImportDomain
|
||||
> {
|
||||
method: 'importDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
providerId: string;
|
||||
/** FQDN(s) of the zone(s) to import — must be visible to the provider account. */
|
||||
domainNames: string[];
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
importedIds?: string[];
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a domain's metadata. Cannot change source / providerId once set.
|
||||
*/
|
||||
export interface IReq_UpdateDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_UpdateDomain
|
||||
> {
|
||||
method: 'updateDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
description?: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a domain and all of its DNS records.
|
||||
* For provider-managed domains, this only removes dcrouter's local record —
|
||||
* it does NOT delete the zone at the provider.
|
||||
*/
|
||||
export interface IReq_DeleteDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_DeleteDomain
|
||||
> {
|
||||
method: 'deleteDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Force-resync a provider-managed domain: re-pulls all records from the
|
||||
* provider API, replacing the cached DnsRecordDocs.
|
||||
* No-op for dcrouter-hosted domains.
|
||||
*/
|
||||
export interface IReq_SyncDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_SyncDomain
|
||||
> {
|
||||
method: 'syncDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
recordCount?: number;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
@@ -12,4 +12,9 @@ export * from './api-tokens.js';
|
||||
export * from './vpn.js';
|
||||
export * from './source-profiles.js';
|
||||
export * from './target-profiles.js';
|
||||
export * from './network-targets.js';
|
||||
export * from './network-targets.js';
|
||||
export * from './users.js';
|
||||
export * from './dns-providers.js';
|
||||
export * from './domains.js';
|
||||
export * from './dns-records.js';
|
||||
export * from './acme-config.js';
|
||||
23
ts_interfaces/requests/users.ts
Normal file
23
ts_interfaces/requests/users.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as authInterfaces from '../data/auth.js';
|
||||
|
||||
/**
|
||||
* List all OpsServer users (admin-only, read-only).
|
||||
* Deliberately omits password/secret fields from the response.
|
||||
*/
|
||||
export interface IReq_ListUsers extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_ListUsers
|
||||
> {
|
||||
method: 'listUsers';
|
||||
request: {
|
||||
identity: authInterfaces.IIdentity;
|
||||
};
|
||||
response: {
|
||||
users: Array<{
|
||||
id: string;
|
||||
username: string;
|
||||
role: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
@@ -64,6 +64,34 @@ export async function createMigrationRunner(
|
||||
migrated++;
|
||||
}
|
||||
ctx.log.log('info', `rename-target-profile-host-to-ip: migrated ${migrated} profile(s)`);
|
||||
})
|
||||
.step('rename-domain-source-manual-to-dcrouter')
|
||||
.from('13.1.0').to('13.8.1')
|
||||
.description('Rename DomainDoc.source value from "manual" to "dcrouter"')
|
||||
.up(async (ctx) => {
|
||||
const collection = ctx.mongo!.collection('domaindoc');
|
||||
const result = await collection.updateMany(
|
||||
{ source: 'manual' },
|
||||
{ $set: { source: 'dcrouter' } },
|
||||
);
|
||||
ctx.log.log(
|
||||
'info',
|
||||
`rename-domain-source-manual-to-dcrouter: migrated ${result.modifiedCount} domain(s)`,
|
||||
);
|
||||
})
|
||||
.step('rename-record-source-manual-to-local')
|
||||
.from('13.8.1').to('13.8.2')
|
||||
.description('Rename DnsRecordDoc.source value from "manual" to "local"')
|
||||
.up(async (ctx) => {
|
||||
const collection = ctx.mongo!.collection('dnsrecorddoc');
|
||||
const result = await collection.updateMany(
|
||||
{ source: 'manual' },
|
||||
{ $set: { source: 'local' } },
|
||||
);
|
||||
ctx.log.log(
|
||||
'info',
|
||||
`rename-record-source-manual-to-local: migrated ${result.modifiedCount} record(s)`,
|
||||
);
|
||||
});
|
||||
|
||||
return migration;
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/dcrouter',
|
||||
version: '13.1.3',
|
||||
version: '13.9.0',
|
||||
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ export interface IConfigState {
|
||||
|
||||
export interface IUiState {
|
||||
activeView: string;
|
||||
activeSubview: string | null;
|
||||
sidebarCollapsed: boolean;
|
||||
autoRefresh: boolean;
|
||||
refreshInterval: number; // milliseconds
|
||||
@@ -116,16 +117,24 @@ 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', 'sourceprofiles', 'networktargets', 'targetprofiles'];
|
||||
const validViews = ['overview', 'network', 'email', 'logs', 'access', 'security', 'domains'];
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const view = segments[0];
|
||||
return validViews.includes(view) ? view : 'overview';
|
||||
};
|
||||
|
||||
// Determine initial subview (second URL segment) from the path
|
||||
const getInitialSubview = (): string | null => {
|
||||
const path = typeof window !== 'undefined' ? window.location.pathname : '/';
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
return segments[1] ?? null;
|
||||
};
|
||||
|
||||
export const uiStatePart = await appState.getStatePart<IUiState>(
|
||||
'ui',
|
||||
{
|
||||
activeView: getInitialView(),
|
||||
activeSubview: getInitialSubview(),
|
||||
sidebarCollapsed: false,
|
||||
autoRefresh: true,
|
||||
refreshInterval: 1000, // 1 second
|
||||
@@ -188,6 +197,28 @@ export const certificateStatePart = await appState.getStatePart<ICertificateStat
|
||||
'soft'
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// ACME Config State (DB-backed singleton, managed via Domains > Certificates)
|
||||
// ============================================================================
|
||||
|
||||
export interface IAcmeConfigState {
|
||||
config: interfaces.data.IAcmeConfig | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
lastUpdated: number;
|
||||
}
|
||||
|
||||
export const acmeConfigStatePart = await appState.getStatePart<IAcmeConfigState>(
|
||||
'acmeConfig',
|
||||
{
|
||||
config: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: 0,
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// Remote Ingress State
|
||||
// ============================================================================
|
||||
@@ -242,6 +273,34 @@ export const routeManagementStatePart = await appState.getStatePart<IRouteManage
|
||||
'soft'
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// Users State (read-only list of OpsServer user accounts)
|
||||
// ============================================================================
|
||||
|
||||
export interface IUser {
|
||||
id: string;
|
||||
username: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export interface IUsersState {
|
||||
users: IUser[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
lastUpdated: number;
|
||||
}
|
||||
|
||||
export const usersStatePart = await appState.getStatePart<IUsersState>(
|
||||
'users',
|
||||
{
|
||||
users: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: 0,
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
|
||||
// Actions for state management
|
||||
interface IActionContext {
|
||||
identity: interfaces.data.IIdentity | null;
|
||||
@@ -428,50 +487,14 @@ export const setActiveViewAction = uiStatePart.createAction<string>(async (state
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// If switching to certificates view, ensure we fetch certificate data
|
||||
if (viewName === 'certificates' && currentState.activeView !== 'certificates') {
|
||||
// If switching to the Domains group, ensure we fetch certificate data
|
||||
// (Certificates is a subview of Domains).
|
||||
if (viewName === 'domains' && currentState.activeView !== 'domains') {
|
||||
setTimeout(() => {
|
||||
certificateStatePart.dispatchAction(fetchCertificateOverviewAction, null);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// If switching to routes view, ensure we fetch route data
|
||||
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);
|
||||
}
|
||||
|
||||
// If switching to apitokens view, ensure we fetch token data
|
||||
if (viewName === 'apitokens' && currentState.activeView !== 'apitokens') {
|
||||
setTimeout(() => {
|
||||
routeManagementStatePart.dispatchAction(fetchApiTokensAction, null);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// If switching to remoteingress view, ensure we fetch edge data
|
||||
if (viewName === 'remoteingress' && currentState.activeView !== 'remoteingress') {
|
||||
setTimeout(() => {
|
||||
remoteIngressStatePart.dispatchAction(fetchRemoteIngressAction, null);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// If switching to security profiles or network targets views, fetch profiles/targets data
|
||||
if ((viewName === 'sourceprofiles' || viewName === 'networktargets') && currentState.activeView !== viewName) {
|
||||
setTimeout(() => {
|
||||
profilesTargetsStatePart.dispatchAction(fetchProfilesAndTargetsAction, null);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// If switching to target profiles view, fetch target profiles data
|
||||
if (viewName === 'targetprofiles' && currentState.activeView !== viewName) {
|
||||
setTimeout(() => {
|
||||
targetProfilesStatePart.dispatchAction(fetchTargetProfilesAction, null);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
return {
|
||||
...currentState,
|
||||
activeView: viewName,
|
||||
@@ -1555,6 +1578,469 @@ export const deleteTargetAction = profilesTargetsStatePart.createAction<{
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Domains State (DNS providers + domains + records)
|
||||
// ============================================================================
|
||||
|
||||
export interface IDomainsState {
|
||||
providers: interfaces.data.IDnsProviderPublic[];
|
||||
domains: interfaces.data.IDomain[];
|
||||
records: interfaces.data.IDnsRecord[];
|
||||
/** id of the currently-selected domain in the DNS records subview. */
|
||||
selectedDomainId: string | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
lastUpdated: number;
|
||||
}
|
||||
|
||||
export const domainsStatePart = await appState.getStatePart<IDomainsState>(
|
||||
'domains',
|
||||
{
|
||||
providers: [],
|
||||
domains: [],
|
||||
records: [],
|
||||
selectedDomainId: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: 0,
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
|
||||
export const fetchDomainsAndProvidersAction = domainsStatePart.createAction(
|
||||
async (statePartArg): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
const currentState = statePartArg.getState()!;
|
||||
if (!context.identity) return currentState;
|
||||
|
||||
try {
|
||||
const providersRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetDnsProviders
|
||||
>('/typedrequest', 'getDnsProviders');
|
||||
const domainsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetDomains
|
||||
>('/typedrequest', 'getDomains');
|
||||
|
||||
const [providersResponse, domainsResponse] = await Promise.all([
|
||||
providersRequest.fire({ identity: context.identity }),
|
||||
domainsRequest.fire({ identity: context.identity }),
|
||||
]);
|
||||
|
||||
return {
|
||||
...currentState,
|
||||
providers: providersResponse.providers,
|
||||
domains: domainsResponse.domains,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: Date.now(),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...currentState,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch domains/providers',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const fetchDnsRecordsForDomainAction = domainsStatePart.createAction<{ domainId: string }>(
|
||||
async (statePartArg, dataArg): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
const currentState = statePartArg.getState()!;
|
||||
if (!context.identity) return currentState;
|
||||
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetDnsRecords
|
||||
>('/typedrequest', 'getDnsRecords');
|
||||
const response = await request.fire({
|
||||
identity: context.identity,
|
||||
domainId: dataArg.domainId,
|
||||
});
|
||||
return {
|
||||
...currentState,
|
||||
records: response.records,
|
||||
selectedDomainId: dataArg.domainId,
|
||||
error: null,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...currentState,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch DNS records',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const createDnsProviderAction = domainsStatePart.createAction<{
|
||||
name: string;
|
||||
type: interfaces.data.TDnsProviderType;
|
||||
credentials: interfaces.data.TDnsProviderCredentials;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_CreateDnsProvider
|
||||
>('/typedrequest', 'createDnsProvider');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
name: dataArg.name,
|
||||
type: dataArg.type,
|
||||
credentials: dataArg.credentials,
|
||||
});
|
||||
if (!response.success) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: response.message || 'Failed to create provider',
|
||||
};
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to create provider',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const updateDnsProviderAction = domainsStatePart.createAction<{
|
||||
id: string;
|
||||
name?: string;
|
||||
credentials?: interfaces.data.TDnsProviderCredentials;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_UpdateDnsProvider
|
||||
>('/typedrequest', 'updateDnsProvider');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
id: dataArg.id,
|
||||
name: dataArg.name,
|
||||
credentials: dataArg.credentials,
|
||||
});
|
||||
if (!response.success) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: response.message || 'Failed to update provider',
|
||||
};
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to update provider',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const deleteDnsProviderAction = domainsStatePart.createAction<{ id: string; force?: boolean }>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_DeleteDnsProvider
|
||||
>('/typedrequest', 'deleteDnsProvider');
|
||||
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 provider',
|
||||
};
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete provider',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const testDnsProviderAction = domainsStatePart.createAction<{ id: string }>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_TestDnsProvider
|
||||
>('/typedrequest', 'testDnsProvider');
|
||||
await request.fire({ identity: context.identity!, id: dataArg.id });
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to test provider',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/** One-shot fetch for the import-domain modal. Does NOT modify state. */
|
||||
export async function fetchProviderDomains(
|
||||
providerId: string,
|
||||
): Promise<{ success: boolean; domains?: interfaces.data.IProviderDomainListing[]; message?: string }> {
|
||||
const context = getActionContext();
|
||||
if (!context.identity) return { success: false, message: 'Not authenticated' };
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_ListProviderDomains
|
||||
>('/typedrequest', 'listProviderDomains');
|
||||
return await request.fire({ identity: context.identity, providerId });
|
||||
}
|
||||
|
||||
export const createDcrouterDomainAction = domainsStatePart.createAction<{
|
||||
name: string;
|
||||
description?: string;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_CreateDomain
|
||||
>('/typedrequest', 'createDomain');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
name: dataArg.name,
|
||||
description: dataArg.description,
|
||||
});
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to create domain' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to create domain',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const importDomainsFromProviderAction = domainsStatePart.createAction<{
|
||||
providerId: string;
|
||||
domainNames: string[];
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_ImportDomain
|
||||
>('/typedrequest', 'importDomain');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
providerId: dataArg.providerId,
|
||||
domainNames: dataArg.domainNames,
|
||||
});
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to import domains' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to import domains',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const deleteDomainAction = domainsStatePart.createAction<{ id: string }>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_DeleteDomain
|
||||
>('/typedrequest', 'deleteDomain');
|
||||
const response = await request.fire({ identity: context.identity!, id: dataArg.id });
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to delete domain' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete domain',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const syncDomainAction = domainsStatePart.createAction<{ id: string }>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_SyncDomain
|
||||
>('/typedrequest', 'syncDomain');
|
||||
const response = await request.fire({ identity: context.identity!, id: dataArg.id });
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to sync domain' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to sync domain',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const createDnsRecordAction = domainsStatePart.createAction<{
|
||||
domainId: string;
|
||||
name: string;
|
||||
type: interfaces.data.TDnsRecordType;
|
||||
value: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_CreateDnsRecord
|
||||
>('/typedrequest', 'createDnsRecord');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
domainId: dataArg.domainId,
|
||||
name: dataArg.name,
|
||||
type: dataArg.type,
|
||||
value: dataArg.value,
|
||||
ttl: dataArg.ttl,
|
||||
proxied: dataArg.proxied,
|
||||
});
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to create record' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDnsRecordsForDomainAction, { domainId: dataArg.domainId });
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to create record',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const updateDnsRecordAction = domainsStatePart.createAction<{
|
||||
id: string;
|
||||
domainId: string;
|
||||
name?: string;
|
||||
value?: string;
|
||||
ttl?: number;
|
||||
proxied?: boolean;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_UpdateDnsRecord
|
||||
>('/typedrequest', 'updateDnsRecord');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
id: dataArg.id,
|
||||
name: dataArg.name,
|
||||
value: dataArg.value,
|
||||
ttl: dataArg.ttl,
|
||||
proxied: dataArg.proxied,
|
||||
});
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to update record' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDnsRecordsForDomainAction, { domainId: dataArg.domainId });
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to update record',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const deleteDnsRecordAction = domainsStatePart.createAction<{ id: string; domainId: string }>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_DeleteDnsRecord
|
||||
>('/typedrequest', 'deleteDnsRecord');
|
||||
const response = await request.fire({ identity: context.identity!, id: dataArg.id });
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Failed to delete record' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDnsRecordsForDomainAction, { domainId: dataArg.domainId });
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete record',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// ACME Config Actions
|
||||
// ============================================================================
|
||||
|
||||
export const fetchAcmeConfigAction = acmeConfigStatePart.createAction(
|
||||
async (statePartArg): Promise<IAcmeConfigState> => {
|
||||
const context = getActionContext();
|
||||
const currentState = statePartArg.getState()!;
|
||||
if (!context.identity) return currentState;
|
||||
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetAcmeConfig
|
||||
>('/typedrequest', 'getAcmeConfig');
|
||||
const response = await request.fire({ identity: context.identity });
|
||||
return {
|
||||
config: response.config,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: Date.now(),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...currentState,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch ACME config',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const updateAcmeConfigAction = acmeConfigStatePart.createAction<{
|
||||
accountEmail?: string;
|
||||
enabled?: boolean;
|
||||
useProduction?: boolean;
|
||||
autoRenew?: boolean;
|
||||
renewThresholdDays?: number;
|
||||
}>(async (statePartArg, dataArg, actionContext): Promise<IAcmeConfigState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_UpdateAcmeConfig
|
||||
>('/typedrequest', 'updateAcmeConfig');
|
||||
const response = await request.fire({
|
||||
identity: context.identity!,
|
||||
accountEmail: dataArg.accountEmail,
|
||||
enabled: dataArg.enabled,
|
||||
useProduction: dataArg.useProduction,
|
||||
autoRenew: dataArg.autoRenew,
|
||||
renewThresholdDays: dataArg.renewThresholdDays,
|
||||
});
|
||||
if (!response.success) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: response.message || 'Failed to update ACME config',
|
||||
};
|
||||
}
|
||||
return await actionContext!.dispatch(fetchAcmeConfigAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Failed to update ACME config',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Route Management Actions
|
||||
// ============================================================================
|
||||
@@ -1784,6 +2270,35 @@ export const fetchApiTokensAction = routeManagementStatePart.createAction(async
|
||||
}
|
||||
});
|
||||
|
||||
// Users (read-only list)
|
||||
export const fetchUsersAction = usersStatePart.createAction(async (statePartArg): Promise<IUsersState> => {
|
||||
const context = getActionContext();
|
||||
const currentState = statePartArg.getState()!;
|
||||
if (!context.identity) return currentState;
|
||||
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_ListUsers
|
||||
>('/typedrequest', 'listUsers');
|
||||
|
||||
const response = await request.fire({
|
||||
identity: context.identity,
|
||||
});
|
||||
|
||||
return {
|
||||
...currentState,
|
||||
users: response.users,
|
||||
error: null,
|
||||
lastUpdated: Date.now(),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
...currentState,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch users',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export async function createApiToken(name: string, scopes: interfaces.data.TApiTokenScope[], expiresInDays?: number | null) {
|
||||
const context = getActionContext();
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
@@ -1944,6 +2459,7 @@ async function dispatchCombinedRefreshActionInner() {
|
||||
const context = getActionContext();
|
||||
if (!context.identity) return;
|
||||
const currentView = uiStatePart.getState()!.activeView;
|
||||
const currentSubview = uiStatePart.getState()!.activeSubview;
|
||||
|
||||
try {
|
||||
// Always fetch basic stats for dashboard widgets
|
||||
@@ -2046,8 +2562,8 @@ async function dispatchCombinedRefreshActionInner() {
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh certificate data if on certificates view
|
||||
if (currentView === 'certificates') {
|
||||
// Refresh certificate data if on Domains > Certificates subview
|
||||
if (currentView === 'domains' && currentSubview === 'certificates') {
|
||||
try {
|
||||
await certificateStatePart.dispatchAction(fetchCertificateOverviewAction, null);
|
||||
} catch (error) {
|
||||
@@ -2055,8 +2571,8 @@ async function dispatchCombinedRefreshActionInner() {
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh remote ingress data if on remoteingress view
|
||||
if (currentView === 'remoteingress') {
|
||||
// Refresh remote ingress data if on the Network → Remote Ingress subview
|
||||
if (currentView === 'network' && currentSubview === 'remoteingress') {
|
||||
try {
|
||||
await remoteIngressStatePart.dispatchAction(fetchRemoteIngressAction, null);
|
||||
} catch (error) {
|
||||
@@ -2064,8 +2580,8 @@ async function dispatchCombinedRefreshActionInner() {
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh VPN data if on vpn view
|
||||
if (currentView === 'vpn') {
|
||||
// Refresh VPN data if on the Network → VPN subview
|
||||
if (currentView === 'network' && currentSubview === 'vpn') {
|
||||
try {
|
||||
await vpnStatePart.dispatchAction(fetchVpnAction, null);
|
||||
} catch (error) {
|
||||
|
||||
2
ts_web/elements/access/index.ts
Normal file
2
ts_web/elements/access/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './ops-view-apitokens.js';
|
||||
export * from './ops-view-users.js';
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as interfaces from '../../dist_ts_interfaces/index.js';
|
||||
import { viewHostCss } from './shared/css.js';
|
||||
import * as appstate from '../../appstate.js';
|
||||
import * as interfaces from '../../../dist_ts_interfaces/index.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
@@ -100,7 +100,7 @@ export class OpsViewApiTokens extends DeesElement {
|
||||
const { apiTokens } = this.routeState;
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">API Tokens</dees-heading>
|
||||
<dees-heading level="3">API Tokens</dees-heading>
|
||||
|
||||
<div class="apiTokensContainer">
|
||||
<dees-table
|
||||
@@ -109,6 +109,7 @@ export class OpsViewApiTokens extends DeesElement {
|
||||
.data=${apiTokens}
|
||||
.dataName=${'token'}
|
||||
.searchable=${true}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(token: interfaces.data.IApiTokenInfo) => ({
|
||||
name: token.name,
|
||||
scopes: this.renderScopePills(token.scopes),
|
||||
140
ts_web/elements/access/ops-view-users.ts
Normal file
140
ts_web/elements/access/ops-view-users.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
css,
|
||||
cssManager,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
|
||||
@customElement('ops-view-users')
|
||||
export class OpsViewUsers extends DeesElement {
|
||||
@state() accessor usersState: appstate.IUsersState = {
|
||||
users: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
lastUpdated: 0,
|
||||
};
|
||||
|
||||
@state() accessor loginState: appstate.ILoginState = {
|
||||
identity: null,
|
||||
isLoggedIn: false,
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const usersSub = appstate.usersStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((usersState) => {
|
||||
this.usersState = usersState;
|
||||
});
|
||||
this.rxSubscriptions.push(usersSub);
|
||||
|
||||
const loginSub = appstate.loginStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((loginState) => {
|
||||
this.loginState = loginState;
|
||||
// Re-fetch users when user logs in (fixes race condition where
|
||||
// the view is created before authentication completes)
|
||||
if (loginState.isLoggedIn) {
|
||||
appstate.usersStatePart.dispatchAction(appstate.fetchUsersAction, null);
|
||||
}
|
||||
});
|
||||
this.rxSubscriptions.push(loginSub);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
.usersContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.roleBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.roleBadge.admin {
|
||||
background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
|
||||
color: ${cssManager.bdTheme('#92400e', '#fbbf24')};
|
||||
}
|
||||
|
||||
.roleBadge.user {
|
||||
background: ${cssManager.bdTheme('#e0f2fe', '#0c4a6e')};
|
||||
color: ${cssManager.bdTheme('#075985', '#7dd3fc')};
|
||||
}
|
||||
|
||||
.sessionBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
background: ${cssManager.bdTheme('#dcfce7', '#14532d')};
|
||||
color: ${cssManager.bdTheme('#166534', '#4ade80')};
|
||||
}
|
||||
|
||||
.userIdCell {
|
||||
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
|
||||
font-size: 11px;
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const { users } = this.usersState;
|
||||
const currentUserId = this.loginState.identity?.userId;
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Users</dees-heading>
|
||||
|
||||
<div class="usersContainer">
|
||||
<dees-table
|
||||
.heading1=${'Users'}
|
||||
.heading2=${'OpsServer user accounts'}
|
||||
.data=${users}
|
||||
.dataName=${'user'}
|
||||
.searchable=${true}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(user: appstate.IUser) => ({
|
||||
ID: html`<span class="userIdCell">${user.id}</span>`,
|
||||
Username: user.username,
|
||||
Role: this.renderRoleBadge(user.role),
|
||||
Session: user.id === currentUserId
|
||||
? html`<span class="sessionBadge">current</span>`
|
||||
: '',
|
||||
})}
|
||||
></dees-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderRoleBadge(role: string): TemplateResult {
|
||||
const cls = role === 'admin' ? 'admin' : 'user';
|
||||
return html`<span class="roleBadge ${cls}">${role}</span>`;
|
||||
}
|
||||
|
||||
async firstUpdated() {
|
||||
if (this.loginState.isLoggedIn) {
|
||||
await appstate.usersStatePart.dispatchAction(appstate.fetchUsersAction, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
224
ts_web/elements/domains/dns-provider-form.ts
Normal file
224
ts_web/elements/domains/dns-provider-form.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
import {
|
||||
DeesElement,
|
||||
html,
|
||||
customElement,
|
||||
type TemplateResult,
|
||||
css,
|
||||
state,
|
||||
property,
|
||||
cssManager,
|
||||
} from '@design.estate/dees-element';
|
||||
import * as interfaces from '../../../dist_ts_interfaces/index.js';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'dns-provider-form': DnsProviderForm;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactive credential form for a DNS provider. Renders the type picker
|
||||
* and the credential fields for the currently-selected type.
|
||||
*
|
||||
* Provider-agnostic — driven entirely by `dnsProviderTypeDescriptors` from
|
||||
* `ts_interfaces/data/dns-provider.ts`. Adding a new provider type means
|
||||
* appending one entry to the descriptors array; this form picks it up
|
||||
* automatically.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* const formEl = document.createElement('dns-provider-form');
|
||||
* formEl.providerName = 'My provider';
|
||||
* // ... pass element into a DeesModal as content ...
|
||||
* // on submit:
|
||||
* const data = formEl.collectData();
|
||||
* // → { name, type, credentials }
|
||||
*
|
||||
* In edit mode, set `lockType = true` so the user cannot change provider
|
||||
* type after creation (credentials shapes don't transfer between types).
|
||||
*/
|
||||
@customElement('dns-provider-form')
|
||||
export class DnsProviderForm extends DeesElement {
|
||||
/** Pre-populated provider name. */
|
||||
@property({ type: String })
|
||||
accessor providerName: string = '';
|
||||
|
||||
/**
|
||||
* Currently selected provider type. Initialized to the first user-creatable
|
||||
* descriptor; caller can override before mounting (e.g. for edit dialogs).
|
||||
* The built-in 'dcrouter' pseudo-provider is excluded from the picker —
|
||||
* operators cannot create another one.
|
||||
*/
|
||||
@state()
|
||||
accessor selectedType: interfaces.data.TDnsProviderType =
|
||||
interfaces.data.dnsProviderTypeDescriptors.find((d) => d.type !== 'dcrouter')?.type ??
|
||||
'cloudflare';
|
||||
|
||||
/** When true, hide the type picker — used in edit dialogs. */
|
||||
@property({ type: Boolean })
|
||||
accessor lockType: boolean = false;
|
||||
|
||||
/**
|
||||
* Help text shown above credentials. Useful for edit dialogs to indicate
|
||||
* that fields can be left blank to keep current values.
|
||||
*/
|
||||
@property({ type: String })
|
||||
accessor credentialsHint: string = '';
|
||||
|
||||
/** Internal map of credential field values, keyed by the descriptor's `key`. */
|
||||
@state()
|
||||
accessor credentialValues: Record<string, string> = {};
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.field {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.helpText {
|
||||
font-size: 12px;
|
||||
opacity: 0.7;
|
||||
margin-top: -6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.typeDescription {
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
margin: 4px 0 16px;
|
||||
padding: 8px 12px;
|
||||
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.credentialsHint {
|
||||
font-size: 12px;
|
||||
opacity: 0.7;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
// Exclude the built-in 'dcrouter' pseudo-provider from the type picker —
|
||||
// operators cannot create another one, it's surfaced at read time by the
|
||||
// backend handler instead.
|
||||
const descriptors = interfaces.data.dnsProviderTypeDescriptors.filter(
|
||||
(d) => d.type !== 'dcrouter',
|
||||
);
|
||||
const descriptor = interfaces.data.getDnsProviderTypeDescriptor(this.selectedType);
|
||||
|
||||
return html`
|
||||
<dees-form>
|
||||
<div class="field">
|
||||
<dees-input-text
|
||||
.key=${'name'}
|
||||
.label=${'Provider name'}
|
||||
.value=${this.providerName}
|
||||
.required=${true}
|
||||
></dees-input-text>
|
||||
</div>
|
||||
|
||||
${this.lockType
|
||||
? html`
|
||||
<div class="field">
|
||||
<dees-input-text
|
||||
.key=${'__type_display'}
|
||||
.label=${'Type'}
|
||||
.value=${descriptor?.displayName ?? this.selectedType}
|
||||
.disabled=${true}
|
||||
></dees-input-text>
|
||||
</div>
|
||||
`
|
||||
: html`
|
||||
<div class="field">
|
||||
<dees-input-dropdown
|
||||
.key=${'__type'}
|
||||
.label=${'Provider type'}
|
||||
.options=${descriptors.map((d) => ({ option: d.displayName, key: d.type }))}
|
||||
.selectedOption=${descriptor
|
||||
? { option: descriptor.displayName, key: descriptor.type }
|
||||
: undefined}
|
||||
@selectedOption=${(e: CustomEvent) => {
|
||||
const newType = (e.detail as any)?.key as
|
||||
| interfaces.data.TDnsProviderType
|
||||
| undefined;
|
||||
if (newType && newType !== this.selectedType) {
|
||||
this.selectedType = newType;
|
||||
this.credentialValues = {};
|
||||
}
|
||||
}}
|
||||
></dees-input-dropdown>
|
||||
</div>
|
||||
`}
|
||||
${descriptor
|
||||
? html`
|
||||
<div class="typeDescription">${descriptor.description}</div>
|
||||
${this.credentialsHint
|
||||
? html`<div class="credentialsHint">${this.credentialsHint}</div>`
|
||||
: ''}
|
||||
${descriptor.credentialFields.map(
|
||||
(f) => html`
|
||||
<div class="field">
|
||||
<dees-input-text
|
||||
.key=${f.key}
|
||||
.label=${f.label}
|
||||
.required=${f.required && !this.lockType}
|
||||
></dees-input-text>
|
||||
${f.helpText ? html`<div class="helpText">${f.helpText}</div>` : ''}
|
||||
</div>
|
||||
`,
|
||||
)}
|
||||
`
|
||||
: html`<p>No provider types registered.</p>`}
|
||||
</dees-form>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the form values and assemble the create/update payload.
|
||||
* Returns the typed credentials object built from the descriptor's keys.
|
||||
*/
|
||||
public async collectData(): Promise<{
|
||||
name: string;
|
||||
type: interfaces.data.TDnsProviderType;
|
||||
credentials: interfaces.data.TDnsProviderCredentials;
|
||||
credentialsTouched: boolean;
|
||||
} | null> {
|
||||
const form = this.shadowRoot?.querySelector('dees-form') as any;
|
||||
if (!form) return null;
|
||||
const data = await form.collectFormData();
|
||||
const descriptor = interfaces.data.getDnsProviderTypeDescriptor(this.selectedType);
|
||||
if (!descriptor) return null;
|
||||
|
||||
// Build the credentials object from the descriptor's field keys.
|
||||
const credsBody: Record<string, string> = {};
|
||||
let credentialsTouched = false;
|
||||
for (const f of descriptor.credentialFields) {
|
||||
const value = data[f.key];
|
||||
if (value !== undefined && value !== null && String(value).length > 0) {
|
||||
credsBody[f.key] = String(value);
|
||||
credentialsTouched = true;
|
||||
}
|
||||
}
|
||||
|
||||
// The discriminator goes on the credentials object so the backend
|
||||
// factory and the discriminated union both stay happy.
|
||||
const credentials = {
|
||||
type: this.selectedType,
|
||||
...credsBody,
|
||||
} as unknown as interfaces.data.TDnsProviderCredentials;
|
||||
|
||||
return {
|
||||
name: String(data.name ?? ''),
|
||||
type: this.selectedType,
|
||||
credentials,
|
||||
credentialsTouched,
|
||||
};
|
||||
}
|
||||
}
|
||||
5
ts_web/elements/domains/index.ts
Normal file
5
ts_web/elements/domains/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './dns-provider-form.js';
|
||||
export * from './ops-view-providers.js';
|
||||
export * from './ops-view-domains.js';
|
||||
export * from './ops-view-dns.js';
|
||||
export * from './ops-view-certificates.js';
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
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 * 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 {
|
||||
@@ -23,17 +23,25 @@ export class OpsViewCertificates extends DeesElement {
|
||||
@state()
|
||||
accessor certState: appstate.ICertificateState = appstate.certificateStatePart.getState()!;
|
||||
|
||||
@state()
|
||||
accessor acmeState: appstate.IAcmeConfigState = appstate.acmeConfigStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.certificateStatePart.select().subscribe((newState) => {
|
||||
const certSub = appstate.certificateStatePart.select().subscribe((newState) => {
|
||||
this.certState = newState;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
this.rxSubscriptions.push(certSub);
|
||||
const acmeSub = appstate.acmeConfigStatePart.select().subscribe((newState) => {
|
||||
this.acmeState = newState;
|
||||
});
|
||||
this.rxSubscriptions.push(acmeSub);
|
||||
}
|
||||
|
||||
async connectedCallback() {
|
||||
await super.connectedCallback();
|
||||
await appstate.certificateStatePart.dispatchAction(appstate.fetchCertificateOverviewAction, null);
|
||||
await appstate.acmeConfigStatePart.dispatchAction(appstate.fetchAcmeConfigAction, null);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
@@ -46,6 +54,62 @@ export class OpsViewCertificates extends DeesElement {
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.acmeCard {
|
||||
padding: 16px 20px;
|
||||
background: ${cssManager.bdTheme('#f9fafb', '#111827')};
|
||||
border: 1px solid ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.acmeCard.acmeCardEmpty {
|
||||
background: ${cssManager.bdTheme('#fffbeb', '#1c1917')};
|
||||
border-color: ${cssManager.bdTheme('#fde68a', '#78350f')};
|
||||
}
|
||||
|
||||
.acmeCardHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.acmeCardTitle {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: ${cssManager.bdTheme('#111827', '#f3f4f6')};
|
||||
}
|
||||
|
||||
.acmeGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 12px 24px;
|
||||
}
|
||||
|
||||
.acmeField {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.acmeLabel {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
}
|
||||
|
||||
.acmeValue {
|
||||
font-size: 13px;
|
||||
color: ${cssManager.bdTheme('#111827', '#f3f4f6')};
|
||||
}
|
||||
|
||||
.acmeEmptyHint {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: ${cssManager.bdTheme('#78350f', '#fde68a')};
|
||||
}
|
||||
|
||||
.statusBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -159,15 +223,154 @@ export class OpsViewCertificates extends DeesElement {
|
||||
const { summary } = this.certState;
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Certificates</dees-heading>
|
||||
<dees-heading level="3">Certificates</dees-heading>
|
||||
|
||||
<div class="certificatesContainer">
|
||||
${this.renderAcmeSettingsCard()}
|
||||
${this.renderStatsTiles(summary)}
|
||||
${this.renderCertificateTable()}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderAcmeSettingsCard(): TemplateResult {
|
||||
const config = this.acmeState.config;
|
||||
|
||||
if (!config) {
|
||||
return html`
|
||||
<div class="acmeCard acmeCardEmpty">
|
||||
<div class="acmeCardHeader">
|
||||
<span class="acmeCardTitle">ACME Settings</span>
|
||||
<dees-button
|
||||
eventName="edit-acme"
|
||||
@click=${() => this.showEditAcmeDialog()}
|
||||
.type=${'highlighted'}
|
||||
>Configure</dees-button>
|
||||
</div>
|
||||
<p class="acmeEmptyHint">
|
||||
No ACME configuration yet. Click <strong>Configure</strong> to set up automated TLS
|
||||
certificate issuance via Let's Encrypt. You'll also need at least one DNS provider
|
||||
under <strong>Domains > Providers</strong>.
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="acmeCard">
|
||||
<div class="acmeCardHeader">
|
||||
<span class="acmeCardTitle">ACME Settings</span>
|
||||
<dees-button eventName="edit-acme" @click=${() => this.showEditAcmeDialog()}>Edit</dees-button>
|
||||
</div>
|
||||
<div class="acmeGrid">
|
||||
<div class="acmeField">
|
||||
<span class="acmeLabel">Account email</span>
|
||||
<span class="acmeValue">${config.accountEmail || '(not set)'}</span>
|
||||
</div>
|
||||
<div class="acmeField">
|
||||
<span class="acmeLabel">Status</span>
|
||||
<span class="acmeValue">
|
||||
<span class="statusBadge ${config.enabled ? 'valid' : 'unknown'}">
|
||||
${config.enabled ? 'enabled' : 'disabled'}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="acmeField">
|
||||
<span class="acmeLabel">Mode</span>
|
||||
<span class="acmeValue">
|
||||
<span class="statusBadge ${config.useProduction ? 'valid' : 'provisioning'}">
|
||||
${config.useProduction ? 'production' : 'staging'}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="acmeField">
|
||||
<span class="acmeLabel">Auto-renew</span>
|
||||
<span class="acmeValue">${config.autoRenew ? 'on' : 'off'}</span>
|
||||
</div>
|
||||
<div class="acmeField">
|
||||
<span class="acmeLabel">Renewal threshold</span>
|
||||
<span class="acmeValue">${config.renewThresholdDays} days</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private async showEditAcmeDialog() {
|
||||
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
|
||||
const current = this.acmeState.config;
|
||||
|
||||
DeesModal.createAndShow({
|
||||
heading: current ? 'Edit ACME Settings' : 'Configure ACME',
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-text
|
||||
.key=${'accountEmail'}
|
||||
.label=${'Account email'}
|
||||
.value=${current?.accountEmail ?? ''}
|
||||
.required=${true}
|
||||
></dees-input-text>
|
||||
<dees-input-checkbox
|
||||
.key=${'enabled'}
|
||||
.label=${'Enabled'}
|
||||
.value=${current?.enabled ?? true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'useProduction'}
|
||||
.label=${"Use Let's Encrypt production (uncheck for staging)"}
|
||||
.value=${current?.useProduction ?? true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'autoRenew'}
|
||||
.label=${'Auto-renew certificates'}
|
||||
.value=${current?.autoRenew ?? true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-text
|
||||
.key=${'renewThresholdDays'}
|
||||
.label=${'Renewal threshold (days)'}
|
||||
.value=${String(current?.renewThresholdDays ?? 30)}
|
||||
></dees-input-text>
|
||||
</dees-form>
|
||||
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
|
||||
Most fields take effect on the next dcrouter restart (SmartAcme is instantiated once at
|
||||
startup). Changing the account email creates a new Let's Encrypt account — only do this
|
||||
if you know what you're doing.
|
||||
</p>
|
||||
`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'Save',
|
||||
action: async (modalArg: any) => {
|
||||
const form = modalArg.shadowRoot
|
||||
?.querySelector('.content')
|
||||
?.querySelector('dees-form');
|
||||
if (!form) return;
|
||||
const data = await form.collectFormData();
|
||||
const email = String(data.accountEmail ?? '').trim();
|
||||
if (!email) {
|
||||
DeesToast.show({
|
||||
message: 'Account email is required',
|
||||
type: 'warning',
|
||||
duration: 2500,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const threshold = parseInt(String(data.renewThresholdDays ?? '30'), 10);
|
||||
await appstate.acmeConfigStatePart.dispatchAction(appstate.updateAcmeConfigAction, {
|
||||
accountEmail: email,
|
||||
enabled: Boolean(data.enabled),
|
||||
useProduction: Boolean(data.useProduction),
|
||||
autoRenew: Boolean(data.autoRenew),
|
||||
renewThresholdDays: Number.isFinite(threshold) ? threshold : 30,
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private renderStatsTiles(summary: appstate.ICertificateState['summary']): TemplateResult {
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
@@ -228,6 +431,7 @@ export class OpsViewCertificates extends DeesElement {
|
||||
return html`
|
||||
<dees-table
|
||||
.data=${this.certState.certificates}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(cert: interfaces.requests.ICertificateInfo) => ({
|
||||
Domain: cert.domain,
|
||||
Routes: this.renderRoutePills(cert.routeNames),
|
||||
273
ts_web/elements/domains/ops-view-dns.ts
Normal file
273
ts_web/elements/domains/ops-view-dns.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
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';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-dns': OpsViewDns;
|
||||
}
|
||||
}
|
||||
|
||||
const RECORD_TYPES: interfaces.data.TDnsRecordType[] = [
|
||||
'A',
|
||||
'AAAA',
|
||||
'CNAME',
|
||||
'MX',
|
||||
'TXT',
|
||||
'NS',
|
||||
'CAA',
|
||||
];
|
||||
|
||||
@customElement('ops-view-dns')
|
||||
export class OpsViewDns extends DeesElement {
|
||||
@state()
|
||||
accessor domainsState: appstate.IDomainsState = appstate.domainsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.domainsStatePart.select().subscribe((newState) => {
|
||||
this.domainsState = newState;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
async connectedCallback() {
|
||||
await super.connectedCallback();
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
|
||||
// If a domain is already selected (e.g. via "View Records" navigation), refresh its records
|
||||
const selected = this.domainsState.selectedDomainId;
|
||||
if (selected) {
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.fetchDnsRecordsForDomainAction, {
|
||||
domainId: selected,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
.dnsContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.domainPicker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: ${cssManager.bdTheme('#f9fafb', '#111827')};
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.sourceBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.sourceBadge.local {
|
||||
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
|
||||
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
|
||||
}
|
||||
|
||||
.sourceBadge.synced {
|
||||
background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
|
||||
color: ${cssManager.bdTheme('#92400e', '#fde047')};
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const domains = this.domainsState.domains;
|
||||
const selectedId = this.domainsState.selectedDomainId;
|
||||
const records = this.domainsState.records;
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">DNS Records</dees-heading>
|
||||
<div class="dnsContainer">
|
||||
<div class="domainPicker">
|
||||
<span>Domain:</span>
|
||||
<dees-input-dropdown
|
||||
.options=${domains.map((d) => ({ option: d.name, key: d.id }))}
|
||||
.selectedOption=${selectedId
|
||||
? { option: domains.find((d) => d.id === selectedId)?.name || '', key: selectedId }
|
||||
: undefined}
|
||||
@selectedOption=${async (e: CustomEvent) => {
|
||||
const id = (e.detail as any)?.key;
|
||||
if (!id) return;
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.fetchDnsRecordsForDomainAction,
|
||||
{ domainId: id },
|
||||
);
|
||||
}}
|
||||
></dees-input-dropdown>
|
||||
</div>
|
||||
|
||||
${selectedId
|
||||
? html`
|
||||
<dees-table
|
||||
.heading1=${'DNS Records'}
|
||||
.heading2=${this.domainHint(selectedId)}
|
||||
.data=${records}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(r: interfaces.data.IDnsRecord) => ({
|
||||
Name: r.name,
|
||||
Type: r.type,
|
||||
Value: r.value,
|
||||
TTL: r.ttl,
|
||||
Source: html`<span class="sourceBadge ${r.source}">${r.source}</span>`,
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'Add Record',
|
||||
iconName: 'lucide:plus',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.showCreateRecordDialog(selectedId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Refresh',
|
||||
iconName: 'lucide:rotateCw',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.fetchDnsRecordsForDomainAction,
|
||||
{ domainId: selectedId },
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Edit',
|
||||
iconName: 'lucide:pencil',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const rec = actionData.item as interfaces.data.IDnsRecord;
|
||||
await this.showEditRecordDialog(rec);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
iconName: 'lucide:trash2',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const rec = actionData.item as interfaces.data.IDnsRecord;
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.deleteDnsRecordAction,
|
||||
{ id: rec.id, domainId: rec.domainId },
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-table>
|
||||
`
|
||||
: html`<p style="opacity: 0.7;">Pick a domain above to view its records.</p>`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private domainHint(domainId: string): string {
|
||||
const domain = this.domainsState.domains.find((d) => d.id === domainId);
|
||||
if (!domain) return '';
|
||||
if (domain.source === 'dcrouter') {
|
||||
return 'Records are served by dcrouter (authoritative).';
|
||||
}
|
||||
return 'Records are stored at the provider — changes here are pushed via the provider API.';
|
||||
}
|
||||
|
||||
private async showCreateRecordDialog(domainId: string) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
heading: 'Add DNS Record',
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-text .key=${'name'} .label=${'Name (FQDN)'} .required=${true}></dees-input-text>
|
||||
<dees-input-dropdown
|
||||
.key=${'type'}
|
||||
.label=${'Type'}
|
||||
.options=${RECORD_TYPES.map((t) => ({ option: t, key: t }))}
|
||||
.required=${true}
|
||||
></dees-input-dropdown>
|
||||
<dees-input-text
|
||||
.key=${'value'}
|
||||
.label=${'Value (for MX use "10 mail.example.com")'}
|
||||
.required=${true}
|
||||
></dees-input-text>
|
||||
<dees-input-text .key=${'ttl'} .label=${'TTL (seconds)'} .value=${'300'}></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 type = (data.type?.key ?? data.type) as interfaces.data.TDnsRecordType;
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.createDnsRecordAction, {
|
||||
domainId,
|
||||
name: String(data.name),
|
||||
type,
|
||||
value: String(data.value),
|
||||
ttl: parseInt(String(data.ttl || '300'), 10),
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async showEditRecordDialog(rec: interfaces.data.IDnsRecord) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
heading: `Edit ${rec.type} ${rec.name}`,
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-text .key=${'name'} .label=${'Name (FQDN)'} .value=${rec.name}></dees-input-text>
|
||||
<dees-input-text .key=${'value'} .label=${'Value'} .value=${rec.value}></dees-input-text>
|
||||
<dees-input-text .key=${'ttl'} .label=${'TTL (seconds)'} .value=${String(rec.ttl)}></dees-input-text>
|
||||
</dees-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.domainsStatePart.dispatchAction(appstate.updateDnsRecordAction, {
|
||||
id: rec.id,
|
||||
domainId: rec.domainId,
|
||||
name: String(data.name),
|
||||
value: String(data.value),
|
||||
ttl: parseInt(String(data.ttl || '300'), 10),
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
335
ts_web/elements/domains/ops-view-domains.ts
Normal file
335
ts_web/elements/domains/ops-view-domains.ts
Normal file
@@ -0,0 +1,335 @@
|
||||
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 { appRouter } from '../../router.js';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-domains': OpsViewDomains;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-domains')
|
||||
export class OpsViewDomains extends DeesElement {
|
||||
@state()
|
||||
accessor domainsState: appstate.IDomainsState = appstate.domainsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.domainsStatePart.select().subscribe((newState) => {
|
||||
this.domainsState = newState;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
async connectedCallback() {
|
||||
await super.connectedCallback();
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
.domainsContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.sourceBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.sourceBadge.dcrouter {
|
||||
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
|
||||
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
|
||||
}
|
||||
|
||||
.sourceBadge.provider {
|
||||
background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
|
||||
color: ${cssManager.bdTheme('#92400e', '#fde047')};
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const domains = this.domainsState.domains;
|
||||
const providersById = new Map(this.domainsState.providers.map((p) => [p.id, p]));
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Domains</dees-heading>
|
||||
<div class="domainsContainer">
|
||||
<dees-table
|
||||
.heading1=${'Domains'}
|
||||
.heading2=${'Domains under management — served by dcrouter (authoritative) or imported from a provider'}
|
||||
.data=${domains}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(d: interfaces.data.IDomain) => ({
|
||||
Name: d.name,
|
||||
Source: this.renderSourceBadge(d, providersById),
|
||||
Authoritative: d.authoritative ? 'yes' : 'no',
|
||||
Nameservers: d.nameservers?.join(', ') || '-',
|
||||
'Last Synced': d.lastSyncedAt
|
||||
? new Date(d.lastSyncedAt).toLocaleString()
|
||||
: '-',
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'Add DcRouter Domain',
|
||||
iconName: 'lucide:plus',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.showCreateDcrouterDialog();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Import from Provider',
|
||||
iconName: 'lucide:download',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.showImportDialog();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Refresh',
|
||||
iconName: 'lucide:rotateCw',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.fetchDomainsAndProvidersAction,
|
||||
null,
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'View Records',
|
||||
iconName: 'lucide:list',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const domain = actionData.item as interfaces.data.IDomain;
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.fetchDnsRecordsForDomainAction,
|
||||
{ domainId: domain.id },
|
||||
);
|
||||
appRouter.navigateToView('domains', 'dns');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Sync Now',
|
||||
iconName: 'lucide:rotateCw',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const domain = actionData.item as interfaces.data.IDomain;
|
||||
if (domain.source !== 'provider') {
|
||||
const { DeesToast } = await import('@design.estate/dees-catalog');
|
||||
DeesToast.show({
|
||||
message: 'Sync only applies to provider-managed domains',
|
||||
type: 'warning',
|
||||
duration: 3000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.syncDomainAction, {
|
||||
id: domain.id,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
iconName: 'lucide:trash2',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const domain = actionData.item as interfaces.data.IDomain;
|
||||
await this.deleteDomain(domain);
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderSourceBadge(
|
||||
d: interfaces.data.IDomain,
|
||||
providersById: Map<string, interfaces.data.IDnsProviderPublic>,
|
||||
): TemplateResult {
|
||||
if (d.source === 'dcrouter') {
|
||||
return html`<span class="sourceBadge dcrouter">DcRouter</span>`;
|
||||
}
|
||||
const provider = d.providerId ? providersById.get(d.providerId) : undefined;
|
||||
return html`<span class="sourceBadge provider">${provider?.name || 'Provider'}</span>`;
|
||||
}
|
||||
|
||||
private async showCreateDcrouterDialog() {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
heading: 'Add DcRouter Domain',
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-text .key=${'name'} .label=${'FQDN (e.g. example.com)'} .required=${true}></dees-input-text>
|
||||
<dees-input-text .key=${'description'} .label=${'Description (optional)'}></dees-input-text>
|
||||
</dees-form>
|
||||
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
|
||||
dcrouter will become the authoritative DNS server for this domain. You'll need to
|
||||
delegate the domain's nameservers to dcrouter to make this effective.
|
||||
</p>
|
||||
`,
|
||||
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.domainsStatePart.dispatchAction(appstate.createDcrouterDomainAction, {
|
||||
name: String(data.name),
|
||||
description: data.description ? String(data.description) : undefined,
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async showImportDialog() {
|
||||
const providers = this.domainsState.providers;
|
||||
if (providers.length === 0) {
|
||||
const { DeesToast } = await import('@design.estate/dees-catalog');
|
||||
DeesToast.show({
|
||||
message: 'Add a DNS provider first (Domains > Providers)',
|
||||
type: 'warning',
|
||||
duration: 3500,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
heading: 'Import Domains from Provider',
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-dropdown
|
||||
.key=${'providerId'}
|
||||
.label=${'Provider'}
|
||||
.options=${providers.map((p) => ({ option: p.name, key: p.id }))}
|
||||
.required=${true}
|
||||
></dees-input-dropdown>
|
||||
<dees-input-text
|
||||
.key=${'domainNames'}
|
||||
.label=${'Comma-separated FQDNs to import (e.g. example.com, foo.com)'}
|
||||
.required=${true}
|
||||
></dees-input-text>
|
||||
</dees-form>
|
||||
<p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
|
||||
Tip: use "List Provider Domains" to see what's available before typing.
|
||||
</p>
|
||||
`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'List Provider Domains',
|
||||
action: async (_modalArg: any) => {
|
||||
const form = _modalArg.shadowRoot
|
||||
?.querySelector('.content')
|
||||
?.querySelector('dees-form');
|
||||
if (!form) return;
|
||||
const data = await form.collectFormData();
|
||||
const providerKey = data.providerId?.key ?? data.providerId;
|
||||
if (!providerKey) {
|
||||
DeesToast.show({ message: 'Pick a provider first', type: 'warning', duration: 2500 });
|
||||
return;
|
||||
}
|
||||
const result = await appstate.fetchProviderDomains(String(providerKey));
|
||||
if (!result.success) {
|
||||
DeesToast.show({
|
||||
message: result.message || 'Failed to fetch domains',
|
||||
type: 'error',
|
||||
duration: 4000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const list = (result.domains ?? []).map((d) => d.name).join(', ');
|
||||
DeesToast.show({
|
||||
message: `Provider has: ${list || '(none)'}`,
|
||||
type: 'info',
|
||||
duration: 8000,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Import',
|
||||
action: async (modalArg: any) => {
|
||||
const form = modalArg.shadowRoot
|
||||
?.querySelector('.content')
|
||||
?.querySelector('dees-form');
|
||||
if (!form) return;
|
||||
const data = await form.collectFormData();
|
||||
const providerKey = data.providerId?.key ?? data.providerId;
|
||||
if (!providerKey) {
|
||||
DeesToast.show({ message: 'Pick a provider', type: 'warning', duration: 2500 });
|
||||
return;
|
||||
}
|
||||
const names = String(data.domainNames || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (names.length === 0) {
|
||||
DeesToast.show({ message: 'Enter at least one FQDN', type: 'warning', duration: 2500 });
|
||||
return;
|
||||
}
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.importDomainsFromProviderAction,
|
||||
{ providerId: String(providerKey), domainNames: names },
|
||||
);
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async deleteDomain(domain: interfaces.data.IDomain) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
heading: `Delete domain ${domain.name}?`,
|
||||
content: html`
|
||||
<p>
|
||||
${domain.source === 'provider'
|
||||
? 'This removes the domain and its cached records from dcrouter only. The zone at the provider is NOT touched.'
|
||||
: 'This removes the domain and all of its DNS records from dcrouter. dcrouter will no longer answer queries for this domain after the next restart.'}
|
||||
</p>
|
||||
`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'Delete',
|
||||
action: async (modalArg: any) => {
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.deleteDomainAction, {
|
||||
id: domain.id,
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
298
ts_web/elements/domains/ops-view-providers.ts
Normal file
298
ts_web/elements/domains/ops-view-providers.ts
Normal file
@@ -0,0 +1,298 @@
|
||||
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 './dns-provider-form.js';
|
||||
import type { DnsProviderForm } from './dns-provider-form.js';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-providers': OpsViewProviders;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-providers')
|
||||
export class OpsViewProviders extends DeesElement {
|
||||
@state()
|
||||
accessor domainsState: appstate.IDomainsState = appstate.domainsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.domainsStatePart.select().subscribe((newState) => {
|
||||
this.domainsState = newState;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
async connectedCallback() {
|
||||
await super.connectedCallback();
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
.providersContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.statusBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.statusBadge.ok {
|
||||
background: ${cssManager.bdTheme('#dcfce7', '#14532d')};
|
||||
color: ${cssManager.bdTheme('#166534', '#4ade80')};
|
||||
}
|
||||
|
||||
.statusBadge.error {
|
||||
background: ${cssManager.bdTheme('#fef2f2', '#450a0a')};
|
||||
color: ${cssManager.bdTheme('#991b1b', '#f87171')};
|
||||
}
|
||||
|
||||
.statusBadge.untested {
|
||||
background: ${cssManager.bdTheme('#f3f4f6', '#1f2937')};
|
||||
color: ${cssManager.bdTheme('#4b5563', '#9ca3af')};
|
||||
}
|
||||
|
||||
.statusBadge.builtin {
|
||||
background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
|
||||
color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const providers = this.domainsState.providers;
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">DNS Providers</dees-heading>
|
||||
<div class="providersContainer">
|
||||
<dees-table
|
||||
.heading1=${'Providers'}
|
||||
.heading2=${'Built-in dcrouter + external DNS provider accounts'}
|
||||
.data=${providers}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(p: interfaces.data.IDnsProviderPublic) => ({
|
||||
Name: p.name,
|
||||
Type: this.providerTypeLabel(p.type),
|
||||
Status: p.builtIn
|
||||
? html`<span class="statusBadge builtin">built-in</span>`
|
||||
: this.renderStatusBadge(p.status),
|
||||
'Last Tested': p.builtIn
|
||||
? '—'
|
||||
: p.lastTestedAt
|
||||
? new Date(p.lastTestedAt).toLocaleString()
|
||||
: 'never',
|
||||
Error: p.builtIn ? '—' : p.lastError || '-',
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'Add Provider',
|
||||
iconName: 'lucide:plus',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.showCreateDialog();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Refresh',
|
||||
iconName: 'lucide:rotateCw',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await appstate.domainsStatePart.dispatchAction(
|
||||
appstate.fetchDomainsAndProvidersAction,
|
||||
null,
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Test Connection',
|
||||
iconName: 'lucide:plug',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
|
||||
await this.testProvider(provider);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Edit',
|
||||
iconName: 'lucide:pencil',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
|
||||
await this.showEditDialog(provider);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
iconName: 'lucide:trash2',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionRelevancyCheckFunc: (p: interfaces.data.IDnsProviderPublic) => !p.builtIn,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const provider = actionData.item as interfaces.data.IDnsProviderPublic;
|
||||
await this.deleteProvider(provider);
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderStatusBadge(status: interfaces.data.TDnsProviderStatus): TemplateResult {
|
||||
return html`<span class="statusBadge ${status}">${status}</span>`;
|
||||
}
|
||||
|
||||
private providerTypeLabel(type: interfaces.data.TDnsProviderType): string {
|
||||
return interfaces.data.getDnsProviderTypeDescriptor(type)?.displayName ?? type;
|
||||
}
|
||||
|
||||
private async showCreateDialog() {
|
||||
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
|
||||
const formEl = document.createElement('dns-provider-form') as DnsProviderForm;
|
||||
DeesModal.createAndShow({
|
||||
heading: 'Add DNS Provider',
|
||||
content: html`${formEl}`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'Create',
|
||||
action: async (modalArg: any) => {
|
||||
const data = await formEl.collectData();
|
||||
if (!data) return;
|
||||
if (!data.name) {
|
||||
DeesToast.show({ message: 'Name is required', type: 'warning', duration: 2500 });
|
||||
return;
|
||||
}
|
||||
if (!data.credentialsTouched) {
|
||||
DeesToast.show({
|
||||
message: 'Fill in the provider credentials',
|
||||
type: 'warning',
|
||||
duration: 2500,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.createDnsProviderAction, {
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
credentials: data.credentials,
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async showEditDialog(provider: interfaces.data.IDnsProviderPublic) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
const formEl = document.createElement('dns-provider-form') as DnsProviderForm;
|
||||
formEl.providerName = provider.name;
|
||||
formEl.selectedType = provider.type;
|
||||
formEl.lockType = true;
|
||||
formEl.credentialsHint =
|
||||
'Leave credential fields blank to keep the current values. Fill them to rotate.';
|
||||
DeesModal.createAndShow({
|
||||
heading: `Edit Provider: ${provider.name}`,
|
||||
content: html`${formEl}`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'Save',
|
||||
action: async (modalArg: any) => {
|
||||
const data = await formEl.collectData();
|
||||
if (!data) return;
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.updateDnsProviderAction, {
|
||||
id: provider.id,
|
||||
name: data.name || provider.name,
|
||||
// Only send credentials if the user actually entered something —
|
||||
// otherwise we keep the current secret untouched.
|
||||
credentials: data.credentialsTouched ? data.credentials : undefined,
|
||||
});
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async testProvider(provider: interfaces.data.IDnsProviderPublic) {
|
||||
const { DeesToast } = await import('@design.estate/dees-catalog');
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.testDnsProviderAction, {
|
||||
id: provider.id,
|
||||
});
|
||||
const updated = appstate.domainsStatePart
|
||||
.getState()!
|
||||
.providers.find((p) => p.id === provider.id);
|
||||
if (updated?.status === 'ok') {
|
||||
DeesToast.show({
|
||||
message: `${provider.name}: connection OK`,
|
||||
type: 'success',
|
||||
duration: 3000,
|
||||
});
|
||||
} else {
|
||||
DeesToast.show({
|
||||
message: `${provider.name}: ${updated?.lastError || 'connection failed'}`,
|
||||
type: 'error',
|
||||
duration: 4000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteProvider(provider: interfaces.data.IDnsProviderPublic) {
|
||||
const linkedDomains = this.domainsState.domains.filter((d) => d.providerId === provider.id);
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
|
||||
const doDelete = async (force: boolean) => {
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.deleteDnsProviderAction, {
|
||||
id: provider.id,
|
||||
force,
|
||||
});
|
||||
};
|
||||
|
||||
if (linkedDomains.length > 0) {
|
||||
DeesModal.createAndShow({
|
||||
heading: `Provider in use`,
|
||||
content: html`
|
||||
<p>
|
||||
Provider <strong>${provider.name}</strong> is referenced by ${linkedDomains.length}
|
||||
domain(s). Deleting will also remove the imported domain(s) and their cached
|
||||
records (the records at ${provider.type} are NOT touched).
|
||||
</p>
|
||||
`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (modalArg: any) => modalArg.destroy() },
|
||||
{
|
||||
name: 'Force Delete',
|
||||
action: async (modalArg: any) => {
|
||||
await doDelete(true);
|
||||
modalArg.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
} else {
|
||||
await doDelete(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
ts_web/elements/email/index.ts
Normal file
2
ts_web/elements/email/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './ops-view-emails.js';
|
||||
export * from './ops-view-email-security.js';
|
||||
160
ts_web/elements/email/ops-view-email-security.ts
Normal file
160
ts_web/elements/email/ops-view-email-security.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
import { type IStatsTile } from '@design.estate/dees-catalog';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-email-security': OpsViewEmailSecurity;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-email-security')
|
||||
export class OpsViewEmailSecurity extends DeesElement {
|
||||
@state()
|
||||
accessor statsState: appstate.IStatsState = appstate.statsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.statsStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((s) => {
|
||||
this.statsState = s;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
h2 {
|
||||
margin: 32px 0 16px 0;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: ${cssManager.bdTheme('#333', '#ccc')};
|
||||
}
|
||||
dees-statsgrid {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.securityCard {
|
||||
background: ${cssManager.bdTheme('#fff', '#222')};
|
||||
border: 1px solid ${cssManager.bdTheme('#e9ecef', '#333')};
|
||||
border-radius: 8px;
|
||||
padding: 24px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.actionButton {
|
||||
margin-top: 16px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const metrics = this.statsState.securityMetrics;
|
||||
|
||||
if (!metrics) {
|
||||
return html`
|
||||
<div class="loadingMessage">
|
||||
<p>Loading security metrics...</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'malware',
|
||||
title: 'Malware Detection',
|
||||
value: metrics.malwareDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:BugOff',
|
||||
color: metrics.malwareDetected > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Malware detected',
|
||||
},
|
||||
{
|
||||
id: 'phishing',
|
||||
title: 'Phishing Detection',
|
||||
value: metrics.phishingDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:Fish',
|
||||
color: metrics.phishingDetected > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Phishing attempts detected',
|
||||
},
|
||||
{
|
||||
id: 'suspicious',
|
||||
title: 'Suspicious Activities',
|
||||
value: metrics.suspiciousActivities,
|
||||
type: 'number',
|
||||
icon: 'lucide:TriangleAlert',
|
||||
color: metrics.suspiciousActivities > 5 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Suspicious activities detected',
|
||||
},
|
||||
{
|
||||
id: 'spam',
|
||||
title: 'Spam Detection',
|
||||
value: metrics.spamDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:Ban',
|
||||
color: '#f59e0b',
|
||||
description: 'Spam emails blocked',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Email Security</dees-heading>
|
||||
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Email Security Configuration</h2>
|
||||
<div class="securityCard">
|
||||
<dees-form>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableSPF'}
|
||||
.label=${'Enable SPF checking'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableDKIM'}
|
||||
.label=${'Enable DKIM validation'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableDMARC'}
|
||||
.label=${'Enable DMARC policy enforcement'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableSpamFilter'}
|
||||
.label=${'Enable spam filtering'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
</dees-form>
|
||||
<dees-button
|
||||
class="actionButton"
|
||||
type="highlighted"
|
||||
@click=${() => this.saveEmailSecuritySettings()}
|
||||
>
|
||||
Save Settings
|
||||
</dees-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private async saveEmailSecuritySettings() {
|
||||
// Config is read-only from the UI for now
|
||||
alert('Email security settings are read-only. Update the dcrouter configuration file to change these settings.');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { DeesElement, property, html, customElement, type TemplateResult, css, state, cssManager } from '@design.estate/dees-element';
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as shared from './shared/index.js';
|
||||
import * as interfaces from '../../dist_ts_interfaces/index.js';
|
||||
import * as plugins from '../../plugins.js';
|
||||
import * as appstate from '../../appstate.js';
|
||||
import * as shared from '../shared/index.js';
|
||||
import * as interfaces from '../../../dist_ts_interfaces/index.js';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
@@ -60,7 +60,7 @@ export class OpsViewEmails extends DeesElement {
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Email Operations</dees-heading>
|
||||
<dees-heading level="3">Email Log</dees-heading>
|
||||
<div class="viewContainer">
|
||||
${this.currentView === 'detail' && this.selectedEmail
|
||||
? html`
|
||||
@@ -1,16 +1,9 @@
|
||||
export * from './ops-dashboard.js';
|
||||
export * from './ops-view-overview.js';
|
||||
export * from './ops-view-network.js';
|
||||
export * from './ops-view-emails.js';
|
||||
export * from './overview/index.js';
|
||||
export * from './network/index.js';
|
||||
export * from './email/index.js';
|
||||
export * from './ops-view-logs.js';
|
||||
export * from './ops-view-config.js';
|
||||
export * from './ops-view-routes.js';
|
||||
export * from './ops-view-apitokens.js';
|
||||
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-sourceprofiles.js';
|
||||
export * from './ops-view-networktargets.js';
|
||||
export * from './ops-view-targetprofiles.js';
|
||||
export * from './shared/index.js';
|
||||
export * from './access/index.js';
|
||||
export * from './security/index.js';
|
||||
export * from './domains/index.js';
|
||||
export * from './shared/index.js';
|
||||
|
||||
7
ts_web/elements/network/index.ts
Normal file
7
ts_web/elements/network/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './ops-view-network-activity.js';
|
||||
export * from './ops-view-routes.js';
|
||||
export * from './ops-view-sourceprofiles.js';
|
||||
export * from './ops-view-networktargets.js';
|
||||
export * from './ops-view-targetprofiles.js';
|
||||
export * from './ops-view-remoteingress.js';
|
||||
export * from './ops-view-vpn.js';
|
||||
@@ -1,12 +1,12 @@
|
||||
import { DeesElement, property, 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 * 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-network': OpsViewNetwork;
|
||||
'ops-view-network-activity': OpsViewNetworkActivity;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,14 +26,14 @@ interface INetworkRequest {
|
||||
route?: string;
|
||||
}
|
||||
|
||||
@customElement('ops-view-network')
|
||||
export class OpsViewNetwork extends DeesElement {
|
||||
@customElement('ops-view-network-activity')
|
||||
export class OpsViewNetworkActivity 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;
|
||||
private static readonly MAX_DATA_POINTS = OpsViewNetworkActivity.CHART_WINDOW_MS / OpsViewNetworkActivity.UPDATE_INTERVAL_MS;
|
||||
|
||||
@state()
|
||||
accessor statsState = appstate.statsStatePart.getState()!;
|
||||
@@ -50,10 +50,10 @@ export class OpsViewNetwork extends DeesElement {
|
||||
|
||||
@state()
|
||||
accessor trafficDataOut: Array<{ x: string | number; y: number }> = [];
|
||||
|
||||
|
||||
// Track if we need to update the chart to avoid unnecessary re-renders
|
||||
private lastChartUpdate = 0;
|
||||
private chartUpdateThreshold = OpsViewNetwork.UPDATE_INTERVAL_MS; // Minimum ms between chart updates
|
||||
private chartUpdateThreshold = OpsViewNetworkActivity.UPDATE_INTERVAL_MS; // Minimum ms between chart updates
|
||||
|
||||
private trafficUpdateTimer: any = null;
|
||||
private requestsPerSecHistory: number[] = []; // Track requests/sec over time for trend
|
||||
@@ -101,17 +101,17 @@ export class OpsViewNetwork extends DeesElement {
|
||||
this.updateNetworkData();
|
||||
});
|
||||
this.rxSubscriptions.push(statsUnsubscribe);
|
||||
|
||||
|
||||
const networkUnsubscribe = appstate.networkStatePart.select().subscribe((state) => {
|
||||
this.networkState = state;
|
||||
this.updateNetworkData();
|
||||
});
|
||||
this.rxSubscriptions.push(networkUnsubscribe);
|
||||
}
|
||||
|
||||
|
||||
private initializeTrafficData() {
|
||||
const now = Date.now();
|
||||
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetwork;
|
||||
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetworkActivity;
|
||||
|
||||
// Initialize with empty data points for both in and out
|
||||
const emptyData = Array.from({ length: MAX_DATA_POINTS }, (_, i) => {
|
||||
@@ -148,7 +148,7 @@ export class OpsViewNetwork extends DeesElement {
|
||||
y: Math.round((p.out * 8) / 1000000 * 10) / 10,
|
||||
}));
|
||||
|
||||
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetwork;
|
||||
const { MAX_DATA_POINTS, UPDATE_INTERVAL_MS } = OpsViewNetworkActivity;
|
||||
|
||||
// Use history as the chart data, keeping the most recent points within the window
|
||||
const sliceStart = Math.max(0, historyIn.length - MAX_DATA_POINTS);
|
||||
@@ -285,8 +285,8 @@ export class OpsViewNetwork extends DeesElement {
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Network Activity</dees-heading>
|
||||
|
||||
<dees-heading level="3">Network Activity</dees-heading>
|
||||
|
||||
<div class="networkContainer">
|
||||
<!-- Stats Grid -->
|
||||
${this.renderNetworkStats()}
|
||||
@@ -307,7 +307,7 @@ export class OpsViewNetwork extends DeesElement {
|
||||
}
|
||||
]}
|
||||
.realtimeMode=${true}
|
||||
.rollingWindow=${OpsViewNetwork.CHART_WINDOW_MS}
|
||||
.rollingWindow=${OpsViewNetworkActivity.CHART_WINDOW_MS}
|
||||
.yAxisFormatter=${(val: number) => `${val} Mbit/s`}
|
||||
></dees-chart-area>
|
||||
|
||||
@@ -347,6 +347,7 @@ export class OpsViewNetwork extends DeesElement {
|
||||
heading1="Recent Network Activity"
|
||||
heading2="Recent network requests"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${true}
|
||||
.paginationSize=${50}
|
||||
dataName="request"
|
||||
@@ -357,7 +358,7 @@ export class OpsViewNetwork extends DeesElement {
|
||||
|
||||
private async showRequestDetails(request: INetworkRequest) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
|
||||
|
||||
await DeesModal.createAndShow({
|
||||
heading: 'Request Details',
|
||||
content: html`
|
||||
@@ -400,10 +401,10 @@ export class OpsViewNetwork extends DeesElement {
|
||||
if (!statusCode) {
|
||||
return html`<span class="statusBadge warning">N/A</span>`;
|
||||
}
|
||||
|
||||
|
||||
const statusClass = statusCode >= 200 && statusCode < 300 ? 'success' :
|
||||
statusCode >= 400 ? 'error' : 'warning';
|
||||
|
||||
|
||||
return html`<span class="statusBadge ${statusClass}">${statusCode}</span>`;
|
||||
}
|
||||
|
||||
@@ -426,26 +427,26 @@ export class OpsViewNetwork extends DeesElement {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
|
||||
return `${size.toFixed(1)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
|
||||
private formatBitsPerSecond(bytesPerSecond: number): string {
|
||||
const bitsPerSecond = bytesPerSecond * 8; // Convert bytes to bits
|
||||
const units = ['bit/s', 'kbit/s', 'Mbit/s', 'Gbit/s'];
|
||||
let size = bitsPerSecond;
|
||||
let unitIndex = 0;
|
||||
|
||||
|
||||
while (size >= 1000 && unitIndex < units.length - 1) {
|
||||
size /= 1000; // Use 1000 for bits (not 1024)
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
|
||||
return `${size.toFixed(1)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
@@ -520,18 +521,9 @@ export class OpsViewNetwork extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-statsgrid
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
.gridActions=${[
|
||||
{
|
||||
name: 'Export Data',
|
||||
iconName: 'lucide:FileOutput',
|
||||
action: async () => {
|
||||
console.log('Export feature coming soon');
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-statsgrid>
|
||||
`;
|
||||
}
|
||||
@@ -615,6 +607,8 @@ export class OpsViewNetwork extends DeesElement {
|
||||
}}
|
||||
heading1="Top Connected IPs"
|
||||
heading2="IPs with most active connections and bandwidth"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${false}
|
||||
dataName="ip"
|
||||
></dees-table>
|
||||
@@ -665,6 +659,7 @@ export class OpsViewNetwork extends DeesElement {
|
||||
heading1="Backend Protocols"
|
||||
heading2="Auto-detected backend protocols and connection pool health"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${false}
|
||||
dataName="backend"
|
||||
></dees-table>
|
||||
@@ -732,12 +727,12 @@ export class OpsViewNetwork extends DeesElement {
|
||||
// Only update if connections changed significantly
|
||||
const newConnectionCount = this.networkState.connections.length;
|
||||
const oldConnectionCount = this.networkRequests.length;
|
||||
|
||||
|
||||
// Check if we need to update the network requests array
|
||||
const shouldUpdate = newConnectionCount !== oldConnectionCount ||
|
||||
const shouldUpdate = newConnectionCount !== oldConnectionCount ||
|
||||
newConnectionCount === 0 ||
|
||||
(newConnectionCount > 0 && this.networkRequests.length === 0);
|
||||
|
||||
|
||||
if (shouldUpdate) {
|
||||
// Convert connection data to network requests format
|
||||
if (newConnectionCount > 0) {
|
||||
@@ -760,62 +755,62 @@ export class OpsViewNetwork extends DeesElement {
|
||||
this.networkRequests = [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Load server-side throughput history into chart (once)
|
||||
if (!this.historyLoaded && this.networkState.throughputHistory && this.networkState.throughputHistory.length > 0) {
|
||||
this.loadThroughputHistory();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private startTrafficUpdateTimer() {
|
||||
this.stopTrafficUpdateTimer(); // Clear any existing timer
|
||||
this.trafficUpdateTimer = setInterval(() => {
|
||||
this.addTrafficDataPoint();
|
||||
}, OpsViewNetwork.UPDATE_INTERVAL_MS);
|
||||
}, OpsViewNetworkActivity.UPDATE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
|
||||
private addTrafficDataPoint() {
|
||||
const now = Date.now();
|
||||
|
||||
|
||||
// Throttle chart updates to avoid excessive re-renders
|
||||
if (now - this.lastChartUpdate < this.chartUpdateThreshold) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const throughput = this.calculateThroughput();
|
||||
|
||||
|
||||
// Convert to Mbps (bytes * 8 / 1,000,000)
|
||||
const throughputInMbps = (throughput.in * 8) / 1000000;
|
||||
const throughputOutMbps = (throughput.out * 8) / 1000000;
|
||||
|
||||
|
||||
// Add new data points
|
||||
const timestamp = new Date(now).toISOString();
|
||||
|
||||
|
||||
const newDataPointIn = {
|
||||
x: timestamp,
|
||||
y: Math.round(throughputInMbps * 10) / 10
|
||||
};
|
||||
|
||||
|
||||
const newDataPointOut = {
|
||||
x: timestamp,
|
||||
y: Math.round(throughputOutMbps * 10) / 10
|
||||
};
|
||||
|
||||
|
||||
// In-place mutation then reassign for Lit reactivity (avoids 4 intermediate arrays)
|
||||
if (this.trafficDataIn.length >= OpsViewNetwork.MAX_DATA_POINTS) {
|
||||
if (this.trafficDataIn.length >= OpsViewNetworkActivity.MAX_DATA_POINTS) {
|
||||
this.trafficDataIn.shift();
|
||||
this.trafficDataOut.shift();
|
||||
}
|
||||
this.trafficDataIn = [...this.trafficDataIn, newDataPointIn];
|
||||
this.trafficDataOut = [...this.trafficDataOut, newDataPointOut];
|
||||
|
||||
|
||||
this.lastChartUpdate = now;
|
||||
}
|
||||
|
||||
|
||||
private stopTrafficUpdateTimer() {
|
||||
if (this.trafficUpdateTimer) {
|
||||
clearInterval(this.trafficUpdateTimer);
|
||||
this.trafficUpdateTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
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 * 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 {
|
||||
@@ -64,13 +64,14 @@ export class OpsViewNetworkTargets extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Network Targets</dees-heading>
|
||||
<dees-heading level="3">Network Targets</dees-heading>
|
||||
<div class="targetsContainer">
|
||||
<dees-statsgrid .tiles=${statsTiles}></dees-statsgrid>
|
||||
<dees-table
|
||||
.heading1=${'Network Targets'}
|
||||
.heading2=${'Reusable host:port destinations for routes'}
|
||||
.data=${targets}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(target: interfaces.data.INetworkTarget) => ({
|
||||
Name: target.name,
|
||||
Host: Array.isArray(target.host) ? target.host.join(', ') : target.host,
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
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 * 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 {
|
||||
@@ -174,7 +174,7 @@ export class OpsViewRemoteIngress extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Remote Ingress</dees-heading>
|
||||
<dees-heading level="3">Remote Ingress</dees-heading>
|
||||
|
||||
${this.riState.newEdgeId ? html`
|
||||
<div class="secretDialog">
|
||||
@@ -220,6 +220,7 @@ export class OpsViewRemoteIngress extends DeesElement {
|
||||
.heading1=${'Edge Nodes'}
|
||||
.heading2=${'Manage remote ingress edge registrations'}
|
||||
.data=${this.riState.edges}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(edge: interfaces.data.IRemoteIngress) => ({
|
||||
name: edge.name,
|
||||
status: this.getEdgeStatusHtml(edge),
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as interfaces from '../../dist_ts_interfaces/index.js';
|
||||
import { viewHostCss } from './shared/css.js';
|
||||
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';
|
||||
|
||||
import {
|
||||
@@ -200,7 +200,7 @@ export class OpsViewRoutes extends DeesElement {
|
||||
});
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Route Management</dees-heading>
|
||||
<dees-heading level="3">Route Management</dees-heading>
|
||||
|
||||
<div class="routesContainer">
|
||||
<dees-statsgrid
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
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 * 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 {
|
||||
@@ -64,13 +64,14 @@ export class OpsViewSourceProfiles extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Source Profiles</dees-heading>
|
||||
<dees-heading level="3">Source Profiles</dees-heading>
|
||||
<div class="profilesContainer">
|
||||
<dees-statsgrid .tiles=${statsTiles}></dees-statsgrid>
|
||||
<dees-table
|
||||
.heading1=${'Source Profiles'}
|
||||
.heading2=${'Reusable source configurations for routes'}
|
||||
.data=${profiles}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(profile: interfaces.data.ISourceProfile) => ({
|
||||
Name: profile.name,
|
||||
Description: profile.description || '-',
|
||||
@@ -7,10 +7,10 @@ import {
|
||||
state,
|
||||
cssManager,
|
||||
} from '@design.estate/dees-element';
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as interfaces from '../../dist_ts_interfaces/index.js';
|
||||
import { viewHostCss } from './shared/css.js';
|
||||
import * as plugins from '../../plugins.js';
|
||||
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 {
|
||||
@@ -77,13 +77,14 @@ export class OpsViewTargetProfiles extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">Target Profiles</dees-heading>
|
||||
<dees-heading level="3">Target Profiles</dees-heading>
|
||||
<div class="profilesContainer">
|
||||
<dees-statsgrid .tiles=${statsTiles}></dees-statsgrid>
|
||||
<dees-table
|
||||
.heading1=${'Target Profiles'}
|
||||
.heading2=${'Define what resources VPN clients can access'}
|
||||
.data=${profiles}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(profile: interfaces.data.ITargetProfile) => ({
|
||||
Name: profile.name,
|
||||
Description: profile.description || '-',
|
||||
@@ -7,10 +7,10 @@ import {
|
||||
state,
|
||||
cssManager,
|
||||
} from '@design.estate/dees-element';
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as interfaces from '../../dist_ts_interfaces/index.js';
|
||||
import { viewHostCss } from './shared/css.js';
|
||||
import * as plugins from '../../plugins.js';
|
||||
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';
|
||||
|
||||
/**
|
||||
@@ -223,7 +223,7 @@ export class OpsViewVpn extends DeesElement {
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="2">VPN</dees-heading>
|
||||
<dees-heading level="3">VPN</dees-heading>
|
||||
<div class="vpnContainer">
|
||||
|
||||
${this.vpnState.newClientConfig ? html`
|
||||
@@ -305,6 +305,7 @@ export class OpsViewVpn extends DeesElement {
|
||||
.heading1=${'VPN Clients'}
|
||||
.heading2=${'Manage WireGuard and SmartVPN client registrations'}
|
||||
.data=${clients}
|
||||
.showColumnFilters=${true}
|
||||
.displayFunction=${(client: interfaces.data.IVpnClient) => {
|
||||
const conn = this.getConnectedInfo(client);
|
||||
let statusHtml;
|
||||
@@ -11,22 +11,51 @@ import {
|
||||
state,
|
||||
type TemplateResult
|
||||
} from '@design.estate/dees-element';
|
||||
import type { IView } from '@design.estate/dees-catalog';
|
||||
|
||||
// Import view components
|
||||
import { OpsViewOverview } from './ops-view-overview.js';
|
||||
import { OpsViewNetwork } from './ops-view-network.js';
|
||||
import { OpsViewEmails } from './ops-view-emails.js';
|
||||
// Top-level / flat views
|
||||
import { OpsViewLogs } from './ops-view-logs.js';
|
||||
import { OpsViewConfig } from './ops-view-config.js';
|
||||
import { OpsViewRoutes } from './ops-view-routes.js';
|
||||
import { OpsViewApiTokens } from './ops-view-apitokens.js';
|
||||
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 { OpsViewSourceProfiles } from './ops-view-sourceprofiles.js';
|
||||
import { OpsViewNetworkTargets } from './ops-view-networktargets.js';
|
||||
import { OpsViewTargetProfiles } from './ops-view-targetprofiles.js';
|
||||
|
||||
// Overview group
|
||||
import { OpsViewOverview } from './overview/ops-view-overview.js';
|
||||
import { OpsViewConfig } from './overview/ops-view-config.js';
|
||||
|
||||
// Network group
|
||||
import { OpsViewNetworkActivity } from './network/ops-view-network-activity.js';
|
||||
import { OpsViewRoutes } from './network/ops-view-routes.js';
|
||||
import { OpsViewSourceProfiles } from './network/ops-view-sourceprofiles.js';
|
||||
import { OpsViewNetworkTargets } from './network/ops-view-networktargets.js';
|
||||
import { OpsViewTargetProfiles } from './network/ops-view-targetprofiles.js';
|
||||
import { OpsViewRemoteIngress } from './network/ops-view-remoteingress.js';
|
||||
import { OpsViewVpn } from './network/ops-view-vpn.js';
|
||||
|
||||
// Email group
|
||||
import { OpsViewEmails } from './email/ops-view-emails.js';
|
||||
import { OpsViewEmailSecurity } from './email/ops-view-email-security.js';
|
||||
|
||||
// Access group
|
||||
import { OpsViewApiTokens } from './access/ops-view-apitokens.js';
|
||||
import { OpsViewUsers } from './access/ops-view-users.js';
|
||||
|
||||
// Security group
|
||||
import { OpsViewSecurityOverview } from './security/ops-view-security-overview.js';
|
||||
import { OpsViewSecurityBlocked } from './security/ops-view-security-blocked.js';
|
||||
import { OpsViewSecurityAuthentication } from './security/ops-view-security-authentication.js';
|
||||
|
||||
// Domains group
|
||||
import { OpsViewProviders } from './domains/ops-view-providers.js';
|
||||
import { OpsViewDomains } from './domains/ops-view-domains.js';
|
||||
import { OpsViewDns } from './domains/ops-view-dns.js';
|
||||
import { OpsViewCertificates } from './domains/ops-view-certificates.js';
|
||||
|
||||
/**
|
||||
* Extended IView with explicit URL slug. Without an explicit `slug`, the URL
|
||||
* slug is derived from `name.toLowerCase().replace(/\s+/g, '')`.
|
||||
*/
|
||||
interface ITabbedView extends IView {
|
||||
slug?: string;
|
||||
subViews?: ITabbedView[];
|
||||
}
|
||||
|
||||
@customElement('ops-dashboard')
|
||||
export class OpsDashboard extends DeesElement {
|
||||
@@ -37,6 +66,7 @@ export class OpsDashboard extends DeesElement {
|
||||
|
||||
@state() accessor uiState: appstate.IUiState = {
|
||||
activeView: 'overview',
|
||||
activeSubview: null,
|
||||
sidebarCollapsed: false,
|
||||
autoRefresh: true,
|
||||
refreshInterval: 1000,
|
||||
@@ -49,27 +79,36 @@ export class OpsDashboard extends DeesElement {
|
||||
error: null,
|
||||
};
|
||||
|
||||
// Store viewTabs as a property to maintain object references
|
||||
private viewTabs = [
|
||||
// Store viewTabs as a property to maintain object references (used for === selectedView identity)
|
||||
private viewTabs: ITabbedView[] = [
|
||||
{
|
||||
name: 'Overview',
|
||||
iconName: 'lucide:layoutDashboard',
|
||||
element: OpsViewOverview,
|
||||
},
|
||||
{
|
||||
name: 'Configuration',
|
||||
iconName: 'lucide:settings',
|
||||
element: OpsViewConfig,
|
||||
subViews: [
|
||||
{ slug: 'stats', name: 'Stats', iconName: 'lucide:activity', element: OpsViewOverview },
|
||||
{ slug: 'configuration', name: 'Configuration', iconName: 'lucide:settings', element: OpsViewConfig },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Network',
|
||||
iconName: 'lucide:network',
|
||||
element: OpsViewNetwork,
|
||||
subViews: [
|
||||
{ slug: 'activity', name: 'Network Activity', iconName: 'lucide:activity', element: OpsViewNetworkActivity },
|
||||
{ slug: 'routes', name: 'Routes', iconName: 'lucide:route', element: OpsViewRoutes },
|
||||
{ slug: 'sourceprofiles', name: 'Source Profiles', iconName: 'lucide:shieldCheck', element: OpsViewSourceProfiles },
|
||||
{ slug: 'networktargets', name: 'Network Targets', iconName: 'lucide:server', element: OpsViewNetworkTargets },
|
||||
{ slug: 'targetprofiles', name: 'Target Profiles', iconName: 'lucide:target', element: OpsViewTargetProfiles },
|
||||
{ slug: 'remoteingress', name: 'Remote Ingress', iconName: 'lucide:globe', element: OpsViewRemoteIngress },
|
||||
{ slug: 'vpn', name: 'VPN', iconName: 'lucide:shield', element: OpsViewVpn },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Emails',
|
||||
name: 'Email',
|
||||
iconName: 'lucide:mail',
|
||||
element: OpsViewEmails,
|
||||
subViews: [
|
||||
{ slug: 'log', name: 'Email Log', iconName: 'lucide:scrollText', element: OpsViewEmails },
|
||||
{ slug: 'security', name: 'Email Security', iconName: 'lucide:shieldCheck', element: OpsViewEmailSecurity },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Logs',
|
||||
@@ -77,52 +116,54 @@ export class OpsDashboard extends DeesElement {
|
||||
element: OpsViewLogs,
|
||||
},
|
||||
{
|
||||
name: 'Routes',
|
||||
iconName: 'lucide:route',
|
||||
element: OpsViewRoutes,
|
||||
},
|
||||
{
|
||||
name: 'SourceProfiles',
|
||||
iconName: 'lucide:shieldCheck',
|
||||
element: OpsViewSourceProfiles,
|
||||
},
|
||||
{
|
||||
name: 'NetworkTargets',
|
||||
iconName: 'lucide:server',
|
||||
element: OpsViewNetworkTargets,
|
||||
},
|
||||
{
|
||||
name: 'TargetProfiles',
|
||||
iconName: 'lucide:target',
|
||||
element: OpsViewTargetProfiles,
|
||||
},
|
||||
{
|
||||
name: 'ApiTokens',
|
||||
iconName: 'lucide:key',
|
||||
element: OpsViewApiTokens,
|
||||
name: 'Access',
|
||||
iconName: 'lucide:keyRound',
|
||||
subViews: [
|
||||
{ slug: 'apitokens', name: 'API Tokens', iconName: 'lucide:key', element: OpsViewApiTokens },
|
||||
{ slug: 'users', name: 'Users', iconName: 'lucide:users', element: OpsViewUsers },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Security',
|
||||
iconName: 'lucide:shield',
|
||||
element: OpsViewSecurity,
|
||||
subViews: [
|
||||
{ slug: 'overview', name: 'Overview', iconName: 'lucide:eye', element: OpsViewSecurityOverview },
|
||||
{ slug: 'blocked', name: 'Blocked IPs', iconName: 'lucide:shieldBan', element: OpsViewSecurityBlocked },
|
||||
{ slug: 'authentication', name: 'Authentication', iconName: 'lucide:lock', element: OpsViewSecurityAuthentication },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Certificates',
|
||||
iconName: 'lucide:badgeCheck',
|
||||
element: OpsViewCertificates,
|
||||
},
|
||||
{
|
||||
name: 'RemoteIngress',
|
||||
name: 'Domains',
|
||||
iconName: 'lucide:globe',
|
||||
element: OpsViewRemoteIngress,
|
||||
},
|
||||
{
|
||||
name: 'VPN',
|
||||
iconName: 'lucide:shield',
|
||||
element: OpsViewVpn,
|
||||
subViews: [
|
||||
{ slug: 'providers', name: 'Providers', iconName: 'lucide:plug', element: OpsViewProviders },
|
||||
{ slug: 'domains', name: 'Domains', iconName: 'lucide:globe', element: OpsViewDomains },
|
||||
{ slug: 'dns', name: 'DNS', iconName: 'lucide:list', element: OpsViewDns },
|
||||
{ slug: 'certificates', name: 'Certificates', iconName: 'lucide:badgeCheck', element: OpsViewCertificates },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** URL slug for a view (explicit `slug` field, or lowercased name with spaces stripped). */
|
||||
private slugFor(view: ITabbedView): string {
|
||||
return view.slug ?? view.name.toLowerCase().replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
/** Find the parent group of a subview, or undefined for top-level views. */
|
||||
private findParent(view: ITabbedView): ITabbedView | undefined {
|
||||
return this.viewTabs.find((v) => v.subViews?.includes(view));
|
||||
}
|
||||
|
||||
/** Look up a view (or subview) by its URL slug pair. */
|
||||
private findViewBySlug(viewSlug: string, subSlug: string | null): ITabbedView | undefined {
|
||||
const top = this.viewTabs.find((v) => this.slugFor(v) === viewSlug);
|
||||
if (!top) return undefined;
|
||||
if (subSlug && top.subViews) {
|
||||
return top.subViews.find((sv) => this.slugFor(sv) === subSlug) ?? top;
|
||||
}
|
||||
return top;
|
||||
}
|
||||
|
||||
private get globalMessages() {
|
||||
const messages: Array<{ id: string; type: string; message: string; dismissible?: boolean }> = [];
|
||||
const config = this.configState.config;
|
||||
@@ -138,17 +179,19 @@ export class OpsDashboard extends DeesElement {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current view tab based on the UI state's activeView.
|
||||
* Get the current view tab based on the UI state's activeView/activeSubview.
|
||||
* Used to pass the correct selectedView to dees-simple-appdash on initial render.
|
||||
*/
|
||||
private get currentViewTab() {
|
||||
return this.viewTabs.find(t => t.name.toLowerCase() === this.uiState.activeView) || this.viewTabs[0];
|
||||
private get currentViewTab(): ITabbedView {
|
||||
return (
|
||||
this.findViewBySlug(this.uiState.activeView, this.uiState.activeSubview) ?? this.viewTabs[0]
|
||||
);
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
document.title = 'DCRouter OpsServer';
|
||||
|
||||
|
||||
// Subscribe to login state
|
||||
const loginSubscription = appstate.loginStatePart
|
||||
.select((stateArg) => stateArg)
|
||||
@@ -161,7 +204,7 @@ export class OpsDashboard extends DeesElement {
|
||||
}
|
||||
});
|
||||
this.rxSubscriptions.push(loginSubscription);
|
||||
|
||||
|
||||
// Subscribe to config state (for global warnings)
|
||||
const configSubscription = appstate.configStatePart
|
||||
.select((stateArg) => stateArg)
|
||||
@@ -176,38 +219,27 @@ export class OpsDashboard extends DeesElement {
|
||||
.subscribe((uiState) => {
|
||||
this.uiState = uiState;
|
||||
// Sync appdash view when state changes (e.g., from URL navigation)
|
||||
this.syncAppdashView(uiState.activeView);
|
||||
this.syncAppdashView(uiState.activeView, uiState.activeSubview);
|
||||
});
|
||||
this.rxSubscriptions.push(uiSubscription);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync the dees-simple-appdash view selection with the current state.
|
||||
* This is needed when the URL changes and we need to update the UI.
|
||||
* This is needed when the URL changes externally (back/forward, deep link).
|
||||
*/
|
||||
private syncAppdashView(viewName: string): void {
|
||||
private syncAppdashView(viewSlug: string, subviewSlug: string | null): void {
|
||||
const appDash = this.shadowRoot?.querySelector('dees-simple-appdash') as any;
|
||||
if (!appDash) return;
|
||||
|
||||
const targetTab = this.viewTabs.find(t => t.name.toLowerCase() === viewName);
|
||||
if (!targetTab) return;
|
||||
const targetView = this.findViewBySlug(viewSlug, subviewSlug);
|
||||
if (!targetView) return;
|
||||
|
||||
// Check if we need to switch (avoid unnecessary updates)
|
||||
if (appDash.selectedView === targetTab) return;
|
||||
if (appDash.selectedView === targetView) return;
|
||||
|
||||
// Update the selected view programmatically
|
||||
appDash.selectedView = targetTab;
|
||||
|
||||
// Update the displayed content
|
||||
const content = appDash.shadowRoot?.querySelector('.appcontent');
|
||||
if (content) {
|
||||
if (appDash.currentView) {
|
||||
appDash.currentView.remove();
|
||||
}
|
||||
const view = new targetTab.element();
|
||||
content.appendChild(view);
|
||||
appDash.currentView = view;
|
||||
}
|
||||
// Use loadView to update both selectedView and the mounted element.
|
||||
// It will dispatch view-select; our handler skips when state already matches.
|
||||
appDash.loadView(targetView);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
@@ -249,7 +281,7 @@ export class OpsDashboard extends DeesElement {
|
||||
public async firstUpdated() {
|
||||
const simpleLogin = this.shadowRoot!.querySelector('dees-simple-login') as any;
|
||||
simpleLogin.addEventListener('login', (e: Event) => {
|
||||
// Handle logout event
|
||||
// Handle login event
|
||||
const detail = (e as CustomEvent).detail;
|
||||
this.login(detail.data.username, detail.data.password);
|
||||
});
|
||||
@@ -258,9 +290,24 @@ export class OpsDashboard extends DeesElement {
|
||||
const appDash = this.shadowRoot!.querySelector('dees-simple-appdash');
|
||||
if (appDash) {
|
||||
appDash.addEventListener('view-select', (e: Event) => {
|
||||
const viewName = (e as CustomEvent).detail.view.name.toLowerCase();
|
||||
// Use router for navigation instead of direct state update
|
||||
appRouter.navigateToView(viewName);
|
||||
const view = (e as CustomEvent).detail.view as ITabbedView;
|
||||
const parent = this.findParent(view);
|
||||
const currentState = appstate.uiStatePart.getState();
|
||||
if (parent) {
|
||||
const parentSlug = this.slugFor(parent);
|
||||
const subSlug = this.slugFor(view);
|
||||
// Skip if already on this exact subview — preserves URL on initial mount
|
||||
if (currentState?.activeView === parentSlug && currentState?.activeSubview === subSlug) {
|
||||
return;
|
||||
}
|
||||
appRouter.navigateToView(parentSlug, subSlug);
|
||||
} else {
|
||||
const slug = this.slugFor(view);
|
||||
if (currentState?.activeView === slug && !currentState?.activeSubview) {
|
||||
return;
|
||||
}
|
||||
appRouter.navigateToView(slug);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle logout event
|
||||
@@ -306,12 +353,12 @@ export class OpsDashboard extends DeesElement {
|
||||
const simpleLogin = this.shadowRoot!.querySelector('dees-simple-login') as any;
|
||||
const form = simpleLogin.shadowRoot!.querySelector('dees-form') as any;
|
||||
form.setStatus('pending', 'Logging in...');
|
||||
|
||||
|
||||
const state = await appstate.loginStatePart.dispatchAction(appstate.loginAction, {
|
||||
username,
|
||||
password,
|
||||
});
|
||||
|
||||
|
||||
if (state.identity) {
|
||||
console.log('Login successful');
|
||||
this.loginState = state;
|
||||
@@ -325,4 +372,4 @@ export class OpsDashboard extends DeesElement {
|
||||
form!.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class OpsViewLogs extends DeesElement {
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Logs</dees-heading>
|
||||
<dees-heading level="3">Logs</dees-heading>
|
||||
|
||||
<dees-chart-log
|
||||
.label=${'Application Logs'}
|
||||
|
||||
@@ -1,453 +0,0 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as shared from './shared/index.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
} from '@design.estate/dees-element';
|
||||
import { type IStatsTile } from '@design.estate/dees-catalog';
|
||||
|
||||
@customElement('ops-view-security')
|
||||
export class OpsViewSecurity extends DeesElement {
|
||||
@state()
|
||||
accessor statsState: appstate.IStatsState = {
|
||||
serverStats: null,
|
||||
emailStats: null,
|
||||
dnsStats: null,
|
||||
securityMetrics: null,
|
||||
radiusStats: null,
|
||||
vpnStats: null,
|
||||
lastUpdated: 0,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
|
||||
@state()
|
||||
accessor selectedTab: 'overview' | 'blocked' | 'authentication' | 'email-security' = 'overview';
|
||||
|
||||
private tabLabelMap: Record<string, string> = {
|
||||
'overview': 'Overview',
|
||||
'blocked': 'Blocked IPs',
|
||||
'authentication': 'Authentication',
|
||||
'email-security': 'Email Security',
|
||||
};
|
||||
|
||||
private labelToTab: Record<string, 'overview' | 'blocked' | 'authentication' | 'email-security'> = {
|
||||
'Overview': 'overview',
|
||||
'Blocked IPs': 'blocked',
|
||||
'Authentication': 'authentication',
|
||||
'Email Security': 'email-security',
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const subscription = appstate.statsStatePart
|
||||
.select((stateArg) => stateArg)
|
||||
.subscribe((statsState) => {
|
||||
this.statsState = statsState;
|
||||
});
|
||||
this.rxSubscriptions.push(subscription);
|
||||
}
|
||||
|
||||
async firstUpdated() {
|
||||
const toggle = this.shadowRoot!.querySelector('dees-input-multitoggle') as any;
|
||||
if (toggle) {
|
||||
const sub = toggle.changeSubject.subscribe(() => {
|
||||
const tab = this.labelToTab[toggle.selectedOption];
|
||||
if (tab) this.selectedTab = tab;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
shared.viewHostCss,
|
||||
css`
|
||||
dees-input-multitoggle {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 32px 0 16px 0;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: ${cssManager.bdTheme('#333', '#ccc')};
|
||||
}
|
||||
|
||||
dees-statsgrid {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.securityCard {
|
||||
background: ${cssManager.bdTheme('#fff', '#222')};
|
||||
border: 1px solid ${cssManager.bdTheme('#e9ecef', '#333')};
|
||||
border-radius: 8px;
|
||||
padding: 24px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.actionButton {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
`,
|
||||
];
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Security</dees-heading>
|
||||
|
||||
<dees-input-multitoggle
|
||||
.type=${'single'}
|
||||
.options=${['Overview', 'Blocked IPs', 'Authentication', 'Email Security']}
|
||||
.selectedOption=${this.tabLabelMap[this.selectedTab]}
|
||||
></dees-input-multitoggle>
|
||||
|
||||
${this.renderTabContent()}
|
||||
`;
|
||||
}
|
||||
|
||||
private renderTabContent() {
|
||||
const metrics = this.statsState.securityMetrics;
|
||||
|
||||
if (!metrics) {
|
||||
return html`
|
||||
<div class="loadingMessage">
|
||||
<p>Loading security metrics...</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
switch(this.selectedTab) {
|
||||
case 'overview':
|
||||
return this.renderOverview(metrics);
|
||||
case 'blocked':
|
||||
return this.renderBlockedIPs(metrics);
|
||||
case 'authentication':
|
||||
return this.renderAuthentication(metrics);
|
||||
case 'email-security':
|
||||
return this.renderEmailSecurity(metrics);
|
||||
}
|
||||
}
|
||||
|
||||
private renderOverview(metrics: any) {
|
||||
const threatLevel = this.calculateThreatLevel(metrics);
|
||||
const threatScore = this.getThreatScore(metrics);
|
||||
|
||||
// Derive active sessions from recent successful auth events (last hour)
|
||||
const allEvents: any[] = metrics.recentEvents || [];
|
||||
const oneHourAgo = Date.now() - 3600000;
|
||||
const recentAuthSuccesses = allEvents.filter(
|
||||
(evt: any) => evt.type === 'authentication' && evt.success === true && evt.timestamp >= oneHourAgo
|
||||
).length;
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'threatLevel',
|
||||
title: 'Threat Level',
|
||||
value: threatScore,
|
||||
type: 'gauge',
|
||||
icon: 'lucide:Shield',
|
||||
gaugeOptions: {
|
||||
min: 0,
|
||||
max: 100,
|
||||
thresholds: [
|
||||
{ value: 0, color: '#ef4444' },
|
||||
{ value: 30, color: '#f59e0b' },
|
||||
{ value: 70, color: '#22c55e' },
|
||||
],
|
||||
},
|
||||
description: `Status: ${threatLevel.toUpperCase()}`,
|
||||
},
|
||||
{
|
||||
id: 'blockedThreats',
|
||||
title: 'Blocked Threats',
|
||||
value: (metrics.blockedIPs?.length || 0) + metrics.spamDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:ShieldCheck',
|
||||
color: '#ef4444',
|
||||
description: 'Total threats blocked today',
|
||||
},
|
||||
{
|
||||
id: 'activeSessions',
|
||||
title: 'Active Sessions',
|
||||
value: recentAuthSuccesses,
|
||||
type: 'number',
|
||||
icon: 'lucide:Users',
|
||||
color: '#22c55e',
|
||||
description: 'Authenticated in last hour',
|
||||
},
|
||||
{
|
||||
id: 'authFailures',
|
||||
title: 'Auth Failures',
|
||||
value: metrics.authenticationFailures,
|
||||
type: 'number',
|
||||
icon: 'lucide:LockOpen',
|
||||
color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Failed login attempts today',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Recent Security Events</h2>
|
||||
<dees-table
|
||||
.heading1=${'Security Events'}
|
||||
.heading2=${'Last 24 hours'}
|
||||
.data=${this.getSecurityEvents(metrics)}
|
||||
.displayFunction=${(item) => ({
|
||||
'Time': new Date(item.timestamp).toLocaleTimeString(),
|
||||
'Event': item.event,
|
||||
'Severity': item.severity,
|
||||
'Details': item.details,
|
||||
})}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderBlockedIPs(metrics: any) {
|
||||
const blockedIPs: string[] = metrics.blockedIPs || [];
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'totalBlocked',
|
||||
title: 'Blocked IPs',
|
||||
value: blockedIPs.length,
|
||||
type: 'number',
|
||||
icon: 'lucide:ShieldBan',
|
||||
color: blockedIPs.length > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Currently blocked addresses',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<dees-table
|
||||
.heading1=${'Blocked IP Addresses'}
|
||||
.heading2=${'IPs blocked due to suspicious activity'}
|
||||
.data=${blockedIPs.map((ip) => ({ ip }))}
|
||||
.displayFunction=${(item) => ({
|
||||
'IP Address': item.ip,
|
||||
'Reason': 'Suspicious activity',
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'Unblock',
|
||||
iconName: 'lucide:shield-off',
|
||||
type: ['contextmenu' as const],
|
||||
actionFunc: async (item) => {
|
||||
await this.unblockIP(item.ip);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Clear All',
|
||||
iconName: 'lucide:trash-2',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.clearBlockedIPs();
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderAuthentication(metrics: any) {
|
||||
// Derive auth events from recentEvents
|
||||
const allEvents: any[] = metrics.recentEvents || [];
|
||||
const authEvents = allEvents.filter((evt: any) => evt.type === 'authentication');
|
||||
const successfulLogins = authEvents.filter((evt: any) => evt.success === true).length;
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'authFailures',
|
||||
title: 'Authentication Failures',
|
||||
value: metrics.authenticationFailures,
|
||||
type: 'number',
|
||||
icon: 'lucide:LockOpen',
|
||||
color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Failed authentication attempts today',
|
||||
},
|
||||
{
|
||||
id: 'successfulLogins',
|
||||
title: 'Successful Logins',
|
||||
value: successfulLogins,
|
||||
type: 'number',
|
||||
icon: 'lucide:Lock',
|
||||
color: '#22c55e',
|
||||
description: 'Successful logins today',
|
||||
},
|
||||
];
|
||||
|
||||
// Map auth events to login history table data
|
||||
const loginHistory = authEvents.map((evt: any) => ({
|
||||
timestamp: evt.timestamp,
|
||||
username: evt.details?.username || 'unknown',
|
||||
ipAddress: evt.ipAddress || 'unknown',
|
||||
success: evt.success ?? false,
|
||||
reason: evt.success ? '' : evt.message || 'Authentication failed',
|
||||
}));
|
||||
|
||||
return html`
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Recent Login Attempts</h2>
|
||||
<dees-table
|
||||
.heading1=${'Login History'}
|
||||
.heading2=${'Recent authentication attempts'}
|
||||
.data=${loginHistory}
|
||||
.displayFunction=${(item) => ({
|
||||
'Time': new Date(item.timestamp).toLocaleString(),
|
||||
'Username': item.username,
|
||||
'IP Address': item.ipAddress,
|
||||
'Status': item.success ? 'Success' : 'Failed',
|
||||
'Reason': item.reason || '-',
|
||||
})}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderEmailSecurity(metrics: any) {
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'malware',
|
||||
title: 'Malware Detection',
|
||||
value: metrics.malwareDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:BugOff',
|
||||
color: metrics.malwareDetected > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Malware detected',
|
||||
},
|
||||
{
|
||||
id: 'phishing',
|
||||
title: 'Phishing Detection',
|
||||
value: metrics.phishingDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:Fish',
|
||||
color: metrics.phishingDetected > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Phishing attempts detected',
|
||||
},
|
||||
{
|
||||
id: 'suspicious',
|
||||
title: 'Suspicious Activities',
|
||||
value: metrics.suspiciousActivities,
|
||||
type: 'number',
|
||||
icon: 'lucide:TriangleAlert',
|
||||
color: metrics.suspiciousActivities > 5 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Suspicious activities detected',
|
||||
},
|
||||
{
|
||||
id: 'spam',
|
||||
title: 'Spam Detection',
|
||||
value: metrics.spamDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:Ban',
|
||||
color: '#f59e0b',
|
||||
description: 'Spam emails blocked',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Email Security Configuration</h2>
|
||||
<div class="securityCard">
|
||||
<dees-form>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableSPF'}
|
||||
.label=${'Enable SPF checking'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableDKIM'}
|
||||
.label=${'Enable DKIM validation'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableDMARC'}
|
||||
.label=${'Enable DMARC policy enforcement'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
<dees-input-checkbox
|
||||
.key=${'enableSpamFilter'}
|
||||
.label=${'Enable spam filtering'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
</dees-form>
|
||||
<dees-button
|
||||
class="actionButton"
|
||||
type="highlighted"
|
||||
@click=${() => this.saveEmailSecuritySettings()}
|
||||
>
|
||||
Save Settings
|
||||
</dees-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private calculateThreatLevel(metrics: any): string {
|
||||
const score = this.getThreatScore(metrics);
|
||||
if (score < 30) return 'alert';
|
||||
if (score < 70) return 'warning';
|
||||
return 'success';
|
||||
}
|
||||
|
||||
private getThreatScore(metrics: any): number {
|
||||
// Simple scoring algorithm
|
||||
let score = 100;
|
||||
const blockedCount = Array.isArray(metrics.blockedIPs) ? metrics.blockedIPs.length : (metrics.blockedIPs || 0);
|
||||
score -= blockedCount * 2;
|
||||
score -= (metrics.authenticationFailures || 0) * 1;
|
||||
score -= (metrics.spamDetected || 0) * 0.5;
|
||||
score -= (metrics.malwareDetected || 0) * 3;
|
||||
score -= (metrics.phishingDetected || 0) * 3;
|
||||
score -= (metrics.suspiciousActivities || 0) * 2;
|
||||
return Math.max(0, Math.min(100, Math.round(score)));
|
||||
}
|
||||
|
||||
private getSecurityEvents(metrics: any): any[] {
|
||||
const events: any[] = metrics.recentEvents || [];
|
||||
return events.map((evt: any) => ({
|
||||
timestamp: evt.timestamp,
|
||||
event: evt.message,
|
||||
severity: evt.level === 'critical' ? 'critical' : evt.level === 'error' ? 'high' : evt.level === 'warn' ? 'warning' : 'info',
|
||||
details: evt.ipAddress ? `IP: ${evt.ipAddress}` : evt.domain ? `Domain: ${evt.domain}` : evt.type,
|
||||
}));
|
||||
}
|
||||
|
||||
private async clearBlockedIPs() {
|
||||
// SmartProxy manages IP blocking — not yet exposed via API
|
||||
alert('Clearing blocked IPs is not yet supported from the UI.');
|
||||
}
|
||||
|
||||
private async unblockIP(ip: string) {
|
||||
// SmartProxy manages IP blocking — not yet exposed via API
|
||||
alert(`Unblocking IP ${ip} is not yet supported from the UI.`);
|
||||
}
|
||||
|
||||
private async saveEmailSecuritySettings() {
|
||||
// Config is read-only from the UI for now
|
||||
alert('Email security settings are read-only. Update the dcrouter configuration file to change these settings.');
|
||||
}
|
||||
}
|
||||
2
ts_web/elements/overview/index.ts
Normal file
2
ts_web/elements/overview/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './ops-view-overview.js';
|
||||
export * from './ops-view-config.js';
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as shared from './shared/index.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import { appRouter } from '../router.js';
|
||||
import * as plugins from '../../plugins.js';
|
||||
import * as shared from '../shared/index.js';
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { appRouter } from '../../router.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
@@ -57,7 +57,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Configuration</dees-heading>
|
||||
<dees-heading level="3">Configuration</dees-heading>
|
||||
|
||||
${this.configState.isLoading
|
||||
? html`
|
||||
@@ -86,7 +86,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
infoText="This view displays the current running configuration. DcRouter is configured through code or remote management."
|
||||
@navigate=${(e: CustomEvent) => {
|
||||
if (e.detail?.view) {
|
||||
appRouter.navigateToView(e.detail.view);
|
||||
appRouter.navigateToView(e.detail.view, e.detail.subview);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -149,7 +149,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
}
|
||||
|
||||
const actions: IConfigSectionAction[] = [
|
||||
{ label: 'View Routes', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'routes' } },
|
||||
{ label: 'View Routes', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'network', subview: 'routes' } },
|
||||
];
|
||||
|
||||
return html`
|
||||
@@ -181,7 +181,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
}
|
||||
|
||||
const actions: IConfigSectionAction[] = [
|
||||
{ label: 'View Emails', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'emails' } },
|
||||
{ label: 'View Emails', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'email', subview: 'log' } },
|
||||
];
|
||||
|
||||
return html`
|
||||
@@ -227,7 +227,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
|
||||
const status = tls.source === 'none' ? 'not-configured' : 'enabled';
|
||||
const actions: IConfigSectionAction[] = [
|
||||
{ label: 'View Certificates', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'certificates' } },
|
||||
{ label: 'View Certificates', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'domains', subview: 'certificates' } },
|
||||
];
|
||||
|
||||
return html`
|
||||
@@ -305,7 +305,7 @@ export class OpsViewConfig extends DeesElement {
|
||||
];
|
||||
|
||||
const actions: IConfigSectionAction[] = [
|
||||
{ label: 'View Remote Ingress', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'remoteingress' } },
|
||||
{ label: 'View Remote Ingress', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'network', subview: 'remoteingress' } },
|
||||
];
|
||||
|
||||
return html`
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import * as shared from './shared/index.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import * as plugins from '../../plugins.js';
|
||||
import * as shared from '../shared/index.js';
|
||||
import * as appstate from '../../appstate.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
@@ -94,7 +94,7 @@ export class OpsViewOverview extends DeesElement {
|
||||
|
||||
public render() {
|
||||
return html`
|
||||
<dees-heading level="2">Overview</dees-heading>
|
||||
<dees-heading level="3">Stats</dees-heading>
|
||||
|
||||
${this.statsState.isLoading ? html`
|
||||
<div class="loadingMessage">
|
||||
3
ts_web/elements/security/index.ts
Normal file
3
ts_web/elements/security/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './ops-view-security-overview.js';
|
||||
export * from './ops-view-security-blocked.js';
|
||||
export * from './ops-view-security-authentication.js';
|
||||
121
ts_web/elements/security/ops-view-security-authentication.ts
Normal file
121
ts_web/elements/security/ops-view-security-authentication.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
import { type IStatsTile } from '@design.estate/dees-catalog';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-security-authentication': OpsViewSecurityAuthentication;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-security-authentication')
|
||||
export class OpsViewSecurityAuthentication extends DeesElement {
|
||||
@state()
|
||||
accessor statsState: appstate.IStatsState = appstate.statsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.statsStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((s) => {
|
||||
this.statsState = s;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
h2 {
|
||||
margin: 32px 0 16px 0;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: ${cssManager.bdTheme('#333', '#ccc')};
|
||||
}
|
||||
dees-statsgrid {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const metrics = this.statsState.securityMetrics;
|
||||
|
||||
if (!metrics) {
|
||||
return html`
|
||||
<div class="loadingMessage">
|
||||
<p>Loading security metrics...</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Derive auth events from recentEvents
|
||||
const allEvents: any[] = metrics.recentEvents || [];
|
||||
const authEvents = allEvents.filter((evt: any) => evt.type === 'authentication');
|
||||
const successfulLogins = authEvents.filter((evt: any) => evt.success === true).length;
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'authFailures',
|
||||
title: 'Authentication Failures',
|
||||
value: metrics.authenticationFailures,
|
||||
type: 'number',
|
||||
icon: 'lucide:LockOpen',
|
||||
color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Failed authentication attempts today',
|
||||
},
|
||||
{
|
||||
id: 'successfulLogins',
|
||||
title: 'Successful Logins',
|
||||
value: successfulLogins,
|
||||
type: 'number',
|
||||
icon: 'lucide:Lock',
|
||||
color: '#22c55e',
|
||||
description: 'Successful logins today',
|
||||
},
|
||||
];
|
||||
|
||||
// Map auth events to login history table data
|
||||
const loginHistory = authEvents.map((evt: any) => ({
|
||||
timestamp: evt.timestamp,
|
||||
username: evt.details?.username || 'unknown',
|
||||
ipAddress: evt.ipAddress || 'unknown',
|
||||
success: evt.success ?? false,
|
||||
reason: evt.success ? '' : evt.message || 'Authentication failed',
|
||||
}));
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Authentication</dees-heading>
|
||||
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Recent Login Attempts</h2>
|
||||
<dees-table
|
||||
.heading1=${'Login History'}
|
||||
.heading2=${'Recent authentication attempts'}
|
||||
.data=${loginHistory}
|
||||
.displayFunction=${(item) => ({
|
||||
'Time': new Date(item.timestamp).toLocaleString(),
|
||||
'Username': item.username,
|
||||
'IP Address': item.ipAddress,
|
||||
'Status': item.success ? 'Success' : 'Failed',
|
||||
'Reason': item.reason || '-',
|
||||
})}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
}
|
||||
118
ts_web/elements/security/ops-view-security-blocked.ts
Normal file
118
ts_web/elements/security/ops-view-security-blocked.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
import { type IStatsTile } from '@design.estate/dees-catalog';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-security-blocked': OpsViewSecurityBlocked;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-security-blocked')
|
||||
export class OpsViewSecurityBlocked extends DeesElement {
|
||||
@state()
|
||||
accessor statsState: appstate.IStatsState = appstate.statsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.statsStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((s) => {
|
||||
this.statsState = s;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
dees-statsgrid {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const metrics = this.statsState.securityMetrics;
|
||||
|
||||
if (!metrics) {
|
||||
return html`
|
||||
<div class="loadingMessage">
|
||||
<p>Loading security metrics...</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const blockedIPs: string[] = metrics.blockedIPs || [];
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'totalBlocked',
|
||||
title: 'Blocked IPs',
|
||||
value: blockedIPs.length,
|
||||
type: 'number',
|
||||
icon: 'lucide:ShieldBan',
|
||||
color: blockedIPs.length > 0 ? '#ef4444' : '#22c55e',
|
||||
description: 'Currently blocked addresses',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Blocked IPs</dees-heading>
|
||||
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<dees-table
|
||||
.heading1=${'Blocked IP Addresses'}
|
||||
.heading2=${'IPs blocked due to suspicious activity'}
|
||||
.data=${blockedIPs.map((ip) => ({ ip }))}
|
||||
.displayFunction=${(item) => ({
|
||||
'IP Address': item.ip,
|
||||
'Reason': 'Suspicious activity',
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'Unblock',
|
||||
iconName: 'lucide:shield-off',
|
||||
type: ['contextmenu' as const],
|
||||
actionFunc: async (item) => {
|
||||
await this.unblockIP(item.ip);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Clear All',
|
||||
iconName: 'lucide:trash-2',
|
||||
type: ['header' as const],
|
||||
actionFunc: async () => {
|
||||
await this.clearBlockedIPs();
|
||||
},
|
||||
},
|
||||
]}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private async clearBlockedIPs() {
|
||||
// SmartProxy manages IP blocking — not yet exposed via API
|
||||
alert('Clearing blocked IPs is not yet supported from the UI.');
|
||||
}
|
||||
|
||||
private async unblockIP(ip: string) {
|
||||
// SmartProxy manages IP blocking — not yet exposed via API
|
||||
alert(`Unblocking IP ${ip} is not yet supported from the UI.`);
|
||||
}
|
||||
}
|
||||
172
ts_web/elements/security/ops-view-security-overview.ts
Normal file
172
ts_web/elements/security/ops-view-security-overview.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import * as appstate from '../../appstate.js';
|
||||
import { viewHostCss } from '../shared/css.js';
|
||||
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
import { type IStatsTile } from '@design.estate/dees-catalog';
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'ops-view-security-overview': OpsViewSecurityOverview;
|
||||
}
|
||||
}
|
||||
|
||||
@customElement('ops-view-security-overview')
|
||||
export class OpsViewSecurityOverview extends DeesElement {
|
||||
@state()
|
||||
accessor statsState: appstate.IStatsState = appstate.statsStatePart.getState()!;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const sub = appstate.statsStatePart
|
||||
.select((s) => s)
|
||||
.subscribe((s) => {
|
||||
this.statsState = s;
|
||||
});
|
||||
this.rxSubscriptions.push(sub);
|
||||
}
|
||||
|
||||
public static styles = [
|
||||
cssManager.defaultStyles,
|
||||
viewHostCss,
|
||||
css`
|
||||
h2 {
|
||||
margin: 32px 0 16px 0;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: ${cssManager.bdTheme('#333', '#ccc')};
|
||||
}
|
||||
dees-statsgrid {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
public render(): TemplateResult {
|
||||
const metrics = this.statsState.securityMetrics;
|
||||
|
||||
if (!metrics) {
|
||||
return html`
|
||||
<div class="loadingMessage">
|
||||
<p>Loading security metrics...</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const threatLevel = this.calculateThreatLevel(metrics);
|
||||
const threatScore = this.getThreatScore(metrics);
|
||||
|
||||
// Derive active sessions from recent successful auth events (last hour)
|
||||
const allEvents: any[] = metrics.recentEvents || [];
|
||||
const oneHourAgo = Date.now() - 3600000;
|
||||
const recentAuthSuccesses = allEvents.filter(
|
||||
(evt: any) => evt.type === 'authentication' && evt.success === true && evt.timestamp >= oneHourAgo
|
||||
).length;
|
||||
|
||||
const tiles: IStatsTile[] = [
|
||||
{
|
||||
id: 'threatLevel',
|
||||
title: 'Threat Level',
|
||||
value: threatScore,
|
||||
type: 'gauge',
|
||||
icon: 'lucide:Shield',
|
||||
gaugeOptions: {
|
||||
min: 0,
|
||||
max: 100,
|
||||
thresholds: [
|
||||
{ value: 0, color: '#ef4444' },
|
||||
{ value: 30, color: '#f59e0b' },
|
||||
{ value: 70, color: '#22c55e' },
|
||||
],
|
||||
},
|
||||
description: `Status: ${threatLevel.toUpperCase()}`,
|
||||
},
|
||||
{
|
||||
id: 'blockedThreats',
|
||||
title: 'Blocked Threats',
|
||||
value: (metrics.blockedIPs?.length || 0) + metrics.spamDetected,
|
||||
type: 'number',
|
||||
icon: 'lucide:ShieldCheck',
|
||||
color: '#ef4444',
|
||||
description: 'Total threats blocked today',
|
||||
},
|
||||
{
|
||||
id: 'activeSessions',
|
||||
title: 'Active Sessions',
|
||||
value: recentAuthSuccesses,
|
||||
type: 'number',
|
||||
icon: 'lucide:Users',
|
||||
color: '#22c55e',
|
||||
description: 'Authenticated in last hour',
|
||||
},
|
||||
{
|
||||
id: 'authFailures',
|
||||
title: 'Auth Failures',
|
||||
value: metrics.authenticationFailures,
|
||||
type: 'number',
|
||||
icon: 'lucide:LockOpen',
|
||||
color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
|
||||
description: 'Failed login attempts today',
|
||||
},
|
||||
];
|
||||
|
||||
return html`
|
||||
<dees-heading level="3">Overview</dees-heading>
|
||||
|
||||
<dees-statsgrid
|
||||
.tiles=${tiles}
|
||||
.minTileWidth=${200}
|
||||
></dees-statsgrid>
|
||||
|
||||
<h2>Recent Security Events</h2>
|
||||
<dees-table
|
||||
.heading1=${'Security Events'}
|
||||
.heading2=${'Last 24 hours'}
|
||||
.data=${this.getSecurityEvents(metrics)}
|
||||
.displayFunction=${(item) => ({
|
||||
'Time': new Date(item.timestamp).toLocaleTimeString(),
|
||||
'Event': item.event,
|
||||
'Severity': item.severity,
|
||||
'Details': item.details,
|
||||
})}
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private calculateThreatLevel(metrics: any): string {
|
||||
const score = this.getThreatScore(metrics);
|
||||
if (score < 30) return 'alert';
|
||||
if (score < 70) return 'warning';
|
||||
return 'success';
|
||||
}
|
||||
|
||||
private getThreatScore(metrics: any): number {
|
||||
// Simple scoring algorithm
|
||||
let score = 100;
|
||||
const blockedCount = Array.isArray(metrics.blockedIPs) ? metrics.blockedIPs.length : (metrics.blockedIPs || 0);
|
||||
score -= blockedCount * 2;
|
||||
score -= (metrics.authenticationFailures || 0) * 1;
|
||||
score -= (metrics.spamDetected || 0) * 0.5;
|
||||
score -= (metrics.malwareDetected || 0) * 3;
|
||||
score -= (metrics.phishingDetected || 0) * 3;
|
||||
score -= (metrics.suspiciousActivities || 0) * 2;
|
||||
return Math.max(0, Math.min(100, Math.round(score)));
|
||||
}
|
||||
|
||||
private getSecurityEvents(metrics: any): any[] {
|
||||
const events: any[] = metrics.recentEvents || [];
|
||||
return events.map((evt: any) => ({
|
||||
timestamp: evt.timestamp,
|
||||
event: evt.message,
|
||||
severity: evt.level === 'critical' ? 'critical' : evt.level === 'error' ? 'high' : evt.level === 'warn' ? 'warning' : 'info',
|
||||
details: evt.ipAddress ? `IP: ${evt.ipAddress}` : evt.domain ? `Domain: ${evt.domain}` : evt.type,
|
||||
}));
|
||||
}
|
||||
}
|
||||
100
ts_web/router.ts
100
ts_web/router.ts
@@ -3,9 +3,39 @@ 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', 'sourceprofiles', 'networktargets', 'targetprofiles'] as const;
|
||||
// Flat top-level views (no subviews)
|
||||
const flatViews = ['logs'] as const;
|
||||
|
||||
export type TValidView = typeof validViews[number];
|
||||
// Tabbed views and their valid subviews
|
||||
const subviewMap: Record<string, readonly string[]> = {
|
||||
overview: ['stats', 'configuration'] as const,
|
||||
network: ['activity', 'routes', 'sourceprofiles', 'networktargets', 'targetprofiles', 'remoteingress', 'vpn'] as const,
|
||||
email: ['log', 'security'] as const,
|
||||
access: ['apitokens', 'users'] as const,
|
||||
security: ['overview', 'blocked', 'authentication'] as const,
|
||||
domains: ['providers', 'domains', 'dns', 'certificates'] as const,
|
||||
};
|
||||
|
||||
// Default subview when user visits the bare parent URL
|
||||
const defaultSubview: Record<string, string> = {
|
||||
overview: 'stats',
|
||||
network: 'activity',
|
||||
email: 'log',
|
||||
access: 'apitokens',
|
||||
security: 'overview',
|
||||
domains: 'domains',
|
||||
};
|
||||
|
||||
export const validTopLevelViews = [...flatViews, ...Object.keys(subviewMap)] as const;
|
||||
export type TValidView = typeof validTopLevelViews[number];
|
||||
|
||||
export function isValidView(view: string): boolean {
|
||||
return (validTopLevelViews as readonly string[]).includes(view);
|
||||
}
|
||||
|
||||
export function isValidSubview(view: string, subview: string): boolean {
|
||||
return subviewMap[view]?.includes(subview) ?? false;
|
||||
}
|
||||
|
||||
class AppRouter {
|
||||
private router: InstanceType<typeof SmartRouter>;
|
||||
@@ -25,12 +55,27 @@ class AppRouter {
|
||||
}
|
||||
|
||||
private setupRoutes(): void {
|
||||
for (const view of validViews) {
|
||||
// Flat views
|
||||
for (const view of flatViews) {
|
||||
this.router.on(`/${view}`, async () => {
|
||||
this.updateViewState(view);
|
||||
this.updateViewState(view, null);
|
||||
});
|
||||
}
|
||||
|
||||
// Tabbed views
|
||||
for (const view of Object.keys(subviewMap)) {
|
||||
// Bare parent → redirect to default subview
|
||||
this.router.on(`/${view}`, async () => {
|
||||
this.navigateTo(`/${view}/${defaultSubview[view]}`);
|
||||
});
|
||||
// Each valid subview
|
||||
for (const sub of subviewMap[view]) {
|
||||
this.router.on(`/${view}/${sub}`, async () => {
|
||||
this.updateViewState(view, sub);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Root redirect
|
||||
this.router.on('/', async () => {
|
||||
this.navigateTo('/overview');
|
||||
@@ -42,7 +87,9 @@ class AppRouter {
|
||||
if (this.suppressStateUpdate) return;
|
||||
|
||||
const currentPath = window.location.pathname;
|
||||
const expectedPath = `/${uiState.activeView}`;
|
||||
const expectedPath = uiState.activeSubview
|
||||
? `/${uiState.activeView}/${uiState.activeSubview}`
|
||||
: `/${uiState.activeView}`;
|
||||
|
||||
if (currentPath !== expectedPath) {
|
||||
this.suppressStateUpdate = true;
|
||||
@@ -57,25 +104,38 @@ class AppRouter {
|
||||
|
||||
if (!path || path === '/') {
|
||||
this.router.pushUrl('/overview');
|
||||
} else {
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const view = segments[0];
|
||||
return;
|
||||
}
|
||||
|
||||
if (validViews.includes(view as TValidView)) {
|
||||
this.updateViewState(view as TValidView);
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const view = segments[0];
|
||||
const sub = segments[1];
|
||||
|
||||
if (!isValidView(view)) {
|
||||
this.router.pushUrl('/overview');
|
||||
return;
|
||||
}
|
||||
|
||||
if (subviewMap[view]) {
|
||||
if (sub && isValidSubview(view, sub)) {
|
||||
this.updateViewState(view, sub);
|
||||
} else {
|
||||
this.router.pushUrl('/overview');
|
||||
// Bare parent or invalid sub → default subview
|
||||
this.router.pushUrl(`/${view}/${defaultSubview[view]}`);
|
||||
}
|
||||
} else {
|
||||
this.updateViewState(view, null);
|
||||
}
|
||||
}
|
||||
|
||||
private updateViewState(view: string): void {
|
||||
private updateViewState(view: string, subview: string | null): void {
|
||||
this.suppressStateUpdate = true;
|
||||
const currentState = appstate.uiStatePart.getState()!;
|
||||
if (currentState.activeView !== view) {
|
||||
if (currentState.activeView !== view || currentState.activeSubview !== subview) {
|
||||
appstate.uiStatePart.setState({
|
||||
...currentState,
|
||||
activeView: view,
|
||||
activeSubview: subview,
|
||||
} as appstate.IUiState);
|
||||
}
|
||||
this.suppressStateUpdate = false;
|
||||
@@ -85,11 +145,17 @@ class AppRouter {
|
||||
this.router.pushUrl(path);
|
||||
}
|
||||
|
||||
public navigateToView(view: string): void {
|
||||
if (validViews.includes(view as TValidView)) {
|
||||
this.navigateTo(`/${view}`);
|
||||
} else {
|
||||
public navigateToView(view: string, subview?: string): void {
|
||||
if (!isValidView(view)) {
|
||||
this.navigateTo('/overview');
|
||||
return;
|
||||
}
|
||||
if (subview && isValidSubview(view, subview)) {
|
||||
this.navigateTo(`/${view}/${subview}`);
|
||||
} else if (subviewMap[view]) {
|
||||
this.navigateTo(`/${view}/${defaultSubview[view]}`);
|
||||
} else {
|
||||
this.navigateTo(`/${view}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user