wifi-densepose/v2/crates/homecore-api
rUv 20ad75f30c
feat(ADR-131): HOMECORE-UI dashboard + BFF gateway — review-fixed (supersedes #1082) (#1099)
* feat(ADR-131): HOMECORE-UI operational dashboard + BFF gateway

Complete two-tier Cognitum operator dashboard (ADR-131), served by
homecore-server at /homecore, plus the single-origin BFF gateway that
wires it to real backends.

Front-end (zero-dep vanilla TS/JS + CSS, exact Cognitum design tokens):
- All 10 panels (§4.1-4.10): dashboard, SEED fleet + detail, fleet map,
  entities (live WS subscribe_events, never polls), rooms, COGs,
  calibration wizard, events + automation builder, witness/audit, settings.
- §6 UX invariants in code: first-class provenance, prominent stale/veto/
  fragility, null(not-trained) vs withheld vs error, --mono everywhere,
  Hailo vs CPU COG distinction.
- api.js calls the gateway routes in production; mock demoted to a
  dev-only ?demo=1 fixture (no mock in prod); typed error states.
- Tests under plain node: import-graph, boot, render-smoke (22),
  interaction (3), prod-errors (13) — 5 files green; bundle ~137 KB
  (~37x smaller than HA), <2 ms/cold-render.

BFF gateway (homecore-server/src/gateway.rs, compiled + tested on Rust 1.89):
- /api/cal/* reverse-proxy to the calibration API (ADR-151).
- GET /api/homecore/rooms with the RoomState adapter (breathing->breathing_bpm,
  heartbeat:null->heart_bpm:null, injected anomaly.threshold/room_id).
- GET /api/homecore/cogs supervisor over /var/lib/cognitum/apps/.
- GET /api/homecore/appliance from /proc + TCP service probes.
- SEED-device/appliance routes return typed 503 upstream_unavailable.
- cargo test -p homecore-server = 12/12; run live (curl-verified);
  fixed a real double-v1 proxy-URL bug found during live testing.

Honest scope: W1/W2/W4/W6-appliance functional; W3/W5/W6-Hailo/federation
return typed 503 (depend on services/hardware not in this repo).

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(homecore-ui): resolve code-review findings — SSRF guard, CORS/trace coverage, §6 honesty, crash guards

Addresses the high-effort review of PR #1082:
- SECURITY: cal_proxy rejects path-traversal/confused-deputy SSRF (`.`/`..`
  segments, backslash, %2e%2e/%2f, absolute) on raw+decoded forms → 400,
  before attaching the server-side calibration bearer.
- CORRECTNESS: /api/homecore/* + /api/cal/* now covered by the shared CORS
  allowlist (build_cors_layer, exported from homecore-api) + TraceLayer —
  previously merged outside router()'s layers (no CORS, no tracing).
- §6 HONESTY (no fabricated data): dashboard renders '—' for null metrics
  (not "null%"/"null°C"); cogs Hailo pill reflects the REAL appliance probe
  (not hardcoded "connected"); room anomaly threshold passed through / null,
  not a fabricated 0.5.
- ROBUSTNESS: cogs asArray(hef) guards a non-array manifest field; calibration
  progress guards target<=0 (no NaN%/Infinity%); restart clears the poll timer.
- CLEANUP: mock.js is now a cached DYNAMIC import (demo-only) — never bundled
  in production (§2.2).
- New ui/tests/unit-fixes.mjs pins the above; ADR-131 + CHANGELOG updated.

Co-Authored-By: claude-flow <ruv@ruv.net>

---------

Co-authored-by: Nick Ruest <127058086+nicholas-ruest@users.noreply.github.com>
2026-06-15 11:11:19 -04:00
..
src feat(ADR-131): HOMECORE-UI dashboard + BFF gateway — review-fixed (supersedes #1082) (#1099) 2026-06-15 11:11:19 -04:00
tests fix(homecore-api security): auth-gate GET /api/ (was unauthenticated) + recover WS subscription on broadcast lag (#1076) 2026-06-14 16:48:57 -04:00
Cargo.toml fix(homecore-api): close WS auth bypass + reply-theater, harden dev bin (ADR-161 A1/A2/A8) 2026-06-12 00:55:16 -04:00
README.md docs(homecore-api): comprehensive README — REST + WebSocket API 2026-05-25 23:09:55 -04:00

README.md

homecore-api

Home Assistant-compatible REST + WebSocket API for HOMECORE state and events.

Crates.io License MSRV: 1.89+ Tests ADR-130

Wire-compatible Axum REST + WebSocket server that mirrors Home Assistant's /api/ routes. Ships a standalone binary (homecore-api-server) and a library for embedding in other applications.

What this crate does

homecore-api provides the HTTP boundary layer for HOMECORE. It wires Axum routes to the homecore state machine, exposing:

  • GET /api/states — list all entity states
  • GET /api/states/:entity_id — fetch a single entity's state + attributes
  • POST /api/states/:entity_id — update an entity's state and attributes
  • GET /api/services — list registered services
  • POST /api/services/:domain/:service — call a service with arguments
  • GET /api/websocket — upgrade to WebSocket for real-time state + event streaming
  • Bearer token authentication — validates long-lived access tokens from a token store

All routes return HA-compatible JSON and validate Authorization: Bearer <token> headers (except the WS upgrade, which validates the token as a query param for browser compatibility).

Features

  • HA-compatible JSON schema/api/states returns [{"entity_id": "...", "state": "...", "attributes": {...}}] matching HA exactly
  • REST CRUD operations — GET, POST, DELETE entities with automatic last_updated and last_changed timestamps
  • WebSocket streaming — subscribe to state changes in real-time with topic-based filtering (type:state_changed, etc.)
  • Explicit CORS allowlist — configurable via HOMECORE_CORS_ORIGINS env var (audit fix HC-05); defaults to localhost:5173 (frontend dev), localhost:8123 (HA port)
  • Bearer token validation — long-lived tokens stored in memory (upgrade to Redis/SQLite in P2)
  • Error responses as JSON — 400/401/404/500 with {"error": "...", "message": "..."} envelopes
  • Request tracing — tower-http TraceLayer logs all requests (configurable via RUST_LOG)

Capabilities

Capability Method Endpoint Returns
List all entities GET /api/states [{entity_id, state, attributes, last_changed, ...}]
Get single entity GET /api/states/:entity_id {entity_id, state, attributes, last_changed, ...} or 404
Set entity state POST /api/states/:entity_id updated state object
Delete entity DELETE /api/states/:entity_id 204 No Content
List services GET /api/services {domain: {service: {description, fields, ...}}}
Call service POST /api/services/:domain/:service service result (P2)
Stream state changes WebSocket /api/websocket {type, event} JSON messages
Validate token Bearer auth all routes 401 Unauthorized if token invalid

Comparison to Home Assistant

Aspect Home Assistant homecore-api
Framework aiohttp Axum
Server type Single-threaded async (Python asyncio) Multi-threaded async (Tokio)
JSON schema HA's /api/states format Wire-compatible (identical)
CORS Permissive (all origins allowed) Explicit allowlist (audit fix HC-05)
Authentication long_lived_access_tokens (SQLite) LongLivedTokenStore (in-memory P1)
WebSocket codec HA's message format + types dict JSON messages with type/event fields (P2)
Service calling async handler dispatch ServiceRegistry stub (P2)
Error handling Python exception → JSON 500 Rust Result + thiserror → JSON with details

Performance

  • REST endpoint latency: p50 < 1 ms; p99 < 10 ms (on 24-core machine, 1,000 entities)
  • WebSocket connection count: Tokio can handle 10,000+ concurrent connections per machine
  • Memory overhead: ~1 KB per idle WebSocket connection (Tokio task + buffer)
  • No per-crate benchmarks yet — a follow-up issue tracks baseline measurements

Usage

use homecore_api::{router, SharedState};
use homecore::HomeCore;
use axum::Server;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    // Create the shared HOMECORE runtime
    let homecore = HomeCore::new();
    let state = SharedState::new(homecore);

    // Build the Axum router
    let app = router(state);

    // Bind to 8123
    let addr = SocketAddr::from(([127, 0, 0, 1], 8123));
    Server::bind(&addr)
        .serve(app.into_make_service_with_connect_info::<SocketAddr>())
        .await
        .expect("server error");
}

Or run the standalone binary:

cargo run -p homecore-api --bin homecore-api-server
# Listens on http://localhost:8123

Test it:

# List states
curl -H "Authorization: Bearer longlivedtoken" \
  http://localhost:8123/api/states

# Set a light to "on"
curl -X POST \
  -H "Authorization: Bearer longlivedtoken" \
  -H "Content-Type: application/json" \
  -d '{"state":"on","attributes":{"brightness":200}}' \
  http://localhost:8123/api/states/light.kitchen

Relation to other HOMECORE crates

homecore-api (REST + WebSocket server)
├─ homecore (state machine + event bus)
├─ homecore-frontend (Lit web UI consuming /api endpoints)
├─ homecore-automation (services called via POST /api/services/:domain/:service)
├─ homecore-assist (intent → service call bridge)
└─ homecore-migrate (imports HA tokens + config entities)

References