Merge branch 'master' into deprecations

This commit is contained in:
Frank Elsinga 2024-09-13 22:51:25 +08:00 committed by GitHub
commit 828d2a73d4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
239 changed files with 18593 additions and 5649 deletions

View file

@ -1,28 +0,0 @@
# Codespaces
You can modifiy Uptime Kuma in your browser without setting up a local development.
![image](https://github.com/louislam/uptime-kuma/assets/1336778/31d9f06d-dd0b-4405-8e0d-a96586ee4595)
1. Click `Code` -> `Create codespace on master`
2. Wait a few minutes until you see there are two exposed ports
3. Go to the `3000` url, see if it is working
![image](https://github.com/louislam/uptime-kuma/assets/1336778/909b2eb4-4c5e-44e4-ac26-6d20ed856e7f)
## Frontend
Since the frontend is using [Vite.js](https://vitejs.dev/), all changes in this area will be hot-reloaded.
You don't need to restart the frontend, unless you try to add a new frontend dependency.
## Backend
The backend does not automatically hot-reload.
You will need to restart the backend after changing something using these steps:
1. Click `Terminal`
2. Click `Codespaces: server-dev` in the right panel
3. Press `Ctrl + C` to stop the server
4. Press `Up` to run `npm run start-server-dev`
![image](https://github.com/louislam/uptime-kuma/assets/1336778/e0c0a350-fe46-4588-9f37-e053c85834d1)

View file

@ -1,23 +0,0 @@
{
"image": "mcr.microsoft.com/devcontainers/javascript-node:dev-18-bookworm",
"features": {
"ghcr.io/devcontainers/features/github-cli:1": {}
},
"updateContentCommand": "npm ci",
"postCreateCommand": "",
"postAttachCommand": {
"frontend-dev": "npm run start-frontend-devcontainer",
"server-dev": "npm run start-server-dev",
"open-port": "gh codespace ports visibility 3001:public -c $CODESPACE_NAME"
},
"customizations": {
"vscode": {
"extensions": [
"streetsidesoftware.code-spell-checker",
"dbaeumer.vscode-eslint",
"GitHub.copilot-chat"
]
}
},
"forwardPorts": [3000, 3001]
}

View file

@ -1,7 +1,6 @@
/.idea /.idea
/node_modules /node_modules
/data* /data*
/cypress
/out /out
/test /test
/kubernetes /kubernetes
@ -18,7 +17,6 @@ README.md
.vscode .vscode
.eslint* .eslint*
.stylelint* .stylelint*
/.devcontainer
/.github /.github
yarn.lock yarn.lock
app.json app.json

View file

@ -1,8 +1,7 @@
module.exports = { module.exports = {
ignorePatterns: [ ignorePatterns: [
"test/*.js", "test/*.js",
"test/cypress", "server/modules/*",
"server/modules/apicache/*",
"src/util.js" "src/util.js"
], ],
root: true, root: true,

View file

@ -24,7 +24,7 @@ body:
required: true required: true
attributes: attributes:
label: "📝 Describe your problem" label: "📝 Describe your problem"
description: "Please walk us through it step by step." description: "Please walk us through it step by step. Include all important details and add screenshots where appropriate"
placeholder: "Describe what are you asking for..." placeholder: "Describe what are you asking for..."
- type: textarea - type: textarea
id: error-msg id: error-msg
@ -56,19 +56,20 @@ body:
placeholder: "Ex. Google Chrome 95.0.4638.69" placeholder: "Ex. Google Chrome 95.0.4638.69"
validations: validations:
required: true required: true
- type: input - type: textarea
id: docker-version id: deployment-info
attributes: attributes:
label: "🐋 Docker Version" label: "🖥️ Deployment Environment"
description: "If running with Docker, which version are you running?" description: |
placeholder: "Ex. Docker 20.10.9 / K8S / Podman" examples:
- **Runtime**: Docker 20.10.9 / nodejs 14.18.0 / K8S via ... v1.3.3 / ..
- **Database**: sqlite/embedded mariadb/external mariadb
- **Filesystem used to store the database on**: Windows/ZFS/btrfs/NFSv3 on a SSD/HDD/eMMC
- **number of monitors**: 42
value: |
- Runtime:
- Database:
- Filesystem used to store the database on:
- number of monitors:
validations: validations:
required: false required: true
- type: input
id: nodejs-version
attributes:
label: "🟩 NodeJS Version"
description: "If running with Node.js? which version are you running?"
placeholder: "Ex. 14.18.0"
validations:
required: false

View file

@ -3,14 +3,14 @@ description: "Submit a bug report to help us improve"
#title: "[Bug] " #title: "[Bug] "
labels: [bug] labels: [bug]
body: body:
- type: checkboxes - type: textarea
id: no-duplicate-issues id: related-issues
validations:
required: true
attributes: attributes:
label: "⚠️ Please verify that this bug has NOT been raised before." label: "📑 I have found these related issues/pull requests"
description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)" description: "Search related issues by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=) and explain what the difference between them or explain that you are unable to find any related issues"
options: placeholder: "Related to #1 by also touching the ... system. They should not be merged because ..."
- label: "I checked and didn't find similar issue"
required: true
- type: checkboxes - type: checkboxes
attributes: attributes:
label: "🛡️ Security Policy" label: "🛡️ Security Policy"
@ -31,7 +31,7 @@ body:
required: true required: true
attributes: attributes:
label: "👟 Reproduction steps" label: "👟 Reproduction steps"
description: "How do you trigger this bug? Please walk us through it step by step." description: "How do you trigger this bug? Please walk us through it step by step. Include all important details and add screenshots where appropriate"
placeholder: "..." placeholder: "..."
- type: textarea - type: textarea
id: expected-behavior id: expected-behavior
@ -73,22 +73,23 @@ body:
placeholder: "Ex. Google Chrome 95.0.4638.69" placeholder: "Ex. Google Chrome 95.0.4638.69"
validations: validations:
required: true required: true
- type: input - type: textarea
id: docker-version id: deployment-info
attributes: attributes:
label: "🐋 Docker Version" label: "🖥️ Deployment Environment"
description: "If running with Docker, which version are you running?" description: |
placeholder: "Ex. Docker 20.10.9 / K8S / Podman" examples:
- **Runtime**: Docker 20.10.9 / nodejs 18.17.1 / K8S via ... v1.3.3 / ..
- **Database**: sqlite/embedded mariadb/external mariadb
- **Filesystem used to store the database on**: Windows/ZFS/btrfs/NFSv3 on a SSD/HDD/eMMC
- **number of monitors**: 42
value: |
- Runtime:
- Database:
- Filesystem used to store the database on:
- number of monitors:
validations: validations:
required: false required: true
- type: input
id: nodejs-version
attributes:
label: "🟩 NodeJS Version"
description: "If running with Node.js? which version are you running?"
placeholder: "Ex. 14.18.0"
validations:
required: false
- type: textarea - type: textarea
id: logs id: logs
attributes: attributes:

View file

@ -3,14 +3,14 @@ description: "Submit a proposal for a new feature"
#title: "[Feature] " #title: "[Feature] "
labels: [feature-request] labels: [feature-request]
body: body:
- type: checkboxes - type: textarea
id: no-duplicate-issues id: related-issues
validations:
required: true
attributes: attributes:
label: "⚠️ Please verify that this feature request has NOT been suggested before." label: "📑 I have found these related issues/pull requests"
description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)" description: "Search related issues by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=) and explain what the difference between them or explain that you are unable to find any related issues"
options: placeholder: "Related to #1 by also touching the ... system. They should not be merged because ..."
- label: "I checked and didn't find similar feature request"
required: true
- type: dropdown - type: dropdown
id: feature-area id: feature-area
attributes: attributes:
@ -18,10 +18,17 @@ body:
description: "What kind of feature request is this?" description: "What kind of feature request is this?"
multiple: true multiple: true
options: options:
- API - API / automation options
- New Notification - New notification-provider
- New Monitor - Change to existing notification-provider
- UI Feature - New monitor
- Change to existing monitor
- Dashboard
- Status-page
- Maintenance
- Deployment
- Certificate expiry
- Settings
- Other - Other
validations: validations:
required: true required: true

View file

@ -22,7 +22,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [macos-latest, ubuntu-latest, windows-latest, ARM64] os: [macos-latest, ubuntu-latest, windows-latest, ARM64]
node: [ 14, 20.5 ] node: [ 18, 20.5 ]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
@ -33,7 +33,6 @@ jobs:
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node }} node-version: ${{ matrix.node }}
- run: npm install npm@9 -g
- run: npm install - run: npm install
- run: npm run build - run: npm run build
- run: npm run test-backend - run: npm run test-backend
@ -46,11 +45,11 @@ jobs:
needs: [ check-linters ] needs: [ check-linters ]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
timeout-minutes: 15 timeout-minutes: 15
if: ${{ github.repository == 'louislam/uptime-kuma' }}
strategy: strategy:
matrix: matrix:
os: [ ARMv7 ] os: [ ARMv7 ]
node: [ 14, 20 ] node: [ 18, 20 ]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
@ -61,7 +60,6 @@ jobs:
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node }} node-version: ${{ matrix.node }}
- run: npm install npm@9 -g
- run: npm ci --production - run: npm ci --production
check-linters: check-linters:

View file

@ -11,7 +11,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
node-version: [16] node-version: [18]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

25
.github/workflows/conflict_labeler.yml vendored Normal file
View file

@ -0,0 +1,25 @@
name: Merge Conflict Labeler
on:
push:
branches:
- master
pull_request_target:
branches:
- master
types: [synchronize]
jobs:
label:
name: Labeling
runs-on: ubuntu-latest
if: ${{ github.repository == 'louislam/uptime-kuma' }}
permissions:
contents: read
pull-requests: write
steps:
- name: Apply label
uses: eps1lon/actions-label-merge-conflict@v3
with:
dirtyLabel: 'needs:resolve-merge-conflict'
repoToken: '${{ secrets.GITHUB_TOKEN }}'

View file

@ -9,14 +9,34 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v8 - uses: actions/stale@v9
with: with:
stale-issue-message: 'We are clearing up our old issues and your ticket has been open for 3 months with no activity. Remove stale label or comment or this will be closed in 2 days.' stale-issue-message: |-
close-issue-message: 'This issue was closed because it has been stalled for 2 days with no activity.' We are clearing up our old `help`-issues and your issue has been open for 60 days with no activity.
days-before-stale: 90 If no comment is made and the stale label is not removed, this issue will be closed in 7 days.
days-before-close: 2 days-before-stale: 60
days-before-close: 7
days-before-pr-stale: -1 days-before-pr-stale: -1
days-before-pr-close: -1 days-before-pr-close: -1
exempt-issue-labels: 'News,Medium,High,discussion,bug,doc,feature-request' exempt-issue-labels: 'News,Medium,High,discussion,bug,doc,feature-request'
exempt-issue-assignees: 'louislam' exempt-issue-assignees: 'louislam'
operations-per-run: 200 operations-per-run: 200
- uses: actions/stale@v9
with:
stale-issue-message: |-
This issue was marked as `cannot-reproduce` by a maintainer.
If an issue is non-reproducible, we cannot fix it, as we do not know what the underlying issue is.
If you have any ideas how we can reproduce this issue, we would love to hear them.
We don't have a good way to deal with truely unreproducible issues and are going to close this issue in a month.
If think there might be other differences in our environment or in how we tried to reproduce this, we would appreciate any ideas.
close-issue-message: |-
This issue will be closed as no way to reproduce it has been found.
If you/somebody finds a way how to (semi-reliably) reproduce this, we can reopen this issue. ^^
days-before-stale: 180
days-before-close: 30
days-before-pr-stale: -1
days-before-pr-close: -1
any-of-issue-labels: 'cannot-reproduce'
operations-per-run: 200

View file

