Explorar el Código

feat(cockpit): 补齐视频会话匿名归属兼容接缝

Kazerin hace 3 semanas
padre
commit
32b2cf4ab8

+ 27 - 0
docs/video-session-anonymous-owner-20261110.sql

@@ -0,0 +1,27 @@
+-- cockpit-video-monitoring/01 — 基于维护者 2026-11-10 提供的实际 DDL。
+-- 原表 user_id int8 NOT NULL;保留原主键、ix_video_session_active、ix_video_session_expire。
+-- 仅生成,未对真实数据库执行。需先备份并核对目标环境;先迁移、后部署新代码。
+-- 一次性迁移:重复执行会失败并回滚,不用 IF NOT EXISTS 掩盖异构字段。
+BEGIN;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN anonymous_token_hash varchar(43) NULL;
+ALTER TABLE app_user.video_play_session
+    ALTER COLUMN user_id DROP NOT NULL;
+ALTER TABLE app_user.video_play_session
+    ADD CONSTRAINT video_session_owner_check CHECK (
+        (user_id IS NOT NULL AND anonymous_token_hash IS NULL)
+        OR (user_id IS NULL AND anonymous_token_hash IS NOT NULL
+            AND anonymous_token_hash ~ '^[A-Za-z0-9_-]{43}$')
+    );
+COMMENT ON COLUMN app_user.video_play_session.anonymous_token_hash
+    IS '匿名观看会话资源归属凭据的SHA-256摘要(Base64URL);不是实名,不存原始凭据';
+COMMIT;
+
+-- 回退须先停止匿名入口,并确认没有任何匿名会话行(含已停止行)。
+-- 不自动删除、伪造 user_id 或迁移历史数据;由维护者决定归档策略。
+-- 确认无匿名行后才可单独执行以下事务(不要与上面的升级事务一起执行):
+-- BEGIN;
+-- ALTER TABLE app_user.video_play_session ALTER COLUMN user_id SET NOT NULL;
+-- ALTER TABLE app_user.video_play_session DROP CONSTRAINT video_session_owner_check;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN anonymous_token_hash;
+-- COMMIT;

+ 43 - 0
docs/video-session-compatibility-20261110.md

@@ -0,0 +1,43 @@
+# 视频会话兼容准备(cockpit-video-monitoring/01)
+
+## 范围
+
+本票只扩展既有视频会话身份及资源归属接缝。管理端 Controller、路由、权限与前端页面不变,不发布驾驶舱视频 HTTP 接口,不增加云台租约或另一套会话/共享流业务。
+
+## 实际结构依据
+
+维护者在 2026-11-10 本次实施会话提供 `app_user.video_play_session` 的实际 DDL:
+
+- `session_id varchar(36)` 主键;`video_id varchar(64)`、`user_id int8`、`mode varchar(16)`、`status varchar(16)` 非空。
+- `stream_id varchar(200)`、`proxy_key varchar(300)`、`gb_device_id varchar(20)`、`gb_channel_id varchar(20)` 可空。
+- `create_time`、`last_seen` 为非空 `sys.timestamp`,默认 CURRENT_TIMESTAMP;`end_time` 可空。
+- `ix_video_session_active(video_id, mode, status)` 和 `ix_video_session_expire(status, last_seen)`;所贴定义无用户外键。
+
+不能用 Java 的 `Long` 类型推断可空。本票的[一次性迁移](<video-session-anonymous-owner-20261110.sql>)保留旧行/主键/索引,只放开 `user_id` 非空并新增匿名凭据摘要及互斥身份检查。**脚本未在真实数据库执行。必须先迁移、再部署依赖新列的代码。** 回退条件与不自动删数据的策略在脚本中说明。
+
+## 公开接缝
+
+- `start(id, range)`、`heartbeat(id)`、`stop(id)`、`control(id, input)` 继续依赖真实业务用户,旧 Controller 不改;旧用户不能通过这些方法管理匿名会话。
+- `startAnonymous(id, range)` 为服务端适配层创建独立会话,返回既有媒体字段、`sessionId`、`mode` 和只返回一次的 `sessionToken`。不是公开匿名路由,也不接收客户端伪造的用户 ID。
+- 匿名 `heartbeat(id, token)`、`stop(id, token)`、`control(id, token, input)` 校验独立资源归属;凭据不能跨会话使用。原始凭据由 SecureRandom 生成 256 位,不进入数据库/日志;仅存 SHA-256 Base64URL 摘要并常量时间比较。
+- 沿用同一张会话表、同一设备行锁、全部 ACTIVE LIVE 的共享计数及 PLAYBACK 占用。不按匿名/用户来源分割计数,不对其它观看者做通道 stop。
+- `requireAnonymousSession(id, token, videoId, mode)` 提供设备/模式/归属/120秒观看有效性的统一校验,不代替能力校验或云台互斥。匿名已停止/超时心跳和控制明确失败,正确归属的 stop 仍可幂等清理;旧接口的已停止心跳保留成功无操作语义。
+- 心跳与释放共用既有设备行锁,并在锁后重新读取;锁查询清除 MyBatis 会话级旧快照,过期回收在锁后重新核对 last_seen。会话登记失败先按锁内预先取得的共享计数补偿媒体,不在已中止的数据库事务中再查计数;清理失败明确告知未确认,不假报成功。
+- 凭据是持有者能力,不是实名;不证明媒体地址受保护,不替代后续内网访问边界、能力/设备映射或物理云台停止验收。
+
+## 离线验证记录
+
+- 基线离线 reactor `test-compile` 成功;核心新增接缝经历缺方法/行为失败 RED → 最小实现 GREEN,包含心跳/停止交错、过期扫描旧快照及事务中止后的媒体补偿反例。
+- 视频专项目前 **50 项通过,0 失败、0 错误、0 跳过**:[旧 HTTP/安全权限合同](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java>) 36 项,[匿名/旧用户与共享资源接缝](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java>) 14 项。
+- 旧 HTTP 测试使用真实 SecurityConfig、JWT 过滤、TokenService、方法权限、Controller 和 VideoDeviceService,无真实应用服务启动;Redis/DB/媒体为外部替身。共享计数用数据库返回字面夹具(3→2→1),没有重写业务计数算法,但也不证明真实 SQL/锁执行。
+- 完整管网 reactor 回归已执行;默认失败即停在 zksy-system。为收齐其余结果,又用 `-Dmaven.test.failure.ignore=true` 继续收集,**该次退出0不代表全绿**:zksy-system 256 项中 2 失败、1 错误;zksy-admin 735 项中 17 失败。失败涉及报警生命周期/过滤权限与驾驶舱事件/历史统计,非视频用例;这些测试及报警实现未被本票修改,未另执行原始基点以作严格归因。保留原结果,不扩本票修复范围。
+- 数据库替身不等于 Kingbase 的真实 SQL、行锁、事务或迁移验证;媒体替身不等于真实播放或设备停止。脚本未执行,后续现场验收仍需迁移/旧新会话并存实证。
+- 双轴代码审查以用户确认的 `4c4bc50a8e6b73eb83ecfe61cffaba3c5a988a61` 为基点,仅审本票独立提交,结论在收尾追加。
+- 按用户本次明确授权,仅执行离线 Java 编译/测试;因项目规则,跳过应用 build/debug、浏览器调试、服务启停、真实迁移和设备操作。
+
+复现命令(仓库根目录,均不启动服务;源码工具保留 mtime 时需先刷新本票改动文件的 mtime,避免旧 compiler 增量缓存漏编):
+
+```bash
+JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 mvn -o -pl pipe-network-service/zksy-admin -am -Dtest=VideoSessionCompatibilityTest,VideoDeviceCompatibilityTest -Dsurefire.failIfNoSpecifiedTests=false test
+JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 mvn -o -pl pipe-network-service/zksy-admin -am test
+```

