From b52c1a11a9f19509bdf7ce58ea61da6c4bab92f6 Mon Sep 17 00:00:00 2001 From: f1devbin <280303226+f1devbin@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:09:53 +0300 Subject: [PATCH] security: restrict Cloudflare Worker to allowed origins - reject requests from unknown origins and requests without Origin (403) - keep ALLOWED_ORIGIN=* as an explicit public-proxy opt-in - add unit tests for origin checks, preflight, paths and proxying - update docs and SECURITY.md; version 3.3.1 --- CHANGELOG.md | 6 +++ README.md | 2 +- README.ru.md | 2 +- SECURITY.md | 1 + package.json | 2 +- proxy/cloudflare-worker.js | 40 +++++++++++++--- tests/proxy.test.mjs | 98 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 142 insertions(+), 9 deletions(-) create mode 100644 tests/proxy.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b5427..97f638d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index eb52e65..b32dd9e 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/README.ru.md b/README.ru.md index 0f883c9..dd348ac 100644 --- a/README.ru.md +++ b/README.ru.md @@ -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). ## Запуск у себя diff --git a/SECURITY.md b/SECURITY.md index e3afa45..11d0d7b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 diff --git a/package.json b/package.json index 819edb1..0523704 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/proxy/cloudflare-worker.js b/proxy/cloudflare-worker.js index d9df665..3f31979 100644 --- a/proxy/cloudflare-worker.js +++ b/proxy/cloudflare-worker.js @@ -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://..workers.dev) into // "Advanced: API server" in Telegram Bot Manager. // @@ -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, @@ -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) }); @@ -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 }); }, }; diff --git a/tests/proxy.test.mjs b/tests/proxy.test.mjs new file mode 100644 index 0000000..c3036af --- /dev/null +++ b/tests/proxy.test.mjs @@ -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'); +});