From 495740292a4afed5ee043b59e54d5f138a30cfa6 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:45:14 +0100 Subject: [PATCH] feat(web): add camera-scoped WebRTC live view --- docker/docker-compose.prod.yml | 8 +- docker/docker-compose.webrtc-local-test.yml | 58 +++++++ docker/docker-compose.webrtc-test.yml | 22 +++ docker/docker-compose.webrtc.yml | 25 +++ docker/docker-compose.yml | 8 + docker/mediamtx.local-test.yml | 17 ++ docker/mediamtx.synthetic-source.yml | 15 ++ docker/mediamtx.yml | 23 +++ docs/docker-compose.md | 77 ++++++++- skills/webrtc-live/SKILL.md | 72 ++++++++ src/Heimdall.Agent/Program.cs | 1 + .../Services/LiveCameraRelayService.cs | 116 +++++++++++++ .../Components/Pages/CameraDetail.razor | 47 ++++- .../Controllers/LiveMediaController.cs | 162 ++++++++++++++++++ .../Localization/SharedResources.en.resx | 6 +- .../Localization/SharedResources.fr.resx | 6 +- .../Localization/SharedResources.resx | 6 +- src/Heimdall.Web/Program.cs | 2 + .../Security/LiveMediaSessionLimiter.cs | 72 ++++++++ src/Heimdall.Web/Security/LiveMediaTickets.cs | 55 ++++++ src/Heimdall.Web/wwwroot/js/live-view.js | 44 +++++ .../LiveCameraRelayServiceTests.cs | 32 ++++ .../LiveMediaSessionLimiterTests.cs | 33 ++++ .../LiveMediaTicketsTests.cs | 52 ++++++ todo.md | 4 +- 25 files changed, 954 insertions(+), 9 deletions(-) create mode 100644 docker/docker-compose.webrtc-local-test.yml create mode 100644 docker/docker-compose.webrtc-test.yml create mode 100644 docker/docker-compose.webrtc.yml create mode 100644 docker/mediamtx.local-test.yml create mode 100644 docker/mediamtx.synthetic-source.yml create mode 100644 docker/mediamtx.yml create mode 100644 skills/webrtc-live/SKILL.md create mode 100644 src/Heimdall.Agent/Services/LiveCameraRelayService.cs create mode 100644 src/Heimdall.Web/Controllers/LiveMediaController.cs create mode 100644 src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs create mode 100644 src/Heimdall.Web/Security/LiveMediaTickets.cs create mode 100644 src/Heimdall.Web/wwwroot/js/live-view.js create mode 100644 tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs create mode 100644 tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs create mode 100644 tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index c86591f..932c387 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -47,6 +47,12 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-} + LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-} + LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false} + LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} + LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} + LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} Sentry__Dsn: ${SENTRY_DSN:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05} Sentry__Release: ${SENTRY_RELEASE:-} @@ -91,5 +97,5 @@ secrets: networks: heimdall-net: - name: heimdall-net + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} driver: bridge diff --git a/docker/docker-compose.webrtc-local-test.yml b/docker/docker-compose.webrtc-local-test.yml new file mode 100644 index 0000000..5ae6683 --- /dev/null +++ b/docker/docker-compose.webrtc-local-test.yml @@ -0,0 +1,58 @@ +# Loopback-only media services for disposable acceptance, never production. +services: + mediamtx: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + environment: + HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} + MTX_AUTHMETHOD: http + MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL} + ports: + - "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp" + - "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp" + - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:8189/udp" + volumes: + - ./mediamtx.local-test.yml:/mediamtx.yml:ro + networks: + - heimdall-net + + heimdall-agent: + image: heimdall-agent:webrtc-test + build: + context: .. + dockerfile: docker/Dockerfile.agent + restart: unless-stopped + network_mode: host + user: "1654:1654" + environment: + ASPNETCORE_URLS: http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081} + Agent__CentralUrl: http://127.0.0.1:${WEB_PORT:-5000} + Agent__AllowInsecureHttp: "true" + Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:-} + Agent__AgentName: webrtc-synthetic-agent + Agent__StateDirectory: /var/lib/heimdall + volumes: + - heimdall_agent_state:/var/lib/heimdall + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}/healthz"] + interval: 10s + timeout: 3s + retries: 3 + start_period: 20s + depends_on: + agent-state-init: + condition: service_completed_successfully + + agent-state-init: + image: heimdall-agent:webrtc-test + build: + context: .. + dockerfile: docker/Dockerfile.agent + user: "0:0" + entrypoint: ["chown", "-R", "1654:1654", "/state"] + volumes: + - heimdall_agent_state:/state + restart: "no" + +volumes: + heimdall_agent_state: diff --git a/docker/docker-compose.webrtc-test.yml b/docker/docker-compose.webrtc-test.yml new file mode 100644 index 0000000..1c02a98 --- /dev/null +++ b/docker/docker-compose.webrtc-test.yml @@ -0,0 +1,22 @@ +# Test-only synthetic camera source. Exposes one local RTSP port so an Agent +# can be configured through Central to pull this generated H.264 stream. +services: + synthetic-camera: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + ports: + - "127.0.0.1:${HEIMDALL_SYNTHETIC_RTSP_PORT:-18554}:8554/tcp" + volumes: + - ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro + networks: + - heimdall-net + + synthetic-camera-publisher: + image: jrottenberg/ffmpeg:7.1-alpine + restart: unless-stopped + entrypoint: ["/bin/sh", "-c"] + command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -profile:v baseline -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 2; done"] + depends_on: + - synthetic-camera + networks: + - heimdall-net diff --git a/docker/docker-compose.webrtc.yml b/docker/docker-compose.webrtc.yml new file mode 100644 index 0000000..4fd8ede --- /dev/null +++ b/docker/docker-compose.webrtc.yml @@ -0,0 +1,25 @@ +# Optional MediaMTX for live camera video. Start after the core stack has +# created heimdall-net. Public DNS and certificates are deployment supplied. +services: + mediamtx: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + environment: + HEIMDALL_WEBRTC_PUBLIC_HOST: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname} + HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} + MTX_AUTHMETHOD: http + MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL} + ports: + - "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp" + - "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp" + - "${HEIMDALL_WEBRTC_UDP_PORT:-8189}:8189/udp" + volumes: + - ./mediamtx.yml:/mediamtx.yml:ro + - ${HEIMDALL_LIVE_MEDIA_CERT_DIR:?Set directory containing server.crt and server.key}:/certs:ro + networks: + - heimdall-net + +networks: + heimdall-net: + external: true + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 2435dda..b5a4177 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -36,6 +36,13 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-} + LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-} + LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false} + LiveMedia__AllowInsecureHttp: ${HEIMDALL_ALLOW_INSECURE_HTTP:-false} + LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} + LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} + LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} ports: - "${WEB_PORT:-5000}:8080" volumes: @@ -61,4 +68,5 @@ volumes: networks: heimdall-net: + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} driver: bridge diff --git a/docker/mediamtx.local-test.yml b/docker/mediamtx.local-test.yml new file mode 100644 index 0000000..2ac6cd9 --- /dev/null +++ b/docker/mediamtx.local-test.yml @@ -0,0 +1,17 @@ +# Loopback-only insecure listeners for disposable workstation acceptance only. +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: "no" +rtspAddress: :8554 +webrtc: true +webrtcAddress: :8889 +webrtcEncryption: false +webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcLocalUDPAddress: :8189 +webrtcAdditionalHosts: ['127.0.0.1'] +pathDefaults: + source: publisher + record: false +paths: + all_others: diff --git a/docker/mediamtx.synthetic-source.yml b/docker/mediamtx.synthetic-source.yml new file mode 100644 index 0000000..55a72b0 --- /dev/null +++ b/docker/mediamtx.synthetic-source.yml @@ -0,0 +1,15 @@ +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: "no" +rtspAddress: :8554 +authMethod: internal +authInternalUsers: + - user: any + pass: + ips: [] + permissions: + - action: publish + - action: read +paths: + all_others: diff --git a/docker/mediamtx.yml b/docker/mediamtx.yml new file mode 100644 index 0000000..a60015a --- /dev/null +++ b/docker/mediamtx.yml @@ -0,0 +1,23 @@ +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: strict +rtspsAddress: :8322 +rtspServerCert: /certs/server.crt +rtspServerKey: /certs/server.key + +webrtc: true +webrtcAddress: :8889 +webrtcEncryption: true +webrtcServerCert: /certs/server.crt +webrtcServerKey: /certs/server.key +webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcLocalUDPAddress: :8189 +webrtcAdditionalHosts: ['${HEIMDALL_WEBRTC_PUBLIC_HOST}'] + +pathDefaults: + source: publisher + record: false + +paths: + all_others: diff --git a/docs/docker-compose.md b/docs/docker-compose.md index a261a83..2e1c4ae 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -138,7 +138,7 @@ docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d Configure Ollama at `http://ollama:11434` in Central's AI settings when enabled. Choose RustFS as the storage provider in Central and use `http://rustfs:9000` as its endpoint. Configure the ntfy server URL in Central's notification settings. -TURN is not required until WebRTC is enabled. +Live view can connect directly when ICE succeeds. For clients behind restrictive NAT/firewalls, deploy and validate TURN, then configure its URLs and matching shared secret in Central; without a reachable relay, those clients may not connect. Redis is provided as a standalone service but is not currently required by Central. Backups are independent of the core startup and require the core network and PostgreSQL service to be running. @@ -146,3 +146,78 @@ network and PostgreSQL service to be running. See [GPU Agent notes](gpu-runtime.md) and [Agent update signing](agent-release-signing.md) for device access and trusted-key setup. + +## Optional live video with WebRTC + +The live-view vertical uses the separately maintained MediaMTX image. It is not +started with the core stack. Configure Central with the public `HEIMDALL_WHEP_URL` +and `HEIMDALL_PUBLISH_RTSPS_URL` (including scheme, host and port only). Provide +`HEIMDALL_MEDIAMTX_AUTH_URL` to the MediaMTX container; when both services share +the default Docker network this can use the Central service name and internal +port. Configure `HEIMDALL_WEBRTC_PUBLIC_HOST`, +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and `HEIMDALL_LIVE_MEDIA_CERT_DIR` for the +public listener and its TLS certificate (`server.crt` and `server.key`). The +certificate must cover both public WHEP and RTSPS hostnames. Open the configured +RTSPS/WHEP TCP ports and WebRTC ICE UDP port in the firewall. Add STUN URLs under +`LiveMedia:IceServers`; for TURN REST credentials set +`LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns +five-minute HMAC credentials to the browser; the shared secret is never sent. +When using `docker-compose.coturn.yml`, configure the Central secret from the same +protected secret source as `docker/secrets/coturn_secret`; protect the Central +`.env` with owner-only permissions. + +Start the core project first so its external `heimdall-net` network exists, then +start MediaMTX with a separate project name: + +```sh +docker compose --env-file docker/.env -f docker/docker-compose.webrtc.yml -p heimdall-live up -d +``` + +Stop only this optional project with `docker compose ... -p heimdall-live down`. +Live publishing requires an assigned Agent and an online, enabled camera. Agent +relays are video-only H.264 passthrough, limited to two simultaneous cameras per +Agent. Central reserves eight viewers per camera and two per user in its process; +use one Central instance until shared reservation storage is configured. A stream +with a browser-incompatible codec is not transcoded. The WHEP read session +expires after ten minutes; the browser deletes the WHEP resource on +stop/navigation. Physical camera and external TURN validation remain deployment +acceptance work. + +### Disposable live-view acceptance + +For an isolated local playback test, use the local-only override and synthetic +source Compose files. Generate a unique `.env` outside the repository with new +PostgreSQL/JWT secrets, loopback ports, `HEIMDALL_NETWORK_NAME`, +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and +`HEIMDALL_MEDIAMTX_AUTH_URL=http://heimdall:8080/api/live-media/auth`. +Configure `HEIMDALL_WHEP_URL=http://127.0.0.1:`, +`HEIMDALL_PUBLISH_RTSPS_URL=rtsp://127.0.0.1:`, +`HEIMDALL_ALLOW_INSECURE_HTTP=true`, +`HEIMDALL_ALLOW_INSECURE_RTSP=true`, and +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN=http://localhost:`. Set +`HEIMDALL_NETWORK_NAME` to a unique network name and select unused values for +`WEB_PORT`, `HEIMDALL_TEST_PUBLISH_PORT`, `HEIMDALL_TEST_WHEP_PORT`, +`HEIMDALL_TEST_ICE_PORT`, `HEIMDALL_SYNTHETIC_RTSP_PORT`, and +`HEIMDALL_TEST_AGENT_PORT`. Insecure protocols are allowed only because all media +ports bind to loopback in this recipe. Then start Central, the local MediaMTX, +and synthetic source from changed source, excluding the Agent until a site token +is available: + +```sh +docker compose -p "$project" --env-file "$env_file" \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.webrtc-local-test.yml \ + -f docker/docker-compose.webrtc-test.yml \ + up -d --build postgresql heimdall mediamtx synthetic-camera synthetic-camera-publisher +``` + +Complete first-admin setup, create a site, put its generated test site token in +the disposable `.env`, and start `heimdall-agent` from the same Compose files. +Create and assign an online camera with the synthetic source RTSP URL, then open +its detail page and start live video. Verify an ungranted user is denied, stop +and disable the camera, and check the Agent process and WHEP session are closed. +Use unique ports and the unique network value for each run. Tear down only this +project with `down --volumes --remove-orphans`, confirm its containers, named +volumes and network are gone, and delete its temporary environment/secret files. +This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS +and HTTPS with a trusted certificate. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md new file mode 100644 index 0000000..df5110e --- /dev/null +++ b/skills/webrtc-live/SKILL.md @@ -0,0 +1,72 @@ +# Live WebRTC implementation and acceptance + +The current vertical provides Agent RTSP re-publishing, Central camera-scoped +Data Protection tickets and MediaMTX auth, and a camera detail WHEP player. +`FEAT-01` stays open until the disposable synthetic acceptance below passes +and external network behavior is measured. + +## Required architecture + +- Keep camera assignment and stream lifecycle in Agent. Only an enabled camera + present in the current Central assignment snapshot may be published. Stop the + publisher when assignment, enablement, configuration, or Agent lifetime ends. +- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's + browser-compatible H.264 stream to a camera-ID path. Prefer passthrough when + the source codec is compatible; otherwise make transcoding an explicit, + bounded option. Start video-only; audio and PTZ require separate acceptance. +- Central issues random, short-lived, purpose-separated publish and read claims + scoped to one camera and one action. Protect claims with the shared Heimdall + Data Protection key ring. MediaMTX HTTP auth must validate exact path, action, + protocol, expiry, Agent assignment for publish, and current user camera rights + for read. Never put RTSP credentials, Central API keys, or reusable TURN + credentials in browser-visible URLs or logs. +- Browser obtains a read session from the authenticated camera API and performs + WHEP with that short-lived bearer token. ICE servers and public WHEP URL must + come from deployment configuration, never source-code hostnames. Do not issue + static TURN credentials to the browser. +- Bound simultaneous Agent publishers and viewers, request duration, retries, + FFmpeg process count, and session lifetime. Ensure cancellation/config changes + reap child processes and release permits. + +## Implementation references + +Use MediaMTX's maintained documentation as the protocol reference: + +- [WHEP/WebRTC read](https://mediamtx.org/docs/read/webrtc) +- [HTTP authentication callbacks](https://mediamtx.org/docs/features/authentication) +- [ICE, TURN, codec and latency details](https://mediamtx.org/docs/features/webrtc-specific-features) +- [Configuration reference](https://mediamtx.org/docs/references/configuration-file) +- [RTSP camera/source behavior](https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/08-rtsp-cameras-and-servers.md) +- [MediaMTX license](https://github.com/bluenviron/mediamtx/blob/main/LICENSE) + +Use H.264 without B-frames for browser compatibility and latency. Validate +actual negotiation in browsers; a successful RTSP publish does not prove WHEP. + +## Required acceptance + +Run from changed source in an isolated disposable Compose project with unique +project name, generated credentials, ports and volumes. The optional +`docker/docker-compose.webrtc-test.yml` starts a local-only generated H.264 +camera feed. Use `docker/docker-compose.webrtc-local-test.yml` plus +`docker/docker-compose.webrtc-test.yml` with the core `docker-compose.yml` in one +unique project. Set unique generated database/JWT credentials, loopback ports, +`HEIMDALL_NETWORK_NAME`, `HEIMDALL_MEDIAMTX_AUTH_URL`, WHEP/publish URLs, and the +Central browser origin in an env file outside the repository. Start Central, +MediaMTX and the synthetic feed first; bootstrap the first admin and site, then +place the generated synthetic site token in the disposable env file and start +the Agent. Configure its assigned camera against the host loopback RTSP port. Do not depend on a physical camera. Verify all of the following: + +1. An assigned Agent receives only its assigned camera's short-lived publish + credential and publishes synthetic H.264 to that camera path. +2. An authorized user obtains a short-lived read claim and a browser-compatible + WHEP session; the browser receives decoded frames. +3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired + token, and user without camera access are rejected. +4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the + matching processes/sessions terminate and resource counts return to baseline. +5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE + secrets. Verify configured ICE/TURN candidate behavior separately. +6. Tear down only that Compose project with volumes/orphans, then verify its + containers, volumes and network are gone. + +Record LAN browser and external TURN runs independently. Current focused API/Web and Agent tests pass. Disposable Compose verified Central bootstrap/site creation, Agent registration, synthetic camera assignment, publish-session issuance and relay start, read ticket callback acceptance, forged-ticket denial, unknown-camera denial, and teardown with no remaining project containers, volumes or networks. A deliberately invalid SDP reached MediaMTX and returned 400; a browser-decoded frame and API-driven disable stop were not verified. Physical camera, LAN, external TURN and real SDP/frame playback remain unvalidated; keep FEAT-01 open until these acceptance gaps are closed. diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 1ceb708..b6c2d18 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -172,6 +172,7 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe sp.GetRequiredService()))); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs new file mode 100644 index 0000000..f0b31ec --- /dev/null +++ b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs @@ -0,0 +1,116 @@ +using System.Diagnostics; +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// Re-publishes assigned primary streams to the configured Central MediaMTX. +public sealed class LiveCameraRelayService( + AgentState state, + IOptions options, + CameraConfigStore cameras, + IHttpClientFactory clients, + ILogger logger) : BackgroundService +{ + private const int MaxPublishers = 2; + private readonly Dictionary _relays = []; + private readonly Dictionary _retryAt = []; + private sealed record Relay(Process Process, DateTimeOffset RenewAt); + private sealed record PublishSession(string Url, DateTimeOffset RenewAt); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + while (!stoppingToken.IsCancellationRequested) + { + try { await SynchronizeAsync(stoppingToken); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); } + try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } + finally { await StopAllAsync(); } + } + + private async Task SynchronizeAsync(CancellationToken ct) + { + var assigned = SelectAssignedCameras(cameras); + foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray()) + await StopAsync(id); + + foreach (var camera in assigned.Values) + { + if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited && + relay.RenewAt > DateTimeOffset.UtcNow) continue; + await StopAsync(camera.CameraId); + if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) || + _retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue; + if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20); + } + } + + internal static IReadOnlyDictionary SelectAssignedCameras(CameraConfigStore cameras) => + cameras.HasCentralConfiguration + ? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl)) + .Take(MaxPublishers).ToDictionary(c => c.CameraId) + : new Dictionary(); + + private static bool IsRtspSource(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && + (uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase)); + + private async Task StartAsync(AgentCameraConfig camera, CancellationToken ct) + { + var client = clients.CreateClient(); + client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey); + using var response = await client.PostAsync( + $"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session", + content: null, ct); + if (!response.IsSuccessStatusCode) return false; + var session = await response.Content.ReadFromJsonAsync(cancellationToken: ct); + if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false; + + var source = camera.RtspUrl; + var start = new ProcessStartInfo { FileName = "ffmpeg", UseShellExecute = false, + RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true }; + foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source, + "-map", "0:v:0", "-an", "-c:v", "copy", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() }) + start.ArgumentList.Add(arg); + try + { + var process = Process.Start(start); + if (process is null) return false; + _ = DrainErrorsAsync(process); + _relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30)); + logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId); + return true; + } + catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; } + } + + private static async Task DrainErrorsAsync(Process process) + { + try { while (await process.StandardError.ReadLineAsync() is not null) { } } + catch (IOException) { } + } + + private async Task StopAsync(Guid cameraId) + { + if (!_relays.Remove(cameraId, out var relay)) return; + try + { + if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true); + await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3)); + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException) + { logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); } + finally { relay.Process.Dispose(); } + } + + private async Task StopAllAsync() + { + foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId); + } +} diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 17d320e..1c63c88 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -6,7 +6,8 @@ @inject NavigationManager Nav @inject UiText Text @inject UiLanguageService Language -@implements IDisposable +@inject IJSRuntime JS +@implements IAsyncDisposable @@ -77,6 +78,16 @@ else + +
+ @Text["CameraDetail_Live"] + + @(_liveEnabled ? Text["CameraDetail_StopLive"] : Text["CameraDetail_WatchLive"]) + +
+ +
+ @* ─── Informations & actions ─── *@ @Text["CameraDetail_Information"] @@ -533,11 +544,43 @@ else _ => Color.Default }; - public void Dispose() + private ElementReference _liveVideo; + private IJSObjectReference? _liveModule; + private bool _liveEnabled; + private bool _liveStarting; + + private async Task ToggleLive() + { + if (_camera is null || _liveStarting) return; + _liveStarting = true; + try + { + _liveModule ??= await JS.InvokeAsync("import", "./js/live-view.js"); + if (_liveEnabled) + { + await _liveModule.InvokeVoidAsync("stop", _camera.Id); + _liveEnabled = false; + } + else + { + await _liveModule.InvokeVoidAsync("start", _camera.Id, _liveVideo); + _liveEnabled = true; + } + } + catch { Snackbar.Add(Text["CameraDetail_LiveUnavailable"], Severity.Warning); } + finally { _liveStarting = false; } + } + + public async ValueTask DisposeAsync() { Language.LanguageChanged -= OnLanguageChanged; _disposed = true; _refreshCts?.Cancel(); _refreshCts?.Dispose(); + if (_liveModule is not null) + { + try { if (_camera is not null) await _liveModule.InvokeVoidAsync("stop", _camera.Id); await _liveModule.DisposeAsync(); } + catch (JSDisconnectedException) { } + } } } diff --git a/src/Heimdall.Web/Controllers/LiveMediaController.cs b/src/Heimdall.Web/Controllers/LiveMediaController.cs new file mode 100644 index 0000000..dc8508d --- /dev/null +++ b/src/Heimdall.Web/Controllers/LiveMediaController.cs @@ -0,0 +1,162 @@ +using System.Text.Json.Serialization; +using System.Security.Cryptography; +using System.Globalization; +using System.Security.Claims; +using System.Text; +using Heimdall.Application.Auth.Services; +using Heimdall.Api.Security; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/live-media")] +[EnableRateLimiting("Api")] +public sealed class LiveMediaController( + IApplicationDbContext db, + ResourceAccess access, + ICameraAccessService cameraAccess, + IIdentityAccountService identity, + LiveMediaSessionLimiter sessions, + LiveMediaTickets tickets, + IConfiguration configuration) : ControllerBase +{ + private static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(2); + + public sealed record AuthRequest([property: JsonPropertyName("token")] string? Token, + [property: JsonPropertyName("user")] string? User, + [property: JsonPropertyName("password")] string? Password, + [property: JsonPropertyName("action")] string? Action, + [property: JsonPropertyName("path")] string? Path, + [property: JsonPropertyName("protocol")] string? Protocol); + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpPost("cameras/{cameraId:guid}/session")] + public async Task CreateReadSession(Guid cameraId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var camera = await db.Cameras.AsNoTracking().Where(c => c.Id == cameraId) + .Select(c => new { c.Status, c.AgentId }).SingleOrDefaultAsync(ct); + if (camera is null) return NotFound(); + if (camera.Status != CameraStatus.Online || camera.AgentId is null) + return Conflict(new { error = "Camera is not available for live view" }); + + var whep = configuration["LiveMedia:WhepUrl"]; + if (!Uri.TryCreate(whep, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("https" or "http") || + !string.IsNullOrEmpty(endpoint.UserInfo) || !string.IsNullOrEmpty(endpoint.Query) || !string.IsNullOrEmpty(endpoint.Fragment) || + (endpoint.Scheme != "https" && !configuration.GetValue("LiveMedia:AllowInsecureHttp"))) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Live media is not configured" }); + var securityStamp = User.FindFirstValue(AccountSessionPolicy.StampClaim); + if (string.IsNullOrWhiteSpace(securityStamp)) return Forbid(); + if (!sessions.TryAcquire(cameraId, requester.Id, out var sessionId)) + return StatusCode(StatusCodes.Status429TooManyRequests, new { error = "Live viewer limit reached" }); + var token = tickets.Issue(cameraId, "read", requester.Id, TicketLifetime, securityStamp, sessionId); + return Ok(new { url = whep.TrimEnd('/') + "/" + cameraId.ToString("D") + "/whep", token, sessionId, + expiresAt = DateTimeOffset.UtcNow.Add(TicketLifetime), iceServers = ReadIceServers() }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpDelete("cameras/{cameraId:guid}/session/{sessionId:guid}")] + public async Task ReleaseReadSession(Guid cameraId, Guid sessionId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + sessions.Release(sessionId, cameraId, requester.Id); + return NoContent(); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPost("agents/{agentId:guid}/cameras/{cameraId:guid}/publish-session")] + public async Task CreatePublishSession(Guid agentId, Guid cameraId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || requester.Id != agentId || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var url = configuration["LiveMedia:PublishRtspUrl"]; + if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("rtsps" or "rtsp") || + !string.IsNullOrEmpty(endpoint.UserInfo) || !string.IsNullOrEmpty(endpoint.Query) || + !string.IsNullOrEmpty(endpoint.Fragment) || endpoint.AbsolutePath is not ("" or "/")) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Live media publishing is not configured" }); + if (endpoint.Scheme != "rtsps" && !configuration.GetValue("LiveMedia:AllowInsecureRtsp")) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Encrypted RTSP publishing is required" }); + var camera = await db.Cameras.AsNoTracking().Where(c => c.Id == cameraId) + .Select(c => new { c.AgentId, c.Status }).SingleOrDefaultAsync(ct); + if (camera is null || camera.AgentId != agentId || camera.Status != CameraStatus.Online) return Conflict(); + var token = tickets.Issue(cameraId, "publish", agentId, TicketLifetime); + var builder = new UriBuilder(endpoint) { Path = cameraId.ToString("D"), Query = "token=" + Uri.EscapeDataString(token) }; + return Ok(new { url = builder.Uri.ToString(), renewAt = DateTimeOffset.UtcNow.AddMinutes(8) }); + } + + // MediaMTX calls this endpoint for each RTSP publish and WHEP read. It is + // intentionally anonymous at ASP.NET level; only an unexpired protected + // ticket with an exact camera/action/path/protocol is accepted. + [AllowAnonymous] + [RequestSizeLimit(16_384)] + [HttpPost("auth")] + public async Task AuthorizeMedia([FromBody] AuthRequest request, CancellationToken ct) + { + var token = string.IsNullOrEmpty(request.Token) ? request.Password : request.Token; + if (!tickets.TryValidateRequest(token, request.Path, request.Action, request.Protocol, out var ticket) || ticket is null) + return Unauthorized(); + + var publish = ticket.Action == "publish" && + await db.Cameras.AsNoTracking().AnyAsync(c => c.Id == ticket.CameraId && c.AgentId == ticket.SubjectId && + c.Status == CameraStatus.Online, ct); + var read = ticket.Action == "read" && + await db.Cameras.AsNoTracking().AnyAsync(c => c.Id == ticket.CameraId && c.Status == CameraStatus.Online, ct) && + await cameraAccess.HasCameraAccessAsync(ticket.SubjectId, ticket.CameraId, ct); + if (read) + { + read = ticket.SessionId is Guid sessionId && sessions.IsActive(sessionId, ticket.CameraId, ticket.SubjectId); + if (!read) return Unauthorized(); + var session = await identity.GetSessionRecordAsync(ticket.SubjectId, ct); + read = session is not null && session.SecurityStamp == ticket.SecurityStamp && + !(session.LockoutEnabled && session.LockoutEnd > DateTimeOffset.UtcNow); + if (read && await db.AppSettings.AsNoTracking().AnyAsync(s => s.Key == "email.confirmation.required" && s.Value == "true", ct)) + read = session!.EmailConfirmed; + } + if (!publish && !read) return Unauthorized(); + var expiry = publish ? DateTimeOffset.UtcNow.AddMinutes(10) : sessions.GetExpiresAt(ticket.SessionId!.Value, ticket.CameraId, ticket.SubjectId); + if (expiry is null || expiry <= DateTimeOffset.UtcNow) return Unauthorized(); + return Ok(new { expireAt = expiry.Value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture) }); + } + + private object[] ReadIceServers() + { + var servers = configuration.GetSection("LiveMedia:IceServers").GetChildren() + .Select(c => c.GetSection("Urls").Get() ?? (c["Urls"] is { } u ? [u] : [])) + .Where(urls => urls.Length > 0 && urls.All(IsIceUrl)).Select(urls => (object)new { urls }) + .ToList(); + var turnUrls = configuration.GetSection("LiveMedia:Turn:Urls").Get() ?? []; + if (turnUrls.Any(url => !IsIceUrl(url) || !(url.StartsWith("turn:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turns:", StringComparison.OrdinalIgnoreCase)))) turnUrls = []; + var sharedSecret = configuration["LiveMedia:Turn:SharedSecret"]; + if (turnUrls.Length > 0 && !string.IsNullOrWhiteSpace(sharedSecret)) + { + var expiry = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds(); + var username = $"{expiry}:{Guid.NewGuid():N}"; + var key = Encoding.UTF8.GetBytes(sharedSecret); + // Coturn's TURN REST shared-secret authentication specifies HMAC-SHA1; this is protocol compatibility, not a general-purpose signature. +#pragma warning disable CA5350 + var credential = Convert.ToBase64String(HMACSHA1.HashData(key, Encoding.UTF8.GetBytes(username))); +#pragma warning restore CA5350 + servers.Add(new { urls = turnUrls, username, credential }); + } + return servers.ToArray(); + } + + private static bool IsIceUrl(string url) => url.StartsWith("stun:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("stuns:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turn:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turns:", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 6558233..bcd7fc9 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Duration Size Play +Live + Watch live + Stop live + Live view is unavailable. Check the media service and camera access. diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 413d4a4..4dcbbdf 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Durée Taille Lire +En direct + Voir en direct + Arrêter le direct + Le direct est indisponible. Vérifiez le service média et les droits caméra. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index b98051f..c47dcd8 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Duration Size Play +Live + Watch live + Stop live + Live view is unavailable. Check the media service and camera access. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index c4aed75..c07f913 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -514,6 +514,8 @@ public partial class Program private static void ConfigureControllers(WebApplicationBuilder builder) { builder.Services.AddScoped(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddControllers(options => { diff --git a/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs b/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs new file mode 100644 index 0000000..e76fb63 --- /dev/null +++ b/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs @@ -0,0 +1,72 @@ +using Heimdall.Application.Metrics; + +namespace Heimdall.Api.Security; + +/// Bounds active viewer reservations per camera and user with expiry as a disconnect fallback. +public sealed class LiveMediaSessionLimiter +{ + private const int CameraLimit = 8; + private const int UserLimit = 2; + private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); + private readonly object _gate = new(); + private readonly Dictionary _sessions = []; + private sealed record Reservation(Guid CameraId, Guid UserId, DateTimeOffset ExpiresAt); + + public bool TryAcquire(Guid cameraId, Guid userId, out Guid sessionId) + { + lock (_gate) + { + Prune(); + if (_sessions.Values.Count(s => s.CameraId == cameraId) >= CameraLimit || + _sessions.Values.Count(s => s.UserId == userId) >= UserLimit) + { + sessionId = Guid.Empty; + return false; + } + sessionId = Guid.NewGuid(); + _sessions.Add(sessionId, new Reservation(cameraId, userId, DateTimeOffset.UtcNow.Add(Lifetime))); + HeimdallMetrics.ViewerAdded(); + return true; + } + } + + public bool IsActive(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + Prune(); + return _sessions.TryGetValue(sessionId, out var value) && value.CameraId == cameraId && value.UserId == userId; + } + } + + public DateTimeOffset? GetExpiresAt(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + Prune(); + return _sessions.TryGetValue(sessionId, out var value) && value.CameraId == cameraId && value.UserId == userId + ? value.ExpiresAt : null; + } + } + + public bool Release(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + if (!_sessions.TryGetValue(sessionId, out var value) || value.CameraId != cameraId || value.UserId != userId || + !_sessions.Remove(sessionId)) return false; + HeimdallMetrics.ViewerRemoved(); + return true; + } + } + + private void Prune() + { + var now = DateTimeOffset.UtcNow; + foreach (var id in _sessions.Where(pair => pair.Value.ExpiresAt <= now).Select(pair => pair.Key).ToArray()) + { + _sessions.Remove(id); + HeimdallMetrics.ViewerRemoved(); + } + } +} diff --git a/src/Heimdall.Web/Security/LiveMediaTickets.cs b/src/Heimdall.Web/Security/LiveMediaTickets.cs new file mode 100644 index 0000000..45d758e --- /dev/null +++ b/src/Heimdall.Web/Security/LiveMediaTickets.cs @@ -0,0 +1,55 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; + +namespace Heimdall.Api.Security; + +public sealed record LiveMediaTicket(Guid CameraId, string Action, Guid SubjectId, DateTimeOffset ExpiresAt, + string? SecurityStamp = null, Guid? SessionId = null); + +/// Issues purpose-bound, time-limited tickets for the MediaMTX auth callback. +public sealed class LiveMediaTickets +{ + private readonly ITimeLimitedDataProtector _protector; + public LiveMediaTickets(IDataProtectionProvider provider) => + _protector = provider.CreateProtector("Heimdall.LiveMedia.v1").ToTimeLimitedDataProtector(); + + public string Issue(Guid cameraId, string action, Guid subjectId, TimeSpan lifetime, string? securityStamp = null, Guid? sessionId = null) + { + if (cameraId == Guid.Empty || subjectId == Guid.Empty || lifetime <= TimeSpan.Zero || lifetime > TimeSpan.FromMinutes(5)) + throw new ArgumentOutOfRangeException(nameof(lifetime)); + var ticket = new LiveMediaTicket(cameraId, action, subjectId, DateTimeOffset.UtcNow.Add(lifetime), securityStamp, sessionId); + return _protector.Protect(JsonSerializer.Serialize(ticket), lifetime); + } + + public bool TryRead(string? token, out LiveMediaTicket? ticket) + { + ticket = null; + if (string.IsNullOrWhiteSpace(token) || token.Length > 4096) return false; + try + { + var json = _protector.Unprotect(token, out _); + ticket = JsonSerializer.Deserialize(json); + return ticket is not null && ticket.CameraId != Guid.Empty && + ticket.SubjectId != Guid.Empty && ticket.ExpiresAt > DateTimeOffset.UtcNow; + } + catch (CryptographicException) { return false; } + catch (JsonException) { return false; } + } + + public bool TryValidateRequest(string? token, string? path, string? action, string? protocol, + out LiveMediaTicket? ticket) + { + if (!TryRead(token, out ticket) || ticket is null || + !string.Equals(path, ticket.CameraId.ToString("D"), StringComparison.OrdinalIgnoreCase) || + !string.Equals(ticket.Action, action, StringComparison.Ordinal) || + ticket.Action is not ("publish" or "read") || + (ticket.Action == "publish" && protocol != "rtsp") || + (ticket.Action == "read" && protocol != "webrtc")) + { + ticket = null; + return false; + } + return true; + } +} diff --git a/src/Heimdall.Web/wwwroot/js/live-view.js b/src/Heimdall.Web/wwwroot/js/live-view.js new file mode 100644 index 0000000..f297a07 --- /dev/null +++ b/src/Heimdall.Web/wwwroot/js/live-view.js @@ -0,0 +1,44 @@ +const active = new Map(); +async function gather(pc) { + if (pc.iceGatheringState === "complete") return; + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error("ICE gathering timeout")), 10000); + pc.addEventListener("icegatheringstatechange", () => { + if (pc.iceGatheringState === "complete") { clearTimeout(timeout); resolve(); } + }); + }); +} +export async function start(cameraId, video) { + await stop(cameraId); + const r = await fetch(`/api/live-media/cameras/${cameraId}/session`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: "{}" }); + if (!r.ok) throw new Error("Live session is unavailable"); + const s = await r.json(); + const pc = new RTCPeerConnection({ iceServers: s.iceServers || [] }); + const state = { pc, token: s.token, url: s.url, sessionId: s.sessionId, resource: null }; + active.set(cameraId, state); + pc.addTransceiver("video", { direction: "recvonly" }); + pc.ontrack = e => { + video.srcObject = e.streams[0]; + video.play().catch(() => {}); + e.track.addEventListener("ended", () => void stop(cameraId), { once: true }); + }; + try { + await pc.setLocalDescription(await pc.createOffer()); + await gather(pc); + const answer = await fetch(s.url, { method: "POST", headers: { Authorization: `Bearer ${s.token}`, "Content-Type": "application/sdp", Accept: "application/sdp" }, body: pc.localDescription.sdp }); + if (!answer.ok) throw new Error("WHEP negotiation failed"); + const location = answer.headers.get("Location"); + state.resource = location ? new URL(location, s.url).toString() : null; + await pc.setRemoteDescription({ type: "answer", sdp: await answer.text() }); + } catch (e) { await stop(cameraId); throw e; } +} +export async function stop(cameraId) { + const s = active.get(cameraId); + if (!s) return; + active.delete(cameraId); + s.pc.close(); + if (s.resource) { try { await fetch(s.resource, { method: "DELETE", headers: { Authorization: `Bearer ${s.token}` } }); } catch { } } + try { await fetch(`/api/live-media/cameras/${cameraId}/session/${s.sessionId}`, { method: "DELETE", credentials: "same-origin" }); } catch { } + const v = document.querySelector(`[data-live-camera="${cameraId}"]`); + if (v) v.srcObject = null; +} diff --git a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs new file mode 100644 index 0000000..1086cd9 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs @@ -0,0 +1,32 @@ +using Heimdall.Agent.Services; + +namespace Heimdall.Agent.Tests; + +public sealed class LiveCameraRelayServiceTests +{ + [Fact] + public void Uses_only_enabled_Rtsp_cameras_from_authoritative_Central_assignment_and_caps_publishers() + { + var store = new CameraConfigStore(); + var fallback = new AgentCameraConfig(Guid.NewGuid(), "fallback", "rtsp://127.0.0.1/fallback", null, true); + store.SetLocalFallback([fallback]); + Assert.Empty(LiveCameraRelayService.SelectAssignedCameras(store)); + + var settings = new Dictionary(); + for (var i = 0; i < 3; i++) + { + var id = Guid.NewGuid(); + settings[$"camera.{id}.rtsp"] = $"rtsp://127.0.0.1/{i}"; + settings[$"camera.{id}.enabled"] = i == 2 ? "false" : "true"; + } + var invalidId = Guid.NewGuid(); + settings[$"camera.{invalidId}.rtsp"] = "file:///etc/passwd"; + settings[$"camera.{invalidId}.enabled"] = "true"; + store.ReplaceCentral(settings); + + var selected = LiveCameraRelayService.SelectAssignedCameras(store); + Assert.Equal(2, selected.Count); + Assert.DoesNotContain(fallback.CameraId, selected.Keys); + Assert.DoesNotContain(invalidId, selected.Keys); + } +} diff --git a/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs b/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs new file mode 100644 index 0000000..e540a5a --- /dev/null +++ b/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs @@ -0,0 +1,33 @@ +using Heimdall.Api.Security; + +namespace Heimdall.Api.Tests; + +public sealed class LiveMediaSessionLimiterTests +{ + [Fact] + public void Viewer_slots_are_camera_and_user_scoped_and_released_by_owner() + { + var limiter = new LiveMediaSessionLimiter(); + var camera = Guid.NewGuid(); + var user = Guid.NewGuid(); + var sessions = new List(); + for (var i = 0; i < 2; i++) + { + Assert.True(limiter.TryAcquire(camera, user, out var session)); + sessions.Add(session); + } + Assert.False(limiter.TryAcquire(Guid.NewGuid(), user, out _)); + Assert.False(limiter.Release(sessions[0], camera, Guid.NewGuid())); + Assert.True(limiter.Release(sessions[0], camera, user)); + Assert.True(limiter.TryAcquire(camera, user, out _)); + } + + [Fact] + public void Camera_limit_bounds_concurrent_viewers() + { + var limiter = new LiveMediaSessionLimiter(); + var camera = Guid.NewGuid(); + for (var i = 0; i < 8; i++) Assert.True(limiter.TryAcquire(camera, Guid.NewGuid(), out _)); + Assert.False(limiter.TryAcquire(camera, Guid.NewGuid(), out _)); + } +} diff --git a/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs b/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs new file mode 100644 index 0000000..c30157f --- /dev/null +++ b/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs @@ -0,0 +1,52 @@ +using Heimdall.Api.Security; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Api.Tests; + +public sealed class LiveMediaTicketsTests +{ + private static LiveMediaTickets CreateTickets() + { + var services = new ServiceCollection(); + services.AddDataProtection().SetApplicationName("Heimdall.LiveMedia.Tests"); + return new LiveMediaTickets(services.BuildServiceProvider().GetRequiredService()); + } + + [Fact] + public void Ticket_is_valid_and_camera_scoped() + { + var tickets = CreateTickets(); + var camera = Guid.NewGuid(); + var agent = Guid.NewGuid(); + var token = tickets.Issue(camera, "publish", agent, TimeSpan.FromMinutes(2)); + + Assert.True(tickets.TryRead(token, out var ticket)); + Assert.Equal(camera, ticket!.CameraId); + Assert.Equal(agent, ticket.SubjectId); + Assert.Equal("publish", ticket.Action); + } + + [Fact] + public void Ticket_rejects_tampering_and_invalid_lifetime() + { + var tickets = CreateTickets(); + var token = tickets.Issue(Guid.NewGuid(), "read", Guid.NewGuid(), TimeSpan.FromMinutes(1)); + + Assert.False(tickets.TryRead(token + "x", out _)); + Assert.Throws(() => tickets.Issue(Guid.NewGuid(), "read", Guid.NewGuid(), TimeSpan.FromMinutes(6))); + } + + [Fact] + public void Publish_claim_is_bound_to_exact_path_action_and_protocol() + { + var tickets = CreateTickets(); + var camera = Guid.NewGuid(); + var token = tickets.Issue(camera, "publish", Guid.NewGuid(), TimeSpan.FromMinutes(1)); + + Assert.True(tickets.TryValidateRequest(token, camera.ToString("D"), "publish", "rtsp", out _)); + Assert.False(tickets.TryValidateRequest(token, Guid.NewGuid().ToString("D"), "publish", "rtsp", out _)); + Assert.False(tickets.TryValidateRequest(token, camera.ToString("D"), "read", "webrtc", out _)); + Assert.False(tickets.TryValidateRequest(token, camera.ToString("D"), "publish", "webrtc", out _)); + } +} diff --git a/todo.md b/todo.md index 91891c9..1da5a00 100644 --- a/todo.md +++ b/todo.md @@ -45,7 +45,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. @@ -53,7 +53,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. -- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures. +- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Restent la validation des seuils sur déploiement et les pannes à valider sur déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. - [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation.