|
| 1 | +// Router secret: Used to authenticate requests to the router to secure the hook |
| 2 | +const ROUTER_SECRET = process.env.ROUTER_SECRET; |
| 3 | + |
| 4 | +// Telegram bot's token for the alerts |
| 5 | +const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN!; |
| 6 | + |
| 7 | +// NEAR Telegram chat IDs |
| 8 | +const TELEGRAM_CHAT_NEAR = process.env.TELEGRAM_CHAT_NEAR; |
| 9 | + |
| 10 | +// Assert environment variables are set |
| 11 | +if (!ROUTER_SECRET || !TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_NEAR) { |
| 12 | + throw new Error( |
| 13 | + "Missing environment variables: ROUTER_SECRET, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_NEAR" |
| 14 | + ); |
| 15 | +} |
| 16 | + |
| 17 | +// Map by endpoint name prefix to Telegram chat ID |
| 18 | +const NAME_PREFIX_TO_TELEGRAM_CHAT_ID: Record< |
| 19 | + string, |
| 20 | + string | string[] | undefined |
| 21 | +> = { |
| 22 | + "Bridging - Near": TELEGRAM_CHAT_NEAR, |
| 23 | + "TEST - Intentional Failure": TELEGRAM_CHAT_NEAR, // For testing. Remove after. |
| 24 | +}; |
| 25 | + |
| 26 | +/** |
| 27 | + * Send a message to a Telegram chat |
| 28 | + * |
| 29 | + * @param token Telegram bot's token |
| 30 | + * @param chatId Telegram chat ID |
| 31 | + * @param text Message to send |
| 32 | + */ |
| 33 | +async function sendTelegramMessage( |
| 34 | + token: string, |
| 35 | + chatId: string, |
| 36 | + text: string |
| 37 | +) { |
| 38 | + const url = `https://api.telegram.org/bot${token}/sendMessage`; |
| 39 | + const body = { |
| 40 | + chat_id: chatId, |
| 41 | + text, |
| 42 | + parse_mode: "MarkdownV2", |
| 43 | + disable_web_page_preview: true, |
| 44 | + }; |
| 45 | + const res = await fetch(url, { |
| 46 | + method: "POST", |
| 47 | + headers: { "content-type": "application/json" }, |
| 48 | + body: JSON.stringify(body), |
| 49 | + }); |
| 50 | + if (!res.ok) throw new Error(await res.text()); |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Escape a string for MarkdownV2 |
| 55 | + * |
| 56 | + * @param s String to escape |
| 57 | + * @returns Escaped string |
| 58 | + */ |
| 59 | +function escapeMdV2(s: string) { |
| 60 | + // Minimal MarkdownV2 escaping for common symbols |
| 61 | + return s.replace(/([_*\[\]()~`>#+\-=|{}.!\\])/g, "\\$1"); |
| 62 | +} |
| 63 | + |
| 64 | +export default { |
| 65 | + /** |
| 66 | + * Handle the request to notify the Telegram chat |
| 67 | + * |
| 68 | + * @param request Request object |
| 69 | + * @returns Response object |
| 70 | + */ |
| 71 | + async fetch(request: Request) { |
| 72 | + try { |
| 73 | + const url = new URL(request.url); |
| 74 | + if (url.searchParams.get("key") !== ROUTER_SECRET) |
| 75 | + return new Response("unauthorized", { status: 401 }); |
| 76 | + |
| 77 | + const payload = await request.json().catch(() => ({} as any)); |
| 78 | + const textPayload = |
| 79 | + typeof payload === "string" ? payload : JSON.stringify(payload); |
| 80 | + |
| 81 | + // Try to extract a site name; fall back if not present |
| 82 | + const siteName = |
| 83 | + /"site(Name)?"\s*:\s*"(?<name>[^"]+)"/i.exec(textPayload)?.groups |
| 84 | + ?.name || |
| 85 | + /(^|>)\s*(?<name>[^<(]+)\s*\(/.exec(textPayload)?.groups?.name || |
| 86 | + "Unknown Site"; |
| 87 | + |
| 88 | + const match = Object.entries(NAME_PREFIX_TO_TELEGRAM_CHAT_ID).find( |
| 89 | + ([k]) => siteName.startsWith(k) |
| 90 | + )?.[1]; |
| 91 | + |
| 92 | + // If no matching route found, skip notification silently |
| 93 | + if (!match) { |
| 94 | + return new Response("no route configured - skipping", { status: 204 }); |
| 95 | + } |
| 96 | + |
| 97 | + const siteEsc = escapeMdV2(siteName); |
| 98 | + const rawEsc = escapeMdV2(textPayload.slice(0, 3500)); |
| 99 | + const msg = `🚨 *Upptime alert*\n• *Site:* ${siteEsc}\n• *Raw:* \`${rawEsc}\``; |
| 100 | + |
| 101 | + const targets = Array.isArray(match) ? match : [match]; |
| 102 | + await Promise.all( |
| 103 | + targets |
| 104 | + .filter(Boolean) |
| 105 | + .map((chatId) => |
| 106 | + sendTelegramMessage(TELEGRAM_BOT_TOKEN, chatId!, msg) |
| 107 | + ) |
| 108 | + ); |
| 109 | + |
| 110 | + return new Response("ok"); |
| 111 | + } catch (e: any) { |
| 112 | + return new Response(`error: ${e?.message || e}`, { status: 500 }); |
| 113 | + } |
| 114 | + }, |
| 115 | +}; |
0 commit comments