Compare commits

...

18 Commits

Author SHA1 Message Date
jkunz e6ebac76b4 v1.27.0
Release / build-and-release (push) Successful in 2m34s
2026-05-21 20:35:07 +00:00
jkunz 27888a9fd1 chore(web): update bundled onebox app 2026-05-21 20:34:36 +00:00
jkunz 3f6b058ce5 feat(web): group onebox sidebar navigation 2026-05-21 20:32:40 +00:00
jkunz ba370cbce8 v1.26.3
Release / build-and-release (push) Successful in 2m29s
2026-05-21 17:06:38 +00:00
jkunz 43c8f261cc fix(web): use dees-table for gateway domains and DNS records views 2026-05-21 17:06:15 +00:00
jkunz 2984c41081 v1.26.2
Release / build-and-release (push) Successful in 2m30s
2026-05-20 14:32:04 +00:00
jkunz d143d73ea9 chore(release): remove duplicate pending heading 2026-05-20 14:31:56 +00:00
jkunz 9f8a6eaa76 chore(release): format pending changelog entry 2026-05-20 14:31:18 +00:00
jkunz 0af8da2c9d chore(release): document proxy reload fix 2026-05-20 14:30:31 +00:00
jkunz fa96d371d6 fix(proxy): reload routes after SmartProxy startup 2026-05-20 14:27:17 +00:00
jkunz 9e4dcc18a2 v1.26.1
Release / build-and-release (push) Successful in 2m31s
2026-05-09 22:36:27 +00:00
jkunz 15574b8629 fix(external-gateway): derive gateway client identity from the dcrouter token and make the settings UI read-only 2026-05-09 22:36:26 +00:00
jkunz b9c90eca3d v1.26.0
Release / build-and-release (push) Successful in 2m36s
2026-05-09 20:04:02 +00:00
jkunz dc37a71802 feat(dcrouter): add managed local dcrouter mode with status controls and gateway integration 2026-05-09 20:04:02 +00:00
jkunz 595e84cdb6 v1.25.0
Release / build-and-release (push) Successful in 2m59s
2026-05-09 11:58:51 +00:00
jkunz 5e04001790 feat(external-gateway): add gateway client domain and DNS record support for dcrouter integration 2026-05-09 11:58:51 +00:00
jkunz 7fe63541b3 fix: align delegate routing settings UI
Release / build-and-release (push) Successful in 2m44s
2026-05-08 19:32:40 +00:00
jkunz 201602b733 fix: use compiled-safe password hashing
Release / build-and-release (push) Successful in 2m34s
2026-05-08 16:36:58 +00:00
37 changed files with 1924 additions and 239 deletions
+65
View File
@@ -1,5 +1,70 @@
# Changelog # Changelog
## Pending
## 2026-05-21 - 1.27.0
### Features
- group Onebox sidebar navigation into Apps, Network, and Registry sections (web)
- add parent/subview routes for grouped app, network, and registry pages
## 2026-05-21 - 1.26.3
### Fixes
- use `dees-table` for gateway domains and DNS records views (web)
- replace custom row grids with catalog tables, filtering, refresh, and row actions
- use dees-table for gateway domains and DNS records views (web)
- replace custom row layouts with dees-table in gateway domains and DNS records views
- add table filtering, refresh actions, and row/context actions for dcrouter management
## 2026-05-20 - 1.26.2
### Fixes
- reload SmartProxy routes after managed startup (proxy)
- reloads SmartProxy routes immediately after the admin API is ready during startup, avoiding an empty route table when Docker task state lags behind service readiness
## 2026-05-09 - 1.26.1 - fix(external-gateway)
derive gateway client identity from the dcrouter token and make the settings UI read-only
- Resolves external gateway ownership and domain sync to use the gateway client context returned by dcrouter instead of a locally entered client ID.
- Falls back to stored gateway client settings only when token context is unavailable.
- Removes editable Gateway Client ID fields from settings and shows them as diagnostic read-only values for managed and external modes.
- Updates external gateway tests to validate token-derived gateway client IDs and admin-token behavior.
## 2026-05-09 - 1.26.0 - feat(dcrouter)
add managed local dcrouter mode with status controls and gateway integration
- Adds a ManagedDcRouterManager to provision and control a local dcrouter container with default gateway settings.
- Updates gateway sync logic to support managed, external, and disabled dcrouter modes, including managed local route targets.
- Exposes managed dcrouter status, start, stop, and restart operations through OpsServer typed requests.
- Extends settings APIs and the settings UI to configure managed dcrouter ports, image, data directory, and mode selection.
- Adjusts Onebox startup to prepare managed dcrouter settings, shift proxy ports when managed mode is active, and initialize the local gateway before route sync.
## 2026-05-09 - 1.25.0 - feat(external-gateway)
add gateway client domain and DNS record support for dcrouter integration
- switch dcrouter route syncing to gateway-client APIs with fallback to legacy workHoster endpoints
- add admin endpoints and frontend views for browsing gateway domains and DNS records
- introduce dcrouterGatewayClientId settings support while preserving compatibility with the legacy workHoster ID
## 2026-05-08 - 1.24.7 - fix(web-ui)
align Delegate Routing settings with the Dees catalog control and theme conventions
- replace raw Delegate Routing inputs and save button with `dees-input-text` and `dees-button`
- style the Delegate Routing card with explicit `cssManager.bdTheme(...)` colors
## 2026-05-08 - 1.24.6 - fix(auth)
avoid bcrypt worker crashes in compiled binaries during login and password creation
- replace bcrypt password hashing with a Web Crypto PBKDF2 hash format
- remove legacy password-hash fallbacks; existing deployments need their admin user hash updated
## 2026-05-08 - 1.24.5 - fix(opsserver) ## 2026-05-08 - 1.24.5 - fix(opsserver)
start the OpsServer with typedserver custom routes registered through the UtilityWebsiteServer hook start the OpsServer with typedserver custom routes registered through the UtilityWebsiteServer hook
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@serve.zone/onebox", "name": "@serve.zone/onebox",
"version": "1.24.5", "version": "1.27.0",
"exports": "./mod.ts", "exports": "./mod.ts",
"tasks": { "tasks": {
"test": "deno test --allow-all test/", "test": "deno test --allow-all test/",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@serve.zone/onebox", "name": "@serve.zone/onebox",
"version": "1.24.5", "version": "1.27.0",
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers", "description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
"main": "mod.ts", "main": "mod.ts",
"type": "module", "type": "module",
+7 -12
View File
@@ -5,8 +5,7 @@ import type { IUser as IDatabaseUser } from '../ts/types.ts';
import { AdminHandler } from '../ts/opsserver/handlers/admin.handler.ts'; import { AdminHandler } from '../ts/opsserver/handlers/admin.handler.ts';
import { import {
hashPassword, hashPassword,
isBcryptHash, isPbkdf2Hash,
needsPasswordUpgrade,
verifyPassword, verifyPassword,
} from '../ts/utils/auth.ts'; } from '../ts/utils/auth.ts';
@@ -45,18 +44,14 @@ async function createAdminHandler(users: IDatabaseUser[]): Promise<AdminHandler>
return adminHandler; return adminHandler;
} }
Deno.test('password helpers support bcrypt and legacy password hashes', async () => { Deno.test('password helpers support PBKDF2 password hashes', async () => {
const password = 'correct horse battery staple'; const password = 'correct horse battery staple';
const bcryptHash = await hashPassword(password); const passwordHash = await hashPassword(password);
assert(isBcryptHash(bcryptHash)); assert(isPbkdf2Hash(passwordHash));
assert(await verifyPassword(password, bcryptHash)); assert(await verifyPassword(password, passwordHash));
assert(!(await verifyPassword('wrong password', bcryptHash))); assert(!(await verifyPassword('wrong password', passwordHash)));
assert(!needsPasswordUpgrade(bcryptHash)); assert(!(await verifyPassword(password, btoa(password))));
const legacyHash = btoa(password);
assert(await verifyPassword(password, legacyHash));
assert(needsPasswordUpgrade(legacyHash));
}); });
Deno.test('verified identity is derived from the signed JWT and database, not client fields', async () => { Deno.test('verified identity is derived from the signed JWT and database, not client fields', async () => {
+69 -10
View File
@@ -62,7 +62,6 @@ class FakeDatabase {
const makeOneboxRef = () => { const makeOneboxRef = () => {
const database = new FakeDatabase(); const database = new FakeDatabase();
database.settings.set('dcrouterGatewayUrl', 'https://edge.example.com'); database.settings.set('dcrouterGatewayUrl', 'https://edge.example.com');
database.settings.set('dcrouterWorkHosterId', 'onebox-1');
database.secretSettings.set('dcrouterGatewayApiToken', 'dcr-token'); database.secretSettings.set('dcrouterGatewayApiToken', 'dcr-token');
let reloadCount = 0; let reloadCount = 0;
@@ -92,8 +91,12 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
}); });
const manager = new ExternalGatewayManager(oneboxRef as any); const manager = new ExternalGatewayManager(oneboxRef as any);
(manager as any).fireDcRouterRequest = async (method: string) => { (manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
assertEquals(method, 'getWorkHosterDomains'); if (method === 'getGatewayClientContext') {
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
}
assertEquals(method, 'getGatewayClientDomains');
assertEquals(requestData.gatewayClientId, 'onebox-token');
return { return {
domains: [ domains: [
{ {
@@ -117,7 +120,7 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
assertEquals(oneboxRef.database.getDomainByName('old.example.com')?.isObsolete, true); assertEquals(oneboxRef.database.getDomainByName('old.example.com')?.isObsolete, true);
}); });
Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster API', async () => { Deno.test('ExternalGatewayManager syncs service routes to dcrouter gatewayClient API', async () => {
const oneboxRef = makeOneboxRef(); const oneboxRef = makeOneboxRef();
oneboxRef.database.settings.set('serverIP', '203.0.113.10'); oneboxRef.database.settings.set('serverIP', '203.0.113.10');
oneboxRef.database.settings.set('httpPort', '8080'); oneboxRef.database.settings.set('httpPort', '8080');
@@ -137,6 +140,9 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
const requests: Array<{ method: string; requestData: Record<string, unknown> }> = []; const requests: Array<{ method: string; requestData: Record<string, unknown> }> = [];
const manager = new ExternalGatewayManager(oneboxRef as any); const manager = new ExternalGatewayManager(oneboxRef as any);
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => { (manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
if (method === 'getGatewayClientContext') {
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
}
requests.push({ method, requestData }); requests.push({ method, requestData });
if (method === 'exportCertificate') { if (method === 'exportCertificate') {
return { success: false }; return { success: false };
@@ -146,14 +152,14 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
await manager.syncServiceRoute(service); await manager.syncServiceRoute(service);
const syncRequest = requests.find((request) => request.method === 'syncWorkAppRoute')!; const syncRequest = requests.find((request) => request.method === 'syncGatewayClientRoute')!;
const route = syncRequest.requestData.route as any; const route = syncRequest.requestData.route as any;
const ownership = syncRequest.requestData.ownership as any; const ownership = syncRequest.requestData.ownership as any;
assertEquals(ownership, { assertEquals(ownership, {
workHosterType: 'onebox', gatewayClientType: 'onebox',
workHosterId: 'onebox-1', gatewayClientId: 'onebox-token',
workAppId: 'hello', appId: 'hello',
hostname: 'hello.example.com', hostname: 'hello.example.com',
}); });
assertEquals(route.match, { ports: [443], domains: ['hello.example.com'] }); assertEquals(route.match, { ports: [443], domains: ['hello.example.com'] });
@@ -162,13 +168,62 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
assertEquals(syncRequest.requestData.enabled, true); assertEquals(syncRequest.requestData.enabled, true);
}); });
Deno.test('ExternalGatewayManager deletes service routes through dcrouter WorkHoster API', async () => { Deno.test('ExternalGatewayManager uses managed dcrouter local target in managed mode', async () => {
const oneboxRef = makeOneboxRef();
(oneboxRef as any).managedDcRouter = {
getMode: () => 'managed',
getGatewayUrl: () => 'http://127.0.0.1:3300',
getAdminToken: async () => 'dcr-managed-token',
ensureGatewayClientId: () => 'onebox-managed',
getRouteTarget: () => ({ host: 'onebox-smartproxy', port: 80 }),
};
const service: IService = {
id: 1,
name: 'hello',
image: 'nginx:latest',
envVars: {},
port: 3000,
domain: 'hello.example.com',
status: 'running',
createdAt: 1,
updatedAt: 1,
};
let syncRequest: Record<string, unknown> | null = null;
const manager = new ExternalGatewayManager(oneboxRef as any);
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>, config: any) => {
if (method === 'getGatewayClientContext') {
return { context: { role: 'admin' } };
}
if (method === 'exportCertificate') {
return { success: false };
}
assertEquals(config.url, 'http://127.0.0.1:3300');
assertEquals(config.apiToken, 'dcr-managed-token');
syncRequest = requestData;
return { success: true, action: 'created', routeId: 'route-1' };
};
await manager.syncServiceRoute(service);
assert(syncRequest);
const route = (syncRequest as Record<string, unknown>).route as any;
const ownership = (syncRequest as Record<string, unknown>).ownership as any;
assertEquals(ownership.gatewayClientId, 'onebox-managed');
assertEquals(route.action.targets, [{ host: 'onebox-smartproxy', port: 80 }]);
});
Deno.test('ExternalGatewayManager deletes service routes through dcrouter gatewayClient API', async () => {
const oneboxRef = makeOneboxRef(); const oneboxRef = makeOneboxRef();
const manager = new ExternalGatewayManager(oneboxRef as any); const manager = new ExternalGatewayManager(oneboxRef as any);
let deleteRequest: Record<string, unknown> | null = null; let deleteRequest: Record<string, unknown> | null = null;
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => { (manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
assertEquals(method, 'syncWorkAppRoute'); if (method === 'getGatewayClientContext') {
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
}
assertEquals(method, 'syncGatewayClientRoute');
deleteRequest = requestData; deleteRequest = requestData;
return { success: true, action: 'deleted', routeId: 'route-1' }; return { success: true, action: 'deleted', routeId: 'route-1' };
}; };
@@ -182,6 +237,7 @@ Deno.test('ExternalGatewayManager deletes service routes through dcrouter WorkHo
assert(deleteRequest); assert(deleteRequest);
const capturedDeleteRequest = deleteRequest as Record<string, unknown>; const capturedDeleteRequest = deleteRequest as Record<string, unknown>;
assertEquals(capturedDeleteRequest.delete, true); assertEquals(capturedDeleteRequest.delete, true);
assertEquals((capturedDeleteRequest.ownership as any).gatewayClientId, 'onebox-token');
assertEquals((capturedDeleteRequest.ownership as any).hostname, 'hello.example.com'); assertEquals((capturedDeleteRequest.ownership as any).hostname, 'hello.example.com');
}); });
@@ -189,6 +245,9 @@ Deno.test('ExternalGatewayManager imports exported dcrouter certificates into On
const oneboxRef = makeOneboxRef(); const oneboxRef = makeOneboxRef();
const manager = new ExternalGatewayManager(oneboxRef as any); const manager = new ExternalGatewayManager(oneboxRef as any);
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => { (manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
if (method === 'getGatewayClientContext') {
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
}
assertEquals(method, 'exportCertificate'); assertEquals(method, 'exportCertificate');
assertEquals(requestData.domain, 'hello.example.com'); assertEquals(requestData.domain, 'hello.example.com');
return { return {
+54
View File
@@ -0,0 +1,54 @@
import { assert, assertEquals } from '@std/assert';
import { ManagedDcRouterManager } from '../ts/classes/managed-dcrouter.ts';
class FakeDatabase {
public settings = new Map<string, string>();
public secretSettings = new Map<string, string>();
getSetting(key: string): string | null {
return this.settings.get(key) ?? null;
}
setSetting(key: string, value: string): void {
this.settings.set(key, value);
}
async getSecretSetting(key: string): Promise<string | null> {
return this.secretSettings.get(key) ?? null;
}
async setSecretSetting(key: string, value: string): Promise<void> {
this.secretSettings.set(key, value);
}
}
Deno.test('ManagedDcRouterManager persists default managed gateway settings', async () => {
const database = new FakeDatabase();
const manager = new ManagedDcRouterManager({ database } as any);
assertEquals(manager.getMode(), 'managed');
await manager.prepareGatewaySettings();
assertEquals(database.getSetting('dcrouterMode'), 'managed');
assertEquals(manager.getMode(), 'managed');
assertEquals(database.getSetting('dcrouterGatewayUrl'), 'http://127.0.0.1:3300');
assertEquals(database.getSetting('dcrouterTargetHost'), 'onebox-smartproxy');
assertEquals(database.getSetting('dcrouterTargetPort'), '80');
assert(database.getSetting('dcrouterGatewayClientId')?.startsWith('onebox-'));
assert((await database.getSecretSetting('dcrouterManagedAdminApiToken'))?.startsWith('dcr_'));
});
Deno.test('ManagedDcRouterManager keeps existing external gateway default external', async () => {
const database = new FakeDatabase();
database.setSetting('dcrouterGatewayUrl', 'https://edge.example.com');
const manager = new ManagedDcRouterManager({ database } as any);
assertEquals(manager.getMode(), 'external');
await manager.prepareGatewaySettings();
assertEquals(database.getSetting('dcrouterMode'), null);
assertEquals(database.getSetting('dcrouterTargetHost'), null);
});
+1 -1
View File
@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@serve.zone/onebox', name: '@serve.zone/onebox',
version: '1.24.2', version: '1.27.0',
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers' description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
} }
+226 -34
View File
@@ -3,19 +3,40 @@ import { logger } from '../logging.ts';
import { getErrorMessage } from '../utils/error.ts'; import { getErrorMessage } from '../utils/error.ts';
import { OneboxDatabase } from './database.ts'; import { OneboxDatabase } from './database.ts';
import type { IDomain, IService } from '../types.ts'; import type { IDomain, IService } from '../types.ts';
import type { TDcRouterMode } from './managed-dcrouter.ts';
type TWorkHosterType = 'onebox'; type TWorkHosterType = 'onebox';
interface IExternalGatewayConfig { interface IExternalGatewayConfig {
url: string; url: string;
apiToken: string; apiToken: string;
workHosterId: string; gatewayClientType?: TWorkHosterType;
gatewayClientId?: string;
/** @deprecated Use gatewayClientId. */
workHosterId?: string;
targetHost?: string; targetHost?: string;
targetPort?: number; targetPort?: number;
} }
interface IGatewayClientContextResponse {
context: {
role: 'admin' | 'gatewayClient' | 'operator';
gatewayClient?: {
type: 'onebox' | 'cloudly' | 'custom';
id: string;
};
};
}
interface IWorkHosterDomain { interface IWorkHosterDomain {
id?: string;
name: string; name: string;
source?: 'dcrouter' | 'provider';
authoritative?: boolean;
providerId?: string;
serviceCount?: number;
managePath?: string;
manageUrl?: string;
capabilities?: { capabilities?: {
canCreateSubdomains: boolean; canCreateSubdomains: boolean;
canManageDnsRecords: boolean; canManageDnsRecords: boolean;
@@ -24,6 +45,26 @@ interface IWorkHosterDomain {
}; };
} }
interface IGatewayDnsRecord {
id: string;
domainId: string;
domainName?: string;
name: string;
type: string;
value: string;
ttl: number;
source: string;
status: 'active' | 'missing';
gatewayClientType: 'onebox' | 'cloudly' | 'custom';
gatewayClientId: string;
appId: string;
hostname: string;
routeId?: string;
serviceName?: string;
managePath?: string;
manageUrl?: string;
}
interface IWorkAppRouteOwnership { interface IWorkAppRouteOwnership {
workHosterType: TWorkHosterType; workHosterType: TWorkHosterType;
workHosterId: string; workHosterId: string;
@@ -31,6 +72,13 @@ interface IWorkAppRouteOwnership {
hostname: string; hostname: string;
} }
interface IGatewayClientOwnership {
gatewayClientType?: TWorkHosterType;
gatewayClientId?: string;
appId: string;
hostname: string;
}
interface IWorkAppRouteSyncResult { interface IWorkAppRouteSyncResult {
success: boolean; success: boolean;
action?: 'created' | 'updated' | 'deleted' | 'unchanged'; action?: 'created' | 'updated' | 'deleted' | 'unchanged';
@@ -88,17 +136,24 @@ export class ExternalGatewayManager {
} }
public async isConfigured(): Promise<boolean> { public async isConfigured(): Promise<boolean> {
const config = await this.getConfig({ requireTarget: false }); if (this.getMode() === 'disabled') {
return Boolean(config); return false;
}
const mode = this.getMode();
const url = mode === 'managed'
? this.oneboxRef.managedDcRouter.getGatewayUrl()
: this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
const apiToken = mode === 'managed'
? await this.oneboxRef.managedDcRouter.getAdminToken()
: await this.database.getSecretSetting('dcrouterGatewayApiToken');
return Boolean(url && apiToken);
} }
public async syncDomains(): Promise<IDomain[]> { public async syncDomains(): Promise<IDomain[]> {
const config = await this.requireConfig({ requireTarget: false }); if (!(await this.isConfigured())) {
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>( return this.database.getDomainsByProvider('dcrouter');
'getWorkHosterDomains', }
{}, const response = { domains: await this.getGatewayDomains() };
config,
);
const activeDomainNames = new Set<string>(); const activeDomainNames = new Set<string>();
const now = Date.now(); const now = Date.now();
@@ -143,6 +198,55 @@ export class ExternalGatewayManager {
return this.database.getDomainsByProvider('dcrouter'); return this.database.getDomainsByProvider('dcrouter');
} }
public async getGatewayDomains(): Promise<IWorkHosterDomain[]> {
const config = await this.getConfig({ requireTarget: false });
if (!config) return [];
try {
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
'getGatewayClientDomains',
config.gatewayClientId ? { gatewayClientId: config.gatewayClientId } : {},
config,
);
return response.domains.map((domain) => ({
...domain,
manageUrl: this.buildManageUrl(config, domain.managePath),
}));
} catch (error) {
logger.debug(`Falling back to legacy gateway domain API: ${getErrorMessage(error)}`);
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
'getWorkHosterDomains',
{},
config,
);
return response.domains.map((domain) => ({
...domain,
manageUrl: this.buildManageUrl(config, domain.managePath),
}));
}
}
public async getGatewayDnsRecords(): Promise<IGatewayDnsRecord[]> {
const config = await this.getConfig({ requireTarget: false });
if (!config) return [];
try {
const response = await this.fireDcRouterRequest<{ records: IGatewayDnsRecord[] }>(
'getGatewayClientDnsRecords',
config.gatewayClientId ? { gatewayClientId: config.gatewayClientId } : {},
config,
);
return response.records.map((record) => ({
...record,
serviceName: record.serviceName || record.appId,
manageUrl: this.buildManageUrl(config, record.managePath),
}));
} catch (error) {
logger.warn(`Failed to fetch gateway DNS records: ${getErrorMessage(error)}`);
return [];
}
}
public async syncServiceRoute(service: IService): Promise<void> { public async syncServiceRoute(service: IService): Promise<void> {
if (!service.domain) return; if (!service.domain) return;
@@ -150,14 +254,24 @@ export class ExternalGatewayManager {
if (!config) return; if (!config) return;
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>( const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
'syncWorkAppRoute', 'syncGatewayClientRoute',
{ {
ownership: this.buildOwnership(service, service.domain, config), ownership: this.buildGatewayClientOwnership(service, service.domain, config),
route: this.buildRoute(service, config), route: this.buildRoute(service, config),
enabled: service.status === 'running', enabled: service.status === 'running',
}, },
config, config,
); ).catch(async () => {
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
'syncWorkAppRoute',
{
ownership: this.buildOwnership(service, service.domain!, config),
route: this.buildRoute(service, config),
enabled: service.status === 'running',
},
config,
);
});
if (!result.success) { if (!result.success) {
throw new Error(result.message || `dcrouter route sync failed for ${service.domain}`); throw new Error(result.message || `dcrouter route sync failed for ${service.domain}`);
@@ -176,13 +290,22 @@ export class ExternalGatewayManager {
if (!config) return; if (!config) return;
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>( const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
'syncWorkAppRoute', 'syncGatewayClientRoute',
{ {
ownership: this.buildOwnership(service, service.domain, config), ownership: this.buildGatewayClientOwnership(service, service.domain, config),
delete: true, delete: true,
}, },
config, config,
); ).catch(async () => {
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
'syncWorkAppRoute',
{
ownership: this.buildOwnership(service, service.domain!, config),
delete: true,
},
config,
);
});
if (!result.success) { if (!result.success) {
throw new Error(result.message || `dcrouter route delete failed for ${service.domain}`); throw new Error(result.message || `dcrouter route delete failed for ${service.domain}`);
@@ -234,8 +357,17 @@ export class ExternalGatewayManager {
} }
private async getConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig | null> { private async getConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig | null> {
const url = this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || ''); const mode = this.getMode();
const apiToken = await this.database.getSecretSetting('dcrouterGatewayApiToken'); if (mode === 'disabled') {
return null;
}
const url = mode === 'managed'
? this.oneboxRef.managedDcRouter.getGatewayUrl()
: this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
const apiToken = mode === 'managed'
? await this.oneboxRef.managedDcRouter.getAdminToken()
: await this.database.getSecretSetting('dcrouterGatewayApiToken');
if (!url || !apiToken) { if (!url || !apiToken) {
return null; return null;
} }
@@ -243,19 +375,40 @@ export class ExternalGatewayManager {
const config: IExternalGatewayConfig = { const config: IExternalGatewayConfig = {
url, url,
apiToken, apiToken,
workHosterId: this.ensureWorkHosterId(),
}; };
const contextClient = await this.getGatewayClientFromToken(config);
if (contextClient) {
config.gatewayClientType = contextClient.type;
config.gatewayClientId = contextClient.id;
config.workHosterId = contextClient.id;
} else {
const fallbackGatewayClientId = mode === 'managed'
? this.oneboxRef.managedDcRouter.ensureGatewayClientId()
: this.getStoredGatewayClientId();
if (fallbackGatewayClientId) {
config.gatewayClientType = 'onebox';
config.gatewayClientId = fallbackGatewayClientId;
config.workHosterId = fallbackGatewayClientId;
}
}
if (options.requireTarget !== false) { if (options.requireTarget !== false) {
config.targetHost = this.database.getSetting('dcrouterTargetHost') if (mode === 'managed') {
|| this.database.getSetting('serverIP') const target = this.oneboxRef.managedDcRouter.getRouteTarget();
|| undefined; config.targetHost = target.host;
const targetPort = this.parsePort( config.targetPort = target.port;
this.database.getSetting('dcrouterTargetPort') } else {
|| this.database.getSetting('httpPort') config.targetHost = this.database.getSetting('dcrouterTargetHost')
|| '80', || this.database.getSetting('serverIP')
); || undefined;
config.targetPort = targetPort; const targetPort = this.parsePort(
this.database.getSetting('dcrouterTargetPort')
|| this.database.getSetting('httpPort')
|| '80',
);
config.targetPort = targetPort;
}
if (!config.targetHost) { if (!config.targetHost) {
throw new Error('dcrouterTargetHost or serverIP must be configured for external gateway route sync'); throw new Error('dcrouterTargetHost or serverIP must be configured for external gateway route sync');
@@ -265,6 +418,10 @@ export class ExternalGatewayManager {
return config; return config;
} }
private getMode(): TDcRouterMode {
return this.oneboxRef.managedDcRouter?.getMode?.() || 'external';
}
private async requireConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig> { private async requireConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig> {
const config = await this.getConfig(options); const config = await this.getConfig(options);
if (!config) { if (!config) {
@@ -288,13 +445,27 @@ export class ExternalGatewayManager {
return port; return port;
} }
private ensureWorkHosterId(): string { private getStoredGatewayClientId(): string {
let workHosterId = this.database.getSetting('dcrouterWorkHosterId'); return this.database.getSetting('dcrouterGatewayClientId') || this.database.getSetting('dcrouterWorkHosterId') || '';
if (!workHosterId) { }
workHosterId = crypto.randomUUID();
this.database.setSetting('dcrouterWorkHosterId', workHosterId); private async getGatewayClientFromToken(config: IExternalGatewayConfig): Promise<{ type: TWorkHosterType; id: string } | null> {
try {
const response = await this.fireDcRouterRequest<IGatewayClientContextResponse>(
'getGatewayClientContext',
{},
config,
);
const gatewayClient = response.context.gatewayClient;
if (!gatewayClient) return null;
if (gatewayClient.type !== 'onebox') {
throw new Error(`dcrouter token is bound to unsupported gateway client type: ${gatewayClient.type}`);
}
return { type: gatewayClient.type, id: gatewayClient.id };
} catch (error) {
logger.debug(`dcrouter gateway client context unavailable: ${getErrorMessage(error)}`);
return null;
} }
return workHosterId;
} }
private buildOwnership( private buildOwnership(
@@ -304,12 +475,28 @@ export class ExternalGatewayManager {
): IWorkAppRouteOwnership { ): IWorkAppRouteOwnership {
return { return {
workHosterType: 'onebox', workHosterType: 'onebox',
workHosterId: config.workHosterId, workHosterId: config.gatewayClientId || '',
workAppId: service.name || `service-${service.id}`, workAppId: service.name || `service-${service.id}`,
hostname, hostname,
}; };
} }
private buildGatewayClientOwnership(
service: Pick<IService, 'id' | 'name'>,
hostname: string,
config: IExternalGatewayConfig,
): IGatewayClientOwnership {
const ownership: IGatewayClientOwnership = {
gatewayClientType: config.gatewayClientType || 'onebox',
appId: service.name || `service-${service.id}`,
hostname,
};
if (config.gatewayClientId) {
ownership.gatewayClientId = config.gatewayClientId;
}
return ownership;
}
private buildRoute(service: IService, config: IExternalGatewayConfig): IDcRouterRouteConfig { private buildRoute(service: IService, config: IExternalGatewayConfig): IDcRouterRouteConfig {
return { return {
name: this.routeName(service.domain!), name: this.routeName(service.domain!),
@@ -335,6 +522,11 @@ export class ExternalGatewayManager {
return `onebox-${domain.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '')}`; return `onebox-${domain.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '')}`;
} }
private buildManageUrl(config: IExternalGatewayConfig, managePath?: string): string {
const normalizedPath = managePath?.startsWith('/') ? managePath : managePath ? `/${managePath}` : '';
return `${config.url}${normalizedPath}`;
}
private async fireDcRouterRequest<TResponse>( private async fireDcRouterRequest<TResponse>(
method: string, method: string,
requestData: Record<string, unknown>, requestData: Record<string, unknown>,
+332
View File
@@ -0,0 +1,332 @@
import * as plugins from '../plugins.ts';
import { logger } from '../logging.ts';
import { getErrorMessage } from '../utils/error.ts';
import { OneboxDatabase } from './database.ts';
export type TDcRouterMode = 'managed' | 'external' | 'disabled';
export interface IManagedDcRouterStatus {
mode: TDcRouterMode;
configured: boolean;
running: boolean;
healthy: boolean;
containerId?: string;
image: string;
gatewayUrl: string;
opsPort: number;
httpPort: number;
httpsPort: number;
message?: string;
}
const containerName = 'onebox-dcrouter';
const defaultImage = 'code.foss.global/serve.zone/dcrouter:latest';
const defaultDataDir = './.nogit/dcrouter-data';
const defaultOpsPort = 3300;
const defaultHttpPort = 80;
const defaultHttpsPort = 443;
const internalBaseDir = '/data';
export class ManagedDcRouterManager {
private database: OneboxDatabase;
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
constructor(private oneboxRef: any) {
this.database = oneboxRef.database;
}
public getMode(): TDcRouterMode {
const storedMode = this.database.getSetting('dcrouterMode');
if (storedMode === 'managed' || storedMode === 'external' || storedMode === 'disabled') {
return storedMode;
}
const hasExternalGateway = Boolean(this.database.getSetting('dcrouterGatewayUrl'));
return hasExternalGateway ? 'external' : 'managed';
}
public getImage(): string {
return this.database.getSetting('dcrouterManagedImage') || defaultImage;
}
public getOpsPort(): number {
return this.parsePort(this.database.getSetting('dcrouterManagedOpsPort'), defaultOpsPort);
}
public getHttpPort(): number {
return this.parsePort(this.database.getSetting('dcrouterManagedHttpPort'), defaultHttpPort);
}
public getHttpsPort(): number {
return this.parsePort(this.database.getSetting('dcrouterManagedHttpsPort'), defaultHttpsPort);
}
public getDataDir(): string {
return this.database.getSetting('dcrouterManagedDataDir') || defaultDataDir;
}
public getGatewayUrl(): string {
return `http://127.0.0.1:${this.getOpsPort()}`;
}
public getRouteTarget(): { host: string; port: number } {
return {
host: 'onebox-smartproxy',
port: 80,
};
}
public ensureGatewayClientId(): string {
let gatewayClientId = this.database.getSetting('dcrouterGatewayClientId')
|| this.database.getSetting('dcrouterWorkHosterId');
if (!gatewayClientId) {
gatewayClientId = `onebox-${crypto.randomUUID()}`;
this.database.setSetting('dcrouterGatewayClientId', gatewayClientId);
}
return gatewayClientId;
}
public async getAdminToken(): Promise<string> {
const existingToken = await this.database.getSecretSetting('dcrouterManagedAdminApiToken');
if (existingToken) {
return existingToken;
}
const token = `dcr_${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().replaceAll('-', '')}`;
await this.database.setSecretSetting('dcrouterManagedAdminApiToken', token);
return token;
}
public async prepareGatewaySettings(): Promise<void> {
if (this.getMode() !== 'managed') {
return;
}
const target = this.getRouteTarget();
this.database.setSetting('dcrouterMode', 'managed');
this.database.setSetting('dcrouterGatewayUrl', this.getGatewayUrl());
this.database.setSetting('dcrouterTargetHost', target.host);
this.database.setSetting('dcrouterTargetPort', String(target.port));
this.ensureGatewayClientId();
await this.getAdminToken();
}
public async init(): Promise<void> {
if (this.getMode() === 'managed') {
await this.start();
return;
}
await this.stop();
}
public async start(options: { recreate?: boolean } = {}): Promise<IManagedDcRouterStatus> {
if (this.getMode() !== 'managed') {
throw new Error('Managed dcrouter mode is not enabled');
}
await this.prepareGatewaySettings();
await this.ensureDockerClient();
if (options.recreate) {
await this.removeExistingContainer();
}
const existingContainer = await this.getExistingContainer();
if (existingContainer) {
if (this.isContainerRunning(existingContainer)) {
await this.waitForReady().catch((error) => {
logger.warn(`Managed dcrouter readiness check failed: ${getErrorMessage(error)}`);
});
return await this.getStatus();
}
await this.startContainer(existingContainer.Id);
await this.waitForReady();
return await this.getStatus();
}
await this.createContainer();
await this.waitForReady();
return await this.getStatus();
}
public async stop(): Promise<IManagedDcRouterStatus> {
await this.ensureDockerClient();
const existingContainer = await this.getExistingContainer();
if (existingContainer && this.isContainerRunning(existingContainer)) {
await this.stopContainer(existingContainer.Id);
}
return await this.getStatus();
}
public async restart(): Promise<IManagedDcRouterStatus> {
return await this.start({ recreate: true });
}
public async getStatus(): Promise<IManagedDcRouterStatus> {
const baseStatus: IManagedDcRouterStatus = {
mode: this.getMode(),
configured: this.getMode() === 'managed',
running: false,
healthy: false,
image: this.getImage(),
gatewayUrl: this.getGatewayUrl(),
opsPort: this.getOpsPort(),
httpPort: this.getHttpPort(),
httpsPort: this.getHttpsPort(),
};
try {
await this.ensureDockerClient();
const existingContainer = await this.getExistingContainer();
if (!existingContainer) {
return baseStatus;
}
const running = this.isContainerRunning(existingContainer);
return {
...baseStatus,
running,
healthy: running ? await this.checkHealthy() : false,
containerId: existingContainer.Id,
};
} catch (error) {
return {
...baseStatus,
message: getErrorMessage(error),
};
}
}
private async ensureDockerClient(): Promise<void> {
if (!this.dockerClient) {
this.dockerClient = new plugins.docker.Docker({
socketPath: 'unix:///var/run/docker.sock',
});
await this.dockerClient.start();
}
}
private parsePort(value: string | null, fallback: number): number {
if (!value) return fallback;
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return fallback;
}
return port;
}
private async getAbsoluteDataDir(): Promise<string> {
const dataDir = plugins.path.resolve(this.getDataDir());
await Deno.mkdir(dataDir, { recursive: true });
return dataDir;
}
private async createContainer(): Promise<void> {
const image = this.getImage();
const token = await this.getAdminToken();
const dataDir = await this.getAbsoluteDataDir();
await this.oneboxRef.docker.pullImage(image);
const response = await this.dockerClient!.request('POST', `/containers/create?name=${containerName}`, {
Image: image,
Env: [
`DCROUTER_BASE_DIR=${internalBaseDir}`,
`DCROUTER_ADMIN_API_TOKEN=${token}`,
'DCROUTER_ADMIN_API_TOKEN_NAME=Onebox Managed Admin Token',
],
Labels: {
'managed-by': 'onebox',
'onebox-type': 'dcrouter',
},
ExposedPorts: {
'80/tcp': {},
'443/tcp': {},
'3000/tcp': {},
},
HostConfig: {
NetworkMode: 'onebox-network',
RestartPolicy: {
Name: 'unless-stopped',
},
Binds: [`${dataDir}:${internalBaseDir}`],
PortBindings: {
'80/tcp': [{ HostIp: '0.0.0.0', HostPort: String(this.getHttpPort()) }],
'443/tcp': [{ HostIp: '0.0.0.0', HostPort: String(this.getHttpsPort()) }],
'3000/tcp': [{ HostIp: '127.0.0.1', HostPort: String(this.getOpsPort()) }],
},
},
});
if (response.statusCode >= 300) {
throw new Error(`Failed to create managed dcrouter container: HTTP ${response.statusCode} - ${JSON.stringify(response.body)}`);
}
await this.startContainer(response.body.Id);
logger.success(`Managed dcrouter container started: ${response.body.Id}`);
}
private async getExistingContainer(): Promise<any | null> {
const filters = encodeURIComponent(JSON.stringify({ name: [containerName] }));
const response = await this.dockerClient!.request('GET', `/containers/json?all=true&filters=${filters}`, {});
if (response.statusCode >= 300 || !Array.isArray(response.body)) {
return null;
}
return response.body.find((container: any) => {
return container.Names?.some((name: string) => name === `/${containerName}` || name === containerName);
}) ?? null;
}
private isContainerRunning(container: any): boolean {
return container.State === 'running' || Boolean(container.Status?.toLowerCase().startsWith('up '));
}
private async startContainer(containerId: string): Promise<void> {
const response = await this.dockerClient!.request('POST', `/containers/${containerId}/start`, {});
if (response.statusCode >= 300 && response.statusCode !== 304) {
throw new Error(`Failed to start managed dcrouter container: HTTP ${response.statusCode}`);
}
}
private async stopContainer(containerId: string): Promise<void> {
const response = await this.dockerClient!.request('POST', `/containers/${containerId}/stop`, {});
if (response.statusCode >= 300 && response.statusCode !== 304) {
throw new Error(`Failed to stop managed dcrouter container: HTTP ${response.statusCode}`);
}
}
private async removeExistingContainer(): Promise<void> {
const existingContainer = await this.getExistingContainer();
if (!existingContainer) {
return;
}
const response = await this.dockerClient!.request('DELETE', `/containers/${existingContainer.Id}?force=true`, {});
if (response.statusCode >= 300) {
throw new Error(`Failed to remove managed dcrouter container: HTTP ${response.statusCode}`);
}
}
private async checkHealthy(): Promise<boolean> {
try {
const response = await fetch(this.getGatewayUrl());
return response.ok;
} catch {
return false;
}
}
private async waitForReady(maxAttempts = 30, intervalMs = 1000): Promise<void> {
for (let i = 0; i < maxAttempts; i++) {
if (await this.checkHealthy()) {
return;
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
throw new Error('Managed dcrouter did not become ready in time');
}
}
+29 -3
View File
@@ -25,6 +25,7 @@ import { ProxyLogReceiver } from './proxy-log-receiver.ts';
import { BackupManager } from './backup-manager.ts'; import { BackupManager } from './backup-manager.ts';
import { BackupScheduler } from './backup-scheduler.ts'; import { BackupScheduler } from './backup-scheduler.ts';
import { ExternalGatewayManager } from './external-gateway.ts'; import { ExternalGatewayManager } from './external-gateway.ts';
import { ManagedDcRouterManager } from './managed-dcrouter.ts';
import { OpsServer } from '../opsserver/index.ts'; import { OpsServer } from '../opsserver/index.ts';
export class Onebox { export class Onebox {
@@ -45,6 +46,7 @@ export class Onebox {
public proxyLogReceiver: ProxyLogReceiver; public proxyLogReceiver: ProxyLogReceiver;
public backupManager: BackupManager; public backupManager: BackupManager;
public backupScheduler: BackupScheduler; public backupScheduler: BackupScheduler;
public managedDcRouter: ManagedDcRouterManager;
public externalGateway: ExternalGatewayManager; public externalGateway: ExternalGatewayManager;
public opsServer: OpsServer; public opsServer: OpsServer;
@@ -88,7 +90,8 @@ export class Onebox {
// Initialize Backup scheduler // Initialize Backup scheduler
this.backupScheduler = new BackupScheduler(this); this.backupScheduler = new BackupScheduler(this);
// Initialize optional dcrouter edge gateway integration // Initialize optional dcrouter gateway integration
this.managedDcRouter = new ManagedDcRouterManager(this);
this.externalGateway = new ExternalGatewayManager(this); this.externalGateway = new ExternalGatewayManager(this);
// Initialize OpsServer (TypedRequest-based server) // Initialize OpsServer (TypedRequest-based server)
@@ -111,6 +114,20 @@ export class Onebox {
// Initialize Docker // Initialize Docker
await this.docker.init(); await this.docker.init();
try {
await this.managedDcRouter.prepareGatewaySettings();
} catch (error) {
logger.warn(`Managed dcrouter settings preparation failed: ${getErrorMessage(error)}`);
}
if (this.managedDcRouter.getMode() !== 'managed') {
try {
await this.managedDcRouter.stop();
} catch (error) {
logger.warn(`Failed to stop inactive managed dcrouter: ${getErrorMessage(error)}`);
}
}
// Start proxy log receiver before reverse proxy startup. // Start proxy log receiver before reverse proxy startup.
try { try {
await this.proxyLogReceiver.start(); await this.proxyLogReceiver.start();
@@ -128,8 +145,9 @@ export class Onebox {
// Start HTTP reverse proxy (non-critical - don't fail init if ports are busy) // Start HTTP reverse proxy (non-critical - don't fail init if ports are busy)
// Use 8080/8443 in dev mode to avoid permission issues // Use 8080/8443 in dev mode to avoid permission issues
const isDev = Deno.env.get('ONEBOX_DEV') === 'true' || Deno.args.includes('--ephemeral'); const isDev = Deno.env.get('ONEBOX_DEV') === 'true' || Deno.args.includes('--ephemeral');
const httpPort = isDev ? 8080 : 80; const isManagedDcRouter = this.managedDcRouter.getMode() === 'managed';
const httpsPort = isDev ? 8443 : 443; const httpPort = isDev || isManagedDcRouter ? 8080 : 80;
const httpsPort = isDev || isManagedDcRouter ? 8443 : 443;
try { try {
await this.reverseProxy.startHttp(httpPort); await this.reverseProxy.startHttp(httpPort);
@@ -165,6 +183,14 @@ export class Onebox {
logger.warn('Cloudflare domain sync initialization failed - domain sync will be limited'); logger.warn('Cloudflare domain sync initialization failed - domain sync will be limited');
} }
// Initialize managed local dcrouter before syncing delegated routes.
try {
await this.managedDcRouter.init();
} catch (error) {
logger.warn('Managed dcrouter initialization failed - local gateway sync will be disabled');
logger.warn(`Error: ${getErrorMessage(error)}`);
}
// Initialize external dcrouter gateway (non-critical) // Initialize external dcrouter gateway (non-critical)
try { try {
await this.externalGateway.init(); await this.externalGateway.init();
+8 -6
View File
@@ -179,7 +179,7 @@ export class SmartProxyManager {
await this.waitForReady(); await this.waitForReady();
this.serviceRunning = true; this.serviceRunning = true;
await this.reloadConfig(); await this.reloadConfig({ skipRunningCheck: true });
logger.success(`SmartProxy started (HTTP: ${this.httpPort}, HTTPS: ${this.httpsPort}, Admin: ${this.adminUrl})`); logger.success(`SmartProxy started (HTTP: ${this.httpPort}, HTTPS: ${this.httpsPort}, Admin: ${this.adminUrl})`);
} catch (error) { } catch (error) {
@@ -360,11 +360,13 @@ export class SmartProxyManager {
return routeConfigs; return routeConfigs;
} }
async reloadConfig(): Promise<void> { async reloadConfig(options: { skipRunningCheck?: boolean } = {}): Promise<void> {
const isRunning = await this.isRunning(); if (!options.skipRunningCheck) {
if (!isRunning) { const isRunning = await this.isRunning();
logger.warn('SmartProxy not running, cannot reload config'); if (!isRunning) {
return; logger.warn('SmartProxy not running, cannot reload config');
return;
}
} }
const routes = this.buildRoutes(); const routes = this.buildRoutes();
+1
View File
@@ -7,6 +7,7 @@ const secretSettingAliases = {
backupPassword: ['backup_encryption_password'], backupPassword: ['backup_encryption_password'],
cloudflareToken: ['cloudflareAPIKey'], cloudflareToken: ['cloudflareAPIKey'],
dcrouterGatewayApiToken: ['externalGatewayApiToken'], dcrouterGatewayApiToken: ['externalGatewayApiToken'],
dcrouterManagedAdminApiToken: [],
} as const; } as const;
type TCanonicalSecretSettingKey = keyof typeof secretSettingAliases; type TCanonicalSecretSettingKey = keyof typeof secretSettingAliases;
+2
View File
@@ -23,6 +23,7 @@ export class OpsServer {
public backupsHandler!: handlers.BackupsHandler; public backupsHandler!: handlers.BackupsHandler;
public schedulesHandler!: handlers.SchedulesHandler; public schedulesHandler!: handlers.SchedulesHandler;
public settingsHandler!: handlers.SettingsHandler; public settingsHandler!: handlers.SettingsHandler;
public managedDcRouterHandler!: handlers.ManagedDcRouterHandler;
public logsHandler!: handlers.LogsHandler; public logsHandler!: handlers.LogsHandler;
public workspaceHandler!: handlers.WorkspaceHandler; public workspaceHandler!: handlers.WorkspaceHandler;
public appStoreHandler!: handlers.AppStoreHandler; public appStoreHandler!: handlers.AppStoreHandler;
@@ -66,6 +67,7 @@ export class OpsServer {
this.backupsHandler = new handlers.BackupsHandler(this); this.backupsHandler = new handlers.BackupsHandler(this);
this.schedulesHandler = new handlers.SchedulesHandler(this); this.schedulesHandler = new handlers.SchedulesHandler(this);
this.settingsHandler = new handlers.SettingsHandler(this); this.settingsHandler = new handlers.SettingsHandler(this);
this.managedDcRouterHandler = new handlers.ManagedDcRouterHandler(this);
this.logsHandler = new handlers.LogsHandler(this); this.logsHandler = new handlers.LogsHandler(this);
this.workspaceHandler = new handlers.WorkspaceHandler(this); this.workspaceHandler = new handlers.WorkspaceHandler(this);
this.appStoreHandler = new handlers.AppStoreHandler(this); this.appStoreHandler = new handlers.AppStoreHandler(this);
+1 -6
View File
@@ -2,7 +2,7 @@ import * as plugins from '../../plugins.ts';
import { logger } from '../../logging.ts'; import { logger } from '../../logging.ts';
import type { OpsServer } from '../classes.opsserver.ts'; import type { OpsServer } from '../classes.opsserver.ts';
import * as interfaces from '../../../ts_interfaces/index.ts'; import * as interfaces from '../../../ts_interfaces/index.ts';
import { hashPassword, needsPasswordUpgrade, verifyPassword } from '../../utils/auth.ts'; import { hashPassword, verifyPassword } from '../../utils/auth.ts';
export interface IJwtData { export interface IJwtData {
userId: string; userId: string;
@@ -112,11 +112,6 @@ export class AdminHandler {
throw new plugins.typedrequest.TypedResponseError('Invalid credentials'); throw new plugins.typedrequest.TypedResponseError('Invalid credentials');
} }
if (needsPasswordUpgrade(user.passwordHash)) {
const upgradedHash = await hashPassword(dataArg.password);
this.opsServerRef.oneboxRef.database.updateUserPassword(user.username, upgradedHash);
}
const expiresAt = Date.now() + 24 * 3600 * 1000; const expiresAt = Date.now() + 24 * 3600 * 1000;
const freshUser = this.opsServerRef.oneboxRef.database.getUserByUsername(user.username) || user; const freshUser = this.opsServerRef.oneboxRef.database.getUserByUsername(user.username) || user;
const identity = await this.createIdentityForUser(freshUser, expiresAt); const identity = await this.createIdentityForUser(freshUser, expiresAt);
+11
View File
@@ -61,5 +61,16 @@ export class DnsHandler {
}, },
), ),
); );
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayDnsRecords>(
'getGatewayDnsRecords',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const records = await this.opsServerRef.oneboxRef.externalGateway.getGatewayDnsRecords();
return { records };
},
),
);
} }
} }
+11
View File
@@ -97,5 +97,16 @@ export class DomainsHandler {
}, },
), ),
); );
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayDomains>(
'getGatewayDomains',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const domains = await this.opsServerRef.oneboxRef.externalGateway.getGatewayDomains();
return { domains };
},
),
);
} }
} }
+1
View File
@@ -10,6 +10,7 @@ export * from './network.handler.ts';
export * from './backups.handler.ts'; export * from './backups.handler.ts';
export * from './schedules.handler.ts'; export * from './schedules.handler.ts';
export * from './settings.handler.ts'; export * from './settings.handler.ts';
export * from './managed-dcrouter.handler.ts';
export * from './logs.handler.ts'; export * from './logs.handler.ts';
export * from './workspace.handler.ts'; export * from './workspace.handler.ts';
export * from './appstore.handler.ts'; export * from './appstore.handler.ts';
@@ -0,0 +1,59 @@
import * as plugins from '../../plugins.ts';
import type { OpsServer } from '../classes.opsserver.ts';
import * as interfaces from '../../../ts_interfaces/index.ts';
import { requireAdminIdentity } from '../helpers/guards.ts';
export class ManagedDcRouterHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
constructor(private opsServerRef: OpsServer) {
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
this.registerHandlers();
}
private registerHandlers(): void {
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetManagedDcRouterStatus>(
'getManagedDcRouterStatus',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const status = await this.opsServerRef.oneboxRef.managedDcRouter.getStatus();
return { status };
},
),
);
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartManagedDcRouter>(
'startManagedDcRouter',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const status = await this.opsServerRef.oneboxRef.managedDcRouter.start();
return { status };
},
),
);
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StopManagedDcRouter>(
'stopManagedDcRouter',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const status = await this.opsServerRef.oneboxRef.managedDcRouter.stop();
return { status };
},
),
);
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RestartManagedDcRouter>(
'restartManagedDcRouter',
async (dataArg) => {
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
const status = await this.opsServerRef.oneboxRef.managedDcRouter.restart();
return { status };
},
),
);
}
}
+25 -4
View File
@@ -18,13 +18,21 @@ export class SettingsHandler {
const cloudflareToken = await db.getSecretSetting('cloudflareToken'); const cloudflareToken = await db.getSecretSetting('cloudflareToken');
const dcrouterGatewayApiToken = await db.getSecretSetting('dcrouterGatewayApiToken'); const dcrouterGatewayApiToken = await db.getSecretSetting('dcrouterGatewayApiToken');
const settingsMap = db.getAllSettings(); const settingsMap = db.getAllSettings();
const managedDcRouter = this.opsServerRef.oneboxRef.managedDcRouter;
return { return {
cloudflareToken: cloudflareToken || '', cloudflareToken: cloudflareToken || '',
cloudflareZoneId: settingsMap['cloudflareZoneId'] || '', cloudflareZoneId: settingsMap['cloudflareZoneId'] || '',
dcrouterMode: managedDcRouter.getMode(),
dcrouterManagedImage: managedDcRouter.getImage(),
dcrouterManagedOpsPort: managedDcRouter.getOpsPort(),
dcrouterManagedHttpPort: managedDcRouter.getHttpPort(),
dcrouterManagedHttpsPort: managedDcRouter.getHttpsPort(),
dcrouterManagedDataDir: managedDcRouter.getDataDir(),
dcrouterGatewayUrl: settingsMap['dcrouterGatewayUrl'] || '', dcrouterGatewayUrl: settingsMap['dcrouterGatewayUrl'] || '',
dcrouterGatewayApiToken: dcrouterGatewayApiToken || '', dcrouterGatewayApiToken: dcrouterGatewayApiToken || '',
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || '', dcrouterGatewayClientId: settingsMap['dcrouterGatewayClientId'] || settingsMap['dcrouterWorkHosterId'] || '',
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || settingsMap['dcrouterGatewayClientId'] || '',
dcrouterTargetHost: settingsMap['dcrouterTargetHost'] || '', dcrouterTargetHost: settingsMap['dcrouterTargetHost'] || '',
dcrouterTargetPort: parseInt(settingsMap['dcrouterTargetPort'] || '0', 10), dcrouterTargetPort: parseInt(settingsMap['dcrouterTargetPort'] || '0', 10),
autoRenewCerts: settingsMap['autoRenewCerts'] === 'true', autoRenewCerts: settingsMap['autoRenewCerts'] === 'true',
@@ -68,8 +76,8 @@ export class SettingsHandler {
} }
if (this.hasExternalGatewaySetting(updates)) { if (this.hasExternalGatewaySetting(updates)) {
this.refreshExternalGateway().catch((error) => { this.refreshDcRouterGateway().catch((error) => {
logger.warn(`External gateway settings refresh failed: ${getErrorMessage(error)}`); logger.warn(`dcrouter gateway settings refresh failed: ${getErrorMessage(error)}`);
}); });
} }
@@ -104,16 +112,29 @@ export class SettingsHandler {
private hasExternalGatewaySetting(settings: Partial<interfaces.data.ISettings>): boolean { private hasExternalGatewaySetting(settings: Partial<interfaces.data.ISettings>): boolean {
return [ return [
'dcrouterMode',
'dcrouterManagedImage',
'dcrouterManagedOpsPort',
'dcrouterManagedHttpPort',
'dcrouterManagedHttpsPort',
'dcrouterManagedDataDir',
'dcrouterGatewayUrl', 'dcrouterGatewayUrl',
'dcrouterGatewayApiToken', 'dcrouterGatewayApiToken',
'dcrouterGatewayClientId',
'dcrouterWorkHosterId', 'dcrouterWorkHosterId',
'dcrouterTargetHost', 'dcrouterTargetHost',
'dcrouterTargetPort', 'dcrouterTargetPort',
].some((key) => Object.prototype.hasOwnProperty.call(settings, key)); ].some((key) => Object.prototype.hasOwnProperty.call(settings, key));
} }
private async refreshExternalGateway(): Promise<void> { private async refreshDcRouterGateway(): Promise<void> {
const onebox = this.opsServerRef.oneboxRef; const onebox = this.opsServerRef.oneboxRef;
if (onebox.managedDcRouter.getMode() === 'managed') {
await onebox.managedDcRouter.restart();
} else {
await onebox.managedDcRouter.stop();
}
await onebox.externalGateway.syncDomains(); await onebox.externalGateway.syncDomains();
const services = onebox.database.getAllServices().filter((service) => service.domain); const services = onebox.database.getAllServices().filter((service) => service.domain);
-4
View File
@@ -55,10 +55,6 @@ export const awsS3 = {
import * as taskbuffer from '@push.rocks/taskbuffer'; import * as taskbuffer from '@push.rocks/taskbuffer';
export { taskbuffer }; export { taskbuffer };
// Crypto utilities (for password hashing, encryption)
import * as bcrypt from 'https://deno.land/x/bcrypt@v0.4.1/mod.ts';
export { bcrypt };
// JWT for authentication // JWT for authentication
import * as jwt from 'https://deno.land/x/djwt@v3.0.2/mod.ts'; import * as jwt from 'https://deno.land/x/djwt@v3.0.2/mod.ts';
export { jwt}; export { jwt};
+8
View File
@@ -259,8 +259,16 @@ export interface IAppSettings {
serverIP?: string; serverIP?: string;
cloudflareToken?: string; cloudflareToken?: string;
cloudflareZoneId?: string; cloudflareZoneId?: string;
dcrouterMode?: 'managed' | 'external' | 'disabled';
dcrouterManagedImage?: string;
dcrouterManagedOpsPort?: number;
dcrouterManagedHttpPort?: number;
dcrouterManagedHttpsPort?: number;
dcrouterManagedDataDir?: string;
dcrouterGatewayUrl?: string; dcrouterGatewayUrl?: string;
dcrouterGatewayApiToken?: string; dcrouterGatewayApiToken?: string;
dcrouterGatewayClientId?: string;
/** @deprecated Use dcrouterGatewayClientId. */
dcrouterWorkHosterId?: string; dcrouterWorkHosterId?: string;
dcrouterTargetHost?: string; dcrouterTargetHost?: string;
dcrouterTargetPort?: number; dcrouterTargetPort?: number;
+78 -12
View File
@@ -1,17 +1,79 @@
import * as plugins from '../plugins.ts'; const pbkdf2HashPattern = /^pbkdf2-sha256\$(\d+)\$([A-Za-z0-9+/=]+)\$([A-Za-z0-9+/=]+)$/;
const pbkdf2Iterations = 210_000;
const pbkdf2KeyLengthBits = 256;
const bcryptHashPattern = /^\$2[abxy]\$\d\d\$/; const bytesToBase64 = (bytesArg: Uint8Array): string => {
let binary = '';
for (const byte of bytesArg) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
};
export function isBcryptHash(passwordHash: string): boolean { const base64ToBytes = (base64Arg: string): Uint8Array => {
return bcryptHashPattern.test(passwordHash); const binary = atob(base64Arg);
} const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
};
export function needsPasswordUpgrade(passwordHash: string): boolean { const timingSafeEqual = (aArg: Uint8Array, bArg: Uint8Array): boolean => {
return !isBcryptHash(passwordHash); if (aArg.length !== bArg.length) {
return false;
}
let diff = 0;
for (let i = 0; i < aArg.length; i++) {
diff |= aArg[i] ^ bArg[i];
}
return diff === 0;
};
const toArrayBuffer = (bytesArg: Uint8Array): ArrayBuffer => {
return bytesArg.buffer.slice(
bytesArg.byteOffset,
bytesArg.byteOffset + bytesArg.byteLength,
) as ArrayBuffer;
};
const derivePasswordHash = async (
passwordArg: string,
saltArg: Uint8Array,
iterationsArg: number,
): Promise<Uint8Array> => {
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(passwordArg),
'PBKDF2',
false,
['deriveBits'],
);
const bits = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
hash: 'SHA-256',
salt: toArrayBuffer(saltArg),
iterations: iterationsArg,
},
key,
pbkdf2KeyLengthBits,
);
return new Uint8Array(bits);
};
export function isPbkdf2Hash(passwordHash: string): boolean {
return pbkdf2HashPattern.test(passwordHash);
} }
export async function hashPassword(password: string): Promise<string> { export async function hashPassword(password: string): Promise<string> {
return await plugins.bcrypt.hash(password); // Use Web Crypto only so compiled binaries do not depend on external worker files.
const salt = crypto.getRandomValues(new Uint8Array(16));
const hash = await derivePasswordHash(password, salt, pbkdf2Iterations);
return `pbkdf2-sha256$${pbkdf2Iterations}$${bytesToBase64(salt)}$${bytesToBase64(hash)}`;
} }
export async function verifyPassword(password: string, passwordHash: string): Promise<boolean> { export async function verifyPassword(password: string, passwordHash: string): Promise<boolean> {
@@ -19,10 +81,14 @@ export async function verifyPassword(password: string, passwordHash: string): Pr
return false; return false;
} }
if (isBcryptHash(passwordHash)) { const pbkdf2Match = passwordHash.match(pbkdf2HashPattern);
return await plugins.bcrypt.compare(password, passwordHash); if (pbkdf2Match) {
const iterations = Number(pbkdf2Match[1]);
const salt = base64ToBytes(pbkdf2Match[2]);
const expectedHash = base64ToBytes(pbkdf2Match[3]);
const actualHash = await derivePasswordHash(password, salt, iterations);
return timingSafeEqual(actualHash, expectedHash);
} }
// Legacy compatibility for older databases that stored base64-encoded passwords. return false;
return passwordHash === btoa(password);
} }
+1 -1
View File
File diff suppressed because one or more lines are too long
+37
View File
@@ -57,3 +57,40 @@ export interface IDnsRecord {
createdAt: number; createdAt: number;
updatedAt: number; updatedAt: number;
} }
export interface IGatewayDomain {
id?: string;
name: string;
source?: 'dcrouter' | 'provider';
authoritative?: boolean;
providerId?: string;
serviceCount?: number;
managePath?: string;
manageUrl?: string;
capabilities?: {
canCreateSubdomains: boolean;
canManageDnsRecords: boolean;
canIssueCertificates: boolean;
canHostEmail: boolean;
};
}
export interface IGatewayDnsRecord {
id: string;
domainId: string;
domainName?: string;
name: string;
type: string;
value: string;
ttl: number;
source: string;
status: 'active' | 'missing';
gatewayClientType: 'onebox' | 'cloudly' | 'custom';
gatewayClientId: string;
appId: string;
hostname: string;
routeId?: string;
serviceName?: string;
managePath?: string;
manageUrl?: string;
}
+24
View File
@@ -2,11 +2,35 @@
* Settings data shapes for Onebox * Settings data shapes for Onebox
*/ */
export type TDcRouterMode = 'managed' | 'external' | 'disabled';
export interface IManagedDcRouterStatus {
mode: TDcRouterMode;
configured: boolean;
running: boolean;
healthy: boolean;
containerId?: string;
image: string;
gatewayUrl: string;
opsPort: number;
httpPort: number;
httpsPort: number;
message?: string;
}
export interface ISettings { export interface ISettings {
cloudflareToken: string; cloudflareToken: string;
cloudflareZoneId: string; cloudflareZoneId: string;
dcrouterMode: TDcRouterMode;
dcrouterManagedImage: string;
dcrouterManagedOpsPort: number;
dcrouterManagedHttpPort: number;
dcrouterManagedHttpsPort: number;
dcrouterManagedDataDir: string;
dcrouterGatewayUrl: string; dcrouterGatewayUrl: string;
dcrouterGatewayApiToken: string; dcrouterGatewayApiToken: string;
dcrouterGatewayClientId: string;
/** @deprecated Use dcrouterGatewayClientId. */
dcrouterWorkHosterId: string; dcrouterWorkHosterId: string;
dcrouterTargetHost: string; dcrouterTargetHost: string;
dcrouterTargetPort: number; dcrouterTargetPort: number;
+13
View File
@@ -56,3 +56,16 @@ export interface IReq_SyncDns extends plugins.typedrequestInterfaces.implementsT
records: data.IDnsRecord[]; records: data.IDnsRecord[];
}; };
} }
export interface IReq_GetGatewayDnsRecords extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetGatewayDnsRecords
> {
method: 'getGatewayDnsRecords';
request: {
identity: data.IIdentity;
};
response: {
records: data.IGatewayDnsRecord[];
};
}
+13
View File
@@ -40,3 +40,16 @@ export interface IReq_SyncDomains extends plugins.typedrequestInterfaces.impleme
domains: data.IDomainDetail[]; domains: data.IDomainDetail[];
}; };
} }
export interface IReq_GetGatewayDomains extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetGatewayDomains
> {
method: 'getGatewayDomains';
request: {
identity: data.IIdentity;
};
response: {
domains: data.IGatewayDomain[];
};
}
+52
View File
@@ -54,3 +54,55 @@ export interface IReq_GetBackupPasswordStatus extends plugins.typedrequestInterf
status: data.IBackupPasswordStatus; status: data.IBackupPasswordStatus;
}; };
} }
export interface IReq_GetManagedDcRouterStatus extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_GetManagedDcRouterStatus
> {
method: 'getManagedDcRouterStatus';
request: {
identity: data.IIdentity;
};
response: {
status: data.IManagedDcRouterStatus;
};
}
export interface IReq_StartManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_StartManagedDcRouter
> {
method: 'startManagedDcRouter';
request: {
identity: data.IIdentity;
};
response: {
status: data.IManagedDcRouterStatus;
};
}
export interface IReq_StopManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_StopManagedDcRouter
> {
method: 'stopManagedDcRouter';
request: {
identity: data.IIdentity;
};
response: {
status: data.IManagedDcRouterStatus;
};
}
export interface IReq_RestartManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_RestartManagedDcRouter
> {
method: 'restartManagedDcRouter';
request: {
identity: data.IIdentity;
};
response: {
status: data.IManagedDcRouterStatus;
};
}
+1 -1
View File
@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@serve.zone/onebox', name: '@serve.zone/onebox',
version: '1.24.2', version: '1.27.0',
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers' description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
} }
+102 -3
View File
@@ -36,6 +36,8 @@ export interface INetworkState {
trafficStats: interfaces.data.ITrafficStats | null; trafficStats: interfaces.data.ITrafficStats | null;
dnsRecords: interfaces.data.IDnsRecord[]; dnsRecords: interfaces.data.IDnsRecord[];
domains: interfaces.data.IDomainDetail[]; domains: interfaces.data.IDomainDetail[];
gatewayDomains: interfaces.data.IGatewayDomain[];
gatewayDnsRecords: interfaces.data.IGatewayDnsRecord[];
certificates: interfaces.data.ICertificate[]; certificates: interfaces.data.ICertificate[];
} }
@@ -52,6 +54,7 @@ export interface IBackupsState {
export interface ISettingsState { export interface ISettingsState {
settings: interfaces.data.ISettings | null; settings: interfaces.data.ISettings | null;
backupPasswordConfigured: boolean; backupPasswordConfigured: boolean;
managedDcRouterStatus: interfaces.data.IManagedDcRouterStatus | null;
} }
export interface IAppStoreState { export interface IAppStoreState {
@@ -61,6 +64,7 @@ export interface IAppStoreState {
export interface IUiState { export interface IUiState {
activeView: string; activeView: string;
activeSubview: string | null;
autoRefresh: boolean; autoRefresh: boolean;
refreshInterval: number; refreshInterval: number;
pendingAppTemplate?: any; pendingAppTemplate?: any;
@@ -110,6 +114,8 @@ export const networkStatePart = await appState.getStatePart<INetworkState>(
trafficStats: null, trafficStats: null,
dnsRecords: [], dnsRecords: [],
domains: [], domains: [],
gatewayDomains: [],
gatewayDnsRecords: [],
certificates: [], certificates: [],
}, },
'soft', 'soft',
@@ -138,6 +144,7 @@ export const settingsStatePart = await appState.getStatePart<ISettingsState>(
{ {
settings: null, settings: null,
backupPasswordConfigured: false, backupPasswordConfigured: false,
managedDcRouterStatus: null,
}, },
'soft', 'soft',
); );
@@ -155,6 +162,7 @@ export const uiStatePart = await appState.getStatePart<IUiState>(
'ui', 'ui',
{ {
activeView: 'dashboard', activeView: 'dashboard',
activeSubview: null,
autoRefresh: true, autoRefresh: true,
refreshInterval: 30000, refreshInterval: 30000,
}, },
@@ -628,6 +636,34 @@ export const fetchDomainsAction = networkStatePart.createAction(async (statePart
} }
}); });
export const fetchGatewayDomainsAction = networkStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetGatewayDomains
>('/typedrequest', 'getGatewayDomains');
const response = await typedRequest.fire({ identity: context.identity! });
return { ...statePartArg.getState(), gatewayDomains: response.domains };
} catch (err) {
console.error('Failed to fetch gateway domains:', err);
return statePartArg.getState();
}
});
export const fetchGatewayDnsRecordsAction = networkStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetGatewayDnsRecords
>('/typedrequest', 'getGatewayDnsRecords');
const response = await typedRequest.fire({ identity: context.identity! });
return { ...statePartArg.getState(), gatewayDnsRecords: response.records };
} catch (err) {
console.error('Failed to fetch gateway DNS records:', err);
return statePartArg.getState();
}
});
export const fetchCertificatesAction = networkStatePart.createAction(async (statePartArg) => { export const fetchCertificatesAction = networkStatePart.createAction(async (statePartArg) => {
const context = getActionContext(); const context = getActionContext();
try { try {
@@ -866,17 +902,21 @@ export const triggerScheduleAction = backupsStatePart.createAction<{ scheduleId:
export const fetchSettingsAction = settingsStatePart.createAction(async (statePartArg) => { export const fetchSettingsAction = settingsStatePart.createAction(async (statePartArg) => {
const context = getActionContext(); const context = getActionContext();
try { try {
const [settingsResp, passwordResp] = await Promise.all([ const [settingsResp, passwordResp, managedDcRouterResp] = await Promise.all([
new plugins.domtools.plugins.typedrequest.TypedRequest< new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetSettings interfaces.requests.IReq_GetSettings
>('/typedrequest', 'getSettings').fire({ identity: context.identity! }), >('/typedrequest', 'getSettings').fire({ identity: context.identity! }),
new plugins.domtools.plugins.typedrequest.TypedRequest< new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetBackupPasswordStatus interfaces.requests.IReq_GetBackupPasswordStatus
>('/typedrequest', 'getBackupPasswordStatus').fire({ identity: context.identity! }), >('/typedrequest', 'getBackupPasswordStatus').fire({ identity: context.identity! }),
new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetManagedDcRouterStatus
>('/typedrequest', 'getManagedDcRouterStatus').fire({ identity: context.identity! }),
]); ]);
return { return {
settings: settingsResp.settings, settings: settingsResp.settings,
backupPasswordConfigured: passwordResp.status.isConfigured, backupPasswordConfigured: passwordResp.status.isConfigured,
managedDcRouterStatus: managedDcRouterResp.status,
}; };
} catch (err) { } catch (err) {
console.error('Failed to fetch settings:', err); console.error('Failed to fetch settings:', err);
@@ -903,6 +943,58 @@ export const updateSettingsAction = settingsStatePart.createAction<{
} }
}); });
export const fetchManagedDcRouterStatusAction = settingsStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetManagedDcRouterStatus
>('/typedrequest', 'getManagedDcRouterStatus').fire({ identity: context.identity! });
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
} catch (err) {
console.error('Failed to fetch managed dcrouter status:', err);
return statePartArg.getState();
}
});
export const startManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_StartManagedDcRouter
>('/typedrequest', 'startManagedDcRouter').fire({ identity: context.identity! });
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
} catch (err) {
console.error('Failed to start managed dcrouter:', err);
return statePartArg.getState();
}
});
export const stopManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_StopManagedDcRouter
>('/typedrequest', 'stopManagedDcRouter').fire({ identity: context.identity! });
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
} catch (err) {
console.error('Failed to stop managed dcrouter:', err);
return statePartArg.getState();
}
});
export const restartManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
const context = getActionContext();
try {
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_RestartManagedDcRouter
>('/typedrequest', 'restartManagedDcRouter').fire({ identity: context.identity! });
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
} catch (err) {
console.error('Failed to restart managed dcrouter:', err);
return statePartArg.getState();
}
});
export const setBackupPasswordAction = settingsStatePart.createAction<{ password: string }>( export const setBackupPasswordAction = settingsStatePart.createAction<{ password: string }>(
async (statePartArg, dataArg) => { async (statePartArg, dataArg) => {
const context = getActionContext(); const context = getActionContext();
@@ -926,10 +1018,17 @@ export const setBackupPasswordAction = settingsStatePart.createAction<{ password
// UI Actions // UI Actions
// ============================================================================ // ============================================================================
export const setActiveViewAction = uiStatePart.createAction<{ view: string }>( export const setActiveViewAction = uiStatePart.createAction<{ view: string; subview?: string | null }>(
async (statePartArg, dataArg) => { async (statePartArg, dataArg) => {
const normalizedView = dataArg.view.toLowerCase().replace(/\s+/g, '-'); const normalizedView = dataArg.view.toLowerCase().replace(/\s+/g, '-');
return { ...statePartArg.getState(), activeView: normalizedView }; const normalizedSubview = dataArg.subview
? dataArg.subview.toLowerCase().replace(/\s+/g, '-')
: null;
return {
...statePartArg.getState(),
activeView: normalizedView,
activeSubview: normalizedSubview,
};
}, },
); );
+170 -53
View File
@@ -12,12 +12,21 @@ import {
type TemplateResult, type TemplateResult,
} from '@design.estate/dees-element'; } from '@design.estate/dees-element';
import type { ObViewDashboard } from './ob-view-dashboard.js'; interface IUnresolvedView {
import type { ObViewServices } from './ob-view-services.js'; slug?: string;
import type { ObViewNetwork } from './ob-view-network.js'; name: string;
import type { ObViewRegistries } from './ob-view-registries.js'; iconName?: string;
import type { ObViewTokens } from './ob-view-tokens.js'; element?: Promise<any>;
import type { ObViewSettings } from './ob-view-settings.js'; subViews?: IUnresolvedView[];
}
interface IResolvedView {
slug?: string;
name: string;
iconName?: string;
element?: any;
subViews?: IResolvedView[];
}
@customElement('ob-app-shell') @customElement('ob-app-shell')
export class ObAppShell extends DeesElement { export class ObAppShell extends DeesElement {
@@ -27,6 +36,7 @@ export class ObAppShell extends DeesElement {
@state() @state()
accessor uiState: appstate.IUiState = { accessor uiState: appstate.IUiState = {
activeView: 'dashboard', activeView: 'dashboard',
activeSubview: null,
autoRefresh: true, autoRefresh: true,
refreshInterval: 30000, refreshInterval: 30000,
}; };
@@ -37,25 +47,93 @@ export class ObAppShell extends DeesElement {
@state() @state()
accessor loginError: string = ''; accessor loginError: string = '';
private viewTabs = [ private viewTabs: IUnresolvedView[] = [
{ name: 'Dashboard', iconName: 'lucide:layoutDashboard', element: (async () => (await import('./ob-view-dashboard.js')).ObViewDashboard)() }, {
{ name: 'App Store', iconName: 'lucide:store', element: (async () => (await import('./ob-view-appstore.js')).ObViewAppStore)() }, slug: 'dashboard',
{ name: 'Services', iconName: 'lucide:boxes', element: (async () => (await import('./ob-view-services.js')).ObViewServices)() }, name: 'Dashboard',
{ name: 'Network', iconName: 'lucide:network', element: (async () => (await import('./ob-view-network.js')).ObViewNetwork)() }, iconName: 'lucide:layoutDashboard',
{ name: 'Registries', iconName: 'lucide:package', element: (async () => (await import('./ob-view-registries.js')).ObViewRegistries)() }, element: (async () => (await import('./ob-view-dashboard.js')).ObViewDashboard)(),
{ name: 'Tokens', iconName: 'lucide:key', element: (async () => (await import('./ob-view-tokens.js')).ObViewTokens)() }, },
{ name: 'Settings', iconName: 'lucide:settings', element: (async () => (await import('./ob-view-settings.js')).ObViewSettings)() }, {
slug: 'apps',
name: 'Apps',
iconName: 'lucide:store',
subViews: [
{
slug: 'app-store',
name: 'App Store',
iconName: 'lucide:store',
element: (async () => (await import('./ob-view-appstore.js')).ObViewAppStore)(),
},
{
slug: 'services',
name: 'Services',
iconName: 'lucide:boxes',
element: (async () => (await import('./ob-view-services.js')).ObViewServices)(),
},
],
},
{
slug: 'network',
name: 'Network',
iconName: 'lucide:network',
subViews: [
{
slug: 'proxy',
name: 'Proxy',
iconName: 'lucide:route',
element: (async () => (await import('./ob-view-network.js')).ObViewNetwork)(),
},
{
slug: 'domains',
name: 'Domains',
iconName: 'lucide:globe',
element: (async () => (await import('./ob-view-domains.js')).ObViewDomains)(),
},
{
slug: 'dns-records',
name: 'DNS Records',
iconName: 'lucide:listTree',
element: (async () => (await import('./ob-view-dns-records.js')).ObViewDnsRecords)(),
},
],
},
{
slug: 'registry',
name: 'Registry',
iconName: 'lucide:package',
subViews: [
{
slug: 'registries',
name: 'Registries',
iconName: 'lucide:package',
element: (async () => (await import('./ob-view-registries.js')).ObViewRegistries)(),
},
{
slug: 'tokens',
name: 'Tokens',
iconName: 'lucide:key',
element: (async () => (await import('./ob-view-tokens.js')).ObViewTokens)(),
},
],
},
{
slug: 'settings',
name: 'Settings',
iconName: 'lucide:settings',
element: (async () => (await import('./ob-view-settings.js')).ObViewSettings)(),
},
]; ];
private resolvedViewTabs: Array<{ name: string; iconName?: string; element: any }> = []; private resolvedViewTabs: IResolvedView[] = [];
constructor() { constructor() {
super(); super();
document.title = 'Onebox'; document.title = 'Onebox';
const loginSubscription = appstate.loginStatePart const loginSubscription = appstate.loginStatePart
.select((stateArg) => stateArg) .select((stateArg: appstate.ILoginState) => stateArg)
.subscribe((loginState) => { .subscribe((loginState: appstate.ILoginState) => {
this.loginState = loginState; this.loginState = loginState;
if (loginState.isLoggedIn) { if (loginState.isLoggedIn) {
appstate.systemStatePart.dispatchAction(appstate.fetchSystemStatusAction, null); appstate.systemStatePart.dispatchAction(appstate.fetchSystemStatusAction, null);
@@ -64,15 +142,56 @@ export class ObAppShell extends DeesElement {
this.rxSubscriptions.push(loginSubscription); this.rxSubscriptions.push(loginSubscription);
const uiSubscription = appstate.uiStatePart const uiSubscription = appstate.uiStatePart
.select((stateArg) => stateArg) .select((stateArg: appstate.IUiState) => stateArg)
.subscribe((uiState) => { .subscribe((uiState: appstate.IUiState) => {
this.uiState = uiState; this.uiState = uiState;
this.syncAppdashView(uiState.activeView); this.syncAppdashView(uiState.activeView, uiState.activeSubview);
}); });
this.rxSubscriptions.push(uiSubscription); this.rxSubscriptions.push(uiSubscription);
} }
public static styles = [ private async resolveViewTabs(tabs: IUnresolvedView[]): Promise<IResolvedView[]> {
return Promise.all(
tabs.map(async (tab) => {
const resolvedTab: IResolvedView = {
slug: tab.slug,
name: tab.name,
iconName: tab.iconName,
};
if (tab.element) {
resolvedTab.element = await tab.element;
}
if (tab.subViews) {
resolvedTab.subViews = await this.resolveViewTabs(tab.subViews);
}
return resolvedTab;
}),
);
}
private slugFor(view: IResolvedView): string {
return view.slug ?? view.name.toLowerCase().replace(/\s+/g, '-');
}
private findParent(view: IResolvedView): IResolvedView | undefined {
return this.resolvedViewTabs.find((viewTab) => viewTab.subViews?.includes(view));
}
private findViewBySlug(viewSlug: string, subviewSlug: string | null): IResolvedView | undefined {
const topLevelView = this.resolvedViewTabs.find((view) => this.slugFor(view) === viewSlug);
if (!topLevelView) return undefined;
if (subviewSlug && topLevelView.subViews) {
return topLevelView.subViews.find((subview) => this.slugFor(subview) === subviewSlug) ?? topLevelView;
}
return topLevelView;
}
private get currentViewTab(): IResolvedView | undefined {
if (this.resolvedViewTabs.length === 0) return undefined;
return this.findViewBySlug(this.uiState.activeView, this.uiState.activeSubview) ?? this.resolvedViewTabs[0];
}
public static override styles = [
cssManager.defaultStyles, cssManager.defaultStyles,
css` css`
:host { :host {
@@ -87,16 +206,14 @@ export class ObAppShell extends DeesElement {
`, `,
]; ];
public render(): TemplateResult { public override render(): TemplateResult {
return html` return html`
<div class="maincontainer"> <div class="maincontainer">
<dees-simple-login name="Onebox"> <dees-simple-login name="Onebox">
<dees-simple-appdash <dees-simple-appdash
name="Onebox" name="Onebox"
.viewTabs=${this.resolvedViewTabs} .viewTabs=${this.resolvedViewTabs}
.selectedView=${this.resolvedViewTabs.find( .selectedView=${this.currentViewTab}
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === this.uiState.activeView
) || this.resolvedViewTabs[0]}
> >
</dees-simple-appdash> </dees-simple-appdash>
</dees-simple-login> </dees-simple-login>
@@ -104,15 +221,8 @@ export class ObAppShell extends DeesElement {
`; `;
} }
public async firstUpdated() { public override async firstUpdated() {
// Resolve async view tab imports this.resolvedViewTabs = await this.resolveViewTabs(this.viewTabs);
this.resolvedViewTabs = await Promise.all(
this.viewTabs.map(async (tab) => ({
name: tab.name,
iconName: tab.iconName,
element: await tab.element,
})),
);
this.requestUpdate(); this.requestUpdate();
await this.updateComplete; await this.updateComplete;
@@ -126,34 +236,44 @@ export class ObAppShell extends DeesElement {
const appDash = this.shadowRoot!.querySelector('dees-simple-appdash') as any; const appDash = this.shadowRoot!.querySelector('dees-simple-appdash') as any;
if (appDash) { if (appDash) {
appDash.addEventListener('view-select', (e: CustomEvent) => { appDash.addEventListener('view-select', (e: CustomEvent) => {
const viewName = e.detail.view.name.toLowerCase().replace(/\s+/g, '-'); const view = e.detail.view as IResolvedView;
appRouter.navigateToView(viewName); const parent = this.findParent(view);
const currentState = appstate.uiStatePart.getState();
if (parent) {
const parentSlug = this.slugFor(parent);
const subviewSlug = this.slugFor(view);
if (currentState.activeView === parentSlug && currentState.activeSubview === subviewSlug) {
return;
}
appRouter.navigateToView(parentSlug, subviewSlug);
} else {
const slug = this.slugFor(view);
if (currentState.activeView === slug && !currentState.activeSubview) {
return;
}
appRouter.navigateToView(slug);
}
}); });
appDash.addEventListener('logout', async () => { appDash.addEventListener('logout', async () => {
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null); await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
}); });
} }
// Load the initial view on the appdash now that tabs are resolved
// Read activeView directly from state (not this.uiState which may be stale)
if (appDash && this.resolvedViewTabs.length > 0) { if (appDash && this.resolvedViewTabs.length > 0) {
const currentActiveView = appstate.uiStatePart.getState().activeView; const currentUiState = appstate.uiStatePart.getState();
const initialView = this.resolvedViewTabs.find( const initialView =
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === currentActiveView, this.findViewBySlug(currentUiState.activeView, currentUiState.activeSubview) ||
) || this.resolvedViewTabs[0]; this.resolvedViewTabs[0];
await appDash.loadView(initialView); await appDash.loadView(initialView);
} }
// Check for stored session (persistent login state)
const loginState = appstate.loginStatePart.getState(); const loginState = appstate.loginStatePart.getState();
if (loginState.identity?.jwt) { if (loginState.identity?.jwt) {
if (loginState.identity.expiresAt > Date.now()) { if (loginState.identity.expiresAt > Date.now()) {
// Switch to dashboard immediately (no flash of login form)
this.loginState = loginState; this.loginState = loginState;
if (simpleLogin) { if (simpleLogin) {
await simpleLogin.switchToSlottedContent(); await simpleLogin.switchToSlottedContent();
} }
// Validate token with server in the background
try { try {
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest< const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_GetSystemStatus interfaces.requests.IReq_GetSystemStatus
@@ -161,11 +281,9 @@ export class ObAppShell extends DeesElement {
const response = await typedRequest.fire({ identity: loginState.identity }); const response = await typedRequest.fire({ identity: loginState.identity });
appstate.systemStatePart.setState({ status: response.status }); appstate.systemStatePart.setState({ status: response.status });
} catch (err) { } catch (err) {
// Token rejected by server - switch back to login
console.warn('Stored session invalid, returning to login:', err); console.warn('Stored session invalid, returning to login:', err);
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null); await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
if (simpleLogin) { if (simpleLogin) {
// Force page reload to show login properly
window.location.reload(); window.location.reload();
} }
} }
@@ -206,14 +324,13 @@ export class ObAppShell extends DeesElement {
} }
} }
private syncAppdashView(viewName: string): void { private syncAppdashView(viewName: string, subviewName: string | null): void {
const appDash = this.shadowRoot?.querySelector('dees-simple-appdash') as any; const appDash = this.shadowRoot?.querySelector('dees-simple-appdash') as any;
if (!appDash || this.resolvedViewTabs.length === 0) return; if (!appDash || this.resolvedViewTabs.length === 0) return;
// Match kebab-case view name (e.g., 'app-store') to tab name (e.g., 'App Store')
const targetTab = this.resolvedViewTabs.find( const targetTab = this.findViewBySlug(viewName, subviewName);
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === viewName if (!targetTab || appDash.selectedView === targetTab) return;
);
if (!targetTab) return;
appDash.loadView(targetTab); appDash.loadView(targetTab);
} }
} }
+2
View File
@@ -36,6 +36,8 @@ export class ObViewDashboard extends DeesElement {
trafficStats: null, trafficStats: null,
dnsRecords: [], dnsRecords: [],
domains: [], domains: [],
gatewayDomains: [],
gatewayDnsRecords: [],
certificates: [], certificates: [],
}; };
+117
View File
@@ -0,0 +1,117 @@
import * as shared from './shared/index.js';
import * as plugins from '../plugins.js';
import * as appstate from '../appstate.js';
import { appRouter } from '../router.js';
import {
DeesElement,
customElement,
html,
state,
css,
cssManager,
type TemplateResult,
} from '@design.estate/dees-element';
type TGatewayDnsRecord = appstate.INetworkState['gatewayDnsRecords'][number];
@customElement('ob-view-dns-records')
export class ObViewDnsRecords extends DeesElement {
@state()
accessor networkState: appstate.INetworkState = {
targets: [],
stats: null,
trafficStats: null,
dnsRecords: [],
domains: [],
gatewayDomains: [],
gatewayDnsRecords: [],
certificates: [],
};
constructor() {
super();
const networkSub = appstate.networkStatePart.select((s) => s).subscribe((newState) => {
this.networkState = newState;
});
this.rxSubscriptions.push(networkSub);
}
public static styles = [
cssManager.defaultStyles,
shared.viewHostCss,
css`
.name { font-weight: 600; }
.value { font-family: monospace; color: var(--ci-shade-5, #71717a); overflow-wrap: anywhere; }
.muted { color: var(--ci-shade-5, #71717a); font-size: 13px; }
.badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
.missing { color: #dc2626; }
.empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
`,
];
async connectedCallback() {
super.connectedCallback();
await appstate.networkStatePart.dispatchAction(appstate.fetchGatewayDnsRecordsAction, null);
}
public render(): TemplateResult {
const records = this.networkState.gatewayDnsRecords;
return html`
<ob-sectionheading>DNS Records</ob-sectionheading>
${records.length
? html`
<dees-table
.heading1=${'Gateway DNS Records'}
.heading2=${'DNS records published through dcrouter for Onebox services'}
.data=${records}
.showColumnFilters=${true}
.displayFunction=${(record: TGatewayDnsRecord) => ({
Name: html`
<div>
<div class="name">${record.name}</div>
${record.domainName ? html`<div class="muted">${record.domainName}</div>` : ''}
</div>
`,
Type: html`<span class="badge">${record.type}</span>`,
Value: html`<span class="value">${record.value || '-'}</span>`,
Status: html`<span class=${record.status === 'missing' ? 'missing' : ''}>${record.status}</span>`,
Service: record.serviceName || record.appId || '-',
})}
.dataActions=${[
{
name: 'Refresh',
iconName: 'lucide:rotateCw',
type: ['header'],
actionFunc: async () => {
await appstate.networkStatePart.dispatchAction(
appstate.fetchGatewayDnsRecordsAction,
null,
);
},
},
{
name: 'View service',
iconName: 'lucide:boxes',
type: ['inRow', 'contextmenu'],
actionFunc: async () => {
appRouter.navigateToView('services');
},
},
{
name: 'Manage in dcrouter',
iconName: 'lucide:externalLink',
type: ['inRow', 'contextmenu'],
actionRelevancyCheckFunc: (record: TGatewayDnsRecord) => !!record.manageUrl,
actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDnsRecord>) => {
if (actionData.item.manageUrl) {
globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
}
},
},
] as plugins.deesCatalog.ITableAction<TGatewayDnsRecord>[]}
></dees-table>
`
: html`<div class="empty">No gateway DNS records found. Configure a dcrouter gateway in Settings.</div>`}
`;
}
}
+108
View File
@@ -0,0 +1,108 @@
import * as shared from './shared/index.js';
import * as plugins from '../plugins.js';
import * as appstate from '../appstate.js';
import {
DeesElement,
customElement,
html,
state,
css,
cssManager,
type TemplateResult,
} from '@design.estate/dees-element';
type TGatewayDomain = appstate.INetworkState['gatewayDomains'][number];
@customElement('ob-view-domains')
export class ObViewDomains extends DeesElement {
@state()
accessor networkState: appstate.INetworkState = {
targets: [],
stats: null,
trafficStats: null,
dnsRecords: [],
domains: [],
gatewayDomains: [],
gatewayDnsRecords: [],
certificates: [],
};
constructor() {
super();
const networkSub = appstate.networkStatePart.select((s) => s).subscribe((newState) => {
this.networkState = newState;
});
this.rxSubscriptions.push(networkSub);
}
public static styles = [
cssManager.defaultStyles,
shared.viewHostCss,
css`
.domain { font-weight: 600; }
.muted { color: var(--ci-shade-5, #71717a); font-size: 13px; }
.badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
.empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
`,
];
async connectedCallback() {
super.connectedCallback();
await appstate.networkStatePart.dispatchAction(appstate.fetchGatewayDomainsAction, null);
}
public render(): TemplateResult {
const domains = this.networkState.gatewayDomains;
return html`
<ob-sectionheading>Domains</ob-sectionheading>
<div class="muted" style="margin-bottom: 16px;">
Domains are managed in dcrouter. Onebox shows gateway visibility for deployed services.
</div>
${domains.length
? html`
<dees-table
.heading1=${'Gateway Domains'}
.heading2=${'Domains imported from dcrouter gateway visibility'}
.data=${domains}
.showColumnFilters=${true}
.displayFunction=${(domain: TGatewayDomain) => ({
Domain: html`
<div>
<div class="domain">${domain.name}</div>
${domain.providerId ? html`<div class="muted">Provider: ${domain.providerId}</div>` : ''}
</div>
`,
Source: html`<span class="badge">${domain.source || 'dcrouter'}</span>`,
Authoritative: domain.authoritative ? 'Yes' : 'No',
Services: domain.serviceCount || 0,
})}
.dataActions=${[
{
name: 'Refresh',
iconName: 'lucide:rotateCw',
type: ['header'],
actionFunc: async () => {
await appstate.networkStatePart.dispatchAction(
appstate.fetchGatewayDomainsAction,
null,
);
},
},
{
name: 'Manage in dcrouter',
iconName: 'lucide:externalLink',
type: ['inRow', 'contextmenu'],
actionRelevancyCheckFunc: (domain: TGatewayDomain) => !!domain.manageUrl,
actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDomain>) => {
if (actionData.item.manageUrl) {
globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
}
},
},
] as plugins.deesCatalog.ITableAction<TGatewayDomain>[]}
></dees-table>
`
: html`<div class="empty">No gateway domains found. Configure a dcrouter gateway in Settings.</div>`}
`;
}
}
+2
View File
@@ -20,6 +20,8 @@ export class ObViewNetwork extends DeesElement {
trafficStats: null, trafficStats: null,
dnsRecords: [], dnsRecords: [],
domains: [], domains: [],
gatewayDomains: [],
gatewayDnsRecords: [],
certificates: [], certificates: [],
}; };
+198 -63
View File
@@ -17,6 +17,7 @@ export class ObViewSettings extends DeesElement {
accessor settingsState: appstate.ISettingsState = { accessor settingsState: appstate.ISettingsState = {
settings: null, settings: null,
backupPasswordConfigured: false, backupPasswordConfigured: false,
managedDcRouterStatus: null,
}; };
@state() @state()
@@ -49,27 +50,29 @@ export class ObViewSettings extends DeesElement {
css` css`
.gateway-card { .gateway-card {
margin-bottom: 24px; margin-bottom: 24px;
border: 1px solid var(--dees-color-border-subtle); border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
border-radius: 12px; border-radius: 12px;
background: var(--dees-color-background, #ffffff); background: ${cssManager.bdTheme('#ffffff', '#09090b')};
overflow: hidden; overflow: hidden;
box-shadow: 0 1px 2px ${cssManager.bdTheme('rgba(0,0,0,0.04)', 'rgba(0,0,0,0.2)')};
} }
.gateway-header { .gateway-header {
padding: 16px 20px; padding: 16px 20px;
border-bottom: 1px solid var(--dees-color-border-subtle); border-bottom: 1px solid ${cssManager.bdTheme('#f4f4f5', '#27272a')};
background: ${cssManager.bdTheme('#fafafa', '#101013')};
} }
.gateway-title { .gateway-title {
font-size: 15px; font-size: 15px;
font-weight: 600; font-weight: 600;
color: var(--dees-color-text-primary); color: ${cssManager.bdTheme('#18181b', '#fafafa')};
} }
.gateway-subtitle { .gateway-subtitle {
margin-top: 4px; margin-top: 4px;
font-size: 13px; font-size: 13px;
color: var(--dees-color-text-muted); color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
} }
.gateway-content { .gateway-content {
@@ -79,38 +82,96 @@ export class ObViewSettings extends DeesElement {
gap: 16px; gap: 16px;
} }
.gateway-mode-row,
.gateway-status-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid ${cssManager.bdTheme('#f4f4f5', '#27272a')};
}
.gateway-mode-row {
justify-content: flex-start;
}
.gateway-mode-button {
border: 1px solid ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
border-radius: 999px;
background: ${cssManager.bdTheme('#ffffff', '#18181b')};
color: ${cssManager.bdTheme('#3f3f46', '#d4d4d8')};
padding: 8px 12px;
font: inherit;
cursor: pointer;
}
.gateway-mode-button.active {
border-color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
background: ${cssManager.bdTheme('#eff6ff', '#172554')};
color: ${cssManager.bdTheme('#1d4ed8', '#bfdbfe')};
}
.gateway-status-label {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
}
.gateway-status-value {
margin-top: 4px;
font-size: 14px;
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
}
.gateway-status-error,
.gateway-disabled {
color: ${cssManager.bdTheme('#b91c1c', '#fca5a5')};
font-size: 13px;
}
.gateway-disabled {
grid-column: 1 / -1;
}
.gateway-actions {
display: flex;
gap: 8px;
}
.gateway-field.full { .gateway-field.full {
grid-column: 1 / -1; grid-column: 1 / -1;
} }
.field-label { .gateway-readonly {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--dees-color-text-secondary);
}
input {
width: 100%;
box-sizing: border-box;
padding: 10px 12px; padding: 10px 12px;
border: 1px solid var(--dees-color-border-subtle); border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
border-radius: 8px; border-radius: 8px;
background: transparent; background: ${cssManager.bdTheme('#fafafa', '#18181b')};
color: var(--dees-color-text-primary);
font-size: 14px;
} }
input:focus { .gateway-readonly-label {
outline: none;
border-color: #3b82f6;
}
.field-hint {
margin-top: 5px;
font-size: 12px; font-size: 12px;
color: var(--dees-color-text-muted); font-weight: 600;
color: ${cssManager.bdTheme('#52525b', '#d4d4d8')};
}
.gateway-readonly-value {
margin-top: 4px;
font-size: 13px;
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
word-break: break-all;
}
.gateway-readonly-hint {
margin-top: 4px;
font-size: 12px;
color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
}
dees-input-text {
width: 100%;
} }
.gateway-footer { .gateway-footer {
@@ -119,25 +180,15 @@ export class ObViewSettings extends DeesElement {
padding: 0 20px 20px; padding: 0 20px 20px;
} }
.save-button {
border: none;
border-radius: 8px;
background: #2563eb;
color: white;
cursor: pointer;
font-size: 13px;
font-weight: 600;
padding: 9px 14px;
}
.save-button:hover {
background: #1d4ed8;
}
@media (max-width: 700px) { @media (max-width: 700px) {
.gateway-content { .gateway-content {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.gateway-status-row {
align-items: flex-start;
flex-direction: column;
}
} }
`, `,
]; ];
@@ -156,6 +207,14 @@ export class ObViewSettings extends DeesElement {
darkMode: true, darkMode: true,
cloudflareToken: '', cloudflareToken: '',
cloudflareZoneId: '', cloudflareZoneId: '',
dcrouterMode: 'managed',
dcrouterManagedImage: 'code.foss.global/serve.zone/dcrouter:latest',
dcrouterManagedOpsPort: 3300,
dcrouterManagedHttpPort: 80,
dcrouterManagedHttpsPort: 443,
dcrouterManagedDataDir: './.nogit/dcrouter-data',
dcrouterGatewayClientId: '',
dcrouterWorkHosterId: '',
autoRenewCerts: false, autoRenewCerts: false,
renewalThreshold: 30, renewalThreshold: 30,
acmeEmail: '', acmeEmail: '',
@@ -187,45 +246,109 @@ export class ObViewSettings extends DeesElement {
private renderExternalGatewaySettings(): TemplateResult { private renderExternalGatewaySettings(): TemplateResult {
const settings = this.settingsState.settings; const settings = this.settingsState.settings;
const mode = settings?.dcrouterMode || 'managed';
return html` return html`
<section class="gateway-card"> <section class="gateway-card">
<div class="gateway-header"> <div class="gateway-header">
<div class="gateway-title">External dcrouter Gateway</div> <div class="gateway-title">dcrouter Gateway</div>
<div class="gateway-subtitle">Delegate public WorkApp routing, DNS, and certificates to a dcrouter edge authority.</div> <div class="gateway-subtitle">Run a local managed dcrouter or delegate routing, DNS, and certificates to an external dcrouter.</div>
</div> </div>
<div class="gateway-mode-row">
${this.renderModeButton('managed', 'Managed Local', mode)}
${this.renderModeButton('external', 'External dcrouter', mode)}
${this.renderModeButton('disabled', 'Disabled', mode)}
</div>
${mode === 'managed' ? this.renderManagedGatewayStatus() : null}
<div class="gateway-content"> <div class="gateway-content">
${this.renderGatewayInput('dcrouterGatewayUrl', 'Gateway URL', settings?.dcrouterGatewayUrl || '', 'https://edge.example.com', 'Base URL of the dcrouter OpsServer.')} ${mode === 'managed' ? html`
${this.renderGatewayInput('dcrouterGatewayApiToken', 'API Token', settings?.dcrouterGatewayApiToken || '', 'dcrouter API token', 'Requires workhosters and certificates scopes.', 'password')} ${this.renderGatewayInput('dcrouterManagedImage', 'dcrouter Image', settings?.dcrouterManagedImage || 'code.foss.global/serve.zone/dcrouter:latest', 'OCI image used for the managed local gateway.')}
${this.renderGatewayInput('dcrouterWorkHosterId', 'WorkHoster ID', settings?.dcrouterWorkHosterId || '', 'optional stable owner ID', 'Leave empty to let Onebox create a stable ID.')} ${this.renderGatewayInput('dcrouterManagedDataDir', 'Data Directory', settings?.dcrouterManagedDataDir || './.nogit/dcrouter-data', 'Host directory mounted into the dcrouter container.')}
${this.renderGatewayInput('dcrouterTargetHost', 'Target Host', settings?.dcrouterTargetHost || '', 'public or private host/IP', 'Defaults to the configured server IP when empty.')} ${this.renderGatewayInput('dcrouterManagedOpsPort', 'Local Ops Port', String(settings?.dcrouterManagedOpsPort || 3300), 'Bound to 127.0.0.1 for Onebox to call dcrouter APIs.')}
${this.renderGatewayInput('dcrouterTargetPort', 'Target Port', String(settings?.dcrouterTargetPort || 80), '80', 'Internal HTTP port dcrouter forwards to.', 'number')} ${this.renderGatewayInput('dcrouterManagedHttpPort', 'Public HTTP Port', String(settings?.dcrouterManagedHttpPort || 80), 'Host port owned by dcrouter for HTTP ingress.')}
${this.renderGatewayInput('dcrouterManagedHttpsPort', 'Public HTTPS Port', String(settings?.dcrouterManagedHttpsPort || 443), 'Host port owned by dcrouter for HTTPS ingress.')}
${this.renderGatewayReadonly('Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || 'Created when managed dcrouter starts', 'Diagnostic only. Onebox manages this local client automatically.')}
` : mode === 'external' ? html`
${this.renderGatewayInput('dcrouterGatewayUrl', 'Gateway URL', settings?.dcrouterGatewayUrl || '', 'Base URL of the dcrouter OpsServer.')}
${this.renderGatewayInput('dcrouterGatewayApiToken', 'API Token', settings?.dcrouterGatewayApiToken || '', 'Requires gateway-client access in dcrouter.', true)}
${this.renderGatewayReadonly('Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || 'Derived from token', 'Configure this in dcrouter Gateway Clients, not in Onebox.')}
${this.renderGatewayInput('dcrouterTargetHost', 'Target Host', settings?.dcrouterTargetHost || '', 'Defaults to the configured server IP when empty.')}
${this.renderGatewayInput('dcrouterTargetPort', 'Target Port', String(settings?.dcrouterTargetPort || 80), 'Internal HTTP port dcrouter forwards to.')}
` : html`
<div class="gateway-disabled">dcrouter route delegation is disabled. Onebox will keep using its local SmartProxy directly.</div>
`}
</div> </div>
<div class="gateway-footer"> <div class="gateway-footer">
<button class="save-button" @click=${() => this.saveExternalGatewaySettings()}>Save Gateway Settings</button> <dees-button
.text=${'Save dcrouter Settings'}
.type=${'default'}
.icon=${'lucide:Save'}
@click=${() => this.saveExternalGatewaySettings()}
></dees-button>
</div> </div>
</section> </section>
`; `;
} }
private renderModeButton(
mode: 'managed' | 'external' | 'disabled',
label: string,
activeMode: string,
): TemplateResult {
return html`
<button
class="gateway-mode-button ${activeMode === mode ? 'active' : ''}"
@click=${() => this.updateGatewayDraft('dcrouterMode', mode)}
>${label}</button>
`;
}
private renderManagedGatewayStatus(): TemplateResult {
const status = this.settingsState.managedDcRouterStatus;
const stateText = status?.running ? (status.healthy ? 'Running' : 'Starting') : 'Stopped';
return html`
<div class="gateway-status-row">
<div>
<div class="gateway-status-label">Managed dcrouter</div>
<div class="gateway-status-value">${stateText}${status?.gatewayUrl ? ` at ${status.gatewayUrl}` : ''}</div>
${status?.message ? html`<div class="gateway-status-error">${status.message}</div>` : null}
</div>
<div class="gateway-actions">
<dees-button .text=${'Start'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.startManagedDcRouterAction, null)}></dees-button>
<dees-button .text=${'Restart'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.restartManagedDcRouterAction, null)}></dees-button>
<dees-button .text=${'Stop'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.stopManagedDcRouterAction, null)}></dees-button>
</div>
</div>
`;
}
private renderGatewayInput( private renderGatewayInput(
key: keyof NonNullable<appstate.ISettingsState['settings']>, key: keyof NonNullable<appstate.ISettingsState['settings']>,
label: string, label: string,
value: string, value: string,
placeholder: string,
hint: string, hint: string,
type: 'text' | 'password' | 'number' = 'text', isPassword = false,
): TemplateResult { ): TemplateResult {
return html` return html`
<label class="gateway-field ${key === 'dcrouterGatewayUrl' ? 'full' : ''}"> <div class="gateway-field ${key === 'dcrouterGatewayUrl' ? 'full' : ''}">
<span class="field-label">${label}</span> <dees-input-text
<input .key=${key}
type=${type} .label=${label}
.value=${value} .value=${value}
placeholder=${placeholder} .description=${hint}
.isPasswordBool=${isPassword}
@input=${(event: Event) => this.updateGatewayDraft(key, (event.target as HTMLInputElement).value)} @input=${(event: Event) => this.updateGatewayDraft(key, (event.target as HTMLInputElement).value)}
/> ></dees-input-text>
<span class="field-hint">${hint}</span> </div>
</label> `;
}
private renderGatewayReadonly(label: string, value: string, hint: string): TemplateResult {
return html`
<div class="gateway-readonly">
<div class="gateway-readonly-label">${label}</div>
<div class="gateway-readonly-value">${value}</div>
<div class="gateway-readonly-hint">${hint}</div>
</div>
`; `;
} }
@@ -234,7 +357,13 @@ export class ObViewSettings extends DeesElement {
value: string, value: string,
): void { ): void {
const currentSettings = this.settingsState.settings || {} as NonNullable<appstate.ISettingsState['settings']>; const currentSettings = this.settingsState.settings || {} as NonNullable<appstate.ISettingsState['settings']>;
const nextValue = key === 'dcrouterTargetPort' ? Number(value) || 0 : value; const numberKeys = new Set([
'dcrouterTargetPort',
'dcrouterManagedOpsPort',
'dcrouterManagedHttpPort',
'dcrouterManagedHttpsPort',
]);
const nextValue = numberKeys.has(key as string) ? Number(value) || 0 : value;
this.settingsState = { this.settingsState = {
...this.settingsState, ...this.settingsState,
settings: { settings: {
@@ -250,12 +379,18 @@ export class ObViewSettings extends DeesElement {
await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, { await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
settings: { settings: {
dcrouterMode: settings.dcrouterMode || 'managed',
dcrouterManagedImage: settings.dcrouterManagedImage || 'code.foss.global/serve.zone/dcrouter:latest',
dcrouterManagedOpsPort: Number(settings.dcrouterManagedOpsPort) || 3300,
dcrouterManagedHttpPort: Number(settings.dcrouterManagedHttpPort) || 80,
dcrouterManagedHttpsPort: Number(settings.dcrouterManagedHttpsPort) || 443,
dcrouterManagedDataDir: settings.dcrouterManagedDataDir || './.nogit/dcrouter-data',
dcrouterGatewayUrl: settings.dcrouterGatewayUrl || '', dcrouterGatewayUrl: settings.dcrouterGatewayUrl || '',
dcrouterGatewayApiToken: settings.dcrouterGatewayApiToken || '', dcrouterGatewayApiToken: settings.dcrouterGatewayApiToken || '',
dcrouterWorkHosterId: settings.dcrouterWorkHosterId || '',
dcrouterTargetHost: settings.dcrouterTargetHost || '', dcrouterTargetHost: settings.dcrouterTargetHost || '',
dcrouterTargetPort: Number(settings.dcrouterTargetPort) || 80, dcrouterTargetPort: Number(settings.dcrouterTargetPort) || 80,
}, },
}); });
await appstate.settingsStatePart.dispatchAction(appstate.fetchManagedDcRouterStatusAction, null);
} }
} }
+94 -24
View File
@@ -3,12 +3,40 @@ import * as appstate from './appstate.js';
const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter; const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;
export const validViews = [ const flatViews = ['dashboard', 'settings'] as const;
'dashboard', 'app-store', 'services', 'network',
'registries', 'tokens', 'settings',
] as const;
export type TValidView = typeof validViews[number]; const subviewMap: Record<string, readonly string[]> = {
apps: ['app-store', 'services'] as const,
network: ['proxy', 'domains', 'dns-records'] as const,
registry: ['registries', 'tokens'] as const,
};
const defaultSubview: Record<string, string> = {
apps: 'app-store',
network: 'proxy',
registry: 'registries',
};
const legacySubviewTargetMap: Record<string, { view: string; subview: string }> = {
'app-store': { view: 'apps', subview: 'app-store' },
services: { view: 'apps', subview: 'services' },
proxy: { view: 'network', subview: 'proxy' },
domains: { view: 'network', subview: 'domains' },
'dns-records': { view: 'network', subview: 'dns-records' },
registries: { view: 'registry', subview: 'registries' },
tokens: { view: 'registry', subview: 'tokens' },
};
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 { class AppRouter {
private router: InstanceType<typeof SmartRouter>; private router: InstanceType<typeof SmartRouter>;
@@ -28,24 +56,37 @@ class AppRouter {
} }
private setupRoutes(): void { private setupRoutes(): void {
for (const view of validViews) { for (const view of flatViews) {
this.router.on(`/${view}`, async () => { this.router.on(`/${view}`, async () => {
this.updateViewState(view); this.updateViewState(view, null);
}); });
} }
// Root redirect for (const view of Object.keys(subviewMap)) {
this.router.on(`/${view}`, async () => {
this.navigateTo(`/${view}/${defaultSubview[view]}`);
});
for (const subview of subviewMap[view]) {
this.router.on(`/${view}/${subview}`, async () => {
this.updateViewState(view, subview);
});
}
}
this.router.on('/', async () => { this.router.on('/', async () => {
this.navigateTo('/dashboard'); this.navigateTo('/dashboard');
}); });
} }
private setupStateSync(): void { private setupStateSync(): void {
appstate.uiStatePart.select((s) => s.activeView).subscribe((activeView) => { appstate.uiStatePart.select().subscribe((uiState: appstate.IUiState) => {
if (this.suppressStateUpdate) return; if (this.suppressStateUpdate) return;
const currentPath = window.location.pathname; const currentPath = window.location.pathname;
const expectedPath = `/${activeView}`; const expectedPath = uiState.activeSubview
? `/${uiState.activeView}/${uiState.activeSubview}`
: `/${uiState.activeView}`;
if (currentPath !== expectedPath) { if (currentPath !== expectedPath) {
this.suppressStateUpdate = true; this.suppressStateUpdate = true;
@@ -60,25 +101,37 @@ class AppRouter {
if (!path || path === '/') { if (!path || path === '/') {
this.router.pushUrl('/dashboard'); this.router.pushUrl('/dashboard');
} else { return;
const segments = path.split('/').filter(Boolean); }
const view = segments[0];
if (validViews.includes(view as TValidView)) { const segments = path.split('/').filter(Boolean);
this.updateViewState(view as TValidView); const view = segments[0];
const subview = segments[1];
if (!isValidView(view)) {
this.router.pushUrl('/dashboard');
return;
}
if (subviewMap[view]) {
if (subview && isValidSubview(view, subview)) {
this.updateViewState(view, subview);
} else { } else {
this.router.pushUrl('/dashboard'); 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; this.suppressStateUpdate = true;
const currentState = appstate.uiStatePart.getState(); const currentState = appstate.uiStatePart.getState();
if (currentState.activeView !== view) { if (currentState.activeView !== view || currentState.activeSubview !== subview) {
appstate.uiStatePart.setState({ appstate.uiStatePart.setState({
...currentState, ...currentState,
activeView: view, activeView: view,
activeSubview: subview,
}); });
} }
this.suppressStateUpdate = false; this.suppressStateUpdate = false;
@@ -88,17 +141,34 @@ class AppRouter {
this.router.pushUrl(path); this.router.pushUrl(path);
} }
public navigateToView(view: string): void { public navigateToView(view: string, subview?: string): void {
const normalized = view.toLowerCase().replace(/\s+/g, '-'); const normalizedView = view.toLowerCase().replace(/\s+/g, '-');
if (validViews.includes(normalized as TValidView)) { const normalizedSubview = subview?.toLowerCase().replace(/\s+/g, '-');
this.navigateTo(`/${normalized}`);
} else { if (!isValidView(normalizedView)) {
const legacyTarget = legacySubviewTargetMap[normalizedView];
if (legacyTarget) {
this.navigateToView(legacyTarget.view, legacyTarget.subview);
return;
}
this.navigateTo('/dashboard'); this.navigateTo('/dashboard');
return;
}
if (normalizedSubview && isValidSubview(normalizedView, normalizedSubview)) {
this.navigateTo(`/${normalizedView}/${normalizedSubview}`);
} else if (subviewMap[normalizedView]) {
this.navigateTo(`/${normalizedView}/${defaultSubview[normalizedView]}`);
} else {
this.navigateTo(`/${normalizedView}`);
} }
} }
public getCurrentView(): string { public getCurrentView(): string {
return appstate.uiStatePart.getState().activeView; const uiState = appstate.uiStatePart.getState();
return uiState.activeSubview
? `${uiState.activeView}/${uiState.activeSubview}`
: uiState.activeView;
} }
public destroy(): void { public destroy(): void {