Эх сурвалжийг харах

feat(cockpit): 发布匿名实时视频专用接口

Kazerin 3 долоо хоног өмнө
parent
commit
01a66fad

+ 91 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitVideoController.java

@@ -0,0 +1,91 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.video.CockpitVideoException;
+import com.zksy.cockpit.video.CockpitVideoService;
+import com.zksy.common.core.domain.AjaxResult;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.time.Clock;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.UUID;
+
+@RestController
+@RequestMapping("/api/cockpit/v1/video")
+public class CockpitVideoController {
+    private final CockpitVideoService videos;
+    private final Clock clock;
+
+    public CockpitVideoController(CockpitVideoService videos, Clock clock) {
+        this.videos = videos;
+        this.clock = clock;
+    }
+
+    @GetMapping("/device")
+    public ResponseEntity<AjaxResult> device(@RequestParam("deviceCode") String code, HttpServletRequest request) {
+        return success(videos.device(code), request);
+    }
+
+    @PostMapping("/live")
+    public ResponseEntity<AjaxResult> live(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.live(field(body, "deviceCode")), request);
+    }
+
+    @PostMapping("/sessions/{id}/heartbeat")
+    public ResponseEntity<AjaxResult> heartbeat(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.heartbeat(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    @PostMapping("/sessions/{id}/stop")
+    public ResponseEntity<AjaxResult> stop(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.stop(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    private static String sessionId(String id) {
+        if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}"))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "播放会话标识无效");
+        return id;
+    }
+
+    private static String field(Map<String, Object> body, String field) {
+        if (body == null || body.size() != 1 || !(body.get(field) instanceof String))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+        return (String) body.get(field);
+    }
+
+    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class,
+            org.springframework.web.bind.MissingServletRequestParameterException.class,
+            org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class})
+    public ResponseEntity<AjaxResult> invalidRequest(Exception failure, HttpServletRequest request) {
+        return error(new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效"), request);
+    }
+
+    private ResponseEntity<AjaxResult> success(Map<String, Object> data, HttpServletRequest request) {
+        data.putAll(metadata(request));
+        return ResponseEntity.ok().cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
+    }
+
+    @ExceptionHandler(CockpitVideoException.class)
+    public ResponseEntity<AjaxResult> error(CockpitVideoException failure, HttpServletRequest request) {
+        Map<String, Object> data = metadata(request);
+        data.put("category", failure.getCategory());
+        data.put("message", failure.getMessage());
+        return ResponseEntity.status(failure.getStatus()).cacheControl(org.springframework.http.CacheControl.noStore())
+                .body(new AjaxResult(failure.getStatus(), failure.getMessage(), data));
+    }
+
+    private Map<String, Object> metadata(HttpServletRequest request) {
+        String requestId = request.getHeader("X-Request-Id");
+        if (requestId == null || !requestId.matches("[A-Za-z0-9._-]{1,100}")) requestId = UUID.randomUUID().toString();
+        Map<String, Object> metadata = new LinkedHashMap<>();
+        metadata.put("requestId", requestId);
+        metadata.put("serverTime", DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(clock.instant().atZone(ZoneId.of("Asia/Shanghai"))));
+        return metadata;
+    }
+}

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

@@ -1,54 +0,0 @@
-package com.zksy.web.controller.cockpit;
-
-import org.junit.jupiter.api.Test;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * Locks the confirmed cockpit anonymous-read policy (2026-09-28): GET /api/cockpit/v1/**
- * is served without authentication, everything else still requires authentication, and
- * deployment relies on intranet network isolation.
- *
- * <p>The full Spring Security chain needs the application context, so this test freezes
- * the matcher contract directly on {@code zksy-framework/.../SecurityConfig.java}.
- */
-class CockpitAnonymousAccessSecurityConfigTest {
-
-    private static final Path SECURITY_CONFIG = Path.of(
-            "..", "zksy-framework", "src", "main", "java", "com", "zksy", "framework",
-            "config", "SecurityConfig.java");
-
-    @Test
-    void cockpitPermitAllIsGetScopedAndSingleRule() throws Exception {
-        assertTrue(Files.exists(SECURITY_CONFIG), "SecurityConfig.java must exist at " + SECURITY_CONFIG);
-        List<String> lines = Files.readAllLines(SECURITY_CONFIG);
-
-        long cockpitPermitLines = lines.stream()
-                .filter(line -> line.contains("permitAll") && line.contains("/api/cockpit"))
-                .count();
-        assertEquals(1, cockpitPermitLines, "exactly one cockpit permitAll rule may exist");
-
-        String permitLine = lines.stream()
-                .filter(line -> line.contains("permitAll") && line.contains("/api/cockpit"))
-                .findFirst()
-                .orElseThrow();
-        assertTrue(permitLine.contains("HttpMethod.GET"),
-                "cockpit permitAll must be scoped to GET only");
-        assertTrue(permitLine.contains("\"/api/cockpit/v1/**\""),
-                "cockpit permitAll must cover /api/cockpit/v1/**");
-    }
-
-    @Test
-    void everythingOutsideCockpitGetStillRequiresAuthentication() throws Exception {
-        String source = Files.readString(SECURITY_CONFIG);
-        assertTrue(source.contains(".anyRequest().authenticated()"),
-                "the catch-all rule must still require authentication");
-        assertTrue(source.contains("\"/ws/deviceStatus\""),
-                "the WebSocket endpoint must keep its existing access rule");
-    }
-}

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

@@ -0,0 +1,469 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.zksy.base.domain.EquipmentBase;
+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.cockpit.video.CockpitVideoService;
+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 com.zksy.web.controller.video.VideoDeviceController;
+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.ValueSource;
+import com.zksy.common.exception.ServiceException;
+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.http.MediaType;
+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.setup.MockMvcBuilders;
+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.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** HTTP seam with the real security/JWT chain and both business services.
+ * Only DB, Redis storage and media transport are replaced. No server, scheduler,
+ * database connection or media/network request is started by this fixture.
+ */
+class CockpitVideoControllerTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String CODE = " CN/摄像机+%2F 001 ";
+    private static final String ID = "internal-ledger-id";
+    private static final String GB = "34020000002000000001";
+    private static final String CHANNEL = "34020000001320000001";
+    private static final String START = "/api/play/start/" + GB + "/" + CHANNEL;
+    private static final String STOP = "/api/play/stop/" + GB + "/" + CHANNEL;
+    private static final String URL = "https://media.invalid/live.flv";
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private EquipmentBaseMapper devices;
+    private EquipmentVideoBindingMapper bindings;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient collector;
+    private EquipmentBase equipment;
+    private VideoDeviceRecord binding;
+
+    @BeforeEach
+    void setUp() {
+        SecurityContextHolder.clearContext();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-test", Map.of(
+                "token.header", "Authorization", "token.secret", "offline-video-contract-only-secret-not-for-production", "token.expireTime", "60")));
+        context.register(HttpConfiguration.class);
+        context.refresh();
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        devices = context.getBean(EquipmentBaseMapper.class);
+        bindings = context.getBean(EquipmentVideoBindingMapper.class);
+        sessions = context.getBean(VideoSessionMapper.class);
+        collector = context.getBean(VideoCollectorClient.class);
+        equipment = new EquipmentBase();
+        equipment.setEquipmentId(ID);
+        equipment.setEquipmentCode(CODE);
+        equipment.setEquipmentName("测试摄像机");
+        equipment.setEquipmentTypeId(20);
+        when(devices.selectList(any())).thenReturn(List.of(equipment));
+        binding = new VideoDeviceRecord();
+        BeanUtils.copyProperties(equipment, binding);
+        binding.setVideoId(ID);
+        binding.setDeviceCode(CODE);
+        binding.setDeviceName("测试摄像机");
+        binding.setSourceType("GB28181");
+        binding.setGbDeviceId(GB);
+        binding.setGbChannelId(CHANNEL);
+        when(bindings.find(ID)).thenReturn(binding);
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL));
+        Map<String, VideoSession> rows = new ConcurrentHashMap<>();
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = call.getArgument(0);
+            rows.put(row.getSessionId(), copy(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 = call.getArgument(0);
+            return rows.replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        // Literal single-viewer DB fixture; no copy of shared-count business logic.
+        when(sessions.selectCount(any())).thenReturn(0L);
+    }
+
+    @AfterEach
+    void tearDown() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    @Test
+    void anonymousDeviceLookupKeepsExactBusinessCodeAndPublishesOnlyConfirmedLiveCapability() throws Exception {
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE).header("X-Request-Id", "video-lookup-1"))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.deviceName").value("测试摄像机"))
+                .andExpect(jsonPath("$.data.typeCode").value("20"))
+                .andExpect(jsonPath("$.data.bound").value(true))
+                .andExpect(jsonPath("$.data.capabilities.live").value(true))
+                .andExpect(jsonPath("$.data.capabilities.records").value(false))
+                .andExpect(jsonPath("$.data.capabilities.playback").value(false))
+                .andExpect(jsonPath("$.data.capabilities.playbackControl").value(false))
+                .andExpect(jsonPath("$.data.capabilities.ptz").value(false))
+                .andExpect(jsonPath("$.data.capabilities.ptzStopGuaranteed").value(false))
+                .andExpect(jsonPath("$.data.requestId").value("video-lookup-1"))
+                .andExpect(jsonPath("$.data.serverTime").value("2026-11-10T16:00:00+08:00"))
+                .andExpect(jsonPath("$.data.equipmentId").doesNotExist())
+                .andExpect(jsonPath("$.data.videoId").doesNotExist())
+                .andExpect(jsonPath("$.data.gbChannelId").doesNotExist());
+        verifyNoInteractions(collector, sessions);
+    }
+
+    @Test
+    void anonymousViewerStartsMaintainsAndIdempotentlyReleasesOnlyItsOwnSession() throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL,
+                "rtcs", "https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play",
+                "native", true, "secret", "internal-secret", "proxyKey", "internal-key"));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.mode").value("LIVE"))
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media.flv").value(URL))
+                .andExpect(jsonPath("$.data.media.webrtc").value("https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play"))
+                .andExpect(jsonPath("$.data.media.native").value(false))
+                .andExpect(jsonPath("$.data.secret").doesNotExist())
+                .andExpect(jsonPath("$.data.stream").doesNotExist())
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.media.secret").doesNotExist())
+                .andExpect(header().string("Cache-Control", "no-store"))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
+                .getJSONObject("data");
+        clearInvocations(collector);
+        session(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden())
+                .andExpect(jsonPath("$.data.category").value("SESSION_FORBIDDEN"));
+        verifyNoInteractions(collector);
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"))
+                .andExpect(jsonPath("$.data.sessionToken").doesNotExist());
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector, times(1)).get(STOP, Map.of());
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isGone())
+                .andExpect(jsonPath("$.data.category").value("SESSION_EXPIRED"));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"GET,/live", "GET,/sessions/example/stop", "GET,/sessions/example/heartbeat",
+            "GET,/devices/remove", "GET,/records", "POST,/device", "PUT,/live", "DELETE,/live",
+            "POST,/sessions/example/control", "POST,/ptz", "POST,/playback", "POST,/devices",
+            "POST,/sessions/example/nested/stop", "POST,/live/nested"})
+    void onlyTheFourPublishedMethodAndPathPairsAreAnonymous(String method, String path) throws Exception {
+        mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), ROOT + path))
+                .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value(401));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"/devices/internal/live", "/devices/internal/playback", "/devices",
+            "/sessions/another/heartbeat", "/sessions/another/stop", "/sessions/another/control"})
+    void legacyVideoEndpointsStillRequireBusinessAuthentication(String path) throws Exception {
+        mvc.perform(post("/api/video" + path)).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"CN/摄像机+%2F 001", " CN/摄像机+%2f 001 ", " CN/摄像机+/ 001 ", "internal-ledger-id"})
+    void neverNormalizesOrDecodesBusinessCodeAgain(String differentCode) throws Exception {
+        mvc.perform(get(ROOT + "/device").param("deviceCode", differentCode))
+                .andExpect(status().isNotFound()).andExpect(jsonPath("$.data.category").value("DEVICE_NOT_FOUND"));
+        verifyNoInteractions(bindings, sessions, collector);
+    }
+
+    @Test
+    void ordinaryDeviceCannotGainVideoFromItsNameOrALeftoverBinding() throws Exception {
+        equipment.setEquipmentTypeId(12);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.typeCode").value("12"))
+                .andExpect(jsonPath("$.data.bound").value(false))
+                .andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict()).andExpect(jsonPath("$.data.category").value("VIDEO_UNAVAILABLE"));
+        verifyNoInteractions(bindings, sessions, collector);
+    }
+
+    @Test
+    void unboundCameraIsGreyWithoutConsultingMediaOrCollectionRecords() throws Exception {
+        when(bindings.find(ID)).thenReturn(null);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.bound").value(false)).andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(sessions, collector);
+    }
+
+    @Test
+    void unknownSourceAndIncompleteGbBindingRemainGrey() throws Exception {
+        binding.setSourceType("unknown");
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.bound").value(true)).andExpect(jsonPath("$.data.capabilities.live").value(false));
+        binding.setSourceType("GB28181");
+        binding.setGbChannelId(null);
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(sessions, collector);
+    }
+
+    @Test
+    void ambiguousOrFailedLedgerQueriesDoNotGuessADeviceOrLeakDatabaseDetails() throws Exception {
+        when(devices.selectList(any())).thenReturn(List.of(equipment, equipment));
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("VIDEO_READ_FAILED"));
+        when(devices.selectList(any())).thenThrow(new IllegalStateException("jdbc password=do-not-publish"));
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("do-not-publish"))));
+        verifyNoInteractions(bindings, collector, sessions);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"{}", "{bad-json", "{\"deviceCode\":123}", "{\"deviceCode\":\"\"}",
+            "{\"deviceCode\":\"x\",\"userId\":1}"})
+    void malformedLiveRequestsUseThePublicInvalidRequestEnvelope(String body) throws Exception {
+        mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON).content(body))
+                .andExpect(status().isBadRequest()).andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+        verifyNoInteractions(devices, bindings, collector, sessions);
+    }
+
+    @Test
+    void missingDeviceQueryIsBadRequestRatherThanAnInternalError() throws Exception {
+        mvc.perform(get(ROOT + "/device")).andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void manualNativeVideoIsExplicitAndNeverLeaksItsLedgerFields() throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl("https://media.invalid/live.mp4");
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.capabilities.live").value(true));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.media.url").value("https://media.invalid/live.mp4"))
+                .andExpect(jsonPath("$.data.media.native").value(true))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verifyNoInteractions(collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"https://user:password@media.invalid/live.mp4", "https://media.invalid/live.mp4?secret=hidden",
+            "https://media.invalid/live.flv", "https://media.invalid/error.html", "ws://media.invalid/live.flv"})
+    void manualSourcesThatCannotBePublicNativeMediaAreGrey(String url) throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl(url);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(collector, sessions);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"https://user:password@media.invalid/live.flv", "https://media.invalid/live.flv?secret=hidden",
+            "https://media.invalid/live.flv?%73ecret=hidden", "https://media.invalid/live.flv?internal-token=hidden",
+            "https://media.invalid/live.flv?proxyKey=hidden", "https://media.invalid/live.flv?password=hidden"})
+    void unsafeMediaAddressTriggersOwnSessionCleanupInsteadOfPublishingCredentials(String url) throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", url));
+        live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void failedStopIsUnconfirmedAndTheSameOwnerCanRetry() throws Exception {
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("secret=hidden transport detail"));
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
+                .andExpect(jsonPath("$.data.message").value("清理未确认,请等待回收"));
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk());
+        doReturn(Map.of()).when(collector).get(STOP, Map.of());
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+    }
+
+    @Test
+    void unsafeMediaAndFailedCompensationDoNotClaimThatResourcesWereStopped() throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL + "?token=hidden"));
+        when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("password=hidden"));
+        live().andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+    }
+
+    @Test
+    void twoAnonymousViewersDoNotShareOwnershipOrStopEachOthersLiveStream() throws Exception {
+        when(sessions.selectCount(any())).thenReturn(0L, 1L, 1L, 0L);
+        JSONObject first = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject second = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        org.junit.jupiter.api.Assertions.assertNotEquals(first.getString("sessionToken"), second.getString("sessionToken"));
+        session(first, "stop", second.getString("sessionToken")).andExpect(status().isForbidden());
+        clearInvocations(collector);
+        session(first, "stop", first.getString("sessionToken")).andExpect(status().isOk());
+        verifyNoInteractions(collector);
+        session(second, "heartbeat", second.getString("sessionToken")).andExpect(status().isOk());
+        session(second, "stop", second.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void upstreamFailureIsSanitizedAndNeverReportedAsAnEmptyOrSuccessfulStream() throws Exception {
+        when(collector.get(START, Map.of())).thenThrow(new ServiceException("password=hidden upstream failure"));
+        live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void manualRtspCredentialsStayInsideProxyAndOnlyPublicWebRtcIsReturned() throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl("rtsp://user:private-password@camera.invalid/live");
+        when(collector.post("/internal/video/manual/start", Map.of("id", ID, "url", binding.getVideoUrl())))
+                .thenReturn(Map.of("stream", "proxy_stream", "proxyKey", "private-proxy-key", "flv", URL,
+                        "webrtc", "https://media.invalid/index/api/webrtc?app=proxy&stream=proxy_stream&type=play"));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.media.native").value(false))
+                .andExpect(jsonPath("$.data.media.webrtc").isNotEmpty())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("private-"))))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector).post("/internal/video/manual/stop", Map.of("key", "private-proxy-key"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"/api/cockpit/v1/security-contract-probe", "/api/cockpit/v1/security-contract-probe/nested"})
+    void existingCockpitReadPolicyAllowsAnonymousGetButNotPost(String path) throws Exception {
+        mvc.perform(get(path)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.reached").value("security-policy-probe"))
+                .andExpect(jsonPath("$.method").value("GET"));
+        mvc.perform(post(path)).andExpect(status().isUnauthorized())
+                .andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.data.category").value("UNAUTHORIZED"))
+                .andExpect(jsonPath("$.reached").doesNotExist());
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @CsvSource({"GET,/api/security-contract-probe", "POST,/api/security-contract-probe",
+            "GET,/ws/deviceStatus/nested", "POST,/ws/deviceStatus/nested"})
+    void theDefaultRuleStillRejectsAnonymousRequestsOutsideExplicitExceptions(String method, String path)
+            throws Exception {
+        mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), path))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.reached").doesNotExist());
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @Test
+    void existingWebSocketHandshakePathStillPassesTheRealAuthenticationChain() throws Exception {
+        // This observes authorization before an Upgrade endpoint, not a real socket handshake.
+        mvc.perform(get("/ws/deviceStatus").header("Connection", "Upgrade").header("Upgrade", "websocket")
+                .header("Sec-WebSocket-Version", "13").header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.reached").value("security-policy-probe"))
+                .andExpect(jsonPath("$.method").value("GET"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    private ResultActions live() throws Exception {
+        return mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))));
+    }
+
+    private ResultActions session(JSONObject viewer, String action, String token) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) return null;
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(source, copy);
+        return copy;
+    }
+
+    /** Replaces the old source-text matcher/count assertions with actual filter-chain outcomes.
+     * The same endpoint accepts GET and POST, so denied requests cannot pass by falling through to 404.
+     * Only the downstream HTTP handler is a fixture; SecurityConfig and all authentication filters are real.
+     */
+    @org.springframework.web.bind.annotation.RestController
+    static class SecurityPolicyProbe {
+        @org.springframework.web.bind.annotation.RequestMapping({"/api/cockpit/v1/security-contract-probe",
+                "/api/cockpit/v1/security-contract-probe/nested", "/api/security-contract-probe",
+                "/ws/deviceStatus", "/ws/deviceStatus/nested"})
+        Map<String, String> reached(javax.servlet.http.HttpServletRequest request) {
+            return Map.of("reached", "security-policy-probe", "method", request.getMethod());
+        }
+    }
+
+    @Configuration
+    @EnableWebMvc
+    @EnableWebSecurity
+    @Import({SecurityConfig.class, PermitAllUrlProperties.class, PermissionService.class,
+            JwtAuthenticationTokenFilter.class, TokenService.class, RedisCache.class,
+            AuthenticationEntryPointImpl.class, CockpitAuthenticationEntryPoint.class,
+            LogoutSuccessHandlerImpl.class, GlobalExceptionHandler.class,
+            CockpitVideoController.class, CockpitVideoService.class, VideoDeviceController.class, SecurityPolicyProbe.class})
+    static class HttpConfiguration {
+        @Bean Clock clock() { return Clock.fixed(Instant.parse("2026-11-10T08:00:00Z"), ZoneOffset.UTC); }
+        @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(); }
+        @Bean CorsFilter corsFilter() { return new ResourcesConfig().corsFilter(); }
+        @Bean EquipmentBaseMapper devices() { return mock(EquipmentBaseMapper.class); }
+        @Bean EquipmentVideoBindingMapper bindings() { return mock(EquipmentVideoBindingMapper.class); }
+        @Bean VideoSessionMapper sessions() { return mock(VideoSessionMapper.class); }
+        @Bean VideoCollectorClient collector() { return mock(VideoCollectorClient.class); }
+        @Bean RedisTemplate<String, Object> redisTemplate() { return mock(RedisTemplate.class); }
+        @Bean VideoDeviceService videoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector,
+                VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings, Clock clock) {
+            return new VideoDeviceService(devices, collector, sessions, mock(EquipmentBaseService.class), bindings, clock);
+        }
+    }
+}

