1
0

api.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package controller
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  7. "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
  8. "github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/session"
  10. "github.com/gin-gonic/gin"
  11. )
  12. // APIController handles the main API routes for the 3x-ui panel, including inbounds and server management.
  13. type APIController struct {
  14. BaseController
  15. inboundController *InboundController
  16. serverController *ServerController
  17. nodeController *NodeController
  18. hostController *HostController
  19. settingController *SettingController
  20. xraySettingController *XraySettingController
  21. userService panel.UserService
  22. apiTokenService panel.ApiTokenService
  23. Tgbot tgbot.Tgbot
  24. }
  25. // NewAPIController creates a new APIController instance and initializes its routes.
  26. func NewAPIController(g *gin.RouterGroup) *APIController {
  27. a := &APIController{}
  28. a.initRouter(g)
  29. return a
  30. }
  31. func (a *APIController) checkAPIAuth(c *gin.Context) {
  32. // A verified client certificate (a completed mTLS handshake) authenticates
  33. // the caller, equivalent to a valid bearer token. api_authed must be set so
  34. // the CSRF middleware lets cert-authed mutations through.
  35. if c.Request.TLS != nil && len(c.Request.TLS.VerifiedChains) > 0 {
  36. if u, err := a.userService.GetFirstUser(); err == nil {
  37. session.SetAPIAuthUser(c, u)
  38. }
  39. c.Set("api_authed", true)
  40. c.Set("api_token_scope", model.ApiScopeNodeSync)
  41. c.Next()
  42. return
  43. }
  44. auth := c.GetHeader("Authorization")
  45. if after, ok := strings.CutPrefix(auth, "Bearer "); ok {
  46. tok := after
  47. if row, ok := a.apiTokenService.MatchToken(tok); ok {
  48. if u, err := a.userService.GetFirstUser(); err == nil {
  49. session.SetAPIAuthUser(c, u)
  50. }
  51. c.Set("api_authed", true)
  52. c.Set("api_token_scope", row.Scope)
  53. c.Next()
  54. return
  55. }
  56. }
  57. if !session.IsLogin(c) {
  58. // A presented Bearer token is not an anonymous scan: return 401 so
  59. // callers can distinguish a bad/disabled token from a wrong base path
  60. // (NoRoute still 404s). XHR keeps 401; bare unauthenticated stays 404.
  61. authHdr := c.GetHeader("Authorization")
  62. if strings.HasPrefix(authHdr, "Bearer ") || c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
  63. c.AbortWithStatus(http.StatusUnauthorized)
  64. } else {
  65. c.AbortWithStatus(http.StatusNotFound)
  66. }
  67. return
  68. }
  69. c.Next()
  70. }
  71. // monitorScopeAllow exposes only status/metrics routes without sensitive data.
  72. // Keys are route patterns relative to /panel/api.
  73. var monitorScopeAllow = map[string]struct{}{
  74. "/server/status": {},
  75. "/server/cpuHistory/:bucket": {},
  76. "/server/history/:metric/:bucket": {},
  77. "/server/xrayMetricsState": {},
  78. "/server/xrayMetricsHistory/:metric/:bucket": {},
  79. "/server/xrayObservatory": {},
  80. "/server/xrayObservatoryHistory/:tag/:bucket": {},
  81. "/server/getXrayVersion": {},
  82. "/server/getPanelUpdateInfo": {},
  83. "/nodes/history/:id/:metric/:bucket": {},
  84. }
  85. // nodeSyncScopeAllow is the node-sync route/method allowlist relative to
  86. // /panel/api; Gin patterns prevent concrete parameters broadening authority.
  87. var nodeSyncScopeAllow = map[string]map[string]struct{}{
  88. "/server/status": {http.MethodGet: {}},
  89. "/inbounds/list": {http.MethodGet: {}},
  90. "/inbounds/add": {http.MethodPost: {}},
  91. "/inbounds/del/:id": {http.MethodPost: {}},
  92. "/inbounds/update/:id": {http.MethodPost: {}},
  93. "/clients/add": {http.MethodPost: {}},
  94. "/clients/del/:email": {http.MethodPost: {}},
  95. "/clients/:email/detach": {http.MethodPost: {}},
  96. "/clients/update/:email": {http.MethodPost: {}},
  97. "/server/restartXrayService": {http.MethodPost: {}},
  98. "/server/getWebCertFiles": {http.MethodGet: {}},
  99. "/server/descendants": {http.MethodGet: {}},
  100. "/clients/resetTraffic/:email": {http.MethodPost: {}},
  101. "/inbounds/resetAllTraffics": {http.MethodPost: {}},
  102. "/inbounds/:id/resetTraffic": {http.MethodPost: {}},
  103. "/clients/onlinesByGuid": {http.MethodPost: {}},
  104. "/clients/onlines": {http.MethodPost: {}},
  105. "/clients/lastOnline": {http.MethodPost: {}},
  106. "/inbounds/pushClientTraffics": {http.MethodPost: {}},
  107. "/server/clientIps": {http.MethodGet: {}, http.MethodPost: {}},
  108. "/clients/clientIpsByGuid": {http.MethodPost: {}},
  109. "/hosts/list": {http.MethodGet: {}},
  110. }
  111. // enforceTokenScope applies explicit allowlists to monitor and node-sync tokens.
  112. // Admin tokens and session-login users retain their existing behavior.
  113. func (a *APIController) enforceTokenScope(c *gin.Context) {
  114. scopeVal, ok := c.Get("api_token_scope")
  115. if !ok {
  116. c.Next()
  117. return
  118. }
  119. scope, _ := scopeVal.(string)
  120. if scope == model.ApiScopeAdmin {
  121. c.Next()
  122. return
  123. }
  124. deny := func() {
  125. c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
  126. "success": false,
  127. "msg": "this API token is not permitted to access this endpoint",
  128. })
  129. }
  130. rel := relAPIPath(c.FullPath())
  131. switch scope {
  132. case model.ApiScopeMonitor:
  133. if _, allowed := monitorScopeAllow[rel]; allowed && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {
  134. c.Next()
  135. return
  136. }
  137. case model.ApiScopeNodeSync:
  138. if methods, allowed := nodeSyncScopeAllow[rel]; allowed {
  139. if _, allowedMethod := methods[c.Request.Method]; allowedMethod {
  140. c.Next()
  141. return
  142. }
  143. }
  144. default:
  145. deny()
  146. return
  147. }
  148. deny()
  149. }
  150. func relAPIPath(fullPath string) string {
  151. const marker = "/panel/api"
  152. _, after, ok := strings.Cut(fullPath, marker)
  153. if !ok {
  154. return ""
  155. }
  156. return after
  157. }
  158. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  159. func (a *APIController) initRouter(g *gin.RouterGroup) {
  160. // Main API group
  161. api := g.Group("/panel/api")
  162. api.Use(a.checkAPIAuth)
  163. api.Use(a.enforceTokenScope)
  164. // Decode + verify the node config envelope (zstd + X-Config-Sha256) and
  165. // advertise support, before CSRF/handlers read the body.
  166. api.Use(middleware.ConfigEnvelopeMiddleware())
  167. api.Use(middleware.CSRFMiddleware())
  168. api.GET("/openapi.json", ServeOpenAPISpec)
  169. // Inbounds API
  170. inbounds := api.Group("/inbounds")
  171. a.inboundController = NewInboundController(inbounds)
  172. clients := api.Group("/clients")
  173. NewClientController(clients)
  174. NewGroupController(clients)
  175. // Server API
  176. server := api.Group("/server")
  177. a.serverController = NewServerController(server)
  178. // Nodes API — multi-panel management
  179. nodes := api.Group("/nodes")
  180. a.nodeController = NewNodeController(nodes)
  181. // Hosts API — per-inbound override endpoints for subscription links
  182. hosts := api.Group("/hosts")
  183. a.hostController = NewHostController(hosts)
  184. // Settings + Xray config management live under the API surface too, so the
  185. // same API token drives them. Paths are /panel/api/setting/* and
  186. // /panel/api/xray/*.
  187. a.settingController = NewSettingController(api)
  188. a.xraySettingController = NewXraySettingController(api)
  189. // Subscription balancers — client-side balancers for the JSON sub output
  190. NewSubBalancerController(api)
  191. // Extra routes
  192. api.POST("/backuptotgbot", a.BackuptoTgbot)
  193. }
  194. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  195. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  196. a.Tgbot.SendBackupToAdmins()
  197. }