import path from "node:path"; import { existsSync, readFileSync, unlinkSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { createAccelerationRelayServer } from "./server/acceleration-relay.js"; import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js"; import { SkinRegistry } from "./admin/skin-registry.js"; import { PluginRegistry } from "./plugins/registry.js"; import { UpdateService } from "./updater/update-service.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.resolve(__dirname, ".."); const CONFIG_PATH = path.join(ROOT_DIR, "config.json"); const CERT_DIR = path.join(ROOT_DIR, "certs"); // Production images mount the persistent volume at /data. Source installs // keep the historical project-local data directory unless overridden. const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "data"); const LOG_DIR = path.join(DATA_DIR, "logs"); const STATIC_DIR = path.join(ROOT_DIR, "web", "dist"); const APP_VERSION = readPackageVersion(); const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS); async function main() { if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") { await runRelayMode(); return; } const [{ createLogger }, { createWebServer }, { APP_PORT }, { WebSpeakDatabase }, { loadOrCreateMasterSecret }, { AdminService }, { JoinTicketStore }] = await Promise.all([ import("./logger.js"), import("./server/server.js"), import("./constants.js"), import("./persistence/database.js"), import("./security/master-secret.js"), import("./admin/admin-service.js"), import("./server/join-ticket.js"), ]); const logger = createLogger(LOG_DIR); const database = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db")); const masterSecret = loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key")); const adminService = new AdminService( database, masterSecret, logger, CONFIG_PATH, undefined, APP_VERSION, ); await adminService.initialize(); removeObsoleteBootstrapFile(); const joinTickets = new JoinTicketStore(); const pluginRegistry = new PluginRegistry(path.join(DATA_DIR, "plugins"), masterSecret); await pluginRegistry.initialize(); logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server"); const hasCert = existsSync(path.join(CERT_DIR, "cert.pem")); const updateService = new UpdateService({ rootDir: ROOT_DIR, dataDir: DATA_DIR, currentVersion: APP_VERSION, logger, port: APP_PORT, https: hasCert, }); updateService.initialize(); let webServer: ReturnType | undefined; webServer = createWebServer({ port: APP_PORT, version: APP_VERSION, logFile: path.join(LOG_DIR, "webspeak.log"), staticDir: STATIC_DIR, certDir: hasCert ? CERT_DIR : undefined, updateService, restartAfterUpdate: () => { void (async () => { if (!updateService.runnerStillHealthy()) { // 202 already promised a restart, but the helper died before this // process left. Stay up and reconcile instead of reporting success // and silently abandoning the update. logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state"); try { updateService.initialize(); } catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); } return; } logger.info("Stopping for scheduled update"); try { await webServer?.stop(); } catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); } database.close(); process.exit(0); })(); }, voiceBridgeOptions: { joinTickets, trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES), webRtc: () => adminService.getWebRtcAudioOptions(), screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS, // The public gateway only uses the relay configuration explicitly // saved in the admin console. Environment variables belong to the // standalone relay process and must never make the relay option appear // in the visitor UI after an administrator disables it. acceleration: () => adminService.getAccelerationRelayOptions(), accelerationName: () => adminService.getAccelerationRelayName(), }, adminService, skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")), pluginRegistry, pluginRuntime: { port: parsePort(process.env.WEBSPEAK_PLUGIN_PORT, 3042), host: process.env.WEBSPEAK_PLUGIN_HOST?.trim() || "0.0.0.0", publicOrigin: process.env.WEBSPEAK_PLUGIN_PUBLIC_ORIGIN?.trim() }, logger, nextVisitorNumber: () => database.nextVisitorNumber(), visitorCount: () => database.getVisitorCount(), }); await webServer.start(); // Graceful shutdown const shutdown = async (signal: string) => { logger.info({ signal }, "Shutting down"); await webServer.stop(); database.close(); process.exit(0); }; process.on("SIGINT", () => shutdown("SIGINT")); process.on("SIGTERM", () => shutdown("SIGTERM")); } async function runRelayMode(): Promise { const token = (process.env.WEBSPEAK_RELAY_TOKEN || process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN)?.trim(); if (!token) throw new Error("WEBSPEAK_RELAY_TOKEN is required in relay mode"); const host = (process.env.WEBSPEAK_RELAY_HOST || process.env.WEBSPEAK_ACCELERATION_RELAY_HOST)?.trim() || "0.0.0.0"; const port = parsePort(process.env.WEBSPEAK_RELAY_PORT || process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087); const allowPrivate = parseBoolean(process.env.WEBSPEAK_RELAY_ALLOW_PRIVATE || process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE); const voiceHost = process.env.WEBSPEAK_VOICE_GATEWAY_HOST?.trim() || "127.0.0.1"; const voicePort = parsePort(process.env.WEBSPEAK_VOICE_GATEWAY_PORT, 3041); const webRtcUdpStart = parsePort(process.env.WEBSPEAK_RELAY_WEBRTC_UDP_START, 40000); const webRtcUdpEnd = parsePort(process.env.WEBSPEAK_RELAY_WEBRTC_UDP_END, 40099); if (webRtcUdpStart > webRtcUdpEnd) throw new Error("Invalid relay WebRTC UDP port range"); const [{ createLogger }, { createVoiceGatewayServer }] = await Promise.all([ import("./logger.js"), import("./server/voice-gateway.js"), ]); const logger = createLogger(LOG_DIR); const [{ WebSpeakDatabase }, { loadOrCreateMasterSecret }, { WorkspaceInvites }] = await Promise.all([ import("./persistence/database.js"), import("./security/master-secret.js"), import("./server/workspace-invites.js"), ]); const inviteDatabase = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db")); const workspaceInvites = new WorkspaceInvites(inviteDatabase, loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key"))); const voiceGateway = createVoiceGatewayServer({ workspaceInvites, host: voiceHost, port: voicePort, sharedToken: token, logger, webRtc: { enabled: process.env.WEBSPEAK_RELAY_WEBRTC_ENABLED === undefined ? true : parseBoolean(process.env.WEBSPEAK_RELAY_WEBRTC_ENABLED), ...(process.env.WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST?.trim() ? { publicHost: process.env.WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST.trim() } : {}), ipv6Enabled: parseBoolean(process.env.WEBSPEAK_RELAY_WEBRTC_IPV6_ENABLED), ...(process.env.WEBSPEAK_RELAY_WEBRTC_STUN_SERVER?.trim() ? { stunServer: process.env.WEBSPEAK_RELAY_WEBRTC_STUN_SERVER.trim() } : {}), udpPortRange: [webRtcUdpStart, webRtcUdpEnd] as [number, number], }, screenShareIceServers: SCREEN_SHARE_ICE_SERVERS, trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES), }); const voiceAddress = await voiceGateway.start(); let relay: Awaited>; try { relay = await createAccelerationRelayServer({ host, port, token, allowPrivate }); } catch (error) { await voiceGateway.stop(); throw error; } console.log(`WebSpeak relay mode listening on ${relay.host}:${relay.port}; voice gateway on ${voiceAddress.host}:${voiceAddress.port}`); let stopping = false; const shutdown = (): void => { if (stopping) return; stopping = true; relay.close(); void voiceGateway.stop().finally(() => { inviteDatabase.close(); process.exit(0); }); }; process.once("SIGINT", shutdown); process.once("SIGTERM", shutdown); } function readPackageVersion(): string { try { const packageJson = JSON.parse(readFileSync(path.join(ROOT_DIR, "package.json"), "utf8")) as { version?: unknown }; return typeof packageJson.version === "string" && packageJson.version ? packageJson.version : "0.1.0"; } catch { return "0.1.0"; } } function removeObsoleteBootstrapFile(): void { try { unlinkSync(path.join(DATA_DIR, "bootstrap")); } catch (error: unknown) { if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; } } function parsePort(value: string | undefined, fallback: number): number { const port = value ? Number(value) : fallback; if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid relay port"); return port; } function parseBoolean(value: string | undefined): boolean { return value === "1" || value?.toLowerCase() === "true"; } function readTrustedProxies(value: string | undefined): string[] | undefined { const entries = value?.split(/[\s,]+/).filter(Boolean) ?? []; return entries.length ? entries : undefined; } function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] { const raw = value?.trim(); if (!raw) return normalizeScreenShareIceServers(); try { const parsed: unknown = JSON.parse(raw); return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined); } catch { // A simple comma/space-separated list is convenient for STUN-only setups. return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls }))); } } main().catch((err) => { console.error("Fatal error:", err); process.exit(1); });