From 4fd5a49175dfc8b84a22630921e143f3c116e8b7 Mon Sep 17 00:00:00 2001 From: seeARMS <3957773+seeARMS@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:46:15 -0800 Subject: [PATCH 1/2] Isolate the standalone AI Port stack and resolve Protect camera names --- README.md | 15 +++++++ config.example.yaml | 2 + docker-compose.aiport.yml | 6 ++- docker-compose.yml | 2 + src/keystone/aiport.py | 74 +++++++++++++++++++++++++++++++-- src/keystone/cli.py | 16 +++++-- src/keystone/config.py | 5 +++ tests/test_aiport_standalone.py | 70 ++++++++++++++++++++++++++++++- tests/test_reset_adoption.py | 7 +++- web/src/lib/derive.test.ts | 16 +++++++ 10 files changed, 200 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 79add61..59dcd7b 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,20 @@ UniFi Protect caps how many cameras can pair with one AI Port based on resolutio - **Docker `macvlan` (recommended):** Use [docker-compose.aiport.yml](docker-compose.aiport.yml) to give each extra AI Port its own LAN IP on a physical NIC (`KEYSTONE_AIPORT_PARENT_IFACE`, `KEYSTONE_AIPORT_SUBNET`, `KEYSTONE_AIPORT_GATEWAY`, `KEYSTONE_AIPORT_IP`). Each container gets its own `:443` and automatic UDP `10001` LAN discovery. *(Linux `macvlan` containers cannot talk directly to the Docker host IP without a macvlan shim, which is fine for AI-Port-only containers because they only connect to Protect and your cameras.)* - **Dedicated IP on an existing host (IP alias / spare NIC):** On a host with a secondary LAN IP (for example `192.0.2.51`), set `aiport.bind_host: 192.0.2.51` and `aiport.advertise_ip: 192.0.2.51` (or `KEYSTONE_AIPORT_BIND_HOST` / `KEYSTONE_AIPORT_ADVERTISE_IP`) to bind `:443` only on that address. Any other service or primary AI Port using port `443` on the same host must also bind its own specific IP rather than `0.0.0.0:443`. When running multiple Keystone processes in the same host network namespace, give each extra instance its own `state_dir` (`KEYSTONE_STATE_DIR`) and `aiport.hostname`, disable its dashboard (`web.enabled: false`) or assign a distinct `web.port`, and set `device.discovery_enabled: false` (adopting the extra AI Port by IP in Protect so only one process owns UDP `10001`). +The standalone Compose file uses the project name `keystone-aiport-2` so you can keep it beside the primary stack. If you set `COMPOSE_PROJECT_NAME` in a shared `.env`, pass `-p keystone-aiport-2` on standalone Compose commands to keep the projects separate. + +**Upgrading an existing standalone container.** To move it from the old shared project, run the commands below from the existing Compose directory. Substitute your container name in the first command if you customized it. The first Compose command removes the old AI Port container and its macvlan network. Keep `./state-aiport-2` mounted at `/state` to preserve its adoption identity, and omit `--remove-orphans` so the primary stack keeps running. + +```sh +old_project=$(docker inspect -f '{{ index .Config.Labels "com.docker.compose.project" }}' keystone-aiport-2) +COMPOSE_REMOVE_ORPHANS=false docker compose -p "$old_project" -f docker-compose.aiport.yml down +docker compose -p keystone-aiport-2 -f docker-compose.aiport.yml up -d +``` + +Each AI Port dashboard lists only cameras paired to that instance. To view a standalone port's cameras, set `KEYSTONE_AIPORT_WEB_ENABLED=true` and open `http://:8088/#cameras` from your trusted LAN. + +To show Protect names alongside MAC addresses, open **Integrations** in your console's Protect app and create an API key with read access to the paired cameras. Set `KEYSTONE_CONTROLLER_API_KEY` in the Compose `.env` for each instance that needs names (or set `controller.api_key` in its `config.yaml`) and recreate its container. Keystone refreshes the local Protect camera list every five minutes over HTTPS on TCP `443`. It pins the console's certificate on first use by default. To verify the certificate on the first connection too, set `KEYSTONE_CONTROLLER_API_FINGERPRINT` to its independently verified SHA-256 fingerprint. An explicit name in `cameras:` takes precedence. Cameras without a known name display their MAC address. + ### Speech-to-Text (event transcripts) @@ -569,6 +583,7 @@ Reasoning models count their thinking against `max_tokens`, so a short caption b | Direction | Port | Purpose | | --- | --- | --- | +| Keystone → Protect | `TCP 443` | Optional Protect API lookup for paired camera names | | Keystone → Protect | `TCP 7442` | UCP4 control WebSocket (`ds`) & AI Port avclient WSS | | Keystone → Protect | `TCP 7443` | Find Anything NL Search WebSocket | | Keystone → Protect | `TCP 7444` | Media export downloads & RAM callbacks | diff --git a/config.example.yaml b/config.example.yaml index 873fd59..6aefe0f 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -12,6 +12,8 @@ controller: media_port: 7444 control_profile: device-service # "device-service" for Protect 7.3+, "ucp4" for strict subprotocol auto_pin_tls: true # Pins Protect's TLS SHA-256 certs on first connect + # api_key: "" # Optional Protect integration key for paired camera names + # api_fingerprint: "" # Optional SHA-256 pin for the console's HTTPS certificate on TCP 443 device: # enabled: true # Set false for a standalone AI-Port-only instance (no AI Key or PostgreSQL) diff --git a/docker-compose.aiport.yml b/docker-compose.aiport.yml index f302fc3..2eb0c52 100644 --- a/docker-compose.aiport.yml +++ b/docker-compose.aiport.yml @@ -20,9 +20,11 @@ # KEYSTONE_AIPORT_IP=192.0.2.61 # 3. Start with: # docker compose -f docker-compose.aiport.yml up -d -# (Add another copy of this service with a new container_name, hostname, IP, and state folder +# (Add another service to this file with a new service name, container_name, hostname, IP, and state folder # for each additional virtual AI Port.) +name: keystone-aiport-2 + services: keystone-aiport-2: image: ghcr.io/seearms/keystone:${KEYSTONE_IMAGE_TAG:-latest} @@ -40,6 +42,8 @@ services: environment: KEYSTONE_STATE_DIR: /state KEYSTONE_CONTROLLER_HOST: ${KEYSTONE_CONTROLLER_IP:?Set KEYSTONE_CONTROLLER_IP in .env} + KEYSTONE_CONTROLLER_API_KEY: ${KEYSTONE_CONTROLLER_API_KEY:-} + KEYSTONE_CONTROLLER_API_FINGERPRINT: ${KEYSTONE_CONTROLLER_API_FINGERPRINT:-} KEYSTONE_DEVICE_ENABLED: "false" KEYSTONE_AIPORT_ENABLED: "true" KEYSTONE_AIPORT_HOSTNAME: ${KEYSTONE_AIPORT_HOSTNAME:-keystone-aiport-2} diff --git a/docker-compose.yml b/docker-compose.yml index d56bfad..71c32f2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -42,6 +42,8 @@ services: environment: KEYSTONE_CONFIG: /config/config.yaml KEYSTONE_STATE_DIR: /state + KEYSTONE_CONTROLLER_API_KEY: ${KEYSTONE_CONTROLLER_API_KEY:-} + KEYSTONE_CONTROLLER_API_FINGERPRINT: ${KEYSTONE_CONTROLLER_API_FINGERPRINT:-} KEYSTONE_CONTROLLER_TRUSTED_PEERS: ${KEYSTONE_CONTROLLER_TRUSTED_PEERS:-} KEYSTONE_DEVICE_ADVERTISE_IP: ${KEYSTONE_DEVICE_ADVERTISE_IP:-} KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD: "true" diff --git a/src/keystone/aiport.py b/src/keystone/aiport.py index f09d10e..bf7e064 100644 --- a/src/keystone/aiport.py +++ b/src/keystone/aiport.py @@ -29,6 +29,7 @@ import aiohttp from aiohttp import web +from yarl import URL from .aiport_audio import ( ALL_PROTECT_AUDIO_TYPES, @@ -66,7 +67,7 @@ resolve_controller_ips, verify_credential_sync, ) -from .config import Config +from .config import PROTECT_API_PORT, Config from .control import DeviceStateStore from .embedder import Embedder from .face import DetectedFace, FaceRecognizer @@ -79,10 +80,16 @@ build_client_ssl_context, build_server_ssl_context, ensure_device_certificate, + load_or_pin_fingerprint, ) from .worker import ACTIVITY_MAX_ITEMS, append_activity LOG = logging.getLogger(__name__) +CAMERA_NAME_REFRESH_SECONDS = 300 + + +def _camera_key(device_id: str) -> str: + return device_id.replace(":", "").replace("-", "").strip().upper() @dataclass @@ -382,6 +389,8 @@ def __init__( self._upload_session: aiohttp.ClientSession | None = None self._ws: aiohttp.ClientWebSocketResponse | None = None self._task: asyncio.Task[None] | None = None + self._camera_names_task: asyncio.Task[None] | None = None + self._protect_camera_names: dict[str, str] = {} self._cameras: dict[str, PairedCameraState] = {} self.connected = False @@ -402,11 +411,59 @@ def _camera_name(self, device_id: str) -> str: cam = self.config.cameras.get(device_id) if cam and cam.name: return cam.name - norm = device_id.replace(":", "").replace("-", "").strip().upper() + norm = _camera_key(device_id) for key, entry in self.config.cameras.items(): - if entry.name and key.replace(":", "").replace("-", "").strip().upper() == norm: + if entry.name and _camera_key(key) == norm: return entry.name - return "" + return self._protect_camera_names.get(norm, "") + + async def _camera_names_loop(self) -> None: + """Refresh display names off the pairing path; the stream-control RPCs carry only MACs.""" + controller = self.config.controller + host = controller.host.strip("[]") + url = URL.build( + scheme="https", + host=host, + port=PROTECT_API_PORT, + path="/proxy/protect/integration/v1/cameras", + ) + fingerprint = None + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session: + while True: + try: + if fingerprint is None: + digest, _ = await asyncio.to_thread( + load_or_pin_fingerprint, + self.config.state_dir, + "api", + host, + PROTECT_API_PORT, + configured_fingerprint=controller.api_fingerprint, + auto_pin=controller.auto_pin_tls, + ) + fingerprint = aiohttp.Fingerprint(bytes.fromhex(digest)) + async with session.get( + url, + headers={"X-API-KEY": controller.api_key}, + ssl=fingerprint, + allow_redirects=False, + ) as response: + if response.status != 200: + LOG.warning("Protect camera name lookup returned HTTP %d", response.status) + else: + cameras = await response.json() + if not isinstance(cameras, list): + raise ValueError("Expected a list of Protect cameras") + self._protect_camera_names = { + _camera_key(camera["mac"]): camera["name"].strip() + for camera in cameras + if isinstance(camera, dict) + and isinstance(camera.get("mac"), str) + and isinstance(camera.get("name"), str) + } + except (OSError, ValueError, aiohttp.ClientError) as exc: + LOG.warning("Protect camera name lookup failed (%s)", type(exc).__name__) + await asyncio.sleep(CAMERA_NAME_REFRESH_SECONDS) @property def native_faces_enabled(self) -> bool: @@ -925,8 +982,17 @@ async def start(self) -> None: timeout=aiohttp.ClientTimeout(total=20, sock_connect=10), ) self._task = asyncio.create_task(self._run_loop(), name="keystone-aiport") + if self.config.controller.api_key: + self._camera_names_task = asyncio.create_task( + self._camera_names_loop(), name="keystone-aiport-camera-names" + ) async def stop(self) -> None: + if self._camera_names_task is not None: + self._camera_names_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._camera_names_task + self._camera_names_task = None for cam in list(self._cameras.values()): await self._stop_camera_pipelines(cam) if self._task is not None: diff --git a/src/keystone/cli.py b/src/keystone/cli.py index b2b9402..341ad75 100644 --- a/src/keystone/cli.py +++ b/src/keystone/cli.py @@ -19,7 +19,7 @@ from . import doctor, macos_cli from .app import KeystoneRuntime from .brand import APP_NAME, APP_SLUG, APP_VERSION, env_var -from .config import AiPortConfig, Config, DeviceConfig, load_config +from .config import PROTECT_API_PORT, AiPortConfig, Config, DeviceConfig, load_config from .discovery import DiscoveryTarget, send_discovery_announce from .macos_power import prevent_idle_sleep from .ort_runtime import GPU_WATCHDOG, exit_for_restart @@ -66,10 +66,14 @@ async def _run_daemon(config: Config) -> None: def _cmd_trust(args: argparse.Namespace) -> int: cfg = load_config(args.config) _setup_logging(cfg.log_level) - for channel, port, explicit in ( + channels = [ ("control", cfg.controller.control_port, args.control_fingerprint or cfg.controller.control_fingerprint), ("search", cfg.controller.search_port, args.search_fingerprint or cfg.controller.search_fingerprint), - ): + ] + api_pin = args.api_fingerprint or cfg.controller.api_fingerprint + if cfg.controller.api_key or api_pin: + channels.append(("api", PROTECT_API_PORT, api_pin)) + for channel, port, explicit in channels: der = fetch_peer_certificate_der(cfg.controller.host, port) fp = cert_fingerprint_sha256(der) print(f"{channel} ({cfg.controller.host}:{port}) SHA-256: {fp}") @@ -285,6 +289,8 @@ def _cmd_faces(args: argparse.Namespace) -> int: "controller-control.pem", "controller-search.sha256", "controller-search.pem", + "controller-api.sha256", + "controller-api.pem", ) _RESET_TARGETS = ("all", "aikey", "aiport") @@ -446,7 +452,8 @@ def _warn_static_macs() -> None: if cfg is not None and clear_tls_pins and not cfg.controller.auto_pin_tls: missing_control = not cfg.controller.control_fingerprint missing_search = cfg.embeddings.enabled and not cfg.controller.search_fingerprint - if missing_control or missing_search: + missing_api = cfg.aiport.enabled and cfg.controller.api_key and not cfg.controller.api_fingerprint + if missing_control or missing_search or missing_api: trust_parts: list[str] = [] if args.state_dir: trust_parts.append(f"KEYSTONE_STATE_DIR={shlex.quote(str(state_dir))}") @@ -610,6 +617,7 @@ def main(argv: list[str] | None = None) -> int: p_trust.add_argument("--pin", action="store_true", help="Save fetched fingerprints to state_dir") p_trust.add_argument("--control-fingerprint", default="", help="Expected control/media SHA-256") p_trust.add_argument("--search-fingerprint", default="", help="Expected search port SHA-256") + p_trust.add_argument("--api-fingerprint", default="", help="Expected Protect integration API SHA-256") p_announce = sub.add_parser( "announce", diff --git a/src/keystone/config.py b/src/keystone/config.py index b4eeb65..96f2f28 100644 --- a/src/keystone/config.py +++ b/src/keystone/config.py @@ -43,6 +43,7 @@ def normalize_mac(mac: str) -> str: CONTROL_PROFILES = ("device-service", "ucp4") +PROTECT_API_PORT = 443 @dataclass @@ -56,6 +57,8 @@ class ControllerConfig: search_fingerprint: str = "" auto_pin_tls: bool = True # Trust-on-first-use if fingerprint not pinned yet trusted_peers: list[str] = field(default_factory=list) + api_key: str = field(default="", repr=False) # Optional Protect integration API key for camera names + api_fingerprint: str = "" # UniFi OS HTTPS (443) can use a different cert from Protect @dataclass @@ -795,6 +798,8 @@ def load_config(config_path: str | Path | None = None, *, use_env: bool = True) ("CONTROLLER_PROFILE", cfg.controller, "control_profile", str), ("CONTROLLER_FINGERPRINT", cfg.controller, "control_fingerprint", str), ("CONTROLLER_SEARCH_FINGERPRINT", cfg.controller, "search_fingerprint", str), + ("CONTROLLER_API_KEY", cfg.controller, "api_key", str), + ("CONTROLLER_API_FINGERPRINT", cfg.controller, "api_fingerprint", str), ("CONTROLLER_AUTO_PIN_TLS", cfg.controller, "auto_pin_tls", _as_bool), ("DEVICE_ENABLED", cfg.device, "enabled", _as_bool), ("DEVICE_HOSTNAME", cfg.device, "hostname", str), diff --git a/tests/test_aiport_standalone.py b/tests/test_aiport_standalone.py index 92f3ca3..df9db5b 100644 --- a/tests/test_aiport_standalone.py +++ b/tests/test_aiport_standalone.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import asyncio import errno import ipaddress import logging @@ -15,14 +16,16 @@ import pytest import yaml from aiohttp import web +from aiohttp.test_utils import TestServer from cryptography import x509 from keystone import aiport as aiport_mod from keystone import app as app_mod from keystone import doctor, macos_cli -from keystone.aiport import AiPortService +from keystone.aiport import AiPortService, PairedCameraState from keystone.app import KeystoneRuntime -from keystone.config import Config, load_config +from keystone.config import CameraContextConfig, Config, load_config +from keystone.tls import build_server_ssl_context, ensure_device_certificate REPO_ROOT = Path(__file__).resolve().parent.parent @@ -134,6 +137,7 @@ async def stop(self) -> None: assert runtime.worker is None assert runtime.search is None assert runtime.aiport is not None + assert runtime.aiport._camera_names_task is None assert not (cfg.state_dir / "device-state.json").exists() assert (cfg.state_dir / "aiport" / "device-state.json").is_file() @@ -161,6 +165,67 @@ async def stop(self) -> None: await runtime.stop() +async def test_aiport_reads_protect_names_by_mac(tmp_path, monkeypatch): + responses = asyncio.Queue() + requests = asyncio.Queue() + redirected = [] + + async def list_cameras(request): + requests.put_nowait(request.headers.get("X-API-KEY")) + return await responses.get() + + async def redirect_target(request): + redirected.append(True) + return web.json_response([]) + + app = web.Application() + app.router.add_get("/proxy/protect/integration/v1/cameras", list_cameras) + app.router.add_get("/redirect", redirect_target) + cert, key = ensure_device_certificate(tmp_path / "console", "020000000001", "127.0.0.1") + server = TestServer(app) + await server.start_server(ssl=build_server_ssl_context(cert, key)) + async with server: + monkeypatch.setattr(aiport_mod, "PROTECT_API_PORT", server.port) + monkeypatch.setattr(aiport_mod, "CAMERA_NAME_REFRESH_SECONDS", 0) + monkeypatch.setenv("KEYSTONE_CONTROLLER_API_KEY", "example-key") + monkeypatch.setenv("KEYSTONE_CONTROLLER_HOST", server.host) + monkeypatch.setenv("KEYSTONE_STATE_DIR", str(tmp_path / "state")) + cfg = load_config() + cfg.aiport.mgmt_port = 0 + cfg.aiport.bind_host = "127.0.0.1" + svc = AiPortService(cfg, expected_fingerprint="0" * 64, detector=_DummyDetector()) + camera = PairedCameraState(device_id="0211223344AA", stream_url="") + svc._cameras[camera.device_id] = camera + + async def serve(response): + responses.put_nowait(response) + # Once the next poll starts, the previous response has been processed. + assert await asyncio.wait_for(requests.get(), 3) == "example-key" + return [(cam["deviceId"], cam["name"]) for cam in svc.status()["pairedCameras"]] + + await svc.start() + try: + assert await asyncio.wait_for(requests.get(), 3) == "example-key" + cameras = [ + {"mac": "02:11:22:33:44:aa", "name": "North Door"}, + {"mac": "02:11:22:33:44:bb", "name": "Other AI Port"}, + ] + assert await serve(web.json_response(cameras)) == [(camera.device_id, "North Door")] + assert await serve(web.Response(status=503)) == [(camera.device_id, "North Door")] + assert await serve(web.Response(status=302, headers={"Location": "/redirect"})) == [ + (camera.device_id, "North Door") + ] + assert not redirected + cameras[0]["name"] = "Driveway" + assert await serve(web.json_response(cameras)) == [(camera.device_id, "Driveway")] + cfg.cameras["02-11-22-33-44-aa"] = CameraContextConfig(name="My alias") + assert svc.status()["pairedCameras"][0]["name"] == "My alias" + cfg.cameras.clear() + assert await serve(web.json_response([])) == [(camera.device_id, "")] + finally: + await svc.stop() + + async def test_aiport_port_443_conflict_gives_actionable_error_and_non_443_warns( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ): @@ -314,6 +379,7 @@ def test_macos_install_daemons_rejects_standalone_aiport_config(tmp_path: Path): def test_compose_aiport_template_is_valid_standalone_macvlan_config(): compose = yaml.safe_load((REPO_ROOT / "docker-compose.aiport.yml").read_text(encoding="utf-8")) + assert compose["name"] == "keystone-aiport-2" svc = compose["services"]["keystone-aiport-2"] assert svc["image"].startswith("ghcr.io/seearms/keystone:") assert svc["cap_add"] == ["NET_BIND_SERVICE"] diff --git a/tests/test_reset_adoption.py b/tests/test_reset_adoption.py index 999217b..a13ceae 100644 --- a/tests/test_reset_adoption.py +++ b/tests/test_reset_adoption.py @@ -29,6 +29,8 @@ def _seed_state(state_dir: Path) -> None: "controller-control.pem", "controller-search.sha256", "controller-search.pem", + "controller-api.sha256", + "controller-api.pem", ): (state_dir / name).write_text("pin", encoding="utf-8") @@ -51,15 +53,16 @@ def test_reset_adoption_all_clears_identity_and_preserves_models_and_history(tmp _seed_state(state_dir) preview = reset_adoption_state(state_dir, dry_run=True) - assert len(preview) == 12 + assert len(preview) == 14 assert (state_dir / "device-state.json").is_file() removed = reset_adoption_state(state_dir, dry_run=False) - assert len(removed) == 12 + assert len(removed) == 14 assert not (state_dir / "device-state.json").exists() assert not (state_dir / "device.crt").exists() assert not (state_dir / "device.key").exists() assert not (state_dir / "controller-control.sha256").exists() + assert not (state_dir / "controller-api.sha256").exists() assert not (state_dir / "aiport").exists() _assert_preserved(state_dir) diff --git a/web/src/lib/derive.test.ts b/web/src/lib/derive.test.ts index a86168c..4a7c017 100644 --- a/web/src/lib/derive.test.ts +++ b/web/src/lib/derive.test.ts @@ -355,6 +355,22 @@ describe("services", () => { }) describe("cameras", () => { + it("shows the paired camera name alongside its MAC and falls back to the MAC alone", () => { + const cameras = deriveCameras({ + aiport: { + enabled: true, + pairedCameras: [ + { deviceId: "021122334401", name: "Front Porch" }, + { deviceId: "021122334402" }, + ], + }, + }) + expect(cameras).toMatchObject([ + { id: "021122334401", name: "Front Porch", showId: true }, + { id: "021122334402", name: "021122334402", showId: false }, + ]) + }) + it("labels VideoToolbox and VA-API with support for older status payloads", () => { const cameras = deriveCameras({ aiport: { From aced42fa6698af1261bf72dc2b3b8e8f030cd02e Mon Sep 17 00:00:00 2001 From: seeARMS <3957773+seeARMS@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:03:24 -0800 Subject: [PATCH 2/2] Honor Protect camera ID aliases and skip unused search pinning --- README.md | 2 +- src/keystone/aiport.py | 26 ++++++++++++++++---------- src/keystone/cli.py | 6 ++++-- tests/test_aiport_standalone.py | 8 +++++++- tests/test_reset_adoption.py | 17 +++++++++++++++++ 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 59dcd7b..3042e42 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ docker compose -p keystone-aiport-2 -f docker-compose.aiport.yml up -d Each AI Port dashboard lists only cameras paired to that instance. To view a standalone port's cameras, set `KEYSTONE_AIPORT_WEB_ENABLED=true` and open `http://:8088/#cameras` from your trusted LAN. -To show Protect names alongside MAC addresses, open **Integrations** in your console's Protect app and create an API key with read access to the paired cameras. Set `KEYSTONE_CONTROLLER_API_KEY` in the Compose `.env` for each instance that needs names (or set `controller.api_key` in its `config.yaml`) and recreate its container. Keystone refreshes the local Protect camera list every five minutes over HTTPS on TCP `443`. It pins the console's certificate on first use by default. To verify the certificate on the first connection too, set `KEYSTONE_CONTROLLER_API_FINGERPRINT` to its independently verified SHA-256 fingerprint. An explicit name in `cameras:` takes precedence. Cameras without a known name display their MAC address. +To show Protect names alongside MAC addresses, open **Integrations** in your console's Protect app and create an API key with read access to the paired cameras. For the standalone Compose template, set `KEYSTONE_CONTROLLER_API_KEY` in its `.env` and recreate the container. Deployments that load a `config.yaml` can also set `controller.api_key` there. Keystone refreshes the local Protect camera list every five minutes over HTTPS on TCP `443`. It pins the console's certificate on first use by default. To verify the certificate on the first connection too, set `KEYSTONE_CONTROLLER_API_FINGERPRINT` to its independently verified SHA-256 fingerprint. If your deployment loads a `config.yaml`, an explicit name in its `cameras:` section takes precedence. Cameras without a known name display their MAC address. diff --git a/src/keystone/aiport.py b/src/keystone/aiport.py index bf7e064..6bba112 100644 --- a/src/keystone/aiport.py +++ b/src/keystone/aiport.py @@ -417,6 +417,21 @@ def _camera_name(self, device_id: str) -> str: return entry.name return self._protect_camera_names.get(norm, "") + def _update_camera_names(self, cameras: Any) -> None: + if not isinstance(cameras, list): + raise ValueError("Expected a list of Protect cameras") + names: dict[str, str] = {} + for camera in cameras: + if not isinstance(camera, dict) or not isinstance(camera.get("mac"), str): + continue + # Configured AI Key aliases are keyed by Protect ID; stream-control RPCs use the MAC. + camera_id = camera.get("id") + alias = self.config.cameras.get(camera_id) if isinstance(camera_id, str) else None + name = (alias and alias.name) or camera.get("name") + if isinstance(name, str): + names[_camera_key(camera["mac"])] = name.strip() + self._protect_camera_names = names + async def _camera_names_loop(self) -> None: """Refresh display names off the pairing path; the stream-control RPCs carry only MACs.""" controller = self.config.controller @@ -451,16 +466,7 @@ async def _camera_names_loop(self) -> None: if response.status != 200: LOG.warning("Protect camera name lookup returned HTTP %d", response.status) else: - cameras = await response.json() - if not isinstance(cameras, list): - raise ValueError("Expected a list of Protect cameras") - self._protect_camera_names = { - _camera_key(camera["mac"]): camera["name"].strip() - for camera in cameras - if isinstance(camera, dict) - and isinstance(camera.get("mac"), str) - and isinstance(camera.get("name"), str) - } + self._update_camera_names(await response.json()) except (OSError, ValueError, aiohttp.ClientError) as exc: LOG.warning("Protect camera name lookup failed (%s)", type(exc).__name__) await asyncio.sleep(CAMERA_NAME_REFRESH_SECONDS) diff --git a/src/keystone/cli.py b/src/keystone/cli.py index 341ad75..8b87507 100644 --- a/src/keystone/cli.py +++ b/src/keystone/cli.py @@ -68,8 +68,10 @@ def _cmd_trust(args: argparse.Namespace) -> int: _setup_logging(cfg.log_level) channels = [ ("control", cfg.controller.control_port, args.control_fingerprint or cfg.controller.control_fingerprint), - ("search", cfg.controller.search_port, args.search_fingerprint or cfg.controller.search_fingerprint), ] + if (cfg.device.enabled and cfg.embeddings.enabled) or args.search_fingerprint: + search_pin = args.search_fingerprint or cfg.controller.search_fingerprint + channels.append(("search", cfg.controller.search_port, search_pin)) api_pin = args.api_fingerprint or cfg.controller.api_fingerprint if cfg.controller.api_key or api_pin: channels.append(("api", PROTECT_API_PORT, api_pin)) @@ -451,7 +453,7 @@ def _warn_static_macs() -> None: _warn_static_macs() if cfg is not None and clear_tls_pins and not cfg.controller.auto_pin_tls: missing_control = not cfg.controller.control_fingerprint - missing_search = cfg.embeddings.enabled and not cfg.controller.search_fingerprint + missing_search = cfg.device.enabled and cfg.embeddings.enabled and not cfg.controller.search_fingerprint missing_api = cfg.aiport.enabled and cfg.controller.api_key and not cfg.controller.api_fingerprint if missing_control or missing_search or missing_api: trust_parts: list[str] = [] diff --git a/tests/test_aiport_standalone.py b/tests/test_aiport_standalone.py index df9db5b..21099bd 100644 --- a/tests/test_aiport_standalone.py +++ b/tests/test_aiport_standalone.py @@ -207,7 +207,7 @@ async def serve(response): try: assert await asyncio.wait_for(requests.get(), 3) == "example-key" cameras = [ - {"mac": "02:11:22:33:44:aa", "name": "North Door"}, + {"id": "camera-1", "mac": "02:11:22:33:44:aa", "name": "North Door"}, {"mac": "02:11:22:33:44:bb", "name": "Other AI Port"}, ] assert await serve(web.json_response(cameras)) == [(camera.device_id, "North Door")] @@ -218,6 +218,12 @@ async def serve(response): assert not redirected cameras[0]["name"] = "Driveway" assert await serve(web.json_response(cameras)) == [(camera.device_id, "Driveway")] + cfg.cameras["camera-1"] = CameraContextConfig(name="Protect ID alias") + for name in ("Driveway", "", None): + cameras[0]["name"] = name + assert await serve(web.json_response(cameras)) == [(camera.device_id, "Protect ID alias")] + del cameras[0]["name"] + assert await serve(web.json_response(cameras)) == [(camera.device_id, "Protect ID alias")] cfg.cameras["02-11-22-33-44-aa"] = CameraContextConfig(name="My alias") assert svc.status()["pairedCameras"][0]["name"] == "My alias" cfg.cameras.clear() diff --git a/tests/test_reset_adoption.py b/tests/test_reset_adoption.py index a13ceae..680204b 100644 --- a/tests/test_reset_adoption.py +++ b/tests/test_reset_adoption.py @@ -14,6 +14,23 @@ from keystone.tls import ensure_device_certificate +def test_standalone_trust_pins_api_without_contacting_search(tmp_path, monkeypatch): + monkeypatch.setenv("KEYSTONE_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("KEYSTONE_CONTROLLER_HOST", "192.0.2.10") + monkeypatch.setenv("KEYSTONE_DEVICE_ENABLED", "false") + monkeypatch.setenv("KEYSTONE_AIPORT_ENABLED", "true") + monkeypatch.setenv("KEYSTONE_CONTROLLER_API_KEY", "example-key") + + def fetch_certificate(host, port): + assert host == "192.0.2.10" and port in (7442, 443) + return b"test certificate" + + monkeypatch.setattr("keystone.cli.fetch_peer_certificate_der", fetch_certificate) + assert cli_main(["trust", "--pin"]) == 0 + assert (tmp_path / "controller-control.sha256").is_file() + assert (tmp_path / "controller-api.sha256").is_file() + + def _seed_state(state_dir: Path) -> None: (state_dir / "aiport").mkdir(parents=True, exist_ok=True) (state_dir / "models" / "clip-vit-l-14").mkdir(parents=True, exist_ok=True)