Personal Telegram developer console for GitHub
test: add webhook security regression tests
davoodmehraban89 committed
Oct 2, 2026 at 16:36 UTC
979b6cc9c0f4030832c2b267a0c2f9e40f306499
1 file changed
+82
test/security.test.js
new
+82
@@ -0,0 +1,82 @@
1
+import test from "node:test";
2
+import assert from "node:assert/strict";
3
+import worker from "../src/index.js";
4
+
5
+function telegramRequest(secret, update) {
6
+ const headers = { "content-type": "application/json" };
7
+ if (secret !== undefined) headers["X-Telegram-Bot-Api-Secret-Token"] = secret;
8
+
9
+ return new Request("https://example.com/telegram/webhook", {
10
+ method: "POST",
11
+ headers,
12
+ body: JSON.stringify(update),
13
+ });
14
+}
15
+
16
+test("webhook fails closed when TELEGRAM_WEBHOOK_SECRET is missing", async () => {
17
+ const req = telegramRequest(undefined, {
18
+ message: { text: "/status", from: { id: 123 }, chat: { id: 123 } },
19
+ });
20
+
21
+ let calls = 0;
22
+ globalThis.fetch = async () => {
23
+ calls += 1;
24
+ return new Response(JSON.stringify({ ok: true }), {
25
+ status: 200,
26
+ headers: { "content-type": "application/json" },
27
+ });
28
+ };
29
+
30
+ const res = await worker.fetch(req, {
31
+ OWNER_TELEGRAM_ID: "123",
32
+ TELEGRAM_BOT_TOKEN: "token",
33
+ });
34
+
35
+ assert.equal(res.status, 503);
36
+ assert.equal(calls, 0);
37
+});
38
+
39
+test("webhook rejects a wrong Telegram secret", async () => {
40
+ const req = telegramRequest("wrong", {
41
+ message: { text: "/status", from: { id: 123 }, chat: { id: 123 } },
42
+ });
43
+
44
+ let calls = 0;
45
+ globalThis.fetch = async () => {
46
+ calls += 1;
47
+ throw new Error("should not call network");
48
+ };
49
+
50
+ const res = await worker.fetch(req, {
51
+ TELEGRAM_WEBHOOK_SECRET: "right",
52
+ OWNER_TELEGRAM_ID: "123",
53
+ TELEGRAM_BOT_TOKEN: "token",
54
+ });
55
+
56
+ assert.equal(res.status, 403);
57
+ assert.equal(calls, 0);
58
+});
59
+
60
+test("unauthorized Telegram users receive no bot response", async () => {
61
+ const req = telegramRequest("right", {
62
+ message: { text: "/status", from: { id: 999 }, chat: { id: 999 } },
63
+ });
64
+
65
+ let calls = 0;
66
+ globalThis.fetch = async () => {
67
+ calls += 1;
68
+ return new Response(JSON.stringify({ ok: true }), {
69
+ status: 200,
70
+ headers: { "content-type": "application/json" },
71
+ });
72
+ };
73
+
74
+ const res = await worker.fetch(req, {
75
+ TELEGRAM_WEBHOOK_SECRET: "right",
76
+ OWNER_TELEGRAM_ID: "123",
77
+ TELEGRAM_BOT_TOKEN: "token",
78
+ });
79
+
80
+ assert.equal(res.status, 200);
81
+ assert.equal(calls, 0);
82
+});