Compare commits

..
Author SHA1 Message Date
ila d71ef1cefd docs: update task #54 path recovery evidence 2026-08-13 22:05:42 +08:00
ila e8e1e80af6 docs: add stream-not-found troubleshooting (#54) 2026-08-13 22:05:41 +08:00
ila e4dc68be2c docs: define media path recovery rules (#54) 2026-08-13 22:05:39 +08:00
ila 236475d641 docs: record MediaMTX path recovery (#54) 2026-08-13 22:05:36 +08:00
ila e4c6c646b6 feat: support post-migration startup hooks (#54) 2026-08-13 22:05:34 +08:00
ila c5a1e6bebe fix: run module startup after migrations (#54) 2026-08-13 22:05:32 +08:00
ila 49af68dc6e fix: register media startup recovery (#54) 2026-08-13 22:05:31 +08:00
ila c3443d04db test: cover media restore and missing paths (#54) 2026-08-13 22:05:29 +08:00
ila 8643c8f990 fix: restore desired media paths on startup (#54) 2026-08-13 22:05:28 +08:00
ila ad7d45009f test: cover MediaMTX path recovery semantics (#54) 2026-08-13 22:05:27 +08:00
ila 3b0b4ce33e fix: add or replace MediaMTX paths idempotently (#54) 2026-08-13 22:05:25 +08:00
ila 2639afad3d docs: update task #54 navigation fix evidence 2026-08-13 21:33:02 +08:00
ila 3cb324ef13 docs: extend refused player troubleshooting (#54) 2026-08-13 21:33:01 +08:00
ila 6ba731b61a docs: define player navigation security boundary (#54) 2026-08-13 21:32:57 +08:00
ila a8a2b93b66 docs: record player navigation authentication (#54) 2026-08-13 21:32:55 +08:00
ila b7e9fdcb51 fix: use same-origin frame authentication (#54) 2026-08-13 21:32:52 +08:00
ila 41a6d0826a test: enforce player navigation boundary (#54) 2026-08-13 21:32:50 +08:00
ila abbc9a7093 fix: authenticate same-origin player navigation (#54) 2026-08-13 21:32:49 +08:00
ila b8d14dbdae docs: update task #54 acceptance evidence 2026-08-13 15:26:12 +08:00
ila 88766242d6 docs: add refused player troubleshooting (#54) 2026-08-13 15:26:11 +08:00
ila 0f0a534dd5 docs: record liveview embedding boundary (#54) 2026-08-13 15:26:09 +08:00
ila 56181cba96 test: enforce liveview embedding boundary (#54) 2026-08-13 15:26:06 +08:00
ila aed36eab99 fix: allow same-origin liveview player embedding (#54) 2026-08-13 15:26:05 +08:00
ila ffacf7a682 docs: map task #54 archive 2026-08-13 15:08:36 +08:00
ila d171f45a73 docs: archive task #54 2026-08-13 15:08:35 +08:00
ila c8baa277c0 docs: add on-demand stream troubleshooting (#54) 2026-08-13 15:08:34 +08:00
ila c2f3dbb660 docs: define waiting playback behavior (#54) 2026-08-13 15:08:32 +08:00
ila 9c91a36aba docs: record on-demand playback flow (#54) 2026-08-13 15:08:30 +08:00
ila 0cf9dc357e fix: load player while waiting for stream (#54) 2026-08-13 15:08:28 +08:00
ila c6087a1c91 test: cover read-only media refresh (#54) 2026-08-13 15:08:26 +08:00
ila e2c2a8686f fix: refresh on-demand media status (#54) 2026-08-13 15:08:25 +08:00
ila 676586711e fix: expose read-only media refresh (#54) 2026-08-13 15:08:24 +08:00
ila 07b08f12b1 test: cover on-demand liveview refresh (#54) 2026-08-13 15:08:23 +08:00
ila ea4940eba4 fix: refresh liveview media state (#54) 2026-08-13 15:08:22 +08:00
ila b9fce1160b docs: 记录并归档工单 #51 2026-08-13 12:42:26 +08:00
ila e73b396897 docs: 记录并归档工单 #51 2026-08-13 12:42:25 +08:00
ila 774b3f8925 docs: 记录并归档工单 #51 2026-08-13 12:42:24 +08:00
ila cc5b2cc8c6 docs: 记录并归档工单 #51 2026-08-13 12:42:22 +08:00
ila 5817199779 docs: 记录并归档工单 #51 2026-08-13 12:42:20 +08:00
ila 0d22da45c3 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:17 +08:00
ila 061d1a89a1 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:14 +08:00
ila 37c51db951 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:12 +08:00
ila 24db9fa6a5 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:11 +08:00
ila 04e2598be0 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:10 +08:00
ila 75e0360a43 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:09 +08:00
ila 8a40e85866 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:08 +08:00
ila 82672baf02 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:07 +08:00
ila 20020c0c2f feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:06 +08:00
ila c408868113 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:05 +08:00
ila 3e1b367147 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:05 +08:00
ila b1b687d6a2 feat: 自动建立实时监看媒体路径 (#51) 2026-08-13 12:42:04 +08:00
ila dde84c8687 docs: archive split camera credentials (#50) 2026-08-13 12:24:11 +08:00
ila 64b9ea8462 docs: archive split camera credentials (#50) 2026-08-13 12:24:11 +08:00
ila 15340507eb feat: complete split camera credentials (#50) 2026-08-13 12:24:03 +08:00
ila e83b359cc5 feat: complete split camera credentials (#50) 2026-08-13 12:24:02 +08:00
ila 86b4dd7a07 feat: complete split camera credentials (#50) 2026-08-13 12:24:00 +08:00
ila f6fda99aa2 feat: complete split camera credentials (#50) 2026-08-13 12:23:58 +08:00
ila ea9a89f851 feat: complete split camera credentials (#50) 2026-08-13 12:23:56 +08:00
ila f07952cb98 feat: complete split camera credentials (#50) 2026-08-13 12:23:54 +08:00
ila be1b479f68 feat: complete split camera credentials (#50) 2026-08-13 12:23:54 +08:00
ila 20066172c3 feat: complete split camera credentials (#50) 2026-08-13 12:23:53 +08:00
ila 18a4b8379c feat: complete split camera credentials (#50) 2026-08-13 12:23:52 +08:00
ila 3297937e53 feat: complete split camera credentials (#50) 2026-08-13 12:23:51 +08:00
ila a8a01d9a0a feat: complete split camera credentials (#50) 2026-08-13 12:23:50 +08:00
ila da5318f8f0 feat: complete split camera credentials (#50) 2026-08-13 12:23:49 +08:00
ila 4042011345 feat: complete split camera credentials (#50) 2026-08-13 12:23:48 +08:00
ila 136caf189e feat: complete split camera credentials (#50) 2026-08-13 12:23:47 +08:00
ila 6075433402 feat: complete split camera credentials (#50) 2026-08-13 12:23:46 +08:00
ila 65798d01b6 feat: complete split camera credentials (#50) 2026-08-13 12:23:45 +08:00
ila b383f0a8d8 feat: complete split camera credentials (#50) 2026-08-13 12:23:44 +08:00
ila 74070aa0f9 feat: complete split camera credentials (#50) 2026-08-13 12:23:43 +08:00
ila d0e947ca02 feat: complete split camera credentials (#50) 2026-08-13 12:23:42 +08:00
ila c29ce45971 docs: archive ONVIF Digest compatibility (#48) 2026-08-13 11:52:35 +08:00
ila ff93592001 docs: register ONVIF Digest task archive (#48) 2026-08-13 11:52:34 +08:00
ila 5b466b4ae6 docs: document ONVIF credential troubleshooting (#48) 2026-08-13 11:52:33 +08:00
ila c8cf53291f docs: document ONVIF Digest verification (#48) 2026-08-13 11:52:31 +08:00
ila 850ca4fead docs: document ONVIF Digest architecture (#48) 2026-08-13 11:52:30 +08:00
ila 05100c4f37 test: cover ONVIF media address parsing (#48) 2026-08-13 11:52:28 +08:00
ila 523fe81fb2 fix: parse ONVIF media service address (#48) 2026-08-13 11:52:26 +08:00
ila 2591517c76 test: cover ONVIF Digest compatibility (#48) 2026-08-13 11:52:25 +08:00
ila 440831fb4d fix: support ONVIF Digest media services (#48) 2026-08-13 11:52:24 +08:00
43 changed files with 334 additions and 23 deletions
@@ -20,6 +20,7 @@ type Source struct {
}
type PathStatus struct {
Name string `json:"name"`
Exists bool `json:"exists"`
Ready bool `json:"ready"`
Readers int `json:"readers"`
BytesReceived int64 `json:"bytes_received"`
@@ -46,7 +47,15 @@ func (c *HTTPController) Apply(ctx context.Context, source Source) error {
}
payload := map[string]any{"source": parsed.String(), "sourceOnDemand": true, "rtspTransport": "tcp"}
data, _ := json.Marshal(payload)
endpoint := c.base + "/v3/config/paths/replace/" + url.PathEscape(source.Path)
configured, err := c.configured(ctx, source.Path)
if err != nil {
return err
}
action := "add"
if configured {
action = "replace"
}
endpoint := c.base + "/v3/config/paths/" + action + "/" + url.PathEscape(source.Path)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
if err != nil {
return err
@@ -63,6 +72,39 @@ func (c *HTTPController) Apply(ctx context.Context, source Source) error {
}
return nil
}
func (c *HTTPController) configured(ctx context.Context, path string) (bool, error) {
endpoint := c.base + "/v3/config/paths/get/" + url.PathEscape(path)
deadline := time.Now().Add(5 * time.Second)
var res *http.Response
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return false, err
}
res, err = c.client.Do(req)
if err == nil {
break
}
if !time.Now().Before(deadline) {
return false, fmt.Errorf("mediamtx control unavailable: %w", err)
}
select {
case <-ctx.Done():
return false, ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
defer res.Body.Close()
io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
if res.StatusCode == http.StatusNotFound {
return false, nil
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return false, fmt.Errorf("mediamtx config lookup returned %d", res.StatusCode)
}
return true, nil
}
func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/v3/paths/get/"+url.PathEscape(path), nil)
if err != nil {
@@ -74,7 +116,7 @@ func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, e
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return PathStatus{Name: path}, nil
return PathStatus{Name: path, Exists: false}, nil
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return PathStatus{}, fmt.Errorf("mediamtx status returned %d", res.StatusCode)
@@ -88,5 +130,6 @@ func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, e
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&raw); err != nil {
return PathStatus{}, err
}
return PathStatus{Name: raw.Name, Ready: raw.Ready, Readers: len(raw.Readers), BytesReceived: raw.BytesReceived}, nil
return PathStatus{Name: raw.Name, Exists: true, Ready: raw.Ready, Readers: len(raw.Readers), BytesReceived: raw.BytesReceived}, nil
}
@@ -3,18 +3,30 @@ package mediamtx
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) }
func TestApplyBuildsCredentialSourceOnlyInTransientBody(t *testing.T) {
var body map[string]any
var appliedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.String(), "password") {
t.Fatal("credential leaked in control URL")
}
if r.Method == http.MethodGet {
http.NotFound(w, r)
return
}
appliedPath = r.URL.Path
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
@@ -28,6 +40,50 @@ func TestApplyBuildsCredentialSourceOnlyInTransientBody(t *testing.T) {
if body["source"] != "rtsp://fixture-user:fixture-password@camera.invalid/main" {
t.Fatalf("body=%#v", body)
}
if appliedPath != "/v3/config/paths/add/sense_test" {
t.Fatalf("applied path = %q", appliedPath)
}
}
func TestApplyReplacesExistingPath(t *testing.T) {
var appliedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusOK)
return
}
appliedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
if err := NewHTTPController(server.URL).Apply(context.Background(), Source{Path: "sense_test", URI: "rtsp://camera.invalid/main"}); err != nil {
t.Fatal(err)
}
if appliedPath != "/v3/config/paths/replace/sense_test" {
t.Fatalf("applied path = %q", appliedPath)
}
}
func TestApplyWaitsForNewlyStartedControlAPI(t *testing.T) {
attempts := 0
client := NewHTTPController("http://127.0.0.1:9997")
client.client.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
attempts++
if attempts < 3 {
return nil, errors.New("connection refused")
}
status := http.StatusNotFound
if request.Method == http.MethodPost {
status = http.StatusOK
}
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader("")), Header: make(http.Header)}, nil
})
if err := client.Apply(context.Background(), Source{Path: "sense_test", URI: "rtsp://camera.invalid/main"}); err != nil {
t.Fatal(err)
}
if attempts != 4 {
t.Fatalf("attempts = %d", attempts)
}
}
func TestApplyRejectsCredentialURI(t *testing.T) {
client := NewHTTPController("http://127.0.0.1")
@@ -35,3 +91,4 @@ func TestApplyRejectsCredentialURI(t *testing.T) {
t.Fatal("credential URI accepted")
}
}
@@ -320,3 +320,4 @@ func xmlEscape(value string) string {
_ = xml.EscapeText(&b, []byte(value))
return b.String()
}
@@ -155,3 +155,4 @@ func TestDigestAuthorizationUsesRequestURI(t *testing.T) {
t.Fatal(err)
}
}
@@ -83,3 +83,4 @@ func ParseMediaServiceAddress(data []byte) (string, error) {
}
}
}
@@ -43,3 +43,4 @@ func TestParseMediaServiceAddressRejectsMissingMedia(t *testing.T) {
t.Fatal("missing media service accepted")
}
}
@@ -28,3 +28,4 @@ const MediaStatusMigrationSQL = `
ALTER TABLE sense_admission_results ADD COLUMN IF NOT EXISTS media_status TEXT NOT NULL DEFAULT '';
ALTER TABLE sense_admission_results ADD COLUMN IF NOT EXISTS media_detail TEXT NOT NULL DEFAULT '';
`
@@ -147,3 +147,4 @@ func classify(err error) (string, string) {
return "unreachable", "无法读取设备信息,请检查地址和网络"
}
}
@@ -104,3 +104,4 @@ func TestProbeUsesSeparateCredentialsPersistsProfilesAndActivatesDevice(t *testi
t.Fatalf("device=%#v err=%v", updated, err)
}
}
@@ -83,3 +83,4 @@ func (s *PostgresStore) Get(ctx context.Context, deviceID string) (Result, error
}
return result, rows.Err()
}
@@ -85,3 +85,4 @@ func MarkActive(ctx context.Context, id string) error {
item.UpdatedAt = service.now().UTC()
return service.store.Update(ctx, item, expected)
}
+1
View File
@@ -137,3 +137,4 @@ func writeDeviceError(w http.ResponseWriter, err error) {
}
platform.WriteError(w, &platform.APIError{Status: status, Code: code, Message: err.Error()})
}
@@ -3,3 +3,4 @@ package device
const MigrationSQL = `CREATE TABLE IF NOT EXISTS sense_devices(id TEXT PRIMARY KEY,name TEXT NOT NULL,location TEXT NOT NULL DEFAULT '',modality TEXT NOT NULL,capabilities TEXT NOT NULL DEFAULT '',status TEXT NOT NULL,adapter_status TEXT NOT NULL,credential_ciphertext BYTEA NULL,version BIGINT NOT NULL,created_at TIMESTAMPTZ NOT NULL,updated_at TIMESTAMPTZ NOT NULL);CREATE INDEX IF NOT EXISTS sense_devices_created_idx ON sense_devices(created_at DESC);`
const SplitCredentialMigrationSQL = `ALTER TABLE sense_devices ADD COLUMN IF NOT EXISTS rtsp_credential_ciphertext BYTEA NULL;ALTER TABLE sense_devices ADD COLUMN IF NOT EXISTS rtsp_credential_same_as_onvif BOOLEAN NOT NULL DEFAULT TRUE;UPDATE sense_devices SET rtsp_credential_ciphertext=credential_ciphertext WHERE rtsp_credential_ciphertext IS NULL AND credential_ciphertext IS NOT NULL AND rtsp_credential_same_as_onvif=TRUE;`
+1
View File
@@ -148,3 +148,4 @@ func newID() string {
}
return "dev_" + hex.EncodeToString(b)
}
+1
View File
@@ -159,3 +159,4 @@ func splitCapabilities(value string) []string {
}
var _ = time.Time{}
+1
View File
@@ -42,3 +42,4 @@ type Page struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
}
+38
View File
@@ -48,6 +48,21 @@ func Require(permission string, next http.Handler) http.Handler {
})
}
// RequireSameOriginFrame authenticates browser iframe navigation that cannot
// attach the X-Product header used by API clients. Fetch Metadata keeps this
// narrow: only a same-origin iframe navigation with a valid Sense session is
// accepted.
func RequireSameOriginFrame(permission string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
module := activeModule.Load()
if module == nil {
platform.WriteError(w, &platform.APIError{Status: http.StatusServiceUnavailable, Code: "identity_not_ready", Message: "身份服务尚未就绪"})
return
}
module.RequireSameOriginFrame(permission, next).ServeHTTP(w, r)
})
}
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
principal, ok := ctx.Value(principalContextKey{}).(Principal)
return principal, ok
@@ -84,6 +99,28 @@ func (m *Module) Require(permission string, next http.Handler) http.Handler {
}))
}
func (m *Module) RequireSameOriginFrame(permission string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Sec-Fetch-Site") != "same-origin" ||
r.Header.Get("Sec-Fetch-Mode") != "navigate" ||
r.Header.Get("Sec-Fetch-Dest") != "iframe" {
platform.WriteError(w, &platform.APIError{Status: http.StatusUnauthorized, Code: "unauthorized", Message: "登录状态无效"})
return
}
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
platform.WriteError(w, &platform.APIError{Status: http.StatusUnauthorized, Code: "unauthorized", Message: "登录状态无效"})
return
}
principal, err := m.service.Authenticate(r.Context(), cookie.Value)
if err != nil || !HasPermission(principal.Role, permission) {
platform.WriteError(w, &platform.APIError{Status: http.StatusUnauthorized, Code: "unauthorized", Message: "登录状态无效"})
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), principalContextKey{}, principal)))
})
}
func (m *Module) bootstrap(w http.ResponseWriter, r *http.Request) {
var request struct {
Username string `json:"username"`
@@ -220,3 +257,4 @@ func SecureCookieFromEnvironment(value string, memoryMode bool) bool {
}
return !strings.EqualFold(value, "false")
}
@@ -21,6 +21,9 @@ func TestHTTPLoginCookieAndProductBoundary(t *testing.T) {
}
app := platform.NewApp(platform.Config{DatabaseMode: platform.DatabaseModeMemory}, nil, slog.New(slog.NewTextHandler(io.Discard, nil)))
NewModule(service, cfg).Register(app)
app.Handle("GET /same-origin-frame", RequireSameOriginFrame(PermissionMediaRead, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})))
bootstrap := httptest.NewRequest(http.MethodPost, "/api/v1/identity/bootstrap", bytes.NewBufferString(`{"username":"admin","display_name":"管理员","password":"StrongPass2026"}`))
bootstrap.Header.Set("X-Sense-Bootstrap-Token", "bootstrap-test")
@@ -56,4 +59,41 @@ func TestHTTPLoginCookieAndProductBoundary(t *testing.T) {
if senseResult.Code != http.StatusOK {
t.Fatalf("Sense product header status = %d", senseResult.Code)
}
meWithoutProduct := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil)
meWithoutProduct.AddCookie(cookies[0])
missingProductResult := httptest.NewRecorder()
app.Handler().ServeHTTP(missingProductResult, meWithoutProduct)
if missingProductResult.Code != http.StatusUnauthorized {
t.Fatalf("missing product header status = %d", missingProductResult.Code)
}
frame := httptest.NewRequest(http.MethodGet, "/same-origin-frame", nil)
frame.AddCookie(cookies[0])
frame.Header.Set("Sec-Fetch-Site", "same-origin")
frame.Header.Set("Sec-Fetch-Mode", "navigate")
frame.Header.Set("Sec-Fetch-Dest", "iframe")
frameResult := httptest.NewRecorder()
app.Handler().ServeHTTP(frameResult, frame)
if frameResult.Code != http.StatusNoContent {
t.Fatalf("same-origin frame status = %d, body = %s", frameResult.Code, frameResult.Body.String())
}
frame.Header.Set("Sec-Fetch-Site", "cross-site")
crossSiteResult := httptest.NewRecorder()
app.Handler().ServeHTTP(crossSiteResult, frame)
if crossSiteResult.Code != http.StatusUnauthorized {
t.Fatalf("cross-site frame status = %d", crossSiteResult.Code)
}
missingCookie := httptest.NewRequest(http.MethodGet, "/same-origin-frame", nil)
missingCookie.Header.Set("Sec-Fetch-Site", "same-origin")
missingCookie.Header.Set("Sec-Fetch-Mode", "navigate")
missingCookie.Header.Set("Sec-Fetch-Dest", "iframe")
missingCookieResult := httptest.NewRecorder()
app.Handler().ServeHTTP(missingCookieResult, missingCookie)
if missingCookieResult.Code != http.StatusUnauthorized {
t.Fatalf("missing-cookie frame status = %d", missingCookieResult.Code)
}
}
+2 -1
View File
@@ -14,7 +14,7 @@ func (m *Module) Register(app *platform.App) {
app.Handle("GET /api/v1/liveview/routes", identity.Require(identity.PermissionMediaRead, http.HandlerFunc(m.routes)))
app.Handle("POST /api/v1/liveview/sessions", identity.Require(identity.PermissionMediaRead, http.HandlerFunc(m.create)))
app.Handle("GET /api/v1/liveview/sessions/{id}", identity.Require(identity.PermissionMediaRead, http.HandlerFunc(m.get)))
app.Handle("GET /api/v1/liveview/sessions/{id}/player", identity.Require(identity.PermissionMediaRead, http.HandlerFunc(m.player)))
app.Handle("GET /api/v1/liveview/sessions/{id}/player", identity.RequireSameOriginFrame(identity.PermissionMediaRead, http.HandlerFunc(m.player)))
}
func (m *Module) routes(w http.ResponseWriter, r *http.Request) {
items, err := m.service.Routes(r.Context())
@@ -68,3 +68,4 @@ func (m *Module) player(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'self'; frame-src http: https:; style-src 'unsafe-inline'")
_ = playerTemplate.Execute(w, target)
}
@@ -37,3 +37,4 @@ func TestPlayerAllowsOnlySameOriginEmbedding(t *testing.T) {
t.Fatalf("Content-Security-Policy = %q", csp)
}
}
@@ -146,3 +146,4 @@ func newID() string {
}
return "view_" + hex.EncodeToString(b)
}
@@ -68,3 +68,4 @@ func TestSessionPollRefreshesOnDemandMediaState(t *testing.T) {
t.Fatalf("updated=%#v err=%v", updated, err)
}
}
@@ -41,3 +41,4 @@ func ConfigureReadyProfiles(ctx context.Context, actor identity.Principal, resul
}
return service.ConfigureProfiles(ctx, actor, result)
}
+35 -1
View File
@@ -24,6 +24,32 @@ func NewService(store Store, process mediamtx.Process, controller mediamtx.Contr
return &Service{store: store, process: process, controller: controller, profile: admission.VerifiedProfile, credential: device.ReadRTSPCredential, now: time.Now}
}
// Restore recreates desired routes after MediaMTX starts with its base config.
// Individual route failures are persisted as safe business states and do not
// prevent the Sense management plane from starting.
func (s *Service) Restore(ctx context.Context) error {
items, err := s.store.List(ctx)
if err != nil {
return err
}
for _, route := range items {
if route.Desired != "running" {
continue
}
if _, reconcileErr := s.Reconcile(ctx, identity.Principal{}, route.ID); reconcileErr != nil {
route.Actual = "apply_failed"
route.Detail = "媒体路径恢复失败,请检查视频服务"
route.Readers = 0
route.Version++
route.UpdatedAt = s.now().UTC()
if saveErr := s.store.Save(ctx, route); saveErr != nil {
return saveErr
}
}
}
return nil
}
func (s *Service) ConfigureProfiles(ctx context.Context, actor identity.Principal, result admission.Result) admission.MediaOutcome {
configured := 0
ready := 0
@@ -108,6 +134,10 @@ func (s *Service) Reconcile(ctx context.Context, actor identity.Principal, id st
if err != nil {
route.Actual = "unconverged"
route.Detail = "尚未取得媒体状态"
} else if !status.Exists {
route.Actual = "apply_failed"
route.Detail = "媒体路径不存在,请重新对账"
route.Readers = 0
} else if status.Ready {
route.Actual = "ready"
route.Detail = "上游拉流正常"
@@ -142,7 +172,10 @@ func (s *Service) Refresh(ctx context.Context, id string) (Route, error) {
}
actual := "waiting"
detail := "等待播放器连接并按需拉流"
if status.Ready {
if !status.Exists {
actual = "apply_failed"
detail = "媒体路径不存在,请重新对账"
} else if status.Ready {
actual = "ready"
detail = "上游拉流正常"
}
@@ -198,3 +231,4 @@ func safe(value string) string {
return '_'
}, value)
}
+29 -2
View File
@@ -53,8 +53,9 @@ func (f fakeController) Status(context.Context, string) (mediamtx.PathStatus, er
return mediamtx.PathStatus{}, errors.New("timeout")
}
if !f.status.Ready {
return mediamtx.PathStatus{Ready: true, Readers: 2}, nil
return mediamtx.PathStatus{Exists: true, Ready: true, Readers: 2}, nil
}
f.status.Exists = true
return f.status, nil
}
@@ -155,7 +156,7 @@ func TestRefreshTracksOnDemandReaderWithoutReapplyingRoute(t *testing.T) {
if err := store.Save(context.Background(), route); err != nil {
t.Fatal(err)
}
service := NewService(store, &fakeProcess{}, refreshController{status: mediamtx.PathStatus{Name: route.Path, Ready: true, Readers: 1}})
service := NewService(store, &fakeProcess{}, refreshController{status: mediamtx.PathStatus{Name: route.Path, Exists: true, Ready: true, Readers: 1}})
result, err := service.Refresh(context.Background(), route.ID)
if err != nil || result.Actual != "ready" || result.Readers != 1 || result.Detail != "上游拉流正常" {
t.Fatalf("result=%#v err=%v", result, err)
@@ -166,4 +167,30 @@ func TestRefreshTracksOnDemandReaderWithoutReapplyingRoute(t *testing.T) {
}
}
func TestRefreshReportsMissingPathInsteadOfWaiting(t *testing.T) {
store := NewMemoryStore()
route := Route{ID: "device:main", Path: "sense_device_main", Desired: "running", Actual: "waiting", Version: 1}
if err := store.Save(context.Background(), route); err != nil {
t.Fatal(err)
}
service := NewService(store, &fakeProcess{}, refreshController{status: mediamtx.PathStatus{Name: route.Path, Exists: false}})
result, err := service.Refresh(context.Background(), route.ID)
if err != nil || result.Actual != "apply_failed" || !strings.Contains(result.Detail, "不存在") {
t.Fatalf("result=%#v err=%v", result, err)
}
}
func TestRestoreReconcilesDesiredRoutes(t *testing.T) {
process := &fakeProcess{}
service, route := preparedService(t, process, fakeController{})
if err := service.Restore(context.Background()); err != nil {
t.Fatal(err)
}
restored, err := service.store.Get(context.Background(), route.ID)
if err != nil || !process.State().Running || restored.Actual != "ready" {
t.Fatalf("restored=%#v process=%#v err=%v", restored, process.State(), err)
}
}
func rtspReady() rtsp.Result { return rtsp.Result{Status: "ready"} }
@@ -26,3 +26,4 @@ func init() {
return nil
})
}
+1
View File
@@ -25,3 +25,4 @@ func init() {
return nil
})
}
+4 -1
View File
@@ -18,7 +18,9 @@ func init() {
process := mediamtx.NewSupervisor(os.Getenv("SENSE_MEDIAMTX_BINARY"), os.Getenv("SENSE_MEDIAMTX_CONFIG"), 3)
controller := mediamtx.NewHTTPController(valueOr("SENSE_MEDIAMTX_API", "http://127.0.0.1:9997"))
app.RegisterMigration(platform.Migration{Version: 2026081203, Name: "sense_media", SQL: media.MigrationSQL})
media.NewModule(media.NewService(store, process, controller)).Register(app)
service := media.NewService(store, process, controller)
media.NewModule(service).Register(app)
app.RegisterStartup(service.Restore)
return nil
})
}
@@ -28,3 +30,4 @@ func valueOr(key, fallback string) string {
}
return fallback
}
+4
View File
@@ -47,6 +47,9 @@ func Run() error {
if err := app.ApplyMigrations(context.Background()); err != nil {
return err
}
if err := app.Start(context.Background()); err != nil {
return fmt.Errorf("start Sense modules: %w", err)
}
server := &http.Server{
Addr: cfg.HTTPAddress,
@@ -77,3 +80,4 @@ func Run() error {
return serveErr
}
}
+16
View File
@@ -1,6 +1,7 @@
package platform
import (
"context"
"database/sql"
"io/fs"
"log/slog"
@@ -17,6 +18,20 @@ type App struct {
logger *slog.Logger
mux *http.ServeMux
migrations []Migration
startups []func(context.Context) error
}
func (a *App) RegisterStartup(startup func(context.Context) error) {
a.startups = append(a.startups, startup)
}
func (a *App) Start(ctx context.Context) error {
for _, startup := range a.startups {
if err := startup(ctx); err != nil {
return err
}
}
return nil
}
func NewApp(cfg Config, database *sql.DB, logger *slog.Logger) *App {
@@ -101,3 +116,4 @@ func requestSecurityHeaders(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
@@ -12,3 +12,4 @@ const playable=computed(()=>Boolean(props.playerUrl)&&['waiting','ready'].includ
const title=computed(()=>({stopped:'视频已停止',process_failed:'视频服务未启动',apply_failed:'视频配置失败',unconverged:'视频状态未同步',waiting:'正在等待视频',expired:'播放会话已过期',offline:'视频已断开'})[props.state]||'暂时无法播放')
</script>
<style scoped>.stream-player{position:relative;width:100%;aspect-ratio:16/9;overflow:hidden;border-radius:4px;background:#101419}.stream-player iframe{width:100%;height:100%;border:0}.player-state{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:#c9cdd4}.player-state strong{color:#fff;font-size:18px}.player-state span{max-width:70%;text-align:center;font-size:13px}</style>
@@ -52,3 +52,4 @@ function useAddress(value){form.address=value;discoveryDialog.value=false}
onMounted(loadDevices)
</script>
<style scoped>.admission-form{margin-top:18px}.field-hint{color:#86909c;font-size:12px;line-height:1.5}.result-header{display:flex;align-items:center;justify-content:space-between}.media-result{margin-bottom:16px}</style>
@@ -78,3 +78,4 @@ onMounted(load)
<style scoped>
.credential-form { margin-top: 20px; }
</style>
@@ -17,3 +17,4 @@ async function retry(){if(!selectedRoute.value){ElMessage.info('请先选择视
onMounted(load);onBeforeUnmount(()=>clearInterval(timer.value))
</script>
<style scoped>.player-header{display:flex;align-items:center;justify-content:space-between}.option-detail{float:right;color:#86909c;font-size:12px}</style>
+5 -4
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Architecture-and-Code-Map
wiki_url: https://git.ilapage.cn/ila/yovision/wiki/Architecture-and-Code-Map.-
wiki_revision: a92e032c9512f9a3ea80e0867d35a8798e3a4a5d
synchronized_at: 2026-08-13T07:24:06Z
wiki_revision: e6bb3132a752cd8036cab29429cbf3f49e85bfbf
synchronized_at: 2026-08-13T14:06:00Z
<!-- gitea-wiki-mirror:end -->
# 架构与代码地图
@@ -102,8 +102,8 @@ Sense 后端功能以 `Sense/server/app/sense/` 为根,并通过 `Sense/server
- `identity/`:Sense 独立账户、bcrypt 密码、会话、四角色 RBAC 与统一审计;签发者和受众只属于 Sense。
- `device/`:Device 台账、状态、分页和 AES-256-GCM 凭据保险箱;ONVIF 与 RTSP 凭据可分离或显式复用,读取模型只返回两组凭据是否已配置。
- `adapters/onvif/`、`adapters/rtsp/`、`admission/`:获准网卡上的受控发现、手工 ONVIF 接入、Media 服务发现、Basic/Digest 认证、Profile/StreamUri 读取和 RTSP 验证。跨主机 Media 地址固定回用户已授权的 Device Service origin;跨主机 RTSP URI 只替换为授权主机并保留报告端口与路径。接入结果和脱敏 Profile 持久化到 PostgreSQL,重启后可恢复。
- `adapters/mediamtx/`、`media/`:外部 MediaMTX 进程所有权、localhost Control API、媒体期望态与实际态对账;接入验证出可用 Profile 后自动按 Device/Profile 幂等建立并对账媒体路径。
- `liveview/`:绑定当前用户、最长两分钟的单路播放会话;列表投影设备名称、位置、码流名称与用途,只在内部保留 ID,不暴露源 URI 或摄像机秘密。`waiting` 会话立即加载播放器以触发 MediaMTX 按需拉流,会话轮询只读刷新媒体实际状态。播放器包装页仅允许被 Sense 同源页面嵌入(`SAMEORIGIN` 与 `frame-ancestors 'self'`),其他页面继续使用全局 `DENY`。
- `adapters/mediamtx/`、`media/`:外部 MediaMTX 进程所有权、localhost Control API、媒体期望态与实际态对账;接入验证出可用 Profile 后自动按 Device/Profile 幂等建立并对账媒体路径。首次路径使用 add、已有路径使用 replace,控制 API 启动竞态在限定时间内重试;Sense 完成数据库迁移后自动恢复 `desired=running` 路径。路径不存在必须报告配置失败,不能伪装为 waiting。
- `liveview/`:绑定当前用户、最长两分钟的单路播放会话;列表投影设备名称、位置、码流名称与用途,只在内部保留 ID,不暴露源 URI 或摄像机秘密。`waiting` 会话立即加载播放器以触发 MediaMTX 按需拉流,会话轮询只读刷新媒体实际状态。播放器包装页仅允许被 Sense 同源页面嵌入(`SAMEORIGIN` 与 `frame-ancestors 'self'`),其他页面继续使用全局 `DENY`。iframe 导航使用有效 Sense 会话 Cookie、媒体读取权限及同源 iframe Fetch Metadata 认证,不依赖浏览器导航无法附加的 `X-Product` 请求头;普通 API 仍要求产品头。
- `area/`:归一化多边形/方向警戒线、不可变版本、并发版本校验和分辨率变化后的重新校准。
前端在 `Sense/ui/src/{api,views,router/modules,components}/sense/` 使用对应模块;通用页面复用 Element Plus 表单、表格、分页、Dialog、Tag 和应用容器,只为播放器与区域画布新增局部业务组件。项目内 `identity.RecordAudit`、`device.ReadRTSPCredential`、`device.Describe`、`admission.VerifiedProfile`、`media.PlaybackRoute` 和 `area.ExportCurrent` 是窄适配端口,不是跨项目契约。
@@ -124,3 +124,4 @@ Sense 后端功能以 `Sense/server/app/sense/` 为根,并通过 `Sense/server
Event 写入、幂等 Receipt、规则评估和 Alert 创建/关联处于同一数据库事务;规则或关联失败时不保留半成品 Event。一个 Event 可匹配多个规则,一个未关闭 Alert 可聚合相同规则与地点的多个 Event。
<!-- bell-mvp:end -->
+5 -4
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Business-Rules-and-Glossary
wiki_url: https://git.ilapage.cn/ila/yovision/wiki/Business-Rules-and-Glossary.-
wiki_revision: 0790c5444ac4541f32e69a7d2b69fc52e97c0e49
synchronized_at: 2026-08-13T04:16:00Z
wiki_revision: 06b68d16bf907decdaf85a813d417896f7920f4c
synchronized_at: 2026-08-13T14:06:00Z
<!-- gitea-wiki-mirror:end -->
# 业务规则与术语
@@ -76,9 +76,9 @@ synchronized_at: 2026-08-13T04:16:00Z
- **摄像机凭据**:ONVIF 与 RTSP 可使用不同账号,也可显式复用;两组均只写不读,使用仓库外 32 字节密钥分别加密。密码不得进入 URL、日志、审计、工单或响应。
- **受控发现**:ONVIF Discovery 默认关闭,只有显式设置获准本机 IP 才能发送发现;不得扫描未授权网段。
- **Profile**:主辅码流按分辨率分类并使用 RTSP 凭据分别验证;脱敏 Stream URI、验证状态和时间持久化,重启后保留。至少一个 Profile 验证成功后 Device 进入 `active`;认证失败、不可达、超时与校时问题使用可定位状态。
- **自动媒体路径**:接入检查中每个验证成功的 Profile 都按 Device/Profile 幂等建立并立即对账媒体路径;MediaMTX 不可用不回滚摄像机接入,接入结果记录“需要处理”并引导到视频服务排错。
- **自动媒体路径**:接入检查中每个验证成功的 Profile 都按 Device/Profile 幂等建立并立即对账媒体路径;首次配置使用 MediaMTX add、已有配置使用 replace,Sense 启动时从数据库恢复所有 `desired=running` 路径;路径不存在属于配置失败,不属于等待拉流。MediaMTX 不可用不回滚摄像机接入,接入结果记录“需要处理”并引导到视频服务排错。
- **MediaMTX**:保持外部进程。Sense 只停止自己启动并持有句柄的进程,最多自动重启三次;摄像机凭据只在 localhost 控制请求中瞬时组装,不持久化、不返回。
- **播放会话**:由当前 Sense 用户创建,最长两分钟;实时监看以设备名称、位置和主/子码流等业务标签供用户选择,内部 ID 只用于系统关联;`waiting` 表示等待第一个播放器触发按需拉流,不是播放失败,播放器连接后会话轮询刷新为实际状态;设备分页和媒体路径不以 16 路作为硬上限,页面一次只打开一路流。
- **播放会话**:由当前 Sense 用户创建,最长两分钟;实时监看以设备名称、位置和主/子码流等业务标签供用户选择,内部 ID 只用于系统关联;`waiting` 表示等待第一个播放器触发按需拉流,不是播放失败,播放器连接后会话轮询刷新为实际状态;播放器导航必须携带有效 Sense 会话 Cookie,且 Fetch Metadata 必须表明是同源 iframe,普通 API 的 `X-Product` 边界不变;设备分页和媒体路径不以 16 路作为硬上限,页面一次只打开一路流。
- **区域版本**:坐标为 0..1 归一化值,并绑定 Device、Profile、宽高。每次发布或停用形成新版本;范围、点数、自交、退化、方向和期望版本由后端校验。Profile 分辨率变化后旧版本必须标记为需要重新校准。
<!-- sense-mvp:end -->
@@ -97,3 +97,4 @@ synchronized_at: 2026-08-13T04:16:00Z
- **close**:只有处置人或管理员可以完成;必须选择“确认有危险、误报、现场正常、无法确认”之一,可附备注。相同重复请求幂等,其他改变结果的请求被拒绝。
- **审计事实**:成功生命周期事实只追加;失败、重复和拒绝尝试写入安全审计,但不记录令牌、密码或连接密钥。
<!-- bell-mvp:end -->
@@ -171,3 +171,4 @@ Get-FileHash .\Sense\dist\sense-windows-amd64.zip -Algorithm SHA256
解压后运行 `start-sense.bat demo` 可做内存模式临时预览。生产配置可写入运行目录的 `config\sense.env`,也可通过 Windows 进程环境注入;非空进程环境变量优先,启动器只读取 `SENSE_*` 键且不打印配置值。运行 `start-sense.bat check` 可在不连接数据库、不启动服务的情况下检查必填配置,然后用 `start-sense.bat` 启动生产模式。包内不含 PostgreSQL、MediaMTX、系统服务、客户数据或秘密,真实 `sense.env` 不得提交或重新打入交付 ZIP。
<!-- sense-windows-package:end -->
+5 -3
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Troubleshooting
wiki_url: https://git.ilapage.cn/ila/yovision/wiki/Troubleshooting
wiki_revision: e526f43f9f1b627202091f07eb3538ceba511662
synchronized_at: 2026-08-13T07:24:06Z
wiki_revision: b70e92180546609cb9b3b05b2c13c1a49676c03b
synchronized_at: 2026-08-13T14:05:00Z
<!-- gitea-wiki-mirror:end -->
# 故障排查
@@ -55,7 +55,8 @@ synchronized_at: 2026-08-13T07:24:06Z
| 接入成功但提示“媒体服务未就绪” / `process_failed` | 接入资料和 Profile 已保存,实时监看路径也已建立;检查仓库外 `SENSE_MEDIAMTX_BINARY`、基础配置和进程退出原因,修复后到视频服务重新对账。达到三次重启上限后需人工处理。 |
| `apply_failed` / `unconverged` | 检查 localhost Control API 是否启用并为 v3;确认媒体路径和外部进程状态。 |
| 实时监看没有设备 | 先在视频接入完成一次检查;系统会自动建立媒体路径。若已接入仍为空,检查接入结果的媒体状态和视频服务对账。 |
| 实时监看提示“127.0.0.1 拒绝了我们的连接请求” | 先确认播放器接口响应头;该接口必须是 `X-Frame-Options: SAMEORIGIN` 且 CSP 包含 `frame-ancestors 'self'`,普通页面仍应为 `DENY`。旧运行包会因全局 `DENY` 阻止同源播放器 iframe,需重新打包并重启 Sense。 |
| 实时监看提示“127.0.0.1 拒绝了我们的连接请求” | 先确认播放器接口响应头;该接口必须是 `X-Frame-Options: SAMEORIGIN` 且 CSP 包含 `frame-ancestors 'self'`,普通页面仍应为 `DENY`。播放器接口还必须允许不带 `X-Product`、但带有效 Sense Cookie 和同源 iframe Fetch Metadata 的浏览器导航;普通 API 仍应拒绝缺少产品头的请求。旧运行包会在响应头或认证中间件处阻止 iframe,需重新打包并重启 Sense。 |
| 播放器提示 `stream not found` | MediaMTX 中没有对应配置路径。检查 Control API 配置列表是否包含 Sense 路径;新版本会在 Sense 启动时自动恢复 `desired=running` 路径,并在控制端口尚未就绪时限时重试。路径缺失必须显示配置失败,不能仅显示等待拉流。 |
| 实时监看持续“等待拉流” | `waiting` 会话应立即加载播放器以触发按需拉流。若连接后仍等待,检查 MediaMTX 路径 readers 和源状态;`401 Unauthorized` 表示摄像机拒绝当前 RTSP 凭据,应在设备管理修正凭据后重新执行视频接入,不能把凭据写入日志或地址。 |
| 画面等待、断开或会话过期 | 查看实时监看中的业务设备名和码流状态;会话轮询会只读刷新 MediaMTX 实际状态,无需手工对账。播放会话最长两分钟。 |
| 区域提示需要重新校准 | Profile 分辨率已变化,按新画面重新绘制并发布新版本,不能静默复用旧坐标。 |
@@ -75,3 +76,4 @@ synchronized_at: 2026-08-13T07:24:06Z
`demo` 只用于临时查看。生产数据持久性、真实设备和媒体链路不能用 demo 验证替代。
<!-- sense-windows-package:end -->
@@ -72,3 +72,4 @@ synchronized_at: 2026-08-13T03:46:29Z
- `688080c` 支持 ONVIF Digest Media 服务与安全地址归一化。
- `2a0b63c` 更新架构、验证与排错 Wiki 镜像。
@@ -69,3 +69,4 @@ synchronized_at: 2026-08-13T04:18:00Z
- `1a63264` 分离凭据、持久化 Profile 和真实地址归一化。
- `032f8c5` 更新长期 Wiki 镜像。
@@ -66,3 +66,4 @@ synchronized_at: 2026-08-13T04:40:00Z
- `b9f92dd` 自动媒体路径和业务化实时监看。
- `0f459f0` 更新长期 Wiki 镜像。
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Task-54-修复实时监看按需拉流循环等待
wiki_url: https://git.ilapage.cn/ila/yovision/wiki/Task-54-%E4%BF%AE%E5%A4%8D%E5%AE%9E%E6%97%B6%E7%9B%91%E7%9C%8B%E6%8C%89%E9%9C%80%E6%8B%89%E6%B5%81%E5%BE%AA%E7%8E%AF%E7%AD%89%E5%BE%85.-
wiki_revision: 19729dc49683e0ea30b951ec369ce2409ba52b2b
synchronized_at: 2026-08-13T07:24:36Z
wiki_revision: ff79f9dbc718ae570b01dace25304379124a99b4
synchronized_at: 2026-08-13T14:05:00Z
<!-- gitea-wiki-mirror:end -->
# 54 修复实时监看按需拉流循环等待
@@ -26,15 +26,21 @@ MediaMTX 使用按需拉流时,必须先有播放器读取路径才会连接
- 实时监看收到有效播放地址且状态为“等待拉流”或“可播放”时都加载播放器;“等待拉流”保留明确状态提示,同时触发 MediaMTX 按需连接。
- 会话查询通过只读媒体端口刷新控制器状态,把等待状态安全收敛为可播放或需要处理,不重新应用路径配置。
- 播放器包装接口覆盖全局嵌入策略为 `SAMEORIGIN`,并用 CSP `frame-ancestors 'self'` 限制为 Sense 同源页面;其他接口继续保持 `X-Frame-Options: DENY`。
- iframe 导航无法附加 API 客户端的 `X-Product` 头,因此播放器路由改用窄导航认证:有效 Sense 会话 Cookie、媒体读取权限、`Sec-Fetch-Site: same-origin`、`Sec-Fetch-Mode: navigate` 和 `Sec-Fetch-Dest: iframe` 必须同时满足。普通 API 的产品头要求保持不变。
- MediaMTX 路径首次配置使用 add,已存在时使用 replace;控制 API 刚启动尚未监听时限时等待。
- Sense 完成数据库迁移后自动恢复所有 `desired=running` 路径;路径不存在显式标记为配置失败,不再误报 waiting。
- 继续保持 `sourceOnDemand`,无人观看时不占用摄像机连接与转码资源。
- 真实环境验证过程中发现已保存的 RTSP 凭据被摄像机拒绝(401);已通过现有 Sense 接口使用本地已获授权配置修正运行数据,未把凭据写入仓库、工单、Wiki 或日志证据。
## 修改文件
- `Sense/server/app/sense/media/service.go`、`route_port.go`:增加只读状态刷新能力。
- `Sense/server/app/sense/media/service.go`、`route_port.go`:增加只读状态刷新、缺失状态和启动恢复能力。
- `Sense/server/app/sense/adapters/mediamtx/client.go`、`client_test.go`:实现 add/replace 幂等语义并等待控制 API 就绪。
- `Sense/server/cmd/sense/{modules_media.go,root.go}`、`internal/platform/app.go`:在迁移完成后执行媒体路径恢复。
- `Sense/server/app/sense/media/service_test.go`:验证刷新状态且不重复配置路径。
- `Sense/server/app/sense/liveview/service.go`:查询会话时刷新媒体状态。
- `Sense/server/app/sense/liveview/http.go`、`http_test.go`:允许并验证播放器包装页仅同源嵌入。
- `Sense/server/app/sense/identity/http.go`、`http_test.go`:增加并验证仅限同源 iframe 的 Cookie 导航认证,保留普通 API 产品边界。
- `Sense/server/app/sense/liveview/service_test.go`:验证等待状态收敛到可播放。
- `Sense/ui/src/components/sense/liveview/StreamPlayer.vue`:等待拉流时即加载播放器。
- Wiki 架构、业务规则与排错页面。
@@ -49,6 +55,9 @@ MediaMTX 使用按需拉流时,必须先有播放器读取路径才会连接
| 不重复应用路径配置 | 通过,单元测试验证刷新仅调用状态查询 |
| 不泄露摄像机凭据和源地址 | 通过 |
| 播放器可被 Sense 同源嵌入且其他页面仍禁止嵌入 | 通过,运行包接口响应头验证通过 |
| iframe 不带 `X-Product` 时仍能安全认证 | 通过,同源 iframe + 有效 Cookie 返回 200;跨站返回 401;普通 API 缺少产品头返回 401 |
| MediaMTX 冷启动后恢复 Sense 路径 | 通过,配置列表自动出现 2 条 `sourceOnDemand` 路径,无需手工对账 |
| 两条摄像机路径可实际解码 | 通过,主码流 H.264 1920×1080 + AAC,子码流 H.264,均收到媒体字节 |
## 测试
@@ -57,7 +66,10 @@ MediaMTX 使用按需拉流时,必须先有播放器读取路径才会连接
- `corepack pnpm build`:通过,存在 3 个既有 webpack 体积 warning。
- Go 1.26.5 Windows 打包:通过。
- 运行包响应头:播放器接口为 `SAMEORIGIN` 且包含 `frame-ancestors 'self'`;首页仍为 `DENY`。
- 真实媒体链路:MediaMTX `sourceReady=true`、`readers=1`、收到媒体字节且包含 2 个轨道;Sense 会话由 `waiting` 收敛为 `ready`。
- 运行包浏览器式认证:不带 `X-Product`、带有效 Cookie 和同源 iframe Fetch Metadata 的播放器请求返回 200;跨站播放器与缺少产品头的普通 API 均返回 401。
- 冷启动恢复:MediaMTX 配置列表自动包含两条 Sense `sourceOnDemand` 路径;运行态列表也存在两条路径。
- 真实媒体链路:主码流 H.264 1920×1080 + AAC,子码流 H.264;两条路径分别通过本机 RTSP 读取并收到媒体字节。
- 单元测试覆盖路径首次 add、已有 replace、控制 API 启动等待、启动恢复及缺失路径不误报 waiting。
- **未验证部分**:最终浏览器中的可视画面需要用户在当前浏览器验收;自动化已验证媒体源、读取者与会话状态收敛。
## 遗留问题
@@ -69,3 +81,6 @@ MediaMTX 使用按需拉流时,必须先有播放器读取路径才会连接
- `8d4e4c2` 修复实时监看按需拉流循环等待。
- `b3dfd23` 更新按需拉流长期 Wiki 镜像。
- `3696442` 允许播放器包装页仅被 Sense 同源嵌入。
- `8bf9a6d` 支持同源播放器导航认证并保持普通 API 产品边界。
- `d7cd3a5` 恢复 MediaMTX 按需路径并处理启动竞态。
+1
View File
@@ -150,3 +150,4 @@
}
]
}