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.
This commit is contained in:
MHSanaei
2026-07-06 16:04:32 +02:00
parent 5e9606aa4d
commit d97bd8643e
54 changed files with 1160 additions and 453 deletions
+130 -1
View File
@@ -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
View File
@@ -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)
@@ -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
View File
@@ -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)
}
// 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) {
// 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"`
}
// 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
var parsed struct {
Users map[string]statsUser `json:"users"`
}
if err := scanner.Err(); err != nil {
logger.Debug("mtproto: metrics scan error:", err)
if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
return nil, false
}
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")
}
value, err = strconv.ParseFloat(valFields[0], 64)
if err != nil {
return "", nil, 0, err
}
return name, labels, value, nil
return parsed.Users, true
}
+54 -88
View File
@@ -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 '{'")
}
})
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 '}'")
}
})
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)
}
})
// 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
}
// 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)
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
}
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)
}
})
_, _ = 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("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)
}
})
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"])
}
}
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()
if _, ok := scrapeStats(port); ok {
t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable")
}
}
+68 -47
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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 = ""
@@ -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
View File
@@ -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
View File
@@ -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)
}
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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",