mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
优化,排查项目问题
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/config"
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
@@ -86,10 +87,19 @@ func applyHTTPSetting(svc *service.Container, key, value string) error {
|
||||
svc.Log.Warn("https setting saved but not applied yet", zap.String("key", key), zap.String("reason", reason))
|
||||
}
|
||||
}
|
||||
|
||||
config.RuntimeMu.RLock()
|
||||
httpsEnabled := svc.Cfg.App.HTTPSEnabled
|
||||
cert := svc.Cfg.App.SSLCert
|
||||
certPath := svc.Cfg.App.SSLCertPath
|
||||
keyMaterial := svc.Cfg.App.SSLKey
|
||||
keyPath := svc.Cfg.App.SSLKeyPath
|
||||
config.RuntimeMu.RUnlock()
|
||||
|
||||
switch key {
|
||||
case "https.enabled":
|
||||
if svc.Cfg.App.HTTPSEnabled {
|
||||
if _, err := service.ResolveSSLKeyPair(svc.Cfg.App.SSLCert, svc.Cfg.App.SSLCertPath, svc.Cfg.App.SSLKey, svc.Cfg.App.SSLKeyPath); err != nil {
|
||||
if httpsEnabled {
|
||||
if _, err := service.ResolveSSLKeyPair(cert, certPath, keyMaterial, keyPath); err != nil {
|
||||
return fmt.Errorf("启用 HTTPS 失败:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -97,7 +107,7 @@ func applyHTTPSetting(svc *service.Container, key, value string) error {
|
||||
if err := validateSSLMaterialSource(key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
if !svc.Cfg.App.HTTPSEnabled {
|
||||
if !httpsEnabled {
|
||||
return nil
|
||||
}
|
||||
if !httpsPairReady(svc) {
|
||||
@@ -144,7 +154,13 @@ func validateSSLMaterialSource(key, value string) error {
|
||||
|
||||
// httpsPairReady 判断基于当前配置解析出的证书/私钥是否完整且匹配。
|
||||
func httpsPairReady(svc *service.Container) bool {
|
||||
_, err := service.ResolveSSLKeyPair(svc.Cfg.App.SSLCert, svc.Cfg.App.SSLCertPath, svc.Cfg.App.SSLKey, svc.Cfg.App.SSLKeyPath)
|
||||
config.RuntimeMu.RLock()
|
||||
cert := svc.Cfg.App.SSLCert
|
||||
certPath := svc.Cfg.App.SSLCertPath
|
||||
keyMaterial := svc.Cfg.App.SSLKey
|
||||
keyPath := svc.Cfg.App.SSLKeyPath
|
||||
config.RuntimeMu.RUnlock()
|
||||
_, err := service.ResolveSSLKeyPair(cert, certPath, keyMaterial, keyPath)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -33,6 +35,21 @@ func dlnaCastHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// SSRF 防护:control_url 必须命中本服务发现到的真实渲染设备,
|
||||
// 防止登录用户借 cast 接口向任意内网地址发起 POST。
|
||||
// 优先用 30s 缓存;未命中时强制重扫一次再校验(设备可能刚上线)。
|
||||
devices, err := svc.DLNA.Discover(c.Request.Context(), false)
|
||||
if err == nil && !dlnaControlURLKnown(devices, req.ControlURL) {
|
||||
devices, err = svc.DLNA.Discover(c.Request.Context(), true)
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !dlnaControlURLKnown(devices, req.ControlURL) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "unknown DLNA device: control_url must come from /api/dlna discovery"})
|
||||
return
|
||||
}
|
||||
if err := svc.DLNA.Cast(c.Request.Context(), req.ControlURL, req.MediaURL); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -40,3 +57,25 @@ func dlnaCastHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// dlnaControlURLKnown 判断 control_url 是否属于发现列表中的设备。
|
||||
// 按解析后的 host:port+path 精确比对,容忍大小写与尾斜杠差异。
|
||||
func dlnaControlURLKnown(devices []service.DLNADevice, controlURL string) bool {
|
||||
want, err := url.Parse(strings.TrimSpace(controlURL))
|
||||
if err != nil || want.Host == "" {
|
||||
return false
|
||||
}
|
||||
for _, dev := range devices {
|
||||
for _, candidate := range []string{dev.ControlURL, dev.Location} {
|
||||
u, err := url.Parse(strings.TrimSpace(candidate))
|
||||
if err != nil || u.Host == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(u.Host, want.Host) &&
|
||||
strings.EqualFold(strings.TrimRight(u.Path, "/"), strings.TrimRight(want.Path, "/")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -132,22 +132,25 @@ func embyMeHandler(svc *service.Container) gin.HandlerFunc {
|
||||
|
||||
func embyGetUserByIDHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
u, err := svc.Emby.FindUser(c.Request.Context(), c.Param("userId"))
|
||||
uid := embyUserID(c)
|
||||
if uid == "" {
|
||||
embyError(c, http.StatusUnauthorized, "not authenticated")
|
||||
return
|
||||
}
|
||||
// 只返回调用者自己的用户对象:客户端误传其他 userId 时回退到
|
||||
// 调用者自身(保留旧行为的兼容语义),但绝不返回他人数据。
|
||||
u, err := svc.Emby.FindUser(c.Request.Context(), uid)
|
||||
if err == nil && u != nil {
|
||||
c.JSON(http.StatusOK, u)
|
||||
return
|
||||
}
|
||||
if authUID := embyUserID(c); authUID != "" && authUID != c.Param("userId") {
|
||||
u, err = svc.Emby.FindUser(c.Request.Context(), authUID)
|
||||
if err == nil && u != nil {
|
||||
c.JSON(http.StatusOK, u)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, embyFallbackUser(c.Param("userId")))
|
||||
c.JSON(http.StatusOK, embyFallbackUser(uid))
|
||||
}
|
||||
}
|
||||
|
||||
// embyFallbackUser 是查库失败时的最后兜底(保持客户端可渲染)。
|
||||
// Policy 必须是最小权限:不声明管理员/删除内容/控制他人等能力,
|
||||
// 实际权限始终由服务端各路由的校验决定。
|
||||
func embyFallbackUser(id string) gin.H {
|
||||
if strings.TrimSpace(id) == "" {
|
||||
id = "mebox-user"
|
||||
@@ -161,10 +164,10 @@ func embyFallbackUser(id string) gin.H {
|
||||
"HasConfiguredEasyPassword": false,
|
||||
"EnableAutoLogin": false,
|
||||
"Policy": gin.H{
|
||||
"IsAdministrator": true,
|
||||
"EnableContentDeletion": true,
|
||||
"EnableRemoteControlOfOtherUsers": true,
|
||||
"EnableSharedDeviceControl": true,
|
||||
"IsAdministrator": false,
|
||||
"EnableContentDeletion": false,
|
||||
"EnableRemoteControlOfOtherUsers": false,
|
||||
"EnableSharedDeviceControl": false,
|
||||
"EnableRemoteAccess": true,
|
||||
"EnableAllDevices": true,
|
||||
"EnableAllChannels": true,
|
||||
|
||||
@@ -368,7 +368,11 @@ func deleteLibraryHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
uid, _ := c.Get("ctx_user_id")
|
||||
svc.Audit.Record(c.Request.Context(), toString(uid), "library.delete", id, c.ClientIP(), "")
|
||||
go func() { _ = svc.Watcher.Refresh(context.Background()) }()
|
||||
// goroutine 内的 panic 无法被 gin.Recovery 捕获,会直接崩掉进程:
|
||||
// 与其他调用点一致先判空。
|
||||
if svc.Watcher != nil {
|
||||
go func() { _ = svc.Watcher.Refresh(context.Background()) }()
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/middleware"
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
@@ -157,6 +159,25 @@ type playlistItemReq struct {
|
||||
MediaID string `json:"media_id" binding:"required"`
|
||||
}
|
||||
|
||||
// playlistWriteGuard 校验当前用户对播放列表的写权限(属主或 admin)。
|
||||
// 校验失败时已写入错误响应,调用方直接 return。
|
||||
func playlistWriteGuard(c *gin.Context, svc *service.Container, playlistID string) (string, bool, bool) {
|
||||
uid, _ := c.Get(middleware.CtxUserID)
|
||||
role, _ := c.Get(middleware.CtxUserRole)
|
||||
isAdmin := role == "admin"
|
||||
if err := svc.Playback.EnsurePlaylistOwner(c.Request.Context(), playlistID, uid.(string), isAdmin); err != nil {
|
||||
if errors.Is(err, service.ErrPlaylistForbidden) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
} else if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "playlist not found"})
|
||||
} else {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
}
|
||||
return "", isAdmin, false
|
||||
}
|
||||
return uid.(string), isAdmin, true
|
||||
}
|
||||
|
||||
func addPlaylistItemHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req playlistItemReq
|
||||
@@ -164,8 +185,12 @@ func addPlaylistItemHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
uid, isAdmin, ok := playlistWriteGuard(c, svc, c.Param("id"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := svc.Playback.AddToPlaylist(
|
||||
c.Request.Context(), c.Param("id"), req.MediaID,
|
||||
c.Request.Context(), c.Param("id"), uid, req.MediaID, isAdmin,
|
||||
); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -176,8 +201,12 @@ func addPlaylistItemHandler(svc *service.Container) gin.HandlerFunc {
|
||||
|
||||
func removePlaylistItemHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid, isAdmin, ok := playlistWriteGuard(c, svc, c.Param("id"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := svc.Playback.RemoveFromPlaylist(
|
||||
c.Request.Context(), c.Param("id"), c.Param("media_id"),
|
||||
c.Request.Context(), c.Param("id"), uid, c.Param("media_id"), isAdmin,
|
||||
); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -188,8 +217,12 @@ func removePlaylistItemHandler(svc *service.Container) gin.HandlerFunc {
|
||||
|
||||
func deletePlaylistHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid, isAdmin, ok := playlistWriteGuard(c, svc, c.Param("id"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := svc.Playback.DeletePlaylist(
|
||||
c.Request.Context(), c.Param("id"),
|
||||
c.Request.Context(), c.Param("id"), uid, isAdmin,
|
||||
); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
||||
@@ -27,6 +27,9 @@ func reorderPlaylistHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
pid := c.Param("id")
|
||||
if _, _, ok := playlistWriteGuard(c, svc, pid); !ok {
|
||||
return
|
||||
}
|
||||
for i, mid := range req.Order {
|
||||
if err := svc.Repo.DB.WithContext(c.Request.Context()).
|
||||
Model(&model.PlaylistItem{}).
|
||||
@@ -44,8 +47,12 @@ func reorderPlaylistHandler(svc *service.Container) gin.HandlerFunc {
|
||||
// /playlists/:id/items/:item_id (vs. the existing /:media_id variant).
|
||||
func deletePlaylistItemByIDHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
pid := c.Param("id")
|
||||
if _, _, ok := playlistWriteGuard(c, svc, pid); !ok {
|
||||
return
|
||||
}
|
||||
if err := svc.Repo.DB.WithContext(c.Request.Context()).
|
||||
Where("playlist_id = ? AND id = ?", c.Param("id"), c.Param("item_id")).
|
||||
Where("playlist_id = ? AND id = ?", pid, c.Param("item_id")).
|
||||
Delete(&model.PlaylistItem{}).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
||||
@@ -14,9 +14,14 @@ import (
|
||||
)
|
||||
|
||||
// statsUserHandler returns a watch-time summary for one user.
|
||||
// 观看统计是隐私数据:仅允许本人或管理员查询。
|
||||
func statsUserHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("id")
|
||||
if !statsCallerAllowed(c, uid) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
var watched int64
|
||||
_ = svc.Repo.DB.Model(&model.PlaybackHistory{}).
|
||||
Where("user_id = ?", uid).
|
||||
@@ -35,8 +40,14 @@ func statsUserHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// statsTopUsersHandler returns the most active users by play count.
|
||||
// 全员排行含用户名与精确时长,仅管理员可查。
|
||||
func statsTopUsersHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get(middleware.CtxUserRole)
|
||||
if role != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
|
||||
if limit <= 0 || limit > 50 {
|
||||
limit = 10
|
||||
@@ -109,3 +120,13 @@ func statsPlayHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
}
|
||||
|
||||
// statsCallerAllowed 判断当前调用者是否允许查看 uid 的观看统计。
|
||||
func statsCallerAllowed(c *gin.Context, uid string) bool {
|
||||
role, _ := c.Get(middleware.CtxUserRole)
|
||||
if role == "admin" {
|
||||
return true
|
||||
}
|
||||
caller, _ := c.Get(middleware.CtxUserID)
|
||||
return toString(caller) == uid
|
||||
}
|
||||
|
||||
@@ -39,11 +39,16 @@ func listSystemConfigHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
func isSecretKey(k string) bool {
|
||||
for _, suffix := range []string{".token", ".secret", ".password", ".api_key", ".cookie"} {
|
||||
for _, suffix := range []string{".token", ".secret", ".password", ".api_key", ".cookie", ".pin"} {
|
||||
if endsWith(k, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// 非后缀型敏感键:可触发服务端任意命令的更新命令等。
|
||||
switch k {
|
||||
case "system.update.command":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
+17
-4
@@ -9,6 +9,8 @@ package handler
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -21,10 +23,21 @@ import (
|
||||
var wsUpgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
// Allow any origin: the AuthRequired middleware already validated the
|
||||
// JWT before we got here, and we never serve sensitive cross-domain
|
||||
// state through the socket.
|
||||
CheckOrigin: func(_ *http.Request) bool { return true },
|
||||
// 同源校验:浏览器跨站页面虽读不到 ?token=,但可能借 cookie 通道
|
||||
// (extractToken 接受 msgo_access_token cookie)发起跨站 WebSocket
|
||||
// 劫持。放行同源与非浏览器客户端(不发 Origin 头的 App/脚本),
|
||||
// 拒绝跨站 Origin。
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil || u.Host == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(u.Host, r.Host)
|
||||
},
|
||||
}
|
||||
|
||||
func wsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
|
||||
Reference in New Issue
Block a user