Files
3x-ui-agent/internal/sub/controller.go
T
Muse 1bd63e6625 settings trim: remove dead settings, upstream remnants, JSON/Clash subscriptions
Per SETTINGS-AUDIT (all three tiers approved 2026-10-23):

Dead settings:
- panelOutbound, ipLimitAllowlist (+ orphan parser job), outboundDownThreshold
- tg fake events outbound.down/outbound.up/xray.crash (no publisher in lite)
- phantom routing sub-tabs (Happ/Clash/Incy) and subJsonRules direct-rules tab
  (no backend keys); subHideSettings moved to the subscription info tab first

Upstream remnants:
- ldap* / smtp* model+schema keys, EmailNotifications orphan component
- twoFactorEnable/twoFactorToken + login-page probe (no backend handler)
- externalTrafficInform*

Newly approved removals:
- JSON subscription family (producer, routes, UA auto-detect, mux/finalmask/
  observatory) and Clash subscription family (producer, routes, UA detect)
- SubBalancer (table, service, controller, settings tab)
- subThemeDir (subscription page falls back to the built-in template)
- datepicker jalalian option (gregorian only; Persian picker removed)

JSON/Clash endpoints now 404; link-format output pinned by regression tests.
Guarded keys untouched: webListen/webPort/webBasePath/certs, tg* chain,
expireDiff/trafficDiff/tgBotProxy, subHideSettings, pageSize/tgLang.
2026-10-22 19:21:07 +00:00

453 lines
13 KiB
Go

