Преглед изворни кода

feat(mtproto): adopt dolonet/mtg-multi and make MTProto inbounds multi-client

Replace the upstream 9seconds/mtg sidecar with the dolonet/mtg-multi fork so a single MTProto inbound can serve many per-user secrets. Each panel client is now one named FakeTLS secret in the fork's [secrets] section: clients are first-class (attach/detach, limits, expiry, per-client tg:// links) exactly like every other protocol, mirroring the WireGuard multi-client model. Per-client traffic and online status come from the fork's /stats JSON API (its Prometheus output has no per-user label), fed into the existing email-keyed client_traffics accumulator; an optional throttle caps concurrent connections. A one-time seeder converts each legacy single-secret inbound into a one-client inbound.

The fork ships only linux/darwin amd64/arm64 binaries but is pure Go, so provisioning builds it from source for every supported platform (release.yml, DockerInit.sh) while keeping the panel-expected mtg-<os>-<arch> filename and the 'run' verb, so process.go is untouched. Also fixes a pre-existing update.sh gap that never renamed the mtg binary for armv6/armv7 updates.
MHSanaei пре 13 часа
родитељ
комит
d97bd8643e
54 измењених фајлова са 1158 додато и 451 уклоњено
  1. 15 13
      .github/workflows/release.yml
  2. 5 3
      CLAUDE.md
  3. 5 11
      DockerInit.sh
  4. 4 2
      docs/architecture.md
  5. 13 0
      frontend/public/openapi.json
  6. 3 0
      frontend/src/generated/examples.ts
  7. 12 0
      frontend/src/generated/schemas.ts
  8. 3 0
      frontend/src/generated/types.ts
  9. 3 0
      frontend/src/generated/zod.ts
  10. 11 18
      frontend/src/lib/xray/inbound-defaults.ts
  11. 2 0
      frontend/src/lib/xray/inbound-form-adapter.ts
  12. 12 7
      frontend/src/lib/xray/inbound-link.ts
  13. 7 1
      frontend/src/lib/xray/link-label.tsx
  14. 48 1
      frontend/src/pages/clients/ClientFormModal.tsx
  15. 14 26
      frontend/src/pages/inbounds/form/protocols/mtproto.tsx
  16. 0 20
      frontend/src/pages/inbounds/info/InboundInfoModal.tsx
  17. 1 0
      frontend/src/pages/inbounds/info/helpers.ts
  18. 1 0
      frontend/src/pages/inbounds/list/helpers.ts
  19. 2 0
      frontend/src/schemas/client.ts
  20. 29 6
      frontend/src/schemas/protocols/inbound/mtproto.ts
  21. 29 2
      frontend/src/test/__snapshots__/protocols.test.ts.snap
  22. 7 1
      frontend/src/test/golden/fixtures/inbound/mtproto-basic.json
  23. 8 1
      frontend/src/test/golden/fixtures/inbound/mtproto-domain-fronting.json
  24. 14 0
      frontend/src/test/link-label.test.ts
  25. 41 0
      frontend/src/test/mtproto-clients-link.test.ts
  26. 130 1
      internal/database/db.go
  27. 78 0
      internal/database/model/model.go
  28. 37 0
      internal/database/model/model_mtproto_test.go
  29. 158 162
      internal/mtproto/manager.go
  30. 52 86
      internal/mtproto/manager_mutation_test.go
  31. 68 47
      internal/mtproto/manager_test.go
  32. 5 4
      internal/mtproto/process.go
  33. 9 15
      internal/sub/service.go
  34. 110 0
      internal/sub/service_mtproto_test.go
  35. 36 22
      internal/web/job/mtproto_job.go
  36. 26 0
      internal/web/service/client_crud.go
  37. 6 0
      internal/web/service/client_inbound_apply.go
  38. 28 2
      internal/web/service/inbound.go
  39. 3 0
      internal/web/service/inbound_clients.go
  40. 49 0
      internal/web/service/inbound_mtproto_test.go
  41. 5 0
      internal/web/translation/ar-EG.json
  42. 5 0
      internal/web/translation/en-US.json
  43. 5 0
      internal/web/translation/es-ES.json
  44. 5 0
      internal/web/translation/fa-IR.json
  45. 5 0
      internal/web/translation/id-ID.json
  46. 5 0
      internal/web/translation/ja-JP.json
  47. 5 0
      internal/web/translation/pt-BR.json
  48. 5 0
      internal/web/translation/ru-RU.json
  49. 5 0
      internal/web/translation/tr-TR.json
  50. 5 0
      internal/web/translation/uk-UA.json
  51. 5 0
      internal/web/translation/vi-VN.json
  52. 5 0
      internal/web/translation/zh-CN.json
  53. 5 0
      internal/web/translation/zh-TW.json
  54. 9 0
      update.sh

+ 15 - 13
.github/workflows/release.yml

@@ -156,14 +156,14 @@ jobs:
           wget -q -O geoip_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat
           wget -q -O geosite_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat
           mv xray xray-linux-${{ matrix.platform }}
-          # mtg (MTProto sidecar) - only for arches mtg publishes
-          MTG_VER="2.2.8"
+          # mtg-multi (MTProto sidecar) is pure Go, so build it from source for the
+          # target arch (GOOS/GOARCH/GOARM are already exported above). Its release
+          # binaries only cover linux/darwin amd64/arm64; skip s390x/armv5 as before.
+          MTG_MULTI_VER="v1.11.0"
           case "${{ matrix.platform }}" in
             amd64|arm64|armv7|armv6|386)
-              wget -q "https://github.com/9seconds/mtg/releases/download/v${MTG_VER}/mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
-              tar -xzf "mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
-              mv "mtg-${MTG_VER}-linux-${{ matrix.platform }}/mtg" "mtg-linux-${{ matrix.platform }}" 2>/dev/null || mv mtg "mtg-linux-${{ matrix.platform }}"
-              rm -rf "mtg-${MTG_VER}-linux-${{ matrix.platform }}" "mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
+              CGO_ENABLED=0 GOBIN="$(pwd)" go install -trimpath -ldflags "-s -w" "github.com/dolonet/mtg-multi@${MTG_MULTI_VER}"
+              mv mtg-multi "mtg-linux-${{ matrix.platform }}"
               ;;
           esac
           cd ../..
@@ -280,13 +280,15 @@ jobs:
           Invoke-WebRequest -Uri "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "geosite_RU.dat"
           Rename-Item xray.exe xray-windows-amd64.exe
 
-          # Download mtg (MTProto sidecar) for Windows
-          $MTG_VER = "2.2.8"
-          Invoke-WebRequest -Uri "https://github.com/9seconds/mtg/releases/download/v$MTG_VER/mtg-$MTG_VER-windows-amd64.zip" -OutFile "mtg-windows-amd64.zip"
-          Expand-Archive -Path "mtg-windows-amd64.zip" -DestinationPath "mtg-tmp"
-          $mtgExe = Get-ChildItem -Path "mtg-tmp" -Recurse -Filter "mtg.exe" | Select-Object -First 1
-          Move-Item $mtgExe.FullName "mtg-windows-amd64.exe"
-          Remove-Item "mtg-windows-amd64.zip", "mtg-tmp" -Recurse -Force
+          # mtg-multi (MTProto sidecar) is pure Go; build it from source since the
+          # fork publishes no Windows release binary.
+          $MTG_MULTI_VER = "v1.11.0"
+          $env:CGO_ENABLED = "0"
+          $env:GOOS = "windows"
+          $env:GOARCH = "amd64"
+          $env:GOBIN = (Get-Location).Path
+          go install -trimpath -ldflags "-s -w" "github.com/dolonet/mtg-multi@$MTG_MULTI_VER"
+          Move-Item "mtg-multi.exe" "mtg-windows-amd64.exe"
 
           cd ..
           Copy-Item -Path ..\windows_files\* -Destination . -Recurse

+ 5 - 3
CLAUDE.md

@@ -11,8 +11,10 @@ file locations when it can answer in one hop.
 - Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
   Runs Xray-core as a managed child process (`internal/xray/process.go`) and
   imports `github.com/xtls/xray-core` for config types + gRPC stats/handler/router
-  API. MTProto inbounds run a second managed child — the `mtg` binary
-  (`internal/mtproto/`) — outside Xray.
+  API. MTProto inbounds run a second managed child — the `mtg-multi` binary
+  (`github.com/dolonet/mtg-multi`, a multi-secret fork built from source;
+  `internal/mtproto/`) — outside Xray, one process per inbound serving each
+  client's FakeTLS secret via the fork's `[secrets]` section.
 - Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux; the executable dir on
   Windows), PostgreSQL optional (`XUI_DB_TYPE` / `XUI_DB_DSN`). The CGo SQLite
   driver (`mattn/go-sqlite3`) needs a C compiler — `CGO_ENABLED=0` builds fail.
@@ -27,7 +29,7 @@ file locations when it can answer in one hop.
   Client, Setting, User), inbound Protocol enum, AutoMigrate + hand-written
   migrations in `db.go`.
 - `internal/xray/` — Xray child-process lifecycle, config generation, gRPC API.
-- `internal/mtproto/` — MTProto inbounds via the bundled `mtg` binary.
+- `internal/mtproto/` — MTProto inbounds via the bundled `mtg-multi` binary.
 - `internal/sub/` — subscription server (raw / JSON / Clash).
 - `internal/eventbus/` — in-process pub/sub (outbound/node health, xray.crash,
   cpu.high, memory.high, login.attempt).

+ 5 - 11
DockerInit.sh

@@ -3,45 +3,39 @@ case $1 in
     amd64)
         ARCH="64"
         FNAME="amd64"
-        MTG_ARCH="amd64"
         ;;
     i386)
         ARCH="32"
         FNAME="i386"
-        MTG_ARCH="386"
         ;;
     armv8 | arm64 | aarch64)
         ARCH="arm64-v8a"
         FNAME="arm64"
-        MTG_ARCH="arm64"
         ;;
     armv7 | arm | arm32)
         ARCH="arm32-v7a"
         FNAME="arm32"
-        MTG_ARCH="armv7"
         ;;
     armv6)
         ARCH="arm32-v6"
         FNAME="armv6"
-        MTG_ARCH="armv6"
         ;;
     *)
         ARCH="64"
         FNAME="amd64"
-        MTG_ARCH="amd64"
         ;;
 esac
-MTG_VER="2.2.8"
+MTG_MULTI_VER="v1.11.0"
 mkdir -p build/bin
 cd build/bin
 curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.6.27/Xray-linux-${ARCH}.zip"
 unzip "Xray-linux-${ARCH}.zip"
 rm -f "Xray-linux-${ARCH}.zip" geoip.dat geosite.dat
 mv xray "xray-linux-${FNAME}"
-curl -sfLRO "https://github.com/9seconds/mtg/releases/download/v${MTG_VER}/mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
-tar -xzf "mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
-mv "mtg-${MTG_VER}-linux-${MTG_ARCH}/mtg" "mtg-linux-${FNAME}" 2>/dev/null || mv mtg "mtg-linux-${FNAME}"
-rm -rf "mtg-${MTG_VER}-linux-${MTG_ARCH}" "mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
+# mtg-multi (MTProto sidecar) is pure Go, so build it from source for the target
+# arch — its release binaries only cover linux/darwin amd64/arm64.
+CGO_ENABLED=0 GOBIN="$(pwd)" go install -trimpath -ldflags "-s -w" "github.com/dolonet/mtg-multi@${MTG_MULTI_VER}"
+mv mtg-multi "mtg-linux-${FNAME}"
 chmod +x "mtg-linux-${FNAME}"
 curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
 curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat

+ 4 - 2
docs/architecture.md

@@ -20,7 +20,9 @@ WebSocket API. A React SPA (built by Vite, embedded into the Go binary) is the U
 separate HTTP server serves **subscription links** to end users.
 
 The panel supervises **two managed child processes**: Xray-core itself and — when MTProto
-inbounds exist — the `mtg` Telegram-proxy binary (`internal/mtproto/`).
+inbounds exist — the `mtg-multi` Telegram-proxy binary (`github.com/dolonet/mtg-multi`, a
+multi-secret fork built from source; `internal/mtproto/`). One process per inbound serves
+every attached client's FakeTLS secret through the fork's `[secrets]` section.
 
 Servers and processes, all launched from `main.go`:
 
@@ -29,7 +31,7 @@ Servers and processes, all launched from `main.go`:
 | **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
 | **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
 | **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
-| **mtg** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds | per inbound |
+| **mtg-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | per inbound |
 
 Two key ideas that explain most of the complexity:
 

+ 13 - 0
frontend/public/openapi.json

@@ -1167,6 +1167,11 @@
             "description": "VLESS simple reverse proxy settings",
             "nullable": true
           },
+          "secret": {
+            "description": "MTProto FakeTLS secret",
+            "example": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d",
+            "type": "string"
+          },
           "security": {
             "description": "Security method (e.g., \"auto\", \"aes-128-gcm\")",
             "type": "string"
@@ -1279,6 +1284,9 @@
             "type": "integer"
           },
           "reverse": {},
+          "secret": {
+            "type": "string"
+          },
           "security": {
             "type": "string"
           },
@@ -1317,6 +1325,7 @@
           "publicKey",
           "reset",
           "reverse",
+          "secret",
           "security",
           "subId",
           "tgId",
@@ -1835,6 +1844,9 @@
           "listen": {
             "type": "string"
           },
