Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 3.3.1 — 2026-11-21

### Fixed
- The optional Cloudflare Worker CORS proxy now rejects requests from origins not listed in `ALLOWED_ORIGIN` and requests without an `Origin` header (403) instead of proxying them, so a deployed worker cannot be used as an open Telegram proxy. `ALLOWED_ORIGIN="*"` remains an explicit opt-in.
- Added unit tests for origin checks, preflight, path validation and proxying.

## 3.3.0 — 2026-11-21

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ If a token leaks, revoke it with [@BotFather](https://t.me/BotFather) → `/revo
Some networks, countries or browser extensions block `api.telegram.org`. In that case deploy the bundled [Cloudflare Worker](proxy/cloudflare-worker.js) (the free plan is enough):

1. Cloudflare dashboard → **Workers & Pages** → **Create** → **Worker** → paste `proxy/cloudflare-worker.js` → **Deploy**.
2. Optional: set the `ALLOWED_ORIGIN` variable to your site origin (default `https://f1devbin.github.io`).
2. Set the `ALLOWED_ORIGIN` variable to your site origin (default `https://f1devbin.github.io`; comma-separated for several). Requests from other origins, and requests without an `Origin` header, are rejected with 403. Use `*` only for a deliberately public proxy.
3. In Telegram Bot Manager open **Advanced: API server** and enter the worker URL.

A [local Bot API server](https://github.com/tdlib/telegram-bot-api) (`http://localhost:8081`) works the same way.
Expand Down
2 changes: 1 addition & 1 deletion README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

## Если api.telegram.org заблокирован

Разверните [Cloudflare Worker](proxy/cloudflare-worker.js) из репозитория (бесплатного тарифа достаточно) и укажите его URL в разделе «Дополнительно: сервер API». Подробности — в [README на английском](README.md#cors-proxy).
Разверните [Cloudflare Worker](proxy/cloudflare-worker.js) из репозитория (бесплатного тарифа достаточно) и укажите его URL в разделе «Дополнительно: сервер API». Воркер принимает только браузерные запросы с `Origin` из `ALLOWED_ORIGIN`; остальные получают 403. `ALLOWED_ORIGIN="*"` — явный выбор публичного прокси. Подробности — в [README на английском](README.md#cors-proxy).

## Запуск у себя

Expand Down
1 change: 1 addition & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- The bot token is used only in the browser to call the Bot API server (`https://api.telegram.org` by default, or the server set in “Advanced: API server”).
- The token is kept in `sessionStorage` (current tab) or, if “Remember on this device” is checked, in `localStorage`. “Disconnect” removes it.
- A strict Content Security Policy allows scripts only from the site itself.
- The optional Cloudflare Worker rejects requests whose `Origin` is not listed in `ALLOWED_ORIGIN` (and requests without an `Origin`) with 403; `ALLOWED_ORIGIN="*"` is an explicit opt-in to a public proxy.

## Reporting a vulnerability

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "telegram-bot-manager",
"version": "3.3.0",
"version": "3.3.1",
"private": true,
"description": "Free online Telegram Bot Manager: set, check and delete webhooks, edit commands, profile, menu button and admin rights right in your browser.",
"type": "module",
Expand Down
40 changes: 34 additions & 6 deletions proxy/cloudflare-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Use it when api.telegram.org is blocked in your network or does not answer from the browser.
//
// Deploy: Cloudflare dashboard → Workers & Pages → Create → Worker → paste this file → Deploy.
// Optionally set the ALLOWED_ORIGIN variable (default: the official GitHub Pages site).
// Set the ALLOWED_ORIGIN variable to your site origin (default: the official GitHub Pages site;
// comma-separated for several origins). Requests from other origins, and requests without an
// Origin header, are rejected with 403. Use ALLOWED_ORIGIN="*" only for a deliberately public proxy.
// Then put the worker URL (https://<name>.<account>.workers.dev) into
// "Advanced: API server" in Telegram Bot Manager.
//
Expand All @@ -13,6 +15,13 @@ const TELEGRAM = 'https://api.telegram.org';
const DEFAULT_ORIGIN = 'https://f1devbin.github.io';
const PATH_RE = /^\/(file\/)?bot\d+:[A-Za-z0-9_-]+\/[^?#]*$/;

function allowedOrigins(env) {
return (env.ALLOWED_ORIGIN || DEFAULT_ORIGIN)
.split(',')
.map((value) => value.trim().replace(/\/+$/, ''))
.filter(Boolean);
}

function corsHeaders(origin) {
return {
'Access-Control-Allow-Origin': origin,
Expand All @@ -23,11 +32,20 @@ function corsHeaders(origin) {
};
}

function forbidden() {
return new Response('Forbidden origin', {
status: 403,
headers: { 'Content-Type': 'text/plain; charset=utf-8', Vary: 'Origin' },
});
}

export default {
async fetch(request, env) {
const allowed = (env.ALLOWED_ORIGIN || DEFAULT_ORIGIN).split(',').map((s) => s.trim());
async fetch(request, env = {}) {
const allowed = allowedOrigins(env);
const wildcard = allowed.includes('*');
const origin = request.headers.get('Origin') || '';
const allowOrigin = allowed.includes('*') ? '*' : allowed.includes(origin) ? origin : allowed[0];
if (!wildcard && !allowed.includes(origin)) return forbidden();
const allowOrigin = wildcard ? '*' : origin;

if (request.method === 'OPTIONS') {
return new Response(null, { status: 204, headers: corsHeaders(allowOrigin) });
Expand All @@ -38,14 +56,24 @@ export default {
return new Response('Not found', { status: 404, headers: corsHeaders(allowOrigin) });
}

// Do not invent a Content-Type for GET requests; Telegram does not need one.
const upstreamHeaders = {};
if (request.method === 'POST') {
upstreamHeaders['Content-Type'] = request.headers.get('Content-Type') || 'application/x-www-form-urlencoded';
}

const upstream = await fetch(TELEGRAM + url.pathname + url.search, {
method: request.method,
headers: { 'Content-Type': request.headers.get('Content-Type') || 'application/x-www-form-urlencoded' },
headers: upstreamHeaders,
body: request.method === 'POST' ? request.body : undefined,
});

const headers = new Headers(upstream.headers);
for (const [key, value] of Object.entries(corsHeaders(allowOrigin))) headers.set(key, value);
const vary = headers.get('Vary');
for (const [key, value] of Object.entries(corsHeaders(allowOrigin))) {
if (key === 'Vary') headers.set(key, vary ? `${vary}, Origin` : 'Origin');
else headers.set(key, value);
}
return new Response(upstream.body, { status: upstream.status, headers });
},
};
98 changes: 98 additions & 0 deletions tests/proxy.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import worker from '../proxy/cloudflare-worker.js';

const ENV = { ALLOWED_ORIGIN: 'https://example.com' };

function request(path, { method = 'POST', origin = 'https://example.com', body = 'x=1' } = {}) {
const headers = {};
if (origin !== null) headers.Origin = origin;
if (method === 'POST') headers['Content-Type'] = 'application/x-www-form-urlencoded';
return new Request(`https://worker.example${path}`, {
method,
headers,
body: method === 'POST' ? body : undefined,
});
}

function mockUpstream(t, calls) {
t.mock.method(globalThis, 'fetch', async (url, init) => {
calls.push({ url: String(url), init });
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
});
}

test('rejects requests without an Origin header', async (t) => {
const calls = [];
mockUpstream(t, calls);
const response = await worker.fetch(request('/bot123:abc/getMe', { origin: null }), ENV);
assert.equal(response.status, 403);
assert.equal(calls.length, 0);
});

test('rejects an origin that is not in ALLOWED_ORIGIN', async (t) => {
const calls = [];
mockUpstream(t, calls);
const response = await worker.fetch(request('/bot123:abc/getMe', { origin: 'https://evil.example' }), ENV);
assert.equal(response.status, 403);
assert.equal(calls.length, 0);
});

test('answers preflight for an allowed origin', async () => {
const response = await worker.fetch(request('/bot123:abc/getMe', { method: 'OPTIONS' }), ENV);
assert.equal(response.status, 204);
assert.equal(response.headers.get('Access-Control-Allow-Origin'), 'https://example.com');
assert.equal(response.headers.get('Access-Control-Allow-Methods'), 'GET, POST, OPTIONS');
assert.equal(response.headers.get('Vary'), 'Origin');
});

test('proxies an allowed POST and returns CORS headers', async (t) => {
const calls = [];
mockUpstream(t, calls);
const response = await worker.fetch(request('/bot123:abc/getMe'), ENV);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { ok: true });
assert.equal(response.headers.get('Access-Control-Allow-Origin'), 'https://example.com');
assert.equal(calls[0].url, 'https://api.telegram.org/bot123:abc/getMe');
assert.equal(calls[0].init.method, 'POST');
assert.equal(calls[0].init.headers['Content-Type'], 'application/x-www-form-urlencoded');
});

test('proxies allowed file downloads without a body', async (t) => {
const calls = [];
mockUpstream(t, calls);
const response = await worker.fetch(
request('/file/bot123:abc/photos/file.png', { method: 'GET' }),
ENV,
);
assert.equal(response.status, 200);
assert.equal(calls[0].url, 'https://api.telegram.org/file/bot123:abc/photos/file.png');
assert.equal(calls[0].init.body, undefined);
});

test('rejects unknown paths and methods with 404', async (t) => {
const calls = [];
mockUpstream(t, calls);
const badPath = await worker.fetch(request('/not-a-bot-path'), ENV);
assert.equal(badPath.status, 404);
const badMethod = await worker.fetch(request('/bot123:abc/getMe', { method: 'PUT' }), ENV);
assert.equal(badMethod.status, 404);
assert.equal(calls.length, 0);
});

test('ALLOWED_ORIGIN="*" is an explicit public-proxy opt-in', async () => {
const env = { ALLOWED_ORIGIN: '*' };
const response = await worker.fetch(request('/bot123:abc/getMe', { method: 'OPTIONS', origin: 'https://any.example' }), env);
assert.equal(response.status, 204);
assert.equal(response.headers.get('Access-Control-Allow-Origin'), '*');
});

test('accepts several origins and normalizes a trailing slash', async () => {
const env = { ALLOWED_ORIGIN: 'https://example.com/, https://other.example' };
const response = await worker.fetch(request('/bot123:abc/getMe', { method: 'OPTIONS', origin: 'https://other.example' }), env);
assert.equal(response.status, 204);
assert.equal(response.headers.get('Access-Control-Allow-Origin'), 'https://other.example');
});
Loading