+ 6 - 0
pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/config/SecurityConfig.java

@@ -122,6 +122,12 @@ public class SecurityConfig
             .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
             // 注解标记允许匿名访问的url
             .authorizeHttpRequests((requests) -> {
+                // Video is a narrow anonymous exception, before any broad GET/annotation rule.
+                requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/video/device").permitAll()
+                    .antMatchers(HttpMethod.POST, "/api/cockpit/v1/video/live",
+                        "/api/cockpit/v1/video/sessions/*/heartbeat",
+                        "/api/cockpit/v1/video/sessions/*/stop").permitAll()
+                    .antMatchers("/api/cockpit/v1/video/**").authenticated();
                 permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
                 requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/**").permitAll()
                     // 对于登录login 注册register 验证码captchaImage 允许匿名访问

+ 16 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoException.java

@@ -0,0 +1,16 @@
+package com.zksy.cockpit.video;
+
+/** Deliberately contains only public, fixed error text; never wraps transport details. */
+public class CockpitVideoException extends RuntimeException {
+    private final int status;
+    private final String category;
+
+    public CockpitVideoException(int status, String category, String message) {
+        super(message);
+        this.status = status;
+        this.category = category;
+    }
+
+    public int getStatus() { return status; }
+    public String getCategory() { return category; }
+}

+ 69 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoMedia.java

@@ -0,0 +1,69 @@
+package com.zksy.cockpit.video;
+
+import com.zksy.base.video.VideoDeviceRecord;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/** Public media allowlist, not a copy of the collector's response or credentials. */
+final class CockpitVideoMedia {
+    private CockpitVideoMedia() { }
+
+    static Map<String, Object> publish(Map<String, Object> source, VideoDeviceRecord binding) {
+        Map<String, Object> media = new LinkedHashMap<>();
+        for (String field : Set.of("url", "flv", "https_flv", "ws_flv", "wss_flv", "hls", "https_hls", "webrtc")) {
+            Object value = source.get(field);
+            if (value instanceof String && publicAddress((String) value)) media.put(field, value);
+        }
+        // StreamContent publishes rtc/rtcs, while the cockpit exposes one WebRTC endpoint.
+        for (String field : new String[]{"rtcs", "rtc"}) {
+            Object value = source.get(field);
+            if (!media.containsKey("webrtc") && value instanceof String && publicAddress((String) value))
+                media.put("webrtc", value);
+        }
+        if (!media.isEmpty()) media.put("native", "MANUAL".equals(binding.getSourceType())
+                && nativeAddress(binding.getVideoUrl()) && binding.getVideoUrl().equals(media.get("url")));
+        return media;
+    }
+
+    static boolean manualSupported(String address) {
+        if (nativeAddress(address)) return true;
+        try {
+            URI uri = URI.create(address);
+            return uri.getHost() != null && Set.of("rtsp", "rtsps", "rtmp", "rtmps").contains(uri.getScheme().toLowerCase(Locale.ROOT));
+        } catch (RuntimeException invalid) { return false; }
+    }
+
+    private static boolean nativeAddress(String address) {
+        if (!publicAddress(address)) return false;
+        URI uri = URI.create(address);
+        String path = uri.getPath().toLowerCase(Locale.ROOT);
+        return Set.of("http", "https").contains(uri.getScheme().toLowerCase(Locale.ROOT))
+                && (path.endsWith(".mp4") || path.endsWith(".webm") || path.endsWith(".ogv")
+                || path.endsWith(".ogg") || path.endsWith(".m3u8"));
+    }
+
+    private static boolean publicAddress(String address) {
+        try {
+            URI uri = URI.create(address);
+            if (uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null
+                    || !Set.of("http", "https", "ws", "wss").contains(uri.getScheme().toLowerCase(Locale.ROOT))) return false;
+            // Fail closed on unknown query fields: do not silently strip a password/token and publish a broken URL.
+            String query = uri.getRawQuery();
+            if (query != null) for (String entry : query.split("&", -1)) {
+                String[] pair = entry.split("=", 2);
+                if (pair.length != 2) return false;
+                String name = URLDecoder.decode(pair[0], StandardCharsets.UTF_8);
+                String value = URLDecoder.decode(pair[1], StandardCharsets.UTF_8);
+                if (!Set.of("app", "stream", "type", "callId").contains(name)
+                        || !value.matches("[A-Za-z0-9_.:-]{1,200}")) return false;
+                if ("type".equals(name) && !"play".equals(value)) return false;
+            }
+            return true;
+        } catch (RuntimeException invalid) { return false; }
+    }
+}

+ 154 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoService.java

@@ -0,0 +1,154 @@
+package com.zksy.cockpit.video;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.common.exception.ServiceException;
+import org.springframework.stereotype.Service;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/** Resolves business identity without normalizing it or publishing internal ledger/binding fields. */
+@Service
+public class CockpitVideoService {
+    private final EquipmentBaseMapper devices;
+    private final EquipmentVideoBindingMapper bindings;
+    private final VideoDeviceService videos;
+
+    public CockpitVideoService(EquipmentBaseMapper devices, EquipmentVideoBindingMapper bindings, VideoDeviceService videos) {
+        this.devices = devices;
+        this.bindings = bindings;
+        this.videos = videos;
+    }
+
+    public Map<String, Object> device(String code) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        boolean bound = binding != null;
+        boolean live = liveSupported(binding);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("typeCode", device.getEquipmentTypeId() == null ? null : device.getEquipmentTypeId().toString());
+        data.put("bound", bound);
+        data.put("capabilities", Map.of("live", live, "records", false, "playback", false,
+                "playbackControl", false, "ptz", false, "ptzStopGuaranteed", false));
+        data.put("unavailableReason", live ? null : "设备未绑定或实时视频能力未确认");
+        return data;
+    }
+
+    public Map<String, Object> live(String code) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!liveSupported(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定或实时视频能力未确认");
+        Map<String, Object> started;
+        try {
+            started = videos.startAnonymous(device.getEquipmentId(), null);
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "实时视频启动失败,请稍后重试");
+        }
+        Map<String, Object> media = CockpitVideoMedia.publish(started, binding);
+        if (media.isEmpty()) {
+            try {
+                videos.stop((String) started.get("sessionId"), (String) started.get("sessionToken"));
+            } catch (RuntimeException failure) {
+                throw new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "媒体不可用且清理未确认,请等待回收");
+            }
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("sessionId", started.get("sessionId"));
+        data.put("sessionToken", started.get("sessionToken"));
+        data.put("mode", "LIVE");
+        data.put("media", media);
+        return data;
+    }
+
+    public Map<String, Object> heartbeat(String id, String token) {
+        try {
+            videos.heartbeat(id, token);
+        } catch (RuntimeException failure) {
+            throw sessionError(failure, false);
+        }
+        return sessionState(id, "ACTIVE");
+    }
+
+    public Map<String, Object> stop(String id, String token) {
+        try {
+            videos.stop(id, token);
+        } catch (RuntimeException failure) {
+            throw sessionError(failure, true);
+        }
+        return sessionState(id, "STOPPED");
+    }
+
+    private static Map<String, Object> sessionState(String id, String state) {
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("sessionId", id);
+        data.put("status", state);
+        return data;
+    }
+
+    private static CockpitVideoException sessionError(RuntimeException error, boolean stop) {
+        // 01's public compatibility seam has no typed codes. Match only its two fixed ownership outcomes.
+        if (error instanceof ServiceException && "播放会话不存在或无权操作".equals(error.getMessage()))
+            return new CockpitVideoException(403, "SESSION_FORBIDDEN", "播放会话不存在或无权操作");
+        if (error instanceof ServiceException && "播放会话已失效".equals(error.getMessage()))
+            return new CockpitVideoException(410, "SESSION_EXPIRED", "播放会话已失效");
+        return stop ? new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "清理未确认,请等待回收")
+                : new CockpitVideoException(503, "SESSION_HEARTBEAT_FAILED", "观看会话维护失败");
+    }
+
+    private VideoDeviceRecord findBinding(EquipmentBase device) {
+        if (!Objects.equals(20, device.getEquipmentTypeId())) return null;
+        try {
+            VideoDeviceRecord binding = bindings.find(device.getEquipmentId());
+            return binding != null && Objects.equals(device.getEquipmentId(), binding.getEquipmentId())
+                    && Objects.equals(device.getEquipmentCode(), binding.getEquipmentCode())
+                    && Objects.equals(20, binding.getEquipmentTypeId()) ? binding : null;
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "视频设备信息暂不可用");
+        }
+    }
+
+    private static boolean liveSupported(VideoDeviceRecord binding) {
+        if (binding == null) return false;
+        if ("GB28181".equals(binding.getSourceType()))
+            return gbId(binding.getGbDeviceId()) && gbId(binding.getGbChannelId());
+        return "MANUAL".equals(binding.getSourceType()) && CockpitVideoMedia.manualSupported(binding.getVideoUrl());
+    }
+
+    private EquipmentBase findDevice(String code) {
+        if (code == null || code.isBlank() || code.length() > 512 || code.codePoints().anyMatch(Character::isISOControl))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "设备业务编码无效");
+        List<EquipmentBase> rows;
+        try {
+            rows = devices.selectList(new QueryWrapper<EquipmentBase>()
+                    .eq("equipment_code", code).eq("del_flag", "0").last("LIMIT 2"));
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "视频设备信息暂不可用");
+        }
+        if (rows == null || rows.isEmpty())
+            throw new CockpitVideoException(404, "DEVICE_NOT_FOUND", "设备不存在");
+        if (rows.size() != 1)
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "设备业务编码存在歧义");
+        EquipmentBase row = rows.get(0);
+        // Defend against a DB collation ignoring whitespace/case, never guess a different identity.
+        if (row == null || !Objects.equals(code, row.getEquipmentCode()))
+            throw new CockpitVideoException(404, "DEVICE_NOT_FOUND", "设备不存在");
+        return row;
+    }
+
+    private static boolean gbId(String value) {
+        return value != null && value.matches("[0-9]{20}");
+    }
+}