api.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
  59. c.AbortWithStatus(http.StatusUnauthorized)
  60. } else {
  61. c.AbortWithStatus(http.StatusNotFound)
  62. }
  63. return
  64. }
  65. c.Next()
  66. }
  67. // monitorScopeAllow exposes only status/metrics routes without sensitive data.
  68. // Keys are route patterns relative to /panel/api.
  69. var monitorScopeAllow = map[string]struct{}{
  70. "/server/status": {},
  71. "/server/cpuHistory/:bucket": {},
  72. "/server/history/:metric/:bucket": {},
  73. "/server/xrayMetricsState": {},
  74. "/server/xrayMetricsHistory/:metric/:bucket": {},
  75. "/server/xrayObservatory": {},
  76. "/server/xrayObservatoryHistory/:tag/:bucket": {},
  77. "/server/getXrayVersion": {},
  78. "/server/getPanelUpdateInfo": {},
  79. "/nodes/history/:id/:metric/:bucket": {},
  80. }
  81. // nodeSyncScopeAllow is the node-sync route/method allowlist relative to
  82. // /panel/api; Gin patterns prevent concrete parameters broadening authority.
  83. var nodeSyncScopeAllow = map[string]map[string]struct{}{
  84. "/server/status": {http.MethodGet: {}},
  85. "/inbounds/list": {http.MethodGet: {}},
  86. "/inbounds/add": {http.MethodPost: {}},
  87. "/inbounds/del/:id": {http.MethodPost: {}},
  88. "/inbounds/update/:id": {http.MethodPost: {}},
  89. "/clients/add": {http.MethodPost: {}},
  90. "/clients/del/:email": {http.MethodPost: {}},
  91. "/clients/:email/detach": {http.MethodPost: {}},
  92. "/clients/update/:email": {http.MethodPost: {}},
  93. "/server/restartXrayService": {http.MethodPost: {}},
  94. "/server/getWebCertFiles": {http.MethodGet: {}},
  95. "/server/descendants": {http.MethodGet: {}},
  96. "/clients/resetTraffic/:email": {http.MethodPost: {}},
  97. "/inbounds/resetAllTraffics": {http.MethodPost: {}},
  98. "/inbounds/:id/resetTraffic": {http.MethodPost: {}},
  99. "/clients/onlinesByGuid": {http.MethodPost: {}},
  100. "/clients/onlines": {http.MethodPost: {}},
  101. "/clients/lastOnline": {http.MethodPost: {}},
  102. "/inbounds/pushClientTraffics": {http.MethodPost: {}},
  103. "/server/clientIps": {http.MethodGet: {}, http.MethodPost: {}},
  104. "/clients/clientIpsByGuid": {http.MethodPost: {}},
  105. "/hosts/list": {http.MethodGet: {}},
  106. }
  107. // enforceTokenScope applies explicit allowlists to monitor and node-sync tokens.
  108. // Admin tokens and session-login users retain their existing behavior.
  109. func (a *APIController) enforceTokenScope(c *gin.Context) {
  110. scopeVal, ok := c.Get("api_token_scope")
  111. if !ok {
  112. c.Next()
  113. return
  114. }
  115. scope, _ := scopeVal.(string)
  116. if scope == model.ApiScopeAdmin {
  117. c.Next()
  118. return
  119. }
  120. deny := func() {
  121. c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
  122. "success": false,
  123. "msg": "this API token is not permitted to access this endpoint",
  124. })
  125. }
  126. rel := relAPIPath(c.FullPath())
  127. switch scope {
  128. case model.ApiScopeMonitor:
  129. if _, allowed := monitorScopeAllow[rel]; allowed && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {
  130. c.Next()
  131. return
  132. }
  133. case model.ApiScopeNodeSync:
  134. if methods, allowed := nodeSyncScopeAllow[rel]; allowed {
  135. if _, allowedMethod := methods[c.Request.Method]; allowedMethod {
  136. c.Next()
  137. return
  138. }
  139. }
  140. default:
  141. deny()
  142. return
  143. }
  144. deny()
  145. }
  146. func relAPIPath(fullPath string) string {
  147. const marker = "/panel/api"
  148. i := strings.Index(fullPath, marker)
  149. if i < 0 {
  150. return ""
  151. }
  152. return fullPath[i+len(marker):]
  153. }
  154. // initRouter sets up the API routes for inbounds, server, and other endpoints.
  155. func (a *APIController) initRouter(g *gin.RouterGroup) {
  156. // Main API group
  157. api := g.Group("/panel/api")
  158. api.Use(a.checkAPIAuth)
  159. api.Use(a.enforceTokenScope)
  160. // Decode + verify the node config envelope (zstd + X-Config-Sha256) and
  161. // advertise support, before CSRF/handlers read the body.
  162. api.Use(middleware.ConfigEnvelopeMiddleware())
  163. api.Use(middleware.CSRFMiddleware())
  164. api.GET("/openapi.json", ServeOpenAPISpec)
  165. // Inbounds API
  166. inbounds := api.Group("/inbounds")
  167. a.inboundController = NewInboundController(inbounds)
  168. clients := api.Group("/clients")
  169. NewClientController(clients)
  170. NewGroupController(clients)
  171. // Server API
  172. server := api.Group("/server")
  173. a.serverController = NewServerController(server)
  174. // Nodes API — multi-panel management
  175. nodes := api.Group("/nodes")
  176. a.nodeController = NewNodeController(nodes)
  177. // Hosts API — per-inbound override endpoints for subscription links
  178. hosts := api.Group("/hosts")
  179. a.hostController = NewHostController(hosts)
  180. // Settings + Xray config management live under the API surface too, so the
  181. // same API token drives them. Paths are /panel/api/setting/* and
  182. // /panel/api/xray/*.
  183. a.settingController = NewSettingController(api)
  184. a.xraySettingController = NewXraySettingController(api)
  185. // Extra routes
  186. api.POST("/backuptotgbot", a.BackuptoTgbot)
  187. }
  188. // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
  189. func (a *APIController) BackuptoTgbot(c *gin.Context) {
  190. a.Tgbot.SendBackupToAdmins()
  191. }