ronantakizawa/codereview-bench huggingface dataset:
Repository: louislam/uptime-kuma
File: server/database.js (JavaScript)

Code before:

    static templatePath = "./db/kuma.db";
    static dataDir;
    static path;

    /**
     * @type {boolean}
     */
    static patched = false;

    /**
     * For Backup only
     */
    static backupPath = null;

    /**
     * Add patch filename in key
     * Values:
     *      true: Add it regardless of order
     *      false: Do nothing
     *      { parents: []}: Need parents before add it
     */
    static patchList = {
        "patch-setting-value-type.sql": true,
        "patch-improve-performance.sql": true,
        "patch-add-retry-interval-monitor.sql": true
    }

    /**
     * The finally version should be 10 after merged tag feature
     * @deprecated Use patchList for any new feature
     */
    static latestVersion = 9;

    static noReject = true;

    static async connect() {
        const acquireConnectionTimeout = 120 * 1000;

        R.setup("sqlite", {
            filename: Database.path,
            useNullAsDefault: true,
            acquireConnectionTimeout: acquireConnectionTimeout,
        }, {
            min: 1,
            max: 1,
            idleTimeoutMillis: 120 * 1000,
            propagateCreateError: false,
            acquireTimeoutMillis: acquireConnectionTimeout,
        });


Review comment (suggestion):
```suggestion
        "patch-add-retry-interval-monitor.sql": true,
```

Code after:

    static templatePath = "./db/kuma.db";
    static dataDir;
    static path;

    /**
     * @type {boolean}
     */
    static patched = false;

    /**
     * For Backup only
     */
    static backupPath = null;

    /**
     * Add patch filename in key
     * Values:
     *      true: Add it regardless of order
     *      false: Do nothing
     *      { parents: []}: Need parents before add it
     */
    static patchList = {
        "patch-setting-value-type.sql": true,
        "patch-improve-performance.sql": true,
        "patch-2fa.sql": true,
        "patch-add-retry-interval-monitor.sql": true,
    }

    /**
     * The finally version should be 10 after merged tag feature
     * @deprecated Use patchList for any new feature
     */
    static latestVersion = 9;

    static noReject = true;

    static async connect() {
        const acquireConnectionTimeout = 120 * 1000;

        R.setup("sqlite", {
            filename: Database.path,
            useNullAsDefault: true,
            acquireConnectionTimeout: acquireConnectionTimeout,
        }, {
            min: 1,
            max: 1,
            idleTimeoutMillis: 120 * 1000,
            propagateCreateError: false,
            acquireTimeoutMillis: acquireConnectionTimeout,
        });
Repository: louislam/uptime-kuma
File: server/notification-providers/octopush.js (JavaScript)

Code before:
                    "sender": notification.octopushSenderName
		};
		await axios.post("https://api.octopush.com/v1/public/sms-campaign/send", data, config)
	    }
	    else if (notification.octopushVersion == 1)
	    {
		let data = {
                    "user_login": notification.octopushDMLogin,
		    "api_key": notification.octopushDMAPIKey,
		    "sms_recipients" : notification.octopushDMPhoneNumber,
		    "sms_sender": notification.octopushDMSenderName,
		    "sms_type": (notification.octopushDMSMSType == 'sms_premium')?'FR':'XXX',
		    "transactional": '1',
		    //octopush not supporting non ascii char
		    "sms_text": msg.replace(/[^\x00-\x7F]/g, ""),
		};

		let config = {
		    headers: {
		        "cache-control": "no-cache"
		    },
		    params: data
		};
		await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config)
	    } else
		throw new Error('Unknown Octopush version !');

            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = Octopush;


Review comment (suggestion):
```suggestion
		throw new Error('Unknown Octopush version!');
```

