page_handler.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package handler
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/url"
  6. "os"
  7. "path/filepath"
  8. "regexp"
  9. "strings"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/response"
  11. middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  12. "github.com/Wei-Shaw/sub2api/internal/service"
  13. "github.com/gin-gonic/gin"
  14. )
  15. var validSlugPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]*$`)
  16. const maxPageFileSize = 1 << 20 // 1MB
  17. type PageHandler struct {
  18. pagesDir string
  19. settingService *service.SettingService
  20. }
  21. func NewPageHandler(dataDir string, settingService *service.SettingService) *PageHandler {
  22. pagesDir := filepath.Join(dataDir, "pages")
  23. _ = os.MkdirAll(pagesDir, 0755)
  24. return &PageHandler{pagesDir: pagesDir, settingService: settingService}
  25. }
  26. // GetPageContent serves raw markdown content for a given slug.
  27. // GET /api/v1/pages/:slug
  28. func (h *PageHandler) GetPageContent(c *gin.Context) {
  29. slug := c.Param("slug")
  30. if !validSlugPattern.MatchString(slug) || len(slug) > 64 {
  31. response.BadRequest(c, "Invalid page slug")
  32. return
  33. }
  34. // Visibility check: slug must be configured in custom_menu_items
  35. // and the user must have permission based on visibility setting
  36. if !h.checkSlugVisibility(c, slug) {
  37. c.JSON(http.StatusNotFound, gin.H{"error": "page not found"})
  38. return
  39. }
  40. filePath := filepath.Join(h.pagesDir, slug+".md")
  41. cleaned := filepath.Clean(filePath)
  42. if !strings.HasPrefix(cleaned, filepath.Clean(h.pagesDir)) {
  43. response.BadRequest(c, "Invalid page slug")
  44. return
  45. }
  46. info, err := os.Stat(cleaned)
  47. if err != nil || info.IsDir() {
  48. c.JSON(http.StatusNotFound, gin.H{"error": "page not found"})
  49. return
  50. }
  51. if info.Size() > maxPageFileSize {
  52. c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "page too large"})
  53. return
  54. }
  55. content, err := os.ReadFile(cleaned)
  56. if err != nil {
  57. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read page"})
  58. return
  59. }
  60. c.Data(http.StatusOK, "text/markdown; charset=utf-8", content)
  61. }
  62. // ListPages returns available page slugs.
  63. // GET /api/v1/pages
  64. func (h *PageHandler) ListPages(c *gin.Context) {
  65. entries, err := os.ReadDir(h.pagesDir)
  66. if err != nil {
  67. response.Success(c, []string{})
  68. return
  69. }
  70. slugs := make([]string, 0, len(entries))
  71. for _, e := range entries {
  72. if e.IsDir() {
  73. continue
  74. }
  75. name := e.Name()
  76. if strings.HasSuffix(name, ".md") {
  77. slugs = append(slugs, strings.TrimSuffix(name, ".md"))
  78. }
  79. }
  80. response.Success(c, slugs)
  81. }
  82. // ServePageImage serves images from data/pages/{slug}/ directory.
  83. // GET /api/v1/pages/:slug/images/*filename
  84. // No JWT required (browser img tags can't carry tokens), but visibility is checked.
  85. func (h *PageHandler) ServePageImage(c *gin.Context) {
  86. slug := c.Param("slug")
  87. filename := c.Param("filename")
  88. filename = strings.TrimPrefix(filename, "/")
  89. if !validSlugPattern.MatchString(slug) || len(slug) > 64 {
  90. c.Status(http.StatusNotFound)
  91. return
  92. }
  93. if !h.checkImageSlugVisibility(c, slug) {
  94. c.Status(http.StatusNotFound)
  95. return
  96. }
  97. imagesDir := filepath.Join(h.pagesDir, slug)
  98. cleaned, ok := resolvePageImagePath(h.pagesDir, imagesDir, filename)
  99. if !ok {
  100. c.Status(http.StatusNotFound)
  101. return
  102. }
  103. info, err := os.Stat(cleaned)
  104. if err != nil || info.IsDir() {
  105. c.Status(http.StatusNotFound)
  106. return
  107. }
  108. c.File(cleaned)
  109. }
  110. func resolvePageImagePath(pagesDir, imagesDir, filename string) (string, bool) {
  111. relPath, ok := cleanPageImageRelativePath(filename)
  112. if !ok {
  113. return "", false
  114. }
  115. cleanedPagesDir := filepath.Clean(pagesDir)
  116. cleanedImagesDir := filepath.Clean(imagesDir)
  117. cleanedTarget := filepath.Clean(filepath.Join(cleanedImagesDir, relPath))
  118. if !isPathWithinBase(cleanedTarget, cleanedImagesDir) {
  119. return "", false
  120. }
  121. realPagesDir, err := filepath.EvalSymlinks(cleanedPagesDir)
  122. if err != nil {
  123. return "", false
  124. }
  125. realImagesDir, err := filepath.EvalSymlinks(cleanedImagesDir)
  126. if err != nil || !isPathWithinBase(realImagesDir, realPagesDir) {
  127. return "", false
  128. }
  129. realTarget, err := filepath.EvalSymlinks(cleanedTarget)
  130. if err != nil || !isPathWithinBase(realTarget, realImagesDir) {
  131. return "", false
  132. }
  133. return realTarget, true
  134. }
  135. func cleanPageImageRelativePath(filename string) (string, bool) {
  136. if filename == "" {
  137. return "", false
  138. }
  139. if strings.HasPrefix(filename, "/") {
  140. return "", false
  141. }
  142. decoded, err := url.PathUnescape(filename)
  143. if err != nil {
  144. return "", false
  145. }
  146. if decoded == "" || strings.HasPrefix(decoded, "/") || strings.Contains(decoded, "\\") || strings.ContainsRune(decoded, 0) {
  147. return "", false
  148. }
  149. parts := make([]string, 0)
  150. for _, part := range strings.Split(decoded, "/") {
  151. switch part {
  152. case "", ".":
  153. continue
  154. case "..":
  155. return "", false
  156. default:
  157. parts = append(parts, part)
  158. }
  159. }
  160. if len(parts) == 0 {
  161. return "", false
  162. }
  163. relPath := filepath.Join(parts...)
  164. if filepath.IsAbs(relPath) || filepath.VolumeName(relPath) != "" {
  165. return "", false
  166. }
  167. return relPath, true
  168. }
  169. func isPathWithinBase(path, base string) bool {
  170. rel, err := filepath.Rel(filepath.Clean(base), filepath.Clean(path))
  171. if err != nil {
  172. return false
  173. }
  174. return rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
  175. }
  176. // findSlugVisibility looks up the slug in custom_menu_items and returns (visibility, found).
  177. func (h *PageHandler) findSlugVisibility(c *gin.Context, slug string) (string, bool) {
  178. if h.settingService == nil {
  179. return "", false
  180. }
  181. raw := h.settingService.GetCustomMenuItemsRaw(c.Request.Context())
  182. if raw == "" || raw == "[]" {
  183. return "", false
  184. }
  185. var items []struct {
  186. URL string `json:"url"`
  187. PageSlug string `json:"page_slug"`
  188. Visibility string `json:"visibility"`
  189. }
  190. if err := json.Unmarshal([]byte(raw), &items); err != nil {
  191. return "", false
  192. }
  193. for _, item := range items {
  194. itemSlug := item.PageSlug
  195. if itemSlug == "" && strings.HasPrefix(item.URL, "md:") {
  196. itemSlug = strings.TrimPrefix(item.URL, "md:")
  197. }
  198. if itemSlug == slug {
  199. return item.Visibility, true
  200. }
  201. }
  202. return "", false
  203. }
  204. // checkSlugVisibility verifies the slug is configured in custom_menu_items
  205. // and the authenticated user has permission to view it.
  206. func (h *PageHandler) checkSlugVisibility(c *gin.Context, slug string) bool {
  207. visibility, found := h.findSlugVisibility(c, slug)
  208. if !found {
  209. return false
  210. }
  211. if visibility == "admin" {
  212. role, _ := middleware2.GetUserRoleFromContext(c)
  213. return service.IsAdminRole(role)
  214. }
  215. return true
  216. }
  217. // checkImageSlugVisibility checks visibility for image requests (no JWT available).
  218. // Only allows user-visible pages; admin-only pages are blocked.
  219. func (h *PageHandler) checkImageSlugVisibility(c *gin.Context, slug string) bool {
  220. visibility, found := h.findSlugVisibility(c, slug)
  221. if !found {
  222. return false
  223. }
  224. return visibility != "admin"
  225. }
  226. // RegisterPageRoutes registers page routes on a router group.
  227. func RegisterPageRoutes(v1 *gin.RouterGroup, dataDir string, jwtAuth gin.HandlerFunc, adminAuth gin.HandlerFunc, settingService *service.SettingService) {
  228. h := NewPageHandler(dataDir, settingService)
  229. // Authenticated page content (JWT required + visibility check)
  230. pages := v1.Group("/pages")
  231. pages.Use(jwtAuth)
  232. {
  233. pages.GET("/:slug", h.GetPageContent)
  234. }
  235. // Images: no JWT (browser img tags can't carry tokens), visibility check in handler
  236. pageImages := v1.Group("/pages")
  237. {
  238. pageImages.GET("/:slug/images/*filename", h.ServePageImage)
  239. }
  240. // Admin-only: list all available pages
  241. adminPages := v1.Group("/pages")
  242. adminPages.Use(adminAuth)
  243. adminPages.Use(middleware2.AdminComplianceGuard(settingService))
  244. {
  245. adminPages.GET("", h.ListPages)
  246. }
  247. }