@ -1,76 +1,193 @@
# Project Info # Project Info
First of all, I want to thank everyone who have made pull requests for Uptime Kuma. I never thought the GitHub community would be so nice! Because of this, I also never thought that other people would actually read and edit my code. It is not very well structured or commented, sorry about that. First of all, I want to thank everyone who have wrote issues or shared pull requests for Uptime Kuma.
I never thought the GitHub community would be so nice!
Because of this, I also never thought that other people would actually read and edit my code.
Parts of the code are not very well-structured or commented, sorry about that.
The project was created with vite.js (vue3). Then I created a subdirectory called "server" for the server part. Both frontend and backend share the same `package.json`. The project was created with `vite.js` and is written in `vue3`.
Our backend lives in the `server`-directory and mostly communicates via websockets.
Both frontend and backend share the same `package.json`.
The frontend code builds into "dist" directory. The server (express.js) exposes the "dist" directory as the root of the endpoint. This is how production is working. For production, the frontend is build into `dist`-directory and the server (`express.js`) exposes the `dist` directory as the root of the endpoint.
For development, we run vite in development mode on another port.
## Key Technical Skills
- Node.js (You should know about promises, async/await, arrow functions, etc.)
- Socket.io
- SCSS
- Vue.js
- Bootstrap
- SQLite
## Directories ## Directories
- config (dev config files) - `config` (dev config files)
- data (App data) - `data` (App data)
- db (Base database and migration scripts) - `db` (Base database and migration scripts)
- dist (Frontend build) - `dist` (Frontend build)
- docker (Dockerfiles) - `docker` (Dockerfiles)
- extra (Extra useful scripts) - `extra` (Extra useful scripts)
- public (Frontend resources for dev only) - `public` (Frontend resources for dev only)
- server (Server source code) - `server` (Server source code)
- src (Frontend source code) - `src` (Frontend source code)
- test (unit test) - `test` (unit test)
## Can I create a pull request for Uptime Kuma? ## Can I create a pull request for Uptime Kuma?
Yes or no, it depends on what you will try to do. Since I don't want to waste your time, be sure to **create an empty draft pull request or open an issue, so we can have a discussion first**. Especially for a large pull request or you don't know if it will be merged or not. Yes or no, it depends on what you will try to do.
Both your and our maintainers time is precious, and we don't want to waste both time.
Here are some references: If you have any questions about any process/.. is not clear, you are likely not alone => please ask them ^^
### ✅ Usually accepted Different guidelines exist for different types of pull requests (PRs):
- <details><summary><b>security fixes</b></summary>
<p>
Submitting security fixes is something that may put the community at risk.
Please read through our [security policy](SECURITY.md) and submit vulnerabilities via an [advisory](https://github.com/louislam/uptime-kuma/security/advisories/new) + [issue](https://github.com/louislam/uptime-kuma/issues/new?assignees=&labels=help&template=security.md) instead.
We encourage you to submit how to fix a vulnerability if you know how to, this is not required.
Following the security policy allows us to properly test, fix bugs.
This review allows us to notice, if there are any changes necessary to unrelated parts like the documentation.
[**PLEASE SEE OUR SECURITY POLICY.**](SECURITY.md)
</p>
</details>
- <details><summary><b>small, non-breaking bug fixes</b></summary>
<p>
If you come across a bug and think you can solve, we appreciate your work.
Please make sure that you follow by these rules:
- keep the PR as small as possible, fix only one thing at a time => keeping it reviewable
- test that your code does what you came it does.
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>translations / internationalisation (i18n)</b></summary>
<p>
We use weblate to localise this project into many languages.
If you are unhappy with a translation this is the best start.
On how to translate using weblate, please see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md).
There are two cases in which a change cannot be done in weblate and requires a PR:
- A text may not be currently localisable. In this case, **adding a new language key** via `$t("languageKey")` might be nessesary
- language keys need to be **added to `en.json`** to be visible in weblate. If this has not happened, a PR is appreciated.
- **Adding a new language** requires a new file see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md)
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>new notification providers</b></summary>
<p>
To set up a new notification provider these files need to be modified/created:
- `server/notification-providers/PROVIDER_NAME.js` is where the heart of the notification provider lives.
- Both `monitorJSON` and `heartbeatJSON` can be `null` for some events.
If both are `null`, this is a general testing message, but if just `heartbeatJSON` is `null` this is a certificate expiry.
- Please wrap the axios call into a
```js
try {
let result = await axios.post(...);
if (result.status === ...) ...
} catch (error) {
this.throwGeneralAxiosError(error);
}
```
- `server/notification.js` is where the backend of the notification provider needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
- `src/components/NotificationDialog.vue` you need to decide if the provider is a regional or a global one and add it with a name to the respective list
- `src/components/notifications/PROVIDER_NAME.vue` is where the frontend of each provider lives.
Please make sure that you have:
- used `HiddenInput` for secret credentials
- included all the necessary helptexts/placeholder/.. to make sure the notification provider is simple to setup for new users.
- include all translations (`{{ $t("Translation key") }}`, [`i18n-t keypath="Translation key">`](https://vue-i18n.intlify.dev/guide/advanced/component.html)) in `src/lang/en.json` to enable our translators to translate this
- `src/components/notifications/index.js` is where the frontend of the provider needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
- Bug fix Offering notifications is close to the core of what we are as an uptime monitor.
- Security fix Therefore, making sure that they work is also really important.
- Adding notification providers Because testing notification providers is quite time intensive, we mostly offload this onto the person contributing a notification provider.
- Adding new language files (see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md))
- Adding new language keys: `$t("...")` To make shure you have tested the notification provider, please include screenshots of the following events in the pull-request description:
- `UP`/`DOWN`
- Certificate Expiry via https://expired.badssl.com/
- Testing (the test button on the notification provider setup page)
Using the following way to format this is encouraged:
```md
| Event | Before | After |
------------------
| `UP` | paste-image-here | paste-image-here |
| `DOWN` | paste-image-here | paste-image-here |
| Certificate-expiry | paste-image-here | paste-image-here |
| Testing | paste-image-here | paste-image-here |
```
### ⚠️ Discussion required <sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>new monitoring types</b></summary>
<p>
- Large pull requests To set up a new notification provider these files need to be modified/created:
- New features - `server/monitor-types/MONITORING_TYPE.js` is the core of each monitor.
the `async check(...)`-function should:
- throw an error for each fault that is detected with an actionable error message
- in the happy-path, you should set `heartbeat.msg` to a successful message and set `heartbeat.status = UP`
- `server/uptime-kuma-server.js` is where the monitoring backend needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
- `src/pages/EditMonitor.vue` is the shared frontend users interact with.
Please make sure that you have:
- used `HiddenInput` for secret credentials
- included all the necessary helptexts/placeholder/.. to make sure the notification provider is simple to setup for new users.
- include all translations (`{{ $t("Translation key") }}`, [`i18n-t keypath="Translation key">`](https://vue-i18n.intlify.dev/guide/advanced/component.html)) in `src/lang/en.json` to enable our translators to translate this
-
### ❌ Won't be merged
- A dedicated PR for translating existing languages (see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md)) <sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
- Do not pass the auto-test </p>
- Any breaking changes </details>
- Duplicated pull requests - <details><summary><b>new features/ major changes / breaking bugfixes</b></summary>
- Buggy <p>
- UI/UX is not close to Uptime Kuma
- Modifications or deletions of existing logic without a valid reason. be sure to **create an empty draft pull request or open an issue, so we can have a discussion first**.
- Adding functions that is completely out of scope This is especially important for a large pull request or you don't know if it will be merged or not.
- Converting existing code into other programming languages
- Unnecessarily large code changes that are hard to review and cause conflicts with other PRs. <sub>Because of the large impact of this work, only senior maintainers may merge PRs in this area.</sub>
</p>
</details>
The above cases may not cover all possible situations. The following rules are essential for making your PR mergable:
- Merging multiple issues by a huge PR is more difficult to review and causes conflicts with other PRs. Please
- (if possible) **create one PR for one issue** or
- (if not possible) **explain which issues a PR addresses and why this PR should not be broken apart**
- Make sure your **PR passes our continuous integration**.
PRs will not be merged unless all CI-Checks are green.
- **Breaking changes** (unless for a good reason and discussed beforehand) will not get merged / not get merged quickly.
Such changes require a major version release.
- **Test your code** before submitting a PR.
Buggy PRs will not be merged.
- Make sure the **UI/UX is close to Uptime Kuma**.
- **Think about the maintainability**:
Don't add functionality that is completely **out of scope**.
Keep in mind that we need to be able to maintain the functionality.
- Don't modify or delete existing logic without a valid reason.
- Don't convert existing code into other programming languages for no reason.
I ([@louislam](https://github.com/louislam)) have the final say. If your pull request does not meet my expectations, I will reject it, no matter how much time you spent on it. Therefore, it is essential to have a discussion beforehand. I ([@louislam](https://github.com/louislam)) have the final say.
If your pull request does not meet my expectations, I will reject it, no matter how much time you spent on it.
Therefore, it is essential to have a discussion beforehand.
I will assign your pull request to a [milestone](https://github.com/louislam/uptime-kuma/milestones), if I plan to review and merge it. I will assign your pull request to a [milestone](https://github.com/louislam/uptime-kuma/milestones), if I plan to review and merge it.
Also, please don't rush or ask for an ETA, because I have to understand the pull request, make sure it is no breaking changes and stick to my vision of this project, especially for large pull requests. Please don't rush or ask for an ETA.
We have to understand the pull request, make sure it has no breaking changes and stick to the vision of this project, especially for large pull requests.
## I'd like to work on an issue. How do I do that?
We have found that assigning people to issues is management-overhead that we don't need.
A short comment that you want to try your hand at this issue is appreciated to save other devs time.
If you come across any problem during development, feel free to leave a comment with what you are stuck on.
### Recommended Pull Request Guideline ### Recommended Pull Request Guideline
Before deep into coding, discussion first is preferred. Creating an empty pull request for discussion would be recommended. Before diving deep into coding, having a discussion first by creating an empty pull request for discussion is preferred.
The rationale behind this is that we can align the direction and scope of the feature to eliminate any conflicts with existing and planned work, and can help by pointing out any potential pitfalls.
1. Fork the project 1. Fork the project
2. Clone your fork repo to local 2. Clone your fork repo to local
@ -84,10 +201,16 @@ Before deep into coding, discussion first is preferred. Creating an empty pull r
## Project Styles ## Project Styles
I personally do not like something that requires so many configurations before you can finally start the app. I hope Uptime Kuma installation will be as easy as like installing a mobile app. I personally do not like something that requires so many configurations before you can finally start the app.
The goal is to make the Uptime Kuma installation as easy as installing a mobile app.
- Easy to install for non-Docker users, no native build dependency is needed (for x86_64/armv7/arm64), no extra config, and no extra effort required to get it running - Easy to install for non-Docker users
- Single container for Docker users, no very complex docker-compose file. Just map the volume and expose the port, then good to go - no native build dependency is needed (for `x86_64`/`armv7`/`arm64`)
- no extra configuration and
- no extra effort required to get it running
- Single container for Docker users
- no complex docker-compose file
- mapping the volume and exposing the port should be the only requirements
- Settings should be configurable in the frontend. Environment variables are discouraged, unless it is related to startup such as `DATA_DIR` - Settings should be configurable in the frontend. Environment variables are discouraged, unless it is related to startup such as `DATA_DIR`
- Easy to use - Easy to use
- The web UI styling should be consistent and nice - The web UI styling should be consistent and nice
@ -107,18 +230,12 @@ I personally do not like something that requires so many configurations before y
## Tools ## Tools
- [`Node.js`](https://nodejs.org/) >= 14 - [`Node.js`](https://nodejs.org/) >= 18
- [`npm`](https://www.npmjs.com/) >= 8.5 - [`npm`](https://www.npmjs.com/) >= 9.3
- [`git`](https://git-scm.com/) - [`git`](https://git-scm.com/)
- IDE that supports [`ESLint`](https://eslint.org/) and EditorConfig (I am using [`IntelliJ IDEA`](https://www.jetbrains.com/idea/)) - IDE that supports [`ESLint`](https://eslint.org/) and EditorConfig (I am using [`IntelliJ IDEA`](https://www.jetbrains.com/idea/))
- A SQLite GUI tool (f.ex. [`SQLite Expert Personal`](https://www.sqliteexpert.com/download.html) or [`DBeaver Community`](https://dbeaver.io/download/)) - A SQLite GUI tool (f.ex. [`SQLite Expert Personal`](https://www.sqliteexpert.com/download.html) or [`DBeaver Community`](https://dbeaver.io/download/))
### GitHub Codespaces
If you don't want to setup an local environment, you can now develop on GitHub Codespaces, read more:
https://github.com/louislam/uptime-kuma/tree/master/.devcontainer
## Git Branches ## Git Branches
- `master`: 2.X.X development. If you want to add a new feature, your pull request should base on this. - `master`: 2.X.X development. If you want to add a new feature, your pull request should base on this.
@ -154,25 +271,25 @@ npm run start-server-dev
It binds to `0.0.0.0:3001` by default. It binds to `0.0.0.0:3001` by default.
It is mainly a socket.io app + express.js. The backend is an `express.js` server with `socket.io` integrated.
It uses `socket.io` to communicate with clients, and most server logic is encapsulated in the `socket.io` handlers.
`express.js` is also used to serve:
express.js is used for: - as an entry point for redirecting to a status page or the dashboard
- the frontend built files (`index.html`, `*.js`, `*.css`, etc.)
- internal APIs of the status page
- entry point such as redirecting to a status page or the dashboard ### Structure in `/server/`
- serving the frontend built files (index.html, .js and .css etc.)
- serving internal APIs of the status page
### Structure in /server/ - `jobs/` (Jobs that are running in another process)
- `model/` (Object model, auto-mapping to the database table name)
- jobs/ (Jobs that are running in another process) - `modules/` (Modified 3rd-party modules)
- model/ (Object model, auto-mapping to the database table name) - `monitor_types/` (Monitor Types)
- modules/ (Modified 3rd-party modules) - `notification-providers/` (individual notification logic)
- monitor_types (Monitor Types) - `routers/` (Express Routers)
- notification-providers/ (individual notification logic) - `socket-handler/` (Socket.io Handlers)
- routers/ (Express Routers) - `server.js` (Server entry point)
- socket-handler (Socket.io Handlers) - `uptime-kuma-server.js` (UptimeKumaServer class, main logic should be here, but some still in `server.js`)
- server.js (Server entry point)
- uptime-kuma-server.js (UptimeKumaServer class, main logic should be here, but some still in `server.js`)
## Frontend Dev Server ## Frontend Dev Server
@ -211,14 +328,15 @@ npm test
## Dependencies ## Dependencies
Both frontend and backend share the same package.json. However, the frontend dependencies are eventually not used in the production environment, because it is usually also baked into dist files. So: Both frontend and backend share the same `package.json`.
However, the frontend dependencies are eventually not used in the production environment, because it is usually also baked into `dist` files. So:
- Frontend dependencies = "devDependencies" - Frontend dependencies = "devDependencies"
- Examples: vue, chart.js - Examples: `vue`, `chart.js`
- Backend dependencies = "dependencies" - Backend dependencies = "dependencies"
- Examples: socket.io, sqlite3 - Examples: `socket.io`, `sqlite3`
- Development dependencies = "devDependencies" - Development dependencies = "devDependencies"
- Examples: eslint, sass - Examples: `eslint`, `sass`
### Update Dependencies ### Update Dependencies
@ -289,54 +407,106 @@ https://github.com/louislam/uptime-kuma-wiki
Check the latest issues and pull requests: Check the latest issues and pull requests:
https://github.com/louislam/uptime-kuma/issues?q=sort%3Aupdated-desc https://github.com/louislam/uptime-kuma/issues?q=sort%3Aupdated-desc
### Release Procedures ### What is a maintainer and what are their roles?
1. Draft a release note This project has multiple maintainers which specialise in different areas.
2. Make sure the repo is cleared Currently, there are 3 maintainers:
3. If the healthcheck is updated, remember to re-compile it: `npm run build-docker-builder-go`
4. `npm run release-final` with env vars: `VERSION` and `GITHUB_TOKEN`
5. Wait until the `Press any key to continue`
6. `git push`
7. Publish the release note as 1.X.X
8. Press any key to continue
9. Deploy to the demo server: `npm run deploy-demo-server`
Checking: | Person | Role | Main Area |
|-------------------|-------------------|------------------|
| `@louislam` | senior maintainer | major features |
| `@chakflying` | junior maintainer | fixing bugs |
| `@commanderstorm` | junior maintainer | issue-management |
- Check all tags is fine on https://hub.docker.com/r/louislam/uptime-kuma/tags ### Procedures
- Try the Docker image with tag 1.X.X (Clean install / amd64 / arm64 / armv7)
- Try clean installation with Node.js
### Release Beta Procedures We have a few procedures we follow. These are documented here:
- <details><summary>Set up a Docker Builder</summary>
<p>
1. Draft a release note, check "This is a pre-release" - amd64, armv7 using local.
2. Make sure the repo is cleared - arm64 using remote arm64 cpu, as the emulator is too slow and can no longer pass the `npm ci` command.
3. `npm run release-beta` with env vars: `VERSION` and `GITHUB_TOKEN` 1. Add the public key to the remote server.
4. Wait until the `Press any key to continue` 2. Add the remote context. The remote machine must be arm64 and installed Docker CE.
5. Publish the release note as 1.X.X-beta.X ```
6. Press any key to continue docker context create oracle-arm64-jp --docker "host=ssh://root@100.107.174.88"
```
3. Create a new builder.
```
docker buildx create --name kuma-builder --platform linux/amd64,linux/arm/v7
docker buildx use kuma-builder
docker buildx inspect --bootstrap
```
4. Append the remote context to the builder.
```
docker buildx create --append --name kuma-builder --platform linux/arm64 oracle-arm64-jp
```
5. Verify the builder and check if the builder is using `kuma-builder`.
```
docker buildx inspect kuma-builder
docker buildx ls
```
</p>
</details>
- <details><summary>Release</summary>
<p>
### Release Wiki 1. Draft a release note
2. Make sure the repo is cleared
3. If the healthcheck is updated, remember to re-compile it: `npm run build-docker-builder-go`
4. `npm run release-final` with env vars: `VERSION` and `GITHUB_TOKEN`
5. Wait until the `Press any key to continue`
6. `git push`
7. Publish the release note as `1.X.X`
8. Press any key to continue
9. Deploy to the demo server: `npm run deploy-demo-server`
#### Setup Repo These Items need to be checked:
```bash - [ ] Check all tags is fine on https://hub.docker.com/r/louislam/uptime-kuma/tags
git clone https://github.com/louislam/uptime-kuma-wiki.git - [ ] Try the Docker image with tag 1.X.X (Clean install / amd64 / arm64 / armv7)
cd uptime-kuma-wiki - [ ] Try clean installation with Node.js
git remote add production https://github.com/louislam/uptime-kuma.wiki.git
``` </p>
</details>
- <details><summary>Release Beta</summary>
<p>
#### Push to Production Wiki 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
</p>
</details>
- <details><summary>Release Wiki</summary>
<p>
```bash **Setup Repo**
git pull
git push production master ```bash
``` git clone https://github.com/louislam/uptime-kuma-wiki.git
cd uptime-kuma-wiki
## Useful Commands git remote add production https://github.com/louislam/uptime-kuma.wiki.git
```
Change the base of a pull request such as `master` to `1.23.X`
**Push to Production Wiki**
```bash
git rebase --onto <new parent> <old parent> ```bash
``` git pull
git push production master
```
</p>
</details>
- <details><summary>Change the base of a pull request such as <code>master</code> to <code>1.23.X</code></summary>
<p>
```bash
git rebase --onto <new parent> <old parent>
```
</p>
</details>

View file

@ -43,11 +43,18 @@ It is a temporary live demo, all data will be deleted after 10 minutes. Sponsore
docker run -d --restart=always -p 3001:3001 -v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1 docker run -d --restart=always -p 3001:3001 -v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
``` ```
Uptime Kuma is now running on http://localhost:3001 Uptime Kuma is now running on <http://0.0.0.0:3001>.
> [!WARNING] > [!WARNING]
> File Systems like **NFS** (Network File System) are **NOT** supported. Please map to a local directory or volume. > File Systems like **NFS** (Network File System) are **NOT** supported. Please map to a local directory or volume.
> [!NOTE]
> If you want to limit exposure to localhost (without exposing port for other users or to use a [reverse proxy](https://github.com/louislam/uptime-kuma/wiki/Reverse-Proxy)), you can expose the port like this:
>
> ```bash
> docker run -d --restart=always -p 127.0.0.1:3001:3001 -v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
> ```
### 💪🏻 Non-Docker ### 💪🏻 Non-Docker
Requirements: Requirements:
@ -56,15 +63,12 @@ Requirements:
- ✅ Major Linux distros such as Debian, Ubuntu, CentOS, Fedora and ArchLinux etc. - ✅ Major Linux distros such as Debian, Ubuntu, CentOS, Fedora and ArchLinux etc.
- ✅ Windows 10 (x64), Windows Server 2012 R2 (x64) or higher - ✅ Windows 10 (x64), Windows Server 2012 R2 (x64) or higher
- ❌ Replit / Heroku - ❌ Replit / Heroku
- [Node.js](https://nodejs.org/en/download/) 14 / 16 / 18 / 20.4 - [Node.js](https://nodejs.org/en/download/) 18 / 20.4
- [npm](https://docs.npmjs.com/cli/) 9 - [npm](https://docs.npmjs.com/cli/) 9
- [Git](https://git-scm.com/downloads) - [Git](https://git-scm.com/downloads)
- [pm2](https://pm2.keymetrics.io/) - For running Uptime Kuma in the background - [pm2](https://pm2.keymetrics.io/) - For running Uptime Kuma in the background
```bash ```bash
# Update your npm
npm install npm@9 -g
git clone https://github.com/louislam/uptime-kuma.git git clone https://github.com/louislam/uptime-kuma.git
cd uptime-kuma cd uptime-kuma
npm run setup npm run setup

View file

@ -1,28 +0,0 @@
const { defineConfig } = require("cypress");
module.exports = defineConfig({
projectId: "vyjuem",
e2e: {
experimentalStudio: true,
setupNodeEvents(on, config) {
},
fixturesFolder: "test/cypress/fixtures",
screenshotsFolder: "test/cypress/screenshots",
videosFolder: "test/cypress/videos",
downloadsFolder: "test/cypress/downloads",
supportFile: "test/cypress/support/e2e.js",
baseUrl: "http://localhost:3002",
defaultCommandTimeout: 10000,
pageLoadTimeout: 60000,
viewportWidth: 1920,
viewportHeight: 1080,
specPattern: [
"test/cypress/e2e/setup.cy.js",
"test/cypress/e2e/**/*.js"
],
},
env: {
baseUrl: "http://localhost:3002",
},
});

View file

@ -1,10 +0,0 @@
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
supportFile: false,
specPattern: [
"test/cypress/unit/**/*.js"
],
}
});

View file

@ -1,11 +1,11 @@
import { defineConfig, devices } from "@playwright/test"; import { defineConfig, devices } from "@playwright/test";
const port = 30001; const port = 30001;
const url = `http://localhost:${port}`; export const url = `http://localhost:${port}`;
export default defineConfig({ export default defineConfig({
// Look for test files in the "tests" directory, relative to this configuration file. // Look for test files in the "tests" directory, relative to this configuration file.
testDir: "../test/e2e", testDir: "../test/e2e/specs",
outputDir: "../private/playwright-test-results", outputDir: "../private/playwright-test-results",
fullyParallel: false, fullyParallel: false,
locale: "en-US", locale: "en-US",
@ -40,9 +40,15 @@ export default defineConfig({
// Configure projects for major browsers. // Configure projects for major browsers.
projects: [ projects: [
{ {
name: "chromium", name: "run-once setup",
testMatch: /setup-process\.once\.js/,
use: { ...devices["Desktop Chrome"] }, use: { ...devices["Desktop Chrome"] },
}, },
{
name: "specs",
use: { ...devices["Desktop Chrome"] },
dependencies: [ "run-once setup" ],
},
/* /*
{ {
name: "firefox", name: "firefox",
@ -52,7 +58,7 @@ export default defineConfig({
// Run your local dev server before starting the tests. // Run your local dev server before starting the tests.
webServer: { webServer: {
command: `node extra/remove-playwright-test-data.js && node server/server.js --port=${port} --data-dir=./data/playwright-test`, command: `node extra/remove-playwright-test-data.js && cross-env NODE_ENV=development node server/server.js --port=${port} --data-dir=./data/playwright-test`,
url, url,
reuseExistingServer: false, reuseExistingServer: false,
cwd: "../", cwd: "../",

View file

@ -2,6 +2,7 @@ import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import visualizer from "rollup-plugin-visualizer"; import visualizer from "rollup-plugin-visualizer";
import viteCompression from "vite-plugin-compression"; import viteCompression from "vite-plugin-compression";
import VueDevTools from "vite-plugin-vue-devtools";
const postCssScss = require("postcss-scss"); const postCssScss = require("postcss-scss");
const postcssRTLCSS = require("postcss-rtlcss"); const postcssRTLCSS = require("postcss-rtlcss");
@ -32,6 +33,7 @@ export default defineConfig({
algorithm: "brotliCompress", algorithm: "brotliCompress",
filter: viteCompressionFilter, filter: viteCompressionFilter,
}), }),
VueDevTools(),
], ],
css: { css: {
postcss: { postcss: {

View file

@ -318,7 +318,10 @@ async function createTables() {
// monitor_tls_info // monitor_tls_info
await knex.schema.createTable("monitor_tls_info", (table) => { await knex.schema.createTable("monitor_tls_info", (table) => {
table.increments("id"); table.increments("id");
table.integer("monitor_id").unsigned().notNullable(); //TODO: no fk ? table.integer("monitor_id").unsigned().notNullable()
.references("id").inTable("monitor")
.onDelete("CASCADE")
.onUpdate("CASCADE");
table.text("info_json"); table.text("info_json");
}); });

View file

@ -0,0 +1,12 @@
exports.up = function (knex) {
return knex.schema
.alterTable("status_page", function (table) {
table.integer("auto_refresh_interval").defaultTo(300).unsigned();
});
};
exports.down = function (knex) {
return knex.schema.alterTable("status_page", function (table) {
table.dropColumn("auto_refresh_interval");
});
};

View file

@ -0,0 +1,26 @@
exports.up = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
})
.alterTable("stat_minutely", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
})
.alterTable("stat_hourly", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
});
};
exports.down = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.dropColumn("extras");
})
.alterTable("stat_minutely", function (table) {
table.dropColumn("extras");
})
.alterTable("stat_hourly", function (table) {
table.dropColumn("extras");
});
};

View file

@ -0,0 +1,16 @@
exports.up = function (knex) {
return knex.schema
.alterTable("monitor", function (table) {
table.string("snmp_oid").defaultTo(null);
table.enum("snmp_version", [ "1", "2c", "3" ]).defaultTo("2c");
table.string("json_path_operator").defaultTo(null);
});
};
exports.down = function (knex) {
return knex.schema.alterTable("monitor", function (table) {
table.dropColumn("snmp_oid");
table.dropColumn("snmp_version");
table.dropColumn("json_path_operator");
});
};

View file

@ -0,0 +1,13 @@
exports.up = function (knex) {
return knex.schema
.alterTable("monitor", function (table) {
table.boolean("cache_bust").notNullable().defaultTo(false);
});
};
exports.down = function (knex) {
return knex.schema
.alterTable("monitor", function (table) {
table.dropColumn("cache_bust");
});
};

View file

@ -0,0 +1,12 @@
exports.up = function (knex) {
return knex.schema
.alterTable("monitor", function (table) {
table.text("conditions").notNullable().defaultTo("[]");
});
};
exports.down = function (knex) {
return knex.schema.alterTable("monitor", function (table) {
table.dropColumn("conditions");
});
};

View file

@ -0,0 +1,18 @@
BEGIN TRANSACTION;
PRAGMA writable_schema = TRUE;
UPDATE
SQLITE_MASTER
SET
sql = replace(sql,
'monitor_id INTEGER NOT NULL',
'monitor_id INTEGER NOT NULL REFERENCES [monitor] ([id]) ON DELETE CASCADE ON UPDATE CASCADE'
)
WHERE
name = 'monitor_tls_info'
AND type = 'table';
PRAGMA writable_schema = RESET;
COMMIT;

View file

@ -0,0 +1,18 @@
BEGIN TRANSACTION;
PRAGMA writable_schema = TRUE;
UPDATE
SQLITE_MASTER
SET
sql = replace(sql,
'monitor_id INTEGER NOT NULL',
'monitor_id INTEGER NOT NULL REFERENCES [monitor] ([id]) ON DELETE CASCADE ON UPDATE CASCADE'
)
WHERE
name = 'monitor_tls_info'
AND type = 'table';
PRAGMA writable_schema = RESET;
COMMIT;

View file

@ -3,7 +3,6 @@ FROM node:20-bookworm-slim AS base2-slim
ARG TARGETPLATFORM ARG TARGETPLATFORM
# Specify --no-install-recommends to skip unused dependencies, make the base much smaller! # Specify --no-install-recommends to skip unused dependencies, make the base much smaller!
# apprise = for notifications (From testing repo)
# sqlite3 = for debugging # sqlite3 = for debugging
# iputils-ping = for ping # iputils-ping = for ping
# util-linux = for setpriv (Should be dropped in 2.0.0?) # util-linux = for setpriv (Should be dropped in 2.0.0?)
@ -12,10 +11,10 @@ ARG TARGETPLATFORM
# ca-certificates = keep the cert up-to-date # ca-certificates = keep the cert up-to-date
# sudo = for start service nscd with non-root user # sudo = for start service nscd with non-root user
# nscd = for better DNS caching # nscd = for better DNS caching
RUN echo "deb http://deb.debian.org/debian testing main" >> /etc/apt/sources.list && \ RUN apt update && \
apt update && \ apt --yes --no-install-recommends install \
apt --yes --no-install-recommends -t testing install apprise sqlite3 ca-certificates && \ sqlite3 \
apt --yes --no-install-recommends -t stable install \ ca-certificates \
iputils-ping \ iputils-ping \
util-linux \ util-linux \
dumb-init \ dumb-init \
@ -25,6 +24,15 @@ RUN echo "deb http://deb.debian.org/debian testing main" >> /etc/apt/sources.lis
rm -rf /var/lib/apt/lists/* && \ rm -rf /var/lib/apt/lists/* && \
apt --yes autoremove apt --yes autoremove
# apprise = for notifications (Install from the deb package, as the stable one is too old) (workaround for #4867)
# Switching to testing repo is no longer working, as the testing repo is not bookworm anymore.
# python3-paho-mqtt (#4859)
RUN curl http://ftp.debian.org/debian/pool/main/a/apprise/apprise_1.8.0-2_all.deb --output apprise.deb && \
apt update && \
apt --yes --no-install-recommends install ./apprise.deb python3-paho-mqtt && \
rm -rf /var/lib/apt/lists/* && \
rm -f apprise.deb && \
apt --yes autoremove
# Install cloudflared # Install cloudflared
RUN curl https://pkg.cloudflare.com/cloudflare-main.gpg --output /usr/share/keyrings/cloudflare-main.gpg && \ RUN curl https://pkg.cloudflare.com/cloudflare-main.gpg --output /usr/share/keyrings/cloudflare-main.gpg && \
@ -42,7 +50,9 @@ COPY ./docker/etc/sudoers /etc/sudoers
# Full Base Image # Full Base Image
# MariaDB, Chromium and fonts # MariaDB, Chromium and fonts
FROM base2-slim AS base2 # Make sure to reuse the slim image here. Uncomment the above line if you want to build it from scratch.
# FROM base2-slim AS base2
FROM louislam/uptime-kuma:base2-slim AS base2
ENV UPTIME_KUMA_ENABLE_EMBEDDED_MARIADB=1 ENV UPTIME_KUMA_ENABLE_EMBEDDED_MARIADB=1
RUN apt update && \ RUN apt update && \
apt --yes --no-install-recommends install chromium fonts-indic fonts-noto fonts-noto-cjk mariadb-server && \ apt --yes --no-install-recommends install chromium fonts-indic fonts-noto fonts-noto-cjk mariadb-server && \

View file

@ -37,7 +37,7 @@ const github = require("@actions/github");
owner: issue.owner, owner: issue.owner,
repo: issue.repo, repo: issue.repo,
issue_number: issue.number, issue_number: issue.number,
body: `@${username}: Hello! :wave:\n\nThis issue is being automatically closed because it does not follow the issue template. Please DO NOT open a blank issue.` body: `@${username}: Hello! :wave:\n\nThis issue is being automatically closed because it does not follow the issue template. Please **DO NOT open blank issues and use our [issue-templates](https://github.com/louislam/uptime-kuma/issues/new/choose) instead**.\nBlank Issues do not contain the context nessesary for a good discussions.`
}); });
// Close the issue // Close the issue

View file

@ -8,6 +8,7 @@ const User = require("../server/model/user");
const { io } = require("socket.io-client"); const { io } = require("socket.io-client");
const { localWebSocketURL } = require("../server/config"); const { localWebSocketURL } = require("../server/config");
const args = require("args-parser")(process.argv); const args = require("args-parser")(process.argv);
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout output: process.stdout
@ -19,10 +20,10 @@ const main = async () => {
} }
console.log("Connecting the database"); console.log("Connecting the database");
Database.initDataDir(args);
await Database.connect(false, false, true);
try { try {
Database.initDataDir(args);
await Database.connect(false, false, true);
// No need to actually reset the password for testing, just make sure no connection problem. It is ok for now. // No need to actually reset the password for testing, just make sure no connection problem. It is ok for now.
if (!process.env.TEST_BACKEND) { if (!process.env.TEST_BACKEND) {
const user = await R.findOne("user"); const user = await R.findOne("user");

9254
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,7 @@
"url": "https://github.com/louislam/uptime-kuma.git" "url": "https://github.com/louislam/uptime-kuma.git"
}, },
"engines": { "engines": {
"node": "14 || 16 || 18 || >= 20.4.0" "node": "18 || >= 20.4.0"
}, },
"scripts": { "scripts": {
"lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .", "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
@ -27,9 +27,7 @@
"build": "vite build --config ./config/vite.config.js", "build": "vite build --config ./config/vite.config.js",
"test": "npm run test-backend && npm run test-e2e", "test": "npm run test-backend && npm run test-e2e",
"test-with-build": "npm run build && npm test", "test-with-build": "npm run build && npm test",
"test-backend": "node test/backend-test-entry.js", "test-backend": "cross-env TEST_BACKEND=1 node --test test/backend-test",
"test-backend:14": "cross-env TEST_BACKEND=1 NODE_OPTIONS=\"--experimental-abortcontroller --no-warnings\" node--test test/backend-test",
"test-backend:18": "cross-env TEST_BACKEND=1 node --test test/backend-test",
"test-e2e": "playwright test --config ./config/playwright.config.js", "test-e2e": "playwright test --config ./config/playwright.config.js",
"test-e2e-ui": "playwright test --config ./config/playwright.config.js --ui --ui-port=51063", "test-e2e-ui": "playwright test --config ./config/playwright.config.js --ui --ui-port=51063",
"playwright-codegen": "playwright codegen localhost:3000 --save-storage=./private/e2e-auth.json", "playwright-codegen": "playwright codegen localhost:3000 --save-storage=./private/e2e-auth.json",
@ -49,7 +47,7 @@
"build-docker-nightly-local": "npm run build && docker build -f docker/dockerfile -t louislam/uptime-kuma:nightly2 --target nightly .", "build-docker-nightly-local": "npm run build && docker build -f docker/dockerfile -t louislam/uptime-kuma:nightly2 --target nightly .",
"build-docker-pr-test": "docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64 -t louislam/uptime-kuma:pr-test2 --target pr-test2 . --push", "build-docker-pr-test": "docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64 -t louislam/uptime-kuma:pr-test2 --target pr-test2 . --push",
"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", "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.23.11 && npm ci --production && npm run download-dist", "setup": "git checkout 1.23.13 && npm ci --production && npm run download-dist",
"download-dist": "node extra/download-dist.js", "download-dist": "node extra/download-dist.js",
"mark-as-nightly": "node extra/mark-as-nightly.js", "mark-as-nightly": "node extra/mark-as-nightly.js",
"reset-password": "node extra/reset-password.js", "reset-password": "node extra/reset-password.js",
@ -77,9 +75,9 @@
"@grpc/grpc-js": "~1.7.3", "@grpc/grpc-js": "~1.7.3",
"@louislam/ping": "~0.4.4-mod.1", "@louislam/ping": "~0.4.4-mod.1",
"@louislam/sqlite3": "15.1.6", "@louislam/sqlite3": "15.1.6",
"@vvo/tzdb": "^6.125.0",
"args-parser": "~1.3.0", "args-parser": "~1.3.0",
"axios": "~0.27.0", "axios": "~0.28.1",
"axios-ntlm": "1.3.0",
"badge-maker": "~3.3.1", "badge-maker": "~3.3.1",
"bcryptjs": "~2.4.3", "bcryptjs": "~2.4.3",
"chardet": "~1.4.0", "chardet": "~1.4.0",
@ -89,12 +87,14 @@
"command-exists": "~1.2.9", "command-exists": "~1.2.9",
"compare-versions": "~3.6.0", "compare-versions": "~3.6.0",
"compression": "~1.7.4", "compression": "~1.7.4",
"croner": "~6.0.5", "croner": "~8.1.0",
"dayjs": "~1.11.5", "dayjs": "~1.11.5",
"dev-null": "^0.1.1",
"dotenv": "~16.0.3", "dotenv": "~16.0.3",
"express": "~4.17.3", "express": "~4.19.2",
"express-basic-auth": "~1.2.1", "express-basic-auth": "~1.2.1",
"express-static-gzip": "~2.1.7", "express-static-gzip": "~2.1.7",
"feed": "^4.2.2",
"form-data": "~4.0.0", "form-data": "~4.0.0",
"gamedig": "^4.2.0", "gamedig": "^4.2.0",
"html-escaper": "^3.0.3", "html-escaper": "^3.0.3",
@ -112,15 +112,17 @@
"knex": "^2.4.2", "knex": "^2.4.2",
"limiter": "~2.1.0", "limiter": "~2.1.0",
"liquidjs": "^10.7.0", "liquidjs": "^10.7.0",
"marked": "^14.0.0",
"mitt": "~3.0.1", "mitt": "~3.0.1",
"mongodb": "~4.17.1", "mongodb": "~4.17.1",
"mqtt": "~4.3.7", "mqtt": "~4.3.7",
"mssql": "~8.1.4", "mssql": "~11.0.0",
"mysql2": "~3.6.2", "mysql2": "~3.9.6",
"nanoid": "~3.3.4", "nanoid": "~3.3.4",
"net-snmp": "^3.11.2",
"node-cloudflared-tunnel": "~1.0.9", "node-cloudflared-tunnel": "~1.0.9",
"node-radius-client": "~1.0.0", "node-radius-client": "~1.0.0",
"nodemailer": "~6.6.5", "nodemailer": "~6.9.13",
"nostr-tools": "^1.13.1", "nostr-tools": "^1.13.1",
"notp": "~2.0.3", "notp": "~2.0.3",
"openid-client": "^5.4.2", "openid-client": "^5.4.2",
@ -136,17 +138,17 @@
"redbean-node": "~0.3.0", "redbean-node": "~0.3.0",
"redis": "~4.5.1", "redis": "~4.5.1",
"semver": "~7.5.4", "semver": "~7.5.4",
"socket.io": "~4.6.1", "socket.io": "~4.7.5",
"socket.io-client": "~4.6.1", "socket.io-client": "~4.7.5",
"socks-proxy-agent": "6.1.1", "socks-proxy-agent": "6.1.1",
"tar": "~6.1.11", "tar": "~6.2.1",
"tcp-ping": "~0.1.1", "tcp-ping": "~0.1.1",
"thirty-two": "~1.0.2", "thirty-two": "~1.0.2",
"tough-cookie": "~4.1.3", "tough-cookie": "~4.1.3",
"ws": "^8.13.0" "ws": "^8.13.0"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "~5.0.1", "@actions/github": "~5.1.1",
"@fortawesome/fontawesome-svg-core": "~1.2.36", "@fortawesome/fontawesome-svg-core": "~1.2.36",
"@fortawesome/free-regular-svg-icons": "~5.15.4", "@fortawesome/free-regular-svg-icons": "~5.15.4",
"@fortawesome/free-solid-svg-icons": "~5.15.4", "@fortawesome/free-solid-svg-icons": "~5.15.4",
@ -170,13 +172,12 @@
"cross-env": "~7.0.3", "cross-env": "~7.0.3",
"delay": "^5.0.0", "delay": "^5.0.0",
"dns2": "~2.0.1", "dns2": "~2.0.1",
"dompurify": "~2.4.3", "dompurify": "~3.0.11",
"eslint": "~8.14.0", "eslint": "~8.14.0",
"eslint-plugin-jsdoc": "~46.4.6", "eslint-plugin-jsdoc": "~46.4.6",
"eslint-plugin-vue": "~8.7.1", "eslint-plugin-vue": "~8.7.1",
"favico.js": "~0.3.10", "favico.js": "~0.3.10",
"get-port-please": "^3.1.1", "get-port-please": "^3.1.1",
"marked": "~4.2.5",
"node-ssh": "~13.1.0", "node-ssh": "~13.1.0",
"postcss-html": "~1.5.0", "postcss-html": "~1.5.0",
"postcss-rtlcss": "~3.7.2", "postcss-rtlcss": "~3.7.2",
@ -189,11 +190,11 @@
"stylelint-config-standard": "~25.0.0", "stylelint-config-standard": "~25.0.0",
"terser": "~5.15.0", "terser": "~5.15.0",
"test": "~3.3.0", "test": "~3.3.0",
"timezones-list": "~3.0.1",
"typescript": "~4.4.4", "typescript": "~4.4.4",
"v-pagination-3": "~0.1.7", "v-pagination-3": "~0.1.7",
"vite": "~5.0.10", "vite": "~5.2.8",
"vite-plugin-compression": "^0.5.1", "vite-plugin-compression": "^0.5.1",
"vite-plugin-vue-devtools": "^7.0.15",
"vue": "~3.4.2", "vue": "~3.4.2",
"vue-chartjs": "~5.2.0", "vue-chartjs": "~5.2.0",
"vue-confirm-dialog": "~1.0.2", "vue-confirm-dialog": "~1.0.2",

View file

@ -129,7 +129,7 @@ function userAuthorizer(username, password, callback) {
* @param {express.Request} req Express request object * @param {express.Request} req Express request object
* @param {express.Response} res Express response object * @param {express.Response} res Express response object
* @param {express.NextFunction} next Next handler in chain * @param {express.NextFunction} next Next handler in chain
* @returns {void} * @returns {Promise<void>}
*/ */
exports.basicAuth = async function (req, res, next) { exports.basicAuth = async function (req, res, next) {
const middleware = basicAuth({ const middleware = basicAuth({
@ -152,7 +152,7 @@ exports.basicAuth = async function (req, res, next) {
* @param {express.Request} req Express request object * @param {express.Request} req Express request object
* @param {express.Response} res Express response object * @param {express.Response} res Express response object
* @param {express.NextFunction} next Next handler in chain * @param {express.NextFunction} next Next handler in chain
* @returns {void} * @returns {Promise<void>}
*/ */
exports.apiAuth = async function (req, res, next) { exports.apiAuth = async function (req, res, next) {
if (!await Settings.get("disableAuth")) { if (!await Settings.get("disableAuth")) {

View file

@ -8,6 +8,7 @@ const server = UptimeKumaServer.getInstance();
const io = server.io; const io = server.io;
const checkVersion = require("./check-version"); const checkVersion = require("./check-version");
const { Settings } = require("./settings"); const { Settings } = require("./settings");
const Database = require("./database");
/** /**
* Send list of notification providers to client * Send list of notification providers to client
@ -144,11 +145,13 @@ async function sendInfo(socket, hideVersion = false) {
let version; let version;
let latestVersion; let latestVersion;
let isContainer; let isContainer;
let dbType;
if (!hideVersion) { if (!hideVersion) {
version = checkVersion.version; version = checkVersion.version;
latestVersion = checkVersion.latestVersion; latestVersion = checkVersion.latestVersion;
isContainer = (process.env.UPTIME_KUMA_IS_CONTAINER === "1"); isContainer = (process.env.UPTIME_KUMA_IS_CONTAINER === "1");
dbType = Database.dbConfig.type;
} }
socket.emit("info", { socket.emit("info", {
@ -156,6 +159,7 @@ async function sendInfo(socket, hideVersion = false) {
latestVersion, latestVersion,
isContainer, isContainer,
primaryBaseURL: await Settings.get("primaryBaseURL"), primaryBaseURL: await Settings.get("primaryBaseURL"),
dbType,
serverTimezone: await server.getTimezone(), serverTimezone: await server.getTimezone(),
serverTimezoneOffset: server.getTimezoneOffset(), serverTimezoneOffset: server.getTimezoneOffset(),
}); });
@ -209,6 +213,32 @@ async function sendRemoteBrowserList(socket) {
return list; return list;
} }
/**
* Send list of monitor types to client
* @param {Socket} socket Socket.io socket instance
* @returns {Promise<void>}
*/
async function sendMonitorTypeList(socket) {
const result = Object.entries(UptimeKumaServer.monitorTypeList).map(([ key, type ]) => {
return [ key, {
supportsConditions: type.supportsConditions,
conditionVariables: type.conditionVariables.map(v => {
return {
id: v.id,
operators: v.operators.map(o => {
return {
id: o.id,
caption: o.caption,
};
}),
};
}),
}];
});
io.to(socket.userID).emit("monitorTypeList", Object.fromEntries(result));
}
module.exports = { module.exports = {
sendNotificationList, sendNotificationList,
sendImportantHeartbeatList, sendImportantHeartbeatList,
@ -218,4 +248,5 @@ module.exports = {
sendInfo, sendInfo,
sendDockerHostList, sendDockerHostList,
sendRemoteBrowserList, sendRemoteBrowserList,
sendMonitorTypeList,
}; };

View file

@ -105,7 +105,8 @@ class Database {
"patch-add-gamedig-given-port.sql": true, "patch-add-gamedig-given-port.sql": true,
"patch-notification-config.sql": true, "patch-notification-config.sql": true,
"patch-fix-kafka-producer-booleans.sql": true, "patch-fix-kafka-producer-booleans.sql": true,
"patch-timeout.sql": true, // The last file so far converted to a knex migration file "patch-timeout.sql": true,
"patch-monitor-tls-info-add-fk.sql": true, // The last file so far converted to a knex migration file
}; };
/** /**
@ -208,9 +209,9 @@ class Database {
let config = {}; let config = {};
let mariadbPoolConfig = { let mariadbPoolConfig = {
afterCreate: function (conn, done) { min: 0,
max: 10,
} idleTimeoutMillis: 30000,
}; };
log.info("db", `Database Type: ${dbConfig.type}`); log.info("db", `Database Type: ${dbConfig.type}`);
@ -378,7 +379,7 @@ class Database {
/** /**
* Patch the database * Patch the database
* @returns {void} * @returns {Promise<void>}
*/ */
static async patch() { static async patch() {
// Still need to keep this for old versions of Uptime Kuma // Still need to keep this for old versions of Uptime Kuma

View file

@ -65,7 +65,7 @@ class DockerHost {
/** /**
* Fetches the amount of containers on the Docker host * Fetches the amount of containers on the Docker host
* @param {object} dockerHost Docker host to check for * @param {object} dockerHost Docker host to check for
* @returns {number} Total amount of containers on the host * @returns {Promise<number>} Total amount of containers on the host
*/ */
static async testDockerHost(dockerHost) { static async testDockerHost(dockerHost) {
const options = { const options = {

View file

@ -9,7 +9,7 @@ class Group extends BeanModel {
* @param {boolean} showTags Should the JSON include monitor tags * @param {boolean} showTags Should the JSON include monitor tags
* @param {boolean} certExpiry Should JSON include info about * @param {boolean} certExpiry Should JSON include info about
* certificate expiry? * certificate expiry?
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON(showTags = false, certExpiry = false) { async toPublicJSON(showTags = false, certExpiry = false) {
let monitorBeanList = await this.getMonitorList(); let monitorBeanList = await this.getMonitorList();
@ -29,7 +29,7 @@ class Group extends BeanModel {
/** /**
* Get all monitors * Get all monitors
* @returns {Bean[]} List of monitors * @returns {Promise<Bean[]>} List of monitors
*/ */
async getMonitorList() { async getMonitorList() {
return R.convertToBeans("monitor", await R.getAll(` return R.convertToBeans("monitor", await R.getAll(`

View file

@ -11,7 +11,7 @@ class Maintenance extends BeanModel {
/** /**
* Return an 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 * Only show necessary data to public
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON() { async toPublicJSON() {
@ -98,7 +98,7 @@ class Maintenance extends BeanModel {
/** /**
* Return an object that ready to parse to JSON * Return an object that ready to parse to JSON
* @param {string} timezone If not specified, the timeRange will be in UTC * @param {string} timezone If not specified, the timeRange will be in UTC
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toJSON(timezone = null) { async toJSON(timezone = null) {
return this.toPublicJSON(timezone); return this.toPublicJSON(timezone);
@ -143,7 +143,7 @@ class Maintenance extends BeanModel {
* Convert data from socket to bean * Convert data from socket to bean
* @param {Bean} bean Bean to fill in * @param {Bean} bean Bean to fill in
* @param {object} obj Data to fill bean with * @param {object} obj Data to fill bean with
* @returns {Bean} Filled bean * @returns {Promise<Bean>} Filled bean
*/ */
static async jsonToBean(bean, obj) { static async jsonToBean(bean, obj) {
if (obj.id) { if (obj.id) {
@ -189,9 +189,9 @@ class Maintenance extends BeanModel {
/** /**
* Throw error if cron is invalid * Throw error if cron is invalid
* @param {string|Date} cron Pattern or date * @param {string|Date} cron Pattern or date
* @returns {Promise<void>} * @returns {void}
*/ */
static async validateCron(cron) { static validateCron(cron) {
let job = new Cron(cron, () => {}); let job = new Cron(cron, () => {});
job.stop(); job.stop();
} }
@ -239,19 +239,7 @@ class Maintenance extends BeanModel {
this.beanMeta.status = "under-maintenance"; this.beanMeta.status = "under-maintenance";
clearTimeout(this.beanMeta.durationTimeout); clearTimeout(this.beanMeta.durationTimeout);
// Check if duration is still in the window. If not, use the duration from the current time to the end of the window let duration = this.inferDuration(customDuration);
let duration;
if (customDuration > 0) {
duration = customDuration;
} else if (this.end_date) {
let d = dayjs(this.end_date).diff(dayjs(), "second");
if (d < this.duration) {
duration = d * 1000;
}
} else {
duration = this.duration * 1000;
}
UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id);
@ -263,9 +251,21 @@ class Maintenance extends BeanModel {
}; };
// Create Cron // Create Cron
this.beanMeta.job = new Cron(this.cron, { if (this.strategy === "recurring-interval") {
timezone: await this.getTimezone(), // For recurring-interval, Croner needs to have interval and startAt
}, startEvent); const startDate = dayjs(this.startDate);
const [ hour, minute ] = this.startTime.split(":");
const startDateTime = startDate.hour(hour).minute(minute);
this.beanMeta.job = new Cron(this.cron, {
timezone: await this.getTimezone(),
interval: this.interval_day * 24 * 60 * 60,
startAt: startDateTime.toISOString(),
}, startEvent);
} else {
this.beanMeta.job = new Cron(this.cron, {
timezone: await this.getTimezone(),
}, startEvent);
}
// Continue if the maintenance is still in the window // Continue if the maintenance is still in the window
let runningTimeslot = this.getRunningTimeslot(); let runningTimeslot = this.getRunningTimeslot();
@ -311,6 +311,24 @@ class Maintenance extends BeanModel {
} }
} }
/**
* Calculate the maintenance duration
* @param {number} customDuration - The custom duration in milliseconds.
* @returns {number} The inferred duration in milliseconds.
*/
inferDuration(customDuration) {
// Check if duration is still in the window. If not, use the duration from the current time to the end of the window
if (customDuration > 0) {
return customDuration;
} else if (this.end_date) {
let d = dayjs(this.end_date).diff(dayjs(), "second");
if (d < this.duration) {
return d * 1000;
}
}
return this.duration * 1000;
}
/** /**
* Stop the maintenance * Stop the maintenance
* @returns {void} * @returns {void}
@ -324,7 +342,7 @@ class Maintenance extends BeanModel {
/** /**
* Is this maintenance currently active * Is this maintenance currently active
* @returns {boolean} The maintenance is active? * @returns {Promise<boolean>} The maintenance is active?
*/ */
async isUnderMaintenance() { async isUnderMaintenance() {
return (await this.getStatus()) === "under-maintenance"; return (await this.getStatus()) === "under-maintenance";
@ -332,7 +350,7 @@ class Maintenance extends BeanModel {
/** /**
* Get the timezone of the maintenance * Get the timezone of the maintenance
* @returns {string} timezone * @returns {Promise<string>} timezone
*/ */
async getTimezone() { async getTimezone() {
if (!this.timezone || this.timezone === "SAME_AS_SERVER") { if (!this.timezone || this.timezone === "SAME_AS_SERVER") {
@ -343,7 +361,7 @@ class Maintenance extends BeanModel {
/** /**
* Get offset for timezone * Get offset for timezone
* @returns {string} offset * @returns {Promise<string>} offset
*/ */
async getTimezoneOffset() { async getTimezoneOffset() {
return dayjs.tz(dayjs(), await this.getTimezone()).format("Z"); return dayjs.tz(dayjs(), await this.getTimezone()).format("Z");
@ -351,7 +369,7 @@ class Maintenance extends BeanModel {
/** /**
* Get the current status of the maintenance * Get the current status of the maintenance
* @returns {string} Current status * @returns {Promise<string>} Current status
*/ */
async getStatus() { async getStatus() {
if (!this.active) { if (!this.active) {
@ -395,10 +413,8 @@ class Maintenance extends BeanModel {
} else if (!this.strategy.startsWith("recurring-")) { } else if (!this.strategy.startsWith("recurring-")) {
this.cron = ""; this.cron = "";
} else if (this.strategy === "recurring-interval") { } else if (this.strategy === "recurring-interval") {
let array = this.start_time.split(":"); // For intervals, the pattern is calculated in the run function as the interval-option is set
let hour = parseInt(array[0]); this.cron = "* * * * *";
let minute = parseInt(array[1]);
this.cron = minute + " " + hour + " */" + this.interval_day + " * *";
this.duration = this.calcDuration(); this.duration = this.calcDuration();
log.debug("maintenance", "Cron: " + this.cron); log.debug("maintenance", "Cron: " + this.cron);
log.debug("maintenance", "Duration: " + this.duration); log.debug("maintenance", "Duration: " + this.duration);

View file

@ -2,10 +2,10 @@ const dayjs = require("dayjs");
const axios = require("axios"); const axios = require("axios");
const { Prometheus } = require("../prometheus"); const { Prometheus } = require("../prometheus");
const { log, UP, DOWN, PENDING, MAINTENANCE, flipStatus, MAX_INTERVAL_SECOND, MIN_INTERVAL_SECOND, const { log, UP, DOWN, PENDING, MAINTENANCE, flipStatus, MAX_INTERVAL_SECOND, MIN_INTERVAL_SECOND,
SQL_DATETIME_FORMAT SQL_DATETIME_FORMAT, evaluateJsonQuery
} = require("../../src/util"); } = require("../../src/util");
const { tcping, ping, checkCertificate, checkStatusCode, getTotalClientInRoom, mssqlQuery, postgresQuery, mysqlQuery, httpNtlm, radius, grpcQuery, const { tcping, ping, checkCertificate, checkStatusCode, getTotalClientInRoom, mssqlQuery, postgresQuery, mysqlQuery, httpNtlm, radius, grpcQuery,
redisPingAsync, mongodbPing, kafkaProducerAsync, getOidcTokenClientCredentials, rootCertificatesFingerprints, axiosAbortSignal redisPingAsync, kafkaProducerAsync, getOidcTokenClientCredentials, rootCertificatesFingerprints, axiosAbortSignal
} = require("../util-server"); } = require("../util-server");
const { R } = require("redbean-node"); const { R } = require("redbean-node");
const { BeanModel } = require("redbean-node/dist/bean-model"); const { BeanModel } = require("redbean-node/dist/bean-model");
@ -17,7 +17,6 @@ const apicache = require("../modules/apicache");
const { UptimeKumaServer } = require("../uptime-kuma-server"); const { UptimeKumaServer } = require("../uptime-kuma-server");
const { DockerHost } = require("../docker"); const { DockerHost } = require("../docker");
const Gamedig = require("gamedig"); const Gamedig = require("gamedig");
const jsonata = require("jsonata");
const jwt = require("jsonwebtoken"); const jwt = require("jsonwebtoken");
const crypto = require("crypto"); const crypto = require("crypto");
const { UptimeCalculator } = require("../uptime-calculator"); const { UptimeCalculator } = require("../uptime-calculator");
@ -44,7 +43,7 @@ class Monitor extends BeanModel {
* @param {boolean} showTags Include tags in JSON * @param {boolean} showTags Include tags in JSON
* @param {boolean} certExpiry Include certificate expiry info in * @param {boolean} certExpiry Include certificate expiry info in
* JSON * JSON
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON(showTags = false, certExpiry = false) { async toPublicJSON(showTags = false, certExpiry = false) {
let obj = { let obj = {
@ -75,7 +74,7 @@ class Monitor extends BeanModel {
* Return an object that ready to parse to JSON * Return an object that ready to parse to JSON
* @param {boolean} includeSensitiveData Include sensitive data in * @param {boolean} includeSensitiveData Include sensitive data in
* JSON * JSON
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toJSON(includeSensitiveData = true) { async toJSON(includeSensitiveData = true) {
@ -97,11 +96,15 @@ class Monitor extends BeanModel {
screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png"; screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png";
} }
const path = await this.getPath();
const pathName = path.join(" / ");
let data = { let data = {
id: this.id, id: this.id,
name: this.name, name: this.name,
description: this.description, description: this.description,
pathName: await this.getPathName(), path,
pathName,
parent: this.parent, parent: this.parent,
childrenIDs: await Monitor.getAllChildrenIDs(this.id), childrenIDs: await Monitor.getAllChildrenIDs(this.id),
url: this.url, url: this.url,
@ -157,7 +160,12 @@ class Monitor extends BeanModel {
kafkaProducerAllowAutoTopicCreation: this.getKafkaProducerAllowAutoTopicCreation(), kafkaProducerAllowAutoTopicCreation: this.getKafkaProducerAllowAutoTopicCreation(),
kafkaProducerMessage: this.kafkaProducerMessage, kafkaProducerMessage: this.kafkaProducerMessage,
screenshot, screenshot,
cacheBust: this.getCacheBust(),
remote_browser: this.remote_browser, remote_browser: this.remote_browser,
snmpOid: this.snmpOid,
jsonPathOperator: this.jsonPathOperator,
snmpVersion: this.snmpVersion,
conditions: JSON.parse(this.conditions),
}; };
if (includeSensitiveData) { if (includeSensitiveData) {
@ -242,12 +250,12 @@ class Monitor extends BeanModel {
/** /**
* Encode user and password to Base64 encoding * Encode user and password to Base64 encoding
* for HTTP "basic" auth, as per RFC-7617 * for HTTP "basic" auth, as per RFC-7617
* @param {string} user Username to encode * @param {string|null} user - The username (nullable if not changed by a user)
* @param {string} pass Password to encode * @param {string|null} pass - The password (nullable if not changed by a user)
* @returns {string} Encoded username:password * @returns {string} Encoded Base64 string
*/ */
encodeBase64(user, pass) { encodeBase64(user, pass) {
return Buffer.from(user + ":" + pass).toString("base64"); return Buffer.from(`${user || ""}:${pass || ""}`).toString("base64");
} }
/** /**
@ -290,6 +298,14 @@ class Monitor extends BeanModel {
return Boolean(this.grpcEnableTls); return Boolean(this.grpcEnableTls);
} }
/**
* Parse to boolean
* @returns {boolean} if cachebusting is enabled
*/
getCacheBust() {
return Boolean(this.cacheBust);
}
/** /**
* Get accepted status codes * Get accepted status codes
* @returns {object} Accepted status codes * @returns {object} Accepted status codes
@ -325,13 +341,13 @@ class Monitor extends BeanModel {
/** /**
* Start monitor * Start monitor
* @param {Server} io Socket server instance * @param {Server} io Socket server instance
* @returns {void} * @returns {Promise<void>}
*/ */
start(io) { async start(io) {
let previousBeat = null; let previousBeat = null;
let retries = 0; let retries = 0;
this.prometheus = new Prometheus(this); this.prometheus = await Prometheus.createAndInitMetrics(this);
const beat = async () => { const beat = async () => {
@ -495,6 +511,14 @@ class Monitor extends BeanModel {
options.data = bodyValue; options.data = bodyValue;
} }
if (this.cacheBust) {
const randomFloatString = Math.random().toString(36);
const cacheBust = randomFloatString.substring(2);
options.params = {
uptime_kuma_cachebuster: cacheBust,
};
}
if (this.proxy_id) { if (this.proxy_id) {
const proxy = await R.load("proxy", this.proxy_id); const proxy = await R.load("proxy", this.proxy_id);
@ -530,6 +554,18 @@ class Monitor extends BeanModel {
} }
} }
let tlsInfo = {};
// Store tlsInfo when secureConnect event is emitted
// The keylog event listener is a workaround to access the tlsSocket
options.httpsAgent.once("keylog", async (line, tlsSocket) => {
tlsSocket.once("secureConnect", async () => {
tlsInfo = checkCertificate(tlsSocket);
tlsInfo.valid = tlsSocket.authorized || false;
await this.handleTlsInfo(tlsInfo);
});
});
log.debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`); log.debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`);
log.debug("monitor", `[${this.name}] Axios Request`); log.debug("monitor", `[${this.name}] Axios Request`);
@ -539,31 +575,19 @@ class Monitor extends BeanModel {
bean.msg = `${res.status} - ${res.statusText}`; bean.msg = `${res.status} - ${res.statusText}`;
bean.ping = dayjs().valueOf() - startTime; bean.ping = dayjs().valueOf() - startTime;
// Check certificate if https is used // fallback for if kelog event is not emitted, but we may still have tlsInfo,
let certInfoStartTime = dayjs().valueOf(); // e.g. if the connection is made through a proxy
if (this.getUrl()?.protocol === "https:") { if (this.getUrl()?.protocol === "https:" && tlsInfo.valid === undefined) {
log.debug("monitor", `[${this.name}] Check cert`); const tlsSocket = res.request.res.socket;
try {
let tlsInfoObject = checkCertificate(res);
tlsInfo = await this.updateTlsInfo(tlsInfoObject);
if (!this.getIgnoreTls() && this.isEnabledExpiryNotification()) { if (tlsSocket) {
log.debug("monitor", `[${this.name}] call checkCertExpiryNotifications`); tlsInfo = checkCertificate(tlsSocket);
await this.checkCertExpiryNotifications(tlsInfoObject); tlsInfo.valid = tlsSocket.authorized || false;
}
} catch (e) { await this.handleTlsInfo(tlsInfo);
if (e.message !== "No TLS certificate in response") {
log.error("monitor", "Caught error");
log.error("monitor", e.message);
}
} }
} }
if (process.env.TIMELOGGER === "1") {
log.debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms");
}
if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID === this.id) { if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID === this.id) {
log.info("monitor", res.data); log.info("monitor", res.data);
} }
@ -595,21 +619,15 @@ class Monitor extends BeanModel {
} else if (this.type === "json-query") { } else if (this.type === "json-query") {
let data = res.data; let data = res.data;
// convert data to object const { status, response } = await evaluateJsonQuery(data, this.jsonPath, this.jsonPathOperator, this.expectedValue);
if (typeof data === "string") {
data = JSON.parse(data);
}
let expression = jsonata(this.jsonPath); if (status) {
let result = await expression.evaluate(data);
if (result.toString() === this.expectedValue) {
bean.msg += ", expected value is found";
bean.status = UP; bean.status = UP;
bean.msg = `JSON query passes (comparing ${response} ${this.jsonPathOperator} ${this.expectedValue})`;
} else { } else {
throw new Error(bean.msg + ", but value is not equal to expected value, value was: [" + result + "]"); throw new Error(`JSON query does not pass (comparing ${response} ${this.jsonPathOperator} ${this.expectedValue})`);
} }
} }
} else if (this.type === "port") { } else if (this.type === "port") {
@ -815,15 +833,6 @@ class Monitor extends BeanModel {
bean.msg = await mysqlQuery(this.databaseConnectionString, this.databaseQuery || "SELECT 1", mysqlPassword); bean.msg = await mysqlQuery(this.databaseConnectionString, this.databaseQuery || "SELECT 1", mysqlPassword);
bean.status = UP; bean.status = UP;
bean.ping = dayjs().valueOf() - startTime; bean.ping = dayjs().valueOf() - startTime;
} else if (this.type === "mongodb") {
let startTime = dayjs().valueOf();
await mongodbPing(this.databaseConnectionString);
bean.msg = "";
bean.status = UP;
bean.ping = dayjs().valueOf() - startTime;
} else if (this.type === "radius") { } else if (this.type === "radius") {
let startTime = dayjs().valueOf(); let startTime = dayjs().valueOf();
@ -854,7 +863,7 @@ class Monitor extends BeanModel {
} else if (this.type === "redis") { } else if (this.type === "redis") {
let startTime = dayjs().valueOf(); let startTime = dayjs().valueOf();
bean.msg = await redisPingAsync(this.databaseConnectionString); bean.msg = await redisPingAsync(this.databaseConnectionString, !this.ignoreTls);
bean.status = UP; bean.status = UP;
bean.ping = dayjs().valueOf() - startTime; bean.ping = dayjs().valueOf() - startTime;
@ -944,7 +953,7 @@ class Monitor extends BeanModel {
log.debug("monitor", `[${this.name}] apicache clear`); log.debug("monitor", `[${this.name}] apicache clear`);
apicache.clear(); apicache.clear();
UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); await UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id);
} else { } else {
bean.important = false; bean.important = false;
@ -990,7 +999,7 @@ class Monitor extends BeanModel {
await R.store(bean); await R.store(bean);
log.debug("monitor", `[${this.name}] prometheus.update`); log.debug("monitor", `[${this.name}] prometheus.update`);
this.prometheus?.update(bean, tlsInfo); await this.prometheus?.update(bean, tlsInfo);
previousBeat = bean; previousBeat = bean;
@ -1099,9 +1108,9 @@ class Monitor extends BeanModel {
/** /**
* Stop monitor * Stop monitor
* @returns {void} * @returns {Promise<void>}
*/ */
stop() { async stop() {
clearTimeout(this.heartbeatInterval); clearTimeout(this.heartbeatInterval);
this.isStop = true; this.isStop = true;
@ -1374,6 +1383,7 @@ class Monitor extends BeanModel {
let notifyDays = await Settings.get("tlsExpiryNotifyDays"); let notifyDays = await Settings.get("tlsExpiryNotifyDays");
if (notifyDays == null || !Array.isArray(notifyDays)) { if (notifyDays == null || !Array.isArray(notifyDays)) {
// Reset Default // Reset Default
await Settings.set("tlsExpiryNotifyDays", [ 7, 14, 21 ], "general");
notifyDays = [ 7, 14, 21 ]; notifyDays = [ 7, 14, 21 ];
await Settings.set("tlsExpiryNotifyDays", notifyDays, "general"); await Settings.set("tlsExpiryNotifyDays", notifyDays, "general");
} }
@ -1528,11 +1538,11 @@ class Monitor extends BeanModel {
} }
/** /**
* Gets Full Path-Name (Groups and Name) * Gets the full path
* @returns {Promise<string>} Full path name of this monitor * @returns {Promise<string[]>} Full path (includes groups and the name) of the monitor
*/ */
async getPathName() { async getPath() {
let path = this.name; const path = [ this.name ];
if (this.parent === null) { if (this.parent === null) {
return path; return path;
@ -1540,7 +1550,7 @@ class Monitor extends BeanModel {
let parent = await Monitor.getParent(this.id); let parent = await Monitor.getParent(this.id);
while (parent !== null) { while (parent !== null) {
path = `${parent.name} / ${path}`; path.unshift(parent.name);
parent = await Monitor.getParent(parent.id); parent = await Monitor.getParent(parent.id);
} }
@ -1570,7 +1580,7 @@ class Monitor extends BeanModel {
} }
/** /**
* Unlinks all children of the the group monitor * Unlinks all children of the group monitor
* @param {number} groupID ID of group to remove children of * @param {number} groupID ID of group to remove children of
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
@ -1612,6 +1622,20 @@ class Monitor extends BeanModel {
return oAuthAccessToken; return oAuthAccessToken;
} }
/**
* Store TLS certificate information and check for expiry
* @param {object} tlsInfo Information about the TLS connection
* @returns {Promise<void>}
*/
async handleTlsInfo(tlsInfo) {
await this.updateTlsInfo(tlsInfo);
this.prometheus?.update(null, tlsInfo);
if (!this.getIgnoreTls() && this.isEnabledExpiryNotification()) {
log.debug("monitor", `[${this.name}] call checkCertExpiryNotifications`);
await this.checkCertExpiryNotifications(tlsInfo);
}
}
} }
module.exports = Monitor; module.exports = Monitor;

View file

@ -4,6 +4,11 @@ const cheerio = require("cheerio");
const { UptimeKumaServer } = require("../uptime-kuma-server"); const { UptimeKumaServer } = require("../uptime-kuma-server");
const jsesc = require("jsesc"); const jsesc = require("jsesc");
const googleAnalytics = require("../google-analytics"); const googleAnalytics = require("../google-analytics");
const { marked } = require("marked");
const { Feed } = require("feed");
const config = require("../config");
const { STATUS_PAGE_ALL_DOWN, STATUS_PAGE_ALL_UP, STATUS_PAGE_MAINTENANCE, STATUS_PAGE_PARTIAL_DOWN, UP, MAINTENANCE, DOWN } = require("../../src/util");
class StatusPage extends BeanModel { class StatusPage extends BeanModel {
@ -13,12 +18,30 @@ class StatusPage extends BeanModel {
*/ */
static domainMappingList = { }; static domainMappingList = { };
/**
* Handle responses to RSS pages
* @param {Response} response Response object
* @param {string} slug Status page slug
* @returns {Promise<void>}
*/
static async handleStatusPageRSSResponse(response, slug) {
let statusPage = await R.findOne("status_page", " slug = ? ", [
slug
]);
if (statusPage) {
response.send(await StatusPage.renderRSS(statusPage, slug));
} else {
response.status(404).send(UptimeKumaServer.getInstance().indexHTML);
}
}
/** /**
* Handle responses to status page * Handle responses to status page
* @param {Response} response Response object * @param {Response} response Response object
* @param {string} indexHTML HTML to render * @param {string} indexHTML HTML to render
* @param {string} slug Status page slug * @param {string} slug Status page slug
* @returns {void} * @returns {Promise<void>}
*/ */
static async handleStatusPageResponse(response, indexHTML, slug) { static async handleStatusPageResponse(response, indexHTML, slug) {
// Handle url with trailing slash (http://localhost:3001/status/) // Handle url with trailing slash (http://localhost:3001/status/)
@ -38,15 +61,51 @@ class StatusPage extends BeanModel {
} }
} }
/**
* SSR for RSS feed
* @param {statusPage} statusPage object
* @param {slug} slug from router
* @returns {Promise<string>} the rendered html
*/
static async renderRSS(statusPage, slug) {
const { heartbeats, statusDescription } = await StatusPage.getRSSPageData(statusPage);
let proto = config.isSSL ? "https" : "http";
let host = `${proto}://${config.hostname || "localhost"}:${config.port}/status/${slug}`;
const feed = new Feed({
title: "uptime kuma rss feed",
description: `current status: ${statusDescription}`,
link: host,
language: "en", // optional, used only in RSS 2.0, possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
updated: new Date(), // optional, default = today
});
heartbeats.forEach(heartbeat => {
feed.addItem({
title: `${heartbeat.name} is down`,
description: `${heartbeat.name} has been down since ${heartbeat.time}`,
id: heartbeat.monitorID,
date: new Date(heartbeat.time),
});
});
return feed.rss2();
}
/** /**
* SSR for status pages * SSR for status pages
* @param {string} indexHTML HTML page to render * @param {string} indexHTML HTML page to render
* @param {StatusPage} statusPage Status page populate HTML with * @param {StatusPage} statusPage Status page populate HTML with
* @returns {void} * @returns {Promise<string>} the rendered html
*/ */
static async renderHTML(indexHTML, statusPage) { static async renderHTML(indexHTML, statusPage) {
const $ = cheerio.load(indexHTML); const $ = cheerio.load(indexHTML);
const description155 = statusPage.description?.substring(0, 155) ?? "";
const description155 = marked(statusPage.description ?? "")
.replace(/<[^>]+>/gm, "")
.trim()
.substring(0, 155);
$("title").text(statusPage.title); $("title").text(statusPage.title);
$("meta[name=description]").attr("content", description155); $("meta[name=description]").attr("content", description155);
@ -93,6 +152,109 @@ class StatusPage extends BeanModel {
return $.root().html(); return $.root().html();
} }
/**
* @param {heartbeats} heartbeats from getRSSPageData
* @returns {number} status_page constant from util.ts
*/
static overallStatus(heartbeats) {
if (heartbeats.length === 0) {
return -1;
}
let status = STATUS_PAGE_ALL_UP;
let hasUp = false;
for (let beat of heartbeats) {
if (beat.status === MAINTENANCE) {
return STATUS_PAGE_MAINTENANCE;
} else if (beat.status === UP) {
hasUp = true;
} else {
status = STATUS_PAGE_PARTIAL_DOWN;
}
}
if (! hasUp) {
status = STATUS_PAGE_ALL_DOWN;
}
return status;
}
/**
* @param {number} status from overallStatus
* @returns {string} description
*/
static getStatusDescription(status) {
if (status === -1) {
return "No Services";
}
if (status === STATUS_PAGE_ALL_UP) {
return "All Systems Operational";
}
if (status === STATUS_PAGE_PARTIAL_DOWN) {
return "Partially Degraded Service";
}
if (status === STATUS_PAGE_ALL_DOWN) {
return "Degraded Service";
}
// TODO: show the real maintenance information: title, description, time
if (status === MAINTENANCE) {
return "Under maintenance";
}
return "?";
}
/**
* Get all data required for RSS
* @param {StatusPage} statusPage Status page to get data for
* @returns {object} Status page data
*/
static async getRSSPageData(statusPage) {
// get all heartbeats that correspond to this statusPage
const config = await statusPage.toPublicJSON();
// Public Group List
const showTags = !!statusPage.show_tags;
const list = await R.find("group", " public = 1 AND status_page_id = ? ORDER BY weight ", [
statusPage.id
]);
let heartbeats = [];
for (let groupBean of list) {
let monitorGroup = await groupBean.toPublicJSON(showTags, config?.showCertificateExpiry);
for (const monitor of monitorGroup.monitorList) {
const heartbeat = await R.findOne("heartbeat", "monitor_id = ? ORDER BY time DESC", [ monitor.id ]);
if (heartbeat) {
heartbeats.push({
...monitor,
status: heartbeat.status,
time: heartbeat.time
});
}
}
}
// calculate RSS feed description
let status = StatusPage.overallStatus(heartbeats);
let statusDescription = StatusPage.getStatusDescription(status);
// keep only DOWN heartbeats in the RSS feed
heartbeats = heartbeats.filter(heartbeat => heartbeat.status === DOWN);
return {
heartbeats,
statusDescription
};
}
/** /**
* Get all status page data in one call * Get all status page data in one call
* @param {StatusPage} statusPage Status page to get data for * @param {StatusPage} statusPage Status page to get data for
@ -238,6 +400,7 @@ class StatusPage extends BeanModel {
description: this.description, description: this.description,
icon: this.getIcon(), icon: this.getIcon(),
theme: this.theme, theme: this.theme,
autoRefreshInterval: this.autoRefreshInterval,
published: !!this.published, published: !!this.published,
showTags: !!this.show_tags, showTags: !!this.show_tags,
domainNameList: this.getDomainNameList(), domainNameList: this.getDomainNameList(),
@ -260,6 +423,7 @@ class StatusPage extends BeanModel {
title: this.title, title: this.title,
description: this.description, description: this.description,
icon: this.getIcon(), icon: this.getIcon(),
autoRefreshInterval: this.autoRefreshInterval,
theme: this.theme, theme: this.theme,
published: !!this.published, published: !!this.published,
showTags: !!this.show_tags, showTags: !!this.show_tags,

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 CatButtes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,77 @@
'use strict';
// Original file https://raw.githubusercontent.com/elasticio/node-ntlm-client/master/lib/flags.js
module.exports.NTLMFLAG_NEGOTIATE_UNICODE = 1 << 0;
/* Indicates that Unicode strings are supported for use in security buffer
data. */
module.exports.NTLMFLAG_NEGOTIATE_OEM = 1 << 1;
/* Indicates that OEM strings are supported for use in security buffer data. */
module.exports.NTLMFLAG_REQUEST_TARGET = 1 << 2;
/* Requests that the server's authentication realm be included in the Type 2
message. */
/* unknown (1<<3) */
module.exports.NTLMFLAG_NEGOTIATE_SIGN = 1 << 4;
/* Specifies that authenticated communication between the client and server
should carry a digital signature (message integrity). */
module.exports.NTLMFLAG_NEGOTIATE_SEAL = 1 << 5;
/* Specifies that authenticated communication between the client and server
should be encrypted (message confidentiality). */
module.exports.NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE = 1 << 6;
/* Indicates that datagram authentication is being used. */
module.exports.NTLMFLAG_NEGOTIATE_LM_KEY = 1 << 7;
/* Indicates that the LAN Manager session key should be used for signing and
sealing authenticated communications. */
module.exports.NTLMFLAG_NEGOTIATE_NETWARE = 1 << 8;
/* unknown purpose */
module.exports.NTLMFLAG_NEGOTIATE_NTLM_KEY = 1 << 9;
/* Indicates that NTLM authentication is being used. */
/* unknown (1<<10) */
module.exports.NTLMFLAG_NEGOTIATE_ANONYMOUS = 1 << 11;
/* Sent by the client in the Type 3 message to indicate that an anonymous
context has been established. This also affects the response fields. */
module.exports.NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED = 1 << 12;
/* Sent by the client in the Type 1 message to indicate that a desired
authentication realm is included in the message. */
module.exports.NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED = 1 << 13;
/* Sent by the client in the Type 1 message to indicate that the client
workstation's name is included in the message. */
module.exports.NTLMFLAG_NEGOTIATE_LOCAL_CALL = 1 << 14;
/* Sent by the server to indicate that the server and client are on the same
machine. Implies that the client may use a pre-established local security
context rather than responding to the challenge. */
module.exports.NTLMFLAG_NEGOTIATE_ALWAYS_SIGN = 1 << 15;
/* Indicates that authenticated communication between the client and server
should be signed with a "dummy" signature. */
module.exports.NTLMFLAG_TARGET_TYPE_DOMAIN = 1 << 16;
/* Sent by the server in the Type 2 message to indicate that the target
authentication realm is a domain. */
module.exports.NTLMFLAG_TARGET_TYPE_SERVER = 1 << 17;
/* Sent by the server in the Type 2 message to indicate that the target
authentication realm is a server. */
module.exports.NTLMFLAG_TARGET_TYPE_SHARE = 1 << 18;
/* Sent by the server in the Type 2 message to indicate that the target
authentication realm is a share. Presumably, this is for share-level
authentication. Usage is unclear. */
module.exports.NTLMFLAG_NEGOTIATE_NTLM2_KEY = 1 << 19;
/* Indicates that the NTLM2 signing and sealing scheme should be used for
protecting authenticated communications. */
module.exports.NTLMFLAG_REQUEST_INIT_RESPONSE = 1 << 20;
/* unknown purpose */
module.exports.NTLMFLAG_REQUEST_ACCEPT_RESPONSE = 1 << 21;
/* unknown purpose */
module.exports.NTLMFLAG_REQUEST_NONNT_SESSION_KEY = 1 << 22;
/* unknown purpose */
module.exports.NTLMFLAG_NEGOTIATE_TARGET_INFO = 1 << 23;
/* Sent by the server in the Type 2 message to indicate that it is including a
Target Information block in the message. */
/* unknown (1<24) */
/* unknown (1<25) */
/* unknown (1<26) */
/* unknown (1<27) */
/* unknown (1<28) */
module.exports.NTLMFLAG_NEGOTIATE_128 = 1 << 29;
/* Indicates that 128-bit encryption is supported. */
module.exports.NTLMFLAG_NEGOTIATE_KEY_EXCHANGE = 1 << 30;
/* Indicates that the client will provide an encrypted master key in
the "Session Key" field of the Type 3 message. */
module.exports.NTLMFLAG_NEGOTIATE_56 = 1 << 31;
//# sourceMappingURL=flags.js.map

View file

@ -0,0 +1,122 @@
'use strict';
// Original source at https://github.com/elasticio/node-ntlm-client/blob/master/lib/hash.js
var crypto = require('crypto');
function createLMResponse(challenge, lmhash) {
var buf = new Buffer.alloc(24), pwBuffer = new Buffer.alloc(21).fill(0);
lmhash.copy(pwBuffer);
calculateDES(pwBuffer.slice(0, 7), challenge).copy(buf);
calculateDES(pwBuffer.slice(7, 14), challenge).copy(buf, 8);
calculateDES(pwBuffer.slice(14), challenge).copy(buf, 16);
return buf;
}
function createLMHash(password) {
var buf = new Buffer.alloc(16), pwBuffer = new Buffer.alloc(14), magicKey = new Buffer.from('KGS!@#$%', 'ascii');
if (password.length > 14) {
buf.fill(0);
return buf;
}
pwBuffer.fill(0);
pwBuffer.write(password.toUpperCase(), 0, 'ascii');
return Buffer.concat([
calculateDES(pwBuffer.slice(0, 7), magicKey),
calculateDES(pwBuffer.slice(7), magicKey)
]);
}
function calculateDES(key, message) {
var desKey = new Buffer.alloc(8);
desKey[0] = key[0] & 0xFE;
desKey[1] = ((key[0] << 7) & 0xFF) | (key[1] >> 1);
desKey[2] = ((key[1] << 6) & 0xFF) | (key[2] >> 2);
desKey[3] = ((key[2] << 5) & 0xFF) | (key[3] >> 3);
desKey[4] = ((key[3] << 4) & 0xFF) | (key[4] >> 4);
desKey[5] = ((key[4] << 3) & 0xFF) | (key[5] >> 5);
desKey[6] = ((key[5] << 2) & 0xFF) | (key[6] >> 6);
desKey[7] = (key[6] << 1) & 0xFF;
for (var i = 0; i < 8; i++) {
var parity = 0;
for (var j = 1; j < 8; j++) {
parity += (desKey[i] >> j) % 2;
}
desKey[i] |= (parity % 2) === 0 ? 1 : 0;
}
var des = crypto.createCipheriv('DES-ECB', desKey, '');
return des.update(message);
}
function createNTLMResponse(challenge, ntlmhash) {
var buf = new Buffer.alloc(24), ntlmBuffer = new Buffer.alloc(21).fill(0);
ntlmhash.copy(ntlmBuffer);
calculateDES(ntlmBuffer.slice(0, 7), challenge).copy(buf);
calculateDES(ntlmBuffer.slice(7, 14), challenge).copy(buf, 8);
calculateDES(ntlmBuffer.slice(14), challenge).copy(buf, 16);
return buf;
}
function createNTLMHash(password) {
var md4sum = crypto.createHash('md4');
md4sum.update(new Buffer.from(password, 'ucs2'));
return md4sum.digest();
}
function createNTLMv2Hash(ntlmhash, username, authTargetName) {
var hmac = crypto.createHmac('md5', ntlmhash);
hmac.update(new Buffer.from(username.toUpperCase() + authTargetName, 'ucs2'));
return hmac.digest();
}
function createLMv2Response(type2message, username, ntlmhash, nonce, targetName) {
var buf = new Buffer.alloc(24), ntlm2hash = createNTLMv2Hash(ntlmhash, username, targetName), hmac = crypto.createHmac('md5', ntlm2hash);
//server challenge
type2message.challenge.copy(buf, 8);
//client nonce
buf.write(nonce || createPseudoRandomValue(16), 16, 'hex');
//create hash
hmac.update(buf.slice(8));
var hashedBuffer = hmac.digest();
hashedBuffer.copy(buf);
return buf;
}
function createNTLMv2Response(type2message, username, ntlmhash, nonce, targetName) {
var buf = new Buffer.alloc(48 + type2message.targetInfo.buffer.length), ntlm2hash = createNTLMv2Hash(ntlmhash, username, targetName), hmac = crypto.createHmac('md5', ntlm2hash);
//the first 8 bytes are spare to store the hashed value before the blob
//server challenge
type2message.challenge.copy(buf, 8);
//blob signature
buf.writeUInt32BE(0x01010000, 16);
//reserved
buf.writeUInt32LE(0, 20);
//timestamp
//TODO: we are loosing precision here since js is not able to handle those large integers
// maybe think about a different solution here
// 11644473600000 = diff between 1970 and 1601
var timestamp = ((Date.now() + 11644473600000) * 10000).toString(16);
var timestampLow = Number('0x' + timestamp.substring(Math.max(0, timestamp.length - 8)));
var timestampHigh = Number('0x' + timestamp.substring(0, Math.max(0, timestamp.length - 8)));
buf.writeUInt32LE(timestampLow, 24, false);
buf.writeUInt32LE(timestampHigh, 28, false);
//random client nonce
buf.write(nonce || createPseudoRandomValue(16), 32, 'hex');
//zero
buf.writeUInt32LE(0, 40);
//complete target information block from type 2 message
type2message.targetInfo.buffer.copy(buf, 44);
//zero
buf.writeUInt32LE(0, 44 + type2message.targetInfo.buffer.length);
hmac.update(buf.slice(8));
var hashedBuffer = hmac.digest();
hashedBuffer.copy(buf);
return buf;
}
function createPseudoRandomValue(length) {
var str = '';
while (str.length < length) {
str += Math.floor(Math.random() * 16).toString(16);
}
return str;
}
module.exports = {
createLMHash: createLMHash,
createNTLMHash: createNTLMHash,
createLMResponse: createLMResponse,
createNTLMResponse: createNTLMResponse,
createLMv2Response: createLMv2Response,
createNTLMv2Response: createNTLMv2Response,
createPseudoRandomValue: createPseudoRandomValue
};
//# sourceMappingURL=hash.js.map

View file

@ -0,0 +1,220 @@
'use strict';
// Original file https://raw.githubusercontent.com/elasticio/node-ntlm-client/master/lib/ntlm.js
var os = require('os'), flags = require('./flags'), hash = require('./hash');
var NTLMSIGNATURE = "NTLMSSP\0";
function createType1Message(workstation, target) {
var dataPos = 32, pos = 0, buf = new Buffer.alloc(1024);
workstation = workstation === undefined ? os.hostname() : workstation;
target = target === undefined ? '' : target;
//signature
buf.write(NTLMSIGNATURE, pos, NTLMSIGNATURE.length, 'ascii');
pos += NTLMSIGNATURE.length;
//message type
buf.writeUInt32LE(1, pos);
pos += 4;
//flags
buf.writeUInt32LE(flags.NTLMFLAG_NEGOTIATE_OEM |
flags.NTLMFLAG_REQUEST_TARGET |
flags.NTLMFLAG_NEGOTIATE_NTLM_KEY |
flags.NTLMFLAG_NEGOTIATE_NTLM2_KEY |
flags.NTLMFLAG_NEGOTIATE_ALWAYS_SIGN, pos);
pos += 4;
//domain security buffer
buf.writeUInt16LE(target.length, pos);
pos += 2;
buf.writeUInt16LE(target.length, pos);
pos += 2;
buf.writeUInt32LE(target.length === 0 ? 0 : dataPos, pos);
pos += 4;
if (target.length > 0) {
dataPos += buf.write(target, dataPos, 'ascii');
}
//workstation security buffer
buf.writeUInt16LE(workstation.length, pos);
pos += 2;
buf.writeUInt16LE(workstation.length, pos);
pos += 2;
buf.writeUInt32LE(workstation.length === 0 ? 0 : dataPos, pos);
pos += 4;
if (workstation.length > 0) {
dataPos += buf.write(workstation, dataPos, 'ascii');
}
return 'NTLM ' + buf.toString('base64', 0, dataPos);
}
function decodeType2Message(str) {
if (str === undefined) {
throw new Error('Invalid argument');
}
//convenience
if (Object.prototype.toString.call(str) !== '[object String]') {
if (str.hasOwnProperty('headers') && str.headers.hasOwnProperty('www-authenticate')) {
str = str.headers['www-authenticate'];
}
else {
throw new Error('Invalid argument');
}
}
var ntlmMatch = /^NTLM ([^,\s]+)/.exec(str);
if (ntlmMatch) {
str = ntlmMatch[1];
}
var buf = new Buffer.from(str, 'base64'), obj = {};
//check signature
if (buf.toString('ascii', 0, NTLMSIGNATURE.length) !== NTLMSIGNATURE) {
throw new Error('Invalid message signature: ' + str);
}
//check message type
if (buf.readUInt32LE(NTLMSIGNATURE.length) !== 2) {
throw new Error('Invalid message type (no type 2)');
}
//read flags
obj.flags = buf.readUInt32LE(20);
obj.encoding = (obj.flags & flags.NTLMFLAG_NEGOTIATE_OEM) ? 'ascii' : 'ucs2';
obj.version = (obj.flags & flags.NTLMFLAG_NEGOTIATE_NTLM2_KEY) ? 2 : 1;
obj.challenge = buf.slice(24, 32);
//read target name
obj.targetName = (function () {
var length = buf.readUInt16LE(12);
//skipping allocated space
var offset = buf.readUInt32LE(16);
if (length === 0) {
return '';
}
if ((offset + length) > buf.length || offset < 32) {
throw new Error('Bad type 2 message');
}
return buf.toString(obj.encoding, offset, offset + length);
})();
//read target info
if (obj.flags & flags.NTLMFLAG_NEGOTIATE_TARGET_INFO) {
obj.targetInfo = (function () {
var info = {};
var length = buf.readUInt16LE(40);
//skipping allocated space
var offset = buf.readUInt32LE(44);
var targetInfoBuffer = new Buffer.alloc(length);
buf.copy(targetInfoBuffer, 0, offset, offset + length);
if (length === 0) {
return info;
}
if ((offset + length) > buf.length || offset < 32) {
throw new Error('Bad type 2 message');
}
var pos = offset;
while (pos < (offset + length)) {
var blockType = buf.readUInt16LE(pos);
pos += 2;
var blockLength = buf.readUInt16LE(pos);
pos += 2;
if (blockType === 0) {
//reached the terminator subblock
break;
}
var blockTypeStr = void 0;
switch (blockType) {
case 1:
blockTypeStr = 'SERVER';
break;
case 2:
blockTypeStr = 'DOMAIN';
break;
case 3:
blockTypeStr = 'FQDN';
break;
case 4:
blockTypeStr = 'DNS';
break;
case 5:
blockTypeStr = 'PARENT_DNS';
break;
default:
blockTypeStr = '';
break;
}
if (blockTypeStr) {
info[blockTypeStr] = buf.toString('ucs2', pos, pos + blockLength);
}
pos += blockLength;
}
return {
parsed: info,
buffer: targetInfoBuffer
};
})();
}
return obj;
}
function createType3Message(type2Message, username, password, workstation, target) {
var dataPos = 52, buf = new Buffer.alloc(1024);
if (workstation === undefined) {
workstation = os.hostname();
}
if (target === undefined) {
target = type2Message.targetName;
}
//signature
buf.write(NTLMSIGNATURE, 0, NTLMSIGNATURE.length, 'ascii');
//message type
buf.writeUInt32LE(3, 8);
if (type2Message.version === 2) {
dataPos = 64;
var ntlmHash = hash.createNTLMHash(password), nonce = hash.createPseudoRandomValue(16), lmv2 = hash.createLMv2Response(type2Message, username, ntlmHash, nonce, target), ntlmv2 = hash.createNTLMv2Response(type2Message, username, ntlmHash, nonce, target);
//lmv2 security buffer
buf.writeUInt16LE(lmv2.length, 12);
buf.writeUInt16LE(lmv2.length, 14);
buf.writeUInt32LE(dataPos, 16);
lmv2.copy(buf, dataPos);
dataPos += lmv2.length;
//ntlmv2 security buffer
buf.writeUInt16LE(ntlmv2.length, 20);
buf.writeUInt16LE(ntlmv2.length, 22);
buf.writeUInt32LE(dataPos, 24);
ntlmv2.copy(buf, dataPos);
dataPos += ntlmv2.length;
}
else {
var lmHash = hash.createLMHash(password), ntlmHash = hash.createNTLMHash(password), lm = hash.createLMResponse(type2Message.challenge, lmHash), ntlm = hash.createNTLMResponse(type2Message.challenge, ntlmHash);
//lm security buffer
buf.writeUInt16LE(lm.length, 12);
buf.writeUInt16LE(lm.length, 14);
buf.writeUInt32LE(dataPos, 16);
lm.copy(buf, dataPos);
dataPos += lm.length;
//ntlm security buffer
buf.writeUInt16LE(ntlm.length, 20);
buf.writeUInt16LE(ntlm.length, 22);
buf.writeUInt32LE(dataPos, 24);
ntlm.copy(buf, dataPos);
dataPos += ntlm.length;
}
//target name security buffer
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? target.length : target.length * 2, 28);
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? target.length : target.length * 2, 30);
buf.writeUInt32LE(dataPos, 32);
dataPos += buf.write(target, dataPos, type2Message.encoding);
//user name security buffer
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? username.length : username.length * 2, 36);
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? username.length : username.length * 2, 38);
buf.writeUInt32LE(dataPos, 40);
dataPos += buf.write(username, dataPos, type2Message.encoding);
//workstation name security buffer
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? workstation.length : workstation.length * 2, 44);
buf.writeUInt16LE(type2Message.encoding === 'ascii' ? workstation.length : workstation.length * 2, 46);
buf.writeUInt32LE(dataPos, 48);
dataPos += buf.write(workstation, dataPos, type2Message.encoding);
if (type2Message.version === 2) {
//session key security buffer
buf.writeUInt16LE(0, 52);
buf.writeUInt16LE(0, 54);
buf.writeUInt32LE(0, 56);
//flags
buf.writeUInt32LE(type2Message.flags, 60);
}
return 'NTLM ' + buf.toString('base64', 0, dataPos);
}
module.exports = {
createType1Message: createType1Message,
decodeType2Message: decodeType2Message,
createType3Message: createType3Message
};
//# sourceMappingURL=ntlm.js.map

View file

@ -0,0 +1,127 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NtlmClient = void 0;
var axios_1 = __importDefault(require("axios"));
var ntlm = __importStar(require("./ntlm"));
var https = __importStar(require("https"));
var http = __importStar(require("http"));
var dev_null_1 = __importDefault(require("dev-null"));
/**
* @param credentials An NtlmCredentials object containing the username and password
* @param AxiosConfig The Axios config for the instance you wish to create
*
* @returns This function returns an axios instance configured to use the provided credentials
*/
function NtlmClient(credentials, AxiosConfig) {
var _this = this;
var config = AxiosConfig !== null && AxiosConfig !== void 0 ? AxiosConfig : {};
if (!config.httpAgent) {
config.httpAgent = new http.Agent({ keepAlive: true });
}
if (!config.httpsAgent) {
config.httpsAgent = new https.Agent({ keepAlive: true });
}
var client = axios_1.default.create(config);
client.interceptors.response.use(function (response) {
return response;
}, function (err) { return __awaiter(_this, void 0, void 0, function () {
var error, t1Msg, t2Msg, t3Msg, stream_1;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
error = err.response;
if (!(error && error.status === 401
&& error.headers['www-authenticate']
&& error.headers['www-authenticate'].includes('NTLM'))) return [3 /*break*/, 3];
// This length check is a hack because SharePoint is awkward and will
// include the Negotiate option when responding with the T2 message
// There is nore we could do to ensure we are processing correctly,
// but this is the easiest option for now
if (error.headers['www-authenticate'].length < 50) {
t1Msg = ntlm.createType1Message(credentials.workstation, credentials.domain);
error.config.headers["Authorization"] = t1Msg;
}
else {
t2Msg = ntlm.decodeType2Message((error.headers['www-authenticate'].match(/^NTLM\s+(.+?)(,|\s+|$)/) || [])[1]);
t3Msg = ntlm.createType3Message(t2Msg, credentials.username, credentials.password, credentials.workstation, credentials.domain);
error.config.headers["X-retry"] = "false";
error.config.headers["Authorization"] = t3Msg;
}
if (!(error.config.responseType === "stream")) return [3 /*break*/, 2];
stream_1 = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
if (!(stream_1 && !stream_1.readableEnded)) return [3 /*break*/, 2];
return [4 /*yield*/, new Promise(function (resolve) {
stream_1.pipe((0, dev_null_1.default)());
stream_1.once('close', resolve);
})];
case 1:
_b.sent();
_b.label = 2;
case 2: return [2 /*return*/, client(error.config)];
case 3: throw err;
}
});
}); });
return client;
}
exports.NtlmClient = NtlmClient;
//# sourceMappingURL=ntlmClient.js.map

View file

@ -0,0 +1,71 @@
const { ConditionExpressionGroup, ConditionExpression, LOGICAL } = require("./expression");
const { operatorMap } = require("./operators");
/**
* @param {ConditionExpression} expression Expression to evaluate
* @param {object} context Context to evaluate against; These are values for variables in the expression
* @returns {boolean} Whether the expression evaluates true or false
* @throws {Error}
*/
function evaluateExpression(expression, context) {
/**
* @type {import("./operators").ConditionOperator|null}
*/
const operator = operatorMap.get(expression.operator) || null;
if (operator === null) {
throw new Error("Unexpected expression operator ID '" + expression.operator + "'. Expected one of [" + operatorMap.keys().join(",") + "]");
}
if (!Object.prototype.hasOwnProperty.call(context, expression.variable)) {
throw new Error("Variable missing in context: " + expression.variable);
}
return operator.test(context[expression.variable], expression.value);
}
/**
* @param {ConditionExpressionGroup} group Group of expressions to evaluate
* @param {object} context Context to evaluate against; These are values for variables in the expression
* @returns {boolean} Whether the group evaluates true or false
* @throws {Error}
*/
function evaluateExpressionGroup(group, context) {
if (!group.children.length) {
throw new Error("ConditionExpressionGroup must contain at least one child.");
}
let result = null;
for (const child of group.children) {
let childResult;
if (child instanceof ConditionExpression) {
childResult = evaluateExpression(child, context);
} else if (child instanceof ConditionExpressionGroup) {
childResult = evaluateExpressionGroup(child, context);
} else {
throw new Error("Invalid child type in ConditionExpressionGroup. Expected ConditionExpression or ConditionExpressionGroup");
}
if (result === null) {
result = childResult; // Initialize result with the first child's result
} else if (child.andOr === LOGICAL.OR) {
result = result || childResult;
} else if (child.andOr === LOGICAL.AND) {
result = result && childResult;
} else {
throw new Error("Invalid logical operator in child of ConditionExpressionGroup. Expected 'and' or 'or'. Got '" + group.andOr + "'");
}
}
if (result === null) {
throw new Error("ConditionExpressionGroup did not result in a boolean.");
}
return result;
}
module.exports = {
evaluateExpression,
evaluateExpressionGroup,
};

View file

@ -0,0 +1,111 @@
/**
* @readonly
* @enum {string}
*/
const LOGICAL = {
AND: "and",
OR: "or",
};
/**
* Recursively processes an array of raw condition objects and populates the given parent group with
* corresponding ConditionExpression or ConditionExpressionGroup instances.
* @param {Array} conditions Array of raw condition objects, where each object represents either a group or an expression.
* @param {ConditionExpressionGroup} parentGroup The parent group to which the instantiated ConditionExpression or ConditionExpressionGroup objects will be added.
* @returns {void}
*/
function processMonitorConditions(conditions, parentGroup) {
conditions.forEach(condition => {
const andOr = condition.andOr === LOGICAL.OR ? LOGICAL.OR : LOGICAL.AND;
if (condition.type === "group") {
const group = new ConditionExpressionGroup([], andOr);
// Recursively process the group's children
processMonitorConditions(condition.children, group);
parentGroup.children.push(group);
} else if (condition.type === "expression") {
const expression = new ConditionExpression(condition.variable, condition.operator, condition.value, andOr);
parentGroup.children.push(expression);
}
});
}
class ConditionExpressionGroup {
/**
* @type {ConditionExpressionGroup[]|ConditionExpression[]} Groups and/or expressions to test
*/
children = [];
/**
* @type {LOGICAL} Connects group result with previous group/expression results
*/
andOr;
/**
* @param {ConditionExpressionGroup[]|ConditionExpression[]} children Groups and/or expressions to test
* @param {LOGICAL} andOr Connects group result with previous group/expression results
*/
constructor(children = [], andOr = LOGICAL.AND) {
this.children = children;
this.andOr = andOr;
}
/**
* @param {Monitor} monitor Monitor instance
* @returns {ConditionExpressionGroup|null} A ConditionExpressionGroup with the Monitor's conditions
*/
static fromMonitor(monitor) {
const conditions = JSON.parse(monitor.conditions);
if (conditions.length === 0) {
return null;
}
const root = new ConditionExpressionGroup();
processMonitorConditions(conditions, root);
return root;
}
}
class ConditionExpression {
/**
* @type {string} ID of variable
*/
variable;
/**
* @type {string} ID of operator
*/
operator;
/**
* @type {string} Value to test with the operator
*/
value;
/**
* @type {LOGICAL} Connects expression result with previous group/expression results
*/
andOr;
/**
* @param {string} variable ID of variable to test against
* @param {string} operator ID of operator to test the variable with
* @param {string} value Value to test with the operator
* @param {LOGICAL} andOr Connects expression result with previous group/expression results
*/
constructor(variable, operator, value, andOr = LOGICAL.AND) {
this.variable = variable;
this.operator = operator;
this.value = value;
this.andOr = andOr;
}
}
module.exports = {
LOGICAL,
ConditionExpressionGroup,
ConditionExpression,
};

View file

@ -0,0 +1,318 @@
class ConditionOperator {
id = undefined;
caption = undefined;
/**
* @type {mixed} variable
* @type {mixed} value
*/
test(variable, value) {
throw new Error("You need to override test()");
}
}
const OP_STR_EQUALS = "equals";
const OP_STR_NOT_EQUALS = "not_equals";
const OP_CONTAINS = "contains";
const OP_NOT_CONTAINS = "not_contains";
const OP_STARTS_WITH = "starts_with";
const OP_NOT_STARTS_WITH = "not_starts_with";
const OP_ENDS_WITH = "ends_with";
const OP_NOT_ENDS_WITH = "not_ends_with";
const OP_NUM_EQUALS = "num_equals";
const OP_NUM_NOT_EQUALS = "num_not_equals";
const OP_LT = "lt";
const OP_GT = "gt";
const OP_LTE = "lte";
const OP_GTE = "gte";
/**
* Asserts a variable is equal to a value.
*/
class StringEqualsOperator extends ConditionOperator {
id = OP_STR_EQUALS;
caption = "equals";
/**
* @inheritdoc
*/
test(variable, value) {
return variable === value;
}
}
/**
* Asserts a variable is not equal to a value.
*/
class StringNotEqualsOperator extends ConditionOperator {
id = OP_STR_NOT_EQUALS;
caption = "not equals";
/**
* @inheritdoc
*/
test(variable, value) {
return variable !== value;
}
}
/**
* Asserts a variable contains a value.
* Handles both Array and String variable types.
*/
class ContainsOperator extends ConditionOperator {
id = OP_CONTAINS;
caption = "contains";
/**
* @inheritdoc
*/
test(variable, value) {
if (Array.isArray(variable)) {
return variable.includes(value);
}
return variable.indexOf(value) !== -1;
}
}
/**
* Asserts a variable does not contain a value.
* Handles both Array and String variable types.
*/
class NotContainsOperator extends ConditionOperator {
id = OP_NOT_CONTAINS;
caption = "not contains";
/**
* @inheritdoc
*/
test(variable, value) {
if (Array.isArray(variable)) {
return !variable.includes(value);
}
return variable.indexOf(value) === -1;
}
}
/**
* Asserts a variable starts with a value.
*/
class StartsWithOperator extends ConditionOperator {
id = OP_STARTS_WITH;
caption = "starts with";
/**
* @inheritdoc
*/
test(variable, value) {
return variable.startsWith(value);
}
}
/**
* Asserts a variable does not start with a value.
*/
class NotStartsWithOperator extends ConditionOperator {
id = OP_NOT_STARTS_WITH;
caption = "not starts with";
/**
* @inheritdoc
*/
test(variable, value) {
return !variable.startsWith(value);
}
}
/**
* Asserts a variable ends with a value.
*/
class EndsWithOperator extends ConditionOperator {
id = OP_ENDS_WITH;
caption = "ends with";
/**
* @inheritdoc
*/
test(variable, value) {
return variable.endsWith(value);
}
}
/**
* Asserts a variable does not end with a value.
*/
class NotEndsWithOperator extends ConditionOperator {
id = OP_NOT_ENDS_WITH;
caption = "not ends with";
/**
* @inheritdoc
*/
test(variable, value) {
return !variable.endsWith(value);
}
}
/**
* Asserts a numeric variable is equal to a value.
*/
class NumberEqualsOperator extends ConditionOperator {
id = OP_NUM_EQUALS;
caption = "equals";
/**
* @inheritdoc
*/
test(variable, value) {
return variable === Number(value);
}
}
/**
* Asserts a numeric variable is not equal to a value.
*/
class NumberNotEqualsOperator extends ConditionOperator {
id = OP_NUM_NOT_EQUALS;
caption = "not equals";
/**
* @inheritdoc
*/
test(variable, value) {
return variable !== Number(value);
}
}
/**
* Asserts a variable is less than a value.
*/
class LessThanOperator extends ConditionOperator {
id = OP_LT;
caption = "less than";
/**
* @inheritdoc
*/
test(variable, value) {
return variable < Number(value);
}
}
/**
* Asserts a variable is greater than a value.
*/
class GreaterThanOperator extends ConditionOperator {
id = OP_GT;
caption = "greater than";
/**
* @inheritdoc
*/
test(variable, value) {
return variable > Number(value);
}
}
/**
* Asserts a variable is less than or equal to a value.
*/
class LessThanOrEqualToOperator extends ConditionOperator {
id = OP_LTE;
caption = "less than or equal to";
/**
* @inheritdoc
*/
test(variable, value) {
return variable <= Number(value);
}
}
/**
* Asserts a variable is greater than or equal to a value.
*/
class GreaterThanOrEqualToOperator extends ConditionOperator {
id = OP_GTE;
caption = "greater than or equal to";
/**
* @inheritdoc
*/
test(variable, value) {
return variable >= Number(value);
}
}
const operatorMap = new Map([
[ OP_STR_EQUALS, new StringEqualsOperator ],
[ OP_STR_NOT_EQUALS, new StringNotEqualsOperator ],
[ OP_CONTAINS, new ContainsOperator ],
[ OP_NOT_CONTAINS, new NotContainsOperator ],
[ OP_STARTS_WITH, new StartsWithOperator ],
[ OP_NOT_STARTS_WITH, new NotStartsWithOperator ],
[ OP_ENDS_WITH, new EndsWithOperator ],
[ OP_NOT_ENDS_WITH, new NotEndsWithOperator ],
[ OP_NUM_EQUALS, new NumberEqualsOperator ],
[ OP_NUM_NOT_EQUALS, new NumberNotEqualsOperator ],
[ OP_LT, new LessThanOperator ],
[ OP_GT, new GreaterThanOperator ],
[ OP_LTE, new LessThanOrEqualToOperator ],
[ OP_GTE, new GreaterThanOrEqualToOperator ],
]);
const defaultStringOperators = [
operatorMap.get(OP_STR_EQUALS),
operatorMap.get(OP_STR_NOT_EQUALS),
operatorMap.get(OP_CONTAINS),
operatorMap.get(OP_NOT_CONTAINS),
operatorMap.get(OP_STARTS_WITH),
operatorMap.get(OP_NOT_STARTS_WITH),
operatorMap.get(OP_ENDS_WITH),
operatorMap.get(OP_NOT_ENDS_WITH)
];
const defaultNumberOperators = [
operatorMap.get(OP_NUM_EQUALS),
operatorMap.get(OP_NUM_NOT_EQUALS),
operatorMap.get(OP_LT),
operatorMap.get(OP_GT),
operatorMap.get(OP_LTE),
operatorMap.get(OP_GTE)
];
module.exports = {
OP_STR_EQUALS,
OP_STR_NOT_EQUALS,
OP_CONTAINS,
OP_NOT_CONTAINS,
OP_STARTS_WITH,
OP_NOT_STARTS_WITH,
OP_ENDS_WITH,
OP_NOT_ENDS_WITH,
OP_NUM_EQUALS,
OP_NUM_NOT_EQUALS,
OP_LT,
OP_GT,
OP_LTE,
OP_GTE,
operatorMap,
defaultStringOperators,
defaultNumberOperators,
ConditionOperator,
};

View file

@ -0,0 +1,31 @@
/**
* Represents a variable used in a condition and the set of operators that can be applied to this variable.
*
* A `ConditionVariable` holds the ID of the variable and a list of operators that define how this variable can be evaluated
* in conditions. For example, if the variable is a request body or a specific field in a request, the operators can include
* operations such as equality checks, comparisons, or other custom evaluations.
*/
class ConditionVariable {
/**
* @type {string}
*/
id;
/**
* @type {import("./operators").ConditionOperator[]}
*/
operators = {};
/**
* @param {string} id ID of variable
* @param {import("./operators").ConditionOperator[]} operators Operators the condition supports
*/
constructor(id, operators = []) {
this.id = id;
this.operators = operators;
}
}
module.exports = {
ConditionVariable,
};

View file

@ -1,13 +1,22 @@
const { MonitorType } = require("./monitor-type"); const { MonitorType } = require("./monitor-type");
const { UP } = require("../../src/util"); const { UP, DOWN } = require("../../src/util");
const dayjs = require("dayjs"); const dayjs = require("dayjs");
const { dnsResolve } = require("../util-server"); const { dnsResolve } = require("../util-server");
const { R } = require("redbean-node"); const { R } = require("redbean-node");
const { ConditionVariable } = require("../monitor-conditions/variables");
const { defaultStringOperators } = require("../monitor-conditions/operators");
const { ConditionExpressionGroup } = require("../monitor-conditions/expression");
const { evaluateExpressionGroup } = require("../monitor-conditions/evaluator");
class DnsMonitorType extends MonitorType { class DnsMonitorType extends MonitorType {
name = "dns"; name = "dns";
supportsConditions = true;
conditionVariables = [
new ConditionVariable("record", defaultStringOperators ),
];
/** /**
* @inheritdoc * @inheritdoc
*/ */
@ -18,28 +27,48 @@ class DnsMonitorType extends MonitorType {
let dnsRes = await dnsResolve(monitor.hostname, monitor.dns_resolve_server, monitor.port, monitor.dns_resolve_type); let dnsRes = await dnsResolve(monitor.hostname, monitor.dns_resolve_server, monitor.port, monitor.dns_resolve_type);
heartbeat.ping = dayjs().valueOf() - startTime; heartbeat.ping = dayjs().valueOf() - startTime;
if (monitor.dns_resolve_type === "A" || monitor.dns_resolve_type === "AAAA" || monitor.dns_resolve_type === "TXT" || monitor.dns_resolve_type === "PTR") { const conditions = ConditionExpressionGroup.fromMonitor(monitor);
dnsMessage += "Records: "; let conditionsResult = true;
dnsMessage += dnsRes.join(" | "); const handleConditions = (data) => conditions ? evaluateExpressionGroup(conditions, data) : true;
} else if (monitor.dns_resolve_type === "CNAME" || monitor.dns_resolve_type === "PTR") {
dnsMessage += dnsRes[0]; switch (monitor.dns_resolve_type) {
} else if (monitor.dns_resolve_type === "CAA") { case "A":
dnsMessage += dnsRes[0].issue; case "AAAA":
} else if (monitor.dns_resolve_type === "MX") { case "TXT":
dnsRes.forEach(record => { case "PTR":
dnsMessage += `Hostname: ${record.exchange} - Priority: ${record.priority} | `; dnsMessage = `Records: ${dnsRes.join(" | ")}`;
}); conditionsResult = dnsRes.some(record => handleConditions({ record }));
dnsMessage = dnsMessage.slice(0, -2); break;
} else if (monitor.dns_resolve_type === "NS") {
dnsMessage += "Servers: "; case "CNAME":
dnsMessage += dnsRes.join(" | "); dnsMessage = dnsRes[0];
} else if (monitor.dns_resolve_type === "SOA") { conditionsResult = handleConditions({ record: dnsRes[0] });
dnsMessage += `NS-Name: ${dnsRes.nsname} | Hostmaster: ${dnsRes.hostmaster} | Serial: ${dnsRes.serial} | Refresh: ${dnsRes.refresh} | Retry: ${dnsRes.retry} | Expire: ${dnsRes.expire} | MinTTL: ${dnsRes.minttl}`; break;
} else if (monitor.dns_resolve_type === "SRV") {
dnsRes.forEach(record => { case "CAA":
dnsMessage += `Name: ${record.name} | Port: ${record.port} | Priority: ${record.priority} | Weight: ${record.weight} | `; dnsMessage = dnsRes[0].issue;
}); conditionsResult = handleConditions({ record: dnsRes[0].issue });
dnsMessage = dnsMessage.slice(0, -2); break;
case "MX":
dnsMessage = dnsRes.map(record => `Hostname: ${record.exchange} - Priority: ${record.priority}`).join(" | ");
conditionsResult = dnsRes.some(record => handleConditions({ record: record.exchange }));
break;
case "NS":
dnsMessage = `Servers: ${dnsRes.join(" | ")}`;
conditionsResult = dnsRes.some(record => handleConditions({ record }));
break;
case "SOA":
dnsMessage = `NS-Name: ${dnsRes.nsname} | Hostmaster: ${dnsRes.hostmaster} | Serial: ${dnsRes.serial} | Refresh: ${dnsRes.refresh} | Retry: ${dnsRes.retry} | Expire: ${dnsRes.expire} | MinTTL: ${dnsRes.minttl}`;
conditionsResult = handleConditions({ record: dnsRes.nsname });
break;
case "SRV":
dnsMessage = dnsRes.map(record => `Name: ${record.name} | Port: ${record.port} | Priority: ${record.priority} | Weight: ${record.weight}`).join(" | ");
conditionsResult = dnsRes.some(record => handleConditions({ record: record.name }));
break;
} }
if (monitor.dns_last_result !== dnsMessage && dnsMessage !== undefined) { if (monitor.dns_last_result !== dnsMessage && dnsMessage !== undefined) {
@ -47,7 +76,7 @@ class DnsMonitorType extends MonitorType {
} }
heartbeat.msg = dnsMessage; heartbeat.msg = dnsMessage;
heartbeat.status = UP; heartbeat.status = conditionsResult ? UP : DOWN;
} }
} }

View file

@ -0,0 +1,63 @@
const { MonitorType } = require("./monitor-type");
const { UP } = require("../../src/util");
const { MongoClient } = require("mongodb");
const jsonata = require("jsonata");
class MongodbMonitorType extends MonitorType {
name = "mongodb";
/**
* @inheritdoc
*/
async check(monitor, heartbeat, _server) {
let command = { "ping": 1 };
if (monitor.databaseQuery) {
command = JSON.parse(monitor.databaseQuery);
}
let result = await this.runMongodbCommand(monitor.databaseConnectionString, command);
if (result["ok"] !== 1) {
throw new Error("MongoDB command failed");
} else {
heartbeat.msg = "Command executed successfully";
}
if (monitor.jsonPath) {
let expression = jsonata(monitor.jsonPath);
result = await expression.evaluate(result);
if (result) {
heartbeat.msg = "Command executed successfully and the jsonata expression produces a result.";
} else {
throw new Error("Queried value not found.");
}
}
if (monitor.expectedValue) {
if (result.toString() === monitor.expectedValue) {
heartbeat.msg = "Command executed successfully and expected value was found";
} else {
throw new Error("Query executed, but value is not equal to expected value, value was: [" + JSON.stringify(result) + "]");
}
}
heartbeat.status = UP;
}
/**
* Connect to and run MongoDB command on a MongoDB database
* @param {string} connectionString The database connection string
* @param {object} command MongoDB command to run on the database
* @returns {Promise<(string[] | object[] | object)>} Response from server
*/
async runMongodbCommand(connectionString, command) {
let client = await MongoClient.connect(connectionString);
let result = await client.db().command(command);
await client.close();
return result;
}
}
module.exports = {
MongodbMonitorType,
};

View file

@ -1,7 +1,19 @@
class MonitorType { class MonitorType {
name = undefined; name = undefined;
/**
* Whether or not this type supports monitor conditions. Controls UI visibility in monitor form.
* @type {boolean}
*/
supportsConditions = false;
/**
* Variables supported by this type. e.g. an HTTP type could have a "response_code" variable to test against.
* This property controls the choices displayed in the monitor edit form.
* @type {import("../monitor-conditions/variables").ConditionVariable[]}
*/
conditionVariables = [];
/** /**
* Run the monitoring check on the given monitor * Run the monitoring check on the given monitor
* @param {Monitor} monitor Monitor to check * @param {Monitor} monitor Monitor to check
@ -12,7 +24,6 @@ class MonitorType {
async check(monitor, heartbeat, server) { async check(monitor, heartbeat, server) {
throw new Error("You need to override check()"); throw new Error("You need to override check()");
} }
} }
module.exports = { module.exports = {

View file

@ -4,15 +4,10 @@ const mqtt = require("mqtt");
const jsonata = require("jsonata"); const jsonata = require("jsonata");
class MqttMonitorType extends MonitorType { class MqttMonitorType extends MonitorType {
name = "mqtt"; name = "mqtt";
/** /**
* Run the monitoring check on the MQTT monitor * @inheritdoc
* @param {Monitor} monitor Monitor to check
* @param {Heartbeat} heartbeat Monitor heartbeat to update
* @param {UptimeKumaServer} server Uptime Kuma server
* @returns {Promise<void>}
*/ */
async check(monitor, heartbeat, server) { async check(monitor, heartbeat, server) {
const receivedMessage = await this.mqttAsync(monitor.hostname, monitor.mqttTopic, { const receivedMessage = await this.mqttAsync(monitor.hostname, monitor.mqttTopic, {
@ -81,7 +76,8 @@ class MqttMonitorType extends MonitorType {
let client = mqtt.connect(mqttUrl, { let client = mqtt.connect(mqttUrl, {
username, username,
password password,
clientId: "uptime-kuma_" + Math.random().toString(16).substr(2, 8)
}); });
client.on("connect", () => { client.on("connect", () => {

View file

@ -10,6 +10,10 @@ const jwt = require("jsonwebtoken");
const config = require("../config"); const config = require("../config");
const { RemoteBrowser } = require("../remote-browser"); const { RemoteBrowser } = require("../remote-browser");
/**
* Cached instance of a browser
* @type {import ("playwright-core").Browser}
*/
let browser = null; let browser = null;
let allowedList = []; let allowedList = [];
@ -71,10 +75,12 @@ async function isAllowedChromeExecutable(executablePath) {
/** /**
* Get the current instance of the browser. If there isn't one, create * Get the current instance of the browser. If there isn't one, create
* it. * it.
* @returns {Promise<Browser>} The browser * @returns {Promise<import ("playwright-core").Browser>} The browser
*/ */
async function getBrowser() { async function getBrowser() {
if (!browser) { if (browser && browser.isConnected()) {
return browser;
} else {
let executablePath = await Settings.get("chromeExecutable"); let executablePath = await Settings.get("chromeExecutable");
executablePath = await prepareChromeExecutable(executablePath); executablePath = await prepareChromeExecutable(executablePath);
@ -83,8 +89,9 @@ async function getBrowser() {
//headless: false, //headless: false,
executablePath, executablePath,
}); });
return browser;
} }
return browser;
} }
/** /**
@ -96,7 +103,7 @@ async function getBrowser() {
async function getRemoteBrowser(remoteBrowserID, userId) { async function getRemoteBrowser(remoteBrowserID, userId) {
let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId); let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId);
log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`); log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`);
browser = chromium.connect(remoteBrowser.url); browser = await chromium.connect(remoteBrowser.url);
return browser; return browser;
} }

View file

@ -0,0 +1,63 @@
const { MonitorType } = require("./monitor-type");
const { UP, log, evaluateJsonQuery } = require("../../src/util");
const snmp = require("net-snmp");
class SNMPMonitorType extends MonitorType {
name = "snmp";
/**
* @inheritdoc
*/
async check(monitor, heartbeat, _server) {
let session;
try {
const sessionOptions = {
port: monitor.port || "161",
retries: monitor.maxretries,
timeout: monitor.timeout * 1000,
version: snmp.Version[monitor.snmpVersion],
};
session = snmp.createSession(monitor.hostname, monitor.radiusPassword, sessionOptions);
// Handle errors during session creation
session.on("error", (error) => {
throw new Error(`Error creating SNMP session: ${error.message}`);
});
const varbinds = await new Promise((resolve, reject) => {
session.get([ monitor.snmpOid ], (error, varbinds) => {
error ? reject(error) : resolve(varbinds);
});
});
log.debug("monitor", `SNMP: Received varbinds (Type: ${snmp.ObjectType[varbinds[0].type]} Value: ${varbinds[0].value})`);
if (varbinds.length === 0) {
throw new Error(`No varbinds returned from SNMP session (OID: ${monitor.snmpOid})`);
}
if (varbinds[0].type === snmp.ObjectType.NoSuchInstance) {
throw new Error(`The SNMP query returned that no instance exists for OID ${monitor.snmpOid}`);
}
// We restrict querying to one OID per monitor, therefore `varbinds[0]` will always contain the value we're interested in.
const value = varbinds[0].value;
const { status, response } = await evaluateJsonQuery(value, monitor.jsonPath, monitor.jsonPathOperator, monitor.expectedValue);
if (status) {
heartbeat.status = UP;
heartbeat.msg = `JSON query passes (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`;
} else {
throw new Error(`JSON query does not pass (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`);
}
} finally {
if (session) {
session.close();
}
}
}
}
module.exports = {
SNMPMonitorType,
};

View file

@ -2,23 +2,13 @@ const { MonitorType } = require("./monitor-type");
const { UP } = require("../../src/util"); const { UP } = require("../../src/util");
const childProcessAsync = require("promisify-child-process"); const childProcessAsync = require("promisify-child-process");
/**
* A TailscalePing class extends the MonitorType.
* It runs Tailscale ping to monitor the status of a specific node.
*/
class TailscalePing extends MonitorType { class TailscalePing extends MonitorType {
name = "tailscale-ping"; name = "tailscale-ping";
/** /**
* Checks the ping status of the URL associated with the monitor. * @inheritdoc
* It then parses the Tailscale ping command output to update the heatrbeat.
* @param {object} monitor The monitor object associated with the check.
* @param {object} heartbeat The heartbeat object to update.
* @returns {Promise<void>}
* @throws Will throw an error if checking Tailscale ping encounters any error
*/ */
async check(monitor, heartbeat) { async check(monitor, heartbeat, _server) {
try { try {
let tailscaleOutput = await this.runTailscalePing(monitor.hostname, monitor.interval); let tailscaleOutput = await this.runTailscalePing(monitor.hostname, monitor.interval);
this.parseTailscaleOutput(tailscaleOutput, heartbeat); this.parseTailscaleOutput(tailscaleOutput, heartbeat);

View file

@ -3,17 +3,15 @@ const { DOWN, UP } = require("../../src/util");
const axios = require("axios"); const axios = require("axios");
class Alerta extends NotificationProvider { class Alerta extends NotificationProvider {
name = "alerta"; name = "alerta";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let alertaUrl = `${notification.alertaApiEndpoint}`;
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json;charset=UTF-8", "Content-Type": "application/json;charset=UTF-8",
@ -40,7 +38,7 @@ class Alerta extends NotificationProvider {
resource: "Message", resource: "Message",
}, data); }, data);
await axios.post(alertaUrl, postData, config); await axios.post(notification.alertaApiEndpoint, postData, config);
} else { } else {
let datadup = Object.assign( { let datadup = Object.assign( {
correlate: [ "service_up", "service_down" ], correlate: [ "service_up", "service_down" ],
@ -52,11 +50,11 @@ class Alerta extends NotificationProvider {
if (heartbeatJSON["status"] === DOWN) { if (heartbeatJSON["status"] === DOWN) {
datadup.severity = notification.alertaAlertState; // critical datadup.severity = notification.alertaAlertState; // critical
datadup.text = "Service " + monitorJSON["type"] + " is down."; datadup.text = "Service " + monitorJSON["type"] + " is down.";
await axios.post(alertaUrl, datadup, config); await axios.post(notification.alertaApiEndpoint, datadup, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
datadup.severity = notification.alertaRecoverState; // cleaned datadup.severity = notification.alertaRecoverState; // cleaned
datadup.text = "Service " + monitorJSON["type"] + " is up."; datadup.text = "Service " + monitorJSON["type"] + " is up.";
await axios.post(alertaUrl, datadup, config); await axios.post(notification.alertaApiEndpoint, datadup, config);
} }
} }
return okMsg; return okMsg;

View file

@ -4,14 +4,14 @@ const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util");
const { Settings } = require("../settings"); const { Settings } = require("../settings");
class AlertNow extends NotificationProvider { class AlertNow extends NotificationProvider {
name = "AlertNow"; name = "AlertNow";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let textMsg = ""; let textMsg = "";
let status = "open"; let status = "open";

View file

@ -11,7 +11,7 @@ class AliyunSMS extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON != null) { if (heartbeatJSON != null) {
@ -44,7 +44,7 @@ class AliyunSMS extends NotificationProvider {
* Send the SMS notification * Send the SMS notification
* @param {BeanModel} notification Notification details * @param {BeanModel} notification Notification details
* @param {string} msgbody Message template * @param {string} msgbody Message template
* @returns {boolean} True if successful else false * @returns {Promise<boolean>} True if successful else false
*/ */
async sendSms(notification, msgbody) { async sendSms(notification, msgbody) {
let params = { let params = {

View file

@ -2,13 +2,14 @@ const NotificationProvider = require("./notification-provider");
const childProcessAsync = require("promisify-child-process"); const childProcessAsync = require("promisify-child-process");
class Apprise extends NotificationProvider { class Apprise extends NotificationProvider {
name = "apprise"; name = "apprise";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const args = [ "-vv", "-b", msg, notification.appriseURL ]; const args = [ "-vv", "-b", msg, notification.appriseURL ];
if (notification.title) { if (notification.title) {
args.push("-t"); args.push("-t");
@ -23,7 +24,7 @@ class Apprise extends NotificationProvider {
if (output) { if (output) {
if (! output.includes("ERROR")) { if (! output.includes("ERROR")) {
return "Sent Successfully"; return okMsg;
} }
throw new Error(output); throw new Error(output);

View file

@ -46,29 +46,29 @@ class Bark extends NotificationProvider {
} }
/** /**
* Add additional parameter for Bark v1 endpoints * Add additional parameter for Bark v1 endpoints.
* Leads to better on device styles (iOS 15 optimized)
* @param {BeanModel} notification Notification to send * @param {BeanModel} notification Notification to send
* @param {string} postUrl URL to append parameters to
* @returns {string} Additional URL parameters * @returns {string} Additional URL parameters
*/ */
appendAdditionalParameters(notification, postUrl) { additionalParameters(notification) {
// set icon to uptime kuma icon, 11kb should be fine // set icon to uptime kuma icon, 11kb should be fine
postUrl += "?icon=" + barkNotificationAvatar; let params = "?icon=" + barkNotificationAvatar;
// grouping all our notifications // grouping all our notifications
if (notification.barkGroup != null) { if (notification.barkGroup != null) {
postUrl += "&group=" + notification.barkGroup; params += "&group=" + notification.barkGroup;
} else { } else {
// default name // default name
postUrl += "&group=" + "UptimeKuma"; params += "&group=" + "UptimeKuma";
} }
// picked a sound, this should follow system's mute status when arrival // picked a sound, this should follow system's mute status when arrival
if (notification.barkSound != null) { if (notification.barkSound != null) {
postUrl += "&sound=" + notification.barkSound; params += "&sound=" + notification.barkSound;
} else { } else {
// default sound // default sound
postUrl += "&sound=" + "telegraph"; params += "&sound=" + "telegraph";
} }
return postUrl; return params;
} }
/** /**
@ -92,7 +92,7 @@ class Bark extends NotificationProvider {
* @param {string} title Message title * @param {string} title Message title
* @param {string} subtitle Message * @param {string} subtitle Message
* @param {string} endpoint Endpoint to send request to * @param {string} endpoint Endpoint to send request to
* @returns {string} Success message * @returns {Promise<string>} Success message
*/ */
async postNotification(notification, title, subtitle, endpoint) { async postNotification(notification, title, subtitle, endpoint) {
let result; let result;
@ -100,9 +100,8 @@ class Bark extends NotificationProvider {
// url encode title and subtitle // url encode title and subtitle
title = encodeURIComponent(title); title = encodeURIComponent(title);
subtitle = encodeURIComponent(subtitle); subtitle = encodeURIComponent(subtitle);
let postUrl = endpoint + "/" + title + "/" + subtitle; const params = this.additionalParameters(notification);
postUrl = this.appendAdditionalParameters(notification, postUrl); result = await axios.get(`${endpoint}/${title}/${subtitle}${params}`);
result = await axios.get(postUrl);
} else { } else {
result = await axios.post(`${endpoint}/push`, { result = await axios.post(`${endpoint}/push`, {
title, title,

View file

@ -0,0 +1,31 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { UP } = require("../../src/util");
class Bitrix24 extends NotificationProvider {
name = "Bitrix24";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
const params = {
user_id: notification.bitrix24UserID,
message: "[B]Uptime Kuma[/B]",
"ATTACH[COLOR]": (heartbeatJSON ?? {})["status"] === UP ? "#b73419" : "#67b518",
"ATTACH[BLOCKS][0][MESSAGE]": msg
};
await axios.get(`${notification.bitrix24WebhookURL}/im.notify.system.add.json`, { params });
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Bitrix24;

View file

@ -0,0 +1,23 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class CallMeBot extends NotificationProvider {
name = "CallMeBot";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
const url = new URL(notification.callMeBotEndpoint);
url.searchParams.set("text", msg);
await axios.get(url.toString());
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = CallMeBot;

View file

@ -0,0 +1,39 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class Cellsynt extends NotificationProvider {
name = "Cellsynt";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const data = {
// docs at https://www.cellsynt.com/en/sms/api-integration
params: {
"username": notification.cellsyntLogin,
"password": notification.cellsyntPassword,
"destination": notification.cellsyntDestination,
"text": msg.replace(/[^\x00-\x7F]/g, ""),
"originatortype": notification.cellsyntOriginatortype,
"originator": notification.cellsyntOriginator,
"allowconcat": notification.cellsyntAllowLongSMS ? 6 : 1
}
};
try {
const resp = await axios.post("https://se-1.cellsynt.net/sms.php", null, data);
if (resp.data == null ) {
throw new Error("Could not connect to Cellsynt, please try again.");
} else if (resp.data.includes("Error:")) {
resp.data = resp.data.replaceAll("Error:", "");
throw new Error(resp.data);
}
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Cellsynt;

View file

@ -2,14 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class ClickSendSMS extends NotificationProvider { class ClickSendSMS extends NotificationProvider {
name = "clicksendsms"; name = "clicksendsms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://rest.clicksend.com/v3/sms/send";
try { try {
let config = { let config = {
headers: { headers: {
@ -28,7 +29,7 @@ class ClickSendSMS extends NotificationProvider {
} }
] ]
}; };
let resp = await axios.post("https://rest.clicksend.com/v3/sms/send", data, config); let resp = await axios.post(url, data, config);
if (resp.data.data.messages[0].status !== "SUCCESS") { if (resp.data.data.messages[0].status !== "SUCCESS") {
let error = "Something gone wrong. Api returned " + resp.data.data.messages[0].status + "."; let error = "Something gone wrong. Api returned " + resp.data.data.messages[0].status + ".";
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

View file

@ -10,7 +10,7 @@ class DingDing extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON != null) { if (heartbeatJSON != null) {
@ -19,9 +19,12 @@ class DingDing extends NotificationProvider {
markdown: { markdown: {
title: `[${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]}`, title: `[${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]}`,
text: `## [${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, text: `## [${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
},
"at": {
"isAtAll": notification.mentioning === "everyone"
} }
}; };
if (this.sendToDingDing(notification, params)) { if (await this.sendToDingDing(notification, params)) {
return okMsg; return okMsg;
} }
} else { } else {
@ -31,7 +34,7 @@ class DingDing extends NotificationProvider {
content: msg content: msg
} }
}; };
if (this.sendToDingDing(notification, params)) { if (await this.sendToDingDing(notification, params)) {
return okMsg; return okMsg;
} }
} }
@ -44,7 +47,7 @@ class DingDing extends NotificationProvider {
* Send message to DingDing * Send message to DingDing
* @param {BeanModel} notification Notification to send * @param {BeanModel} notification Notification to send
* @param {object} params Parameters of message * @param {object} params Parameters of message
* @returns {boolean} True if successful else false * @returns {Promise<boolean>} True if successful else false
*/ */
async sendToDingDing(notification, params) { async sendToDingDing(notification, params) {
let timestamp = Date.now(); let timestamp = Date.now();
@ -62,7 +65,7 @@ class DingDing extends NotificationProvider {
if (result.data.errmsg === "ok") { if (result.data.errmsg === "ok") {
return true; return true;
} }
return false; throw new Error(result.data.errmsg);
} }
/** /**

View file

@ -3,17 +3,20 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Discord extends NotificationProvider { class Discord extends NotificationProvider {
name = "discord"; name = "discord";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
const discordDisplayName = notification.discordUsername || "Uptime Kuma"; const discordDisplayName = notification.discordUsername || "Uptime Kuma";
const webhookUrl = new URL(notification.discordWebhookUrl);
if (notification.discordChannelType === "postToThread") {
webhookUrl.searchParams.append("thread_id", notification.threadId);
}
// If heartbeatJSON is null, assume we're testing. // If heartbeatJSON is null, assume we're testing.
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
@ -21,30 +24,15 @@ class Discord extends NotificationProvider {
username: discordDisplayName, username: discordDisplayName,
content: msg, content: msg,
}; };
await axios.post(notification.discordWebhookUrl, discordtestdata);
if (notification.discordChannelType === "createNewForumPost") {
discordtestdata.thread_name = notification.postName;
}
await axios.post(webhookUrl.toString(), discordtestdata);
return okMsg; return okMsg;
} }
let address;
switch (monitorJSON["type"]) {
case "ping":
address = monitorJSON["hostname"];
break;
case "port":
case "dns":
case "gamedig":
case "steam":
address = monitorJSON["hostname"];
if (monitorJSON["port"]) {
address += ":" + monitorJSON["port"];
}
break;
default:
address = monitorJSON["url"];
break;
}
// If heartbeatJSON is not null, we go into the normal alerting loop. // If heartbeatJSON is not null, we go into the normal alerting loop.
if (heartbeatJSON["status"] === DOWN) { if (heartbeatJSON["status"] === DOWN) {
let discorddowndata = { let discorddowndata = {
@ -60,7 +48,7 @@ class Discord extends NotificationProvider {
}, },
{ {
name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL", name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL",
value: monitorJSON["type"] === "push" ? "Heartbeat" : address, value: this.extractAdress(monitorJSON),
}, },
{ {
name: `Time (${heartbeatJSON["timezone"]})`, name: `Time (${heartbeatJSON["timezone"]})`,
@ -73,12 +61,14 @@ class Discord extends NotificationProvider {
], ],
}], }],
}; };
if (notification.discordChannelType === "createNewForumPost") {
discorddowndata.thread_name = notification.postName;
}
if (notification.discordPrefixMessage) { if (notification.discordPrefixMessage) {
discorddowndata.content = notification.discordPrefixMessage; discorddowndata.content = notification.discordPrefixMessage;
} }
await axios.post(notification.discordWebhookUrl, discorddowndata); await axios.post(webhookUrl.toString(), discorddowndata);
return okMsg; return okMsg;
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
@ -95,7 +85,7 @@ class Discord extends NotificationProvider {
}, },
{ {
name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL", name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL",
value: monitorJSON["type"] === "push" ? "Heartbeat" : address, value: this.extractAdress(monitorJSON),
}, },
{ {
name: `Time (${heartbeatJSON["timezone"]})`, name: `Time (${heartbeatJSON["timezone"]})`,
@ -109,11 +99,15 @@ class Discord extends NotificationProvider {
}], }],
}; };
if (notification.discordChannelType === "createNewForumPost") {
discordupdata.thread_name = notification.postName;
}
if (notification.discordPrefixMessage) { if (notification.discordPrefixMessage) {
discordupdata.content = notification.discordPrefixMessage; discordupdata.content = notification.discordPrefixMessage;
} }
await axios.post(notification.discordWebhookUrl, discordupdata); await axios.post(webhookUrl.toString(), discordupdata);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

View file

@ -9,8 +9,7 @@ class Feishu extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let feishuWebHookUrl = notification.feishuWebHookUrl;
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
@ -20,59 +19,67 @@ class Feishu extends NotificationProvider {
text: msg, text: msg,
}, },
}; };
await axios.post(feishuWebHookUrl, testdata); await axios.post(notification.feishuWebHookUrl, testdata);
return okMsg; return okMsg;
} }
if (heartbeatJSON["status"] === DOWN) { if (heartbeatJSON["status"] === DOWN) {
let downdata = { let downdata = {
msg_type: "post", msg_type: "interactive",
content: { card: {
post: { config: {
zh_cn: { update_multi: false,
title: "UptimeKuma Alert: [Down] " + monitorJSON["name"], wide_screen_mode: true,
content: [
[
{
tag: "text",
text:
"[Down] " +
heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
},
],
],
},
}, },
}, header: {
title: {
tag: "plain_text",
content: "UptimeKuma Alert: [Down] " + monitorJSON["name"],
},
template: "red",
},
elements: [
{
tag: "div",
text: {
tag: "lark_md",
content: getContent(heartbeatJSON),
},
}
]
}
}; };
await axios.post(feishuWebHookUrl, downdata); await axios.post(notification.feishuWebHookUrl, downdata);
return okMsg; return okMsg;
} }
if (heartbeatJSON["status"] === UP) { if (heartbeatJSON["status"] === UP) {
let updata = { let updata = {
msg_type: "post", msg_type: "interactive",
content: { card: {
post: { config: {
zh_cn: { update_multi: false,
title: "UptimeKuma Alert: [Up] " + monitorJSON["name"], wide_screen_mode: true,
content: [
[
{
tag: "text",
text:
"[Up] " +
heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
},
],
],
},
}, },
}, header: {
title: {
tag: "plain_text",
content: "UptimeKuma Alert: [UP] " + monitorJSON["name"],
},
template: "green",
},
elements: [
{
tag: "div",
text: {
tag: "lark_md",
content: getContent(heartbeatJSON),
},
},
]
}
}; };
await axios.post(feishuWebHookUrl, updata); await axios.post(notification.feishuWebHookUrl, updata);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {
@ -81,4 +88,17 @@ class Feishu extends NotificationProvider {
} }
} }
/**
* Get content
* @param {?object} heartbeatJSON Heartbeat details (For Up/Down only)
* @returns {string} Return Successful Message
*/
function getContent(heartbeatJSON) {
return [
"**Message**: " + heartbeatJSON["msg"],
"**Ping**: " + (heartbeatJSON["ping"] == null ? "N/A" : heartbeatJSON["ping"] + " ms"),
`**Time (${heartbeatJSON["timezone"]})**: ${heartbeatJSON["localDateTime"]}`
].join("\n");
}
module.exports = Feishu; module.exports = Feishu;

View file

@ -62,6 +62,15 @@ class FlashDuty extends NotificationProvider {
* @returns {string} Success message * @returns {string} Success message
*/ */
async postNotification(notification, title, body, monitorInfo, eventStatus) { async postNotification(notification, title, body, monitorInfo, eventStatus) {
let labels = {
resource: this.genMonitorUrl(monitorInfo),
check: monitorInfo.name,
};
if (monitorInfo.tags && monitorInfo.tags.length > 0) {
for (let tag of monitorInfo.tags) {
labels[tag.name] = tag.value;
}
}
const options = { const options = {
method: "POST", method: "POST",
url: "https://api.flashcat.cloud/event/push/alert/standard?integration_key=" + notification.flashdutyIntegrationKey, url: "https://api.flashcat.cloud/event/push/alert/standard?integration_key=" + notification.flashdutyIntegrationKey,
@ -71,9 +80,7 @@ class FlashDuty extends NotificationProvider {
title, title,
event_status: eventStatus || "Info", event_status: eventStatus || "Info",
alert_key: String(monitorInfo.id) || Math.random().toString(36).substring(7), alert_key: String(monitorInfo.id) || Math.random().toString(36).substring(7),
labels: monitorInfo?.tags?.reduce((acc, item) => ({ ...acc, labels,
[item.name]: item.value
}), { resource: this.genMonitorUrl(monitorInfo) }),
} }
}; };

View file

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class FreeMobile extends NotificationProvider { class FreeMobile extends NotificationProvider {
name = "FreeMobile"; name = "FreeMobile";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://smsapi.free-mobile.fr/sendmsg?msg=${encodeURIComponent(msg.replace("🔴", "⛔️"))}`, { await axios.post(`https://smsapi.free-mobile.fr/sendmsg?msg=${encodeURIComponent(msg.replace("🔴", "⛔️"))}`, {
"user": notification.freemobileUser, "user": notification.freemobileUser,

View file

@ -3,21 +3,20 @@ const axios = require("axios");
const { UP } = require("../../src/util"); const { UP } = require("../../src/util");
class GoAlert extends NotificationProvider { class GoAlert extends NotificationProvider {
name = "GoAlert"; name = "GoAlert";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let closeAction = "close";
let data = { let data = {
summary: msg, summary: msg,
}; };
if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { if (heartbeatJSON != null && heartbeatJSON["status"] === UP) {
data["action"] = closeAction; data["action"] = "close";
} }
let headers = { let headers = {
"Content-Type": "multipart/form-data", "Content-Type": "multipart/form-data",
@ -27,7 +26,6 @@ class GoAlert extends NotificationProvider {
}; };
await axios.post(`${notification.goAlertBaseURL}/api/v2/generic/incoming?token=${notification.goAlertToken}`, data, config); await axios.post(`${notification.goAlertBaseURL}/api/v2/generic/incoming?token=${notification.goAlertToken}`, data, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
let msg = (error.response.data) ? error.response.data : "Error without response"; let msg = (error.response.data) ? error.response.data : "Error without response";
throw new Error(msg); throw new Error(msg);

View file

@ -1,41 +1,86 @@
const NotificationProvider = require("./notification-provider"); const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
const { getMonitorRelativeURL } = require("../../src/util"); const { getMonitorRelativeURL, DOWN, UP } = require("../../src/util");
const { DOWN, UP } = require("../../src/util");
const { Settings } = require("../settings"); const { Settings } = require("../settings");
class GoogleChat extends NotificationProvider { class GoogleChat extends NotificationProvider {
name = "GoogleChat"; name = "GoogleChat";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
// Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic // Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic
let textMsg = ""; let chatHeader = {
if (heartbeatJSON && heartbeatJSON.status === UP) { title: "Uptime Kuma Alert",
textMsg = "✅ Application is back online\n"; };
} else if (heartbeatJSON && heartbeatJSON.status === DOWN) {
textMsg = "🔴 Application went down\n"; if (monitorJSON && heartbeatJSON) {
chatHeader["title"] =
heartbeatJSON["status"] === UP
? `${monitorJSON["name"]} is back online`
: `🔴 ${monitorJSON["name"]} went down`;
} }
if (monitorJSON && monitorJSON.name) { // always show msg
textMsg += `*${monitorJSON.name}*\n`; let sectionWidgets = [
{
textParagraph: {
text: `<b>Message:</b>\n${msg}`,
},
},
];
// add time if available
if (heartbeatJSON) {
sectionWidgets.push({
textParagraph: {
text: `<b>Time (${heartbeatJSON["timezone"]}):</b>\n${heartbeatJSON["localDateTime"]}`,
},
});
} }
textMsg += `${msg}`; // add button for monitor link if available
const baseURL = await Settings.get("primaryBaseURL"); const baseURL = await Settings.get("primaryBaseURL");
if (baseURL && monitorJSON) { if (baseURL) {
textMsg += `\n${baseURL + getMonitorRelativeURL(monitorJSON.id)}`; const urlPath = monitorJSON ? getMonitorRelativeURL(monitorJSON.id) : "/";
sectionWidgets.push({
buttonList: {
buttons: [
{
text: "Visit Uptime Kuma",
onClick: {
openLink: {
url: baseURL + urlPath,
},
},
},
],
},
});
} }
const data = { let chatSections = [
"text": textMsg, {
widgets: sectionWidgets,
},
];
// construct json data
let data = {
cardsV2: [
{
card: {
header: chatHeader,
sections: chatSections,
},
},
],
}; };
await axios.post(notification.googleChatWebhookURL, data); await axios.post(notification.googleChatWebhookURL, data);

View file

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Gorush extends NotificationProvider { class Gorush extends NotificationProvider {
name = "gorush"; name = "gorush";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let platformMapping = { let platformMapping = {
"ios": 1, "ios": 1,

View file

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Gotify extends NotificationProvider { class Gotify extends NotificationProvider {
name = "gotify"; name = "gotify";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (notification.gotifyserverurl && notification.gotifyserverurl.endsWith("/")) { if (notification.gotifyserverurl && notification.gotifyserverurl.endsWith("/")) {
notification.gotifyserverurl = notification.gotifyserverurl.slice(0, -1); notification.gotifyserverurl = notification.gotifyserverurl.slice(0, -1);

View file

@ -3,19 +3,18 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class GrafanaOncall extends NotificationProvider { class GrafanaOncall extends NotificationProvider {
name = "GrafanaOncall"; name = "GrafanaOncall";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
if (!notification.GrafanaOncallURL) { if (!notification.GrafanaOncallURL) {
throw new Error("GrafanaOncallURL cannot be empty"); throw new Error("GrafanaOncallURL cannot be empty");
} }
let okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON === null) { if (heartbeatJSON === null) {
let grafanaupdata = { let grafanaupdata = {
@ -23,10 +22,7 @@ class GrafanaOncall extends NotificationProvider {
message: msg, message: msg,
state: "alerting", state: "alerting",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanaupdata);
notification.GrafanaOncallURL,
grafanaupdata
);
return okMsg; return okMsg;
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let grafanadowndata = { let grafanadowndata = {
@ -34,10 +30,7 @@ class GrafanaOncall extends NotificationProvider {
message: heartbeatJSON["msg"], message: heartbeatJSON["msg"],
state: "alerting", state: "alerting",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanadowndata);
notification.GrafanaOncallURL,
grafanadowndata
);
return okMsg; return okMsg;
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let grafanaupdata = { let grafanaupdata = {
@ -45,10 +38,7 @@ class GrafanaOncall extends NotificationProvider {
message: heartbeatJSON["msg"], message: heartbeatJSON["msg"],
state: "ok", state: "ok",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanaupdata);
notification.GrafanaOncallURL,
grafanaupdata
);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

View file

@ -0,0 +1,33 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class GtxMessaging extends NotificationProvider {
name = "gtxmessaging";
/**
* @inheritDoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
// The UP/DOWN symbols will be replaced with `???` by gtx-messaging
const text = msg.replaceAll("🔴 ", "").replaceAll("✅ ", "");
try {
const data = new URLSearchParams();
data.append("from", notification.gtxMessagingFrom.trim());
data.append("to", notification.gtxMessagingTo.trim());
data.append("text", text);
const url = `https://rest.gtx-messaging.net/smsc/sendsms/${notification.gtxMessagingApiKey}/json`;
await axios.post(url, data);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = GtxMessaging;

View file

@ -0,0 +1,52 @@
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
const { setting } = require("../util-server");
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class HeiiOnCall extends NotificationProvider {
name = "HeiiOnCall";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const payload = heartbeatJSON || {};
const baseURL = await setting("primaryBaseURL");
if (baseURL && monitorJSON) {
payload["url"] = baseURL + getMonitorRelativeURL(monitorJSON.id);
}
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + notification.heiiOnCallApiKey,
},
};
const heiiUrl = `https://heiioncall.com/triggers/${notification.heiiOnCallTriggerId}/`;
// docs https://heiioncall.com/docs#manual-triggers
try {
if (!heartbeatJSON) {
// Testing or general notification like certificate expiry
payload["msg"] = msg;
await axios.post(heiiUrl + "alert", payload, config);
return okMsg;
}
if (heartbeatJSON.status === DOWN) {
await axios.post(heiiUrl + "alert", payload, config);
return okMsg;
}
if (heartbeatJSON.status === UP) {
await axios.post(heiiUrl + "resolve", payload, config);
return okMsg;
}
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = HeiiOnCall;

View file

@ -9,7 +9,9 @@ class HomeAssistant extends NotificationProvider {
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, message, monitor = null, heartbeat = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const notificationService = notification?.notificationService || defaultNotificationService; const notificationService = notification?.notificationService || defaultNotificationService;
try { try {
@ -17,10 +19,12 @@ class HomeAssistant extends NotificationProvider {
`${notification.homeAssistantUrl.trim().replace(/\/*$/, "")}/api/services/notify/${notificationService}`, `${notification.homeAssistantUrl.trim().replace(/\/*$/, "")}/api/services/notify/${notificationService}`,
{ {
title: "Uptime Kuma", title: "Uptime Kuma",
message, message: msg,
...(notificationService !== "persistent_notification" && { data: { ...(notificationService !== "persistent_notification" && { data: {
name: monitor?.name, name: monitorJSON?.name,
status: heartbeat?.status, status: heartbeatJSON?.status,
channel: "Uptime Kuma",
icon_url: "https://github.com/louislam/uptime-kuma/blob/master/public/icon.png?raw=true",
} }), } }),
}, },
{ {
@ -31,7 +35,7 @@ class HomeAssistant extends NotificationProvider {
} }
); );
return "Sent Successfully."; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);
} }

View file

@ -0,0 +1,42 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class Keep extends NotificationProvider {
name = "Keep";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
let data = {
heartbeat: heartbeatJSON,
monitor: monitorJSON,
msg,
};
let config = {
headers: {
"x-api-key": notification.webhookAPIKey,
"content-type": "application/json",
},
};
let url = notification.webhookURL;
if (url.endsWith("/")) {
url = url.slice(0, -1);
}
let webhookURL = url + "/alerts/event/uptimekuma";
await axios.post(webhookURL, data, config);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Keep;

View file

@ -2,15 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Kook extends NotificationProvider { class Kook extends NotificationProvider {
name = "Kook"; name = "Kook";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let url = "https://www.kookapp.cn/api/v3/message/create"; const url = "https://www.kookapp.cn/api/v3/message/create";
let data = { let data = {
target_id: notification.kookGuildID, target_id: notification.kookGuildID,
content: msg, content: msg,

View file

@ -3,16 +3,16 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Line extends NotificationProvider { class Line extends NotificationProvider {
name = "line"; name = "line";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api.line.me/v2/bot/message/push";
try { try {
let lineAPIUrl = "https://api.line.me/v2/bot/message/push";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -29,7 +29,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, testMessage, config); await axios.post(url, testMessage, config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downMessage = { let downMessage = {
"to": notification.lineUserID, "to": notification.lineUserID,
@ -43,7 +43,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, downMessage, config); await axios.post(url, downMessage, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upMessage = { let upMessage = {
"to": notification.lineUserID, "to": notification.lineUserID,
@ -57,7 +57,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, upMessage, config); await axios.post(url, upMessage, config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

View file

@ -4,16 +4,16 @@ const qs = require("qs");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class LineNotify extends NotificationProvider { class LineNotify extends NotificationProvider {
name = "LineNotify"; name = "LineNotify";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://notify-api.line.me/api/notify";
try { try {
let lineAPIUrl = "https://notify-api.line.me/api/notify";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
@ -24,7 +24,7 @@ class LineNotify extends NotificationProvider {
let testMessage = { let testMessage = {
"message": msg, "message": msg,
}; };
await axios.post(lineAPIUrl, qs.stringify(testMessage), config); await axios.post(url, qs.stringify(testMessage), config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downMessage = { let downMessage = {
"message": "\n[🔴 Down]\n" + "message": "\n[🔴 Down]\n" +
@ -32,7 +32,7 @@ class LineNotify extends NotificationProvider {
heartbeatJSON["msg"] + "\n" + heartbeatJSON["msg"] + "\n" +
`Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lineAPIUrl, qs.stringify(downMessage), config); await axios.post(url, qs.stringify(downMessage), config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upMessage = { let upMessage = {
"message": "\n[✅ Up]\n" + "message": "\n[✅ Up]\n" +
@ -40,7 +40,7 @@ class LineNotify extends NotificationProvider {
heartbeatJSON["msg"] + "\n" + heartbeatJSON["msg"] + "\n" +
`Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lineAPIUrl, qs.stringify(upMessage), config); await axios.post(url, qs.stringify(upMessage), config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

View file

@ -3,28 +3,23 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class LunaSea extends NotificationProvider { class LunaSea extends NotificationProvider {
name = "lunasea"; name = "lunasea";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let lunaseaurl = ""; const url = "https://notify.lunasea.app/v1";
if (notification.lunaseaTarget === "user") {
lunaseaurl = "https://notify.lunasea.app/v1/custom/user/" + notification.lunaseaUserID;
} else {
lunaseaurl = "https://notify.lunasea.app/v1/custom/device/" + notification.lunaseaDevice;
}
try { try {
const target = this.getTarget(notification);
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
let testdata = { let testdata = {
"title": "Uptime Kuma Alert", "title": "Uptime Kuma Alert",
"body": msg, "body": msg,
}; };
await axios.post(lunaseaurl, testdata); await axios.post(`${url}/custom/${target}`, testdata);
return okMsg; return okMsg;
} }
@ -35,7 +30,7 @@ class LunaSea extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lunaseaurl, downdata); await axios.post(`${url}/custom/${target}`, downdata);
return okMsg; return okMsg;
} }
@ -46,13 +41,25 @@ class LunaSea extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lunaseaurl, updata); await axios.post(`${url}/custom/${target}`, updata);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);
} }
}
/**
* Generates the lunasea target to send the notification to
* @param {BeanModel} notification Notification details
* @returns {string} The target to send the notification to
*/
getTarget(notification) {
if (notification.lunaseaTarget === "user") {
return "user/" + notification.lunaseaUserID;
}
return "device/" + notification.lunaseaDevice;
} }
} }

View file

@ -10,7 +10,7 @@ class Matrix extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const size = 20; const size = 20;
const randomString = encodeURIComponent( const randomString = encodeURIComponent(

View file

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Mattermost extends NotificationProvider { class Mattermost extends NotificationProvider {
name = "mattermost"; name = "mattermost";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
const mattermostUserName = notification.mattermostusername || "Uptime Kuma"; const mattermostUserName = notification.mattermostusername || "Uptime Kuma";
// If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing. // If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing.
@ -98,10 +98,7 @@ class Mattermost extends NotificationProvider {
}, },
], ],
}; };
await axios.post( await axios.post(notification.mattermostWebhookUrl, mattermostdata);
notification.mattermostWebhookUrl,
mattermostdata
);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

View file

@ -1,4 +1,3 @@
const { log } = require("../../src/util");
const NotificationProvider = require("./notification-provider"); const NotificationProvider = require("./notification-provider");
const { const {
relayInit, relayInit,
@ -12,16 +11,7 @@ const {
// polyfills for node versions // polyfills for node versions
const semver = require("semver"); const semver = require("semver");
const nodeVersion = process.version; const nodeVersion = process.version;
if (semver.lt(nodeVersion, "16.0.0")) { if (semver.lt(nodeVersion, "20.0.0")) {
log.warn("monitor", "Node <= 16 is unsupported for nostr, sorry :(");
} else if (semver.lt(nodeVersion, "18.0.0")) {
// polyfills for node 16
global.crypto = require("crypto");
global.WebSocket = require("isomorphic-ws");
if (typeof crypto !== "undefined" && !crypto.subtle && crypto.webcrypto) {
crypto.subtle = crypto.webcrypto.subtle;
}
} else if (semver.lt(nodeVersion, "20.0.0")) {
// polyfills for node 18 // polyfills for node 18
global.crypto = require("crypto"); global.crypto = require("crypto");
global.WebSocket = require("isomorphic-ws"); global.WebSocket = require("isomorphic-ws");
@ -107,7 +97,7 @@ class Nostr extends NotificationProvider {
/** /**
* Get public keys for recipients * Get public keys for recipients
* @param {string} recipients Newline delimited list of recipients * @param {string} recipients Newline delimited list of recipients
* @returns {nip19.DecodeResult[]} Public keys * @returns {Promise<nip19.DecodeResult[]>} Public keys
*/ */
async getPublicKeys(recipients) { async getPublicKeys(recipients) {
const recipientsList = recipients.split("\n"); const recipientsList = recipients.split("\n");

View file

@ -19,6 +19,36 @@ class NotificationProvider {
throw new Error("Have to override Notification.send(...)"); throw new Error("Have to override Notification.send(...)");
} }
/**
* Extracts the address from a monitor JSON object based on its type.
* @param {?object} monitorJSON Monitor details (For Up/Down only)
* @returns {string} The extracted address based on the monitor type.
*/
extractAdress(monitorJSON) {
if (!monitorJSON) {
return "";
}
switch (monitorJSON["type"]) {
case "push":
return "Heartbeat";
case "ping":
return monitorJSON["hostname"];
case "port":
case "dns":
case "gamedig":
case "steam":
if (monitorJSON["port"]) {
return monitorJSON["hostname"] + ":" + monitorJSON["port"];
}
return monitorJSON["hostname"];
default:
if (![ "https://", "http://", "" ].includes(monitorJSON["url"])) {
return monitorJSON["url"];
}
return "";
}
}
/** /**
* Throws an error * Throws an error
* @param {any} error The error to throw * @param {any} error The error to throw

View file

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Ntfy extends NotificationProvider { class Ntfy extends NotificationProvider {
name = "ntfy"; name = "ntfy";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let headers = {}; let headers = {};
if (notification.ntfyAuthenticationMethod === "usernamePassword") { if (notification.ntfyAuthenticationMethod === "usernamePassword") {
@ -31,7 +31,7 @@ class Ntfy extends NotificationProvider {
"priority": notification.ntfyPriority, "priority": notification.ntfyPriority,
"tags": [ "test_tube" ], "tags": [ "test_tube" ],
}; };
await axios.post(`${notification.ntfyserverurl}`, ntfyTestData, { headers: headers }); await axios.post(notification.ntfyserverurl, ntfyTestData, { headers: headers });
return okMsg; return okMsg;
} }
let tags = []; let tags = [];
@ -54,20 +54,23 @@ class Ntfy extends NotificationProvider {
"priority": priority, "priority": priority,
"title": monitorJSON.name + " " + status + " [Uptime-Kuma]", "title": monitorJSON.name + " " + status + " [Uptime-Kuma]",
"tags": tags, "tags": tags,
"actions": [ };
if (monitorJSON.url && monitorJSON.url !== "https://") {
data.actions = [
{ {
"action": "view", "action": "view",
"label": "Open " + monitorJSON.name, "label": "Open " + monitorJSON.name,
"url": monitorJSON.url, "url": monitorJSON.url,
} },
] ];
}; }
if (notification.ntfyIcon) { if (notification.ntfyIcon) {
data.icon = notification.ntfyIcon; data.icon = notification.ntfyIcon;
} }
await axios.post(`${notification.ntfyserverurl}`, data, { headers: headers }); await axios.post(notification.ntfyserverurl, data, { headers: headers });
return okMsg; return okMsg;

View file

@ -2,14 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Octopush extends NotificationProvider { class Octopush extends NotificationProvider {
name = "octopush"; name = "octopush";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const urlV2 = "https://api.octopush.com/v1/public/sms-campaign/send";
const urlV1 = "https://www.octopush-dm.com/api/sms/json";
try { try {
// Default - V2 // Default - V2
@ -33,7 +34,7 @@ class Octopush extends NotificationProvider {
"purpose": "alert", "purpose": "alert",
"sender": notification.octopushSenderName "sender": notification.octopushSenderName
}; };
await axios.post("https://api.octopush.com/v1/public/sms-campaign/send", data, config); await axios.post(urlV2, data, config);
} else if (notification.octopushVersion === "1") { } else if (notification.octopushVersion === "1") {
let data = { let data = {
"user_login": notification.octopushDMLogin, "user_login": notification.octopushDMLogin,
@ -55,7 +56,7 @@ class Octopush extends NotificationProvider {
// V1 API returns 200 even on error so we must check // V1 API returns 200 even on error so we must check
// response data // response data
let response = await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config); let response = await axios.post(urlV1, {}, config);
if ("error_code" in response.data) { if ("error_code" in response.data) {
if (response.data.error_code !== "000") { if (response.data.error_code !== "000") {
this.throwGeneralAxiosError(`Octopush error ${JSON.stringify(response.data)}`); this.throwGeneralAxiosError(`Octopush error ${JSON.stringify(response.data)}`);

View file

@ -2,23 +2,23 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class OneBot extends NotificationProvider { class OneBot extends NotificationProvider {
name = "OneBot"; name = "OneBot";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let httpAddr = notification.httpAddr; let url = notification.httpAddr;
if (!httpAddr.startsWith("http")) { if (!url.startsWith("http")) {
httpAddr = "http://" + httpAddr; url = "http://" + url;
} }
if (!httpAddr.endsWith("/")) { if (!url.endsWith("/")) {
httpAddr += "/"; url += "/";
} }
let onebotAPIUrl = httpAddr + "send_msg"; url += "send_msg";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -37,7 +37,7 @@ class OneBot extends NotificationProvider {
data["message_type"] = "private"; data["message_type"] = "private";
data["user_id"] = notification.recieverId; data["user_id"] = notification.recieverId;
} }
await axios.post(onebotAPIUrl, data, config); await axios.post(url, data, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

View file

@ -0,0 +1,47 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class Onesender extends NotificationProvider {
name = "Onesender";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
let data = {
heartbeat: heartbeatJSON,
monitor: monitorJSON,
msg,
to: notification.onesenderReceiver,
type: "text",
recipient_type: "individual",
text: {
body: msg
}
};
if (notification.onesenderTypeReceiver === "private") {
data.to = notification.onesenderReceiver + "@s.whatsapp.net";
} else {
data.recipient_type = "group";
data.to = notification.onesenderReceiver + "@g.us";
}
let config = {
headers: {
"Authorization": "Bearer " + notification.onesenderToken,
}
};
await axios.post(notification.onesenderURL, data, config);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Onesender;

View file

@ -4,10 +4,9 @@ const { UP, DOWN } = require("../../src/util");
const opsgenieAlertsUrlEU = "https://api.eu.opsgenie.com/v2/alerts"; const opsgenieAlertsUrlEU = "https://api.eu.opsgenie.com/v2/alerts";
const opsgenieAlertsUrlUS = "https://api.opsgenie.com/v2/alerts"; const opsgenieAlertsUrlUS = "https://api.opsgenie.com/v2/alerts";
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
class Opsgenie extends NotificationProvider { class Opsgenie extends NotificationProvider {
name = "Opsgenie"; name = "Opsgenie";
/** /**

View file

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class PromoSMS extends NotificationProvider { class PromoSMS extends NotificationProvider {
name = "promosms"; name = "promosms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://promosms.com/api/rest/v3_2/sms";
if (notification.promosmsAllowLongSMS === undefined) { if (notification.promosmsAllowLongSMS === undefined) {
notification.promosmsAllowLongSMS = false; notification.promosmsAllowLongSMS = false;
@ -36,7 +36,7 @@ class PromoSMS extends NotificationProvider {
"sender": notification.promosmsSenderName "sender": notification.promosmsSenderName
}; };
let resp = await axios.post("https://promosms.com/api/rest/v3_2/sms", data, config); let resp = await axios.post(url, data, config);
if (resp.data.response.status !== 0) { if (resp.data.response.status !== 0) {
let error = "Something gone wrong. Api returned " + resp.data.response.status + "."; let error = "Something gone wrong. Api returned " + resp.data.response.status + ".";

View file

@ -4,17 +4,16 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Pushbullet extends NotificationProvider { class Pushbullet extends NotificationProvider {
name = "pushbullet"; name = "pushbullet";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api.pushbullet.com/v2/pushes";
try { try {
let pushbulletUrl = "https://api.pushbullet.com/v2/pushes";
let config = { let config = {
headers: { headers: {
"Access-Token": notification.pushbulletAccessToken, "Access-Token": notification.pushbulletAccessToken,
@ -27,7 +26,7 @@ class Pushbullet extends NotificationProvider {
"title": "Uptime Kuma Alert", "title": "Uptime Kuma Alert",
"body": msg, "body": msg,
}; };
await axios.post(pushbulletUrl, data, config); await axios.post(url, data, config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downData = { let downData = {
"type": "note", "type": "note",
@ -36,7 +35,7 @@ class Pushbullet extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
}; };
await axios.post(pushbulletUrl, downData, config); await axios.post(url, downData, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upData = { let upData = {
"type": "note", "type": "note",
@ -45,7 +44,7 @@ class Pushbullet extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
}; };
await axios.post(pushbulletUrl, upData, config); await axios.post(url, upData, config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

View file

@ -3,17 +3,15 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class PushDeer extends NotificationProvider { class PushDeer extends NotificationProvider {
name = "PushDeer"; name = "PushDeer";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let endpoint = "/message/push"; const serverUrl = notification.pushdeerServer || "https://api2.pushdeer.com";
let serverUrl = notification.pushdeerServer || "https://api2.pushdeer.com"; const url = `${serverUrl.trim().replace(/\/*$/, "")}/message/push`;
let pushdeerlink = `${serverUrl.trim().replace(/\/*$/, "")}${endpoint}`;
let valid = msg != null && monitorJSON != null && heartbeatJSON != null; let valid = msg != null && monitorJSON != null && heartbeatJSON != null;
@ -34,7 +32,7 @@ class PushDeer extends NotificationProvider {
}; };
try { try {
let res = await axios.post(pushdeerlink, data); let res = await axios.post(url, data);
if ("error" in res.data) { if ("error" in res.data) {
let error = res.data.error; let error = res.data.error;

View file

@ -1,16 +1,18 @@
const { getMonitorRelativeURL } = require("../../src/util");
const { setting } = require("../util-server");
const NotificationProvider = require("./notification-provider"); const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Pushover extends NotificationProvider { class Pushover extends NotificationProvider {
name = "pushover"; name = "pushover";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let pushoverlink = "https://api.pushover.net/1/messages.json"; const url = "https://api.pushover.net/1/messages.json";
let data = { let data = {
"message": msg, "message": msg,
@ -24,6 +26,12 @@ class Pushover extends NotificationProvider {
"html": 1, "html": 1,
}; };
const baseURL = await setting("primaryBaseURL");
if (baseURL && monitorJSON) {
data["url"] = baseURL + getMonitorRelativeURL(monitorJSON.id);
data["url_title"] = "Link to Monitor";
}
if (notification.pushoverdevice) { if (notification.pushoverdevice) {
data.device = notification.pushoverdevice; data.device = notification.pushoverdevice;
} }
@ -33,11 +41,11 @@ class Pushover extends NotificationProvider {
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
await axios.post(pushoverlink, data); await axios.post(url, data);
return okMsg; return okMsg;
} else { } else {
data.message += `\n<b>Time (${heartbeatJSON["timezone"]})</b>:${heartbeatJSON["localDateTime"]}`; data.message += `\n<b>Time (${heartbeatJSON["timezone"]})</b>:${heartbeatJSON["localDateTime"]}`;
await axios.post(pushoverlink, data); await axios.post(url, data);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

View file

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Pushy extends NotificationProvider { class Pushy extends NotificationProvider {
name = "pushy"; name = "pushy";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://api.pushy.me/push?api_key=${notification.pushyAPIKey}`, { await axios.post(`https://api.pushy.me/push?api_key=${notification.pushyAPIKey}`, {

View file

@ -5,14 +5,14 @@ const { getMonitorRelativeURL, DOWN } = require("../../src/util");
const { Settings } = require("../settings"); const { Settings } = require("../settings");
class RocketChat extends NotificationProvider { class RocketChat extends NotificationProvider {
name = "rocket.chat"; name = "rocket.chat";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
let data = { let data = {

View file

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class ServerChan extends NotificationProvider { class ServerChan extends NotificationProvider {
name = "ServerChan"; name = "ServerChan";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://sctapi.ftqq.com/${notification.serverChanSendKey}.send`, { await axios.post(`https://sctapi.ftqq.com/${notification.serverChanSendKey}.send`, {
"title": this.checkStatus(heartbeatJSON, monitorJSON), "title": this.checkStatus(heartbeatJSON, monitorJSON),

View file

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class SerwerSMS extends NotificationProvider { class SerwerSMS extends NotificationProvider {
name = "serwersms"; name = "serwersms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api2.serwersms.pl/messages/send_sms";
try { try {
let config = { let config = {
@ -25,7 +25,7 @@ class SerwerSMS extends NotificationProvider {
"sender": notification.serwersmsSenderName, "sender": notification.serwersmsSenderName,
}; };
let resp = await axios.post("https://api2.serwersms.pl/messages/send_sms", data, config); let resp = await axios.post(url, data, config);
if (!resp.data.success) { if (!resp.data.success) {
if (resp.data.error) { if (resp.data.error) {

View file

@ -0,0 +1,57 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { DOWN, UP } = require("../../src/util");
class SevenIO extends NotificationProvider {
name = "SevenIO";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const data = {
to: notification.sevenioTo,
from: notification.sevenioSender || "Uptime Kuma",
text: msg,
};
const config = {
baseURL: "https://gateway.seven.io/api/",
headers: {
"Content-Type": "application/json",
"X-API-Key": notification.sevenioApiKey,
},
};
try {
// testing or certificate expiry notification
if (heartbeatJSON == null) {
await axios.post("sms", data, config);
return okMsg;
}
let address = this.extractAdress(monitorJSON);
if (address !== "") {
address = `(${address}) `;
}
// If heartbeatJSON is not null, we go into the normal alerting loop.
if (heartbeatJSON["status"] === DOWN) {
data.text = `Your service ${monitorJSON["name"]} ${address}went down at ${heartbeatJSON["localDateTime"]} ` +
`(${heartbeatJSON["timezone"]}). Error: ${heartbeatJSON["msg"]}`;
} else if (heartbeatJSON["status"] === UP) {
data.text = `Your service ${monitorJSON["name"]} ${address}went back up at ${heartbeatJSON["localDateTime"]} ` +
`(${heartbeatJSON["timezone"]}).`;
}
await axios.post("sms", data, config);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = SevenIO;

View file

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Signal extends NotificationProvider { class Signal extends NotificationProvider {
name = "signal"; name = "signal";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let data = { let data = {

Some files were not shown because too many files have changed in this diff Show more