+ 261 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java

@@ -0,0 +1,261 @@
+package com.zksy.web.controller.cockpit;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.video.*;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.common.exception.ServiceException;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.BeanUtils;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import java.util.*;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/** Public service contract. Persistence and media are boundary substitutes, not a database integration test. */
+class VideoSessionCompatibilityTest {
+    private final VideoSessionMapper sessions = mock(VideoSessionMapper.class);
+    private final EquipmentVideoBindingMapper bindings = mock(EquipmentVideoBindingMapper.class);
+    private final VideoCollectorClient media = mock(VideoCollectorClient.class);
+    private final Map<String, VideoSession> rows = new HashMap<>();
+    private VideoDeviceService service;
+    private static final String DEVICE = "camera-1";
+    private static final String LIVE_START = "/api/play/start/34020000001320000001/34020000001320000002";
+    private static final String LIVE_STOP = "/api/play/stop/34020000001320000001/34020000001320000002";
+
+    @BeforeEach void setUp() {
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
+        VideoDeviceRecord device = new VideoDeviceRecord();
+        device.setEquipmentId(DEVICE);
+        device.setSourceType("GB28181");
+        device.setGbDeviceId("34020000001320000001");
+        device.setGbChannelId("34020000001320000002");
+        when(bindings.find(DEVICE)).thenReturn(device);
+        when(media.get(eq(LIVE_START), anyMap())).thenReturn(Map.of("stream", "live-1", "flv", "https://media.invalid/live.flv"));
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = copy(call.getArgument(0));
+            rows.put(row.getSessionId(), row);
+            return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(call -> copy(rows.get(call.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = copy(call.getArgument(0));
+            rows.put(row.getSessionId(), row);
+            return 1;
+        });
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings);
+    }
+
+    @AfterEach void clearIdentity() { SecurityContextHolder.clearContext(); }
+
+    @Test void anonymousViewersHaveIndependentCredentialsAndCannotMaintainEachOther() {
+        Map<String, Object> first = service.startAnonymous(DEVICE, null);
+        Map<String, Object> second = service.startAnonymous(DEVICE, null);
+        String id = (String) first.get("sessionId");
+        String token = (String) first.get("sessionToken");
+        assertEquals("LIVE", first.get("mode"));
+        assertEquals("https://media.invalid/live.flv", first.get("flv"));
+        assertNotEquals(token, second.get("sessionToken"));
+        assertNotEquals(id, token);
+        assertDoesNotThrow(() -> service.heartbeat(id, token));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, (String) second.get("sessionToken")));
+        assertThrows(ServiceException.class, () -> service.stop(id, (String) second.get("sessionToken")));
+        assertThrows(ServiceException.class, () -> service.stop(id, null));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void playbackControlRequiresItsOwnAnonymousCredentialAndActivePlayback() {
+        when(media.get(eq("/api/playback/start"), anyMap())).thenReturn(Map.of("stream", "record-1", "flv", "https://media.invalid/record.flv"));
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime("2026-11-10 10:00:00");
+        range.setEndTime("2026-11-10 10:10:00");
+        Map<String, Object> playback = service.startAnonymous(DEVICE, range);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) playback.get("sessionId"), token = (String) playback.get("sessionToken");
+        VideoRequests.Control pause = new VideoRequests.Control();
+        pause.setAction("pause");
+        assertThrows(ServiceException.class, () -> service.control(id, (String) live.get("sessionToken"), pause));
+        assertThrows(ServiceException.class, () -> service.control((String) live.get("sessionId"), (String) live.get("sessionToken"), pause));
+        verify(media, never()).get(eq("/api/playback/pause/record-1"), anyMap());
+        service.control(id, token, pause);
+        verify(media).get(eq("/api/playback/pause/record-1"), anyMap());
+        service.stop(id, token);
+        assertThrows(ServiceException.class, () -> service.control(id, token, pause));
+    }
+
+    @Test void anonymousValidityChecksDeviceModeAndWatchingTimeoutWithoutPreventingCleanup() {
+        Clock clock = mock(Clock.class);
+        when(clock.getZone()).thenReturn(ZoneOffset.ofHours(8));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:00:00Z"));
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings, clock);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, "another-device", "LIVE"));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, DEVICE, "PLAYBACK"));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:00Z"));
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:01Z"));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        assertDoesNotThrow(() -> service.stop(id, token));
+        assertDoesNotThrow(() -> service.stop(id, token));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void aRenewedWatcherIsNotStoppedByAnOlderExpiryScan() {
+        Clock clock = mock(Clock.class);
+        when(clock.getZone()).thenReturn(ZoneOffset.ofHours(8));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:00:00Z"));
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings, clock);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        // The storage boundary returns an old scan snapshot, while selectById returns current data.
+        VideoSession snapshot = copy(rows.get(id));
+        when(sessions.selectList(any())).thenReturn(List.of(snapshot));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:01:59Z"));
+        service.heartbeat(id, token);
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:01Z"));
+        service.expireSessions();
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false})
+    void heartbeatCannotResurrectAWatcherStoppedAfterItsInitialRead(boolean anonymous) {
+        login(41);
+        Map<String, Object> live = anonymous ? service.startAnonymous(DEVICE, null) : service.start(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        java.util.concurrent.atomic.AtomicBoolean race = new java.util.concurrent.atomic.AtomicBoolean(true);
+        when(sessions.selectById(id)).thenAnswer(call -> {
+            VideoSession snapshot = copy(rows.get(id));
+            if (race.getAndSet(false)) {
+                if (anonymous) service.stop(id, token); else service.stop(id);
+            }
+            return snapshot;
+        });
+        if (anonymous) {
+            assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+            service.stop(id, token);
+        } else {
+            assertDoesNotThrow(() -> service.heartbeat(id)); // legacy stopped heartbeat remains an idempotent no-op
+            service.stop(id);
+        }
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(longs = {0, 1})
+    void failedRegistrationCompensatesWithoutStoppingAnExistingViewer(long existingViewers) {
+        if (existingViewers > 0) { login(41); service.start(DEVICE, null); }
+        // Literal database results: no viewer, or the one existing business-user viewer.
+        when(sessions.selectCount(any())).thenReturn(existingViewers);
+        when(sessions.insert(any(VideoSession.class))).thenReturn(0);
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(media, times(existingViewers == 0 ? 1 : 0)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void mixedUserAndAnonymousViewersReleaseOnlyTheLastSharedLiveStream() {
+        login(41);
+        Map<String, Object> legacy = service.start(DEVICE, null);
+        assertFalse(legacy.containsKey("sessionToken"));
+        SecurityContextHolder.clearContext();
+        Map<String, Object> first = service.startAnonymous(DEVICE, null);
+        Map<String, Object> second = service.startAnonymous(DEVICE, null);
+        String oldId = (String) legacy.get("sessionId"), firstId = (String) first.get("sessionId"), secondId = (String) second.get("sessionId");
+        String firstToken = (String) first.get("sessionToken"), secondToken = (String) second.get("sessionToken");
+        // A fresh service instance must use persisted ownership, not an in-process token registry.
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions, mock(EquipmentBaseService.class), bindings);
+        assertThrows(ServiceException.class, () -> service.stop(oldId, firstToken));
+        login(41);
+        assertThrows(ServiceException.class, () -> service.stop(firstId));
+        assertThrows(ServiceException.class, () -> service.heartbeat(firstId));
+        // External DB boundary fixtures for 3 -> 2 -> 1 viewers. No shared-count algorithm is copied here.
+        when(sessions.selectCount(any())).thenReturn(2L, 1L, 0L);
+        service.stop(firstId, firstToken);
+        service.heartbeat(secondId, secondToken);
+        service.heartbeat(oldId);
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+        service.stop(oldId);
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+        service.stop(secondId, secondToken);
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void playbackOccupiedByAnotherSourceIsRejectedWithoutStartingOrStoppingIt() {
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime("2026-11-10 10:00:00"); range.setEndTime("2026-11-10 10:10:00");
+        when(sessions.selectCount(any())).thenReturn(1L); // one ACTIVE playback in the storage boundary
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, range));
+        login(41);
+        assertThrows(ServiceException.class, () -> service.start(DEVICE, range));
+        verifyNoInteractions(media);
+    }
+
+    @Test void mediaStopFailureRemainsAnErrorAndCanBeRetried() {
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        when(media.get(eq(LIVE_STOP), anyMap())).thenThrow(new ServiceException("媒体不可用"));
+        assertThrows(ServiceException.class, () -> service.stop(id, token));
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        when(media.get(eq(LIVE_STOP), anyMap())).thenReturn(Map.of());
+        service.stop(id, token);
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+    }
+
+    @Test void failedRegistrationAndFailedCompensationExplicitlyReportUnconfirmedCleanup() {
+        when(sessions.insert(any(VideoSession.class))).thenThrow(new IllegalStateException("database unavailable"));
+        when(media.get(eq(LIVE_STOP), anyMap())).thenThrow(new ServiceException("media unavailable"));
+        ServiceException failure = assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        assertEquals("播放会话登记失败,媒体清理未确认,请联系管理员", failure.getMessage());
+    }
+
+    @Test void missingLoginIsRejectedBeforeStartingMediaThroughTheLegacySeam() {
+        SecurityContextHolder.clearContext();
+        assertThrows(ServiceException.class, () -> service.start(DEVICE, null));
+        verifyNoInteractions(media);
+    }
+
+    @Test void databaseAbortingTheInsertDoesNotPreventMediaCompensation() {
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            // PostgreSQL/Kingbase rejects further queries in an aborted transaction.
+            when(sessions.selectCount(any())).thenThrow(new IllegalStateException("transaction is aborted"));
+            throw new IllegalStateException("insert failed");
+        });
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    private static VideoSession copy(VideoSession row) {
+        if (row == null) return null;
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(row, copy);
+        return copy;
+    }
+
+    private static void login(long userId) {
+        LoginUser user = new LoginUser();
+        user.setUserId(userId);
+        SecurityContextHolder.getContext().setAuthentication(
+                new UsernamePasswordAuthenticationToken(user, null, List.of()));
+    }
+}

