Repository: louislam/uptime-kuma
File: server/monitor-types/mqtt.js (JavaScript)

Code before:
     * @param {string} topic MQTT topic
     * @param {object} options MQTT options. Contains port, username,
     * password, webSocketPath and interval (interval defaults to 20)
     * @returns {Promise<string>} Received MQTT message
     */
    mqttAsync(hostname, topic, options = {}) {
        return new Promise((resolve, reject) => {
            const { port, username, password, webSocketPath, interval = 20 } = options;

            // Adds MQTT protocol to the hostname if not already present
            if (!/^(?:http|mqtt|ws)s?:\/\//.test(hostname)) {
                hostname = "mqtt://" + hostname;
            }

            const timeoutID = setTimeout(() => {
                log.debug("mqtt", "MQTT timeout triggered");
                client.end();
                reject(new Error("Timeout, Message not received"));
            }, interval * 1000 * 0.8);

            // Construct the URL based on protocol
            let mqttUrl;
            if (hostname.startsWith("ws://") || hostname.startsWith("wss://")) {
                // For WebSocket connections, include the path
                const path = webSocketPath || "";
                mqttUrl = `${hostname}:${port}${path}`;
            } else {
                // For regular MQTT connections
                mqttUrl = `${hostname}:${port}`;
            }

            log.debug("mqtt", `MQTT connecting to ${mqttUrl}`);

            let client = mqtt.connect(mqttUrl, {
                username,
                password,
                clientId: "uptime-kuma_" + Math.random().toString(16).substr(2, 8)
            });

            client.on("connect", () => {
                log.debug("mqtt", "MQTT connected");

                try {
                    client.subscribe(topic, () => {
                        log.debug("mqtt", "MQTT subscribed to topic");
                    });
                } catch (e) {
                    client.end();
                    clearTimeout(timeoutID);
                    reject(new Error("Cannot subscribe topic"));
                }

Review comment (suggestion):
you need to verify that `webSocketPath` starts with `/` or append it if it starts not.

In addition to this verification, the frontend should also have an regex for this.

Code after:
     * @param {string} topic MQTT topic
     * @param {object} options MQTT options. Contains port, username,
     * password, websocketPath and interval (interval defaults to 20)
     * @returns {Promise<string>} Received MQTT message
     */
    mqttAsync(hostname, topic, options = {}) {
        return new Promise((resolve, reject) => {
            const { port, username, password, websocketPath, interval = 20 } = options;

            // Adds MQTT protocol to the hostname if not already present
            if (!/^(?:http|mqtt|ws)s?:\/\//.test(hostname)) {
                hostname = "mqtt://" + hostname;
            }

            const timeoutID = setTimeout(() => {
                log.debug("mqtt", "MQTT timeout triggered");
                client.end();
                reject(new Error("Timeout, Message not received"));
            }, interval * 1000 * 0.8);

            // Construct the URL based on protocol
            let mqttUrl = `${hostname}:${port}`;
            if (hostname.startsWith("ws://") || hostname.startsWith("wss://")) {
                if (websocketPath && !websocketPath.startsWith("/")) {
                    mqttUrl = `${hostname}:${port}/${websocketPath || ""}`;
                } else {
                    mqttUrl = `${hostname}:${port}${websocketPath || ""}`;
                }
            }

            log.debug("mqtt", `MQTT connecting to ${mqttUrl}`);

            let client = mqtt.connect(mqttUrl, {
                username,
                password,
                clientId: "uptime-kuma_" + Math.random().toString(16).substr(2, 8)
            });

            client.on("connect", () => {
                log.debug("mqtt", "MQTT connected");

                try {
                    client.subscribe(topic, () => {
                        log.debug("mqtt", "MQTT subscribed to topic");
                    });
                } catch (e) {
                    client.end();
                    clearTimeout(timeoutID);
                    reject(new Error("Cannot subscribe topic"));
                }
            });