Code after:
                };
                await axios.post("https://api.octopush.com/v1/public/sms-campaign/send", data, config)
            } else if (notification.octopushVersion == 1) {
                let data = {
                    "user_login": notification.octopushDMLogin,
                    "api_key": notification.octopushDMAPIKey,
                    "sms_recipients": notification.octopushDMPhoneNumber,
                    "sms_sender": notification.octopushDMSenderName,
                    "sms_type": (notification.octopushDMSMSType == "sms_premium") ? "FR" : "XXX",
                    "transactional": "1",
                    //octopush not supporting non ascii char
                    "sms_text": msg.replace(/[^\x00-\x7F]/g, ""),
                };

                let config = {
                    headers: {
                        "cache-control": "no-cache"
                    },
                    params: data
                };
                await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config)
            } else {
                throw new Error("Unknown Octopush version!");
            }

            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = Octopush;
Repository: louislam/uptime-kuma
File: extra/entrypoint.sh (Shell)

Code before:
#!/usr/bin/env sh

set -e

files_ownership () {
    chown -hRc "${PUID=1000}":"${PGID=1000}" /app/data
}

echo "==> Performing startup jobs and maintenance tasks"
files_ownership

echo "==> Starting application with user ${PUID=1000} group ${PGID=1000}"
exec setpriv --reuid "${PUID=1000}" --regid "${PGID=1000}" --clear-groups "$@"


Review comment (suggestion):
Consider adding default values here `1000` and using that variable below, instead of using the value `1000` in so many places.

Code after:
#!/usr/bin/env sh

# set -e Exit the script if an error happens
set -e
PUID=${PUID=1000}
PGID=${PGID=1000}

files_ownership () {
    # -h Changes the ownership of an encountered symbolic link and not that of the file or directory pointed to by the symbolic link.
    # -R Recursively descends the specified directories
    # -c Like verbose but report only when a change is made
    chown -hRc "$PUID":"$PGID" /app/data
}

echo "==> Performing startup jobs and maintenance tasks"
files_ownership

echo "==> Starting application with user $PUID group $PGID"

# --clear-groups Clear supplementary groups.
exec setpriv --reuid "$PUID" --regid "$PGID" --clear-groups "$@"
Repository: louislam/uptime-kuma
File: src/i18n.js (JavaScript)

Code before:
    en,
    "zh-HK": zhHK,
    "de-DE": deDE,
    "nl-NL": nlNL,
    "es-ES": esEs,
    "pt-BR": ptBR,
    "fr-FR": frFR,
    "it-IT": itIT,
    "ja": ja,
    "da-DK": daDK,
    "sr": sr,
    "sr-latn": srLatn,
    "sv-SE": svSE,
    "tr-TR": trTR,
    "ko-KR": koKR,
    "ru-RU": ruRU,
    "zh-CN": zhCN,
    "pl": pl,
    "et-EE": etEE,
};

export const i18n = createI18n({
    locale: localStorage.locale || "en",
    fallbackLocale: "en",
    silentFallbackWarn: true,
    silentTranslationWarn: process.env.NODE_ENV !== "development",
    messages: languageList,
});


Review comment (bug):
Maybe better to add another env var to determine this. Sometimes there are too many language warnings that push out other important debug messages.

Code after:
import zhHK from "./languages/zh-HK";

const languageList = {
    en,
    "zh-HK": zhHK,
    "bg-BG": bgBG,
    "de-DE": deDE,
    "nl-NL": nlNL,
    "es-ES": esEs,
    "fa": fa,
    "pt-BR": ptBR,
    "fr-FR": frFR,
    "hu": hu,
    "it-IT": itIT,
    "ja": ja,
    "da-DK": daDK,
    "sr": sr,
    "sr-latn": srLatn,
    "sv-SE": svSE,
    "tr-TR": trTR,
    "ko-KR": koKR,
    "ru-RU": ruRU,
    "zh-CN": zhCN,
    "pl": pl,
    "et-EE": etEE,
};

const rtlLangs = ["fa"];

export const currentLocale = () => localStorage.locale || "en";