+          "mtprotoDomain": {
+            "type": "string"
+          },
           "nodeAddress": {
             "description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
             "type": "string"
@@ -2803,6 +2815,7 @@
                       "enable": true,
                       "id": 1,
                       "listen": "",
+                      "mtprotoDomain": "",
                       "nodeAddress": "",
                       "nodeId": null,
                       "port": 443,

+ 3 - 0
frontend/src/generated/examples.ts

@@ -234,6 +234,7 @@ export const EXAMPLES: Record<string, unknown> = {
     "publicKey": "",
     "reset": 0,
     "reverse": null,
+    "secret": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d",
     "security": "",
     "subId": "",
     "tgId": 0,
@@ -265,6 +266,7 @@ export const EXAMPLES: Record<string, unknown> = {
     "publicKey": "",
     "reset": 0,
     "reverse": null,
+    "secret": "",
     "security": "",
     "subId": "",
     "tgId": 0,
@@ -402,6 +404,7 @@ export const EXAMPLES: Record<string, unknown> = {
     "enable": true,
     "id": 1,
     "listen": "",
+    "mtprotoDomain": "",
     "nodeAddress": "",
     "nodeId": null,
     "port": 443,

+ 12 - 0
frontend/src/generated/schemas.ts

@@ -1141,6 +1141,11 @@ export const SCHEMAS: Record<string, unknown> = {
         "description": "VLESS simple reverse proxy settings",
         "nullable": true
       },
+      "secret": {
+        "description": "MTProto FakeTLS secret",
+        "example": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d",
+        "type": "string"
+      },
       "security": {
         "description": "Security method (e.g., \"auto\", \"aes-128-gcm\")",
         "type": "string"
@@ -1253,6 +1258,9 @@ export const SCHEMAS: Record<string, unknown> = {
         "type": "integer"
       },
       "reverse": {},
+      "secret": {
+        "type": "string"
+      },
       "security": {
         "type": "string"
       },
@@ -1291,6 +1299,7 @@ export const SCHEMAS: Record<string, unknown> = {
       "publicKey",
       "reset",
       "reverse",
+      "secret",
       "security",
       "subId",
       "tgId",
@@ -1809,6 +1818,9 @@ export const SCHEMAS: Record<string, unknown> = {
       "listen": {
         "type": "string"
       },
+      "mtprotoDomain": {
+        "type": "string"
+      },
       "nodeAddress": {
         "description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
         "type": "string"

+ 3 - 0
frontend/src/generated/types.ts

@@ -242,6 +242,7 @@ export interface Client {
   publicKey?: string;
   reset: number;
   reverse?: ClientReverse | null;
+  secret?: string;
   security: string;
   subId: string;
   tgId: number;
@@ -275,6 +276,7 @@ export interface ClientRecord {
   publicKey: string;
   reset: number;
   reverse: unknown;
+  secret: string;
   security: string;
   subId: string;
   tgId: number;
@@ -396,6 +398,7 @@ export interface InboundOption {
   enable: boolean;
   id: number;
   listen?: string;
+  mtprotoDomain?: string;
   nodeAddress?: string;
   nodeId?: number | null;
   port: number;

+ 3 - 0
frontend/src/generated/zod.ts

@@ -258,6 +258,7 @@ export const ClientSchema = z.object({
   publicKey: z.string().optional(),
   reset: z.number().int(),
   reverse: z.lazy(() => ClientReverseSchema).nullable().optional(),
+  secret: z.string().optional(),
   security: z.string(),
   subId: z.string(),
   tgId: z.number().int(),
@@ -293,6 +294,7 @@ export const ClientRecordSchema = z.object({
   publicKey: z.string(),
   reset: z.number().int(),
   reverse: z.unknown(),
+  secret: z.string(),
   security: z.string(),
   subId: z.string(),
   tgId: z.number().int(),
@@ -423,6 +425,7 @@ export const InboundOptionSchema = z.object({
   enable: z.boolean(),
   id: z.number().int(),
   listen: z.string().optional(),
+  mtprotoDomain: z.string().optional(),
   nodeAddress: z.string().optional(),
   nodeId: z.number().int().nullable().optional(),
   port: z.number().int(),

+ 11 - 18
frontend/src/lib/xray/inbound-defaults.ts

@@ -3,7 +3,7 @@ import { RandomUtil, Wireguard } from '@/utils';
 import type { HttpInboundSettings } from '@/schemas/protocols/inbound/http';
 import type { HysteriaClient, HysteriaInboundSettings } from '@/schemas/protocols/inbound/hysteria';
 import type { MixedInboundSettings } from '@/schemas/protocols/inbound/mixed';
-import type { MtprotoInboundSettings } from '@/schemas/protocols/inbound/mtproto';
+import type { MtprotoClient, MtprotoInboundSettings } from '@/schemas/protocols/inbound/mtproto';
 import type { ShadowsocksClient, ShadowsocksInboundSettings } from '@/schemas/protocols/inbound/shadowsocks';
 import type { TrojanClient, TrojanInboundSettings } from '@/schemas/protocols/inbound/trojan';
 import type { TunInboundSettings } from '@/schemas/protocols/inbound/tun';
@@ -216,26 +216,19 @@ export function generateMtprotoSecret(domain: string): string {
   return `ee${RandomUtil.randomSeq(32, { type: 'hex' })}${domainToHex(domain)}`;
 }
 
-// mtprotoSecretForDomain rewrites only the domain suffix of an existing secret,
-// preserving its 16-byte random middle when valid (generating one otherwise).
-// Mirrors the Go model.HealMtprotoSecret so editing the FakeTLS domain doesn't
-// needlessly rotate the secret's identity.
-export function mtprotoSecretForDomain(currentSecret: string, domain: string): string {
-  let body = currentSecret;
-  if (body.startsWith('ee') || body.startsWith('dd')) {
-    body = body.slice(2);
-  }
-  const middle = /^[0-9a-f]{32}/i.test(body)
-    ? body.slice(0, 32)
-    : RandomUtil.randomSeq(32, { type: 'hex' });
-  return `ee${middle}${domainToHex(domain)}`;
+export function createDefaultMtprotoInboundSettings(): MtprotoInboundSettings {
+  return {
+    fakeTlsDomain: 'www.cloudflare.com',
+    clients: [],
+  };
 }
 
-export function createDefaultMtprotoInboundSettings(): MtprotoInboundSettings {
-  const fakeTlsDomain = 'www.cloudflare.com';
+// createDefaultMtprotoClient seeds a new MTProto client with a fresh FakeTLS
+// secret fronting the given domain. Mirrors the WireGuard client default: the
+// backend re-derives the secret on save, so this is only for immediate display.
+export function createDefaultMtprotoClient(domain: string): Partial<MtprotoClient> {
   return {
-    fakeTlsDomain,
-    secret: generateMtprotoSecret(fakeTlsDomain),
+    secret: generateMtprotoSecret(domain || 'www.cloudflare.com'),
   };
 }
 

+ 2 - 0
frontend/src/lib/xray/inbound-form-adapter.ts

@@ -2,6 +2,7 @@ import type { InboundFormValues, ShareAddrStrategy, TrafficReset } from '@/schem
 import type { InboundSettings } from '@/schemas/protocols/inbound';
 import {
   HysteriaClientSchema,
+  MtprotoClientSchema,
   ShadowsocksClientSchema,
   TrojanClientSchema,
   VlessClientSchema,
@@ -238,6 +239,7 @@ function clientSchemaForProtocol(protocol: string): z.ZodType | null {
     case 'shadowsocks': return ShadowsocksClientSchema;
     case 'hysteria': return HysteriaClientSchema;
     case 'wireguard': return WireguardClientSchema;
+    case 'mtproto': return MtprotoClientSchema;
     default: return null;
   }
 }

+ 12 - 7
frontend/src/lib/xray/inbound-link.ts

@@ -778,18 +778,21 @@ export interface GenMtprotoLinkInput {
   inbound: Inbound;
   address: string;
   port?: number;
+  clientSecret?: string;
+  remark?: string;
 }
 
-// Builds a Telegram proxy deep link for an mtproto inbound:
+// Builds a per-client Telegram proxy deep link for an mtproto inbound from the
+// client's own FakeTLS secret.
 export function genMtprotoLink(input: GenMtprotoLinkInput): string {
-  const { inbound, address, port = inbound.port } = input;
+  const { inbound, address, port = inbound.port, clientSecret = '', remark = '' } = input;
   if (inbound.protocol !== 'mtproto') return '';
-  const secret = inbound.settings.secret ?? '';
-  if (secret.length === 0) return '';
+  if (clientSecret.length === 0) return '';
   const url = new URL('tg://proxy');
   url.searchParams.set('server', address);
   url.searchParams.set('port', String(port));
-  url.searchParams.set('secret', secret);
+  url.searchParams.set('secret', clientSecret);
+  if (remark) url.hash = encodeURIComponent(remark);
   return url.toString();
 }
 
@@ -1044,7 +1047,7 @@ export function preferPublicHost(browserHost: string, publicHost: string): strin
 // `this.clients` getter, which used isSSMultiUser to gate). Returns null
 // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
 // clients, and any protocol without a clients array.
-type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string; subId?: string };
+type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; secret?: string; email?: string; subId?: string };
 
 // Mirror of the Go subKey: the stable per-client identity spx derivation
 // keys on — subscription id first, unique email as the fallback.
@@ -1062,6 +1065,8 @@ export function getInboundClients(inbound: Inbound): ClientShape[] | null {
       return (inbound.settings.clients ?? []) as ClientShape[];
     case 'hysteria':
       return (inbound.settings.clients ?? []) as ClientShape[];
+    case 'mtproto':
+      return (inbound.settings.clients ?? []) as ClientShape[];
     case 'shadowsocks': {
       const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
       return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
@@ -1125,7 +1130,7 @@ export function genLink(input: GenLinkInput): string {
         externalProxy,
       });
     case 'mtproto':
-      return genMtprotoLink({ inbound, address, port });
+      return genMtprotoLink({ inbound, address, port, clientSecret: client.secret ?? '', remark });
     default:
       return '';
   }

+ 7 - 1
frontend/src/lib/xray/link-label.tsx

@@ -25,6 +25,7 @@ const PROTOCOL_LABELS: Record<string, string> = {
   hysteria: 'Hysteria',
   wireguard: 'WireGuard',
   wg: 'WireGuard',
+  tg: 'MTProto',
 };
 
 const PROTOCOL_COLORS: Record<string, string> = {
@@ -35,12 +36,14 @@ const PROTOCOL_COLORS: Record<string, string> = {
   Hysteria: 'magenta',
   Hysteria2: 'magenta',
   WireGuard: 'cyan',
+  MTProto: 'blue',
 };
 
 const SECURITY_COLORS: Record<string, string> = {
   TLS: 'green',
   XTLS: 'green',
   REALITY: 'purple',
+  FAKETLS: 'green',
 };
 
 const TRANSPORT_COLOR = 'gold';
@@ -83,10 +86,13 @@ export function parseLinkParts(link: string): LinkParts | null {
       const url = new URL(trimmed);
       network = url.searchParams.get('type') ?? '';
       security = url.searchParams.get('security') ?? '';
-      port = url.port;
+      /* tg://proxy links (mtproto) carry the port in a `port` query param, not
+         the URL authority, so fall back to it when there is no authority port. */
+      port = url.port || (url.searchParams.get('port') ?? '');
       const hash = url.hash.replace(/^#/, '');
       try { remark = decodeURIComponent(hash); } catch { remark = hash; }
     } catch { /* not URL-shaped, fall back to protocol only */ }
+    if (scheme === 'tg') security = 'FakeTLS';
   }
   if (security === 'none') security = '';
   return {

+ 48 - 1
frontend/src/pages/clients/ClientFormModal.tsx

@@ -24,6 +24,7 @@ import dayjs from 'dayjs';
 import type { Dayjs } from 'dayjs';
 import { HttpUtil, RandomUtil, Wireguard } from '@/utils';
 import { formatInboundLabel } from '@/lib/inbounds/label';
+import { generateMtprotoSecret } from '@/lib/xray/inbound-defaults';
 import { normalizeClientIps, type ClientIpInfo } from '@/lib/clients/ip-log';
 import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
 import { TLS_FLOW_CONTROL } from '@/schemas/primitives';
@@ -35,7 +36,7 @@ const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
 const VMESS_SECURITY_OPTIONS = ['auto', 'aes-128-gcm', 'chacha20-poly1305', 'none', 'zero'] as const;
 
 const MULTI_CLIENT_PROTOCOLS = new Set([
-  'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard',
+  'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard', 'mtproto',
 ]);
 
 const CLIENT_FORM_MODAL_Z_INDEX = 1000;
@@ -117,6 +118,7 @@ interface FormState {
   wgPublicKey: string;
   wgPreSharedKey: string;
   wgAllowedIPs: string;
+  secret: string;
 }
 
 function emptyForm(): FormState {
@@ -145,6 +147,7 @@ function emptyForm(): FormState {
     wgPublicKey: '',
     wgPreSharedKey: '',
     wgAllowedIPs: '',
+    secret: '',
   };
 }
 
@@ -249,6 +252,7 @@ export default function ClientFormModal({
         wgPublicKey: client.publicKey || '',
         wgPreSharedKey: client.preSharedKey || '',
         wgAllowedIPs: client.allowedIPs || '',
+        secret: client.secret || '',
       };
       if (et < 0) {
         next.delayedStart = true;
@@ -310,6 +314,22 @@ export default function ClientFormModal({
     return ids;
   }, [inbounds]);
 
+  const mtprotoIds = useMemo(() => {
+    const ids = new Set<number>();
+    for (const row of inbounds || []) {
+      if (row && row.protocol === 'mtproto') ids.add(row.id);
+    }
+    return ids;
+  }, [inbounds]);
+
+  const mtprotoDomain = useMemo(() => {
+    for (const id of form.inboundIds || []) {
+      const ib = (inbounds || []).find((row) => row.id === id);
+      if (ib?.protocol === 'mtproto' && ib.mtprotoDomain) return ib.mtprotoDomain;
+    }
+    return 'www.cloudflare.com';
+  }, [form.inboundIds, inbounds]);
+
   const ss2022Method = useMemo(() => {
     for (const id of form.inboundIds || []) {
       const ib = (inbounds || []).find((row) => row.id === id);
@@ -345,11 +365,20 @@ export default function ClientFormModal({
     [form.inboundIds, wireguardIds],
   );
 
+  const showMtproto = useMemo(
+    () => (form.inboundIds || []).some((id) => mtprotoIds.has(id)),
+    [form.inboundIds, mtprotoIds],
+  );
+
   function regenerateWireguardKeys() {
     const kp = Wireguard.generateKeypair();
     setForm((prev) => ({ ...prev, wgPrivateKey: kp.privateKey, wgPublicKey: kp.publicKey }));
   }
 
+  function regenerateMtprotoSecret() {
+    update('secret', generateMtprotoSecret(mtprotoDomain));
+  }
+
   useEffect(() => {
     if (!showFlow && form.flow) {
 
@@ -373,6 +402,12 @@ export default function ClientFormModal({
     ));
   }, [ss2022Method]);
 
+  useEffect(() => {
+    if (showMtproto && !form.secret) {
+      update('secret', generateMtprotoSecret(mtprotoDomain));
+    }
+  }, [showMtproto, form.secret, mtprotoDomain]);
+
   const inboundOptions = useMemo(
     () => (inbounds || [])
       .filter((ib) => MULTI_CLIENT_PROTOCOLS.has(ib.protocol || ''))
@@ -502,6 +537,10 @@ export default function ClientFormModal({
       }
     }
 
+    if (showMtproto) {
+      clientPayload.secret = form.secret;
+    }
+
     const externalLinks: ExternalLinkInput[] = form.externalLinks
       .map((r) => ({ kind: r.kind, value: r.value.trim(), remark: '' }))
       .filter((r) => r.value !== '');
@@ -822,6 +861,14 @@ export default function ClientFormModal({
                         </Form.Item>
                       </>
                     )}
+                    {showMtproto && (
+                      <Form.Item label={t('pages.clients.mtprotoSecret')} extra={t('pages.clients.mtprotoSecretHint')}>
+                        <Space.Compact style={{ display: 'flex' }}>
+                          <Input value={form.secret} style={{ flex: 1 }} onChange={(e) => update('secret', e.target.value)} />
+                          <Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={regenerateMtprotoSecret} />
+                        </Space.Compact>
+                      </Form.Item>
+                    )}
                   </>
                 ),
               },

+ 14 - 26
frontend/src/pages/inbounds/form/protocols/mtproto.tsx

@@ -1,8 +1,6 @@
 import { useTranslation } from 'react-i18next';
-import { Button, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
-import { ReloadOutlined } from '@ant-design/icons';
+import { Form, Input, InputNumber, Select, Switch } from 'antd';
 
-import { generateMtprotoSecret, mtprotoSecretForDomain } from '@/lib/xray/inbound-defaults';
 import { useOutboundTags } from '@/api/queries/useOutboundTags';
 
 export default function MtprotoFields() {
@@ -12,29 +10,12 @@ export default function MtprotoFields() {
   const { data: outboundTags } = useOutboundTags();
   return (
     <>
-      <Form.Item name={['settings', 'fakeTlsDomain']} label={t('pages.inbounds.form.fakeTlsDomain')}>
-        <Input
-          placeholder="www.cloudflare.com"
-          onChange={(e) => {
-            const current = (form.getFieldValue(['settings', 'secret']) as string) ?? '';
-            form.setFieldValue(['settings', 'secret'], mtprotoSecretForDomain(current, e.target.value));
-          }}
-        />
-      </Form.Item>
-      <Form.Item label={t('pages.inbounds.form.mtprotoSecret')}>
-        <Space.Compact block>
-          <Form.Item name={['settings', 'secret']} noStyle>
-            <Input readOnly style={{ width: 'calc(100% - 32px)' }} />
-          </Form.Item>
-          <Button
-            aria-label={t('regenerate')}
-            icon={<ReloadOutlined />}
-            onClick={() => {
-              const domain = form.getFieldValue(['settings', 'fakeTlsDomain']);
-              form.setFieldValue(['settings', 'secret'], generateMtprotoSecret(domain as string));
-            }}
-          />
-        </Space.Compact>
+      <Form.Item
+        name={['settings', 'fakeTlsDomain']}
+        label={t('pages.inbounds.form.fakeTlsDomain')}
+        tooltip={t('pages.inbounds.form.mtprotoFakeTlsDomainHint')}
+      >
+        <Input placeholder="www.cloudflare.com" />
       </Form.Item>
       <Form.Item
         name={['settings', 'domainFronting', 'ip']}
@@ -75,6 +56,13 @@ export default function MtprotoFields() {
       <Form.Item name={['settings', 'debug']} label={t('pages.inbounds.form.mtgDebug')} valuePropName="checked">
         <Switch />
       </Form.Item>
+      <Form.Item
+        name={['settings', 'throttleMaxConnections']}
+        label={t('pages.inbounds.form.mtgThrottleMaxConnections')}
+        tooltip={t('pages.inbounds.form.mtgThrottleMaxConnectionsHint')}
+      >
+        <InputNumber min={0} placeholder="0" style={{ width: '100%' }} />
+      </Form.Item>
       <Form.Item
         name={['settings', 'routeThroughXray']}
         label={t('pages.inbounds.form.mtgRouteThroughXray')}

+ 0 - 20
frontend/src/pages/inbounds/info/InboundInfoModal.tsx

@@ -633,15 +633,6 @@ export default function InboundInfoModal({
             <dt>{t('pages.inbounds.form.fakeTlsDomain')}</dt>
             <dd><Tag color="green" className="value-tag">{inbound.settings.fakeTlsDomain as string}</Tag></dd>
           </div>
-          <div className="info-row">
-            <dt>{t('pages.inbounds.form.mtprotoSecret')}</dt>
-            <dd className="value-block">
-              <code className="value-code">{inbound.settings.secret as string}</code>
-              <Tooltip title={t('copy')}>
-                <Button size="small" className="value-copy" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyText(inbound.settings.secret as string, t)} />
-              </Tooltip>
-            </dd>
-          </div>
           {(() => {
             const s = inbound.settings;
             const df = s.domainFronting as { ip?: string; port?: number; proxyProtocol?: boolean } | undefined;
@@ -683,17 +674,6 @@ export default function InboundInfoModal({
               </>
             );
           })()}
-          {links.length > 0 && (
-            <div className="info-row">
-              <dt>{t('pages.inbounds.copyLink')}</dt>
-              <dd className="value-block">
-                <code className="value-code">{links[0].link}</code>
-                <Tooltip title={t('copy')}>
-                  <Button size="small" className="value-copy" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyText(links[0].link, t)} />
-                </Tooltip>
-              </dd>
-            </div>
-          )}
         </dl>
       )}
 

+ 1 - 0
frontend/src/pages/inbounds/info/helpers.ts

@@ -16,6 +16,7 @@ const LINK_PROTOCOLS: ReadonlySet<string> = new Set([
   Protocols.TROJAN,
   Protocols.SHADOWSOCKS,
   Protocols.HYSTERIA,
+  Protocols.MTPROTO,
 ]);
 
 export function hasShareLink(protocol: string): boolean {

+ 1 - 0
frontend/src/pages/inbounds/list/helpers.ts

@@ -72,6 +72,7 @@ export function isInboundMultiUser(record: { protocol: string; settings: unknown
     case 'vless':
     case 'trojan':
     case 'hysteria':
+    case 'mtproto':
       return true;
     case 'shadowsocks':
       return isSSMultiUser({ protocol: 'shadowsocks', settings: readSettings(record.settings) });

+ 2 - 0
frontend/src/schemas/client.ts

@@ -37,6 +37,7 @@ export const ClientRecordSchema = z.object({
   allowedIPs: z.string().optional(),
   preSharedKey: z.string().optional(),
   keepAlive: z.number().optional(),
+  secret: z.string().optional(),
   createdAt: z.number().optional(),
   updatedAt: z.number().optional(),
 }).loose();
@@ -52,6 +53,7 @@ export const InboundOptionSchema = z.object({
   wgPublicKey: z.string().optional(),
   wgMtu: z.number().optional(),
   wgDns: z.string().optional(),
+  mtprotoDomain: z.string().optional(),
   // Hosting node id; absent/null for this panel's own inbounds (#4997).
   nodeId: z.number().nullable().optional(),
   // Share-host resolution inputs, mirroring the backend resolveInboundAddress so

+ 29 - 6
frontend/src/schemas/protocols/inbound/mtproto.ts

@@ -10,18 +10,41 @@ export const MtprotoDomainFrontingSchema = z.object({
 });
 export type MtprotoDomainFronting = z.infer<typeof MtprotoDomainFrontingSchema>;
 
-// MTProto (Telegram) inbound. Served by an mtg sidecar process, not Xray, so
-// it has no clients and no stream settings. `secret` is the FakeTLS secret
-// (ee-prefixed); the backend rebuilds it to match `fakeTlsDomain` on save.
-// The remaining fields map to optional mtg config knobs and are written to the
-// generated mtg.toml only when set.
+// An MTProto (Telegram) inbound client (multi-client model). Each client is one
+// named FakeTLS secret the mtg-multi sidecar serves through its [secrets]
+// section; `secret` is the ee-prefixed FakeTLS secret whose trailing domain the
+// backend rebuilds on save. `fakeTlsDomain` is stored on the inbound as the
+// default domain used when generating a new client's secret.
+export const MtprotoClientSchema = z.object({
+  secret: z.string().default(''),
+  email: z.string().min(1),
+  limitIp: z.number().int().min(0).default(0),
+  totalGB: z.number().int().min(0).default(0),
+  expiryTime: z.number().int().default(0),
+  enable: z.boolean().default(true),
+  tgId: z.union([z.number(), z.string()]).transform((v) => Number(v) || 0).default(0),
+  subId: z.string().default(''),
+  comment: z.string().default(''),
+  reset: z.number().int().min(0).default(0),
+  created_at: z.number().int().optional(),
+  updated_at: z.number().int().optional(),
+});
+export type MtprotoClient = z.infer<typeof MtprotoClientSchema>;
+
+// MTProto (Telegram) inbound. Served by an mtg-multi sidecar process, not Xray,
+// so it has no stream settings. Each client carries its own FakeTLS secret and
+// is served on the shared inbound port. The remaining fields map to optional mtg
+// config knobs and are written to the generated mtg config only when set.
 export const MtprotoInboundSettingsSchema = z.object({
   fakeTlsDomain: z.string().default('www.cloudflare.com'),
-  secret: z.string().default(''),
+  clients: z.array(MtprotoClientSchema).default([]),
   proxyProtocolListener: z.boolean().optional(),
   preferIp: z.enum(['prefer-ipv6', 'prefer-ipv4', 'only-ipv6', 'only-ipv4']).optional(),
   debug: z.boolean().optional(),
   domainFronting: MtprotoDomainFrontingSchema.optional(),
+  // Caps concurrent connections across all users with a fair-share algorithm;
+  // 0 or unset disables throttling.
+  throttleMaxConnections: z.number().int().min(0).optional(),
   // When set, the mtg sidecar dials Telegram through a loopback SOCKS bridge in
   // the Xray config so the egress obeys routing rules. `outboundTag` optionally
   // forces that traffic out a specific outbound/balancer. `routeXrayPort` is the

+ 29 - 2
frontend/src/test/__snapshots__/protocols.test.ts.snap

@@ -63,8 +63,21 @@ exports[`InboundSettingsSchema fixtures > parses mtproto-basic byte-stably 1`] =
 {
   "protocol": "mtproto",
   "settings": {
+    "clients": [
+      {
+        "comment": "",
+        "email": "mtproto-user",
+        "enable": true,
+        "expiryTime": 0,
+        "limitIp": 0,
+        "reset": 0,
+        "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+        "subId": "",
+        "tgId": 0,
+        "totalGB": 0,
+      },
+    ],
     "fakeTlsDomain": "www.cloudflare.com",
-    "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
   },
 }
 `;
@@ -73,6 +86,20 @@ exports[`InboundSettingsSchema fixtures > parses mtproto-domain-fronting byte-st
 {
   "protocol": "mtproto",
   "settings": {
+    "clients": [
+      {
+        "comment": "",
+        "email": "mtproto-user",
+        "enable": true,
+        "expiryTime": 0,
+        "limitIp": 0,
+        "reset": 0,
+        "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+        "subId": "",
+        "tgId": 0,
+        "totalGB": 0,
+      },
+    ],
     "debug": true,
     "domainFronting": {
       "ip": "127.0.0.1",
@@ -82,7 +109,7 @@ exports[`InboundSettingsSchema fixtures > parses mtproto-domain-fronting byte-st
     "fakeTlsDomain": "www.cloudflare.com",
     "preferIp": "prefer-ipv4",
     "proxyProtocolListener": true,
-    "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+    "throttleMaxConnections": 5000,
   },
 }
 `;

+ 7 - 1
frontend/src/test/golden/fixtures/inbound/mtproto-basic.json

@@ -2,6 +2,12 @@
   "protocol": "mtproto",
   "settings": {
     "fakeTlsDomain": "www.cloudflare.com",
-    "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d"
+    "clients": [
+      {
+        "email": "mtproto-user",
+        "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+        "enable": true
+      }
+    ]
   }
 }

+ 8 - 1
frontend/src/test/golden/fixtures/inbound/mtproto-domain-fronting.json

@@ -2,10 +2,17 @@
   "protocol": "mtproto",
   "settings": {
     "fakeTlsDomain": "www.cloudflare.com",
-    "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+    "clients": [
+      {
+        "email": "mtproto-user",
+        "secret": "ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d",
+        "enable": true
+      }
+    ],
     "proxyProtocolListener": true,
     "preferIp": "prefer-ipv4",
     "debug": true,
+    "throttleMaxConnections": 5000,
     "domainFronting": {
       "ip": "127.0.0.1",
       "port": 9443,

+ 14 - 0
frontend/src/test/link-label.test.ts

@@ -26,4 +26,18 @@ describe('link-label parseLinkParts', () => {
   it('returns null for an unparseable scheme', () => {
     expect(parseLinkParts('not-a-link')).toBeNull();
   });
+
+  // MTProto share links are tg://proxy deep links whose port rides in a query
+  // param, not the URL authority; they carry no transport and use FakeTLS.
+  it('labels an mtproto tg://proxy link with its query-param port and FakeTLS', () => {
+    const parts = parseLinkParts(
+      'tg://proxy?server=host.example.com&port=8443&secret=ee00#mt-inbound',
+    );
+    expect(parts?.protocol).toBe('MTProto');
+    expect(parts?.network).toBe('');
+    expect(parts?.security).toBe('FAKETLS');
+    expect(parts?.port).toBe('8443');
+    expect(parts?.remark).toBe('mt-inbound');
+    expect(parts && linkMetaText(parts)).toBe('mt-inbound:8443');
+  });
 });

+ 41 - 0
frontend/src/test/mtproto-clients-link.test.ts

@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { genInboundLinks } from '@/lib/xray/inbound-link';
+import { InboundSchema } from '@/schemas/api/inbound';
+
+// Multi-client MTProto renders one tg://proxy deep link per entry in
+// settings.clients, each carrying that client's own FakeTLS secret.
+function mtprotoInbound() {
+  return InboundSchema.parse({
+    id: 70,
+    remark: 'mt-mc',
+    port: 8443,
+    protocol: 'mtproto',
+    settings: {
+      fakeTlsDomain: 'www.cloudflare.com',
+      clients: [
+        {
+          email: 'alice',
+          secret: 'ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d',
+          enable: true,
+        },
+        {
+          email: 'bob',
+          secret: 'eeabcdefabcdefabcdefabcdefabcdef01676f6f676c652e636f6d',
+          enable: true,
+        },
+      ],
+    },
+  });
+}
+
+describe('mtproto multi-client link fan-out', () => {
+  it('emits one tg://proxy per client from settings.clients', () => {
+    const out = genInboundLinks({ inbound: mtprotoInbound(), remark: 'mt-mc', fallbackHostname: 'mt.example.test' });
+    const links = out.split('\r\n').filter(Boolean);
+    expect(links).toHaveLength(2);
+    expect(links[0]).toContain('tg://proxy');
+    expect(links[0]).toContain('secret=ee0123456789abcdef0123456789abcdef7777772e636c6f7564666c6172652e636f6d');
+    expect(links[1]).toContain('secret=eeabcdefabcdefabcdefabcdefabcdef01676f6f676c652e636f6d');
+  });
+});

+ 130 - 1
internal/database/db.go

@@ -370,6 +370,130 @@ func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[
 	}
 }
 
+// seedMtprotoSecretsToClients converts each legacy single-secret mtproto inbound
+// into a one-client inbound so MTProto joins the shared multi-client model: the
+// inbound-level secret becomes the first client's FakeTLS secret, and a
+// ClientRecord + client_inbounds link are created so per-client traffic, limits,
+// and share links work exactly like every other protocol. One-time, self-gated
+// on the "MtprotoSecretsToClients" seeder row. Mirrors seedWireguardPeersToClients.
+func seedMtprotoSecretsToClients() error {
+	var history []string
+	if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
+		return err
+	}
+	if slices.Contains(history, "MtprotoSecretsToClients") {
+		return nil
+	}
+
+	var inbounds []model.Inbound
+	if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
+		return err
+	}
+
+	return db.Transaction(func(tx *gorm.DB) error {
+		usedEmails := map[string]struct{}{}
+		var existingEmails []string
+		if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
+			return err
+		}
+		for _, e := range existingEmails {
+			usedEmails[e] = struct{}{}
+		}
+
+		for _, inbound := range inbounds {
+			if strings.TrimSpace(inbound.Settings) == "" {
+				continue
+			}
+			var settings map[string]any
+			if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
+				log.Printf("MtprotoSecretsToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
+				continue
+			}
+			if clients, ok := settings["clients"].([]any); ok && len(clients) > 0 {
+				continue
+			}
+
+			var linkCount int64
+			if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
+				return err
+			}
+			if linkCount > 0 {
+				continue
+			}
+
+			secret, _ := settings["secret"].(string)
+			secret = strings.TrimSpace(secret)
+			if secret == "" {
+				domain, _ := settings["fakeTlsDomain"].(string)
+				secret = model.GenerateFakeTLSSecret(strings.TrimSpace(domain))
+			}
+
+			email := mtprotoInboundClientEmail(inbound.Remark, usedEmails)
+			usedEmails[email] = struct{}{}
+
+			obj := map[string]any{
+				"email":  email,
+				"secret": secret,
+				"enable": true,
+				"subId":  random.NumLower(16),
+			}
+			c := model.Client{Email: email, Secret: secret, Enable: true, SubID: obj["subId"].(string)}
+
+			incoming := c.ToRecord()
+			var row model.ClientRecord
+			err := tx.Where("email = ?", email).First(&row).Error
+			if errors.Is(err, gorm.ErrRecordNotFound) {
+				if err := tx.Create(incoming).Error; err != nil {
+					return err
+				}
+				row = *incoming
+			} else if err != nil {
+				return err
+			} else {
+				model.MergeClientRecord(&row, incoming)
+				if err := tx.Save(&row).Error; err != nil {
+					return err
+				}
+			}
+
+			link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
+			if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
+				FirstOrCreate(&link).Error; err != nil {
+				return err
+			}
+
+			delete(settings, "secret")
+			settings["clients"] = []any{obj}
+			newSettings, err := json.Marshal(settings)
+			if err != nil {
+				return err
+			}
+			if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
+				Update("settings", string(newSettings)).Error; err != nil {
+				return err
+			}
+		}
+		return tx.Create(&model.HistoryOfSeeders{SeederName: "MtprotoSecretsToClients"}).Error
+	})
+}
+
+// mtprotoInboundClientEmail derives a stable, unique client email for a migrated
+// mtproto inbound from its remark.
+func mtprotoInboundClientEmail(remark string, used map[string]struct{}) string {
+	base := strings.TrimSpace(remark)
+	if base == "" {
+		base = "mtproto"
+	}
+	email := strings.ReplaceAll(base, " ", "-")
+	candidate := email
+	for n := 2; ; n++ {
+		if _, taken := used[candidate]; !taken {
+			return candidate
+		}
+		candidate = email + "-" + strconv.Itoa(n)
+	}
+}
+
 // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
 // and inserts one Host row per entry on tx, returning the number of rows created.
 // It is the shared core of both the one-time seedHostsFromExternalProxy startup
@@ -687,7 +811,7 @@ func runSeeders(isUsersEmpty bool) error {
 	}
 
 	if empty && isUsersEmpty {
-		seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients"}
+		seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients", "MtprotoSecretsToClients"}
 		for _, name := range seeders {
 			if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
 				return err
@@ -796,6 +920,11 @@ func runSeeders(isUsersEmpty bool) error {
 		return err
 	}
 
+	// Self-gated on the "MtprotoSecretsToClients" row.
+	if err := seedMtprotoSecretsToClients(); err != nil {
+		return err
+	}
+
 	// Idempotent, not seeder-gated: bad values can re-enter via a restored
 	// backup, so re-check on every start.
 	return normalizeSettingPaths()

+ 78 - 0
internal/database/model/model.go

@@ -487,6 +487,74 @@ func HealMtprotoSecret(settings string) (string, bool) {
 	return string(out), true
 }
 
+// mtprotoSecretDomain extracts the FakeTLS domain embedded in the tail of a
+// secret, returning an empty string when the secret is malformed. Each mtproto
+// client carries its own domain inside its secret, so healing preserves it
+// instead of forcing every client onto the inbound-level default.
+func mtprotoSecretDomain(secret string) string {
+	s := secret
+	if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
+		s = s[2:]
+	}
+	if len(s) <= 32 {
+		return ""
+	}
+	decoded, err := hex.DecodeString(s[32:])
+	if err != nil || len(decoded) == 0 {
+		return ""
+	}
+	return string(decoded)
+}
+
+// HealMtprotoClientSecrets normalises every client's FakeTLS secret in an
+// mtproto inbound's settings JSON: each secret is rebuilt so it stays a valid
+// FakeTLS value, keeping the client's own embedded domain when present and
+// falling back to the inbound-level fakeTlsDomain otherwise. Returns the
+// rewritten settings and true when anything changed.
+func HealMtprotoClientSecrets(settings string) (string, bool) {
+	if settings == "" {
+		return settings, false
+	}
+	var parsed map[string]any
+	if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
+		return settings, false
+	}
+	clients, ok := parsed["clients"].([]any)
+	if !ok || len(clients) == 0 {
+		return settings, false
+	}
+	defaultDomain, _ := parsed["fakeTlsDomain"].(string)
+	defaultDomain = strings.TrimSpace(defaultDomain)
+	changed := false
+	for _, raw := range clients {
+		client, ok := raw.(map[string]any)
+		if !ok {
+			continue
+		}
+		secret, _ := client["secret"].(string)
+		domain := mtprotoSecretDomain(secret)
+		if domain == "" {
+			domain = defaultDomain
+		}
+		if domain == "" {
+			continue
+		}
+		expected := "ee" + mtprotoSecretMiddle(secret) + hex.EncodeToString([]byte(domain))
+		if secret != expected {
+			client["secret"] = expected
+			changed = true
+		}
+	}
+	if !changed {
+		return settings, false
+	}
+	out, err := json.MarshalIndent(parsed, "", "  ")
+	if err != nil {
+		return settings, false
+	}
+	return string(out), true
+}
+
 // Setting stores key-value configuration settings for the 3x-ui panel.
 type Setting struct {
 	Id    int    `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
@@ -603,6 +671,7 @@ type Client struct {
 	AllowedIPs   []string       `json:"allowedIPs,omitempty"`
 	PreSharedKey string         `json:"preSharedKey,omitempty"`
 	KeepAlive    int            `json:"keepAlive,omitempty"`
+	Secret       string         `json:"secret,omitempty" example:"ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"` // MTProto FakeTLS secret
 	Email        string         `json:"email"`                        // Client email identifier
 	LimitIP      int            `json:"limitIp"`                      // IP limit for this client
 	TotalGB      int64          `json:"totalGB" form:"totalGB"`       // Total traffic limit in GB
@@ -632,6 +701,7 @@ type ClientRecord struct {
 	AllowedIPs   string `json:"allowedIPs" gorm:"column:wg_allowed_ips"`
 	PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"`
 	KeepAlive    int    `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`
+	Secret       string `json:"secret" gorm:"column:secret"`
 	LimitIP      int    `json:"limitIp" gorm:"column:limit_ip"`
 	TotalGB      int64  `json:"totalGB" gorm:"column:total_gb"`
 	ExpiryTime   int64  `json:"expiryTime" gorm:"column:expiry_time"`
@@ -815,6 +885,7 @@ func (c *Client) ToRecord() *ClientRecord {
 		AllowedIPs:   strings.Join(c.AllowedIPs, ","),
 		PreSharedKey: c.PreSharedKey,
 		KeepAlive:    c.KeepAlive,
+		Secret:       c.Secret,
 	}
 	if c.Reverse != nil {
 		if b, err := json.Marshal(c.Reverse); err == nil {
@@ -866,6 +937,7 @@ func (r *ClientRecord) ToClient() *Client {
 		AllowedIPs:   splitWireguardAllowedIPs(r.AllowedIPs),
 		PreSharedKey: r.PreSharedKey,
 		KeepAlive:    r.KeepAlive,
+		Secret:       r.Secret,
 	}
 	if r.Reverse != "" {
 		var rev ClientReverse
@@ -1017,6 +1089,12 @@ func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientM
 			keepSecret("preSharedKey")
 		}
 	}
+	if existing.Secret != incoming.Secret && incoming.Secret != "" {
+		if incomingNewer || existing.Secret == "" {
+			existing.Secret = incoming.Secret
+			keepSecret("secret")
+		}
+	}
 	if existing.AllowedIPs != incoming.AllowedIPs && incoming.AllowedIPs != "" {
 		if incomingNewer || existing.AllowedIPs == "" {
 			keep("allowedIPs", existing.AllowedIPs, incoming.AllowedIPs, incoming.AllowedIPs)

+ 37 - 0
internal/database/model/model_mtproto_test.go

@@ -69,3 +69,40 @@ func TestHealMtprotoSecret(t *testing.T) {
 		t.Fatal("expected no change when fakeTlsDomain is missing")
 	}
 }
+
+func TestHealMtprotoClientSecrets(t *testing.T) {
+	// An empty client secret is filled from the inbound-level default domain.
+	in := `{"fakeTlsDomain":"a.com","clients":[{"email":"x","secret":""}]}`
+	out, changed := HealMtprotoClientSecrets(in)
+	if !changed {
+		t.Fatal("expected an empty client secret to be filled")
+	}
+	var parsed map[string]any
+	if err := json.Unmarshal([]byte(out), &parsed); err != nil {
+		t.Fatalf("healed settings not valid json: %v", err)
+	}
+	clients := parsed["clients"].([]any)
+	got := clients[0].(map[string]any)["secret"].(string)
+	if !strings.HasPrefix(got, "ee") || !strings.HasSuffix(got, hex.EncodeToString([]byte("a.com"))) {
+		t.Fatalf("filled client secret malformed: %q", got)
+	}
+
+	// Healing is idempotent once every client secret is valid.
+	if _, changed2 := HealMtprotoClientSecrets(out); changed2 {
+		t.Fatal("expected no change for already-valid client secrets")
+	}
+
+	// A client's own embedded domain is preserved even when it differs from the
+	// inbound-level default (per-client domain fronting).
+	own := "ee00112233445566778899aabbccddeeff" + hex.EncodeToString([]byte("b.com"))
+	in3 := `{"fakeTlsDomain":"a.com","clients":[{"email":"y","secret":"` + own + `"}]}`
+	out3, changed3 := HealMtprotoClientSecrets(in3)
+	if changed3 {
+		t.Fatalf("a valid per-client secret must be left untouched, got %q", out3)
+	}
+
+	// No clients array — nothing to heal.
+	if _, changed4 := HealMtprotoClientSecrets(`{"fakeTlsDomain":"a.com"}`); changed4 {
+		t.Fatal("expected no change when there are no clients")
+	}
+}

+ 158 - 162
internal/mtproto/manager.go

@@ -1,7 +1,6 @@
 package mtproto
 
 import (
-	"bufio"
 	"context"
 	"encoding/json"
 	"fmt"
@@ -17,13 +16,23 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/internal/logger"
 )
 
-// Instance is the desired runtime configuration of one mtproto inbound.
-type Instance struct {
-	Id     int
-	Tag    string
-	Listen string
-	Port   int
+// SecretEntry is one named FakeTLS secret served by an mtg-multi process. Name is
+// the client email, used both as the [secrets] key and as the per-user key in the
+// /stats API so traffic can be attributed back to the client.
+type SecretEntry struct {
+	Name   string
 	Secret string
+}
+
+// Instance is the desired runtime configuration of one mtproto inbound. A single
+// mtg-multi process serves every active client's secret through the [secrets]
+// section, so one inbound maps to one process with many named secrets.
+type Instance struct {
+	Id      int
+	Tag     string
+	Listen  string
+	Port    int
+	Secrets []SecretEntry
 
 	// Optional mtg tuning; each is omitted from the generated TOML when
 	// zero-valued so mtg falls back to its own defaults.
@@ -34,6 +43,10 @@ type Instance struct {
 	FrontingPort          int
 	FrontingProxyProtocol bool
 
+	// ThrottleMaxConnections caps concurrent connections across all users with a
+	// fair-share algorithm; zero disables throttling.
+	ThrottleMaxConnections int
+
 	// When RouteThroughXray is set, mtg dials Telegram through the loopback
 	// SOCKS bridge the panel injects into the Xray config at XrayRoutePort, so
 	// the egress obeys the core's routing rules instead of going out directly.
@@ -50,37 +63,47 @@ func (inst Instance) bindTo() string {
 }
 
 // fingerprint changes whenever any value that ends up in the generated TOML
-// changes, so ensureLocked restarts mtg when the operator edits a setting.
+// changes, so ensureLocked restarts mtg when the operator edits a setting or a
+// client is added, removed, disabled, or re-keyed.
 func (inst Instance) fingerprint() string {
-	return strings.Join([]string{
+	parts := []string{
 		inst.bindTo(),
-		inst.Secret,
 		strconv.FormatBool(inst.Debug),
 		strconv.FormatBool(inst.ProxyProtocolListener),
 		inst.PreferIP,
 		inst.FrontingIP,
 		strconv.Itoa(inst.FrontingPort),
 		strconv.FormatBool(inst.FrontingProxyProtocol),
+		strconv.Itoa(inst.ThrottleMaxConnections),
 		strconv.FormatBool(inst.RouteThroughXray),
 		strconv.Itoa(inst.XrayRoutePort),
-	}, "|")
+	}
+	for _, e := range inst.Secrets {
+		parts = append(parts, e.Name+"="+e.Secret)
+	}
+	return strings.Join(parts, "|")
 }
 
-// Traffic is a per-inbound traffic delta scraped from an mtg metrics endpoint.
+// Traffic is a per-client traffic delta scraped from an mtg /stats endpoint. Tag
+// is the owning inbound's tag and Email is the client the bytes belong to.
 type Traffic struct {
-	Tag  string
-	Up   int64
-	Down int64
+	Tag   string
+	Email string
+	Up    int64
+	Down  int64
+}
+
+type clientCounters struct {
+	up   int64
+	down int64
 }
 
 type managed struct {
 	proc        *Process
 	tag         string
 	fingerprint string
-	metricsPort int
-	lastUp      int64
-	lastDown    int64
-	haveLast    bool
+	apiPort     int
+	last        map[string]clientCounters
 }
 
 // Manager owns the set of running mtg processes keyed by inbound id.
@@ -106,49 +129,61 @@ func GetManager() *Manager {
 }
 
 // InstanceFromInbound derives a desired Instance from an mtproto inbound,
-// healing the FakeTLS secret so it always matches the configured domain.
-// Returns false when the inbound is not a usable mtproto inbound.
+// building one named secret per active client. Secrets are healed on save (see
+// normalizeMtprotoSecret) and by the migration, so they are read as-is here to
+// keep the fingerprint stable across reconciles. Returns false when the inbound
+// is not a usable mtproto inbound or has no active client secret to serve.
 func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
 	if ib == nil || ib.Protocol != model.MTProto {
 		return Instance{}, false
 	}
 	settings := ib.Settings
-	if healed, ok := model.HealMtprotoSecret(settings); ok {
-		settings = healed
-	}
 	var parsed struct {
-		Secret                string `json:"secret"`
-		Debug                 bool   `json:"debug"`
-		ProxyProtocolListener bool   `json:"proxyProtocolListener"`
-		PreferIP              string `json:"preferIp"`
+		ProxyProtocolListener bool `json:"proxyProtocolListener"`
+		Debug                 bool `json:"debug"`
 		DomainFronting        struct {
 			IP            string `json:"ip"`
 			Port          int    `json:"port"`
 			ProxyProtocol bool   `json:"proxyProtocol"`
 		} `json:"domainFronting"`
-		RouteThroughXray bool `json:"routeThroughXray"`
-		RouteXrayPort    int  `json:"routeXrayPort"`
+		PreferIP               string `json:"preferIp"`
+		ThrottleMaxConnections int    `json:"throttleMaxConnections"`
+		RouteThroughXray       bool   `json:"routeThroughXray"`
+		RouteXrayPort          int    `json:"routeXrayPort"`
+		Clients                []struct {
+			Email  string `json:"email"`
+			Secret string `json:"secret"`
+			Enable bool   `json:"enable"`
+		} `json:"clients"`
 	}
 	if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
 		return Instance{}, false
 	}
-	if parsed.Secret == "" {
+	secrets := make([]SecretEntry, 0, len(parsed.Clients))
+	for _, c := range parsed.Clients {
+		if !c.Enable || c.Secret == "" || c.Email == "" {
+			continue
+		}
+		secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret})
+	}
+	if len(secrets) == 0 {
 		return Instance{}, false
 	}
 	return Instance{
-		Id:                    ib.Id,
-		Tag:                   ib.Tag,
-		Listen:                ib.Listen,
-		Port:                  ib.Port,
-		Secret:                parsed.Secret,
-		Debug:                 parsed.Debug,
-		ProxyProtocolListener: parsed.ProxyProtocolListener,
-		PreferIP:              parsed.PreferIP,
-		FrontingIP:            parsed.DomainFronting.IP,
-		FrontingPort:          parsed.DomainFronting.Port,
-		FrontingProxyProtocol: parsed.DomainFronting.ProxyProtocol,
-		RouteThroughXray:      parsed.RouteThroughXray,
-		XrayRoutePort:         parsed.RouteXrayPort,
+		Id:                     ib.Id,
+		Tag:                    ib.Tag,
+		Listen:                 ib.Listen,
+		Port:                   ib.Port,
+		Secrets:                secrets,
+		Debug:                  parsed.Debug,
+		ProxyProtocolListener:  parsed.ProxyProtocolListener,
+		PreferIP:               parsed.PreferIP,
+		FrontingIP:             parsed.DomainFronting.IP,
+		FrontingPort:           parsed.DomainFronting.Port,
+		FrontingProxyProtocol:  parsed.DomainFronting.ProxyProtocol,
+		ThrottleMaxConnections: parsed.ThrottleMaxConnections,
+		RouteThroughXray:       parsed.RouteThroughXray,
+		XrayRoutePort:          parsed.RouteXrayPort,
 	}, true
 }
 
@@ -185,12 +220,12 @@ func (m *Manager) ensureLocked(inst Instance) error {
 		_ = cur.proc.Stop()
 		delete(m.procs, inst.Id)
 	}
-	metricsPort, err := FreeLocalPort()
+	apiPort, err := FreeLocalPort()
 	if err != nil {
 		return err
 	}
 	cfgPath := configPathForID(inst.Id)
-	if err := writeConfig(cfgPath, inst, metricsPort); err != nil {
+	if err := writeConfig(cfgPath, inst, apiPort); err != nil {
 		return err
 	}
 	proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id))
@@ -201,7 +236,8 @@ func (m *Manager) ensureLocked(inst Instance) error {
 		proc:        proc,
 		tag:         inst.Tag,
 		fingerprint: fp,
-		metricsPort: metricsPort,
+		apiPort:     apiPort,
+		last:        map[string]clientCounters{},
 	}
 	logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo())
 	return nil
@@ -255,18 +291,15 @@ func (m *Manager) StopAll() {
 	}
 }
 
-// CollectTraffic scrapes each running mtg metrics endpoint and returns the
-// per-inbound byte deltas since the previous scrape.
-func (m *Manager) CollectTraffic() []Traffic {
-	// Snapshot the state we need under the lock, then release before doing
-	// network I/O so that Ensure/Reconcile/Remove are not blocked.
+// CollectTraffic scrapes each running mtg /stats endpoint and returns the
+// per-client byte deltas since the previous scrape, plus the emails of clients
+// with at least one live connection.
+func (m *Manager) CollectTraffic() ([]Traffic, []string) {
 	type snap struct {
-		id          int
-		metricsPort int
-		tag         string
-		haveLast    bool
-		lastUp      int64
-		lastDown    int64
+		id      int
+		apiPort int
+		tag     string
+		last    map[string]clientCounters
 	}
 	m.mu.Lock()
 	snaps := make([]snap, 0, len(m.procs))
@@ -274,54 +307,57 @@ func (m *Manager) CollectTraffic() []Traffic {
 		if cur.proc == nil || !cur.proc.IsRunning() {
 			continue
 		}
-		snaps = append(snaps, snap{
-			id:          id,
-			metricsPort: cur.metricsPort,
-			tag:         cur.tag,
-			haveLast:    cur.haveLast,
-			lastUp:      cur.lastUp,
-			lastDown:    cur.lastDown,
-		})
+		lastCopy := make(map[string]clientCounters, len(cur.last))
+		for k, v := range cur.last {
+			lastCopy[k] = v
+		}
+		snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, tag: cur.tag, last: lastCopy})
 	}
 	m.mu.Unlock()
 
-	out := make([]Traffic, 0, len(snaps))
+	var out []Traffic
+	var online []string
 	for _, s := range snaps {
-		up, down, ok := scrapeTraffic(s.metricsPort)
+		users, ok := scrapeStats(s.apiPort)
 		if !ok {
 			continue
 		}
-		var du, dd int64
-		if s.haveLast {
-			du = up - s.lastUp
-			dd = down - s.lastDown
+		newLast := make(map[string]clientCounters, len(users))
+		for email, u := range users {
+			up := u.BytesIn
+			down := u.BytesOut
+			newLast[email] = clientCounters{up: up, down: down}
+			if u.Connections > 0 {
+				online = append(online, email)
+			}
+			prev, had := s.last[email]
+			if !had {
+				continue
+			}
+			du := up - prev.up
+			dd := down - prev.down
 			if du < 0 {
 				du = 0
 			}
 			if dd < 0 {
 				dd = 0
 			}
+			if du > 0 || dd > 0 {
+				out = append(out, Traffic{Tag: s.tag, Email: email, Up: du, Down: dd})
+			}
 		}
 
-		// Re-acquire lock to persist the new baseline, but only if the entry
-		// still exists (it may have been removed during the scrape).
 		m.mu.Lock()
 		if cur, ok := m.procs[s.id]; ok {
-			cur.lastUp = up
-			cur.lastDown = down
-			cur.haveLast = true
+			cur.last = newLast
 		}
 		m.mu.Unlock()
-
-		if s.haveLast && (du > 0 || dd > 0) {
-			out = append(out, Traffic{Tag: s.tag, Up: du, Down: dd})
-		}
 	}
-	return out
+	return out, online
 }
 
 // FreeLocalPort asks the OS for an unused loopback TCP port. It is used both
-// for mtg's metrics endpoint and to allocate the per-inbound SOCKS egress
+// for mtg's /stats API endpoint and to allocate the per-inbound SOCKS egress
 // bridge port persisted into mtproto inbound settings.
 func FreeLocalPort() (int, error) {
 	l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
@@ -332,13 +368,13 @@ func FreeLocalPort() (int, error) {
 	return l.Addr().(*net.TCPAddr).Port, nil
 }
 
-// renderConfig builds the mtg TOML for an instance. Top-level keys must precede
-// any [section] header in TOML, so the layout is: required keys, then the
-// optional scalar tuning, then [domain-fronting], and finally [stats.prometheus]
-// — which x-ui always emits and scrapes for traffic (see scrapeTraffic).
-func renderConfig(inst Instance, metricsPort int) string {
+// renderConfig builds the mtg-multi TOML for an instance. Top-level keys must
+// precede any [section] header in TOML, and [secrets] must be the final section
+// so trailing keys are not swallowed by another table. The layout is therefore:
+// top-level scalars (incl. api-bind-to), then [domain-fronting], [network] and
+// [throttle], and finally [secrets] with one named secret per active client.
+func renderConfig(inst Instance, apiPort int) string {
 	var b strings.Builder
-	fmt.Fprintf(&b, "secret = %q\n", inst.Secret)
 	fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo())
 	if inst.Debug {
 		b.WriteString("debug = true\n")
@@ -349,10 +385,11 @@ func renderConfig(inst Instance, metricsPort int) string {
 	if inst.PreferIP != "" {
 		fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP)
 	}
+	fmt.Fprintf(&b, "api-bind-to = \"127.0.0.1:%d\"\n", apiPort)
 	if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol {
 		b.WriteString("\n[domain-fronting]\n")
 		if inst.FrontingIP != "" {
-			fmt.Fprintf(&b, "ip = %q\n", inst.FrontingIP)
+			fmt.Fprintf(&b, "host = %q\n", inst.FrontingIP)
 		}
 		if inst.FrontingPort > 0 {
 			fmt.Fprintf(&b, "port = %d\n", inst.FrontingPort)
@@ -367,92 +404,51 @@ func renderConfig(inst Instance, metricsPort int) string {
 	if inst.RouteThroughXray && inst.XrayRoutePort > 0 {
 		fmt.Fprintf(&b, "\n[network]\nproxies = [\"socks5://127.0.0.1:%d\"]\n", inst.XrayRoutePort)
 	}
-	fmt.Fprintf(&b, "\n[stats.prometheus]\nenabled = true\nbind-to = \"127.0.0.1:%d\"\nhttp-path = \"/metrics\"\nmetric-prefix = \"mtg\"\n", metricsPort)
+	if inst.ThrottleMaxConnections > 0 {
+		fmt.Fprintf(&b, "\n[throttle]\nmax-connections = %d\n", inst.ThrottleMaxConnections)
+	}
+	b.WriteString("\n[secrets]\n")
+	for _, e := range inst.Secrets {
+		fmt.Fprintf(&b, "%q = %q\n", e.Name, e.Secret)
+	}
 	return b.String()
 }
 
-func writeConfig(path string, inst Instance, metricsPort int) error {
+func writeConfig(path string, inst Instance, apiPort int) error {
 	if err := os.MkdirAll(configDir(), 0o750); err != nil {
 		return err
 	}
-	return os.WriteFile(path, []byte(renderConfig(inst, metricsPort)), 0o640)
+	return os.WriteFile(path, []byte(renderConfig(inst, apiPort)), 0o640)
+}
+
+// statsUser is one entry of the mtg-multi /stats users map. bytes_in is traffic
+// the client sent to the proxy (upload) and bytes_out is what the proxy returned
+// (download).
+type statsUser struct {
+	Connections int64 `json:"connections"`
+	BytesIn     int64 `json:"bytes_in"`
+	BytesOut    int64 `json:"bytes_out"`
 }
 
-// scrapeTraffic reads the mtg Prometheus metrics endpoint and sums byte
-// counters by direction. mtg exposes a traffic counter labelled with a
-// direction; "to_telegram" is treated as upload and "to_client" as download.
-// Best-effort: an unreachable endpoint or unrecognised format yields ok=false.
-func scrapeTraffic(port int) (up int64, down int64, ok bool) {
+// scrapeStats reads the mtg-multi /stats JSON API and returns the per-user
+// cumulative counters. Best-effort: an unreachable endpoint or unparseable body
+// yields ok=false.
+func scrapeStats(port int) (map[string]statsUser, bool) {
 	client := http.Client{Timeout: 3 * time.Second}
-	req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/metrics", port), nil)
-	if reqErr != nil {
-		return 0, 0, false
+	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil)
+	if err != nil {
+		return nil, false
 	}
 	resp, err := client.Do(req)
 	if err != nil {
-		return 0, 0, false
+		return nil, false
 	}
 	defer resp.Body.Close()
-	scanner := bufio.NewScanner(resp.Body)
-	scanner.Buffer(make([]byte, 64*1024), 1024*1024)
-	found := false
-	for scanner.Scan() {
-		line := strings.TrimSpace(scanner.Text())
-		if line == "" || line[0] == '#' || !strings.Contains(line, "traffic") {
-			continue
-		}
-		name, labels, value, perr := parseMetricLine(line)
-		if perr != nil || !strings.HasPrefix(name, "mtg") {
-			continue
-		}
-		switch labels["direction"] {
-		case "to_telegram", "egress", "up":
-			up += int64(value)
-		case "to_client", "ingress", "down":
-			down += int64(value)
-		default:
-			down += int64(value)
-		}
-		found = true
-	}
-	if err := scanner.Err(); err != nil {
-		logger.Debug("mtproto: metrics scan error:", err)
-	}
-	return up, down, found
-}
-
-func parseMetricLine(line string) (name string, labels map[string]string, value float64, err error) {
-	labels = map[string]string{}
-	var rest string
-	if brace := strings.IndexByte(line, '{'); brace >= 0 {
-		name = line[:brace]
-		end := strings.IndexByte(line, '}')
-		if end < brace {
-			return "", nil, 0, fmt.Errorf("malformed metric line")
-		}
-		for kv := range strings.SplitSeq(line[brace+1:end], ",") {
-			before, after, ok := strings.Cut(kv, "=")
-			if !ok {
-				continue
-			}
-			labels[strings.TrimSpace(before)] = strings.Trim(strings.TrimSpace(after), `"`)
-		}
-		rest = strings.TrimSpace(line[end+1:])
-	} else {
-		fields := strings.Fields(line)
-		if len(fields) < 2 {
-			return "", nil, 0, fmt.Errorf("malformed metric line")
-		}
-		name = fields[0]
-		rest = fields[1]
-	}
-	valFields := strings.Fields(rest)
-	if len(valFields) == 0 {
-		return "", nil, 0, fmt.Errorf("missing metric value")
+	var parsed struct {
+		Users map[string]statsUser `json:"users"`
 	}
-	value, err = strconv.ParseFloat(valFields[0], 64)
-	if err != nil {
-		return "", nil, 0, err
+	if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
+		return nil, false
 	}
-	return name, labels, value, nil
+	return parsed.Users, true
 }

+ 52 - 86
internal/mtproto/manager_mutation_test.go

@@ -1,99 +1,65 @@
 package mtproto
 
 import (
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"strconv"
 	"testing"
 )
 
-// TestParseMetricLineBraceBoundary pins the contract of the brace-position
-// guard in parseMetricLine (manager.go:425 -> `if end < brace`).
-//
-// Once a '{' is found at index `brace`, the matching '}' must appear AFTER it.
-// A '}' that precedes the '{', or a '{' with no closing '}' at all
-// (strings.IndexByte returns -1, which is < brace), is a malformed line and
-// must yield an error rather than slicing past the brace.
-func TestParseMetricLineBraceBoundary(t *testing.T) {
-	t.Run("closing brace before opening brace is malformed", func(t *testing.T) {
-		// '}' at index 8 comes before '{' at index 16: end < brace must hold,
-		// so this is rejected. Mutating `<` to `>`/`>=` would accept it.
-		_, _, _, err := parseMetricLine(`mtg_x_a}_b{direction="x"} 5`)
-		if err == nil {
-			t.Fatal("expected error for '}' appearing before '{'")
-		}
-	})
+// serverPort extracts the loopback port a httptest server bound to, so
+// scrapeStats can rebuild the same http://127.0.0.1:<port>/stats URL.
+func serverPort(t *testing.T, srv *httptest.Server) int {
+	t.Helper()
+	u, err := url.Parse(srv.URL)
+	if err != nil {
+		t.Fatalf("parse url: %v", err)
+	}
+	port, err := strconv.Atoi(u.Port())
+	if err != nil {
+		t.Fatalf("parse port: %v", err)
+	}
+	return port
+}
 
-	t.Run("opening brace with no closing brace is malformed", func(t *testing.T) {
-		// No '}' at all -> end == -1, which is < brace. Must error.
-		// If the guard were dropped/inverted the code would slice line[brace+1:-1]
-		// and panic; asserting a clean error keeps that contract.
-		_, _, _, err := parseMetricLine(`mtg_traffic{direction="x" 5`)
-		if err == nil {
-			t.Fatal("expected error for '{' without a closing '}'")
+func TestScrapeStats(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/stats" {
+			http.NotFound(w, r)
+			return
 		}
-	})
+		_, _ = io.WriteString(w, `{"started_at":"2026-01-01T00:00:00Z","total_connections":2,`+
+			`"users":{`+
+			`"alice":{"connections":2,"bytes_in":100,"bytes_out":200,"last_seen":"2026-01-01T00:01:00Z"},`+
+			`"bob":{"connections":0,"bytes_in":5,"bytes_out":7,"last_seen":null}}}`)
+	}))
+	defer srv.Close()
 
-	t.Run("well-formed braces are accepted", func(t *testing.T) {
-		// '{' at index 11, '}' at index 25: end > brace, so the guard must NOT
-		// fire and parsing must succeed. Guards against a mutant that always errors.
-		name, labels, val, err := parseMetricLine(`mtg_traffic{direction="up"} 42`)
-		if err != nil {
-			t.Fatalf("well-formed line should parse: %v", err)
-		}
-		if name != "mtg_traffic" {
-			t.Fatalf("name=%q", name)
-		}
-		if labels["direction"] != "up" {
-			t.Fatalf("labels=%v", labels)
-		}
-		if val != 42 {
-			t.Fatalf("val=%v", val)
-		}
-	})
+	users, ok := scrapeStats(serverPort(t, srv))
+	if !ok {
+		t.Fatal("scrapeStats should succeed against a valid /stats endpoint")
+	}
+	if len(users) != 2 {
+		t.Fatalf("expected 2 users, got %d: %+v", len(users), users)
+	}
+	if users["alice"].BytesIn != 100 || users["alice"].BytesOut != 200 || users["alice"].Connections != 2 {
+		t.Fatalf("alice stats parsed wrong: %+v", users["alice"])
+	}
+	if users["bob"].Connections != 0 || users["bob"].BytesIn != 5 {
+		t.Fatalf("bob stats parsed wrong: %+v", users["bob"])
+	}
 }
 
-// TestParseMetricLineLabelEqualsBoundary pins the contract of the '=' guard in
-// the per-label loop (manager.go:430 -> `if eq < 0`).
-//
-//   - eq < 0  (no '=' in the segment): the segment is skipped, no label added.
-//   - eq == 0 (segment begins with '='): the key is empty but the pair is STILL
-//     parsed, producing labels[""] = value. The boundary is `< 0`, not `<= 0`.
-func TestParseMetricLineLabelEqualsBoundary(t *testing.T) {
-	t.Run("label segment without '=' is skipped, not fatal", func(t *testing.T) {
-		// "novalue" has no '=' (eq == -1) and must be skipped. A real key=val
-		// segment in the same line must still be parsed. Mutating `< 0` to `> 0`
-		// would take kv[:eq] with eq=-1 and panic; mutating away the skip would
-		// also corrupt parsing.
-		name, labels, val, err := parseMetricLine(`mtg_traffic{novalue,direction="down"} 9`)
-		if err != nil {
-			t.Fatalf("line with a value-less label should still parse: %v", err)
-		}
-		if name != "mtg_traffic" {
-			t.Fatalf("name=%q", name)
-		}
-		if _, present := labels["novalue"]; present {
-			t.Fatalf("value-less segment must not create a label: %v", labels)
-		}
-		if labels["direction"] != "down" {
-			t.Fatalf("real label must still be parsed: %v", labels)
-		}
-		if val != 9 {
-			t.Fatalf("val=%v", val)
-		}
-	})
+func TestScrapeStatsUnreachable(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		http.NotFound(w, r)
+	}))
+	port := serverPort(t, srv)
+	srv.Close()
 
-	t.Run("label segment beginning with '=' is parsed as empty key", func(t *testing.T) {
-		// "=onlyvalue": eq == 0. Since the guard is `< 0`, this is NOT skipped:
-		// it yields labels[""] = "onlyvalue". A mutant changing `< 0` to `<= 0`
-		// would skip it, losing the empty-key entry.
-		_, labels, _, err := parseMetricLine(`mtg_traffic{=onlyvalue} 1`)
-		if err != nil {
-			t.Fatalf("segment with empty key should still parse: %v", err)
-		}
-		v, present := labels[""]
-		if !present {
-			t.Fatalf("eq==0 segment must produce an empty-key label: %v", labels)
-		}
-		if v != "onlyvalue" {
-			t.Fatalf("empty-key label value=%q", v)
-		}
-	})
+	if _, ok := scrapeStats(port); ok {
+		t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable")
+	}
 }

+ 68 - 47
internal/mtproto/manager_test.go

@@ -7,48 +7,36 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/internal/database/model"
 )
 
-func TestParseMetricLine(t *testing.T) {
-	name, labels, val, err := parseMetricLine(`mtg_traffic{direction="to_client"} 12345`)
-	if err != nil {
-		t.Fatal(err)
-	}
-	if name != "mtg_traffic" {
-		t.Fatalf("name=%q", name)
-	}
-	if labels["direction"] != "to_client" {
-		t.Fatalf("labels=%v", labels)
-	}
-	if val != 12345 {
-		t.Fatalf("val=%v", val)
-	}
-
-	name2, _, val2, err2 := parseMetricLine(`mtg_concurrency 7`)
-	if err2 != nil {
-		t.Fatal(err2)
-	}
-	if name2 != "mtg_concurrency" || val2 != 7 {
-		t.Fatalf("got %q %v", name2, val2)
-	}
-}
-
 func TestInstanceFromInbound(t *testing.T) {
+	aliceSecret := "ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d"
 	ib := &model.Inbound{
 		Id:       3,
 		Tag:      "inbound-3",
 		Listen:   "0.0.0.0",
 		Port:     8443,
 		Protocol: model.MTProto,
-		Settings: `{"fakeTlsDomain":"example.com","secret":"",` +
+		Settings: `{"fakeTlsDomain":"example.com",` +
 			`"debug":true,"proxyProtocolListener":true,"preferIp":"prefer-ipv4",` +
 			`"domainFronting":{"ip":"127.0.0.1","port":9443,"proxyProtocol":true},` +
-			`"routeThroughXray":true,"routeXrayPort":50000}`,
+			`"throttleMaxConnections":5000,` +
+			`"routeThroughXray":true,"routeXrayPort":50000,` +
+			`"clients":[` +
+			`{"email":"alice","secret":"` + aliceSecret + `","enable":true},` +
+			`{"email":"bob","secret":"","enable":true},` +
+			`{"email":"carol","secret":"eeaa","enable":false}]}`,
 	}
 	inst, ok := InstanceFromInbound(ib)
 	if !ok {
 		t.Fatal("expected a usable instance")
 	}
-	if inst.Secret == "" {
-		t.Fatal("secret should be healed to a non-empty value")
+	if len(inst.Secrets) != 1 {
+		t.Fatalf("only the enabled client with a secret should be served, got %d: %+v", len(inst.Secrets), inst.Secrets)
+	}
+	if inst.Secrets[0].Name != "alice" {
+		t.Fatalf("secret name should be the client email, got %q", inst.Secrets[0].Name)
+	}
+	if inst.Secrets[0].Secret != aliceSecret {
+		t.Fatalf("a valid secret must be preserved, got %q", inst.Secrets[0].Secret)
 	}
 	if inst.Port != 8443 || inst.Id != 3 {
 		t.Fatalf("bad instance %+v", inst)
@@ -59,6 +47,9 @@ func TestInstanceFromInbound(t *testing.T) {
 	if inst.FrontingIP != "127.0.0.1" || inst.FrontingPort != 9443 || !inst.FrontingProxyProtocol {
 		t.Fatalf("domain-fronting not parsed: %+v", inst)
 	}
+	if inst.ThrottleMaxConnections != 5000 {
+		t.Fatalf("throttle not parsed: %+v", inst)
+	}
 	if !inst.RouteThroughXray || inst.XrayRoutePort != 50000 {
 		t.Fatalf("xray routing not parsed: %+v", inst)
 	}
@@ -66,13 +57,21 @@ func TestInstanceFromInbound(t *testing.T) {
 	if _, ok := InstanceFromInbound(&model.Inbound{Protocol: model.VLESS}); ok {
 		t.Fatal("non-mtproto inbound should not produce an instance")
 	}
+
+	noSecrets := &model.Inbound{Protocol: model.MTProto, Settings: `{"clients":[{"email":"x","secret":"","enable":true}]}`}
+	if _, ok := InstanceFromInbound(noSecrets); ok {
+		t.Fatal("an inbound with no active secret should not produce an instance")
+	}
 }
 
 func TestRenderConfig(t *testing.T) {
-	// A bare instance emits only the required keys and the prometheus block,
-	// with no optional keys and no [domain-fronting] section.
-	bare := renderConfig(Instance{Secret: "ee00", Listen: "0.0.0.0", Port: 8443}, 5000)
-	for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]"} {
+	// A bare instance emits only the required keys, api-bind-to, and the
+	// [secrets] section, with no optional keys and no [domain-fronting].
+	bare := renderConfig(Instance{
+		Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}},
+		Listen:  "0.0.0.0", Port: 8443,
+	}, 5000)
+	for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]"} {
 		if strings.Contains(bare, unwanted) {
 			t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare)
 		}
@@ -80,57 +79,73 @@ func TestRenderConfig(t *testing.T) {
 	if !strings.Contains(bare, `bind-to = "0.0.0.0:8443"`) {
 		t.Fatalf("missing bind-to:\n%s", bare)
 	}
-	if !strings.Contains(bare, "[stats.prometheus]") || !strings.Contains(bare, "127.0.0.1:5000") {
-		t.Fatalf("prometheus block must always be present:\n%s", bare)
+	if !strings.Contains(bare, `api-bind-to = "127.0.0.1:5000"`) {
+		t.Fatalf("api-bind-to must always be present:\n%s", bare)
+	}
+	if !strings.Contains(bare, "[secrets]") || !strings.Contains(bare, `"alice" = "ee00"`) {
+		t.Fatalf("secrets block must carry the client secret:\n%s", bare)
 	}
 
-	// A fully configured instance emits every option and the fronting section.
+	// A fully configured instance emits every option, the fronting section (as
+	// host, not the fork-deprecated ip), the throttle block, and [secrets] last.
 	full := renderConfig(Instance{
-		Secret: "ee11", Listen: "0.0.0.0", Port: 443,
+		Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}},
+		Listen:  "0.0.0.0", Port: 443,
 		Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6",
 		FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true,
+		ThrottleMaxConnections: 5000,
 	}, 6000)
 	for _, want := range []string{
 		"debug = true\n",
 		"proxy-protocol-listener = true\n",
 		`prefer-ip = "only-ipv6"`,
 		"[domain-fronting]",
-		`ip = "127.0.0.1"`,
+		`host = "127.0.0.1"`,
 		"port = 9443",
 		"proxy-protocol = true\n",
+		"[throttle]",
+		"max-connections = 5000",
 	} {
 		if !strings.Contains(full, want) {
 			t.Fatalf("full config missing %q:\n%s", want, full)
 		}
 	}
-	// TOML requires top-level keys before any [section] header.
+	if strings.Contains(full, `ip = "127.0.0.1"`) {
+		t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full)
+	}
+	// TOML requires top-level keys before any [section] header, and [secrets]
+	// must be the final section so trailing keys are not swallowed by a table.
 	if strings.Index(full, "prefer-ip") > strings.Index(full, "[domain-fronting]") {
 		t.Fatalf("top-level keys must precede the [domain-fronting] section:\n%s", full)
 	}
-	if strings.LastIndex(full, "[domain-fronting]") > strings.Index(full, "[stats.prometheus]") {
-		t.Fatalf("[domain-fronting] must precede [stats.prometheus]:\n%s", full)
+	if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[domain-fronting]") {
+		t.Fatalf("[secrets] must be the final section:\n%s", full)
+	}
+	if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") {
+		t.Fatalf("[throttle] must precede [secrets]:\n%s", full)
 	}
 }
 
 func TestRenderConfigXrayEgress(t *testing.T) {
 	// Routing through Xray emits a [network] proxies upstream pointing at the
-	// loopback SOCKS bridge, before the prometheus block.
+	// loopback SOCKS bridge, before the [secrets] section.
 	routed := renderConfig(Instance{
-		Secret: "ee22", Listen: "0.0.0.0", Port: 443,
+		Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}},
+		Listen:  "0.0.0.0", Port: 443,
 		RouteThroughXray: true, XrayRoutePort: 50000,
 	}, 7000)
 	if !strings.Contains(routed, "[network]") ||
 		!strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) {
 		t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed)
 	}
-	if strings.Index(routed, "[network]") > strings.Index(routed, "[stats.prometheus]") {
-		t.Fatalf("[network] must precede [stats.prometheus]:\n%s", routed)
+	if strings.Index(routed, "[network]") > strings.Index(routed, "[secrets]") {
+		t.Fatalf("[network] must precede [secrets]:\n%s", routed)
 	}
 
 	// Without the flag (or without a port) the section is omitted.
 	for _, inst := range []Instance{
-		{Secret: "ee", Listen: "0.0.0.0", Port: 443},
-		{Secret: "ee", Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
+		{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443},
+		{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
 	} {
 		if got := renderConfig(inst, 7000); strings.Contains(got, "[network]") {
 			t.Fatalf("unrouted config must omit [network]:\n%s", got)
@@ -139,7 +154,7 @@ func TestRenderConfigXrayEgress(t *testing.T) {
 }
 
 func TestFingerprintReactsToOptions(t *testing.T) {
-	base := Instance{Secret: "ee", Listen: "0.0.0.0", Port: 443}
+	base := Instance{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443}
 	for name, mutate := range map[string]func(*Instance){
 		"debug":         func(i *Instance) { i.Debug = true },
 		"listener":      func(i *Instance) { i.ProxyProtocolListener = true },
@@ -147,10 +162,16 @@ func TestFingerprintReactsToOptions(t *testing.T) {
 		"frontingIP":    func(i *Instance) { i.FrontingIP = "127.0.0.1" },
 		"frontingPort":  func(i *Instance) { i.FrontingPort = 9443 },
 		"frontingProxy": func(i *Instance) { i.FrontingProxyProtocol = true },
+		"throttle":      func(i *Instance) { i.ThrottleMaxConnections = 5000 },
 		"routeXray":     func(i *Instance) { i.RouteThroughXray = true },
 		"routeXrayPort": func(i *Instance) { i.XrayRoutePort = 50000 },
+		"addSecret":     func(i *Instance) { i.Secrets = append(i.Secrets, SecretEntry{Name: "b", Secret: "ff"}) },
+		"changeSecret":  func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a", Secret: "ee99"}} },
 	} {
 		changed := base
+		if strings.HasPrefix(name, "addSecret") || strings.HasPrefix(name, "changeSecret") {
+			changed.Secrets = append([]SecretEntry(nil), base.Secrets...)
+		}
 		mutate(&changed)
 		if base.fingerprint() == changed.fingerprint() {
 			t.Fatalf("fingerprint must change when %s changes", name)

+ 5 - 4
internal/mtproto/process.go

@@ -1,7 +1,8 @@
-// Package mtproto manages mtg (github.com/9seconds/mtg) sidecar processes that
-// serve MTProto FakeTLS proxies. Xray-core has no mtproto protocol, so mtproto
-// inbounds are run as standalone mtg processes — one process per inbound —
-// entirely outside the Xray config and lifecycle.
+// Package mtproto manages mtg-multi (github.com/dolonet/mtg-multi) sidecar
+// processes that serve MTProto FakeTLS proxies. Xray-core has no mtproto
+// protocol, so mtproto inbounds are run as standalone mtg processes — one
+// process per inbound, each serving every active client's secret through the
+// mtg-multi [secrets] section — entirely outside the Xray config and lifecycle.
 package mtproto
 
 import (

+ 9 - 15
internal/sub/service.go

@@ -465,7 +465,7 @@ func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error)
 		JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
 		JOIN clients ON clients.id = client_inbounds.client_id
 		WHERE
-			inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria','wireguard')
+			inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria','wireguard','mtproto')
 			AND clients.sub_id = ? AND inbounds.enable = ?
 	)`, subId, true).Order("sub_sort_index ASC").Order("id ASC").Find(&inbounds).Error
 	if err != nil {
@@ -662,29 +662,23 @@ func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) stri
 	return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", ""))
 }
 
-// genMtprotoLink builds a Telegram proxy deep link for an mtproto inbound:
-func (s *SubService) genMtprotoLink(inbound *model.Inbound, _ string) string {
+// genMtprotoLink builds a per-client Telegram proxy deep link for an mtproto
+// inbound: the server/port pair plus the client's own FakeTLS secret. Returns ""
+// when the client has no secret.
+func (s *SubService) genMtprotoLink(inbound *model.Inbound, email string) string {
 	if inbound.Protocol != model.MTProto {
 		return ""
 	}
-	settings := map[string]any{}
-	_ = json.Unmarshal([]byte(inbound.Settings), &settings)
-	secret, _ := settings["secret"].(string)
-	if secret == "" {
-		if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
-			_ = json.Unmarshal([]byte(healed), &settings)
-			secret, _ = settings["secret"].(string)
-		}
-	}
-	if secret == "" {
+	resolved, ok := s.clientForLink(inbound, email)
+	if !ok || resolved.Secret == "" {
 		return ""
 	}
 	params := map[string]string{
 		"server": s.resolveInboundAddress(inbound),
 		"port":   fmt.Sprintf("%d", inbound.Port),
-		"secret": secret,
+		"secret": resolved.Secret,
 	}
-	return buildLinkWithParams("tg://proxy", params, "")
+	return buildLinkWithParams("tg://proxy", params, s.genRemark(inbound, email, "", ""))
 }
 
 // Protocol link generators are intentionally ordered as:

+ 110 - 0
internal/sub/service_mtproto_test.go

@@ -0,0 +1,110 @@
+package sub
+
+import (
+	"net/url"
+	"strings"
+	"testing"
+
+	"github.com/mhsanaei/3x-ui/v3/internal/database"
+	"github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const mtprotoTestSecret = "ee8196fe6ed8b637d001f91d6952cfcdf07777772e636c6f7564666c6172652e636f6d"
+
+func TestGenMtprotoLinkFields(t *testing.T) {
+	inbound := &model.Inbound{
+		Listen:   "203.0.113.7",
+		Port:     8443,
+		Protocol: model.MTProto,
+		Remark:   "mt-sub",
+		Settings: `{"fakeTlsDomain":"www.cloudflare.com","clients":[{"email":"user","enable":true,"secret":"` + mtprotoTestSecret + `"}]}`,
+	}
+
+	s := &SubService{}
+	link := s.genMtprotoLink(inbound, "user")
+
+	u, err := url.Parse(link)
+	if err != nil {
+		t.Fatalf("link does not parse: %v\n got: %s", err, link)
+	}
+	if u.Scheme != "tg" || u.Host != "proxy" {
+		t.Fatalf("link = %q, want a tg://proxy deep link", link)
+	}
+	q := u.Query()
+	if q.Get("server") != "203.0.113.7" {
+		t.Fatalf("server = %q, want 203.0.113.7", q.Get("server"))
+	}
+	if q.Get("port") != "8443" {
+		t.Fatalf("port = %q, want 8443", q.Get("port"))
+	}
+	if q.Get("secret") != mtprotoTestSecret {
+		t.Fatalf("secret = %q, want the client's FakeTLS secret", q.Get("secret"))
+	}
+}
+
+func TestGenMtprotoLinkWrongProtocol(t *testing.T) {
+	s := &SubService{}
+	vless := &model.Inbound{Protocol: model.VLESS, Settings: `{"clients":[{"email":"user"}]}`}
+	if got := s.genMtprotoLink(vless, "user"); got != "" {
+		t.Fatalf("wrong protocol should yield empty link, got %q", got)
+	}
+}
+
+func TestGenMtprotoLinkNoSecret(t *testing.T) {
+	s := &SubService{}
+	inbound := &model.Inbound{
+		Protocol: model.MTProto,
+		Port:     8443,
+		Settings: `{"fakeTlsDomain":"www.cloudflare.com","clients":[{"email":"user"}]}`,
+	}
+	if got := s.genMtprotoLink(inbound, "user"); got != "" {
+		t.Fatalf("client without secret should yield empty link, got %q", got)
+	}
+}
+
+// Regression: an mtproto inbound must resolve for a subscription id the same way
+// every other client-bearing protocol does. It was previously dropped from the
+// getInboundsBySubId protocol allowlist, so multi-client MTProto subscriptions
+// (and the public sub page) emitted no tg://proxy link at all.
+func TestGetInboundsBySubIdIncludesMtproto(t *testing.T) {
+	initSubDB(t)
+	db := database.GetDB()
+
+	in := &model.Inbound{
+		Port:     8443,
+		Protocol: model.MTProto,
+		Enable:   true,
+		Tag:      "mt-sub",
+		Settings: `{"fakeTlsDomain":"www.cloudflare.com","clients":[{"email":"u@mt","enable":true,"subId":"submt","secret":"` + mtprotoTestSecret + `"}]}`,
+	}
+	if err := db.Create(in).Error; err != nil {
+		t.Fatalf("create inbound: %v", err)
+	}
+	rec := &model.ClientRecord{Email: "u@mt", SubID: "submt", Enable: true, Secret: mtprotoTestSecret}
+	if err := db.Create(rec).Error; err != nil {
+		t.Fatalf("create client: %v", err)
+	}
+	if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: in.Id}).Error; err != nil {
+		t.Fatalf("create link: %v", err)
+	}
+
+	s := &SubService{}
+	inbounds, err := s.getInboundsBySubId("submt")
+	if err != nil {
+		t.Fatalf("getInboundsBySubId: %v", err)
+	}
+	if len(inbounds) != 1 || inbounds[0].Id != in.Id {
+		t.Fatalf("mtproto inbound not returned for subId: %+v", inbounds)
+	}
+
+	links, emails, _, _, err := s.GetSubs("submt", "sub.example.com")
+	if err != nil {
+		t.Fatalf("GetSubs: %v", err)
+	}
+	if len(links) != 1 || len(emails) != 1 || emails[0] != "u@mt" {
+		t.Fatalf("subscription did not emit the mtproto client: links=%v emails=%v", links, emails)
+	}
+	if !strings.HasPrefix(links[0], "tg://proxy") || !strings.Contains(links[0], "secret="+mtprotoTestSecret) {
+		t.Fatalf("subscription link is not a tg://proxy carrying the client secret: %q", links[0])
+	}
+}

+ 36 - 22
internal/web/job/mtproto_job.go

@@ -10,8 +10,8 @@ import (
 
 // MtprotoJob reconciles the running mtg sidecar processes against the enabled
 // mtproto inbounds in the database, restarts any that crashed, and folds the
-// per-inbound traffic scraped from each mtg metrics endpoint into the usual
-// inbound traffic accounting.
+// per-client traffic scraped from each mtg /stats endpoint into the usual client
+// and inbound traffic accounting.
 type MtprotoJob struct {
 	inboundService service.InboundService
 }
@@ -21,8 +21,8 @@ func NewMtprotoJob() *MtprotoJob {
 	return new(MtprotoJob)
 }
 
-// Run reconciles desired mtproto inbounds with running mtg processes and
-// records traffic deltas.
+// Run reconciles desired mtproto inbounds with running mtg processes and records
+// per-client traffic deltas and online status.
 func (j *MtprotoJob) Run() {
 	inbounds, err := j.inboundService.GetAllInbounds()
 	if err != nil {
@@ -32,12 +32,14 @@ func (j *MtprotoJob) Run() {
 
 	var desired []mtproto.Instance
 	routedTags := make(map[string]bool)
+	activeTags := make([]string, 0)
 	for _, ib := range inbounds {
 		if ib.Protocol != model.MTProto || !ib.Enable || ib.NodeID != nil {
 			continue
 		}
 		if inst, ok := mtproto.InstanceFromInbound(ib); ok {
 			desired = append(desired, inst)
+			activeTags = append(activeTags, inst.Tag)
 			if inst.RouteThroughXray {
 				routedTags[inst.Tag] = true
 			}
@@ -47,29 +49,41 @@ func (j *MtprotoJob) Run() {
 	mgr := mtproto.GetManager()
 	mgr.Reconcile(desired)
 
-	deltas := mgr.CollectTraffic()
-	if len(deltas) == 0 {
-		return
-	}
-	traffics := make([]*xray.Traffic, 0, len(deltas))
+	deltas, onlineEmails := mgr.CollectTraffic()
+
+	// A routed inbound's total is already metered through the Xray bridge by
+	// xray_traffic_job, so only non-routed inbounds are rolled up here; per-client
+	// deltas are always kept, since the bridge cannot tell mtproto users apart.
+	clientTraffics := make([]*xray.ClientTraffic, 0, len(deltas))
+	inboundUp := make(map[string]int64)
+	inboundDown := make(map[string]int64)
 	for _, d := range deltas {
-		// Routed inbounds egress through the Xray SOCKS bridge, which carries the
-		// inbound's tag and is metered by xray_traffic_job. Folding mtg's own
-		// metrics in too would double-count, so skip them here.
-		if routedTags[d.Tag] {
-			continue
+		clientTraffics = append(clientTraffics, &xray.ClientTraffic{
+			Email: d.Email,
+			Up:    d.Up,
+			Down:  d.Down,
+		})
+		if !routedTags[d.Tag] {
+			inboundUp[d.Tag] += d.Up
+			inboundDown[d.Tag] += d.Down
 		}
+	}
+
+	traffics := make([]*xray.Traffic, 0, len(inboundUp))
+	for tag, up := range inboundUp {
 		traffics = append(traffics, &xray.Traffic{
 			IsInbound: true,
-			Tag:       d.Tag,
-			Up:        d.Up,
-			Down:      d.Down,
+			Tag:       tag,
+			Up:        up,
+			Down:      inboundDown[tag],
 		})
 	}
-	if len(traffics) == 0 {
-		return
-	}
-	if _, _, err := j.inboundService.AddTraffic(traffics, nil); err != nil {
-		logger.Warning("mtproto job: add traffic failed:", err)
+
+	if len(traffics) > 0 || len(clientTraffics) > 0 {
+		if _, _, err := j.inboundService.AddTraffic(traffics, clientTraffics); err != nil {
+			logger.Warning("mtproto job: add traffic failed:", err)
+		}
 	}
+
+	j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags)
 }

+ 26 - 0
internal/web/service/client_crud.go

@@ -142,10 +142,36 @@ func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound)
 		if c.Auth == "" {
 			c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
 		}
+	case model.MTProto:
+		if c.Secret == "" {
+			c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
+		}
 	}
 	return nil
 }
 
+// defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
+// inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
+const defaultMtprotoDomain = "www.cloudflare.com"
+
+// mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
+// back to the default when unset, so a generated client secret always fronts a
+// real hostname.
+func mtprotoDomainFromSettings(settings string) string {
+	domain := ""
+	if settings != "" {
+		var m map[string]any
+		if err := json.Unmarshal([]byte(settings), &m); err == nil {
+			domain, _ = m["fakeTlsDomain"].(string)
+		}
+	}
+	domain = strings.TrimSpace(domain)
+	if domain == "" {
+		return defaultMtprotoDomain
+	}
+	return domain
+}
+
 func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
 	if !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
 		c.Flow = ""

+ 6 - 0
internal/web/service/client_inbound_apply.go

@@ -384,6 +384,10 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
 			if client.PublicKey == "" {
 				return false, common.NewError("wireguard client requires a key")
 			}
+		case "mtproto":
+			if client.Secret == "" {
+				return false, common.NewError("mtproto client requires a secret")
+			}
 		default:
 			if client.ID == "" {
 				return false, common.NewError("empty client ID")
@@ -549,6 +553,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
 		newClientId = clients[0].Auth
 	case "wireguard":
 		newClientId = clients[0].Email
+	case "mtproto":
+		newClientId = clients[0].Email
 	default:
 		newClientId = clients[0].ID
 	}

+ 28 - 2
internal/web/service/inbound.go

@@ -303,6 +303,7 @@ type InboundOption struct {
 	WgPublicKey    string `json:"wgPublicKey,omitempty"`
 	WgMtu          int    `json:"wgMtu,omitempty"`
 	WgDns          string `json:"wgDns,omitempty"`
+	MtprotoDomain  string `json:"mtprotoDomain,omitempty"`
 	// Hosting node; nil for this panel's own inbounds. Lets the clients
 	// page map a node filter onto inbound IDs (#4997).
 	NodeId *int `json:"nodeId,omitempty"`
@@ -363,6 +364,7 @@ func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error)
 			WgPublicKey:       wgPublicKey,
 			WgMtu:             wgMtu,
 			WgDns:             wgDns,
+			MtprotoDomain:     inboundMtprotoDomain(r.Protocol, r.Settings),
 			NodeId:            r.NodeId,
 			NodeAddress:       r.NodeAddress,
 			Listen:            r.Listen,
@@ -399,6 +401,22 @@ func inboundWireguardHints(protocol string, settings string) (string, int, strin
 	return publicKey, parsed.MTU, parsed.DNS
 }
 
+// inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
+// the clients UI to seed a new mtproto client's secret with the right fronting
+// hostname.
+func inboundMtprotoDomain(protocol string, settings string) string {
+	if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
+		return ""
+	}
+	var parsed struct {
+		FakeTLSDomain string `json:"fakeTlsDomain"`
+	}
+	if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
+		return ""
+	}
+	return strings.TrimSpace(parsed.FakeTLSDomain)
+}
+
 // GetAllInbounds retrieves all inbounds with client stats.
 func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
 	db := database.GetDB()
@@ -512,8 +530,9 @@ func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
 	}
 }
 
-// normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
-// always valid and matches the configured domain before the row is persisted.
+// normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
+// always valid before the row is persisted. It also heals a legacy inbound-level
+// secret for any inbound that predates the multi-client migration.
 func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
 	if inbound.Protocol != model.MTProto {
 		return
@@ -521,6 +540,9 @@ func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
 	if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
 		inbound.Settings = healed
 	}
+	if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
+		inbound.Settings = healed
+	}
 }
 
 // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
@@ -711,6 +733,10 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
 			if client.Auth == "" {
 				return inbound, false, common.NewError("empty client ID")
 			}
+		case "mtproto":
+			if client.Secret == "" {
+				return inbound, false, common.NewError("mtproto client requires a secret")
+			}
 		default:
 			if client.ID == "" {
 				return inbound, false, common.NewError("empty client ID")

+ 3 - 0
internal/web/service/inbound_clients.go

@@ -212,6 +212,7 @@ func (s *InboundService) buildTargetClientFromSource(source model.Client, target
 	target.Password = ""
 	target.Auth = ""
 	target.Flow = ""
+	target.Secret = ""
 
 	targetProtocol := targetInbound.Protocol
 	switch targetProtocol {
@@ -227,6 +228,8 @@ func (s *InboundService) buildTargetClientFromSource(source model.Client, target
 		target.Password = s.generateRandomCredential(targetProtocol)
 	case model.Hysteria:
 		target.Auth = s.generateRandomCredential(targetProtocol)
+	case model.MTProto:
+		target.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(targetInbound.Settings))
 	default:
 		target.ID = s.generateRandomCredential(targetProtocol)
 	}

+ 49 - 0
internal/web/service/inbound_mtproto_test.go

@@ -1,7 +1,9 @@
 package service
 
 import (
+	"encoding/hex"
 	"encoding/json"
+	"strings"
 	"testing"
 
 	"github.com/mhsanaei/3x-ui/v3/internal/database/model"
@@ -92,3 +94,50 @@ func TestNormalizeMtprotoXrayPort(t *testing.T) {
 		t.Fatalf("disabling routing must drop the inert outbound tag, got %s", ib.Settings)
 	}
 }
+
+func TestFillProtocolDefaultsMtproto(t *testing.T) {
+	cs := &ClientService{}
+	ib := &model.Inbound{Protocol: model.MTProto, Settings: `{"fakeTlsDomain":"example.com"}`}
+
+	c := &model.Client{Email: "u"}
+	if err := cs.fillProtocolDefaults(c, ib); err != nil {
+		t.Fatal(err)
+	}
+	if !strings.HasPrefix(c.Secret, "ee") || !strings.HasSuffix(c.Secret, hex.EncodeToString([]byte("example.com"))) {
+		t.Fatalf("mtproto client should get a FakeTLS secret fronting the inbound domain, got %q", c.Secret)
+	}
+
+	// An existing secret is not overwritten.
+	pre := &model.Client{Email: "v", Secret: "eepreset"}
+	if err := cs.fillProtocolDefaults(pre, ib); err != nil {
+		t.Fatal(err)
+	}
+	if pre.Secret != "eepreset" {
+		t.Fatalf("an existing secret must be preserved, got %q", pre.Secret)
+	}
+
+	// With no inbound domain the default fronting host is used.
+	c2 := &model.Client{Email: "w"}
+	if err := cs.fillProtocolDefaults(c2, &model.Inbound{Protocol: model.MTProto, Settings: `{}`}); err != nil {
+		t.Fatal(err)
+	}
+	if !strings.HasSuffix(c2.Secret, hex.EncodeToString([]byte(defaultMtprotoDomain))) {
+		t.Fatalf("a domainless inbound should front the default host, got %q", c2.Secret)
+	}
+}
+
+func TestNormalizeMtprotoSecretHealsClients(t *testing.T) {
+	s := &InboundService{}
+	ib := &model.Inbound{Protocol: model.MTProto, Settings: `{"fakeTlsDomain":"a.com","clients":[{"email":"x","secret":""}]}`}
+	s.normalizeMtprotoSecret(ib)
+
+	var parsed map[string]any
+	if err := json.Unmarshal([]byte(ib.Settings), &parsed); err != nil {
+		t.Fatalf("healed settings not valid json: %v", err)
+	}
+	clients := parsed["clients"].([]any)
+	got := clients[0].(map[string]any)["secret"].(string)
+	if !strings.HasPrefix(got, "ee") || !strings.HasSuffix(got, hex.EncodeToString([]byte("a.com"))) {
+		t.Fatalf("client secret should be healed to front the inbound domain, got %q", got)
+	}
+}

+ 5 - 0
internal/web/translation/ar-EG.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "الصادر",
         "mtgRouteOutboundHint": "اختياري. إجبار حركة Telegram على الخروج عبر هذا الصادر (أو الموازِن). اتركه فارغًا لتقرر قواعد التوجيه.",
         "mtgRouteOutboundPlaceholder": "استخدام قواعد التوجيه",
+        "mtprotoFakeTlsDomainHint": "نطاق FakeTLS الافتراضي المستخدم لإنشاء سر عميل جديد. يمكن لكل عميل استخدام نطاقه الخاص.",
+        "mtgThrottleMaxConnections": "الحد الأقصى للاتصالات",
+        "mtgThrottleMaxConnectionsHint": "تحديد الاتصالات المتزامنة لجميع المستخدمين بتوزيع عادل. القيمة 0 تعطّل الميزة.",
         "visionTestseed": "Vision testseed",
         "version": "الإصدار",
         "udpIdleTimeout": "UDP idle timeout (ثانية)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "مفتاح وايرغارد المشترك مسبقًا",
       "wireguardAllowedIPs": "عناوين IP المسموحة لوايرغارد",
       "wireguardAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
+      "mtprotoSecret": "سر MTProto",
+      "mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.",
       "reverseTag": "وسم عكسي",
       "reverseTagPlaceholder": "Reverse tag اختياري",
       "telegramId": "معرّف مستخدم تلغرام",

+ 5 - 0
internal/web/translation/en-US.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "Outbound",
         "mtgRouteOutboundHint": "Optional. Force Telegram traffic out through this outbound (or balancer). Leave empty to let your routing rules decide.",
         "mtgRouteOutboundPlaceholder": "Use routing rules",
+        "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.",
         "visionTestseed": "Vision testseed",
         "version": "Version",
         "udpIdleTimeout": "UDP idle timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "WireGuard Pre-Shared Key",
       "wireguardAllowedIPs": "WireGuard Allowed IPs",
       "wireguardAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
+      "mtprotoSecret": "MTProto secret",
+      "mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.",
       "reverseTag": "Reverse tag",
       "reverseTagPlaceholder": "Optional reverse tag",
       "telegramId": "Telegram user ID",

+ 5 - 0
internal/web/translation/es-ES.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "Salida",
         "mtgRouteOutboundHint": "Opcional. Fuerza el tráfico de Telegram a salir por esta salida (o balanceador). Déjalo vacío para que decidan tus reglas de enrutamiento.",
         "mtgRouteOutboundPlaceholder": "Usar reglas de enrutamiento",
+        "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.",
         "visionTestseed": "Vision testseed",
         "version": "Versión",
         "udpIdleTimeout": "UDP idle timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Clave precompartida de WireGuard",
       "wireguardAllowedIPs": "IP permitidas de WireGuard",
       "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.",
       "reverseTag": "Etiqueta inversa",
       "reverseTagPlaceholder": "Reverse tag opcional",
       "telegramId": "ID de usuario de Telegram",

+ 5 - 0
internal/web/translation/fa-IR.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "خروجی",
         "mtgRouteOutboundHint": "اختیاری. ترافیک تلگرام را وادار کنید از این خروجی (یا متعادل‌کننده) خارج شود. برای اینکه قوانین مسیریابی تصمیم بگیرند، خالی بگذارید.",
         "mtgRouteOutboundPlaceholder": "استفاده از قوانین مسیریابی",
+        "mtprotoFakeTlsDomainHint": "دامنه پیش‌فرض FakeTLS برای ساخت سکرت کلاینت جدید. هر کلاینت می‌تواند دامنه مخصوص خود را داشته باشد.",
+        "mtgThrottleMaxConnections": "حداکثر اتصالات",
+        "mtgThrottleMaxConnectionsHint": "محدود کردن اتصالات همزمان همه کاربران با تقسیم منصفانه. مقدار ۰ غیرفعال است.",
         "visionTestseed": "Vision testseed",
         "version": "نسخه",
         "udpIdleTimeout": "UDP idle timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "کلید پیش‌اشتراکی وایرگارد",
       "wireguardAllowedIPs": "آی‌پی‌های مجاز وایرگارد",
       "wireguardAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودی‌ها را با کاما جدا کنید",
+      "mtprotoSecret": "سکرت MTProto",
+      "mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.",
       "reverseTag": "تگ معکوس",
       "reverseTagPlaceholder": "Reverse tag اختیاری",
       "telegramId": "شناسه کاربر تلگرام",

+ 5 - 0
internal/web/translation/id-ID.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "Outbound",
         "mtgRouteOutboundHint": "Opsional. Paksa lalu lintas Telegram keluar melalui outbound (atau balancer) ini. Biarkan kosong agar aturan routing yang menentukan.",
         "mtgRouteOutboundPlaceholder": "Gunakan aturan routing",
+        "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.",
         "visionTestseed": "Vision testseed",
         "version": "Versi",
         "udpIdleTimeout": "UDP idle timeout (d)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Kunci Pra-Berbagi WireGuard",
       "wireguardAllowedIPs": "IP yang Diizinkan WireGuard",
       "wireguardAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
+      "mtprotoSecret": "Secret MTProto",
+      "mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.",
       "reverseTag": "Reverse tag",
       "reverseTagPlaceholder": "Reverse tag opsional",
       "telegramId": "ID pengguna Telegram",

+ 5 - 0
internal/web/translation/ja-JP.json

@@ -543,6 +543,9 @@
         "mtgRouteOutbound": "アウトバウンド",
         "mtgRouteOutboundHint": "任意。Telegram トラフィックをこのアウトバウンド(またはバランサー)から強制的に送出します。空欄にするとルーティングルールに従います。",
         "mtgRouteOutboundPlaceholder": "ルーティングルールを使用",
+        "mtprotoFakeTlsDomainHint": "新しいクライアントのシークレット生成に使う既定の FakeTLS ドメイン。クライアントごとに別のドメインを使用できます。",
+        "mtgThrottleMaxConnections": "最大接続数",
+        "mtgThrottleMaxConnectionsHint": "全ユーザーの同時接続数を公平配分で制限します。0 で無効。",
         "visionTestseed": "Vision testseed",
         "version": "バージョン",
         "udpIdleTimeout": "UDP idle timeout (秒)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "WireGuard 事前共有鍵",
       "wireguardAllowedIPs": "WireGuard 許可IP",
       "wireguardAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
+      "mtprotoSecret": "MTProto シークレット",
+      "mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。",
       "reverseTag": "Reverse tag",
       "reverseTagPlaceholder": "任意の Reverse tag",
       "telegramId": "Telegram ユーザー ID",

+ 5 - 0
internal/web/translation/pt-BR.json

@@ -543,6 +543,9 @@
         "mtgRouteOutbound": "Saída",
         "mtgRouteOutboundHint": "Opcional. Force o tráfego do Telegram a sair por esta saída (ou balanceador). Deixe vazio para que suas regras de roteamento decidam.",
         "mtgRouteOutboundPlaceholder": "Usar regras de roteamento",
+        "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.",
         "visionTestseed": "Vision testseed",
         "version": "Versão",
         "udpIdleTimeout": "UDP idle timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Chave pré-compartilhada do WireGuard",
       "wireguardAllowedIPs": "IPs permitidos do WireGuard",
       "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.",
       "reverseTag": "Tag reversa",
       "reverseTagPlaceholder": "Reverse tag opcional",
       "telegramId": "ID de usuário do Telegram",

+ 5 - 0
internal/web/translation/ru-RU.json

@@ -543,6 +543,9 @@
         "mtgRouteOutbound": "Исходящее",
         "mtgRouteOutboundHint": "Необязательно. Принудительно направить трафик Telegram через это исходящее соединение (или балансировщик). Оставьте пустым, чтобы решали ваши правила маршрутизации.",
         "mtgRouteOutboundPlaceholder": "Использовать правила маршрутизации",
+        "mtprotoFakeTlsDomainHint": "Домен FakeTLS по умолчанию для генерации секрета нового клиента. Каждый клиент может использовать свой домен.",
+        "mtgThrottleMaxConnections": "Макс. подключений",
+        "mtgThrottleMaxConnectionsHint": "Ограничение одновременных подключений всех пользователей по справедливому распределению. 0 — отключено.",
         "visionTestseed": "Vision testseed",
         "version": "Версия",
         "udpIdleTimeout": "UDP idle timeout (с)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Общий ключ WireGuard",
       "wireguardAllowedIPs": "Разрешённые IP WireGuard",
       "wireguardAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
+      "mtprotoSecret": "Секрет MTProto",
+      "mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.",
       "reverseTag": "Обратный тег",
       "reverseTagPlaceholder": "Необязательный Reverse tag",
       "telegramId": "ID пользователя Telegram",

+ 5 - 0
internal/web/translation/tr-TR.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "Giden",
         "mtgRouteOutboundHint": "İsteğe bağlı. Telegram trafiğini bu giden bağlantı (veya dengeleyici) üzerinden çıkmaya zorlar. Yönlendirme kurallarınızın karar vermesi için boş bırakın.",
         "mtgRouteOutboundPlaceholder": "Yönlendirme kurallarını kullan",
+        "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.",
         "visionTestseed": "Vision Testseed",
         "version": "Sürüm",
         "udpIdleTimeout": "UDP Idle Timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "WireGuard Ön Paylaşımlı Anahtar",
       "wireguardAllowedIPs": "WireGuard İzin Verilen IP'ler",
       "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.",
       "reverseTag": "Reverse Tag",
       "reverseTagPlaceholder": "İsteğe Bağlı Reverse Tag",
       "telegramId": "Telegram Kullanıcı ID'si",

+ 5 - 0
internal/web/translation/uk-UA.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "Вихідне",
         "mtgRouteOutboundHint": "Необов'язково. Примусово спрямувати трафік Telegram через це вихідне з'єднання (або балансувальник). Залиште порожнім, щоб вирішували ваші правила маршрутизації.",
         "mtgRouteOutboundPlaceholder": "Використовувати правила маршрутизації",
+        "mtprotoFakeTlsDomainHint": "Домен FakeTLS за замовчуванням для генерації секрету нового клієнта. Кожен клієнт може використовувати власний домен.",
+        "mtgThrottleMaxConnections": "Макс. з'єднань",
+        "mtgThrottleMaxConnectionsHint": "Обмеження одночасних з'єднань усіх користувачів зі справедливим розподілом. 0 — вимкнено.",
         "visionTestseed": "Vision testseed",
         "version": "Версія",
         "udpIdleTimeout": "UDP idle timeout (с)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Спільний ключ WireGuard",
       "wireguardAllowedIPs": "Дозволені IP WireGuard",
       "wireguardAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
+      "mtprotoSecret": "Секрет MTProto",
+      "mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.",
       "reverseTag": "Зворотний тег",
       "reverseTagPlaceholder": "Необов'язковий Reverse tag",
       "telegramId": "ID користувача Telegram",

+ 5 - 0
internal/web/translation/vi-VN.json

@@ -543,6 +543,9 @@
         "mtgRouteOutbound": "Outbound",
         "mtgRouteOutboundHint": "Tùy chọn. Buộc lưu lượng Telegram đi ra qua outbound (hoặc bộ cân bằng) này. Để trống để các quy tắc định tuyến của bạn quyết định.",
         "mtgRouteOutboundPlaceholder": "Dùng quy tắc định tuyến",
+        "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.",
         "visionTestseed": "Vision testseed",
         "version": "Phiên bản",
         "udpIdleTimeout": "UDP idle timeout (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "Khóa chia sẻ trước WireGuard",
       "wireguardAllowedIPs": "IP được phép WireGuard",
       "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.",
       "reverseTag": "Reverse tag",
       "reverseTagPlaceholder": "Reverse tag tùy chọn",
       "telegramId": "ID người dùng Telegram",

+ 5 - 0
internal/web/translation/zh-CN.json

@@ -542,6 +542,9 @@
         "mtgRouteOutbound": "出站",
         "mtgRouteOutboundHint": "可选。强制 Telegram 流量经由此出站(或负载均衡器)发出。留空则由您的路由规则决定。",
         "mtgRouteOutboundPlaceholder": "使用路由规则",
+        "mtprotoFakeTlsDomainHint": "生成新客户端密钥时使用的默认 FakeTLS 域名。每个客户端可使用各自的域名。",
+        "mtgThrottleMaxConnections": "最大连接数",
+        "mtgThrottleMaxConnectionsHint": "按公平分配限制所有用户的并发连接数。0 表示不限制。",
         "visionTestseed": "Vision testseed",
         "version": "版本",
         "udpIdleTimeout": "UDP 空闲超时 (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "WireGuard 预共享密钥",
       "wireguardAllowedIPs": "WireGuard 允许的 IP",
       "wireguardAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
+      "mtprotoSecret": "MTProto 密钥",
+      "mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。",
       "reverseTag": "反向标签",
       "reverseTagPlaceholder": "可选 Reverse tag",
       "telegramId": "Telegram 用户 ID",

+ 5 - 0
internal/web/translation/zh-TW.json

@@ -522,6 +522,9 @@
         "mtgRouteOutbound": "出站",
         "mtgRouteOutboundHint": "選填。強制 Telegram 流量經由此出站(或負載平衡器)送出。留空則由您的路由規則決定。",
         "mtgRouteOutboundPlaceholder": "使用路由規則",
+        "mtprotoFakeTlsDomainHint": "產生新用戶端金鑰時使用的預設 FakeTLS 網域。每個用戶端可使用各自的網域。",
+        "mtgThrottleMaxConnections": "最大連線數",
+        "mtgThrottleMaxConnectionsHint": "以公平分配限制所有使用者的並行連線數。0 表示不限制。",
         "visionTestseed": "Vision testseed",
         "version": "版本",
         "udpIdleTimeout": "UDP 閒置逾時 (s)",
@@ -907,6 +910,8 @@
       "wireguardPreSharedKey": "WireGuard 預共用金鑰",
       "wireguardAllowedIPs": "WireGuard 允許的 IP",
       "wireguardAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
+      "mtprotoSecret": "MTProto 金鑰",
+      "mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。",
       "reverseTag": "反向標籤",
       "reverseTagPlaceholder": "選用 Reverse tag",
       "telegramId": "Telegram 使用者 ID",

+ 9 - 0
update.sh

@@ -1053,9 +1053,18 @@ update_x-ui() {
     if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
         mv bin/xray-linux-$(arch) bin/xray-linux-arm32 > /dev/null 2>&1
         chmod +x bin/xray-linux-arm32 > /dev/null 2>&1
+        if [[ -f bin/mtg-linux-$(arch) ]]; then
+            mv bin/mtg-linux-$(arch) bin/mtg-linux-arm > /dev/null 2>&1
+            chmod +x bin/mtg-linux-arm > /dev/null 2>&1
+        fi
     fi
 
     chmod +x x-ui bin/xray-linux-$(arch) > /dev/null 2>&1
+    if [[ -f bin/mtg-linux-arm ]]; then
+        chmod +x bin/mtg-linux-arm > /dev/null 2>&1
+    elif [[ -f bin/mtg-linux-$(arch) ]]; then
+        chmod +x bin/mtg-linux-$(arch) > /dev/null 2>&1
+    fi
 
     echo -e "${green}Downloading and installing x-ui.sh script...${plain}"
     local xui_script_temp="/usr/bin/x-ui-temp.$$"