mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-08 21:56:08 +00:00
feat(mtproto): per-client ad-tags, management-API auth, and record secret sync
Catch the panel up to the mtg-multi README (v1.14.0): - Each client can now carry its own 32-hex advertising tag overriding the inbound-level one. The tag lives on the client (settings JSON is the source of truth, clients.ad_tag is the UI projection), is rendered into the fork's [secret-ad-tags] section for active secrets only (mtg rejects a config whose override names an unknown secret), is pushed per entry through PUT /secrets, and is part of the reload fingerprint so a tag edit hot-applies without dropping connections. - The loopback management API can replace the whole secret set, so every mtg process now gets a random per-process api-token; the manager sends it as a bearer token on PUT /secrets and GET /stats and reuses it across config rewrites, because mtg reads the token only at startup. - Malformed tags are rejected at every save path and additionally dropped in InstanceFromInbound: one bad tag would otherwise fail the whole generated config and take every client of the inbound down with it. - SyncInbound never copied a re-keyed mtproto secret into the canonical clients table, so the clients page and subscription links kept serving the old secret, which mtg then rejects. It is now guarded-copied like the other credentials.
This commit is contained in:
@@ -435,6 +435,15 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
|
||||
return needRestart, err
|
||||
}
|
||||
|
||||
// Same shape as the group write above: SyncInbound keeps a stored ad-tag
|
||||
// when the incoming settings carry none, so clearing the override must be
|
||||
// applied here, where the editor always round-trips the field.
|
||||
if err := database.GetDB().Model(&model.ClientRecord{}).
|
||||
Where("id = ?", id).
|
||||
UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
|
||||
return needRestart, err
|
||||
}
|
||||
|
||||
if err := database.GetDB().Model(&model.ClientRecord{}).
|
||||
Where("id = ?", id).
|
||||
UpdateColumn("enable", updated.Enable).Error; err != nil {
|
||||
|
||||
@@ -388,6 +388,9 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
|
||||
if client.Secret == "" {
|
||||
return false, common.NewError("mtproto client requires a secret")
|
||||
}
|
||||
if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
|
||||
return false, common.NewError("mtproto client ad tag must be 32 hex characters")
|
||||
}
|
||||
default:
|
||||
if client.ID == "" {
|
||||
return false, common.NewError("empty client ID")
|
||||
@@ -579,6 +582,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if strings.TrimSpace(clients[0].Email) == "" {
|
||||
return false, common.NewError("client email is required")
|
||||
}
|
||||
if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
|
||||
return false, common.NewError("mtproto client ad tag must be 32 hex characters")
|
||||
}
|
||||
|
||||
if clients[0].Email != oldEmail {
|
||||
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
|
||||
|
||||
@@ -75,6 +75,12 @@ func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.
|
||||
if incoming.Auth != "" {
|
||||
row.Auth = incoming.Auth
|
||||
}
|
||||
if incoming.Secret != "" {
|
||||
row.Secret = incoming.Secret
|
||||
}
|
||||
if incoming.AdTag != "" {
|
||||
row.AdTag = incoming.AdTag
|
||||
}
|
||||
row.Flow = incoming.Flow
|
||||
if incoming.Security != "" {
|
||||
row.Security = incoming.Security
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
func TestSyncInbound_UpdatesMtprotoSecretAndAdTag(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
|
||||
db := database.GetDB()
|
||||
|
||||
mtproto := &model.Inbound{Tag: "mtproto-in", Enable: true, Port: 10004, Protocol: model.MTProto}
|
||||
if err := db.Create(mtproto).Error; err != nil {
|
||||
t.Fatalf("create mtproto inbound: %v", err)
|
||||
}
|
||||
|
||||
svc := ClientService{}
|
||||
const email = "tg@example.com"
|
||||
const firstSecret = "ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d"
|
||||
const rekeyedSecret = "eefedcba9876543210fedcba98765432106578616d706c652e636f6d"
|
||||
const firstTag = "0123456789abcdef0123456789abcdef"
|
||||
const retaggedTag = "fedcba9876543210fedcba9876543210"
|
||||
|
||||
first := model.Client{Email: email, Secret: firstSecret, AdTag: firstTag, Enable: true}
|
||||
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{first}); err != nil {
|
||||
t.Fatalf("SyncInbound (create): %v", err)
|
||||
}
|
||||
|
||||
var row model.ClientRecord
|
||||
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
|
||||
t.Fatalf("lookup client row: %v", err)
|
||||
}
|
||||
if row.Secret != firstSecret || row.AdTag != firstTag {
|
||||
t.Fatalf("create must store secret and ad tag: got secret=%q adTag=%q", row.Secret, row.AdTag)
|
||||
}
|
||||
|
||||
rekeyed := model.Client{Email: email, Secret: rekeyedSecret, AdTag: retaggedTag, Enable: true}
|
||||
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{rekeyed}); err != nil {
|
||||
t.Fatalf("SyncInbound (rekey): %v", err)
|
||||
}
|
||||
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
|
||||
t.Fatalf("lookup client row after rekey: %v", err)
|
||||
}
|
||||
if row.Secret != rekeyedSecret {
|
||||
t.Errorf("a re-keyed secret must reach the client record (sub links and the clients page read it), got %q", row.Secret)
|
||||
}
|
||||
if row.AdTag != retaggedTag {
|
||||
t.Errorf("a changed ad tag must reach the client record, got %q", row.AdTag)
|
||||
}
|
||||
|
||||
secretless := model.Client{Email: email, Enable: true}
|
||||
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{secretless}); err != nil {
|
||||
t.Fatalf("SyncInbound (secretless): %v", err)
|
||||
}
|
||||
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
|
||||
t.Fatalf("lookup client row after secretless sync: %v", err)
|
||||
}
|
||||
if row.Secret != rekeyedSecret || row.AdTag != retaggedTag {
|
||||
t.Errorf("a payload without mtproto fields must not wipe them: got secret=%q adTag=%q", row.Secret, row.AdTag)
|
||||
}
|
||||
}
|
||||
@@ -739,6 +739,9 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
|
||||
if client.Secret == "" {
|
||||
return inbound, false, common.NewError("mtproto client requires a secret")
|
||||
}
|
||||
if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
|
||||
return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
|
||||
}
|
||||
default:
|
||||
if client.ID == "" {
|
||||
return inbound, false, common.NewError("empty client ID")
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
|
||||
"mtprotoSecret": "سر MTProto",
|
||||
"mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.",
|
||||
"mtprotoAdTag": "علامة إعلانية (قناة مموّلة)",
|
||||
"mtprotoAdTagHint": "علامة اختيارية مكوّنة من 32 حرفًا ست عشريًا تُطبَّق على هذا العميل فقط بدلًا من العلامة الإعلانية المشتركة. اتركها فارغة لاستخدام العلامة المشتركة.",
|
||||
"reverseTag": "وسم عكسي",
|
||||
"reverseTagPlaceholder": "Reverse tag اختياري",
|
||||
"telegramId": "معرّف مستخدم تلغرام",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
|
||||
"mtprotoSecret": "MTProto secret",
|
||||
"mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.",
|
||||
"mtprotoAdTag": "Ad-tag (sponsored channel)",
|
||||
"mtprotoAdTagHint": "Optional 32-character hex tag applied to this client only, overriding the shared ad-tag. Leave empty to use the shared tag.",
|
||||
"reverseTag": "Reverse tag",
|
||||
"reverseTagPlaceholder": "Optional reverse tag",
|
||||
"telegramId": "Telegram user ID",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas",
|
||||
"mtprotoSecret": "Secreto MTProto",
|
||||
"mtprotoSecretHint": "El secreto FakeTLS del cliente. Vuelve a generarlo para cambiarlo.",
|
||||
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
|
||||
"mtprotoAdTagHint": "Etiqueta hexadecimal opcional de 32 caracteres aplicada solo a este cliente, en lugar del ad-tag compartido. Déjala vacía para usar la etiqueta compartida.",
|
||||
"reverseTag": "Etiqueta inversa",
|
||||
"reverseTagPlaceholder": "Reverse tag opcional",
|
||||
"telegramId": "ID de usuario de Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودیها را با کاما جدا کنید",
|
||||
"mtprotoSecret": "سکرت MTProto",
|
||||
"mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.",
|
||||
"mtprotoAdTag": "برچسب تبلیغاتی (کانال حامی)",
|
||||
"mtprotoAdTagHint": "برچسب هگزادسیمال اختیاری ۳۲ کاراکتری که فقط برای این کلاینت بهجای برچسب تبلیغاتی مشترک اعمال میشود. برای استفاده از برچسب مشترک خالی بگذارید.",
|
||||
"reverseTag": "تگ معکوس",
|
||||
"reverseTagPlaceholder": "Reverse tag اختیاری",
|
||||
"telegramId": "شناسه کاربر تلگرام",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
|
||||
"mtprotoSecret": "Secret MTProto",
|
||||
"mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.",
|
||||
"mtprotoAdTag": "Ad-tag (kanal bersponsor)",
|
||||
"mtprotoAdTagHint": "Tag heksadesimal 32 karakter opsional yang hanya berlaku untuk klien ini, menggantikan ad-tag bersama. Biarkan kosong untuk memakai tag bersama.",
|
||||
"reverseTag": "Reverse tag",
|
||||
"reverseTagPlaceholder": "Reverse tag opsional",
|
||||
"telegramId": "ID pengguna Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
|
||||
"mtprotoSecret": "MTProto シークレット",
|
||||
"mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。",
|
||||
"mtprotoAdTag": "広告タグ(スポンサーチャンネル)",
|
||||
"mtprotoAdTagHint": "このクライアントにのみ適用される任意の 32 文字の 16 進数タグで、共有の広告タグを上書きします。空欄にすると共有タグが使われます。",
|
||||
"reverseTag": "Reverse tag",
|
||||
"reverseTagPlaceholder": "任意の Reverse tag",
|
||||
"telegramId": "Telegram ユーザー ID",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas",
|
||||
"mtprotoSecret": "Segredo MTProto",
|
||||
"mtprotoSecretHint": "O segredo FakeTLS do cliente. Gere novamente para trocá-lo.",
|
||||
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
|
||||
"mtprotoAdTagHint": "Tag hexadecimal opcional de 32 caracteres aplicada somente a este cliente, substituindo a ad-tag compartilhada. Deixe vazio para usar a tag compartilhada.",
|
||||
"reverseTag": "Tag reversa",
|
||||
"reverseTagPlaceholder": "Reverse tag opcional",
|
||||
"telegramId": "ID de usuário do Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
|
||||
"mtprotoSecret": "Секрет MTProto",
|
||||
"mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.",
|
||||
"mtprotoAdTag": "Рекламный тег (спонсорский канал)",
|
||||
"mtprotoAdTagHint": "Необязательный шестнадцатеричный тег из 32 символов, применяемый только к этому клиенту вместо общего рекламного тега. Оставьте пустым, чтобы использовать общий тег.",
|
||||
"reverseTag": "Обратный тег",
|
||||
"reverseTagPlaceholder": "Необязательный Reverse tag",
|
||||
"telegramId": "ID пользователя Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın",
|
||||
"mtprotoSecret": "MTProto sırrı",
|
||||
"mtprotoSecretHint": "İstemcinin FakeTLS sırrı. Değiştirmek için yeniden oluşturun.",
|
||||
"mtprotoAdTag": "Reklam etiketi (sponsorlu kanal)",
|
||||
"mtprotoAdTagHint": "Yalnızca bu istemciye uygulanan ve ortak reklam etiketinin yerine geçen isteğe bağlı 32 karakterlik onaltılık etiket. Ortak etiketi kullanmak için boş bırakın.",
|
||||
"reverseTag": "Reverse Tag",
|
||||
"reverseTagPlaceholder": "İsteğe Bağlı Reverse Tag",
|
||||
"telegramId": "Telegram Kullanıcı ID'si",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
|
||||
"mtprotoSecret": "Секрет MTProto",
|
||||
"mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.",
|
||||
"mtprotoAdTag": "Рекламний тег (спонсорський канал)",
|
||||
"mtprotoAdTagHint": "Необовʼязковий шістнадцятковий тег із 32 символів, що застосовується лише до цього клієнта замість спільного рекламного тега. Залиште порожнім, щоб використовувати спільний тег.",
|
||||
"reverseTag": "Зворотний тег",
|
||||
"reverseTagPlaceholder": "Необов'язковий Reverse tag",
|
||||
"telegramId": "ID користувача Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy",
|
||||
"mtprotoSecret": "Secret MTProto",
|
||||
"mtprotoSecretHint": "Secret FakeTLS của client. Tạo lại để thay đổi.",
|
||||
"mtprotoAdTag": "Ad-tag (kênh tài trợ)",
|
||||
"mtprotoAdTagHint": "Thẻ thập lục phân 32 ký tự tùy chọn chỉ áp dụng cho client này, thay cho ad-tag dùng chung. Để trống để dùng thẻ chung.",
|
||||
"reverseTag": "Reverse tag",
|
||||
"reverseTagPlaceholder": "Reverse tag tùy chọn",
|
||||
"telegramId": "ID người dùng Telegram",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
|
||||
"mtprotoSecret": "MTProto 密钥",
|
||||
"mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。",
|
||||
"mtprotoAdTag": "广告标签(赞助频道)",
|
||||
"mtprotoAdTagHint": "可选的 32 位十六进制标签,仅对该客户端生效,覆盖共享广告标签。留空则使用共享标签。",
|
||||
"reverseTag": "反向标签",
|
||||
"reverseTagPlaceholder": "可选 Reverse tag",
|
||||
"telegramId": "Telegram 用户 ID",
|
||||
|
||||
@@ -918,6 +918,8 @@
|
||||
"wireguardAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
|
||||
"mtprotoSecret": "MTProto 金鑰",
|
||||
"mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。",
|
||||
"mtprotoAdTag": "廣告標籤(贊助頻道)",
|
||||
"mtprotoAdTagHint": "選填的 32 位十六進位標籤,僅對該用戶端生效,覆蓋共用廣告標籤。留空則使用共用標籤。",
|
||||
"reverseTag": "反向標籤",
|
||||
"reverseTagPlaceholder": "選用 Reverse tag",
|
||||
"telegramId": "Telegram 使用者 ID",
|
||||
|
||||
Reference in New Issue
Block a user