feat(mtproto): per-client ad-tags, management-API auth, and record secret sync

Catch the panel up to the mtg-multi README (v1.14.0):

- Each client can now carry its own 32-hex advertising tag overriding the
  inbound-level one. The tag lives on the client (settings JSON is the
  source of truth, clients.ad_tag is the UI projection), is rendered into
  the fork's [secret-ad-tags] section for active secrets only (mtg rejects
  a config whose override names an unknown secret), is pushed per entry
  through PUT /secrets, and is part of the reload fingerprint so a tag
  edit hot-applies without dropping connections.
- The loopback management API can replace the whole secret set, so every
  mtg process now gets a random per-process api-token; the manager sends
  it as a bearer token on PUT /secrets and GET /stats and reuses it across
  config rewrites, because mtg reads the token only at startup.
- Malformed tags are rejected at every save path and additionally dropped
  in InstanceFromInbound: one bad tag would otherwise fail the whole
  generated config and take every client of the inbound down with it.
- SyncInbound never copied a re-keyed mtproto secret into the canonical
  clients table, so the clients page and subscription links kept serving
  the old secret, which mtg then rejects. It is now guarded-copied like
  the other credentials.
This commit is contained in:
MHSanaei
2026-07-07 12:00:43 +02:00
parent 659f0f404c
commit 43500a5470
33 changed files with 361 additions and 54 deletions
+5 -3
View File
@@ -14,9 +14,11 @@ file locations when it can answer in one hop.
API. MTProto inbounds run a second managed child — the `mtg-multi` binary API. MTProto inbounds run a second managed child — the `mtg-multi` binary
(`github.com/mhsanaei/mtg-multi`, a multi-secret fork built from source; (`github.com/mhsanaei/mtg-multi`, a multi-secret fork built from source;
`internal/mtproto/`) — outside Xray, one process per inbound serving each `internal/mtproto/`) — outside Xray, one process per inbound serving each
client's FakeTLS secret via the fork's `[secrets]` section. Client edits are client's FakeTLS secret via the fork's `[secrets]` section (plus per-client
hot-applied through the fork's `POST /reload` so connections survive; the ad-tags via `[secret-ad-tags]`). Client and ad-tag edits are hot-applied
manager falls back to a process restart on older binaries. through the fork's management API (`PUT /secrets`, bearer-token guarded) so
connections survive; the manager falls back to a process restart on older
binaries.
- Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux; the executable dir on - 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 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. driver (`mattn/go-sqlite3`) needs a C compiler — `CGO_ENABLED=0` builds fail.
+4 -3
View File
@@ -22,9 +22,10 @@ separate HTTP server serves **subscription links** to end users.
The panel supervises **two managed child processes**: Xray-core itself and — when MTProto The panel supervises **two managed child processes**: Xray-core itself and — when MTProto
inbounds exist — the `mtg-multi` Telegram-proxy binary (`github.com/mhsanaei/mtg-multi`, a inbounds exist — the `mtg-multi` Telegram-proxy binary (`github.com/mhsanaei/mtg-multi`, a
multi-secret fork built from source; `internal/mtproto/`). One process per inbound serves 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. A client edit every attached client's FakeTLS secret through the fork's `[secrets]` section, plus optional
is hot-applied via the fork's `POST /reload` endpoint (connections survive), with a process per-client sponsored-channel ad-tags via `[secret-ad-tags]`. A client or ad-tag edit is
restart as the fallback on older binaries. hot-applied via the fork's management API (`PUT /secrets`, guarded by a per-process bearer
token), with a process restart as the fallback on older binaries.
Servers and processes, all launched from `main.go`: Servers and processes, all launched from `main.go`:
+8
View File
@@ -1092,6 +1092,10 @@
"Client": { "Client": {
"description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.",
"properties": { "properties": {
"adTag": {
"example": "0123456789abcdef0123456789abcdef",
"type": "string"
},
"allowedIPs": { "allowedIPs": {
"items": { "items": {
"type": "string" "type": "string"
@@ -1231,6 +1235,9 @@
}, },
"ClientRecord": { "ClientRecord": {
"properties": { "properties": {
"adTag": {
"type": "string"
},
"allowedIPs": { "allowedIPs": {
"type": "string" "type": "string"
}, },
@@ -1306,6 +1313,7 @@
} }
}, },
"required": [ "required": [
"adTag",
"allowedIPs", "allowedIPs",
"auth", "auth",
"comment", "comment",
+2
View File
@@ -214,6 +214,7 @@ export const EXAMPLES: Record<string, unknown> = {
"token": "new-token-string" "token": "new-token-string"
}, },
"Client": { "Client": {
"adTag": "0123456789abcdef0123456789abcdef",
"allowedIPs": [ "allowedIPs": [
"" ""
], ],
@@ -248,6 +249,7 @@ export const EXAMPLES: Record<string, unknown> = {
"inboundId": 0 "inboundId": 0
}, },
"ClientRecord": { "ClientRecord": {
"adTag": "",
"allowedIPs": "", "allowedIPs": "",
"auth": "", "auth": "",
"comment": "", "comment": "",
+8
View File
@@ -1066,6 +1066,10 @@ export const SCHEMAS: Record<string, unknown> = {
"Client": { "Client": {
"description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.",
"properties": { "properties": {
"adTag": {
"example": "0123456789abcdef0123456789abcdef",
"type": "string"
},
"allowedIPs": { "allowedIPs": {
"items": { "items": {
"type": "string" "type": "string"
@@ -1205,6 +1209,9 @@ export const SCHEMAS: Record<string, unknown> = {
}, },
"ClientRecord": { "ClientRecord": {
"properties": { "properties": {
"adTag": {
"type": "string"
},
"allowedIPs": { "allowedIPs": {
"type": "string" "type": "string"
}, },
@@ -1280,6 +1287,7 @@ export const SCHEMAS: Record<string, unknown> = {
} }
}, },
"required": [ "required": [
"adTag",
"allowedIPs", "allowedIPs",
"auth", "auth",
"comment", "comment",
+2
View File
@@ -224,6 +224,7 @@ export interface ApiTokenView {
} }
export interface Client { export interface Client {
adTag?: string;
allowedIPs?: string[]; allowedIPs?: string[];
auth?: string; auth?: string;
comment: string; comment: string;
@@ -258,6 +259,7 @@ export interface ClientInbound {
} }
export interface ClientRecord { export interface ClientRecord {
adTag: string;
allowedIPs: string; allowedIPs: string;
auth: string; auth: string;
comment: string; comment: string;
+2
View File
@@ -240,6 +240,7 @@ export const ApiTokenViewSchema = z.object({
export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>; export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>;
export const ClientSchema = z.object({ export const ClientSchema = z.object({
adTag: z.string().optional(),
allowedIPs: z.array(z.string()).optional(), allowedIPs: z.array(z.string()).optional(),
auth: z.string().optional(), auth: z.string().optional(),
comment: z.string(), comment: z.string(),
@@ -276,6 +277,7 @@ export const ClientInboundSchema = z.object({
export type ClientInbound = z.infer<typeof ClientInboundSchema>; export type ClientInbound = z.infer<typeof ClientInboundSchema>;
export const ClientRecordSchema = z.object({ export const ClientRecordSchema = z.object({
adTag: z.string(),
allowedIPs: z.string(), allowedIPs: z.string(),
auth: z.string(), auth: z.string(),
comment: z.string(), comment: z.string(),
+25 -6
View File
@@ -119,6 +119,7 @@ interface FormState {
wgPreSharedKey: string; wgPreSharedKey: string;
wgAllowedIPs: string; wgAllowedIPs: string;
secret: string; secret: string;
adTag: string;
} }
function emptyForm(): FormState { function emptyForm(): FormState {
@@ -148,6 +149,7 @@ function emptyForm(): FormState {
wgPreSharedKey: '', wgPreSharedKey: '',
wgAllowedIPs: '', wgAllowedIPs: '',
secret: '', secret: '',
adTag: '',
}; };
} }
@@ -253,6 +255,7 @@ export default function ClientFormModal({
wgPreSharedKey: client.preSharedKey || '', wgPreSharedKey: client.preSharedKey || '',
wgAllowedIPs: client.allowedIPs || '', wgAllowedIPs: client.allowedIPs || '',
secret: client.secret || '', secret: client.secret || '',
adTag: client.adTag || '',
}; };
if (et < 0) { if (et < 0) {
next.delayedStart = true; next.delayedStart = true;
@@ -538,7 +541,13 @@ export default function ClientFormModal({
} }
if (showMtproto) { if (showMtproto) {
const adTag = form.adTag.trim();
if (adTag !== '' && !/^[0-9a-fA-F]{32}$/.test(adTag)) {
messageApi.error(t('pages.inbounds.form.mtgAdTagInvalid'));
return;
}
clientPayload.secret = form.secret; clientPayload.secret = form.secret;
clientPayload.adTag = adTag;
} }
const externalLinks: ExternalLinkInput[] = form.externalLinks const externalLinks: ExternalLinkInput[] = form.externalLinks
@@ -862,12 +871,22 @@ export default function ClientFormModal({
</> </>
)} )}
{showMtproto && ( {showMtproto && (
<Form.Item label={t('pages.clients.mtprotoSecret')} extra={t('pages.clients.mtprotoSecretHint')}> <>
<Space.Compact style={{ display: 'flex' }}> <Form.Item label={t('pages.clients.mtprotoSecret')} extra={t('pages.clients.mtprotoSecretHint')}>
<Input value={form.secret} style={{ flex: 1 }} onChange={(e) => update('secret', e.target.value)} /> <Space.Compact style={{ display: 'flex' }}>
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={regenerateMtprotoSecret} /> <Input value={form.secret} style={{ flex: 1 }} onChange={(e) => update('secret', e.target.value)} />
</Space.Compact> <Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={regenerateMtprotoSecret} />
</Form.Item> </Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.mtprotoAdTag')} extra={t('pages.clients.mtprotoAdTagHint')}>
<Input
value={form.adTag}
allowClear
placeholder="0123456789abcdef0123456789abcdef"
onChange={(e) => update('adTag', e.target.value)}
/>
</Form.Item>
</>
)} )}
</> </>
), ),
+1
View File
@@ -38,6 +38,7 @@ export const ClientRecordSchema = z.object({
preSharedKey: z.string().optional(), preSharedKey: z.string().optional(),
keepAlive: z.number().optional(), keepAlive: z.number().optional(),
secret: z.string().optional(), secret: z.string().optional(),
adTag: z.string().optional(),
createdAt: z.number().optional(), createdAt: z.number().optional(),
updatedAt: z.number().optional(), updatedAt: z.number().optional(),
}).loose(); }).loose();
@@ -17,6 +17,11 @@ export type MtprotoDomainFronting = z.infer<typeof MtprotoDomainFrontingSchema>;
// default domain used when generating a new client's secret. // default domain used when generating a new client's secret.
export const MtprotoClientSchema = z.object({ export const MtprotoClientSchema = z.object({
secret: z.string().default(''), secret: z.string().default(''),
adTag: z
.string()
.regex(/^[0-9a-fA-F]{32}$/, 'pages.inbounds.form.mtgAdTagInvalid')
.or(z.literal(''))
.optional(),
email: z.string().min(1), email: z.string().min(1),
limitIp: z.number().int().min(0).default(0), limitIp: z.number().int().min(0).default(0),
totalGB: z.number().int().min(0).default(0), totalGB: z.number().int().min(0).default(0),
+16
View File
@@ -456,6 +456,18 @@ func mtprotoSecretMiddle(secret string) string {
return mtprotoRandomMiddle() return mtprotoRandomMiddle()
} }
// ValidMtprotoAdTag reports whether a Telegram advertising tag from
// @MTProxybot is well-formed: exactly 16 bytes as 32 hex characters. mtg
// refuses to start (or rejects a live update) on a malformed tag, so every
// write path validates before the tag can reach a generated config.
func ValidMtprotoAdTag(tag string) bool {
if len(tag) != 32 {
return false
}
_, err := hex.DecodeString(tag)
return err == nil
}
// StripMtprotoInboundSecret removes the vestigial inbound-level `secret` from an // StripMtprotoInboundSecret removes the vestigial inbound-level `secret` from an
// mtproto inbound's settings JSON. MTProto is multi-client: every secret lives on // mtproto inbound's settings JSON. MTProto is multi-client: every secret lives on
// a client, and mtg's [secrets] config plus every share link read only the // a client, and mtg's [secrets] config plus every share link read only the
@@ -666,6 +678,7 @@ type Client struct {
PreSharedKey string `json:"preSharedKey,omitempty"` PreSharedKey string `json:"preSharedKey,omitempty"`
KeepAlive int `json:"keepAlive,omitempty"` KeepAlive int `json:"keepAlive,omitempty"`
Secret string `json:"secret,omitempty" example:"ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"` Secret string `json:"secret,omitempty" example:"ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"`
AdTag string `json:"adTag,omitempty" example:"0123456789abcdef0123456789abcdef"`
Email string `json:"email"` // Client email identifier Email string `json:"email"` // Client email identifier
LimitIP int `json:"limitIp"` // IP limit for this client LimitIP int `json:"limitIp"` // IP limit for this client
TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
@@ -696,6 +709,7 @@ type ClientRecord struct {
PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"` PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"`
KeepAlive int `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"` KeepAlive int `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`
Secret string `json:"secret" gorm:"column:secret"` Secret string `json:"secret" gorm:"column:secret"`
AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"`
LimitIP int `json:"limitIp" gorm:"column:limit_ip"` LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
TotalGB int64 `json:"totalGB" gorm:"column:total_gb"` TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"` ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
@@ -880,6 +894,7 @@ func (c *Client) ToRecord() *ClientRecord {
PreSharedKey: c.PreSharedKey, PreSharedKey: c.PreSharedKey,
KeepAlive: c.KeepAlive, KeepAlive: c.KeepAlive,
Secret: c.Secret, Secret: c.Secret,
AdTag: c.AdTag,
} }
if c.Reverse != nil { if c.Reverse != nil {
if b, err := json.Marshal(c.Reverse); err == nil { if b, err := json.Marshal(c.Reverse); err == nil {
@@ -932,6 +947,7 @@ func (r *ClientRecord) ToClient() *Client {
PreSharedKey: r.PreSharedKey, PreSharedKey: r.PreSharedKey,
KeepAlive: r.KeepAlive, KeepAlive: r.KeepAlive,
Secret: r.Secret, Secret: r.Secret,
AdTag: r.AdTag,
} }
if r.Reverse != "" { if r.Reverse != "" {
var rev ClientReverse var rev ClientReverse
+93 -25
View File
@@ -3,6 +3,8 @@ package mtproto
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/rand"
"encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net" "net"
@@ -20,10 +22,13 @@ import (
// SecretEntry is one named FakeTLS secret served by an mtg-multi process. Name is // 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 // 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. // /stats API so traffic can be attributed back to the client. AdTag is the
// client's own advertising-tag override, emitted into the [secret-ad-tags]
// section; empty falls back to the instance-level tag.
type SecretEntry struct { type SecretEntry struct {
Name string Name string
Secret string Secret string
AdTag string
} }
// Instance is the desired runtime configuration of one mtproto inbound. A single // Instance is the desired runtime configuration of one mtproto inbound. A single
@@ -98,13 +103,13 @@ func (inst Instance) structuralFingerprint() string {
// secretsFingerprint identifies the reloadable secret config regardless of // secretsFingerprint identifies the reloadable secret config regardless of
// client order, so a reordered clients array in the stored settings does not // client order, so a reordered clients array in the stored settings does not
// read as a change. It moves whenever a client is added, removed, disabled, or // read as a change. It moves whenever a client is added, removed, disabled,
// re-keyed, or the advertising tag changes — all of which mtg applies through // re-keyed, or re-tagged, or the global advertising tag changes — all of which
// /reload without dropping connections. // mtg applies in place without dropping connections.
func (inst Instance) secretsFingerprint() string { func (inst Instance) secretsFingerprint() string {
pairs := make([]string, 0, len(inst.Secrets)) pairs := make([]string, 0, len(inst.Secrets))
for _, e := range inst.Secrets { for _, e := range inst.Secrets {
pairs = append(pairs, e.Name+"="+e.Secret) pairs = append(pairs, e.Name+"="+e.Secret+";tag="+e.AdTag)
} }
slices.Sort(pairs) slices.Sort(pairs)
return "adtag=" + inst.AdTag + "|" + strings.Join(pairs, "|") return "adtag=" + inst.AdTag + "|" + strings.Join(pairs, "|")
@@ -130,6 +135,7 @@ type managed struct {
structuralFP string structuralFP string
secretsFP string secretsFP string
apiPort int apiPort int
apiToken string
last map[string]clientCounters last map[string]clientCounters
} }
@@ -183,6 +189,7 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
Clients []struct { Clients []struct {
Email string `json:"email"` Email string `json:"email"`
Secret string `json:"secret"` Secret string `json:"secret"`
AdTag string `json:"adTag"`
Enable bool `json:"enable"` Enable bool `json:"enable"`
} `json:"clients"` } `json:"clients"`
} }
@@ -194,7 +201,7 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
if !c.Enable || c.Secret == "" || c.Email == "" { if !c.Enable || c.Secret == "" || c.Email == "" {
continue continue
} }
secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret}) secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret, AdTag: usableAdTag(c.AdTag)})
} }
if len(secrets) == 0 { if len(secrets) == 0 {
return Instance{}, false return Instance{}, false
@@ -214,12 +221,24 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
ThrottleMaxConnections: parsed.ThrottleMaxConnections, ThrottleMaxConnections: parsed.ThrottleMaxConnections,
RouteThroughXray: parsed.RouteThroughXray, RouteThroughXray: parsed.RouteThroughXray,
XrayRoutePort: parsed.RouteXrayPort, XrayRoutePort: parsed.RouteXrayPort,
AdTag: strings.TrimSpace(parsed.AdTag), AdTag: usableAdTag(parsed.AdTag),
PublicIPv4: strings.TrimSpace(parsed.PublicIPv4), PublicIPv4: strings.TrimSpace(parsed.PublicIPv4),
PublicIPv6: strings.TrimSpace(parsed.PublicIPv6), PublicIPv6: strings.TrimSpace(parsed.PublicIPv6),
}, true }, true
} }
// usableAdTag returns a stored advertising tag only when it is well-formed.
// The save paths validate tags, but settings can arrive from raw API payloads
// or older data, and one malformed tag in a generated config makes mtg reject
// the whole file — taking every client of the inbound down with it.
func usableAdTag(tag string) string {
tag = strings.TrimSpace(tag)
if !model.ValidMtprotoAdTag(tag) {
return ""
}
return tag
}
// Ensure starts the mtg process for an instance, or restarts it when its // Ensure starts the mtg process for an instance, or restarts it when its
// configuration changed. A no-op when the desired process is already running. // configuration changed. A no-op when the desired process is already running.
func (m *Manager) Ensure(inst Instance) error { func (m *Manager) Ensure(inst Instance) error {
@@ -277,10 +296,10 @@ func (m *Manager) ensureLocked(inst Instance) error {
cur.tag = inst.Tag cur.tag = inst.Tag
return nil return nil
case ensureReload: case ensureReload:
if err := writeConfig(configPathForID(inst.Id), inst, cur.apiPort); err != nil { if err := writeConfig(configPathForID(inst.Id), inst, cur.apiPort, cur.apiToken); err != nil {
return err return err
} }
if applySecrets(cur.apiPort, inst) { if applySecrets(cur.apiPort, cur.apiToken, inst) {
cur.tag = inst.Tag cur.tag = inst.Tag
cur.secretsFP = secFP cur.secretsFP = secFP
logger.Infof("mtproto: applied secret update to inbound %d in place", inst.Id) logger.Infof("mtproto: applied secret update to inbound %d in place", inst.Id)
@@ -297,8 +316,12 @@ func (m *Manager) ensureLocked(inst Instance) error {
if err != nil { if err != nil {
return err return err
} }
apiToken, err := newAPIToken()
if err != nil {
return err
}
cfgPath := configPathForID(inst.Id) cfgPath := configPathForID(inst.Id)
if err := writeConfig(cfgPath, inst, apiPort); err != nil { if err := writeConfig(cfgPath, inst, apiPort, apiToken); err != nil {
return err return err
} }
proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id)) proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id))
@@ -311,6 +334,7 @@ func (m *Manager) ensureLocked(inst Instance) error {
structuralFP: structFP, structuralFP: structFP,
secretsFP: secFP, secretsFP: secFP,
apiPort: apiPort, apiPort: apiPort,
apiToken: apiToken,
last: map[string]clientCounters{}, last: map[string]clientCounters{},
} }
logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo()) logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo())
@@ -370,10 +394,11 @@ func (m *Manager) StopAll() {
// with at least one live connection. // with at least one live connection.
func (m *Manager) CollectTraffic() ([]Traffic, []string) { func (m *Manager) CollectTraffic() ([]Traffic, []string) {
type snap struct { type snap struct {
id int id int
apiPort int apiPort int
tag string apiToken string
last map[string]clientCounters tag string
last map[string]clientCounters
} }
m.mu.Lock() m.mu.Lock()
snaps := make([]snap, 0, len(m.procs)) snaps := make([]snap, 0, len(m.procs))
@@ -385,14 +410,14 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) {
for k, v := range cur.last { for k, v := range cur.last {
lastCopy[k] = v lastCopy[k] = v
} }
snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, tag: cur.tag, last: lastCopy}) snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy})
} }
m.mu.Unlock() m.mu.Unlock()
var out []Traffic var out []Traffic
var online []string var online []string
for _, s := range snaps { for _, s := range snaps {
users, ok := scrapeStats(s.apiPort) users, ok := scrapeStats(s.apiPort, s.apiToken)
if !ok { if !ok {
continue continue
} }
@@ -445,9 +470,11 @@ func FreeLocalPort() (int, error) {
// renderConfig builds the mtg-multi TOML for an instance. Top-level keys must // 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 // 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: // 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 // top-level scalars (incl. api-bind-to and api-token), then [domain-fronting],
// [throttle], and finally [secrets] with one named secret per active client. // [network] and [throttle], then [secret-ad-tags] for clients overriding the
func renderConfig(inst Instance, apiPort int) string { // global advertising tag, and finally [secrets] with one named secret per
// active client.
func renderConfig(inst Instance, apiPort int, apiToken string) string {
var b strings.Builder var b strings.Builder
fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo()) fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo())
if inst.Debug { if inst.Debug {
@@ -460,6 +487,9 @@ func renderConfig(inst Instance, apiPort int) string {
fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP) fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP)
} }
fmt.Fprintf(&b, "api-bind-to = \"127.0.0.1:%d\"\n", apiPort) fmt.Fprintf(&b, "api-bind-to = \"127.0.0.1:%d\"\n", apiPort)
if apiToken != "" {
fmt.Fprintf(&b, "api-token = %q\n", apiToken)
}
if inst.AdTag != "" { if inst.AdTag != "" {
fmt.Fprintf(&b, "ad-tag = %q\n", inst.AdTag) fmt.Fprintf(&b, "ad-tag = %q\n", inst.AdTag)
} }
@@ -490,6 +520,20 @@ func renderConfig(inst Instance, apiPort int) string {
if inst.ThrottleMaxConnections > 0 { if inst.ThrottleMaxConnections > 0 {
fmt.Fprintf(&b, "\n[throttle]\nmax-connections = %d\n", inst.ThrottleMaxConnections) fmt.Fprintf(&b, "\n[throttle]\nmax-connections = %d\n", inst.ThrottleMaxConnections)
} }
// Only clients present in [secrets] may appear here: mtg rejects a config
// whose [secret-ad-tags] names an unknown secret, so a disabled client's
// override must vanish together with its secret.
tagged := false
for _, e := range inst.Secrets {
if e.AdTag == "" {
continue
}
if !tagged {
b.WriteString("\n[secret-ad-tags]\n")
tagged = true
}
fmt.Fprintf(&b, "%q = %q\n", e.Name, e.AdTag)
}
b.WriteString("\n[secrets]\n") b.WriteString("\n[secrets]\n")
for _, e := range inst.Secrets { for _, e := range inst.Secrets {
fmt.Fprintf(&b, "%q = %q\n", e.Name, e.Secret) fmt.Fprintf(&b, "%q = %q\n", e.Name, e.Secret)
@@ -497,11 +541,11 @@ func renderConfig(inst Instance, apiPort int) string {
return b.String() return b.String()
} }
func writeConfig(path string, inst Instance, apiPort int) error { func writeConfig(path string, inst Instance, apiPort int, apiToken string) error {
if err := os.MkdirAll(configDir(), 0o750); err != nil { if err := os.MkdirAll(configDir(), 0o750); err != nil {
return err return err
} }
return os.WriteFile(path, []byte(renderConfig(inst, apiPort)), 0o640) return os.WriteFile(path, []byte(renderConfig(inst, apiPort, apiToken)), 0o640)
} }
// statsUser is one entry of the mtg-multi /stats users map. bytes_in is traffic // statsUser is one entry of the mtg-multi /stats users map. bytes_in is traffic
@@ -515,6 +559,7 @@ type statsUser struct {
type secretPutEntry struct { type secretPutEntry struct {
Secret string `json:"secret"` Secret string `json:"secret"`
AdTag string `json:"ad_tag,omitempty"`
} }
type secretsPutBody struct { type secretsPutBody struct {
@@ -525,19 +570,40 @@ type secretsPutBody struct {
func secretsPayload(inst Instance) secretsPutBody { func secretsPayload(inst Instance) secretsPutBody {
secrets := make(map[string]secretPutEntry, len(inst.Secrets)) secrets := make(map[string]secretPutEntry, len(inst.Secrets))
for _, e := range inst.Secrets { for _, e := range inst.Secrets {
secrets[e.Name] = secretPutEntry{Secret: e.Secret} secrets[e.Name] = secretPutEntry{Secret: e.Secret, AdTag: e.AdTag}
} }
return secretsPutBody{Secrets: secrets, AdTag: inst.AdTag} return secretsPutBody{Secrets: secrets, AdTag: inst.AdTag}
} }
// applySecrets pushes the desired secret set and advertising tag to a running // newAPIToken mints the bearer token one mtg process and its manager share for
// the lifetime of that process. The management API can replace the whole
// secret set, so even though it only listens on loopback it must not be open
// to every local process. The token lives in the generated config (mtg reads
// it at startup only — a rewritten token would not apply until a restart,
// which is why the reload path reuses the stored one) and in the manager's
// memory, nowhere else.
func newAPIToken() (string, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
func authorize(req *http.Request, token string) {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}
// applySecrets pushes the desired secret set and advertising tags to a running
// mtg-multi through its management API (PUT /secrets on the same loopback port // mtg-multi through its management API (PUT /secrets on the same loopback port
// that serves /stats), so a client add, removal, re-key, or ad-tag change is // that serves /stats), so a client add, removal, re-key, or ad-tag change is
// applied in place. mtg keeps every connection whose secret is unchanged and // applied in place. mtg keeps every connection whose secret is unchanged and
// closes only the removed or re-keyed ones. It returns true only on a 200: an // closes only the removed or re-keyed ones. It returns true only on a 200: an
// older binary without the endpoint (404), a refused connection, or any other // older binary without the endpoint (404), a refused connection, or any other
// status yields false, so the caller falls back to a full restart. // status yields false, so the caller falls back to a full restart.
func applySecrets(port int, inst Instance) bool { func applySecrets(port int, token string, inst Instance) bool {
body, err := json.Marshal(secretsPayload(inst)) body, err := json.Marshal(secretsPayload(inst))
if err != nil { if err != nil {
return false return false
@@ -548,6 +614,7 @@ func applySecrets(port int, inst Instance) bool {
return false return false
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
authorize(req, token)
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
return false return false
@@ -559,12 +626,13 @@ func applySecrets(port int, inst Instance) bool {
// scrapeStats reads the mtg-multi /stats JSON API and returns the per-user // scrapeStats reads the mtg-multi /stats JSON API and returns the per-user
// cumulative counters. Best-effort: an unreachable endpoint or unparseable body // cumulative counters. Best-effort: an unreachable endpoint or unparseable body
// yields ok=false. // yields ok=false.
func scrapeStats(port int) (map[string]statsUser, bool) { func scrapeStats(port int, token string) (map[string]statsUser, bool) {
client := http.Client{Timeout: 3 * time.Second} client := http.Client{Timeout: 3 * time.Second}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil) req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil)
if err != nil { if err != nil {
return nil, false return nil, false
} }
authorize(req, token)
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
return nil, false return nil, false
+6 -2
View File
@@ -30,6 +30,10 @@ func TestScrapeStats(t *testing.T) {
http.NotFound(w, r) http.NotFound(w, r)
return return
} }
if r.Header.Get("Authorization") != "Bearer sesame" {
w.WriteHeader(http.StatusUnauthorized)
return
}
_, _ = io.WriteString(w, `{"started_at":"2026-01-01T00:00:00Z","total_connections":2,`+ _, _ = io.WriteString(w, `{"started_at":"2026-01-01T00:00:00Z","total_connections":2,`+
`"users":{`+ `"users":{`+
`"alice":{"connections":2,"bytes_in":100,"bytes_out":200,"last_seen":"2026-01-01T00:01:00Z"},`+ `"alice":{"connections":2,"bytes_in":100,"bytes_out":200,"last_seen":"2026-01-01T00:01:00Z"},`+
@@ -37,7 +41,7 @@ func TestScrapeStats(t *testing.T) {
})) }))
defer srv.Close() defer srv.Close()
users, ok := scrapeStats(serverPort(t, srv)) users, ok := scrapeStats(serverPort(t, srv), "sesame")
if !ok { if !ok {
t.Fatal("scrapeStats should succeed against a valid /stats endpoint") t.Fatal("scrapeStats should succeed against a valid /stats endpoint")
} }
@@ -59,7 +63,7 @@ func TestScrapeStatsUnreachable(t *testing.T) {
port := serverPort(t, srv) port := serverPort(t, srv)
srv.Close() srv.Close()
if _, ok := scrapeStats(port); ok { if _, ok := scrapeStats(port, ""); ok {
t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable") t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable")
} }
} }
+20 -5
View File
@@ -116,26 +116,34 @@ func TestApplySecrets(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
var gotMethod, gotPath string var gotMethod, gotPath, gotAuth string
var gotBody secretsPutBody var gotBody secretsPutBody
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path gotMethod, gotPath, gotAuth = r.Method, r.URL.Path, r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&gotBody) _ = json.NewDecoder(r.Body).Decode(&gotBody)
w.WriteHeader(tc.status) w.WriteHeader(tc.status)
})) }))
defer srv.Close() defer srv.Close()
inst := mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"}) inst := mtgInst(1,
SecretEntry{Name: "alice", Secret: "ee01"},
SecretEntry{Name: "bob", Secret: "ee02", AdTag: "fedcba9876543210fedcba9876543210"})
inst.AdTag = "0123456789abcdef0123456789abcdef" inst.AdTag = "0123456789abcdef0123456789abcdef"
if got := applySecrets(serverPort(t, srv), inst); got != tc.want { if got := applySecrets(serverPort(t, srv), "sesame", inst); got != tc.want {
t.Fatalf("applySecrets = %v, want %v", got, tc.want) t.Fatalf("applySecrets = %v, want %v", got, tc.want)
} }
if gotMethod != http.MethodPut || gotPath != "/secrets" { if gotMethod != http.MethodPut || gotPath != "/secrets" {
t.Fatalf("expected PUT /secrets, got %s %s", gotMethod, gotPath) t.Fatalf("expected PUT /secrets, got %s %s", gotMethod, gotPath)
} }
if gotAuth != "Bearer sesame" {
t.Fatalf("expected the bearer token on the request, got %q", gotAuth)
}
if gotBody.Secrets["alice"].Secret != "ee01" || gotBody.AdTag != "0123456789abcdef0123456789abcdef" { if gotBody.Secrets["alice"].Secret != "ee01" || gotBody.AdTag != "0123456789abcdef0123456789abcdef" {
t.Fatalf("payload must carry the secret and ad-tag: %+v", gotBody) t.Fatalf("payload must carry the secret and ad-tag: %+v", gotBody)
} }
if gotBody.Secrets["alice"].AdTag != "" || gotBody.Secrets["bob"].AdTag != "fedcba9876543210fedcba9876543210" {
t.Fatalf("payload must carry per-client ad-tag overrides only where set: %+v", gotBody)
}
}) })
} }
@@ -143,7 +151,7 @@ func TestApplySecrets(t *testing.T) {
srv := httptest.NewServer(http.NotFoundHandler()) srv := httptest.NewServer(http.NotFoundHandler())
port := serverPort(t, srv) port := serverPort(t, srv)
srv.Close() srv.Close()
if applySecrets(port, mtgInst(1, SecretEntry{Name: "a", Secret: "ee"})) { if applySecrets(port, "", mtgInst(1, SecretEntry{Name: "a", Secret: "ee"})) {
t.Fatal("a refused connection must yield false") t.Fatal("a refused connection must yield false")
} }
}) })
@@ -159,6 +167,10 @@ func TestEnsureHotReloadKeepsProcess(t *testing.T) {
} }
waitSpawnCount(t, pidFile, 1) waitSpawnCount(t, pidFile, 1)
orig := mgr.procs[1].proc orig := mgr.procs[1].proc
origToken := mgr.procs[1].apiToken
if origToken == "" {
t.Fatal("a started process must get an api token")
}
reloaded := make(chan struct{}, 1) reloaded := make(chan struct{}, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -201,6 +213,9 @@ func TestEnsureHotReloadKeepsProcess(t *testing.T) {
if !strings.Contains(string(cfg), fmt.Sprintf("api-bind-to = \"127.0.0.1:%d\"", serverPort(t, srv))) { if !strings.Contains(string(cfg), fmt.Sprintf("api-bind-to = \"127.0.0.1:%d\"", serverPort(t, srv))) {
t.Fatalf("reload must reuse the same api port:\n%s", cfg) t.Fatalf("reload must reuse the same api port:\n%s", cfg)
} }
if !strings.Contains(string(cfg), fmt.Sprintf("api-token = %q", origToken)) {
t.Fatalf("reload must reuse the token the running process was started with:\n%s", cfg)
}
mgr.StopAll() mgr.StopAll()
} }
+44 -10
View File
@@ -20,8 +20,9 @@ func TestInstanceFromInbound(t *testing.T) {
`"domainFronting":{"ip":"127.0.0.1","port":9443,"proxyProtocol":true},` + `"domainFronting":{"ip":"127.0.0.1","port":9443,"proxyProtocol":true},` +
`"throttleMaxConnections":5000,` + `"throttleMaxConnections":5000,` +
`"routeThroughXray":true,"routeXrayPort":50000,` + `"routeThroughXray":true,"routeXrayPort":50000,` +
`"adTag":" 0123456789abcdef0123456789abcdef ",` +
`"clients":[` + `"clients":[` +
`{"email":"alice","secret":"` + aliceSecret + `","enable":true},` + `{"email":"alice","secret":"` + aliceSecret + `","adTag":"fedcba9876543210fedcba9876543210","enable":true},` +
`{"email":"bob","secret":"","enable":true},` + `{"email":"bob","secret":"","enable":true},` +
`{"email":"carol","secret":"eeaa","enable":false}]}`, `{"email":"carol","secret":"eeaa","enable":false}]}`,
} }
@@ -38,6 +39,12 @@ func TestInstanceFromInbound(t *testing.T) {
if inst.Secrets[0].Secret != aliceSecret { if inst.Secrets[0].Secret != aliceSecret {
t.Fatalf("a valid secret must be preserved, got %q", inst.Secrets[0].Secret) t.Fatalf("a valid secret must be preserved, got %q", inst.Secrets[0].Secret)
} }
if inst.Secrets[0].AdTag != "fedcba9876543210fedcba9876543210" {
t.Fatalf("the client ad-tag override must be parsed, got %q", inst.Secrets[0].AdTag)
}
if inst.AdTag != "0123456789abcdef0123456789abcdef" {
t.Fatalf("the inbound ad-tag must be trimmed and kept, got %q", inst.AdTag)
}
if inst.Port != 8443 || inst.Id != 3 { if inst.Port != 8443 || inst.Id != 3 {
t.Fatalf("bad instance %+v", inst) t.Fatalf("bad instance %+v", inst)
} }
@@ -62,6 +69,17 @@ func TestInstanceFromInbound(t *testing.T) {
if _, ok := InstanceFromInbound(noSecrets); ok { if _, ok := InstanceFromInbound(noSecrets); ok {
t.Fatal("an inbound with no active secret should not produce an instance") t.Fatal("an inbound with no active secret should not produce an instance")
} }
badTags := &model.Inbound{Protocol: model.MTProto, Settings: `{"adTag":"nope",` +
`"clients":[{"email":"x","secret":"ee00","adTag":"deadbeef","enable":true}]}`}
badInst, ok := InstanceFromInbound(badTags)
if !ok {
t.Fatal("expected a usable instance despite malformed ad tags")
}
if badInst.AdTag != "" || badInst.Secrets[0].AdTag != "" {
t.Fatalf("malformed ad tags must be dropped so the generated config stays valid, got global=%q client=%q",
badInst.AdTag, badInst.Secrets[0].AdTag)
}
} }
func TestRenderConfig(t *testing.T) { func TestRenderConfig(t *testing.T) {
@@ -70,8 +88,8 @@ func TestRenderConfig(t *testing.T) {
bare := renderConfig(Instance{ bare := renderConfig(Instance{
Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}}, Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}},
Listen: "0.0.0.0", Port: 8443, Listen: "0.0.0.0", Port: 8443,
}, 5000) }, 5000, "")
for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]"} { for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[secret-ad-tags]", "api-token"} {
if strings.Contains(bare, unwanted) { if strings.Contains(bare, unwanted) {
t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare) t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare)
} }
@@ -87,21 +105,26 @@ func TestRenderConfig(t *testing.T) {
} }
// A fully configured instance emits every option, the fronting section (as // A fully configured instance emits every option, the fronting section (as
// host, not the fork-deprecated ip), the throttle block, and [secrets] last. // host, not the fork-deprecated ip), the throttle block, the per-client
// ad-tag overrides, and [secrets] last.
full := renderConfig(Instance{ full := renderConfig(Instance{
Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}}, Secrets: []SecretEntry{
Listen: "0.0.0.0", Port: 443, {Name: "alice", Secret: "ee11"},
{Name: "bob", Secret: "ee22", AdTag: "fedcba9876543210fedcba9876543210"},
},
Listen: "0.0.0.0", Port: 443,
Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6", Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6",
FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true, FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true,
ThrottleMaxConnections: 5000, ThrottleMaxConnections: 5000,
AdTag: "0123456789abcdef0123456789abcdef", AdTag: "0123456789abcdef0123456789abcdef",
PublicIPv4: "1.2.3.4", PublicIPv4: "1.2.3.4",
PublicIPv6: "2001:db8::1", PublicIPv6: "2001:db8::1",
}, 6000) }, 6000, "sesame")
for _, want := range []string{ for _, want := range []string{
"debug = true\n", "debug = true\n",
"proxy-protocol-listener = true\n", "proxy-protocol-listener = true\n",
`prefer-ip = "only-ipv6"`, `prefer-ip = "only-ipv6"`,
`api-token = "sesame"`,
`ad-tag = "0123456789abcdef0123456789abcdef"`, `ad-tag = "0123456789abcdef0123456789abcdef"`,
`public-ipv4 = "1.2.3.4"`, `public-ipv4 = "1.2.3.4"`,
`public-ipv6 = "2001:db8::1"`, `public-ipv6 = "2001:db8::1"`,
@@ -111,6 +134,8 @@ func TestRenderConfig(t *testing.T) {
"proxy-protocol = true\n", "proxy-protocol = true\n",
"[throttle]", "[throttle]",
"max-connections = 5000", "max-connections = 5000",
"[secret-ad-tags]",
`"bob" = "fedcba9876543210fedcba9876543210"`,
} { } {
if !strings.Contains(full, want) { if !strings.Contains(full, want) {
t.Fatalf("full config missing %q:\n%s", want, full) t.Fatalf("full config missing %q:\n%s", want, full)
@@ -119,6 +144,9 @@ func TestRenderConfig(t *testing.T) {
if strings.Contains(full, `ip = "127.0.0.1"`) { if strings.Contains(full, `ip = "127.0.0.1"`) {
t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full) t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full)
} }
if strings.Contains(full, `"alice" = "0123456789abcdef0123456789abcdef"`) || strings.Contains(full, `"alice" = ""`) {
t.Fatalf("a client without an override must not appear in [secret-ad-tags]:\n%s", full)
}
// TOML requires top-level keys before any [section] header, and [secrets] // 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. // 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]") { if strings.Index(full, "prefer-ip") > strings.Index(full, "[domain-fronting]") {
@@ -130,6 +158,9 @@ func TestRenderConfig(t *testing.T) {
if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") { if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") {
t.Fatalf("[throttle] must precede [secrets]:\n%s", full) t.Fatalf("[throttle] must precede [secrets]:\n%s", full)
} }
if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[secret-ad-tags]") {
t.Fatalf("[secret-ad-tags] must precede [secrets]:\n%s", full)
}
} }
func TestRenderConfigXrayEgress(t *testing.T) { func TestRenderConfigXrayEgress(t *testing.T) {
@@ -139,7 +170,7 @@ func TestRenderConfigXrayEgress(t *testing.T) {
Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}}, Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}},
Listen: "0.0.0.0", Port: 443, Listen: "0.0.0.0", Port: 443,
RouteThroughXray: true, XrayRoutePort: 50000, RouteThroughXray: true, XrayRoutePort: 50000,
}, 7000) }, 7000, "")
if !strings.Contains(routed, "[network]") || if !strings.Contains(routed, "[network]") ||
!strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) { !strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) {
t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed) t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed)
@@ -153,7 +184,7 @@ func TestRenderConfigXrayEgress(t *testing.T) {
{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},
{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true}, {Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
} { } {
if got := renderConfig(inst, 7000); strings.Contains(got, "[network]") { if got := renderConfig(inst, 7000, ""); strings.Contains(got, "[network]") {
t.Fatalf("unrouted config must omit [network]:\n%s", got) t.Fatalf("unrouted config must omit [network]:\n%s", got)
} }
} }
@@ -195,6 +226,9 @@ func TestFingerprintSplit(t *testing.T) {
"remove": func(i *Instance) { i.Secrets = nil }, "remove": func(i *Instance) { i.Secrets = nil },
"rename": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a2", Secret: "ee"}} }, "rename": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a2", Secret: "ee"}} },
"adTag": func(i *Instance) { i.AdTag = "0123456789abcdef0123456789abcdef" }, "adTag": func(i *Instance) { i.AdTag = "0123456789abcdef0123456789abcdef" },
"clientAdTag": func(i *Instance) {
i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", AdTag: "0123456789abcdef0123456789abcdef"}}
},
} { } {
t.Run("secrets/"+name, func(t *testing.T) { t.Run("secrets/"+name, func(t *testing.T) {
changed := base changed := base
@@ -212,7 +246,7 @@ func TestFingerprintSplit(t *testing.T) {
t.Run("orderInsensitive", func(t *testing.T) { t.Run("orderInsensitive", func(t *testing.T) {
forward := Instance{Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}, {Name: "bob", Secret: "ee22"}}} forward := Instance{Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}, {Name: "bob", Secret: "ee22"}}}
reversed := Instance{Secrets: []SecretEntry{{Name: "bob", Secret: "ee22"}, {Name: "alice", Secret: "ee11"}}} reversed := Instance{Secrets: []SecretEntry{{Name: "bob", Secret: "ee22"}, {Name: "alice", Secret: "ee11"}}}
if got, want := forward.secretsFingerprint(), "adtag=|alice=ee11|bob=ee22"; got != want { if got, want := forward.secretsFingerprint(), "adtag=|alice=ee11;tag=|bob=ee22;tag="; got != want {
t.Fatalf("secrets fingerprint must join sorted pairs: got %q, want %q", got, want) t.Fatalf("secrets fingerprint must join sorted pairs: got %q, want %q", got, want)
} }
if forward.secretsFingerprint() != reversed.secretsFingerprint() { if forward.secretsFingerprint() != reversed.secretsFingerprint() {
+9
View File
@@ -435,6 +435,15 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
return needRestart, err return needRestart, err
} }
// Same shape as the group write above: SyncInbound keeps a stored ad-tag
// when the incoming settings carry none, so clearing the override must be
// applied here, where the editor always round-trips the field.
if err := database.GetDB().Model(&model.ClientRecord{}).
Where("id = ?", id).
UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
return needRestart, err
}
if err := database.GetDB().Model(&model.ClientRecord{}). if err := database.GetDB().Model(&model.ClientRecord{}).
Where("id = ?", id). Where("id = ?", id).
UpdateColumn("enable", updated.Enable).Error; err != nil { UpdateColumn("enable", updated.Enable).Error; err != nil {
@@ -388,6 +388,9 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
if client.Secret == "" { if client.Secret == "" {
return false, common.NewError("mtproto client requires a secret") return false, common.NewError("mtproto client requires a secret")
} }
if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
return false, common.NewError("mtproto client ad tag must be 32 hex characters")
}
default: default:
if client.ID == "" { if client.ID == "" {
return false, common.NewError("empty client ID") return false, common.NewError("empty client ID")
@@ -579,6 +582,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if strings.TrimSpace(clients[0].Email) == "" { if strings.TrimSpace(clients[0].Email) == "" {
return false, common.NewError("client email is required") return false, common.NewError("client email is required")
} }
if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
return false, common.NewError("mtproto client ad tag must be 32 hex characters")
}
if clients[0].Email != oldEmail { if clients[0].Email != oldEmail {
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil) existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
+6
View File
@@ -75,6 +75,12 @@ func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.
if incoming.Auth != "" { if incoming.Auth != "" {
row.Auth = incoming.Auth row.Auth = incoming.Auth
} }
if incoming.Secret != "" {
row.Secret = incoming.Secret
}
if incoming.AdTag != "" {
row.AdTag = incoming.AdTag
}
row.Flow = incoming.Flow row.Flow = incoming.Flow
if incoming.Security != "" { if incoming.Security != "" {
row.Security = incoming.Security row.Security = incoming.Security
@@ -0,0 +1,70 @@
package service
import (
"path/filepath"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestSyncInbound_UpdatesMtprotoSecretAndAdTag(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
db := database.GetDB()
mtproto := &model.Inbound{Tag: "mtproto-in", Enable: true, Port: 10004, Protocol: model.MTProto}
if err := db.Create(mtproto).Error; err != nil {
t.Fatalf("create mtproto inbound: %v", err)
}
svc := ClientService{}
const email = "tg@example.com"
const firstSecret = "ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d"
const rekeyedSecret = "eefedcba9876543210fedcba98765432106578616d706c652e636f6d"
const firstTag = "0123456789abcdef0123456789abcdef"
const retaggedTag = "fedcba9876543210fedcba9876543210"
first := model.Client{Email: email, Secret: firstSecret, AdTag: firstTag, Enable: true}
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{first}); err != nil {
t.Fatalf("SyncInbound (create): %v", err)
}
var row model.ClientRecord
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("lookup client row: %v", err)
}
if row.Secret != firstSecret || row.AdTag != firstTag {
t.Fatalf("create must store secret and ad tag: got secret=%q adTag=%q", row.Secret, row.AdTag)
}
rekeyed := model.Client{Email: email, Secret: rekeyedSecret, AdTag: retaggedTag, Enable: true}
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{rekeyed}); err != nil {
t.Fatalf("SyncInbound (rekey): %v", err)
}
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("lookup client row after rekey: %v", err)
}
if row.Secret != rekeyedSecret {
t.Errorf("a re-keyed secret must reach the client record (sub links and the clients page read it), got %q", row.Secret)
}
if row.AdTag != retaggedTag {
t.Errorf("a changed ad tag must reach the client record, got %q", row.AdTag)
}
secretless := model.Client{Email: email, Enable: true}
if err := svc.SyncInbound(nil, mtproto.Id, []model.Client{secretless}); err != nil {
t.Fatalf("SyncInbound (secretless): %v", err)
}
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("lookup client row after secretless sync: %v", err)
}
if row.Secret != rekeyedSecret || row.AdTag != retaggedTag {
t.Errorf("a payload without mtproto fields must not wipe them: got secret=%q adTag=%q", row.Secret, row.AdTag)
}
}
+3
View File
@@ -739,6 +739,9 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
if client.Secret == "" { if client.Secret == "" {
return inbound, false, common.NewError("mtproto client requires a secret") return inbound, false, common.NewError("mtproto client requires a secret")
} }
if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
}
default: default:
if client.ID == "" { if client.ID == "" {
return inbound, false, common.NewError("empty client ID") return inbound, false, common.NewError("empty client ID")
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل", "wireguardAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
"mtprotoSecret": "سر MTProto", "mtprotoSecret": "سر MTProto",
"mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.", "mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.",
"mtprotoAdTag": "علامة إعلانية (قناة مموّلة)",
"mtprotoAdTagHint": "علامة اختيارية مكوّنة من 32 حرفًا ست عشريًا تُطبَّق على هذا العميل فقط بدلًا من العلامة الإعلانية المشتركة. اتركها فارغة لاستخدام العلامة المشتركة.",
"reverseTag": "وسم عكسي", "reverseTag": "وسم عكسي",
"reverseTagPlaceholder": "Reverse tag اختياري", "reverseTagPlaceholder": "Reverse tag اختياري",
"telegramId": "معرّف مستخدم تلغرام", "telegramId": "معرّف مستخدم تلغرام",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas", "wireguardAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
"mtprotoSecret": "MTProto secret", "mtprotoSecret": "MTProto secret",
"mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.", "mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.",
"mtprotoAdTag": "Ad-tag (sponsored channel)",
"mtprotoAdTagHint": "Optional 32-character hex tag applied to this client only, overriding the shared ad-tag. Leave empty to use the shared tag.",
"reverseTag": "Reverse tag", "reverseTag": "Reverse tag",
"reverseTagPlaceholder": "Optional reverse tag", "reverseTagPlaceholder": "Optional reverse tag",
"telegramId": "Telegram user ID", "telegramId": "Telegram user ID",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas", "wireguardAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas",
"mtprotoSecret": "Secreto MTProto", "mtprotoSecret": "Secreto MTProto",
"mtprotoSecretHint": "El secreto FakeTLS del cliente. Vuelve a generarlo para cambiarlo.", "mtprotoSecretHint": "El secreto FakeTLS del cliente. Vuelve a generarlo para cambiarlo.",
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
"mtprotoAdTagHint": "Etiqueta hexadecimal opcional de 32 caracteres aplicada solo a este cliente, en lugar del ad-tag compartido. Déjala vacía para usar la etiqueta compartida.",
"reverseTag": "Etiqueta inversa", "reverseTag": "Etiqueta inversa",
"reverseTagPlaceholder": "Reverse tag opcional", "reverseTagPlaceholder": "Reverse tag opcional",
"telegramId": "ID de usuario de Telegram", "telegramId": "ID de usuario de Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودی‌ها را با کاما جدا کنید", "wireguardAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودی‌ها را با کاما جدا کنید",
"mtprotoSecret": "سکرت MTProto", "mtprotoSecret": "سکرت MTProto",
"mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.", "mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.",
"mtprotoAdTag": "برچسب تبلیغاتی (کانال حامی)",
"mtprotoAdTagHint": "برچسب هگزادسیمال اختیاری ۳۲ کاراکتری که فقط برای این کلاینت به‌جای برچسب تبلیغاتی مشترک اعمال می‌شود. برای استفاده از برچسب مشترک خالی بگذارید.",
"reverseTag": "تگ معکوس", "reverseTag": "تگ معکوس",
"reverseTagPlaceholder": "Reverse tag اختیاری", "reverseTagPlaceholder": "Reverse tag اختیاری",
"telegramId": "شناسه کاربر تلگرام", "telegramId": "شناسه کاربر تلگرام",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma", "wireguardAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
"mtprotoSecret": "Secret MTProto", "mtprotoSecret": "Secret MTProto",
"mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.", "mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.",
"mtprotoAdTag": "Ad-tag (kanal bersponsor)",
"mtprotoAdTagHint": "Tag heksadesimal 32 karakter opsional yang hanya berlaku untuk klien ini, menggantikan ad-tag bersama. Biarkan kosong untuk memakai tag bersama.",
"reverseTag": "Reverse tag", "reverseTag": "Reverse tag",
"reverseTagPlaceholder": "Reverse tag opsional", "reverseTagPlaceholder": "Reverse tag opsional",
"telegramId": "ID pengguna Telegram", "telegramId": "ID pengguna Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り", "wireguardAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
"mtprotoSecret": "MTProto シークレット", "mtprotoSecret": "MTProto シークレット",
"mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。", "mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。",
"mtprotoAdTag": "広告タグ(スポンサーチャンネル)",
"mtprotoAdTagHint": "このクライアントにのみ適用される任意の 32 文字の 16 進数タグで、共有の広告タグを上書きします。空欄にすると共有タグが使われます。",
"reverseTag": "Reverse tag", "reverseTag": "Reverse tag",
"reverseTagPlaceholder": "任意の Reverse tag", "reverseTagPlaceholder": "任意の Reverse tag",
"telegramId": "Telegram ユーザー ID", "telegramId": "Telegram ユーザー ID",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas", "wireguardAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas",
"mtprotoSecret": "Segredo MTProto", "mtprotoSecret": "Segredo MTProto",
"mtprotoSecretHint": "O segredo FakeTLS do cliente. Gere novamente para trocá-lo.", "mtprotoSecretHint": "O segredo FakeTLS do cliente. Gere novamente para trocá-lo.",
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
"mtprotoAdTagHint": "Tag hexadecimal opcional de 32 caracteres aplicada somente a este cliente, substituindo a ad-tag compartilhada. Deixe vazio para usar a tag compartilhada.",
"reverseTag": "Tag reversa", "reverseTag": "Tag reversa",
"reverseTagPlaceholder": "Reverse tag opcional", "reverseTagPlaceholder": "Reverse tag opcional",
"telegramId": "ID de usuário do Telegram", "telegramId": "ID de usuário do Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми", "wireguardAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
"mtprotoSecret": "Секрет MTProto", "mtprotoSecret": "Секрет MTProto",
"mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.", "mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.",
"mtprotoAdTag": "Рекламный тег (спонсорский канал)",
"mtprotoAdTagHint": "Необязательный шестнадцатеричный тег из 32 символов, применяемый только к этому клиенту вместо общего рекламного тега. Оставьте пустым, чтобы использовать общий тег.",
"reverseTag": "Обратный тег", "reverseTag": "Обратный тег",
"reverseTagPlaceholder": "Необязательный Reverse tag", "reverseTagPlaceholder": "Необязательный Reverse tag",
"telegramId": "ID пользователя Telegram", "telegramId": "ID пользователя Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın", "wireguardAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın",
"mtprotoSecret": "MTProto sırrı", "mtprotoSecret": "MTProto sırrı",
"mtprotoSecretHint": "İstemcinin FakeTLS sırrı. Değiştirmek için yeniden oluşturun.", "mtprotoSecretHint": "İstemcinin FakeTLS sırrı. Değiştirmek için yeniden oluşturun.",
"mtprotoAdTag": "Reklam etiketi (sponsorlu kanal)",
"mtprotoAdTagHint": "Yalnızca bu istemciye uygulanan ve ortak reklam etiketinin yerine geçen isteğe bağlı 32 karakterlik onaltılık etiket. Ortak etiketi kullanmak için boş bırakın.",
"reverseTag": "Reverse Tag", "reverseTag": "Reverse Tag",
"reverseTagPlaceholder": "İsteğe Bağlı Reverse Tag", "reverseTagPlaceholder": "İsteğe Bağlı Reverse Tag",
"telegramId": "Telegram Kullanıcı ID'si", "telegramId": "Telegram Kullanıcı ID'si",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами", "wireguardAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
"mtprotoSecret": "Секрет MTProto", "mtprotoSecret": "Секрет MTProto",
"mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.", "mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.",
"mtprotoAdTag": "Рекламний тег (спонсорський канал)",
"mtprotoAdTagHint": "Необовʼязковий шістнадцятковий тег із 32 символів, що застосовується лише до цього клієнта замість спільного рекламного тега. Залиште порожнім, щоб використовувати спільний тег.",
"reverseTag": "Зворотний тег", "reverseTag": "Зворотний тег",
"reverseTagPlaceholder": "Необов'язковий Reverse tag", "reverseTagPlaceholder": "Необов'язковий Reverse tag",
"telegramId": "ID користувача Telegram", "telegramId": "ID користувача Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy", "wireguardAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy",
"mtprotoSecret": "Secret MTProto", "mtprotoSecret": "Secret MTProto",
"mtprotoSecretHint": "Secret FakeTLS của client. Tạo lại để thay đổi.", "mtprotoSecretHint": "Secret FakeTLS của client. Tạo lại để thay đổi.",
"mtprotoAdTag": "Ad-tag (kênh tài trợ)",
"mtprotoAdTagHint": "Thẻ thập lục phân 32 ký tự tùy chọn chỉ áp dụng cho client này, thay cho ad-tag dùng chung. Để trống để dùng thẻ chung.",
"reverseTag": "Reverse tag", "reverseTag": "Reverse tag",
"reverseTagPlaceholder": "Reverse tag tùy chọn", "reverseTagPlaceholder": "Reverse tag tùy chọn",
"telegramId": "ID người dùng Telegram", "telegramId": "ID người dùng Telegram",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔", "wireguardAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
"mtprotoSecret": "MTProto 密钥", "mtprotoSecret": "MTProto 密钥",
"mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。", "mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。",
"mtprotoAdTag": "广告标签(赞助频道)",
"mtprotoAdTagHint": "可选的 32 位十六进制标签,仅对该客户端生效,覆盖共享广告标签。留空则使用共享标签。",
"reverseTag": "反向标签", "reverseTag": "反向标签",
"reverseTagPlaceholder": "可选 Reverse tag", "reverseTagPlaceholder": "可选 Reverse tag",
"telegramId": "Telegram 用户 ID", "telegramId": "Telegram 用户 ID",
+2
View File
@@ -918,6 +918,8 @@
"wireguardAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔", "wireguardAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
"mtprotoSecret": "MTProto 金鑰", "mtprotoSecret": "MTProto 金鑰",
"mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。", "mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。",
"mtprotoAdTag": "廣告標籤(贊助頻道)",
"mtprotoAdTagHint": "選填的 32 位十六進位標籤,僅對該用戶端生效,覆蓋共用廣告標籤。留空則使用共用標籤。",
"reverseTag": "反向標籤", "reverseTag": "反向標籤",
"reverseTagPlaceholder": "選用 Reverse tag", "reverseTagPlaceholder": "選用 Reverse tag",
"telegramId": "Telegram 使用者 ID", "telegramId": "Telegram 使用者 ID",