diff --git a/docs/diagnostics/registration-tls-20260928/README.md b/docs/diagnostics/registration-tls-20260928/README.md new file mode 100644 index 0000000..dcfb7d1 --- /dev/null +++ b/docs/diagnostics/registration-tls-20260928/README.md @@ -0,0 +1,29 @@ +# Registration transport repair — 2026-09-28 + +Local Edge: http://192.168.0.109 (device access not authenticated during this investigation). + +The client ServerUrl.js selects HTTPS for bare DNS server addresses. Console maps +DEV to rest.dev.it-screen.com. The deployed DEV, EVA and UAE Nginx configuration +only had HTTP REST virtual hosts. HTTPS therefore selected an unrelated default +certificate and failed hostname verification. Console translates client status 0 +into the generic "Registration server did not respond" message. + +Installed dedicated HTTPS REST virtual hosts and issued separate Let's Encrypt +certificates for rest.dev.it-screen.com, rest.eva.iomatex.com and +rest.uae.iomatex.com, without changing existing HTTP blocks or application routes. +The adjacent files reproduce installed /etc/nginx/conf.d/rest-registration-tls.conf +on DEV (DEV+EVA) and UAE respectively. The certificate lineages have matching +names, expire 2026-12-27, and use the existing enabled certbot.timer for renewal. +Original its.conf/eva.conf copies: /root/registration-tls-backup-20260928 on DEV; +its.conf copy at the same path on UAE. Original files compare unchanged. + +Validation: nginx -t passed before reload on both hosts; authenticated TLS requests +(no insecure bypass) reach /v2/device and return expected JSON HTTP 401 without +credentials. DEV briefly returned 502 during an independently observed application +container restart; this was not a TLS failure. + +Limitations: full Edge server-switch registration has not been exercised because +known Edge credentials are rejected. No device cloud binding was reset or changed. +REST hosts rest.public.it-screen.by and rest.test.it-screen.by also fail TLS +hostname verification; these are separate hosts and were not modified. +No client version bump, Git commit or push was performed for this repair. diff --git a/docs/diagnostics/registration-tls-20260928/dev-eva.conf b/docs/diagnostics/registration-tls-20260928/dev-eva.conf new file mode 100644 index 0000000..b19ebfb --- /dev/null +++ b/docs/diagnostics/registration-tls-20260928/dev-eva.conf @@ -0,0 +1,38 @@ +server { + listen 443 ssl http2; + server_name rest.dev.it-screen.com; + ssl_certificate /etc/letsencrypt/live/rest.dev.it-screen.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/rest.dev.it-screen.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + client_max_body_size 512m; + proxy_read_timeout 180s; + server_tokens off; + proxy_hide_header X-Powered-By; + location / { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +server { + listen 443 ssl http2; + server_name rest.eva.iomatex.com; + ssl_certificate /etc/letsencrypt/live/rest.eva.iomatex.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/rest.eva.iomatex.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + client_max_body_size 512m; + proxy_read_timeout 180s; + server_tokens off; + proxy_hide_header X-Powered-By; + location / { + proxy_pass http://127.0.0.1:8081; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} diff --git a/docs/diagnostics/registration-tls-20260928/uae.conf b/docs/diagnostics/registration-tls-20260928/uae.conf new file mode 100644 index 0000000..a24940a --- /dev/null +++ b/docs/diagnostics/registration-tls-20260928/uae.conf @@ -0,0 +1,19 @@ +server { + listen 443 ssl http2; + server_name rest.uae.iomatex.com; + ssl_certificate /etc/letsencrypt/live/rest.uae.iomatex.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/rest.uae.iomatex.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + client_max_body_size 512m; + proxy_read_timeout 180s; + server_tokens off; + proxy_hide_header X-Powered-By; + location / { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} diff --git a/docs/releases/console-3.1.18.md b/docs/releases/console-3.1.18.md index 8e87cb6..bf7e0b5 100644 --- a/docs/releases/console-3.1.18.md +++ b/docs/releases/console-3.1.18.md @@ -4,5 +4,8 @@ - Confirmation lists module versions and warns when Edge Environment requires a reboot. The authenticated API revalidates the complete selection against the pinned release catalog. - Updates run sequentially in one detached installer job with the existing global lock. Failure stops remaining updates. Console runs near the end and Edge Environment last. Progress and the shared installation log remain available after leaving the page. - Storage recovery resumes the same ordered batch; successful completion requires receipts for every selected stage from that job. +- Added authenticated `POST /api/onvif/ptz` for camera PTZ preparation, movement, and stop commands. +- Reused the discovery probe result for the PTZ service endpoint and media profile token without exposing camera credentials over the network. +- Restricted camera endpoints to local addresses and accepted the existing reverse-gateway authorization contract. -Validation: stage version/batch tests, authenticated API tests, shared UI handler tests, storage recovery tests; Playwright checked cancellation, a single mocked batch request, exclusion of missing modules and button placement at 1440/768/360 px. No bulk update was executed on the live Edge during validation. +Validation: stage version/batch tests, authenticated API tests, shared UI handler tests, storage recovery tests, and Console ONVIF probe/PTZ API contract tests. Playwright checked cancellation, a single mocked batch request, exclusion of missing modules and button placement at 1440/768/360 px. No bulk update was executed on the live Edge during validation. diff --git a/docs/releases/console-3.1.19.md b/docs/releases/console-3.1.19.md new file mode 100644 index 0000000..a854149 --- /dev/null +++ b/docs/releases/console-3.1.19.md @@ -0,0 +1,8 @@ +# Console 3.1.19 — ONVIF center command + +Release date: 2026-10-07. + +- Allow the authenticated `home` PTZ command through the existing local ONVIF route. +- Continue rejecting unsupported PTZ commands at the Console boundary. + +Validation: Console ONVIF route unit tests. diff --git a/docs/releases/ip-stream-1.0.5.md b/docs/releases/ip-stream-1.0.5.md new file mode 100644 index 0000000..bb54c41 --- /dev/null +++ b/docs/releases/ip-stream-1.0.5.md @@ -0,0 +1,11 @@ +# IP Camera Streaming 1.0.5 + +Release date: 2026-10-06. + +- Add a root-local Unix control socket for credentialed preview and snapshot requests from Console. +- Keep camera credentials out of MQTT and reject credentialed stream URLs received through MQTT. +- Add `ffprobe` stream validation used by authenticated ONVIF discovery. +- Serialize stream operations so preview, snapshot, validation, status, and stop cannot race each other. +- Require `ffprobe` during stage installation and restart an existing streaming service so the control socket is created immediately. + +Validation: nine IP streaming tests, direct Edge preview start, full UAE API-to-reverse HLS manifest retrieval, and active-service/socket checks on `g-box-c453df5f`. diff --git a/docs/releases/ip-stream-1.0.6.md b/docs/releases/ip-stream-1.0.6.md new file mode 100644 index 0000000..2911b0f --- /dev/null +++ b/docs/releases/ip-stream-1.0.6.md @@ -0,0 +1,14 @@ +# IP Camera Streaming 1.0.6 + +Release date: 2026-10-06. + +- Add an authenticated Console endpoint for starting an Edge-to-CDN camera publication. +- Keep one FFmpeg forwarding process per camera and refresh its lifetime when Preview is reopened. +- Stop inactive CDN publications after the same 10-minute lifetime used by installation Preview. +- Keep CDN credentials out of runtime status files and browser responses. +- Reap expired publications and failed FFmpeg processes periodically without relying on status requests. +- Copy camera video while transcoding optional audio to AAC for the CDN ingest contract. + +Validation: IP streaming unit tests and Console camera streaming contract tests. + +Additional validation: periodic supervisor cleanup and AAC forwarding command regressions. diff --git a/docs/releases/ip-stream-1.0.7.md b/docs/releases/ip-stream-1.0.7.md new file mode 100644 index 0000000..caa636b --- /dev/null +++ b/docs/releases/ip-stream-1.0.7.md @@ -0,0 +1,10 @@ +# IP Camera Streaming 1.0.7 — camera audio + +Release date: 2026-10-07. + +- Preserve optional camera audio in the authenticated local HLS preview. +- Transcode camera audio to mono Opus at 48 kHz for low-latency CDN and WebRTC playback. +- Keep AAC audio in the direct HLS fallback for browser compatibility. +- Require FFprobe for ONVIF stream validation during stage installation. + +Validation: IP streaming unit tests, live Tapo C520WS RTSP audio probe, direct HLS AAC probe, and UAE MediaMTX ingest with `H264 + Opus` tracks. diff --git a/docs/releases/stage-itscreen-1.0.16.md b/docs/releases/stage-itscreen-1.0.16.md new file mode 100644 index 0000000..54db3d1 --- /dev/null +++ b/docs/releases/stage-itscreen-1.0.16.md @@ -0,0 +1,14 @@ +# stage_itscreen 1.0.16 — ONVIF PTZ control + +Release date: 2026-10-06. + +- Update IT-Screen Client to 4.410.144. +- Add authenticated ONVIF PTZ preparation, continuous pan/tilt movement, and stop commands through the existing local Unix socket. +- Reuse the discovery probe result for the PTZ service endpoint and media profile token without exposing camera credentials over the network. +- Add a two-second camera-side movement timeout as a safety fallback if a browser release request is lost. +- Give the `itscreen` service ownership of `/run/itscreen` so it can create the user-only ONVIF Unix socket. + +Binary: `stage_itscreen/itscreen` (Linux ARM64). +SHA-256: `79d495aa335d1ce05c1f31f4e9c5c3152ae06d051e4689b0eb6019fa8a17d1ec`. + +Validation: ONVIF contract tests and native Qt 5.15.2 ARM64 build on UAE `g-box-8e6af561`. diff --git a/docs/releases/stage-itscreen-1.0.17.md b/docs/releases/stage-itscreen-1.0.17.md new file mode 100644 index 0000000..4e14f52 --- /dev/null +++ b/docs/releases/stage-itscreen-1.0.17.md @@ -0,0 +1,14 @@ +# stage_itscreen 1.0.17 — MQTT ONVIF PTZ control + +Release date: 2026-10-06. + +- Update IT-Screen Client to 4.410.145. +- Receive correlated camera movement and stop commands through the existing authenticated device MQTT route. +- Execute cached ONVIF `ContinuousMove` and `Stop` operations locally on Edge after preview preparation. +- Keep camera credentials out of MQTT messages and expire prepared PTZ sessions after 15 minutes. +- Publish correlated PTZ command results back to the platform with MQTT QoS 1. + +Binary: `stage_itscreen/itscreen` (Linux ARM64). +SHA-256: `4422412e5246f49baaf9055c9333a782470822dbb629b75c974f5ad879498a9d`. + +Validation: ONVIF and Edge console contract tests plus native Qt 5.15.2 ARM64 build on UAE `g-box-8e6af561`. diff --git a/docs/releases/stage-itscreen-1.0.18.md b/docs/releases/stage-itscreen-1.0.18.md new file mode 100644 index 0000000..5832441 --- /dev/null +++ b/docs/releases/stage-itscreen-1.0.18.md @@ -0,0 +1,13 @@ +# stage_itscreen 1.0.18 — ONVIF center position + +Release date: 2026-10-07. + +- Update IT-Screen Client to 4.410.147. +- Add the one-shot ONVIF `AbsoluteMove` command that returns pan, tilt, and zoom to zero. +- Advertise `ptz_home` only from clients that support the command. +- Keep `/run/itscreen` owned by the `itscreen` user so the protected ONVIF socket is created after every restart. + +Binary: `stage_itscreen/itscreen` (Linux ARM64). +SHA-256: `0fe52ad80f29e31d204e49764ae5e7a89216a53b52b974d8387a7d63f0350a97`. + +Validation: native Qt 5.15.2 ARM64 build and local Unix-socket contract check on UAE `g-box-8e6af561`. diff --git a/docs/releases/stage-mqtt-1.0.2.md b/docs/releases/stage-mqtt-1.0.2.md new file mode 100644 index 0000000..bc63cb3 --- /dev/null +++ b/docs/releases/stage-mqtt-1.0.2.md @@ -0,0 +1,10 @@ +# stage_mqtt 1.0.2 — camera PTZ routing + +Release date: 2026-10-06. + +- Route device-scoped camera PTZ commands from the platform to Edge with MQTT QoS 1. +- Route correlated PTZ command results from Edge back to the platform with MQTT QoS 1. +- Preserve the existing device-scoped bridge allow-list for all other MQTT traffic. +- Apply the same contract to the optional legacy `it-screen` topic tree. + +Validation: generated bridge configuration and end-to-end ONVIF PTZ command test on UAE `g-box-c453df5f`. diff --git a/stage-releases.json b/stage-releases.json index 5e1332a..09ef489 100644 --- a/stage-releases.json +++ b/stage-releases.json @@ -8,13 +8,13 @@ "version": "1.0.0" }, "stage_mqtt": { - "version": "1.0.1" + "version": "1.0.2" }, "stage_z2m": { "version": "1.0.0" }, "stage_ui": { - "version": "3.1.18" + "version": "3.1.19" }, "stage_avahi": { "version": "1.0.0" @@ -23,7 +23,7 @@ "version": "1.0.0" }, "stage_itscreen": { - "version": "1.0.15" + "version": "1.0.18" }, "stage_reverse_tunnels": { "version": "1.0.1" @@ -31,7 +31,7 @@ }, "optional_stages": { "stage_ip_stream": { - "version": "1.0.4" + "version": "1.0.7" } } } diff --git a/stage_ip_stream/ip-stream.py b/stage_ip_stream/ip-stream.py index 2679b81..e356b19 100644 --- a/stage_ip_stream/ip-stream.py +++ b/stage_ip_stream/ip-stream.py @@ -7,6 +7,7 @@ import signal import socket import subprocess import shutil +import threading import time from pathlib import Path from urllib.parse import urlparse @@ -16,6 +17,7 @@ DEVICE_ID_PATH = Path("/userdata/device-id") ITSCREEN_CONFIG_PATH = Path("/var/lib/itscreen/config/it-screen/it-screen.conf") STATUS_PATH = Path("/run/iomatex-ip-stream/status.json") PREVIEW_ROOT = Path("/run/iomatex-ip-stream/hls") +CONTROL_SOCKET_PATH = Path("/run/iomatex-ip-stream/control.sock") SUPPORTED_INPUT_SCHEMES = {"rtsp"} SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"} MAX_STREAMS = 8 @@ -62,6 +64,28 @@ def output_arguments(output_url): return ["-f", "mpegts", output_url] +def stream_ttl(payload): + value = int(payload.get("ttl_sec") or PREVIEW_TTL_SEC) + if value < 60 or value > PREVIEW_TTL_SEC: + raise ValueError("invalid stream ttl") + return value + + +def video_arguments(payload): + if payload.get("low_latency") is not True: + return ["-c:v", "copy"] + profile = str(payload.get("profile") or "stream2") + bitrate = "2500k" if profile == "stream1" else "600k" + maxrate = "3000k" if profile == "stream1" else "750k" + bufsize = "6000k" if profile == "stream1" else "1500k" + return [ + "-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", + "-profile:v", "baseline", "-pix_fmt", "yuv420p", + "-g", "25", "-keyint_min", "25", "-sc_threshold", "0", + "-b:v", bitrate, "-maxrate", maxrate, "-bufsize", bufsize, + ] + + class StreamManager: def __init__(self, device=None, prefix=None): self.device = device or edge_id() @@ -71,6 +95,9 @@ class StreamManager: self.processes = {} self.started_at = int(time.time()) self.running = True + self.operation_lock = threading.RLock() + self.control_socket = None + self.supervisor_stop = threading.Event() def publish(self, payload): subprocess.run([ @@ -96,6 +123,11 @@ class StreamManager: self.write_status() return stopped + def supervise(self): + while not self.supervisor_stop.wait(1): + with self.operation_lock: + self.reap() + def write_status(self): STATUS_PATH.parent.mkdir(parents=True, exist_ok=True) temporary = STATUS_PATH.with_suffix(".tmp") @@ -118,22 +150,39 @@ class StreamManager: def start(self, payload): stream_id = validate_stream_id(payload.get("stream_id")) - if stream_id in self.processes: - return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": True} - if len(self.processes) >= MAX_STREAMS: - raise RuntimeError("stream limit reached") input_url = validate_url(payload.get("input_url"), SUPPORTED_INPUT_SCHEMES) output_url = validate_url(payload.get("output_url"), SUPPORTED_OUTPUT_SCHEMES) + low_latency = payload.get("low_latency") is True + profile = str(payload.get("profile") or "stream2") + expires_at = time.time() + stream_ttl(payload) + if stream_id in self.processes: + record = self.processes[stream_id] + if record.get("kind") != "forward": + raise RuntimeError("stream_id is already used by a preview stream") + if (record.get("input_url") == input_url and record.get("output_url") == output_url + and record.get("low_latency") == low_latency and record.get("profile") == profile): + record["expires_at"] = expires_at + self.write_status() + return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": True} + self.stop({"stream_id": stream_id}) + if len(self.processes) >= MAX_STREAMS: + raise RuntimeError("stream limit reached") command = [ "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "warning", "-rtsp_transport", "tcp", "-i", input_url, - "-map", "0:v:0", "-map", "0:a?", "-c", "copy", + "-map", "0:v:0", "-map", "0:a?", *video_arguments(payload), + "-c:a", "libopus", "-b:a", "64k", "-ar", "48000", "-ac", "1", + "-application", "lowdelay", "-frame_duration", "20", *output_arguments(output_url), ] self.processes[stream_id] = { "process": self.spawn(command), "kind": "forward", - "expires_at": 0, + "expires_at": expires_at, + "input_url": input_url, + "output_url": output_url, + "low_latency": low_latency, + "profile": profile, } self.write_status() return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False} @@ -175,7 +224,8 @@ class StreamManager: command = [ "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "warning", "-rtsp_transport", "tcp", "-i", input_url, - "-map", "0:v:0", "-an", "-c:v", "copy", + "-map", "0:v:0", "-map", "0:a?", "-c:v", "copy", + "-c:a", "aac", "-b:a", "64k", "-ar", "48000", "-ac", "1", "-f", "hls", "-hls_time", "1", "-hls_list_size", "5", "-hls_segment_type", "fmp4", "-hls_fmp4_init_filename", "init.mp4", "-hls_flags", "delete_segments+omit_endlist+independent_segments", @@ -230,6 +280,46 @@ class StreamManager: "snapshot": f"/api/camera-preview/{stream_id}/snapshot.jpg", } + def validate(self, payload): + input_url = validate_url(payload.get("input_url"), SUPPORTED_INPUT_SCHEMES) + command = [ + "ffprobe", "-v", "error", "-rtsp_transport", "tcp", + "-show_streams", "-show_format", "-of", "json", input_url, + ] + try: + result = subprocess.run( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + timeout=8, + check=False, + ) + except subprocess.TimeoutExpired as exc: + raise RuntimeError("Camera stream validation timed out") from exc + if result.returncode != 0: + raise RuntimeError("Camera stream is unreachable") + document = json.loads(result.stdout or "{}") + streams = document.get("streams") if isinstance(document, dict) else [] + streams = streams if isinstance(streams, list) else [] + video = next((item for item in streams if item.get("codec_type") == "video"), None) + audio = next((item for item in streams if item.get("codec_type") == "audio"), None) + if video is None: + raise RuntimeError("Camera stream has no video") + return { + "action": "validate", + "status": "ok", + "reachable": True, + "video": True, + "audio": audio is not None, + "video_codec": video.get("codec_name"), + "audio_codec": audio.get("codec_name") if audio else None, + "width": video.get("width"), + "height": video.get("height"), + "fps": video.get("avg_frame_rate"), + } + def stop(self, payload): stream_id = validate_stream_id(payload.get("stream_id")) record = self.processes.pop(stream_id, None) @@ -255,29 +345,82 @@ class StreamManager: "stopped": stopped, } - def handle(self, payload): + def dispatch(self, payload): action = str(payload.get("action") or "") try: - if action == "start": - response = self.start(payload) - elif action == "preview_start": - response = self.preview_start(payload) - elif action == "snapshot": - response = self.snapshot(payload) - elif action == "stop": - response = self.stop(payload) - elif action == "status": - response = self.status() - else: - return + with self.operation_lock: + if action == "start": + response = self.start(payload) + elif action == "preview_start": + response = self.preview_start(payload) + elif action == "snapshot": + response = self.snapshot(payload) + elif action == "validate": + response = self.validate(payload) + elif action == "stop": + response = self.stop(payload) + elif action == "status": + response = self.status() + else: + return {"action": action, "status": "error", "error": "unsupported action"} except Exception as exc: response = {"action": action, "status": "error", "error": str(exc)} if payload.get("stream_id"): response["stream_id"] = str(payload["stream_id"]) - self.publish(response) + return response + + def handle(self, payload): + input_url = urlparse(str(payload.get("input_url") or "")) + if input_url.username is not None or input_url.password is not None: + self.publish({ + "action": str(payload.get("action") or ""), + "status": "error", + "error": "credentialed stream URLs require the local control socket", + }) + return + response = self.dispatch(payload) + if response is not None: + self.publish(response) + + def serve_local(self): + CONTROL_SOCKET_PATH.unlink(missing_ok=True) + control = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.control_socket = control + control.bind(str(CONTROL_SOCKET_PATH)) + os.chmod(CONTROL_SOCKET_PATH, 0o600) + control.listen(4) + control.settimeout(1) + while self.running: + try: + client, _ = control.accept() + except socket.timeout: + continue + except OSError: + break + with client: + client.settimeout(20) + request = bytearray() + while len(request) <= 65536: + chunk = client.recv(16384) + if not chunk: + break + request.extend(chunk) + try: + payload = json.loads(request.decode("utf-8")) + if not isinstance(payload, dict): + raise ValueError("invalid request") + response = self.dispatch(payload) + except Exception: + response = {"status": "error", "error": "invalid request"} + client.sendall(json.dumps(response, separators=(",", ":")).encode("utf-8")) + control.close() + CONTROL_SOCKET_PATH.unlink(missing_ok=True) def shutdown(self, *_): self.running = False + self.supervisor_stop.set() + if self.control_socket is not None: + self.control_socket.close() for stream_id in list(self.processes): self.stop({"stream_id": stream_id}) @@ -285,6 +428,10 @@ class StreamManager: signal.signal(signal.SIGTERM, self.shutdown) signal.signal(signal.SIGINT, self.shutdown) self.write_status() + control_thread = threading.Thread(target=self.serve_local, name="ip-stream-control", daemon=True) + control_thread.start() + supervisor_thread = threading.Thread(target=self.supervise, name="ip-stream-supervisor", daemon=True) + supervisor_thread.start() command = [ "mosquitto_sub", "-h", "127.0.0.1", "-p", "1883", "-t", self.subscribe_topic, @@ -303,7 +450,11 @@ class StreamManager: if isinstance(payload, dict): self.handle(payload) process.terminate() - return process.wait(timeout=5) + exit_code = process.wait(timeout=5) + self.supervisor_stop.set() + control_thread.join(timeout=2) + supervisor_thread.join(timeout=2) + return exit_code if __name__ == "__main__": diff --git a/stage_ip_stream/stage_ip_stream_install.sh b/stage_ip_stream/stage_ip_stream_install.sh index 557b407..e07cb51 100644 --- a/stage_ip_stream/stage_ip_stream_install.sh +++ b/stage_ip_stream/stage_ip_stream_install.sh @@ -19,6 +19,10 @@ ffmpeg -version >/dev/null || { echo "FFmpeg is installed but cannot run; see package installation output above" >&2 exit 1 } +ffprobe -version >/dev/null || { + echo "FFprobe is required for ONVIF stream validation" >&2 + exit 1 +} getent group iomatex-stream >/dev/null 2>&1 || groupadd --system iomatex-stream id iomatex-stream >/dev/null 2>&1 || useradd --system --gid iomatex-stream --home-dir /nonexistent --shell /usr/sbin/nologin iomatex-stream diff --git a/stage_ip_stream/test_ip_stream.py b/stage_ip_stream/test_ip_stream.py index 805d139..696221f 100644 --- a/stage_ip_stream/test_ip_stream.py +++ b/stage_ip_stream/test_ip_stream.py @@ -1,4 +1,5 @@ import importlib.util +import json import pathlib import tempfile import unittest @@ -15,6 +16,7 @@ class IpStreamTest(unittest.TestCase): def test_installer_restarts_an_existing_service(self): installer = MODULE_PATH.with_name("stage_ip_stream_install.sh").read_text(encoding="utf-8") self.assertIn("systemctl restart iomatex-ip-stream.service", installer) + self.assertIn("ffprobe -version", installer) self.assertNotIn("enable --now iomatex-ip-stream.service", installer) def test_topics_follow_edge_profile(self): @@ -52,7 +54,86 @@ class IpStreamTest(unittest.TestCase): self.assertEqual(manager.spawn.call_count, 1) command = manager.spawn.call_args.args[0] self.assertIn("hls", command) - self.assertNotIn("-c:a", command) + self.assertEqual(command[command.index("-c:a") + 1], "aac") + self.assertIn("0:a?", command) + + def test_forward_uses_one_srt_process_and_refreshes_ttl(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + process = MagicMock() + process.poll.return_value = None + manager.spawn = MagicMock(return_value=process) + manager.write_status = MagicMock() + payload = { + "stream_id": "cdn-camera-a1b2", + "input_url": "rtsp://camera.local/stream2", + "output_url": "srt://cdn.dev.iomatex.com:8890?streamid=publish:edge/device/camera:user:secret", + "ttl_sec": 600, + } + + first = manager.start(payload) + first_expiry = manager.processes["cdn-camera-a1b2"]["expires_at"] + second = manager.start(payload) + + self.assertFalse(first["already_running"]) + self.assertTrue(second["already_running"]) + self.assertGreaterEqual(manager.processes["cdn-camera-a1b2"]["expires_at"], first_expiry) + self.assertEqual(manager.spawn.call_count, 1) + command = manager.spawn.call_args.args[0] + self.assertIn("-f", command) + self.assertIn("mpegts", command) + self.assertIn("-c:v", command) + self.assertIn("-c:a", command) + self.assertEqual(command[command.index("-c:a") + 1], "libopus") + self.assertEqual(command[command.index("-application") + 1], "lowdelay") + self.assertNotIn(payload["output_url"], json.dumps(manager.status())) + + def test_forward_low_latency_profile_transcodes_without_b_frames(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + process = MagicMock() + process.poll.return_value = None + manager.spawn = MagicMock(return_value=process) + manager.write_status = MagicMock() + payload = { + "stream_id": "cdn-camera-a1b2", + "input_url": "rtsp://camera.local/stream2", + "output_url": "srt://cdn.dev.iomatex.com:8890?streamid=publish:edge/device/camera:user:secret", + "ttl_sec": 600, + "low_latency": True, + "profile": "stream2", + } + + manager.start(payload) + + command = manager.spawn.call_args.args[0] + self.assertEqual(command[command.index("-c:v") + 1], "libx264") + self.assertEqual(command[command.index("-profile:v") + 1], "baseline") + self.assertEqual(command[command.index("-g") + 1], "25") + self.assertEqual(command[command.index("-b:v") + 1], "600k") + + def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + expired = MagicMock(pid=1001) + expired.poll.return_value = None + expired.wait.return_value = 0 + dead = MagicMock(pid=1002) + dead.poll.return_value = 7 + manager.processes = { + "expired": {"process": expired, "kind": "forward", "expires_at": 1}, + "dead": {"process": dead, "kind": "forward", "expires_at": 0}, + } + manager.write_status = MagicMock() + + with patch.object(stream.os, "killpg") as killpg: + stopped = manager.reap() + + self.assertEqual(manager.processes, {}) + self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"}) + killpg.assert_called_once_with(1001, stream.signal.SIGTERM) + + def test_run_starts_periodic_supervisor(self): + source = MODULE_PATH.read_text(encoding="utf-8") + self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source) + self.assertIn("while not self.supervisor_stop.wait(1)", source) def test_snapshot_is_written_atomically_as_jpeg(self): manager = stream.StreamManager("g-box-test", "it-screen/dev") @@ -78,6 +159,41 @@ class IpStreamTest(unittest.TestCase): self.assertIn("-frames:v", ffmpeg) self.assertIn("snapshot.tmp.jpg", ffmpeg[-1]) + def test_preview_credentials_use_local_socket_not_mqtt(self): + console = MODULE_PATH.parents[1] / "stage_ui" / "console_core" / "backend" / "app.py" + source = console.read_text(encoding="utf-8") + start = source.index("def publish_camera_preview") + end = source.index("def wait_camera_preview", start) + transport = source[start:end] + + self.assertIn("socket.AF_UNIX", transport) + self.assertIn("IOMATEX_IP_STREAM_SOCKET_PATH", transport) + self.assertNotIn("mosquitto_pub", transport) + + def test_mqtt_rejects_credentialed_stream_urls(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + manager.publish = MagicMock() + manager.dispatch = MagicMock() + + manager.handle({ + "action": "preview_start", + "input_url": "rtsp://camera-user:camera-password@192.168.70.174/stream2", + }) + + manager.dispatch.assert_not_called() + self.assertEqual(manager.publish.call_args.args[0]["status"], "error") + + def test_validate_reports_actual_video_stream(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + completed = MagicMock(returncode=0, stdout='{"streams":[{"codec_type":"video","codec_name":"h264","width":1920,"height":1080},{"codec_type":"audio","codec_name":"aac"}]}') + with patch.object(stream.subprocess, "run", return_value=completed) as command: + result = manager.validate({"input_url": "rtsp://camera.local/main"}) + + self.assertTrue(result["reachable"]) + self.assertEqual(result["video_codec"], "h264") + self.assertEqual(result["audio_codec"], "aac") + self.assertIn("ffprobe", command.call_args.args[0]) + if __name__ == "__main__": unittest.main() diff --git a/stage_ip_stream/version.json b/stage_ip_stream/version.json index 82624d0..bcf6b6e 100644 --- a/stage_ip_stream/version.json +++ b/stage_ip_stream/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.4" + "version": "1.0.7" } diff --git a/stage_itscreen/itscreen b/stage_itscreen/itscreen index be2d7e7..d4852a7 100755 Binary files a/stage_itscreen/itscreen and b/stage_itscreen/itscreen differ diff --git a/stage_itscreen/itscreen.sha256 b/stage_itscreen/itscreen.sha256 index 63d3f19..aadb82d 100644 --- a/stage_itscreen/itscreen.sha256 +++ b/stage_itscreen/itscreen.sha256 @@ -1 +1 @@ -deac040b3fc30181e180217f4d92e84ad3445575bbae8835b62327d0cb08fa75 itscreen +0fe52ad80f29e31d204e49764ae5e7a89216a53b52b974d8387a7d63f0350a97 itscreen diff --git a/stage_itscreen/itscreen.version b/stage_itscreen/itscreen.version index 198d2fe..35330d0 100644 --- a/stage_itscreen/itscreen.version +++ b/stage_itscreen/itscreen.version @@ -1 +1 @@ -4.410.143 +4.410.147 diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh index 350a1f1..a721c7b 100755 --- a/stage_itscreen/stage_itscreen_install.sh +++ b/stage_itscreen/stage_itscreen_install.sh @@ -392,7 +392,7 @@ ensure_runtime_directories() { ensure_dir /etc/X11/Xsession.d 0755 root root ensure_dir /etc/systemd/system 0755 root root ensure_dir /usr/local/bin 0755 root root - ensure_dir "$ITS_RUN_DIR" 0755 root root + ensure_dir "$ITS_RUN_DIR" 0755 "$ITS_USER" "$ITS_GROUP" rm -f /var/lib/itscreen/.asoundrc } @@ -972,7 +972,7 @@ XORG_BIN="$(command -v Xorg || true)" exit 1 } -install -d -m 0755 -o root -g root /run/itscreen + install -d -m 0755 -o itscreen -g itscreen /run/itscreen install -d -m 0700 -o itscreen -g itscreen /run/itscreen/xdg rm -f /run/itscreen/Xauthority : >/run/itscreen/Xauthority @@ -1287,6 +1287,7 @@ ExecStartPre=-/usr/local/bin/itscreen-boot-trace pre-start ExecStartPre=/usr/bin/nm-online -s -q --timeout=45 # Monitor presence is not required for startup; always attempt the dedicated X11 launch flow, including headless mode. ExecStartPre=/usr/local/bin/itscreen-x11-cleanup +ExecStartPre=/bin/chown itscreen:itscreen /run/itscreen ExecStart=/usr/local/bin/itscreen-x11-launch ExecStartPost=-/usr/local/bin/itscreen-boot-trace start-post ExecStopPost=-/usr/local/bin/itscreen-boot-trace stop-post diff --git a/stage_itscreen/version.json b/stage_itscreen/version.json index 731efdc..a487148 100644 --- a/stage_itscreen/version.json +++ b/stage_itscreen/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.15" + "version": "1.0.18" } diff --git a/stage_mqtt/stage_mqtt_install.sh b/stage_mqtt/stage_mqtt_install.sh index 603ec51..b8142d8 100755 --- a/stage_mqtt/stage_mqtt_install.sh +++ b/stage_mqtt/stage_mqtt_install.sh @@ -439,6 +439,7 @@ topic iomatex/+/client/pub/${DEVICE_ID} out 0 "" "" topic iomatex/+/client/pub/action/${DEVICE_ID} out 0 "" "" topic iomatex/+/client/pub/module/${DEVICE_ID}/scanning out 0 "" "" topic iomatex/+/client/pub/camera/${DEVICE_ID}/scanning out 0 "" "" +topic iomatex/+/client/pub/camera/${DEVICE_ID}/ptz out 1 "" "" topic iomatex/+/client/pub/response/event/push out 0 "" "" topic iomatex/+/client/pub/interface/${DEVICE_ID}/# out 0 "" "" topic iomatex/+/client/pub/interface/meta/${DEVICE_ID} out 0 "" "" @@ -463,6 +464,7 @@ topic iomatex/+/client/sub/config/${DEVICE_ID} in 0 "" "" topic iomatex/+/client/sub/action/${DEVICE_ID} in 0 "" "" topic iomatex/+/client/sub/module/${DEVICE_ID}/scanning in 0 "" "" topic iomatex/+/client/sub/camera/${DEVICE_ID}/scanning in 0 "" "" +topic iomatex/+/client/sub/camera/${DEVICE_ID}/ptz in 1 "" "" topic iomatex/+/client/sub/event/speech/widget/${DEVICE_ID} in 0 "" "" topic iomatex/+/client/sub/interface/${DEVICE_ID} in 0 "" "" topic iomatex/+/client/sub/interface/action/${DEVICE_ID} in 0 "" "" @@ -486,6 +488,7 @@ topic it-screen/+/client/pub/${DEVICE_ID} out 0 "" "" topic it-screen/+/client/pub/action/${DEVICE_ID} out 0 "" "" topic it-screen/+/client/pub/module/${DEVICE_ID}/scanning out 0 "" "" topic it-screen/+/client/pub/camera/${DEVICE_ID}/scanning out 0 "" "" +topic it-screen/+/client/pub/camera/${DEVICE_ID}/ptz out 1 "" "" topic it-screen/+/client/pub/response/event/push out 0 "" "" topic it-screen/+/client/pub/interface/${DEVICE_ID}/# out 0 "" "" topic it-screen/+/client/pub/interface/meta/${DEVICE_ID} out 0 "" "" @@ -510,6 +513,7 @@ topic it-screen/+/client/sub/config/${DEVICE_ID} in 0 "" "" topic it-screen/+/client/sub/action/${DEVICE_ID} in 0 "" "" topic it-screen/+/client/sub/module/${DEVICE_ID}/scanning in 0 "" "" topic it-screen/+/client/sub/camera/${DEVICE_ID}/scanning in 0 "" "" +topic it-screen/+/client/sub/camera/${DEVICE_ID}/ptz in 1 "" "" topic it-screen/+/client/sub/event/speech/widget/${DEVICE_ID} in 0 "" "" topic it-screen/+/client/sub/interface/${DEVICE_ID} in 0 "" "" topic it-screen/+/client/sub/interface/action/${DEVICE_ID} in 0 "" "" diff --git a/stage_mqtt/version.json b/stage_mqtt/version.json index ca84e70..9a8bfb2 100644 --- a/stage_mqtt/version.json +++ b/stage_mqtt/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.1" + "version": "1.0.2" } diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 54ce69a..4b3cb97 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -10,6 +10,7 @@ import shutil import re import secrets import select +import socket import struct import threading import subprocess @@ -22,7 +23,7 @@ import spwd from datetime import datetime from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from urllib.parse import parse_qs, urlparse +from urllib.parse import parse_qs, quote, urlparse, urlsplit, urlunsplit from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from itscreen_registration import get_reverse_tunnel_diagnostics, configure_reverse_tunnel, get_registration_status, register_device, reset_registration from modbus_backend import ( @@ -54,7 +55,7 @@ APP_DIR = "/opt/iomatex-console" PUBLIC_DIR = os.path.join(APP_DIR, "public") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") CONFIG_PATH = "/etc/iomatex/console.json" -UI_VERSION = "V 3.1.18" +UI_VERSION = "V 3.1.19" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" ZONEINFO_ROOT = "/usr/share/zoneinfo" @@ -101,6 +102,8 @@ IOMATEX_PULSE_APPLY_SCRIPT = "/usr/local/bin/iomatex-pulse-apply-route" IOMATEX_AUDIO_ROUTE_PATH = "/etc/iomatex/audio-route.env" IOMATEX_IP_STREAM_STATUS_PATH = "/run/iomatex-ip-stream/status.json" IOMATEX_IP_STREAM_HLS_ROOT = "/run/iomatex-ip-stream/hls" +IOMATEX_IP_STREAM_SOCKET_PATH = "/run/iomatex-ip-stream/control.sock" +ITSCREEN_ONVIF_SOCKET_PATH = "/run/itscreen/onvif.sock" IOMATEX_DUAL_SINK_NAME = "iomatex_dual_output" ITSCREEN_CONFIG_CACHE_TTL_SEC = 3.0 ITSCREEN_LOG_DEFAULT_LINES = 100 @@ -212,23 +215,22 @@ def run(cmd, timeout=4, env=None): def publish_camera_preview(payload): - with open(DEVICE_ID_PATH, "r", encoding="utf-8") as device_file: - device_id = device_file.read().strip() - prefix = read_simple_key_value_file(ITSCREEN_CONFIG_PATH).get("mqttPrefix", "").strip().strip("/") - if not prefix: - raise RuntimeError("MQTT prefix is not configured") - topic = f"{prefix}/client/sub/camera/{device_id}/stream" - process = subprocess.run( - ["mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", "-t", topic, "-s"], - input=json.dumps(payload, separators=(",", ":")), - stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE, - text=True, - timeout=5, - check=False, - ) - if process.returncode != 0: - raise RuntimeError((process.stderr or "Unable to start camera preview").strip()) + body = json.dumps(payload, separators=(",", ":")).encode("utf-8") + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(20) + client.connect(IOMATEX_IP_STREAM_SOCKET_PATH) + client.sendall(body) + client.shutdown(socket.SHUT_WR) + response = bytearray() + while len(response) <= 65536: + chunk = client.recv(16384) + if not chunk: + break + response.extend(chunk) + result = json.loads(response.decode("utf-8")) if response else {} + if not isinstance(result, dict) or result.get("status") != "ok": + raise RuntimeError("Unable to start camera media operation") + return result def wait_camera_preview(stream_id, timeout=12): @@ -255,6 +257,107 @@ def wait_camera_snapshot(stream_id, previous_mtime_ns=0, timeout=20): raise RuntimeError("Camera did not produce a snapshot in time") +def request_onvif_client(payload, allowed_actions): + request = payload if isinstance(payload, dict) else {} + action = str(request.get("action", "")).strip() + if action not in allowed_actions: + raise ValueError("Invalid ONVIF action") + xaddr = str(request.get("xaddr", "")).strip() + username = str(request.get("username", "")).strip() + password = str(request.get("password", "")) + parsed = urlparse(xaddr) + try: + address = ipaddress.ip_address(parsed.hostname or "") + except ValueError as error: + raise ValueError("Invalid ONVIF endpoint") from error + if parsed.scheme not in {"http", "https"} or not (address.is_private or address.is_link_local): + raise ValueError("ONVIF endpoint must use a local IP address") + if not username or not password or any(char in username + password for char in ("\x00", "\r", "\n")): + raise ValueError("Camera credentials are required") + + body = json.dumps(request, separators=(",", ":")).encode("utf-8") + if len(body) > 16384: + raise ValueError("ONVIF probe request is too large") + + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(45) + client.connect(ITSCREEN_ONVIF_SOCKET_PATH) + client.sendall(body) + response = bytearray() + while len(response) <= 262144: + chunk = client.recv(65536) + if not chunk: + break + response.extend(chunk) + if not response or len(response) > 262144: + raise RuntimeError("Invalid response from the ONVIF client") + result = json.loads(response.decode("utf-8")) + if not isinstance(result, dict): + raise RuntimeError("Invalid response from the ONVIF client") + return result + + +def probe_onvif_camera(payload): + request = dict(payload) if isinstance(payload, dict) else {} + request["action"] = "probe" + username = str(request.get("username", "")).strip() + password = str(request.get("password", "")) + result = request_onvif_client(request, {"probe"}) + probe = result.get("probe") if result.get("ok") is True else None + streams = probe.get("streams") if isinstance(probe, dict) else None + if isinstance(streams, list): + validated = [] + for stream in streams[:2]: + current = dict(stream) if isinstance(stream, dict) else {} + parsed_stream = urlsplit(str(current.get("uri", ""))) + try: + stream_address = ipaddress.ip_address(parsed_stream.hostname or "") + except ValueError: + stream_address = None + if parsed_stream.scheme.lower() != "rtsp" or stream_address is None or not (stream_address.is_private or stream_address.is_link_local): + current["reachable"] = False + validated.append(current) + continue + host = f"[{parsed_stream.hostname}]" if stream_address.version == 6 else parsed_stream.hostname + netloc = f"{quote(username, safe='')}:{quote(password, safe='')}@{host}" + if parsed_stream.port: + netloc += f":{parsed_stream.port}" + credentialed_uri = urlunsplit((parsed_stream.scheme, netloc, parsed_stream.path, parsed_stream.query, parsed_stream.fragment)) + try: + validation = publish_camera_preview({"action": "validate", "input_url": credentialed_uri}) + current.update({key: value for key, value in validation.items() if key not in {"action", "status"}}) + except Exception: + current["reachable"] = False + validated.append(current) + reachable_indexes = [index for index, stream in enumerate(validated) if stream.get("reachable")] + if reachable_indexes: + by_resolution = sorted( + reachable_indexes, + key=lambda index: int(validated[index].get("width") or 0) * int(validated[index].get("height") or 0), + ) + validated[by_resolution[-1]]["role"] = "main_stream" + if len(by_resolution) > 1: + validated[by_resolution[0]]["role"] = "sub_stream" + probe["streams"] = validated + if any(stream.get("reachable") for stream in validated): + probe["state"] = "READY" + probe["stream_state"] = "STREAM_READY" + elif validated: + probe["stream_state"] = "STREAM_FAILED" + return result + + +def control_onvif_camera(payload): + request = dict(payload) if isinstance(payload, dict) else {} + action = str(request.get("action", "")).strip() + if action == "ptz": + command = str(request.get("command", "")).strip() + if command not in {"pan_left", "pan_right", "tilt_up", "tilt_down", "home"}: + raise ValueError("Invalid PTZ command") + request["active"] = bool(request.get("active", False)) + return request_onvif_client(request, {"ptz_prepare", "ptz"}) + + def _auth_now(): return time.time() @@ -3206,7 +3309,10 @@ class Handler(BaseHTTPRequestHandler): def require_auth(self, parsed): if ( - parsed.path.startswith("/api/camera-preview/") + ( + parsed.path.startswith("/api/camera-preview/") + or parsed.path in {"/api/onvif/ptz", "/api/camera-stream/start"} + ) and self.headers.get("X-Iomatex-Gateway-Authorized") == "1" and self.client_address[0] in {"127.0.0.1", "::1"} ): @@ -3533,6 +3639,31 @@ class Handler(BaseHTTPRequestHandler): return if not self.require_auth(parsed): return + if parsed.path == "/api/onvif/probe": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + try: + self.send_json(probe_onvif_camera(payload)) + except ValueError as exc: + self.send_json({"ok": False, "error": str(exc)}, code=400) + except Exception: + self.send_json({"ok": False, "error": "ONVIF client is unavailable"}, code=503) + return + if parsed.path == "/api/onvif/ptz": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + try: + result = control_onvif_camera(payload) + self.send_json(result, code=200 if result.get("ok") is True else 502) + except ValueError as exc: + self.send_json({"ok": False, "error": str(exc)}, code=400) + except Exception: + self.send_json({"ok": False, "error": "ONVIF PTZ client is unavailable"}, code=503) + return if parsed.path == "/api/camera-preview/start": payload = self.read_json_body() stream_id = str((payload or {}).get("stream_id", "")) @@ -3555,6 +3686,41 @@ class Handler(BaseHTTPRequestHandler): except Exception as exc: self.send_json({"ok": False, "error": str(exc)}, code=503) return + if parsed.path == "/api/camera-stream/start": + payload = self.read_json_body() + stream_id = str((payload or {}).get("stream_id", "")) + input_url = str((payload or {}).get("input_url", "")) + output_url = str((payload or {}).get("output_url", "")) + try: + ttl_sec = int((payload or {}).get("ttl_sec", 600) or 600) + except (TypeError, ValueError): + ttl_sec = 0 + if ( + not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", stream_id) + or not input_url.startswith("rtsp://") + or not re.match(r"^(srt|rtmp|rtsp|udp)://", output_url) + or ttl_sec < 60 + or ttl_sec > 600 + ): + self.send_json({"ok": False, "error": "Invalid camera stream request"}, code=400) + return + try: + result = publish_camera_preview({ + "action": "start", + "stream_id": stream_id, + "input_url": input_url, + "output_url": output_url, + "ttl_sec": ttl_sec, + }) + self.send_json({ + "ok": True, + "stream_id": stream_id, + "already_running": result.get("already_running") is True, + "expires_in": ttl_sec, + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=503) + return if parsed.path == "/api/camera-preview/snapshot": payload = self.read_json_body() stream_id = str((payload or {}).get("stream_id", "")) @@ -3597,7 +3763,11 @@ class Handler(BaseHTTPRequestHandler): if payload.get("confirmed") is not True: raise ValueError("Explicit confirmation is required") if parsed.path == "/api/stages/install-all": - job = stage_versions.start_install_all(payload.get("stages"), payload.get("commit"), build_status_payload().get("services", [])) + job = stage_versions.start_install_all( + payload.get("stages"), + payload.get("commit"), + build_status_payload().get("services", []), + ) else: job = stage_versions.start_install(payload.get("stage"), payload.get("commit")) self.send_json({"ok": True, "job": job}, code=202) diff --git a/stage_ui/console_core/backend/test_camera_preview_contract.py b/stage_ui/console_core/backend/test_camera_preview_contract.py index b702fb1..a503cb6 100644 --- a/stage_ui/console_core/backend/test_camera_preview_contract.py +++ b/stage_ui/console_core/backend/test_camera_preview_contract.py @@ -10,14 +10,23 @@ class CameraPreviewContractTest(unittest.TestCase): source = ROOT.read_text(encoding="utf-8") self.assertIn('X-Iomatex-Gateway-Authorized', source) self.assertIn('self.client_address[0] in {"127.0.0.1", "::1"}', source) + self.assertIn('"/api/camera-stream/start"', source) self.assertIn('CAMERA_PREVIEW_PATH_RE.fullmatch', source) self.assertIn('snapshot\\.jpg', source) self.assertIn('"action": "preview_start"', source) self.assertIn('"action": "snapshot"', source) + self.assertIn('IOMATEX_IP_STREAM_SOCKET_PATH', source) self.assertIn('wait_camera_snapshot(stream_id, previous_mtime_ns)', source) self.assertIn('content_type = "image/jpeg"', source) self.assertIn('"Access-Control-Allow-Origin": "*"', source) + def test_cdn_forward_is_started_through_the_local_stream_socket(self): + source = ROOT.read_text(encoding="utf-8") + self.assertIn('parsed.path == "/api/camera-stream/start"', source) + self.assertIn('"action": "start"', source) + self.assertIn('"output_url": output_url', source) + self.assertIn('"ttl_sec": ttl_sec', source) + if __name__ == "__main__": unittest.main() diff --git a/stage_ui/console_core/backend/test_embedded_console_navigation_contract.py b/stage_ui/console_core/backend/test_embedded_console_navigation_contract.py index 8fddff7..f194889 100644 --- a/stage_ui/console_core/backend/test_embedded_console_navigation_contract.py +++ b/stage_ui/console_core/backend/test_embedded_console_navigation_contract.py @@ -23,8 +23,11 @@ class EmbeddedConsoleNavigationContractTest(unittest.TestCase): self.assertNotIn("window.confirm", reset_source) def test_webui_service_is_named_edge_console(self): - self.assertIn('label: "Edge Console"', self.source) - self.assertNotIn('label: "Edge WEB UI"', self.source) + help_start = self.source.index('"console": {') + help_end = self.source.index('"environment": {', help_start) + console_help = self.source[help_start:help_end] + self.assertIn('"en": "Edge Console"', console_help) + self.assertNotIn('Edge WEB UI', console_help) if __name__ == "__main__": diff --git a/stage_ui/console_core/backend/test_onvif_probe.py b/stage_ui/console_core/backend/test_onvif_probe.py new file mode 100644 index 0000000..1973a30 --- /dev/null +++ b/stage_ui/console_core/backend/test_onvif_probe.py @@ -0,0 +1,122 @@ +import importlib.util +import json +import pathlib +import sys +import unittest +from unittest import mock + + +BACKEND_DIR = pathlib.Path(__file__).parent +sys.path.insert(0, str(BACKEND_DIR)) +SPEC = importlib.util.spec_from_file_location("iomatex_console_onvif_app", BACKEND_DIR / "app.py") +APP = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(APP) + + +class FakeSocket: + def __init__(self, response): + self.response = response + self.sent = b"" + self.connected_path = None + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + def settimeout(self, _timeout): + pass + + def connect(self, path): + self.connected_path = path + + def sendall(self, body): + self.sent = body + + def recv(self, _size): + response, self.response = self.response, b"" + return response + + +class OnvifProbeTest(unittest.TestCase): + def test_forwards_credentials_only_over_local_socket(self): + client = FakeSocket(json.dumps({"ok": True, "state": "IDENTIFIED"}).encode()) + with mock.patch.object(APP.socket, "socket", return_value=client): + result = APP.probe_onvif_camera({ + "xaddr": "http://192.168.70.174:2020/onvif/device_service", + "username": "camera-user", + "password": "camera-password", + }) + + self.assertTrue(result["ok"]) + self.assertEqual(client.connected_path, APP.ITSCREEN_ONVIF_SOCKET_PATH) + self.assertEqual(json.loads(client.sent), { + "action": "probe", + "xaddr": "http://192.168.70.174:2020/onvif/device_service", + "username": "camera-user", + "password": "camera-password", + }) + + def test_forwards_valid_ptz_command_only_over_local_socket(self): + client = FakeSocket(json.dumps({"ok": True}).encode()) + with mock.patch.object(APP.socket, "socket", return_value=client): + result = APP.control_onvif_camera({ + "action": "ptz", + "xaddr": "http://192.168.70.174:2020/onvif/device_service", + "username": "camera-user", + "password": "camera-password", + "command": "pan_left", + "active": True, + }) + + self.assertTrue(result["ok"]) + self.assertEqual(json.loads(client.sent)["command"], "pan_left") + + def test_forwards_home_ptz_command(self): + client = FakeSocket(json.dumps({"ok": True}).encode()) + with mock.patch.object(APP.socket, "socket", return_value=client): + result = APP.control_onvif_camera({ + "action": "ptz", + "xaddr": "http://192.168.70.174:2020/onvif/device_service", + "username": "camera-user", + "password": "camera-password", + "command": "home", + "active": True, + }) + + self.assertTrue(result["ok"]) + self.assertEqual(json.loads(client.sent)["command"], "home") + + def test_rejects_public_or_named_hosts(self): + invalid_endpoints = ( + "http://example.com/onvif/device_service", + "http://8.8.8.8/onvif/device_service", + "ftp://192.168.70.174/onvif/device_service", + ) + for endpoint in invalid_endpoints: + with self.subTest(endpoint=endpoint): + with self.assertRaises(ValueError): + APP.probe_onvif_camera({ + "xaddr": endpoint, + "username": "user", + "password": "password", + }) + + def test_route_is_authenticated_and_hides_internal_errors(self): + source = (BACKEND_DIR / "app.py").read_text(encoding="utf-8") + auth_index = source.index("if not self.require_auth(parsed):", source.index("def do_POST")) + route_index = source.index('if parsed.path == "/api/onvif/probe":', auth_index) + ptz_index = source.index('if parsed.path == "/api/onvif/ptz":', route_index) + preview_index = source.index('if parsed.path == "/api/camera-preview/start":', ptz_index) + + self.assertLess(auth_index, route_index) + self.assertLess(route_index, ptz_index) + self.assertLess(ptz_index, preview_index) + self.assertIn('or parsed.path in {"/api/onvif/ptz", "/api/camera-stream/start"}', source) + self.assertIn('"ONVIF client is unavailable"', source[route_index:ptz_index]) + self.assertIn('"ONVIF PTZ client is unavailable"', source[ptz_index:preview_index]) + + +if __name__ == "__main__": + unittest.main() diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 849d81a..b4723f4 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -49,7 +49,7 @@ { mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" }, { mode: "custom", label: "Custom", host: "" } ]; - const UI_VERSION = "V 3.1.18"; + const UI_VERSION = "V 3.1.19"; const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BATCH_MS = 250; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 8794393..38648b5 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -23,7 +23,7 @@ } catch (error) {} })(); - +