Files
onebox/ts/classes/reverseproxy.ts
T

246 lines
7.1 KiB
TypeScript
Raw Normal View History

2025-11-18 00:03:24 +00:00
/**
* Reverse Proxy for Onebox
*
* Delegates to SmartProxy (running as Docker service) for production-grade reverse proxy
* with TLS termination, WebSocket proxying, and zero-downtime configuration updates.
*
* Routes use Docker service names (e.g., onebox-hello-world:80) for container-to-container
* communication within the Docker overlay network.
2025-11-18 00:03:24 +00:00
*/
import { logger } from '../logging.ts';
import { getErrorMessage } from '../utils/error.ts';
2025-11-18 00:03:24 +00:00
import { OneboxDatabase } from './database.ts';
import { SmartProxyManager } from './smartproxy.ts';
2025-11-18 00:03:24 +00:00
interface IProxyRoute {
domain: string;
targetHost: string;
targetPort: number;
serviceId: number;
serviceName?: string;
2025-11-18 00:03:24 +00:00
}
export class OneboxReverseProxy {
private oneboxRef: any;
private database: OneboxDatabase;
private smartProxy: SmartProxyManager;
2025-11-18 00:03:24 +00:00
private routes: Map<string, IProxyRoute> = new Map();
2025-11-26 12:16:50 +00:00
private httpPort = 8080; // Default to dev ports (will be overridden if production)
private httpsPort = 8443;
2025-11-18 00:03:24 +00:00
constructor(oneboxRef: any) {
this.oneboxRef = oneboxRef;
this.database = oneboxRef.database;
this.smartProxy = new SmartProxyManager({
2025-11-26 12:16:50 +00:00
httpPort: this.httpPort,
httpsPort: this.httpsPort,
});
2025-11-18 00:03:24 +00:00
}
/**
* Initialize reverse proxy - SmartProxy runs as Docker service, no setup needed
2025-11-18 00:03:24 +00:00
*/
async init(): Promise<void> {
logger.info('Reverse proxy initialized (SmartProxy Docker service)');
2025-11-18 00:03:24 +00:00
}
/**
2025-11-26 12:16:50 +00:00
* Start the HTTP/HTTPS reverse proxy server
* SmartProxy handles both HTTP and HTTPS on the configured ports
2025-11-18 00:03:24 +00:00
*/
async startHttp(port?: number): Promise<void> {
if (port) {
this.httpPort = port;
this.smartProxy.setPorts(this.httpPort, this.httpsPort);
2025-11-18 00:03:24 +00:00
}
try {
await this.smartProxy.start();
logger.success(`Reverse proxy started on port ${this.httpPort} (SmartProxy Docker service)`);
2025-11-18 00:03:24 +00:00
} catch (error) {
2025-11-26 12:16:50 +00:00
logger.error(`Failed to start reverse proxy: ${getErrorMessage(error)}`);
2025-11-18 00:03:24 +00:00
throw error;
}
}
/**
* Start HTTPS - SmartProxy already handles HTTPS when started
2025-11-26 12:16:50 +00:00
* This method exists for interface compatibility
2025-11-18 00:03:24 +00:00
*/
async startHttps(port?: number): Promise<void> {
if (port) {
this.httpsPort = port;
this.smartProxy.setPorts(this.httpPort, this.httpsPort);
2025-11-18 00:03:24 +00:00
}
const status = this.smartProxy.getStatus();
2025-11-26 12:16:50 +00:00
if (status.running) {
logger.info(`HTTPS already running on port ${this.httpsPort} via SmartProxy`);
2025-11-26 12:16:50 +00:00
} else {
await this.smartProxy.start();
2025-11-18 00:03:24 +00:00
}
}
2025-11-26 09:36:40 +00:00
/**
2025-11-26 12:16:50 +00:00
* Stop the reverse proxy
2025-11-18 00:03:24 +00:00
*/
async stop(): Promise<void> {
await this.smartProxy.stop();
2025-11-26 12:16:50 +00:00
logger.info('Reverse proxy stopped');
2025-11-18 00:03:24 +00:00
}
/**
* Add a route for a service
* Uses Docker service name for upstream (SmartProxy runs in same Docker network)
2025-11-18 00:03:24 +00:00
*/
async addRoute(serviceId: number, domain: string, targetPort: number): Promise<void> {
try {
// Get service info from database
2025-11-18 00:03:24 +00:00
const service = this.database.getServiceByID(serviceId);
if (!service) {
throw new Error(`Service not found: ${serviceId}`);
2025-11-18 00:03:24 +00:00
}
// Use Docker service name as upstream target
// SmartProxy runs on the same Docker network, so it can resolve service names directly
const serviceName = `onebox-${service.name}`;
const targetHost = serviceName;
2025-11-18 00:03:24 +00:00
const route: IProxyRoute = {
domain,
targetHost,
targetPort,
serviceId,
serviceName,
2025-11-18 00:03:24 +00:00
};
this.routes.set(domain, route);
2025-11-26 12:16:50 +00:00
// Add route to SmartProxy using Docker service name
2025-11-26 12:16:50 +00:00
const upstream = `${targetHost}:${targetPort}`;
await this.smartProxy.addRoute(domain, upstream);
2025-11-26 12:16:50 +00:00
logger.success(`Added proxy route: ${domain} -> ${upstream}`);
2025-11-18 00:03:24 +00:00
} catch (error) {
logger.error(`Failed to add route for ${domain}: ${getErrorMessage(error)}`);
2025-11-18 00:03:24 +00:00
throw error;
}
}
/**
* Remove a route
*/
removeRoute(domain: string): void {
if (this.routes.delete(domain)) {
// Remove from SmartProxy (async but we don't wait)
this.smartProxy.removeRoute(domain).catch((error) => {
logger.error(`Failed to remove SmartProxy route for ${domain}: ${getErrorMessage(error)}`);
2025-11-26 12:16:50 +00:00
});
2025-11-18 00:03:24 +00:00
logger.success(`Removed proxy route: ${domain}`);
} else {
logger.warn(`Route not found: ${domain}`);
}
}
/**
* Get all routes
*/
getRoutes(): IProxyRoute[] {
return Array.from(this.routes.values());
}
/**
* Reload routes from database
*/
async reloadRoutes(): Promise<void> {
try {
logger.info('Reloading proxy routes...');
// Clear local and SmartProxy routes
2025-11-18 00:03:24 +00:00
this.routes.clear();
this.smartProxy.clear();
2025-11-18 00:03:24 +00:00
const services = this.database.getAllServices();
for (const service of services) {
// Route by domain if running (containerID is the service ID for Swarm services)
2025-11-18 00:03:24 +00:00
if (service.domain && service.status === 'running' && service.containerID) {
await this.addRoute(service.id!, service.domain, service.port);
}
}
logger.success(`Loaded ${this.routes.size} proxy routes`);
} catch (error) {
logger.error(`Failed to reload routes: ${getErrorMessage(error)}`);
2025-11-18 00:03:24 +00:00
throw error;
}
}
/**
2025-11-26 12:16:50 +00:00
* Add TLS certificate for a domain
* Sends PEM content to SmartProxy via Admin API
2025-11-18 00:03:24 +00:00
*/
2025-11-26 12:16:50 +00:00
async addCertificate(domain: string, certPem: string, keyPem: string): Promise<void> {
if (!certPem || !keyPem) {
logger.warn(`Cannot add certificate for ${domain}: missing PEM content`);
return;
}
2025-11-18 00:03:24 +00:00
await this.smartProxy.addCertificate(domain, certPem, keyPem);
2025-11-18 00:03:24 +00:00
}
/**
* Remove TLS certificate for a domain
*/
removeCertificate(domain: string): void {
this.smartProxy.removeCertificate(domain).catch((error) => {
2025-11-26 12:16:50 +00:00
logger.error(`Failed to remove certificate for ${domain}: ${getErrorMessage(error)}`);
});
2025-11-18 00:03:24 +00:00
}
/**
* Reload TLS certificates from database
2025-11-18 00:03:24 +00:00
*/
async reloadCertificates(): Promise<void> {
try {
logger.info('Reloading TLS certificates from database...');
2025-11-18 00:03:24 +00:00
const certificates = this.database.getAllSSLCertificates();
for (const cert of certificates) {
// Use fullchainPem for the cert (includes intermediates) and keyPem for the key
if (cert.domain && cert.fullchainPem && cert.keyPem) {
await this.smartProxy.addCertificate(cert.domain, cert.fullchainPem, cert.keyPem);
} else {
logger.warn(`Skipping certificate for ${cert.domain}: missing PEM content`);
2025-11-18 00:03:24 +00:00
}
}
logger.success(`Loaded ${this.smartProxy.getCertificates().length} TLS certificates`);
2025-11-18 00:03:24 +00:00
} catch (error) {
logger.error(`Failed to reload certificates: ${getErrorMessage(error)}`);
2025-11-18 00:03:24 +00:00
throw error;
}
}
/**
* Get status of reverse proxy
*/
getStatus() {
const smartProxyStatus = this.smartProxy.getStatus();
2025-11-18 00:03:24 +00:00
return {
http: {
running: smartProxyStatus.running,
port: smartProxyStatus.httpPort,
2025-11-18 00:03:24 +00:00
},
https: {
running: smartProxyStatus.running,
port: smartProxyStatus.httpsPort,
certificates: smartProxyStatus.certificates,
2025-11-18 00:03:24 +00:00
},
routes: smartProxyStatus.routes,
backend: 'smartproxy-docker',
2025-11-18 00:03:24 +00:00
};
}
}