Files
3x-ui/internal/sub/json_info_node_test.go
T
DIMFLIX 2dd903ea8e feat(sub): bake Happ/INCY routing profiles into the JSON subscription (#6402)
* feat(sub): parse generic Happ/INCY routing payloads for the JSON subscription

Accepts the routing-rules format emitted for Happ and INCY (inline JSON,
happ:// or incy:// deeplink, or a remote https:// URL resolved through the
existing remote routing cache). The JSON subscription will bake these
rules into its documents so header-ignoring clients still get routing.

* feat(sub): bake Happ/INCY routing profiles into JSON subscription documents

When subJsonRoutingRules is set, every emitted document (per-inbound and
balancer alike) carries the profile's dns and routing rules baked in, so
header-ignoring clients like Happ and INCY still get routing; the legacy
simple-rules merge only applies when no profile is set. The balancer
document builder keeps rewriting proxy-tag rules to the balancer.

* feat(sub): add the subJsonRoutingRules setting

Plumbed from the settings store through the subscription server into
SubJsonService, so admins can set a routing profile once and every JSON
subscription document carries it.

* chore(api): regenerate OpenAPI artifacts for subJsonRoutingRules

* feat(web): routing profile editor for the JSON subscription

A textarea inside the JSON card accepts the routing profile (inline JSON,
happ/incy deeplink, or https URL) with a remote-source badge; the badge
helper moves to a shared module. Keys added to all 13 locales.

* fix(sub): warm and lazily resolve the baked JSON routing source

The routing profile was resolved once at service construction: a remote
URL that was cold at that moment baked default routing forever, and the
cron job never warmed it. The job now warms the subJsonRoutingRules URL,
and the profile resolves per request with an in-memory memo (a failed
resolve is not cached), so a warmed cache takes effect without a restart.

* feat(sub): fall back to the JSON routing profile for the Routing header

Happ and INCY download the geo files a routing profile references
through the Routing response header. When the Happ header setting was
blank the header stayed unset, and clients fetched no geo files even
though a JSON routing profile was configured. A blank setting now falls
back to the JSON profile: happ/incy deeplinks pass through, inline JSON
and remote URLs are normalized to a happ:// deeplink; an unusable or
oversized value leaves the header unset. Locale captions mention the
fallback.

* fix(sub): pass routingRules arg at call sites added by main

Main gained four NewSubJsonService call sites after this branch forked;
update them to the five-arg signature so internal/sub builds again.

* fix(sub): address code review findings on the baked JSON routing

The memoised baked template never invalidated, so an edited remote
profile kept serving the superseded dns/routing subtrees until a panel
restart; bakedTemplate now re-resolves the spec per request and rebuilds
only when the payload actually changed (regression-tested).

subJsonRoutingRules shared the happ persistence row with
subRoutingRules, so only the last-written setting survived a restart;
it now resolves under its own jsonhapp kind with the same validation
and size caps. The setting also joins validateSettingsURLs, so remote
values are canonicalised and bad URLs are rejected on save.

Also: drop the unreachable half of the remote-source guard, cut the
overlong comment blocks to the two-line convention, and deduplicate
remoteSourceBadge in the General tab. Merges upstream/main (call sites
for the widened NewSubJsonService signature).

* style(sub): gofumpt the json_routing imports

* fix(sub): accept happ add/ deeplinks and bound the routing warning

The baked-JSON routing parser only recognised happ://routing/onadd/, but
normalizeHappRouting treats happ://routing/add/ as an equally valid routing
deeplink. An operator pasting the add/ form got the Routing header set, so
the panel looked configured, while every JSON subscription document silently
carried the default routing instead of their profile.

resolveJsonRoutingSpec logged one warning per call and bakedTemplate calls it
once per emitted document, so a single fetch of an unusable profile wrote one
identical warning per document. On the public subscription server that floods
the 10240-entry buffer the panel's log view reads, evicting real entries. Log
only when the message changes, and reset on a successful resolve so a profile
that recovers and fails again is still reported.

Also resolve the template once in buildBalancerConfig: two resolves could
straddle a profile refresh and pair one revision's dns with the other's
routing.
2026-09-10 17:05:54 +02:00

248 lines
6.7 KiB
Go

package sub
import (
"fmt"
"strings"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestSubJson_InfoNode_Active(t *testing.T) {
setupInfoNodeTestDB(t)
db := database.GetDB()
ib := &model.Inbound{
Id: 1,
UserId: 1,
Remark: "Germany-VLESS",
Enable: true,
Port: 443,
Protocol: model.VLESS,
Settings: `{"clients":[{"id":"c1-uuid","email":"user1@test.com","subId":"sub-json","enable":true,"totalGB":10737418240}]}`,
StreamSettings: `{"network":"tcp","security":"none"}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
rec := &model.ClientRecord{
Id: 1,
Email: "user1@test.com",
SubID: "sub-json",
UUID: "c1-uuid",
Enable: true,
TotalGB: 10737418240,
}
if err := db.Create(rec).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ClientInbound{InboundId: 1, ClientId: 1}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: 1,
Email: "user1@test.com",
Up: 1073741824,
Down: 1073741824,
Total: 10737418240,
Enable: true,
}).Error; err != nil {
t.Fatal(err)
}
sub := NewSubService("{{EMAIL}}|📊{{TRAFFIC_LEFT}}")
sub.subInfoNodeEnable = true
jsonSvc := NewSubJsonService("", "", "", "", sub)
out, _, err := jsonSvc.GetJson("sub-json", "sub.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if !strings.Contains(out, "user1@test.com|📊8.00GB") {
t.Fatalf("expected dummy remark in JSON remarks, got:\n%s", out)
}
if !strings.Contains(out, `"protocol": "socks"`) && !strings.Contains(out, `"protocol":"socks"`) {
t.Fatalf("expected socks outbound in JSON, got:\n%s", out)
}
}
func TestSubJson_InfoNode_Expired(t *testing.T) {
setupInfoNodeTestDB(t)
db := database.GetDB()
expiredTime := time.Now().Add(-24 * time.Hour).UnixMilli()
ib := &model.Inbound{
Id: 1,
UserId: 1,
Remark: "Germany-VLESS",
Enable: true,
Port: 443,
Protocol: model.VLESS,
Settings: fmt.Sprintf(`{"clients":[{"id":"c1-uuid","email":"exp@test.com","subId":"sub-json-exp","enable":true,"expiryTime":%d}]}`, expiredTime),
StreamSettings: `{"network":"tcp","security":"none"}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
rec := &model.ClientRecord{
Id: 1,
Email: "exp@test.com",
SubID: "sub-json-exp",
UUID: "c1-uuid",
Enable: true,
ExpiryTime: expiredTime,
}
if err := db.Create(rec).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ClientInbound{InboundId: 1, ClientId: 1}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: 1,
Email: "exp@test.com",
ExpiryTime: expiredTime,
Enable: true,
}).Error; err != nil {
t.Fatal(err)
}
sub := NewSubService("{{INBOUND}}")
sub.subInfoNodeEnable = true
sub.subExpiredTemplate = service.DefaultSubExpiredTemplate
jsonSvc := NewSubJsonService("", "", "", "", sub)
out, _, err := jsonSvc.GetJson("sub-json-exp", "sub.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if !strings.Contains(out, "Expired") || !strings.Contains(out, "exp@test.com") {
t.Fatalf("expected expired remark in JSON remarks, got:\n%s", out)
}
if strings.Contains(out, "Germany-VLESS") {
t.Fatalf("expired subscription must NOT contain working inbound in JSON, got:\n%s", out)
}
}
func TestSubJson_InfoNode_Depleted(t *testing.T) {
setupInfoNodeTestDB(t)
db := database.GetDB()
ib := &model.Inbound{
Id: 1,
UserId: 1,
Remark: "Germany-VLESS",
Enable: true,
Port: 443,
Protocol: model.VLESS,
Settings: `{"clients":[{"id":"c1-uuid","email":"dep@test.com","subId":"sub-json-dep","enable":true,"totalGB":5368709120}]}`,
StreamSettings: `{"network":"tcp","security":"none"}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
rec := &model.ClientRecord{
Id: 1,
Email: "dep@test.com",
SubID: "sub-json-dep",
UUID: "c1-uuid",
Enable: true,
TotalGB: 5368709120,
}
if err := db.Create(rec).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ClientInbound{InboundId: 1, ClientId: 1}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: 1,
Email: "dep@test.com",
Up: 3221225472,
Down: 2147483648,
Total: 5368709120,
Enable: true,
}).Error; err != nil {
t.Fatal(err)
}
sub := NewSubService("{{INBOUND}}")
sub.subInfoNodeEnable = true
sub.subTrafficDepletedTemplate = service.DefaultSubTrafficDepletedTemplate
jsonSvc := NewSubJsonService("", "", "", "", sub)
out, _, err := jsonSvc.GetJson("sub-json-dep", "sub.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if !strings.Contains(out, "Traffic Depleted") || !strings.Contains(out, "dep@test.com") {
t.Fatalf("expected depleted remark in JSON remarks, got:\n%s", out)
}
if strings.Contains(out, "Germany-VLESS") {
t.Fatalf("depleted subscription must NOT contain working inbound in JSON, got:\n%s", out)
}
}
func TestSubJson_InfoNode_StatusActive(t *testing.T) {
setupInfoNodeTestDB(t)
db := database.GetDB()
ib := &model.Inbound{
Id: 1,
UserId: 1,
Remark: "Germany-VLESS",
Enable: true,
Port: 443,
Protocol: model.VLESS,
Settings: `{"clients":[{"id":"c1-uuid","email":"user1@test.com","subId":"sub-json-status","enable":true,"totalGB":10737418240}]}`,
StreamSettings: `{"network":"tcp","security":"none"}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
rec := &model.ClientRecord{
Id: 1,
Email: "user1@test.com",
SubID: "sub-json-status",
UUID: "c1-uuid",
Enable: true,
TotalGB: 10737418240,
}
if err := db.Create(rec).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ClientInbound{InboundId: 1, ClientId: 1}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: 1,
Email: "user1@test.com",
Up: 100,
Down: 100,
Total: 10737418240,
Enable: true,
}).Error; err != nil {
t.Fatal(err)
}
sub := NewSubService("{{EMAIL}}|{{STATUS_EMOJI}} {{STATUS}}")
sub.subInfoNodeEnable = true
jsonSvc := NewSubJsonService("", "", "", "", sub)
out, _, err := jsonSvc.GetJson("sub-json-status", "sub.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if !strings.Contains(out, "user1@test.com|✅ active") {
t.Fatalf("expected 'user1@test.com|✅ active' in JSON remarks, got:\n%s", out)
}
}