package sub
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"os"
"strings"
"unicode"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
// writeSubError translates a service-layer result into an HTTP response.
// A nil error with no rows means the subId doesn't match anything (deleted
// client, never-existed id) and becomes 404. A real error becomes 500. No
// body — VPN clients only look at the status.
func writeSubError(c *gin.Context, err error) {
if err == nil {
c.Status(http.StatusNotFound)
return
}
c.Status(http.StatusInternalServerError)
}
// SUBController handles HTTP requests for subscription links.
type SUBController struct {
subTitle string
subSupportUrl string
subProfileUrl string
subAnnounce string
subHideSettings bool
subPath string
subEncrypt bool
updateInterval string
subService *SubService
clientService service.ClientService
settingService service.SettingService
}
type subControllerConfig struct {
subPath string
subEncrypt bool
remarkTemplate string
updateInterval string
subTitle string
subSupportURL string
subProfileURL string
subAnnounce string
subHideSettings bool
}
type SUBControllerOption func(*subControllerConfig)
func WithSUBPath(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subPath = value }
}
func WithSUBEncryption(value bool) SUBControllerOption {
return func(config *subControllerConfig) { config.subEncrypt = value }
}
func WithSUBRemarkTemplate(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.remarkTemplate = value }
}
func WithSUBUpdateInterval(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.updateInterval = value }
}
func WithSUBTitle(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subTitle = value }
}
func WithSUBSupportURL(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subSupportURL = value }
}
func WithSUBProfileURL(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subProfileURL = value }
}
func WithSUBAnnounce(value string) SUBControllerOption {
return func(config *subControllerConfig) { config.subAnnounce = value }
}
func WithSUBHideSettings(value bool) SUBControllerOption {
return func(config *subControllerConfig) { config.subHideSettings = value }
}
func defaultSUBControllerConfig() subControllerConfig {
return subControllerConfig{
subPath: "/sub/",
subEncrypt: true,
remarkTemplate: service.DefaultRemarkTemplate,
updateInterval: "12",
}
}
// NewSUBController creates a new subscription controller with the given configuration.
func NewSUBController(g *gin.RouterGroup, options ...SUBControllerOption) *SUBController {
config := defaultSUBControllerConfig()
for _, option := range options {
option(&config)
}
sub := NewSubService(config.remarkTemplate)
a := &SUBController{
subTitle: config.subTitle,
subSupportUrl: config.subSupportURL,
subProfileUrl: config.subProfileURL,
subAnnounce: config.subAnnounce,
subHideSettings: config.subHideSettings,
subPath: config.subPath,
subEncrypt: config.subEncrypt,
updateInterval: config.updateInterval,
subService: sub,
}
a.initRouter(g)
return a
}
// initRouter registers HTTP routes for subscription links on the provided
// router group.
func (a *SUBController) initRouter(g *gin.RouterGroup) {
gLink := g.Group(a.subPath)
gLink.GET(":subid", a.subs)
gLink.HEAD(":subid", a.subs)
}
// maybeServeSubPage renders the HTML info page when the request comes from a
// browser (Accept: text/html) or explicitly asks for it (?html=1 or ?view=html).
// It reports whether the request was handled. The remark template's per-client
// info is for the content a client app imports — the raw subscription body. A
// browser viewing the HTML info page gets clean, name-only remarks (usage is
// shown in the page summary).
func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
accept := c.GetHeader("Accept")
wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
if !wantsHTML {
return false
}
page, ok := a.buildSubPageData(c)
if !ok {
return true
}
a.serveSubPage(c, page.BasePath, page)
return true
}
func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool {
if !strings.EqualFold(c.Query("format"), "info") {
return false
}
page, ok := a.buildSubPageData(c)
if !ok {
return true
}
info := a.subPageContext(page)
delete(info, "links")
info["emails"] = dedupeEmails(page.Emails)
setNoCacheHeaders(c)
c.JSON(http.StatusOK, info)
return true
}
func (a *SUBController) buildSubPageData(c *gin.Context) (PageData, bool) {
subId := c.Param("subid")
_, host, _, hostHeader := a.subService.ResolveRequest(c)
subReq := a.subService.ForRequest(host)
subReq.subscriptionBody = false
subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
if err != nil || len(subs) == 0 {
writeSubError(c, err)
return PageData{}, false
}
subURL := subReq.BuildURLs(a.subPath, subId)
basePath, exists := c.Get("base_path")
if !exists {
basePath = "/"
}
basePathStr := basePath.(string)
metadata := a.metadataForSubRequest(func() *SubService { return subReq }, subId, "")
page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, basePathStr, metadata.Title, metadata.SupportURL)
page.SubAnnounce = metadata.Announce
return page, true
}
func dedupeEmails(emails []string) []string {
out := make([]string, 0, len(emails))
seen := make(map[string]struct{}, len(emails))
for _, email := range emails {
if email == "" {
continue
}
if _, dup := seen[email]; dup {
continue
}
seen[email] = struct{}{}
out = append(out, email)
}
return out
}
// subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
func (a *SUBController) subs(c *gin.Context) {
userAgent := c.GetHeader("User-Agent")
if a.maybeServeSubInfo(c) {
logSubscriptionRoute(userAgent, "info")
return
}
if a.maybeServeSubPage(c) {
logSubscriptionRoute(userAgent, "html")
return
}
if !a.enforceHwid(c) {
return
}
logSubscriptionRoute(userAgent, "raw")
subId := c.Param("subid")
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
subReq := a.subService.ForRequest(host)
subReq.subscriptionBody = true
subs, _, _, traffic, err := subReq.getSubs(subId)
if err != nil || len(subs) == 0 {
writeSubError(c, err)
} else {
var result strings.Builder
for _, sub := range subs {
result.WriteString(sub)
result.WriteString("\n")
}
// Add headers
header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
profileURL := fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
metadata := a.metadataForSubRequest(func() *SubService { return subReq }, subId, profileURL)
a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subHideSettings)
if a.subEncrypt {
c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
} else {
c.String(200, result.String())
}
a.recordSubscriptionFetch(c)
}
}
func (a *SUBController) recordSubscriptionFetch(c *gin.Context) {
if c.Request == nil || c.Request.Method != http.MethodGet || c.Writer.Status() != http.StatusOK {
return
}
if err := a.subService.RecordSubscriptionFetch(c.Param("subid")); err != nil {
logger.Warning("Failed to record subscription fetch:", err)
}
}
func logSubscriptionRoute(userAgent, branch string) {
logger.Debugf("Subscription request routed: branch=%s user_agent=%q", branch, sanitizeUserAgentForLog(userAgent))
}
func sanitizeUserAgentForLog(userAgent string) string {
clean := strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return ' '
}
return r
}, userAgent)
runes := []rune(clean)
if len(runes) > 512 {
return string(runes[:512])
}
return clean
}
// serveSubPage renders internal/web/dist/subpage.html for the current subscription
// request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
// we inject that here, along with window.X_UI_BASE_PATH so the
// page's static asset references resolve correctly when the panel runs
// behind a URL prefix.
func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
var body []byte
if diskBody, diskErr := os.ReadFile("internal/web/dist/subpage.html"); diskErr == nil {
body = diskBody
} else {
readBody, err := fs.ReadFile(distFS, "dist/subpage.html")
if err != nil {
c.String(http.StatusInternalServerError, "missing embedded subpage")
return
}
body = readBody
}
// Vite emits absolute asset URLs (`/assets/...`); when the panel is
// installed under a custom URL prefix, rewrite them so the bundle
// loads from `<basePath>assets/...` where the static handler is
// actually mounted.
if basePath != "/" && basePath != "" {
body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
}
subData := a.subPageContext(page)
subDataJSON, err := json.Marshal(subData)
if err != nil {
subDataJSON = []byte("{}")
}
// Defense-in-depth string-escape for the basePath embed — admin-
// controlled but cheap to harden.
jsEscape := strings.NewReplacer(
`\`, `\\`,
`"`, `\"`,
"\n", `\n`,
"\r", `\r`,
"<", `<`,
">", `>`,
"&", `&`,
)
escapedBase := jsEscape.Replace(basePath)
inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
`window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
out := bytes.Replace(body, []byte("</head>"), inject, 1)
setNoCacheHeaders(c)
c.Data(http.StatusOK, "text/html; charset=utf-8", out)
}
// subPageContext builds the shared view-model map: the template context for
// custom sub themes, the window.__SUB_PAGE_DATA__ payload the SPA reads, and
// (without links) the ?format=info JSON body. The panel's "Calendar Type"
// setting decides whether dates render Gregorian or Jalali — surfaced here so
// consumers match the rest of the panel without a round-trip.
func (a *SUBController) subPageContext(page PageData) map[string]any {
datepicker, _ := a.settingService.GetDatepicker()
if datepicker == "" {
datepicker = "gregorian"
}
return map[string]any{
"sId": page.SId,
"enabled": page.Enabled,
"isOnline": page.IsOnline,
"download": page.Download,
"upload": page.Upload,
"total": page.Total,
"used": page.Used,
"remained": page.Remained,
"expire": page.Expire,
"lastOnline": page.LastOnline,
"downloadByte": page.DownloadByte,
"uploadByte": page.UploadByte,
"totalByte": page.TotalByte,
"subUrl": page.SubUrl,
"subTitle": page.SubTitle,
"subSupportUrl": page.SubSupportUrl,
"links": page.Result,
"emails": page.Emails,
"datepicker": datepicker,
"announce": page.SubAnnounce,
}
}
func (a *SUBController) enforceHwid(c *gin.Context) bool {
result, err := a.clientService.EnforceHwidForSubID(c.Param("subid"), service.HwidRequest{
Hwid: c.GetHeader("X-HWID"),
UserAgent: c.GetHeader("User-Agent"),
DeviceOS: c.GetHeader("X-Device-OS"),
OsVersion: c.GetHeader("X-Ver-OS"),
DeviceModel: c.GetHeader("X-Device-Model"),
})
if err != nil {
writeSubError(c, err)
return false
}
applyHwidHeaders(c, result)
if !result.Allowed {
c.Status(http.StatusNotFound)
return false
}
return true
}
func applyHwidHeaders(c *gin.Context, result service.HwidGateResult) {
if result.Active {
c.Header("X-Hwid-Active", "true")
}
if result.NotSupported {
c.Header("X-Hwid-Not-Supported", "true")
}
if result.LimitReached {
c.Header("X-Hwid-Limit", "true")
}
if result.MaxDevicesReached {
c.Header("X-Hwid-Max-Devices-Reached", "true")
}
}
// setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
// clients and browsers always fetch fresh traffic/expiry data.
func setNoCacheHeaders(c *gin.Context) {
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
c.Header("Pragma", "no-cache")
c.Header("Expires", "0")
}
// ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
func (a *SUBController) ApplyCommonHeaders(
c *gin.Context,
header,
updateInterval,
profileTitle string,
profileSupportUrl string,
profileUrl string,
profileAnnounce string,
profileHideSettings bool,
) {
c.Writer.Header().Set("Subscription-Userinfo", header)
c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
// Basics
if profileTitle != "" {
c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
}
if profileSupportUrl != "" {
c.Writer.Header().Set("Support-Url", profileSupportUrl)
}
if profileUrl != "" {
c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
}
if profileAnnounce != "" {
c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
}
if profileHideSettings {
c.Writer.Header().Set("Hide-Settings", "1")
}
}