diff --git a/.env.example b/.env.example index b23921c..7d194f6 100644 --- a/.env.example +++ b/.env.example @@ -69,21 +69,6 @@ VESSELAPI_IN_INGEST=0 # (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor # currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as # its lookup/fallback is a planned follow-up. -# -# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a -# read-only map + news. Configure the three vars below or admin endpoints -# answer 403 {"detail": "admin auth not configured"} (fail closed — the public -# site keeps working). In the cluster they come from Secret `osint-admin`. -# Generate the hash: python app/auth.py hash 'your password' -# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))' -ADMIN_USER= -ADMIN_PASSWORD_HASH= -ADMIN_SESSION_SECRET= -# Optional: force the session cookie's Secure flag (1/true/yes) when the app is -# reached over plain HTTP behind a TLS-terminating proxy that rewrites -# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway). -# Leave unset locally so the cookie works over http://localhost. -ADMIN_COOKIE_SECURE= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). @@ -98,25 +83,6 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Hermes-4.3-36B remains after a Postgres miss. Env wins when set. # SUMMARY_MODEL= NEWS_BATCH_SIZE=50 -# Map-phase grading: the map model scores each article 0-100, and only blocks -# with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first). -# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least -# SUMMARY_FALLBACK_MIN_SCORE are used; if none do, the reduce phase gets an -# empty DATA section (SUMMARY_FALLBACK_TOP=0 does the same unconditionally). -SUMMARY_MIN_SCORE=60 -SUMMARY_TOP_N=12 -SUMMARY_FALLBACK_TOP=3 -SUMMARY_FALLBACK_MIN_SCORE=40 -# Syndication dedupe: the same wire story arrives from many station domains -# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed -# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised -# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped) -# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike. -# The highest-scoring copy represents the story; the rest are still written to -# article_scores with selected=false and duplicate_of = the surviving article id. -# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour). -SUMMARY_DEDUPE=1 -SUMMARY_DEDUPE_SIMILARITY=0.85 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index b51b488..b2c2a0d 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -1,28 +1,21 @@ -# Build changed OSINT images and publish them to the Forgejo container -# registry. Deployment is NOT done here: the cluster (homek8s, namespace -# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the -# final step prints the tag to pin and a human opens that manifest PR. +# Build changed OSINT images, publish to the Forgejo container registry, then +# redeploy on the Pi runner (docker.sock mounted). # # Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT -# rebuilt on a normal merge — Postgres stays up. Rebuild it only when -# Dockerfile.pg changes, or via workflow_dispatch rebuild_pg. -# -# Registry endpoints -# CI push host: forgejo.forgejo.svc.cluster.local:3000 — plain HTTP -# ClusterIP, whitelisted by --insecure-registry on the amd64 -# runner's dind daemon. 127.0.0.1:3000 stopped working when -# Forgejo moved into k8s: inside an in-cluster job pod, loopback -# is the pod itself, so login died with "connection refused". -# Public pull: forgejo.siriusdevops.com (HTTPS via Cloudflare; kubelet pulls -# from here). Do NOT push here — Cloudflare 413s layers ≳100MB. +# rebuilt or pulled on a normal merge — Postgres stays up. Rebuild it only +# when Dockerfile.pg changes, or via workflow_dispatch rebuild_pg. # +# Public pull host: forgejo.siriusdevops.com (NOT ghcr.io) +# CI push host: 127.0.0.1:3000 — Cloudflare 413s layers ≳100MB on the public +# hostname, even from the Pi (hairpins out through the tunnel). # Images (public names): -# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64- -# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64- -# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64- -# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64- +# forgejo.siriusdevops.com/sirius/osint-dashboard +# forgejo.siriusdevops.com/sirius/osint-dashboard-pg +# forgejo.siriusdevops.com/sirius/osint-news-scraper +# forgejo.siriusdevops.com/sirius/osint-news-summarizer # # Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host. +# Deploy still uses the local docker socket on the runner host (rpi). name: build-and-deploy @@ -42,19 +35,17 @@ on: env: PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }} - PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000 + PUSH_REGISTRY: 127.0.0.1:3000 OWNER: sirius + # Keep compose project/volumes stable on the Pi + COMPOSE_PROJECT_NAME: osint-dashboard jobs: - build-push: - # `amd64` only exists on siriussec-amd64, which is also the node the - # workloads run on — so the images are built on the architecture they are - # pulled to. `runs-on: docker` matched the Pi's arm64 runner, which - # produced images the amd64 cluster could never run. - # No job-level `permissions:` block: Forgejo ignores it (it emits a - # pre-execution warning) and the push authenticates with the FORGEJO_TOKEN - # user PAT instead, because the package registry rejects the Actions token. - runs-on: amd64 + build-push-deploy: + runs-on: docker + permissions: + contents: read + packages: write steps: - name: Checkout uses: https://code.forgejo.org/actions/checkout@v4 @@ -69,6 +60,7 @@ jobs: SCRAPER=0 SUM=0 PG=0 + COMPOSE=0 mark() { case "$1" in @@ -80,6 +72,8 @@ jobs: SCRAPER=1 ;; news/summerizer/*) SUM=1 ;; + docker-compose.yml|scripts/compose-reup.sh) + COMPOSE=1 ;; esac } @@ -114,8 +108,9 @@ jobs: echo "scraper=$SCRAPER" echo "summarizer=$SUM" echo "pg=$PG" + echo "compose=$COMPOSE" } >> "$GITHUB_OUTPUT" - echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG" + echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG compose=$COMPOSE" - name: Image refs id: img @@ -125,11 +120,10 @@ jobs: PUB="${PUBLIC_REGISTRY}" OWN="${OWNER}" SHA="${GITHUB_SHA::12}" - TAG="amd64-${SHA}" { echo "reg=$PUSH" echo "pub=$PUB" - echo "tag=$TAG" + echo "sha=$SHA" echo "app=$PUSH/$OWN/osint-dashboard" echo "pg=$PUSH/$OWN/osint-dashboard-pg" echo "scraper=$PUSH/$OWN/osint-news-scraper" @@ -137,69 +131,113 @@ jobs: } >> "$GITHUB_OUTPUT" echo "Push registry: $PUSH" echo "Public pull: $PUB" - echo "Image tag: $TAG" + echo "SHA tag: $SHA" - name: Login to Forgejo registry if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1' run: | set -euo pipefail # GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages - # reject the Actions token). Use a user PAT. - # The PAT must carry the `write:package` scope: Forgejo mints a push - # token even without it and then rejects every blob upload with - # `unauthorized: reqPackageAccess` (routers/api/packages/api.go - # reqPackageAccess -> AccessTokenScopeWritePackage). - # Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the - # FORGEJO_/GITHUB_ prefixes and refuses to create or update them via - # the API. - if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then - echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)" + # reject the Actions token). Use a user PAT with write:package. + if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then + echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)" exit 1 fi - echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \ + echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \ -u sirius --password-stdin - name: Build application image (api / ingester / cameras) if: steps.plan.outputs.app == '1' run: | set -ex - IMG="${{ steps.img.outputs.app }}" - TAG="${{ steps.img.outputs.tag }}" - docker build -f Dockerfile -t "${IMG}:${TAG}" . - docker push "${IMG}:${TAG}" + APP="${{ steps.img.outputs.app }}" + SHA="${{ steps.img.outputs.sha }}" + docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \ + -t "localhost/osint-dashboard:latest" . + docker push "${APP}:latest" + docker push "${APP}:${SHA}" - name: Build news-scraper image if: steps.plan.outputs.scraper == '1' run: | set -ex IMG="${{ steps.img.outputs.scraper }}" - TAG="${{ steps.img.outputs.tag }}" - docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper - docker push "${IMG}:${TAG}" + SHA="${{ steps.img.outputs.sha }}" + docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \ + -t "localhost/osint-news-scraper:latest" news/scraper + docker push "${IMG}:latest" + docker push "${IMG}:${SHA}" - name: Build news-summarizer image if: steps.plan.outputs.summarizer == '1' run: | set -ex IMG="${{ steps.img.outputs.summarizer }}" - TAG="${{ steps.img.outputs.tag }}" - docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer - docker push "${IMG}:${TAG}" + SHA="${{ steps.img.outputs.sha }}" + docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \ + -t "localhost/osint-news-summarizer:latest" news/summerizer + docker push "${IMG}:latest" + docker push "${IMG}:${SHA}" - name: Build / refresh Timescale+PostGIS image if: steps.plan.outputs.pg == '1' run: | set -ex - IMG="${{ steps.img.outputs.pg }}" - TAG="${{ steps.img.outputs.tag }}" - docker build -f Dockerfile.pg -t "${IMG}:${TAG}" . - docker push "${IMG}:${TAG}" + PG="${{ steps.img.outputs.pg }}" + SHA="${{ steps.img.outputs.sha }}" + if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \ + -t "localhost/osint-dashboard-pg:latest" .; then + docker push "${PG}:latest" + docker push "${PG}:${SHA}" + elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then + echo "WARN: Dockerfile.pg build failed; keeping existing local pg image" + else + echo "ERROR: cannot build or find osint-dashboard-pg image" + exit 1 + fi + + - name: Deploy on runner host (compose) + run: | + set -ex + cd "${GITHUB_WORKSPACE}" + APP="${{ steps.plan.outputs.app }}" + SCRAPER="${{ steps.plan.outputs.scraper }}" + SUM="${{ steps.plan.outputs.summarizer }}" + PG="${{ steps.plan.outputs.pg }}" + COMPOSE="${{ steps.plan.outputs.compose }}" + + SVCS=() + [ "$APP" = "1" ] && SVCS+=(app ingester camera-service) + [ "$SCRAPER" = "1" ] && SVCS+=(news-scraper) + [ "$SUM" = "1" ] && SVCS+=(news-summarizer) + if [ "$COMPOSE" = "1" ]; then + # compose/script change: bounce workers so env/command updates apply. + # Still do not bounce Postgres. + for s in app ingester camera-service news-scraper news-summarizer; do + case " ${SVCS[*]} " in + *" $s "*) ;; + *) SVCS+=("$s") ;; + esac + done + fi + + chmod +x scripts/compose-reup.sh + if [ "$PG" = "1" ]; then + FORCE_RECREATE_DB=1 COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ + scripts/compose-reup.sh "${SVCS[@]}" db + elif [ "${#SVCS[@]}" -gt 0 ]; then + COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ + scripts/compose-reup.sh "${SVCS[@]}" + else + echo "No image or compose changes — leave running containers alone" + docker compose --profile ingest ps + fi + docker image prune -f + echo "osint-dashboard deploy done; db image left in place unless pg=1" - name: Summary if: always() run: | - TAG="${{ steps.img.outputs.tag }}" - PUB="${{ steps.img.outputs.pub }}" { echo "## Image plan" echo "- app: \`${{ steps.plan.outputs.app }}\`" @@ -207,23 +245,5 @@ jobs: echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`" echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`" echo - if [ -n "$TAG" ]; then - echo "## Pin in homek8s (apps/base/osint)" - echo "Pushed tag: \`${TAG}\`. Set the workload images in" - echo "\`apps/base/osint/kustomization.yaml\` to:" - echo - echo '```yaml' - echo "images:" - echo " - name: ${PUB}/${OWNER}/osint-dashboard" - echo " newTag: ${TAG}" - echo " - name: ${PUB}/${OWNER}/osint-news-scraper" - echo " newTag: ${TAG}" - echo " - name: ${PUB}/${OWNER}/osint-news-summarizer" - echo " newTag: ${TAG}" - echo '```' - else - echo "_No tag computed — the earlier steps failed before Image refs._" - fi - echo - echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)." + echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)." } >> "$GITHUB_STEP_SUMMARY" diff --git a/alembic/versions/012_article_scores.py b/alembic/versions/012_article_scores.py deleted file mode 100644 index 853ded7..0000000 --- a/alembic/versions/012_article_scores.py +++ /dev/null @@ -1,39 +0,0 @@ -"""article_scores: per-article map-phase grades for threshold tuning - -Revision ID: 012_article_scores -Revises: 011_geofence_alerts_fence -Create Date: 2026-11-13 -""" - -from alembic import op - -revision = "012_article_scores" -down_revision = "011_geofence_alerts_fence" -branch_labels = None -depends_on = None - - -def upgrade() -> None: - op.execute( - """ - CREATE TABLE IF NOT EXISTS article_scores ( - article_id INTEGER NOT NULL, - summary_id INTEGER, - score INTEGER NOT NULL, - category TEXT, - selected BOOLEAN NOT NULL, - model TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (article_id, created_at) - ) - """ - ) - op.execute( - "CREATE INDEX IF NOT EXISTS ix_article_scores_summary " - "ON article_scores (summary_id)" - ) - - -def downgrade() -> None: - op.execute("DROP INDEX IF EXISTS ix_article_scores_summary") - op.execute("DROP TABLE IF EXISTS article_scores") diff --git a/alembic/versions/013_article_scores_duplicate_of.py b/alembic/versions/013_article_scores_duplicate_of.py deleted file mode 100644 index 2fcfb8b..0000000 --- a/alembic/versions/013_article_scores_duplicate_of.py +++ /dev/null @@ -1,23 +0,0 @@ -"""article_scores.duplicate_of: link a syndicated copy to its representative - -Revision ID: 013_article_scores_duplicate_of -Revises: 012_article_scores -Create Date: 2026-11-13 -""" - -from alembic import op - -revision = "013_article_scores_duplicate_of" -down_revision = "012_article_scores" -branch_labels = None -depends_on = None - - -def upgrade() -> None: - op.execute( - "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER" - ) - - -def downgrade() -> None: - op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of") diff --git a/alembic/versions/014_article_scores_geo.py b/alembic/versions/014_article_scores_geo.py deleted file mode 100644 index 49ba951..0000000 --- a/alembic/versions/014_article_scores_geo.py +++ /dev/null @@ -1,40 +0,0 @@ -"""article_scores geo: per-article proximate location for /api/news/blips - -Revision ID: 014_article_scores_geo -Revises: 013_article_scores_duplicate_of -Create Date: 2026-11-19 - -Additive nullable columns on article_scores (every graded article keeps -its grading row; geo rides along when derivable). Partial bbox index for -the blips endpoint's bbox= filter. Idempotent DDL mirrors the summarizer's -ensure_tables so either start order is safe. -""" - -from alembic import op - -revision = "014_article_scores_geo" -down_revision = "013_article_scores_duplicate_of" -branch_labels = None -depends_on = None - - -def upgrade() -> None: - op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT") - op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION") - op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION") - op.execute( - "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT" - ) - op.execute( - "CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox " - "ON article_scores (lon, lat) " - "WHERE lat IS NOT NULL AND lon IS NOT NULL" - ) - - -def downgrade() -> None: - op.execute("DROP INDEX IF EXISTS ix_article_scores_geo_bbox") - op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_confidence") - op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lon") - op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lat") - op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_name") diff --git a/app/auth.py b/app/auth.py deleted file mode 100644 index a9ac75e..0000000 --- a/app/auth.py +++ /dev/null @@ -1,589 +0,0 @@ -"""Single-admin authentication for the OSINT dashboard. - -The public site stays read-only for anonymous visitors; the one admin (the -operator) unlocks API-key management, settings and every state-changing route. - -Design notes ------------- -* **Deny by default.** :class:`AdminAuthMiddleware` inspects every ``/api/*`` - request. Only the explicit read allowlist below is reachable without a - session; everything else needs a valid signed cookie. ``/api/auth/*`` is the - bootstrap surface and handles its own checks. -* **Fail closed.** With ``ADMIN_PASSWORD_HASH`` or ``ADMIN_SESSION_SECRET`` - unset/empty, admin endpoints answer ``403 {"detail": "admin auth not - configured"}``. There is no default password and no bypass; public reads and - the HUD keep working. -* **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac`` - and the session token is an HMAC-SHA256 signature over a base64url JSON - payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and - ``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or - when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an - HTTP origin listener, where Envoy normalizes the header to ``http``). -* **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer`` - are rejected when the origin host differs from the request host. Requests - without either header (curl, server-to-server) are allowed — the signed, - SameSite=Lax session cookie is what authenticates them. - -Environment (exact names, supplied by the ``osint-admin`` Secret): - -``ADMIN_USER`` - Admin username. -``ADMIN_PASSWORD_HASH`` - ``pbkdf2_sha256$$$``. Generate with:: - - python app/auth.py hash 'your password' - -``ADMIN_SESSION_SECRET`` - HMAC key for session tokens. Generate with:: - - python -c 'import secrets; print(secrets.token_urlsafe(48))' -""" - -from __future__ import annotations - -import base64 -import hashlib -import hmac -import json -import os -import re -import secrets -import time -from collections import deque -from urllib.parse import parse_qs, urlparse - -from fastapi import APIRouter, Request -from fastapi.responses import HTMLResponse, JSONResponse - -# ── Constants ──────────────────────────────────────────────────────────────── - -COOKIE_NAME = "osint_session" -SESSION_TTL_SECONDS = 7 * 24 * 60 * 60 -PBKDF2_ALGORITHM = "pbkdf2_sha256" -PBKDF2_ITERATIONS = 260_000 -_ITERATIONS_FLOOR, _ITERATIONS_CEIL = 1_000, 5_000_000 - -LOGIN_WINDOW_SECONDS = 15 * 60 -LOGIN_MAX_FAILURES = 5 - -_STATE_CHANGING = frozenset({"POST", "PUT", "PATCH", "DELETE"}) - -# ── Public read allowlist ──────────────────────────────────────────────────── -# Anonymous visitors get the map + news HUD. Every path here was audited as a -# pure read (no writes, no spend of a stored API key). Anything absent requires -# the admin session. - -PUBLIC_GET_EXACT = frozenset({ - # core - "/api/health", - "/api/ready", - "/api/stats", - # events / sources / entities / alerts / documents - "/api/sources", - "/api/events", - "/api/fires", - "/api/entities", - "/api/alerts", - "/api/documents", - # analytics - "/api/analytics/summary", - "/api/analytics/timeline", - "/api/analytics/sentiment/by-source", - # cameras - "/api/cameras", - # news - "/api/news", - "/api/news/summaries", - "/api/news/ticker", - "/api/news/map", - "/api/news/blips", - # map / live layers - "/api/map/layers", - "/api/map/chokepoints", - "/api/map/radar", - "/api/map/sentinel1", - "/api/map/gpsjam", - "/api/map/times", - "/api/conflicts", - "/api/aircraft", - "/api/aircraft/photo", - "/api/trains", - "/api/vessels", - "/api/tracks/range", - "/api/satellites", - "/api/infrastructure", - "/api/place", - # geofences (reads only — create/patch/delete stay admin) - "/api/geofences", - "/api/geofence-alerts", - # fire / weather overlays - "/api/fire-aircraft", - "/api/fire-incidents", - "/api/fire-perimeters", - "/api/weather-alerts", - "/api/storms", -}) - -PUBLIC_GET_PATTERNS = tuple(re.compile(p) for p in ( - r"^/api/events/[^/]+$", - r"^/api/entities/[^/]+$", - r"^/api/entities/[^/]+/events$", - r"^/api/cameras/[^/]+$", - r"^/api/cameras/[^/]+/(?:snapshot|stream|hls\.m3u8|hlsseg)$", - r"^/api/geofences/[^/]+/at$", -)) - -# POST is only public for the read-only query endpoint. -PUBLIC_POST_EXACT = frozenset({"/api/search"}) - - -def is_public(path: str, method: str) -> bool: - """True when ``method path`` may be served without an admin session.""" - if not path.startswith("/api/"): - return True - if path.startswith("/api/auth/"): - return True - norm = path.rstrip("/") or "/" - if method in ("GET", "HEAD"): - if norm in PUBLIC_GET_EXACT: - return True - return any(p.match(norm) for p in PUBLIC_GET_PATTERNS) - if method == "POST": - return norm in PUBLIC_POST_EXACT - return False - - -# ── Config (read per call so tests and reloads pick up env changes) ───────── - -def _env(name: str) -> str: - return (os.environ.get(name) or "").strip() - - -def admin_user() -> str: - return _env("ADMIN_USER") - - -def admin_password_hash() -> str: - return _env("ADMIN_PASSWORD_HASH") - - -def session_secret() -> str: - return _env("ADMIN_SESSION_SECRET") - - -def auth_configured() -> bool: - """Fail closed: both the password hash and the signing key must be set.""" - return bool(admin_password_hash() and session_secret()) - - -# ── Password hashing (stdlib PBKDF2-SHA256) ───────────────────────────────── - -def _b64e(raw: bytes) -> str: - return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") - - -def _b64d(text: str) -> bytes: - pad = "=" * (-len(text) % 4) - return base64.urlsafe_b64decode(text + pad) - - -def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS, - salt: bytes | None = None) -> str: - """Return ``pbkdf2_sha256$$$``.""" - salt = salt if salt is not None else secrets.token_bytes(16) - dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) - return f"{PBKDF2_ALGORITHM}${iterations}${_b64e(salt)}${_b64e(dk)}" - - -def verify_password(password: str, stored: str) -> bool: - """Constant-time check of ``password`` against a stored PBKDF2 string.""" - if not stored: - return False - try: - algorithm, iterations_s, salt_b64, hash_b64 = stored.split("$", 3) - iterations = int(iterations_s) - salt = _b64d(salt_b64) - expected = _b64d(hash_b64) - except (ValueError, TypeError): - return False - if algorithm != PBKDF2_ALGORITHM: - return False - if not (_ITERATIONS_FLOOR <= iterations <= _ITERATIONS_CEIL): - return False - dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) - return hmac.compare_digest(dk, expected) - - -def _const_eq(a: str, b: str) -> bool: - return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8")) - - -# ── Session tokens ─────────────────────────────────────────────────────────── - -def _sign(body: str, secret: str) -> str: - digest = hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest() - return _b64e(digest) - - -def create_session_token(user: str, *, now: float | None = None) -> str: - secret = session_secret() - if not secret: - raise RuntimeError("ADMIN_SESSION_SECRET is not configured") - issued = int(now if now is not None else time.time()) - payload = {"v": 1, "sub": user, "iat": issued, "exp": issued + SESSION_TTL_SECONDS} - body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")) - return f"{body}.{_sign(body, secret)}" - - -def verify_session_token(token: str | None, *, now: float | None = None) -> str | None: - """Return the username for a valid token, else ``None``. Never raises.""" - if not token or "." not in token: - return None - secret = session_secret() - if not secret: - return None - body, signature = token.rsplit(".", 1) - try: - expected = _sign(body, secret) - if not hmac.compare_digest(signature.encode("utf-8"), expected.encode("utf-8")): - return None - except (UnicodeEncodeError, ValueError, TypeError): - return None - try: - payload = json.loads(_b64d(body)) - version = payload["v"] - subject = str(payload["sub"]) - issued = int(payload["iat"]) - expires = int(payload["exp"]) - except (ValueError, KeyError, TypeError): - return None - now_s = int(now if now is not None else time.time()) - if version != 1: - return None - if expires <= now_s or issued > now_s + 300: - return None - expected = admin_user() - if not expected or not _const_eq(subject, expected): - return None - return subject - - -def current_user(request: Request) -> str | None: - """The authenticated admin username for this request, else ``None``.""" - if not auth_configured(): - return None - return verify_session_token(request.cookies.get(COOKIE_NAME)) - - -# ── Cookie helpers ─────────────────────────────────────────────────────────── - -def _is_https(request: Request) -> bool: - proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower() - if proto: - return proto == "https" - return request.url.scheme == "https" - - -_TRUTHY = {"1", "true", "yes"} - - -def cookie_secure_forced() -> bool: - """``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only. - - Read on every call so tests and restarts pick up env changes; the header - inference in :func:`_is_https` stays as the fallback. - """ - return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY - - -def set_session_cookie(response, request: Request, token: str) -> None: - response.set_cookie( - COOKIE_NAME, - token, - max_age=SESSION_TTL_SECONDS, - httponly=True, - samesite="lax", - secure=cookie_secure_forced() or _is_https(request), - path="/", - ) - - -def clear_session_cookie(response) -> None: - response.delete_cookie(COOKIE_NAME, path="/", httponly=True, samesite="lax") - - -# ── Login rate limiting (in-memory; single replica) ───────────────────────── - -_failures: dict[str, deque[float]] = {} - - -def client_ip(request: Request) -> str: - forwarded = request.headers.get("x-forwarded-for") or "" - first = forwarded.split(",")[0].strip() - if first: - return first - return request.client.host if request.client else "unknown" - - -def _prune(bucket: deque[float], now: float) -> None: - while bucket and now - bucket[0] > LOGIN_WINDOW_SECONDS: - bucket.popleft() - - -def rate_limited(ip: str, *, now: float | None = None) -> bool: - now_s = time.time() if now is None else now - bucket = _failures.get(ip) - if not bucket: - return False - _prune(bucket, now_s) - return len(bucket) >= LOGIN_MAX_FAILURES - - -def record_failure(ip: str, *, now: float | None = None) -> None: - now_s = time.time() if now is None else now - if len(_failures) > 10_000: # bound memory against IP spraying - for key in [k for k, v in _failures.items() if not v or now_s - v[-1] > LOGIN_WINDOW_SECONDS]: - _failures.pop(key, None) - bucket = _failures.setdefault(ip, deque()) - _prune(bucket, now_s) - bucket.append(now_s) - - -def reset_failures(ip: str | None = None) -> None: - """Clear the limiter (used by logout success and tests).""" - if ip is None: - _failures.clear() - else: - _failures.pop(ip, None) - - -# ── CSRF (origin host must match the request host when supplied) ──────────── - -def origin_allowed(request: Request) -> bool: - if request.method.upper() not in _STATE_CHANGING: - return True - origin = request.headers.get("origin") or request.headers.get("referer") - if not origin: - return True # no browser context: session cookie is the credential - host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "") - host = host.split(",")[0].strip().lower() - try: - origin_host = urlparse(origin).netloc.strip().lower() - except ValueError: - return False - if not host or not origin_host: - return False - return origin_host == host - - -# ── Middleware ─────────────────────────────────────────────────────────────── - -def _json_response(status: int, detail: str) -> JSONResponse: - return JSONResponse({"detail": detail}, status_code=status) - - -class AdminAuthMiddleware: - """Deny-by-default gate for ``/api/*`` (pure ASGI; keeps streaming intact).""" - - def __init__(self, app): - self.app = app - - async def __call__(self, scope, receive, send): - if scope.get("type") != "http": - return await self.app(scope, receive, send) - path = scope.get("path") or "" - method = (scope.get("method") or "GET").upper() - if not path.startswith("/api/") or is_public(path, method): - return await self.app(scope, receive, send) - - request = Request(scope) - if not auth_configured(): - return await _json_response(403, "admin auth not configured")(scope, receive, send) - if current_user(request) is None: - return await _json_response(401, "admin authentication required")(scope, receive, send) - if not origin_allowed(request): - return await _json_response(403, "cross-origin admin request blocked")(scope, receive, send) - return await self.app(scope, receive, send) - - -# ── Auth routes ───────────────────────────────────────────────────────────── - -router = APIRouter() - - -@router.get("/api/auth/me") -async def auth_me(request: Request): - """Always 200 — the HUD uses this to show/hide admin UI.""" - user = current_user(request) - return {"authenticated": user is not None, "admin": user is not None} - - -async def _read_credentials(request: Request) -> dict: - """Accept form-encoded or JSON bodies (never trust the claimed type).""" - raw = await request.body() - if not raw: - return {} - ctype = (request.headers.get("content-type") or "").lower() - if "json" in ctype: - try: - payload = json.loads(raw) - except (ValueError, TypeError): - return {} - return payload if isinstance(payload, dict) else {} - if "form" in ctype or "urlencoded" in ctype: - try: - parsed = parse_qs(raw.decode("utf-8", "replace")) - except (ValueError, TypeError): - return {} - return {k: v[0] for k, v in parsed.items() if v} - # Unknown content type: try JSON, then form. - try: - payload = json.loads(raw) - if isinstance(payload, dict): - return payload - except (ValueError, TypeError): - pass - try: - parsed = parse_qs(raw.decode("utf-8", "replace")) - except (ValueError, TypeError): - return {} - return {k: v[0] for k, v in parsed.items() if v} - - -@router.post("/api/auth/login") -async def auth_login(request: Request): - ip = client_ip(request) - if not auth_configured(): - return _json_response(403, "admin auth not configured") - if rate_limited(ip): - return _json_response(429, "too many failed login attempts") - - data = await _read_credentials(request) - username = str(data.get("username") or data.get("user") or "") - password = str(data.get("password") or "") - - user_ok = bool(username) and bool(admin_user()) and _const_eq(username, admin_user()) - pass_ok = verify_password(password, admin_password_hash()) - if not (user_ok and pass_ok): - record_failure(ip) - return _json_response(401, "invalid credentials") - - reset_failures(ip) - response = JSONResponse({"authenticated": True, "admin": True}) - set_session_cookie(response, request, create_session_token(admin_user())) - return response - - -@router.post("/api/auth/logout") -async def auth_logout(request: Request): - # NOTE: never clear the login limiter here — logout is unauthenticated and - # would otherwise let an attacker reset the rate limit between guesses. - response = JSONResponse({"authenticated": False, "admin": False}) - clear_session_cookie(response) - return response - - -_LOGIN_PAGE = """ - - - - - -Admin sign-in · OSINT// - - - -
-
OSINT// ADMIN
-

