fix(sub): render nothing when every host of an inbound is excluded from a format (#7096)

hostEndpoints and subscriptionHostVariants returned the same empty result
for an inbound with no enabled hosts and for one whose enabled hosts are
all excluded from the requested format. The second case therefore fell
back to the inbound's bare address, the address the operator had hidden.

The all-excluded case is now reported separately and renders nothing in
raw, json and clash, in both sort modes, in the link export and in the
panel's own host selection. Traffic accounting and the usage header are
kept. Inbounds with no hosts, or only disabled ones, render as before.
This commit is contained in:
mjbe71
2026-11-24 03:30:02 +03:30
committed by GitHub
parent 04be3da8fc
commit 5ebc8adb19
14 changed files with 333 additions and 30 deletions
+19
View File
@@ -164,10 +164,29 @@ export function hostEndpointsFor(
return endpoints;
}
// allHostsExcluded mirrors the backend's closed case: the inbound has enabled Hosts and every one
// is excluded from subType, so it renders nothing there instead of its own address.
export function allHostsExcluded(
records: HostRecord[],
inboundId: number,
subType: 'raw' | 'clash' = 'raw',
): boolean {
const enabled = records.filter((r) => !r.isDisabled && r.inboundIds.includes(inboundId));
return enabled.length > 0 && enabled.every((r) => r.excludeFromSubTypes?.includes(subType));
}
// Panel-built links of these protocols read Hosts; the rest still show the
// inbound's own address on the inbounds page.
const HOST_LINK_PROTOCOLS: ReadonlySet<string> = new Set(['mtproto', 'wireguard', 'amneziawg']);
export function hostLinksClosed(
inbound: Inbound,
inboundId: number,
records: HostRecord[],
): boolean {
return HOST_LINK_PROTOCOLS.has(inbound.protocol) && allHostsExcluded(records, inboundId);
}
export function withHostEndpoints(
inbound: Inbound,
inboundId: number,
@@ -1,10 +1,10 @@
import { hostEndpointsFor, type HostEndpoint } from '@/lib/hosts/host-link';
import { allHostsExcluded, hostEndpointsFor, type HostEndpoint } from '@/lib/hosts/host-link';
import { preferPublicHost, resolveShareHost } from '@/lib/xray/inbound-link';
import type { InboundOption } from '@/hooks/useClients';
import type { HostRecord } from '@/schemas/api/host';
// One client config per Host the subscription of that format advertises for the
// inbound; `undefined` stands for the inbound's own address when no Host applies.
// One client config per Host the subscription of that format advertises for the inbound;
// `undefined` is the inbound's own address when it has no enabled Host, none when all are excluded.
export function tunnelConfigEndpoints(
inbound: InboundOption,
hosts: HostRecord[],
@@ -12,6 +12,7 @@ export function tunnelConfigEndpoints(
publicHost: string,
subType: 'raw' | 'clash' = 'raw',
): (HostEndpoint | undefined)[] {
if (allHostsExcluded(hosts, inbound.id, subType)) return [];
const defaultDest = resolveShareHost(
inbound,
inbound.nodeAddress ?? '',
+11 -2
View File
@@ -39,7 +39,7 @@ import { useMediaQuery } from '@/hooks/useMediaQuery';
import { useWebSocket } from '@/hooks/useWebSocket';
import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useHostsQuery } from '@/api/queries/useHostsQuery';
import { withHostEndpoints } from '@/lib/hosts/host-link';
import { hostLinksClosed, withHostEndpoints } from '@/lib/hosts/host-link';
import AppSidebar from '@/layouts/AppSidebar';
const TextModal = lazy(() => import('@/components/feedback/TextModal'));
import type { TextModalTab } from '@/components/feedback/TextModal';
@@ -335,9 +335,18 @@ export default function InboundsPage() {
const projected = checkFallback(dbInbound);
const hostOverride = hostOverrideFor(dbInbound);
const fallbackHostname = preferPublicHost(window.location.hostname, subSettings.publicHost);
const baseInbound = inboundFromDb(projected);
if (hostLinksClosed(baseInbound, dbInbound.id, hosts)) {
openText({
title: t('pages.inbounds.exportLinksTitle'),
content: '',
fileName: projected.remark || 'inbound',
});
return;
}
const genInput = {
inbound: withHostEndpoints(
inboundFromDb(projected),
baseInbound,
dbInbound.id,
hosts,
hostOverride,
@@ -17,7 +17,7 @@ import {
preferPublicHost,
} from '@/lib/xray/inbound-link';
import { inboundFromDb } from '@/lib/xray/inbound-from-db';
import { withHostEndpoints } from '@/lib/hosts/host-link';
import { hostLinksClosed, withHostEndpoints } from '@/lib/hosts/host-link';
import {
buildInboundInfo,
@@ -150,14 +150,21 @@ export default function InboundInfoModal({
window.location.hostname,
subSettings?.publicHost ?? '',
);
const baseInbound = inboundFromDb(dbInbound);
const inboundForLinks = withHostEndpoints(
inboundFromDb(dbInbound),
baseInbound,
dbInbound.id,
hosts,
nodeAddress,
fallbackHostname,
);
if (info.protocol === Protocols.WIREGUARD) {
if (hostLinksClosed(baseInbound, dbInbound.id, hosts)) {
setWireguardConfigs([]);
setWireguardLinks([]);
setAmneziawgConfigs([]);
setAmneziawgLinks([]);
setLinks([]);
} else if (info.protocol === Protocols.WIREGUARD) {
setWireguardConfigs(
genWireguardPeerConfigs({
inbound: inboundForLinks,
@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest';
import type { InboundOption } from '@/hooks/useClients';
import { allHostsExcluded, hostLinksClosed, withHostEndpoints } from '@/lib/hosts/host-link';
import { tunnelConfigEndpoints } from '@/pages/clients/tunnelEndpoints';
import { InboundSchema } from '@/schemas/api/inbound';
import type { HostRecord } from '@/schemas/api/host';
const PANEL = 'panel.example.com';
function hostRecord(overrides: Partial<HostRecord>): HostRecord {
return {
groupId: 'g',
inboundIds: [7],
hosts: ['edge.example.com:443'],
remark: 'H',
...overrides,
};
}
const tuicInbound = { id: 7, port: 8443, protocol: 'tuic', listen: '' } as unknown as InboundOption;
// Mirrors the backend's closed case: enabled hosts exist and every one of them
// is excluded from the format, so the inbound renders nothing there.
describe('allHostsExcluded', () => {
it('is true when every enabled host of the inbound excludes the format', () => {
const records = [
hostRecord({ excludeFromSubTypes: ['raw'] }),
hostRecord({ groupId: 'g2', excludeFromSubTypes: ['raw', 'clash'] }),
];
expect(allHostsExcluded(records, 7, 'raw')).toBe(true);
});
it('is false while one enabled host still serves the format', () => {
const records = [
hostRecord({ excludeFromSubTypes: ['raw'] }),
hostRecord({ groupId: 'g2', excludeFromSubTypes: ['clash'] }),
];
expect(allHostsExcluded(records, 7, 'raw')).toBe(false);
});
it('is false with no hosts, only disabled hosts, or hosts of other inbounds', () => {
expect(allHostsExcluded([], 7, 'raw')).toBe(false);
expect(
allHostsExcluded([hostRecord({ isDisabled: true, excludeFromSubTypes: ['raw'] })], 7, 'raw'),
).toBe(false);
expect(
allHostsExcluded([hostRecord({ inboundIds: [8], excludeFromSubTypes: ['raw'] })], 7, 'raw'),
).toBe(false);
});
});
describe('tunnelConfigEndpoints with excluded hosts', () => {
it('yields no config when every host is excluded from the format', () => {
const hosts = [hostRecord({ excludeFromSubTypes: ['raw'] })];
expect(tunnelConfigEndpoints(tuicInbound, hosts, PANEL, '')).toEqual([]);
});
it('keeps the inbound own address when it has no enabled host', () => {
expect(tunnelConfigEndpoints(tuicInbound, [], PANEL, '')).toEqual([undefined]);
const disabled = [hostRecord({ isDisabled: true, excludeFromSubTypes: ['raw'] })];
expect(tunnelConfigEndpoints(tuicInbound, disabled, PANEL, '')).toEqual([undefined]);
});
it('still lists the hosts of a format they are not excluded from', () => {
const hosts = [hostRecord({ excludeFromSubTypes: ['raw'] })];
const clash = tunnelConfigEndpoints(tuicInbound, hosts, PANEL, '', 'clash');
expect(clash.map((ep) => ep?.dest)).toEqual(['edge.example.com']);
});
});
describe('hostLinksClosed', () => {
const wireguard = InboundSchema.parse({
port: 51820,
protocol: 'wireguard',
settings: { secretKey: 'iJ2cBkrSGqRwIfYIDIxk7hr5RXfdR93MfJUL7yqkkH8=', peers: [], clients: [] },
});
it('closes host-reading protocols whose hosts are all excluded from raw', () => {
const hosts = [hostRecord({ excludeFromSubTypes: ['raw'] })];
expect(hostLinksClosed(wireguard, 7, hosts)).toBe(true);
// the open case must keep producing the host endpoints it did before
const open = [hostRecord({})];
expect(hostLinksClosed(wireguard, 7, open)).toBe(false);
expect(withHostEndpoints(wireguard, 7, open, '', PANEL).streamSettings).toMatchObject({
externalProxy: [{ dest: 'edge.example.com', port: 443 }],
});
});
it('leaves protocols that do not read hosts alone', () => {
const vless = InboundSchema.parse({ port: 443, protocol: 'vless', settings: { clients: [] } });
const hosts = [hostRecord({ excludeFromSubTypes: ['raw'] })];
expect(hostLinksClosed(vless, 7, hosts)).toBe(false);
});
});
+17
View File
@@ -134,6 +134,23 @@ describe('withHostEndpoints', () => {
excludeFromSubTypes: ['raw'],
},
{ groupId: 'other', inboundIds: [8], hosts: ['c.example.com:443'] },
{ groupId: 'served', inboundIds: [7], hosts: ['d.example.com:443'] },
],
'',
'panel.example.com',
);
expect(got.streamSettings?.externalProxy).toEqual([
{ forceTls: 'same', dest: 'd.example.com', port: 443, remark: '' },
]);
});
it('keeps the inbound as is when it has no enabled Host of its own', () => {
const got = withHostEndpoints(
inbound,
7,
[
{ groupId: 'disabled', inboundIds: [7], hosts: ['a.example.com:443'], isDisabled: true },
{ groupId: 'other', inboundIds: [8], hosts: ['c.example.com:443'] },
],
'',
'panel.example.com',
@@ -148,12 +148,17 @@ describe('clients page tunnel configs follow Hosts', () => {
hosts: ['raw.example.com:443'],
excludeFromSubTypes: ['clash'],
},
{
groupId: 'both',
inboundIds: [7],
hosts: ['both.example.com:443'],
},
];
const configs = tunnelConfigEndpoints(inbound, hosts, PANEL, '', 'clash').map((ep) =>
buildTuicClientConfig(client, inbound, PANEL, '', ep),
);
expect(configs).toHaveLength(1);
expect(configs[0]).toContain(`server: ${PANEL}`);
expect(configs[0]).toContain('server: both.example.com');
});
it('names two Hosts of one inbound apart', () => {
+6 -1
View File
@@ -74,9 +74,10 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri
}
subReq.projectThroughFallbackMaster(inbound)
var baseEps []map[string]any
var hostsClosed bool
baseStream := inbound.StreamSettings
if !subReq.hostsFirst {
if baseEps = subReq.hostEndpoints(inbound, "clash"); len(baseEps) > 0 {
if baseEps, hostsClosed = subReq.hostEndpoints(inbound, "clash"); len(baseEps) > 0 {
injectExternalProxy(inbound, baseEps)
}
}
@@ -85,6 +86,10 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri
hasEnabledClient = true
}
seenEmails[client.Email] = struct{}{}
if hostsClosed {
hasBoundClosed = true
continue
}
if subReq.hostsFirst {
variants, closed := subReq.clientHostVariants(inbound, client, "clash")
hasBoundClosed = hasBoundClosed || closed
+126
View File
@@ -0,0 +1,126 @@
package sub
import (
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
type formatOutput struct {
rendered bool
header string
up, down int64
}
func renderFormat(t *testing.T, format string) formatOutput {
t.Helper()
switch format {
case "raw":
links, _, _, traffic, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
return formatOutput{rendered: len(links) > 0, up: traffic.Up, down: traffic.Down}
case "json":
out, header, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson("s1", "req.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
return formatOutput{rendered: strings.TrimSpace(out) != "", header: header}
default:
out, header, err := NewSubClashService(false, "", false, NewSubService("")).GetClash("s1", "req.example.com")
if err != nil {
t.Fatalf("GetClash: %v", err)
}
return formatOutput{rendered: strings.TrimSpace(out) != "", header: header}
}
}
// An inbound whose every host is excluded from a format must not leak the bare
// inbound into that format, in both host sort modes; usage is still accounted.
func TestSub_AllHostsFormatExcluded_RendersNothing(t *testing.T) {
for _, mode := range []string{"legacy", "hosts-first"} {
for _, format := range []string{"raw", "json", "clash"} {
t.Run(mode+"/"+format, func(t *testing.T) {
seedSubDB(t)
setHostSortMode(t, mode)
ib := seedSubInbound(t, "s1", "allex", 449, 1, tcpTLSStream)
seedHost(t, &model.Host{
InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443,
Security: "tls", Sni: "a.sni", ExcludeFromSubTypes: []string{format},
})
seedHost(t, &model.Host{
InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443,
Security: "tls", Sni: "b.sni", ExcludeFromSubTypes: []string{format},
})
if err := database.GetDB().Create(&xray.ClientTraffic{InboundId: ib.Id, Email: "allex@e", Up: 300, Down: 400, Enable: true}).Error; err != nil {
t.Fatalf("seed traffic: %v", err)
}
got := renderFormat(t, format)
if got.rendered {
t.Fatalf("%s with every host excluded must render nothing", format)
}
switch format {
case "raw":
if got.up != 300 || got.down != 400 {
t.Fatalf("usage = up %d/down %d, want 300/400", got.up, got.down)
}
default:
if !strings.HasPrefix(got.header, "upload=300; download=400; ") {
t.Fatalf("header = %q, want usage prefix", got.header)
}
}
for _, other := range []string{"raw", "json", "clash"} {
if other != format && !renderFormat(t, other).rendered {
t.Fatalf("%s is not excluded and must still render", other)
}
}
})
}
}
}
// Disabled hosts are switched off, not excluded: an inbound left with only
// disabled hosts keeps rendering its own address, as before.
func TestSub_OnlyDisabledHosts_StillRendersInbound(t *testing.T) {
for _, mode := range []string{"legacy", "hosts-first"} {
t.Run(mode, func(t *testing.T) {
seedSubDB(t)
setHostSortMode(t, mode)
ib := seedSubInbound(t, "s1", "dis", 450, 1, tcpTLSStream)
seedHost(t, &model.Host{
InboundId: ib.Id, SortOrder: 1, Remark: "D", Address: "d.cdn.com", Port: 443,
Security: "tls", Sni: "d.sni", IsDisabled: true,
})
for _, format := range []string{"raw", "json", "clash"} {
if !renderFormat(t, format).rendered {
t.Fatalf("%s: inbound with only disabled hosts must still render", format)
}
}
})
}
}
// The panel's link export and per-client link paths must also drop an inbound
// whose hosts are all excluded from raw.
func TestLinkProvider_AllHostsRawExcluded_NoLinks(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "lp", 451, 1, tcpTLSStream)
seedHost(t, &model.Host{
InboundId: ib.Id, SortOrder: 1, Remark: "L", Address: "l.cdn.com", Port: 443,
Security: "tls", Sni: "l.sni", ExcludeFromSubTypes: []string{"raw"},
})
provider := NewLinkProvider()
if links := provider.LinksForClient("req.example.com", ib, "lp@e"); len(links) != 0 {
t.Fatalf("LinksForClient must be empty, got %v", links)
}
if links := provider.LinksForInbounds("req.example.com", []*model.Inbound{ib}); len(links) != 0 {
t.Fatalf("LinksForInbounds must be empty, got %v", links)
}
}
+9 -2
View File
@@ -84,17 +84,24 @@ func hostOrderGroupID(h *model.Host) string {
return fmt.Sprintf("fallback_%d", h.Id)
}
// subscriptionHostVariants returns one variant per enabled host not excluded from format, a single
// host-less variant for an inbound with no enabled host, and none when all its hosts are excluded.
func (s *SubService) subscriptionHostVariants(inbound *model.Inbound, format string) []subscriptionHostVariant {
var variants []subscriptionHostVariant
enabled := 0
for _, h := range s.hostsByInbound[inbound.Id] {
if h.IsDisabled || slices.Contains(h.ExcludeFromSubTypes, format) {
if h.IsDisabled {
continue
}
enabled++
if slices.Contains(h.ExcludeFromSubTypes, format) {
continue
}
order := s.hostGroupOrders[hostOrderGroupID(h)]
order.inboundSort, order.inboundID, order.hostID = inbound.SubSortIndex, inbound.Id, h.Id
variants = append(variants, subscriptionHostVariant{h, &order})
}
if len(variants) == 0 {
if enabled == 0 {
return []subscriptionHostVariant{{}}
}
return variants
+13 -13
View File
@@ -100,7 +100,7 @@ func (s *SubService) clientHostVariants(inbound *model.Inbound, client model.Cli
state, hosts := s.clientHostBinding(inbound, client)
switch state {
case hostBindingNone:
return all, false
return all, len(all) == 0
case hostBindingClosed:
return nil, true
}
@@ -112,13 +112,9 @@ func (s *SubService) clientHostVariants(inbound *model.Inbound, client model.Cli
return variants, len(variants) == 0
}
// hostEndpoints loads an inbound's enabled hosts for the given subscription
// format ("raw"|"json"|"clash") and returns them as externalProxy-shaped maps so
// the existing per-format renderers can fan out one link/proxy per host. Returns
// nil when the inbound has no applicable host — the caller then uses the legacy
// inbound/externalProxy path, preserving byte-identical output for zero-host
// inbounds.
func (s *SubService) hostEndpoints(inbound *model.Inbound, format string) []map[string]any {
// hostEndpoints returns the externalProxy-shaped endpoints of the inbound's enabled hosts for format, nil without any;
// closed reports that all of them are excluded from format, so the inbound renders nothing there.
func (s *SubService) hostEndpoints(inbound *model.Inbound, format string) (eps []map[string]any, closed bool) {
var hosts []*model.Host
if s.hostsByInbound != nil {
hosts = s.hostsByInbound[inbound.Id]
@@ -127,20 +123,24 @@ func (s *SubService) hostEndpoints(inbound *model.Inbound, format string) []map[
Order("sort_order asc, id asc").
Find(&hosts).Error; err != nil {
logger.Warning("SubService - hostEndpoints:", err)
return nil
return nil, false
}
if len(hosts) == 0 {
return nil
return nil, false
}
defaultDest := s.resolveInboundAddress(inbound)
eps := make([]map[string]any, 0, len(hosts))
enabled := 0
for _, h := range hosts {
if h.IsDisabled || slices.Contains(h.ExcludeFromSubTypes, format) {
if h.IsDisabled {
continue
}
enabled++
if slices.Contains(h.ExcludeFromSubTypes, format) {
continue
}
eps = append(eps, s.hostEndpointMaps(h, defaultDest, inbound.Port)...)
}
return eps
return eps, enabled > 0 && len(eps) == 0
}
// hostEndpointMaps is one host's externalProxy entries: a CIDR address expands into RandomCount
+6 -1
View File
@@ -152,12 +152,13 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo
}
subReq.projectThroughFallbackMaster(inbound)
var baseEps []map[string]any
var hostsClosed bool
baseStream := inbound.StreamSettings
// getConfig rewrites inbound.Listen/Port per endpoint while rendering a client, so bound
// endpoints resolve against this pre-loop snapshot.
baseInbound := *inbound
if !subReq.hostsFirst {
if baseEps = subReq.hostEndpoints(inbound, "json"); len(baseEps) > 0 {
if baseEps, hostsClosed = subReq.hostEndpoints(inbound, "json"); len(baseEps) > 0 {
injectExternalProxy(inbound, baseEps)
}
}
@@ -168,6 +169,10 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo
hasEnabledClient = true
}
seenEmails[client.Email] = struct{}{}
if hostsClosed {
hasBoundClosed = true
continue
}
if subReq.hostsFirst {
variants, closed := subReq.clientHostVariants(&baseInbound, client, "json")
hasBoundClosed = hasBoundClosed || closed
+4 -1
View File
@@ -38,7 +38,10 @@ func (p *LinkProvider) SubLinksForSubId(host, subId string) ([]string, error) {
func (p *LinkProvider) LinksForClient(host string, inbound *model.Inbound, email string) []string {
svc := p.build(host)
svc.projectThroughFallbackMaster(inbound)
baseEps := svc.hostEndpoints(inbound, "raw")
baseEps, closed := svc.hostEndpoints(inbound, "raw")
if closed {
return nil
}
if client, ok := svc.clientForLink(inbound, email); ok {
effectiveEps, bound := svc.clientHostEndpoints(inbound, client, "raw", baseEps)
if bound && len(effectiveEps) == 0 {
+7 -3
View File
@@ -590,14 +590,15 @@ func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.Clie
// Host overrides apply AFTER fallback projection so a host's
// address/TLS wins over the projected master stream.
var hostEps []map[string]any
var hostsClosed bool
if !s.hostsFirst {
hostEps = s.hostEndpoints(inbound, "raw")
hostEps, hostsClosed = s.hostEndpoints(inbound, "raw")
}
for _, client := range clients {
if client.Enable {
hasEnabledClient = true
}
if s.rendered.spent() {
if hostsClosed || s.rendered.spent() {
seenEmails[client.Email] = struct{}{}
continue
}
@@ -698,7 +699,10 @@ func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
}
s.primeLinkClients(inbound.Id, clients, true)
s.projectThroughFallbackMaster(inbound)
hostEps := s.hostEndpoints(inbound, "raw")
hostEps, hostsClosed := s.hostEndpoints(inbound, "raw")
if hostsClosed {
return nil
}
var out []string
seen := make(map[string]struct{}, len(clients))
for _, client := range clients {