export const localeDirection = () => {
    return rtlLangs.includes(currentLocale()) ? "rtl" : "ltr";
};

export const i18n = createI18n({
    locale: currentLocale(),
    fallbackLocale: "en",
    silentFallbackWarn: true,
    silentTranslationWarn: true,
    messages: languageList,
});
Repository: louislam/uptime-kuma
File: src/pages/EditMonitor.vue (Vue)

Code before:
            return null;
        },

        pageName() {
            return this.$t((this.isAdd) ? "Add New Monitor" : "Edit");
        },

        isAdd() {
            return this.$route.path === "/add";
        },

        isEdit() {
            return this.$route.path.startsWith("/edit");
        },

        pushURL() {
            return this.$root.baseURL + "/api/push/" + this.monitor.pushToken + "?msg=OK&ping=";
        },

        bodyPlaceholder() {
            return `{
    "id": 124357,
    "username": "admin",
    "password": "myAdminPassword"
}`;
        },

        headersPlaceholder() {
            return "Authorization: Bearer abc123\nContent-Type: application/json";
        }

    },
    watch: {

        "$route.fullPath"() {
            this.init();
        },

        "monitor.interval"(value, oldValue) {
            // Link interval and retryInterval if they are the same value.
            if (this.monitor.retryInterval === oldValue) {
                this.monitor.retryInterval = value;
            }
        },

        "monitor.type"() {
            if (this.monitor.type === "push") {
                if (! this.monitor.pushToken) {
                    this.monitor.pushToken = genSecret(10);
                }
            }

Review comment (suggestion):
```suggestion
        bodyPlaceholder() {
            return `{
                "id": 124357,
                "username": "admin",
                "password": "myAdminPassword"
            }`;
        },
```

Code after:
        ipRegex() {

            // Allow to test with simple dns server with port (127.0.0.1:5300)
            if (! isDev) {
                return this.ipRegexPattern;
            }
            return null;
        },

        pageName() {
            return this.$t((this.isAdd) ? "Add New Monitor" : "Edit");
        },

        isAdd() {
            return this.$route.path === "/add";
        },

        isEdit() {
            return this.$route.path.startsWith("/edit");
        },

        pushURL() {
            return this.$root.baseURL + "/api/push/" + this.monitor.pushToken + "?msg=OK&ping=";
        },

        bodyPlaceholder() {
            return this.decodeHtml("&lbrace;\n\t\"id\": 124357,\n\t\"username\": \"admin\",\n\t\"password\": \"myAdminPassword\"\n&rbrace;");
        },

        headersPlaceholder() {
            return this.decodeHtml("&lbrace;\n\t\"Authorization\": \"Bearer abc123\",\n\t\"Content-Type\": \"application/json\"\n&rbrace;");
        }

    },
    watch: {

        "$route.fullPath"() {
            this.init();
        },

        "monitor.interval"(value, oldValue) {
            // Link interval and retryInterval if they are the same value.
            if (this.monitor.retryInterval === oldValue) {
                this.monitor.retryInterval = value;
            }
        },

        "monitor.type"() {
            if (this.monitor.type === "push") {
                if (! this.monitor.pushToken) {
                    this.monitor.pushToken = genSecret(10);
Repository: louislam/uptime-kuma
File: server/notification-providers/promosms.js (JavaScript)

Code before:
const axios = require("axios");

class PromoSMS extends NotificationProvider {

    name = "promosms";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";

        try {
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Basic " + Buffer.from(notification.promosmsLogin + ":" + notification.promosmsPassword).toString('base64'),
                    "Accept": "text/json",
                }
            };
            let data = {
                "recipients": [ notification.promosmsPhoneNumber ],
                //Lets remove non ascii char
                "text": msg.replace(/[^\x00-\x7F]/g, ""),
                "type": Number(notification.promosmsSMSType),
                "sender": notification.promosmsSenderName
            };

            await axios.post("https://promosms.com/api/rest/v3_2/sms", data, config).then(resp => {
                if (resp.data.response.status !== 0) {
                    let error = "Something gone wrong. Api returned " + resp.data.response.status + ".";
                    this.throwGeneralAxiosError(error);
                }
            });
            
            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = PromoSMS;


Review comment (suggestion):
I think `.then(...)` is not necessary, as it will throw error if the status code is a bad code.

Code after:
const axios = require("axios");

class PromoSMS extends NotificationProvider {

    name = "promosms";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";

        try {
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Basic " + Buffer.from(notification.promosmsLogin + ":" + notification.promosmsPassword).toString('base64'),
                    "Accept": "text/json",
                }
            };
            let data = {
                "recipients": [ notification.promosmsPhoneNumber ],
                //Lets remove non ascii char
                "text": msg.replace(/[^\x00-\x7F]/g, ""),
                "type": Number(notification.promosmsSMSType),
                "sender": notification.promosmsSenderName
            };

            let resp = await axios.post("https://promosms.com/api/rest/v3_2/sms", data, config);

            if (resp.data.response.status !== 0) {
                let error = "Something gone wrong. Api returned " + resp.data.response.status + ".";
                this.throwGeneralAxiosError(error);
            }
            
            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = PromoSMS;
Repository: louislam/uptime-kuma
File: server/server.js (JavaScript)

Code before:
            try {
                checkLogin(socket);

                await R.exec("UPDATE `user` SET twofa_status = 0 WHERE id = ? ", [
                    socket.userID,
                ]);

                callback({
                    ok: true,
                    msg: "2FA Disabled.",
                });
            } catch (error) {
                callback({
                    ok: false,
                    msg: "Error while trying to change 2FA.",
                });
            }
        });

        socket.on("verifyToken", async (token, callback) => {
            let user = await R.findOne("user", " id = ? AND active = 1 ", [
                socket.userID,
            ]);

            let verify = notp.totp.verify(token, user.twofa_secret, { "window": 1,
                "time": 30 });

            if (verify && verify.delta == 0) {
                callback({
                    ok: true,
                    valid: true,
                });
            } else {
                callback({
                    ok: false,
                    msg: "Invalid Token.",
                    valid: false,
                });
            }
        });

        socket.on("twoFAStatus", async (callback) => {
            checkLogin(socket);

            try {
                let user = await R.findOne("user", " id = ? AND active = 1 ", [
                    socket.userID,
                ]);

                if (user.twofa_status == 1) {
                    callback({

Review comment (suggestion):
Please move `{ "window": 1, "time": 30 }` to const variable

Code after:
                });
            }
        });

        socket.on("disable2FA", async (callback) => {
            try {
                checkLogin(socket);

                await R.exec("UPDATE `user` SET twofa_status = 0 WHERE id = ? ", [
                    socket.userID,
                ]);

                callback({
                    ok: true,
                    msg: "2FA Disabled.",
                });
            } catch (error) {
                callback({
                    ok: false,
                    msg: "Error while trying to change 2FA.",
                });
            }
        });

        socket.on("verifyToken", async (token, callback) => {
            let user = await R.findOne("user", " id = ? AND active = 1 ", [
                socket.userID,
            ]);

            let verify = notp.totp.verify(token, user.twofa_secret, twofa_verification_opts);

            if (verify && verify.delta == 0) {
                callback({
                    ok: true,
                    valid: true,
                });
            } else {
                callback({
                    ok: false,
                    msg: "Invalid Token.",
                    valid: false,
                });
            }
        });

        socket.on("twoFAStatus", async (callback) => {
            checkLogin(socket);

            try {
                let user = await R.findOne("user", " id = ? AND active = 1 ", [
                    socket.userID,
Repository: louislam/uptime-kuma
File: server/notification-providers/dingding.js (JavaScript)

Code before:
const NotificationProvider = require("./notification-provider");
const { DOWN, UP } = require("../../src/util");
const { default: axios } = require("axios");
const Crypto = require("crypto");

class DingDing extends NotificationProvider {
    name = "DingDing";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";

        try {
            if (heartbeatJSON != null) {
                var params = {
                    msgtype:"markdown",
                    markdown:{
                        title: monitorJSON["name"],
                        text: `## [${this.statusToString(heartbeatJSON["status"])}] \n > ${heartbeatJSON["msg"]}  \n > Time(UTC):${heartbeatJSON["time"]}`,
                    }
                };
                if (this.sendToDingDing(notification, params)) {
                    return okMsg;
                }
            } else {
                var params = {
                    msgtype:"text",
                    text:{
                        content:msg
                    }
                };
                if (this.sendToDingDing(notification, params)) {
                    return okMsg;
                }
            }
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }

    async sendToDingDing(notification, params) {
        var timestamp=Date.now()

Review comment (suggestion):
```suggestion
                    msgtype: "markdown",
                    markdown: {
```

Code after:
const NotificationProvider = require("./notification-provider");
const { DOWN, UP } = require("../../src/util");
const { default: axios } = require("axios");
const Crypto = require("crypto");

class DingDing extends NotificationProvider {
    name = "DingDing";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";

        try {
            if (heartbeatJSON != null) {
                let params = {
                    msgtype: "markdown",
                    markdown: {
                        title: monitorJSON["name"],
                        text: `## [${this.statusToString(heartbeatJSON["status"])}] \n > ${heartbeatJSON["msg"]}  \n > Time(UTC):${heartbeatJSON["time"]}`,
                    }
                };
                if (this.sendToDingDing(notification, params)) {
                    return okMsg;
                }
            } else {
                let params = {
                    msgtype: "text",
                    text: {
                        content: msg
                    }
                };
                if (this.sendToDingDing(notification, params)) {
                    return okMsg;
                }
            }
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }

    async sendToDingDing(notification, params) {
        let timestamp = Date.now();
Repository: louislam/uptime-kuma
File: server/notification-providers/dingding.js (JavaScript)

Code before:
        }
    }

    async sendToDingDing(notification, params) {
        var timestamp=Date.now()

        var config = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            url: `${notification.webHookUrl}&timestamp=${timestamp}&sign=${encodeURIComponent(this.sign(timestamp, notification.secretKey))}`,
            data: JSON.stringify(params),
        };

        var result = await axios(config);
        if (result.data.errmsg == "ok") {
            return true;
        }
        return false;
    }

    /** DingDing sign */
    sign(timestamp,secretKey) {
        return Crypto
            .createHmac("sha256",Buffer.from(secretKey, 'utf8'))
            .update(Buffer.from(`${timestamp}\n${secretKey}`, 'utf8'))
            .digest("base64");
    }

    statusToString(status) {
        switch (status) {
            case DOWN:
                return "DOWN";
            case UP:
                return "UP";
            default:
                return status;
        }
    }
}

module.exports = DingDing;


Review comment (security):
```suggestion
            .createHmac("sha256", Buffer.from(secretKey, 'utf8'))
```

Code after:
        }
    }

    async sendToDingDing(notification, params) {
        let timestamp = Date.now();

        let config = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            url: `${notification.webHookUrl}&timestamp=${timestamp}&sign=${encodeURIComponent(this.sign(timestamp, notification.secretKey))}`,
            data: JSON.stringify(params),
        };

        let result = await axios(config);
        if (result.data.errmsg == "ok") {
            return true;
        }
        return false;
    }

    /** DingDing sign */
    sign(timestamp, secretKey) {
        return Crypto
            .createHmac("sha256", Buffer.from(secretKey, "utf8"))
            .update(Buffer.from(`${timestamp}\n${secretKey}`, "utf8"))
            .digest("base64");
    }

    statusToString(status) {
        switch (status) {
            case DOWN:
                return "DOWN";
            case UP:
                return "UP";
            default:
                return status;
        }
    }
}

module.exports = DingDing;