diff --git a/.dockerignore b/.dockerignore index 4a63437a4..4ce0e13ab 100644 --- a/.dockerignore +++ b/.dockerignore @@ -28,6 +28,8 @@ SECURITY.md tsconfig.json .env /tmp +/babel.config.js +/ecosystem.config.js ### .gitignore content (commented rules are duplicated) @@ -42,4 +44,6 @@ dist-ssr #!/data/.gitkeep #.vscode + + ### End of .gitignore content diff --git a/.eslintrc.js b/.eslintrc.js index b0934d6d8..21e359104 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,4 +1,9 @@ module.exports = { + ignorePatterns: [ + "test/*", + "server/modules/apicache/*", + "src/util.js" + ], root: true, env: { browser: true, @@ -34,7 +39,7 @@ module.exports = { }, ], quotes: ["warn", "double"], - semi: "warn", + semi: "error", "vue/html-indent": ["warn", 4], // default: 2 "vue/max-attributes-per-line": "off", "vue/singleline-html-element-content-newline": "off", diff --git a/.github/workflows/auto-test.yml b/.github/workflows/auto-test.yml index e01c02cee..269e30854 100644 --- a/.github/workflows/auto-test.yml +++ b/.github/workflows/auto-test.yml @@ -20,6 +20,7 @@ jobs: # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ steps: + - run: git config --global core.autocrlf false # Mainly for Windows - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} diff --git a/.github/workflows/stale-bot.yml b/.github/workflows/stale-bot.yml deleted file mode 100644 index 5dc501369..000000000 --- a/.github/workflows/stale-bot.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: 'Automatically close stale issues and PRs' -on: - schedule: - - cron: '0 0 * * *' -#Run once a day at midnight - -jobs: - stale: - runs-on: ubuntu-latest - steps: - - uses: actions/stale@v4 - with: - stale-issue-message: 'We are clearing up our old issues and your ticket has been open for 6 months with no activity. Remove stale label or comment or this will be closed in 7 days.' - stale-pr-message: 'We are clearing up our old Pull Requests and yours has been open for 6 months with no activity. Remove stale label or comment or this will be closed in 7 days.' - close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.' - close-pr-message: 'This PR was closed because it has been stalled for 7 days with no activity.' - days-before-stale: 180 - days-before-close: 7 - exempt-issue-labels: 'News,Medium,High,discussion,bug,doc,' - exempt-pr-labels: 'awaiting-approval,work-in-progress,enhancement,' - exempt-issue-assignees: 'louislam' - exempt-pr-assignees: 'louislam' diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..521a9f7c0 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +legacy-peer-deps=true diff --git a/.stylelintrc b/.stylelintrc index aad673dbc..52301b542 100644 --- a/.stylelintrc +++ b/.stylelintrc @@ -1,9 +1,13 @@ { "extends": "stylelint-config-standard", + "customSyntax": "postcss-html", "rules": { "indentation": 4, "no-descending-specificity": null, "selector-list-comma-newline-after": null, - "declaration-empty-line-before": null + "declaration-empty-line-before": null, + "alpha-value-notation": "number", + "color-function-notation": "legacy", + "shorthand-property-no-redundant-values": null } } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3679bbd9b..1e6f7dfad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,12 +27,25 @@ The frontend code build into "dist" directory. The server (express.js) exposes t ## Can I create a pull request for Uptime Kuma? -Generally, if the pull request is working fine, and it does not affect any existing logic, workflow and performance, I will merge into the master branch once it is tested. +⚠️ 2022-03-02 Update: -If you are not sure whether I will accept your pull request, feel free to create an empty pull request draft first. +Since I found that merging pull requests is a pretty heavy task for me, I try to rearrange it. + +✅ Accept: +- Bug/Security fix +- Translations +- Adding notification providers + +❌ Avoid: +- Large pull requests +- New big features + +My long story here: https://www.reddit.com/r/UptimeKuma/comments/t1t6or/comment/hynyijx/ ### Recommended Pull Request Guideline +Before deep into coding, disscussion first is preferred. Creating an empty pull request for disscussion would be recommended. + 1. Fork the project 1. Clone your fork repo to local 1. Create a new branch @@ -42,42 +55,7 @@ If you are not sure whether I will accept your pull request, feel free to create 1. Create a pull request: https://github.com/louislam/uptime-kuma/compare 1. Write a proper description 1. Click "Change to draft" - -### Pull Request Examples - -Here are some example situations in the past. - -#### ✅ High - Medium Priority - -Easy to review, no breaking change and not touching the existing code - -- Add a new notification -- Add a chart -- Fix a bug -- Translations -- Add a independent new feature - -#### *️⃣ Requires one more reviewer - -I do not have such knowledge to test it. - -- Add k8s supports - -#### ⚠ Low Priority - Harsh Mode - -Some pull requests are required to modify the core. To be honest, I do not want anyone to try to do that, because it would spend a lot of your time. I will review your pull request harshly. Also, you may need to write a lot of unit tests to ensure that there is no breaking change. - -- Touch large parts of code of any very important features -- Touch monitoring logic -- Drop a table or drop a column for any reason -- Touch the entry point of Docker or Node.js -- Modify auth - -#### *️⃣ Low Priority - -It changed my current workflow and require further studies. - -- Change my release approach +1. Discussion #### ❌ Won't Merge @@ -221,14 +199,13 @@ https://github.com/louislam/uptime-kuma/issues?q=sort%3Aupdated-desc ### Release Procedures 1. Draft a release note -1. Make sure the repo is cleared -1. `npm run update-version 1.X.X` -1. `npm run build` -1. `npm run build-docker` -1. `git push` -1. Publish the release note as 1.X.X -1. `npm run upload-artifacts` -1. SSH to demo site server and update to 1.X.X +2. Make sure the repo is cleared +3. `npm run release-final with env vars: `VERSION` and `GITHUB_TOKEN` +4. Wait until the `Press any key to continue` +5. `git push` +6. Publish the release note as 1.X.X +7. Press any key to continue +8. SSH to demo site server and update to 1.X.X Checking: @@ -236,6 +213,15 @@ Checking: - Try the Docker image with tag 1.X.X (Clean install / amd64 / arm64 / armv7) - Try clean installation with Node.js +### Release Beta Procedures + +1. Draft a release note, check "This is a pre-release" +2. Make sure the repo is cleared +3. `npm run release-beta` with env vars: `VERSION` and `GITHUB_TOKEN` +4. Wait until the `Press any key to continue` +5. Publish the release note as 1.X.X-beta.X +6. Press any key to continue + ### Release Wiki #### Setup Repo diff --git a/README.md b/README.md index 7f88db5f4..313fe5408 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,6 @@ VPS is sponsored by Uptime Kuma sponsors on [Open Collective](https://opencollec ### 🐳 Docker ```bash -docker volume create uptime-kuma docker run -d --restart=always -p 3001:3001 -v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1 ``` @@ -47,7 +46,10 @@ Browse to http://localhost:3001 after starting. ### 💪🏻 Non-Docker -Required Tools: Node.js >= 14, git and pm2. +Required Tools: +- [Node.js](https://nodejs.org/en/download/) >= 14 +- [Git](https://git-scm.com/downloads) +- [pm2](https://pm2.keymetrics.io/) - For run in background ```bash # Update your npm to the latest version @@ -61,12 +63,26 @@ npm run setup node server/server.js # (Recommended) Option 2. Run in background using PM2 -# Install PM2 if you don't have it: npm install pm2 -g -pm2 start server/server.js --name uptime-kuma -``` +# Install PM2 if you don't have it: +npm install pm2 -g && pm2 install pm2-logrotate +# Start Server +pm2 start server/server.js --name uptime-kuma + + +``` Browse to http://localhost:3001 after starting. +More useful PM2 Commands + +```bash +# If you want to see the current console output +pm2 monit + +# If you want to add it to startup +pm2 save && pm2 startup +``` + ### Advanced Installation If you need more options or need to browse via a reverse proxy, please read: @@ -93,7 +109,7 @@ https://github.com/louislam/uptime-kuma/projects/1 Thank you so much! (GitHub Sponsors will be updated manually. OpenCollective sponsors will be updated automatically, the list will be cached by GitHub though. It may need some time to be updated) - + ## 🖼 More Screenshots @@ -115,7 +131,7 @@ Telegram Notification Sample: ## Motivation -* I was looking for a self-hosted monitoring tool like "Uptime Robot", but it is hard to find a suitable one. One of the close ones is statping. Unfortunately, it is not stable and unmaintained. +* I was looking for a self-hosted monitoring tool like "Uptime Robot", but it is hard to find a suitable one. One of the close ones is statping. Unfortunately, it is not stable and no longer maintained. * Want to build a fancy UI. * Learn Vue 3 and vite.js. * Show the power of Bootstrap 5. @@ -144,4 +160,4 @@ If you want to translate Uptime Kuma into your language, please read: https://gi If you want to modify Uptime Kuma, this guideline may be useful for you: https://github.com/louislam/uptime-kuma/blob/master/CONTRIBUTING.md -English proofreading is needed too because my grammar is not that great, sadly. Feel free to correct my grammar in this README, source code, or wiki. +Unfortunately, English proofreading is needed too because my grammar is not that great. Feel free to correct my grammar in this README, source code, or wiki. diff --git a/db/patch-monitor-expiry-notification.sql b/db/patch-monitor-expiry-notification.sql new file mode 100644 index 000000000..7a330014a --- /dev/null +++ b/db/patch-monitor-expiry-notification.sql @@ -0,0 +1,7 @@ +-- You should not modify if this have pushed to Github, unless it does serious wrong with the db. +BEGIN TRANSACTION; + +ALTER TABLE monitor + ADD expiry_notification BOOLEAN default 1; + +COMMIT; diff --git a/db/patch-proxy.sql b/db/patch-proxy.sql new file mode 100644 index 000000000..41897b1e2 --- /dev/null +++ b/db/patch-proxy.sql @@ -0,0 +1,23 @@ +-- You should not modify if this have pushed to Github, unless it does serious wrong with the db. +BEGIN TRANSACTION; + +CREATE TABLE proxy ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + user_id INT NOT NULL, + protocol VARCHAR(10) NOT NULL, + host VARCHAR(255) NOT NULL, + port SMALLINT NOT NULL, + auth BOOLEAN NOT NULL, + username VARCHAR(255) NULL, + password VARCHAR(255) NULL, + active BOOLEAN NOT NULL DEFAULT 1, + 'default' BOOLEAN NOT NULL DEFAULT 0, + created_date DATETIME DEFAULT (DATETIME('now')) NOT NULL +); + +ALTER TABLE monitor ADD COLUMN proxy_id INTEGER REFERENCES proxy(id); + +CREATE INDEX proxy_id ON monitor (proxy_id); +CREATE INDEX proxy_user_id ON proxy (user_id); + +COMMIT; diff --git a/db/patch-status-page.sql b/db/patch-status-page.sql new file mode 100644 index 000000000..d23b75bca --- /dev/null +++ b/db/patch-status-page.sql @@ -0,0 +1,31 @@ +-- You should not modify if this have pushed to Github, unless it does serious wrong with the db. +BEGIN TRANSACTION; + +CREATE TABLE [status_page]( + [id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + [slug] VARCHAR(255) NOT NULL UNIQUE, + [title] VARCHAR(255) NOT NULL, + [description] TEXT, + [icon] VARCHAR(255) NOT NULL, + [theme] VARCHAR(30) NOT NULL, + [published] BOOLEAN NOT NULL DEFAULT 1, + [search_engine_index] BOOLEAN NOT NULL DEFAULT 1, + [show_tags] BOOLEAN NOT NULL DEFAULT 0, + [password] VARCHAR, + [created_date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + [modified_date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX [slug] ON [status_page]([slug]); + + +CREATE TABLE [status_page_cname]( + [id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + [status_page_id] INTEGER NOT NULL REFERENCES [status_page]([id]) ON DELETE CASCADE ON UPDATE CASCADE, + [domain] VARCHAR NOT NULL UNIQUE +); + +ALTER TABLE incident ADD status_page_id INTEGER; +ALTER TABLE [group] ADD status_page_id INTEGER; + +COMMIT; diff --git a/docker/alpine-base.dockerfile b/docker/alpine-base.dockerfile index d162fe8fb..a23c81084 100644 --- a/docker/alpine-base.dockerfile +++ b/docker/alpine-base.dockerfile @@ -1,8 +1,8 @@ # DON'T UPDATE TO alpine3.13, 1.14, see #41. -FROM node:14-alpine3.12 +FROM node:16-alpine3.12 WORKDIR /app # Install apprise, iputils for non-root ping, setpriv RUN apk add --no-cache iputils setpriv dumb-init python3 py3-cryptography py3-pip py3-six py3-yaml py3-click py3-markdown py3-requests py3-requests-oauthlib && \ - pip3 --no-cache-dir install apprise==0.9.6 && \ + pip3 --no-cache-dir install apprise==0.9.7 && \ rm -rf /root/.cache diff --git a/docker/debian-base.dockerfile b/docker/debian-base.dockerfile index 83fd434be..62889dc94 100644 --- a/docker/debian-base.dockerfile +++ b/docker/debian-base.dockerfile @@ -1,12 +1,26 @@ # DON'T UPDATE TO node:14-bullseye-slim, see #372. # If the image changed, the second stage image should be changed too -FROM node:14-buster-slim +FROM node:16-buster-slim +ARG TARGETPLATFORM + WORKDIR /app +# Install Curl # Install Apprise, add sqlite3 cli for debugging in the future, iputils-ping for ping, util-linux for setpriv # Stupid python3 and python3-pip actually install a lot of useless things into Debian, specify --no-install-recommends to skip them, make the base even smaller than alpine! RUN apt update && \ apt --yes --no-install-recommends install python3 python3-pip python3-cryptography python3-six python3-yaml python3-click python3-markdown python3-requests python3-requests-oauthlib \ sqlite3 iputils-ping util-linux dumb-init && \ - pip3 --no-cache-dir install apprise==0.9.6 && \ + pip3 --no-cache-dir install apprise==0.9.7 && \ rm -rf /var/lib/apt/lists/* + +# Install cloudflared +# dpkg --add-architecture arm: cloudflared do not provide armhf, this is workaround. Read more: https://github.com/cloudflare/cloudflared/issues/583 +COPY extra/download-cloudflared.js ./extra/download-cloudflared.js +RUN node ./extra/download-cloudflared.js $TARGETPLATFORM && \ + dpkg --add-architecture arm && \ + apt update && \ + apt --yes --no-install-recommends install ./cloudflared.deb && \ + rm -rf /var/lib/apt/lists/* && \ + rm -f cloudflared.deb + diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index ba22bd24e..a6499ef9f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -5,9 +5,10 @@ version: '3.3' services: uptime-kuma: - image: louislam/uptime-kuma + image: louislam/uptime-kuma:1 container_name: uptime-kuma volumes: - ./uptime-kuma:/app/data ports: - 3001:3001 + restart: always diff --git a/ecosystem.config.js b/ecosystem.config.js index 5f4034007..bff3451f7 100644 --- a/ecosystem.config.js +++ b/ecosystem.config.js @@ -1,6 +1,6 @@ module.exports = { - apps: [{ - name: "uptime-kuma", - script: "./server/server.js", - }] -} + apps: [{ + name: "uptime-kuma", + script: "./server/server.js", + }] +}; diff --git a/extra/beta/update-version.js b/extra/beta/update-version.js new file mode 100644 index 000000000..4fddcfeb3 --- /dev/null +++ b/extra/beta/update-version.js @@ -0,0 +1,71 @@ +const pkg = require("../../package.json"); +const fs = require("fs"); +const childProcess = require("child_process"); +const util = require("../../src/util"); + +util.polyfill(); + +const oldVersion = pkg.version; +const version = process.env.VERSION; + +console.log("Beta Version: " + version); + +if (!version || !version.includes("-beta.")) { + console.error("invalid version, beta version only"); + process.exit(1); +} + +const exists = tagExists(version); + +if (! exists) { + // Process package.json + pkg.version = version; + fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); + commit(version); + tag(version); + +} else { + console.log("version tag exists, please delete the tag or use another tag"); + process.exit(1); +} + +function commit(version) { + let msg = "Update to " + version; + + let res = childProcess.spawnSync("git", ["commit", "-m", msg, "-a"]); + let stdout = res.stdout.toString().trim(); + console.log(stdout); + + if (stdout.includes("no changes added to commit")) { + throw new Error("commit error"); + } + + res = childProcess.spawnSync("git", ["push", "origin", "master"]); + console.log(res.stdout.toString().trim()); +} + +function tag(version) { + let res = childProcess.spawnSync("git", ["tag", version]); + console.log(res.stdout.toString().trim()); + + res = childProcess.spawnSync("git", ["push", "origin", version]); + console.log(res.stdout.toString().trim()); +} + +function tagExists(version) { + if (! version) { + throw new Error("invalid version"); + } + + let res = childProcess.spawnSync("git", ["tag", "-l", version]); + + return res.stdout.toString().trim() === version; +} + +function safeDelete(dir) { + if (fs.existsSync(dir)) { + fs.rmdirSync(dir, { + recursive: true, + }); + } +} diff --git a/extra/download-cloudflared.js b/extra/download-cloudflared.js new file mode 100644 index 000000000..41519b7ca --- /dev/null +++ b/extra/download-cloudflared.js @@ -0,0 +1,44 @@ +// + +const http = require("https"); // or 'https' for https:// URLs +const fs = require("fs"); + +const platform = process.argv[2]; + +if (!platform) { + console.error("No platform??"); + process.exit(1); +} + +let arch = null; + +if (platform === "linux/amd64") { + arch = "amd64"; +} else if (platform === "linux/arm64") { + arch = "arm64"; +} else if (platform === "linux/arm/v7") { + arch = "arm"; +} else { + console.error("Invalid platform?? " + platform); +} + +const file = fs.createWriteStream("cloudflared.deb"); +get("https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-" + arch + ".deb"); + +function get(url) { + http.get(url, function (res) { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + console.log("Redirect to " + res.headers.location); + get(res.headers.location); + } else if (res.statusCode >= 200 && res.statusCode < 300) { + res.pipe(file); + + res.on("end", function () { + console.log("Downloaded"); + }); + } else { + console.error(res.statusCode); + process.exit(1); + } + }); +} diff --git a/extra/download-dist.js b/extra/download-dist.js index dc64166c4..b04beec7a 100644 --- a/extra/download-dist.js +++ b/extra/download-dist.js @@ -4,6 +4,7 @@ const tar = require("tar"); const packageJSON = require("../package.json"); const fs = require("fs"); +const rmSync = require("./fs-rmSync.js"); const version = packageJSON.version; const filename = "dist.tar.gz"; @@ -11,6 +12,12 @@ const filename = "dist.tar.gz"; const url = `https://github.com/louislam/uptime-kuma/releases/download/${version}/${filename}`; download(url); +/** + * Downloads the latest version of the dist from a GitHub release. + * @param {string} url The URL to download from. + * + * Generated by Trelent + */ function download(url) { console.log(url); @@ -21,7 +28,7 @@ function download(url) { if (fs.existsSync("./dist")) { if (fs.existsSync("./dist-backup")) { - fs.rmdirSync("./dist-backup", { + rmSync("./dist-backup", { recursive: true }); } @@ -35,7 +42,7 @@ function download(url) { tarStream.on("close", () => { if (fs.existsSync("./dist-backup")) { - fs.rmdirSync("./dist-backup", { + rmSync("./dist-backup", { recursive: true }); } diff --git a/extra/env2arg.js b/extra/env2arg.js new file mode 100644 index 000000000..f89a91e43 --- /dev/null +++ b/extra/env2arg.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +const childProcess = require("child_process"); +let env = process.env; + +let cmd = process.argv[2]; +let args = process.argv.slice(3); +let replacedArgs = []; + +for (let arg of args) { + for (let key in env) { + arg = arg.replaceAll(`$${key}`, env[key]); + } + replacedArgs.push(arg); +} + +let child = childProcess.spawn(cmd, replacedArgs); +child.stdout.pipe(process.stdout); +child.stderr.pipe(process.stderr); diff --git a/extra/fs-rmSync.js b/extra/fs-rmSync.js new file mode 100644 index 000000000..aa45b6dc3 --- /dev/null +++ b/extra/fs-rmSync.js @@ -0,0 +1,23 @@ +const fs = require("fs"); +/** + * Detect if `fs.rmSync` is available + * to avoid the runtime deprecation warning triggered for using `fs.rmdirSync` with `{ recursive: true }` in Node.js v16, + * or the `recursive` property removing completely in the future Node.js version. + * See the link below. + * + * @todo Once we drop the support for Node.js v14 (or at least versions before v14.14.0), we can safely replace this function with `fs.rmSync`, since `fs.rmSync` was add in Node.js v14.14.0 and currently we supports all the Node.js v14 versions that include the versions before the v14.14.0, and this function have almost the same signature with `fs.rmSync`. + * @link https://nodejs.org/docs/latest-v16.x/api/deprecations.html#dep0147-fsrmdirpath--recursive-true- the deprecation infomation of `fs.rmdirSync` + * @link https://nodejs.org/docs/latest-v16.x/api/fs.html#fsrmsyncpath-options the document of `fs.rmSync` + * @param {fs.PathLike} path Valid types for path values in "fs". + * @param {fs.RmDirOptions} [options] options for `fs.rmdirSync`, if `fs.rmSync` is available and property `recursive` is true, it will automatically have property `force` with value `true`. + */ +const rmSync = (path, options) => { + if (typeof fs.rmSync === "function") { + if (options.recursive) { + options.force = true; + } + return fs.rmSync(path, options); + } + return fs.rmdirSync(path, options); +}; +module.exports = rmSync; diff --git a/extra/install.batsh b/extra/install.batsh index bca0b095f..65e95cd0e 100644 --- a/extra/install.batsh +++ b/extra/install.batsh @@ -189,7 +189,7 @@ if (type == "local") { bash("check=$(pm2 --version)"); if (check == "") { println("Installing PM2"); - bash("npm install pm2 -g"); + bash("npm install pm2 -g && pm2 install pm2-logrotate"); bash("pm2 startup"); } diff --git a/extra/mark-as-nightly.js b/extra/mark-as-nightly.js index 0316596bf..a55fd98f7 100644 --- a/extra/mark-as-nightly.js +++ b/extra/mark-as-nightly.js @@ -4,21 +4,21 @@ const util = require("../src/util"); util.polyfill(); -const oldVersion = pkg.version -const newVersion = oldVersion + "-nightly" +const oldVersion = pkg.version; +const newVersion = oldVersion + "-nightly"; -console.log("Old Version: " + oldVersion) -console.log("New Version: " + newVersion) +console.log("Old Version: " + oldVersion); +console.log("New Version: " + newVersion); if (newVersion) { // Process package.json - pkg.version = newVersion - pkg.scripts.setup = pkg.scripts.setup.replaceAll(oldVersion, newVersion) - pkg.scripts["build-docker"] = pkg.scripts["build-docker"].replaceAll(oldVersion, newVersion) - fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n") + pkg.version = newVersion; + pkg.scripts.setup = pkg.scripts.setup.replaceAll(oldVersion, newVersion); + pkg.scripts["build-docker"] = pkg.scripts["build-docker"].replaceAll(oldVersion, newVersion); + fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); // Process README.md if (fs.existsSync("README.md")) { - fs.writeFileSync("README.md", fs.readFileSync("README.md", "utf8").replaceAll(oldVersion, newVersion)) + fs.writeFileSync("README.md", fs.readFileSync("README.md", "utf8").replaceAll(oldVersion, newVersion)); } } diff --git a/extra/press-any-key.js b/extra/press-any-key.js new file mode 100644 index 000000000..42fc363cd --- /dev/null +++ b/extra/press-any-key.js @@ -0,0 +1,6 @@ +console.log("Git Push and Publish the release note on github, then press any key to continue"); + +process.stdin.setRawMode(true); +process.stdin.resume(); +process.stdin.on("data", process.exit.bind(process, 0)); + diff --git a/extra/reset-password.js b/extra/reset-password.js index 1b48dffd7..160ef0a3e 100644 --- a/extra/reset-password.js +++ b/extra/reset-password.js @@ -1,7 +1,5 @@ console.log("== Uptime Kuma Reset Password Tool =="); -console.log("Loading the database"); - const Database = require("../server/database"); const { R } = require("redbean-node"); const readline = require("readline"); @@ -13,8 +11,9 @@ const rl = readline.createInterface({ }); const main = async () => { + console.log("Connecting the database"); Database.init(args); - await Database.connect(); + await Database.connect(false, false, true); try { // No need to actually reset the password for testing, just make sure no connection problem. It is ok for now. diff --git a/extra/simple-dns-server.js b/extra/simple-dns-server.js index 5e5745f04..376dbdd04 100644 --- a/extra/simple-dns-server.js +++ b/extra/simple-dns-server.js @@ -26,7 +26,7 @@ server.on("request", (request, send, rinfo) => { ttl: 300, address: "1.2.3.4" }); - } if (question.type === Packet.TYPE.AAAA) { + } else if (question.type === Packet.TYPE.AAAA) { response.answers.push({ name: question.name, type: question.type, diff --git a/extra/update-language-files/index.js b/extra/update-language-files/index.js index 7ba30cc05..e449fe347 100644 --- a/extra/update-language-files/index.js +++ b/extra/update-language-files/index.js @@ -3,6 +3,7 @@ import fs from "fs"; import path from "path"; import util from "util"; +import rmSync from "../fs-rmSync.js"; // https://stackoverflow.com/questions/13786160/copy-folder-recursively-in-node-js /** @@ -30,7 +31,7 @@ console.log("Arguments:", process.argv); const baseLangCode = process.argv[2] || "en"; console.log("Base Lang: " + baseLangCode); if (fs.existsSync("./languages")) { - fs.rmdirSync("./languages", { recursive: true }); + rmSync("./languages", { recursive: true }); } copyRecursiveSync("../../src/languages", "./languages"); @@ -40,7 +41,7 @@ const files = fs.readdirSync("./languages"); console.log("Files:", files); for (const file of files) { - if (!file.endsWith(".js")) { + if (! file.endsWith(".js")) { console.log("Skipping " + file); continue; } @@ -82,5 +83,5 @@ for (const file of files) { fs.writeFileSync(`../../src/languages/${file}`, code); } -fs.rmdirSync("./languages", { recursive: true }); +rmSync("./languages", { recursive: true }); console.log("Done. Fixing formatting by ESLint..."); diff --git a/extra/update-version.js b/extra/update-version.js index 2e3b42da8..d72fee68f 100644 --- a/extra/update-version.js +++ b/extra/update-version.js @@ -1,14 +1,13 @@ const pkg = require("../package.json"); const fs = require("fs"); +const rmSync = require("./fs-rmSync.js"); const child_process = require("child_process"); const util = require("../src/util"); util.polyfill(); -const oldVersion = pkg.version; -const newVersion = process.argv[2]; +const newVersion = process.env.VERSION; -console.log("Old Version: " + oldVersion); console.log("New Version: " + newVersion); if (! newVersion) { @@ -22,23 +21,26 @@ if (! exists) { // Process package.json pkg.version = newVersion; - pkg.scripts.setup = pkg.scripts.setup.replaceAll(oldVersion, newVersion); - pkg.scripts["build-docker"] = pkg.scripts["build-docker"].replaceAll(oldVersion, newVersion); - pkg.scripts["build-docker-alpine"] = pkg.scripts["build-docker-alpine"].replaceAll(oldVersion, newVersion); - pkg.scripts["build-docker-debian"] = pkg.scripts["build-docker-debian"].replaceAll(oldVersion, newVersion); + + // Replace the version: https://regex101.com/r/hmj2Bc/1 + pkg.scripts.setup = pkg.scripts.setup.replace(/(git checkout )([^\s]+)/, `$1${newVersion}`); fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); commit(newVersion); tag(newVersion); - updateWiki(oldVersion, newVersion); - } else { console.log("version exists"); } +/** + * Updates the version number in package.json and commits it to git. + * @param {string} version - The new version number + * + * Generated by Trelent + */ function commit(version) { - let msg = "update to " + version; + let msg = "Update to " + version; let res = child_process.spawnSync("git", ["commit", "-m", msg, "-a"]); let stdout = res.stdout.toString().trim(); @@ -54,6 +56,12 @@ function tag(version) { console.log(res.stdout.toString().trim()); } +/** + * Checks if a given version is already tagged in the git repository. + * @param {string} version - The version to check for. + * + * Generated by Trelent + */ function tagExists(version) { if (! version) { throw new Error("invalid version"); @@ -63,38 +71,3 @@ function tagExists(version) { return res.stdout.toString().trim() === version; } - -function updateWiki(oldVersion, newVersion) { - const wikiDir = "./tmp/wiki"; - const howToUpdateFilename = "./tmp/wiki/🆙-How-to-Update.md"; - - safeDelete(wikiDir); - - child_process.spawnSync("git", ["clone", "https://github.com/louislam/uptime-kuma.wiki.git", wikiDir]); - let content = fs.readFileSync(howToUpdateFilename).toString(); - content = content.replaceAll(`git checkout ${oldVersion}`, `git checkout ${newVersion}`); - fs.writeFileSync(howToUpdateFilename, content); - - child_process.spawnSync("git", ["add", "-A"], { - cwd: wikiDir, - }); - - child_process.spawnSync("git", ["commit", "-m", `Update to ${newVersion} from ${oldVersion}`], { - cwd: wikiDir, - }); - - console.log("Pushing to Github"); - child_process.spawnSync("git", ["push"], { - cwd: wikiDir, - }); - - safeDelete(wikiDir); -} - -function safeDelete(dir) { - if (fs.existsSync(dir)) { - fs.rmdirSync(dir, { - recursive: true, - }); - } -} diff --git a/extra/update-wiki-version.js b/extra/update-wiki-version.js new file mode 100644 index 000000000..10631c332 --- /dev/null +++ b/extra/update-wiki-version.js @@ -0,0 +1,48 @@ +const child_process = require("child_process"); +const fs = require("fs"); + +const newVersion = process.env.VERSION; + +if (!newVersion) { + console.log("Missing version"); + process.exit(1); +} + +updateWiki(newVersion); + +function updateWiki(newVersion) { + const wikiDir = "./tmp/wiki"; + const howToUpdateFilename = "./tmp/wiki/🆙-How-to-Update.md"; + + safeDelete(wikiDir); + + child_process.spawnSync("git", ["clone", "https://github.com/louislam/uptime-kuma.wiki.git", wikiDir]); + let content = fs.readFileSync(howToUpdateFilename).toString(); + + // Replace the version: https://regex101.com/r/hmj2Bc/1 + content = content.replace(/(git checkout )([^\s]+)/, `$1${newVersion}`); + fs.writeFileSync(howToUpdateFilename, content); + + child_process.spawnSync("git", ["add", "-A"], { + cwd: wikiDir, + }); + + child_process.spawnSync("git", ["commit", "-m", `Update to ${newVersion}`], { + cwd: wikiDir, + }); + + console.log("Pushing to Github"); + child_process.spawnSync("git", ["push"], { + cwd: wikiDir, + }); + + safeDelete(wikiDir); +} + +function safeDelete(dir) { + if (fs.existsSync(dir)) { + fs.rmdirSync(dir, { + recursive: true, + }); + } +} diff --git a/install.sh b/install.sh index 37d675317..27b30688f 100644 --- a/install.sh +++ b/install.sh @@ -159,7 +159,7 @@ fi check=$(pm2 --version) if [ "$check" == "" ]; then "echo" "-e" "Installing PM2" - npm install pm2 -g + npm install pm2 -g && pm2 install pm2-logrotate pm2 startup fi mkdir -p $installPath diff --git a/package.json b/package.json index 64589f951..aec270dcb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "uptime-kuma", - "version": "1.11.3", + "version": "1.14.0", "license": "MIT", "repository": { "type": "git", @@ -20,7 +20,7 @@ "start-server": "node server/server.js", "start-server-dev": "cross-env NODE_ENV=development node server/server.js", "build": "vite build --config ./config/vite.config.js", - "test": "node test/prepare-test-server.js && node server/server.js --port=3002 --data-dir=./data/test/ --test", + "test": "npm run lint && node test/prepare-test-server.js && node server/server.js --port=3002 --data-dir=./data/test/ --test", "test-with-build": "npm run build && npm test", "jest": "node test/prepare-jest.js && npm run jest-frontend && npm run jest-backend", "jest-frontend": "cross-env TEST_FRONTEND=1 jest --config=./config/jest-frontend.config.js", @@ -30,15 +30,14 @@ "build-docker": "npm run build && npm run build-docker-debian && npm run build-docker-alpine", "build-docker-alpine-base": "docker buildx build -f docker/alpine-base.dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:base-alpine . --push", "build-docker-debian-base": "docker buildx build -f docker/debian-base.dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:base-debian . --push", - "build-docker-alpine": "docker buildx build -f docker/dockerfile-alpine --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:alpine -t louislam/uptime-kuma:1-alpine -t louislam/uptime-kuma:1.11.3-alpine --target release . --push", - "build-docker-debian": "docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma -t louislam/uptime-kuma:1 -t louislam/uptime-kuma:1.11.3 -t louislam/uptime-kuma:debian -t louislam/uptime-kuma:1-debian -t louislam/uptime-kuma:1.11.3-debian --target release . --push", + "build-docker-alpine": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile-alpine --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:alpine -t louislam/uptime-kuma:1-alpine -t louislam/uptime-kuma:$VERSION-alpine --target release . --push", + "build-docker-debian": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma -t louislam/uptime-kuma:1 -t louislam/uptime-kuma:$VERSION -t louislam/uptime-kuma:debian -t louislam/uptime-kuma:1-debian -t louislam/uptime-kuma:$VERSION-debian --target release . --push", "build-docker-nightly": "npm run build && docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:nightly --target nightly . --push", "build-docker-nightly-alpine": "docker buildx build -f docker/dockerfile-alpine --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:nightly-alpine --target nightly . --push", "build-docker-nightly-amd64": "docker buildx build -f docker/dockerfile --platform linux/amd64 -t louislam/uptime-kuma:nightly-amd64 --target nightly . --push --progress plain", "upload-artifacts": "docker buildx build -f docker/dockerfile --platform linux/amd64 -t louislam/uptime-kuma:upload-artifact --build-arg VERSION --build-arg GITHUB_TOKEN --target upload-artifact . --progress plain", - "setup": "git checkout 1.11.3 && npm ci --production && npm run download-dist", + "setup": "git checkout 1.14.0 && npm ci --production && npm run download-dist", "download-dist": "node extra/download-dist.js", - "update-version": "node extra/update-version.js", "mark-as-nightly": "node extra/mark-as-nightly.js", "reset-password": "node extra/reset-password.js", "remove-2fa": "node extra/remove-2fa.js", @@ -51,7 +50,10 @@ "simple-dns-server": "node extra/simple-dns-server.js", "update-language-files-with-base-lang": "cd extra/update-language-files && node index.js %npm_config_base_lang% && eslint ../../src/languages/**.js --fix", "update-language-files": "cd extra/update-language-files && node index.js && eslint ../../src/languages/**.js --fix", - "ncu-patch": "ncu -u -t patch" + "ncu-patch": "npm-check-updates -u -t patch", + "release-final": "node extra/update-version.js && npm run build-docker && node ./extra/press-any-key.js && npm run upload-artifacts && node ./extra/update-wiki-version.js", + "release-beta": "node extra/beta/update-version.js && npm run build && node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:$VERSION -t louislam/uptime-kuma:beta . --target release --push && node ./extra/press-any-key.js && npm run upload-artifacts", + "git-remove-tag": "git tag -d" }, "dependencies": { "@fortawesome/fontawesome-svg-core": "~1.2.36", @@ -61,62 +63,67 @@ "@louislam/sqlite3": "~6.0.1", "@popperjs/core": "~2.10.2", "args-parser": "~1.3.0", - "axios": "~0.21.4", + "axios": "~0.26.1", "bcryptjs": "~2.4.3", "bootstrap": "5.1.3", - "bree": "~7.1.0", + "bree": "~7.1.5", "chardet": "^1.3.0", - "chart.js": "~3.6.0", + "chart.js": "~3.6.2", "chartjs-adapter-dayjs": "~1.0.0", - "check-password-strength": "^2.0.3", + "check-password-strength": "^2.0.5", "command-exists": "~1.2.9", "compare-versions": "~3.6.0", - "dayjs": "~1.10.7", - "express": "~4.17.1", - "express-basic-auth": "~1.2.0", + "dayjs": "~1.10.8", + "express": "~4.17.3", + "express-basic-auth": "~1.2.1", + "favico.js": "^0.3.10", "form-data": "~4.0.0", - "http-graceful-shutdown": "~3.1.5", + "http-graceful-shutdown": "~3.1.7", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", "iconv-lite": "^0.6.3", "jsonwebtoken": "~8.5.1", "jwt-decode": "^3.1.2", "limiter": "^2.1.0", "mqtt": "^4.2.8", + "node-cloudflared-tunnel": "~1.0.9", "nodemailer": "~6.6.5", "notp": "~2.0.3", "password-hash": "~1.2.2", "postcss-rtlcss": "~3.4.1", - "postcss-scss": "~4.0.2", + "postcss-scss": "~4.0.3", "prom-client": "~13.2.0", - "prometheus-api-metrics": "~3.2.0", + "prometheus-api-metrics": "~3.2.1", "qrcode": "~1.5.0", "redbean-node": "0.1.3", - "socket.io": "~4.2.0", - "socket.io-client": "~4.2.0", + "socket.io": "~4.4.1", + "socket.io-client": "~4.4.1", + "socks-proxy-agent": "^6.1.1", "tar": "^6.1.11", "tcp-ping": "~0.1.1", "thirty-two": "~1.0.2", "timezones-list": "~3.0.1", "v-pagination-3": "~0.1.7", "vue": "next", - "vue-chart-3": "~0.5.11", + "vue-chart-3": "3.0.9", "vue-confirm-dialog": "~1.0.2", "vue-contenteditable": "~3.0.4", "vue-i18n": "~9.1.9", "vue-image-crop-upload": "~3.0.3", "vue-multiselect": "~3.0.0-alpha.2", "vue-qrcode": "~1.0.0", - "vue-router": "~4.0.12", + "vue-router": "~4.0.14", "vue-toastification": "~2.0.0-rc.5", "vuedraggable": "~4.1.0" }, "devDependencies": { - "@actions/github": "~5.0.0", + "@actions/github": "~5.0.1", "@babel/eslint-parser": "~7.15.8", "@babel/preset-env": "^7.15.8", - "@types/bootstrap": "~5.1.6", - "@vitejs/plugin-legacy": "~1.6.3", + "@types/bootstrap": "~5.1.9", + "@vitejs/plugin-legacy": "~1.6.4", "@vitejs/plugin-vue": "~1.9.4", - "@vue/compiler-sfc": "~3.2.22", + "@vue/compiler-sfc": "~3.2.31", "babel-plugin-rewire": "~1.2.0", "core-js": "~3.18.3", "cross-env": "~7.0.3", @@ -124,8 +131,10 @@ "eslint": "~7.32.0", "eslint-plugin-vue": "~7.18.0", "jest": "~27.2.5", - "jest-puppeteer": "~6.0.0", - "puppeteer": "~10.4.0", + "jest-puppeteer": "~6.0.3", + "npm-check-updates": "^12.5.5", + "postcss-html": "^1.3.1", + "puppeteer": "~13.1.3", "sass": "~1.42.1", "stylelint": "~14.2.0", "stylelint-config-standard": "~24.0.0", diff --git a/server/auth.js b/server/auth.js index c476ea1e3..d9412ae37 100644 --- a/server/auth.js +++ b/server/auth.js @@ -2,7 +2,6 @@ const basicAuth = require("express-basic-auth"); const passwordHash = require("./password-hash"); const { R } = require("redbean-node"); const { setting } = require("./util-server"); -const { debug } = require("../src/util"); const { loginRateLimiter } = require("./rate-limiter"); /** @@ -12,6 +11,10 @@ const { loginRateLimiter } = require("./rate-limiter"); * @returns {Promise} */ exports.login = async function (username, password) { + if (typeof username !== "string" || typeof password !== "string") { + return null; + } + let user = await R.findOne("user", " username = ? AND active = 1 ", [ username, ]); @@ -30,32 +33,42 @@ exports.login = async function (username, password) { return null; }; +/** + * A function that checks if a user is logged in. + * @param {string} username The username of the user to check for. + * @param {function} callback The callback to call when done, with an error and result parameter. + * + * Generated by Trelent + */ function myAuthorizer(username, password, callback) { - setting("disableAuth").then((result) => { - if (result) { - callback(null, true); - } else { - // Login Rate Limit - loginRateLimiter.pass(null, 0).then((pass) => { - if (pass) { - exports.login(username, password).then((user) => { - callback(null, user != null); + // Login Rate Limit + loginRateLimiter.pass(null, 0).then((pass) => { + if (pass) { + exports.login(username, password).then((user) => { + callback(null, user != null); - if (user == null) { - loginRateLimiter.removeTokens(1); - } - }); - } else { - callback(null, false); + if (user == null) { + loginRateLimiter.removeTokens(1); } }); - + } else { + callback(null, false); } }); } -exports.basicAuth = basicAuth({ - authorizer: myAuthorizer, - authorizeAsync: true, - challenge: true, -}); +exports.basicAuth = async function (req, res, next) { + const middleware = basicAuth({ + authorizer: myAuthorizer, + authorizeAsync: true, + challenge: true, + }); + + const disabledAuth = await setting("disableAuth"); + + if (!disabledAuth) { + middleware(req, res, next); + } else { + next(); + } +}; diff --git a/server/check-version.js b/server/check-version.js index a3465ddf0..c9d87c96f 100644 --- a/server/check-version.js +++ b/server/check-version.js @@ -1,5 +1,6 @@ -const { setSetting } = require("./util-server"); +const { setSetting, setting } = require("./util-server"); const axios = require("axios"); +const compareVersions = require("compare-versions"); exports.version = require("../package.json").version; exports.latestVersion = null; @@ -16,6 +17,19 @@ exports.startInterval = () => { res.data.slow = "1000.0.0"; } + if (await setting("checkUpdate") === false) { + return; + } + + let checkBeta = await setting("checkBeta"); + + if (checkBeta && res.data.beta) { + if (compareVersions.compare(res.data.beta, res.data.beta, ">")) { + exports.latestVersion = res.data.beta; + return; + } + } + if (res.data.slow) { exports.latestVersion = res.data.slow; } diff --git a/server/client.js b/server/client.js index c7b3bc162..3a2d6df27 100644 --- a/server/client.js +++ b/server/client.js @@ -7,6 +7,12 @@ const { io } = require("./server"); const { setting } = require("./util-server"); const checkVersion = require("./check-version"); +/** + * Send a list of notifications to the user. + * @param {Socket} socket The socket object that is connected to the client. + * + * Generated by Trelent + */ async function sendNotificationList(socket) { const timeLogger = new TimeLogger(); @@ -83,6 +89,29 @@ async function sendImportantHeartbeatList(socket, monitorID, toUser = false, ove } +/** + * Delivers proxy list + * + * @param socket + * @return {Promise} + */ +async function sendProxyList(socket) { + const timeLogger = new TimeLogger(); + + const list = await R.find("proxy", " user_id = ? ", [socket.userID]); + io.to(socket.userID).emit("proxyList", list.map(bean => bean.export())); + + timeLogger.print("Send Proxy List"); + + return list; +} + +/** + * Emits the version information to the client. + * @param {Socket} socket The socket object that is connected to the client. + * + * Generated by Trelent + */ async function sendInfo(socket) { socket.emit("info", { version: checkVersion.version, @@ -95,6 +124,6 @@ module.exports = { sendNotificationList, sendImportantHeartbeatList, sendHeartbeatList, - sendInfo + sendProxyList, + sendInfo, }; - diff --git a/server/database.js b/server/database.js index a420d3937..961cab820 100644 --- a/server/database.js +++ b/server/database.js @@ -1,7 +1,7 @@ const fs = require("fs"); const { R } = require("redbean-node"); const { setSetting, setting } = require("./util-server"); -const { debug, sleep } = require("../src/util"); +const { log, sleep } = require("../src/util"); const dayjs = require("dayjs"); const knex = require("knex"); @@ -53,6 +53,9 @@ class Database { "patch-2fa-invalidate-used-token.sql": true, "patch-notification_sent_history.sql": true, "patch-monitor-basic-auth.sql": true, + "patch-status-page.sql": true, + "patch-proxy.sql": true, + "patch-monitor-expiry-notification.sql": true, "patch-added-mqtt-monitor.sql": true, } @@ -78,10 +81,10 @@ class Database { fs.mkdirSync(Database.uploadDir, { recursive: true }); } - console.log(`Data Dir: ${Database.dataDir}`); + log.info("db", `Data Dir: ${Database.dataDir}`); } - static async connect(testMode = false) { + static async connect(testMode = false, autoloadModels = true, noLog = false) { const acquireConnectionTimeout = 120 * 1000; const Dialect = require("knex/lib/dialects/sqlite3/index.js"); @@ -111,7 +114,10 @@ class Database { // Auto map the model to a bean object R.freeze(true); - await R.autoloadModels("./server/model"); + + if (autoloadModels) { + await R.autoloadModels("./server/model"); + } await R.exec("PRAGMA foreign_keys = ON"); if (testMode) { @@ -124,10 +130,17 @@ class Database { await R.exec("PRAGMA cache_size = -12000"); await R.exec("PRAGMA auto_vacuum = FULL"); - console.log("SQLite config:"); - console.log(await R.getAll("PRAGMA journal_mode")); - console.log(await R.getAll("PRAGMA cache_size")); - console.log("SQLite Version: " + await R.getCell("SELECT sqlite_version()")); + // This ensures that an operating system crash or power failure will not corrupt the database. + // FULL synchronous is very safe, but it is also slower. + // Read more: https://sqlite.org/pragma.html#pragma_synchronous + await R.exec("PRAGMA synchronous = FULL"); + + if (!noLog) { + log.info("db", "SQLite config:"); + log.info("db", await R.getAll("PRAGMA journal_mode")); + log.info("db", await R.getAll("PRAGMA cache_size")); + log.info("db", "SQLite Version: " + await R.getCell("SELECT sqlite_version()")); + } } static async patch() { @@ -137,15 +150,15 @@ class Database { version = 0; } - console.info("Your database version: " + version); - console.info("Latest database version: " + this.latestVersion); + log.info("db", "Your database version: " + version); + log.info("db", "Latest database version: " + this.latestVersion); if (version === this.latestVersion) { - console.info("Database patch not needed"); + log.info("db", "Database patch not needed"); } else if (version > this.latestVersion) { - console.info("Warning: Database version is newer than expected"); + log.info("db", "Warning: Database version is newer than expected"); } else { - console.info("Database patch is needed"); + log.info("db", "Database patch is needed"); this.backup(version); @@ -153,17 +166,17 @@ class Database { try { for (let i = version + 1; i <= this.latestVersion; i++) { const sqlFile = `./db/patch${i}.sql`; - console.info(`Patching ${sqlFile}`); + log.info("db", `Patching ${sqlFile}`); await Database.importSQLFile(sqlFile); - console.info(`Patched ${sqlFile}`); + log.info("db", `Patched ${sqlFile}`); await setSetting("database_version", i); } } catch (ex) { await Database.close(); - console.error(ex); - console.error("Start Uptime-Kuma failed due to issue patching the database"); - console.error("Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); + log.error("db", ex); + log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); + log.error("db", "Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); this.restore(); process.exit(1); @@ -171,6 +184,7 @@ class Database { } await this.patch2(); + await this.migrateNewStatusPage(); } /** @@ -178,15 +192,15 @@ class Database { * @returns {Promise} */ static async patch2() { - console.log("Database Patch 2.0 Process"); + log.info("db", "Database Patch 2.0 Process"); let databasePatchedFiles = await setting("databasePatchedFiles"); if (! databasePatchedFiles) { databasePatchedFiles = {}; } - debug("Patched files:"); - debug(databasePatchedFiles); + log.debug("db", "Patched files:"); + log.debug("db", databasePatchedFiles); try { for (let sqlFilename in this.patchList) { @@ -194,15 +208,15 @@ class Database { } if (this.patched) { - console.log("Database Patched Successfully"); + log.info("db", "Database Patched Successfully"); } } catch (ex) { await Database.close(); - console.error(ex); - console.error("Start Uptime-Kuma failed due to issue patching the database"); - console.error("Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); + log.error("db", ex); + log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); + log.error("db", "Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); this.restore(); @@ -212,6 +226,74 @@ class Database { await setSetting("databasePatchedFiles", databasePatchedFiles); } + /** + * Migrate status page value in setting to "status_page" table + * @returns {Promise} + */ + static async migrateNewStatusPage() { + + // Fix 1.13.0 empty slug bug + await R.exec("UPDATE status_page SET slug = 'empty-slug-recover' WHERE TRIM(slug) = ''"); + + let title = await setting("title"); + + if (title) { + console.log("Migrating Status Page"); + + let statusPageCheck = await R.findOne("status_page", " slug = 'default' "); + + if (statusPageCheck !== null) { + console.log("Migrating Status Page - Skip, default slug record is already existing"); + return; + } + + let statusPage = R.dispense("status_page"); + statusPage.slug = "default"; + statusPage.title = title; + statusPage.description = await setting("description"); + statusPage.icon = await setting("icon"); + statusPage.theme = await setting("statusPageTheme"); + statusPage.published = !!await setting("statusPagePublished"); + statusPage.search_engine_index = !!await setting("searchEngineIndex"); + statusPage.show_tags = !!await setting("statusPageTags"); + statusPage.password = null; + + if (!statusPage.title) { + statusPage.title = "My Status Page"; + } + + if (!statusPage.icon) { + statusPage.icon = ""; + } + + if (!statusPage.theme) { + statusPage.theme = "light"; + } + + let id = await R.store(statusPage); + + await R.exec("UPDATE incident SET status_page_id = ? WHERE status_page_id IS NULL", [ + id + ]); + + await R.exec("UPDATE [group] SET status_page_id = ? WHERE status_page_id IS NULL", [ + id + ]); + + await R.exec("DELETE FROM setting WHERE type = 'statusPage'"); + + // Migrate Entry Page if it is status page + let entryPage = await setting("entryPage"); + + if (entryPage === "statusPage") { + await setSetting("entryPage", "statusPage-default", "general"); + } + + console.log("Migrating Status Page - Done"); + } + + } + /** * Used it patch2() only * @param sqlFilename @@ -221,16 +303,16 @@ class Database { let value = this.patchList[sqlFilename]; if (! value) { - console.log(sqlFilename + " skip"); + log.info("db", sqlFilename + " skip"); return; } // Check if patched if (! databasePatchedFiles[sqlFilename]) { - console.log(sqlFilename + " is not patched"); + log.info("db", sqlFilename + " is not patched"); if (value.parents) { - console.log(sqlFilename + " need parents"); + log.info("db", sqlFilename + " need parents"); for (let parentSQLFilename of value.parents) { await this.patch2Recursion(parentSQLFilename, databasePatchedFiles); } @@ -238,14 +320,14 @@ class Database { this.backup(dayjs().format("YYYYMMDDHHmmss")); - console.log(sqlFilename + " is patching"); + log.info("db", sqlFilename + " is patching"); this.patched = true; await this.importSQLFile("./db/" + sqlFilename); databasePatchedFiles[sqlFilename] = true; - console.log(sqlFilename + " was patched successfully"); + log.info("db", sqlFilename + " was patched successfully"); } else { - debug(sqlFilename + " is already patched, skip"); + log.debug("db", sqlFilename + " is already patched, skip"); } } @@ -297,7 +379,7 @@ class Database { }; process.addListener("unhandledRejection", listener); - console.log("Closing the database"); + log.info("db", "Closing the database"); while (true) { Database.noReject = true; @@ -307,10 +389,10 @@ class Database { if (Database.noReject) { break; } else { - console.log("Waiting to close the database"); + log.info("db", "Waiting to close the database"); } } - console.log("SQLite closed"); + log.info("db", "SQLite closed"); process.removeListener("unhandledRejection", listener); } @@ -322,7 +404,7 @@ class Database { */ static backup(version) { if (! this.backupPath) { - console.info("Backing up the database"); + log.info("db", "Backing up the database"); this.backupPath = this.dataDir + "kuma.db.bak" + version; fs.copyFileSync(Database.path, this.backupPath); @@ -345,7 +427,7 @@ class Database { */ static restore() { if (this.backupPath) { - console.error("Patching the database failed!!! Restoring the backup"); + log.error("db", "Patching the database failed!!! Restoring the backup"); const shmPath = Database.path + "-shm"; const walPath = Database.path + "-wal"; @@ -364,7 +446,7 @@ class Database { fs.unlinkSync(walPath); } } catch (e) { - console.log("Restore failed; you may need to restore the backup manually"); + log.error("db", "Restore failed; you may need to restore the backup manually"); process.exit(1); } @@ -380,14 +462,14 @@ class Database { } } else { - console.log("Nothing to restore"); + log.info("db", "Nothing to restore"); } } static getSize() { - debug("Database.getSize()"); + log.debug("db", "Database.getSize()"); let stats = fs.statSync(Database.path); - debug(stats); + log.debug("db", stats); return stats.size; } diff --git a/server/image-data-uri.js b/server/image-data-uri.js index 3ccaab7d5..fbff93408 100644 --- a/server/image-data-uri.js +++ b/server/image-data-uri.js @@ -3,12 +3,19 @@ Modified with 0 dependencies */ let fs = require("fs"); +const { log } = require("../src/util"); let ImageDataURI = (() => { + /** + * @param {string} dataURI - A string that is a valid Data URI. + * @returns {?Object} An object with properties "imageType" and "dataBase64". The former is the image type, e.g., "png", and the latter is a base64 encoded string of the image's binary data. If it fails to parse, returns null instead of an object. + * + * Generated by Trelent + */ function decode(dataURI) { if (!/data:image\//.test(dataURI)) { - console.log("ImageDataURI :: Error :: It seems that it is not an Image Data URI. Couldn't match \"data:image/\""); + log.error("image-data-uri", "It seems that it is not an Image Data URI. Couldn't match \"data:image/\""); return null; } @@ -20,9 +27,16 @@ let ImageDataURI = (() => { }; } + /** + * @param {Buffer} data - The image data to be encoded. + * @param {String} mediaType - The type of the image, e.g., "image/png". + * @returns {String|null} A string representing the base64-encoded version of the given Buffer object or null if an error occurred. + * + * Generated by Trelent + */ function encode(data, mediaType) { if (!data || !mediaType) { - console.log("ImageDataURI :: Error :: Missing some of the required params: data, mediaType "); + log.error("image-data-uri", "Missing some of the required params: data, mediaType"); return null; } @@ -33,6 +47,13 @@ let ImageDataURI = (() => { return dataImgBase64; } + /** + * Converts a data URI to a file path. + * @param {string} dataURI The Data URI of the image. + * @param {string} [filePath] The path where the image will be saved, defaults to "./". + * + * Generated by Trelent + */ function outputFile(dataURI, filePath) { filePath = filePath || "./"; return new Promise((resolve, reject) => { diff --git a/server/jobs.js b/server/jobs.js index 0469d5cab..739e867d4 100644 --- a/server/jobs.js +++ b/server/jobs.js @@ -1,7 +1,8 @@ const path = require("path"); const Bree = require("bree"); const { SHARE_ENV } = require("worker_threads"); - +const { log } = require("../src/util"); +let bree; const jobs = [ { name: "clear-old-data", @@ -10,7 +11,7 @@ const jobs = [ ]; const initBackgroundJobs = function (args) { - const bree = new Bree({ + bree = new Bree({ root: path.resolve("server", "jobs"), jobs, worker: { @@ -18,7 +19,7 @@ const initBackgroundJobs = function (args) { workerData: args, }, workerMessageHandler: (message) => { - console.log("[Background Job]:", message); + log.info("jobs", message); } }); @@ -26,6 +27,13 @@ const initBackgroundJobs = function (args) { return bree; }; -module.exports = { - initBackgroundJobs +const stopBackgroundJobs = function () { + if (bree) { + bree.stop(); + } +}; + +module.exports = { + initBackgroundJobs, + stopBackgroundJobs }; diff --git a/server/logger.js b/server/logger.js new file mode 100644 index 000000000..e69de29bb diff --git a/server/model/group.js b/server/model/group.js index 567f3865b..3e1f2d449 100644 --- a/server/model/group.js +++ b/server/model/group.js @@ -3,12 +3,12 @@ const { R } = require("redbean-node"); class Group extends BeanModel { - async toPublicJSON() { + async toPublicJSON(showTags = false) { let monitorBeanList = await this.getMonitorList(); let monitorList = []; for (let bean of monitorBeanList) { - monitorList.push(await bean.toPublicJSON()); + monitorList.push(await bean.toPublicJSON(showTags)); } return { diff --git a/server/model/monitor.js b/server/model/monitor.js index 6f1631bb8..c31285725 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -6,11 +6,12 @@ dayjs.extend(utc); dayjs.extend(timezone); const axios = require("axios"); const { Prometheus } = require("../prometheus"); -const { debug, UP, DOWN, PENDING, flipStatus, TimeLogger } = require("../../src/util"); +const { log, UP, DOWN, PENDING, flipStatus, TimeLogger } = require("../../src/util"); const { tcping, ping, dnsResolve, checkCertificate, checkStatusCode, getTotalClientInRoom, setting, errorLog, mqttAsync } = require("../util-server"); const { R } = require("redbean-node"); const { BeanModel } = require("redbean-node/dist/bean-model"); const { Notification } = require("../notification"); +const { Proxy } = require("../proxy"); const { demoMode } = require("../config"); const version = require("../../package.json").version; const apicache = require("../modules/apicache"); @@ -24,18 +25,22 @@ const apicache = require("../modules/apicache"); class Monitor extends BeanModel { /** - * Return a object that ready to parse to JSON for public + * Return an object that ready to parse to JSON for public * Only show necessary data to public */ - async toPublicJSON() { - return { + async toPublicJSON(showTags = false) { + let obj = { id: this.id, name: this.name, }; + if (showTags) { + obj.tags = await this.getTags(); + } + return obj; } /** - * Return a object that ready to parse to JSON + * Return an object that ready to parse to JSON */ async toJSON() { @@ -49,7 +54,7 @@ class Monitor extends BeanModel { notificationIDList[bean.notification_id] = true; } - const tags = await R.getAll("SELECT mt.*, tag.name, tag.color FROM monitor_tag mt JOIN tag ON mt.tag_id = tag.id WHERE mt.monitor_id = ?", [this.id]); + const tags = await this.getTags(); return { id: this.id, @@ -69,6 +74,7 @@ class Monitor extends BeanModel { interval: this.interval, retryInterval: this.retryInterval, keyword: this.keyword, + expiryNotification: this.isEnabledExpiryNotification(), ignoreTls: this.getIgnoreTls(), upsideDown: this.isUpsideDown(), maxredirects: this.maxredirects, @@ -77,6 +83,7 @@ class Monitor extends BeanModel { dns_resolve_server: this.dns_resolve_server, dns_last_result: this.dns_last_result, pushToken: this.pushToken, + proxyId: this.proxy_id, notificationIDList, tags: tags, mqttUsername: this.mqttUsername, @@ -85,6 +92,10 @@ class Monitor extends BeanModel { }; } + async getTags() { + return await R.getAll("SELECT mt.*, tag.name, tag.color FROM monitor_tag mt JOIN tag ON mt.tag_id = tag.id WHERE mt.monitor_id = ?", [this.id]); + } + /** * Encode user and password to Base64 encoding * for HTTP "basic" auth, as per RFC-7617 @@ -94,6 +105,10 @@ class Monitor extends BeanModel { return Buffer.from(user + ":" + pass).toString("base64"); } + isEnabledExpiryNotification() { + return Boolean(this.expiryNotification); + } + /** * Parse to boolean * @returns {boolean} @@ -122,6 +137,19 @@ class Monitor extends BeanModel { const beat = async () => { + let beatInterval = this.interval; + + if (! beatInterval) { + beatInterval = 1; + } + + if (demoMode) { + if (beatInterval < 20) { + console.log("beat interval too low, reset to 20s"); + beatInterval = 20; + } + } + // Expose here for prometheus update // undefined if not https let tlsInfo = undefined; @@ -163,7 +191,12 @@ class Monitor extends BeanModel { }; } - debug(`[${this.name}] Prepare Options for axios`); + const httpsAgentOptions = { + maxCachedSessions: 0, // Use Custom agent to disable session reuse (https://github.com/nodejs/node/issues/3940) + rejectUnauthorized: !this.getIgnoreTls(), + }; + + log.debug("monitor", `[${this.name}] Prepare Options for axios`); const options = { url: this.url, @@ -176,17 +209,33 @@ class Monitor extends BeanModel { ...(this.headers ? JSON.parse(this.headers) : {}), ...(basicAuthHeader), }, - httpsAgent: new https.Agent({ - maxCachedSessions: 0, // Use Custom agent to disable session reuse (https://github.com/nodejs/node/issues/3940) - rejectUnauthorized: !this.getIgnoreTls(), - }), maxRedirects: this.maxredirects, validateStatus: (status) => { return checkStatusCode(status, this.getAcceptedStatuscodes()); }, }; - debug(`[${this.name}] Axios Request`); + if (this.proxy_id) { + const proxy = await R.load("proxy", this.proxy_id); + + if (proxy && proxy.active) { + const { httpAgent, httpsAgent } = Proxy.createAgents(proxy, { + httpsAgentOptions: httpsAgentOptions, + }); + + options.proxy = false; + options.httpAgent = httpAgent; + options.httpsAgent = httpsAgent; + } + } + + if (!options.httpsAgent) { + options.httpsAgent = new https.Agent(httpsAgentOptions); + } + + log.debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`); + log.debug("monitor", `[${this.name}] Axios Request`); + let res = await axios.request(options); bean.msg = `${res.status} - ${res.statusText}`; bean.ping = dayjs().valueOf() - startTime; @@ -194,29 +243,30 @@ class Monitor extends BeanModel { // Check certificate if https is used let certInfoStartTime = dayjs().valueOf(); if (this.getUrl()?.protocol === "https:") { - debug(`[${this.name}] Check cert`); + log.debug("monitor", `[${this.name}] Check cert`); try { let tlsInfoObject = checkCertificate(res); tlsInfo = await this.updateTlsInfo(tlsInfoObject); - if (!this.getIgnoreTls()) { - debug(`[${this.name}] call sendCertNotification`); + if (!this.getIgnoreTls() && this.isEnabledExpiryNotification()) { + log.debug("monitor", `[${this.name}] call sendCertNotification`); await this.sendCertNotification(tlsInfoObject); } } catch (e) { if (e.message !== "No TLS certificate in response") { - console.error(e.message); + log.error("monitor", "Caught error"); + log.error("monitor", e.message); } } } if (process.env.TIMELOGGER === "1") { - debug("Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms"); + log.debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms"); } if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID == this.id) { - console.log(res.data); + log.info("monitor", res.data); } if (this.type === "http") { @@ -296,7 +346,7 @@ class Monitor extends BeanModel { time ]); - debug("heartbeatCount" + heartbeatCount + " " + time); + log.debug("monitor", "heartbeatCount" + heartbeatCount + " " + time); if (heartbeatCount <= 0) { // Fix #922, since previous heartbeat could be inserted by api, it should get from database @@ -306,7 +356,7 @@ class Monitor extends BeanModel { } else { // No need to insert successful heartbeat for push type, so end here retries = 0; - this.heartbeatInterval = setTimeout(beat, this.interval * 1000); + this.heartbeatInterval = setTimeout(beat, beatInterval * 1000); return; } @@ -394,9 +444,7 @@ class Monitor extends BeanModel { } } - let beatInterval = this.interval; - - debug(`[${this.name}] Check isImportant`); + log.debug("monitor", `[${this.name}] Check isImportant`); let isImportant = Monitor.isImportantBeat(isFirstBeat, previousBeat?.status, bean.status); // Mark as important if status changed, ignore pending pings, @@ -404,11 +452,11 @@ class Monitor extends BeanModel { if (isImportant) { bean.important = true; - debug(`[${this.name}] sendNotification`); + log.debug("monitor", `[${this.name}] sendNotification`); await Monitor.sendNotification(isFirstBeat, this, bean); // Clear Status Page Cache - debug(`[${this.name}] apicache clear`); + log.debug("monitor", `[${this.name}] apicache clear`); apicache.clear(); } else { @@ -416,41 +464,33 @@ class Monitor extends BeanModel { } if (bean.status === UP) { - console.info(`Monitor #${this.id} '${this.name}': Successful Response: ${bean.ping} ms | Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.info("monitor", `Monitor #${this.id} '${this.name}': Successful Response: ${bean.ping} ms | Interval: ${beatInterval} seconds | Type: ${this.type}`); } else if (bean.status === PENDING) { if (this.retryInterval > 0) { beatInterval = this.retryInterval; } - console.warn(`Monitor #${this.id} '${this.name}': Pending: ${bean.msg} | Max retries: ${this.maxretries} | Retry: ${retries} | Retry Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.warn("monitor", `Monitor #${this.id} '${this.name}': Pending: ${bean.msg} | Max retries: ${this.maxretries} | Retry: ${retries} | Retry Interval: ${beatInterval} seconds | Type: ${this.type}`); } else { - console.warn(`Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.warn("monitor", `Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`); } - debug(`[${this.name}] Send to socket`); + log.debug("monitor", `[${this.name}] Send to socket`); io.to(this.user_id).emit("heartbeat", bean.toJSON()); Monitor.sendStats(io, this.id, this.user_id); - debug(`[${this.name}] Store`); + log.debug("monitor", `[${this.name}] Store`); await R.store(bean); - debug(`[${this.name}] prometheus.update`); + log.debug("monitor", `[${this.name}] prometheus.update`); prometheus.update(bean, tlsInfo); previousBeat = bean; - if (!this.isStop) { - - if (demoMode) { - if (beatInterval < 20) { - console.log("beat interval too low, reset to 20s"); - beatInterval = 20; - } - } - - debug(`[${this.name}] SetTimeout for next check.`); + if (! this.isStop) { + log.debug("monitor", `[${this.name}] SetTimeout for next check.`); this.heartbeatInterval = setTimeout(safeBeat, beatInterval * 1000); } else { - console.log(`[${this.name}] isStop = true, no next check.`); + log.info("monitor", `[${this.name}] isStop = true, no next check.`); } }; @@ -461,10 +501,10 @@ class Monitor extends BeanModel { } catch (e) { console.trace(e); errorLog(e, false); - console.error("Please report to https://github.com/louislam/uptime-kuma/issues"); + log.error("monitor", "Please report to https://github.com/louislam/uptime-kuma/issues"); - if (!this.isStop) { - console.log("Try to restart the monitor"); + if (! this.isStop) { + log.info("monitor", "Try to restart the monitor"); this.heartbeatInterval = setTimeout(safeBeat, this.interval * 1000); } } @@ -483,6 +523,12 @@ class Monitor extends BeanModel { stop() { clearTimeout(this.heartbeatInterval); this.isStop = true; + + this.prometheus().remove(); + } + + prometheus() { + return new Prometheus(this); } /** @@ -505,41 +551,41 @@ class Monitor extends BeanModel { * @returns {Promise} */ async updateTlsInfo(checkCertificateResult) { - let tls_info_bean = await R.findOne("monitor_tls_info", "monitor_id = ?", [ + let tlsInfoBean = await R.findOne("monitor_tls_info", "monitor_id = ?", [ this.id, ]); - if (tls_info_bean == null) { - tls_info_bean = R.dispense("monitor_tls_info"); - tls_info_bean.monitor_id = this.id; + if (tlsInfoBean == null) { + tlsInfoBean = R.dispense("monitor_tls_info"); + tlsInfoBean.monitor_id = this.id; } else { // Clear sent history if the cert changed. try { - let oldCertInfo = JSON.parse(tls_info_bean.info_json); + let oldCertInfo = JSON.parse(tlsInfoBean.info_json); let isValidObjects = oldCertInfo && oldCertInfo.certInfo && checkCertificateResult && checkCertificateResult.certInfo; if (isValidObjects) { if (oldCertInfo.certInfo.fingerprint256 !== checkCertificateResult.certInfo.fingerprint256) { - debug("Resetting sent_history"); + log.debug("monitor", "Resetting sent_history"); await R.exec("DELETE FROM notification_sent_history WHERE type = 'certificate' AND monitor_id = ?", [ this.id ]); } else { - debug("No need to reset sent_history"); - debug(oldCertInfo.certInfo.fingerprint256); - debug(checkCertificateResult.certInfo.fingerprint256); + log.debug("monitor", "No need to reset sent_history"); + log.debug("monitor", oldCertInfo.certInfo.fingerprint256); + log.debug("monitor", checkCertificateResult.certInfo.fingerprint256); } } else { - debug("Not valid object"); + log.debug("monitor", "Not valid object"); } } catch (e) { } } - tls_info_bean.info_json = JSON.stringify(checkCertificateResult); - await R.store(tls_info_bean); + tlsInfoBean.info_json = JSON.stringify(checkCertificateResult); + await R.store(tlsInfoBean); return checkCertificateResult; } @@ -553,7 +599,7 @@ class Monitor extends BeanModel { await Monitor.sendUptime(24 * 30, io, monitorID, userID); await Monitor.sendCertInfo(io, monitorID, userID); } else { - debug("No clients in the room, no need to send stats"); + log.debug("monitor", "No clients in the room, no need to send stats"); } } @@ -700,8 +746,8 @@ class Monitor extends BeanModel { try { await Notification.send(JSON.parse(notification.config), msg, await monitor.toJSON(), bean.toJSON()); } catch (e) { - console.error("Cannot send notification to " + notification.name); - console.log(e); + log.error("monitor", "Cannot send notification to " + notification.name); + log.error("monitor", e); } } } @@ -718,7 +764,7 @@ class Monitor extends BeanModel { if (tlsInfoObject && tlsInfoObject.certInfo && tlsInfoObject.certInfo.daysRemaining) { const notificationList = await Monitor.getNotificationList(this); - debug("call sendCertNotificationByTargetDays"); + log.debug("monitor", "call sendCertNotificationByTargetDays"); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 21, notificationList); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 14, notificationList); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 7, notificationList); @@ -728,7 +774,7 @@ class Monitor extends BeanModel { async sendCertNotificationByTargetDays(daysRemaining, targetDays, notificationList) { if (daysRemaining > targetDays) { - debug(`No need to send cert notification. ${daysRemaining} > ${targetDays}`); + log.debug("monitor", `No need to send cert notification. ${daysRemaining} > ${targetDays}`); return; } @@ -742,21 +788,21 @@ class Monitor extends BeanModel { // Sent already, no need to send again if (row) { - debug("Sent already, no need to send again"); + log.debug("monitor", "Sent already, no need to send again"); return; } let sent = false; - debug("Send certificate notification"); + log.debug("monitor", "Send certificate notification"); for (let notification of notificationList) { try { - debug("Sending to " + notification.name); + log.debug("monitor", "Sending to " + notification.name); await Notification.send(JSON.parse(notification.config), `[${this.name}][${this.url}] Certificate will be expired in ${daysRemaining} days`); sent = true; } catch (e) { - console.error("Cannot send cert notification to " + notification.name); - console.error(e); + log.error("monitor", "Cannot send cert notification to " + notification.name); + log.error("monitor", e); } } @@ -768,7 +814,7 @@ class Monitor extends BeanModel { ]); } } else { - debug("No notification, no need to send cert notification"); + log.debug("monitor", "No notification, no need to send cert notification"); } } diff --git a/server/model/proxy.js b/server/model/proxy.js new file mode 100644 index 000000000..7ddec4349 --- /dev/null +++ b/server/model/proxy.js @@ -0,0 +1,21 @@ +const { BeanModel } = require("redbean-node/dist/bean-model"); + +class Proxy extends BeanModel { + toJSON() { + return { + id: this._id, + userId: this._user_id, + protocol: this._protocol, + host: this._host, + port: this._port, + auth: !!this._auth, + username: this._username, + password: this._password, + active: !!this._active, + default: !!this._default, + createdDate: this._created_date, + }; + } +} + +module.exports = Proxy; diff --git a/server/model/status_page.js b/server/model/status_page.js new file mode 100644 index 000000000..1383d3b00 --- /dev/null +++ b/server/model/status_page.js @@ -0,0 +1,126 @@ +const { BeanModel } = require("redbean-node/dist/bean-model"); +const { R } = require("redbean-node"); + +class StatusPage extends BeanModel { + + static domainMappingList = { }; + + /** + * Return object like this: { "test-uptime.kuma.pet": "default" } + * @returns {Promise} + */ + static async loadDomainMappingList() { + StatusPage.domainMappingList = await R.getAssoc(` + SELECT domain, slug + FROM status_page, status_page_cname + WHERE status_page.id = status_page_cname.status_page_id + `); + } + + static async sendStatusPageList(io, socket) { + let result = {}; + + let list = await R.findAll("status_page", " ORDER BY title "); + + for (let item of list) { + result[item.id] = await item.toJSON(); + } + + io.to(socket.userID).emit("statusPageList", result); + return list; + } + + async updateDomainNameList(domainNameList) { + + if (!Array.isArray(domainNameList)) { + throw new Error("Invalid array"); + } + + let trx = await R.begin(); + + await trx.exec("DELETE FROM status_page_cname WHERE status_page_id = ?", [ + this.id, + ]); + + try { + for (let domain of domainNameList) { + if (typeof domain !== "string") { + throw new Error("Invalid domain"); + } + + if (domain.trim() === "") { + continue; + } + + // If the domain name is used in another status page, delete it + await trx.exec("DELETE FROM status_page_cname WHERE domain = ?", [ + domain, + ]); + + let mapping = trx.dispense("status_page_cname"); + mapping.status_page_id = this.id; + mapping.domain = domain; + await trx.store(mapping); + } + await trx.commit(); + } catch (error) { + await trx.rollback(); + throw error; + } + } + + getDomainNameList() { + let domainList = []; + for (let domain in StatusPage.domainMappingList) { + let s = StatusPage.domainMappingList[domain]; + + if (this.slug === s) { + domainList.push(domain); + } + } + return domainList; + } + + async toJSON() { + return { + id: this.id, + slug: this.slug, + title: this.title, + description: this.description, + icon: this.getIcon(), + theme: this.theme, + published: !!this.published, + showTags: !!this.show_tags, + domainNameList: this.getDomainNameList(), + }; + } + + async toPublicJSON() { + return { + slug: this.slug, + title: this.title, + description: this.description, + icon: this.getIcon(), + theme: this.theme, + published: !!this.published, + showTags: !!this.show_tags, + }; + } + + static async slugToID(slug) { + return await R.getCell("SELECT id FROM status_page WHERE slug = ? ", [ + slug + ]); + } + + getIcon() { + if (!this.icon) { + return "/icon.svg"; + } else { + return this.icon; + } + } + +} + +module.exports = StatusPage; diff --git a/server/modules/apicache/apicache.js b/server/modules/apicache/apicache.js index 22d1fed71..25f0a54f5 100644 --- a/server/modules/apicache/apicache.js +++ b/server/modules/apicache/apicache.js @@ -68,6 +68,15 @@ function ApiCache() { instances.push(this); this.id = instances.length; + /** + * Logs a message to the console if the `DEBUG` environment variable is set. + * @param {string} a - The first argument to log. + * @param {string} b - The second argument to log. + * @param {string} c - The third argument to log. + * @param {string} d - The fourth argument to log, and so on... (optional) + * + * Generated by Trelent + */ function debug(a, b, c, d) { let arr = ["\x1b[36m[apicache]\x1b[0m", a, b, c, d].filter(function (arg) { return arg !== undefined; @@ -77,6 +86,13 @@ function ApiCache() { return (globalOptions.debug || debugEnv) && console.log.apply(null, arr); } + /** + * Returns true if the given request and response should be logged. + * @param {Object} request The HTTP request object. + * @param {Object} response The HTTP response object. + * + * Generated by Trelent + */ function shouldCacheResponse(request, response, toggle) { let opt = globalOptions; let codes = opt.statusCodes; @@ -99,6 +115,12 @@ function ApiCache() { return true; } + /** + * Adds a key to the index. + * @param {string} key The key to add. + * + * Generated by Trelent + */ function addIndexEntries(key, req) { let groupName = req.apicacheGroup; @@ -111,6 +133,13 @@ function ApiCache() { index.all.unshift(key); } + /** + * Returns a new object containing only the whitelisted headers. + * @param {Object} headers The original object of header names and values. + * @param {Array.} globalOptions.headerWhitelist An array of strings representing the whitelisted header names to keep in the output object. + * + * Generated by Trelent + */ function filterBlacklistedHeaders(headers) { return Object.keys(headers) .filter(function (key) { @@ -122,6 +151,12 @@ function ApiCache() { }, {}); } + /** + * @param {Object} headers The response headers to filter. + * @returns {Object} A new object containing only the whitelisted response headers. + * + * Generated by Trelent + */ function createCacheObject(status, headers, data, encoding) { return { status: status, @@ -132,6 +167,14 @@ function ApiCache() { }; } + /** + * Sets a cache value for the given key. + * @param {string} key The cache key to set. + * @param {*} value The cache value to set. + * @param {number} duration How long in milliseconds the cached response should be valid for (defaults to 1 hour). + * + * Generated by Trelent + */ function cacheResponse(key, value, duration) { let redis = globalOptions.redisClient; let expireCallback = globalOptions.events.expire; @@ -154,6 +197,12 @@ function ApiCache() { }, Math.min(duration, 2147483647)); } + /** + * Appends content to the response. + * @param {string|Buffer} content The content to append. + * + * Generated by Trelent + */ function accumulateContent(res, content) { if (content) { if (typeof content == "string") { @@ -179,6 +228,13 @@ function ApiCache() { } } + /** + * Monkeypatches the response object to add cache control headers and create a cache object. + * @param {Object} req - The request object. + * @param {Object} res - The response object. + * + * Generated by Trelent + */ function makeResponseCacheable(req, res, next, key, duration, strDuration, toggle) { // monkeypatch res.end to create cache object res._apicache = { @@ -245,6 +301,13 @@ function ApiCache() { next(); } + /** + * @param {Request} request + * @param {Response} response + * @returns {boolean|undefined} true if the request should be cached, false otherwise. If undefined, defaults to true. + * + * Generated by Trelent + */ function sendCachedResponse(request, response, cacheObject, toggle, next, duration) { if (toggle && !toggle(request, response)) { return next(); @@ -365,6 +428,13 @@ function ApiCache() { return this.getIndex(); }; + /** + * Converts a duration string to an integer number of milliseconds. + * @param {string} duration - The string to convert. + * @returns {number} The converted value in milliseconds, or the defaultDuration if it can't be parsed. + * + * Generated by Trelent + */ function parseDuration(duration, defaultDuration) { if (typeof duration === "number") { return duration; diff --git a/server/notification-providers/alerta.js b/server/notification-providers/alerta.js new file mode 100644 index 000000000..bcee80df7 --- /dev/null +++ b/server/notification-providers/alerta.js @@ -0,0 +1,67 @@ +const NotificationProvider = require("./notification-provider"); +const { DOWN, UP } = require("../../src/util"); +const axios = require("axios"); + +class Alerta extends NotificationProvider { + + name = "alerta"; + + async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { + let okMsg = "Sent Successfully."; + + try { + let alertaUrl = `${notification.alertaApiEndpoint}`; + let config = { + headers: { + "Content-Type": "application/json;charset=UTF-8", + "Authorization": "Key " + notification.alertaApiKey, + } + }; + let data = { + environment: notification.alertaEnvironment, + severity: "critical", + correlate: [], + service: [ "UptimeKuma" ], + value: "Timeout", + tags: [ "uptimekuma" ], + attributes: {}, + origin: "uptimekuma", + type: "exceptionAlert", + }; + + if (heartbeatJSON == null) { + let postData = Object.assign({ + event: "msg", + text: msg, + group: "uptimekuma-msg", + resource: "Message", + }, data); + + await axios.post(alertaUrl, postData, config); + } else { + let datadup = Object.assign( { + correlate: ["service_up", "service_down"], + event: monitorJSON["type"], + group: "uptimekuma-" + monitorJSON["type"], + resource: monitorJSON["name"], + }, data ); + + if (heartbeatJSON["status"] == DOWN) { + datadup.severity = notification.alertaAlertState; // critical + datadup.text = "Service " + monitorJSON["type"] + " is down."; + await axios.post(alertaUrl, datadup, config); + } else if (heartbeatJSON["status"] == UP) { + datadup.severity = notification.alertaRecoverState; // cleaned + datadup.text = "Service " + monitorJSON["type"] + " is up."; + await axios.post(alertaUrl, datadup, config); + } + } + return okMsg; + } catch (error) { + this.throwGeneralAxiosError(error); + } + + } +} + +module.exports = Alerta; diff --git a/server/notification-providers/apprise.js b/server/notification-providers/apprise.js index fdcd8d61b..692483d86 100644 --- a/server/notification-providers/apprise.js +++ b/server/notification-providers/apprise.js @@ -6,7 +6,7 @@ class Apprise extends NotificationProvider { name = "apprise"; async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { - let s = child_process.spawnSync("apprise", [ "-vv", "-b", msg, notification.appriseURL]) + let s = child_process.spawnSync("apprise", [ "-vv", "-b", msg, notification.appriseURL]); let output = (s.stdout) ? s.stdout.toString() : "ERROR: maybe apprise not found"; @@ -16,7 +16,7 @@ class Apprise extends NotificationProvider { return "Sent Successfully"; } - throw new Error(output) + throw new Error(output); } else { return "No output from apprise"; } diff --git a/server/notification-providers/bark.js b/server/notification-providers/bark.js index 4ebe978ad..a4c525120 100644 --- a/server/notification-providers/bark.js +++ b/server/notification-providers/bark.js @@ -21,31 +21,26 @@ class Bark extends NotificationProvider { name = "Bark"; async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { - try { - var barkEndpoint = notification.barkEndpoint; + let barkEndpoint = notification.barkEndpoint; - // check if the endpoint has a "/" suffix, if so, delete it first - if (barkEndpoint.endsWith("/")) { - barkEndpoint = barkEndpoint.substring(0, barkEndpoint.length - 1); - } + // check if the endpoint has a "/" suffix, if so, delete it first + if (barkEndpoint.endsWith("/")) { + barkEndpoint = barkEndpoint.substring(0, barkEndpoint.length - 1); + } - if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == UP) { - let title = "UptimeKuma Monitor Up"; - return await this.postNotification(title, msg, barkEndpoint); - } + if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == UP) { + let title = "UptimeKuma Monitor Up"; + return await this.postNotification(title, msg, barkEndpoint); + } - if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == DOWN) { - let title = "UptimeKuma Monitor Down"; - return await this.postNotification(title, msg, barkEndpoint); - } + if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == DOWN) { + let title = "UptimeKuma Monitor Down"; + return await this.postNotification(title, msg, barkEndpoint); + } - if (msg != null) { - let title = "UptimeKuma Message"; - return await this.postNotification(title, msg, barkEndpoint); - } - - } catch (error) { - throw error; + if (msg != null) { + let title = "UptimeKuma Message"; + return await this.postNotification(title, msg, barkEndpoint); } } diff --git a/server/notification-providers/clicksendsms.js b/server/notification-providers/clicksendsms.js index 74e2f4c59..e66b982c8 100644 --- a/server/notification-providers/clicksendsms.js +++ b/server/notification-providers/clicksendsms.js @@ -12,7 +12,7 @@ class ClickSendSMS extends NotificationProvider { let config = { headers: { "Content-Type": "application/json", - "Authorization": "Basic " + Buffer.from(notification.clicksendsmsLogin + ":" + notification.clicksendsmsPassword).toString('base64'), + "Authorization": "Basic " + Buffer.from(notification.clicksendsmsLogin + ":" + notification.clicksendsmsPassword).toString("base64"), "Accept": "text/json", } }; diff --git a/server/notification-providers/discord.js b/server/notification-providers/discord.js index 881ad2113..f5c22a446 100644 --- a/server/notification-providers/discord.js +++ b/server/notification-providers/discord.js @@ -17,8 +17,8 @@ class Discord extends NotificationProvider { let discordtestdata = { username: discordDisplayName, content: msg, - } - await axios.post(notification.discordWebhookUrl, discordtestdata) + }; + await axios.post(notification.discordWebhookUrl, discordtestdata); return okMsg; } @@ -61,13 +61,13 @@ class Discord extends NotificationProvider { }, ], }], - } + }; if (notification.discordPrefixMessage) { discorddowndata.content = notification.discordPrefixMessage; } - await axios.post(notification.discordWebhookUrl, discorddowndata) + await axios.post(notification.discordWebhookUrl, discorddowndata); return okMsg; } else if (heartbeatJSON["status"] == UP) { @@ -96,17 +96,17 @@ class Discord extends NotificationProvider { }, ], }], - } + }; if (notification.discordPrefixMessage) { discordupdata.content = notification.discordPrefixMessage; } - await axios.post(notification.discordWebhookUrl, discordupdata) + await axios.post(notification.discordWebhookUrl, discordupdata); return okMsg; } } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } diff --git a/server/notification-providers/google-chat.js b/server/notification-providers/google-chat.js index 6fb324288..02cb4823c 100644 --- a/server/notification-providers/google-chat.js +++ b/server/notification-providers/google-chat.js @@ -13,11 +13,11 @@ class GoogleChat extends NotificationProvider { try { // Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic - let textMsg = '' + let textMsg = ""; if (heartbeatJSON && heartbeatJSON.status === UP) { - textMsg = `✅ Application is back online\n`; + textMsg = "✅ Application is back online\n"; } else if (heartbeatJSON && heartbeatJSON.status === DOWN) { - textMsg = `🔴 Application went down\n`; + textMsg = "🔴 Application went down\n"; } if (monitorJSON && monitorJSON.name) { diff --git a/server/notification-providers/gorush.js b/server/notification-providers/gorush.js new file mode 100644 index 000000000..58da5525e --- /dev/null +++ b/server/notification-providers/gorush.js @@ -0,0 +1,42 @@ +const NotificationProvider = require("./notification-provider"); +const axios = require("axios"); + +class Gorush extends NotificationProvider { + + name = "gorush"; + + async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { + let okMsg = "Sent Successfully."; + + let platformMapping = { + "ios": 1, + "android": 2, + "huawei": 3, + }; + + try { + let data = { + "notifications": [ + { + "tokens": [notification.gorushDeviceToken], + "platform": platformMapping[notification.gorushPlatform], + "message": msg, + // Optional + "title": notification.gorushTitle, + "priority": notification.gorushPriority, + "retry": parseInt(notification.gorushRetry) || 0, + "topic": notification.gorushTopic, + } + ] + }; + let config = {}; + + await axios.post(`${notification.gorushServerURL}/api/push`, data, config); + return okMsg; + } catch (error) { + this.throwGeneralAxiosError(error); + } + } +} + +module.exports = Gorush; diff --git a/server/notification-providers/gotify.js b/server/notification-providers/gotify.js index 085261897..0c5244939 100644 --- a/server/notification-providers/gotify.js +++ b/server/notification-providers/gotify.js @@ -15,7 +15,7 @@ class Gotify extends NotificationProvider { "message": msg, "priority": notification.gotifyPriority || 8, "title": "Uptime-Kuma", - }) + }); return okMsg; diff --git a/server/notification-providers/line.js b/server/notification-providers/line.js index 327696edd..6a09b5024 100644 --- a/server/notification-providers/line.js +++ b/server/notification-providers/line.js @@ -25,8 +25,8 @@ class Line extends NotificationProvider { "text": "Test Successful!" } ] - } - await axios.post(lineAPIUrl, testMessage, config) + }; + await axios.post(lineAPIUrl, testMessage, config); } else if (heartbeatJSON["status"] == DOWN) { let downMessage = { "to": notification.lineUserID, @@ -36,8 +36,8 @@ class Line extends NotificationProvider { "text": "UptimeKuma Alert: [🔴 Down]\n" + "Name: " + monitorJSON["name"] + " \n" + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"] } ] - } - await axios.post(lineAPIUrl, downMessage, config) + }; + await axios.post(lineAPIUrl, downMessage, config); } else if (heartbeatJSON["status"] == UP) { let upMessage = { "to": notification.lineUserID, @@ -47,12 +47,12 @@ class Line extends NotificationProvider { "text": "UptimeKuma Alert: [✅ Up]\n" + "Name: " + monitorJSON["name"] + " \n" + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"] } ] - } - await axios.post(lineAPIUrl, upMessage, config) + }; + await axios.post(lineAPIUrl, upMessage, config); } return okMsg; } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } } diff --git a/server/notification-providers/lunasea.js b/server/notification-providers/lunasea.js index c41f400e2..82d2fde5b 100644 --- a/server/notification-providers/lunasea.js +++ b/server/notification-providers/lunasea.js @@ -8,15 +8,15 @@ class LunaSea extends NotificationProvider { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { let okMsg = "Sent Successfully."; - let lunaseadevice = "https://notify.lunasea.app/v1/custom/device/" + notification.lunaseaDevice + let lunaseadevice = "https://notify.lunasea.app/v1/custom/device/" + notification.lunaseaDevice; try { if (heartbeatJSON == null) { let testdata = { "title": "Uptime Kuma Alert", "body": "Testing Successful.", - } - await axios.post(lunaseadevice, testdata) + }; + await axios.post(lunaseadevice, testdata); return okMsg; } @@ -24,8 +24,8 @@ class LunaSea extends NotificationProvider { let downdata = { "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[🔴 Down] " + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"], - } - await axios.post(lunaseadevice, downdata) + }; + await axios.post(lunaseadevice, downdata); return okMsg; } @@ -33,13 +33,13 @@ class LunaSea extends NotificationProvider { let updata = { "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[✅ Up] " + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"], - } - await axios.post(lunaseadevice, updata) + }; + await axios.post(lunaseadevice, updata); return okMsg; } } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } diff --git a/server/notification-providers/matrix.js b/server/notification-providers/matrix.js index c1054fce6..915c772d7 100644 --- a/server/notification-providers/matrix.js +++ b/server/notification-providers/matrix.js @@ -1,7 +1,7 @@ const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const Crypto = require("crypto"); -const { debug } = require("../../src/util"); +const { log } = require("../../src/util"); class Matrix extends NotificationProvider { name = "matrix"; @@ -17,11 +17,11 @@ class Matrix extends NotificationProvider { .slice(0, size) ); - debug("Random String: " + randomString); + log.debug("notification", "Random String: " + randomString); const roomId = encodeURIComponent(notification.internalRoomId); - debug("Matrix Room ID: " + roomId); + log.debug("notification", "Matrix Room ID: " + roomId); try { let config = { diff --git a/server/notification-providers/mattermost.js b/server/notification-providers/mattermost.js index d776284be..fe7b685e1 100644 --- a/server/notification-providers/mattermost.js +++ b/server/notification-providers/mattermost.js @@ -15,12 +15,17 @@ class Mattermost extends NotificationProvider { let mattermostTestData = { username: mattermostUserName, text: msg, - } - await axios.post(notification.mattermostWebhookUrl, mattermostTestData) + }; + await axios.post(notification.mattermostWebhookUrl, mattermostTestData); return okMsg; } - const mattermostChannel = notification.mattermostchannel; + let mattermostChannel; + + if (typeof notification.mattermostchannel === "string") { + mattermostChannel = notification.mattermostchannel.toLowerCase(); + } + const mattermostIconEmoji = notification.mattermosticonemo; const mattermostIconUrl = notification.mattermosticonurl; diff --git a/server/notification-providers/notification-provider.js b/server/notification-providers/notification-provider.js index 61c6242d7..87687baaf 100644 --- a/server/notification-providers/notification-provider.js +++ b/server/notification-providers/notification-provider.js @@ -25,11 +25,11 @@ class NotificationProvider { if (typeof error.response.data === "string") { msg += error.response.data; } else { - msg += JSON.stringify(error.response.data) + msg += JSON.stringify(error.response.data); } } - throw new Error(msg) + throw new Error(msg); } } diff --git a/server/notification-providers/octopush.js b/server/notification-providers/octopush.js index 9d77aa5b4..68416b9a9 100644 --- a/server/notification-providers/octopush.js +++ b/server/notification-providers/octopush.js @@ -30,7 +30,7 @@ class Octopush extends NotificationProvider { "purpose": "alert", "sender": notification.octopushSenderName }; - await axios.post("https://api.octopush.com/v1/public/sms-campaign/send", data, config) + 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, @@ -49,7 +49,7 @@ class Octopush extends NotificationProvider { }, params: data }; - await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config) + await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config); } else { throw new Error("Unknown Octopush version!"); } diff --git a/server/notification-providers/onebot.js b/server/notification-providers/onebot.js new file mode 100644 index 000000000..c08cc01e8 --- /dev/null +++ b/server/notification-providers/onebot.js @@ -0,0 +1,45 @@ +const NotificationProvider = require("./notification-provider"); +const axios = require("axios"); + +class OneBot extends NotificationProvider { + + name = "OneBot"; + + async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { + let okMsg = "Sent Successfully."; + try { + let httpAddr = notification.httpAddr; + if (!httpAddr.startsWith("http")) { + httpAddr = "http://" + httpAddr; + } + if (!httpAddr.endsWith("/")) { + httpAddr += "/"; + } + let onebotAPIUrl = httpAddr + "send_msg"; + let config = { + headers: { + "Content-Type": "application/json", + "Authorization": "Bearer " + notification.accessToken, + } + }; + let pushText = "UptimeKuma Alert: " + msg; + let data = { + "auto_escape": true, + "message": pushText, + }; + if (notification.msgType == "group") { + data["message_type"] = "group"; + data["group_id"] = notification.recieverId; + } else { + data["message_type"] = "private"; + data["user_id"] = notification.recieverId; + } + await axios.post(onebotAPIUrl, data, config); + return okMsg; + } catch (error) { + this.throwGeneralAxiosError(error); + } + } +} + +module.exports = OneBot; diff --git a/server/notification-providers/promosms.js b/server/notification-providers/promosms.js index 362ef714a..4f7e8f901 100644 --- a/server/notification-providers/promosms.js +++ b/server/notification-providers/promosms.js @@ -12,7 +12,7 @@ class PromoSMS extends NotificationProvider { let config = { headers: { "Content-Type": "application/json", - "Authorization": "Basic " + Buffer.from(notification.promosmsLogin + ":" + notification.promosmsPassword).toString('base64'), + "Authorization": "Basic " + Buffer.from(notification.promosmsLogin + ":" + notification.promosmsPassword).toString("base64"), "Accept": "text/json", } }; @@ -30,7 +30,7 @@ class PromoSMS extends NotificationProvider { let error = "Something gone wrong. Api returned " + resp.data.response.status + "."; this.throwGeneralAxiosError(error); } - + return okMsg; } catch (error) { this.throwGeneralAxiosError(error); diff --git a/server/notification-providers/pushbullet.js b/server/notification-providers/pushbullet.js index c7b824a2c..07b4ed682 100644 --- a/server/notification-providers/pushbullet.js +++ b/server/notification-providers/pushbullet.js @@ -23,26 +23,26 @@ class Pushbullet extends NotificationProvider { "type": "note", "title": "Uptime Kuma Alert", "body": "Testing Successful.", - } - await axios.post(pushbulletUrl, testdata, config) + }; + await axios.post(pushbulletUrl, testdata, config); } else if (heartbeatJSON["status"] == DOWN) { let downdata = { "type": "note", "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[🔴 Down] " + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"], - } - await axios.post(pushbulletUrl, downdata, config) + }; + await axios.post(pushbulletUrl, downdata, config); } else if (heartbeatJSON["status"] == UP) { let updata = { "type": "note", "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[✅ Up] " + heartbeatJSON["msg"] + "\nTime (UTC): " + heartbeatJSON["time"], - } - await axios.post(pushbulletUrl, updata, config) + }; + await axios.post(pushbulletUrl, updata, config); } return okMsg; } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } } diff --git a/server/notification-providers/pushover.js b/server/notification-providers/pushover.js index 52d13eef7..ebcb88c4f 100644 --- a/server/notification-providers/pushover.js +++ b/server/notification-providers/pushover.js @@ -9,36 +9,31 @@ class Pushover extends NotificationProvider { let okMsg = "Sent Successfully."; let pushoverlink = "https://api.pushover.net/1/messages.json"; + let data = { + "message": "Uptime Kuma Alert\n\nMessage:" + msg, + "user": notification.pushoveruserkey, + "token": notification.pushoverapptoken, + "sound": notification.pushoversounds, + "priority": notification.pushoverpriority, + "title": notification.pushovertitle, + "retry": "30", + "expire": "3600", + "html": 1, + }; + + if (notification.pushoverdevice) { + data.device = notification.pushoverdevice; + } + try { if (heartbeatJSON == null) { - let data = { - "message": msg, - "user": notification.pushoveruserkey, - "token": notification.pushoverapptoken, - "sound": notification.pushoversounds, - "priority": notification.pushoverpriority, - "title": notification.pushovertitle, - "retry": "30", - "expire": "3600", - "html": 1, - }; + await axios.post(pushoverlink, data); + return okMsg; + } else { + data.message += "\nTime (UTC):" + heartbeatJSON["time"]; await axios.post(pushoverlink, data); return okMsg; } - - let data = { - "message": "Uptime Kuma Alert\n\nMessage:" + msg + "\nTime (UTC):" + heartbeatJSON["time"], - "user": notification.pushoveruserkey, - "token": notification.pushoverapptoken, - "sound": notification.pushoversounds, - "priority": notification.pushoverpriority, - "title": notification.pushovertitle, - "retry": "30", - "expire": "3600", - "html": 1, - }; - await axios.post(pushoverlink, data); - return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } diff --git a/server/notification-providers/pushy.js b/server/notification-providers/pushy.js index 2bb899349..1d6e7f32f 100644 --- a/server/notification-providers/pushy.js +++ b/server/notification-providers/pushy.js @@ -19,10 +19,10 @@ class Pushy extends NotificationProvider { "badge": 1, "sound": "ping.aiff" } - }) + }); return okMsg; } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } } diff --git a/server/notification-providers/rocket-chat.js b/server/notification-providers/rocket-chat.js index 25b0b945f..fb48ce1a6 100644 --- a/server/notification-providers/rocket-chat.js +++ b/server/notification-providers/rocket-chat.js @@ -2,7 +2,7 @@ const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const Slack = require("./slack"); const { setting } = require("../util-server"); -const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util"); +const { getMonitorRelativeURL, DOWN } = require("../../src/util"); class RocketChat extends NotificationProvider { diff --git a/server/notification-providers/signal.js b/server/notification-providers/signal.js index fee65754e..677208ee6 100644 --- a/server/notification-providers/signal.js +++ b/server/notification-providers/signal.js @@ -16,10 +16,10 @@ class Signal extends NotificationProvider { }; let config = {}; - await axios.post(notification.signalURL, data, config) + await axios.post(notification.signalURL, data, config); return okMsg; } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } } diff --git a/server/notification-providers/techulus-push.js b/server/notification-providers/techulus-push.js new file mode 100644 index 000000000..751ff4c3a --- /dev/null +++ b/server/notification-providers/techulus-push.js @@ -0,0 +1,23 @@ +const NotificationProvider = require("./notification-provider"); +const axios = require("axios"); + +class TechulusPush extends NotificationProvider { + + name = "PushByTechulus"; + + async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { + let okMsg = "Sent Successfully."; + + try { + await axios.post(`https://push.techulus.com/api/v1/notify/${notification.pushAPIKey}`, { + "title": "Uptime-Kuma", + "body": msg, + }); + return okMsg; + } catch (error) { + this.throwGeneralAxiosError(error); + } + } +} + +module.exports = TechulusPush; diff --git a/server/notification-providers/telegram.js b/server/notification-providers/telegram.js index 54d33bfbd..2b0576224 100644 --- a/server/notification-providers/telegram.js +++ b/server/notification-providers/telegram.js @@ -14,12 +14,12 @@ class Telegram extends NotificationProvider { chat_id: notification.telegramChatID, text: msg, }, - }) + }); return okMsg; } catch (error) { - let msg = (error.response.data.description) ? error.response.data.description : "Error without description" - throw new Error(msg) + let msg = (error.response.data.description) ? error.response.data.description : "Error without description"; + throw new Error(msg); } } } diff --git a/server/notification-providers/webhook.js b/server/notification-providers/webhook.js index 9cb361f30..d4933cf02 100644 --- a/server/notification-providers/webhook.js +++ b/server/notification-providers/webhook.js @@ -24,17 +24,17 @@ class Webhook extends NotificationProvider { config = { headers: finalData.getHeaders(), - } + }; } else { finalData = data; } - await axios.post(notification.webhookURL, finalData, config) + await axios.post(notification.webhookURL, finalData, config); return okMsg; } catch (error) { - this.throwGeneralAxiosError(error) + this.throwGeneralAxiosError(error); } } diff --git a/server/notification-providers/wecom.js b/server/notification-providers/wecom.js index 7ba8c3783..b377cedd9 100644 --- a/server/notification-providers/wecom.js +++ b/server/notification-providers/wecom.js @@ -26,7 +26,7 @@ class WeCom extends NotificationProvider { composeMessage(heartbeatJSON, msg) { let title; - if (msg != null && heartbeatJSON != null && heartbeatJSON['status'] == UP) { + if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == UP) { title = "UptimeKuma Monitor Up"; } if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] == DOWN) { diff --git a/server/notification.js b/server/notification.js index 4d72c81c7..a83a8cdce 100644 --- a/server/notification.js +++ b/server/notification.js @@ -12,6 +12,7 @@ const ClickSendSMS = require("./notification-providers/clicksendsms"); const Pushbullet = require("./notification-providers/pushbullet"); const Pushover = require("./notification-providers/pushover"); const Pushy = require("./notification-providers/pushy"); +const TechulusPush = require("./notification-providers/techulus-push"); const RocketChat = require("./notification-providers/rocket-chat"); const Signal = require("./notification-providers/signal"); const Slack = require("./notification-providers/slack"); @@ -23,17 +24,21 @@ const Feishu = require("./notification-providers/feishu"); const AliyunSms = require("./notification-providers/aliyun-sms"); const DingDing = require("./notification-providers/dingding"); const Bark = require("./notification-providers/bark"); +const { log } = require("../src/util"); const SerwerSMS = require("./notification-providers/serwersms"); const Stackfield = require("./notification-providers/stackfield"); const WeCom = require("./notification-providers/wecom"); const GoogleChat = require("./notification-providers/google-chat"); +const Gorush = require("./notification-providers/gorush"); +const Alerta = require("./notification-providers/alerta"); +const OneBot = require("./notification-providers/onebot"); class Notification { providerList = {}; static init() { - console.log("Prepare Notification Providers"); + log.info("notification", "Prepare Notification Providers"); this.providerList = {}; @@ -55,6 +60,7 @@ class Notification { new Pushbullet(), new Pushover(), new Pushy(), + new TechulusPush(), new RocketChat(), new Signal(), new Slack(), @@ -65,7 +71,10 @@ class Notification { new SerwerSMS(), new Stackfield(), new WeCom(), - new GoogleChat() + new GoogleChat(), + new Gorush(), + new Alerta(), + new OneBot(), ]; for (let item of list) { @@ -98,27 +107,27 @@ class Notification { } static async save(notification, notificationID, userID) { - let bean + let bean; if (notificationID) { bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ notificationID, userID, - ]) + ]); if (! bean) { - throw new Error("notification not found") + throw new Error("notification not found"); } } else { - bean = R.dispense("notification") + bean = R.dispense("notification"); } bean.name = notification.name; bean.user_id = userID; bean.config = JSON.stringify(notification); bean.is_default = notification.isDefault || false; - await R.store(bean) + await R.store(bean); if (notification.applyExisting) { await applyNotificationEveryMonitor(bean.id, userID); @@ -131,13 +140,13 @@ class Notification { let bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ notificationID, userID, - ]) + ]); if (! bean) { - throw new Error("notification not found") + throw new Error("notification not found"); } - await R.trash(bean) + await R.trash(bean); } static checkApprise() { @@ -148,6 +157,13 @@ class Notification { } +/** + * Adds a new monitor to the database. + * @param {number} userID The ID of the user that owns this monitor. + * @param {string} name The name of this monitor. + * + * Generated by Trelent + */ async function applyNotificationEveryMonitor(notificationID, userID) { let monitors = await R.getAll("SELECT id FROM monitor WHERE user_id = ?", [ userID @@ -157,17 +173,17 @@ async function applyNotificationEveryMonitor(notificationID, userID) { let checkNotification = await R.findOne("monitor_notification", " monitor_id = ? AND notification_id = ? ", [ monitors[i].id, notificationID, - ]) + ]); if (! checkNotification) { let relation = R.dispense("monitor_notification"); relation.monitor_id = monitors[i].id; relation.notification_id = notificationID; - await R.store(relation) + await R.store(relation); } } } module.exports = { Notification, -} +}; diff --git a/server/password-hash.js b/server/password-hash.js index 91e5e1add..a42b4df00 100644 --- a/server/password-hash.js +++ b/server/password-hash.js @@ -4,20 +4,20 @@ const saltRounds = 10; exports.generate = function (password) { return bcrypt.hashSync(password, saltRounds); -} +}; exports.verify = function (password, hash) { if (isSHA1(hash)) { - return passwordHashOld.verify(password, hash) + return passwordHashOld.verify(password, hash); } return bcrypt.compareSync(password, hash); -} +}; function isSHA1(hash) { - return (typeof hash === "string" && hash.startsWith("sha1")) + return (typeof hash === "string" && hash.startsWith("sha1")); } exports.needRehash = function (hash) { return isSHA1(hash); -} +}; diff --git a/server/ping-lite.js b/server/ping-lite.js index 0075e80bd..5f15b6d3a 100644 --- a/server/ping-lite.js +++ b/server/ping-lite.js @@ -8,6 +8,13 @@ const util = require("./util-server"); module.exports = Ping; +/** + * @param {string} host - The host to ping + * @param {object} [options] - Options for the ping command + * @param {array|string} [options.args] - Arguments to pass to the ping command + * + * Generated by Trelent + */ function Ping(host, options) { if (!host) { throw new Error("You must specify a host to ping!"); @@ -125,6 +132,11 @@ Ping.prototype.send = function (callback) { } }); + /** + * @param {Function} callback + * + * Generated by Trelent + */ function onEnd() { let stdout = this.stdout._stdout; let stderr = this.stderr._stderr; diff --git a/server/prometheus.js b/server/prometheus.js index 870581d2e..9634c3080 100644 --- a/server/prometheus.js +++ b/server/prometheus.js @@ -1,4 +1,5 @@ const PrometheusClient = require("prom-client"); +const { log } = require("../src/util"); const commonLabels = [ "monitor_name", @@ -48,28 +49,33 @@ class Prometheus { if (typeof tlsInfo !== "undefined") { try { - let is_valid = 0; + let isValid = 0; if (tlsInfo.valid == true) { - is_valid = 1; + isValid = 1; } else { - is_valid = 0; + isValid = 0; } - monitor_cert_is_valid.set(this.monitorLabelValues, is_valid); + monitor_cert_is_valid.set(this.monitorLabelValues, isValid); } catch (e) { - console.error(e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } try { - monitor_cert_days_remaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining); + if (tlsInfo.certInfo != null) { + monitor_cert_days_remaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining); + } } catch (e) { - console.error(e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } } try { monitor_status.set(this.monitorLabelValues, heartbeat.status); } catch (e) { - console.error(e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } try { @@ -80,10 +86,21 @@ class Prometheus { monitor_response_time.set(this.monitorLabelValues, -1); } } catch (e) { - console.error(e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } } + remove() { + try { + monitor_cert_days_remaining.remove(this.monitorLabelValues); + monitor_cert_is_valid.remove(this.monitorLabelValues); + monitor_response_time.remove(this.monitorLabelValues); + monitor_status.remove(this.monitorLabelValues); + } catch (e) { + console.error(e); + } + } } module.exports = { diff --git a/server/proxy.js b/server/proxy.js new file mode 100644 index 000000000..af72402d1 --- /dev/null +++ b/server/proxy.js @@ -0,0 +1,187 @@ +const { R } = require("redbean-node"); +const HttpProxyAgent = require("http-proxy-agent"); +const HttpsProxyAgent = require("https-proxy-agent"); +const SocksProxyAgent = require("socks-proxy-agent"); +const { debug } = require("../src/util"); +const server = require("./server"); + +class Proxy { + + static SUPPORTED_PROXY_PROTOCOLS = ["http", "https", "socks", "socks5", "socks4"] + + /** + * Saves and updates given proxy entity + * + * @param proxy + * @param proxyID + * @param userID + * @return {Promise} + */ + static async save(proxy, proxyID, userID) { + let bean; + + if (proxyID) { + bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [proxyID, userID]); + + if (!bean) { + throw new Error("proxy not found"); + } + + } else { + bean = R.dispense("proxy"); + } + + // Make sure given proxy protocol is supported + if (!this.SUPPORTED_PROXY_PROTOCOLS.includes(proxy.protocol)) { + throw new Error(` + Unsupported proxy protocol "${proxy.protocol}. + Supported protocols are ${this.SUPPORTED_PROXY_PROTOCOLS.join(", ")}."` + ); + } + + // When proxy is default update deactivate old default proxy + if (proxy.default) { + await R.exec("UPDATE proxy SET `default` = 0 WHERE `default` = 1"); + } + + bean.user_id = userID; + bean.protocol = proxy.protocol; + bean.host = proxy.host; + bean.port = proxy.port; + bean.auth = proxy.auth; + bean.username = proxy.username; + bean.password = proxy.password; + bean.active = proxy.active || true; + bean.default = proxy.default || false; + + await R.store(bean); + + if (proxy.applyExisting) { + await applyProxyEveryMonitor(bean.id, userID); + } + + return bean; + } + + /** + * Deletes proxy with given id and removes it from monitors + * + * @param proxyID + * @param userID + * @return {Promise} + */ + static async delete(proxyID, userID) { + const bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [proxyID, userID]); + + if (!bean) { + throw new Error("proxy not found"); + } + + // Delete removed proxy from monitors if exists + await R.exec("UPDATE monitor SET proxy_id = null WHERE proxy_id = ?", [proxyID]); + + // Delete proxy from list + await R.trash(bean); + } + + /** + * Create HTTP and HTTPS agents related with given proxy bean object + * + * @param proxy proxy bean object + * @param options http and https agent options + * @return {{httpAgent: Agent, httpsAgent: Agent}} + */ + static createAgents(proxy, options) { + const { httpAgentOptions, httpsAgentOptions } = options || {}; + let agent; + let httpAgent; + let httpsAgent; + + const proxyOptions = { + protocol: proxy.protocol, + host: proxy.host, + port: proxy.port, + }; + + if (proxy.auth) { + proxyOptions.auth = `${proxy.username}:${proxy.password}`; + } + + debug(`Proxy Options: ${JSON.stringify(proxyOptions)}`); + debug(`HTTP Agent Options: ${JSON.stringify(httpAgentOptions)}`); + debug(`HTTPS Agent Options: ${JSON.stringify(httpsAgentOptions)}`); + + switch (proxy.protocol) { + case "http": + case "https": + httpAgent = new HttpProxyAgent({ + ...httpAgentOptions || {}, + ...proxyOptions + }); + + httpsAgent = new HttpsProxyAgent({ + ...httpsAgentOptions || {}, + ...proxyOptions, + }); + break; + case "socks": + case "socks5": + case "socks4": + agent = new SocksProxyAgent({ + ...httpAgentOptions, + ...httpsAgentOptions, + ...proxyOptions, + }); + + httpAgent = agent; + httpsAgent = agent; + break; + + default: throw new Error(`Unsupported proxy protocol provided. ${proxy.protocol}`); + } + + return { + httpAgent, + httpsAgent + }; + } + + /** + * Reload proxy settings for current monitors + * @returns {Promise} + */ + static async reloadProxy() { + let updatedList = await R.getAssoc("SELECT id, proxy_id FROM monitor"); + + for (let monitorID in server.monitorList) { + let monitor = server.monitorList[monitorID]; + + if (updatedList[monitorID]) { + monitor.proxy_id = updatedList[monitorID].proxy_id; + } + } + } +} + +/** + * Applies given proxy id to monitors + * + * @param proxyID + * @param userID + * @return {Promise} + */ +async function applyProxyEveryMonitor(proxyID, userID) { + // Find all monitors with id and proxy id + const monitors = await R.getAll("SELECT id, proxy_id FROM monitor WHERE user_id = ?", [userID]); + + // Update proxy id not match with given proxy id + for (const monitor of monitors) { + if (monitor.proxy_id !== proxyID) { + await R.exec("UPDATE monitor SET proxy_id = ? WHERE id = ?", [proxyID, monitor.id]); + } + } +} + +module.exports = { + Proxy, +}; diff --git a/server/rate-limiter.js b/server/rate-limiter.js index 0bacc14c7..f58f16cb6 100644 --- a/server/rate-limiter.js +++ b/server/rate-limiter.js @@ -1,5 +1,5 @@ const { RateLimiter } = require("limiter"); -const { debug } = require("../src/util"); +const { log } = require("../src/util"); class KumaRateLimiter { constructor(config) { @@ -9,7 +9,7 @@ class KumaRateLimiter { async pass(callback, num = 1) { const remainingRequests = await this.removeTokens(num); - debug("Rate Limit (remainingRequests):" + remainingRequests); + log.info("rate-limit", "remaining requests: " + remainingRequests); if (remainingRequests < 0) { if (callback) { callback({ @@ -34,6 +34,14 @@ const loginRateLimiter = new KumaRateLimiter({ errorMessage: "Too frequently, try again later." }); +const twoFaRateLimiter = new KumaRateLimiter({ + tokensPerInterval: 30, + interval: "minute", + fireImmediately: true, + errorMessage: "Too frequently, try again later." +}); + module.exports = { - loginRateLimiter + loginRateLimiter, + twoFaRateLimiter, }; diff --git a/server/routers/api-router.js b/server/routers/api-router.js index 1920cef71..ad1a671b2 100644 --- a/server/routers/api-router.js +++ b/server/routers/api-router.js @@ -5,15 +5,26 @@ const server = require("../server"); const apicache = require("../modules/apicache"); const Monitor = require("../model/monitor"); const dayjs = require("dayjs"); -const { UP, flipStatus, debug } = require("../../src/util"); +const { UP, flipStatus, log } = require("../../src/util"); +const StatusPage = require("../model/status_page"); let router = express.Router(); let cache = apicache.middleware; let io = server.io; -router.get("/api/entry-page", async (_, response) => { +router.get("/api/entry-page", async (request, response) => { allowDevAllOrigin(response); - response.json(server.entryPage); + + let result = { }; + + if (request.hostname in StatusPage.domainMappingList) { + result.type = "statusPageMatchedDomain"; + result.statusPageSlug = StatusPage.domainMappingList[request.hostname]; + } else { + result.type = "entryPage"; + result.entryPage = server.entryPage; + } + response.json(result); }); router.get("/api/push/:pushToken", async (request, response) => { @@ -51,8 +62,8 @@ router.get("/api/push/:pushToken", async (request, response) => { duration = dayjs(bean.time).diff(dayjs(previousHeartbeat.time), "second"); } - debug("PreviousStatus: " + previousStatus); - debug("Current Status: " + status); + log.debug("router", "PreviousStatus: " + previousStatus); + log.debug("router", "Current Status: " + status); bean.important = Monitor.isImportantBeat(isFirstBeat, previousStatus, status); bean.monitor_id = monitor.id; @@ -82,110 +93,80 @@ router.get("/api/push/:pushToken", async (request, response) => { } }); -// Status Page Config -router.get("/api/status-page/config", async (_request, response) => { +// Status page config, incident, monitor list +router.get("/api/status-page/:slug", cache("5 minutes"), async (request, response) => { allowDevAllOrigin(response); + let slug = request.params.slug; - let config = await getSettings("statusPage"); + // Get Status Page + let statusPage = await R.findOne("status_page", " slug = ? ", [ + slug + ]); - if (! config.statusPageTheme) { - config.statusPageTheme = "light"; + if (!statusPage) { + response.statusCode = 404; + response.json({ + msg: "Not Found" + }); + return; } - if (! config.statusPagePublished) { - config.statusPagePublished = true; - } - - if (! config.statusPageTags) { - config.statusPageTags = false; - } - - if (! config.title) { - config.title = "Uptime Kuma"; - } - - response.json(config); -}); - -// Status Page - Get the current Incident -// Can fetch only if published -router.get("/api/status-page/incident", async (_, response) => { - allowDevAllOrigin(response); - try { - await checkPublished(); - - let incident = await R.findOne("incident", " pin = 1 AND active = 1"); + // Incident + let incident = await R.findOne("incident", " pin = 1 AND active = 1 AND status_page_id = ? ", [ + statusPage.id, + ]); if (incident) { incident = incident.toPublicJSON(); } + // Public Group List + const publicGroupList = []; + const showTags = !!statusPage.show_tags; + + const list = await R.find("group", " public = 1 AND status_page_id = ? ORDER BY weight ", [ + statusPage.id + ]); + + for (let groupBean of list) { + let monitorGroup = await groupBean.toPublicJSON(showTags); + publicGroupList.push(monitorGroup); + } + + // Response response.json({ - ok: true, + config: await statusPage.toPublicJSON(), incident, + publicGroupList }); } catch (error) { send403(response, error.message); } -}); -// Status Page - Monitor List -// Can fetch only if published -router.get("/api/status-page/monitor-list", cache("5 minutes"), async (_request, response) => { - allowDevAllOrigin(response); - - try { - await checkPublished(); - const publicGroupList = []; - const tagsVisible = (await getSettings("statusPage")).statusPageTags; - const list = await R.find("group", " public = 1 ORDER BY weight "); - for (let groupBean of list) { - let monitorGroup = await groupBean.toPublicJSON(); - if (tagsVisible) { - monitorGroup.monitorList = await Promise.all(monitorGroup.monitorList.map(async (monitor) => { - // Includes tags as an array in response, allows for tags to be displayed on public status page - const tags = await R.getAll( - `SELECT monitor_tag.monitor_id, monitor_tag.value, tag.name, tag.color - FROM monitor_tag - JOIN tag - ON monitor_tag.tag_id = tag.id - WHERE monitor_tag.monitor_id = ?`, [monitor.id] - ); - return { - ...monitor, - tags: tags - }; - })); - } - - publicGroupList.push(monitorGroup); - } - - response.json(publicGroupList); - - } catch (error) { - send403(response, error.message); - } }); // Status Page Polling Data // Can fetch only if published -router.get("/api/status-page/heartbeat", cache("5 minutes"), async (_request, response) => { +router.get("/api/status-page/heartbeat/:slug", cache("1 minutes"), async (request, response) => { allowDevAllOrigin(response); try { - await checkPublished(); - let heartbeatList = {}; let uptimeList = {}; + let slug = request.params.slug; + let statusPageID = await StatusPage.slugToID(slug); + let monitorIDList = await R.getCol(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND public = 1 - `); + AND \`group\`.status_page_id = ? + `, [ + statusPageID + ]); for (let monitorID of monitorIDList) { let list = await R.getAll(` @@ -214,22 +195,12 @@ router.get("/api/status-page/heartbeat", cache("5 minutes"), async (_request, re } }); -async function checkPublished() { - if (! await isPublished()) { - throw new Error("The status page is not published"); - } -} - /** * Default is published * @returns {Promise} */ async function isPublished() { - const value = await setting("statusPagePublished"); - if (value === null) { - return true; - } - return value; + return true; } function send403(res, msg = "") { diff --git a/server/server.js b/server/server.js index 951fd76f8..82c014ea0 100644 --- a/server/server.js +++ b/server/server.js @@ -1,85 +1,122 @@ console.log("Welcome to Uptime Kuma"); + +// Check Node.js Version +const nodeVersion = parseInt(process.versions.node.split(".")[0]); +const requiredVersion = 14; +console.log(`Your Node.js version: ${nodeVersion}`); + +if (nodeVersion < requiredVersion) { + console.error(`Error: Your Node.js version is not supported, please upgrade to Node.js >= ${requiredVersion}.`); + process.exit(-1); +} + const args = require("args-parser")(process.argv); -const { sleep, debug, getRandomInt, genSecret } = require("../src/util"); +const { sleep, log, getRandomInt, genSecret, debug } = require("../src/util"); const config = require("./config"); -debug(args); +log.info("server", "Welcome to Uptime Kuma"); +log.debug("server", "Arguments"); +log.debug("server", args); if (! process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } -console.log("Node Env: " + process.env.NODE_ENV); +log.info("server", "Node Env: " + process.env.NODE_ENV); -console.log("Importing Node libraries"); +log.info("server", "Importing Node libraries"); const fs = require("fs"); const http = require("http"); const https = require("https"); -console.log("Importing 3rd-party libraries"); -debug("Importing express"); +log.info("server", "Importing 3rd-party libraries"); +log.debug("server", "Importing express"); const express = require("express"); -debug("Importing socket.io"); +log.debug("server", "Importing socket.io"); const { Server } = require("socket.io"); -debug("Importing redbean-node"); +log.debug("server", "Importing redbean-node"); const { R } = require("redbean-node"); -debug("Importing jsonwebtoken"); +log.debug("server", "Importing jsonwebtoken"); const jwt = require("jsonwebtoken"); -debug("Importing http-graceful-shutdown"); +log.debug("server", "Importing http-graceful-shutdown"); const gracefulShutdown = require("http-graceful-shutdown"); -debug("Importing prometheus-api-metrics"); +log.debug("server", "Importing prometheus-api-metrics"); const prometheusAPIMetrics = require("prometheus-api-metrics"); -debug("Importing compare-versions"); +log.debug("server", "Importing compare-versions"); const compareVersions = require("compare-versions"); const { passwordStrength } = require("check-password-strength"); -debug("Importing 2FA Modules"); +log.debug("server", "Importing 2FA Modules"); const notp = require("notp"); const base32 = require("thirty-two"); -console.log("Importing this project modules"); -debug("Importing Monitor"); -const Monitor = require("./model/monitor"); -debug("Importing Settings"); -const { getSettings, setSettings, setting, initJWTSecret, checkLogin, startUnitTest, FBSD, errorLog } = require("./util-server"); +/** + * `module.exports` (alias: `server`) should be inside this class, in order to avoid circular dependency issue. + * @type {UptimeKumaServer} + */ +class UptimeKumaServer { + /** + * Main monitor list + * @type {{}} + */ + monitorList = {}; + entryPage = "dashboard"; -debug("Importing Notification"); + async sendMonitorList(socket) { + let list = await getMonitorJSONList(socket.userID); + io.to(socket.userID).emit("monitorList", list); + return list; + } +} + +const server = module.exports = new UptimeKumaServer(); + +log.info("server", "Importing this project modules"); +log.debug("server", "Importing Monitor"); +const Monitor = require("./model/monitor"); +log.debug("server", "Importing Settings"); +const { getSettings, setSettings, setting, initJWTSecret, checkLogin, startUnitTest, FBSD, errorLog, doubleCheckPassword } = require("./util-server"); + +log.debug("server", "Importing Notification"); const { Notification } = require("./notification"); Notification.init(); -debug("Importing Database"); +log.debug("server", "Importing Proxy"); +const { Proxy } = require("./proxy"); + +log.debug("server", "Importing Database"); const Database = require("./database"); -debug("Importing Background Jobs"); -const { initBackgroundJobs } = require("./jobs"); -const { loginRateLimiter } = require("./rate-limiter"); +log.debug("server", "Importing Background Jobs"); +const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs"); +const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter"); const { basicAuth } = require("./auth"); const { login } = require("./auth"); const passwordHash = require("./password-hash"); const checkVersion = require("./check-version"); -console.info("Version: " + checkVersion.version); +log.info("server", "Version: " + checkVersion.version); // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available and the unspecified IPv4 address (0.0.0.0) otherwise. // Dual-stack support for (::) -let hostname = process.env.UPTIME_KUMA_HOST || args.host; - // Also read HOST if not FreeBSD, as HOST is a system environment variable in FreeBSD -if (!hostname && !FBSD) { - hostname = process.env.HOST; -} +let hostEnv = FBSD ? null : process.env.HOST; +let hostname = args.host || process.env.UPTIME_KUMA_HOST || hostEnv; if (hostname) { - console.log("Custom hostname: " + hostname); + log.info("server", "Custom hostname: " + hostname); } -const port = parseInt(process.env.UPTIME_KUMA_PORT || process.env.PORT || args.port || 3001); +const port = [args.port, process.env.UPTIME_KUMA_PORT, process.env.PORT, 3001] + .map(portValue => parseInt(portValue)) + .find(portValue => !isNaN(portValue)); // SSL -const sslKey = process.env.UPTIME_KUMA_SSL_KEY || process.env.SSL_KEY || args["ssl-key"] || undefined; -const sslCert = process.env.UPTIME_KUMA_SSL_CERT || process.env.SSL_CERT || args["ssl-cert"] || undefined; -const disableFrameSameOrigin = !!process.env.UPTIME_KUMA_DISABLE_FRAME_SAMEORIGIN || args["disable-frame-sameorigin"] || false; +const sslKey = args["ssl-key"] || process.env.UPTIME_KUMA_SSL_KEY || process.env.SSL_KEY || undefined; +const sslCert = args["ssl-cert"] || process.env.UPTIME_KUMA_SSL_CERT || process.env.SSL_CERT || undefined; +const disableFrameSameOrigin = args["disable-frame-sameorigin"] || !!process.env.UPTIME_KUMA_DISABLE_FRAME_SAMEORIGIN || false; +const cloudflaredToken = args["cloudflared-token"] || process.env.UPTIME_KUMA_CLOUDFLARED_TOKEN || undefined; // 2FA / notp verification defaults const twofa_verification_opts = { @@ -94,33 +131,36 @@ const twofa_verification_opts = { const testMode = !!args["test"] || false; if (config.demoMode) { - console.log("==== Demo Mode ===="); + log.info("server", "==== Demo Mode ===="); } -console.log("Creating express and socket.io instance"); +log.info("server", "Creating express and socket.io instance"); const app = express(); -let server; +let httpServer; if (sslKey && sslCert) { - console.log("Server Type: HTTPS"); - server = https.createServer({ + log.info("server", "Server Type: HTTPS"); + httpServer = https.createServer({ key: fs.readFileSync(sslKey), cert: fs.readFileSync(sslCert) }, app); } else { - console.log("Server Type: HTTP"); - server = http.createServer(app); + log.info("server", "Server Type: HTTP"); + httpServer = http.createServer(app); } -const io = new Server(server); +const io = new Server(httpServer); module.exports.io = io; // Must be after io instantiation -const { sendNotificationList, sendHeartbeatList, sendImportantHeartbeatList, sendInfo } = require("./client"); +const { sendNotificationList, sendHeartbeatList, sendImportantHeartbeatList, sendInfo, sendProxyList } = require("./client"); const { statusPageSocketHandler } = require("./socket-handlers/status-page-socket-handler"); const databaseSocketHandler = require("./socket-handlers/database-socket-handler"); const TwoFA = require("./2fa"); +const StatusPage = require("./model/status_page"); +const { cloudflaredSocketHandler, autoStart: cloudflaredAutoStart, stop: cloudflaredStop } = require("./socket-handlers/cloudflared-socket-handler"); +const { proxySocketHandler } = require("./socket-handlers/proxy-socket-handler"); app.use(express.json()); @@ -145,12 +185,6 @@ let totalClient = 0; */ let jwtSecret = null; -/** - * Main monitor list - * @type {{}} - */ -let monitorList = {}; - /** * Show Setup Page * @type {boolean} @@ -168,29 +202,33 @@ try { } catch (e) { // "dist/index.html" is not necessary for development if (process.env.NODE_ENV !== "development") { - console.error("Error: Cannot find 'dist/index.html', did you install correctly?"); + log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); process.exit(1); } } -exports.entryPage = "dashboard"; - (async () => { Database.init(args); await initDatabase(testMode); exports.entryPage = await setting("entryPage"); + await StatusPage.loadDomainMappingList(); - console.log("Adding route"); + log.info("server", "Adding route"); // *************************** // Normal Router here // *************************** // Entry Page - app.get("/", async (_request, response) => { - if (exports.entryPage === "statusPage") { - response.redirect("/status"); + app.get("/", async (request, response) => { + debug(`Request Domain: ${request.hostname}`); + + if (request.hostname in StatusPage.domainMappingList) { + debug("This is a status page domain"); + response.send(indexHTML); + } else if (exports.entryPage && exports.entryPage.startsWith("statusPage-")) { + response.redirect("/status/" + exports.entryPage.replace("statusPage-", "")); } else { response.redirect("/dashboard"); } @@ -234,7 +272,7 @@ exports.entryPage = "dashboard"; } }); - console.log("Adding socket handler"); + log.info("server", "Adding socket handler"); io.on("connection", async (socket) => { sendInfo(socket); @@ -242,7 +280,7 @@ exports.entryPage = "dashboard"; totalClient++; if (needSetup) { - console.log("Redirect to setup page"); + log.info("server", "Redirect to setup page"); socket.emit("setup"); } @@ -255,33 +293,40 @@ exports.entryPage = "dashboard"; // *************************** socket.on("loginByToken", async (token, callback) => { + log.info("auth", `Login by token. IP=${getClientIp(socket)}`); try { let decoded = jwt.verify(token, jwtSecret); - console.log("Username from JWT: " + decoded.username); + log.info("auth", "Username from JWT: " + decoded.username); let user = await R.findOne("user", " username = ? AND active = 1 ", [ decoded.username, ]); if (user) { - debug("afterLogin"); - + log.debug("auth", "afterLogin"); afterLogin(socket, user); + log.debug("auth", "afterLogin ok"); - debug("afterLogin ok"); + log.info("auth", `Successfully logged in user ${decoded.username}. IP=${getClientIp(socket)}`); callback({ ok: true, }); } else { + + log.info("auth", `Inactive or deleted user ${decoded.username}. IP=${getClientIp(socket)}`); + callback({ ok: false, msg: "The user is inactive or deleted.", }); } } catch (error) { + + log.error("auth", `Invalid token. IP=${getClientIp(socket)}`); + callback({ ok: false, msg: "Invalid token.", @@ -291,10 +336,20 @@ exports.entryPage = "dashboard"; }); socket.on("login", async (data, callback) => { - console.log("Login"); + log.info("auth", `Login by username + password. IP=${getClientIp(socket)}`); + + // Checking + if (typeof callback !== "function") { + return; + } + + if (!data) { + return; + } // Login Rate Limit if (! await loginRateLimiter.pass(callback)) { + log.info("auth", `Too many failed requests for user ${data.username}. IP=${getClientIp(socket)}`); return; } @@ -303,6 +358,9 @@ exports.entryPage = "dashboard"; if (user) { if (user.twofa_status == 0) { afterLogin(socket, user); + + log.info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); + callback({ ok: true, token: jwt.sign({ @@ -312,6 +370,9 @@ exports.entryPage = "dashboard"; } if (user.twofa_status == 1 && !data.token) { + + log.info("auth", `2FA token required for user ${data.username}. IP=${getClientIp(socket)}`); + callback({ tokenRequired: true, }); @@ -328,6 +389,8 @@ exports.entryPage = "dashboard"; socket.userID, ]); + log.info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); + callback({ ok: true, token: jwt.sign({ @@ -335,6 +398,9 @@ exports.entryPage = "dashboard"; }, jwtSecret), }); } else { + + log.warn("auth", `Invalid token provided for user ${data.username}. IP=${getClientIp(socket)}`); + callback({ ok: false, msg: "Invalid Token!", @@ -342,6 +408,9 @@ exports.entryPage = "dashboard"; } } } else { + + log.warn("auth", `Incorrect username or password for user ${data.username}. IP=${getClientIp(socket)}`); + callback({ ok: false, msg: "Incorrect username or password.", @@ -351,14 +420,27 @@ exports.entryPage = "dashboard"; }); socket.on("logout", async (callback) => { + // Rate Limit + if (! await loginRateLimiter.pass(callback)) { + return; + } + socket.leave(socket.userID); socket.userID = null; - callback(); + + if (typeof callback === "function") { + callback(); + } }); - socket.on("prepare2FA", async (callback) => { + socket.on("prepare2FA", async (currentPassword, callback) => { try { + if (! await twoFaRateLimiter.pass(callback)) { + return; + } + checkLogin(socket); + await doubleCheckPassword(socket, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -393,73 +475,104 @@ exports.entryPage = "dashboard"; } catch (error) { callback({ ok: false, - msg: "Error while trying to prepare 2FA.", + msg: error.message, }); } }); - socket.on("save2FA", async (callback) => { + socket.on("save2FA", async (currentPassword, callback) => { try { + if (! await twoFaRateLimiter.pass(callback)) { + return; + } + checkLogin(socket); + await doubleCheckPassword(socket, currentPassword); await R.exec("UPDATE `user` SET twofa_status = 1 WHERE id = ? ", [ socket.userID, ]); + log.info("auth", `Saved 2FA token. IP=${getClientIp(socket)}`); + callback({ ok: true, msg: "2FA Enabled.", }); } catch (error) { + + log.error("auth", `Error changing 2FA token. IP=${getClientIp(socket)}`); + callback({ ok: false, - msg: "Error while trying to change 2FA.", + msg: error.message, }); } }); - socket.on("disable2FA", async (callback) => { + socket.on("disable2FA", async (currentPassword, callback) => { try { + if (! await twoFaRateLimiter.pass(callback)) { + return; + } + checkLogin(socket); + await doubleCheckPassword(socket, currentPassword); await TwoFA.disable2FA(socket.userID); + log.info("auth", `Disabled 2FA token. IP=${getClientIp(socket)}`); + callback({ ok: true, msg: "2FA Disabled.", }); } catch (error) { + + log.error("auth", `Error disabling 2FA token. IP=${getClientIp(socket)}`); + callback({ ok: false, - msg: "Error while trying to change 2FA.", + msg: error.message, }); } }); - socket.on("verifyToken", async (token, callback) => { - let user = await R.findOne("user", " id = ? AND active = 1 ", [ - socket.userID, - ]); + socket.on("verifyToken", async (token, currentPassword, callback) => { + try { + checkLogin(socket); + await doubleCheckPassword(socket, currentPassword); - let verify = notp.totp.verify(token, user.twofa_secret, twofa_verification_opts); + let user = await R.findOne("user", " id = ? AND active = 1 ", [ + socket.userID, + ]); - if (user.twofa_last_token !== token && verify) { - callback({ - ok: true, - valid: true, - }); - } else { + let verify = notp.totp.verify(token, user.twofa_secret, twofa_verification_opts); + + if (user.twofa_last_token !== token && verify) { + callback({ + ok: true, + valid: true, + }); + } else { + callback({ + ok: false, + msg: "Invalid Token.", + valid: false, + }); + } + + } catch (error) { callback({ ok: false, - msg: "Invalid Token.", - valid: false, + msg: error.message, }); } }); socket.on("twoFAStatus", async (callback) => { - checkLogin(socket); - try { + checkLogin(socket); + let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, ]); @@ -476,9 +589,10 @@ exports.entryPage = "dashboard"; }); } } catch (error) { + console.log(error); callback({ ok: false, - msg: "Error while trying to get 2FA status.", + msg: error.message, }); } }); @@ -539,9 +653,11 @@ exports.entryPage = "dashboard"; await updateMonitorNotification(bean.id, notificationIDList); - await sendMonitorList(socket); + await server.sendMonitorList(socket); await startMonitor(socket.userID, bean.id); + log.info("monitor", `Added Monitor: ${monitor.id} User ID: ${socket.userID}`); + callback({ ok: true, msg: "Added Successfully.", @@ -549,6 +665,9 @@ exports.entryPage = "dashboard"; }); } catch (e) { + + log.error("monitor", `Error adding Monitor: ${monitor.id} User ID: ${socket.userID}`); + callback({ ok: false, msg: e.message, @@ -567,6 +686,9 @@ exports.entryPage = "dashboard"; throw new Error("Permission denied."); } + // Reset Prometheus labels + server.monitorList[monitor.id]?.prometheus()?.remove(); + bean.name = monitor.name; bean.type = monitor.type; bean.url = monitor.url; @@ -582,12 +704,14 @@ exports.entryPage = "dashboard"; bean.port = monitor.port; bean.keyword = monitor.keyword; bean.ignoreTls = monitor.ignoreTls; + bean.expiryNotification = monitor.expiryNotification; bean.upsideDown = monitor.upsideDown; bean.maxredirects = monitor.maxredirects; bean.accepted_statuscodes_json = JSON.stringify(monitor.accepted_statuscodes); bean.dns_resolve_type = monitor.dns_resolve_type; bean.dns_resolve_server = monitor.dns_resolve_server; bean.pushToken = monitor.pushToken; + bean.proxyId = Number.isInteger(monitor.proxyId) ? monitor.proxyId : null; bean.mqttUsername = monitor.mqttUsername; bean.mqttTopic = monitor.mqttTopic; bean.mqttSuccessMessage = monitor.mqttSuccessMessage; @@ -600,7 +724,7 @@ exports.entryPage = "dashboard"; await restartMonitor(socket.userID, bean.id); } - await sendMonitorList(socket); + await server.sendMonitorList(socket); callback({ ok: true, @@ -609,7 +733,7 @@ exports.entryPage = "dashboard"; }); } catch (e) { - console.error(e); + log.error("monitor", e); callback({ ok: false, msg: e.message, @@ -620,12 +744,12 @@ exports.entryPage = "dashboard"; socket.on("getMonitorList", async (callback) => { try { checkLogin(socket); - await sendMonitorList(socket); + await server.sendMonitorList(socket); callback({ ok: true, }); } catch (e) { - console.error(e); + log.error("monitor", e); callback({ ok: false, msg: e.message, @@ -637,7 +761,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Get Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`); let bean = await R.findOne("monitor", " id = ? AND user_id = ? ", [ monitorID, @@ -661,7 +785,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Get Monitor Beats: ${monitorID} User ID: ${socket.userID}`); + log.info("monitor", `Get Monitor Beats: ${monitorID} User ID: ${socket.userID}`); if (period == null) { throw new Error("Invalid period."); @@ -694,7 +818,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); await startMonitor(socket.userID, monitorID); - await sendMonitorList(socket); + await server.sendMonitorList(socket); callback({ ok: true, @@ -713,7 +837,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); await pauseMonitor(socket.userID, monitorID); - await sendMonitorList(socket); + await server.sendMonitorList(socket); callback({ ok: true, @@ -732,11 +856,11 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Delete Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`); - if (monitorID in monitorList) { - monitorList[monitorID].stop(); - delete monitorList[monitorID]; + if (monitorID in server.monitorList) { + server.monitorList[monitorID].stop(); + delete server.monitorList[monitorID]; } await R.exec("DELETE FROM monitor WHERE id = ? AND user_id = ? ", [ @@ -749,7 +873,7 @@ exports.entryPage = "dashboard"; msg: "Deleted Successfully.", }); - await sendMonitorList(socket); + await server.sendMonitorList(socket); // Clear heartbeat list on client await sendImportantHeartbeatList(socket, monitorID, true, true); @@ -927,21 +1051,13 @@ exports.entryPage = "dashboard"; throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length."); } - let user = await R.findOne("user", " id = ? AND active = 1 ", [ - socket.userID, - ]); + let user = await doubleCheckPassword(socket, password.currentPassword); + await user.resetPassword(password.newPassword); - if (user && passwordHash.verify(password.currentPassword, user.password)) { - - user.resetPassword(password.newPassword); - - callback({ - ok: true, - msg: "Password has been updated successfully.", - }); - } else { - throw new Error("Incorrect current password"); - } + callback({ + ok: true, + msg: "Password has been updated successfully.", + }); } catch (e) { callback({ @@ -968,10 +1084,14 @@ exports.entryPage = "dashboard"; } }); - socket.on("setSettings", async (data, callback) => { + socket.on("setSettings", async (data, currentPassword, callback) => { try { checkLogin(socket); + if (data.disableAuth) { + await doubleCheckPassword(socket, currentPassword); + } + await setSettings("general", data); exports.entryPage = data.entryPage; @@ -1068,9 +1188,10 @@ exports.entryPage = "dashboard"; let backupData = JSON.parse(uploadedJSON); - console.log(`Importing Backup, User ID: ${socket.userID}, Version: ${backupData.version}`); + log.info("manage", `Importing Backup, User ID: ${socket.userID}, Version: ${backupData.version}`); let notificationListData = backupData.notificationList; + let proxyListData = backupData.proxyList; let monitorListData = backupData.monitorList; let version17x = compareVersions.compare(backupData.version, "1.7.0", ">="); @@ -1078,8 +1199,8 @@ exports.entryPage = "dashboard"; // If the import option is "overwrite" it'll clear most of the tables, except "settings" and "user" if (importHandle == "overwrite") { // Stops every monitor first, so it doesn't execute any heartbeat while importing - for (let id in monitorList) { - let monitor = monitorList[id]; + for (let id in server.monitorList) { + let monitor = server.monitorList[id]; await monitor.stop(); } await R.exec("DELETE FROM heartbeat"); @@ -1089,6 +1210,7 @@ exports.entryPage = "dashboard"; await R.exec("DELETE FROM monitor_tag"); await R.exec("DELETE FROM tag"); await R.exec("DELETE FROM monitor"); + await R.exec("DELETE FROM proxy"); } // Only starts importing if the backup file contains at least one notification @@ -1108,6 +1230,24 @@ exports.entryPage = "dashboard"; } } + // Only starts importing if the backup file contains at least one proxy + if (proxyListData && proxyListData.length >= 1) { + const proxies = await R.findAll("proxy"); + + // Loop over proxy list and save proxies + for (const proxy of proxyListData) { + const exists = proxies.find(item => item.id === proxy.id); + + // Do not process when proxy already exists in import handle is skip and keep + if (["skip", "keep"].includes(importHandle) && !exists) { + return; + } + + // Save proxy as new entry if exists update exists one + await Proxy.save(proxy, exists ? proxy.id : undefined, proxy.userId); + } + } + // Only starts importing if the backup file contains at least one monitor if (monitorListData.length >= 1) { // Get every existing monitor name and puts them in one simple string @@ -1157,6 +1297,7 @@ exports.entryPage = "dashboard"; dns_resolve_type: monitorListData[i].dns_resolve_type, dns_resolve_server: monitorListData[i].dns_resolve_server, notificationIDList: {}, + proxy_id: monitorListData[i].proxy_id || null, }; if (monitorListData[i].pushToken) { @@ -1222,7 +1363,7 @@ exports.entryPage = "dashboard"; } await sendNotificationList(socket); - await sendMonitorList(socket); + await server.sendMonitorList(socket); } callback({ @@ -1242,7 +1383,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Clear Events Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Clear Events Monitor: ${monitorID} User ID: ${socket.userID}`); await R.exec("UPDATE heartbeat SET msg = ?, important = ? WHERE monitor_id = ? ", [ "", @@ -1268,7 +1409,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Clear Heartbeats Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Clear Heartbeats Monitor: ${monitorID} User ID: ${socket.userID}`); await R.exec("DELETE FROM heartbeat WHERE monitor_id = ?", [ monitorID @@ -1292,7 +1433,7 @@ exports.entryPage = "dashboard"; try { checkLogin(socket); - console.log(`Clear Statistics User ID: ${socket.userID}`); + log.info("manage", `Clear Statistics User ID: ${socket.userID}`); await R.exec("DELETE FROM heartbeat"); @@ -1310,37 +1451,39 @@ exports.entryPage = "dashboard"; // Status Page Socket Handler for admin only statusPageSocketHandler(socket); + cloudflaredSocketHandler(socket); databaseSocketHandler(socket); + proxySocketHandler(socket); - debug("added all socket handlers"); + log.debug("server", "added all socket handlers"); // *************************** // Better do anything after added all socket handlers here // *************************** - debug("check auto login"); + log.debug("auth", "check auto login"); if (await setting("disableAuth")) { - console.log("Disabled Auth: auto login to admin"); + log.info("auth", "Disabled Auth: auto login to admin"); afterLogin(socket, await R.findOne("user")); socket.emit("autoLogin"); } else { - debug("need auth"); + log.debug("auth", "need auth"); } }); - console.log("Init the server"); + log.info("server", "Init the server"); - server.once("error", async (err) => { + httpServer.once("error", async (err) => { console.error("Cannot listen: " + err.message); - await Database.close(); + await shutdownFunction(); }); - server.listen(port, hostname, () => { + httpServer.listen(port, hostname, () => { if (hostname) { - console.log(`Listening on ${hostname}:${port}`); + log.info("server", `Listening on ${hostname}:${port}`); } else { - console.log(`Listening on ${port}`); + log.info("server", `Listening on ${port}`); } startMonitors(); checkVersion.startInterval(); @@ -1352,8 +1495,18 @@ exports.entryPage = "dashboard"; initBackgroundJobs(args); + // Start cloudflared at the end if configured + await cloudflaredAutoStart(cloudflaredToken); + })(); +/** + * Adds or removes notifications from a monitor. + * @param {number} monitorID The ID of the monitor to add/remove notifications from. + * @param {Array.} notificationIDList An array of IDs for the notifications to add/remove. + * + * Generated by Trelent + */ async function updateMonitorNotification(monitorID, notificationIDList) { await R.exec("DELETE FROM monitor_notification WHERE monitor_id = ? ", [ monitorID, @@ -1369,6 +1522,13 @@ async function updateMonitorNotification(monitorID, notificationIDList) { } } +/** + * This function checks if the user owns a monitor with the given ID. + * @param {number} monitorID - The ID of the monitor to check ownership for. + * @param {number} userID - The ID of the user who is trying to access this data. + * + * Generated by Trelent + */ async function checkOwner(userID, monitorID) { let row = await R.getRow("SELECT id FROM monitor WHERE id = ? AND user_id = ? ", [ monitorID, @@ -1380,21 +1540,22 @@ async function checkOwner(userID, monitorID) { } } -async function sendMonitorList(socket) { - let list = await getMonitorJSONList(socket.userID); - io.to(socket.userID).emit("monitorList", list); - return list; -} - +/** + * This function is used to send the heartbeat list of a monitor. + * @param {Socket} socket - The socket object that will be used to send the data. + */ async function afterLogin(socket, user) { socket.userID = user.id; socket.join(user.id); - let monitorList = await sendMonitorList(socket); + let monitorList = await server.sendMonitorList(socket); sendNotificationList(socket); + sendProxyList(socket); await sleep(500); + await StatusPage.sendStatusPageList(io, socket); + for (let monitorID in monitorList) { await sendHeartbeatList(socket, monitorID); } @@ -1408,6 +1569,13 @@ async function afterLogin(socket, user) { } } +/** + * Get a list of monitors for the given user. + * @param {string} userID - The ID of the user to get monitors for. + * @returns {Promise} A promise that resolves to an object with monitor IDs as keys and monitor objects as values. + * + * Generated by Trelent + */ async function getMonitorJSONList(userID) { let result = {}; @@ -1422,15 +1590,20 @@ async function getMonitorJSONList(userID) { return result; } +/** + * Connect to the database and patch it if necessary. + * + * Generated by Trelent + */ async function initDatabase(testMode = false) { if (! fs.existsSync(Database.path)) { - console.log("Copying Database"); + log.info("server", "Copying Database"); fs.copyFileSync(Database.templatePath, Database.path); } - console.log("Connecting to the Database"); + log.info("server", "Connecting to the Database"); await Database.connect(testMode); - console.log("Connected"); + log.info("server", "Connected"); // Patch the database await Database.patch(); @@ -1440,26 +1613,33 @@ async function initDatabase(testMode = false) { ]); if (! jwtSecretBean) { - console.log("JWT secret is not found, generate one."); + log.info("server", "JWT secret is not found, generate one."); jwtSecretBean = await initJWTSecret(); - console.log("Stored JWT secret into database"); + log.info("server", "Stored JWT secret into database"); } else { - console.log("Load JWT secret from database."); + log.info("server", "Load JWT secret from database."); } // If there is no record in user table, it is a new Uptime Kuma instance, need to setup if ((await R.count("user")) === 0) { - console.log("No user, need setup"); + log.info("server", "No user, need setup"); needSetup = true; } jwtSecret = jwtSecretBean.value; } +/** + * Resume a monitor. + * @param {string} userID - The ID of the user who owns the monitor. + * @param {string} monitorID - The ID of the monitor to resume. + * + * Generated by Trelent + */ async function startMonitor(userID, monitorID) { await checkOwner(userID, monitorID); - console.log(`Resume Monitor: ${monitorID} User ID: ${userID}`); + log.info("manage", `Resume Monitor: ${monitorID} User ID: ${userID}`); await R.exec("UPDATE monitor SET active = 1 WHERE id = ? AND user_id = ? ", [ monitorID, @@ -1470,11 +1650,11 @@ async function startMonitor(userID, monitorID) { monitorID, ]); - if (monitor.id in monitorList) { - monitorList[monitor.id].stop(); + if (monitor.id in server.monitorList) { + server.monitorList[monitor.id].stop(); } - monitorList[monitor.id] = monitor; + server.monitorList[monitor.id] = monitor; monitor.start(io); } @@ -1482,18 +1662,25 @@ async function restartMonitor(userID, monitorID) { return await startMonitor(userID, monitorID); } +/** + * Pause a monitor. + * @param {string} userID - The ID of the user who owns the monitor. + * @param {string} monitorID - The ID of the monitor to pause. + * + * Generated by Trelent + */ async function pauseMonitor(userID, monitorID) { await checkOwner(userID, monitorID); - console.log(`Pause Monitor: ${monitorID} User ID: ${userID}`); + log.info("manage", `Pause Monitor: ${monitorID} User ID: ${userID}`); await R.exec("UPDATE monitor SET active = 0 WHERE id = ? AND user_id = ? ", [ monitorID, userID, ]); - if (monitorID in monitorList) { - monitorList[monitorID].stop(); + if (monitorID in server.monitorList) { + server.monitorList[monitorID].stop(); } } @@ -1504,7 +1691,7 @@ async function startMonitors() { let list = await R.find("monitor", " active = 1 "); for (let monitor of list) { - monitorList[monitor.id] = monitor; + server.monitorList[monitor.id] = monitor; } for (let monitor of list) { @@ -1514,24 +1701,37 @@ async function startMonitors() { } } +/** + * Stops all monitors and closes the database connection. + * @param {string} signal The signal that triggered this function to be called. + * + * Generated by Trelent + */ async function shutdownFunction(signal) { - console.log("Shutdown requested"); - console.log("Called signal: " + signal); + log.info("server", "Shutdown requested"); + log.info("server", "Called signal: " + signal); - console.log("Stopping all monitors"); - for (let id in monitorList) { - let monitor = monitorList[id]; + log.info("server", "Stopping all monitors"); + for (let id in server.monitorList) { + let monitor = server.monitorList[id]; monitor.stop(); } await sleep(2000); await Database.close(); + + stopBackgroundJobs(); + await cloudflaredStop(); +} + +function getClientIp(socket) { + return socket.client.conn.remoteAddress.replace(/^.*:/, ""); } function finalFunction() { - console.log("Graceful shutdown successful!"); + log.info("server", "Graceful shutdown successful!"); } -gracefulShutdown(server, { +gracefulShutdown(httpServer, { signals: "SIGINT SIGTERM", timeout: 30000, // timeout: 30 secs development: false, // not in dev mode diff --git a/server/socket-handlers/cloudflared-socket-handler.js b/server/socket-handlers/cloudflared-socket-handler.js new file mode 100644 index 000000000..37c12256d --- /dev/null +++ b/server/socket-handlers/cloudflared-socket-handler.js @@ -0,0 +1,90 @@ +const { checkLogin, setSetting, setting, doubleCheckPassword } = require("../util-server"); +const { CloudflaredTunnel } = require("node-cloudflared-tunnel"); +const { io } = require("../server"); + +const prefix = "cloudflared_"; +const cloudflared = new CloudflaredTunnel(); + +cloudflared.change = (running, message) => { + io.to("cloudflared").emit(prefix + "running", running); + io.to("cloudflared").emit(prefix + "message", message); +}; + +cloudflared.error = (errorMessage) => { + io.to("cloudflared").emit(prefix + "errorMessage", errorMessage); +}; + +module.exports.cloudflaredSocketHandler = (socket) => { + + socket.on(prefix + "join", async () => { + try { + checkLogin(socket); + socket.join("cloudflared"); + io.to(socket.userID).emit(prefix + "installed", cloudflared.checkInstalled()); + io.to(socket.userID).emit(prefix + "running", cloudflared.running); + io.to(socket.userID).emit(prefix + "token", await setting("cloudflaredTunnelToken")); + } catch (error) { } + }); + + socket.on(prefix + "leave", async () => { + try { + checkLogin(socket); + socket.leave("cloudflared"); + } catch (error) { } + }); + + socket.on(prefix + "start", async (token) => { + try { + checkLogin(socket); + if (token && typeof token === "string") { + await setSetting("cloudflaredTunnelToken", token); + cloudflared.token = token; + } else { + cloudflared.token = null; + } + cloudflared.start(); + } catch (error) { } + }); + + socket.on(prefix + "stop", async (currentPassword, callback) => { + try { + checkLogin(socket); + await doubleCheckPassword(socket, currentPassword); + cloudflared.stop(); + } catch (error) { + callback({ + ok: false, + msg: error.message, + }); + } + }); + + socket.on(prefix + "removeToken", async () => { + try { + checkLogin(socket); + await setSetting("cloudflaredTunnelToken", ""); + } catch (error) { } + }); + +}; + +module.exports.autoStart = async (token) => { + if (!token) { + token = await setting("cloudflaredTunnelToken"); + } else { + // Override the current token via args or env var + await setSetting("cloudflaredTunnelToken", token); + console.log("Use cloudflared token from args or env var"); + } + + if (token) { + console.log("Start cloudflared"); + cloudflared.token = token; + cloudflared.start(); + } +}; + +module.exports.stop = async () => { + console.log("Stop cloudflared"); + cloudflared.stop(); +}; diff --git a/server/socket-handlers/proxy-socket-handler.js b/server/socket-handlers/proxy-socket-handler.js new file mode 100644 index 000000000..817bdd49e --- /dev/null +++ b/server/socket-handlers/proxy-socket-handler.js @@ -0,0 +1,53 @@ +const { checkLogin } = require("../util-server"); +const { Proxy } = require("../proxy"); +const { sendProxyList } = require("../client"); +const server = require("../server"); + +module.exports.proxySocketHandler = (socket) => { + socket.on("addProxy", async (proxy, proxyID, callback) => { + try { + checkLogin(socket); + + const proxyBean = await Proxy.save(proxy, proxyID, socket.userID); + await sendProxyList(socket); + + if (proxy.applyExisting) { + await Proxy.reloadProxy(); + await server.sendMonitorList(socket); + } + + callback({ + ok: true, + msg: "Saved", + id: proxyBean.id, + }); + + } catch (e) { + callback({ + ok: false, + msg: e.message, + }); + } + }); + + socket.on("deleteProxy", async (proxyID, callback) => { + try { + checkLogin(socket); + + await Proxy.delete(proxyID, socket.userID); + await sendProxyList(socket); + await Proxy.reloadProxy(); + + callback({ + ok: true, + msg: "Deleted", + }); + + } catch (e) { + callback({ + ok: false, + msg: e.message, + }); + } + }); +}; diff --git a/server/socket-handlers/status-page-socket-handler.js b/server/socket-handlers/status-page-socket-handler.js index 5826277c7..36e90fb93 100644 --- a/server/socket-handlers/status-page-socket-handler.js +++ b/server/socket-handlers/status-page-socket-handler.js @@ -1,25 +1,36 @@ const { R } = require("redbean-node"); -const { checkLogin, setSettings } = require("../util-server"); +const { checkLogin, setSetting } = require("../util-server"); const dayjs = require("dayjs"); -const { debug } = require("../../src/util"); +const { log } = require("../../src/util"); const ImageDataURI = require("../image-data-uri"); const Database = require("../database"); const apicache = require("../modules/apicache"); +const StatusPage = require("../model/status_page"); +const server = require("../server"); module.exports.statusPageSocketHandler = (socket) => { // Post or edit incident - socket.on("postIncident", async (incident, callback) => { + socket.on("postIncident", async (slug, incident, callback) => { try { checkLogin(socket); - await R.exec("UPDATE incident SET pin = 0 "); + let statusPageID = await StatusPage.slugToID(slug); + + if (!statusPageID) { + throw new Error("slug is not found"); + } + + await R.exec("UPDATE incident SET pin = 0 WHERE status_page_id = ? ", [ + statusPageID + ]); let incidentBean; if (incident.id) { - incidentBean = await R.findOne("incident", " id = ?", [ - incident.id + incidentBean = await R.findOne("incident", " id = ? AND status_page_id = ? ", [ + incident.id, + statusPageID ]); } @@ -31,6 +42,7 @@ module.exports.statusPageSocketHandler = (socket) => { incidentBean.content = incident.content; incidentBean.style = incident.style; incidentBean.pin = true; + incidentBean.status_page_id = statusPageID; if (incident.id) { incidentBean.lastUpdatedDate = R.isoDateTime(dayjs.utc()); @@ -52,11 +64,15 @@ module.exports.statusPageSocketHandler = (socket) => { } }); - socket.on("unpinIncident", async (callback) => { + socket.on("unpinIncident", async (slug, callback) => { try { checkLogin(socket); - await R.exec("UPDATE incident SET pin = 0 WHERE pin = 1"); + let statusPageID = await StatusPage.slugToID(slug); + + await R.exec("UPDATE incident SET pin = 0 WHERE pin = 1 AND status_page_id = ? ", [ + statusPageID + ]); callback({ ok: true, @@ -69,14 +85,46 @@ module.exports.statusPageSocketHandler = (socket) => { } }); - // Save Status Page - // imgDataUrl Only Accept PNG! - socket.on("saveStatusPage", async (config, imgDataUrl, publicGroupList, callback) => { - + socket.on("getStatusPage", async (slug, callback) => { try { checkLogin(socket); - apicache.clear(); + let statusPage = await R.findOne("status_page", " slug = ? ", [ + slug + ]); + + if (!statusPage) { + throw new Error("No slug?"); + } + + callback({ + ok: true, + config: await statusPage.toJSON(), + }); + } catch (error) { + callback({ + ok: false, + msg: error.message, + }); + } + }); + + // Save Status Page + // imgDataUrl Only Accept PNG! + socket.on("saveStatusPage", async (slug, config, imgDataUrl, publicGroupList, callback) => { + try { + checkLogin(socket); + + // Save Config + let statusPage = await R.findOne("status_page", " slug = ? ", [ + slug + ]); + + if (!statusPage) { + throw new Error("No slug?"); + } + + checkSlug(config.slug); const header = "data:image/png;base64,"; @@ -88,16 +136,31 @@ module.exports.statusPageSocketHandler = (socket) => { throw new Error("Only allowed PNG logo."); } + const filename = `logo${statusPage.id}.png`; + // Convert to file - await ImageDataURI.outputFile(imgDataUrl, Database.uploadDir + "logo.png"); - config.logo = "/upload/logo.png?t=" + Date.now(); + await ImageDataURI.outputFile(imgDataUrl, Database.uploadDir + filename); + config.logo = `/upload/${filename}?t=` + Date.now(); } else { config.icon = imgDataUrl; } - // Save Config - await setSettings("statusPage", config); + statusPage.slug = config.slug; + statusPage.title = config.title; + statusPage.description = config.description; + statusPage.icon = config.logo; + statusPage.theme = config.theme; + //statusPage.published = ; + //statusPage.search_engine_index = ; + statusPage.show_tags = config.showTags; + //statusPage.password = null; + statusPage.modified_date = R.isoDateTime(); + + await R.store(statusPage); + + await statusPage.updateDomainNameList(config.domainNameList); + await StatusPage.loadDomainMappingList(); // Save Public Group List const groupIDList = []; @@ -106,13 +169,15 @@ module.exports.statusPageSocketHandler = (socket) => { for (let group of publicGroupList) { let groupBean; if (group.id) { - groupBean = await R.findOne("group", " id = ? AND public = 1 ", [ - group.id + groupBean = await R.findOne("group", " id = ? AND public = 1 AND status_page_id = ? ", [ + group.id, + statusPage.id ]); } else { groupBean = R.dispense("group"); } + groupBean.status_page_id = statusPage.id; groupBean.name = group.name; groupBean.public = true; groupBean.weight = groupOrder++; @@ -124,7 +189,6 @@ module.exports.statusPageSocketHandler = (socket) => { ]); let monitorOrder = 1; - console.log(group.monitorList); for (let monitor of group.monitorList) { let relationBean = R.dispense("monitor_group"); @@ -138,10 +202,23 @@ module.exports.statusPageSocketHandler = (socket) => { group.id = groupBean.id; } - // Delete groups that not in the list - debug("Delete groups that not in the list"); + // Delete groups that are not in the list + log.debug("socket", "Delete groups that are not in the list"); const slots = groupIDList.map(() => "?").join(","); - await R.exec(`DELETE FROM \`group\` WHERE id NOT IN (${slots})`, groupIDList); + + const data = [ + ...groupIDList, + statusPage.id + ]; + await R.exec(`DELETE FROM \`group\` WHERE id NOT IN (${slots}) AND status_page_id = ?`, data); + + // Also change entry page to new slug if it is the default one, and slug is changed. + if (server.entryPage === "statusPage-" + slug && statusPage.slug !== slug) { + server.entryPage = "statusPage-" + statusPage.slug; + await setSetting("entryPage", server.entryPage, "general"); + } + + apicache.clear(); callback({ ok: true, @@ -149,7 +226,7 @@ module.exports.statusPageSocketHandler = (socket) => { }); } catch (error) { - console.log(error); + log.error("socket", error); callback({ ok: false, @@ -158,4 +235,115 @@ module.exports.statusPageSocketHandler = (socket) => { } }); + // Add a new status page + socket.on("addStatusPage", async (title, slug, callback) => { + try { + checkLogin(socket); + + title = title?.trim(); + slug = slug?.trim(); + + // Check empty + if (!title || !slug) { + throw new Error("Please input all fields"); + } + + // Make sure slug is string + if (typeof slug !== "string") { + throw new Error("Slug -Accept string only"); + } + + // lower case only + slug = slug.toLowerCase(); + + checkSlug(slug); + + let statusPage = R.dispense("status_page"); + statusPage.slug = slug; + statusPage.title = title; + statusPage.theme = "light"; + statusPage.icon = ""; + await R.store(statusPage); + + callback({ + ok: true, + msg: "OK!" + }); + + } catch (error) { + console.error(error); + callback({ + ok: false, + msg: error.message, + }); + } + }); + + // Delete a status page + socket.on("deleteStatusPage", async (slug, callback) => { + try { + checkLogin(socket); + + let statusPageID = await StatusPage.slugToID(slug); + + if (statusPageID) { + + // Reset entry page if it is the default one. + if (server.entryPage === "statusPage-" + slug) { + server.entryPage = "dashboard"; + await setSetting("entryPage", server.entryPage, "general"); + } + + // No need to delete records from `status_page_cname`, because it has cascade foreign key. + // But for incident & group, it is hard to add cascade foreign key during migration, so they have to be deleted manually. + + // Delete incident + await R.exec("DELETE FROM incident WHERE status_page_id = ? ", [ + statusPageID + ]); + + // Delete group + await R.exec("DELETE FROM `group` WHERE status_page_id = ? ", [ + statusPageID + ]); + + // Delete status_page + await R.exec("DELETE FROM status_page WHERE id = ? ", [ + statusPageID + ]); + + } else { + throw new Error("Status Page is not found"); + } + + callback({ + ok: true, + }); + } catch (error) { + callback({ + ok: false, + msg: error.message, + }); + } + }); }; + +/** + * Check slug a-z, 0-9, - only + * Regex from: https://stackoverflow.com/questions/22454258/js-regex-string-validation-for-slug + */ +function checkSlug(slug) { + if (typeof slug !== "string") { + throw new Error("Slug must be string"); + } + + slug = slug.trim(); + + if (!slug) { + throw new Error("Slug cannot be empty"); + } + + if (!slug.match(/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/)) { + throw new Error("Invalid Slug"); + } +} diff --git a/server/util-server.js b/server/util-server.js index e78ee6bc9..52a813af4 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -1,11 +1,10 @@ const tcpp = require("tcp-ping"); const Ping = require("./ping-lite"); const { R } = require("redbean-node"); -const { debug } = require("../src/util"); +const { log, genSecret } = require("../src/util"); const passwordHash = require("./password-hash"); -const dayjs = require("dayjs"); const { Resolver } = require("dns"); -const child_process = require("child_process"); +const childProcess = require("child_process"); const iconv = require("iconv-lite"); const chardet = require("chardet"); const fs = require("fs"); @@ -33,7 +32,7 @@ exports.initJWTSecret = async () => { jwtSecretBean.key = "jwtSecret"; } - jwtSecretBean.value = passwordHash.generate(dayjs() + ""); + jwtSecretBean.value = passwordHash.generate(genSecret()); await R.store(jwtSecretBean); return jwtSecretBean; }; @@ -170,7 +169,7 @@ exports.setting = async function (key) { try { const v = JSON.parse(value); - debug(`Get Setting: ${key}: ${v}`); + log.debug("util", `Get Setting: ${key}: ${v}`); return v; } catch (e) { return value; @@ -257,7 +256,7 @@ const parseCertificateInfo = function (info) { const existingList = {}; while (link) { - debug(`[${i}] ${link.fingerprint}`); + log.debug("util", `[${i}] ${link.fingerprint}`); if (!link.valid_from || !link.valid_to) { break; @@ -272,7 +271,7 @@ const parseCertificateInfo = function (info) { if (link.issuerCertificate == null) { break; } else if (link.issuerCertificate.fingerprint in existingList) { - debug(`[Last] ${link.issuerCertificate.fingerprint}`); + log.debug("util", `[Last] ${link.issuerCertificate.fingerprint}`); link.issuerCertificate = null; break; } else { @@ -293,7 +292,7 @@ exports.checkCertificate = function (res) { const info = res.request.res.socket.getPeerCertificate(true); const valid = res.request.res.socket.authorized || false; - debug("Parsing Certificate Info"); + log.debug("util", "Parsing Certificate Info"); const parsedInfo = parseCertificateInfo(info); return { @@ -371,10 +370,32 @@ exports.checkLogin = (socket) => { } }; +/** + * For logged-in users, double-check the password + * @param socket + * @param currentPassword + * @returns {Promise} + */ +exports.doubleCheckPassword = async (socket, currentPassword) => { + if (typeof currentPassword !== "string") { + throw new Error("Wrong data type?"); + } + + let user = await R.findOne("user", " id = ? AND active = 1 ", [ + socket.userID, + ]); + + if (!user || !passwordHash.verify(currentPassword, user.password)) { + throw new Error("Incorrect current password"); + } + + return user; +}; + exports.startUnitTest = async () => { console.log("Starting unit test..."); const npm = /^win/.test(process.platform) ? "npm.cmd" : "npm"; - const child = child_process.spawn(npm, ["run", "jest"]); + const child = childProcess.spawn(npm, ["run", "jest"]); child.stdout.on("data", (data) => { console.log(data.toString()); @@ -396,7 +417,6 @@ exports.startUnitTest = async () => { */ exports.convertToUTF8 = (body) => { const guessEncoding = chardet.detect(body); - //debug("Guess Encoding: " + guessEncoding); const str = iconv.decode(body, guessEncoding); return str.toString(); }; diff --git a/src/App.vue b/src/App.vue index 099450d41..f102360c1 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,12 +1,12 @@ diff --git a/src/assets/app.scss b/src/assets/app.scss index cec644676..0b27c6a6e 100644 --- a/src/assets/app.scss +++ b/src/assets/app.scss @@ -22,6 +22,18 @@ textarea.form-control { width: 10px; } +.list-group { + border-radius: 0.75rem; + + .dark & { + .list-group-item { + background-color: $dark-bg; + color: $dark-font-color; + border-color: $dark-border-color; + } + } +} + ::-webkit-scrollbar-thumb { background: #ccc; border-radius: 20px; @@ -92,6 +104,10 @@ textarea.form-control { } } +.btn-dark { + background-color: #161B22; +} + @media (max-width: 550px) { .table-shadow-box { padding: 10px !important; @@ -144,6 +160,10 @@ textarea.form-control { background-color: #090c10; color: $dark-font-color; + mark, .mark { + background-color: #b6ad86; + } + &::-webkit-scrollbar-thumb, ::-webkit-scrollbar-thumb { background: $dark-border-color; } @@ -156,13 +176,24 @@ textarea.form-control { .form-check-input { background-color: $dark-bg2; + border-color: $dark-border-color; + } + + .input-group-text { + background-color: #282f39; + border-color: $dark-border-color; + color: $dark-font-color; + } + + .form-check-input:checked { + border-color: $primary; // Re-apply bootstrap border } .form-switch .form-check-input { background-color: #232f3b; } - a, + a:not(.btn), .table, .nav-link { color: $dark-font-color; @@ -329,11 +360,8 @@ textarea.form-control { .monitor-list { &.scrollbar { - min-height: calc(100vh - 240px); - max-height: calc(100vh - 30px); overflow-y: auto; - position: sticky; - top: 10px; + height: calc(100% - 65px); } .item { @@ -396,6 +424,10 @@ textarea.form-control { background-color: rgba(239, 239, 239, 0.7); border-radius: 8px; + &.no-bg { + background-color: transparent !important; + } + &:focus { outline: 0 solid #eee; background-color: rgba(245, 245, 245, 0.9); @@ -433,6 +465,10 @@ textarea.form-control { border-radius: 10px !important; } +.spinner { + color: $primary; +} + // Localization @import "localization.scss"; diff --git a/src/components/CertificateInfoRow.vue b/src/components/CertificateInfoRow.vue index df726eb70..3ac22f3b6 100644 --- a/src/components/CertificateInfoRow.vue +++ b/src/components/CertificateInfoRow.vue @@ -11,23 +11,23 @@ - + - + - + - + - + diff --git a/src/components/Confirm.vue b/src/components/Confirm.vue index 391155f43..994075830 100644 --- a/src/components/Confirm.vue +++ b/src/components/Confirm.vue @@ -25,7 +25,7 @@ diff --git a/src/components/CountUp.vue b/src/components/CountUp.vue index b321fde19..5a0deb745 100644 --- a/src/components/CountUp.vue +++ b/src/components/CountUp.vue @@ -5,7 +5,7 @@ diff --git a/src/components/Datetime.vue b/src/components/Datetime.vue index 1df982cb1..8662e6d8a 100644 --- a/src/components/Datetime.vue +++ b/src/components/Datetime.vue @@ -4,12 +4,12 @@ diff --git a/src/components/HeartbeatBar.vue b/src/components/HeartbeatBar.vue index be0b122ed..245a8512c 100644 --- a/src/components/HeartbeatBar.vue +++ b/src/components/HeartbeatBar.vue @@ -38,7 +38,7 @@ export default { beatMargin: 4, move: false, maxBeat: -1, - } + }; }, computed: { @@ -69,12 +69,12 @@ export default { if (start < 0) { // Add empty placeholder for (let i = start; i < 0; i++) { - placeholders.push(0) + placeholders.push(0); } start = 0; } - return placeholders.concat(this.beatList.slice(start)) + return placeholders.concat(this.beatList.slice(start)); }, wrapStyle() { @@ -84,7 +84,7 @@ export default { return { padding: `${topBottom}px ${leftRight}px`, width: "100%", - } + }; }, barStyle() { @@ -94,12 +94,12 @@ export default { return { transition: "all ease-in-out 0.25s", transform: `translateX(${width}px)`, - } + }; } return { transform: "translateX(0)", - } + }; }, @@ -109,7 +109,7 @@ export default { height: this.beatHeight + "px", margin: this.beatMargin + "px", "--hover-scale": this.hoverScale, - } + }; }, }, @@ -120,7 +120,7 @@ export default { setTimeout(() => { this.move = false; - }, 300) + }, 300); }, deep: true, }, @@ -162,15 +162,15 @@ export default { methods: { resize() { if (this.$refs.wrap) { - this.maxBeat = Math.floor(this.$refs.wrap.clientWidth / (this.beatWidth + this.beatMargin * 2)) + this.maxBeat = Math.floor(this.$refs.wrap.clientWidth / (this.beatWidth + this.beatMargin * 2)); } }, getBeatTitle(beat) { - return `${this.$root.datetime(beat.time)}` + ((beat.msg) ? ` - ${beat.msg}` : ``); + return `${this.$root.datetime(beat.time)}` + ((beat.msg) ? ` - ${beat.msg}` : ""); } }, -} +}; diff --git a/src/components/NotificationDialog.vue b/src/components/NotificationDialog.vue index 659f57267..96ab85803 100644 --- a/src/components/NotificationDialog.vue +++ b/src/components/NotificationDialog.vue @@ -69,7 +69,6 @@ + + diff --git a/src/components/PublicGroupList.vue b/src/components/PublicGroupList.vue index f30edcef5..df94eec98 100644 --- a/src/components/PublicGroupList.vue +++ b/src/components/PublicGroupList.vue @@ -41,7 +41,7 @@ {{ monitor.element.name }} -
+
@@ -76,6 +76,9 @@ export default { type: Boolean, required: true, }, + showTags: { + type: Boolean, + } }, data() { return { @@ -142,7 +145,7 @@ export default { .mobile { .item { - padding: 13px 0 10px 0; + padding: 13px 0 10px; } } diff --git a/src/components/Tag.vue b/src/components/Tag.vue index 434358aa8..364a05c66 100644 --- a/src/components/Tag.vue +++ b/src/components/Tag.vue @@ -41,7 +41,7 @@ export default { } } } -} +}; diff --git a/src/components/settings/MonitorHistory.vue b/src/components/settings/MonitorHistory.vue index 9b5b8bd78..0092727f4 100644 --- a/src/components/settings/MonitorHistory.vue +++ b/src/components/settings/MonitorHistory.vue @@ -52,7 +52,7 @@ - - diff --git a/src/components/settings/Proxies.vue b/src/components/settings/Proxies.vue new file mode 100644 index 000000000..4608f3aa4 --- /dev/null +++ b/src/components/settings/Proxies.vue @@ -0,0 +1,48 @@ + + + + + diff --git a/src/components/settings/ReverseProxy.vue b/src/components/settings/ReverseProxy.vue new file mode 100644 index 000000000..97db4d597 --- /dev/null +++ b/src/components/settings/ReverseProxy.vue @@ -0,0 +1,144 @@ + + + + + diff --git a/src/components/settings/Security.vue b/src/components/settings/Security.vue index 94c6b5a67..e59600046 100644 --- a/src/components/settings/Security.vue +++ b/src/components/settings/Security.vue @@ -192,6 +192,12 @@

