feat(tgbot): access levels and /start account binding (#6518)

* feat(tgbot): gate the bot behind three user levels

Every Telegram account that found the bot could run /help, /status and
/usage, and tap any client button it could forge: nothing separated an
account no admin had bound from a customer.

Each update now resolves to stranger, client or admin, and commands are
allowlisted per level so a command added later stays admin-only until it
is listed. A stranger may run /start and /id only, and /start answers with
the ChatID an admin needs to bind it; a stranger's callbacks are answered
and dropped. Client detection reads the same tgId lookup as
clientOwnedByTgUser, so the level gate and the ownership check agree.

The bot also ignores everything outside private chats: authorization keys
on the sender while wizard state keys on the chat, and the two are the
same identity only in a private chat.

* feat(tgbot): bind Telegram accounts through /start deep links

Linking a customer meant the customer sending /id and an admin copying
the ChatID into the client by hand, which does not scale past a few
customers and is easy to get wrong.

The admin client card now offers an invite link, t.me/<bot>?start=<subId>,
and the first account to open it is bound through the existing
SetClientTelegramUserID. A subId already grants the subscription, so
binding gives the holder nothing the token did not. A subscription that
spans several clients binds all of them, and is refused if any part
belongs to another account; re-opening your own link is idempotent.
Unknown and already-claimed tokens share one reply, so the link cannot
be used to probe for valid subIds.

* fix(tgbot): harden invite claims after review

Review of the access-level and binding change found five problems:

- Concurrent claims of one link all read the client as unbound, all bound
  and all were told so, while only the last write held. Resolving and
  binding now share one lock, and a bind that fails part-way through a
  multi-client subscription undoes the bindings it already made.
- A subId has no minimum strength and the bot needs only its public
  username, so /start was an unthrottled guessing oracle. Non-admin claim
  attempts are capped at five per account per hour, the first refused one
  notifies the admins, and the Subscription ID field now says it doubles
  as the bot invite code.
- levelOf expanded every inbound's client JSON on every non-admin update.
  It now reads the indexed tg_id column of the clients table.
- A button tapped in a group chat was dropped unanswered and kept
  spinning, with nothing logged. It is answered now, and each ignored chat
  is logged once.
- The subId was pasted raw into the t.me link, so '#' or '&' truncated it
  and Telegram rejects anything outside A-Za-z0-9_-. The payload is now
  base64url, and a subId too long for the 64-character limit is refused.

* fix(tgbot): answer group chats again and make the claim race test bite

ignoredChat dropped every non-private chat because wizard state was
keyed by chat while authorization keyed on the sender. #6604 on main
re-keyed that state by (chat, user) so admins can drive the bot from a
group, so after the merge the drop only took the whole bot away from
those admins, report keyboards sent to a group included. The level gate
already keys on the sender, so group chats need no special case.

TestConcurrentClaimsBindOnlyOneAccount passed with inviteClaimMu
removed: the first claimant took the pool's idle connection and bound
before the rest had opened theirs, so no two ever raced. It now holds
the inbound write the binds need until every claimant has resolved,
and fails without the lock ("6 accounts told they bound").

TestCommandAllowed restated the commandsByLevel map; TestGateCommand
drives the same allowlist through gateCommand. TestIgnoredChat goes
with the code it pinned.

* docs(tgbot): document access levels and invite links

The command table still said /help and /status answer anyone. An
account no admin has linked now reaches only /start and /id, and a
customer is linked through the client card's Invite Link, whose token
is the Subscription ID. Updated in en, fa, ru and zh.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
pcxzs
2026-09-27 15:03:29 +03:30
committed by GitHub
parent 6f40a75909
commit 7aa5fc085f
25 changed files with 801 additions and 11 deletions
@@ -53,13 +53,22 @@ Additional commands:
| Command | Who | Action |
| ------------------ | ------ | ------------------------------------------------------------ |
| `/start`, `/help` | anyone | Greeting and the menu of inline buttons |
| `/status` | anyone | Confirm the bot is alive |
| `/start` | anyone | Greeting and the menu of inline buttons; an unlinked account gets only its Telegram ID |
| `/help` | both | The menu of inline buttons |
| `/status` | both | Confirm the bot is alive |
| `/id` | anyone | Show your Telegram numeric ID |
| `/usage <arg>` | both | Admins search clients; users look up their own usage |
| `/inbound <remark>`| admin | Show an inbound's details |
| `/restart` | admin | Restart Xray |
A user is a Telegram account linked to at least one client. Any other account
can run only `/start` and `/id`; the bot ignores its other commands and
button taps. To link a customer, tap **Invite Link** on the client's card in the bot and
send them the `t.me` link: the first account to open it is linked to every
client that shares that Subscription ID. The Subscription ID is the invite code,
so keep it long and random. Each account gets five claim attempts an hour, and
admins are notified when one runs out.
Admins also get inline-button flows for server usage, sorted traffic reports,
resetting traffic, DB backups, ban logs, listing inbounds/clients, online
clients, "depleting soon", and a full **add-client** wizard. Regular users get
@@ -53,13 +53,22 @@ icon: Send
| فرمان | چه کسی | عملکرد |
| ------------------ | ------ | ------------------------------------------------------------ |
| `/start`، `/help` | همه | پیام خوش‌آمدگویی و منوی دکمه‌های درون‌خطی |
| `/status` | همه | تأیید فعال بودن ربات |
| `/start` | همه | پیام خوش‌آمدگویی و منوی دکمه‌های درون‌خطی؛ حساب متصل‌نشده فقط شناسه‌ی Telegram خود را می‌گیرد |
| `/help` | هر دو | منوی دکمه‌های درون‌خطی |
| `/status` | هر دو | تأیید فعال بودن ربات |
| `/id` | همه | نمایش شناسه‌ی عددی Telegram شما |
| `/usage <arg>` | هر دو | ادمین‌ها کلاینت‌ها را جست‌وجو می‌کنند؛ کاربران مصرف خود را می‌بینند |
| `/inbound <remark>`| ادمین | نمایش جزئیات یک ورودی |
| `/restart` | ادمین | راه‌اندازی مجدد Xray |
کاربر یعنی حساب Telegramی که دست‌کم به یک کلاینت متصل است. هر حساب دیگری فقط
`/start` و `/id` را می‌تواند اجرا کند و ربات فرمان‌ها و دکمه‌های دیگر آن را نادیده
می‌گیرد. برای اتصال یک مشتری، در کارت کلاینت در ربات روی **لینک دعوت** بزنید و لینک `t.me`
را برایش بفرستید: نخستین حسابی که آن را باز کند به همه‌ی کلاینت‌هایی که آن شناسه
اشتراک را دارند متصل می‌شود. شناسه اشتراک همان کد دعوت است، پس آن را طولانی و
تصادفی نگه دارید. هر حساب در هر ساعت پنج بار می‌تواند تلاش کند و پس از آن به
ادمین‌ها اطلاع داده می‌شود.
ادمین‌ها همچنین جریان‌های دکمه‌ی درون‌خطی برای مصرف سرور، گزارش‌های ترافیک مرتب‌شده،
بازنشانی ترافیک، پشتیبان‌گیری از DB، گزارش‌های مسدودسازی، فهرست کردن ورودی‌ها/کلاینت‌ها،
کلاینت‌های آنلاین، «به‌زودی تمام‌شونده» و یک جادوگر کامل **افزودن کلاینت** را در اختیار دارند.
@@ -55,13 +55,23 @@ chat ID** (через запятую). Сохраните, затем напиш
| Команда | Кому | Действие |
| ------------------ | ------ | ------------------------------------------------------------ |
| `/start`, `/help` | всем | Приветствие и меню встроенных кнопок |
| `/status` | всем | Подтверждает, что бот работает |
| `/start` | всем | Приветствие и меню встроенных кнопок; непривязанный аккаунт получает только свой Telegram ID |
| `/help` | обоим | Меню встроенных кнопок |
| `/status` | обоим | Подтверждает, что бот работает |
| `/id` | всем | Показывает ваш числовой Telegram ID |
| `/usage <arg>` | обоим | Администраторы ищут клиентов; пользователи смотрят свой расход |
| `/inbound <remark>`| админ | Показывает сведения о входящем подключении |
| `/restart` | админ | Перезапускает Xray |
Пользователь — это аккаунт Telegram, привязанный хотя бы к одному клиенту. Любой
другой аккаунт может выполнять только `/start` и `/id`; остальные его команды и
нажатия кнопок бот игнорирует. Чтобы привязать клиента, нажмите
**Ссылка-приглашение** в карточке клиента в боте и отправьте ему ссылку `t.me`: первый
открывший её аккаунт привязывается ко всем клиентам с этим ID подписки. ID
подписки служит кодом приглашения, поэтому делайте его длинным и случайным.
У каждого аккаунта пять попыток в час, после чего администраторы получают
уведомление.
Администраторам также доступны сценарии со встроенными кнопками: использование
сервера, отсортированные отчёты по трафику, сброс трафика, резервные копии БД,
журналы блокировок, список входящих подключений/клиентов, онлайн-клиенты,
@@ -51,13 +51,20 @@ icon: Send
| 命令 | 适用对象 | 作用 |
| ------------------ | ------ | ------------------------------------------------------------ |
| `/start`、`/help` | 任何人 | 问候语以及内联按钮菜单 |
| `/status` | 任何人 | 确认机器人在线 |
| `/start` | 任何人 | 问候语以及内联按钮菜单;未绑定的账号只会收到自己的 Telegram ID |
| `/help` | 两者 | 内联按钮菜单 |
| `/status` | 两者 | 确认机器人在线 |
| `/id` | 任何人 | 显示你的 Telegram 数字 ID |
| `/usage <arg>` | 两者 | 管理员可搜索客户端;用户则查询自己的用量 |
| `/inbound <remark>`| 管理员 | 显示某个入站的详情 |
| `/restart` | 管理员 | 重启 Xray |
用户是指至少绑定了一个客户端的 Telegram 账号。其他账号只能使用 `/start` 和
`/id`,机器人会忽略它们的其他命令和按钮点击。要绑定客户,请在机器人的客户端卡片上点击
**邀请链接**,并把 `t.me` 链接发给对方:第一个打开该链接的账号会绑定到共用该订阅
ID 的所有客户端。订阅 ID 就是邀请码,因此请保持其足够长且随机。每个账号每小时
可尝试五次,用完后会通知管理员。
管理员还可通过内联按钮使用一系列功能:服务器用量、按流量排序的报告、
重置流量、数据库备份、封禁日志、列出入站/客户端、在线客户端、
“即将耗尽”,以及完整的**添加客户端**向导。普通用户则可以使用按钮查看