Personal Telegram developer console for GitHub
feat: add temporary Telegram webhook self-registration
Adds a tested temporary endpoint that registers the Telegram webhook to the current Worker origin without exposing the bot token in browser history.
davoodmehraban89 committed
Oct 2, 2026 at 18:36 UTC
0fb03c97c882b0b3a913c65deb94092d50c0efdf
2 files changed
+61
src/index.js
+30
@@ -115,6 +115,27 @@ async function handleCommand(env, message) {
115
await sendMessage(env, chatId, "فرمان شناخته نشد. /start را بزن.");
116
}
117
118
+async function setupTelegramWebhook(request, env) {
119
+ if (!env.TELEGRAM_BOT_TOKEN || !env.TELEGRAM_WEBHOOK_SECRET) {
120
+ return text("Telegram secrets not configured", 503);
121
+ }
122
+
123
+ const url = new URL(request.url);
124
+ const webhookUrl = `${url.origin}/telegram/webhook`;
125
+
126
+ const result = await telegramApi(env, "setWebhook", {
127
+ url: webhookUrl,
128
+ secret_token: env.TELEGRAM_WEBHOOK_SECRET,
129
+ allowed_updates: ["message"],
130
+ });
131
+
132
+ return json({
133
+ ok: true,
134
+ webhook: webhookUrl,
135
+ telegram_ok: Boolean(result?.ok),
136
+ });
137
+}
138
+
139
async function handleTelegramWebhook(request, env) {
140
const expected = env.TELEGRAM_WEBHOOK_SECRET;
141
if (!expected) return text("Webhook secret not configured", 503);
@@ -142,6 +163,15 @@ export default {
163
});
164
}
165
166
+ if (request.method === "GET" && url.pathname === "/telegram/setup") {
167
+ try {
168
+ return await setupTelegramWebhook(request, env);
169
+ } catch (error) {
170
+ console.error(error);
171
+ return text("Telegram webhook setup failed", 500);
172
+ }
173
+ }
174
+
175
if (request.method === "POST" && url.pathname === "/telegram/webhook") {
176
try {
177
return await handleTelegramWebhook(request, env);
test/security.test.js
+31
@@ -80,3 +80,34 @@ test("unauthorized Telegram users receive no bot response", async () => {
80
assert.equal(res.status, 200);
81
assert.equal(calls, 0);
82
});
83
+
84
+test("temporary setup endpoint registers Telegram webhook to this worker", async () => {
85
+ const req = new Request("https://nexa-dev-bot.example.workers.dev/telegram/setup", {
86
+ method: "GET",
87
+ });
88
+
89
+ let captured;
90
+ globalThis.fetch = async (url, init) => {
91
+ captured = {
92
+ url: String(url),
93
+ body: JSON.parse(init.body),
94
+ };
95
+ return new Response(JSON.stringify({ ok: true, result: true }), {
96
+ status: 200,
97
+ headers: { "content-type": "application/json" },
98
+ });
99
+ };
100
+
101
+ const res = await worker.fetch(req, {
102
+ TELEGRAM_WEBHOOK_SECRET: "secret",
103
+ TELEGRAM_BOT_TOKEN: "token",
104
+ });
105
+
106
+ assert.equal(res.status, 200);
107
+ assert.equal(captured.url, "https://api.telegram.org/bottoken/setWebhook");
108
+ assert.deepEqual(captured.body, {
109
+ url: "https://nexa-dev-bot.example.workers.dev/telegram/webhook",
110
+ secret_token: "secret",
111
+ allowed_updates: ["message"],
112
+ });
113
+});