Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<AI-Port-IP>: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. 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.

</details>

### Speech-to-Text (event transcripts)
Expand Down Expand Up @@ -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 |
Expand Down
2 changes: 2 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion docker-compose.aiport.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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}
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
80 changes: 76 additions & 4 deletions src/keystone/aiport.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import aiohttp
from aiohttp import web
from yarl import URL

from .aiport_audio import (
ALL_PROTECT_AUDIO_TYPES,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -402,11 +411,65 @@ 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, "")

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
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:
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)

@property
def native_faces_enabled(self) -> bool:
Expand Down Expand Up @@ -925,8 +988,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:
Expand Down
22 changes: 16 additions & 6 deletions src/keystone/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -66,10 +66,16 @@ 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),
):
]
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))
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}")
Expand Down Expand Up @@ -285,6 +291,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")

Expand Down Expand Up @@ -445,8 +453,9 @@ 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
if missing_control or missing_search:
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] = []
if args.state_dir:
trust_parts.append(f"KEYSTONE_STATE_DIR={shlex.quote(str(state_dir))}")
Expand Down Expand Up @@ -610,6 +619,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",
Expand Down
5 changes: 5 additions & 0 deletions src/keystone/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def normalize_mac(mac: str) -> str:


CONTROL_PROFILES = ("device-service", "ucp4")
PROTECT_API_PORT = 443


@dataclass
Expand All @@ -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
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading