Skip to content

Build your personal knowledge base with Trilium Notes

9.8 KB
Raw Blame
import { app_info as appInfo, getLog, getMessagingProvider, getPlatform, utils } from "@triliumnext/core";
import type { Express } from "express";
import fs from "fs";
import http from "http";
import https from "https";
import { networkInterfaces } from "os";

import buildApp from "./app.js";
import { TRILIUM_LOGO } from "./log_provider.js";
import config from "./services/config.js";
import dataDir from "./services/data_dir.js";
import { startCpuProfiler, writeCpuProfile } from "./services/cpu_profiler.js";
import { registerOcrHandlers } from "./services/handlers.js";
import host from "./services/host.js";
import { registerServerLlmExtensions } from "./services/llm/index.js";
import { listListeningUrls } from "./services/network_addresses.js";
import port from "./services/port.js";
import { installProcessErrorHandlers, markAppReady } from "./services/process_errors.js";
import { isScriptingEnabled } from "./services/scripting_guard.js";
import { isElectron } from "./services/utils.js";
import { publishHealthcheckTarget } from "./services/healthcheck.js";
import { getDbSize } from "./services/sql_init.js";
import { isHttpAttachableMessagingProvider } from "./services/ws_messaging_provider.js";

const MINIMUM_NODE_VERSION = "20.0.0";

export default async function startTriliumServer(): Promise<Express> {
    await displayStartupMessage();

    // setup basic error handling even before requiring dependencies, since those can produce errors as well
    installProcessErrorHandlers();

    // When TRILIUM_PROFILE is set we drive the V8 CPU profiler ourselves rather than relying on Node's
    // --cpu-prof flag: that flag flushes its file during the normal shutdown path, which the exit() handler
    // below short-circuits with process.exit(0), so the profile is silently never written.
    const profilerSession = startCpuProfiler();

    let exiting = false;
    function exit(reason: string) {
        if (exiting) {
            return;
        }
        exiting = true;
        console.log(reason);
        // Writing the profile needs an async inspector round-trip. On a signal this races the process
        // teardown and often loses, so the reliable trigger is the Enter keypress wired up below; the
        // signal path is best-effort.
        writeCpuProfile(profilerSession, () => process.exit(0));
    }

    process.on("SIGINT", () => exit("Caught interrupt/termination signal. Exiting."));
    process.on("SIGTERM", () => exit("Caught interrupt/termination signal. Exiting."));

    if (profilerSession) {
        // Pressing Enter fires during normal event-loop operation, so the async profile flush completes
        // before we exit β€” unlike Ctrl+C, which the V8 inspector round-trip can't reliably outrun.
        process.stdin.resume();
        process.stdin.on("data", () => exit("Writing CPU profile and exiting (TRILIUM_PROFILE)."));
    }

    if (utils.compareVersions(process.versions.node, MINIMUM_NODE_VERSION) < 0) {
        console.error();
        console.error(`The Trilium server requires Node.js ${MINIMUM_NODE_VERSION} and later in order to start.\n`);
        console.error(`\tCurrent version:\t${process.versions.node}`);
        console.error(`\tExpected version:\t${MINIMUM_NODE_VERSION}`);
        console.error();
        process.exit(1);
    }

    const app = await buildApp();
    const httpServer = startHttpServer(app);

    // Only providers that serve clients over the TCP listener need the HTTP server
    // and session parser (the server's WebSocket provider, or the desktop composite
    // when LAN access is on). A pure Electron-IPC provider isn't HTTP-attachable, so
    // it's skipped here and no WS endpoint is bound. Gating on the capability rather
    // than a concrete type keeps www.ts platform-agnostic.
    const messaging = getMessagingProvider();
    if (isHttpAttachableMessagingProvider(messaging)) {
        const sessionParser = (await import("./routes/session_parser.js")).default;
        messaging.attachToHttpServer(httpServer, sessionParser);
    }

    const { ws } = await import("@triliumnext/core");
    ws.init();

    registerOcrHandlers();
    registerServerLlmExtensions();

    // Everything the application needs in order to be usable is now up, so from here on an escaped error
    // is a contained failure rather than a broken startup, and stops being fatal.
    markAppReady();

    return app;
}

async function displayStartupMessage() {
    getLog().info(`\n${TRILIUM_LOGO} ${appInfo.appVersion}\n`);
    getLog().info(`πŸ“¦ Versions:    app=${appInfo.appVersion} db=${appInfo.dbVersion} sync=${appInfo.syncVersion} clipper=${appInfo.clipperProtocolVersion}`);
    getLog().info(`πŸ”§ Build:       ${utils.formatUtcTime(appInfo.buildDate)} (${appInfo.buildRevision.substring(0, 10)})`);
    getLog().info(`πŸ“‚ Data dir:    ${appInfo.dataDirectory}`);
    getLog().info(`⏰ UTC time:    ${utils.formatUtcTime(appInfo.utcDateTime)}`);

    // for perf. issues it's good to know the rough configuration
    const cpuInfos = (await import("os")).cpus();
    if (cpuInfos && cpuInfos[0] !== undefined) {
        // https://github.com/zadam/trilium/pull/3957
        const cpuModel = (cpuInfos[0].model || "").trimEnd();
        getLog().info(`πŸ’» CPU:         ${cpuModel} (${cpuInfos.length}-core @ ${cpuInfos[0].speed} Mhz)`);
    }
    getLog().info(`πŸ’Ύ DB size:     ${utils.formatSize(getDbSize() * 1024)}`);

    if (isScriptingEnabled()) {
        getLog().warn("Backend script execution is ENABLED. Backend scripts have full server access including " +
                 "filesystem, network, and OS commands. Only enable in trusted environments.");
    } else {
        getLog().info("Backend script execution is DISABLED. Set [Security] backendScriptingEnabled=true in config.ini to enable.");
    }

    getLog().info("");
}

function startHttpServer(app: Express) {
    app.set("port", port);
    app.set("host", host);

    // Check from config whether to trust reverse proxies to supply user IPs, hostnames and protocols
    if (config["Network"]["trustedReverseProxy"]) {
        if (config["Network"]["trustedReverseProxy"] === true || config["Network"]["trustedReverseProxy"].trim().length) {
            app.set("trust proxy", config["Network"]["trustedReverseProxy"]);
        }
    }

    getLog().info(`Trusted reverse proxy: ${app.get("trust proxy")}`);

    let httpServer: http.Server | https.Server;

    if (config["Network"]["https"]) {
        if (!config["Network"]["keyPath"] || !config["Network"]["keyPath"].trim().length) {
            throw new Error("keyPath in config.ini is required when https=true, but it's empty");
        }

        if (!config["Network"]["certPath"] || !config["Network"]["certPath"].trim().length) {
            throw new Error("certPath in config.ini is required when https=true, but it's empty");
        }

        const options = {
            key: fs.readFileSync(config["Network"]["keyPath"]),
            cert: fs.readFileSync(config["Network"]["certPath"])
        };

        httpServer = https.createServer(options, app);

        getLog().info(`App HTTPS server starting up at port ${port}`);
    } else {
        httpServer = http.createServer(app);

        getLog().info(`App HTTP server starting up at port ${port}`);
    }

    /**
     * Listen on provided port, on all network interfaces.
     */

    httpServer.keepAliveTimeout = 120000 * 5;
    const listenOnTcp = port !== 0;

    if (listenOnTcp) {
        httpServer.listen(port, host); // TCP socket.
    } else {
        httpServer.listen(host); // Unix socket.
    }

    httpServer.on("error", (error) => {
        let message = error.stack || "An unexpected error has occurred.";

        // handle specific listen errors with friendly messages
        if ("code" in error) {
            switch (error.code) {
                case "EACCES":
                    message = `Port ${port} requires elevated privileges. It's recommended to use port above 1024.`;
                    break;
                case "EADDRINUSE":
                    message = `Port ${port} is already in use. Most likely, another Trilium process is already running. You might try to find it, kill it, and try again.`;
                    break;
                case "EADDRNOTAVAIL":
                    message = `Unable to start the server on host '${host}'. Make sure the host (defined in 'config.ini' or via the 'TRILIUM_HOST' environment variable) is an IP address that can be listened on.`;
                    break;
            }
        }

        const platform = getPlatform();
        if (platform.shouldIgnoreStartupError?.(error)) {
            console.error(message);
        } else {
            platform.crash(`Error while initializing the server: ${message}`);
        }
    });

    httpServer.on("listening", () => {
        if (listenOnTcp) {
            getLog().info(`Listening on port ${port}`);
            printListeningUrls();
        } else {
            getLog().info(`Listening on unix socket ${host}`);
        }

        publishHealthcheckTarget(
            dataDir.TRILIUM_DATA_DIR, httpServer.address(), config.Network.https);
    });

    return httpServer;
}

/**
 * Prints the URLs the server answers on. It writes to the console only, since the log file ends
 * up in bug reports and the list can hold a public address. Desktop has no console to read, and
 * in a container the interfaces belong to the container network rather than the host.
 */
function printListeningUrls() {
    if (isElectron || fs.existsSync("/.dockerenv") || fs.existsSync("/run/.containerenv")) {
        return;
    }

    const protocol = config["Network"]["https"] ? "https" : "http";
    const { local, network } = listListeningUrls(protocol, host, port, networkInterfaces());

    if (local) {
        console.log(`🌐 Local:       ${local}`);
    }
    for (const [index, url] of network.entries()) {
        console.log(`${index === 0 ? "🌐 Network:     " : "                "}${url}`);
    }
}