Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Lemmmy committed Feb 20, 2024
0 parents commit 89e7d1f
Show file tree
Hide file tree
Showing 19 changed files with 370 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true

[*.{js,ts,jsx,tsx,css,json}]
indent_style = space
indent_size = 2
ij_javascript_spaces_within_imports = true
ij_typescript_spaces_within_imports = true
ij_typescript_use_double_quotes = true
17 changes: 17 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Deploy Worker
on:
push:
pull_request:
repository_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 60
needs: test
steps:
- uses: actions/checkout@v2
- name: Build & Deploy Worker
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CF_API_TOKEN }}
accountId: ${{ secrets.CF_ACCOUNT_ID }}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.env
.dev.vars
node_modules
.wrangler
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/grafana-discord-worker.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions .idea/highlightedFiles.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Drew Edwards

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.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Grafana → Discord webhook for Cloudflare Workers

[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/Lemmmy/grafana-discord-worker)

Simple worker to proxy Grafana webhook requests to Discord in a more concise format. Not extensively tested or
comprehensive.

![](https://lemmmy.s-ul.eu/IuqTEiGQ.png)

## Usage

1. Deploy this worker to Cloudflare Workers
2. Create a new webhook in Discord
3. Generate a random secret key (e.g. 24 characters) and create a new environment variable in the worker called
`TOKEN_1`. The value should be the secret key, followed by a comma (`,`), followed by the Discord webhook URL. For
example:
`TOKEN_1=secretkey,https://discord.com/api/webhooks/1234567890/ABCDEFGHIJKLM`
4. Create as many more tokens as you need, e.g. `TOKEN_2`, `TOKEN_3`, etc. Each one can route to a different Discord
webhook.
5. In Grafana, go to **Alerting****Contact points****Add contact point**
- **Integration**: Webhook
- **URL**: `https://grafana-discord-worker.yourusername.workers.dev/webhook`
- **HTTP method**: POST
- **Authorization Header - Scheme**: Bearer
- **Authorization Header - Credentials**: The secret key you created in step 3
6. Test the contact point, and save it when there are no problems.

The description of the alert will use the summary of the alert, or the description if it is not available. No other
information is currently shown.

## License

MIT
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "grafana-discord-worker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "npx wrangler dev",
"deploy-worker": "npx wrangler deploy",
"preinstall": "npx only-allow pnpm"
},
"keywords": [],
"author": "Lemmmy",
"license": "ISC",
"devDependencies": {
"@cloudflare/workers-types": "^4.20240208.0",
"typescript": "^5.3.3"
}
}
25 changes: 25 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

82 changes: 82 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Env, GrafanaWebhook } from "./types";

function findSecret(token: string | undefined | null, env: Env): string | null {
if (!token) return null;

// Iterate through all the keys in the environment until a match for the token is found, then return the URL.
for (let i = 0; i < Object.keys(env).length; i++) {
const key: keyof Env = `TOKEN_${i + 1}`;
if (env[key]) {
const [envToken, url] = env[key].split(",");
if (envToken === token) return url;
}
}

return null;
}

async function handleGrafanaWebhook(req: Request, forwardingUrl: string) {
const body = await req.json();
const { status, alerts } = body as GrafanaWebhook;

if (!status) {
return new Response("No status found", { status: 400 });
}

const alertsText = alerts
.map((alert) => {
const status = alert.status === "firing" ? "🔥" : "✅";
const title = alert?.labels?.alertname ?? "No title";
const url = alert.generatorURL;

const annotations = alert.annotations;
const text = annotations.description || annotations.summary || "No description provided";

const titleUrl = url ? `[${title}](${url})` : title;
const silenceUrl = alert.silenceURL ? ` [(silence)](${alert.silenceURL})` : "";

return `${status} **${titleUrl}**${silenceUrl}\n${text}`;
})
.join("\n\n");

const overallStatus = status === "firing" ? "🔥 **FIRING**" : "✅ **RESOLVED**";
let message = `${overallStatus}\n\n${alertsText}`;
if (message.length > 2044) {
message = message.substring(0, 2044) + "…";
}

const payload = {
content: message,
};

await fetch(forwardingUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});

return new Response("OK");
}

export default {
async fetch(req: Request, env: Env) {
const url = new URL(req.url);
const { pathname } = url;

if (pathname === "/webhook") {
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });

// Get the token from the `Authentication: Bearer <token>` header
const authHeader = req.headers.get("Authorization");
const token = authHeader?.split("Bearer ")[1];
const forwardingUrl = findSecret(token, env);
if (!forwardingUrl) return new Response("Unauthorized", { status: 401 });

return handleGrafanaWebhook(req, forwardingUrl);
} else {
return new Response("Not found", { status: 404 });
}
},
}
34 changes: 34 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export interface Env {
[key: `TOKEN_${string}`]: string;
}

type Status = "firing" | "resolved";

export interface GrafanaWebhook {
receiver : string;
status : Status;
orgId : number;
alerts : GrafanaAlert[];
groupLabels : Record<string , string>;
commonLabels : Record<string , string>;
commonAnnotations: Record<string , string>;
externalURL : string;
version : string;
groupKey : string;
truncatedAlerts : number;
}

interface GrafanaAlert {
status : Status;
labels : Record<string, string>;
annotations : Record<string, string>;
startsAt : string;
endsAt : string;
values : Record<string, number>;
generatorURL: string;
fingerprint : string;
silenceURL : string;
dashboardURL: string;
panelURL : string;
imageURL : string;
}
22 changes: 22 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"include": ["src"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"target": "es2021",
"lib": ["es2021"],
"module": "es2022",
"moduleResolution": "node",
"types": [
"@cloudflare/workers-types"
],
"resolveJsonModule": true,
"allowJs": true,
"checkJs": false,
"noEmit": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
19 changes: 19 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name = "grafana-discord-worker"
main = "src/index.ts"
compatibility_date = "2024-02-20"
env = { }

[triggers]
crons = [ ]

[vars]
# Create a variable for each Discord webhook URL you want to use, and the corresponding URL token, separated by a
# comma.
#
# For example:
# TOKEN_1 = dJalOiSOKpw7eBLA6G3mO6CU,https://discord.com/api/webhooks/1234567890/ABCDEFGHIJKLM
# TOKEN_2 = UDmyLMVjNdPFF0zKetxfmDV6,https://discord.com/api/webhooks/0987654321/XYZABCDEFGHIJKLM
# The webhook URLs will then be: https://your-worker.your-domain.workers.dev/webhook
# Authenticate with header: Bearer dJalOiSOKpw7eBLA6G3mO6CU
#
# Run `echo <VALUE> | wrangler secret put <NAME>` for each one

0 comments on commit 89e7d1f

Please sign in to comment.