fix(mtproto): stop dropping connections on client/inbound edits; add live updates + ad-tag (#5838)

* fix(mtproto): split the mtg fingerprint into structural and secrets parts

A reordered clients array in the stored settings used to read as a config
change because the fingerprint concatenated secrets in array order, and one
opaque fingerprint could not tell a restart-worthy change (bind address,
fronting, throttle) from a secret-set change a reload-capable mtg can absorb
in place. Sort the secret pairs so order stops mattering, and split the value
so the upcoming hot-reload path can decide between keeping, reloading, and
restarting the process.

* fix(mtproto): stop restarting mtg on every inbound edit

Saving an mtproto inbound tore down and respawned its mtg sidecar even when
nothing material changed, dropping every live Telegram connection: the update
path pushed DelInbound+AddInbound, and Remove deletes the manager's map entry,
so Ensure's fingerprint no-op gate could never fire. Route mtproto updates
through a single Ensure call so an edit that leaves the generated TOML alone
keeps the process, and only real config changes restart it.

Capturing the pre-edit protocol also fixes a latent leak: changing an
inbound's protocol away from mtproto never stopped the sidecar, because the
snapshot handed to the runtime already carried the new protocol and the
removal took the xray branch, leaving an orphaned mtg holding the port.

An mtproto push failure no longer requests an xray restart - xray cannot fix
the sidecar, and the 10s reconcile job self-heals it.

The regression test fakes mtg by re-executing the test binary, counting
spawns through a pid file: an unchanged save and a remark-only edit must keep
the process, a re-keyed secret must restart it.

* fix(mtproto): exclude depleted clients from the reconcile job to match the sync push

The 10s reconcile job derived mtg secret sets from raw inbound settings while
the interactive push filtered clients through buildRuntimeInboundForAPI, which
drops client_traffics-disabled (depleted or expired) clients. The two paths
therefore disagreed on the fingerprint - each disagreement one needless mtg
restart dropping live connections - and worse, the job kept serving depleted
clients' secrets indefinitely, so running out of traffic never actually cut an
mtproto client's access.

DesiredMtprotoInstances now builds the job's desired state with the same
depletion overlay the push uses (one bulk client_traffics query), drops
inbounds whose every secret is filtered away so their sidecar stops, and
AddInbound pushes the filtered payload too so an imported inbound carrying
disabled stats does not seed a fingerprint the next reconcile disagrees with.

* feat(mtproto): hot-reload mtg secrets in place instead of restarting

A client add, removal, re-key, or enable-toggle changes only the [secrets]
section of the generated config, yet the panel could apply it only by killing
and respawning the mtg sidecar, dropping every Telegram connection on that
inbound. Split the ensure decision three ways: an identical config is a no-op,
a secrets-only change rewrites the TOML on the same api port and asks mtg to
hot-swap it via POST /reload, and a structural change (or a failed reload)
falls back to the full stop-and-start.

The reload endpoint is served by the mhsanaei/mtg-multi fork; against an older
binary the POST 404s and the manager restarts exactly as before, so panel and
binary upgrades stay order-independent.

* feat(mtproto): apply single-client edits to the sidecar immediately

Client CRUD on an mtproto inbound was a runtime no-op, so an add, delete,
re-key, or enable-toggle only reached mtg on the next 10s reconcile. With the
sidecar now able to hot-reload, push the change straight after the edit commits:
applyLocalMtproto rebuilds the inbound's filtered client set and re-applies it,
so a new client works within a moment (and, on a reload-capable binary, without
disturbing the others) and deleting the last client stops the process.

The three interactive single-client paths (add, update, delete) call it; bulk
operations still ride the reconcile job, which converges to the same state.

* chore(mtproto): pin mtg-multi to the mhsanaei fork v1.13.3

The reload endpoint the panel now uses lives in the mhsanaei/mtg-multi fork, so
point the source-build pin (DockerInit.sh + both release.yml matrices) at it and
bump to v1.13.3. The install still produces the same mtg-multi binary name, so
the mtg-<os>-<arch> rename and everything downstream are unchanged. Docs and the
package comment note the hot-reload path and its restart fallback.

* feat(mtproto): apply live secret updates via the management API and add ad-tag

Two capabilities the mhsanaei/mtg-multi v1.13.3 fork exposes are now surfaced by
the sidecar manager.

Live updates go through PUT /secrets on the fork's management API instead of
POST /reload: the panel already holds the whole desired set per inbound, so it
sends secrets and the advertising tag as one JSON call that mtg applies
atomically, keeping every unchanged connection and closing only removed or
re-keyed ones. The config file is still written first so a restart or crash
recovery reproduces the state, and any non-200 (an older binary, a refused
connection) still falls back to a full restart.

Per-inbound ad-tag adds an optional 32-hex Telegram advertising tag plus
public-ipv4/public-ipv6 overrides. The ad-tag rides the reloadable secrets
fingerprint, so changing it hot-applies without dropping connections; the public
IPs are proxy-construction parameters and sit in the structural fingerprint, so a
change there restarts the process. Empty public IPs are omitted so mtg
auto-detects the reachable address.

* feat(inbounds): expose the mtproto ad-tag and public IP in the inbound form

Adds an Ad-tag field (validated as 32 hex characters) plus optional Public IPv4
and Public IPv6 overrides to the MTProto inbound form, backed by the same-named
settings the sidecar writes into the mtg config. The public IPs are optional —
left blank, mtg auto-detects the reachable address the ad-tag middle proxy needs.
English strings are added to every locale; the non-English ones carry the
English text until translated and fall back to it meanwhile.

* ci(mtproto): install mtg-multi from prebuilt release binaries

The fork now publishes release archives for every platform we package, so
download and unpack the matching mtg-multi-<ver>-<os>-<arch> binary instead of
compiling it from source with go install. Faster builds and no toolchain step,
and the archive's platform labels line up with our matrix; the produced
mtg-<os>-<arch> filenames are unchanged.

* i18n(mtproto): localize the ad-tag and public IP strings

The six mtgAdTag*/mtgPublicIp* keys shipped with English text in every locale as
a placeholder. Translate them into the twelve non-English locales (Arabic,
Spanish, Persian, Indonesian, Japanese, Portuguese-BR, Russian, Turkish,
Ukrainian, Vietnamese, and Simplified/Traditional Chinese); en-US is unchanged.

* retired goreportcard.com
This commit is contained in:
Sanaei
2026-07-07 01:13:24 +02:00
committed by GitHub
parent 84b6423020
commit 6214ff4edc
40 changed files with 1166 additions and 97 deletions
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "نطاق FakeTLS الافتراضي المستخدم لإنشاء سر عميل جديد. يمكن لكل عميل استخدام نطاقه الخاص.",
"mtgThrottleMaxConnections": "الحد الأقصى للاتصالات",
"mtgThrottleMaxConnectionsHint": "تحديد الاتصالات المتزامنة لجميع المستخدمين بتوزيع عادل. القيمة 0 تعطّل الميزة.",
"mtgAdTag": "علامة إعلانية (قناة مموّلة)",
"mtgAdTagHint": "علامة اختيارية مكوّنة من 32 حرفًا ست عشريًا يتم الحصول عليها عند تسجيل البروكسي في تلغرام. عند تعيينها، يتم توجيه العملاء عبر البروكسيات الوسيطة في تلغرام وتظهر قناة مموّلة أعلى قائمة محادثاتهم. تتطلب عنوان IP عامًا يمكن الوصول إليه - عيّنه أدناه أو اترك mtg يكتشفه تلقائيًا.",
"mtgAdTagInvalid": "يجب أن تتكوّن العلامة الإعلانية من 32 حرفًا ست عشريًا بالضبط.",
"mtgPublicIpv4": "عنوان IPv4 العام",
"mtgPublicIpv6": "عنوان IPv6 العام",
"mtgPublicIpHint": "العنوان العام لهذا الخادم الذي يمكن الوصول إليه، ويُستخدم بواسطة البروكسي الوسيط للعلامة الإعلانية. اتركه فارغًا ليكتشفه mtg تلقائيًا.",
"visionTestseed": "Vision testseed",
"version": "الإصدار",
"udpIdleTimeout": "UDP idle timeout (ثانية)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "Default FakeTLS domain used to generate a new client's secret. Each client can front its own domain.",
"mtgThrottleMaxConnections": "Max connections",
"mtgThrottleMaxConnectionsHint": "Cap concurrent connections across all users with a fair-share limit. 0 disables throttling.",
"mtgAdTag": "Ad-tag (sponsored channel)",
"mtgAdTagHint": "Optional 32-character hex tag from Telegram's proxy registration. When set, clients are routed through Telegram middle proxies and a sponsored channel appears at the top of their chat list. Requires a reachable public IP - set one below or let mtg auto-detect it.",
"mtgAdTagInvalid": "Ad-tag must be exactly 32 hexadecimal characters.",
"mtgPublicIpv4": "Public IPv4",
"mtgPublicIpv6": "Public IPv6",
"mtgPublicIpHint": "This server's reachable public address, used by the ad-tag middle proxy. Leave blank to let mtg auto-detect it.",
"visionTestseed": "Vision testseed",
"version": "Version",
"udpIdleTimeout": "UDP idle timeout (s)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "Dominio FakeTLS predeterminado para generar el secreto de un nuevo cliente. Cada cliente puede usar su propio dominio.",
"mtgThrottleMaxConnections": "Conexiones máximas",
"mtgThrottleMaxConnectionsHint": "Limita las conexiones simultáneas de todos los usuarios con reparto equitativo. 0 desactiva el límite.",
"mtgAdTag": "Ad-tag (canal patrocinado)",
"mtgAdTagHint": "Etiqueta hexadecimal opcional de 32 caracteres del registro de proxy de Telegram. Si se establece, los clientes se enrutan a través de los proxies intermedios de Telegram y aparece un canal patrocinado en la parte superior de su lista de chats. Requiere una IP pública accesible: configúrala abajo o deja que mtg la detecte automáticamente.",
"mtgAdTagInvalid": "El ad-tag debe tener exactamente 32 caracteres hexadecimales.",
"mtgPublicIpv4": "IPv4 pública",
"mtgPublicIpv6": "IPv6 pública",
"mtgPublicIpHint": "La dirección pública accesible de este servidor, usada por el proxy intermedio del ad-tag. Déjalo en blanco para que mtg la detecte automáticamente.",
"visionTestseed": "Vision testseed",
"version": "Versión",
"udpIdleTimeout": "UDP idle timeout (s)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "دامنه پیش‌فرض FakeTLS برای ساخت سکرت کلاینت جدید. هر کلاینت می‌تواند دامنه مخصوص خود را داشته باشد.",
"mtgThrottleMaxConnections": "حداکثر اتصالات",
"mtgThrottleMaxConnectionsHint": "محدود کردن اتصالات همزمان همه کاربران با تقسیم منصفانه. مقدار ۰ غیرفعال است.",
"mtgAdTag": "برچسب تبلیغاتی (کانال حامی)",
"mtgAdTagHint": "برچسب هگزادسیمال اختیاری ۳۲ کاراکتری که هنگام ثبت پروکسی در تلگرام دریافت می‌شود. با تنظیم آن، کاربران از طریق پروکسی‌های میانی تلگرام هدایت می‌شوند و یک کانال حامی در بالای فهرست گفتگوهایشان نمایش داده می‌شود. به یک IP عمومی در دسترس نیاز دارد - آن را در پایین تنظیم کنید یا بگذارید mtg به‌طور خودکار آن را تشخیص دهد.",
"mtgAdTagInvalid": "برچسب تبلیغاتی باید دقیقاً ۳۲ کاراکتر هگزادسیمال باشد.",
"mtgPublicIpv4": "IPv4 عمومی",
"mtgPublicIpv6": "IPv6 عمومی",
"mtgPublicIpHint": "نشانی عمومی و در‌دسترس این سرور که پروکسی میانی برچسب تبلیغاتی از آن استفاده می‌کند. برای تشخیص خودکار توسط mtg، خالی بگذارید.",
"visionTestseed": "Vision testseed",
"version": "نسخه",
"udpIdleTimeout": "UDP idle timeout (s)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "Domain FakeTLS default untuk membuat secret klien baru. Setiap klien bisa memakai domainnya sendiri.",
"mtgThrottleMaxConnections": "Koneksi maksimum",
"mtgThrottleMaxConnectionsHint": "Batasi koneksi bersamaan semua pengguna dengan pembagian adil. 0 menonaktifkan.",
"mtgAdTag": "Ad-tag (kanal bersponsor)",
"mtgAdTagHint": "Tag heksadesimal 32 karakter opsional dari pendaftaran proxy Telegram. Jika diatur, klien dirutekan melalui proxy perantara Telegram dan kanal bersponsor muncul di bagian atas daftar obrolan mereka. Memerlukan IP publik yang dapat dijangkau - atur di bawah atau biarkan mtg mendeteksinya secara otomatis.",
"mtgAdTagInvalid": "Ad-tag harus tepat 32 karakter heksadesimal.",
"mtgPublicIpv4": "IPv4 Publik",
"mtgPublicIpv6": "IPv6 Publik",
"mtgPublicIpHint": "Alamat publik server ini yang dapat dijangkau, digunakan oleh proxy perantara ad-tag. Biarkan kosong agar mtg mendeteksinya secara otomatis.",
"visionTestseed": "Vision testseed",
"version": "Versi",
"udpIdleTimeout": "UDP idle timeout (d)",
+6
View File
@@ -546,6 +546,12 @@
"mtprotoFakeTlsDomainHint": "新しいクライアントのシークレット生成に使う既定の FakeTLS ドメイン。クライアントごとに別のドメインを使用できます。",
"mtgThrottleMaxConnections": "最大接続数",
"mtgThrottleMaxConnectionsHint": "全ユーザーの同時接続数を公平配分で制限します。0 で無効。",
"mtgAdTag": "広告タグ(スポンサーチャンネル)",
"mtgAdTagHint": "Telegram のプロキシ登録で取得する任意の 32 文字の 16 進数タグ。設定すると、クライアントは Telegram の中間プロキシ経由でルーティングされ、スポンサーチャンネルがチャット一覧の先頭に表示されます。到達可能なパブリック IP が必要です。下で設定するか、mtg に自動検出させてください。",
"mtgAdTagInvalid": "広告タグは正確に 32 文字の 16 進数である必要があります。",
"mtgPublicIpv4": "パブリック IPv4",
"mtgPublicIpv6": "パブリック IPv6",
"mtgPublicIpHint": "広告タグの中間プロキシが使用する、このサーバーの到達可能なパブリックアドレス。空欄にすると mtg が自動検出します。",
"visionTestseed": "Vision testseed",
"version": "バージョン",
"udpIdleTimeout": "UDP idle timeout (秒)",
+6
View File
@@ -546,6 +546,12 @@
"mtprotoFakeTlsDomainHint": "Domínio FakeTLS padrão usado para gerar o segredo de um novo cliente. Cada cliente pode usar seu próprio domínio.",
"mtgThrottleMaxConnections": "Conexões máximas",
"mtgThrottleMaxConnectionsHint": "Limita conexões simultâneas de todos os usuários com distribuição justa. 0 desativa o limite.",
"mtgAdTag": "Ad-tag (canal patrocinado)",
"mtgAdTagHint": "Tag hexadecimal opcional de 32 caracteres do registro de proxy do Telegram. Quando definida, os clientes são roteados pelos proxies intermediários do Telegram e um canal patrocinado aparece no topo da lista de conversas. Requer um IP público acessível - defina um abaixo ou deixe o mtg detectá-lo automaticamente.",
"mtgAdTagInvalid": "A ad-tag deve ter exatamente 32 caracteres hexadecimais.",
"mtgPublicIpv4": "IPv4 público",
"mtgPublicIpv6": "IPv6 público",
"mtgPublicIpHint": "O endereço público acessível deste servidor, usado pelo proxy intermediário da ad-tag. Deixe em branco para o mtg detectá-lo automaticamente.",
"visionTestseed": "Vision testseed",
"version": "Versão",
"udpIdleTimeout": "UDP idle timeout (s)",
+6
View File
@@ -546,6 +546,12 @@
"mtprotoFakeTlsDomainHint": "Домен FakeTLS по умолчанию для генерации секрета нового клиента. Каждый клиент может использовать свой домен.",
"mtgThrottleMaxConnections": "Макс. подключений",
"mtgThrottleMaxConnectionsHint": "Ограничение одновременных подключений всех пользователей по справедливому распределению. 0 — отключено.",
"mtgAdTag": "Рекламный тег (спонсорский канал)",
"mtgAdTagHint": "Необязательный шестнадцатеричный тег из 32 символов, получаемый при регистрации прокси в Telegram. Если задан, клиенты маршрутизируются через промежуточные прокси Telegram, и спонсорский канал появляется вверху списка чатов. Требуется доступный публичный IP - укажите его ниже или позвольте mtg определить его автоматически.",
"mtgAdTagInvalid": "Рекламный тег должен содержать ровно 32 шестнадцатеричных символа.",
"mtgPublicIpv4": "Публичный IPv4",
"mtgPublicIpv6": "Публичный IPv6",
"mtgPublicIpHint": "Доступный публичный адрес этого сервера, используемый промежуточным прокси рекламного тега. Оставьте пустым, чтобы mtg определил его автоматически.",
"visionTestseed": "Vision testseed",
"version": "Версия",
"udpIdleTimeout": "UDP idle timeout (с)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "Yeni bir istemcinin sırrını oluştururken kullanılan varsayılan FakeTLS alan adı. Her istemci kendi alan adını kullanabilir.",
"mtgThrottleMaxConnections": "Maks. bağlantı",
"mtgThrottleMaxConnectionsHint": "Tüm kullanıcıların eşzamanlı bağlantılarını adil paylaşımla sınırlar. 0 devre dışı bırakır.",
"mtgAdTag": "Reklam etiketi (sponsorlu kanal)",
"mtgAdTagHint": "Telegram proxy kaydından alınan isteğe bağlı 32 karakterlik onaltılık etiket. Ayarlandığında istemciler Telegram ara proxy'leri üzerinden yönlendirilir ve sohbet listelerinin en üstünde sponsorlu bir kanal görünür. Erişilebilir bir genel IP gerektirir - aşağıdan ayarlayın veya mtg'nin otomatik algılamasına izin verin.",
"mtgAdTagInvalid": "Reklam etiketi tam olarak 32 onaltılık karakter olmalıdır.",
"mtgPublicIpv4": "Genel IPv4",
"mtgPublicIpv6": "Genel IPv6",
"mtgPublicIpHint": "Bu sunucunun erişilebilir genel adresi; reklam etiketi ara proxy'si tarafından kullanılır. mtg'nin otomatik algılaması için boş bırakın.",
"visionTestseed": "Vision Testseed",
"version": "Sürüm",
"udpIdleTimeout": "UDP Idle Timeout (s)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "Домен FakeTLS за замовчуванням для генерації секрету нового клієнта. Кожен клієнт може використовувати власний домен.",
"mtgThrottleMaxConnections": "Макс. з'єднань",
"mtgThrottleMaxConnectionsHint": "Обмеження одночасних з'єднань усіх користувачів зі справедливим розподілом. 0 — вимкнено.",
"mtgAdTag": "Рекламний тег (спонсорський канал)",
"mtgAdTagHint": "Необовʼязковий шістнадцятковий тег із 32 символів, який видається під час реєстрації проксі в Telegram. Якщо задано, клієнти маршрутизуються через проміжні проксі Telegram, а спонсорський канал зʼявляється вгорі списку чатів. Потрібна доступна публічна IP-адреса - вкажіть її нижче або дозвольте mtg визначити її автоматично.",
"mtgAdTagInvalid": "Рекламний тег має містити рівно 32 шістнадцяткові символи.",
"mtgPublicIpv4": "Публічний IPv4",
"mtgPublicIpv6": "Публічний IPv6",
"mtgPublicIpHint": "Доступна публічна адреса цього сервера, яку використовує проміжний проксі рекламного тега. Залиште порожнім, щоб mtg визначив її автоматично.",
"visionTestseed": "Vision testseed",
"version": "Версія",
"udpIdleTimeout": "UDP idle timeout (с)",
+6
View File
@@ -546,6 +546,12 @@
"mtprotoFakeTlsDomainHint": "Tên miền FakeTLS mặc định dùng để tạo secret cho client mới. Mỗi client có thể dùng tên miền riêng.",
"mtgThrottleMaxConnections": "Số kết nối tối đa",
"mtgThrottleMaxConnectionsHint": "Giới hạn kết nối đồng thời của tất cả người dùng theo phân bổ công bằng. 0 để tắt.",
"mtgAdTag": "Ad-tag (kênh tài trợ)",
"mtgAdTagHint": "Thẻ thập lục phân 32 ký tự tùy chọn từ đăng ký proxy của Telegram. Khi được đặt, client sẽ được định tuyến qua các proxy trung gian của Telegram và một kênh tài trợ xuất hiện ở đầu danh sách trò chuyện. Cần một IP công khai có thể truy cập - đặt bên dưới hoặc để mtg tự phát hiện.",
"mtgAdTagInvalid": "Ad-tag phải có đúng 32 ký tự thập lục phân.",
"mtgPublicIpv4": "IPv4 công khai",
"mtgPublicIpv6": "IPv6 công khai",
"mtgPublicIpHint": "Địa chỉ công khai có thể truy cập của máy chủ này, được proxy trung gian ad-tag sử dụng. Để trống để mtg tự phát hiện.",
"visionTestseed": "Vision testseed",
"version": "Phiên bản",
"udpIdleTimeout": "UDP idle timeout (s)",
+6
View File
@@ -545,6 +545,12 @@
"mtprotoFakeTlsDomainHint": "生成新客户端密钥时使用的默认 FakeTLS 域名。每个客户端可使用各自的域名。",
"mtgThrottleMaxConnections": "最大连接数",
"mtgThrottleMaxConnectionsHint": "按公平分配限制所有用户的并发连接数。0 表示不限制。",
"mtgAdTag": "广告标签(赞助频道)",
"mtgAdTagHint": "可选的 32 位十六进制标签,从 Telegram 代理注册处获取。设置后,客户端将通过 Telegram 中间代理路由,赞助频道会显示在其聊天列表顶部。需要可访问的公网 IP —— 在下方设置,或让 mtg 自动检测。",
"mtgAdTagInvalid": "广告标签必须为 32 位十六进制字符。",
"mtgPublicIpv4": "公网 IPv4",
"mtgPublicIpv6": "公网 IPv6",
"mtgPublicIpHint": "本服务器可访问的公网地址,供广告标签的中间代理使用。留空则由 mtg 自动检测。",
"visionTestseed": "Vision testseed",
"version": "版本",
"udpIdleTimeout": "UDP 空闲超时 (s)",
+6
View File
@@ -525,6 +525,12 @@
"mtprotoFakeTlsDomainHint": "產生新用戶端金鑰時使用的預設 FakeTLS 網域。每個用戶端可使用各自的網域。",
"mtgThrottleMaxConnections": "最大連線數",
"mtgThrottleMaxConnectionsHint": "以公平分配限制所有使用者的並行連線數。0 表示不限制。",
"mtgAdTag": "廣告標籤(贊助頻道)",
"mtgAdTagHint": "選填的 32 位十六進位標籤,從 Telegram 代理註冊處取得。設定後,用戶端會透過 Telegram 中間代理路由,贊助頻道會顯示在其聊天清單頂端。需要可存取的公網 IP —— 在下方設定,或讓 mtg 自動偵測。",
"mtgAdTagInvalid": "廣告標籤必須為 32 位十六進位字元。",
"mtgPublicIpv4": "公網 IPv4",
"mtgPublicIpv6": "公網 IPv6",
"mtgPublicIpHint": "本伺服器可存取的公網位址,供廣告標籤的中間代理使用。留空則由 mtg 自動偵測。",
"visionTestseed": "Vision testseed",
"version": "版本",
"udpIdleTimeout": "UDP 閒置逾時 (s)",