feat(settings): configurable public IP refresh, IPv6 detection and override (#7189)

Since 3.11.0 the panel asks outside IP-echo services for its public address every five minutes, and on a server with no IPv6 it retried the IPv6 services forever. Operators with static addresses had no way to stop it (#7176).

Add four General settings: the refresh interval (0 keeps the first answer), a switch for IPv6 detection, and a fixed IPv4 and IPv6 address that replace the lookup. The defaults keep today's behaviour. Clearing an override forgets the earlier success, so the next lookup is not timed from before the pin.
This commit is contained in:
Nikan Zeyaei
2026-11-24 14:29:32 +03:30
committed by GitHub
parent 5b71e534d2
commit b39ac90f1e
28 changed files with 625 additions and 19 deletions
+38
View File
@@ -170,6 +170,21 @@
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -652,6 +667,10 @@
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
@@ -961,6 +980,21 @@
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -1451,6 +1485,10 @@
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
+38
View File
@@ -170,6 +170,21 @@
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -652,6 +667,10 @@
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
@@ -961,6 +980,21 @@
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -1451,6 +1485,10 @@
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
+8
View File
@@ -43,6 +43,10 @@ export const EXAMPLES: Record<string, unknown> = {
"outboundDownThreshold": 1,
"pageSize": 0,
"panelOutbound": "",
"publicIpRefreshMinutes": 0,
"publicIpv4Override": "",
"publicIpv6Detect": false,
"publicIpv6Override": "",
"realityScanCandidates": "",
"remarkTemplate": "",
"restartXrayOnClientDisable": false,
@@ -233,6 +237,10 @@ export const EXAMPLES: Record<string, unknown> = {
"outboundDownThreshold": 1,
"pageSize": 0,
"panelOutbound": "",
"publicIpRefreshMinutes": 0,
"publicIpv4Override": "",
"publicIpv6Detect": false,
"publicIpv6Override": "",
"realityScanCandidates": "",
"remarkTemplate": "",
"restartXrayOnClientDisable": false,
+38
View File
@@ -144,6 +144,21 @@ export const SCHEMAS: Record<string, unknown> = {
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -626,6 +641,10 @@ export const SCHEMAS: Record<string, unknown> = {
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
@@ -935,6 +954,21 @@ export const SCHEMAS: Record<string, unknown> = {
"panelOutbound": {
"type": "string"
},
"publicIpRefreshMinutes": {
"description": "0 stops refreshing the detected public IP after the first success.",
"maximum": 10080,
"minimum": 0,
"type": "integer"
},
"publicIpv4Override": {
"type": "string"
},
"publicIpv6Detect": {
"type": "boolean"
},
"publicIpv6Override": {
"type": "string"
},
"realityScanCandidates": {
"type": "string"
},
@@ -1425,6 +1459,10 @@ export const SCHEMAS: Record<string, unknown> = {
"outboundDownThreshold",
"pageSize",
"panelOutbound",
"publicIpRefreshMinutes",
"publicIpv4Override",
"publicIpv6Detect",
"publicIpv6Override",
"realityScanCandidates",
"remarkTemplate",
"restartXrayOnClientDisable",
+8
View File
@@ -52,6 +52,10 @@ export interface AllSetting {
outboundDownThreshold: number;
pageSize: number;
panelOutbound: string;
publicIpRefreshMinutes: number;
publicIpv4Override: string;
publicIpv6Detect: boolean;
publicIpv6Override: string;
realityScanCandidates: string;
remarkTemplate: string;
restartXrayOnClientDisable: boolean;
@@ -243,6 +247,10 @@ export interface AllSettingView {
outboundDownThreshold: number;
pageSize: number;
panelOutbound: string;
publicIpRefreshMinutes: number;
publicIpv4Override: string;
publicIpv6Detect: boolean;
publicIpv6Override: string;
realityScanCandidates: string;
remarkTemplate: string;
restartXrayOnClientDisable: boolean;
+8
View File
@@ -70,6 +70,10 @@ export const AllSettingSchema = z.object({
outboundDownThreshold: z.number().int().min(1).max(100),
pageSize: z.number().int().min(0).max(1000),
panelOutbound: z.string(),
publicIpRefreshMinutes: z.number().int().min(0).max(10080),
publicIpv4Override: z.string(),
publicIpv6Detect: z.boolean(),
publicIpv6Override: z.string(),
realityScanCandidates: z.string(),
remarkTemplate: z.string(),
restartXrayOnClientDisable: z.boolean(),
@@ -262,6 +266,10 @@ export const AllSettingViewSchema = z.object({
outboundDownThreshold: z.number().int().min(1).max(100),
pageSize: z.number().int().min(0).max(1000),
panelOutbound: z.string(),
publicIpRefreshMinutes: z.number().int().min(0).max(10080),
publicIpv4Override: z.string(),
publicIpv6Detect: z.boolean(),
publicIpv6Override: z.string(),
realityScanCandidates: z.string(),
remarkTemplate: z.string(),
restartXrayOnClientDisable: z.boolean(),
+4
View File
@@ -9,6 +9,10 @@ export class AllSetting {
webKeyFile = '';
webBasePath = '/';
sessionMaxAge = 360;
publicIpRefreshMinutes = 5;
publicIpv6Detect = true;
publicIpv4Override = '';
publicIpv6Override = '';
trustedProxyCIDRs = '127.0.0.1/32,::1/128';
realityScanCandidates =
'www.cloudflare.com:443,www.microsoft.com:443,www.amazon.com:443,aws.amazon.com:443,www.samsung.com:443,www.nvidia.com:443,www.amd.com:443,www.intel.com:443,www.sony.com:443,dl.google.com:443';
@@ -253,6 +253,65 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.publicIpRefresh')}
badge={
<DefaultSettingTag
settingKey="publicIpRefreshMinutes"
value={allSetting.publicIpRefreshMinutes}
/>
}
description={t('pages.settings.publicIpRefreshDesc')}
>
<InputNumber
value={allSetting.publicIpRefreshMinutes}
min={0}
max={10080}
style={{ width: '100%' }}
onChange={onNumber((v) => updateSetting({ publicIpRefreshMinutes: v }))}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.publicIpv6Detect')}
badge={
<DefaultSettingTag
settingKey="publicIpv6Detect"
value={allSetting.publicIpv6Detect}
/>
}
description={t('pages.settings.publicIpv6DetectDesc')}
>
<Switch
checked={allSetting.publicIpv6Detect}
onChange={(v) => updateSetting({ publicIpv6Detect: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.publicIpv4Override')}
description={t('pages.settings.publicIpOverrideDesc')}
>
<Input
value={allSetting.publicIpv4Override}
onChange={(e) => updateSetting({ publicIpv4Override: e.target.value.trim() })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.publicIpv6Override')}
description={t('pages.settings.publicIpOverrideDesc')}
>
<Input
value={allSetting.publicIpv6Override}
onChange={(e) => updateSetting({ publicIpv6Override: e.target.value.trim() })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.trustedProxyCidrs')}
+4
View File
@@ -19,6 +19,10 @@ export const AllSettingSchema = z
webKeyFile: z.string().optional(),
webBasePath: absolutePath.optional(),
sessionMaxAge: z.number().int().min(1).max(525600).optional(),
publicIpRefreshMinutes: z.number().int().min(0).max(10080).optional(),
publicIpv6Detect: z.boolean().optional(),
publicIpv4Override: z.string().optional(),
publicIpv6Override: z.string().optional(),
trustedProxyCIDRs: z.string().optional(),
realityScanCandidates: z.string().optional(),
ipLimitAllowlist: z.string().optional(),
+29
View File
@@ -145,3 +145,32 @@ func TestCheckValidNormalizesPanelAndSubDomains(t *testing.T) {
}
}
}
// The override is displayed on the overview and used in backup filenames, so a
// hostname, wrong-family or zoned address must be rejected at save time.
func TestCheckValidPublicIPOverride(t *testing.T) {
cases := []struct {
v4, v6, want string
}{
{"", "", ""},
{"203.0.113.9", "2001:db8::1", ""},
{"example.com", "", "public IPv4 override is not a valid IPv4 address: example.com"},
{"2001:db8::1", "", "public IPv4 override is not a valid IPv4 address: 2001:db8::1"},
{"", "203.0.113.9", "public IPv6 override is not a valid IPv6 address: 203.0.113.9"},
{"", "fe80::1%eth0", "public IPv6 override is not a valid IPv6 address: fe80::1%eth0"},
{"", "::ffff:203.0.113.9", "public IPv6 override is not a valid IPv6 address: ::ffff:203.0.113.9"},
}
for _, c := range cases {
s := &AllSetting{WebPort: 2053, SubPort: 2096, PublicIpv4Override: c.v4, PublicIpv6Override: c.v6}
err := s.CheckValid()
if c.want == "" {
if err != nil {
t.Errorf("v4=%q v6=%q: unexpected error %v", c.v4, c.v6, err)
}
continue
}
if err == nil || err.Error() != c.want {
t.Errorf("v4=%q v6=%q: err=%v, want %q", c.v4, c.v6, err, c.want)
}
}
}
+40 -11
View File
@@ -21,17 +21,22 @@ type Msg struct {
}
type AllSetting struct {
WebListen string `json:"webListen" form:"webListen"`
WebDomain string `json:"webDomain" form:"webDomain"`
WebPort int `json:"webPort" form:"webPort" validate:"gte=1,lte=65535"`
WebCertFile string `json:"webCertFile" form:"webCertFile"`
WebKeyFile string `json:"webKeyFile" form:"webKeyFile"`
WebBasePath string `json:"webBasePath" form:"webBasePath"`
SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge" validate:"gte=1,lte=525600"`
TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"`
RealityScanCandidates string `json:"realityScanCandidates" form:"realityScanCandidates"`
IpLimitAllowlist string `json:"ipLimitAllowlist" form:"ipLimitAllowlist"`
PanelOutbound string `json:"panelOutbound" form:"panelOutbound"`
WebListen string `json:"webListen" form:"webListen"`
WebDomain string `json:"webDomain" form:"webDomain"`
WebPort int `json:"webPort" form:"webPort" validate:"gte=1,lte=65535"`
WebCertFile string `json:"webCertFile" form:"webCertFile"`
WebKeyFile string `json:"webKeyFile" form:"webKeyFile"`
WebBasePath string `json:"webBasePath" form:"webBasePath"`
SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge" validate:"gte=1,lte=525600"`
// 0 stops refreshing the detected public IP after the first success.
PublicIpRefreshMinutes int `json:"publicIpRefreshMinutes" form:"publicIpRefreshMinutes" validate:"gte=0,lte=10080"`
PublicIpv6Detect bool `json:"publicIpv6Detect" form:"publicIpv6Detect"`
PublicIpv4Override string `json:"publicIpv4Override" form:"publicIpv4Override"`
PublicIpv6Override string `json:"publicIpv6Override" form:"publicIpv6Override"`
TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"`
RealityScanCandidates string `json:"realityScanCandidates" form:"realityScanCandidates"`
IpLimitAllowlist string `json:"ipLimitAllowlist" form:"ipLimitAllowlist"`
PanelOutbound string `json:"panelOutbound" form:"panelOutbound"`
PageSize int `json:"pageSize" form:"pageSize" validate:"gte=0,lte=1000"`
ExpireDiff int `json:"expireDiff" form:"expireDiff" validate:"gte=0"`
@@ -397,6 +402,13 @@ func (s *AllSetting) CheckValid() error {
}
}
if err := checkPublicIPOverride(s.PublicIpv4Override, true); err != nil {
return err
}
if err := checkPublicIPOverride(s.PublicIpv6Override, false); err != nil {
return err
}
if err := checkIPOrCIDRList(s.TrustedProxyCIDRs, "trusted proxy CIDR is not valid:"); err != nil {
return err
}
@@ -421,6 +433,23 @@ func (s *AllSetting) CheckValid() error {
return nil
}
// checkPublicIPOverride accepts an empty value or a bare address of the
// family; the override is shown on the overview and used in backup filenames.
func checkPublicIPOverride(value string, wantV4 bool) error {
if value == "" {
return nil
}
ip, err := netip.ParseAddr(value)
if err != nil || ip.Zone() != "" || ip.Is4() != wantV4 || ip.Is4In6() {
family := "IPv6"
if wantV4 {
family = "IPv4"
}
return common.NewErrorf("public %s override is not a valid %s address: %s", family, family, value)
}
return nil
}
// listenAddressesConflict reports whether two listen addresses on the same port
// would collide at bind time. A wildcard listen ("", "0.0.0.0", "::") overlaps
// every address, so it conflicts with anything on that port; two specific
+81 -6
View File
@@ -157,6 +157,10 @@ type ServerService struct {
cachedIPv6 string
nextIPv4Lookup time.Time
nextIPv6Lookup time.Time
ipv4OKAt time.Time
ipv6OKAt time.Time
ipv4Fixed bool
ipv6Fixed bool
ipv6RetryInterval time.Duration
publicIPLookupDone chan struct{}
mu sync.Mutex
@@ -467,6 +471,60 @@ const (
publicIPRetryInterval = time.Minute
)
// publicIPNever is the deadline of a lookup that must not run again.
var publicIPNever = time.Date(9999, 1, 1, 0, 0, 0, 0, time.UTC)
type publicIPSettings struct {
refresh time.Duration // 0: keep the first successful answer
ipv6 bool
override4 string
override6 string
}
// publicIPSettingsSource is a variable so tests can run without a database.
var publicIPSettingsSource = func(s *ServerService) publicIPSettings {
p := publicIPSettings{refresh: publicIPRefreshInterval, ipv6: true}
if m, err := s.settingService.GetPublicIpRefreshMinutes(); err != nil {
logger.Warning("get public IP refresh interval failed:", err)
} else {
p.refresh = time.Duration(m) * time.Minute
}
if v, err := s.settingService.GetPublicIpv6Detect(); err != nil {
logger.Warning("get public IPv6 detection failed:", err)
} else {
p.ipv6 = v
}
if v, err := s.settingService.GetPublicIpv4Override(); err == nil {
p.override4 = strings.TrimSpace(v)
}
if v, err := s.settingService.GetPublicIpv6Override(); err == nil {
p.override6 = strings.TrimSpace(v)
}
return p
}
// publicIPDeadline is when a successful answer obtained at okAt goes stale.
func publicIPDeadline(okAt time.Time, refresh time.Duration) time.Time {
if refresh == 0 {
return publicIPNever
}
return okAt.Add(refresh)
}
// settlePublicIP makes one family follow the settings: a fixed value pins it
// and stops lookups; a changed interval re-times the last success.
func settlePublicIP(fixed string, pinned *bool, cached *string, next, okAt *time.Time, refresh time.Duration) {
switch {
case fixed != "":
*cached, *next, *pinned = fixed, publicIPNever, true
case *pinned:
// okAt is zeroed so a pre-pin success cannot re-time the next tick.
*cached, *next, *pinned, *okAt = "", time.Time{}, false, time.Time{}
case !okAt.IsZero():
*next = publicIPDeadline(*okAt, refresh)
}
}
// resolvePublicIPs waits for the initial lookup so cold backups can use it.
// Warm callers use cached addresses while a refresh runs in the background.
func (s *ServerService) resolvePublicIPs() {
@@ -477,9 +535,9 @@ func (s *ServerService) resolvePublicIPs() {
}
// refreshedPublicIP retains a known address through temporary lookup failures.
func refreshedPublicIP(cached, fetched string, now time.Time) (string, time.Time) {
func refreshedPublicIP(cached, fetched string, now time.Time, refresh time.Duration) (string, time.Time) {
if fetched != "" && fetched != "N/A" {
return fetched, now.Add(publicIPRefreshInterval)
return fetched, publicIPDeadline(now, refresh)
}
if cached == "" {
cached = "N/A"
@@ -500,6 +558,14 @@ func nextPublicIPv6RetryInterval(previous time.Duration) time.Duration {
}
}
// lookupOKAt is the zero time for a failed lookup, so only successes re-time.
func lookupOKAt(fetched string, now time.Time) time.Time {
if fetched == "" || fetched == "N/A" {
return time.Time{}
}
return now
}
// firstPublicIP returns the first service that answers, or "N/A" when every
// one of them fails.
func firstPublicIP(services []string) string {
@@ -516,7 +582,14 @@ func firstPublicIP(services []string) string {
// resolvePublicIPsInBackground shares one lookup without blocking status samples.
// Each address family has its own deadline; cached values stay readable.
func (s *ServerService) resolvePublicIPsInBackground() <-chan struct{} {
p := publicIPSettingsSource(s)
fixed6 := p.override6
if fixed6 == "" && !p.ipv6 {
fixed6 = "N/A"
}
s.mu.Lock()
settlePublicIP(p.override4, &s.ipv4Fixed, &s.cachedIPv4, &s.nextIPv4Lookup, &s.ipv4OKAt, p.refresh)
settlePublicIP(fixed6, &s.ipv6Fixed, &s.cachedIPv6, &s.nextIPv6Lookup, &s.ipv6OKAt, p.refresh)
if done := s.publicIPLookupDone; done != nil {
s.mu.Unlock()
return done
@@ -544,11 +617,13 @@ func (s *ServerService) resolvePublicIPsInBackground() <-chan struct{} {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
if wantIPv4 {
s.cachedIPv4, s.nextIPv4Lookup = refreshedPublicIP(s.cachedIPv4, ipv4, now)
if wantIPv4 && !s.ipv4Fixed {
s.cachedIPv4, s.nextIPv4Lookup = refreshedPublicIP(s.cachedIPv4, ipv4, now, p.refresh)
s.ipv4OKAt = lookupOKAt(ipv4, now)
}
if wantIPv6 {
s.cachedIPv6, s.nextIPv6Lookup = refreshedPublicIP(s.cachedIPv6, ipv6, now)
if wantIPv6 && !s.ipv6Fixed {
s.cachedIPv6, s.nextIPv6Lookup = refreshedPublicIP(s.cachedIPv6, ipv6, now, p.refresh)
s.ipv6OKAt = lookupOKAt(ipv6, now)
if ipv6 != "" && ipv6 != "N/A" {
s.ipv6RetryInterval = 0
} else {
@@ -68,11 +68,16 @@ func (f publicIPTestTransport) RoundTrip(r *http.Request) (*http.Response, error
func stubPublicIPServices(t *testing.T, respond publicIPTestTransport) {
t.Helper()
oldTransport, old4, old6 := http.DefaultTransport, publicIPv4Services, publicIPv6Services
oldTransport, old4, old6, oldSettings := http.DefaultTransport, publicIPv4Services, publicIPv6Services, publicIPSettingsSource
publicIPSettingsSource = func(*ServerService) publicIPSettings {
return publicIPSettings{refresh: publicIPRefreshInterval, ipv6: true}
}
http.DefaultTransport = respond
publicIPv4Services = []string{"https://ipv4.example.test/primary", "https://ipv4.example.test/fallback"}
publicIPv6Services = []string{"https://ipv6.example.test/primary", "https://ipv6.example.test/fallback"}
t.Cleanup(func() { http.DefaultTransport, publicIPv4Services, publicIPv6Services = oldTransport, old4, old6 })
t.Cleanup(func() {
http.DefaultTransport, publicIPv4Services, publicIPv6Services, publicIPSettingsSource = oldTransport, old4, old6, oldSettings
})
}
func publicIPResponse(status int, body string) (*http.Response, error) {
@@ -591,3 +596,148 @@ func TestGetPublicIPAcceptsOnlyAnAddress(t *testing.T) {
})
}
}
func setPublicIPSettings(t *testing.T, p *publicIPSettings) {
t.Helper()
publicIPSettingsSource = func(*ServerService) publicIPSettings { return *p }
}
// A static-IP VPS asked for no periodic lookups; refresh 0 must hold the first
// answer for good while a failed first lookup is still retried.
func TestPublicIPRefreshZeroKeepsFirstSuccessAndRetriesFailure(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var calls atomic.Int32
fail4 := true
stubPublicIPServices(t, func(r *http.Request) (*http.Response, error) {
calls.Add(1)
if r.URL.Hostname() == "ipv4.example.test" {
if fail4 {
return publicIPResponse(500, "")
}
return publicIPResponse(200, "192.0.2.10")
}
return publicIPResponse(200, "2001:db8::10")
})
setPublicIPSettings(t, &publicIPSettings{refresh: 0, ipv6: true})
svc := &ServerService{}
svc.resolvePublicIPs()
assertCachedPublicIPs(t, svc, "N/A", "2001:db8::10")
fail4 = false
time.Sleep(publicIPRetryInterval)
svc.resolvePublicIPsInBackground()
synctest.Wait()
assertCachedPublicIPs(t, svc, "192.0.2.10", "2001:db8::10")
before := calls.Load()
time.Sleep(48 * time.Hour)
svc.resolvePublicIPsInBackground()
synctest.Wait()
if got := calls.Load(); got != before {
t.Fatalf("lookups after the first success: %d new requests, want 0", got-before)
}
})
}
// Raising refresh from "never" back to an interval must apply to an address
// already looked up, not wait out the old deadline.
func TestPublicIPIntervalChangeRetimesLastSuccess(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var calls atomic.Int32
stubPublicIPServices(t, func(r *http.Request) (*http.Response, error) {
calls.Add(1)
return publicIPResponse(200, "192.0.2.10")
})
p := &publicIPSettings{refresh: 0, ipv6: false}
setPublicIPSettings(t, p)
svc := &ServerService{}
svc.resolvePublicIPs()
synctest.Wait()
before := calls.Load()
p.refresh = time.Hour
time.Sleep(time.Hour)
svc.resolvePublicIPsInBackground()
synctest.Wait()
if got := calls.Load(); got != before+1 {
t.Fatalf("requests after interval change = %d, want %d", got, before+1)
}
})
}
// IPv4-only hosts must not contact any IPv6 echo service, and IPv6 detection
// must resume once re-enabled.
func TestPublicIPv6DisabledSkipsLookupsAndResumesWhenEnabled(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var v6Calls atomic.Int32
stubPublicIPServices(t, func(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() == "ipv6.example.test" {
v6Calls.Add(1)
return publicIPResponse(200, "2001:db8::10")
}
return publicIPResponse(200, "192.0.2.10")
})
p := &publicIPSettings{refresh: publicIPRefreshInterval, ipv6: false}
setPublicIPSettings(t, p)
svc := &ServerService{}
svc.resolvePublicIPs()
time.Sleep(time.Hour)
svc.resolvePublicIPsInBackground()
synctest.Wait()
if got := v6Calls.Load(); got != 0 {
t.Fatalf("IPv6 services contacted %d times while disabled", got)
}
assertCachedPublicIPs(t, svc, "192.0.2.10", "N/A")
p.ipv6 = true
svc.resolvePublicIPsInBackground()
synctest.Wait()
assertCachedPublicIPs(t, svc, "192.0.2.10", "2001:db8::10")
})
}
// An override replaces lookup for its family only, and clearing it resumes lookup.
func TestPublicIPOverridePinsOneFamilyAndClearingResumesLookup(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var v4Calls atomic.Int32
stubPublicIPServices(t, func(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() == "ipv4.example.test" {
v4Calls.Add(1)
return publicIPResponse(200, "192.0.2.10")
}
return publicIPResponse(200, "2001:db8::10")
})
p := &publicIPSettings{refresh: publicIPRefreshInterval, ipv6: true, override4: "198.51.100.7"}
setPublicIPSettings(t, p)
svc := &ServerService{}
svc.resolvePublicIPs()
time.Sleep(time.Hour)
svc.resolvePublicIPsInBackground()
synctest.Wait()
if got := v4Calls.Load(); got != 0 {
t.Fatalf("IPv4 services contacted %d times despite an override", got)
}
assertCachedPublicIPs(t, svc, "198.51.100.7", "2001:db8::10")
p.override4 = ""
svc.resolvePublicIPsInBackground()
synctest.Wait()
assertCachedPublicIPs(t, svc, "192.0.2.10", "2001:db8::10")
})
}
// A success from before the override must not re-time the family once the
// override is cleared, or refresh 0 would leave it blank until restart.
func TestSettlePublicIPClearedOverrideForgetsOldSuccess(t *testing.T) {
var (
pinned bool
cached string
next, okAt = time.Time{}, time.Now()
)
settlePublicIP("198.51.100.7", &pinned, &cached, &next, &okAt, 0)
settlePublicIP("", &pinned, &cached, &next, &okAt, 0)
settlePublicIP("", &pinned, &cached, &next, &okAt, 0)
if !next.IsZero() || cached != "" {
t.Fatalf("after clearing override next=%v cached=%q, want immediate lookup", next, cached)
}
}
+20
View File
@@ -74,6 +74,10 @@ var defaultValueMap = map[string]string{
"nodeMtlsClientCAPem": "",
"webBasePath": normalizeBasePath(getEnv("XUI_INIT_WEB_BASE_PATH", "/")),
"sessionMaxAge": "360",
"publicIpRefreshMinutes": "5",
"publicIpv6Detect": "true",
"publicIpv4Override": "",
"publicIpv6Override": "",
"trustedProxyCIDRs": DefaultTrustedProxyCIDRs,
"realityScanCandidates": DefaultRealityScanCandidatesCSV,
"ipLimitAllowlist": "",
@@ -750,6 +754,22 @@ func (s *SettingService) GetTrafficDiff() (int, error) {
return s.getInt("trafficDiff")
}
func (s *SettingService) GetPublicIpRefreshMinutes() (int, error) {
return s.getInt("publicIpRefreshMinutes")
}
func (s *SettingService) GetPublicIpv6Detect() (bool, error) {
return s.getBool("publicIpv6Detect")
}
func (s *SettingService) GetPublicIpv4Override() (string, error) {
return s.getString("publicIpv4Override")
}
func (s *SettingService) GetPublicIpv6Override() (string, error) {
return s.getString("publicIpv6Override")
}
func (s *SettingService) GetSessionMaxAge() (int, error) {
return s.getInt("sessionMaxAge")
}
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "استقبل إشعار بكل محاولة تسجيل دخول للبانل مع اسم المستخدم، الـ IP، والوقت.",
"sessionMaxAge": "مدة الجلسة",
"sessionMaxAgeDesc": "المدة اللي تفضل فيها مسجل دخول. (الوحدة: دقيقة)",
"publicIpRefresh": "تحديث الـ IP العام",
"publicIpRefreshDesc": "كل قد إيه اللوحة تعيد اكتشاف الـ IP العام عن طريق خدمات خارجية. 0 يعني تكتشفه مرة واحدة ومايتحدثش. (الوحدة: دقيقة)",
"publicIpv6Detect": "اكتشاف IPv6 العام",
"publicIpv6DetectDesc": "اقفله على السيرفرات اللي IPv4 بس عشان يتخطى كل عمليات البحث عن IPv6.",
"publicIpv4Override": "تجاوز IPv4 العام",
"publicIpv6Override": "تجاوز IPv6 العام",
"publicIpOverrideDesc": "استخدم العنوان ده بدل اكتشافه؛ مفيش أي طلبات خارجية له. سيبه فاضي للاكتشاف التلقائي.",
"expireTimeDiff": "تنبيه بتاريخ الانتهاء",
"expireTimeDiffDesc": "استقبل تنبيه قبل ما توصل لتاريخ الانتهاء بالمدة المحددة. (الوحدة: يوم)",
"trafficDiff": "تنبيه حد الترافيك",
+7
View File
@@ -1422,6 +1422,13 @@
"tgNotifyLoginDesc": "Get notified about the username, IP address, and time whenever someone attempts to log into your web panel.",
"sessionMaxAge": "Session Duration",
"sessionMaxAgeDesc": "The duration for which you can stay logged in. (unit: minute)",
"publicIpRefresh": "Public IP Refresh",
"publicIpRefreshDesc": "How often the panel re-detects its public IP through external services. 0 detects once and never refreshes. (unit: minute)",
"publicIpv6Detect": "Detect Public IPv6",
"publicIpv6DetectDesc": "Turn off on IPv4-only servers to skip all IPv6 lookups.",
"publicIpv4Override": "Public IPv4 Override",
"publicIpv6Override": "Public IPv6 Override",
"publicIpOverrideDesc": "Use this address instead of detecting it; no external lookups are made for it. Leave empty to detect.",
"expireTimeDiff": "Expiration Date Notification",
"expireTimeDiffDesc": "Get notified about expiration date when reaching this threshold. (unit: day)",
"trafficDiff": "Traffic Cap Notification",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Muestra el nombre de usuario, dirección IP y hora cuando alguien intenta iniciar sesión en su panel.",
"sessionMaxAge": "Edad Máxima de Sesión",
"sessionMaxAgeDesc": "La duración de una sesión de inicio de sesión (unidad: minutos).",
"publicIpRefresh": "Actualización de IP pública",
"publicIpRefreshDesc": "Con qué frecuencia el panel vuelve a detectar su IP pública mediante servicios externos. 0 la detecta una vez y no la actualiza. (unidad: minuto)",
"publicIpv6Detect": "Detectar IPv6 pública",
"publicIpv6DetectDesc": "Desactívalo en servidores solo IPv4 para omitir todas las consultas IPv6.",
"publicIpv4Override": "IPv4 pública manual",
"publicIpv6Override": "IPv6 pública manual",
"publicIpOverrideDesc": "Usa esta dirección en lugar de detectarla; no se hacen consultas externas para ella. Déjalo vacío para detectarla.",
"expireTimeDiff": "Umbral de Expiración para Notificación",
"expireTimeDiffDesc": "Reciba notificaciones sobre la expiración de la cuenta antes del umbral (unidad: días).",
"trafficDiff": "Umbral de Tráfico para Notificación",
+7
View File
@@ -1301,6 +1301,13 @@
"tgNotifyLoginDesc": "نام‌کاربری، آدرس آی‌پی، و زمان ورود، فردی که سعی می‌کند وارد پنل شود را نمایش می‌دهد",
"sessionMaxAge": "بیشینه زمان جلسه وب",
"sessionMaxAgeDesc": "(بیشینه زمانی که می‌توانید لاگین بمانید. (واحد: دقیقه",
"publicIpRefresh": "به‌روزرسانی IP عمومی",
"publicIpRefreshDesc": "هر چند وقت یک‌بار پنل IP عمومی خود را از طریق سرویس‌های خارجی دوباره شناسایی کند. مقدار 0 فقط یک‌بار شناسایی می‌کند و دیگر به‌روز نمی‌کند. (واحد: دقیقه)",
"publicIpv6Detect": "شناسایی IPv6 عمومی",
"publicIpv6DetectDesc": "روی سرورهای فقط IPv4 خاموش کنید تا همهٔ جست‌وجوهای IPv6 انجام نشود.",
"publicIpv4Override": "IPv4 عمومی دستی",
"publicIpv6Override": "IPv6 عمومی دستی",
"publicIpOverrideDesc": "به‌جای شناسایی، از این آدرس استفاده می‌شود و هیچ درخواست خارجی برای آن ارسال نمی‌شود. برای شناسایی خودکار خالی بگذارید.",
"expireTimeDiff": "آستانه زمان باقی مانده",
"expireTimeDiffDesc": "(فاصله زمانی هشدار تا رسیدن به زمان انقضا. (واحد: روز",
"trafficDiff": "آستانه ترافیک باقی مانده",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Dapatkan notifikasi tentang username, alamat IP, dan waktu setiap kali seseorang mencoba masuk ke panel web Anda.",
"sessionMaxAge": "Durasi Sesi",
"sessionMaxAgeDesc": "Durasi di mana Anda dapat tetap masuk. (unit: menit)",
"publicIpRefresh": "Penyegaran IP Publik",
"publicIpRefreshDesc": "Seberapa sering panel mendeteksi ulang IP publiknya melalui layanan eksternal. 0 mendeteksi sekali dan tidak pernah menyegarkan. (satuan: menit)",
"publicIpv6Detect": "Deteksi IPv6 Publik",
"publicIpv6DetectDesc": "Matikan pada server khusus IPv4 untuk melewati semua pencarian IPv6.",
"publicIpv4Override": "Penimpaan IPv4 Publik",
"publicIpv6Override": "Penimpaan IPv6 Publik",
"publicIpOverrideDesc": "Gunakan alamat ini alih-alih mendeteksinya; tidak ada permintaan eksternal untuknya. Kosongkan untuk mendeteksi.",
"expireTimeDiff": "Notifikasi Tanggal Kedaluwarsa",
"expireTimeDiffDesc": "Dapatkan notifikasi tentang tanggal kedaluwarsa saat mencapai ambang batas ini. (unit: hari)",
"trafficDiff": "Notifikasi Batas Traffic",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "誰かがパネルにログインしようとしたときに、ユーザー名、IPアドレス、時間を表示する",
"sessionMaxAge": "セッション期間",
"sessionMaxAgeDesc": "ログイン状態を保持する期間(単位:分)",
"publicIpRefresh": "パブリックIPの更新",
"publicIpRefreshDesc": "外部サービスでパブリックIPを再検出する間隔。0なら一度だけ検出し、更新しません。(単位: 分)",
"publicIpv6Detect": "パブリックIPv6を検出",
"publicIpv6DetectDesc": "IPv4のみのサーバーではオフにすると、IPv6の問い合わせをすべて省略します。",
"publicIpv4Override": "パブリックIPv4の手動指定",
"publicIpv6Override": "パブリックIPv6の手動指定",
"publicIpOverrideDesc": "検出せずにこのアドレスを使用します。外部への問い合わせは行いません。空欄の場合は自動検出します。",
"expireTimeDiff": "有効期限通知のしきい値",
"expireTimeDiffDesc": "このしきい値に達した場合、有効期限に関する通知を受け取る(単位:日)",
"trafficDiff": "トラフィック消耗しきい値",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Receba notificações sobre o nome de usuário, endereço IP e horário sempre que alguém tentar fazer login no seu painel web.",
"sessionMaxAge": "Duração da Sessão",
"sessionMaxAgeDesc": "A duração pela qual você pode permanecer logado. (unidade: minuto)",
"publicIpRefresh": "Atualização do IP público",
"publicIpRefreshDesc": "Com que frequência o painel detecta novamente seu IP público por serviços externos. 0 detecta uma vez e nunca atualiza. (unidade: minuto)",
"publicIpv6Detect": "Detectar IPv6 público",
"publicIpv6DetectDesc": "Desative em servidores apenas IPv4 para ignorar todas as consultas IPv6.",
"publicIpv4Override": "IPv4 público manual",
"publicIpv6Override": "IPv6 público manual",
"publicIpOverrideDesc": "Usa este endereço em vez de detectá-lo; nenhuma consulta externa é feita para ele. Deixe vazio para detectar.",
"expireTimeDiff": "Notificação de Expiração",
"expireTimeDiffDesc": "Receba notificações sobre a data de expiração ao atingir esse limite. (unidade: dia)",
"trafficDiff": "Notificação de Limite de Tráfego",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Отображает имя пользователя, IP-адрес и время, когда кто-то пытается войти в вашу панель.",
"sessionMaxAge": "Продолжительность сессии",
"sessionMaxAgeDesc": "Продолжительность сессии в системе (значение: минута)",
"publicIpRefresh": "Обновление публичного IP",
"publicIpRefreshDesc": "Как часто панель заново определяет свой публичный IP через внешние сервисы. 0 — определить один раз и больше не обновлять. (единица: минута)",
"publicIpv6Detect": "Определять публичный IPv6",
"publicIpv6DetectDesc": "Отключите на серверах только с IPv4, чтобы пропускать все запросы IPv6.",
"publicIpv4Override": "Публичный IPv4 вручную",
"publicIpv6Override": "Публичный IPv6 вручную",
"publicIpOverrideDesc": "Использовать этот адрес вместо определения; внешние запросы для него не выполняются. Оставьте пустым для автоопределения.",
"expireTimeDiff": "Задержка уведомления об истечении сессии",
"expireTimeDiffDesc": "Получение уведомления об истечении срока действия сессии до достижения порогового значения (значение: день)",
"trafficDiff": "Порог трафика для уведомления",
+7
View File
@@ -1422,6 +1422,13 @@
"tgNotifyLoginDesc": "Pri každom pokuse o prihlásenie do panelu poslať používateľské meno, IP adresu a čas.",
"sessionMaxAge": "Platnosť prihlásenia",
"sessionMaxAgeDesc": "Ako dlho môžete zostať prihlásení (jednotka: minúta).",
"publicIpRefresh": "Obnovenie verejnej IP",
"publicIpRefreshDesc": "Ako často panel znova zisťuje svoju verejnú IP cez externé služby. 0 zistí raz a už neobnovuje. (jednotka: minúta)",
"publicIpv6Detect": "Zisťovať verejnú IPv6",
"publicIpv6DetectDesc": "Vypnite na serveroch len s IPv4, aby sa preskočili všetky dotazy IPv6.",
"publicIpv4Override": "Ručná verejná IPv4",
"publicIpv6Override": "Ručná verejná IPv6",
"publicIpOverrideDesc": "Použije sa táto adresa namiesto zisťovania; nevykonajú sa pre ňu žiadne externé dotazy. Ak chcete automatické zisťovanie, nechajte prázdne.",
"expireTimeDiff": "Upozornenie na koniec platnosti",
"expireTimeDiffDesc": "Upozorniť na koniec platnosti pri dosiahnutí tohto prahu (jednotka: deň).",
"trafficDiff": "Upozornenie na dátový limit",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Birisi web panelinize giriş yapmaya çalıştığında kullanıcı adı, IP adresi ve zaman hakkında bildirim almanızı sağlar.",
"sessionMaxAge": "Oturum Süresi",
"sessionMaxAgeDesc": "Giriş yaptıktan sonra oturum süresi. (birim: dakika)",
"publicIpRefresh": "Genel IP Yenileme",
"publicIpRefreshDesc": "Panelin genel IP'sini harici hizmetlerle ne sıklıkla yeniden tespit edeceği. 0 bir kez tespit eder ve bir daha yenilemez. (birim: dakika)",
"publicIpv6Detect": "Genel IPv6'yı Tespit Et",
"publicIpv6DetectDesc": "Yalnızca IPv4 olan sunucularda tüm IPv6 sorgularını atlamak için kapatın.",
"publicIpv4Override": "Genel IPv4 Elle Girişi",
"publicIpv6Override": "Genel IPv6 Elle Girişi",
"publicIpOverrideDesc": "Tespit etmek yerine bu adres kullanılır; bunun için harici sorgu yapılmaz. Otomatik tespit için boş bırakın.",
"expireTimeDiff": "Son Kullanma Tarihi Bildirimi",
"expireTimeDiffDesc": "Bu eşik seviyesine ulaşıldığında son kullanma tarihi hakkında bildirim almanızı sağlar. (birim: gün)",
"trafficDiff": "Trafik Sınırı Bildirimi",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Отримувати сповіщення про ім'я користувача, IP-адресу та час щоразу, коли хтось намагається увійти у вашу веб-панель.",
"sessionMaxAge": "Тривалість сеансу",
"sessionMaxAgeDesc": "Тривалість, протягом якої ви можете залишатися в системі. (одиниця: хвилина)",
"publicIpRefresh": "Оновлення публічної IP",
"publicIpRefreshDesc": "Як часто панель повторно визначає свою публічну IP через зовнішні сервіси. 0 — визначити один раз і більше не оновлювати. (одиниця: хвилина)",
"publicIpv6Detect": "Визначати публічну IPv6",
"publicIpv6DetectDesc": "Вимкніть на серверах лише з IPv4, щоб пропускати всі запити IPv6.",
"publicIpv4Override": "Публічна IPv4 вручну",
"publicIpv6Override": "Публічна IPv6 вручну",
"publicIpOverrideDesc": "Використовувати цю адресу замість визначення; зовнішні запити для неї не виконуються. Залиште порожнім для автовизначення.",
"expireTimeDiff": "Повідомлення про дату закінчення",
"expireTimeDiffDesc": "Отримувати сповіщення про термін дії при досягненні цього порогу. (одиниця: день)",
"trafficDiff": "Повідомлення про обмеження трафіку",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "Hiển thị tên người dùng, địa chỉ IP và thời gian khi ai đó cố gắng đăng nhập vào bảng điều khiển của bạn.",
"sessionMaxAge": "Thời gian tối đa của phiên",
"sessionMaxAgeDesc": "Thời gian của phiên đăng nhập (đơn vị: phút)",
"publicIpRefresh": "Làm mới IP công khai",
"publicIpRefreshDesc": "Tần suất bảng điều khiển phát hiện lại IP công khai qua dịch vụ bên ngoài. 0 là phát hiện một lần và không làm mới. (đơn vị: phút)",
"publicIpv6Detect": "Phát hiện IPv6 công khai",
"publicIpv6DetectDesc": "Tắt trên máy chủ chỉ có IPv4 để bỏ qua mọi truy vấn IPv6.",
"publicIpv4Override": "IPv4 công khai thủ công",
"publicIpv6Override": "IPv6 công khai thủ công",
"publicIpOverrideDesc": "Dùng địa chỉ này thay vì phát hiện; không có truy vấn bên ngoài nào cho nó. Để trống để tự phát hiện.",
"expireTimeDiff": "Ngưỡng hết hạn cho thông báo",
"expireTimeDiffDesc": "Nhận thông báo về việc hết hạn tài khoản trước ngưỡng này (đơn vị: ngày)",
"trafficDiff": "Ngưỡng lưu lượng cho thông báo",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "当有人试图登录你的面板时显示用户名、IP 地址和时间",
"sessionMaxAge": "会话时长",
"sessionMaxAgeDesc": "保持登录状态的时长(单位:分钟)",
"publicIpRefresh": "公网 IP 刷新",
"publicIpRefreshDesc": "面板通过外部服务重新检测公网 IP 的间隔。0 表示仅检测一次,不再刷新。(单位:分钟)",
"publicIpv6Detect": "检测公网 IPv6",
"publicIpv6DetectDesc": "仅有 IPv4 的服务器请关闭,以跳过所有 IPv6 查询。",
"publicIpv4Override": "手动指定公网 IPv4",
"publicIpv6Override": "手动指定公网 IPv6",
"publicIpOverrideDesc": "使用此地址而不进行检测,不会为其发起任何外部查询。留空则自动检测。",
"expireTimeDiff": "到期通知阈值",
"expireTimeDiffDesc": "达到此阈值时,将收到有关到期时间的通知(单位:天)",
"trafficDiff": "流量耗尽阈值",
+7
View File
@@ -1297,6 +1297,13 @@
"tgNotifyLoginDesc": "當有人試圖登入你的面板時顯示使用者名稱、IP 地址和時間",
"sessionMaxAge": "會話時長",
"sessionMaxAgeDesc": "保持登入狀態的時長(單位:分鐘)",
"publicIpRefresh": "公網 IP 重新整理",
"publicIpRefreshDesc": "面板透過外部服務重新偵測公網 IP 的間隔。0 表示僅偵測一次,不再重新整理。(單位:分鐘)",
"publicIpv6Detect": "偵測公網 IPv6",
"publicIpv6DetectDesc": "僅有 IPv4 的伺服器請關閉,以略過所有 IPv6 查詢。",
"publicIpv4Override": "手動指定公網 IPv4",
"publicIpv6Override": "手動指定公網 IPv6",
"publicIpOverrideDesc": "使用此位址而不進行偵測,不會為其發起任何外部查詢。留空則自動偵測。",
"expireTimeDiff": "到期通知閾值",
"expireTimeDiffDesc": "達到此閾值時,將收到有關到期時間的通知(單位:天)",
"trafficDiff": "流量耗盡閾值",