mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-14 09:05:01 +03:00
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:
@@ -104,6 +104,17 @@ func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int,
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// sub_id carries a plain index, not a unique one: one subscription can cover
|
||||
// several clients, so callers acting on a subId must handle all of them.
|
||||
func (s *ClientService) GetRecordsBySubID(subId string) ([]*model.ClientRecord, error) {
|
||||
if subId == "" {
|
||||
return nil, errors.New("sub_id must not be empty")
|
||||
}
|
||||
var rows []*model.ClientRecord
|
||||
err := database.GetDB().Where("sub_id = ?", subId).Order("id ASC").Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (s *ClientService) GetRecordsByTgID(tgId int64) ([]*model.ClientRecord, error) {
|
||||
if tgId <= 0 {
|
||||
return nil, errors.New("tg_id must be a positive integer")
|
||||
|
||||
@@ -745,6 +745,7 @@ func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
|
||||
),
|
||||
tu.InlineKeyboardRow(
|
||||
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
|
||||
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.inviteLink")).WithCallbackData(t.encodeQuery("client_invite_link "+email)),
|
||||
),
|
||||
tu.InlineKeyboardRow(
|
||||
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package tgbot
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"html"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
)
|
||||
|
||||
type inviteOutcome int
|
||||
|
||||
const (
|
||||
inviteInvalid inviteOutcome = iota
|
||||
inviteTaken
|
||||
inviteAlreadyOwned
|
||||
inviteBindable
|
||||
)
|
||||
|
||||
// A client's SubID doubles as its invite token: whoever holds it can already
|
||||
// fetch the subscription, so binding grants no access the token did not.
|
||||
func (t *Tgbot) resolveInviteToken(token string, fromID int64) (inviteOutcome, []*model.ClientRecord) {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" || fromID <= 0 {
|
||||
return inviteInvalid, nil
|
||||
}
|
||||
records, err := t.clientService.GetRecordsBySubID(token)
|
||||
if err != nil || len(records) == 0 {
|
||||
return inviteInvalid, nil
|
||||
}
|
||||
return classifyInvite(records, fromID), records
|
||||
}
|
||||
|
||||
// One subscription can span several clients, so a token is claimable only when
|
||||
// no part of it belongs to someone else.
|
||||
func classifyInvite(records []*model.ClientRecord, fromID int64) inviteOutcome {
|
||||
unbound := false
|
||||
for _, record := range records {
|
||||
switch record.TgID {
|
||||
case 0:
|
||||
unbound = true
|
||||
case fromID:
|
||||
default:
|
||||
return inviteTaken
|
||||
}
|
||||
}
|
||||
if unbound {
|
||||
return inviteBindable
|
||||
}
|
||||
return inviteAlreadyOwned
|
||||
}
|
||||
|
||||
// Claims run on concurrent handlers, so resolving and binding happen under one
|
||||
// lock: a second claimant must see the first one's binding, not the rows it read.
|
||||
var inviteClaimMu sync.Mutex
|
||||
|
||||
// claimInvite reports the outcome it told the user, bindErr aside, so a caller
|
||||
// can tell a bind that landed from a refusal without reading the reply.
|
||||
func (t *Tgbot) claimInvite(chatId int64, fromID int64, payload string) inviteOutcome {
|
||||
token, ok := decodeInvitePayload(payload)
|
||||
if !ok {
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteInvalid"))
|
||||
return inviteInvalid
|
||||
}
|
||||
|
||||
inviteClaimMu.Lock()
|
||||
outcome, records := t.resolveInviteToken(token, fromID)
|
||||
var bindErr error
|
||||
if outcome == inviteBindable {
|
||||
bindErr = t.bindRecordsToUser(records, fromID)
|
||||
}
|
||||
inviteClaimMu.Unlock()
|
||||
|
||||
switch outcome {
|
||||
case inviteAlreadyOwned:
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteBound", "Email=="+recordEmails(records)))
|
||||
case inviteBindable:
|
||||
if bindErr != nil {
|
||||
logger.Warning("tgbot: invite bind failed:", bindErr)
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"))
|
||||
return inviteInvalid
|
||||
}
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteBound", "Email=="+recordEmails(records)))
|
||||
default:
|
||||
// Unknown and already-claimed tokens share one reply, so a prober cannot
|
||||
// tell a valid SubID from an invalid one.
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteInvalid"))
|
||||
}
|
||||
return outcome
|
||||
}
|
||||
|
||||
func recordEmails(records []*model.ClientRecord) string {
|
||||
emails := make([]string, 0, len(records))
|
||||
for _, record := range records {
|
||||
emails = append(emails, record.Email)
|
||||
}
|
||||
return strings.Join(emails, ", ")
|
||||
}
|
||||
|
||||
// Every unbound client behind the token is bound, so a subscription spanning
|
||||
// several inbounds does not leave the customer holding only part of it. A failure
|
||||
// part-way undoes this claim's bindings, so the reply never hides a half-bind.
|
||||
func (t *Tgbot) bindRecordsToUser(records []*model.ClientRecord, tgID int64) error {
|
||||
var bound []int
|
||||
for _, record := range records {
|
||||
if record.TgID != 0 {
|
||||
continue
|
||||
}
|
||||
traffic, err := t.inboundService.GetClientTrafficByEmail(record.Email)
|
||||
if err == nil && traffic == nil {
|
||||
err = common.NewError("no traffic record for client:", record.Email)
|
||||
}
|
||||
if err == nil {
|
||||
err = t.setClientTgID(traffic.Id, tgID)
|
||||
}
|
||||
if err != nil {
|
||||
for _, trafficID := range bound {
|
||||
if undoErr := t.setClientTgID(trafficID, EmptyTelegramUserID); undoErr != nil {
|
||||
logger.Warning("tgbot: undoing partial invite bind failed:", undoErr)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
bound = append(bound, traffic.Id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Tgbot) setClientTgID(trafficID int, tgID int64) error {
|
||||
needRestart, err := t.clientService.SetClientTelegramUserID(&t.inboundService, trafficID, tgID)
|
||||
if needRestart {
|
||||
t.xrayService.SetToNeedRestart()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Telegram accepts only A-Za-z0-9_- in a start payload, at most 64 characters,
|
||||
// while a subId may hold '#', '&' or non-ASCII; base64url carries any subId
|
||||
// that fits intact instead of letting the link truncate it into another one.
|
||||
const maxInvitePayload = 64
|
||||
|
||||
func encodeInvitePayload(subID string) (string, bool) {
|
||||
payload := base64.RawURLEncoding.EncodeToString([]byte(subID))
|
||||
return payload, len(payload) <= maxInvitePayload
|
||||
}
|
||||
|
||||
func decodeInvitePayload(payload string) (string, bool) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(payload))
|
||||
if err != nil || len(raw) == 0 {
|
||||
return "", false
|
||||
}
|
||||
return string(raw), true
|
||||
}
|
||||
|
||||
func (t *Tgbot) sendInviteLink(chatId int64, email string) {
|
||||
record, err := t.clientService.GetRecordByEmail(nil, email)
|
||||
username := botUsername()
|
||||
if err != nil || record.SubID == "" || username == "" {
|
||||
logger.Warning("tgbot: invite link unavailable for", email, err)
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"))
|
||||
return
|
||||
}
|
||||
payload, ok := encodeInvitePayload(record.SubID)
|
||||
if !ok {
|
||||
logger.Warning("tgbot: subId of", email, "is too long for a Telegram invite link")
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"))
|
||||
return
|
||||
}
|
||||
link := "https://t.me/" + username + "?start=" + payload
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteLink", "Email=="+email, "Link=="+link))
|
||||
}
|
||||
|
||||
// A subId can be short or human-readable, so claim attempts are capped per
|
||||
// Telegram account: guessing stays slow, and admins hear about whoever tries.
|
||||
const (
|
||||
inviteAttemptLimit = 5
|
||||
inviteAttemptWindow = time.Hour
|
||||
)
|
||||
|
||||
type inviteAttempts struct {
|
||||
windowStart time.Time
|
||||
count int
|
||||
}
|
||||
|
||||
var (
|
||||
inviteAttemptsMu sync.Mutex
|
||||
inviteAttemptsBy = map[int64]*inviteAttempts{}
|
||||
inviteAttemptsNow = time.Now
|
||||
)
|
||||
|
||||
// allowInviteAttempt counts one claim attempt and reports whether it may run.
|
||||
// Admins are told once per window, on the first attempt past the limit.
|
||||
func (t *Tgbot) allowInviteAttempt(from *telego.User) bool {
|
||||
now := inviteAttemptsNow()
|
||||
inviteAttemptsMu.Lock()
|
||||
for id, a := range inviteAttemptsBy {
|
||||
if now.Sub(a.windowStart) >= inviteAttemptWindow {
|
||||
delete(inviteAttemptsBy, id)
|
||||
}
|
||||
}
|
||||
a, ok := inviteAttemptsBy[from.ID]
|
||||
if !ok {
|
||||
a = &inviteAttempts{windowStart: now}
|
||||
inviteAttemptsBy[from.ID] = a
|
||||
}
|
||||
a.count++
|
||||
count := a.count
|
||||
inviteAttemptsMu.Unlock()
|
||||
|
||||
if count == inviteAttemptLimit+1 {
|
||||
t.SendMsgToTgbotAdmins(t.I18nBot("tgbot.messages.inviteRateLimitedAdmin",
|
||||
"User=="+tgUserMention(from),
|
||||
"ID=="+strconv.FormatInt(from.ID, 10),
|
||||
"Limit=="+strconv.Itoa(inviteAttemptLimit)))
|
||||
}
|
||||
return count <= inviteAttemptLimit
|
||||
}
|
||||
|
||||
func tgUserMention(from *telego.User) string {
|
||||
id := strconv.FormatInt(from.ID, 10)
|
||||
name := strings.TrimSpace(from.FirstName + " " + from.LastName)
|
||||
if name == "" {
|
||||
name = id
|
||||
}
|
||||
mention := `<a href="tg://user?id=` + id + `">` + html.EscapeString(name) + `</a>`
|
||||
if from.Username != "" {
|
||||
mention += " @" + html.EscapeString(from.Username)
|
||||
}
|
||||
return mention
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package tgbot
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
)
|
||||
|
||||
func seedClientRecord(t *testing.T, email, subID string, tgID int64) {
|
||||
t.Helper()
|
||||
rec := &model.ClientRecord{Email: email, SubID: subID, TgID: tgID, Enable: true}
|
||||
if err := database.GetDB().Create(rec).Error; err != nil {
|
||||
t.Fatalf("seed client %s: %v", email, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Binding is first-claim-wins: the owner re-tapping is idempotent, and no part of
|
||||
// a subscription held by someone else is ever reassigned.
|
||||
func TestResolveInviteToken(t *testing.T) {
|
||||
tb, _ := newLinksCallbackTgbot(t, ownerMail)
|
||||
seedClientRecord(t, "free@x", "sub-free", 0)
|
||||
seedClientRecord(t, "held@x", "sub-held", 5150)
|
||||
seedClientRecord(t, "shared-a@x", "sub-shared", 0)
|
||||
seedClientRecord(t, "shared-b@x", "sub-shared", 0)
|
||||
seedClientRecord(t, "part-mine@x", "sub-part-mine", 7000)
|
||||
seedClientRecord(t, "part-free@x", "sub-part-mine", 0)
|
||||
seedClientRecord(t, "part-free2@x", "sub-part-held", 0)
|
||||
seedClientRecord(t, "part-held@x", "sub-part-held", 9999)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
token string
|
||||
from int64
|
||||
want inviteOutcome
|
||||
records int
|
||||
}{
|
||||
{"unclaimed binds", "sub-free", 7000, inviteBindable, 1},
|
||||
{"token is trimmed", " sub-free\n", 7000, inviteBindable, 1},
|
||||
{"owner is idempotent", "sub-held", 5150, inviteAlreadyOwned, 1},
|
||||
{"someone else's is refused", "sub-held", 7000, inviteTaken, 1},
|
||||
{"shared subscription binds whole", "sub-shared", 7000, inviteBindable, 2},
|
||||
{"finishing a partly owned one binds", "sub-part-mine", 7000, inviteBindable, 2},
|
||||
{"partly held by another is refused", "sub-part-held", 7000, inviteTaken, 2},
|
||||
{"unknown token", "sub-nope", 7000, inviteInvalid, 0},
|
||||
{"empty token", "", 7000, inviteInvalid, 0},
|
||||
{"missing sender", "sub-free", 0, inviteInvalid, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, records := tb.resolveInviteToken(c.token, c.from)
|
||||
if got != c.want || len(records) != c.records {
|
||||
t.Errorf("%s: got (%d, %d records), want (%d, %d records)", c.name, got, len(records), c.want, c.records)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mustInvitePayload(t *testing.T, subID string) string {
|
||||
t.Helper()
|
||||
payload, ok := encodeInvitePayload(subID)
|
||||
if !ok {
|
||||
t.Fatalf("encodeInvitePayload(%q) refused", subID)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// newInviteTgbot seeds one unbound client whose subId is sub-invite.
|
||||
func newInviteTgbot(t *testing.T, email string) (*Tgbot, func(string) int) {
|
||||
t.Helper()
|
||||
tb, calls := newLinksCallbackTgbot(t, email)
|
||||
if err := database.GetDB().Model(&model.Inbound{}).Where("1 = 1").
|
||||
Update("settings", `{"clients":[{"id":"6f1d2c3e-8a4b-4c5d-9e6f-7a8b9c0d1e2f","email":"`+email+`","subId":"sub-invite"}]}`).Error; err != nil {
|
||||
t.Fatalf("unbind seeded client: %v", err)
|
||||
}
|
||||
seedClientRecord(t, email, "sub-invite", 0)
|
||||
withAdmins(t, 1)
|
||||
return tb, calls
|
||||
}
|
||||
|
||||
// Regression test: a subId with URL metacharacters was pasted raw into the link,
|
||||
// so Telegram truncated it; every legal subId that fits must survive the trip.
|
||||
func TestInvitePayloadRoundTrip(t *testing.T) {
|
||||
for _, subID := range []string{"a1B2c3D4e5F6g7H8", "team#1", "alice&bob", "x?y=z", "کاربر", strings.Repeat("s", 48)} {
|
||||
payload, ok := encodeInvitePayload(subID)
|
||||
if !ok {
|
||||
t.Errorf("encodeInvitePayload(%q) refused", subID)
|
||||
continue
|
||||
}
|
||||
if strings.Trim(payload, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") != "" {
|
||||
t.Errorf("payload %q for %q has characters Telegram rejects", payload, subID)
|
||||
}
|
||||
if got, ok := decodeInvitePayload(payload); !ok || got != subID {
|
||||
t.Errorf("round trip of %q = (%q, %v)", subID, got, ok)
|
||||
}
|
||||
}
|
||||
if _, ok := encodeInvitePayload(strings.Repeat("s", 49)); ok {
|
||||
t.Error("a subId past 64 payload characters must be refused, not truncated")
|
||||
}
|
||||
for _, payload := range []string{"", "not base64!", " "} {
|
||||
if _, ok := decodeInvitePayload(payload); ok {
|
||||
t.Errorf("decodeInvitePayload(%q) accepted", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test: accounts opening one link at once all read TgID == 0, all bound
|
||||
// and were all told so, while only the last write held; exactly one may succeed.
|
||||
func TestConcurrentClaimsBindOnlyOneAccount(t *testing.T) {
|
||||
tb, _ := newInviteTgbot(t, "raced@x")
|
||||
payload := mustInvitePayload(t, "sub-invite")
|
||||
|
||||
claimants := []int64{8101, 8102, 8103, 8104, 8105, 8106}
|
||||
outcomes := make([]inviteOutcome, len(claimants))
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i, id := range claimants {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
outcomes[i] = tb.claimInvite(id, id, payload)
|
||||
}()
|
||||
}
|
||||
// Hold the inbound write every bind needs, so all claimants resolve before any
|
||||
// bind lands; otherwise the first bind outruns the rest and hides the race.
|
||||
hold := database.GetDB().Begin()
|
||||
if err := hold.Exec("UPDATE inbounds SET remark = remark").Error; err != nil {
|
||||
t.Fatalf("hold inbound write: %v", err)
|
||||
}
|
||||
close(start)
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if err := hold.Commit().Error; err != nil {
|
||||
t.Fatalf("release inbound write: %v", err)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
told, holders := 0, 0
|
||||
for i, id := range claimants {
|
||||
if outcomes[i] == inviteBindable {
|
||||
told++
|
||||
}
|
||||
if tb.levelOf(id) == levelClient {
|
||||
holders++
|
||||
}
|
||||
}
|
||||
if told != 1 || holders != 1 {
|
||||
t.Errorf("%d accounts told they bound, %d holding the client; want 1 and 1", told, holders)
|
||||
}
|
||||
}
|
||||
|
||||
// A stranger opening a valid invite link must come out of it a client.
|
||||
func TestClaimInvitePromotesStrangerToClient(t *testing.T) {
|
||||
const email = "invitee@x"
|
||||
tb, calls := newInviteTgbot(t, email)
|
||||
|
||||
const newcomer = int64(8080)
|
||||
if got := tb.levelOf(newcomer); got != levelStranger {
|
||||
t.Fatalf("levelOf before claim = %d, want stranger", got)
|
||||
}
|
||||
|
||||
tb.claimInvite(newcomer, newcomer, mustInvitePayload(t, "sub-invite"))
|
||||
|
||||
if got := tb.levelOf(newcomer); got != levelClient {
|
||||
t.Errorf("levelOf after claim = %d, want client", got)
|
||||
}
|
||||
if n := calls("sendMessage"); n != 1 {
|
||||
t.Errorf("sendMessage calls = %d, want 1 confirmation", n)
|
||||
}
|
||||
if outcome, _ := tb.resolveInviteToken("sub-invite", 9999); outcome != inviteTaken {
|
||||
t.Errorf("second claimant outcome = %d, want taken", outcome)
|
||||
}
|
||||
}
|
||||
|
||||
// Guessing a subId must stay slow: past five attempts an hour an account is
|
||||
// refused, and admins are told once per window rather than once per attempt.
|
||||
func TestInviteAttemptLimit(t *testing.T) {
|
||||
_, calls := newLinksCallbackTgbot(t, ownerMail)
|
||||
withAdmins(t, 1, 2)
|
||||
tb := &Tgbot{}
|
||||
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
origNow, origBy := inviteAttemptsNow, inviteAttemptsBy
|
||||
inviteAttemptsNow = func() time.Time { return now }
|
||||
inviteAttemptsBy = map[int64]*inviteAttempts{}
|
||||
t.Cleanup(func() { inviteAttemptsNow, inviteAttemptsBy = origNow, origBy })
|
||||
|
||||
guesser := &telego.User{ID: 6666, FirstName: "<b>x</b>"}
|
||||
for i := 1; i <= inviteAttemptLimit; i++ {
|
||||
if !tb.allowInviteAttempt(guesser) {
|
||||
t.Fatalf("attempt %d refused, want allowed", i)
|
||||
}
|
||||
}
|
||||
for range 3 {
|
||||
if tb.allowInviteAttempt(guesser) {
|
||||
t.Fatal("attempt past the limit allowed")
|
||||
}
|
||||
}
|
||||
if n := calls("sendMessage"); n != 2 {
|
||||
t.Errorf("sendMessage calls = %d, want 2: one notice per admin, once per window", n)
|
||||
}
|
||||
if !tb.allowInviteAttempt(&telego.User{ID: 7777}) {
|
||||
t.Error("another account was refused by the guesser's limit")
|
||||
}
|
||||
|
||||
now = now.Add(inviteAttemptWindow)
|
||||
if !tb.allowInviteAttempt(guesser) {
|
||||
t.Error("attempt after the window refused, want allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTgUserMentionEscapesName(t *testing.T) {
|
||||
got := tgUserMention(&telego.User{ID: 42, FirstName: "<b>Eve</b>", Username: "eve"})
|
||||
want := `<a href="tg://user?id=42"><b>Eve</b></a> @eve`
|
||||
if got != want {
|
||||
t.Errorf("tgUserMention = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package tgbot
|
||||
|
||||
import (
|
||||
"github.com/mymmrac/telego"
|
||||
tu "github.com/mymmrac/telego/telegoutil"
|
||||
)
|
||||
|
||||
// userLevel decides what the bot admits to existing at all: a Telegram account
|
||||
// that no admin has bound to a client must not be able to explore the bot.
|
||||
type userLevel int
|
||||
|
||||
const (
|
||||
levelStranger userLevel = iota
|
||||
levelClient
|
||||
levelAdmin
|
||||
)
|
||||
|
||||
// levelOf runs on every update, a stranger's included, so it reads the indexed
|
||||
// tg_id column of the clients table rather than expanding every inbound's JSON.
|
||||
func (t *Tgbot) levelOf(tgUserID int64) userLevel {
|
||||
if checkAdmin(tgUserID) {
|
||||
return levelAdmin
|
||||
}
|
||||
if tgUserID <= 0 {
|
||||
return levelStranger
|
||||
}
|
||||
records, err := t.clientService.GetRecordsByTgID(tgUserID)
|
||||
if err != nil || len(records) == 0 {
|
||||
return levelStranger
|
||||
}
|
||||
return levelClient
|
||||
}
|
||||
|
||||
// Commands are allowlisted rather than denied one by one: a command added later
|
||||
// stays out of reach of non-admins until it is deliberately listed here.
|
||||
var commandsByLevel = map[userLevel]map[string]bool{
|
||||
// /id stays open because an admin binding by hand still asks for the ChatID.
|
||||
levelStranger: {"start": true, "id": true},
|
||||
levelClient: {"start": true, "help": true, "status": true, "id": true, "usage": true},
|
||||
}
|
||||
|
||||
func commandAllowed(level userLevel, command string) bool {
|
||||
if level == levelAdmin {
|
||||
return true
|
||||
}
|
||||
return commandsByLevel[level][command]
|
||||
}
|
||||
|
||||
// gateCommand reports whether a command reaches answerCommand, and as whom. A
|
||||
// stranger's refused command gets no reply, so the bot reveals nothing to probe.
|
||||
func (t *Tgbot) gateCommand(message *telego.Message) (isAdmin bool, ok bool) {
|
||||
level := t.levelOf(message.From.ID)
|
||||
command, _, _ := tu.ParseCommand(message.Text)
|
||||
if commandAllowed(level, command) {
|
||||
return level == levelAdmin, true
|
||||
}
|
||||
if level == levelClient {
|
||||
t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.commands.unknown"))
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// gateCallback answers a stranger's tap without acting on it: a stranger holds
|
||||
// no keyboard of ours, so any callback data from one is forged or stale.
|
||||
func (t *Tgbot) gateCallback(query *telego.CallbackQuery) (isAdmin bool, ok bool) {
|
||||
level := t.levelOf(query.From.ID)
|
||||
if level == levelStranger {
|
||||
t.sendCallbackAnswerTgBot(query.ID, "")
|
||||
return false, false
|
||||
}
|
||||
return level == levelAdmin, true
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package tgbot
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
)
|
||||
|
||||
func withAdmins(t *testing.T, ids ...int64) {
|
||||
t.Helper()
|
||||
tgBotMutex.Lock()
|
||||
orig := adminIds
|
||||
adminIds = ids
|
||||
tgBotMutex.Unlock()
|
||||
t.Cleanup(func() {
|
||||
tgBotMutex.Lock()
|
||||
adminIds = orig
|
||||
tgBotMutex.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
// newLevelTgbot binds ownerMail to ownerTgID in both the inbound settings and
|
||||
// the clients table, and makes account 1 the only admin.
|
||||
func newLevelTgbot(t *testing.T) (*Tgbot, func(string) int) {
|
||||
t.Helper()
|
||||
tb, calls := newLinksCallbackTgbot(t, ownerMail)
|
||||
seedClientRecord(t, ownerMail, "sub-owned", ownerTgID)
|
||||
withAdmins(t, 1)
|
||||
return tb, calls
|
||||
}
|
||||
|
||||
func commandFrom(tgUserID int64, text string) *telego.Message {
|
||||
return &telego.Message{
|
||||
From: &telego.User{ID: tgUserID},
|
||||
Chat: telego.Chat{ID: tgUserID, Type: telego.ChatTypePrivate},
|
||||
Text: text,
|
||||
}
|
||||
}
|
||||
|
||||
func TestLevelOfFollowsTheClientBinding(t *testing.T) {
|
||||
tb, _ := newLevelTgbot(t)
|
||||
|
||||
for id, want := range map[int64]userLevel{1: levelAdmin, ownerTgID: levelClient, 777: levelStranger, 0: levelStranger} {
|
||||
if got := tb.levelOf(id); got != want {
|
||||
t.Errorf("levelOf(%d) = %d, want %d", id, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A stranger's refused command must get no reply at all, while a bound client
|
||||
// is still told the command is unknown, as before the gate existed.
|
||||
func TestGateCommand(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
from int64
|
||||
text string
|
||||
wantOK bool
|
||||
wantAdmin bool
|
||||
wantSends int
|
||||
}{
|
||||
{"stranger start", 777, "/start", true, false, 0},
|
||||
{"stranger help", 777, "/help", false, false, 0},
|
||||
{"stranger admin command", 777, "/restart", false, false, 0},
|
||||
{"client usage", ownerTgID, "/usage", true, false, 0},
|
||||
{"client admin command", ownerTgID, "/clearall", false, false, 1},
|
||||
{"admin", 1, "/clearall", true, true, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
tb, calls := newLevelTgbot(t)
|
||||
|
||||
isAdmin, ok := tb.gateCommand(commandFrom(c.from, c.text))
|
||||
if ok != c.wantOK || isAdmin != c.wantAdmin {
|
||||
t.Errorf("gateCommand = (%v, %v), want (%v, %v)", isAdmin, ok, c.wantAdmin, c.wantOK)
|
||||
}
|
||||
if n := calls("sendMessage"); n != c.wantSends {
|
||||
t.Errorf("sendMessage calls = %d, want %d", n, c.wantSends)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test: a stranger's forged callback must be answered, so the button
|
||||
// stops spinning, and must never reach answerCallback.
|
||||
func TestGateCallbackStopsStrangers(t *testing.T) {
|
||||
tb, calls := newLevelTgbot(t)
|
||||
|
||||
query := &telego.CallbackQuery{ID: "q1", From: telego.User{ID: 777}, Data: "client_sub_links " + ownerMail}
|
||||
if _, ok := tb.gateCallback(query); ok {
|
||||
t.Fatal("gateCallback admitted a stranger")
|
||||
}
|
||||
if n := calls("answerCallbackQuery"); n != 1 {
|
||||
t.Errorf("answerCallbackQuery calls = %d, want 1", n)
|
||||
}
|
||||
|
||||
query.From.ID = ownerTgID
|
||||
if isAdmin, ok := tb.gateCallback(query); !ok || isAdmin {
|
||||
t.Errorf("gateCallback(client) = (%v, %v), want (false, true)", isAdmin, ok)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,9 @@ func (t *Tgbot) OnReceive() {
|
||||
// Use goroutine with worker pool for concurrent command processing
|
||||
go runBotHandler(func() {
|
||||
userStateMgr.clear(messageActor(message))
|
||||
t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
|
||||
if isAdmin, ok := t.gateCommand(&message); ok {
|
||||
t.answerCommand(&message, message.Chat.ID, isAdmin)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}, th.AnyCommand())
|
||||
@@ -105,7 +107,9 @@ func (t *Tgbot) OnReceive() {
|
||||
// Use goroutine with worker pool for concurrent callback processing
|
||||
go runBotHandler(func() {
|
||||
userStateMgr.clear(callbackActor(&query))
|
||||
t.answerCallback(&query, checkAdmin(query.From.ID))
|
||||
if isAdmin, ok := t.gateCallback(&query); ok {
|
||||
t.answerCallback(&query, isAdmin)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}, th.AnyCallbackQueryWithMessage())
|
||||
@@ -227,6 +231,18 @@ func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin boo
|
||||
msg += t.I18nBot("tgbot.commands.help")
|
||||
msg += t.I18nBot("tgbot.commands.pleaseChoose")
|
||||
case "start":
|
||||
if len(commandArgs) > 0 {
|
||||
if !isAdmin && !t.allowInviteAttempt(message.From) {
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.inviteRateLimited"))
|
||||
return
|
||||
}
|
||||
t.claimInvite(chatId, message.From.ID, commandArgs[0])
|
||||
}
|
||||
// A stranger learns only its ChatID, which is what an admin needs to bind it.
|
||||
if !isAdmin && t.levelOf(message.From.ID) == levelStranger {
|
||||
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(message.From.ID, 10)))
|
||||
return
|
||||
}
|
||||
msg += t.I18nBot("tgbot.commands.start", "Firstname=="+html.EscapeString(message.From.FirstName))
|
||||
if isAdmin {
|
||||
msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
|
||||
@@ -792,6 +808,9 @@ func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool
|
||||
case "tg_user":
|
||||
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
|
||||
t.clientTelegramUserInfo(chatId, email)
|
||||
case "client_invite_link":
|
||||
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.inviteLink"))
|
||||
t.sendInviteLink(chatId, email)
|
||||
case "tgid_remove":
|
||||
inlineKeyboard := tu.InlineKeyboard(
|
||||
tu.InlineKeyboardRow(
|
||||
|
||||
Reference in New Issue
Block a user