Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b9c90eca3d | |||
| dc37a71802 | |||
| 595e84cdb6 | |||
| 5e04001790 | |||
| 7fe63541b3 | |||
| 201602b733 |
@@ -1,5 +1,35 @@
|
||||
# Changelog
|
||||
|
||||
## 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)
|
||||
|
||||
start the OpsServer with typedserver custom routes registered through the UtilityWebsiteServer hook
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "1.24.5",
|
||||
"version": "1.26.0",
|
||||
"exports": "./mod.ts",
|
||||
"tasks": {
|
||||
"test": "deno test --allow-all test/",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "1.24.5",
|
||||
"version": "1.26.0",
|
||||
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
|
||||
"main": "mod.ts",
|
||||
"type": "module",
|
||||
|
||||
+7
-12
@@ -5,8 +5,7 @@ import type { IUser as IDatabaseUser } from '../ts/types.ts';
|
||||
import { AdminHandler } from '../ts/opsserver/handlers/admin.handler.ts';
|
||||
import {
|
||||
hashPassword,
|
||||
isBcryptHash,
|
||||
needsPasswordUpgrade,
|
||||
isPbkdf2Hash,
|
||||
verifyPassword,
|
||||
} from '../ts/utils/auth.ts';
|
||||
|
||||
@@ -45,18 +44,14 @@ async function createAdminHandler(users: IDatabaseUser[]): Promise<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 bcryptHash = await hashPassword(password);
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
assert(isBcryptHash(bcryptHash));
|
||||
assert(await verifyPassword(password, bcryptHash));
|
||||
assert(!(await verifyPassword('wrong password', bcryptHash)));
|
||||
assert(!needsPasswordUpgrade(bcryptHash));
|
||||
|
||||
const legacyHash = btoa(password);
|
||||
assert(await verifyPassword(password, legacyHash));
|
||||
assert(needsPasswordUpgrade(legacyHash));
|
||||
assert(isPbkdf2Hash(passwordHash));
|
||||
assert(await verifyPassword(password, passwordHash));
|
||||
assert(!(await verifyPassword('wrong password', passwordHash)));
|
||||
assert(!(await verifyPassword(password, btoa(password))));
|
||||
});
|
||||
|
||||
Deno.test('verified identity is derived from the signed JWT and database, not client fields', async () => {
|
||||
|
||||
@@ -62,6 +62,7 @@ class FakeDatabase {
|
||||
const makeOneboxRef = () => {
|
||||
const database = new FakeDatabase();
|
||||
database.settings.set('dcrouterGatewayUrl', 'https://edge.example.com');
|
||||
database.settings.set('dcrouterGatewayClientId', 'onebox-1');
|
||||
database.settings.set('dcrouterWorkHosterId', 'onebox-1');
|
||||
database.secretSettings.set('dcrouterGatewayApiToken', 'dcr-token');
|
||||
|
||||
@@ -92,8 +93,9 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
|
||||
});
|
||||
|
||||
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||
(manager as any).fireDcRouterRequest = async (method: string) => {
|
||||
assertEquals(method, 'getWorkHosterDomains');
|
||||
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||
assertEquals(method, 'getGatewayClientDomains');
|
||||
assertEquals(requestData.gatewayClientId, 'onebox-1');
|
||||
return {
|
||||
domains: [
|
||||
{
|
||||
@@ -117,7 +119,7 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
|
||||
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();
|
||||
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||
oneboxRef.database.settings.set('httpPort', '8080');
|
||||
@@ -146,14 +148,14 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
|
||||
|
||||
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 ownership = syncRequest.requestData.ownership as any;
|
||||
|
||||
assertEquals(ownership, {
|
||||
workHosterType: 'onebox',
|
||||
workHosterId: 'onebox-1',
|
||||
workAppId: 'hello',
|
||||
gatewayClientType: 'onebox',
|
||||
gatewayClientId: 'onebox-1',
|
||||
appId: 'hello',
|
||||
hostname: 'hello.example.com',
|
||||
});
|
||||
assertEquals(route.match, { ports: [443], domains: ['hello.example.com'] });
|
||||
@@ -162,13 +164,56 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
|
||||
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 === '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 manager = new ExternalGatewayManager(oneboxRef as any);
|
||||
let deleteRequest: Record<string, unknown> | null = null;
|
||||
|
||||
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||
assertEquals(method, 'syncWorkAppRoute');
|
||||
assertEquals(method, 'syncGatewayClientRoute');
|
||||
deleteRequest = requestData;
|
||||
return { success: true, action: 'deleted', routeId: 'route-1' };
|
||||
};
|
||||
@@ -182,6 +227,7 @@ Deno.test('ExternalGatewayManager deletes service routes through dcrouter WorkHo
|
||||
assert(deleteRequest);
|
||||
const capturedDeleteRequest = deleteRequest as Record<string, unknown>;
|
||||
assertEquals(capturedDeleteRequest.delete, true);
|
||||
assertEquals((capturedDeleteRequest.ownership as any).gatewayClientId, 'onebox-1');
|
||||
assertEquals((capturedDeleteRequest.ownership as any).hostname, 'hello.example.com');
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '1.24.2',
|
||||
version: '1.26.0',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
+165
-18
@@ -3,19 +3,29 @@ import { logger } from '../logging.ts';
|
||||
import { getErrorMessage } from '../utils/error.ts';
|
||||
import { OneboxDatabase } from './database.ts';
|
||||
import type { IDomain, IService } from '../types.ts';
|
||||
import type { TDcRouterMode } from './managed-dcrouter.ts';
|
||||
|
||||
type TWorkHosterType = 'onebox';
|
||||
|
||||
interface IExternalGatewayConfig {
|
||||
url: string;
|
||||
apiToken: string;
|
||||
gatewayClientId: string;
|
||||
/** @deprecated Use gatewayClientId. */
|
||||
workHosterId: string;
|
||||
targetHost?: string;
|
||||
targetPort?: number;
|
||||
}
|
||||
|
||||
interface IWorkHosterDomain {
|
||||
id?: string;
|
||||
name: string;
|
||||
source?: 'dcrouter' | 'provider';
|
||||
authoritative?: boolean;
|
||||
providerId?: string;
|
||||
serviceCount?: number;
|
||||
managePath?: string;
|
||||
manageUrl?: string;
|
||||
capabilities?: {
|
||||
canCreateSubdomains: boolean;
|
||||
canManageDnsRecords: boolean;
|
||||
@@ -24,6 +34,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 {
|
||||
workHosterType: TWorkHosterType;
|
||||
workHosterId: string;
|
||||
@@ -31,6 +61,13 @@ interface IWorkAppRouteOwnership {
|
||||
hostname: string;
|
||||
}
|
||||
|
||||
interface IGatewayClientOwnership {
|
||||
gatewayClientType: TWorkHosterType;
|
||||
gatewayClientId: string;
|
||||
appId: string;
|
||||
hostname: string;
|
||||
}
|
||||
|
||||
interface IWorkAppRouteSyncResult {
|
||||
success: boolean;
|
||||
action?: 'created' | 'updated' | 'deleted' | 'unchanged';
|
||||
@@ -88,17 +125,18 @@ export class ExternalGatewayManager {
|
||||
}
|
||||
|
||||
public async isConfigured(): Promise<boolean> {
|
||||
if (this.getMode() === 'disabled') {
|
||||
return false;
|
||||
}
|
||||
const config = await this.getConfig({ requireTarget: false });
|
||||
return Boolean(config);
|
||||
}
|
||||
|
||||
public async syncDomains(): Promise<IDomain[]> {
|
||||
const config = await this.requireConfig({ requireTarget: false });
|
||||
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
|
||||
'getWorkHosterDomains',
|
||||
{},
|
||||
config,
|
||||
);
|
||||
if (!(await this.isConfigured())) {
|
||||
return this.database.getDomainsByProvider('dcrouter');
|
||||
}
|
||||
const response = { domains: await this.getGatewayDomains() };
|
||||
|
||||
const activeDomainNames = new Set<string>();
|
||||
const now = Date.now();
|
||||
@@ -143,6 +181,55 @@ export class ExternalGatewayManager {
|
||||
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',
|
||||
{ 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',
|
||||
{ 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> {
|
||||
if (!service.domain) return;
|
||||
|
||||
@@ -150,14 +237,24 @@ export class ExternalGatewayManager {
|
||||
if (!config) return;
|
||||
|
||||
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||
'syncGatewayClientRoute',
|
||||
{
|
||||
ownership: this.buildGatewayClientOwnership(service, service.domain, config),
|
||||
route: this.buildRoute(service, config),
|
||||
enabled: service.status === 'running',
|
||||
},
|
||||
config,
|
||||
).catch(async () => {
|
||||
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||
'syncWorkAppRoute',
|
||||
{
|
||||
ownership: this.buildOwnership(service, service.domain, config),
|
||||
ownership: this.buildOwnership(service, service.domain!, config),
|
||||
route: this.buildRoute(service, config),
|
||||
enabled: service.status === 'running',
|
||||
},
|
||||
config,
|
||||
);
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.message || `dcrouter route sync failed for ${service.domain}`);
|
||||
@@ -176,13 +273,22 @@ export class ExternalGatewayManager {
|
||||
if (!config) return;
|
||||
|
||||
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||
'syncGatewayClientRoute',
|
||||
{
|
||||
ownership: this.buildGatewayClientOwnership(service, service.domain, config),
|
||||
delete: true,
|
||||
},
|
||||
config,
|
||||
).catch(async () => {
|
||||
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||
'syncWorkAppRoute',
|
||||
{
|
||||
ownership: this.buildOwnership(service, service.domain, config),
|
||||
ownership: this.buildOwnership(service, service.domain!, config),
|
||||
delete: true,
|
||||
},
|
||||
config,
|
||||
);
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.message || `dcrouter route delete failed for ${service.domain}`);
|
||||
@@ -234,19 +340,37 @@ export class ExternalGatewayManager {
|
||||
}
|
||||
|
||||
private async getConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig | null> {
|
||||
const url = this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
|
||||
const apiToken = await this.database.getSecretSetting('dcrouterGatewayApiToken');
|
||||
const mode = this.getMode();
|
||||
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) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const gatewayClientId = mode === 'managed'
|
||||
? this.oneboxRef.managedDcRouter.ensureGatewayClientId()
|
||||
: this.ensureGatewayClientId();
|
||||
const config: IExternalGatewayConfig = {
|
||||
url,
|
||||
apiToken,
|
||||
workHosterId: this.ensureWorkHosterId(),
|
||||
gatewayClientId,
|
||||
workHosterId: gatewayClientId,
|
||||
};
|
||||
|
||||
if (options.requireTarget !== false) {
|
||||
if (mode === 'managed') {
|
||||
const target = this.oneboxRef.managedDcRouter.getRouteTarget();
|
||||
config.targetHost = target.host;
|
||||
config.targetPort = target.port;
|
||||
} else {
|
||||
config.targetHost = this.database.getSetting('dcrouterTargetHost')
|
||||
|| this.database.getSetting('serverIP')
|
||||
|| undefined;
|
||||
@@ -256,6 +380,7 @@ export class ExternalGatewayManager {
|
||||
|| '80',
|
||||
);
|
||||
config.targetPort = targetPort;
|
||||
}
|
||||
|
||||
if (!config.targetHost) {
|
||||
throw new Error('dcrouterTargetHost or serverIP must be configured for external gateway route sync');
|
||||
@@ -265,6 +390,10 @@ export class ExternalGatewayManager {
|
||||
return config;
|
||||
}
|
||||
|
||||
private getMode(): TDcRouterMode {
|
||||
return this.oneboxRef.managedDcRouter?.getMode?.() || 'external';
|
||||
}
|
||||
|
||||
private async requireConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig> {
|
||||
const config = await this.getConfig(options);
|
||||
if (!config) {
|
||||
@@ -288,13 +417,13 @@ export class ExternalGatewayManager {
|
||||
return port;
|
||||
}
|
||||
|
||||
private ensureWorkHosterId(): string {
|
||||
let workHosterId = this.database.getSetting('dcrouterWorkHosterId');
|
||||
if (!workHosterId) {
|
||||
workHosterId = crypto.randomUUID();
|
||||
this.database.setSetting('dcrouterWorkHosterId', workHosterId);
|
||||
private ensureGatewayClientId(): string {
|
||||
let gatewayClientId = this.database.getSetting('dcrouterGatewayClientId') || this.database.getSetting('dcrouterWorkHosterId');
|
||||
if (!gatewayClientId) {
|
||||
gatewayClientId = crypto.randomUUID();
|
||||
this.database.setSetting('dcrouterGatewayClientId', gatewayClientId);
|
||||
}
|
||||
return workHosterId;
|
||||
return gatewayClientId;
|
||||
}
|
||||
|
||||
private buildOwnership(
|
||||
@@ -304,12 +433,25 @@ export class ExternalGatewayManager {
|
||||
): IWorkAppRouteOwnership {
|
||||
return {
|
||||
workHosterType: 'onebox',
|
||||
workHosterId: config.workHosterId,
|
||||
workHosterId: config.gatewayClientId,
|
||||
workAppId: service.name || `service-${service.id}`,
|
||||
hostname,
|
||||
};
|
||||
}
|
||||
|
||||
private buildGatewayClientOwnership(
|
||||
service: Pick<IService, 'id' | 'name'>,
|
||||
hostname: string,
|
||||
config: IExternalGatewayConfig,
|
||||
): IGatewayClientOwnership {
|
||||
return {
|
||||
gatewayClientType: 'onebox',
|
||||
gatewayClientId: config.gatewayClientId,
|
||||
appId: service.name || `service-${service.id}`,
|
||||
hostname,
|
||||
};
|
||||
}
|
||||
|
||||
private buildRoute(service: IService, config: IExternalGatewayConfig): IDcRouterRouteConfig {
|
||||
return {
|
||||
name: this.routeName(service.domain!),
|
||||
@@ -335,6 +477,11 @@ export class ExternalGatewayManager {
|
||||
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>(
|
||||
method: string,
|
||||
requestData: Record<string, unknown>,
|
||||
|
||||
@@ -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
@@ -25,6 +25,7 @@ import { ProxyLogReceiver } from './proxy-log-receiver.ts';
|
||||
import { BackupManager } from './backup-manager.ts';
|
||||
import { BackupScheduler } from './backup-scheduler.ts';
|
||||
import { ExternalGatewayManager } from './external-gateway.ts';
|
||||
import { ManagedDcRouterManager } from './managed-dcrouter.ts';
|
||||
import { OpsServer } from '../opsserver/index.ts';
|
||||
|
||||
export class Onebox {
|
||||
@@ -45,6 +46,7 @@ export class Onebox {
|
||||
public proxyLogReceiver: ProxyLogReceiver;
|
||||
public backupManager: BackupManager;
|
||||
public backupScheduler: BackupScheduler;
|
||||
public managedDcRouter: ManagedDcRouterManager;
|
||||
public externalGateway: ExternalGatewayManager;
|
||||
public opsServer: OpsServer;
|
||||
|
||||
@@ -88,7 +90,8 @@ export class Onebox {
|
||||
// Initialize Backup scheduler
|
||||
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);
|
||||
|
||||
// Initialize OpsServer (TypedRequest-based server)
|
||||
@@ -111,6 +114,20 @@ export class Onebox {
|
||||
// Initialize Docker
|
||||
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.
|
||||
try {
|
||||
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)
|
||||
// Use 8080/8443 in dev mode to avoid permission issues
|
||||
const isDev = Deno.env.get('ONEBOX_DEV') === 'true' || Deno.args.includes('--ephemeral');
|
||||
const httpPort = isDev ? 8080 : 80;
|
||||
const httpsPort = isDev ? 8443 : 443;
|
||||
const isManagedDcRouter = this.managedDcRouter.getMode() === 'managed';
|
||||
const httpPort = isDev || isManagedDcRouter ? 8080 : 80;
|
||||
const httpsPort = isDev || isManagedDcRouter ? 8443 : 443;
|
||||
|
||||
try {
|
||||
await this.reverseProxy.startHttp(httpPort);
|
||||
@@ -165,6 +183,14 @@ export class Onebox {
|
||||
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)
|
||||
try {
|
||||
await this.externalGateway.init();
|
||||
|
||||
@@ -7,6 +7,7 @@ const secretSettingAliases = {
|
||||
backupPassword: ['backup_encryption_password'],
|
||||
cloudflareToken: ['cloudflareAPIKey'],
|
||||
dcrouterGatewayApiToken: ['externalGatewayApiToken'],
|
||||
dcrouterManagedAdminApiToken: [],
|
||||
} as const;
|
||||
|
||||
type TCanonicalSecretSettingKey = keyof typeof secretSettingAliases;
|
||||
|
||||
@@ -23,6 +23,7 @@ export class OpsServer {
|
||||
public backupsHandler!: handlers.BackupsHandler;
|
||||
public schedulesHandler!: handlers.SchedulesHandler;
|
||||
public settingsHandler!: handlers.SettingsHandler;
|
||||
public managedDcRouterHandler!: handlers.ManagedDcRouterHandler;
|
||||
public logsHandler!: handlers.LogsHandler;
|
||||
public workspaceHandler!: handlers.WorkspaceHandler;
|
||||
public appStoreHandler!: handlers.AppStoreHandler;
|
||||
@@ -66,6 +67,7 @@ export class OpsServer {
|
||||
this.backupsHandler = new handlers.BackupsHandler(this);
|
||||
this.schedulesHandler = new handlers.SchedulesHandler(this);
|
||||
this.settingsHandler = new handlers.SettingsHandler(this);
|
||||
this.managedDcRouterHandler = new handlers.ManagedDcRouterHandler(this);
|
||||
this.logsHandler = new handlers.LogsHandler(this);
|
||||
this.workspaceHandler = new handlers.WorkspaceHandler(this);
|
||||
this.appStoreHandler = new handlers.AppStoreHandler(this);
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as plugins from '../../plugins.ts';
|
||||
import { logger } from '../../logging.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.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 {
|
||||
userId: string;
|
||||
@@ -112,11 +112,6 @@ export class AdminHandler {
|
||||
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 freshUser = this.opsServerRef.oneboxRef.database.getUserByUsername(user.username) || user;
|
||||
const identity = await this.createIdentityForUser(freshUser, expiresAt);
|
||||
|
||||
@@ -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 };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export * from './network.handler.ts';
|
||||
export * from './backups.handler.ts';
|
||||
export * from './schedules.handler.ts';
|
||||
export * from './settings.handler.ts';
|
||||
export * from './managed-dcrouter.handler.ts';
|
||||
export * from './logs.handler.ts';
|
||||
export * from './workspace.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 };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,21 @@ export class SettingsHandler {
|
||||
const cloudflareToken = await db.getSecretSetting('cloudflareToken');
|
||||
const dcrouterGatewayApiToken = await db.getSecretSetting('dcrouterGatewayApiToken');
|
||||
const settingsMap = db.getAllSettings();
|
||||
const managedDcRouter = this.opsServerRef.oneboxRef.managedDcRouter;
|
||||
|
||||
return {
|
||||
cloudflareToken: cloudflareToken || '',
|
||||
cloudflareZoneId: settingsMap['cloudflareZoneId'] || '',
|
||||
dcrouterMode: managedDcRouter.getMode(),
|
||||
dcrouterManagedImage: managedDcRouter.getImage(),
|
||||
dcrouterManagedOpsPort: managedDcRouter.getOpsPort(),
|
||||
dcrouterManagedHttpPort: managedDcRouter.getHttpPort(),
|
||||
dcrouterManagedHttpsPort: managedDcRouter.getHttpsPort(),
|
||||
dcrouterManagedDataDir: managedDcRouter.getDataDir(),
|
||||
dcrouterGatewayUrl: settingsMap['dcrouterGatewayUrl'] || '',
|
||||
dcrouterGatewayApiToken: dcrouterGatewayApiToken || '',
|
||||
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || '',
|
||||
dcrouterGatewayClientId: settingsMap['dcrouterGatewayClientId'] || settingsMap['dcrouterWorkHosterId'] || '',
|
||||
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || settingsMap['dcrouterGatewayClientId'] || '',
|
||||
dcrouterTargetHost: settingsMap['dcrouterTargetHost'] || '',
|
||||
dcrouterTargetPort: parseInt(settingsMap['dcrouterTargetPort'] || '0', 10),
|
||||
autoRenewCerts: settingsMap['autoRenewCerts'] === 'true',
|
||||
@@ -68,8 +76,8 @@ export class SettingsHandler {
|
||||
}
|
||||
|
||||
if (this.hasExternalGatewaySetting(updates)) {
|
||||
this.refreshExternalGateway().catch((error) => {
|
||||
logger.warn(`External gateway settings refresh failed: ${getErrorMessage(error)}`);
|
||||
this.refreshDcRouterGateway().catch((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 {
|
||||
return [
|
||||
'dcrouterMode',
|
||||
'dcrouterManagedImage',
|
||||
'dcrouterManagedOpsPort',
|
||||
'dcrouterManagedHttpPort',
|
||||
'dcrouterManagedHttpsPort',
|
||||
'dcrouterManagedDataDir',
|
||||
'dcrouterGatewayUrl',
|
||||
'dcrouterGatewayApiToken',
|
||||
'dcrouterGatewayClientId',
|
||||
'dcrouterWorkHosterId',
|
||||
'dcrouterTargetHost',
|
||||
'dcrouterTargetPort',
|
||||
].some((key) => Object.prototype.hasOwnProperty.call(settings, key));
|
||||
}
|
||||
|
||||
private async refreshExternalGateway(): Promise<void> {
|
||||
private async refreshDcRouterGateway(): Promise<void> {
|
||||
const onebox = this.opsServerRef.oneboxRef;
|
||||
if (onebox.managedDcRouter.getMode() === 'managed') {
|
||||
await onebox.managedDcRouter.restart();
|
||||
} else {
|
||||
await onebox.managedDcRouter.stop();
|
||||
}
|
||||
|
||||
await onebox.externalGateway.syncDomains();
|
||||
|
||||
const services = onebox.database.getAllServices().filter((service) => service.domain);
|
||||
|
||||
@@ -55,10 +55,6 @@ export const awsS3 = {
|
||||
import * as taskbuffer from '@push.rocks/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
|
||||
import * as jwt from 'https://deno.land/x/djwt@v3.0.2/mod.ts';
|
||||
export { jwt};
|
||||
|
||||
@@ -259,8 +259,16 @@ export interface IAppSettings {
|
||||
serverIP?: string;
|
||||
cloudflareToken?: string;
|
||||
cloudflareZoneId?: string;
|
||||
dcrouterMode?: 'managed' | 'external' | 'disabled';
|
||||
dcrouterManagedImage?: string;
|
||||
dcrouterManagedOpsPort?: number;
|
||||
dcrouterManagedHttpPort?: number;
|
||||
dcrouterManagedHttpsPort?: number;
|
||||
dcrouterManagedDataDir?: string;
|
||||
dcrouterGatewayUrl?: string;
|
||||
dcrouterGatewayApiToken?: string;
|
||||
dcrouterGatewayClientId?: string;
|
||||
/** @deprecated Use dcrouterGatewayClientId. */
|
||||
dcrouterWorkHosterId?: string;
|
||||
dcrouterTargetHost?: string;
|
||||
dcrouterTargetPort?: number;
|
||||
|
||||
+78
-12
@@ -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 {
|
||||
return bcryptHashPattern.test(passwordHash);
|
||||
}
|
||||
const base64ToBytes = (base64Arg: string): Uint8Array => {
|
||||
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 {
|
||||
return !isBcryptHash(passwordHash);
|
||||
const timingSafeEqual = (aArg: Uint8Array, bArg: Uint8Array): boolean => {
|
||||
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> {
|
||||
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> {
|
||||
@@ -19,10 +81,14 @@ export async function verifyPassword(password: string, passwordHash: string): Pr
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isBcryptHash(passwordHash)) {
|
||||
return await plugins.bcrypt.compare(password, passwordHash);
|
||||
const pbkdf2Match = passwordHash.match(pbkdf2HashPattern);
|
||||
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 passwordHash === btoa(password);
|
||||
return false;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -57,3 +57,40 @@ export interface IDnsRecord {
|
||||
createdAt: 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;
|
||||
}
|
||||
|
||||
@@ -2,11 +2,35 @@
|
||||
* 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 {
|
||||
cloudflareToken: string;
|
||||
cloudflareZoneId: string;
|
||||
dcrouterMode: TDcRouterMode;
|
||||
dcrouterManagedImage: string;
|
||||
dcrouterManagedOpsPort: number;
|
||||
dcrouterManagedHttpPort: number;
|
||||
dcrouterManagedHttpsPort: number;
|
||||
dcrouterManagedDataDir: string;
|
||||
dcrouterGatewayUrl: string;
|
||||
dcrouterGatewayApiToken: string;
|
||||
dcrouterGatewayClientId: string;
|
||||
/** @deprecated Use dcrouterGatewayClientId. */
|
||||
dcrouterWorkHosterId: string;
|
||||
dcrouterTargetHost: string;
|
||||
dcrouterTargetPort: number;
|
||||
|
||||
@@ -56,3 +56,16 @@ export interface IReq_SyncDns extends plugins.typedrequestInterfaces.implementsT
|
||||
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[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,3 +40,16 @@ export interface IReq_SyncDomains extends plugins.typedrequestInterfaces.impleme
|
||||
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[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -54,3 +54,55 @@ export interface IReq_GetBackupPasswordStatus extends plugins.typedrequestInterf
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '1.24.2',
|
||||
version: '1.26.0',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
+91
-1
@@ -36,6 +36,8 @@ export interface INetworkState {
|
||||
trafficStats: interfaces.data.ITrafficStats | null;
|
||||
dnsRecords: interfaces.data.IDnsRecord[];
|
||||
domains: interfaces.data.IDomainDetail[];
|
||||
gatewayDomains: interfaces.data.IGatewayDomain[];
|
||||
gatewayDnsRecords: interfaces.data.IGatewayDnsRecord[];
|
||||
certificates: interfaces.data.ICertificate[];
|
||||
}
|
||||
|
||||
@@ -52,6 +54,7 @@ export interface IBackupsState {
|
||||
export interface ISettingsState {
|
||||
settings: interfaces.data.ISettings | null;
|
||||
backupPasswordConfigured: boolean;
|
||||
managedDcRouterStatus: interfaces.data.IManagedDcRouterStatus | null;
|
||||
}
|
||||
|
||||
export interface IAppStoreState {
|
||||
@@ -110,6 +113,8 @@ export const networkStatePart = await appState.getStatePart<INetworkState>(
|
||||
trafficStats: null,
|
||||
dnsRecords: [],
|
||||
domains: [],
|
||||
gatewayDomains: [],
|
||||
gatewayDnsRecords: [],
|
||||
certificates: [],
|
||||
},
|
||||
'soft',
|
||||
@@ -138,6 +143,7 @@ export const settingsStatePart = await appState.getStatePart<ISettingsState>(
|
||||
{
|
||||
settings: null,
|
||||
backupPasswordConfigured: false,
|
||||
managedDcRouterStatus: null,
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
@@ -628,6 +634,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) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
@@ -866,17 +900,21 @@ export const triggerScheduleAction = backupsStatePart.createAction<{ scheduleId:
|
||||
export const fetchSettingsAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const [settingsResp, passwordResp] = await Promise.all([
|
||||
const [settingsResp, passwordResp, managedDcRouterResp] = await Promise.all([
|
||||
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetSettings
|
||||
>('/typedrequest', 'getSettings').fire({ identity: context.identity! }),
|
||||
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetBackupPasswordStatus
|
||||
>('/typedrequest', 'getBackupPasswordStatus').fire({ identity: context.identity! }),
|
||||
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetManagedDcRouterStatus
|
||||
>('/typedrequest', 'getManagedDcRouterStatus').fire({ identity: context.identity! }),
|
||||
]);
|
||||
return {
|
||||
settings: settingsResp.settings,
|
||||
backupPasswordConfigured: passwordResp.status.isConfigured,
|
||||
managedDcRouterStatus: managedDcRouterResp.status,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch settings:', err);
|
||||
@@ -903,6 +941,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 }>(
|
||||
async (statePartArg, dataArg) => {
|
||||
const context = getActionContext();
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
|
||||
import type { ObViewDashboard } from './ob-view-dashboard.js';
|
||||
import type { ObViewServices } from './ob-view-services.js';
|
||||
import type { ObViewDomains } from './ob-view-domains.js';
|
||||
import type { ObViewDnsRecords } from './ob-view-dns-records.js';
|
||||
import type { ObViewNetwork } from './ob-view-network.js';
|
||||
import type { ObViewRegistries } from './ob-view-registries.js';
|
||||
import type { ObViewTokens } from './ob-view-tokens.js';
|
||||
@@ -41,6 +43,8 @@ export class ObAppShell extends DeesElement {
|
||||
{ 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)() },
|
||||
{ name: 'Services', iconName: 'lucide:boxes', element: (async () => (await import('./ob-view-services.js')).ObViewServices)() },
|
||||
{ name: 'Domains', iconName: 'lucide:globe', element: (async () => (await import('./ob-view-domains.js')).ObViewDomains)() },
|
||||
{ name: 'DNS Records', iconName: 'lucide:listTree', element: (async () => (await import('./ob-view-dns-records.js')).ObViewDnsRecords)() },
|
||||
{ name: 'Network', iconName: 'lucide:network', element: (async () => (await import('./ob-view-network.js')).ObViewNetwork)() },
|
||||
{ name: 'Registries', iconName: 'lucide:package', element: (async () => (await import('./ob-view-registries.js')).ObViewRegistries)() },
|
||||
{ name: 'Tokens', iconName: 'lucide:key', element: (async () => (await import('./ob-view-tokens.js')).ObViewTokens)() },
|
||||
|
||||
@@ -36,6 +36,8 @@ export class ObViewDashboard extends DeesElement {
|
||||
trafficStats: null,
|
||||
dnsRecords: [],
|
||||
domains: [],
|
||||
gatewayDomains: [],
|
||||
gatewayDnsRecords: [],
|
||||
certificates: [],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import * as shared from './shared/index.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';
|
||||
|
||||
@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`
|
||||
.table { border: 1px solid var(--ci-shade-2, #e4e4e7); border-radius: 10px; overflow: hidden; }
|
||||
.row { display: grid; grid-template-columns: 2fr 90px 2fr 90px 140px 220px; gap: 16px; align-items: center; padding: 14px 16px; border-bottom: 1px solid var(--ci-shade-2, #e4e4e7); }
|
||||
.row:last-child { border-bottom: none; }
|
||||
.header { font-size: 12px; font-weight: 700; text-transform: uppercase; color: var(--ci-shade-5, #71717a); background: var(--ci-shade-1, #f4f4f5); }
|
||||
.name { font-weight: 600; }
|
||||
.value { font-family: monospace; color: var(--ci-shade-5, #71717a); overflow-wrap: anywhere; }
|
||||
.badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
|
||||
.missing { color: #dc2626; }
|
||||
a, button.link { color: var(--ci-primary, #2563eb); background: none; border: none; padding: 0; cursor: pointer; font: inherit; text-decoration: none; }
|
||||
.actions { display: flex; gap: 12px; }
|
||||
.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>
|
||||
<div class="table">
|
||||
<div class="row header">
|
||||
<span>Name</span>
|
||||
<span>Type</span>
|
||||
<span>Value</span>
|
||||
<span>Status</span>
|
||||
<span>Service</span>
|
||||
<span>Actions</span>
|
||||
</div>
|
||||
${records.length ? records.map((record) => html`
|
||||
<div class="row ${record.status === 'missing' ? 'missing' : ''}">
|
||||
<span class="name">${record.name}</span>
|
||||
<span><span class="badge">${record.type}</span></span>
|
||||
<span class="value">${record.value || '-'}</span>
|
||||
<span>${record.status}</span>
|
||||
<span>${record.serviceName || record.appId}</span>
|
||||
<span class="actions">
|
||||
<button class="link" @click=${() => appRouter.navigateToView('services')}>View service</button>
|
||||
${record.manageUrl ? html`<a href=${record.manageUrl} target="_blank" rel="noopener">Manage in dcrouter</a>` : ''}
|
||||
</span>
|
||||
</div>
|
||||
`) : html`<div class="empty">No gateway DNS records found. Configure a dcrouter gateway in Settings.</div>`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import * as shared from './shared/index.js';
|
||||
import * as appstate from '../appstate.js';
|
||||
import {
|
||||
DeesElement,
|
||||
customElement,
|
||||
html,
|
||||
state,
|
||||
css,
|
||||
cssManager,
|
||||
type TemplateResult,
|
||||
} from '@design.estate/dees-element';
|
||||
|
||||
@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`
|
||||
.table {
|
||||
border: 1px solid var(--ci-shade-2, #e4e4e7);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 120px 120px 140px;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--ci-shade-2, #e4e4e7);
|
||||
}
|
||||
.row:last-child { border-bottom: none; }
|
||||
.header { font-size: 12px; font-weight: 700; text-transform: uppercase; color: var(--ci-shade-5, #71717a); background: var(--ci-shade-1, #f4f4f5); }
|
||||
.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; }
|
||||
a { color: var(--ci-primary, #2563eb); text-decoration: none; }
|
||||
.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>
|
||||
<div class="table">
|
||||
<div class="row header">
|
||||
<span>Domain</span>
|
||||
<span>Source</span>
|
||||
<span>Authoritative</span>
|
||||
<span>Services</span>
|
||||
<span>Actions</span>
|
||||
</div>
|
||||
${domains.length ? domains.map((domain) => html`
|
||||
<div class="row">
|
||||
<span>
|
||||
<span class="domain">${domain.name}</span>
|
||||
${domain.providerId ? html`<div class="muted">Provider: ${domain.providerId}</div>` : ''}
|
||||
</span>
|
||||
<span><span class="badge">${domain.source || 'dcrouter'}</span></span>
|
||||
<span>${domain.authoritative ? 'Yes' : 'No'}</span>
|
||||
<span>${domain.serviceCount || 0}</span>
|
||||
<span>${domain.manageUrl ? html`<a href=${domain.manageUrl} target="_blank" rel="noopener">Manage in dcrouter</a>` : '-'}</span>
|
||||
</div>
|
||||
`) : html`<div class="empty">No gateway domains found. Configure a dcrouter gateway in Settings.</div>`}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,8 @@ export class ObViewNetwork extends DeesElement {
|
||||
trafficStats: null,
|
||||
dnsRecords: [],
|
||||
domains: [],
|
||||
gatewayDomains: [],
|
||||
gatewayDnsRecords: [],
|
||||
certificates: [],
|
||||
};
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ export class ObViewSettings extends DeesElement {
|
||||
accessor settingsState: appstate.ISettingsState = {
|
||||
settings: null,
|
||||
backupPasswordConfigured: false,
|
||||
managedDcRouterStatus: null,
|
||||
};
|
||||
|
||||
@state()
|
||||
@@ -49,27 +50,29 @@ export class ObViewSettings extends DeesElement {
|
||||
css`
|
||||
.gateway-card {
|
||||
margin-bottom: 24px;
|
||||
border: 1px solid var(--dees-color-border-subtle);
|
||||
border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
|
||||
border-radius: 12px;
|
||||
background: var(--dees-color-background, #ffffff);
|
||||
background: ${cssManager.bdTheme('#ffffff', '#09090b')};
|
||||
overflow: hidden;
|
||||
box-shadow: 0 1px 2px ${cssManager.bdTheme('rgba(0,0,0,0.04)', 'rgba(0,0,0,0.2)')};
|
||||
}
|
||||
|
||||
.gateway-header {
|
||||
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 {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--dees-color-text-primary);
|
||||
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
|
||||
}
|
||||
|
||||
.gateway-subtitle {
|
||||
margin-top: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--dees-color-text-muted);
|
||||
color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
|
||||
}
|
||||
|
||||
.gateway-content {
|
||||
@@ -79,38 +82,70 @@ export class ObViewSettings extends DeesElement {
|
||||
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 {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--dees-color-text-secondary);
|
||||
}
|
||||
|
||||
input {
|
||||
dees-input-text {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--dees-color-border-subtle);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--dees-color-text-primary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
margin-top: 5px;
|
||||
font-size: 12px;
|
||||
color: var(--dees-color-text-muted);
|
||||
}
|
||||
|
||||
.gateway-footer {
|
||||
@@ -119,25 +154,15 @@ export class ObViewSettings extends DeesElement {
|
||||
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) {
|
||||
.gateway-content {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.gateway-status-row {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
@@ -156,6 +181,14 @@ export class ObViewSettings extends DeesElement {
|
||||
darkMode: true,
|
||||
cloudflareToken: '',
|
||||
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,
|
||||
renewalThreshold: 30,
|
||||
acmeEmail: '',
|
||||
@@ -187,45 +220,99 @@ export class ObViewSettings extends DeesElement {
|
||||
|
||||
private renderExternalGatewaySettings(): TemplateResult {
|
||||
const settings = this.settingsState.settings;
|
||||
const mode = settings?.dcrouterMode || 'managed';
|
||||
return html`
|
||||
<section class="gateway-card">
|
||||
<div class="gateway-header">
|
||||
<div class="gateway-title">External dcrouter Gateway</div>
|
||||
<div class="gateway-subtitle">Delegate public WorkApp routing, DNS, and certificates to a dcrouter edge authority.</div>
|
||||
<div class="gateway-title">dcrouter Gateway</div>
|
||||
<div class="gateway-subtitle">Run a local managed dcrouter or delegate routing, DNS, and certificates to an external dcrouter.</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">
|
||||
${this.renderGatewayInput('dcrouterGatewayUrl', 'Gateway URL', settings?.dcrouterGatewayUrl || '', 'https://edge.example.com', 'Base URL of the dcrouter OpsServer.')}
|
||||
${this.renderGatewayInput('dcrouterGatewayApiToken', 'API Token', settings?.dcrouterGatewayApiToken || '', 'dcrouter API token', 'Requires workhosters and certificates scopes.', 'password')}
|
||||
${this.renderGatewayInput('dcrouterWorkHosterId', 'WorkHoster ID', settings?.dcrouterWorkHosterId || '', 'optional stable owner ID', 'Leave empty to let Onebox create a stable ID.')}
|
||||
${this.renderGatewayInput('dcrouterTargetHost', 'Target Host', settings?.dcrouterTargetHost || '', 'public or private host/IP', 'Defaults to the configured server IP when empty.')}
|
||||
${this.renderGatewayInput('dcrouterTargetPort', 'Target Port', String(settings?.dcrouterTargetPort || 80), '80', 'Internal HTTP port dcrouter forwards to.', 'number')}
|
||||
${mode === 'managed' ? html`
|
||||
${this.renderGatewayInput('dcrouterManagedImage', 'dcrouter Image', settings?.dcrouterManagedImage || 'code.foss.global/serve.zone/dcrouter:latest', 'OCI image used for the managed local gateway.')}
|
||||
${this.renderGatewayInput('dcrouterManagedDataDir', 'Data Directory', settings?.dcrouterManagedDataDir || './.nogit/dcrouter-data', 'Host directory mounted into the dcrouter container.')}
|
||||
${this.renderGatewayInput('dcrouterManagedOpsPort', 'Local Ops Port', String(settings?.dcrouterManagedOpsPort || 3300), 'Bound to 127.0.0.1 for Onebox to call dcrouter APIs.')}
|
||||
${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.renderGatewayInput('dcrouterGatewayClientId', 'Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || '', 'Leave empty to let Onebox create a stable ID.')}
|
||||
` : 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.renderGatewayInput('dcrouterGatewayClientId', 'Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || '', 'Leave empty to let Onebox create a stable ID.')}
|
||||
${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 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>
|
||||
</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(
|
||||
key: keyof NonNullable<appstate.ISettingsState['settings']>,
|
||||
label: string,
|
||||
value: string,
|
||||
placeholder: string,
|
||||
hint: string,
|
||||
type: 'text' | 'password' | 'number' = 'text',
|
||||
isPassword = false,
|
||||
): TemplateResult {
|
||||
return html`
|
||||
<label class="gateway-field ${key === 'dcrouterGatewayUrl' ? 'full' : ''}">
|
||||
<span class="field-label">${label}</span>
|
||||
<input
|
||||
type=${type}
|
||||
<div class="gateway-field ${key === 'dcrouterGatewayUrl' ? 'full' : ''}">
|
||||
<dees-input-text
|
||||
.key=${key}
|
||||
.label=${label}
|
||||
.value=${value}
|
||||
placeholder=${placeholder}
|
||||
.description=${hint}
|
||||
.isPasswordBool=${isPassword}
|
||||
@input=${(event: Event) => this.updateGatewayDraft(key, (event.target as HTMLInputElement).value)}
|
||||
/>
|
||||
<span class="field-hint">${hint}</span>
|
||||
</label>
|
||||
></dees-input-text>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -234,7 +321,13 @@ export class ObViewSettings extends DeesElement {
|
||||
value: string,
|
||||
): void {
|
||||
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,
|
||||
settings: {
|
||||
@@ -250,12 +343,19 @@ export class ObViewSettings extends DeesElement {
|
||||
|
||||
await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
|
||||
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 || '',
|
||||
dcrouterGatewayApiToken: settings.dcrouterGatewayApiToken || '',
|
||||
dcrouterWorkHosterId: settings.dcrouterWorkHosterId || '',
|
||||
dcrouterGatewayClientId: settings.dcrouterGatewayClientId || settings.dcrouterWorkHosterId || '',
|
||||
dcrouterTargetHost: settings.dcrouterTargetHost || '',
|
||||
dcrouterTargetPort: Number(settings.dcrouterTargetPort) || 80,
|
||||
},
|
||||
});
|
||||
await appstate.settingsStatePart.dispatchAction(appstate.fetchManagedDcRouterStatusAction, null);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import * as appstate from './appstate.js';
|
||||
const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;
|
||||
|
||||
export const validViews = [
|
||||
'dashboard', 'app-store', 'services', 'network',
|
||||
'dashboard', 'app-store', 'services', 'domains', 'dns-records', 'network',
|
||||
'registries', 'tokens', 'settings',
|
||||
] as const;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user