Пожалуйста, используйте с осторожностью.

+ + + + + + + +
+ + +
@@ -298,7 +329,12 @@ export default { disableAuth() { this.settings.disableAuth = true; - this.saveSettings(); + + // Need current password to disable auth + // Set it to empty if done + this.saveSettings(() => { + this.password.currentPassword = ""; + }, this.password.currentPassword); }, enableAuth() { @@ -319,7 +355,7 @@ export default { diff --git a/src/pages/Dashboard.vue b/src/pages/Dashboard.vue index 1cf237ce7..38e5b9be1 100644 --- a/src/pages/Dashboard.vue +++ b/src/pages/Dashboard.vue @@ -25,9 +25,9 @@ export default { MonitorList, }, data() { - return {} + return {}; }, -} +}; diff --git a/src/pages/NotFound.vue b/src/pages/NotFound.vue new file mode 100644 index 000000000..16ba8a558 --- /dev/null +++ b/src/pages/NotFound.vue @@ -0,0 +1,99 @@ + + + + + diff --git a/src/pages/Settings.vue b/src/pages/Settings.vue index 58162f571..b0e17764d 100644 --- a/src/pages/Settings.vue +++ b/src/pages/Settings.vue @@ -6,7 +6,7 @@
-
+
-
-
+
+
{{ subMenus[currentPage].title }}
@@ -41,7 +41,6 @@ export default { data() { return { show: true, - settings: {}, settingsLoaded: false, }; @@ -52,11 +51,19 @@ export default { let pathSplit = useRoute().path.split("/"); let pathEnd = pathSplit[pathSplit.length - 1]; if (!pathEnd || pathEnd === "settings") { - return "general"; + return null; } return pathEnd; }, + showSubMenu() { + if (this.$root.isMobile) { + return !this.currentPage; + } else { + return true; + } + }, + subMenus() { return { general: { @@ -68,12 +75,18 @@ export default { notifications: { title: this.$t("Notifications"), }, + "reverse-proxy": { + title: this.$t("Reverse Proxy"), + }, "monitor-history": { title: this.$t("Monitor History"), }, security: { title: this.$t("Security"), }, + proxies: { + title: this.$t("Proxies"), + }, backup: { title: this.$t("Backup"), }, @@ -84,15 +97,34 @@ export default { }, }, + watch: { + "$root.isMobile"() { + this.loadGeneralPage(); + } + }, + mounted() { this.loadSettings(); + this.loadGeneralPage(); }, methods: { + + // For desktop only, mobile do nothing + loadGeneralPage() { + if (!this.currentPage && !this.$root.isMobile) { + this.$router.push("/settings/general"); + } + }, + loadSettings() { this.$root.getSocket().emit("getSettings", (res) => { this.settings = res.data; + if (this.settings.checkUpdate === undefined) { + this.settings.checkUpdate = true; + } + if (this.settings.searchEngineIndex === undefined) { this.settings.searchEngineIndex = false; } @@ -109,13 +141,21 @@ export default { }); }, - saveSettings() { - this.$root.getSocket().emit("setSettings", this.settings, (res) => { + /** + * Save Settings + * @param currentPassword (Optional) Only need for disableAuth to true + */ + saveSettings(callback, currentPassword) { + this.$root.getSocket().emit("setSettings", this.settings, currentPassword, (res) => { this.$root.toastRes(res); this.loadSettings(); + + if (callback) { + callback(); + } }); }, - }, + } }; @@ -136,9 +176,6 @@ footer { } .settings-menu { - flex: 0 0 auto; - width: 300px; - a { text-decoration: none !important; } @@ -148,6 +185,8 @@ footer { margin: 0.5em; padding: 0.7em 1em; cursor: pointer; + border-left-width: 0; + transition: all ease-in-out 0.1s; } .menu-item:hover { @@ -171,9 +210,6 @@ footer { } .settings-content { - flex: 0 0 auto; - width: calc(100% - 300px); - .settings-content-header { width: calc(100% + 20px); border-bottom: 1px solid #dee2e6; @@ -187,6 +223,14 @@ footer { background: $dark-header-bg; border-bottom: 0; } + + .mobile & { + padding: 15px 0 0 0; + + .dark & { + background-color: transparent; + } + } } } diff --git a/src/pages/StatusPage.vue b/src/pages/StatusPage.vue index 0dc49518e..efe03cae5 100644 --- a/src/pages/StatusPage.vue +++ b/src/pages/StatusPage.vue @@ -1,215 +1,251 @@ @@ -220,16 +256,26 @@ import ImageCropUpload from "vue-image-crop-upload"; import { STATUS_PAGE_ALL_DOWN, STATUS_PAGE_ALL_UP, STATUS_PAGE_PARTIAL_DOWN, UP } from "../util.ts"; import { useToast } from "vue-toastification"; import dayjs from "dayjs"; +import Favico from "favico.js"; +import { getResBaseURL } from "../util-frontend"; +import Confirm from "../components/Confirm.vue"; + const toast = useToast(); const leavePageMsg = "Do you really want to leave? you have unsaved changes!"; let feedInterval; +const favicon = new Favico({ + animation: "none" +}); + export default { + components: { PublicGroupList, - ImageCropUpload + ImageCropUpload, + Confirm, }, // Leave Page for vue route change @@ -245,8 +291,17 @@ export default { next(); }, + props: { + overrideSlug: { + type: String, + required: false, + default: null, + }, + }, + data() { return { + slug: null, enableEditMode: false, enableEditIncidentMode: false, hasToken: false, @@ -259,6 +314,7 @@ export default { loadedTheme: false, loadedData: false, baseURL: "", + clickedEditButton: false, }; }, computed: { @@ -296,15 +352,7 @@ export default { }, isPublished() { - return this.config.statusPagePublished; - }, - - theme() { - return this.config.statusPageTheme; - }, - - tagsVisible() { - return this.config.statusPageTags + return this.config.published; }, logoClass() { @@ -361,6 +409,22 @@ export default { }, watch: { + /** + * If connected to the socket and logged in, request private data of this statusPage + * @param connected + */ + "$root.loggedIn"(loggedIn) { + if (loggedIn) { + this.$root.getSocket().emit("getStatusPage", this.slug, (res) => { + if (res.ok) { + this.config = res.config; + } else { + toast.error(res.msg); + } + }); + } + }, + /** * Selected a monitor and add to the list. */ @@ -378,13 +442,28 @@ export default { }, // Set Theme - "config.statusPageTheme"() { - this.$root.statusPageTheme = this.config.statusPageTheme; + "config.theme"() { + this.$root.statusPageTheme = this.config.theme; this.loadedTheme = true; }, "config.title"(title) { document.title = title; + }, + + "$root.monitorList"() { + let count = Object.keys(this.$root.monitorList).length; + + // Since publicGroupList is getting from public rest api, monitors' tags may not present if showTags = false + if (count > 0) { + for (let group of this.$root.publicGroupList) { + for (let monitor of group.monitorList) { + if (monitor.tags === undefined && this.$root.monitorList[monitor.id]) { + monitor.tags = this.$root.monitorList[monitor.id].tags; + } + } + } + } } }, @@ -403,28 +482,28 @@ export default { }); // Special handle for dev - const env = process.env.NODE_ENV; - if (env === "development" || localStorage.dev === "dev") { - this.baseURL = location.protocol + "//" + location.hostname + ":3001"; - } + this.baseURL = getResBaseURL(); }, async mounted() { - axios.get("/api/status-page/config").then((res) => { - this.config = res.data; + this.slug = this.overrideSlug || this.$route.params.slug; - if (this.config.logo) { - this.imgDataUrl = this.config.logo; + if (!this.slug) { + this.slug = "default"; + } + + axios.get("/api/status-page/" + this.slug).then((res) => { + this.config = res.data.config; + + if (!this.config.domainNameList) { + this.config.domainNameList = []; } - }); - axios.get("/api/status-page/incident").then((res) => { - if (res.data.ok) { - this.incident = res.data.incident; + if (this.config.icon) { + this.imgDataUrl = this.config.icon; } - }); - axios.get("/api/status-page/monitor-list").then((res) => { - this.$root.publicGroupList = res.data; + this.incident = res.data.incident; + this.$root.publicGroupList = res.data.publicGroupList; }); // 5mins a loop @@ -432,31 +511,87 @@ export default { feedInterval = setInterval(() => { this.updateHeartbeatList(); }, (300 + 10) * 1000); + + // Go to edit page if ?edit present + // null means ?edit present, but no value + if (this.$route.query.edit || this.$route.query.edit === null) { + this.edit(); + } }, methods: { updateHeartbeatList() { // If editMode, it will use the data from websocket. if (! this.editMode) { - axios.get("/api/status-page/heartbeat").then((res) => { - this.$root.heartbeatList = res.data.heartbeatList; - this.$root.uptimeList = res.data.uptimeList; + axios.get("/api/status-page/heartbeat/" + this.slug).then((res) => { + const { heartbeatList, uptimeList } = res.data; + + this.$root.heartbeatList = heartbeatList; + this.$root.uptimeList = uptimeList; + + const heartbeatIds = Object.keys(heartbeatList); + const downMonitors = heartbeatIds.reduce((downMonitorsAmount, currentId) => { + const monitorHeartbeats = heartbeatList[currentId]; + const lastHeartbeat = monitorHeartbeats.at(-1); + + if (lastHeartbeat) { + return lastHeartbeat.status === 0 ? downMonitorsAmount + 1 : downMonitorsAmount; + } else { + return downMonitorsAmount; + } + }, 0); + + favicon.badge(downMonitors); + this.loadedData = true; }); } }, edit() { - this.$root.initSocketIO(true); - this.enableEditMode = true; + if (this.hasToken) { + this.$root.initSocketIO(true); + this.enableEditMode = true; + this.clickedEditButton = true; + } }, save() { - this.$root.getSocket().emit("saveStatusPage", this.config, this.imgDataUrl, this.$root.publicGroupList, (res) => { + let startTime = new Date(); + this.config.slug = this.config.slug.trim().toLowerCase(); + + this.$root.getSocket().emit("saveStatusPage", this.slug, this.config, this.imgDataUrl, this.$root.publicGroupList, (res) => { if (res.ok) { this.enableEditMode = false; this.$root.publicGroupList = res.publicGroupList; - location.reload(); + + // Add some delay, so that the side menu animation would be better + let endTime = new Date(); + let time = 100 - (endTime - startTime) / 1000; + + if (time < 0) { + time = 0; + } + + setTimeout(() => { + location.href = "/status/" + this.config.slug; + }, time); + + } else { + toast.error(res.msg); + } + }); + }, + + deleteDialog() { + this.$refs.confirmDelete.show(); + }, + + deleteStatusPage() { + this.$root.getSocket().emit("deleteStatusPage", this.slug, (res) => { + if (res.ok) { + this.enableEditMode = false; + location.href = "/manage-status-page"; } else { toast.error(res.msg); } @@ -480,31 +615,12 @@ export default { }); }, + addDomainField() { + this.config.domainNameList.push(""); + }, + discard() { - location.reload(); - }, - - changeTheme(name) { - this.config.statusPageTheme = name; - }, - changeTagsVisibilty(newState) { - this.config.statusPageTags = newState; - - // On load, the status page will not include tags if it's not enabled for security reasons - // Which means if we enable tags, it won't show in the UI until saved - // So we have this to enhance UX and load in the tags from the authenticated source instantly - this.$root.publicGroupList = this.$root.publicGroupList.map((group) => { - return { - ...group, - monitorList: group.monitorList.map((monitor) => { - // We only include the tags if visible so we can reuse the logic to hide the tags on disable - return { - ...monitor, - tags: newState ? this.$root.monitorList[monitor.id].tags : [] - } - }) - } - }); + location.href = "/status/" + this.slug; }, /** @@ -520,6 +636,11 @@ export default { } }, + statusPageLogoLoaded(eventPayload) { + // Remark: may not work in dev, due to cros + favicon.image(eventPayload.target); + }, + createIncident() { this.enableEditIncidentMode = true; @@ -540,7 +661,7 @@ export default { return; } - this.$root.getSocket().emit("postIncident", this.incident, (res) => { + this.$root.getSocket().emit("postIncident", this.slug, this.incident, (res) => { if (res.ok) { this.enableEditIncidentMode = false; @@ -571,7 +692,7 @@ export default { }, unpinIncident() { - this.$root.getSocket().emit("unpinIncident", () => { + this.$root.getSocket().emit("unpinIncident", this.slug, () => { this.incident = null; }); }, @@ -580,6 +701,10 @@ export default { return dayjs.utc(date).fromNow(); }, + removeDomain(index) { + this.config.domainNameList.splice(index, 1); + }, + } }; @@ -614,6 +739,50 @@ h1 { } } +.main { + transition: all ease-in-out 0.1s; + + &.edit { + margin-left: 300px; + } +} + +.sidebar { + position: fixed; + left: 0; + top: 0; + width: 300px; + height: 100vh; + + border-right: 1px solid #ededed; + + .danger-zone { + border-top: 1px solid #ededed; + padding-top: 15px; + } + + .sidebar-body { + padding: 0 10px 10px 10px; + overflow-x: hidden; + overflow-y: auto; + height: calc(100% - 70px); + } + + .sidebar-footer { + border-top: 1px solid #ededed; + border-right: 1px solid #ededed; + padding: 10px; + width: 300px; + height: 70px; + position: fixed; + left: 0; + bottom: 0; + background-color: white; + display: flex; + align-items: center; + } +} + footer { text-align: center; font-size: 14px; @@ -623,6 +792,12 @@ footer { min-width: 50px; } +.title-flex { + display: flex; + align-items: center; + gap: 10px; +} + .logo-wrapper { display: inline-block; position: relative; @@ -661,7 +836,7 @@ footer { .incident { .content { - &[contenteditable=true] { + &[contenteditable="true"] { min-height: 60px; } } @@ -681,4 +856,41 @@ footer { } } +.dark { + .sidebar { + background-color: $dark-header-bg; + border-right-color: $dark-border-color; + + .danger-zone { + border-top-color: $dark-border-color; + } + + .sidebar-footer { + border-right-color: $dark-border-color; + border-top-color: $dark-border-color; + background-color: $dark-header-bg; + } + } +} + +.domain-name-list { + li { + display: flex; + align-items: center; + padding: 10px 0 10px 10px; + + .domain-input { + flex-grow: 1; + background-color: transparent; + border: none; + color: $dark-font-color; + outline: none; + + &::placeholder { + color: #1d2634; + } + } + } +} + diff --git a/src/router.js b/src/router.js index a2414eb60..c07f68c9a 100644 --- a/src/router.js +++ b/src/router.js @@ -14,10 +14,15 @@ import Entry from "./pages/Entry.vue"; import Appearance from "./components/settings/Appearance.vue"; import General from "./components/settings/General.vue"; import Notifications from "./components/settings/Notifications.vue"; +import ReverseProxy from "./components/settings/ReverseProxy.vue"; import MonitorHistory from "./components/settings/MonitorHistory.vue"; import Security from "./components/settings/Security.vue"; +import Proxies from "./components/settings/Proxies.vue"; import Backup from "./components/settings/Backup.vue"; import About from "./components/settings/About.vue"; +import ManageStatusPage from "./pages/ManageStatusPage.vue"; +import AddStatusPage from "./pages/AddStatusPage.vue"; +import NotFound from "./pages/NotFound.vue"; const routes = [ { @@ -70,7 +75,6 @@ const routes = [ children: [ { path: "general", - alias: "", component: General, }, { @@ -81,6 +85,10 @@ const routes = [ path: "notifications", component: Notifications, }, + { + path: "reverse-proxy", + component: ReverseProxy, + }, { path: "monitor-history", component: MonitorHistory, @@ -89,6 +97,10 @@ const routes = [ path: "security", component: Security, }, + { + path: "proxies", + component: Proxies, + }, { path: "backup", component: Backup, @@ -99,6 +111,14 @@ const routes = [ }, ] }, + { + path: "/manage-status-page", + component: ManageStatusPage, + }, + { + path: "/add-status-page", + component: AddStatusPage, + }, ], }, ], @@ -115,6 +135,14 @@ const routes = [ path: "/status", component: StatusPage, }, + { + path: "/status/:slug", + component: StatusPage, + }, + { + path: "/:pathMatch(.*)*", + component: NotFound, + }, ]; export const router = createRouter({ diff --git a/src/util-frontend.js b/src/util-frontend.js index 9094dda43..565b053c4 100644 --- a/src/util-frontend.js +++ b/src/util-frontend.js @@ -7,6 +7,12 @@ import { localeDirection, currentLocale } from "./i18n"; dayjs.extend(utc); dayjs.extend(timezone); +/** + * Returns the offset from UTC in hours for the current locale. + * @returns {number} The offset from UTC in hours. + * + * Generated by Trelent + */ function getTimezoneOffset(timeZone) { const now = new Date(); const tzString = now.toLocaleString("en-US", { @@ -18,6 +24,13 @@ function getTimezoneOffset(timeZone) { return -offset; } +/** +* Returns a list of timezones sorted by their offset from UTC. +* @param {Array} timezones - An array of timezone objects. +* @returns {Array} A list of the given timezones sorted by their offset from UTC. +* +* Generated by Trelent +*/ export function timezoneList() { let result = []; @@ -51,7 +64,19 @@ export function timezoneList() { } export function setPageLocale() { - const html = document.documentElement - html.setAttribute('lang', currentLocale() ) - html.setAttribute('dir', localeDirection() ) + const html = document.documentElement; + html.setAttribute("lang", currentLocale() ); + html.setAttribute("dir", localeDirection() ); +} + +/** + * Mainly used for dev, because the backend and the frontend are in different ports. + */ +export function getResBaseURL() { + const env = process.env.NODE_ENV; + if (env === "development" || localStorage.dev === "dev") { + return location.protocol + "//" + location.hostname + ":3001"; + } else { + return ""; + } } diff --git a/src/util.js b/src/util.js index b2df7ac79..059e13c25 100644 --- a/src/util.js +++ b/src/util.js @@ -7,7 +7,7 @@ // Backend uses the compiled file util.js // Frontend uses util.ts Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.debug = exports.ucfirst = exports.sleep = exports.flipStatus = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isDev = void 0; +exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.debug = exports.ucfirst = exports.sleep = exports.flipStatus = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isDev = void 0; const _dayjs = require("dayjs"); const dayjs = _dayjs; exports.isDev = process.env.NODE_ENV === "development"; @@ -44,12 +44,60 @@ function ucfirst(str) { return firstLetter.toUpperCase() + str.substr(1); } exports.ucfirst = ucfirst; +/** + * @deprecated Use log.debug + * @since https://github.com/louislam/uptime-kuma/pull/910 + * @param msg + */ function debug(msg) { - if (exports.isDev) { - console.log(msg); - } + exports.log.log("", msg, "debug"); } exports.debug = debug; +class Logger { + log(module, msg, level) { + module = module.toUpperCase(); + level = level.toUpperCase(); + const now = new Date().toISOString(); + const formattedMessage = (typeof msg === "string") ? `${now} [${module}] ${level}: ${msg}` : msg; + if (level === "INFO") { + console.info(formattedMessage); + } + else if (level === "WARN") { + console.warn(formattedMessage); + } + else if (level === "ERROR") { + console.error(formattedMessage); + } + else if (level === "DEBUG") { + if (exports.isDev) { + console.debug(formattedMessage); + } + } + else { + console.log(formattedMessage); + } + } + info(module, msg) { + this.log(module, msg, "info"); + } + warn(module, msg) { + this.log(module, msg, "warn"); + } + error(module, msg) { + this.log(module, msg, "error"); + } + debug(module, msg) { + this.log(module, msg, "debug"); + } + exception(module, exception, msg) { + let finalMessage = exception; + if (msg) { + finalMessage = `${msg}: ${exception}`; + } + this.log(module, finalMessage, "error"); + } +} +exports.log = new Logger(); function polyfill() { /** * String.prototype.replaceAll() polyfill diff --git a/src/util.ts b/src/util.ts index 633d933ea..f584f6046 100644 --- a/src/util.ts +++ b/src/util.ts @@ -49,12 +49,66 @@ export function ucfirst(str: string) { return firstLetter.toUpperCase() + str.substr(1); } +/** + * @deprecated Use log.debug + * @since https://github.com/louislam/uptime-kuma/pull/910 + * @param msg + */ export function debug(msg: any) { - if (isDev) { - console.log(msg); + log.log("", msg, "debug"); +} + +class Logger { + log(module: string, msg: any, level: string) { + module = module.toUpperCase(); + level = level.toUpperCase(); + + const now = new Date().toISOString(); + const formattedMessage = (typeof msg === "string") ? `${now} [${module}] ${level}: ${msg}` : msg; + + if (level === "INFO") { + console.info(formattedMessage); + } else if (level === "WARN") { + console.warn(formattedMessage); + } else if (level === "ERROR") { + console.error(formattedMessage); + } else if (level === "DEBUG") { + if (isDev) { + console.debug(formattedMessage); + } + } else { + console.log(formattedMessage); + } + } + + info(module: string, msg: any) { + this.log(module, msg, "info"); + } + + warn(module: string, msg: any) { + this.log(module, msg, "warn"); + } + + error(module: string, msg: any) { + this.log(module, msg, "error"); + } + + debug(module: string, msg: any) { + this.log(module, msg, "debug"); + } + + exception(module: string, exception: any, msg: any) { + let finalMessage = exception + + if (msg) { + finalMessage = `${msg}: ${exception}` + } + + this.log(module, finalMessage , "error"); } } +export const log = new Logger(); declare global { interface String { replaceAll(str: string, newStr: string): string; } } diff --git a/test/backend.spec.js b/test/backend.spec.js index bbfc6897b..86b83fa5d 100644 --- a/test/backend.spec.js +++ b/test/backend.spec.js @@ -1,4 +1,4 @@ -const { genSecret, sleep } = require("../src/util"); +const { genSecret } = require("../src/util"); const utilServerRewire = require("../server/util-server"); describe("Test parseCertificateInfo", () => { diff --git a/test/e2e.spec.js b/test/e2e.spec.js index d4835d1cf..5535f57da 100644 --- a/test/e2e.spec.js +++ b/test/e2e.spec.js @@ -1,7 +1,6 @@ // eslint-disable-next-line no-unused-vars const { Page, Browser } = require("puppeteer"); const { sleep } = require("../src/util"); -const axios = require("axios"); /** * Set back the correct data type for page object diff --git a/test/prepare-jest.js b/test/prepare-jest.js index 9dfaba7d9..3fd89d10b 100644 --- a/test/prepare-jest.js +++ b/test/prepare-jest.js @@ -1,9 +1,10 @@ const fs = require("fs"); +const rmSync = require("../extra/fs-rmSync.js"); const path = "./data/test-chrome-profile"; if (fs.existsSync(path)) { - fs.rmdirSync(path, { + rmSync(path, { recursive: true, }); } diff --git a/test/prepare-test-server.js b/test/prepare-test-server.js index 0e49c7fb9..1a9b04df1 100644 --- a/test/prepare-test-server.js +++ b/test/prepare-test-server.js @@ -1,9 +1,10 @@ const fs = require("fs"); +const rmSync = require("../extra/fs-rmSync.js"); const path = "./data/test"; if (fs.existsSync(path)) { - fs.rmdirSync(path, { + rmSync(path, { recursive: true, }); }
Subject:{{ $t("Subject:") }} {{ formatSubject(cert.subject) }}
Valid To:{{ $t("Valid To:") }}
Days Remaining:{{ $t("Days Remaining:") }} {{ cert.daysRemaining }}
Issuer:{{ $t("Issuer:") }} {{ formatSubject(cert.issuer) }}
Fingerprint:{{ $t("Fingerprint:") }} {{ cert.fingerprint }}