Sign in

- - - - - - - -
- - - -""" - -_NOT_CONFIGURED = ('
Admin auth is not configured on this server. ' - 'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.
') - - -@router.get("/login", response_class=HTMLResponse) -async def login_page(): - html = _LOGIN_PAGE - if not auth_configured(): - html = html.replace('', - _NOT_CONFIGURED.replace('class="msg"', 'class="msg" id="msg" role="alert"')) - response = HTMLResponse(html) - response.headers["Cache-Control"] = "no-store" - return response - - -# ── CLI: generate a password hash ──────────────────────────────────────────── - -def _main(argv: list[str]) -> int: - if len(argv) != 2 or argv[0] != "hash": - print("usage: python app/auth.py hash ''") - return 2 - print(hash_password(argv[1])) - return 0 - - -if __name__ == "__main__": - import sys - - raise SystemExit(_main(sys.argv[1:])) diff --git a/app/camera_config.py b/app/camera_config.py index 7376087..2ccff69 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -59,8 +59,7 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots") SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300")) SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0")) -# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators. -# This service does not publish on it; cameras live in the cameras table. +# NATS subject cameras are published on (consumed by the shared ingester). CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") diff --git a/app/camera_scraper.py b/app/camera_scraper.py index d1ca366..10dde21 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -11,8 +11,8 @@ Pipeline per cycle: 2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text `url[|lat,lon|vendor|location]` lines). 3. Geocode missing coords via Nominatim at <=1 req/s. - 4. Upsert into the `cameras` table keyed by sha256(url_hash). - Discovery is not published as an event. + 4. Publish each camera to NATS (`events.camera`) for the shared ingester, + and upsert into the `cameras` table keyed by sha256(url_hash). Snapshots are cached locally with a TTL; nothing is fetched more often than the cache allows. diff --git a/app/config.py b/app/config.py index ea89a8d..b2bdab8 100644 --- a/app/config.py +++ b/app/config.py @@ -107,12 +107,3 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5")) # Run the VesselAPI poller inside the dashboard process (default on, like AIS). VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes") VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes") - -# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser -# viewports; with no tab open it persisted nothing and aircraft_positions went -# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint -# presets while idle, so the hypertable keeps advancing unattended. -ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8")) -ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes") -# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol. -ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30")) diff --git a/app/geofence.py b/app/geofence.py index 342f1c4..f010a3f 100644 --- a/app/geofence.py +++ b/app/geofence.py @@ -7,7 +7,6 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``. from __future__ import annotations import json -import logging from datetime import datetime, timedelta, timezone from typing import Any from uuid import uuid4 @@ -16,19 +15,6 @@ from sqlalchemy import text from database import async_session -logger = logging.getLogger("osint.geofence") - -# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it. -# ``camera`` is never a hit kind. -EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"}) -_CAMERA_CAP = 5 -_NEWS_CAP = 3 -# Process-local "already paged" set for polled incidents. The 5-minute -# cooldown still applies; this stops a later poll (or a restart that -# re-reads the DB check) from treating a durable hit as new. Not used -# for moving adsb/ais/firms targets. -_notified_once: set[tuple[str, str, str]] = set() - def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]: if not isinstance(geojson, dict): @@ -113,160 +99,6 @@ _recent_hits: dict[tuple[str, str], datetime] = {} _HIT_COOLDOWN = timedelta(minutes=5) -def iso_z(ts: datetime) -> str: - """UTC ISO-8601 with a Z suffix so it is safe in a query string.""" - if ts.tzinfo is None: - ts = ts.replace(tzinfo=timezone.utc) - return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def snapshot_path(gid: str, ts: datetime) -> str: - return f"/api/geofences/{gid}/at?ts={iso_z(ts)}" - - -def camera_evidence(row: dict) -> dict: - """Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp).""" - cid = str(row.get("id") or "") - name = row.get("name") - if name is None: - name = row.get("location_name") or "" - return { - "id": cid, - "name": str(name or ""), - "snapshot_url": f"/api/cameras/{cid}/snapshot", - } - - -def news_evidence(row: dict) -> dict: - return { - "headline": str(row.get("headline") or ""), - "url": str(row.get("url") or ""), - "importance": str(row.get("importance") or ""), - } - - -def evidence_pack( - gid: str, ts: datetime, cameras: list[dict], news: list[dict], -) -> dict: - return { - "cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]], - "news": [news_evidence(r) for r in news[:_NEWS_CAP]], - "snapshot": snapshot_path(gid, ts), - } - - -def polygon_bbox(geojson: dict) -> str | None: - """``minlon,minlat,maxlon,maxlat`` of the outer ring, or None.""" - try: - rings = _rings_from_geojson(geojson) - except (ValueError, TypeError, KeyError): - return None - pts = rings[0] - lons = [p[0] for p in pts] - lats = [p[1] for p in pts] - return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}" - - -def earthquake_entity_id(row: dict) -> str: - """Stable id shared by the insert hook and the catch-up scan.""" - raw = row.get("raw") - if isinstance(raw, str): - try: - raw = json.loads(raw) - except ValueError: - raw = None - if isinstance(raw, dict) and raw.get("usgs_id"): - return str(raw["usgs_id"]) - url = row.get("url") - if url and str(url).strip(): - return str(url).strip() - return str(row.get("id") or row.get("event_id") or "") - - -def fire_incident_entity_id(marker: dict) -> str: - """IrwinID when the feed has one, else a stable name|state|discovered key.""" - extra = marker.get("extra") or {} - for key in ("irwin_id", "unique_fire_id"): - val = extra.get(key) - if val: - return str(val) - name = marker.get("id") or marker.get("label") or "incident" - state = extra.get("state") or "" - discovered = extra.get("discovered") or "" - return f"{name}|{state}|{discovered}" - - -# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL. -_CAMERAS_INSIDE_SQL = """ - SELECT id::text AS id, - COALESCE(location_name, '') AS name - FROM cameras - WHERE location_lat IS NOT NULL - AND location_lon IS NOT NULL - AND ST_Intersects( - (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), - ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326) - ) - ORDER BY ST_Distance( - ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326), - ST_SetSRID(ST_MakePoint(:lon, :lat), 4326) - ) - LIMIT :limit -""" - -_NEWS_INSIDE_SQL = """ - SELECT headline, - COALESCE(url, '') AS url, - COALESCE(importance, '') AS importance - FROM news_items - WHERE lat IS NOT NULL - AND lon IS NOT NULL - AND ST_Intersects( - (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), - ST_SetSRID(ST_MakePoint(lon, lat), 4326) - ) - ORDER BY created_at DESC - LIMIT :limit -""" - -_ALREADY_SQL = """ - SELECT 1 - FROM geofence_alerts - WHERE geofence_id = CAST(:gid AS uuid) - AND source_kind = :source_kind - AND entity_id = :entity_id - LIMIT 1 -""" - - -async def _rows(sql: str, params: dict) -> list[dict]: - async with async_session() as session: - result = await session.execute(text(sql), params) - return [dict(r) for r in result.mappings().all()] - - -async def build_evidence( - gid: str, *, lat: float, lon: float, now: datetime, -) -> dict: - """Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence. - - Empty arrays if none or the query fails. Snapshot is a path, not a body. - """ - cameras: list[dict] = [] - news: list[dict] = [] - try: - cameras = await _rows(_CAMERAS_INSIDE_SQL, { - "gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP, - }) - except Exception: - logger.exception("evidence cameras query failed gid=%s", gid) - try: - news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP}) - except Exception: - logger.exception("evidence news query failed gid=%s", gid) - return evidence_pack(gid, now, cameras, news) - - async def refresh_cache() -> list[dict]: global _cache async with async_session() as session: @@ -417,24 +249,12 @@ async def record_and_notify( lat: float, lon: float, payload: dict[str, Any] | None = None, - skip_existing: bool = False, ) -> int: """Insert a geofence_alerts row per hit and WS-push to viewport clients. PostGIS ST_Intersects is the source of truth. The in-process GeoJSON cache is not a reject filter — the FIRMS ingester never fills it. - - ``source_kind=camera`` is refused (no row, no WS). Earthquake, fire - incident, and news hits get an ``evidence`` object; adsb/ais/firms - keep the caller payload unchanged. - - ``skip_existing`` is for polled incidents (same id every cycle). It - does not change the 5-minute cooldown. A failed existence check - skips the hit so a broken read cannot page every fence. """ - if source_kind == "camera": - logger.warning("refusing geofence notify for source_kind=camera") - return 0 hits = await st_intersects(lon, lat) if not hits: return 0 @@ -455,33 +275,6 @@ async def record_and_notify( hits = fresh async with async_session() as session: for fence in hits: - once_key = (str(fence["id"]), source_kind, str(entity_id)) - if skip_existing: - if once_key in _notified_once: - continue - try: - existing = await session.execute( - text(_ALREADY_SQL), - { - "gid": fence["id"], - "source_kind": source_kind, - "entity_id": str(entity_id), - }, - ) - if existing.first() is not None: - _notified_once.add(once_key) - continue - except Exception: - logger.exception( - "geofence existing-hit check failed kind=%s entity=%s", - source_kind, entity_id, - ) - continue - body_payload = dict(payload or {}) - if source_kind in EVIDENCE_KINDS: - body_payload["evidence"] = await build_evidence( - str(fence["id"]), lat=lat, lon=lon, now=now, - ) aid = str(uuid4()) body = { "id": aid, @@ -491,7 +284,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": body_payload, + "payload": payload or {}, "created_at": now.isoformat(), } try: @@ -513,7 +306,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": json.dumps(body_payload), + "payload": json.dumps(payload or {}), }, ) except Exception: @@ -521,8 +314,6 @@ async def record_and_notify( sent += await manager.publish_point( "geofence_alert", body, lat=lat, lon=lon, ) - if skip_existing: - _notified_once.add(once_key) try: await session.commit() except Exception: @@ -679,166 +470,3 @@ async def snapshot_at(gid: str, ts: datetime) -> dict | None: "vessels": vessels, "fires": fires, } - - -_QUAKE_SCAN_SQL = """ - SELECT id::text AS id, url, title, location_lat, location_lon, raw - FROM events - WHERE source_type = 'earthquake' - AND location_lat IS NOT NULL - AND location_lon IS NOT NULL - AND source_timestamp >= now() - interval '7 days' - ORDER BY source_timestamp DESC - LIMIT :limit -""" - -# Same pin set as GET /api/news/map: kind=map, flagged, coords, last 24h. -_NEWS_SCAN_SQL = """ - SELECT id::text AS id, headline, url, importance, lat, lon - FROM news_items - WHERE kind = 'map' - AND lat IS NOT NULL - AND lon IS NOT NULL - AND importance IN ('critical', 'high') - AND created_at >= now() - interval '24 hours' - ORDER BY created_at DESC - LIMIT :limit -""" - - -async def scan_earthquakes(limit: int = 200) -> int: - """Catch-up: quakes already in ``events`` when a fence is drawn later.""" - try: - rows = await _rows(_QUAKE_SCAN_SQL, {"limit": int(limit)}) - except Exception: - logger.exception("earthquake geofence scan failed") - return 0 - n = 0 - for row in rows: - lat, lon = row.get("location_lat"), row.get("location_lon") - if lat is None or lon is None: - continue - eid = earthquake_entity_id(row) - if not eid: - continue - try: - n += await record_and_notify( - source_kind="earthquake", - entity_id=eid, - lat=float(lat), - lon=float(lon), - payload={"title": row.get("title"), "url": row.get("url") or ""}, - skip_existing=True, - ) - except Exception: - logger.exception("earthquake geofence notify failed entity=%s", eid) - return n - - -async def scan_news_pins(limit: int = 200) -> int: - """Read ``news_items`` map pins. Does not import the summarizer.""" - try: - rows = await _rows(_NEWS_SCAN_SQL, {"limit": int(limit)}) - except Exception: - logger.exception("news geofence scan failed") - return 0 - n = 0 - for row in rows: - lat, lon = row.get("lat"), row.get("lon") - if lat is None or lon is None: - continue - eid = str(row.get("id") or "") - if not eid: - continue - try: - n += await record_and_notify( - source_kind="news", - entity_id=eid, - lat=float(lat), - lon=float(lon), - payload={ - "headline": row.get("headline") or "", - "url": row.get("url") or "", - "importance": row.get("importance") or "", - }, - skip_existing=True, - ) - except Exception: - logger.exception("news geofence notify failed entity=%s", eid) - return n - - -async def poll_fire_incidents(fences: list[dict] | None = None) -> int: - """WFIGS incidents are not stored. Fetch each active fence's bbox. - - ``load_fire_incidents`` does not mutate the map cache or correlate - aircraft. A point in the bbox but outside the polygon is dropped - before ``record_and_notify``; ST_Intersects is still the write guard. - """ - if fences is None: - fences = [f for f in cached_fences() if f.get("active", True)] - from live_layers import load_fire_incidents - - n = 0 - seen: set[str] = set() - for fence in fences: - if not fence.get("active", True): - continue - bbox = polygon_bbox(fence.get("geojson") or {}) - if not bbox: - continue - try: - incidents = await load_fire_incidents(bbox) - except Exception: - logger.exception("wfigs fence poll failed bbox=%s", bbox) - continue - if not isinstance(incidents, list): - continue - for inc in incidents: - if not isinstance(inc, dict): - continue - lat, lon = inc.get("lat"), inc.get("lon") - if lat is None or lon is None: - continue - if not point_in_geojson(float(lon), float(lat), fence.get("geojson") or {}): - continue - eid = fire_incident_entity_id(inc) - if not eid or eid in seen: - continue - seen.add(eid) - try: - n += await record_and_notify( - source_kind="fire_incident", - entity_id=eid, - lat=float(lat), - lon=float(lon), - payload={ - "label": inc.get("label"), - "extra": inc.get("extra") or {}, - }, - skip_existing=True, - ) - except Exception: - logger.exception("fire_incident geofence notify failed entity=%s", eid) - return n - - -async def scan_geofence_feeds() -> int: - """Ingester-loop catch-up. No-op when no active fence is cached. - - Earthquakes also notify on insert (``ingestor.ingest_event``). This - scan covers rows already stored, WFIGS (not persisted), and news - pins written by the summarizer process. - """ - try: - await refresh_cache() - except Exception: - logger.exception("geofence cache refresh failed") - fences = [f for f in cached_fences() if f.get("active", True)] - if not fences: - return 0 - n = 0 - n += await scan_earthquakes() - n += await scan_news_pins() - n += await poll_fire_incidents(fences) - return n diff --git a/app/ingestor.py b/app/ingestor.py index 8b2e07c..ccf1471 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -219,32 +219,9 @@ async def ingest_event(msg: dict): await session.commit() event_id = result.inserted_primary_key[0] # type: ignore[union-attr] logger.info("Ingested event %s from source %s", event_id, msg.get("source_type")) - # Cameras are persisted as events only. Never a geofence hit. - if event_row["source_type"] == "earthquake": - await _notify_earthquake(event_row, event_id) return event_id -async def _notify_earthquake(event_row: dict, event_id) -> None: - """One hit per new quake. Dedup already dropped replays; skip if no point.""" - lat, lon = event_row.get("location_lat"), event_row.get("location_lon") - if lat is None or lon is None: - return - try: - from geofence import earthquake_entity_id, record_and_notify - row = {**event_row, "id": str(event_id)} - await record_and_notify( - source_kind="earthquake", - entity_id=earthquake_entity_id(row), - lat=float(lat), - lon=float(lon), - payload={"title": event_row.get("title"), "url": event_row.get("url") or ""}, - skip_existing=True, - ) - except Exception: - logger.exception("earthquake geofence notify failed") - - async def start_nats_consumer(): """Start NATS JetStream consumer for OSINT events.""" nc = await nats.connect(NATS_URLS) diff --git a/app/live_layers.py b/app/live_layers.py index 3c1d92e..99d28ac 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -743,25 +743,18 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]: continue props = feat.get("properties") or {} name = str(props.get("IncidentName") or "Incident").strip() - extra = { - "acres": props.get("IncidentSize"), - "contained": props.get("PercentContained"), - "state": props.get("POOState"), - "category": props.get("IncidentTypeCategory"), - "cause": props.get("FireCause"), - "discovered": props.get("FireDiscoveryDateTime"), - "src": "wfigs", - } - irwin = props.get("IrwinID") - if irwin: - extra["irwin_id"] = str(irwin) - ufi = props.get("UniqueFireIdentifier") - if ufi: - extra["unique_fire_id"] = str(ufi) out.append(to_marker( name, lat, lon, label=name, - extra=extra, + extra={ + "acres": props.get("IncidentSize"), + "contained": props.get("PercentContained"), + "state": props.get("POOState"), + "category": props.get("IncidentTypeCategory"), + "cause": props.get("FireCause"), + "discovered": props.get("FireDiscoveryDateTime"), + "src": "wfigs", + }, )) return out @@ -1091,27 +1084,17 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict: return params -_WFIGS_INCIDENT_FIELDS = ( - "IncidentName,IncidentSize,FireDiscoveryDateTime,POOState," - "PercentContained,IncidentTypeCategory,FireCause," - "IrwinID,UniqueFireIdentifier" -) - - -async def load_fire_incidents(bbox: str | None) -> list[dict]: - """WFIGS points for a bbox. No last-known mutation, no aircraft correlate.""" +async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: params = _wfigs_params(bbox) - params["outFields"] = _WFIGS_INCIDENT_FIELDS + params["outFields"] = ( + "IncidentName,IncidentSize,FireDiscoveryDateTime,POOState," + "PercentContained,IncidentTypeCategory,FireCause" + ) async def _load(): return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params)) rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load) - return list(rows or []) - - -async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: - rows = await load_fire_incidents(bbox) fire_last_known[:] = list(rows) if rows and aircraft_last_known: from fire_aircraft import correlate_and_notify diff --git a/app/main.py b/app/main.py index 00d0d6f..049d96c 100644 --- a/app/main.py +++ b/app/main.py @@ -34,16 +34,15 @@ from sqlalchemy import and_, func, or_, select, text from sqlalchemy.ext.asyncio import AsyncSession from database import async_session, init_extensions -from auth import AdminAuthMiddleware, router as auth_router from models import ( alerts, documents, entities, entity_events, events, feed_sources, fires, - articles, article_scores, article_summaries, news_items, + articles, article_summaries, news_items, ) from schemas import ( AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate, ConflictZoneOut, ConflictsOut, DashboardSummary, EntityCreate, EntityKind, EntityOut, - EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut, + EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, NewsSummaryOut, NewsTickerItemOut, FeedSourceCreate, FeedSourceOut, FeedSourceUpdate, KeyOut, KeyValueIn, @@ -57,7 +56,6 @@ from camera_scraper import is_public_url from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals from fire_sources import ingest_fires from keystore import KeyFormatError, delete_key, list_keys, set_key -from news_title import unwrap_cdata_title from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, @@ -118,57 +116,17 @@ app = FastAPI( ) app.add_middleware(GZipMiddleware, minimum_size=1024) -# Single-admin auth: deny-by-default on /api/* with an explicit public read -# allowlist (app/auth.py), plus /login, /api/auth/{login,logout,me}. -app.add_middleware(AdminAuthMiddleware) -app.include_router(auth_router) - STATIC_DIR = Path(__file__).parent / "static" -def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]: - """Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat). - - Used only while no browser viewport is registered: without it the refresh - loop persists nothing and ``aircraft_positions`` silently stalls whenever - nobody has the map open. - """ - from chokepoints import chokepoints - - out: list[tuple[float, float, float, float]] = [] - for preset in chokepoints(): - try: - # Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order). - minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(",")) - except (KeyError, TypeError, ValueError): - continue - out.append((minlon, minlat, maxlon, maxlat)) - return out - - async def _adsb_refresh_loop() -> None: - """Poll ADSB.lol for connected viewports — never from GET /api/aircraft. - - When no client viewport is registered the loop sweeps the watch boxes - (chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps - advancing with no map open. - """ + """Poll ADSB.lol for connected viewports — never from GET /api/aircraft.""" from ws_manager import manager from live_layers import fetch_aircraft - from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL - - watch_boxes: list[tuple[float, float, float, float]] | None = None while True: - interval = ADSB_REFRESH_INTERVAL try: boxes = manager.viewports() - if not boxes and ADSB_WATCH_ENABLED: - if watch_boxes is None: - watch_boxes = _adsb_watch_boxes() - boxes = watch_boxes - interval = ADSB_WATCH_INTERVAL - logger.debug("adsb_idle_watch", boxes=len(boxes)) for box in boxes: bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}" try: @@ -177,7 +135,7 @@ async def _adsb_refresh_loop() -> None: logger.warning("adsb_refresh_failed", error=str(exc)) except Exception as exc: # noqa: BLE001 logger.warning("adsb_refresh_loop", error=str(exc)) - await asyncio.sleep(interval) + await asyncio.sleep(8) class CachedStaticFiles(StaticFiles): @@ -308,14 +266,7 @@ async def _pipeline_checks(session) -> dict: await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60) await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60) - # Same closed-at-now window as GET /api/news. A future max() made age_s - # negative and hid a fresh list. NULL timestamps are not fresh. - await _age( - "SELECT max(timestamp) FROM articles " - "WHERE timestamp IS NOT NULL AND timestamp <= now()", - "articles", - 2 * 3600, - ) + await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600) await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600) return checks @@ -341,7 +292,7 @@ async def _stats_counts() -> dict: aircraft_last_known, vessel_last_known, train_count, nws_alert_count, ) - counts: dict = { + counts: dict[str, int | str] = { "aircraft": len(aircraft_last_known), "vessels": len(vessel_last_known), "trains": train_count, @@ -373,41 +324,9 @@ async def _stats_counts() -> dict: logger.warning("stats_db_failed", error=str(exc)) counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") - # Public booleans only. Never include the stored value, a prefix, or last-4. - counts["feeds"] = await _feed_flags() return counts -async def _key_configured(*names: str) -> bool: - """True when any named key has a non-empty value in the api_keys store. - - Uses keystore.get_api_key — not env, not a second store. The value is - discarded after the emptiness check. - """ - from keystore import get_api_key - - for name in names: - value = await get_api_key(name) - if isinstance(value, str) and value.strip(): - return True - return False - - -async def _feed_flags() -> dict: - """HUD layer flags. Fail closed (configured false) if the store is down.""" - try: - vessels = await _key_configured("AISSTREAM_API_KEY", "VESSELAPI_API_KEY") - fires = await _key_configured("FIRMS_MAP_KEY") - except Exception as exc: # noqa: BLE001 - logger.warning("stats_feed_flags_failed", error=str(exc)) - vessels = False - fires = False - return { - "vessels": {"configured": vessels}, - "fires": {"configured": fires}, - } - - @app.get("/api/stats") async def api_stats(): """Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s.""" @@ -1368,12 +1287,7 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).where( - or_( - articles.c.timestamp.is_(None), - articles.c.timestamp <= func.now(), - ) - ).order_by( + stmt = select(articles).order_by( articles.c.timestamp.desc().nullslast() ) if domain: @@ -1384,7 +1298,7 @@ async def list_news( rows = (await session.execute(stmt)).mappings().all() return [ NewsArticleOut( - id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"], + id=r["id"], title=r["title"], url=r["url"], content=r["content"] if include_content else None, domain=r["domain"], timestamp=r["timestamp"], ) @@ -1537,94 +1451,6 @@ async def list_news_map( ] -@app.get("/api/news/blips", response_model=list[NewsBlipOut]) -async def list_news_blips( - bbox: str | None = Query( - None, - description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the " - "result set by article coordinates. Omit for all blips.", - ), - since: datetime | None = Query( - None, - description="Only gradings created at/after this UTC instant. " - "Defaults to the last 24 hours.", - ), - limit: int = Query(1000, ge=1, le=5000), -): - """Per-article proximate geo blips: EVERY graded article with a derivable - location (not just the critical/high map pins). Deduped by article id — - the latest grading's geo wins. Only finite lat/lon rows, newest first. - """ - if since is None: - since = datetime.now(timezone.utc) - timedelta(hours=24) - async with async_session() as session: - # DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC - # keeps the latest grading per article; the outer query re-sorts - # newest-first and applies the limit. NaN is excluded explicitly: - # Postgres sorts NaN above every finite value, so range checks - # alone would let it through. prefix_with keeps this renderable on - # both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0). - stmt = ( - select( - article_scores.c.article_id.label("id"), - articles.c.title.label("headline"), - articles.c.url, - articles.c.domain, - article_scores.c.location_name, - article_scores.c.lat, - article_scores.c.lon, - article_scores.c.location_confidence, - article_scores.c.category, - article_scores.c.score, - article_scores.c.created_at, - ) - .select_from( - article_scores.join(articles, articles.c.id == article_scores.c.article_id) - ) - .where( - article_scores.c.lat.isnot(None), - article_scores.c.lon.isnot(None), - article_scores.c.lat.between(-90, 90), - article_scores.c.lon.between(-180, 180), - text("article_scores.lat <> 'NaN'::double precision"), - text("article_scores.lon <> 'NaN'::double precision"), - article_scores.c.created_at >= since, - ) - .prefix_with("DISTINCT ON (article_scores.article_id)") - .order_by(article_scores.c.article_id, article_scores.c.created_at.desc()) - ) - if bbox: - parts = [p.strip() for p in bbox.split(",")] - if len(parts) != 4: - raise HTTPException( - 422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)" - ) - try: - minlon, minlat, maxlon, maxlat = (float(p) for p in parts) - except ValueError: - raise HTTPException( - 422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'" - ) - stmt = stmt.where( - and_( - article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon, - article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat, - ) - ) - latest = stmt.subquery() - ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit) - rows = (await session.execute(ordered)).mappings().all() - return [ - NewsBlipOut( - id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"], - location_name=r["location_name"], lat=r["lat"], lon=r["lon"], - location_confidence=r["location_confidence"], category=r["category"], - score=r["score"], created_at=r["created_at"], - ) - for r in rows - ] - - @app.get("/api/news/models", response_model=NewsModelsOut) async def list_news_models(): """Nous model catalog for the summarizer selector. Never 502s.""" @@ -1951,31 +1777,24 @@ async def api_delete_geofence(gid: str): @app.get("/api/geofences/{gid}/at") async def api_geofence_at( gid: str, - timestamp: str | None = Query( - None, description="ISO-8601 instant for the 1-minute DVR bucket", - ), - ts: str | None = Query( - None, - description="Alias of timestamp. Evidence snapshot URLs use this name.", - ), + timestamp: str = Query(..., description="ISO-8601 instant for the 1-minute DVR bucket"), ): """Aircraft/vessels/fires inside this fence at time T. Never writes.""" from geofence import snapshot_at from tracks import parse_timestamp - raw_ts = timestamp or ts try: - ts_parsed = parse_timestamp(raw_ts) + ts = parse_timestamp(timestamp) except ValueError as exc: raise HTTPException(422, str(exc)) from exc - if ts_parsed is None: + if ts is None: raise HTTPException(422, "timestamp required") try: - body = await snapshot_at(gid, ts_parsed) + body = await snapshot_at(gid, ts) except Exception: body = { "geofence_id": gid, - "timestamp": ts_parsed.isoformat(), + "timestamp": ts.isoformat(), "aircraft": [], "vessels": [], "fires": [], @@ -1990,23 +1809,15 @@ async def api_geofence_alerts( geofence_id: UUID | None = Query(None), since: str | None = Query(None, description="ISO-8601 inclusive lower bound"), until: str | None = Query(None, description="ISO-8601 inclusive upper bound"), - source_kind: str | None = Query( - None, - description="firms|ais|adsb|earthquake|fire_incident|news", - ), + source_kind: str | None = Query(None, description="firms|ais|adsb"), limit: int = Query(100, ge=1, le=500), ): """Hit log for drawn fences. Not /api/alerts (entity/keyword).""" from geofence import list_alerts from tracks import parse_timestamp - if source_kind is not None and source_kind not in ( - "firms", "ais", "adsb", "earthquake", "fire_incident", "news", - ): - raise HTTPException( - 422, - "source_kind must be one of: firms, ais, adsb, earthquake, fire_incident, news", - ) + if source_kind is not None and source_kind not in ("firms", "ais", "adsb"): + raise HTTPException(422, "source_kind must be one of: firms, ais, adsb") try: since_ts = parse_timestamp(since) if since else None until_ts = parse_timestamp(until) if until else None diff --git a/app/models.py b/app/models.py index 4ffbb96..f3b528d 100644 --- a/app/models.py +++ b/app/models.py @@ -4,7 +4,7 @@ from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import ( - Boolean, Column, Enum, Float, Index, Integer, String, Text, + Column, Enum, Float, Index, Integer, String, Text, DateTime, JSON, func, Table, PrimaryKeyConstraint, ) from sqlalchemy.dialects.postgresql import UUID, TSVECTOR @@ -242,34 +242,3 @@ news_items = Table( Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False), ) Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at) - - -# Per-article map-phase grades (alembic 012/013/014). One row per graded -# article per run; PK (article_id, created_at) lets re-grades accumulate. -# Geo columns are nullable: only articles with a derivable location carry -# coordinates, served by GET /api/news/blips. -article_scores = Table( - "article_scores", - metadata, - Column("article_id", Integer, nullable=False), - Column("summary_id", Integer), - Column("score", Integer, nullable=False), - Column("category", Text), - Column("selected", Boolean, nullable=False), - Column("model", Text), - Column("duplicate_of", Integer), - Column("location_name", Text), - Column("lat", Float), - Column("lon", Float), - Column("location_confidence", Text), - Column("created_at", DateTime(timezone=True), - server_default=func.now(), nullable=False), - PrimaryKeyConstraint("article_id", "created_at"), -) -Index("ix_article_scores_summary", article_scores.c.summary_id) -Index( - "ix_article_scores_geo_bbox", - article_scores.c.lon, article_scores.c.lat, - postgresql_where=article_scores.c.lat.isnot(None) - & article_scores.c.lon.isnot(None), -) diff --git a/app/news_title.py b/app/news_title.py deleted file mode 100644 index 29ada1d..0000000 --- a/app/news_title.py +++ /dev/null @@ -1,33 +0,0 @@ -"""News title cleanup for the read path. - -Same rule as ``news/scraper/newsScraper/feed_util.py:unwrap_cdata_title``. -The API image does not include the scraper package, so the function is -copied rather than imported. Existing rows are fixed here on read; this -module does not write. -""" - -from __future__ import annotations - -import re - -# Whole-title CDATA wrapper only. Leading/trailing whitespace around the -# markers belongs to the wrapper, not the title. -_CDATA_WRAPPER = re.compile( - r"\A\s*\s*\Z", - re.DOTALL, -) - - -def unwrap_cdata_title(title: str | None) -> str | None: - """Strip a surrounding CDATA wrapper. Anything else is unchanged. - - ```` and ``\\n `` become - ``Hello``. Real HTML (``Hello``) and a title that merely contains - the markers are returned as-is. Non-strings pass through. - """ - if not isinstance(title, str): - return title - match = _CDATA_WRAPPER.match(title) - if match is None: - return title - return match.group(1).strip() diff --git a/app/run_camera_service.py b/app/run_camera_service.py index 74d774f..c550d04 100644 --- a/app/run_camera_service.py +++ b/app/run_camera_service.py @@ -1,10 +1,9 @@ """Long-running camera discovery service. -Discovers cameras on an interval and upserts them into the `cameras` table -(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an -event: this process does not publish `events.camera` messages. Those were -inserted as events rows and flooded the HUD feed. The cameras table is the -index. +Follows the existing ingest pattern: discovers cameras on an interval and +publishes each one as a NATS message (`events.camera`) so the shared NATS -> +ingester pipeline persists them; also upserts directly into the `cameras` +table (dedupe by url_hash) for the /api/cameras bbox query. Env: CAMERA_SOURCE_URLS comma-separated public directory/list URLs @@ -15,6 +14,7 @@ Env: from __future__ import annotations import asyncio +import json import logging import sys from pathlib import Path @@ -22,12 +22,16 @@ from pathlib import Path sys_path = str(Path(__file__).parent) sys.path.insert(0, sys_path) +import nats # noqa: E402 + from camera_config import ( # noqa: E402 - CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, + CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT, SNAPSHOT_CACHE_DIR, ) -from camera_scraper import run_cycle # noqa: E402 -from database import init_extensions # noqa: E402 +from camera_models import cameras # noqa: E402 +from camera_scraper import run_cycle, url_hash # noqa: E402 +from database import async_session, init_extensions # noqa: E402 +from config import NATS_URL # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") @@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service") ENABLED = sys.argv[1:] != ["--once"] -async def publish_new_cameras(rows: list | None = None) -> int: - """Do not publish camera discoveries as events. - - ``run_cycle`` already upserts the cameras table, which backs - ``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a - test; none are JetStream-published, so the ingester inserts 0 events - with source_type=camera. - """ - del rows - return 0 +async def publish_new_cameras() -> int: + """Publish cameras seen in the latest cycle to NATS for the ingester.""" + from datetime import datetime, timezone, timedelta + cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2) + published = 0 + try: + nc = await nats.connect(NATS_URL) + except Exception: # noqa: BLE001 + logger.warning("NATS unavailable — skipping publish pass") + return 0 + try: + js = nc.jetstream() + async with async_session() as session: + rows = (await session.execute( + cameras.select().where(cameras.c.last_seen >= cutoff) + )).mappings().all() + for r in rows: + msg = { + "source_type": "camera", + "title": f"Open camera ({r['vendor'] or 'unknown vendor'})", + "url": r["source_url"], + "location_lat": r["location_lat"], + "location_lon": r["location_lon"], + "location_name": r["location_name"], + "tags": ["osint", "camera", r["discovery_source"]], + "raw": { + "url_hash": r["url_hash"], + "snapshot_url": r["snapshot_url"], + "vendor": r["vendor"], + "device_type": r["device_type"], + "first_seen": r["first_seen"].isoformat(), + "last_seen": r["last_seen"].isoformat(), + }, + "source_timestamp": datetime.now(timezone.utc).isoformat(), + } + await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode()) + published += 1 + if published >= 500: # per-cycle cap + break + finally: + await nc.close() + return published async def main() -> None: @@ -57,7 +93,8 @@ async def main() -> None: try: n = await run_cycle() p = await publish_new_cameras() - logger.info("cycle: %d stored, %d camera events published", n, p) + logger.info("cycle: %d stored, %d published to %s", + n, p, CAMERA_NATS_SUBJECT) except Exception: # noqa: BLE001 logger.exception("camera cycle error") if not ENABLED: # --once mode diff --git a/app/run_ingester.py b/app/run_ingester.py index 2ef49e6..5d94389 100644 --- a/app/run_ingester.py +++ b/app/run_ingester.py @@ -56,11 +56,8 @@ async def producer_loop() -> None: try: g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50) logger.info("GDELT -> %d articles", g) - except Exception as exc: # noqa: BLE001 - # Quota/backoff cases are handled inside ingest_gdelt (one clean - # line); anything reaching here is a real failure and a stack - # trace every 5 minutes is not actionable, so keep it to one line. - logger.warning("GDELT fetch failed: %s", exc) + except Exception: # noqa: BLE001 + logger.exception("GDELT fetch failed") if ENABLE_QUAKES: try: q = await ingest_earthquakes() @@ -119,24 +116,6 @@ async def fire_loop() -> None: await asyncio.sleep(FIRMS_INTERVAL) -async def geofence_feed_loop() -> None: - """Hear quakes already stored, WFIGS incidents, and news map pins. - - WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS - or AIS key). News pins are read from ``news_items``; the summarizer - is not imported. New earthquakes also notify from ``ingest_event``. - """ - logger.info("geofence feed loop starting (interval=%ss)", INTERVAL) - while True: - try: - from geofence import scan_geofence_feeds - n = await scan_geofence_feeds() - logger.info("geofence feeds -> %d notifies", n) - except Exception: # noqa: BLE001 - logger.exception("geofence feed scan failed") - await asyncio.sleep(INTERVAL) - - async def main() -> None: logger.info( "ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)", @@ -147,9 +126,7 @@ async def main() -> None: await refresh_cache() except Exception: logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)") - tasks: list[asyncio.Task] = [ - asyncio.create_task(geofence_feed_loop()), - ] + tasks: list[asyncio.Task] = [] if ENABLE_FIRES: # Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs # and idles otherwise). diff --git a/app/schemas.py b/app/schemas.py index 1834634..64676fc 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -314,26 +314,6 @@ class NewsMapItemOut(BaseModel): created_at: datetime -class NewsBlipOut(BaseModel): - """One per-article proximate geo blip as exposed by GET /api/news/blips. - - Frozen wire contract (card t_bc15eb53): every graded article with a - derivable location, deduped by article id (latest grading wins). - Unlike /api/news/map this is NOT limited to critical/high items. - """ - id: int - headline: str - url: Optional[str] = None - domain: Optional[str] = None - location_name: Optional[str] = None - lat: float - lon: float - location_confidence: Optional[str] = None - category: Optional[str] = None - score: Optional[int] = None - created_at: datetime - - class NewsModelId(BaseModel): """One model id as exposed by GET /api/news/models.""" diff --git a/app/sources.py b/app/sources.py index 115b55c..7d587a5 100644 --- a/app/sources.py +++ b/app/sources.py @@ -2,15 +2,9 @@ from __future__ import annotations -import html -import io import json import logging -import os -import re -import time -import zipfile -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone from email.utils import parsedate_to_datetime import httpx @@ -149,61 +143,6 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]: } -# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window -# grows with request volume, so the only useful reaction to a 429 is to stop -# asking: skip whole producer cycles, doubling the wait from BASE to MAX. -GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300")) -GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800")) -_gdelt_backoff_secs = 0 -_gdelt_backoff_until = 0.0 # time.monotonic() - - -def gdelt_backoff_remaining() -> float: - """Seconds left in the GDELT cooldown window (0 = ready to call).""" - return max(0.0, _gdelt_backoff_until - time.monotonic()) - - -def _gdelt_backoff_until_iso() -> str: - return ( - datetime.now(timezone.utc).replace(microsecond=0) - + timedelta(seconds=gdelt_backoff_remaining()) - ).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _gdelt_start_backoff(retry_after: float | None = None) -> None: - global _gdelt_backoff_secs, _gdelt_backoff_until - wait = retry_after or min( - GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2) - ) - _gdelt_backoff_secs = int(wait) - _gdelt_backoff_until = time.monotonic() + wait - - -def _gdelt_clear_backoff() -> None: - global _gdelt_backoff_secs, _gdelt_backoff_until - _gdelt_backoff_secs = 0 - _gdelt_backoff_until = 0.0 - - -def _gdelt_retry_after(resp: httpx.Response) -> float | None: - """Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither.""" - raw = resp.headers.get("retry-after") - if not raw: - return None - raw = raw.strip() - try: - return max(1.0, float(raw)) - except ValueError: - pass - try: - return max( - 1.0, - (parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(), - ) - except (TypeError, ValueError): - return None - - def _parse_gdelt_seendate(value: object) -> str: if isinstance(value, str) and len(value) >= 15: try: @@ -236,59 +175,25 @@ def parse_gdelt_articles(data: dict) -> list[dict]: return events -async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50): - """Fetch articles from the GDELT DOC 2.0 API. - - GDELT enforces a per-IP quota that answers ``429`` with a plain-text body - ("Please limit requests to one every 5 seconds"), sends **no** Retry-After, - and widens the block window as request volume accumulates. So a 429 is not - retried: the ingester stops calling until a backoff window expires, and the - cycle is skipped with a single log line. See ``gdelt_backoff_remaining``. - """ - remaining = gdelt_backoff_remaining() - if remaining > 0: - logger.info( - "GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining) - ) - return 0 - +async def ingest_gdelt(query: str = "", max_articles: int = 50): + """Fetch articles from the GDELT DOC 2.0 API.""" params = gdelt_params(query=query, max_articles=max_articles) + data: dict = {"articles": []} async with httpx.AsyncClient( timeout=60, headers=_ua_headers(), follow_redirects=True, ) as client: try: resp = await client.get(GDELT_API, params=params) - except httpx.TransportError as exc: - # gdeltproject.org certs have expired in the wild; HTTP fallback. - # Only transport failures (TLS/connect) get the fallback — an HTTP - # error status is a quota answer and retrying it just burns the - # same per-IP budget a second time. - logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc) - http_url = GDELT_API.replace("https://", "http://", 1) - resp = await client.get(http_url, params=params) - - if resp.status_code == 429: - _gdelt_start_backoff(_gdelt_retry_after(resp)) - logger.warning( - "GDELT 429 (rate limited) -> backing off until %s", - _gdelt_backoff_until_iso(), - ) - return 0 - - try: resp.raise_for_status() data = resp.json() - except (httpx.HTTPStatusError, ValueError) as exc: - # GDELT also signals errors/throttling as HTTP 200 + prose, so a - # JSON decode failure is "busy", not "no results". - _gdelt_start_backoff(_gdelt_retry_after(resp)) - logger.warning( - "GDELT unusable response (HTTP %s: %s) -> backing off until %s", - resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(), - ) - return 0 + except (httpx.TransportError, httpx.HTTPStatusError) as exc: + # gdeltproject.org certs have expired in the wild; HTTP fallback. + logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc) + http_url = GDELT_API.replace("https://", "http://", 1) + resp = await client.get(http_url, params=params) + resp.raise_for_status() + data = resp.json() - _gdelt_clear_backoff() events = parse_gdelt_articles(data if isinstance(data, dict) else {}) for event in events: await publish_event("events.gdelt", event) @@ -296,240 +201,6 @@ async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50): return len(events) -# ─── GDELT 2.0 15-minute bulk files (throttle-free) ───────────────────── -# -# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is -# published every 15 minutes as static files under /gdeltv2/ with no key and no -# quota, indexed by ``lastupdate.txt``: -# *.export.CSV.zip events (CAMEO codes) -# *.mentions.CSV.zip event->article mentions (URL + confidence, no title) -# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source -# domain, themes, locations with lat/lon, tone, and the -# page title in the V2ExtrasXML column -# GKG is the one that carries title + geo, so map a filtered row into the same -# event shape ``parse_gdelt_articles`` produces and let the existing -# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working. - -GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes") -GDELT_BULK_LASTUPDATE = os.getenv( - "GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt" -) -GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100")) - -# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the -# 15-minute file behind it only changes 4x/hour. -_gdelt_bulk_last_file: str | None = None - -_PAGE_TITLE_RE = re.compile(r"(.*?)", re.DOTALL) -_PAGE_PUB_TS_RE = re.compile(r"(\d{14})<") - - -def gdelt_query_terms(query: str = "") -> list[str]: - """CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms. - - Used to filter bulk rows against their GKG theme tokens instead of - publishing every article in the 15-minute window. - """ - q = (query or "").strip() or GDELT_DEFAULT_QUERY - terms: list[str] = [] - for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE): - term = part.strip().strip('"').strip("'").strip().lower() - if term and term not in terms: - terms.append(term) - return terms - - -def _term_hits_themes(term: str, themes: str) -> bool: - """Term matches when every word of it appears in the theme token list.""" - words = [w for w in re.split(r"[\s_\-]+", term) if w] - return bool(words) and all(w in themes for w in words) - - -def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None: - """``(filename, https_url)`` of the newest GKG file in lastupdate.txt. - - lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise - so the fetch never follows a redirect into a stale mirror. - """ - for line in (lastupdate_text or "").splitlines(): - parts = line.split() - if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"): - continue - url = parts[2] - if url.startswith("http://"): - url = "https://" + url[len("http://"):] - return url.rsplit("/", 1)[-1], url - return None - - -def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]: - """First location in a V2Locations field -> (lat, lon, name). - - V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the - adm2 slot is sometimes dropped, so read the triple from the end. - """ - segment = (field or "").split(";", 1)[0] - parts = segment.split("#") - if len(parts) < 5: - return None, None, None - name = parts[1].strip() or None - try: - lat = float(parts[-3]) - lon = float(parts[-2]) - except (TypeError, ValueError): - return None, None, name - if not (-90 <= lat <= 90 and -180 <= lon <= 180): - return None, None, name - return lat, lon, name - - -def _gkg_tone(field: str) -> float | None: - try: - return _parse_gdelt_tone(field.split(",", 1)[0]) - except (AttributeError, IndexError): - return None - - -def _gkg_timestamp(row: list[str], extras: str) -> str: - """Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp.""" - stamps = [] - pub = _PAGE_PUB_TS_RE.search(extras) - if pub is not None: - stamps.append(pub.group(1)) - if len(row) > 1 and isinstance(row[1], str): - stamps.append(row[1][:14]) - for stamp in stamps: - try: - return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace( - tzinfo=timezone.utc - ).isoformat() - except ValueError: - continue - return datetime.now(timezone.utc).isoformat() - - -def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None: - """Map one GKG CSV row into the ``events.gdelt`` event shape. - - Returns None when the row has no usable URL or matches none of ``terms``. - """ - if len(row) < 8: - return None - url = (row[4] or "").strip() - if not url.startswith(("http://", "https://")): - return None - - raw_themes = row[7] or "" - themes = raw_themes.lower() - matched = [t for t in terms if _term_hits_themes(t, themes)] - if not matched: - return None - - extras = row[-1] if isinstance(row[-1], str) else "" - title_match = _PAGE_TITLE_RE.search(extras) - title = html.unescape(title_match.group(1)).strip() if title_match else None - - lat = lon = loc_name = None - for idx in (9, 10): - if idx < len(row): - lat, lon, loc_name = _gkg_location(row[idx]) - if lat is not None: - break - - theme_tokens = [t for t in raw_themes.split(";") if t] - tags = matched + [ - t for t in theme_tokens - if any(w in t.lower() for w in matched) - ] - tags = list(dict.fromkeys(tags))[:10] - - return { - "source_type": "gdel-t2", - "title": title, - "body": (row[3] or "").strip() or None, - "url": url, - "location_lat": lat, - "location_lon": lon, - "location_name": loc_name, - "source_timestamp": _gkg_timestamp(row, extras), - "tags": tags, - "raw": { - "gkg_record_id": row[0], - "source_common_name": row[3], - "source_collection": row[2], - "themes": theme_tokens[:12], - "tone": _gkg_tone(row[15]) if len(row) > 15 else None, - "bulk_file": bulk_file, - }, - } - - -async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int: - """Publish new articles from the newest 15-minute GKG bulk file. - - No API key, no per-IP quota, and the existing URL dedupe means re-reading - the same file after a restart publishes nothing new. - """ - global _gdelt_bulk_last_file - cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events - - async with httpx.AsyncClient( - timeout=120, headers=_ua_headers(), follow_redirects=True, - ) as client: - index = await client.get(GDELT_BULK_LASTUPDATE) - index.raise_for_status() - picked = select_gdelt_bulk_url(index.text) - if picked is None: - logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt") - return 0 - filename, url = picked - if filename == _gdelt_bulk_last_file: - logger.debug("GDELT bulk: %s already ingested; nothing new", filename) - return 0 - archive = await client.get(url) - archive.raise_for_status() - - terms = gdelt_query_terms(query) - events: list[dict] = [] - scanned = 0 - with zipfile.ZipFile(io.BytesIO(archive.content)) as zf: - member = zf.namelist()[0] - with zf.open(member) as fh: - for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"): - if not line.strip(): - continue - scanned += 1 - event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename) - if event is not None and len(events) < cap: - events.append(event) - - published = await _publish_unknown("events.gdelt", events) - _gdelt_bulk_last_file = filename - logger.info( - "GDELT bulk %s: %d/%d rows matched %s, %d new articles published", - filename, len(events), scanned, "/".join(terms), published, - ) - return published - - -async def ingest_gdelt(query: str = "", max_articles: int = 50): - """GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback. - - The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff) - only runs when the bulk fetch itself fails, so the per-IP quota is no longer - on the hot path. - """ - if GDELT_BULK_ENABLED: - try: - return await ingest_gdelt_bulk(query=query) - except Exception as exc: # noqa: BLE001 — any bulk failure falls back - logger.warning( - "GDELT bulk fetch failed (%s: %s); falling back to DOC API", - type(exc).__name__, str(exc)[:160], - ) - return await _ingest_gdelt_doc(query=query, max_articles=max_articles) - - def _parse_gdelt_tone(tone: str) -> float | None: """Parse GDELT tone string to a -1..1 sentiment score.""" try: diff --git a/app/static/index.html b/app/static/index.html index 28b058a..e75f9bb 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -3,10 +3,10 @@ - OSINT// + OSINT//DASHBOARD — Global Situational Awareness Terminal - + @@ -35,12 +35,12 @@ --text: #c8e6f2; --muted: #5f7d95; --topbar-h: 46px; - --dock-h: 32px; /* one NEWS ticker; MKT hidden until live */ + --dock-h: 62px; } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; } body { - font-family: 'IBM Plex Sans', 'Segoe UI', system-ui, sans-serif; + font-family: 'Rajdhani', 'Segoe UI', system-ui, sans-serif; background: var(--bg-0); color: var(--text); overflow: hidden; font-size: 15px; letter-spacing: 0.01em; @@ -48,12 +48,12 @@ ::selection { background: var(--cyan-dim); color: #eafcff; } :focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; } a { color: var(--cyan); } - .mono, code, kbd { font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-variant-numeric: tabular-nums; } + .mono, code, kbd { font-family: 'Share Tech Mono', ui-monospace, SFMono-Regular, Menlo, monospace; } .btn { background: linear-gradient(180deg, var(--bg-3), var(--bg-2)); border: 1px solid var(--line); color: var(--text); border-radius: 4px; padding: 0.35rem 0.9rem; cursor: pointer; - font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; + font-family: 'Rajdhani', sans-serif; font-weight: 600; font-size: 0.8rem; letter-spacing: 0.06em; text-transform: uppercase; transition: border-color .15s, box-shadow .15s, color .15s; } @@ -84,18 +84,18 @@ } .brand { display: flex; align-items: center; gap: 0.65rem; min-width: 0; } .brand-mark { - font-family: 'IBM Plex Sans', sans-serif; color: var(--cyan); + font-family: 'Orbitron', sans-serif; color: var(--cyan); font-size: 1.05rem; text-shadow: 0 0 12px var(--cyan-glow); border: 1px solid var(--line-hi); padding: 0.1rem 0.34rem; border-radius: 3px; background: rgba(53,224,255,0.06); } .brand-name { - font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; font-size: 0.95rem; + font-family: 'Orbitron', sans-serif; font-weight: 700; font-size: 0.95rem; color: #eafcff; letter-spacing: 0.14em; white-space: nowrap; } .brand-name .accent { color: var(--cyan); text-shadow: 0 0 10px var(--cyan-glow); } .brand-sub { - font-family: 'IBM Plex Mono', monospace; font-size: 0.58rem; + font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; color: var(--muted); letter-spacing: 0.22em; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @@ -103,7 +103,7 @@ .topbar-right { display: flex; align-items: center; gap: 1rem; } .sys-status { display: flex; align-items: center; gap: 0.5rem; - font-family: 'IBM Plex Mono', monospace; font-size: 0.72rem; + font-family: 'Share Tech Mono', monospace; font-size: 0.72rem; color: var(--muted); white-space: nowrap; } .sys-status .sep { opacity: 0.35; } @@ -112,10 +112,6 @@ .dot.bad { background: var(--red); box-shadow: 0 0 8px var(--red); } .dot.dim { background: var(--muted); box-shadow: none; animation: none; } @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } } - .clock, .lp-count, .hud-chip b, #utc-clock, #dvr-label { - font-variant-numeric: tabular-nums; - font-family: 'IBM Plex Mono', ui-monospace, monospace; - } .clock { color: var(--cyan); } @media (max-width: 720px) { .sys-status .hide-sm { display: none; } } @@ -125,7 +121,7 @@ display: flex; align-items: center; gap: 0.5rem; background: linear-gradient(180deg, var(--bg-3), var(--bg-2)); border: 1px solid var(--line-hi); color: var(--text); - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.72rem; font-weight: 700; + font-family: 'Orbitron', sans-serif; font-size: 0.72rem; font-weight: 700; letter-spacing: 0.16em; padding: 0.42rem 0.85rem; border-radius: 4px; cursor: pointer; transition: border-color .15s, box-shadow .15s; } @@ -147,7 +143,7 @@ .nav-item { display: flex; align-items: center; gap: 0.6rem; width: 100%; background: none; border: none; color: var(--text); text-align: left; - font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; font-size: 0.88rem; + font-family: 'Rajdhani', sans-serif; font-weight: 600; font-size: 0.88rem; letter-spacing: 0.09em; text-transform: uppercase; padding: 0.55rem 0.7rem; border-radius: 4px; cursor: pointer; border-left: 2px solid transparent; @@ -157,20 +153,6 @@ .nav-item.primary .ico { color: var(--magenta); } .nav-sep { height: 1px; background: var(--line); margin: 0.35rem 0.3rem; } - /* ═══════════════ ADMIN GATE (UX only — the API is the real gate) ═══ - Elements marked data-admin stay hidden until /api/auth/me reports a - valid admin session (body.is-admin). Fails closed: no JS => hidden. */ - body:not(.is-admin) [data-admin] { display: none !important; } - .admin-link { - font-size: 0.62rem; letter-spacing: 0.16em; text-transform: uppercase; - color: var(--muted); text-decoration: none; border: 1px solid var(--line); - border-radius: 3px; padding: 0.28rem 0.5rem; white-space: nowrap; - transition: color .15s, border-color .15s; - } - .admin-link:hover, .admin-link:focus-visible { color: var(--cyan); border-color: var(--cyan); } - body.is-admin .admin-link { color: var(--magenta); border-color: var(--magenta); } - - /* ═══════════════ STAGE / VIEWS ═══════════════ */ .stage { /* 100vh first for old browsers; 100dvh shrinks with mobile URL chrome */ @@ -195,12 +177,17 @@ max-width: calc(100% - 300px); /* keep off LAYERS (left) and zoom (right) */ justify-content: center; } - .chokepoint-btns { display: none; } - #chokepoint-select { display: inline-block; min-width: 8rem; } + .chokepoint-btns { display: flex; flex-wrap: wrap; align-items: center; gap: 0.25rem; } + .chokepoint-btns .btn { padding: 0.22rem 0.42rem; font-size: 0.66rem; letter-spacing: 0.04em; } + .chokepoint-btns .btn.is-on { + border-color: var(--cyan); color: var(--cyan); + box-shadow: 0 0 8px var(--cyan-glow); background: rgba(53,224,255,0.10); + } + #chokepoint-select { display: none; } .map-toolbar select, .map-toolbar input[type="date"], .map-toolbar input[type="datetime-local"] { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.3rem 0.45rem; font-size: 0.76rem; - font-family: 'IBM Plex Mono', monospace; color-scheme: dark; + font-family: 'Share Tech Mono', monospace; color-scheme: dark; } .map-toolbar select:focus, .map-toolbar input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .map-toolbar .btn { padding: 0.3rem 0.6rem; font-size: 0.72rem; } @@ -219,7 +206,7 @@ .leaflet-control-zoom a:hover { background: var(--bg-3) !important; color: var(--cyan) !important; } .leaflet-control-attribution { background: rgba(3,6,9,0.78) !important; color: #8fa8bd !important; - font-family: 'IBM Plex Mono', monospace !important; font-size: 10px !important; + font-family: 'Share Tech Mono', monospace !important; font-size: 10px !important; } .leaflet-control-attribution a { color: var(--cyan) !important; } .leaflet-popup-content-wrapper, .leaflet-popup-tip { @@ -274,25 +261,10 @@ .marker-cluster-medium div { font-size: 11px; } .marker-cluster-large div { font-size: 12px; } - /* ── Article blip clusters (quiet violet, matches the small blips) ── */ - .marker-cluster-articles { background-color: rgba(160, 108, 213, 0.16); } - .marker-cluster-articles div { - background-color: rgba(122, 74, 160, 0.88); - color: #efe6f9; - font-weight: 600; - box-shadow: 0 0 10px rgba(160, 108, 213, 0.35), 0 0 2px rgba(3, 6, 9, 0.9); - } - .articles-sm div { font-size: 10px; } - .articles-md div { font-size: 11px; } - .articles-lg div { font-size: 12px; } - /* FIRMS heat is visual-only (no listeners) but its canvas sits on top - of the overlay pane and eats clicks meant for vector blips/pins. */ - .leaflet-heatmap-layer { pointer-events: none; } - /* ── Map hint + HUD chips ── */ .map-hint { position: absolute; left: 12px; bottom: 12px; z-index: 500; - font-family: 'IBM Plex Mono', monospace; font-size: 0.68rem; color: var(--muted); + font-family: 'Share Tech Mono', monospace; font-size: 0.68rem; color: var(--muted); background: rgba(6,11,20,0.72); border: 1px solid var(--line); border-radius: 4px; padding: 0.3rem 0.6rem; max-width: 60%; text-shadow: 0 0 6px rgba(0,0,0,0.8); @@ -303,7 +275,7 @@ } .hud-chip { display: flex; align-items: center; gap: 0.45rem; - font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); background: rgba(6,11,20,0.78); border: 1px solid var(--line); border-radius: 4px; padding: 0.26rem 0.55rem; letter-spacing: 0.06em; backdrop-filter: blur(4px); @@ -314,14 +286,13 @@ .hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; } .hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); } .hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); } - .hud-chip .c.articles { background: #a06cd5; box-shadow: 0 0 6px rgba(160,108,213,0.6); } .hud-chip.off { opacity: 0.4; } #dvr-bar { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); z-index: 520; display: flex; align-items: center; gap: 0.55rem; background: rgba(6,11,20,0.86); border: 1px solid var(--line-hi); border-radius: 4px; padding: 0.28rem 0.7rem; - font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); min-width: 280px; max-width: 52%; } #dvr-bar input[type=range] { flex: 1; accent-color: var(--cyan); } @@ -332,7 +303,7 @@ } #dvr-toast .gf-alert { background: rgba(255,46,151,0.16); border: 1px solid var(--magenta); - color: var(--text); font-family: 'IBM Plex Mono', monospace; + color: var(--text); font-family: 'Share Tech Mono', monospace; font-size: 0.68rem; padding: 0.4rem 0.6rem; margin-bottom: 0.35rem; border-radius: 4px; } @@ -340,19 +311,17 @@ /* ── Layer control panel (dark HUD) ── */ #layer-panel { position: absolute; top: 58px; left: 12px; z-index: 600; - width: min(320px, calc(100% - 24px)); max-width: 320px; - max-height: calc(100% - 74px); overflow: hidden; + width: 268px; max-height: calc(100% - 74px); overflow: hidden; background: rgba(6,11,20,0.86); backdrop-filter: blur(8px); border: 1px solid var(--line-hi); border-radius: 6px; box-shadow: 0 0 22px rgba(53,224,255,0.14), 0 0 2px rgba(53,224,255,0.4); color: var(--text); font-size: 0.78rem; display: flex; flex-direction: column; clip-path: polygon(0 8px, 8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px)); } - #layer-panel.collapsed { width: auto; max-width: 320px; } .lp-head { display: flex; justify-content: space-between; align-items: center; padding: 0.55rem 0.75rem; border-bottom: 1px solid var(--line); - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; font-weight: 700; + font-family: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 10px rgba(53,224,255,0.55); cursor: pointer; user-select: none; background: linear-gradient(180deg, rgba(53,224,255,0.07), transparent); @@ -372,8 +341,7 @@ .lp-dot.fires { background: #fb923c; box-shadow: 0 0 7px #fb923c; } .lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; } .lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); } - .lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); } - .lp-dot.articles { background: #a06cd5; box-shadow: 0 0 7px rgba(160,108,213,0.6); } + .lp-dot.news { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); border-radius: 1px; transform: rotate(45deg); } .lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); } .lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; } .lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; } @@ -389,16 +357,15 @@ box-shadow: 0 0 7px #64748b; } .lp-dot.conflicts { background: #ff2a6d; box-shadow: 0 0 7px #ff2a6d; } - .lp-count { font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; color: var(--cyan); } + .lp-count { font-family: 'Share Tech Mono', monospace; font-size: 0.7rem; color: var(--cyan); } .lp-sub { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; } - .lp-opacity { display: none; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } - .lp-layer:has(.lp-name input[type="checkbox"]:checked) .lp-opacity { display: flex; } + .lp-opacity { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } .lp-opacity input[type="range"] { flex: 1; accent-color: var(--cyan); height: 4px; cursor: pointer; } - .lp-opacity b { color: var(--text); font-family: 'IBM Plex Mono', monospace; font-weight: 400; min-width: 2.4em; text-align: right; } - .lp-select { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.22rem 0.35rem; font-size: 0.68rem; font-family: 'IBM Plex Mono', monospace; color-scheme: dark; } + .lp-opacity b { color: var(--text); font-family: 'Share Tech Mono', monospace; font-weight: 400; min-width: 2.4em; text-align: right; } + .lp-select { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.22rem 0.35rem; font-size: 0.68rem; font-family: 'Share Tech Mono', monospace; color-scheme: dark; } .lp-select:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .lp-legend { border-top: 1px solid var(--line); padding-top: 0.5rem; display: flex; flex-direction: column; gap: 0.35rem; } - .lp-legend h4 { font-size: 0.58rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin: 0; font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; } + .lp-legend h4 { font-size: 0.58rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin: 0; font-family: 'Rajdhani', sans-serif; font-weight: 600; } .lp-ramp { height: 8px; border-radius: 4px; background: linear-gradient(90deg, #2563eb, #38bdf8, #f59e0b, #ef4444, #fde047); box-shadow: 0 0 8px rgba(251,146,60,0.35) inset; } .lp-ramp-scale { display: flex; justify-content: space-between; font-size: 0.58rem; color: var(--muted); } .lp-heat-legend { display: flex; align-items: center; justify-content: space-between; font-size: 0.64rem; color: var(--muted); gap: 0.5rem; } @@ -407,34 +374,11 @@ .lp-future .lp-name { cursor: not-allowed; } .lp-error { color: var(--red); font-size: 0.66rem; } .lp-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } - .gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 9.5rem; overflow-y: auto; } - .gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.35rem; font-size: 0.64rem; flex-wrap: wrap; } - .gf-item.selected { outline: 1px solid var(--cyan); background: rgba(53,224,255,0.08); border-radius: 3px; } - .gf-item .gf-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); background: none; border: 0; font: inherit; cursor: pointer; text-align: left; flex: 1 1 6rem; min-width: 0; padding: 0.12rem 0; } - .gf-item .gf-name:hover { color: var(--cyan); } - .gf-item .gf-actions { display: flex; align-items: center; gap: 0.28rem; flex: 0 0 auto; } - .gf-item input.gf-active { accent-color: var(--cyan); cursor: pointer; width: 14px; height: 14px; } - .gf-del, .gf-go, .gf-ren { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'IBM Plex Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } - .gf-go, .gf-ren { border-color: var(--cyan); color: var(--cyan); } + .gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 8rem; overflow-y: auto; } + .gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; font-size: 0.64rem; } + .gf-item span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); } + .gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } .gf-del:hover { background: rgba(255,46,151,0.16); } - .gf-go:hover, .gf-ren:hover { background: rgba(53,224,255,0.14); } - .gf-draw-row { flex-wrap: wrap; gap: 0.35rem; } - #gf-finish, #gf-cancel { min-height: 32px; } - #gf-draw-bar { - position: absolute; left: 12px; bottom: 52px; z-index: 530; - display: flex; gap: 0.4rem; align-items: center; - background: rgba(6,11,20,0.86); border: 1px solid var(--line-hi); - border-radius: 4px; padding: 0.22rem 0.4rem; - } - #gf-draw-bar[hidden] { display: none !important; } - .gf-inbox { display: flex; flex-direction: column; gap: 0.18rem; max-height: 8rem; overflow-y: auto; margin-top: 0.28rem; } - .gf-hit { - cursor: pointer; font-size: 0.58rem; line-height: 1.35; color: var(--text); - padding: 0.22rem 0.28rem; border: 1px solid var(--line); border-radius: 3px; - font-family: 'IBM Plex Mono', monospace; - } - .gf-hit:hover, .gf-hit:focus { border-color: var(--cyan); outline: none; background: rgba(53,224,255,0.08); } - .gf-hit .gf-hit-meta { color: var(--muted); } /* ── Keyboard cheat sheet (centered; keep off LAYERS / zoom / dock) ── */ .cheat-sheet { @@ -452,7 +396,7 @@ } .cheat-sheet[hidden] { display: none !important; } .cheat-sheet h3 { - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.72rem; letter-spacing: 0.16em; + font-family: 'Orbitron', sans-serif; font-size: 0.72rem; letter-spacing: 0.16em; color: var(--cyan); margin: 0 0 0.65rem; text-transform: uppercase; } .cheat-sheet dl { display: grid; grid-template-columns: auto 1fr; gap: 0.35rem 0.85rem; margin: 0; } @@ -478,26 +422,26 @@ .pd-head { display: flex; justify-content: space-between; align-items: center; padding: 0.55rem 0.95rem 0.55rem 0.85rem; border-bottom: 1px solid var(--line); - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; font-weight: 700; + font-family: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 10px rgba(53,224,255,0.55); background: linear-gradient(180deg, rgba(53,224,255,0.07), transparent); } .pd-close { background: transparent; border: 1px solid var(--line); color: var(--muted); - font-family: 'IBM Plex Mono', monospace; font-size: 0.78rem; + font-family: 'Share Tech Mono', monospace; font-size: 0.78rem; width: 28px; height: 28px; border-radius: 4px; cursor: pointer; line-height: 1; flex-shrink: 0; margin-right: 2px; } .pd-close:hover { border-color: var(--cyan); color: var(--cyan); } .pd-body { padding: 0.55rem 0.75rem 0.7rem; overflow-y: auto; display: flex; flex-direction: column; gap: 0.55rem; min-height: 0; flex: 1; } - .pd-status { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); } + .pd-status { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } .pd-status.err { color: var(--red); } - .pd-coords { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--cyan); letter-spacing: 0.04em; } - .pd-name { font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; font-size: 0.92rem; color: var(--text); line-height: 1.25; } + .pd-coords { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--cyan); letter-spacing: 0.04em; } + .pd-name { font-family: 'Rajdhani', sans-serif; font-weight: 700; font-size: 0.92rem; color: var(--text); line-height: 1.25; } .pd-addr { font-size: 0.72rem; color: var(--muted); line-height: 1.4; } .pd-sec { - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.58rem; letter-spacing: 0.12em; + font-family: 'Orbitron', sans-serif; font-size: 0.58rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); margin-top: 0.15rem; } .pd-list { display: flex; flex-direction: column; gap: 0.18rem; } @@ -505,11 +449,11 @@ display: flex; justify-content: space-between; align-items: baseline; gap: 0.5rem; background: transparent; border: 0; border-left: 2px solid var(--line); color: var(--text); text-align: left; cursor: pointer; padding: 0.22rem 0.35rem; - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.78rem; font-weight: 600; + font-family: 'Rajdhani', sans-serif; font-size: 0.78rem; font-weight: 600; } .pd-item:hover, .pd-item:focus-visible { border-left-color: var(--cyan); color: var(--cyan); background: rgba(53,224,255,0.06); } - .pd-item .k { text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.58rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; flex-shrink: 0; } - .pd-item .d { font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; color: var(--cyan); white-space: nowrap; } + .pd-item .k { text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.58rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; flex-shrink: 0; } + .pd-item .d { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); white-space: nowrap; } .pd-empty { font-size: 0.72rem; color: var(--muted); font-style: italic; } .pd-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } @@ -520,7 +464,7 @@ .cam-pop .thumb.placeholder { display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 0.7rem; height: 80px; } .cam-pop table { width: 100%; font-size: 0.72rem; border-collapse: collapse; } .cam-pop td { padding: 0.12rem 0.2rem; vertical-align: top; } - .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'IBM Plex Mono', monospace; } + .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'Share Tech Mono', monospace; } .cam-pop a { color: var(--cyan); word-break: break-all; } .cam-pop .ps-photo { margin-top: 0.45rem; } .cam-pop .ps-photo a.ps-link { display: block; } @@ -533,7 +477,7 @@ .cam-pop .ps-credit a { color: var(--cyan); } .cam-pop .ps-loading { font-size: 0.68rem; color: var(--muted); margin-top: 0.35rem; } .role-badge { - display: inline-block; font-family: 'IBM Plex Mono', monospace; + display: inline-block; font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; font-weight: 700; letter-spacing: 0.12em; padding: 0.08rem 0.4rem; border-radius: 3px; margin-left: 0.4rem; vertical-align: middle; @@ -547,8 +491,8 @@ animation: emerg-pulse 1.4s ease-in-out infinite; } .blip-pop { min-width: 200px; max-width: 260px; } - .blip-pop .blip-src { font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } - .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; margin: 0.2rem 0 0.3rem; } + .blip-pop .blip-src { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } + .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.2rem 0 0.3rem; } .blip-pop .blip-desc { font-size: 0.72rem; color: var(--text); line-height: 1.35; margin-top: 0.15rem; } /* ── Sub-views (News / Events / Alerts / ... ) ── */ @@ -557,7 +501,7 @@ max-width: 1280px; margin: 0 auto; } .subview > h2 { - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.95rem; font-weight: 700; + font-family: 'Orbitron', sans-serif; font-size: 0.95rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--text); display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.35rem; } @@ -569,13 +513,13 @@ box-shadow: 0 0 18px rgba(53,224,255,0.05); } .panel h3 { - font-size: 0.68rem; font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; + font-size: 0.68rem; font-family: 'Orbitron', sans-serif; font-weight: 700; text-transform: uppercase; letter-spacing: 0.16em; color: var(--muted); margin-bottom: 0.6rem; } table { width: 100%; border-collapse: collapse; font-size: 0.86rem; } th, td { text-align: left; padding: 0.5rem 0.65rem; border-bottom: 1px solid var(--line); } - th { color: var(--muted); font-weight: 600; font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.1em; font-family: 'IBM Plex Sans', sans-serif; } + th { color: var(--muted); font-weight: 600; font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.1em; font-family: 'Rajdhani', sans-serif; } tr:hover td { background: rgba(53,224,255,0.04); } .badge { display: inline-block; padding: 0.12rem 0.5rem; border-radius: 3px; font-size: 0.7rem; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase; } .badge-positive { background: rgba(83,240,165,0.12); color: var(--green); border: 1px solid rgba(83,240,165,0.35); } @@ -588,7 +532,7 @@ /* ── Stats strip (Events view) ── */ .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0.8rem; margin-bottom: 1.1rem; } .stat-card { position: relative; overflow: hidden; } - .stat-card .value { font-family: 'IBM Plex Sans', sans-serif; font-size: 1.5rem; font-weight: 700; color: var(--text); letter-spacing: 0.04em; } + .stat-card .value { font-family: 'Orbitron', sans-serif; font-size: 1.5rem; font-weight: 700; color: var(--text); letter-spacing: 0.04em; } .stat-card .value.cyan { color: var(--cyan); text-shadow: 0 0 14px var(--cyan-glow); } .stat-card .value.red { color: var(--red); text-shadow: 0 0 14px rgba(255,93,93,0.4); } .stat-card::after { @@ -601,14 +545,14 @@ .search-box input { flex: 1; background: var(--bg-1); border: 1px solid var(--line); border-radius: 4px; padding: 0.55rem 0.9rem; color: var(--text); - font-size: 0.88rem; font-family: 'IBM Plex Sans', sans-serif; + font-size: 0.88rem; font-family: 'Rajdhani', sans-serif; } .search-box input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 10px var(--cyan-glow); } /* ── News view ── */ .news-head { display: flex; justify-content: space-between; align-items: flex-end; gap: 1rem; margin-bottom: 0.9rem; flex-wrap: wrap; } .news-refresh { display: flex; align-items: center; gap: 0.6rem; } - .news-updated { font-size: 0.7rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; } + .news-updated { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; } .news-summary { position: relative; background: linear-gradient(160deg, rgba(53,224,255,0.10), rgba(10,19,34,0.7) 45%); border: 1px solid rgba(53,224,255,0.35); border-radius: 8px; padding: 1rem 1.25rem 1.1rem; @@ -619,19 +563,19 @@ content: ''; position: absolute; inset: 0; pointer-events: none; background: radial-gradient(140px 70px at 85% -10%, rgba(53,224,255,0.18), transparent 70%); } - .ns-kicker { font-family: 'IBM Plex Sans', sans-serif; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 12px rgba(53,224,255,0.6); display: flex; align-items: center; gap: 0.5rem; } - .ns-badge { font-size: 0.58rem; font-weight: 700; background: rgba(53,224,255,0.14); border: 1px solid rgba(53,224,255,0.4); border-radius: 3px; padding: 0.1rem 0.45rem; color: var(--cyan); letter-spacing: 0.1em; font-family: 'IBM Plex Mono', monospace; } - .ns-time { font-size: 0.68rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; margin: 0.35rem 0 0.6rem; } + .ns-kicker { font-family: 'Orbitron', sans-serif; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 12px rgba(53,224,255,0.6); display: flex; align-items: center; gap: 0.5rem; } + .ns-badge { font-size: 0.58rem; font-weight: 700; background: rgba(53,224,255,0.14); border: 1px solid rgba(53,224,255,0.4); border-radius: 3px; padding: 0.1rem 0.45rem; color: var(--cyan); letter-spacing: 0.1em; font-family: 'Share Tech Mono', monospace; } + .ns-time { font-size: 0.68rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.35rem 0 0.6rem; } .ns-body { font-size: 0.9rem; line-height: 1.62; color: var(--text); white-space: pre-wrap; position: relative; z-index: 1; } - .ns-body h1, .ns-body h2, .ns-body h3, .ns-body h4 { font-size: 0.98rem; margin: 0.5rem 0 0.25rem; color: var(--cyan); font-family: 'IBM Plex Sans', sans-serif; } + .ns-body h1, .ns-body h2, .ns-body h3, .ns-body h4 { font-size: 0.98rem; margin: 0.5rem 0 0.25rem; color: var(--cyan); font-family: 'Rajdhani', sans-serif; } .ns-body ul, .ns-body ol { margin: 0.35rem 0 0.35rem 1.2rem; } .ns-body li { margin-bottom: 0.2rem; } - .ns-body code { background: rgba(3,6,9,0.6); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.3rem; font-size: 0.85em; font-family: 'IBM Plex Mono', monospace; } + .ns-body code { background: rgba(3,6,9,0.6); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.3rem; font-size: 0.85em; font-family: 'Share Tech Mono', monospace; } .ns-empty { color: var(--muted); font-size: 0.85rem; font-style: italic; } .ns-loading { color: var(--muted); font-size: 0.85rem; } .ns-error { color: var(--red); font-size: 0.85rem; } - .news-list-head { display: flex; justify-content: space-between; align-items: center; font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin-bottom: 0.4rem; } - .news-count { font-size: 0.66rem; color: var(--cyan); font-family: 'IBM Plex Mono', monospace; } + .news-list-head { display: flex; justify-content: space-between; align-items: center; font-family: 'Orbitron', sans-serif; font-size: 0.68rem; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin-bottom: 0.4rem; } + .news-count { font-size: 0.66rem; color: var(--cyan); font-family: 'Share Tech Mono', monospace; } .news-list { max-height: 52vh; min-height: 120px; overflow-y: auto; border: 1px solid var(--line); border-radius: 6px; background: rgba(6,11,20,0.4); } .news-list::-webkit-scrollbar { width: 8px; } .news-list::-webkit-scrollbar-track { background: rgba(14,26,46,0.4); border-radius: 8px; } @@ -640,10 +584,10 @@ .news-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.55rem 0.9rem; border-bottom: 1px solid rgba(20,50,74,0.5); text-decoration: none; color: var(--text); transition: background .15s, box-shadow .15s; } .news-item:last-child { border-bottom: none; } .news-item:hover { background: rgba(53,224,255,0.06); box-shadow: inset 2px 0 0 var(--cyan); } - .news-dom { font-size: 0.62rem; font-family: 'IBM Plex Mono', monospace; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.25); border-radius: 3px; padding: 0.1rem 0.45rem; white-space: nowrap; flex-shrink: 0; max-width: 30%; overflow: hidden; text-overflow: ellipsis; } + .news-dom { font-size: 0.62rem; font-family: 'Share Tech Mono', monospace; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.25); border-radius: 3px; padding: 0.1rem 0.45rem; white-space: nowrap; flex-shrink: 0; max-width: 30%; overflow: hidden; text-overflow: ellipsis; } .news-title { flex: 1; font-size: 0.86rem; line-height: 1.35; color: var(--text); word-break: break-word; } .news-item:hover .news-title { color: var(--cyan); } - .news-time { font-size: 0.68rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; white-space: nowrap; flex-shrink: 0; } + .news-time { font-size: 0.68rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; white-space: nowrap; flex-shrink: 0; } .news-geo { color: var(--green); font-size: 0.8rem; flex-shrink: 0; text-shadow: 0 0 8px rgba(83,240,165,0.6); } .news-loading, .news-error { padding: 1rem 0.9rem; color: var(--muted); font-size: 0.85rem; } .news-error { color: var(--red); } @@ -655,14 +599,14 @@ .key-card:hover { box-shadow: 0 0 22px rgba(53,224,255,0.12); } .key-card.set { border-color: rgba(83,240,165,0.45); box-shadow: 0 0 16px rgba(83,240,165,0.12); } .key-head { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; margin-bottom: 0.35rem; } - .key-name { font-family: 'IBM Plex Mono', monospace; font-size: 0.86rem; font-weight: 600; color: var(--cyan); word-break: break-all; } - .key-status { font-size: 0.68rem; font-family: 'IBM Plex Mono', monospace; padding: 0.18rem 0.55rem; border-radius: 3px; white-space: nowrap; } + .key-name { font-family: 'Share Tech Mono', monospace; font-size: 0.86rem; font-weight: 600; color: var(--cyan); word-break: break-all; } + .key-status { font-size: 0.68rem; font-family: 'Share Tech Mono', monospace; padding: 0.18rem 0.55rem; border-radius: 3px; white-space: nowrap; } .key-status.set { background: rgba(83,240,165,0.1); color: var(--green); box-shadow: 0 0 10px rgba(83,240,165,0.3); } .key-status.missing { background: rgba(255,93,93,0.1); color: var(--red); box-shadow: 0 0 10px rgba(255,93,93,0.2); } .key-desc { font-size: 0.8rem; color: var(--muted); margin-bottom: 0.7rem; overflow-wrap: anywhere; } - .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'IBM Plex Mono', monospace; } + .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'Share Tech Mono', monospace; } .key-form { display: flex; gap: 0.5rem; } - .key-form input { flex: 1; background: var(--bg-0); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; color: var(--text); font-size: 0.82rem; font-family: 'IBM Plex Mono', monospace; } + .key-form input { flex: 1; background: var(--bg-0); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; color: var(--text); font-size: 0.82rem; font-family: 'Share Tech Mono', monospace; } .key-form input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .key-form .btn { white-space: nowrap; } .key-form .btn-danger { border-color: rgba(255,93,93,0.5); color: var(--red); } @@ -678,17 +622,17 @@ .set-row textarea, .set-row input[type="text"], .set-row select { background: var(--bg-0); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; font-size: 0.85rem; - font-family: 'IBM Plex Mono', monospace; color-scheme: dark; + font-family: 'Share Tech Mono', monospace; color-scheme: dark; } .set-row textarea:focus, .set-row input:focus, .set-row select:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .set-note { font-size: 0.72rem; color: var(--muted); line-height: 1.5; } .set-note code { background: rgba(3,6,9,0.7); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.35rem; font-size: 0.82em; } .set-actions { display: flex; gap: 0.6rem; margin-top: 0.4rem; } - .set-saved { color: var(--green); font-size: 0.75rem; font-family: 'IBM Plex Mono', monospace; min-height: 1.1rem; } + .set-saved { color: var(--green); font-size: 0.75rem; font-family: 'Share Tech Mono', monospace; min-height: 1.1rem; } .sys-row { display: flex; justify-content: space-between; padding: 0.32rem 0; border-bottom: 1px dashed var(--line); font-size: 0.8rem; } .sys-row:last-child { border-bottom: none; } .sys-row .k { color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.68rem; } - .sys-row .v { font-family: 'IBM Plex Mono', monospace; } + .sys-row .v { font-family: 'Share Tech Mono', monospace; } /* ═══════════════ BOTTOM DOCK: tickers ═══════════════ */ .dock { @@ -705,22 +649,19 @@ .tick-label { display: flex; align-items: center; justify-content: center; gap: 0.4rem; min-width: 74px; padding: 0 0.7rem; flex-shrink: 0; - font-family: 'IBM Plex Sans', sans-serif; font-size: 0.62rem; font-weight: 700; + font-family: 'Orbitron', sans-serif; font-size: 0.62rem; font-weight: 700; letter-spacing: 0.2em; color: #02131c; background: var(--cyan); text-shadow: none; position: relative; clip-path: polygon(0 0, calc(100% - 8px) 0, 100% 100%, 0 100%); } - .ticker.news .tick-label { background: var(--cyan); color: #02131c; } - .ticker.market[hidden] { display: none !important; } - .dock.news-only { height: 32px; } - .dock.news-only .ticker { height: 100%; } + .ticker.news .tick-label { background: var(--magenta); color: #1c0311; } .tick-label .st { animation: pulse 1.6s infinite; } .tick-wrap { flex: 1; overflow: hidden; position: relative; display: flex; align-items: center; mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%); -webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%); } .tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; } - .ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */ + .ticker.news .tick-track { animation-duration: 90s; } .tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; } @keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } } .tick-group { display: flex; align-items: center; } @@ -729,20 +670,20 @@ font-size: 0.82rem; padding: 0 1rem; color: var(--text); text-decoration: none; font-weight: 500; } - .tick-item .sym { font-family: 'IBM Plex Mono', monospace; color: var(--cyan); font-size: 0.74rem; } - .tick-item .price { font-family: 'IBM Plex Mono', monospace; color: var(--text); } + .tick-item .sym { font-family: 'Share Tech Mono', monospace; color: var(--cyan); font-size: 0.74rem; } + .tick-item .price { font-family: 'Share Tech Mono', monospace; color: var(--text); } .tick-item .chg.up { color: var(--green); } .tick-item .chg.down { color: var(--red); } .tick-item .chg.flat { color: var(--muted); } - .tick-item .dom { font-family: 'IBM Plex Mono', monospace; font-size: 0.64rem; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.22); border-radius: 3px; padding: 0.05rem 0.4rem; } - .tick-item .tt { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); } + .tick-item .dom { font-family: 'Share Tech Mono', monospace; font-size: 0.64rem; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.22); border-radius: 3px; padding: 0.05rem 0.4rem; } + .tick-item .tt { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } .tick-item .sep { color: var(--line-hi); } button.tick-item { cursor: pointer; background: transparent; border: 0; font: inherit; color: inherit; } .tick-item.brief { cursor: pointer; background: linear-gradient(90deg, rgba(255,46,151,0.12), transparent 70%); border-left: 2px solid var(--magenta); font-weight: 600; } - .tick-item .b-tag { font-family: 'IBM Plex Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } + .tick-item .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } .tick-item .b-tag.critical { background: var(--red); } .tick-item .b-tag.high { background: var(--amber); } .tick-item .b-tag.medium { background: var(--cyan); color: #041018; } @@ -753,7 +694,7 @@ .tick-sep { color: var(--line-hi); } .tick-tag { display: flex; align-items: center; flex-shrink: 0; padding: 0 0.8rem; - font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; + font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); border-left: 1px solid var(--line); } @@ -769,16 +710,16 @@ } .boot.gone { opacity: 0; pointer-events: none; } .boot-inner { text-align: center; } - .boot-mark { font-family: 'IBM Plex Sans', sans-serif; font-size: 2.2rem; color: var(--cyan); text-shadow: 0 0 24px var(--cyan-glow); margin-bottom: 0.6rem; } - .boot-title { font-family: 'IBM Plex Sans', sans-serif; font-size: 1.3rem; font-weight: 900; letter-spacing: 0.3em; color: #eafcff; } + .boot-mark { font-family: 'Orbitron', sans-serif; font-size: 2.2rem; color: var(--cyan); text-shadow: 0 0 24px var(--cyan-glow); margin-bottom: 0.6rem; } + .boot-title { font-family: 'Orbitron', sans-serif; font-size: 1.3rem; font-weight: 900; letter-spacing: 0.3em; color: #eafcff; } .boot-title span { color: var(--cyan); } - .boot-sub { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); letter-spacing: 0.3em; margin-top: 0.5rem; } + .boot-sub { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); letter-spacing: 0.3em; margin-top: 0.5rem; } .boot-bar { width: 220px; height: 3px; margin: 1.1rem auto 0; background: var(--bg-2); border-radius: 2px; overflow: hidden; } .boot-bar i { display: block; height: 100%; width: 40%; background: linear-gradient(90deg, transparent, var(--cyan), transparent); animation: bootSweep 0.9s linear infinite; } @keyframes bootSweep { from { transform: translateX(-100%); } to { transform: translateX(350%); } } @media (max-width: 820px) { - :root { --topbar-h: 42px; --dock-h: 32px; } + :root { --topbar-h: 42px; --dock-h: 56px; } .tick-label { min-width: 56px; padding: 0 0.5rem; } .tick-tag { display: none; } .hud-chips { display: none; } @@ -846,13 +787,6 @@ min-width: 0; min-height: 32px; } - #gf-draw-bar { - left: 8px; - bottom: 56px; - } - #gf-finish, #gf-cancel, #gf-draw-bar .btn, .gf-go, .gf-del, .gf-ren { - min-height: 32px; - } .leaflet-control-attribution { display: none !important; } .leaflet-top.leaflet-right .leaflet-control-zoom { margin-top: 8px; @@ -892,7 +826,8 @@
◢◤
-
OSINT//
+
OSINT//DASHBOARD
+
GLOBAL SITUATIONAL AWARENESS TERMINAL
@@ -906,7 +841,6 @@
- SIGN IN @@ -942,7 +876,7 @@ Strait - +
@@ -951,8 +885,8 @@
- -
-
- - - -
-
-
-
- + off
+
Sun terminator overlay. Default off. No API.
@@ -1006,14 +932,14 @@
- + 0
Opacity 100%
- + 0
@@ -1027,30 +953,27 @@
+
Geolocated events from the ingest pipeline. Color = source type.
- + 0
-
-
-
- - 0 -
+
LLM-estimated locations from the 15-min brief. Pins only for critical/high.
- + IEM
Opacity 70%
+
IEM NEXRAD over CONUS, RainViewer elsewhere. Tiles load in the browser.
- + 0
@@ -1062,14 +985,15 @@
- + 7d
Opacity 80%
+
Cloud-penetrating C-band. Last 7 days, viewport bbox. Tiles from same-origin TiTiler — not fetched on load.
- + 0
@@ -1081,37 +1005,48 @@
- + 0
+
Magenta = military · orange = firefighting · red = emergency (7700/7600/7500) · else altitude. Click a plane for type / squawk / operator.
- + 0
+
Amtraker · ODC-By
- + 0
+
Two feeds: AISStream (US live) and VesselAPI (Hormuz, 5×/day). Paste both keys on the Keys page. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
- + +
+
+
Click vertices, double-click to close. Delete a saved fence from the list or its popup.
+
+
+
+ 0
- + 0
+
Curated theatres · color by severity · news counts, not LiveUAMap.
@@ -1144,7 +1079,6 @@
CAMS —
BLIPS —
NEWS —
-
ARTICLES —
live
-
@@ -1277,7 +1207,7 @@ -
+

⇪ Data Ingestion

Manually trigger feed pulls & NATS processing

@@ -1310,7 +1240,7 @@
-
+

⚿ API Keys

Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.

@@ -1337,7 +1267,7 @@
-
+

News Summarizer

Takes effect on the next 15-min run. No container restart.

@@ -1388,8 +1318,8 @@
- - + +
@@ -1420,8 +1350,8 @@ -