feat: add workhoster gateway API
This commit is contained in:
@@ -256,6 +256,15 @@ export class RouteConfigManager {
|
||||
return this.updateRoute(id, { enabled });
|
||||
}
|
||||
|
||||
public findApiRouteByExternalKey(externalKey: string): IRoute | undefined {
|
||||
for (const route of this.routes.values()) {
|
||||
if (route.origin === 'api' && route.metadata?.externalKey === externalKey) {
|
||||
return route;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Private: seed routes from constructor config
|
||||
// =========================================================================
|
||||
@@ -443,6 +452,15 @@ export class RouteConfigManager {
|
||||
lastResolvedAt: typeof metadata.lastResolvedAt === 'number' && Number.isFinite(metadata.lastResolvedAt)
|
||||
? metadata.lastResolvedAt
|
||||
: undefined,
|
||||
ownerType: metadata.ownerType === 'workhoster' || metadata.ownerType === 'operator' || metadata.ownerType === 'system'
|
||||
? metadata.ownerType
|
||||
: undefined,
|
||||
workHosterType: metadata.workHosterType === 'onebox' || metadata.workHosterType === 'cloudly' || metadata.workHosterType === 'custom'
|
||||
? metadata.workHosterType
|
||||
: undefined,
|
||||
workHosterId: normalizeString(metadata.workHosterId),
|
||||
workAppId: normalizeString(metadata.workAppId),
|
||||
externalKey: normalizeString(metadata.externalKey),
|
||||
};
|
||||
|
||||
if (!normalized.sourceProfileRef) {
|
||||
@@ -454,6 +472,12 @@ export class RouteConfigManager {
|
||||
if (!normalized.sourceProfileRef && !normalized.networkTargetRef) {
|
||||
normalized.lastResolvedAt = undefined;
|
||||
}
|
||||
if (normalized.ownerType !== 'workhoster') {
|
||||
normalized.workHosterType = undefined;
|
||||
normalized.workHosterId = undefined;
|
||||
normalized.workAppId = undefined;
|
||||
normalized.externalKey = undefined;
|
||||
}
|
||||
|
||||
if (Object.values(normalized).every((value) => value === undefined)) {
|
||||
return undefined;
|
||||
|
||||
@@ -38,6 +38,7 @@ export class OpsServer {
|
||||
private dnsRecordHandler!: handlers.DnsRecordHandler;
|
||||
private acmeConfigHandler!: handlers.AcmeConfigHandler;
|
||||
private emailDomainHandler!: handlers.EmailDomainHandler;
|
||||
private workHosterHandler!: handlers.WorkHosterHandler;
|
||||
|
||||
constructor(dcRouterRefArg: DcRouter) {
|
||||
this.dcRouterRef = dcRouterRefArg;
|
||||
@@ -106,6 +107,7 @@ export class OpsServer {
|
||||
this.dnsRecordHandler = new handlers.DnsRecordHandler(this);
|
||||
this.acmeConfigHandler = new handlers.AcmeConfigHandler(this);
|
||||
this.emailDomainHandler = new handlers.EmailDomainHandler(this);
|
||||
this.workHosterHandler = new handlers.WorkHosterHandler(this);
|
||||
|
||||
console.log('✅ OpsServer TypedRequest handlers initialized');
|
||||
}
|
||||
@@ -119,4 +121,4 @@ export class OpsServer {
|
||||
await this.server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,21 +26,51 @@ export function deriveCertDomainName(domain: string): string | undefined {
|
||||
}
|
||||
|
||||
export class CertificateHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter?.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
const viewRouter = this.opsServerRef.viewRouter;
|
||||
const adminRouter = this.opsServerRef.adminRouter;
|
||||
private async requireAuth(
|
||||
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
|
||||
requiredScope?: interfaces.data.TApiTokenScope,
|
||||
): Promise<string> {
|
||||
if (request.identity?.jwt) {
|
||||
try {
|
||||
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
|
||||
identity: request.identity,
|
||||
});
|
||||
if (isAdmin) return request.identity.userId;
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
|
||||
// ---- Read endpoints (viewRouter — valid identity required via middleware) ----
|
||||
if (request.apiToken) {
|
||||
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
|
||||
if (tokenManager) {
|
||||
const token = await tokenManager.validateToken(request.apiToken);
|
||||
if (token) {
|
||||
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
|
||||
return token.createdBy;
|
||||
}
|
||||
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new plugins.typedrequest.TypedResponseError('unauthorized');
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
const router = this.typedrouter;
|
||||
|
||||
// Get Certificate Overview
|
||||
viewRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetCertificateOverview>(
|
||||
'getCertificateOverview',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:read');
|
||||
const certificates = await this.buildCertificateOverview();
|
||||
const summary = this.buildSummary(certificates);
|
||||
return { certificates, summary };
|
||||
@@ -48,53 +78,56 @@ export class CertificateHandler {
|
||||
)
|
||||
);
|
||||
|
||||
// ---- Write endpoints (adminRouter — admin identity required via middleware) ----
|
||||
|
||||
// Legacy route-based reprovision (backward compat)
|
||||
adminRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ReprovisionCertificate>(
|
||||
'reprovisionCertificate',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:write');
|
||||
return this.reprovisionCertificateByRoute(dataArg.routeName);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Domain-based reprovision (preferred)
|
||||
adminRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ReprovisionCertificateDomain>(
|
||||
'reprovisionCertificateDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:write');
|
||||
return this.reprovisionCertificateDomain(dataArg.domain, dataArg.forceRenew);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Delete certificate
|
||||
adminRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteCertificate>(
|
||||
'deleteCertificate',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:write');
|
||||
return this.deleteCertificate(dataArg.domain);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Export certificate
|
||||
adminRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ExportCertificate>(
|
||||
'exportCertificate',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:read');
|
||||
return this.exportCertificate(dataArg.domain);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Import certificate
|
||||
adminRouter.addTypedHandler(
|
||||
router.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ImportCertificate>(
|
||||
'importCertificate',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'certificates:write');
|
||||
return this.importCertificate(dataArg.cert);
|
||||
}
|
||||
)
|
||||
|
||||
@@ -18,4 +18,5 @@ export * from './dns-provider.handler.js';
|
||||
export * from './domain.handler.js';
|
||||
export * from './dns-record.handler.js';
|
||||
export * from './acme-config.handler.js';
|
||||
export * from './email-domain.handler.js';
|
||||
export * from './email-domain.handler.js';
|
||||
export * from './workhoster.handler.js';
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import * as plugins from '../../plugins.js';
|
||||
import type { OpsServer } from '../classes.opsserver.js';
|
||||
import * as interfaces from '../../../ts_interfaces/index.js';
|
||||
|
||||
export class WorkHosterHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private async requireAuth(
|
||||
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
|
||||
requiredScope?: interfaces.data.TApiTokenScope,
|
||||
): Promise<string> {
|
||||
if (request.identity?.jwt) {
|
||||
try {
|
||||
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
|
||||
identity: request.identity,
|
||||
});
|
||||
if (isAdmin) return request.identity.userId;
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
|
||||
if (request.apiToken) {
|
||||
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
|
||||
if (tokenManager) {
|
||||
const token = await tokenManager.validateToken(request.apiToken);
|
||||
if (token) {
|
||||
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
|
||||
return token.createdBy;
|
||||
}
|
||||
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new plugins.typedrequest.TypedResponseError('unauthorized');
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayCapabilities>(
|
||||
'getGatewayCapabilities',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'workhosters:read');
|
||||
return { capabilities: this.getGatewayCapabilities() };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetWorkHosterDomains>(
|
||||
'getWorkHosterDomains',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'workhosters:read');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { domains: [] };
|
||||
|
||||
const docs = await dnsManager.listDomains();
|
||||
const domains = docs.map((domainDoc) => {
|
||||
const domain = dnsManager.toPublicDomain(domainDoc);
|
||||
const canManageDnsRecords = domain.source === 'dcrouter' || Boolean(domain.providerId);
|
||||
return {
|
||||
...domain,
|
||||
capabilities: {
|
||||
canCreateSubdomains: canManageDnsRecords,
|
||||
canManageDnsRecords,
|
||||
canIssueCertificates: Boolean(this.opsServerRef.dcRouterRef.smartProxy),
|
||||
canHostEmail: Boolean(this.opsServerRef.dcRouterRef.emailDomainManager),
|
||||
},
|
||||
} satisfies interfaces.data.IWorkHosterDomain;
|
||||
});
|
||||
return { domains };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SyncWorkAppRoute>(
|
||||
'syncWorkAppRoute',
|
||||
async (dataArg) => {
|
||||
const userId = await this.requireAuth(dataArg, 'workhosters:write');
|
||||
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
|
||||
if (!manager) {
|
||||
return { success: false, message: 'Route management not initialized' };
|
||||
}
|
||||
|
||||
const externalKey = this.buildExternalKey(dataArg.ownership);
|
||||
const existingRoute = manager.findApiRouteByExternalKey(externalKey);
|
||||
|
||||
if (dataArg.delete) {
|
||||
if (!existingRoute) {
|
||||
return { success: true, action: 'unchanged' };
|
||||
}
|
||||
const result = await manager.deleteRoute(existingRoute.id);
|
||||
return result.success
|
||||
? { success: true, action: 'deleted', routeId: existingRoute.id }
|
||||
: { success: false, message: result.message };
|
||||
}
|
||||
|
||||
if (!dataArg.route) {
|
||||
return { success: false, message: 'route is required unless delete=true' };
|
||||
}
|
||||
|
||||
const metadata: interfaces.data.IRouteMetadata = {
|
||||
ownerType: 'workhoster',
|
||||
workHosterType: dataArg.ownership.workHosterType,
|
||||
workHosterId: dataArg.ownership.workHosterId,
|
||||
workAppId: dataArg.ownership.workAppId,
|
||||
externalKey,
|
||||
};
|
||||
const route = this.normalizeWorkAppRoute(dataArg.route, dataArg.ownership, externalKey);
|
||||
|
||||
if (existingRoute) {
|
||||
const result = await manager.updateRoute(existingRoute.id, {
|
||||
route,
|
||||
enabled: dataArg.enabled ?? true,
|
||||
metadata,
|
||||
});
|
||||
return result.success
|
||||
? { success: true, action: 'updated', routeId: existingRoute.id }
|
||||
: { success: false, message: result.message };
|
||||
}
|
||||
|
||||
const routeId = await manager.createRoute(route, userId, dataArg.enabled ?? true, metadata);
|
||||
return { success: true, action: 'created', routeId };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private getGatewayCapabilities(): interfaces.data.IGatewayCapabilities {
|
||||
const dcRouter = this.opsServerRef.dcRouterRef;
|
||||
return {
|
||||
routes: {
|
||||
read: Boolean(dcRouter.routeConfigManager),
|
||||
write: Boolean(dcRouter.routeConfigManager),
|
||||
idempotentSync: Boolean(dcRouter.routeConfigManager),
|
||||
},
|
||||
domains: {
|
||||
read: Boolean(dcRouter.dnsManager),
|
||||
write: Boolean(dcRouter.dnsManager),
|
||||
},
|
||||
certificates: {
|
||||
read: Boolean(dcRouter.smartProxy),
|
||||
export: Boolean(dcRouter.smartProxy),
|
||||
forceRenew: Boolean(dcRouter.smartProxy),
|
||||
},
|
||||
email: {
|
||||
domains: Boolean(dcRouter.emailDomainManager),
|
||||
inbound: Boolean(dcRouter.emailServer),
|
||||
outbound: Boolean(dcRouter.emailServer),
|
||||
},
|
||||
remoteIngress: {
|
||||
enabled: Boolean(dcRouter.options.remoteIngressConfig?.enabled),
|
||||
},
|
||||
dns: {
|
||||
authoritative: Boolean(dcRouter.options.dnsScopes?.length),
|
||||
providerManaged: Boolean(dcRouter.dnsManager),
|
||||
},
|
||||
http3: {
|
||||
enabled: dcRouter.options.http3?.enabled !== false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private buildExternalKey(ownership: interfaces.data.IWorkAppRouteOwnership): string {
|
||||
return [
|
||||
ownership.workHosterType,
|
||||
ownership.workHosterId,
|
||||
ownership.workAppId,
|
||||
ownership.hostname,
|
||||
].map((part) => part.trim()).join(':');
|
||||
}
|
||||
|
||||
private normalizeWorkAppRoute(
|
||||
route: interfaces.data.IDcRouterRouteConfig,
|
||||
ownership: interfaces.data.IWorkAppRouteOwnership,
|
||||
externalKey: string,
|
||||
): interfaces.data.IDcRouterRouteConfig {
|
||||
const normalizedRoute = { ...route };
|
||||
if (!normalizedRoute.name) {
|
||||
normalizedRoute.name = `workapp-${externalKey.replace(/[^a-zA-Z0-9-]+/g, '-').slice(0, 80)}`;
|
||||
}
|
||||
return normalizedRoute;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user