+ 451 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java

@@ -0,0 +1,451 @@
+package com.zksy.web.controller.video;
+
+import com.alibaba.fastjson2.JSON;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.base.video.VideoSession;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.common.core.redis.RedisCache;
+import com.zksy.framework.config.ResourcesConfig;
+import com.zksy.framework.config.SecurityConfig;
+import com.zksy.framework.config.properties.PermitAllUrlProperties;
+import com.zksy.framework.security.filter.JwtAuthenticationTokenFilter;
+import com.zksy.framework.security.handle.AuthenticationEntryPointImpl;
+import com.zksy.framework.security.handle.CockpitAuthenticationEntryPoint;
+import com.zksy.framework.security.handle.LogoutSuccessHandlerImpl;
+import com.zksy.framework.web.exception.GlobalExceptionHandler;
+import com.zksy.framework.web.service.PermissionService;
+import com.zksy.framework.web.service.TokenService;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+
+import javax.servlet.Filter;
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * The agreed seam is the existing /api/video HTTP contract, not controller metadata.
+ * Uses the real controller, SecurityConfig, method authorization, PermissionService,
+ * JWT filter, TokenService, RedisCache, exception handlers and VideoDeviceService.
+ * Only database/media boundaries and RedisTemplate storage are replaced in memory.
+ * No preinstalled Authentication, security-test request postprocessor, service stub,
+ * private-method assertion or source-text assertion stands in for those behaviors.
+ *
+ * <p>This is an isolated single-session contract test: it does not verify SQL,
+ * transaction locking, scheduled expiry or old/cockpit mixed-session reference counts.
+ * The mapper's count is zero because each fixture has no competing session. The
+ * service is constructed by a bean factory, not component-scanned: its scheduling
+ * configuration is intentionally not bootstrapped. No Boot application, Nacos,
+ * servlet server, database connection or media/Redis network client is started.
+ */
+class VideoDeviceCompatibilityTest {
+    private static final long OWNER = 41L;
+    private static final long OTHER_USER = 42L;
+    private static final String DEVICE_ID = "legacy-video-01";
+    private static final String GB_DEVICE = "34020000002000000001";
+    private static final String GB_CHANNEL = "34020000001320000001";
+    private static final String STREAM = "legacy_stream_001";
+    private static final String MEDIA_URL = "https://media.invalid/legacy.flv";
+    private static final String START_TIME = "2026-10-01 10:00:00";
+    private static final String END_TIME = "2026-10-01 10:30:00";
+    private static final String RANGE_JSON = "{\"startTime\":\"2026-10-01 10:00:00\","
+            + "\"endTime\":\"2026-10-01 10:30:00\"}";
+    private static final String CONTROL_JSON = "{\"action\":\"pause\"}";
+
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private TokenService tokens;
+    private EquipmentBaseMapper devices;
+    private EquipmentVideoBindingMapper bindings;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient collector;
+
+    @BeforeEach
+    void setUp() {
+        SecurityContextHolder.clearContext();
+        RequestContextHolder.resetRequestAttributes();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-test", Map.of(
+                "token.header", "Authorization",
+                "token.secret", "dmlkZW8tY29tcGF0aWJpbGl0eS10ZXN0LW9ubHktbm90LWEtcHJvZHVjdGlvbi1zZWNyZXQtdmlkZW8tY29tcGF0aWJpbGl0eS10ZXN0",
+                "token.expireTime", "60")));
+        context.register(HttpContractConfiguration.class);
+        context.refresh();
+        // Mount the actual FilterChainProxy; spring-security-test is not required.
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        tokens = context.getBean(TokenService.class);
+        devices = context.getBean(EquipmentBaseMapper.class);
+        bindings = context.getBean(EquipmentVideoBindingMapper.class);
+        sessions = context.getBean(VideoSessionMapper.class);
+        collector = context.getBean(VideoCollectorClient.class);
+
+        VideoDeviceRecord device = new VideoDeviceRecord();
+        device.setEquipmentId(DEVICE_ID);
+        device.setVideoId(DEVICE_ID);
+        device.setSourceType("GB28181");
+        device.setGbDeviceId(GB_DEVICE);
+        device.setGbChannelId(GB_CHANNEL);
+        when(bindings.find(DEVICE_ID)).thenReturn(device);
+        Map<String, Object> playback = Map.of("stream", STREAM, "url", MEDIA_URL,
+                "proxyKey", "internal-media-proxy-key");
+        when(collector.get("/api/play/start/" + GB_DEVICE + "/" + GB_CHANNEL, Map.of()))
+                .thenReturn(playback);
+        when(collector.get("/api/playback/start", rangeParameters())).thenReturn(playback);
+
+        Map<String, VideoSession> rows = new ConcurrentHashMap<>();
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(invocation -> {
+            VideoSession row = invocation.getArgument(0);
+            rows.put(row.getSessionId(), copy(row));
+            return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(invocation -> copy(rows.get(invocation.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(invocation -> {
+            VideoSession row = invocation.getArgument(0);
+            return rows.replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        when(sessions.selectCount(any())).thenReturn(0L);
+    }
+
+    @AfterEach
+    void tearDown() {
+        try {
+            if (context != null) {
+                context.close();
+            }
+        } finally {
+            SecurityContextHolder.clearContext();
+            RequestContextHolder.resetRequestAttributes();
+        }
+    }
+
+    @Test
+    void playPermissionStartsLiveWithTheLegacyResponseFields() throws Exception {
+        startSession(Operation.LIVE, token(OWNER, "video:device:play"));
+        verify(collector).get("/api/play/start/" + GB_DEVICE + "/" + GB_CHANNEL, Map.of());
+    }
+
+    @Test
+    void recordPermissionStartsPlaybackWithTheLegacyRangeFields() throws Exception {
+        startSession(Operation.PLAYBACK, token(OWNER, "video:device:record"));
+        verify(collector).get("/api/playback/start", rangeParameters());
+    }
+
+    @ParameterizedTest(name = "{0} rejects unrelated and empty permission sets")
+    @EnumSource(Operation.class)
+    void loggedInUsersWithoutTheRequiredPermissionAreRejectedBeforeBusinessAccess(Operation operation)
+            throws Exception {
+        for (String bearer : Arrays.asList(token(OWNER, "video:device:list"), token(OWNER))) {
+            perform(operation, "not-reached", bearer)
+                    .andExpect(status().isOk())
+                    .andExpect(jsonPath("$.code").value(403))
+                    .andExpect(jsonPath("$.msg").value("没有权限,请联系管理员授权"));
+        }
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} does not accept {1}")
+    @CsvSource({
+            "LIVE, video:device:record",
+            "PLAYBACK, video:device:play",
+            "CONTROL, video:device:play"
+    })
+    void playAndRecordPermissionsAreNotInterchangeableForStartAndControl(Operation operation, String permission)
+            throws Exception {
+        perform(operation, "not-reached", token(OWNER, permission))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.msg").value("没有权限,请联系管理员授权"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} on {1}: {2} allows only the session owner")
+    @CsvSource({
+            "HEARTBEAT, LIVE, video:device:play",
+            "HEARTBEAT, LIVE, video:device:record",
+            "HEARTBEAT, PLAYBACK, video:device:play",
+            "HEARTBEAT, PLAYBACK, video:device:record",
+            "STOP, LIVE, video:device:play",
+            "STOP, LIVE, video:device:record",
+            "STOP, PLAYBACK, video:device:play",
+            "STOP, PLAYBACK, video:device:record",
+            "CONTROL, PLAYBACK, video:device:record"
+    })
+    void sessionActionsKeepAnyPermissionSemanticsButStillRequireTheRealSessionOwner(
+            Operation operation, Operation start, String permission) throws Exception {
+        // Create ownership via HTTP and the JWT principal, never by seeding an owner in a service stub.
+        String sessionId = startSession(start, token(OWNER, "video:device:play", "video:device:record"));
+        clearInvocations(devices, bindings, sessions, collector);
+
+        perform(operation, sessionId, token(OTHER_USER, permission))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.msg").value("播放会话不存在或无权操作"));
+        verifyNoInteractions(devices, bindings, collector);
+        verify(sessions, never()).updateById(any(VideoSession.class));
+        verify(sessions, never()).lockVideo(anyString());
+
+        success(perform(operation, sessionId, token(OWNER, permission)));
+        if (operation == Operation.CONTROL) {
+            verify(collector).get("/api/playback/pause/" + STREAM, Map.of());
+        } else if (operation == Operation.STOP) {
+            String path = start == Operation.LIVE
+                    ? "/api/play/stop/" + GB_DEVICE + "/" + GB_CHANNEL
+                    : "/api/playback/stop/" + GB_DEVICE + "/" + GB_CHANNEL + "/" + STREAM;
+            verify(collector).get(path, Map.of());
+        } else {
+            verify(sessions).updateById(any(VideoSession.class));
+            verifyNoInteractions(collector);
+        }
+    }
+
+    @ParameterizedTest(name = "legacy control action {0}")
+    @CsvSource({
+            "pause, 0, /api/playback/pause/legacy_stream_001",
+            "resume, 0, /api/playback/resume/legacy_stream_001",
+            "seek, 45, /api/playback/seek/legacy_stream_001/45",
+            "speed, 2, /api/playback/speed/legacy_stream_001/2.0"
+    })
+    void recordPermissionKeepsLegacyPlaybackControlBodyAndMediaCommand(
+            String action, double value, String mediaPath) throws Exception {
+        String bearer = token(OWNER, "video:device:record");
+        String sessionId = startSession(Operation.PLAYBACK, bearer);
+        clearInvocations(collector);
+        success(mvc.perform(post("/api/video/sessions/{id}/control", sessionId)
+                .header("Authorization", bearer).contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("action", action, "value", value)))));
+        verify(collector).get(mediaPath, Map.of());
+    }
+
+    @ParameterizedTest(name = "anonymous {0} keeps legacy code 401, not cockpit HTTP 401")
+    @EnumSource(Operation.class)
+    void anonymousRequestsAreRejectedByTheRealSecurityChain(Operation operation) throws Exception {
+        MockHttpServletRequestBuilder request = request(operation, "not-reached");
+        mvc.perform(request).andExpect(status().isOk())
+                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
+                .andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.msg").value(
+                        "请求访问:" + path(operation, "not-reached") + ",认证失败,无法访问系统资源"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} cannot authenticate with an invalid or revoked JWT")
+    @EnumSource(Operation.class)
+    void malformedAndRevokedTokensCannotBypassAuthentication(Operation operation) throws Exception {
+        String revoked = token(OWNER, "video:device:play", "video:device:record");
+        LoginUser login = tokens.getLoginUserByToken(revoked);
+        tokens.delLoginUser(login.getToken());
+        for (String bearer : Arrays.asList("Bearer not-a-jwt", revoked)) {
+            perform(operation, "not-reached", bearer)
+                    .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401));
+        }
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "missing session is not accessible through {0}")
+    @EnumSource(value = Operation.class, names = {"HEARTBEAT", "STOP", "CONTROL"})
+    void missingSessionUsesTheSameLegacyOwnershipFailure(Operation operation) throws Exception {
+        perform(operation, "missing-session", token(OWNER, "video:device:play", "video:device:record"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.msg").value("播放会话不存在或无权操作"));
+        verifyNoInteractions(devices, bindings, collector);
+        verify(sessions, never()).updateById(any(VideoSession.class));
+    }
+
+    private String startSession(Operation operation, String bearer) throws Exception {
+        String mode = operation == Operation.LIVE ? "LIVE" : "PLAYBACK";
+        String body = success(perform(operation, DEVICE_ID, bearer))
+                .andExpect(jsonPath("$.data.sessionId").isNotEmpty())
+                .andExpect(jsonPath("$.data.mode").value(mode))
+                .andExpect(jsonPath("$.data.stream").value(STREAM))
+                .andExpect(jsonPath("$.data.url").value(MEDIA_URL))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
+        return JSON.parseObject(body).getJSONObject("data").getString("sessionId");
+    }
+
+    private ResultActions success(ResultActions result) throws Exception {
+        return result.andExpect(status().isOk())
+                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"));
+    }
+
+    private ResultActions perform(Operation operation, String sessionId, String bearer) throws Exception {
+        return mvc.perform(request(operation, sessionId).header("Authorization", bearer));
+    }
+
+    private MockHttpServletRequestBuilder request(Operation operation, String sessionId) {
+        MockHttpServletRequestBuilder request = post(path(operation, sessionId));
+        if (operation == Operation.PLAYBACK) {
+            request.contentType(MediaType.APPLICATION_JSON).content(RANGE_JSON);
+        } else if (operation == Operation.CONTROL) {
+            request.contentType(MediaType.APPLICATION_JSON).content(CONTROL_JSON);
+        }
+        return request;
+    }
+
+    private String path(Operation operation, String sessionId) {
+        String resource = operation == Operation.LIVE || operation == Operation.PLAYBACK
+                ? "/devices/" + DEVICE_ID : "/sessions/" + sessionId;
+        return "/api/video" + resource + "/" + operation.name().toLowerCase(Locale.ROOT);
+    }
+
+    private String token(long userId, String... permissions) {
+        SysUser user = new SysUser();
+        user.setUserId(userId);
+        user.setUserName("video-user-" + userId);
+        LoginUser login = new LoginUser(userId, 101L, user, new HashSet<>(Arrays.asList(permissions)));
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setRemoteAddr("127.0.0.1"); // TokenService's location lookup short-circuits for an internal IP.
+        request.addHeader("User-Agent", "VideoDeviceCompatibilityTest");
+        ServletRequestAttributes attributes = new ServletRequestAttributes(request);
+        RequestContextHolder.setRequestAttributes(attributes);
+        try {
+            return "Bearer " + tokens.createToken(login);
+        } finally {
+            attributes.requestCompleted();
+            RequestContextHolder.resetRequestAttributes();
+        }
+    }
+
+    private static Map<String, Object> rangeParameters() {
+        return Map.of("deviceId", GB_DEVICE, "channelId", GB_CHANNEL,
+                "startTime", START_TIME, "endTime", END_TIME, "type", "all");
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) {
+            return null;
+        }
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(source, copy);
+        return copy;
+    }
+
+    enum Operation { LIVE, PLAYBACK, HEARTBEAT, STOP, CONTROL }
+
+    @Configuration
+    @EnableWebMvc
+    @EnableWebSecurity
+    @Import({SecurityConfig.class, PermitAllUrlProperties.class, PermissionService.class,
+            JwtAuthenticationTokenFilter.class, TokenService.class, RedisCache.class,
+            AuthenticationEntryPointImpl.class, CockpitAuthenticationEntryPoint.class,
+            LogoutSuccessHandlerImpl.class, GlobalExceptionHandler.class, VideoDeviceController.class})
+    static class HttpContractConfiguration {
+        @Bean
+        Clock clock() {
+            return Clock.systemUTC();
+        }
+
+        @Bean
+        UserDetailsService userDetailsService() {
+            return new InMemoryUserDetailsManager();
+        }
+
+        @Bean
+        CorsFilter corsFilter() {
+            // Reuse the real CORS bean factory, without importing unrelated resource/interceptor setup.
+            return new ResourcesConfig().corsFilter();
+        }
+
+        @Bean
+        EquipmentBaseMapper equipmentBaseMapper() {
+            return mock(EquipmentBaseMapper.class);
+        }
+
+        @Bean
+        EquipmentVideoBindingMapper equipmentVideoBindingMapper() {
+            return mock(EquipmentVideoBindingMapper.class);
+        }
+
+        @Bean
+        VideoSessionMapper videoSessionMapper() {
+            return mock(VideoSessionMapper.class);
+        }
+
+        @Bean
+        VideoCollectorClient videoCollectorClient() {
+            return mock(VideoCollectorClient.class);
+        }
+
+        @Bean
+        VideoDeviceService videoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector,
+                VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings) {
+            // Equipment writes are outside these five endpoints; no ledger service graph is bootstrapped.
+            return new VideoDeviceService(devices, collector, sessions, mock(EquipmentBaseService.class), bindings);
+        }
+
+        @Bean
+        @SuppressWarnings("unchecked")
+        RedisTemplate<String, Object> redisTemplate() {
+            Map<String, Object> values = new ConcurrentHashMap<>();
+            RedisTemplate<String, Object> template = mock(RedisTemplate.class);
+            ValueOperations<String, Object> operations = mock(ValueOperations.class);
+            when(template.opsForValue()).thenReturn(operations);
+            when(operations.get(anyString())).thenAnswer(invocation -> values.get(invocation.getArgument(0)));
+            doAnswer(invocation -> {
+                values.put(invocation.getArgument(0), invocation.getArgument(1));
+                return null;
+            }).when(operations).set(anyString(), any(), anyLong(), any(TimeUnit.class));
+            when(template.delete(anyString())).thenAnswer(invocation -> values.remove(invocation.getArgument(0)) != null);
+            return template;
+        }
+    }
+}

+ 2 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/mapper/VideoSessionMapper.java

@@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 
 @Mapper
 public interface VideoSessionMapper extends BaseMapper<VideoSession> {
+    // Discard session-local snapshots before re-reading ownership/status under the lock.
+    @Options(flushCache = Options.FlushCachePolicy.TRUE)
     @Select("SELECT equipment_id FROM app_user.equipment_base WHERE equipment_id=#{videoId} FOR UPDATE")
     String lockVideo(@Param("videoId") String videoId);
 }

+ 129 - 13
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java

@@ -16,6 +16,11 @@ import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Clock;
 import java.time.Duration;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
@@ -29,6 +34,7 @@ public class VideoDeviceService {
     public static final int VIDEO_EQUIPMENT_TYPE_ID = 20;
 
     private static final String GB28181 = "GB28181";
+    private static final SecureRandom RANDOM = new SecureRandom();
 
     private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
     private final EquipmentBaseMapper devices;
@@ -36,8 +42,15 @@ public class VideoDeviceService {
     private final VideoCollectorClient collector;
     private final VideoSessionMapper sessions;
     private final EquipmentBaseService equipmentService;
+    private final Clock clock;
 
+    @org.springframework.beans.factory.annotation.Autowired
     public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
+        this(devices, collector, sessions, equipmentService, bindings, Clock.systemDefaultZone());
+    }
+
+    public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings, Clock clock) {
+        this.clock=Objects.requireNonNull(clock);
         this.bindings=bindings;
         this.devices=devices;
         this.collector=collector;
@@ -131,10 +144,29 @@ public class VideoDeviceService {
         return response instanceof Map?new HashMap<>((Map<String,Object>)response):Map.of();
     }
     @Transactional
-    @SuppressWarnings("unchecked") public Map<String,Object> start(String id,VideoRequests.Range range) {
+    public Map<String,Object> start(String id,VideoRequests.Range range) {
+        // Resolve identity before allocating media resources.
+        return startSession(id, range, SecurityUtils.getUserId(), null);
+    }
+
+    /** Internal seam for the cockpit adapter; no anonymous HTTP route is published here. */
+    @Transactional
+    public Map<String,Object> startAnonymous(String id,VideoRequests.Range range) {
+        byte[] secret = new byte[32];
+        RANDOM.nextBytes(secret);
+        String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
+        Map<String,Object> data = startSession(id, range, null, tokenHash(token));
+        data.put("sessionToken", token);
+        return data;
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String,Object> startSession(String id,VideoRequests.Range range,Long userId,String anonymousTokenHash) {
         VideoDeviceRecord row=find(id);
         sessions.lockVideo(id);
         String mode=range==null?"LIVE":"PLAYBACK";
+        // Capture under the video lock, before an insert error can abort the DB transaction.
+        long existingLive=range==null?activeLiveCount(id,null):0;
         Object response;
         if(range!=null) {
             requireGb(row);
@@ -153,16 +185,26 @@ public class VideoDeviceService {
         VideoSession session=new VideoSession();
         session.setSessionId(UUID.randomUUID().toString());
         session.setVideoId(id);
-        session.setUserId(SecurityUtils.getUserId());
+        session.setUserId(userId);
+        session.setAnonymousTokenHash(anonymousTokenHash);
         session.setMode(mode);
         session.setStatus("ACTIVE");
         session.setGbDeviceId(row.getGbDeviceId());
         session.setGbChannelId(row.getGbChannelId());
         session.setStreamId((String)data.get("stream"));
         session.setProxyKey((String)data.remove("proxyKey"));
-        session.setCreateTime(LocalDateTime.now());
+        session.setCreateTime(LocalDateTime.now(clock));
         session.setLastSeen(session.getCreateTime());
-        sessions.insert(session);
+        try {
+            if(sessions.insert(session)!=1)throw new ServiceException("播放会话登记失败");
+        } catch(RuntimeException registrationFailure) {
+            try { stopMedia(session,existingLive); }
+            catch(RuntimeException cleanupFailure) {
+                log.warn("视频会话登记失败且媒体清理未确认: {}",session.getSessionId());
+                throw new ServiceException("播放会话登记失败,媒体清理未确认,请联系管理员");
+            }
+            throw new ServiceException("播放会话登记失败");
+        }
         data.put("sessionId",session.getSessionId());
         data.put("mode",mode);
         return data;
@@ -180,17 +222,62 @@ public class VideoDeviceService {
         requireGb(row);
         collector.get("/api/front-end/ptz/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of("command",input.getCommand(),"horizonSpeed",input.getSpeed(),"verticalSpeed",input.getSpeed(),"zoomSpeed",input.getZoomSpeed()));
     }
+    /** Checks only ownership and watching validity, not device capability or exclusive PTZ rights. */
+    public void requireAnonymousSession(String id,String token,String videoId,String mode) {
+        VideoSession s=ownedAnonymous(id,token);
+        requireActiveAnonymous(s);
+        if(!Objects.equals(videoId,s.getVideoId())||!Objects.equals(mode,s.getMode()))throw new ServiceException("播放会话与设备或播放模式不匹配");
+    }
+
+    private void requireActiveAnonymous(VideoSession s) {
+        if(!"ACTIVE".equals(s.getStatus())||s.getLastSeen()==null||s.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120)))
+            throw new ServiceException("播放会话已失效");
+    }
+
+    private VideoSession ownedAnonymous(String id,String token) {
+        if(token==null||!token.matches("[A-Za-z0-9_-]{43}"))throw new ServiceException("播放会话不存在或无权操作");
+        VideoSession s=sessions.selectById(id);
+        if(s==null||s.getUserId()!=null||s.getAnonymousTokenHash()==null||!MessageDigest.isEqual(
+                s.getAnonymousTokenHash().getBytes(StandardCharsets.US_ASCII),
+                tokenHash(token).getBytes(StandardCharsets.US_ASCII)))throw new ServiceException("播放会话不存在或无权操作");
+        return s;
+    }
+
+    private static String tokenHash(String token) {
+        try {
+            return Base64.getUrlEncoder().withoutPadding().encodeToString(
+                    MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII)));
+        } catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
+    }
+
+    @Transactional
+    public void heartbeat(String id,String token) {
+        VideoSession s=ownedAnonymous(id,token);
+        sessions.lockVideo(s.getVideoId());
+        s=ownedAnonymous(id,token);
+        requireActiveAnonymous(s);
+        s.setLastSeen(LocalDateTime.now(clock));
+        sessions.updateById(s);
+    }
+
+    @Transactional
+    public void stop(String id,String token) {
+        finish(ownedAnonymous(id,token));
+    }
+
     private VideoSession owned(String id) {
         VideoSession s=sessions.selectById(id);
-        if(s==null||!Objects.equals(s.getUserId(),SecurityUtils.getUserId()))throw new ServiceException("播放会话不存在或无权操作");
+        if(s==null||s.getAnonymousTokenHash()!=null||s.getUserId()==null||!Objects.equals(s.getUserId(),SecurityUtils.getUserId()))throw new ServiceException("播放会话不存在或无权操作");
         return s;
     }
     @Transactional
 
     public void heartbeat(String id) {
         VideoSession s=owned(id);
+        sessions.lockVideo(s.getVideoId());
+        s=owned(id);
         if("ACTIVE".equals(s.getStatus())) {
-            s.setLastSeen(LocalDateTime.now());
+            s.setLastSeen(LocalDateTime.now(clock));
             sessions.updateById(s);
         }
     }
@@ -200,22 +287,50 @@ public class VideoDeviceService {
         finish(owned(id));
     }
     private void finish(VideoSession session) {
+        finish(session,null);
+    }
+
+    private void finish(VideoSession session,LocalDateTime expiredBefore) {
         if(!"ACTIVE".equals(session.getStatus()))return;
         sessions.lockVideo(session.getVideoId());
         VideoSession current=sessions.selectById(session.getSessionId());
         if(current==null||!"ACTIVE".equals(current.getStatus()))return;
-        long others=sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,session.getVideoId()).eq(VideoSession::getStatus,"ACTIVE").eq(VideoSession::getMode,"LIVE").ne(VideoSession::getSessionId,session.getSessionId()));
+        if(expiredBefore!=null&&current.getLastSeen()!=null&&!current.getLastSeen().isBefore(expiredBefore))return;
+        stopMedia(current,activeLiveCount(current.getVideoId(),current.getSessionId()));
+        current.setStatus("STOPPED");
+        current.setEndTime(LocalDateTime.now(clock));
+        sessions.updateById(current);
+    }
+
+    private long activeLiveCount(String videoId,String excludingSessionId) {
+        return sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,videoId)
+                .eq(VideoSession::getStatus,"ACTIVE").eq(VideoSession::getMode,"LIVE")
+                .ne(excludingSessionId!=null,VideoSession::getSessionId,excludingSessionId));
+    }
+
+    // No DB access: compensation must also work after a failed SQL statement.
+    private void stopMedia(VideoSession session,long others) {
         if("PLAYBACK".equals(session.getMode()))collector.get("/api/playback/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId()+"/"+safeStream(session.getStreamId()),Map.of());
         else if(others==0&&session.getGbDeviceId()!=null)collector.get("/api/play/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId(),Map.of());
         else if(others==0&&session.getProxyKey()!=null)collector.post("/internal/video/manual/stop",Map.of("key",session.getProxyKey()));
-        current.setStatus("STOPPED");
-        current.setEndTime(LocalDateTime.now());
-        sessions.updateById(current);
+    }
+
+    @Transactional
+    public void control(String id,String token,VideoRequests.Control input) {
+        VideoSession s=ownedAnonymous(id,token);
+        sessions.lockVideo(s.getVideoId());
+        s=ownedAnonymous(id,token);
+        requireActiveAnonymous(s);
+        controlSession(s,input);
     }
 
     public void control(String id,VideoRequests.Control input) {
-        VideoSession s=owned(id);
+        controlSession(owned(id),input);
+    }
+
+    private void controlSession(VideoSession s,VideoRequests.Control input) {
         if(!"ACTIVE".equals(s.getStatus())||!"PLAYBACK".equals(s.getMode()))throw new ServiceException("没有正在进行的录像回放");
+        if(input==null||input.getAction()==null||!Set.of("pause","resume","speed","seek").contains(input.getAction()))throw new ServiceException("不支持的回放控制操作");
         String suffix="";
         if("speed".equals(input.getAction())) {
             if(input.getValue()==null||!Set.of(0.25,0.5,1.0,2.0,4.0).contains(input.getValue()))throw new ServiceException("回放速度支持 0.25、0.5、1、2、4 倍");
@@ -229,8 +344,9 @@ public class VideoDeviceService {
     }
     @Scheduled(fixedDelay=30000)
     @Transactional public void expireSessions() {
-        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getStatus,"ACTIVE").lt(VideoSession::getLastSeen,LocalDateTime.now().minusSeconds(120))))try {
-            finish(s);
+        LocalDateTime expiredBefore=LocalDateTime.now(clock).minusSeconds(120);
+        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getStatus,"ACTIVE").lt(VideoSession::getLastSeen,expiredBefore)))try {
+            finish(s,expiredBefore);
         }
         catch(Exception e) {
             log.warn("视频会话回收失败,稍后重试: {}",s.getSessionId());

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoSession.java

@@ -10,6 +10,11 @@ public class VideoSession {
     @TableId(type=IdType.INPUT) private String sessionId;
     private String videoId;
     private Long userId;
+    // Anonymous ownership is independent of business users; the bearer token is never persisted.
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    @lombok.ToString.Exclude
+    private String anonymousTokenHash;
     private String mode;
     private String streamId;
     private String proxyKey;