fix: 允许同源嵌入实时监看播放器 (#54)

This commit is contained in:
QiuSW
2026-08-13 15:23:42 +08:00
parent 825d64a9d6
commit 36964427fc
2 changed files with 44 additions and 1 deletions
+5 -1
View File
@@ -61,6 +61,10 @@ func (m *Module) player(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-src http: https:; style-src 'unsafe-inline'")
// This endpoint is the authenticated, same-origin wrapper loaded by the
// live-view page. Keep the global DENY policy everywhere else, and allow
// only Sense itself to embed this wrapper.
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'self'; frame-src http: https:; style-src 'unsafe-inline'")
_ = playerTemplate.Execute(w, target)
}
@@ -0,0 +1,39 @@
package liveview
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"yovision.local/sense/app/sense/media"
)
func TestPlayerAllowsOnlySameOriginEmbedding(t *testing.T) {
service, err := NewService("http://127.0.0.1:8889", time.Minute)
if err != nil {
t.Fatal(err)
}
route := media.Route{ID: "device:main", Path: "sense_device_main", Desired: "running", Actual: "ready"}
service.route = func(context.Context, string) (media.Route, error) { return route, nil }
service.refresh = func(context.Context, string) (media.Route, error) { return route, nil }
service.sessions["view_test"] = Session{ID: "view_test", RouteID: route.ID, ExpiresAt: time.Now().Add(time.Minute)}
req := httptest.NewRequest(http.MethodGet, "/api/v1/liveview/sessions/view_test/player", nil)
req.SetPathValue("id", "view_test")
res := httptest.NewRecorder()
NewModule(service).player(res, req)
if res.Code != http.StatusOK {
t.Fatalf("status = %d", res.Code)
}
if got := res.Header().Get("X-Frame-Options"); got != "SAMEORIGIN" {
t.Fatalf("X-Frame-Options = %q", got)
}
csp := res.Header().Get("Content-Security-Policy")
if !strings.Contains(csp, "frame-ancestors 'self'") {
t.Fatalf("Content-Security-Policy = %q", csp)
}
}