feat(sub): opt-in per-client rate limit for the subscription server (#6966)

A loop probing subscription ids, or one misbehaving app, could turn the subscription server into a database load generator, and there was nothing to cap it.

Add a setting, off by default, that limits how many subscription fetches one client address may make per minute (60 by default, 1 to 1000); requests over it get 429 with Retry-After. Static assets stay outside the guard. The client address comes from the same resolution the panel's login limiter uses, now shared in internal/util/clientip, so trustedProxyCIDRs decides it in one place for the panel and the subscription server.
This commit is contained in:
amirim
2026-11-24 20:21:32 +03:00
committed by GitHub
parent dd46ab8e8b
commit f9e15a6b9b
34 changed files with 803 additions and 131 deletions
@@ -23,6 +23,8 @@ panel's subscription settings:
| `subCertFile` / `subKeyFile` | _(none)_ | TLS cert + key — when set, the server serves **HTTPS**. |
| `subEncrypt` | `true` | Base64-encode the raw subscription body. |
| `subUpdates` | `12` | Suggested refresh interval (hours) sent to clients. |
| `subRateLimitEnable` | `false` | Limit how often one client address may fetch subscription URLs; over the limit the server answers `429` with `Retry-After`. |
| `subRateLimit` | `60` | Fetches allowed per client address and minute (1–1000) while the limit is on. Behind a reverse proxy, `trustedProxyCIDRs` decides which address counts as the client. |
A subscription URL looks like:
+20
View File
@@ -532,6 +532,14 @@
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -793,6 +801,8 @@
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
@@ -1357,6 +1367,14 @@
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -1626,6 +1644,8 @@
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
+20
View File
@@ -532,6 +532,14 @@
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -793,6 +801,8 @@
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
@@ -1357,6 +1367,14 @@
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -1626,6 +1644,8 @@
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
+4
View File
@@ -156,6 +156,8 @@ export const EXAMPLES: Record<string, unknown> = {
"subPort": 1,
"subProfileMode": "",
"subProfileUrl": "",
"subRateLimit": 1,
"subRateLimitEnable": false,
"subRoutingRules": "",
"subShowIdentityOnAllLinks": false,
"subSupportUrl": "",
@@ -352,6 +354,8 @@ export const EXAMPLES: Record<string, unknown> = {
"subPort": 1,
"subProfileMode": "",
"subProfileUrl": "",
"subRateLimit": 1,
"subRateLimitEnable": false,
"subRoutingRules": "",
"subShowIdentityOnAllLinks": false,
"subSupportUrl": "",
+20
View File
@@ -506,6 +506,14 @@ export const SCHEMAS: Record<string, unknown> = {
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -767,6 +775,8 @@ export const SCHEMAS: Record<string, unknown> = {
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
@@ -1331,6 +1341,14 @@ export const SCHEMAS: Record<string, unknown> = {
"subProfileUrl": {
"type": "string"
},
"subRateLimit": {
"maximum": 1000,
"minimum": 1,
"type": "integer"
},
"subRateLimitEnable": {
"type": "boolean"
},
"subRoutingRules": {
"type": "string"
},
@@ -1600,6 +1618,8 @@ export const SCHEMAS: Record<string, unknown> = {
"subPort",
"subProfileMode",
"subProfileUrl",
"subRateLimit",
"subRateLimitEnable",
"subRoutingRules",
"subShowIdentityOnAllLinks",
"subSupportUrl",
+4
View File
@@ -161,6 +161,8 @@ export interface AllSetting {
subPort: number;
subProfileMode: string;
subProfileUrl: string;
subRateLimit: number;
subRateLimitEnable: boolean;
subRoutingRules: string;
subShowIdentityOnAllLinks: boolean;
subSupportUrl: string;
@@ -358,6 +360,8 @@ export interface AllSettingView {
subPort: number;
subProfileMode: string;
subProfileUrl: string;
subRateLimit: number;
subRateLimitEnable: boolean;
subRoutingRules: string;
subShowIdentityOnAllLinks: boolean;
subSupportUrl: string;
+4
View File
@@ -171,6 +171,8 @@ export const AllSettingSchema = z.object({
subPort: z.number().int().min(1).max(65535),
subProfileMode: z.string(),
subProfileUrl: z.string(),
subRateLimit: z.number().int().min(1).max(1000),
subRateLimitEnable: z.boolean(),
subRoutingRules: z.string(),
subShowIdentityOnAllLinks: z.boolean(),
subSupportUrl: z.string(),
@@ -369,6 +371,8 @@ export const AllSettingViewSchema = z.object({
subPort: z.number().int().min(1).max(65535),
subProfileMode: z.string(),
subProfileUrl: z.string(),
subRateLimit: z.number().int().min(1).max(1000),
subRateLimitEnable: z.boolean(),
subRoutingRules: z.string(),
subShowIdentityOnAllLinks: z.boolean(),
subSupportUrl: z.string(),
+2
View File
@@ -75,6 +75,8 @@ export class AllSetting {
subKeyFile = '';
externalSubUserAgent = 'v2rayNG/1.8.5';
subUpdates = 12;
subRateLimitEnable = false;
subRateLimit = 60;
subEncrypt = true;
subURI = '';
subJsonURI = '';
@@ -273,6 +273,34 @@ export default function SubscriptionGeneralTab({
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subRateLimitEnable')}
description={t('pages.settings.subRateLimitEnableDesc')}
>
<Switch
checked={allSetting.subRateLimitEnable}
onChange={(v) => updateSetting({ subRateLimitEnable: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subRateLimit')}
badge={
<DefaultSettingTag settingKey="subRateLimit" value={allSetting.subRateLimit} />
}
description={t('pages.settings.subRateLimitDesc')}
>
<InputNumber
value={allSetting.subRateLimit}
min={1}
max={1000}
style={{ width: '100%' }}
onChange={onNumber((v) => updateSetting({ subRateLimit: v }))}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.externalSubUserAgent')}
+2
View File
@@ -88,6 +88,8 @@ export const AllSettingFieldsSchema = z
subKeyFile: z.string().optional(),
externalSubUserAgent: z.string().max(512).optional(),
subUpdates: z.number().int().min(0).max(525600).optional(),
subRateLimitEnable: z.boolean().optional(),
subRateLimit: z.number().int().min(1).max(1000).optional(),
subEncrypt: z.boolean().optional(),
subURI: z.string().optional(),
subJsonURI: z.string().optional(),
+20
View File
@@ -95,6 +95,9 @@ type SUBController struct {
subTemplateCache map[string]*cachedSubTemplate
releaseSettingsCache func()
rateLimiter *subRateLimiter
trustedProxyCIDRs string
}
type subControllerConfig struct {
@@ -137,10 +140,22 @@ type subControllerConfig struct {
subIncyEnableRouting bool
subIncyRoutingRules string
rateLimiter *subRateLimiter
trustedProxyCIDRs string
}
type SUBControllerOption func(*subControllerConfig)
// WithSUBRateLimit installs the per-client subscription rate limit guard.
// A nil limiter keeps the historical unlimited behavior.
func WithSUBRateLimit(limiter *subRateLimiter, trustedProxyCIDRs string) SUBControllerOption {
return func(c *subControllerConfig) {
c.rateLimiter = limiter
c.trustedProxyCIDRs = trustedProxyCIDRs
}
}
func WithSUBPath(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subPath = value }
}
@@ -341,6 +356,9 @@ func NewSUBController(g *gin.RouterGroup, options ...SUBControllerOption) *SUBCo
subTemplateCache: map[string]*cachedSubTemplate{},
releaseSettingsCache: releaseSettingsCache,
rateLimiter: config.rateLimiter,
trustedProxyCIDRs: config.trustedProxyCIDRs,
}
a.initRouter(g)
return a
@@ -349,6 +367,8 @@ func NewSUBController(g *gin.RouterGroup, options ...SUBControllerOption) *SUBCo
// initRouter registers HTTP routes for subscription links and JSON endpoints
// on the provided router group.
func (a *SUBController) initRouter(g *gin.RouterGroup) {
// Static assets mount on the engine outside this group: cheap, no DB reads, intentionally unguarded.
g.Use(subRateLimitGuard(a.rateLimiter, a.trustedProxyCIDRs))
gLink := g.Group(a.subPath, setNoCacheHeaders)
gLink.GET(":subid", a.subs)
gLink.HEAD(":subid", a.subs)
+3 -27
View File
@@ -1,14 +1,13 @@
package sub
import (
"net"
"net/netip"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/clientip"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
@@ -64,29 +63,6 @@ func warnSuppressedForwardedHeaders(c *gin.Context) {
}
func remoteAddrInCIDRs(remoteAddr, cidrs string) bool {
host := remoteAddr
if h, _, err := net.SplitHostPort(remoteAddr); err == nil {
host = h
}
addr, err := netip.ParseAddr(strings.TrimSpace(host))
if err != nil {
return false
}
addr = addr.Unmap()
for value := range strings.SplitSeq(cidrs, ",") {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if prefix, err := netip.ParsePrefix(value); err == nil {
if prefix.Contains(addr) {
return true
}
continue
}
if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr.Unmap() {
return true
}
}
return false
addr, ok := clientip.Parse(remoteAddr)
return ok && clientip.Trusted(addr, cidrs)
}
+154
View File
@@ -0,0 +1,154 @@
package sub
import (
"container/list"
"math"
"net/http"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/clientip"
)
const (
// subRateLimitDefaultPerMinute is the fallback per-client limit when the stored setting is unreadable or zero.
subRateLimitDefaultPerMinute = 60
// subRateLimitMaxPerMinute clamps the read path: a hand-edited DB row must not scale one bucket to unbounded memory.
subRateLimitMaxPerMinute = 1000
// subRateLimitWindow is the fixed window one subRateLimiter counts over.
subRateLimitWindow = time.Minute
// subRateLimitMaxKeys bounds tracked client buckets; each holds at most `limit` timestamps.
subRateLimitMaxKeys = 4096
// subRateLimitIdleTTL drops buckets for clients that stopped requesting.
subRateLimitIdleTTL = 20 * time.Minute
)
// subRateLimiter is a fixed-capacity sliding-window rate limiter keyed by client identity: a subId
// probe loop must not turn into a database load generator.
type subRateLimiter struct {
mu sync.Mutex
limit int
window time.Duration
capacity int
idleTTL time.Duration
now func() time.Time
buckets map[string]*subRateBucket
lru *list.List // front = least recently used key
}
type subRateBucket struct {
hits []time.Time
lastSeen time.Time
element *list.Element
}
func newSubRateLimiter(limit int, window time.Duration) *subRateLimiter {
if limit < 1 {
limit = 1
}
if window <= 0 {
window = subRateLimitWindow
}
return &subRateLimiter{
limit: limit,
window: window,
capacity: subRateLimitMaxKeys,
idleTTL: subRateLimitIdleTTL,
now: time.Now,
buckets: make(map[string]*subRateBucket),
lru: list.New(),
}
}
// allow records one request for key and reports whether it is under the window limit. When it is
// not, retryAfter is the time until the oldest hit in the window ages out.
func (l *subRateLimiter) allow(key string) (retryAfter time.Duration, ok bool) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
l.purgeIdleLocked(now)
b := l.buckets[key]
if b == nil {
if len(l.buckets) >= l.capacity {
l.evictOldestLocked()
}
b = &subRateBucket{}
b.element = l.lru.PushBack(key)
l.buckets[key] = b
} else {
l.lru.MoveToBack(b.element)
}
cutoff := now.Add(-l.window)
keep := 0
for keep < len(b.hits) && b.hits[keep].Before(cutoff) {
keep++
}
b.hits = b.hits[keep:]
b.lastSeen = now
if len(b.hits) >= l.limit {
return b.hits[0].Add(l.window).Sub(now), false
}
b.hits = append(b.hits, now)
return 0, true
}
// purgeIdleLocked drops buckets idle for longer than idleTTL; the LRU front is the least recently
// used, so the scan stops at the first fresh entry. Callers hold l.mu.
func (l *subRateLimiter) purgeIdleLocked(now time.Time) {
cutoff := now.Add(-l.idleTTL)
for l.lru.Len() > 0 {
front := l.lru.Front()
key := front.Value.(string)
if l.buckets[key].lastSeen.After(cutoff) {
return
}
l.removeLocked(front, key)
}
}
// evictOldestLocked drops one least-recently-used bucket to make room; it only runs at capacity,
// i.e. under a flood of distinct identities. Callers hold l.mu.
func (l *subRateLimiter) evictOldestLocked() {
front := l.lru.Front()
if front == nil {
return
}
l.removeLocked(front, front.Value.(string))
}
func (l *subRateLimiter) removeLocked(element *list.Element, key string) {
l.lru.Remove(element)
delete(l.buckets, key)
}
// subRateLimitGuard rejects over-limit requests with 429 + Retry-After, keyed on the panel login
// limiter's client identity. A nil limiter is a no-op for direct NewSUBController users.
func subRateLimitGuard(limiter *subRateLimiter, trustedProxyCIDRs string) gin.HandlerFunc {
return func(c *gin.Context) {
if limiter == nil {
c.Next()
return
}
ip := clientip.Resolve(c.Request.RemoteAddr, c.GetHeader("X-Real-IP"), c.GetHeader("X-Forwarded-For"), trustedProxyCIDRs)
if retryAfter, ok := limiter.allow(ip); !ok {
seconds := int(math.Ceil(retryAfter.Seconds()))
if seconds < 1 {
seconds = 1
}
c.Header("Retry-After", strconv.Itoa(seconds))
logger.Debugf("sub: rate limit hit for %s, retry after %ds", ip, seconds)
c.AbortWithStatus(http.StatusTooManyRequests)
return
}
c.Next()
}
}
+298
View File
@@ -0,0 +1,298 @@
package sub
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func baseTime() time.Time {
return time.Unix(1_000_000, 0)
}
func TestSubRateLimiterAllowsUnderLimit(t *testing.T) {
limiter := newSubRateLimiter(3, time.Minute)
now := baseTime()
limiter.now = func() time.Time { return now }
for i := 0; i < 3; i++ {
if _, ok := limiter.allow("1.2.3.4"); !ok {
t.Fatalf("request %d under the limit was rejected", i+1)
}
}
retryAfter, ok := limiter.allow("1.2.3.4")
if ok {
t.Fatal("request over the limit was allowed")
}
if want := time.Minute; retryAfter > want || retryAfter <= want-time.Second {
t.Fatalf("retryAfter = %v, want ~%v", retryAfter, want)
}
// A different client gets its own bucket.
if _, ok := limiter.allow("5.6.7.8"); !ok {
t.Fatal("another client was rejected for the first client's usage")
}
}
func TestSubRateLimiterWindowSlides(t *testing.T) {
limiter := newSubRateLimiter(2, time.Minute)
now := baseTime()
limiter.now = func() time.Time { return now }
limiter.allow("c")
limiter.allow("c")
if _, ok := limiter.allow("c"); ok {
t.Fatal("third request in the window was allowed")
}
// Half the window later the two hits are still counted.
now = now.Add(30 * time.Second)
if _, ok := limiter.allow("c"); ok {
t.Fatal("request was allowed while the window is still full")
}
// One window after the first hit it ages out and a slot frees up.
now = now.Add(31 * time.Second)
if _, ok := limiter.allow("c"); !ok {
t.Fatal("request was rejected after the window slid past the old hits")
}
}
func TestSubRateLimiterRetryAfterPointsAtOldestHit(t *testing.T) {
limiter := newSubRateLimiter(1, time.Minute)
now := baseTime()
limiter.now = func() time.Time { return now }
limiter.allow("c")
now = now.Add(20 * time.Second)
retryAfter, ok := limiter.allow("c")
if ok {
t.Fatal("second request was allowed")
}
if want := 40 * time.Second; retryAfter != want {
t.Fatalf("retryAfter = %v, want %v (oldest hit + window - now)", retryAfter, want)
}
}
func TestSubRateLimiterEvictsIdleAndCapacity(t *testing.T) {
limiter := newSubRateLimiter(2, time.Minute)
limiter.capacity = 2
now := baseTime()
limiter.now = func() time.Time { return now }
limiter.allow("a")
limiter.allow("b")
// A third key at capacity evicts the least recently used ("a").
limiter.allow("c")
if len(limiter.buckets) != 2 {
t.Fatalf("buckets = %d, want 2", len(limiter.buckets))
}
if _, contains := limiter.buckets["a"]; contains {
t.Fatal("least recently used bucket was kept at capacity")
}
// Touching "b" makes "c" the LRU front; the next insert evicts "c".
limiter.allow("b")
limiter.allow("d")
if _, contains := limiter.buckets["c"]; contains {
t.Fatal("eviction did not follow the LRU order")
}
if _, contains := limiter.buckets["b"]; !contains {
t.Fatal("recently used bucket was evicted")
}
// Idle buckets age out on the next request after the TTL.
now = now.Add(subRateLimitIdleTTL + time.Minute)
limiter.allow("e")
if _, contains := limiter.buckets["b"]; contains {
t.Fatal("idle bucket survived the idle TTL")
}
}
func TestSubRateLimiterConcurrentKeys(t *testing.T) {
limiter := newSubRateLimiter(50, time.Minute)
const clients = 8
const perClient = 100
var mu sync.Mutex
allowed := make(map[string]int, clients)
var wg sync.WaitGroup
for i := 0; i < clients; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key := fmt.Sprintf("10.0.0.%d", i)
for j := 0; j < perClient; j++ {
if _, ok := limiter.allow(key); ok {
mu.Lock()
allowed[key]++
mu.Unlock()
}
}
}(i)
}
wg.Wait()
for key, count := range allowed {
if count > 50 {
t.Fatalf("%s got %d allowed requests, limit is 50", key, count)
}
}
if len(allowed) == 0 {
t.Fatal("no requests were allowed at all")
}
}
func TestSubRateLimitGuard(t *testing.T) {
gin.SetMode(gin.TestMode)
limiter := newSubRateLimiter(2, time.Minute)
now := baseTime()
limiter.now = func() time.Time { return now }
router := gin.New()
router.GET("/sub/:id", subRateLimitGuard(limiter, service.DefaultTrustedProxyCIDRs), func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})
for i := 0; i < 2; i++ {
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sub/abc", nil))
if w.Code != http.StatusOK {
t.Fatalf("request %d: code = %d, want 200", i+1, w.Code)
}
}
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sub/abc", nil))
if w.Code != http.StatusTooManyRequests {
t.Fatalf("third request: code = %d, want 429", w.Code)
}
// limit=1, first hit at t=0, reject at t=0: the window frees in exactly 60s.
if got := w.Header().Get("Retry-After"); got != "60" {
t.Fatalf("Retry-After = %q, want \"60\"", got)
}
// A nil limiter keeps the historical behavior: everything passes.
openRouter := gin.New()
openRouter.GET("/sub/:id", subRateLimitGuard(nil, ""), func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})
for i := 0; i < 5; i++ {
w := httptest.NewRecorder()
openRouter.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sub/abc", nil))
if w.Code != http.StatusOK {
t.Fatalf("nil limiter request %d: code = %d, want 200", i+1, w.Code)
}
}
}
// One bucket per real client: a trusted proxy's clients stay apart, and an untrusted
// peer cannot leave its bucket by rotating X-Forwarded-For.
func TestSubRateLimitGuardKeysOnTheResolvedClient(t *testing.T) {
gin.SetMode(gin.TestMode)
limiter := newSubRateLimiter(1, time.Minute)
limiter.now = baseTime
router := gin.New()
router.GET("/sub/:id", subRateLimitGuard(limiter, "127.0.0.1/32"), func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})
steps := []struct {
name, remoteAddr, forwardedFor string
want int
}{
{"untrusted peer, first request", "203.0.113.7:4434", "1.1.1.1", http.StatusOK},
{"untrusted peer rotates the header", "203.0.113.7:4434", "2.2.2.2", http.StatusTooManyRequests},
{"proxied client A", "127.0.0.1:5555", "198.51.100.1", http.StatusOK},
{"proxied client B", "127.0.0.1:5555", "198.51.100.2", http.StatusOK},
{"proxied client A again", "127.0.0.1:5555", "198.51.100.1", http.StatusTooManyRequests},
}
for _, step := range steps {
req := httptest.NewRequest(http.MethodGet, "/sub/abc", nil)
req.RemoteAddr = step.remoteAddr
req.Header.Set("X-Forwarded-For", step.forwardedFor)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != step.want {
t.Fatalf("%s: code = %d, want %d", step.name, w.Code, step.want)
}
}
}
// initRouter's group-level Use must 429 every subscription format route when limited; unlimited,
// handlers answer 404 themselves — the exact code proves the guard did not interfere.
func TestSUBControllerRateLimitCoversAllRoutes(t *testing.T) {
gin.SetMode(gin.TestMode)
tmp := t.TempDir()
t.Chdir(tmp)
if err := os.MkdirAll("internal/web/dist", 0o755); err != nil {
t.Fatalf("mkdir dist: %v", err)
}
if err := os.WriteFile("internal/web/dist/subpage.html", []byte("<html><head></head><body></body></html>"), 0o644); err != nil {
t.Fatalf("write subpage: %v", err)
}
t.Setenv("XUI_DB_FOLDER", tmp)
dbtest.InitDB(t, filepath.Join(tmp, "x-ui.db"))
limited := func(withLimit bool) *gin.Engine {
router := gin.New()
options := []SUBControllerOption{
WithSUBPath("/sub/"),
WithSUBJsonPath("/json/"),
WithSUBJsonEnabled(true),
WithSUBClashPath("/clash/"),
WithSUBClashEnabled(true),
}
if withLimit {
limiter := newSubRateLimiter(1, time.Minute)
limiter.now = func() time.Time { return baseTime() }
options = append(options, WithSUBRateLimit(limiter, service.DefaultTrustedProxyCIDRs))
}
NewSUBController(router.Group("/"), options...)
return router
}
paths := []string{"/sub/abc", "/sub/abc/hwid-status", "/json/abc", "/clash/abc", "/clash-legacy/abc", "/mihomo/abc"}
// With limit=1 the priming request consumes the slot (handler → 404); every later route rejects.
router := limited(true)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sub/prime", nil))
if w.Code != http.StatusNotFound {
t.Fatalf("priming request: code = %d, want 404 from the handler (limiter must allow it)", w.Code)
}
for _, path := range paths {
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
if w.Code != http.StatusTooManyRequests {
t.Fatalf("limited %s: code = %d, want 429", path, w.Code)
}
if w.Header().Get("Retry-After") == "" {
t.Fatalf("limited %s: 429 without Retry-After", path)
}
}
// Unlimited controller: the guard is a no-op, handlers answer 404 for the
// unknown subId — never 429, never 5xx.
open := limited(false)
for _, path := range paths {
w := httptest.NewRecorder()
open.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
if w.Code != http.StatusNotFound {
t.Fatalf("unlimited %s: code = %d, want 404 from the handler", path, w.Code)
}
}
}
+20
View File
@@ -140,6 +140,25 @@ func (s *Server) initRouter() (*gin.Engine, error) {
SubUpdates = "10"
}
// Off by default; an unreadable limit falls back to the default instead of failing the start.
subRateLimitEnable, err := s.settingService.GetSubRateLimitEnable()
if err != nil {
return nil, err
}
var subRateLimiterInst *subRateLimiter
subRateTrustedCIDRs := service.DefaultTrustedProxyCIDRs
if subRateLimitEnable {
subRateLimit, err := s.settingService.GetSubRateLimit()
if err != nil || subRateLimit < 1 {
subRateLimit = subRateLimitDefaultPerMinute
}
subRateLimit = min(subRateLimit, subRateLimitMaxPerMinute)
subRateLimiterInst = newSubRateLimiter(subRateLimit, subRateLimitWindow)
if value, err := s.settingService.GetTrustedProxyCIDRs(); err == nil && strings.TrimSpace(value) != "" {
subRateTrustedCIDRs = value
}
}
SubJsonMux, err := s.settingService.GetSubJsonMux()
if err != nil {
SubJsonMux = ""
@@ -379,6 +398,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
WithSUBIncyConfig(incyCfg),
WithSUBIncyEnableRouting(SubIncyEnableRouting),
WithSUBIncyRoutingRules(SubIncyRoutingRules),
WithSUBRateLimit(subRateLimiterInst, subRateTrustedCIDRs),
)
return engine, nil
+99
View File
@@ -0,0 +1,99 @@
// Package clientip resolves the address a request came from behind trusted reverse proxies.
package clientip
import (
"net"
"net/netip"
"strings"
)
// Resolve returns the address rate limiters key on: forwarded headers count only
// when remoteAddr is inside trustedCIDRs, and never when they contradict each other.
func Resolve(remoteAddr, xRealIP, xForwardedFor, trustedCIDRs string) string {
remoteIP, ok := Parse(remoteAddr)
if !ok {
return "unknown"
}
if !Trusted(remoteIP, trustedCIDRs) {
return remoteIP.String()
}
realIP, hasRealIP := Parse(xRealIP)
forwardedIP, hasForwarded := forwardedClient(xForwardedFor, trustedCIDRs)
switch {
case hasRealIP && hasForwarded && realIP != forwardedIP:
// A proxy rewrites at most one of the two, so the other is the client's
// own claim; neither may pick the identity a limiter keys on.
return remoteIP.String()
case hasForwarded:
return forwardedIP.String()
case hasRealIP:
return realIP.String()
}
return remoteIP.String()
}
// forwardedClient walks X-Forwarded-For from the proxy end: entries a client sent
// come first, so the first hop that is not a trusted proxy is the address one saw.
func forwardedClient(xForwardedFor, trustedCIDRs string) (netip.Addr, bool) {
parts := strings.Split(xForwardedFor, ",")
var client netip.Addr
found := false
for i := len(parts) - 1; i >= 0; i-- {
ip, ok := Parse(parts[i])
if !ok {
break
}
client, found = ip, true
if !Trusted(ip, trustedCIDRs) {
break
}
}
return client, found
}
// Trusted reports whether addr is inside the comma-separated CIDR or address list;
// an entry that parses as neither is skipped.
func Trusted(addr netip.Addr, trustedCIDRs string) bool {
addr = addr.Unmap()
for value := range strings.SplitSeq(trustedCIDRs, ",") {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if prefix, err := netip.ParsePrefix(value); err == nil {
if prefix.Contains(addr) {
return true
}
continue
}
if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr {
return true
}
}
return false
}
// Parse reads an address from a header value or a RemoteAddr, with or without a port.
func Parse(value string) (netip.Addr, bool) {
candidate := strings.TrimSpace(value)
if candidate == "" {
return netip.Addr{}, false
}
if ip, err := netip.ParseAddr(candidate); err == nil {
return ip.Unmap(), true
}
if host, _, err := net.SplitHostPort(candidate); err == nil {
if ip, err := netip.ParseAddr(strings.TrimSpace(host)); err == nil {
return ip.Unmap(), true
}
}
if strings.Count(candidate, ":") == 1 {
if host, _, err := net.SplitHostPort("[" + candidate + "]"); err == nil {
if ip, err := netip.ParseAddr(strings.TrimSpace(host)); err == nil {
return ip.Unmap(), true
}
}
}
return netip.Addr{}, false
}
+30
View File
@@ -0,0 +1,30 @@
package clientip
import "testing"
func TestResolve(t *testing.T) {
tests := []struct {
name string
remoteAddr, xRealIP, xff string
trusted string
want string
}{
{name: "untrusted peer cannot set headers", remoteAddr: "203.0.113.7:4434", xRealIP: "8.8.8.8", xff: "9.9.9.9", trusted: "127.0.0.1/32", want: "203.0.113.7"},
{name: "first untrusted hop behind two proxies", remoteAddr: "127.0.0.1:5555", xff: "203.0.113.9, 10.1.1.1", trusted: "127.0.0.1/32,10.0.0.0/8", want: "203.0.113.9"},
{name: "client-sent leftmost entry is ignored", remoteAddr: "127.0.0.1:5555", xff: "6.6.6.6, 203.0.113.9, 10.1.1.1", trusted: "127.0.0.1/32,10.0.0.0/8", want: "203.0.113.9"},
{name: "real IP agreeing with the chain", remoteAddr: "127.0.0.1:5555", xRealIP: "198.51.100.4", xff: "198.51.100.4", trusted: "127.0.0.1/32", want: "198.51.100.4"},
{name: "real IP contradicting the chain falls back to the proxy", remoteAddr: "127.0.0.1:5555", xRealIP: "6.6.6.6", xff: "198.51.100.4", trusted: "127.0.0.1/32", want: "127.0.0.1"},
{name: "real IP alone from a trusted proxy", remoteAddr: "127.0.0.1:5555", xRealIP: "198.51.100.4", trusted: "127.0.0.1/32", want: "198.51.100.4"},
{name: "malformed headers fall back to the proxy", remoteAddr: "127.0.0.1:5555", xRealIP: "also-garbage", xff: "garbage", trusted: "127.0.0.1/32", want: "127.0.0.1"},
{name: "bare address in the trusted list", remoteAddr: "[::1]:5555", xff: "198.51.100.4", trusted: "127.0.0.1/32, ::1", want: "198.51.100.4"},
{name: "unparseable trusted entry is skipped", remoteAddr: "10.2.3.4:5555", xff: "198.51.100.4", trusted: "not-an-ip,10.0.0.0/8", want: "198.51.100.4"},
{name: "unparseable peer has no identity", remoteAddr: "not-an-address", trusted: "127.0.0.1/32", want: "unknown"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Resolve(tt.remoteAddr, tt.xRealIP, tt.xff, tt.trusted); got != tt.want {
t.Fatalf("Resolve(%q, %q, %q, %q) = %q, want %q", tt.remoteAddr, tt.xRealIP, tt.xff, tt.trusted, got, tt.want)
}
})
}
}
+5 -104
View File
@@ -2,91 +2,27 @@ package controller
import (
"fmt"
"net"
"net/http"
"net/netip"
"path/filepath"
"runtime"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/clientip"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/gin-gonic/gin"
)
// getRemoteIp extracts the real IP address from the request headers or remote address.
// getRemoteIp is the request's client address, the identity the login limiter keys on.
func getRemoteIp(c *gin.Context) string {
remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
if !ok {
return "unknown"
}
if !isTrustedProxy(remoteIP) {
return remoteIP
}
realIP, hasRealIP := extractTrustedIP(c.GetHeader("X-Real-IP"))
forwardedIP, hasForwarded := forwardedForClient(c.GetHeader("X-Forwarded-For"))
switch {
case hasRealIP && hasForwarded && realIP != forwardedIP:
// A proxy rewrites at most one of the two, so the other is the client's
// own claim; neither may pick the identity the login limiter keys on.
return remoteIP
case hasForwarded:
return forwardedIP
case hasRealIP:
return realIP
}
return remoteIP
}
// forwardedForClient walks X-Forwarded-For from the proxy end: entries a client sent
// come first, so the first hop that is not a trusted proxy is the address one saw.
func forwardedForClient(xff string) (string, bool) {
parts := strings.Split(xff, ",")
client := ""
for i := len(parts) - 1; i >= 0; i-- {
ip, ok := extractTrustedIP(parts[i])
if !ok {
break
}
client = ip
if !isTrustedProxy(ip) {
break
}
}
return client, client != ""
return clientip.Resolve(c.Request.RemoteAddr, c.GetHeader("X-Real-IP"), c.GetHeader("X-Forwarded-For"), trustedProxyCIDRs())
}
func isTrustedForwardedRequest(c *gin.Context) bool {
remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
return ok && isTrustedProxy(remoteIP)
}
func isTrustedProxy(ip string) bool {
addr, err := netip.ParseAddr(ip)
if err != nil {
return false
}
trusted := trustedProxyCIDRs()
for value := range strings.SplitSeq(trusted, ",") {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if prefix, err := netip.ParsePrefix(value); err == nil {
if prefix.Contains(addr) {
return true
}
continue
}
if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr.Unmap() {
return true
}
}
return false
remoteIP, ok := clientip.Parse(c.Request.RemoteAddr)
return ok && clientip.Trusted(remoteIP, trustedProxyCIDRs())
}
func trustedProxyCIDRs() (trusted string) {
@@ -101,41 +37,6 @@ func trustedProxyCIDRs() (trusted string) {
return trusted
}
func extractTrustedIP(value string) (string, bool) {
candidate := strings.TrimSpace(value)
if candidate == "" {
return "", false
}
if ip, ok := parseIPCandidate(candidate); ok {
return ip.String(), true
}
if host, _, err := net.SplitHostPort(candidate); err == nil {
if ip, ok := parseIPCandidate(host); ok {
return ip.String(), true
}
}
if strings.Count(candidate, ":") == 1 {
if host, _, err := net.SplitHostPort(fmt.Sprintf("[%s]", candidate)); err == nil {
if ip, ok := parseIPCandidate(host); ok {
return ip.String(), true
}
}
}
return "", false
}
func parseIPCandidate(value string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(strings.TrimSpace(value))
if err != nil {
return netip.Addr{}, false
}
return ip.Unmap(), true
}
// jsonMsg sends a JSON response with a message and error status.
func jsonMsg(c *gin.Context, msg string, err error) {
jsonMsgObj(c, msg, nil, err)
+2
View File
@@ -120,6 +120,8 @@ type AllSetting struct {
SubKeyFile string `json:"subKeyFile" form:"subKeyFile"`
ExternalSubUserAgent string `json:"externalSubUserAgent" form:"externalSubUserAgent"`
SubUpdates int `json:"subUpdates" form:"subUpdates" validate:"gte=0,lte=525600"`
SubRateLimitEnable bool `json:"subRateLimitEnable" form:"subRateLimitEnable"`
SubRateLimit int `json:"subRateLimit" form:"subRateLimit" validate:"gte=1,lte=1000"`
ExternalTrafficInformEnable bool `json:"externalTrafficInformEnable" form:"externalTrafficInformEnable"`
ExternalTrafficInformURI string `json:"externalTrafficInformURI" form:"externalTrafficInformURI"`
RestartXrayOnClientDisable bool `json:"restartXrayOnClientDisable" form:"restartXrayOnClientDisable"`
+10
View File
@@ -184,6 +184,8 @@ var defaultValueMap = map[string]string{
"subKeyFile": "",
"externalSubUserAgent": DefaultExternalSubUserAgent,
"subUpdates": "12",
"subRateLimitEnable": "false",
"subRateLimit": "60",
"subEncrypt": "true",
"subURI": "",
"subJsonPath": "/json/",
@@ -1233,6 +1235,14 @@ func (s *SettingService) GetSubUpdates() (string, error) {
return s.getString("subUpdates")
}
func (s *SettingService) GetSubRateLimitEnable() (bool, error) {
return s.getBool("subRateLimitEnable")
}
func (s *SettingService) GetSubRateLimit() (int, error) {
return s.getInt("subRateLimit")
}
func (s *SettingService) GetExternalSubUserAgent() (string, error) {
value, err := s.getString("externalSubUserAgent")
if err != nil {
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "اسم الدومين لخدمة الاشتراك. (سيبه فاضي عشان يستمع على كل الدومينات والـ IPs). كمان بيتستخدم كدومين افتراضي لرابط الاشتراك اللي بيظهر لو حقل «مسار البروكسي العكسي» فاضي — املا «مسار البروكسي العكسي» لو اللوحة والاشتراك بيتفتحوا من دومينات مختلفة (زي لما يكونوا ورا بروكسي عكسي).",
"subUpdates": "فترات التحديث",
"subUpdatesDesc": "فترات تحديث رابط الاشتراك في تطبيقات العملاء. (الوحدة: ساعة)",
"subRateLimitEnable": "تحديد معدل الاشتراكات",
"subRateLimitEnableDesc": "يحدد عدد مرات جلب عناوين الاشتراك لكل عنوان IP للعميل. الطلبات التي تتجاوز الحد تحصل على HTTP 429 مع تلميح Retry-After. نطاقات CIDR للبروكسي الموثوقة (الإعدادات العامة) تحدد العنوان الذي يُحتسب به العميل.",
"subRateLimit": "طلبات في الدقيقة",
"subRateLimitDesc": "الحد الأقصى لعدد عمليات جلب الاشتراك لكل عنوان IP للعميل في الدقيقة أثناء تشغيل التحديد.",
"externalSubUserAgent": "User-Agent للاشتراك الخارجي",
"externalSubUserAgentDesc": "ترويسة User-Agent عند جلب رابط الاشتراك الخارجي للعميل. اتركه فارغًا لاستخدام الافتراضي (v2rayNG/1.8.5). بعض المزودين يرفضون العملاء غير المعروفين.",
"subEncrypt": "تشفير",
+4
View File
@@ -1540,6 +1540,10 @@
"subDomainDesc": "The domain name for the subscription service. (leave blank to listen on all domains and IPs). Also used as the fallback domain for the displayed subscription link when \"Reverse Proxy URI\" is empty — set \"Reverse Proxy URI\" if the panel and the subscription are reached through different domains (e.g. behind a reverse proxy).",
"subUpdates": "Update Intervals",
"subUpdatesDesc": "The update intervals of the subscription URL in the client apps. (unit: hour)",
"subRateLimitEnable": "Subscription rate limit",
"subRateLimitEnableDesc": "Limit how often each client IP may fetch subscription URLs. Requests over the limit get HTTP 429 with a Retry-After hint. Trusted proxy CIDRs (General settings) decide which address a client is counted by.",
"subRateLimit": "Requests per minute",
"subRateLimitDesc": "The maximum number of subscription fetches per client IP and minute while the rate limit is on.",
"externalSubUserAgent": "External subscription User-Agent",
"externalSubUserAgentDesc": "User-Agent header sent when the panel fetches a client external subscription URL. Leave blank to use the default (v2rayNG/1.8.5). Some providers reject unknown clients.",
"subEncrypt": "Encode",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Dejar en blanco por defecto para monitorear todos los dominios e IPs. También se usa como dominio de reserva para el enlace de suscripción mostrado cuando «URI de proxy inverso» está vacío — configure «URI de proxy inverso» si el panel y la suscripción se acceden por dominios diferentes (por ejemplo, detrás de un proxy inverso).",
"subUpdates": "Intervalos de Actualización de Suscripción",
"subUpdatesDesc": "Horas de intervalo entre actualizaciones en la aplicación del cliente.",
"subRateLimitEnable": "Límite de frecuencia de suscripciones",
"subRateLimitEnableDesc": "Limita la frecuencia con la que cada IP de cliente puede obtener las URL de suscripción. Las solicitudes que superan el límite reciben HTTP 429 con una pista Retry-After. Los CIDR de proxy confiables (ajustes generales) deciden por qué dirección se cuenta a un cliente.",
"subRateLimit": "Solicitudes por minuto",
"subRateLimitDesc": "El número máximo de descargas de suscripción por IP de cliente y minuto mientras el límite está activo.",
"externalSubUserAgent": "User-Agent de suscripción externa",
"externalSubUserAgentDesc": "Cabecera User-Agent al obtener la URL de suscripción externa del cliente. Déjelo vacío para usar el valor predeterminado (v2rayNG/1.8.5). Algunos proveedores rechazan clientes desconocidos.",
"subEncrypt": "Codificar",
+4
View File
@@ -1419,6 +1419,10 @@
"subDomainDesc": "آدرس دامنه برای سرویس سابسکریپشن. برای گوش دادن به تمام دامنه‌ها و آی‌پی‌ها خالی‌بگذارید. همچنین وقتی «مسیر پراکسی معکوس» خالی باشد، به عنوان دامنه پیش‌فرض لینک سابسکریپشن نمایش‌داده‌شده استفاده می‌شود — اگر پنل و سابسکریپشن از دامنه‌های متفاوتی در دسترس هستند (مثلاً پشت یک پراکسی معکوس)، «مسیر پراکسی معکوس» را پر کنید.",
"subUpdates": "فاصله بروزرسانی‌ سابسکریپشن",
"subUpdatesDesc": "(فاصله مابین بروزرسانی در برنامه‌های کاربری. (واحد: ساعت",
"subRateLimitEnable": "محدودیت نرخ اشتراک",
"subRateLimitEnableDesc": "محدود می‌کند که هر IP کلاینت چه اندازه می‌تواند URLهای اشتراک را دریافت کند. درخواست‌های بیش از حد، HTTP 429 همراه با Retry-After می‌گیرند. CIDRهای پروکسی معتمد (تنظیمات عمومی) تعیین می‌کنند کلاینت با چه آدرسی شمرده شود.",
"subRateLimit": "درخواست در دقیقه",
"subRateLimitDesc": "حداکثر تعداد دریافت اشتراک به‌ازای هر IP کلاینت در دقیقه وقتی محدودیت فعال است.",
"externalSubUserAgent": "User-Agent اشتراک خارجی",
"externalSubUserAgentDesc": "هدر User-Agent هنگام واکشی URL اشتراک خارجی کلاینت. خالی بگذارید تا پیش‌فرض (v2rayNG/1.8.5) استفاده شود. بعضی ارائه‌دهنده‌ها کلاینت ناشناس را رد می‌کنند.",
"subEncrypt": "انکود",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Nama domain untuk layanan langganan. (biarkan kosong untuk mendengarkan semua domain dan IP). Juga digunakan sebagai domain cadangan untuk tautan langganan yang ditampilkan ketika \"URI Proxy Terbalik\" kosong — atur \"URI Proxy Terbalik\" jika panel dan langganan diakses melalui domain yang berbeda (misalnya di belakang reverse proxy).",
"subUpdates": "Interval Pembaruan",
"subUpdatesDesc": "Interval pembaruan URL langganan dalam aplikasi klien. (unit: jam)",
"subRateLimitEnable": "Batas laju langganan",
"subRateLimitEnableDesc": "Membatasi seberapa sering setiap IP klien dapat mengambil URL langganan. Permintaan di atas batas mendapat HTTP 429 dengan petunjuk Retry-After. CIDR proxy tepercaya (pengaturan umum) menentukan alamat yang dipakai menghitung klien.",
"subRateLimit": "Permintaan per menit",
"subRateLimitDesc": "Jumlah maksimum pengambilan langganan per IP klien per menit selama batas laju aktif.",
"externalSubUserAgent": "User-Agent langganan eksternal",
"externalSubUserAgentDesc": "Header User-Agent saat panel mengambil URL langganan eksternal klien. Kosongkan untuk memakai bawaan (v2rayNG/1.8.5). Beberapa penyedia menolak klien yang tidak dikenal.",
"subEncrypt": "Encode",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "サブスクリプションサービスが監視するドメイン(空白にするとすべてのドメインとIPを監視)。「リバースプロキシURI」が空の場合、表示されるサブスクリプションリンクのフォールバックドメインとしても使われます — パネルとサブスクリプションが異なるドメイン(例: リバースプロキシの背後)でアクセスされる場合は「リバースプロキシURI」を設定してください。",
"subUpdates": "更新間隔",
"subUpdatesDesc": "クライアントアプリケーションでサブスクリプションURLの更新間隔(単位:時間)",
"subRateLimitEnable": "サブスクリプションのレート制限",
"subRateLimitEnableDesc": "クライアント IP ごとにサブスクリプション URL を取得できる頻度を制限します。制限を超えたリクエストには Retry-After ヒント付きの HTTP 429 を返します。信頼されたプロキシ CIDR(一般設定)がクライアントをどのアドレスで数えるかを決めます。",
"subRateLimit": "1 分あたりのリクエスト数",
"subRateLimitDesc": "レート制限が有効な間、クライアント IP ごとに 1 分あたりに許可されるサブスクリプション取得の最大数。",
"externalSubUserAgent": "外部サブスクリプションの User-Agent",
"externalSubUserAgentDesc": "クライアントの外部サブスクリプション URL を取得するときに送る User-Agent。空欄の場合はデフォルト(v2rayNG/1.8.5)を使用します。一部のプロバイダーは未知のクライアントを拒否します。",
"subEncrypt": "エンコード",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "O nome de domínio para o serviço de assinatura. (deixe em branco para escutar em todos os domínios e IPs). Também é usado como domínio de fallback para o link de assinatura exibido quando \"URI de Proxy Reverso\" estiver vazio — configure \"URI de Proxy Reverso\" se o painel e a assinatura forem acessados por domínios diferentes (por exemplo, atrás de um proxy reverso).",
"subUpdates": "Intervalos de Atualização",
"subUpdatesDesc": "Os intervalos de atualização da URL de assinatura nos aplicativos de cliente. (unidade: hora)",
"subRateLimitEnable": "Limite de taxa de assinaturas",
"subRateLimitEnableDesc": "Limita a frequência com que cada IP de cliente pode buscar URLs de assinatura. Solicitações acima do limite recebem HTTP 429 com uma dica Retry-After. Os CIDRs de proxy confiáveis (configurações gerais) definem por qual endereço um cliente é contado.",
"subRateLimit": "Solicitações por minuto",
"subRateLimitDesc": "O número máximo de buscas de assinatura por IP de cliente e minuto enquanto o limite estiver ativo.",
"externalSubUserAgent": "User-Agent de assinatura externa",
"externalSubUserAgentDesc": "Cabeçalho User-Agent ao buscar a URL de assinatura externa do cliente. Deixe em branco para usar o padrão (v2rayNG/1.8.5). Alguns provedores rejeitam clientes desconhecidos.",
"subEncrypt": "Codificar",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Оставьте пустым по умолчанию, чтобы слушать все домены и IP-адреса. Также используется как домен по умолчанию для отображаемой ссылки подписки, если поле «URI обратного прокси» пустое — заполните «URI обратного прокси», если панель и подписка доступны на разных доменах (например, за reverse-proxy).",
"subUpdates": "Интервалы обновления подписки",
"subUpdatesDesc": "Интервал между обновлениями в клиентском приложении (в часах)",
"subRateLimitEnable": "Ограничение частоты подписок",
"subRateLimitEnableDesc": "Ограничивает, как часто каждый IP-адрес клиента может запрашивать URL-адреса подписки. Запросы сверх лимита получают HTTP 429 с подсказкой Retry-After. Доверенные CIDR прокси (общие настройки) определяют, по какому адресу учитывается клиент.",
"subRateLimit": "Запросов в минуту",
"subRateLimitDesc": "Максимальное количество запросов подписки на одну IP-адрес клиента в минуту, когда ограничение включено.",
"externalSubUserAgent": "User-Agent внешней подписки",
"externalSubUserAgentDesc": "Заголовок User-Agent при загрузке внешней подписки клиента. Оставьте пустым для значения по умолчанию (v2rayNG/1.8.5). Некоторые провайдеры отклоняют неизвестных клиентов.",
"subEncrypt": "Кодировать",
+4
View File
@@ -1540,6 +1540,10 @@
"subDomainDesc": "Doména služby odberu. Prázdne pole umožní všetky domény a IP adresy. Ak je pole „URI reverzného proxy“ prázdne, použije sa aj ako náhradná doména zobrazeného odkazu na odber. Ak sú panel a odber dostupné cez odlišné domény, napr. za reverzným proxy, nastavte „URI reverzného proxy“.",
"subUpdates": "Interval aktualizácií",
"subUpdatesDesc": "Interval aktualizácie odberu v klientskych aplikáciách (jednotka: hodina).",
"subRateLimitEnable": "Rýchlostný limit predplatných",
"subRateLimitEnableDesc": "Obmedzuje, ako často môže každá IP adresa klienta sťahovať URL adresy predplatných. Požiadavky nad limit dostanú HTTP 429 s hintom Retry-After. Dôveryhodné proxy CIDR (všeobecné nastavenia) určujú, podľa ktorej adresy sa klient počíta.",
"subRateLimit": "Požiadaviek za minútu",
"subRateLimitDesc": "Maximálny počet stiahnutí predplatného na IP adresu klienta a minútu, kým je rýchlostný limit zapnutý.",
"externalSubUserAgent": "User-Agent externého odberu",
"externalSubUserAgentDesc": "Hlavička User-Agent odosielaná pri načítaní externého odberu klienta. Prázdne pole použije predvolenú hodnotu v2rayNG/1.8.5. Niektorí poskytovatelia neznámych klientov odmietajú.",
"subEncrypt": "Kódovanie",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Abonelik hizmeti için alan adı. (tüm alan adlarını ve IP'leri dinlemek için boş bırakın). Ayrıca, \"Ters Proxy URI\" boşsa gösterilen abonelik bağlantısı için yedek alan adı olarak da kullanılır — panel ve abonelik farklı alan adları üzerinden erişiliyorsa (örneğin bir ters proxy arkasında) \"Ters Proxy URI\"yi ayarlayın.",
"subUpdates": "Güncelleme Aralıkları",
"subUpdatesDesc": "İstemci uygulamalarındaki abonelik URL'sinin güncellenme aralığı. (birim: saat)",
"subRateLimitEnable": "Abonelik hız sınırı",
"subRateLimitEnableDesc": "Her istemci IP'sinin abonelik URL'lerini ne sıklıkla çekebileceğini sınırlar. Limiti aşan istekler Retry-After ipucuyla HTTP 429 alır. Güvenilir proxy CIDR'leri (genel ayarlar) bir istemcinin hangi adresle sayılacağını belirler.",
"subRateLimit": "Dakika başına istek",
"subRateLimitDesc": "Hız sınırı açıkken istemci IP başına dakikada izin verilen maksimum abonelik çekme sayısı.",
"externalSubUserAgent": "Harici abonelik User-Agent",
"externalSubUserAgentDesc": "Panel istemci harici abonelik URL’sini çekerken gönderilen User-Agent. Boş bırakılırsa varsayılan (v2rayNG/1.8.5) kullanılır. Bazı sağlayıcılar bilinmeyen istemcileri reddeder.",
"subEncrypt": "Kodla",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Ім'я домену для служби підписки. (залиште порожнім, щоб слухати всі домени та IP-адреси). Також використовується як резервний домен для показаного посилання підписки, коли «URI зворотного проксі» порожнє — вкажіть «URI зворотного проксі», якщо панель і підписка доступні через різні домени (наприклад, за зворотним проксі).",
"subUpdates": "Інтервали оновлення",
"subUpdatesDesc": "Інтервали оновлення URL-адреси підписки в клієнтських програмах. (одиниця: година)",
"subRateLimitEnable": "Обмеження частоти підписок",
"subRateLimitEnableDesc": "Обмежує, як часто кожна IP-адреса клієнта може запитувати URL-адреси підписок. Запити понад ліміт отримують HTTP 429 з підказкою Retry-After. Довірені CIDR проксі (загальні налаштування) визначають, за якою адресою враховується клієнт.",
"subRateLimit": "Запитів на хвилину",
"subRateLimitDesc": "Максимальна кількість запитів підписок на одну IP-адресу клієнта за хвилину, коли обмеження увімкнено.",
"externalSubUserAgent": "User-Agent зовнішньої підписки",
"externalSubUserAgentDesc": "Заголовок User-Agent під час завантаження зовнішньої підписки клієнта. Залиште порожнім для значення за замовчуванням (v2rayNG/1.8.5). Деякі провайдери відхиляють невідомих клієнтів.",
"subEncrypt": "Кодувати",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "Mặc định để trống để nghe tất cả các tên miền và IP. Cũng được dùng làm tên miền dự phòng cho liên kết đăng ký hiển thị khi \"URI proxy trung gian\" để trống — hãy đặt \"URI proxy trung gian\" nếu bảng điều khiển và đăng ký được truy cập qua các tên miền khác nhau (ví dụ: đứng sau proxy trung gian).",
"subUpdates": "Khoảng thời gian cập nhật gói đăng ký",
"subUpdatesDesc": "Số giờ giữa các cập nhật trong ứng dụng khách",
"subRateLimitEnable": "Giới hạn tốc độ gói đăng ký",
"subRateLimitEnableDesc": "Giới hạn tần suất mỗi IP khách hàng có thể tải các URL gói đăng ký. Các yêu cầu vượt giới hạn nhận HTTP 429 kèm gợi ý Retry-After. Các CIDR proxy đáng tin (cài đặt chung) quyết định địa chỉ nào được dùng để đếm khách hàng.",
"subRateLimit": "Yêu cầu mỗi phút",
"subRateLimitDesc": "Số lần tải gói đăng ký tối đa cho mỗi IP khách hàng mỗi phút khi giới hạn tốc độ đang bật.",
"externalSubUserAgent": "User-Agent đăng ký bên ngoài",
"externalSubUserAgentDesc": "Header User-Agent khi panel tải URL đăng ký bên ngoài của client. Để trống để dùng mặc định (v2rayNG/1.8.5). Một số nhà cung cấp từ chối client lạ.",
"subEncrypt": "Mã hóa",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "订阅服务监听的域名(留空表示监听所有域名和 IP)。当「反向代理 URI」为空时,也会作为显示的订阅链接的回退域名——如果面板和订阅通过不同的域名访问(例如位于反向代理之后),请设置「反向代理 URI」。",
"subUpdates": "更新间隔",
"subUpdatesDesc": "客户端应用中订阅 URL 的更新间隔(单位:小时)",
"subRateLimitEnable": "订阅请求限速",
"subRateLimitEnableDesc": "限制每个客户端 IP 获取订阅 URL 的频率。超过限制的请求会收到带有 Retry-After 提示的 HTTP 429。可信代理 CIDR(常规设置)决定客户端按哪个地址计数。",
"subRateLimit": "每分钟请求数",
"subRateLimitDesc": "限速开启时,每个客户端 IP 每分钟允许获取订阅的最大次数。",
"externalSubUserAgent": "外部订阅 User-Agent",
"externalSubUserAgentDesc": "面板拉取客户端外部订阅 URL 时发送的 User-Agent。留空则使用默认值(v2rayNG/1.8.5)。部分服务商会拒绝未知客户端。",
"subEncrypt": "编码",
+4
View File
@@ -1415,6 +1415,10 @@
"subDomainDesc": "訂閱服務監聽的域名(留空表示監聽所有域名和 IP)。當「反向代理 URI」為空時,也會作為顯示的訂閱連結的備援域名——如果面板和訂閱透過不同的域名存取(例如位於反向代理之後),請設定「反向代理 URI」。",
"subUpdates": "更新間隔",
"subUpdatesDesc": "客戶端應用中訂閱 URL 的更新間隔(單位:小時)",
"subRateLimitEnable": "訂閱請求限速",
"subRateLimitEnableDesc": "限制每個用戶端 IP 取得訂閱 URL 的頻率。超過限制的請求會收到帶有 Retry-After 提示的 HTTP 429。可信任代理 CIDR(一般設定)決定用戶端以哪個位址計數。",
"subRateLimit": "每分鐘請求數",
"subRateLimitDesc": "限速開啟時,每個用戶端 IP 每分鐘允許取得訂閱的最大次數。",
"externalSubUserAgent": "外部訂閱 User-Agent",
"externalSubUserAgentDesc": "面板擷取用戶外部訂閱 URL 時傳送的 User-Agent。留空則使用預設值(v2rayNG/1.8.5)。部分服務商會拒絕未知用戶端。",
"subEncrypt": "編碼",