diff --git a/.env.example b/.env.example index d64b31b..b23921c 100644 --- a/.env.example +++ b/.env.example @@ -31,20 +31,6 @@ NOMINATIM_URL=https://nominatim.openstreetmap.org NOMINATIM_MIN_INTERVAL=1.1 SNAPSHOT_TTL_SECONDS=300 -# ── masscan active camera discovery (host-level systemd service, NOT compose) ─ -# Continuous rolling sweep for open RTSP port 554 across a range. Runs on the -# Pi host via deploy/osint-masscan.service (needs root + raw sockets). Results -# land in the same `cameras` table as the scraper (discovery_source=masscan). -# NOTE: 200 pps is the residential-safe default. 1k/10k pps saturated a home -# uplink. A full 0.0.0.0/0 sweep at 200 pps takes ~8 months (rolling). -MASSCAN_RANGE=0.0.0.0/0 -MASSCAN_PORTS=554 -MASSCAN_RATE=200 -MASSCAN_RETRIES=1 -MASSCAN_WAIT=0 -MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt -MASSCAN_FLUSH_EVERY=250 - # ── NASA FIRMS (active fire / hotspot ingest) ────────────────────────────── # MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/ # (1-minute signup, no payment). Leave blank to keep fire ingest idle. @@ -83,6 +69,21 @@ 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). @@ -97,6 +98,25 @@ 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 6116fdf..b51b488 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -1,17 +1,28 @@ -# Build all OSINT images, publish to the Forgejo container registry, then -# redeploy on the Pi runner (docker.sock mounted). +# 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. +# +# 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. # -# 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 -# forgejo.siriusdevops.com/sirius/osint-dashboard-pg -# forgejo.siriusdevops.com/sirius/osint-news-scraper -# forgejo.siriusdevops.com/sirius/osint-news-summarizer +# 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- # # 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 @@ -19,23 +30,92 @@ on: push: branches: [main, master] workflow_dispatch: + inputs: + rebuild_pg: + description: Rebuild Timescale+PostGIS (Dockerfile.pg) + type: boolean + default: false + rebuild_all: + description: Rebuild every app image (ignore path filter) + type: boolean + default: false env: PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }} - PUSH_REGISTRY: 127.0.0.1:3000 + PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000 OWNER: sirius - # Keep compose project/volumes stable on the Pi - COMPOSE_PROJECT_NAME: osint-dashboard jobs: - build-push-deploy: - runs-on: docker - permissions: - contents: read - packages: write + 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 steps: - name: Checkout uses: https://code.forgejo.org/actions/checkout@v4 + with: + fetch-depth: 50 + + - name: Plan image builds + id: plan + run: | + set -euo pipefail + APP=0 + SCRAPER=0 + SUM=0 + PG=0 + + mark() { + case "$1" in + Dockerfile.pg) + PG=1 ;; + Dockerfile|app/*|alembic/*|alembic.ini) + APP=1 ;; + news/scraper/*) + SCRAPER=1 ;; + news/summerizer/*) + SUM=1 ;; + esac + } + + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + APP=1; SCRAPER=1; SUM=1 + if [ "${{ github.event.inputs.rebuild_all }}" = "true" ]; then + APP=1; SCRAPER=1; SUM=1; PG=1 + fi + if [ "${{ github.event.inputs.rebuild_pg }}" = "true" ]; then + PG=1 + fi + else + BEFORE="${{ github.event.before }}" + SHA="${GITHUB_SHA}" + ZEROS="0000000000000000000000000000000000000000" + if [ -z "$BEFORE" ] || [ "$BEFORE" = "$ZEROS" ]; then + echo "No previous SHA — build app images, skip pg" + APP=1; SCRAPER=1; SUM=1 + elif ! git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then + echo "Previous SHA $BEFORE not in history — build app images, skip pg" + APP=1; SCRAPER=1; SUM=1 + else + while IFS= read -r f; do + [ -z "$f" ] && continue + mark "$f" + done < <(git diff --name-only "$BEFORE" "$SHA") + fi + fi + + { + echo "app=$APP" + echo "scraper=$SCRAPER" + echo "summarizer=$SUM" + echo "pg=$PG" + } >> "$GITHUB_OUTPUT" + echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG" - name: Image refs id: img @@ -45,10 +125,11 @@ jobs: PUB="${PUBLIC_REGISTRY}" OWN="${OWNER}" SHA="${GITHUB_SHA::12}" + TAG="amd64-${SHA}" { echo "reg=$PUSH" echo "pub=$PUB" - echo "sha=$SHA" + echo "tag=$TAG" echo "app=$PUSH/$OWN/osint-dashboard" echo "pg=$PUSH/$OWN/osint-dashboard-pg" echo "scraper=$PUSH/$OWN/osint-news-scraper" @@ -56,109 +137,93 @@ jobs: } >> "$GITHUB_OUTPUT" echo "Push registry: $PUSH" echo "Public pull: $PUB" - echo "SHA tag: $SHA" + echo "Image tag: $TAG" - 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 with write:package. - if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then - echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)" + # 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)" exit 1 fi - echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \ + echo "${{ secrets.REGISTRY_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 - 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}" + IMG="${{ steps.img.outputs.app }}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f Dockerfile -t "${IMG}:${TAG}" . + docker push "${IMG}:${TAG}" - name: Build news-scraper image + if: steps.plan.outputs.scraper == '1' run: | set -ex IMG="${{ steps.img.outputs.scraper }}" - 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}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper + docker push "${IMG}:${TAG}" - name: Build news-summarizer image + if: steps.plan.outputs.summarizer == '1' run: | set -ex IMG="${{ steps.img.outputs.summarizer }}" - 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}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer + docker push "${IMG}:${TAG}" - name: Build / refresh Timescale+PostGIS image + if: steps.plan.outputs.pg == '1' run: | set -ex - PG="${{ steps.img.outputs.pg }}" - SHA="${{ steps.img.outputs.sha }}" - # Prefer rebuild so registry always has a current pg image. If packagecloud - # is unreachable, fall back to whatever local image already exists. - 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; retagging existing local pg image into registry" - docker tag "localhost/osint-dashboard-pg:latest" "${PG}:latest" - docker tag "localhost/osint-dashboard-pg:latest" "${PG}:${SHA}" - docker push "${PG}:latest" - docker push "${PG}:${SHA}" - 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}" - # Pull from Forgejo registry into local tags compose expects, then up. - # Compose file still uses localhost/* for stable local names; we mirror - # registry tags so a cold host can recover via docker pull. - REG="${{ steps.img.outputs.reg }}" - PUB="${{ steps.img.outputs.pub }}" - OWN="${{ env.OWNER }}" - for name in osint-dashboard osint-dashboard-pg osint-news-scraper osint-news-summarizer; do - docker pull "${REG}/${OWN}/${name}:latest" || true - docker tag "${REG}/${OWN}/${name}:latest" "localhost/${name}:latest" || true - docker tag "${REG}/${OWN}/${name}:latest" "${PUB}/${OWN}/${name}:latest" || true - done - # Do NOT set COMPOSE_PROJECT_NAME differently — volumes must stay - # osint-dashboard_osint-pgdata (pinned by `name:` in compose). - docker compose build --no-cache app ingester camera-service news-scraper news-summarizer || \ - docker compose build app ingester camera-service news-scraper news-summarizer - # Name-pinned containers (container_name: osint-dashboard, …) collide - # when compose tries to create instead of recreate — e.g. leftover from - # a different working_dir or a half-failed previous up. down + rm -f - # the known names, then up the full ingest profile. - chmod +x scripts/compose-reup.sh - COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ - scripts/compose-reup.sh - docker image prune -f - echo "osint-dashboard deployed; images also on ${PUB}/${OWN}/" + IMG="${{ steps.img.outputs.pg }}" + TAG="${{ steps.img.outputs.tag }}" + docker build -f Dockerfile.pg -t "${IMG}:${TAG}" . + docker push "${IMG}:${TAG}" - name: Summary if: always() run: | + TAG="${{ steps.img.outputs.tag }}" + PUB="${{ steps.img.outputs.pub }}" { - echo "## Forgejo registry images" - echo "Pushed via ${{ steps.img.outputs.reg }} (loopback). Pull publicly:" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard-pg:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-scraper:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-summarizer:latest\`" + echo "## Image plan" + echo "- app: \`${{ steps.plan.outputs.app }}\`" + echo "- news-scraper: \`${{ steps.plan.outputs.scraper }}\`" + 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)." } >> "$GITHUB_STEP_SUMMARY" diff --git a/alembic/versions/009_vessels.py b/alembic/versions/009_vessels.py new file mode 100644 index 0000000..8f0dd01 --- /dev/null +++ b/alembic/versions/009_vessels.py @@ -0,0 +1,41 @@ +"""vessels — daily VesselAPI snapshots for DVR as-of + +Revision ID: 009_vessels +Revises: 008_summary_kind +Create Date: 2026-08-29 +""" + +from alembic import op + +revision = "009_vessels" +down_revision = "008_summary_kind" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + CREATE TABLE IF NOT EXISTS vessels ( + mmsi TEXT NOT NULL, + poll_at TIMESTAMPTZ NOT NULL, + lat DOUBLE PRECISION NOT NULL, + lon DOUBLE PRECISION NOT NULL, + heading DOUBLE PRECISION, + speed DOUBLE PRECISION, + label TEXT, + extra JSONB, + PRIMARY KEY (mmsi, poll_at) + ) + """ + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)" + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)" + ) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS vessels") diff --git a/alembic/versions/010_bbox_gist.py b/alembic/versions/010_bbox_gist.py new file mode 100644 index 0000000..a7feab3 --- /dev/null +++ b/alembic/versions/010_bbox_gist.py @@ -0,0 +1,29 @@ +"""GIST bbox indexes for events/fires map-pan queries. + +Revision ID: 010_bbox_gist +Revises: 009_vessels +Create Date: 2026-09-01 +""" + +from alembic import op + +revision = "010_bbox_gist" +down_revision = "009_vessels" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "CREATE INDEX IF NOT EXISTS ix_events_geom_gist ON events " + "USING gist (ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326))" + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_fires_geom_gist ON fires " + "USING gist (ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_fires_geom_gist") + op.execute("DROP INDEX IF EXISTS ix_events_geom_gist") diff --git a/alembic/versions/011_geofence_alerts_fence.py b/alembic/versions/011_geofence_alerts_fence.py new file mode 100644 index 0000000..4b29f74 --- /dev/null +++ b/alembic/versions/011_geofence_alerts_fence.py @@ -0,0 +1,24 @@ +"""geofence_alerts (geofence_id, created_at DESC) for fence-scoped hit log + +Revision ID: 011_geofence_alerts_fence +Revises: 010_bbox_gist +Create Date: 2026-09-01 +""" + +from alembic import op + +revision = "011_geofence_alerts_fence" +down_revision = "010_bbox_gist" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "CREATE INDEX IF NOT EXISTS ix_geofence_alerts_fence_created " + "ON geofence_alerts (geofence_id, created_at DESC)" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_geofence_alerts_fence_created") diff --git a/alembic/versions/012_article_scores.py b/alembic/versions/012_article_scores.py new file mode 100644 index 0000000..853ded7 --- /dev/null +++ b/alembic/versions/012_article_scores.py @@ -0,0 +1,39 @@ +"""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 new file mode 100644 index 0000000..2fcfb8b --- /dev/null +++ b/alembic/versions/013_article_scores_duplicate_of.py @@ -0,0 +1,23 @@ +"""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 new file mode 100644 index 0000000..49ba951 --- /dev/null +++ b/alembic/versions/014_article_scores_geo.py @@ -0,0 +1,40 @@ +"""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 new file mode 100644 index 0000000..a9ac75e --- /dev/null +++ b/app/auth.py @@ -0,0 +1,589 @@ +"""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/bg_jobs.py b/app/bg_jobs.py index 8d14747..3a38173 100644 --- a/app/bg_jobs.py +++ b/app/bg_jobs.py @@ -1,50 +1,19 @@ -"""Background masscan / ffmpeg — never block a FastAPI request on a scan. +"""Background ffmpeg — never block a FastAPI request on a frame grab. -masscan is capped at 200 pps (home uplink saturates at 1k+). ffmpeg frame -grabs are scheduled with asyncio.create_task and shared per URL. +ffmpeg frame grabs are scheduled with asyncio.create_task and shared per URL. """ from __future__ import annotations import asyncio -import logging import shutil from cachetools import TTLCache -logger = logging.getLogger("osint.bg_jobs") - -MASSCAN_PPS_CAP = 200 - -_masscan_task: asyncio.Task | None = None _ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300) _ffmpeg_tasks: dict[str, asyncio.Task] = {} _FFMPEG = shutil.which("ffmpeg") -def schedule_masscan_pass() -> bool: - """Kick one capped masscan pass. Returns False if a pass is already running.""" - global _masscan_task - if _masscan_task is not None and not _masscan_task.done(): - return False - _masscan_task = asyncio.create_task(_run_masscan_capped()) - return True - - -async def _run_masscan_capped() -> None: - import masscan_config as cfg - from run_masscan_service import _verify_excludefile, run_pass - - orig = cfg.MASSCAN_RATE - if orig > MASSCAN_PPS_CAP: - logger.warning("capping masscan rate %s pps -> %s", orig, MASSCAN_PPS_CAP) - cfg.MASSCAN_RATE = MASSCAN_PPS_CAP - try: - _verify_excludefile() - await run_pass() - finally: - cfg.MASSCAN_RATE = orig - - def cached_ffmpeg_jpeg(url: str) -> bytes | None: return _ffmpeg_cache.get(url) diff --git a/app/camera_config.py b/app/camera_config.py index fd12ab6..7376087 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -16,6 +16,8 @@ CALTRANS_CCTV_URLS = tuple( f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json" for n in range(1, 13) ) +# MDOT MiDrive official DOT CCTV list (fields carry rendered HTML). +MDOT_CAMERA_URL = "https://mdotjboss.state.mi.us/MiDrive/camera/list" _DEFAULT_SOURCE_URL = ",".join(( # Publicly published open-camera list (markdown bullets of stream URLs). "https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md", @@ -25,6 +27,10 @@ _DEFAULT_SOURCE_URL = ",".join(( "https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson", # Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12). *CALTRANS_CCTV_URLS, + # Oregon DOT TripCheck public CCTV JPEG inventory (Esri JSON). + "https://www.tripcheck.com/Scripts/map/data/cctvinventory.js", + # Official MDOT MiDrive CCTV (JPEG stills, Michigan). + MDOT_CAMERA_URL, )) CAMERA_SOURCE_URLS = [ u.strip() @@ -53,5 +59,18 @@ 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")) -# NATS subject cameras are published on (consumed by the shared ingester). +# 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. CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") + + +# ── UDOT IBI 511 traffic cameras ────────────────────────────────────────── +# DataTables endpoint (POST form-encoded; server caps at 100 rows/page no +# matter what `length` is sent). No API key. Snapshot stills live at a stable +# /map/Cctv/{id} URL — same URL always serves the latest frame, so we store +# the URL and never scrape every frame ourselves. +UDOT_IBI_URL = "https://prod-ut.ibi511.com/List/GetData/Cameras" +UDOT_IBI_BASE = "https://prod-ut.ibi511.com" +UDOT_IBI_PAGE_SIZE = 100 +# Safety cap on pages per cycle so a runaway recordsTotal cannot fan out. +UDOT_IBI_MAX_PAGES = int(os.getenv("UDOT_IBI_MAX_PAGES", "40")) diff --git a/app/camera_preview.py b/app/camera_preview.py index 2c89e77..e6f924c 100644 --- a/app/camera_preview.py +++ b/app/camera_preview.py @@ -1,7 +1,7 @@ """Resolve a browser-renderable preview for a camera. HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can -stream. masscan finds are stored as `rtsp://IP/` with no snapshot_url, so +stream. Some scraper sources store `rtsp://` URLs with no snapshot_url, so the map popup used to skip the entirely and the leftover source link handed the browser an rtsp:// URL (which opens VLC). @@ -42,16 +42,6 @@ _HTTP_PATHS = ( "/tmpfs/auto.jpg", ) -# Browser-playable MJPEG paths the /stream proxy can pass through. -_MJPEG_PATHS = ( - "/mjpg/video.mjpg", - "/video.mjpg", - "/cgi-bin/mjpg/video.cgi", - "/axis-cgi/mjpg/video.cgi", - "/nphMotionJpeg", - "/mjpeg.cgi", -) - _FFMPEG = shutil.which("ffmpeg") @@ -87,55 +77,6 @@ async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None: return None -async def _http_feed_url(url: str, timeout: float = 2.5) -> str | None: - """Return url if it looks like an unauthenticated image/MJPEG feed.""" - try: - async with httpx.AsyncClient( - timeout=timeout, follow_redirects=True, - headers={"User-Agent": USER_AGENT}, - ) as c: - async with c.stream("GET", url) as r: - if r.status_code != 200: - return None - ctype = (r.headers.get("content-type") or "").lower() - if "html" in ctype or ctype.startswith("text/"): - return None - if any(x in ctype for x in ("image/", "multipart", "mjpeg", "octet-stream")): - # Read a little to reject empty/error bodies. - chunk = b"" - async for b in r.aiter_bytes(): - chunk += b - if len(chunk) >= 64: - break - if len(chunk) < 64: - return None - if b"html" in chunk[:64].lower(): - return None - return url - except Exception: # noqa: BLE001 - return None - return None - - -async def probe_public_feed(host: str) -> str | None: - """Unauthenticated HTTP still or MJPEG URL for this host, or None. - - Used at masscan ingest time so dead RTSP-only hosts never hit the map. - No credentials, no RTSP path-walking (too slow / rarely public). - """ - urls = [f"http://{host}{p}" for p in _HTTP_PATHS] - urls.append(f"http://{host}:8080/shot.jpg") - urls.extend(f"http://{host}{p}" for p in _MJPEG_PATHS) - results = await asyncio.gather( - *(_http_feed_url(u) for u in urls), - return_exceptions=True, - ) - for url, hit in zip(urls, results): - if isinstance(hit, str) and hit: - return hit - return None - - async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None: """Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails. diff --git a/app/camera_scraper.py b/app/camera_scraper.py index ad5dc91..d1ca366 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. Publish each camera to NATS (`events.camera`) for the shared ingester, - and upsert into the `cameras` table keyed by sha256(url_hash). + 4. Upsert into the `cameras` table keyed by sha256(url_hash). + Discovery is not published as an event. Snapshots are cached locally with a TTL; nothing is fetched more often than the cache allows. @@ -25,6 +25,7 @@ import hashlib import ipaddress import json import logging +import math import re import time from datetime import datetime, timezone @@ -37,6 +38,7 @@ from camera_config import ( CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE, NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT, SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT, + UDOT_IBI_URL, UDOT_IBI_BASE, UDOT_IBI_PAGE_SIZE, UDOT_IBI_MAX_PAGES, ) from camera_models import cameras from database import async_session @@ -114,6 +116,15 @@ class RateLimitedClient: self._last[host] = time.monotonic() return await self.client.get(url, **kw) + async def post(self, url: str, **kw) -> httpx.Response: + host = urlparse(url).netloc + now = time.monotonic() + wait = self._last.get(host, 0.0) + self._delay - now + if wait > 0: + await asyncio.sleep(wait) + self._last[host] = time.monotonic() + return await self.client.post(url, **kw) + async def aclose(self): await self.client.aclose() @@ -379,6 +390,201 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]: return out +# ── UDOT IBI 511 ────────────────────────────────────────────────────────── +# Utah bbox (lat 36.9–42.1, lon -114.2–-108.9). WKT is `POINT (lng lat)`. +_UDOT_IBI_MIN_LAT, _UDOT_IBI_MAX_LAT = 36.9, 42.1 +_UDOT_IBI_MIN_LON, _UDOT_IBI_MAX_LON = -114.2, -108.9 +_UDOT_WKT_POINT_RE = re.compile( + r"POINT\s*\(\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\)", re.I, +) + + +def parse_udot_ibi_page(text: str, source_name: str = "udot") -> list[dict]: + """Parse one UDOT IBI 511 DataTables camera page (`{"data": [...]}`). + + Skips rows whose first image is `blocked` or `disabled`, and drops any + point outside the Utah bbox. The `/map/Cctv/{id}` URL is a stable identity + (always serves the latest frame), so it is stored as both source_url and + snapshot_url — we never scrape frames ourselves. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + rows = payload.get("data") if isinstance(payload, dict) else None + if not isinstance(rows, list): + return [] + out: list[dict] = [] + for row in rows: + if not isinstance(row, dict): + continue + cam_id = row.get("id") + images = row.get("images") or [] + if cam_id is None or not images: + continue + img = images[0] or {} + if img.get("blocked") or img.get("disabled"): + continue + lon = lat = None + try: + wkt = (row.get("latLng") or {}).get("geography") or {} + wkt = wkt.get("wellKnownText") or "" + m = _UDOT_WKT_POINT_RE.match(str(wkt).strip()) + if m: + lon, lat = float(m.group(1)), float(m.group(2)) + except (AttributeError, TypeError, ValueError): + lon = lat = None + if lat is None or lon is None: + continue + if not (_UDOT_IBI_MIN_LAT <= lat <= _UDOT_IBI_MAX_LAT + and _UDOT_IBI_MIN_LON <= lon <= _UDOT_IBI_MAX_LON): + continue + snap = f"{UDOT_IBI_BASE}/map/Cctv/{cam_id}" + roadway, direction, location = ( + row.get("roadway"), row.get("direction"), row.get("location"), + ) + name = ", ".join( + str(b) for b in (roadway, direction, location) + if b and str(b).strip() and str(b).strip().lower() != "unknown" + ) or None + out.append({ + "source_url": snap, + "snapshot_url": snap, + "discovery_source": source_name, + "location_lat": lat, + "location_lon": lon, + "location_name": name, + "vendor": "UDOT", + "device_type": "http", + "raw": { + "udot_id": cam_id, + "agency": row.get("source"), + "source_id": row.get("sourceId"), + "roadway": roadway, + "direction": direction, + }, + }) + return out + + +# Oregon DOT TripCheck inventory bounding box (approx state extent). +ODOT_BBOX = (41.9, 46.3, -124.6, -116.4) # lat_min, lat_max, lon_min, lon_max + + +def parse_odot_json(text: str, source_name: str) -> list[dict]: + """Parse Oregon DOT TripCheck cctvinventory Esri-style JSON. + + Store the JPEG still as snapshot_url (map thumbs); never RTSP. Keep only + rows with finite coordinates inside Oregon and a usable filename. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + lat_min, lat_max, lon_min, lon_max = ODOT_BBOX + out: list[dict] = [] + for feat in payload.get("features") or []: + attrs = (feat or {}).get("attributes") or {} + filename = (attrs.get("filename") or "").strip() + if not filename: + continue + try: + lat = float(attrs.get("latitude")) + lon = float(attrs.get("longitude")) + except (TypeError, ValueError): + continue + if not (math.isfinite(lat) and math.isfinite(lon)): + continue + if not (lat_min <= lat <= lat_max and lon_min <= lon <= lon_max): + continue + jpeg = f"https://tripcheck.com/RoadCams/cams/{filename}" + title = (attrs.get("title") or "").strip() + out.append({ + "source_url": jpeg, + "snapshot_url": jpeg, + "discovery_source": "odot", + "location_lat": lat, + "location_lon": lon, + "location_name": title or None, + "vendor": "ODOT", + "device_type": "http", + }) + return out + + +# MDOT MiDrive field extractors (fields carry rendered HTML). +_MDOT_LAT_RE = re.compile(r"lat=(-?\d+(?:\.\d+)?)", re.I) +_MDOT_LON_RE = re.compile(r"lon=(-?\d+(?:\.\d+)?)", re.I) +_MDOT_ID_RE = re.compile(r"[?&]id=(\d+)", re.I) +_MDOT_IMG_RE = re.compile(r']+src=["\']([^"\']+)["\']', re.I) + +# Michigan bbox (docs/osiris-ideas.md §3.2): lat 41.6–48.3, lon -90.5–-82.1. +MDOT_LAT_RANGE = (41.6, 48.3) +MDOT_LON_RANGE = (-90.5, -82.1) + + +def parse_mdot_json(text: str, source_name: str) -> list[dict]: + """Parse MDOT MiDrive `camera/list` JSON (fields carry rendered HTML). + + Coordinates and the stable id live in the `county` field's map link + (`/MiDrive/map?...lat=&lon=&id=`); the `image` field carries an `` + whose src is the JPEG still. Out-of-bbox and coord-less rows are dropped. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + if not isinstance(payload, list): + return [] + out: list[dict] = [] + for row in payload: + if not isinstance(row, dict): + continue + county_html = row.get("county") or "" + m_lat = _MDOT_LAT_RE.search(county_html) + m_lon = _MDOT_LON_RE.search(county_html) + m_id = _MDOT_ID_RE.search(county_html) + if not (m_lat and m_lon and m_id): + continue # missing coordinates / stable id → drop + try: + lat = float(m_lat.group(1)) + lon = float(m_lon.group(1)) + except ValueError: + continue + if not (MDOT_LAT_RANGE[0] <= lat <= MDOT_LAT_RANGE[1] + and MDOT_LON_RANGE[0] <= lon <= MDOT_LON_RANGE[1]): + continue # out of Michigan bbox → drop + img_m = _MDOT_IMG_RE.search(row.get("image") or "") + if not img_m: + continue + snap = img_m.group(1).strip() + low = snap.lower() + if not (low.startswith("http://") or low.startswith("https://")): + continue + if low.startswith("rtsp"): + continue + cam_id = m_id.group(1) + route = (row.get("route") or "").strip() + loc = (row.get("location") or "").strip().lstrip("@").strip() + county_name = county_html.split(" list[dict]: """Parse willytop8/Live-Environment-Streams GeoJSON. @@ -490,6 +696,10 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder, body = resp.text if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url: cams = parse_caltrans_json(body, name) + elif "cctvinventory" in src_url or "tripcheck.com" in src_url: + cams = parse_odot_json(body, name) + elif "mdotjboss.state.mi.us" in src_url or "/MiDrive/camera/list" in src_url: + cams = parse_mdot_json(body, name) elif ("getCameraDataByLoc" in src_url or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])): cams = parse_alertwest_json(body, name) @@ -549,6 +759,54 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder, return out +# ── UDOT IBI 511 paginated fetcher ──────────────────────────────────────── + +async def scrape_udot_ibi(client: RateLimitedClient) -> list[dict]: + """Page through the UDOT IBI 511 DataTables endpoint and normalize. + + POSTs `start`/`length` form fields (server caps at 100 rows/page), walking + pages until `recordsTotal` is exhausted or UDOT_IBI_MAX_PAGES is hit. + """ + out: list[dict] = [] + seen: set[str] = set() + start = 0 + for _ in range(UDOT_IBI_MAX_PAGES): + try: + resp = await client.post( + UDOT_IBI_URL, + data={ + "start": str(start), + "length": str(UDOT_IBI_PAGE_SIZE), + "lang": "en-US", + }, + headers={"X-Requested-With": "XMLHttpRequest"}, + ) + resp.raise_for_status() + body = resp.text + except Exception: # noqa: BLE001 + logger.exception("failed to fetch UDOT IBI page start=%d", start) + break + try: + payload = json.loads(body) + except ValueError: + logger.warning("UDOT IBI non-JSON response at start=%d", start) + break + total = int(payload.get("recordsTotal") or 0) + rows = payload.get("data") or [] + if not isinstance(rows, list) or not rows: + break + for cam in parse_udot_ibi_page(body, "udot"): + if cam["source_url"] in seen: + continue + seen.add(cam["source_url"]) + out.append(cam) + if start + len(rows) >= total: + break + start += len(rows) + logger.info("UDOT IBI yielded %d cameras", len(out)) + return out + + # ── Persistence ──────────────────────────────────────────────────────────── async def upsert_cameras(cams: list[dict]) -> int: @@ -600,6 +858,7 @@ async def run_cycle() -> int: try: results = await asyncio.gather( *(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS), + scrape_udot_ibi(client), return_exceptions=True, ) all_cams: list[dict] = [] diff --git a/app/chokepoints.py b/app/chokepoints.py new file mode 100644 index 0000000..fdd98db --- /dev/null +++ b/app/chokepoints.py @@ -0,0 +1,62 @@ +"""Static chokepoint preset catalog — one-tap fly-to targets for the map. + +Pure data, no upstream calls and no VesselAPI quota spend. ``vesselapi`` is +``True`` only for Hormuz (the single box the VesselAPI poller already covers); +every other strait is AISStream-only until a human later spends quota. Never +call VesselAPI from here. + +Bounding boxes are ``minlat,minlon,maxlat,maxlon`` (VesselAPI order) and each +stays within the ``|dLat|+|dLon| <= 4`` span rule enforced by +``vesselapi.validate_bbox_span``. +""" + +from __future__ import annotations + +# id → preset. ``center`` is ``[lat, lon]`` for Leaflet ``setView``. +_CHOKEPOINTS: tuple[dict, ...] = ( + { + "id": "hormuz", + "title": "Strait of Hormuz", + "bbox": "25.5,55.4,27.3,57.2", + "center": [26.4, 56.5], + "zoom": 9, + "vesselapi": True, + }, + { + "id": "bab_el_mandeb", + "title": "Bab el-Mandeb", + "bbox": "12.0,42.8,13.5,44.3", + "center": [12.7, 43.4], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "suez", + "title": "Suez / N. Red Sea", + "bbox": "29.5,32.0,31.0,33.5", + "center": [30.0,32.5], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "malacca", + "title": "Malacca / Singapore", + "bbox": "1.0,103.0,2.5,104.5", + "center": [1.3, 103.8], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "taiwan", + "title": "Taiwan Strait", + "bbox": "23.5,119.0,25.0,120.5", + "center": [24.2, 119.8], + "zoom": 9, + "vesselapi": False, + }, +) + + +def chokepoints() -> list[dict]: + """Return a fresh copy of the catalog (callers must not mutate the source).""" + return [dict(p) for p in _CHOKEPOINTS] diff --git a/app/config.py b/app/config.py index d93f492..ea89a8d 100644 --- a/app/config.py +++ b/app/config.py @@ -71,6 +71,9 @@ FIRMS_DATASETS = [d.strip() for d in _FIRMS_DATASETS_RAW.split(",") if d.strip() OSINT_USER_AGENT = os.getenv( "OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)" ) +# Nominatim reverse (GET /api/place). Camera scraper has its own copy in camera_config. +NOMINATIM_URL = os.getenv("NOMINATIM_URL", "https://nominatim.openstreetmap.org") +NOMINATIM_MIN_INTERVAL = float(os.getenv("NOMINATIM_MIN_INTERVAL", "1.0")) # Self-hosted TiTiler (warps Sentinel-1 signed COGs into XYZ tiles on the Pi). # TITILER_PUBLIC_BASE is the same-origin path prefix the browser hits through @@ -104,3 +107,12 @@ 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/conflicts.py b/app/conflicts.py new file mode 100644 index 0000000..bfc48cd --- /dev/null +++ b/app/conflicts.py @@ -0,0 +1,168 @@ +"""Curated OSINT conflict-zone catalog + point-in-bbox event counting. + +A static, human-curated list of active conflict theatres (war / high / +elevated). Purely descriptive — this is a catalog, not a live feed and not a +scrape of LiveUAMap or any other source. Severity and descriptions are +editorial judgement kept short and factual. + +Each zone carries an internal ``bbox`` (``min_lat, min_lon, max_lat, max_lon``) +used only to count pre-existing geocoded news/GDELT/``/api/news/map`` rows that +fall inside it. The bbox is not part of the API response; callers get the +``eventCount`` roll-up instead. + +Never call an upstream API from here — event counts come from rows already in +the local database (``events`` with geocoords + ``news_items`` map pins). +""" + +from __future__ import annotations + +from datetime import datetime + +# id → zone. ``lat``/``lon`` is the fly-to anchor; ``bbox`` is the internal +# count window in ``min_lat, min_lon, max_lat, max_lon`` order. +_ZONES: tuple[dict, ...] = ( + { + "id": "ukraine", + "label": "Ukraine", + "severity": "war", + "lat": 48.5, + "lon": 31.0, + "description": "Full-scale Russian invasion since 2022; active front lines in the east and south.", + "bbox": (44.3, 22.1, 52.4, 40.2), + }, + { + "id": "gaza", + "label": "Gaza", + "severity": "war", + "lat": 31.4, + "lon": 34.4, + "description": "Israel–Hamas war; sustained fighting and a severe humanitarian crisis in the Gaza Strip.", + "bbox": (31.0, 34.1, 31.8, 34.7), + }, + { + "id": "sudan", + "label": "Sudan", + "severity": "war", + "lat": 15.5, + "lon": 30.0, + "description": "Civil war between the SAF and RSF since 2023, with mass displacement across the country.", + "bbox": (8.7, 21.8, 22.0, 38.6), + }, + { + "id": "myanmar", + "label": "Myanmar", + "severity": "war", + "lat": 21.5, + "lon": 96.0, + "description": "Post-2021 coup conflict pitting the junta against resistance and ethnic armed groups.", + "bbox": (9.5, 92.2, 28.5, 101.2), + }, + { + "id": "drc", + "label": "DR Congo", + "severity": "war", + "lat": -1.5, + "lon": 28.0, + "description": "Eastern DRC conflict involving M23 and other armed groups; heavy displacement around Goma.", + "bbox": (-5.0, 26.0, 3.0, 31.0), + }, + { + "id": "yemen", + "label": "Yemen", + "severity": "war", + "lat": 15.5, + "lon": 47.5, + "description": "Protracted Houthi–government/coalition war with one of the world's worst humanitarian emergencies.", + "bbox": (12.6, 42.5, 19.0, 54.0), + }, + { + "id": "syria", + "label": "Syria", + "severity": "war", + "lat": 34.5, + "lon": 38.5, + "description": "Multi-sided civil war; government, opposition, and external actors continue to engage.", + "bbox": (32.3, 35.7, 37.3, 42.4), + }, + { + "id": "lebanon", + "label": "Lebanon", + "severity": "high", + "lat": 33.9, + "lon": 35.9, + "description": "Israel–Hezbollah hostilities with periodic escalation along the southern border.", + "bbox": (33.0, 35.0, 34.7, 36.6), + }, + { + "id": "sahel", + "label": "Sahel", + "severity": "high", + "lat": 14.5, + "lon": 0.0, + "description": "Jihadist insurgencies across Mali, Burkina Faso, and Niger destabilising the central Sahel.", + "bbox": (10.0, -10.0, 20.0, 12.0), + }, + { + "id": "somalia", + "label": "Somalia", + "severity": "high", + "lat": 6.0, + "lon": 45.0, + "description": "Al-Shabaab insurgency against the federal government and security forces.", + "bbox": (-2.0, 41.0, 12.0, 51.5), + }, + { + "id": "red_sea", + "label": "Red Sea", + "severity": "high", + "lat": 18.0, + "lon": 40.0, + "description": "Houthi attacks on commercial shipping transiting the Red Sea corridor.", + "bbox": (12.0, 34.0, 22.0, 44.0), + }, + { + "id": "taiwan_strait", + "label": "Taiwan Strait", + "severity": "elevated", + "lat": 24.5, + "lon": 119.5, + "description": "Heightened military standoff between China and Taiwan, including deterrence patrols.", + "bbox": (21.9, 117.0, 26.5, 122.0), + }, + { + "id": "korean_dmz", + "label": "Korean DMZ", + "severity": "elevated", + "lat": 38.3, + "lon": 127.0, + "description": "Heavily fortified inter-Korean border with periodic tensions and military drills.", + "bbox": (37.5, 126.0, 39.0, 128.5), + }, +) + +SEVERITIES: frozenset[str] = frozenset({"war", "high", "elevated"}) + + +def conflict_zones() -> list[dict]: + """Return a fresh shallow copy of the catalog (callers must not mutate).""" + return [dict(z) for z in _ZONES] + + +def zone_event_stats( + points: list[tuple[float, float, datetime | None]], + bbox: tuple[float, float, float, float], +) -> tuple[int, datetime | None]: + """Count points inside ``bbox`` and return (count, latest timestamp). + + ``points`` is an iterable of ``(lat, lon, ts)``; ``ts`` may be ``None``. + ``bbox`` is ``(min_lat, min_lon, max_lat, max_lon)``. + """ + min_lat, min_lon, max_lat, max_lon = bbox + count = 0 + latest: datetime | None = None + for lat, lon, ts in points: + if min_lat <= lat <= max_lat and min_lon <= lon <= max_lon: + count += 1 + if ts is not None and (latest is None or ts > latest): + latest = ts + return count, latest diff --git a/app/fire_sources.py b/app/fire_sources.py index c27b0f7..46f9fe9 100644 --- a/app/fire_sources.py +++ b/app/fire_sources.py @@ -22,6 +22,7 @@ UTC date (YYYY-MM-DD). from __future__ import annotations import csv +import hashlib import io import json import logging @@ -44,6 +45,11 @@ from upstream_cache import firms_cache logger = logging.getLogger("osint.firms") +# In-process poll state: skip byte-identical CSVs, persist only new hotspots. +# Survives the 15-minute loop; one full ON CONFLICT after process start. +_csv_digest: dict[tuple, bytes] = {} +_seen_ids: dict[tuple, set[int]] = {} + # ── FIRMS API ───────────────────────────────────────────────────────────── FIRMS_AREA_CSV = ( @@ -86,33 +92,34 @@ def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None: return None -def parse_firms_csv(text: str) -> list[dict]: - """Parse a FIRMS area CSV payload into normalized fire messages. +def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int: + return hash((round(lat, 5), round(lon, 5), acq_iso, satellite)) - Returns one dict per hotspot with the fields stored in the ``fires`` table - (acq_time already combined into a UTC ISO timestamp). Rows that don't look - like valid VIIRS detections are skipped rather than failing the whole poll. + +def parse_firms_csv_delta( + text: str, skip_ids: set[int] | None = None, +) -> tuple[list[dict], set[int]]: + """Parse FIRMS CSV; optionally drop hotspots already seen this process. + + Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not + materialize the raw CSV as a list of lists. """ - rows = list(csv.reader(io.StringIO(text))) - if not rows: - return [] - - # Locate the real header row. FIRMS normally returns the CSV header first, - # but occasionally prepends a legend/info line, so scan until we see the - # canonical header. - header_idx = 0 - for i, row in enumerate(rows): + reader = csv.reader(io.StringIO(text)) + header = None + for row in reader: if row and row[0].strip().lower() == "latitude" and len(row) >= 4: - header_idx = i + header = [c.strip().lower() for c in row] break - header = [c.strip().lower() for c in rows[header_idx]] - # Guard against a header that isn't actually the FIRMS one. - if "latitude" not in header or "longitude" not in header: - logger.warning("FIRMS payload does not look like a hotspot CSV (first row: %r)", header[:6]) - return [] + if not header or "latitude" not in header or "longitude" not in header: + logger.warning( + "FIRMS payload does not look like a hotspot CSV (first row: %r)", + (header or [])[:6], + ) + return [], set() points: list[dict] = [] - for row in rows[header_idx + 1:]: + ids: set[int] = set() + for row in reader: if len(row) < len(header): continue rec = dict(zip(header, row)) @@ -123,13 +130,19 @@ def parse_firms_csv(text: str) -> list[dict]: acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time")) if acq_time is None: continue + sat = str(rec.get("satellite") or "").strip() + acq_iso = acq_time.isoformat() + hid = _hotspot_id(lat, lon, acq_iso, sat) + ids.add(hid) + if skip_ids is not None and hid in skip_ids: + continue points.append({ "latitude": lat, "longitude": lon, "brightness": _to_float(rec.get("bright_ti4")), "confidence": str(rec.get("confidence") or "").strip(), - "acq_time": acq_time.isoformat(), - "satellite": str(rec.get("satellite") or "").strip(), + "acq_time": acq_iso, + "satellite": sat, "instrument": str(rec.get("instrument") or "").strip(), "bright_ti5": _to_float(rec.get("bright_ti5")), "frp": _to_float(rec.get("frp")), @@ -138,6 +151,17 @@ def parse_firms_csv(text: str) -> list[dict]: "track": _to_float(rec.get("track")), "version": str(rec.get("version") or "").strip(), }) + return points, ids + + +def parse_firms_csv(text: str) -> list[dict]: + """Parse a FIRMS area CSV payload into normalized fire messages. + + Returns one dict per hotspot with the fields stored in the ``fires`` table + (acq_time already combined into a UTC ISO timestamp). Rows that don't look + like valid VIIRS detections are skipped rather than failing the whole poll. + """ + points, _ids = parse_firms_csv_delta(text) return points @@ -215,11 +239,18 @@ async def ingest_fires(bbox: str | None = None) -> int: dataset, first_line, ) continue - points = parse_firms_csv(text) - published = await persist_hotspots(points) + poll_key = (dataset, area, FIRMS_DAYS) + digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest() + if _csv_digest.get(poll_key) == digest: + logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset) + continue + points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key)) + published = await persist_hotspots(points) if points else 0 + _csv_digest[poll_key] = digest + _seen_ids[poll_key] = ids total_published += published logger.info( "FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d", - len(points), area, dataset, published, + len(ids), area, dataset, published, ) return total_published diff --git a/app/geofence.py b/app/geofence.py index 398c73b..342f1c4 100644 --- a/app/geofence.py +++ b/app/geofence.py @@ -7,6 +7,7 @@ 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 @@ -15,6 +16,19 @@ 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): @@ -99,6 +113,160 @@ _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: @@ -249,12 +417,24 @@ 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 @@ -275,6 +455,33 @@ 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, @@ -284,7 +491,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": payload or {}, + "payload": body_payload, "created_at": now.isoformat(), } try: @@ -306,7 +513,7 @@ async def record_and_notify( "entity_id": str(entity_id), "lat": lat, "lon": lon, - "payload": json.dumps(payload or {}), + "payload": json.dumps(body_payload), }, ) except Exception: @@ -314,8 +521,324 @@ 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: pass return sent + + +async def list_alerts( + *, + geofence_id: str | None = None, + since: datetime | None = None, + until: datetime | None = None, + source_kind: str | None = None, + limit: int = 100, +) -> list[dict]: + """Filterable hit log. Empty list if the DB is down — never raises.""" + where = ["TRUE"] + params: dict[str, Any] = {"limit": int(limit)} + if geofence_id: + where.append("geofence_id = CAST(:geofence_id AS uuid)") + params["geofence_id"] = geofence_id + if since is not None: + where.append("created_at >= :since") + params["since"] = since + if until is not None: + where.append("created_at <= :until") + params["until"] = until + if source_kind: + where.append("source_kind = :source_kind") + params["source_kind"] = source_kind + sql = f""" + SELECT id::text, geofence_id::text, source_kind, entity_id, + lat, lon, payload, created_at + FROM geofence_alerts + WHERE {' AND '.join(where)} + ORDER BY created_at DESC + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute(text(sql), params)).mappings().all() + out = [] + for r in rows: + item = dict(r) + if item.get("created_at") is not None: + item["created_at"] = item["created_at"].isoformat() + out.append(item) + return out + except Exception: + return [] + + +async def get_geofence(gid: str) -> dict | None: + current = next((f for f in _cache if f["id"] == gid), None) + if current is not None: + return current + try: + await refresh_cache() + except Exception: + return None + return next((f for f in _cache if f["id"] == gid), None) + + +def _marker_from_track(row) -> dict: + from live_layers import to_marker + + extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True} + return to_marker( + row["id"], row["lat"], row["lon"], + heading=row.get("heading"), speed=row.get("speed"), + label=row.get("label") or row["id"], + extra=extra, + ) + + +async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]: + table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min" + id_col = "hex" if kind == "aircraft" else "mmsi" + sql = f""" + SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket + FROM {table} + WHERE bucket = :bucket + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(lon, lat), 4326) + ) + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute( + text(sql), {"bucket": bucket, "gid": gid, "limit": limit}, + )).mappings().all() + return [ + _marker_from_track(r) + for r in rows + if r["lat"] is not None and r["lon"] is not None + ] + except Exception: + return [] + + +async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]: + from tracks import minute_bucket + + bucket = minute_bucket(ts) + t1 = bucket + timedelta(minutes=1) + sql = """ + SELECT latitude, longitude, brightness, confidence, acq_time, satellite, + instrument, bright_ti5, frp, daynight + FROM fires + WHERE acq_time >= :t0 AND acq_time < :t1 + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) + ) + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute( + text(sql), + {"t0": bucket, "t1": t1, "gid": gid, "limit": limit}, + )).mappings().all() + out = [] + for r in rows: + item = dict(r) + if item.get("acq_time") is not None: + item["acq_time"] = item["acq_time"].isoformat() + out.append(item) + return out + except Exception: + return [] + + +async def snapshot_at(gid: str, ts: datetime) -> dict | None: + """Positions inside the fence at time T. None if the fence is missing. + + Does not persist or notify. Empty lists if track/fire queries fail. + """ + fence = await get_geofence(gid) + if fence is None: + return None + from tracks import minute_bucket + + bucket = minute_bucket(ts) + aircraft = await _cagg_inside(gid, "aircraft", bucket) + vessels = await _cagg_inside(gid, "vessel", bucket) + fires = await _fires_inside(gid, ts) + return { + "geofence_id": gid, + "timestamp": ts.isoformat(), + "aircraft": aircraft, + "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 ac0bcbd..8b2e07c 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -213,15 +213,38 @@ async def ingest_event(msg: dict): claimed = await session.execute(dedup) if not claimed.rowcount: await session.commit() - logger.info("skip duplicate event url=%s", key) + logger.debug("skip duplicate event url=%s", key) return None result = await session.execute(events_table.insert().values(**event_row)) 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 b6e80d1..3c1d92e 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -50,10 +50,19 @@ PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentine # Self-hosted TiTiler on the Pi, exposed same-origin through the osint.rpi.local # nginx vhost. Relative template — Leaflet resolves it against the page origin, # so the browser never touches a raw loopback port or titiler.xyz. -TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}@1x" -SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window +TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}" +SENTINEL1_TTL = 6 * 3600 # S-1 revisit is 6–12 days; cache the COG all afternoon +SENTINEL1_CELL = 2.0 # degrees — pan/zoom inside a cell reuses the same scene +SENTINEL1_STAC_LIMIT = 8 SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer" +# GPSJAM (John Wiseman / ADS-B Exchange): daily H3 hexes of aircraft nav +# accuracy. Hexes are published as a gzip CSV at a stable per-date URL, soon +# after midnight UTC. Red/yellow != proven jamming. +GPSJAM_BASE = "https://gpsjam.org" +GPSJAM_RES = 4 +GPSJAM_TTL = 3600.0 # 1h — whole-world layer, fetched once per day effectively + IEM_NEXRAD = "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png" GIBS_THERMAL = ( "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" @@ -88,6 +97,11 @@ _MAX_VESSELS = 6000 # Last ADS-B snapshot + WFIGS points for fire↔tanker correlation. aircraft_last_known: dict[str, dict] = {} fire_last_known: list[dict] = [] +# Last-known counts for the cheap GET /api/stats HUD counter. Updated by the +# upstream fetchers so the stats endpoint never does its own network/SQL fan-out +# for these layers; reads are O(1) in-process. +train_count: int = 0 +nws_alert_count: int = 0 def overlay_catalog() -> dict: @@ -135,6 +149,30 @@ def overlay_catalog() -> dict: "vessels": {"id": "vessels", "kind": "points", "endpoint": "/api/vessels"}, "trains": {"id": "trains", "kind": "points", "endpoint": "/api/trains"}, "storms": {"id": "storms", "kind": "points", "endpoint": "/api/storms"}, + "gpsjam": { + "id": "gpsjam", + "kind": "geojson", + "endpoint": "/api/map/gpsjam", + "attribution": "GPSJAM / John Wiseman / ADS-B Exchange", + }, + "satellites": { + "id": "satellites", + "kind": "points", + "endpoint": "/api/satellites", + "attribution": "CelesTrak (GP JSON / SGP4)", + }, + "infra_nuclear": { + "id": "infra_nuclear", + "kind": "points", + "endpoint": "/api/infrastructure?types=nuclear", + "attribution": "OpenStreetMap contributors / Overpass API", + }, + "conflicts": { + "id": "conflicts", + "kind": "points", + "endpoint": "/api/conflicts", + "attribution": "Curated OSINT conflict catalog", + }, } @@ -705,18 +743,25 @@ 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={ - "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", - }, + extra=extra, )) return out @@ -951,16 +996,24 @@ async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dic return transform_amtraker(await _get_json(AMTRAKER_TRAINS)) rows = await _ttl_get("amtraker:trains", 20.0, _load) + global train_count + train_count = len(rows) if bbox: minlon, minlat, maxlon, maxlat = parse_bbox(bbox) return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) return rows[:limit] -async def fetch_vessels(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: +async def fetch_vessels( + bbox: str | None, + limit: int = DEFAULT_LIMIT, + src: str | None = None, +) -> list[dict]: async with vessel_lock: rows = [dict(v) for v in vessel_last_known.values() if v.get("lat") is not None and v.get("lon") is not None] + if src and src != "all": + rows = [r for r in rows if (r.get("extra") or {}).get("src") == src] if bbox: minlon, minlat, maxlon, maxlat = parse_bbox(bbox) return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) @@ -993,8 +1046,18 @@ async def upsert_vessel(marker: dict) -> None: vessel_last_known[vid] = stored if len(vessel_last_known) > _MAX_VESSELS: excess = len(vessel_last_known) - int(_MAX_VESSELS * 0.9) + # AISStream's live US-coast feed can crowd the shared store past + # _MAX_VESSELS and evict the Hormuz VesselAPI rows (refreshed only + # every VESSELAPI_INTERVAL) as "oldest". Keep src=vesselapi rows + # resident so the blind-spot box stays visible between polls. + evictable = [ + k for k, v in vessel_last_known.items() + if (v.get("extra") or {}).get("src") != "vesselapi" + ] + if len(evictable) < excess: + excess = len(evictable) oldest = sorted( - vessel_last_known, + evictable, key=lambda k: vessel_last_known[k].get("seen_at", ""), )[:excess] for k in oldest: @@ -1028,17 +1091,27 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict: return params -async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: +_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.""" params = _wfigs_params(bbox) - params["outFields"] = ( - "IncidentName,IncidentSize,FireDiscoveryDateTime,POOState," - "PercentContained,IncidentTypeCategory,FireCause" - ) + params["outFields"] = _WFIGS_INCIDENT_FIELDS 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 @@ -1088,6 +1161,8 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict: logger.warning("NWS alerts fetch failed: %s", exc) nws_ok = False nws_fc = {"features": []} + global nws_alert_count + nws_alert_count = len(nws_fc.get("features") or []) sbw_fc = await _ttl_get("iem:sbw", 45.0, _load_iem) features = [] for feat in nws_fc.get("features") or []: @@ -1194,9 +1269,15 @@ async def _pc_call(coro: Awaitable[Any]) -> Any: def sign_cog_url(href: str, token: str) -> str: - """Append a SAS token to a PC blob URL (respect existing query string).""" + """Append a SAS token to a PC blob URL (respect existing query string). + + PC's SAS endpoint returns the token as an already-percent-encoded query + string (``st=…&se=…&sp=rl&…&sig=…``). Azure only honours those parameters + when they sit top-level on the blob URL — wrapping them under a single + ``token=`` param yields 403/409, so we append the token verbatim. + """ sep = "&" if "?" in href else "?" - return f"{href}{sep}token={quote(token, safe='')}" + return f"{href}{sep}{token}" def sentinel1_tile_url(signed_cog: str) -> str: @@ -1209,25 +1290,71 @@ def sentinel1_tile_url(signed_cog: str) -> str: return f"{TITILER_COG_TILES}?{params}" +def feature_bbox(feat: dict) -> list[float] | None: + """STAC Feature bbox as [minlon, minlat, maxlon, maxlat], or None.""" + raw = feat.get("bbox") if isinstance(feat, dict) else None + if isinstance(raw, (list, tuple)) and len(raw) >= 4: + try: + return [float(raw[0]), float(raw[1]), float(raw[2]), float(raw[3])] + except (TypeError, ValueError): + pass + geom = (feat or {}).get("geometry") or {} + coords = geom.get("coordinates") if isinstance(geom, dict) else None + if not coords: + return None + lons: list[float] = [] + lats: list[float] = [] + + def _walk(node: Any) -> None: + if isinstance(node, (list, tuple)) and node and isinstance(node[0], (int, float)): + lons.append(float(node[0])) + lats.append(float(node[1])) + elif isinstance(node, (list, tuple)): + for child in node: + _walk(child) + + _walk(coords) + if not lons: + return None + return [min(lons), min(lats), max(lons), max(lats)] + + +def pick_sentinel_feature(features: list, lon: float, lat: float) -> dict | None: + """Prefer the scene whose bbox covers the viewport center; else first.""" + if not features: + return None + for feat in features: + bb = feature_bbox(feat) + if bb and bb[0] <= lon <= bb[2] and bb[1] <= lat <= bb[3]: + return feat + return features[0] + + async def fetch_sentinel1(bbox: str) -> dict | None: """Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready. Returns the overlay tile-template dict, or ``None`` when no GRD imagery covers the bbox in the last 7 days (caller maps to 404). Queries Planetary - Computer only when called; cached per quantized bbox + UTC day. + Computer only when called; cached per 2° cell + UTC day so pan/zoom inside + the same region reuses the COG instead of picking a neighbouring swath. """ minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox( + minlon, minlat, maxlon, maxlat, step=SENTINEL1_CELL, + ) day = datetime.now(timezone.utc).date().isoformat() - key = f"sentinel1:{day}:{bbox_cell_key(bbox)}" + key = f"sentinel1:{day}:{qminlon:.4f},{qminlat:.4f},{qmaxlon:.4f},{qmaxlat:.4f}" + clon = (qminlon + qmaxlon) / 2.0 + clat = (qminlat + qmaxlat) / 2.0 async def _load() -> dict | None: now = datetime.now(timezone.utc) week_ago = now - timedelta(days=7) payload = { "collections": ["sentinel-1-grd"], - "bbox": [minlon, minlat, maxlon, maxlat], + "bbox": [qminlon, qminlat, qmaxlon, qmaxlat], "datetime": f"{week_ago.isoformat()}/{now.isoformat()}", - "limit": 1, + "limit": SENTINEL1_STAC_LIMIT, "sortby": [{"field": "datetime", "direction": "desc"}], } data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload)) @@ -1235,7 +1362,9 @@ async def fetch_sentinel1(bbox: str) -> dict | None: if not features: return None - feat = features[0] + feat = pick_sentinel_feature(features, clon, clat) + if not feat: + return None assets = feat.get("assets") or {} chosen_href: str | None = None polarization: str | None = None @@ -1264,6 +1393,184 @@ async def fetch_sentinel1(bbox: str) -> dict | None: "datetime": props.get("datetime") or feat.get("datetime"), "polarization": polarization, "attribution": SENTINEL1_ATTRIBUTION, + "bbox": feature_bbox(feat), } return await _ttl_get(key, float(SENTINEL1_TTL), _load) +# ── GPSJAM ────────────────────────────────────────────────────────────────── + + +def gpsjam_level(percent_bad: float) -> str: + """Map a denoised bad-aircraft percentage to GPSJAM's three tiers.""" + if percent_bad > 10.0: + return "high" + if percent_bad > 2.0: + return "medium" + return "low" + + +def gpsjam_csv_to_geojson(text: str) -> dict: + """Convert a GPSJAM daily CSV to a world FeatureCollection of hex polygons. + + Rows are ``hex,count_good_aircraft,count_bad_aircraft``. The interference + percentage uses GPSJAM's published denoise formula + ``100 * (bad - 1) / (good + bad)``; hexes with zero bad aircraft are the + "normal" background and are dropped (the base map already shows nothing). + """ + import csv + import io + + import h3 + + features = [] + for row in csv.DictReader(io.StringIO(text)): + hex_id = (row.get("hex") or "").strip() + if not hex_id: + continue + try: + good = int(row.get("count_good_aircraft") or 0) + bad = int(row.get("count_bad_aircraft") or 0) + except (TypeError, ValueError): + continue + if bad < 1: + continue + denom = good + bad + percent = 100.0 * (bad - 1) / denom if denom > 0 else 0.0 + try: + # h3 returns (lat, lng); GeoJSON needs (lng, lat) closed rings. + ring = [[lng, lat] for lat, lng in h3.cell_to_boundary(hex_id)] + except Exception: # malformed/unknown cell id — skip + continue + ring.append(ring[0]) + features.append({ + "type": "Feature", + "geometry": {"type": "Polygon", "coordinates": [ring]}, + "properties": { + "level": gpsjam_level(percent), + "percent_bad": round(percent, 2), + "good": good, + "bad": bad, + "hex": hex_id, + }, + }) + return {"type": "FeatureCollection", "features": features} + + +async def fetch_gpsjam(date: str) -> dict: + """Fetch + convert one GPSJAM daily hex layer (whole world, 1h TTL).""" + url = f"{GPSJAM_BASE}/data/{date}-h3_{GPSJAM_RES}.csv" + + async def _load(): + if _http is None: + async with httpx.AsyncClient( + timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(), + ) as client: + resp = await client.get(url) + resp.raise_for_status() + return gpsjam_csv_to_geojson(resp.text) + resp = await _http.get(url) + resp.raise_for_status() + return gpsjam_csv_to_geojson(resp.text) + + return await _ttl_get(f"gpsjam:{date}", GPSJAM_TTL, _load) +# ── Infrastructure (Overpass) ─────────────────────────────────────────────── + + +OVERPASS_INTERPRETER = "https://overpass-api.de/api/interpreter" +# One in-flight query per quantized bbox (the per-key lock in _ttl_get). Overpass +# asks for a 25s server timeout in-band; the client gives it 30s of headroom. +OVERPASS_TIMEOUT = httpx.Timeout(30.0, connect=5.0) +INFRA_TTL = 24 * 3600 # 24h per quantized bbox — static infrastructure + +# `types=` enum. Nuclear ships first; military/hospital slot in behind the same +# query template without touching the transport. Overpass bbox is +# (south, west, north, east), i.e. (minlat, minlon, maxlat, maxlon). +_INFRA_QUERIES: dict[str, str] = { + "nuclear": ( + '[out:json][timeout:25];\n' + 'nwr["power"="plant"]["plant:source"="nuclear"]({bbox});\n' + 'out center;' + ), +} + + +def infra_query(type_: str, minlon: float, minlat: float, maxlon: float, maxlat: float) -> str: + """Render one Overpass query with the bbox substituted in south,west,north,east.""" + bbox = f"{minlat},{minlon},{maxlat},{maxlon}" + return _INFRA_QUERIES[type_].replace("{bbox}", bbox) + + +def normalize_infra_element(elem: dict, type_: str) -> dict | None: + """Map one Overpass element to ``{id, name, lat, lon, type, extra}``. + + ``out center`` gives nodes their own ``lat``/``lon`` and ways/relations a + ``center``. Elements with no usable coordinate are dropped. + """ + etype = elem.get("type") + eid = elem.get("id") + if eid is None: + return None + if etype == "node": + lat, lon = elem.get("lat"), elem.get("lon") + else: + center = elem.get("center") or {} + lat, lon = center.get("lat"), center.get("lon") + if lat is None or lon is None: + return None + tags = elem.get("tags") or {} + name = tags.get("name") or tags.get("ref") or f"{etype}/{eid}" + extra = {k: v for k, v in tags.items() if k != "name"} + return { + "id": f"{etype}/{eid}", + "name": name, + "lat": lat, + "lon": lon, + "type": type_, + "extra": extra, + } + + +def overpass_nuclear_to_markers(data: dict) -> list[dict]: + """Convert an Overpass JSON response to normalized nuclear markers.""" + markers = [] + for elem in data.get("elements") or []: + marker = normalize_infra_element(elem, "nuclear") + if marker is not None: + markers.append(marker) + return markers + + +async def fetch_infrastructure(types: str, bbox: str) -> list[dict]: + """Fetch Overpass infrastructure markers, cached 24h per quantized bbox. + + ``types`` is a single supported enum value (``nuclear`` for now). ``bbox`` + is ``minlon,minlat,maxlon,maxlat``. + """ + requested = [t.strip() for t in types.split(",") if t.strip()] + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + key = f"infra:{','.join(requested)}:{bbox_cell_key(bbox)}" + + async def _load() -> list[dict]: + # One query per requested type, concatenated. Nuclear is the only type + # today; the loop keeps the shape ready for military/hospital. + out: list[dict] = [] + for type_ in requested: + query = infra_query(type_, minlon, minlat, maxlon, maxlat) + if _http is None: + async with httpx.AsyncClient( + timeout=OVERPASS_TIMEOUT, follow_redirects=True, + headers=_headers(), + ) as client: + resp = await client.post(OVERPASS_INTERPRETER, data={"data": query}) + resp.raise_for_status() + out.extend(overpass_nuclear_to_markers(resp.json())) + else: + resp = await _http.post( + OVERPASS_INTERPRETER, data={"data": query}, + timeout=OVERPASS_TIMEOUT, + ) + resp.raise_for_status() + out.extend(overpass_nuclear_to_markers(resp.json())) + return out + + return await _ttl_get(key, float(INFRA_TTL), _load) diff --git a/app/main.py b/app/main.py index 6b39d71..00d0d6f 100644 --- a/app/main.py +++ b/app/main.py @@ -14,15 +14,19 @@ from __future__ import annotations import asyncio import json import logging +import re +import time from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from decimal import Decimal from pathlib import Path from typing import NoReturn +from urllib.parse import urlparse from uuid import UUID +import httpx import structlog -from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect +from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect from fastapi.middleware.gzip import GZipMiddleware from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles @@ -30,16 +34,18 @@ 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_summaries, news_items, + articles, article_scores, article_summaries, news_items, ) from schemas import ( AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate, + ConflictZoneOut, ConflictsOut, DashboardSummary, EntityCreate, EntityKind, EntityOut, - EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, + EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut, NewsSummaryOut, NewsTickerItemOut, - FeedSourceCreate, FeedSourceOut, + FeedSourceCreate, FeedSourceOut, FeedSourceUpdate, KeyOut, KeyValueIn, NewsModelsOut, SettingsIn, SettingsOut, SearchResult, SentimentSummary, SourceType, @@ -47,16 +53,20 @@ from schemas import ( GeofenceCreate, GeofenceUpdate, ) from ingestor import ingest_event, fetch_and_process -from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals +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, - fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, fetch_storms, - fetch_trains, fetch_vessels, fetch_weather_alerts, overlay_catalog, - parse_bbox, UpstreamRateLimited, + fetch_gpsjam, fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, + fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts, + fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited, ) +from satellites import fetch_satellites, parse_groups, DEFAULT_GROUPS +from place import reverse_geocode logging.basicConfig(level=logging.INFO) logger = structlog.get_logger("osint.dashboard") @@ -72,6 +82,11 @@ async def _lifespan(app: FastAPI): await refresh_cache() except Exception: pass + try: + from vesselapi import hydrate_last_known + await hydrate_last_known() + except Exception: + pass from config import AISSTREAM_IN_APP, VESSELAPI_IN_APP ais_task = None vesselapi_task = None @@ -103,17 +118,57 @@ 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.""" + """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. + """ 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: @@ -122,7 +177,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(8) + await asyncio.sleep(interval) class CachedStaticFiles(StaticFiles): @@ -253,7 +308,14 @@ 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) - await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600) + # 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(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600) return checks @@ -265,6 +327,99 @@ def overlay_json(data, max_age: int) -> JSONResponse: return resp +# ── HUD counters ───────────────────────────────────────────────────────── + +# Cheap ~100 B–2 KB counts for the layer rail. Cached in-process so the HUD +# can poll every second without re-hitting SQL or upstream feeds. +_STATS_TTL = 20.0 +_stats_cache: dict[str, tuple[float, dict]] = {} + + +async def _stats_counts() -> dict: + """Fan out to in-memory last-known / cheap SQL counts. Never raises.""" + from live_layers import ( + aircraft_last_known, vessel_last_known, train_count, nws_alert_count, + ) + + counts: dict = { + "aircraft": len(aircraft_last_known), + "vessels": len(vessel_last_known), + "trains": train_count, + "cameras": 0, + "fires": 0, + "quakes": 0, + "alerts": nws_alert_count, + } + + # SQL counts are best-effort: a down DB or missing table must not 500 the + # rail — the frontend still renders with zeros. + try: + from camera_models import cameras as cam_table + async with async_session() as session: + counts["cameras"] = int( + (await session.execute(select(func.count()).select_from(cam_table))).scalar() or 0 + ) + counts["fires"] = int( + (await session.execute(select(func.count()).select_from(fires))).scalar() or 0 + ) + counts["quakes"] = int( + (await session.execute( + select(func.count()).select_from(events).where( + events.c.source_type == "earthquake" + ) + )).scalar() or 0 + ) + except Exception as exc: # noqa: BLE001 + 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.""" + now = time.monotonic() + cached = _stats_cache.get("stats") + if cached and now - cached[0] < _STATS_TTL: + return cached[1] + payload = await _stats_counts() + _stats_cache["stats"] = (now, payload) + return overlay_json(payload, 15) + + # ── Feed Sources ────────────────────────────────────────────────────────── @app.get("/api/sources", response_model=list[FeedSourceOut]) @@ -294,20 +449,22 @@ async def create_source(payload: FeedSourceCreate): @app.patch("/api/sources/{source_id}") -async def update_source(source_id: UUID, payload: dict): - """Update a feed source (e.g., toggle enabled).""" +async def update_source(source_id: UUID, payload: FeedSourceUpdate): + """Update a feed source (name/url/config/enabled only).""" + values = payload.model_dump(exclude_unset=True) async with async_session() as session: row = (await session.execute( select(feed_sources).where(feed_sources.c.id == source_id) )).mappings().one_or_none() if not row: raise HTTPException(404, "Source not found") - await session.execute( - feed_sources.update() - .where(feed_sources.c.id == source_id) - .values(**payload) - ) - await session.commit() + if values: + await session.execute( + feed_sources.update() + .where(feed_sources.c.id == source_id) + .values(**values) + ) + await session.commit() return {"ok": True} @@ -750,9 +907,15 @@ async def put_settings(payload: SettingsIn): # ── Ingestion Triggers ─────────────────────────────────────────────────── +def _require_public_url(url: str, field: str) -> None: + if not is_public_url(url): + raise HTTPException(400, f"{field} is not a public URL") + + @app.post("/api/ingest/rss") async def trigger_rss_ingest(feed_url: str, source_id: str | None = None): """Trigger RSS feed ingestion.""" + _require_public_url(feed_url, "feed_url") count = await ingest_rss_feed(feed_url, source_id) return {"status": "ok", "items_ingested": count} @@ -760,6 +923,10 @@ async def trigger_rss_ingest(feed_url: str, source_id: str | None = None): @app.post("/api/ingest/gdelt") async def trigger_gdelt_ingest(query: str = "", max_articles: int = 50): """Trigger GDELT data ingestion.""" + _require_public_url(GDELT_API, "GDELT target") + parsed = urlparse(query) + if parsed.scheme in ("http", "https") and parsed.hostname: + _require_public_url(query, "query") count = await ingest_gdelt(query, max_articles) return {"status": "ok", "articles_ingested": count} @@ -785,24 +952,16 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50): return {"status": "ok", "signals_ingested": count} -@app.post("/api/ingest/masscan") -async def trigger_masscan(background_tasks: BackgroundTasks): - """Queue one masscan pass at ≤200 pps. Does not block the request on the scan.""" - from bg_jobs import MASSCAN_PPS_CAP, schedule_masscan_pass - - async def _kick() -> None: - schedule_masscan_pass() - - background_tasks.add_task(_kick) - return JSONResponse( - {"status": "accepted", "rate_pps": MASSCAN_PPS_CAP}, - status_code=202, - ) - - @app.websocket("/ws/live") async def live_ws(ws: WebSocket): - """Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}.""" + """Viewport-filtered AIS/ADS-B fan-out. + + Client JSON: + {"type":"viewport","bbox":"minlon,minlat,maxlon,maxlat"} + {"type":"watch_geofences","ids":["", ...]} — empty list = none + geofence_alert delivers if the point is in-viewport OR geofence_id is watched. + AIS/ADS-B/fire_aircraft stay viewport-only. + """ from ws_manager import manager client_id = str(id(ws)) @@ -828,6 +987,10 @@ async def live_ws(ws: WebSocket): manager.set_viewport(client_id, parse_bbox(str(data["bbox"]))) except ValueError: continue + elif data.get("type") == "watch_geofences": + ids = data.get("ids") or [] + if isinstance(ids, list): + manager.set_watched_geofences(client_id, [str(x) for x in ids]) except WebSocketDisconnect: pass finally: @@ -979,7 +1142,7 @@ async def list_cameras( True, description="Only cameras with a verified HTTP/MJPEG snapshot_url " "(the ones that actually preview). Set false to include " - "unverified masscan port-554 hits.", + "rows without a snapshot_url.", ), limit: int = Query(500, ge=1, le=5000), ): @@ -1056,7 +1219,7 @@ async def get_camera(camera_id: UUID): async def camera_snapshot(camera_id: UUID): """Still image for one camera. - HTTP cameras go through the TTL cache. masscan/RTSP finds have no HTTP + HTTP cameras go through the TTL cache. RTSP finds have no HTTP snapshot_url — we probe common still-image paths and, failing that, grab one JPEG frame from RTSP via ffmpeg. No credentials are tried. """ @@ -1205,7 +1368,12 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).order_by( + stmt = select(articles).where( + or_( + articles.c.timestamp.is_(None), + articles.c.timestamp <= func.now(), + ) + ).order_by( articles.c.timestamp.desc().nullslast() ) if domain: @@ -1216,7 +1384,7 @@ async def list_news( rows = (await session.execute(stmt)).mappings().all() return [ NewsArticleOut( - id=r["id"], title=r["title"], url=r["url"], + id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"], content=r["content"] if include_content else None, domain=r["domain"], timestamp=r["timestamp"], ) @@ -1261,6 +1429,7 @@ async def list_news_summaries( _FLAGGED = ("critical", "high") +_LESSER = ("medium", "low") @app.get("/api/news/ticker", response_model=list[NewsTickerItemOut]) @@ -1271,7 +1440,7 @@ async def list_news_ticker( ), limit: int = Query(20, ge=1, le=50), ): - """Flagged ticker rows (critical/high), newest first. No LLM required.""" + """Ticker rows: critical/high first; medium/low if nothing is flagged.""" async with async_session() as session: stmt = ( select(news_items) @@ -1285,6 +1454,19 @@ async def list_news_ticker( stmt = stmt.where(news_items.c.created_at >= since) stmt = stmt.limit(limit) rows = (await session.execute(stmt)).mappings().all() + if not rows: + stmt = ( + select(news_items) + .where( + news_items.c.kind == "ticker", + news_items.c.importance.in_(_LESSER), + ) + .order_by(news_items.c.created_at.desc()) + ) + if since: + stmt = stmt.where(news_items.c.created_at >= since) + stmt = stmt.limit(limit) + rows = (await session.execute(stmt)).mappings().all() return [ NewsTickerItemOut( id=r["id"], headline=r["headline"], importance=r["importance"], @@ -1355,6 +1537,94 @@ 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.""" @@ -1400,6 +1670,69 @@ async def map_layers(): return {"layers": MAP_LAYERS, "overlays": overlay_catalog()} +@app.get("/api/map/chokepoints") +async def map_chokepoints(): + """Static one-tap fly-to presets (Strait of Hormuz, Bab el-Mandeb, …). + + Pure catalog — no upstream calls and no VesselAPI quota spend. ``vesselapi`` + is True only for Hormuz (the box the VesselAPI poller already covers). + """ + from chokepoints import chokepoints + return {"chokepoints": chokepoints()} + + +async def _fetch_geocoded_points() -> list[tuple[float, float, datetime | None]]: + """Collect geocoded ``(lat, lon, ts)`` rows from the local DB. + + Sources are the flagged map pins (``news_items`` kind=map) and geocoded + news/GDELT events (``events`` with ``location_lat/lon``). This is the + pre-existing geocoded corpus the conflict-zone counters roll up — no + upstream scraping and no generated/jittered coordinates. + """ + async with async_session() as session: + map_rows = ( + await session.execute( + select(news_items.c.lat, news_items.c.lon, news_items.c.created_at) + .where( + news_items.c.kind == "map", + news_items.c.lat.isnot(None), + news_items.c.lon.isnot(None), + ) + ) + ).all() + event_rows = ( + await session.execute( + select(events.c.location_lat, events.c.location_lon, events.c.source_timestamp) + .where( + events.c.source_type.in_(["rss", "gdel-t2"]), + events.c.location_lat.isnot(None), + events.c.location_lon.isnot(None), + ) + ) + ).all() + return [tuple(r) for r in map_rows] + [tuple(r) for r in event_rows] + + +@app.get("/api/conflicts", response_model=ConflictsOut) +async def list_conflicts(): + """Curated conflict-zone catalog with per-zone event counts. + + Static catalogue (severity + short factual description) merged with a live + ``eventCount`` roll-up of pre-existing geocoded news/GDELT//api/news/map + rows inside each zone bbox. Empty DB → ``eventCount=0`` (never 502). + """ + from conflicts import conflict_zones, zone_event_stats + + points = await _fetch_geocoded_points() + timestamp = datetime.now(timezone.utc) + zones = [] + for z in conflict_zones(): + bbox = z.pop("bbox") + count, latest = zone_event_stats(points, bbox) + zones.append({**z, "eventCount": count, "lastUpdated": latest}) + return {"zones": zones, "timestamp": timestamp} + + def _upstream_or_502(exc: Exception, name: str) -> NoReturn: logger.warning("live_layer_upstream_failed", layer=name, error=str(exc)) raise HTTPException(502, f"{name} upstream unavailable: {exc}") from exc @@ -1499,21 +1832,36 @@ async def list_vessels( bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), limit: int = Query(2000, ge=1, le=5000), timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"), + src: str | None = Query(None, description="aisstream|vesselapi|all (default all)"), ): """AIS last-known — union of two independent providers. AISStream (extra.src="aisstream", live US-coast WebSocket) and VesselAPI (extra.src="vesselapi", Strait of Hormuz 5×/day poll) both upsert into the same store. Empty without either key / until the first successful poll. + ``src`` filters the union to one provider (default ``all``) so a Hormuz + view can skip the ~5k CONUS AISStream rows. """ + if src is not None and src not in ("aisstream", "vesselapi", "all"): + raise HTTPException(422, "src must be one of: aisstream, vesselapi, all") if bbox: _parse_bbox_query(bbox) try: from tracks import fetch_positions_at, parse_timestamp ts = parse_timestamp(timestamp) if ts is not None: - return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5) - return overlay_json(await fetch_vessels(bbox, limit), 5) + from vesselapi import fetch_vessels_as_of + if src == "vesselapi": + return overlay_json(await fetch_vessels_as_of(ts, bbox, limit), 5) + ais = await fetch_positions_at("vessel", ts, bbox, limit) + if src == "aisstream": + return overlay_json(ais, 5) + va = await fetch_vessels_as_of(ts, bbox, limit) + by_id = {m["id"]: m for m in ais} + for m in va: + by_id[m["id"]] = m + return overlay_json(list(by_id.values())[:limit], 5) + return overlay_json(await fetch_vessels(bbox, limit, src=src), 5) except ValueError as exc: raise HTTPException(422, str(exc)) from exc @@ -1594,33 +1942,83 @@ async def api_update_geofence(gid: str, payload: GeofenceUpdate): @app.delete("/api/geofences/{gid}", status_code=204) async def api_delete_geofence(gid: str): from geofence import delete_geofence - await delete_geofence(gid) + ok = await delete_geofence(gid) + if not ok: + raise HTTPException(404, "geofence not found") return None -@app.get("/api/geofence-alerts") -async def api_geofence_alerts(limit: int = Query(100, ge=1, le=500)): - from sqlalchemy import text as sql_text +@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.", + ), +): + """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: - async with async_session() as session: - rows = (await session.execute(sql_text( - """ - SELECT id::text, geofence_id::text, source_kind, entity_id, - lat, lon, payload, created_at - FROM geofence_alerts - ORDER BY created_at DESC - LIMIT :limit - """ - ), {"limit": limit})).mappings().all() - out = [] - for r in rows: - item = dict(r) - if item.get("created_at") is not None: - item["created_at"] = item["created_at"].isoformat() - out.append(item) - return out + ts_parsed = parse_timestamp(raw_ts) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + if ts_parsed is None: + raise HTTPException(422, "timestamp required") + try: + body = await snapshot_at(gid, ts_parsed) except Exception: - return [] + body = { + "geofence_id": gid, + "timestamp": ts_parsed.isoformat(), + "aircraft": [], + "vessels": [], + "fires": [], + } + if body is None: + raise HTTPException(404, "geofence not found") + return body + + +@app.get("/api/geofence-alerts") +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", + ), + 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", + ) + try: + since_ts = parse_timestamp(since) if since else None + until_ts = parse_timestamp(until) if until else None + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + return await list_alerts( + geofence_id=str(geofence_id) if geofence_id else None, + since=since_ts, + until=until_ts, + source_kind=source_kind, + limit=limit, + ) @app.get("/api/fire-aircraft") @@ -1682,6 +2080,122 @@ async def list_storms(): _upstream_or_502(exc, "storms") +@app.get("/api/place") +async def get_place( + lat: float = Query(..., ge=-90, le=90), + lon: float = Query(..., ge=-180, le=180), +): + """Nominatim reverse geocode for the map \"What's here?\" dossier. + + Identifying ``OSINT_USER_AGENT``, 1 req/s, 60s cache, 500 keys. The HUD + lists already-loaded overlay entities client-side — this route does not + refetch aircraft/vessels/cameras/fires. + """ + try: + return overlay_json(await reverse_geocode(lat, lon), 60) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "nominatim") + + +_GPSJAM_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + + +@app.get("/api/map/gpsjam") +async def map_gpsjam( + date: str | None = Query(None, description="YYYY-MM-DD (default: yesterday UTC)"), +): + """GPSJAM daily GPS-interference hex layer (whole world, GeoJSON). + + Red/yellow hexes correlate with suspected jamming but are NOT proof of it. + Fetched once per day from gpsjam.org (ADS-B Exchange data) and cached 1h. + """ + target = date + if target is None: + target = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y-%m-%d") + if not _GPSJAM_DATE.match(target): + raise HTTPException(422, "date must be YYYY-MM-DD") + try: + fc = await fetch_gpsjam(target) + except httpx.HTTPStatusError as exc: + if exc.response.status_code == 404: + return JSONResponse( + {"error": "unavailable", "href": "https://gpsjam.org/", + "date": target}, + ) + _upstream_or_502(exc, "gpsjam") + except Exception as exc: + _upstream_or_502(exc, "gpsjam") + if not fc.get("features"): + return JSONResponse( + {"error": "unavailable", "href": "https://gpsjam.org/", "date": target}, + ) + return overlay_json(fc, 3600) + + +@app.get("/api/satellites") +async def list_satellites( + groups: str | None = Query(None, description="Comma-separated CelesTrak groups"), + bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), + limit: int = Query(2000, ge=1, le=5000), +): + """Last-known satellite positions from CelesTrak GP JSON, SGP4-propagated. + + Default groups are ``stations,weather`` (tens of objects). The GP element + blob is fetched at most once per 2 hours per group and cached; positions + are re-propagated on every request. Falls back to the last good blob on a + CelesTrak 403 / stale response, and to SatNOGS TLE only when the cache is + empty. Unknown groups 400. + """ + try: + group_list = parse_groups(groups if groups is not None else ",".join(DEFAULT_GROUPS)) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + if bbox: + _parse_bbox_query(bbox) + try: + payload = await fetch_satellites(group_list, bbox=bbox, limit=limit) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "satellites") + return overlay_json(payload, 30) + + +_INFRA_TYPES = frozenset({"nuclear"}) + + +@app.get("/api/infrastructure") +async def api_infrastructure( + types: str = Query(..., description="comma-separated enum (nuclear)"), + bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), +): + """Overpass-derived static infrastructure markers (nuclear power plants). + + ``bbox`` is required; ``types`` is a comma-separated subset of ``nuclear``. + Fetched from Overpass (identifying UA, 25s query) and cached 24h per + quantized bbox. Markers are ``{id, name, lat, lon, type, extra}``. + """ + if not bbox: + raise HTTPException(400, "bbox required (minlon,minlat,maxlon,maxlat)") + requested = [t.strip() for t in (types or "").split(",") if t.strip()] + if not requested: + raise HTTPException(422, "types required (e.g. nuclear)") + unknown = [t for t in requested if t not in _INFRA_TYPES] + if unknown: + raise HTTPException( + 422, f"unsupported types: {', '.join(unknown)} (supported: nuclear)" + ) + try: + markers = await fetch_infrastructure(",".join(requested), bbox) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "infrastructure") + return overlay_json(markers, 86400) + + @app.get("/api/map/times") async def map_layer_times( layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"), @@ -1712,4 +2226,4 @@ app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static" if __name__ == "__main__": import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) + uvicorn.run(app, host="0.0.0.0", port=8000, workers=1) # single worker: in-memory WS/pubsub + layer caches diff --git a/app/masscan_config.py b/app/masscan_config.py deleted file mode 100644 index 3606d3f..0000000 --- a/app/masscan_config.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Active camera-discovery configuration (masscan-based, env-driven). - -All knobs read from the environment with safe defaults. The scanner targets -open TCP port 554 (RTSP — the typical IP-camera port) across a configured -range and feeds results into the same `cameras` table as the passive scraper -(discovery_source='masscan'), deduped by URL hash. - -ETHICS / SCOPE (mirrors camera_scraper.py): - * Detection only — a SYN port scan for OPEN hosts. No credential guessing, - no login attempts, no banner grabbing, and no access to camera feeds. - * Private / reserved ranges are excluded via MASSCAN_EXCLUDEFILE so the - scanner never probes RFC1918, loopback, link-local, multicast, or the - bogons. Fail closed if the excludefile is missing. - -TIMING REALITY: at the residential-safe default of 200 pps a full IPv4 -sweep (0.0.0.0/0, ~4.29B addresses) takes ~8 months. This is therefore a -CONTINUOUS ROLLING SWEEP, not a "finish in a day" job: masscan streams -open hosts to stdout and the runner ingests them incrementally, then -restarts the sweep when a pass completes. New cameras are detected as they -appear on each pass. 1k/10k pps saturated a home uplink — do not raise the -rate unless you are on a VPS / unmetered link. -""" - -from __future__ import annotations - -import os - -# Path to the masscan binary (installed on the Pi host). -MASSCAN_BIN = os.getenv("MASSCAN_BIN", "masscan") - -# CIDR(s) to sweep. Default = the whole public IPv4 space. -MASSCAN_RANGE = os.getenv("MASSCAN_RANGE", "0.0.0.0/0") - -# Port(s) to probe. Default 554 = RTSP, the typical IP-camera port. -MASSCAN_PORTS = os.getenv("MASSCAN_PORTS", "554") - -# Packets/sec. 200 is the residential-safe default — 1k/10k pps saturated -# a home uplink. Raise only on a VPS / unmetered link. -MASSCAN_RATE = int(os.getenv("MASSCAN_RATE", "200")) - -# Retransmission count. 1 maximizes unique-host coverage at low rate; the -# default (10) spends most of the budget re-probing the same hosts. -MASSCAN_RETRIES = int(os.getenv("MASSCAN_RETRIES", "1")) - -# Seconds to keep listening for straggler responses after the last probe. -# 0 avoids a 10s tail per pass; tiny loss of the very last hosts is fine -# since the sweep repeats. -MASSCAN_WAIT = int(os.getenv("MASSCAN_WAIT", "0")) - -# Excludefile path on the Pi host. Must contain RFC1918/loopback/link-local/ -# multicast/bogons so the scanner never probes private ranges. Fail closed if -# the file is absent (the runner refuses to start rather than scan wide). -MASSCAN_EXCLUDEFILE = os.getenv( - "MASSCAN_EXCLUDEFILE", "/etc/osint-dashboard/masscan-excludes.txt" -) - -# Ingest batch size — flush this many newly-seen hosts to the DB per round. -MASSCAN_FLUSH_EVERY = int(os.getenv("MASSCAN_FLUSH_EVERY", "250")) - -# NATS subject newly-found cameras are published on (same feed as the -# passive scraper so the shared ingester persists them). -MASSCAN_NATS_SUBJECT = os.getenv("MASSCAN_NATS_SUBJECT", "events.camera") - -# discovery_source tag written into the cameras table. -MASSCAN_DISCOVERY_SOURCE = os.getenv("MASSCAN_DISCOVERY_SOURCE", "masscan") diff --git a/app/masscan_scanner.py b/app/masscan_scanner.py deleted file mode 100644 index 3aa287a..0000000 --- a/app/masscan_scanner.py +++ /dev/null @@ -1,226 +0,0 @@ -"""masscan result parsing + ingestion for the OSINT dashboard. - -Turns a stream of masscan JSON-lines (open port 554 hosts) into rows in the -`cameras` table with discovery_source='masscan', deduped by URL hash against -whatever the passive scraper already found. Newly discovered hosts are also -published to NATS (`events.camera`) so the shared ingester pipeline persists -them exactly like scraper finds. - -Scope: detection of OPEN hosts only. No credentials, no banners, no feed -access. Private/reserved ranges never enter masscan (see excludefile). -""" - -from __future__ import annotations - -import asyncio -import json -import logging -from datetime import datetime, timezone - -from camera_models import cameras -from camera_scraper import url_hash, geolocate_ips -from database import async_session - -from masscan_config import ( - MASSCAN_NATS_SUBJECT, MASSCAN_DISCOVERY_SOURCE, -) - -logger = logging.getLogger("osint.masscan_scanner") - - -# ── URL building ────────────────────────────────────────────────────────── - -def build_rtsp_url(ip: str) -> str: - """Canonical URL for an open-RTSP host. Used as the dedupe key.""" - return f"rtsp://{ip}/" - - -# ── masscan JSON parsing ────────────────────────────────────────────────── -# masscan --output-format=json --output-file=- emits line-delimited JSON on a -# pipe (a bare object per open host), not the array form used for seekable -# files. We parse per-line and tolerate an accidental leading '['. - -def parse_masscan_line(line: str) -> list[dict]: - """Parse one masscan stdout line into a list of host records. - - A line may contain one JSON object or, defensively, be wrapped in an - array. Returns [] on anything unparseable (harmless — the sweep repeats). - """ - s = line.strip() - if not s: - return [] - s = s.lstrip("[").rstrip("]").strip() - if not s: - return [] - # Multiple records may share a line separated by '},{'. - if s.endswith(","): - s = s[:-1].rstrip() - out: list[dict] = [] - for cand in _split_records(s): - try: - obj = json.loads(cand) - except (json.JSONDecodeError, ValueError): - continue - if isinstance(obj, dict) and obj.get("ip"): - out.append(obj) - return out - - -def _split_records(s: str) -> list[str]: - """Split a buffer into individual JSON object strings, honoring nesting.""" - records, depth, start = [], 0, 0 - for i, ch in enumerate(s): - if ch == "{": - if depth == 0: - start = i - depth += 1 - elif ch == "}": - depth -= 1 - if depth == 0: - records.append(s[start:i + 1]) - return records - - -def extract_open_ips(records: list[dict], port: int) -> list[str]: - """Return the list of IPs from records that have `port` open.""" - ips: list[str] = [] - for rec in records: - for p in rec.get("ports", []): - if p.get("port") == port and p.get("status") == "open": - ips.append(rec["ip"]) - break - return ips - - -# ── Persistence ─────────────────────────────────────────────────────────── - -async def ingest_open_hosts(ips: list[str]) -> tuple[int, list[str]]: - """Insert-or-refresh camera rows for open RTSP hosts that have a public feed. - - A host only lands in the table (and therefore on the map) if an - unauthenticated HTTP still or MJPEG URL responds. Port-554-only hosts - are skipped. Returns (newly_inserted, hosts_with_working_feed). - """ - if not ips: - return 0, [] - from camera_preview import probe_public_feed - - unique = list(dict.fromkeys(ips)) - sem = asyncio.Semaphore(20) - - async def _probe(ip: str) -> tuple[str, str | None]: - async with sem: - return ip, await probe_public_feed(ip) - - probed = await asyncio.gather(*(_probe(ip) for ip in unique)) - live = [(ip, feed) for ip, feed in probed if feed] - if not live: - logger.info("masscan ingest: 0 working feeds of %d open-554 hosts", - len(unique)) - return 0, [] - - now = datetime.now(timezone.utc) - coords = await geolocate_ips([ip for ip, _ in live]) - new = 0 - async with async_session() as session: - for ip, feed in live: - url = build_rtsp_url(ip) - h = url_hash(url) - lat, lon = coords.get(ip, (None, None)) - existing = (await session.execute( - cameras.select().where(cameras.c.url_hash == h) - )).one_or_none() - if existing is None: - await session.execute(cameras.insert().values( - url_hash=h, - source_url=url, - snapshot_url=feed, - discovery_source=MASSCAN_DISCOVERY_SOURCE, - location_lat=lat, - location_lon=lon, - location_name=f"{ip} (IP-geo)" if lat is not None else None, - vendor=None, - device_type="rtsp", - first_seen=now, - last_seen=now, - raw={"discovered_via": "masscan", "port": 554, - "public_feed": feed}, - )) - new += 1 - else: - await session.execute(cameras.update().where( - cameras.c.url_hash == h - ).values( - last_seen=now, - snapshot_url=feed, - location_lat=lat, - location_lon=lon, - location_name=f"{ip} (IP-geo)" if lat is not None else None, - )) - await session.commit() - logger.info("masscan ingest: %d new working feeds (%d probed, %d open-554)", - new, len(live), len(unique)) - return new, [ip for ip, _ in live] - - -# ── NATS publish ────────────────────────────────────────────────────────── - -async def publish_new_hosts(ips: list[str]) -> int: - """Publish newly-found open hosts to NATS for the shared ingester. - - Returns the number of messages published (0 if NATS is down). - """ - import json as _json - import nats - from config import NATS_URL - - if not ips: - return 0 - try: - nc = await nats.connect(NATS_URL) - except Exception: # noqa: BLE001 - logger.warning("NATS unavailable — skipping publish pass") - return 0 - published = 0 - try: - js = nc.jetstream() - for ip in dict.fromkeys(ips): - url = build_rtsp_url(ip) - msg = { - "source_type": "camera", - "title": f"Open RTSP camera ({ip})", - "url": url, - "location_lat": None, - "location_lon": None, - "location_name": None, - "tags": ["osint", "camera", MASSCAN_DISCOVERY_SOURCE], - "raw": { - "url_hash": url_hash(url), - "source_url": url, - "snapshot_url": None, - "vendor": None, - "device_type": "rtsp", - "discovered_via": "masscan", - "port": 554, - }, - "source_timestamp": datetime.now(timezone.utc).isoformat(), - } - await js.publish(MASSCAN_NATS_SUBJECT, _json.dumps(msg).encode()) - published += 1 - finally: - await nc.close() - logger.info("published %d masscan finds to %s", published, MASSCAN_NATS_SUBJECT) - return published - - -# ── Batch drain helper used by the runner ───────────────────────────────── - -async def flush(seen: set[str], new_accum: int) -> tuple[int, int]: - """Ingest + publish the accumulated host set; return (new, published).""" - if not seen: - return 0, 0 - ips = list(seen) - new, live = await ingest_open_hosts(ips) - published = await publish_new_hosts(live) - seen.clear() - return new, published diff --git a/app/models.py b/app/models.py index f3b528d..4ffbb96 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 ( - Column, Enum, Float, Index, Integer, String, Text, + Boolean, Column, Enum, Float, Index, Integer, String, Text, DateTime, JSON, func, Table, PrimaryKeyConstraint, ) from sqlalchemy.dialects.postgresql import UUID, TSVECTOR @@ -242,3 +242,34 @@ 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 new file mode 100644 index 0000000..29ada1d --- /dev/null +++ b/app/news_title.py @@ -0,0 +1,33 @@ +"""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/place.py b/app/place.py new file mode 100644 index 0000000..e1729ee --- /dev/null +++ b/app/place.py @@ -0,0 +1,99 @@ +"""Nominatim reverse-geocode proxy for the map place dossier. + +Browser clients cannot set an identifying User-Agent, and Nominatim typically +blocks CORS — so the HUD calls GET /api/place instead of talking to OSM +directly. Cache 60s / 500 keys; never exceed 1 req/s upstream. +""" + +from __future__ import annotations + +import asyncio +import time + +import httpx +from cachetools import TTLCache + +from config import NOMINATIM_MIN_INTERVAL, NOMINATIM_URL, OSINT_USER_AGENT + +_NOMINATIM = NOMINATIM_URL.rstrip("/") + +place_cache: TTLCache = TTLCache(maxsize=500, ttl=60) + +_lock = asyncio.Lock() +_last_req = 0.0 + +_ADDR_KEEP = ( + "house_number", "road", "neighbourhood", "suburb", "city", "town", + "village", "hamlet", "county", "state", "postcode", "country", "country_code", +) + + +def cache_key(lat: float, lon: float) -> str: + return f"{lat:.4f},{lon:.4f}" + + +def slim_place(lat: float, lon: float, data: dict | None) -> dict: + data = data or {} + raw_addr = data.get("address") + addr_in: dict = raw_addr if isinstance(raw_addr, dict) else {} + address = {k: addr_in[k] for k in _ADDR_KEEP if addr_in.get(k)} + err = data.get("error") + display = None if err else (data.get("display_name") or None) + name = None if err else (data.get("name") or address.get("city") + or address.get("town") or address.get("village") or None) + return { + "lat": lat, + "lon": lon, + "display_name": display, + "name": name, + "address": address, + "osm_type": None if err else data.get("osm_type"), + "osm_id": None if err else data.get("osm_id"), + "attribution": "© OpenStreetMap contributors", + } + + +async def reverse_geocode(lat: float, lon: float) -> dict: + """Reverse-geocode a point. Cache hits skip Nominatim entirely.""" + if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0): + raise ValueError("lat/lon out of range") + key = cache_key(lat, lon) + qlat, qlon = (float(p) for p in key.split(",")) + async with _lock: + hit = place_cache.get(key) + if hit is not None: + return hit + global _last_req + wait = _last_req + NOMINATIM_MIN_INTERVAL - time.monotonic() + if wait > 0: + await asyncio.sleep(wait) + body = await _fetch_nominatim(qlat, qlon) + _last_req = time.monotonic() + place_cache[key] = body + return body + + +async def _fetch_nominatim(lat: float, lon: float) -> dict: + headers = { + "User-Agent": OSINT_USER_AGENT, + "Accept": "application/json", + } + url = f"{_NOMINATIM}/reverse" + params = { + "lat": f"{lat:.6f}", + "lon": f"{lon:.6f}", + "format": "jsonv2", + "addressdetails": "1", + "zoom": "18", + } + async with _http_client(timeout=10.0, follow_redirects=True) as client: + r = await client.get(url, params=params, headers=headers) + r.raise_for_status() + data = r.json() + if not isinstance(data, dict): + data = {} + return slim_place(lat, lon, data) + + +def _http_client(**kwargs): + return httpx.AsyncClient(**kwargs) diff --git a/app/requirements.txt b/app/requirements.txt index 691ab71..733d94d 100644 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -12,3 +12,5 @@ python-dateutil>=2.9 structlog>=24.4 websockets>=14 cachetools>=5.5 +h3>=4.0 +sgp4>=2.23 diff --git a/app/run_camera_service.py b/app/run_camera_service.py index c550d04..74d774f 100644 --- a/app/run_camera_service.py +++ b/app/run_camera_service.py @@ -1,9 +1,10 @@ """Long-running camera discovery service. -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. +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. Env: CAMERA_SOURCE_URLS comma-separated public directory/list URLs @@ -14,7 +15,6 @@ Env: from __future__ import annotations import asyncio -import json import logging import sys from pathlib import Path @@ -22,16 +22,12 @@ 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_NATS_SUBJECT, + CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, SNAPSHOT_CACHE_DIR, ) -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 +from camera_scraper import run_cycle # noqa: E402 +from database import init_extensions # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") @@ -40,48 +36,16 @@ logger = logging.getLogger("osint.camera_service") ENABLED = sys.argv[1:] != ["--once"] -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 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 main() -> None: @@ -93,8 +57,7 @@ async def main() -> None: try: n = await run_cycle() p = await publish_new_cameras() - logger.info("cycle: %d stored, %d published to %s", - n, p, CAMERA_NATS_SUBJECT) + logger.info("cycle: %d stored, %d camera events published", n, p) 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 5d94389..2ef49e6 100644 --- a/app/run_ingester.py +++ b/app/run_ingester.py @@ -56,8 +56,11 @@ async def producer_loop() -> None: try: g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50) logger.info("GDELT -> %d articles", g) - except Exception: # noqa: BLE001 - logger.exception("GDELT fetch failed") + 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) if ENABLE_QUAKES: try: q = await ingest_earthquakes() @@ -116,6 +119,24 @@ 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)", @@ -126,7 +147,9 @@ 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] = [] + tasks: list[asyncio.Task] = [ + asyncio.create_task(geofence_feed_loop()), + ] if ENABLE_FIRES: # Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs # and idles otherwise). diff --git a/app/run_masscan_service.py b/app/run_masscan_service.py deleted file mode 100644 index 2628576..0000000 --- a/app/run_masscan_service.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Continuous masscan rolling-sweep service for the OSINT dashboard. - -Runs masscan against the configured range for open port 554 (RTSP), streams -the JSON-lines output, and ingests open hosts into the `cameras` table (new -finds only) plus publishes them to NATS — exactly like the passive scraper. - -Because a full IPv4 sweep at a conservative rate takes days, this runs -masscan CONTINUOUSLY: each pass streams results in as they're found, and when -a pass completes the sweep restarts from the top. New cameras are picked up -on every pass. - -Ethics: detection-only (open-port SYN scan). Private/reserved ranges are -excluded and the service REFUSES to start if the excludefile is missing, so -we never probe private space by accident. - -Run once (for a manual/test pass): python app/run_masscan_service.py --once -Run forever (systemd): python app/run_masscan_service.py -""" - -from __future__ import annotations - -import asyncio -import logging -import os -import sys -from pathlib import Path - -sys_path = str(Path(__file__).parent) -sys.path.insert(0, sys_path) - -import masscan_config as cfg # noqa: E402 -from database import init_extensions # noqa: E402 -from masscan_scanner import ( # noqa: E402 - parse_masscan_line, extract_open_ips, flush, -) - -logging.basicConfig(level=logging.INFO, - format="%(asctime)s %(levelname)s %(name)s: %(message)s") -logger = logging.getLogger("osint.masscan_service") - -ONCE = "--once" in sys.argv[1:] - - -def _verify_excludefile() -> None: - """Fail closed: refuse to sweep the wide range without an excludefile.""" - if not cfg.MASSCAN_EXCLUDEFILE: - raise SystemExit("MASSCAN_EXCLUDEFILE is empty — refusing to run") - if not Path(cfg.MASSCAN_EXCLUDEFILE).is_file(): - raise SystemExit( - f"excludefile {cfg.MASSCAN_EXCLUDEFILE!r} missing — refusing to " - f"run (would risk probing private ranges). Install the excludefile " - f"first (see deploy/masscan-excludes.txt)." - ) - - -def build_command() -> list[str]: - cmd = [ - cfg.MASSCAN_BIN, - cfg.MASSCAN_RANGE, - f"-p{cfg.MASSCAN_PORTS}", - f"--rate={cfg.MASSCAN_RATE}", - f"--retries={cfg.MASSCAN_RETRIES}", - f"--wait={cfg.MASSCAN_WAIT}", - "--output-format=json", - "--output-file=-", - ] - if cfg.MASSCAN_EXCLUDEFILE: - cmd.append(f"--excludefile={cfg.MASSCAN_EXCLUDEFILE}") - return cmd - - -async def _drain_stderr(stream: asyncio.StreamReader) -> None: - """Consume masscan's progress chatter so its stderr pipe never fills.""" - while True: - line = await stream.readline() - if not line: - break - text = line.decode(errors="ignore").strip() - if text and not text.startswith("rate:"): - logger.debug("masscan: %s", text) - - -async def run_pass() -> tuple[int, int]: - """Run one full sweep pass, ingesting incrementally. - - Returns (new_hosts, total_hosts_seen) for the whole pass. - """ - cmd = build_command() - logger.info("starting masscan pass: %s", " ".join(cmd)) - proc = await asyncio.create_subprocess_exec( - *cmd, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - ) - if proc.stderr is not None: - asyncio.ensure_future(_drain_stderr(proc.stderr)) - - seen: set[str] = set() - total_seen = 0 - total_new = 0 - try: - while True: - raw = await proc.stdout.readline() - if not raw: - break - records = parse_masscan_line(raw.decode(errors="ignore")) - for ip in extract_open_ips(records, 554): - if ip in seen: - continue - seen.add(ip) - if len(seen) >= cfg.MASSCAN_FLUSH_EVERY: - new, _published = await flush(seen, total_new) - total_new += new - total_seen += new - # Drain the final partial batch. - if seen: - new, _published = await flush(seen, total_new) - total_new += new - rc = await proc.wait() - except asyncio.CancelledError: - proc.kill() - raise - logger.info("masscan pass finished (rc=%s): %d new hosts ingested", - rc, total_new) - return total_new, total_seen - - -async def main() -> None: - _verify_excludefile() - await init_extensions() - logger.info( - "masscan service starting: range=%s ports=%s rate=%s pps (full sweep " - "~%.0fh at this rate)", - cfg.MASSCAN_RANGE, cfg.MASSCAN_PORTS, cfg.MASSCAN_RATE, - 4.29e9 / cfg.MASSCAN_RATE / 3600, - ) - while True: - try: - await run_pass() - except Exception: # noqa: BLE001 - logger.exception("masscan pass error") - if ONCE: - return - # Small gap between passes so the restart is visible in logs. - await asyncio.sleep(5) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/app/satellites.py b/app/satellites.py new file mode 100644 index 0000000..8bbd963 --- /dev/null +++ b/app/satellites.py @@ -0,0 +1,289 @@ +"""CelesTrak satellites last-known overlay. + +Fetches GP **JSON** (OMM mean elements — not TLE) per group at most once per +2 hours, caches the element blob, and propagates positions with a real SGP4 +library on every request. Positions move every second; the *element set* is +what we cache, not the derived lat/lon. + +Catalog numbers >= 100000 only fit OMM/JSON, never a 5-column TLE field, so +elements are initialized through :func:`sgp4.omm.initialize` (which consumes +the CelesTrak GP JSON fields verbatim) rather than round-tripping to TLE. + +CelesTrak usage policy is non-negotiable: fetch the GP JSON blob at most once +per 2 hours per group, never fan out every GROUP, never also fetch +``GROUP=active`` plus subsets, and identify with ``OSINT_USER_AGENT``. +""" + +from __future__ import annotations + +import logging +import math +from datetime import datetime, timezone +from urllib.parse import quote + +logger = logging.getLogger("osint.satellites") + +CELESTRAK_GP = "https://celestrak.org/NORAD/elements/gp.php" +SATNOGS_TLE = "https://db.satnogs.org/api/tle/" +DEFAULT_GROUPS = ("stations", "weather") +ALLOWED_GROUPS = ("stations", "weather", "gps-ops", "starlink") +# CelesTrak policy: do not hit gp.php more than once per 2 hours per group. +SATELLITE_TTL = 2 * 3600.0 +SOURCE_CELESTRAK = "celestrak" +SOURCE_SATNOGS = "satnogs" +DEFAULT_LIMIT = 2000 + +# WGS-84 ellipsoid for TEME -> geodetic. +_WGS84_A = 6378.137 +_WGS84_F = 1.0 / 298.257223563 + +# Last-good element blob per group, kept past TTL so a 403 / "has not updated +# since ..." still serves the previous set instead of failing the overlay. +_last_good: dict[str, list[dict]] = {} + + +def parse_groups(raw: str | None) -> list[str]: + """Validate + normalize a comma-separated group list. Raises ValueError. + + Starlink is allowed only when explicitly requested (never in the default); + it is a large supplemental feed, not part of the stations/weather default. + """ + groups = [g.strip().lower() for g in (raw or "").split(",") if g.strip()] + if not groups: + raise ValueError("groups must be a non-empty comma-separated list") + bad = [g for g in groups if g not in ALLOWED_GROUPS] + if bad: + raise ValueError(f"unknown group(s): {', '.join(bad)}") + # Dedup, preserve order. + seen: set[str] = set() + out: list[str] = [] + for g in groups: + if g not in seen: + seen.add(g) + out.append(g) + return out + + +def _teme_to_geodetic( + r: tuple[float, float, float], + jd: float, + fr: float, +) -> tuple[float, float, float]: + """SGP4 TEME position (km) -> geodetic (lat_deg, lon_deg, alt_km). + + Rotate TEME into an Earth-fixed frame via GMST, then iterate the WGS-84 + geodetic conversion. Good to well under a km for a ground-track overlay. + """ + # GMST (radians) from UT1 ~= UTC here (sub-second error is negligible). + d = (jd + fr) - 2451545.0 + t = d / 36525.0 + gmst_s = ( + 67310.54841 + + (876600.0 * 3600.0 + 8640184.812866) * t + + 0.093104 * t * t + - 6.2e-6 * t * t * t + ) + theta = math.radians((gmst_s % 86400.0) / 240.0) + + x, y, z = r + xe = x * math.cos(theta) + y * math.sin(theta) + ye = -x * math.sin(theta) + y * math.cos(theta) + ze = z + + e2 = _WGS84_F * (2.0 - _WGS84_F) + p = math.sqrt(xe * xe + ye * ye) + lon = math.atan2(ye, xe) + lat = math.atan2(ze, p * (1.0 - e2)) + alt = 0.0 + for _ in range(10): + n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2) + alt = p / math.cos(lat) - n + lat = math.atan2(ze, p * (1.0 - e2 * n / (n + alt))) + n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2) + alt = p / math.cos(lat) - n + return math.degrees(lat), math.degrees(lon), alt + + +def propagate_gp( + elements: list[dict], + group: str, + now: datetime, +) -> list[dict]: + """Propagate CelesTrak GP JSON elements to geodetic positions at ``now``. + + Pure and deterministic given ``now``. Returns ``[{id, name, lat, lon, + alt_km, group}]``; malformed elements and propagation errors are skipped. + """ + from sgp4.api import Satrec, jday + import sgp4.omm as omm + + jd, fr = jday( + now.year, now.month, now.day, + now.hour, now.minute, now.second + now.microsecond / 1e6, + ) + out: list[dict] = [] + for rec in elements: + if not isinstance(rec, dict): + continue + sat = Satrec() + try: + omm.initialize(sat, rec) + except (KeyError, ValueError, TypeError): + continue + err, r, _v = sat.sgp4(jd, fr) + if err != 0: + continue + lat, lon, alt = _teme_to_geodetic(r, jd, fr) + norad = rec.get("NORAD_CAT_ID") + out.append({ + "id": str(norad) if norad is not None else "", + "name": rec.get("OBJECT_NAME") or str(norad or ""), + "lat": round(lat, 5), + "lon": round(lon, 5), + "alt_km": round(alt, 2), + "group": group, + }) + return out + + +def _max_epoch(elements: list[dict]) -> str | None: + """Most recent EPOCH across an element set (ISO-8601 lexical max).""" + epochs = [ + str(e["EPOCH"]) for e in elements + if isinstance(e, dict) and e.get("EPOCH") + ] + return max(epochs) if epochs else None + + +def propagate_satnogs_tle( + payload: list[dict], + group: str, + now: datetime, +) -> tuple[list[dict], str | None]: + """Fallback parser for SatNOGS TLE JSON (``[{tle0,tle1,tle2,updated}]``). + + Returns ``(satellites, epoch)`` where epoch is the max ``updated`` time. + Only used when the CelesTrak cache is completely empty. + """ + from sgp4.api import Satrec, jday + + jd, fr = jday( + now.year, now.month, now.day, + now.hour, now.minute, now.second + now.microsecond / 1e6, + ) + out: list[dict] = [] + epochs: list[str] = [] + for rec in payload or []: + if not isinstance(rec, dict): + continue + line1 = rec.get("tle1") + line2 = rec.get("tle2") + if not line1 or not line2: + continue + try: + sat = Satrec.twoline2rv(line1, line2) + except (ValueError, TypeError): + continue + e, r, _v = sat.sgp4(jd, fr) + if e != 0: + continue + lat, lon, alt = _teme_to_geodetic(r, jd, fr) + satnum = getattr(sat, "satnum_str", None) or rec.get("norad_cat_id") + name = (rec.get("tle0") or "").strip().lstrip("0").strip() or str(satnum or "") + out.append({ + "id": str(satnum).strip() or "", + "name": name, + "lat": round(lat, 5), + "lon": round(lon, 5), + "alt_km": round(alt, 2), + "group": group, + }) + if rec.get("updated"): + epochs.append(str(rec["updated"])) + return out, (max(epochs) if epochs else None) + + +async def _group_elements(group: str) -> tuple[list[dict], str | None]: + """CelesTrak GP blob for one group, TTL-cached with a last-good fallback. + + Returns ``(elements, epoch)``. On a fetch failure (403 / "has not updated + since ...") falls back to the previous successful blob for that group. + """ + from live_layers import _get_json, _ttl_get + + url = f"{CELESTRAK_GP}?GROUP={quote(group)}&FORMAT=JSON" + + async def _load() -> list[dict]: + data = await _get_json(url) + if not isinstance(data, list): + raise ValueError(f"unexpected CelesTrak payload for {group}") + if data: + _last_good[group] = data + return data + + key = f"celestrak:gp:{group}" + try: + elements = await _ttl_get(key, SATELLITE_TTL, _load) + except Exception as exc: # noqa: BLE001 + logger.warning("celestrak_fetch_failed group=%s: %s", group, exc) + elements = _last_good.get(group, []) + if not elements: + return [], None + return elements, _max_epoch(elements) + + +async def fetch_satellites( + groups: list[str], + bbox: str | None = None, + limit: int = DEFAULT_LIMIT, +) -> dict: + """Assemble the ``/api/satellites`` payload for the requested groups.""" + from live_layers import _get_json, _ttl_get, filter_points_bbox, parse_bbox + + now = datetime.now(timezone.utc) + satellites: list[dict] = [] + epoch: str | None = None + source = SOURCE_CELESTRAK + + for group in groups: + elements, group_epoch = await _group_elements(group) + if not elements: + continue + if group_epoch and (epoch is None or group_epoch > epoch): + epoch = group_epoch + satellites.extend(propagate_gp(elements, group, now)) + + if not satellites: + # Fallback only when the CelesTrak cache is entirely empty — never + # poll both providers every cycle. + async def _load_satnogs() -> list[dict]: + data = await _get_json(SATNOGS_TLE, params={"format": "json"}) + return data if isinstance(data, list) else [] + + try: + satnogs = await _ttl_get("satnogs:tle", SATELLITE_TTL, _load_satnogs) + except Exception as exc: # noqa: BLE001 + logger.warning("satnogs_fetch_failed: %s", exc) + satnogs = [] + if satnogs: + source = SOURCE_SATNOGS + for group in groups: + rows, sn_epoch = propagate_satnogs_tle(satnogs, group, now) + if sn_epoch and (epoch is None or sn_epoch > epoch): + epoch = sn_epoch + satellites.extend(rows) + + if bbox: + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + satellites = filter_points_bbox( + satellites, minlon, minlat, maxlon, maxlat, limit, + ) + else: + satellites = satellites[:limit] + + return { + "satellites": satellites, + "source": source, + "tle_epoch": epoch, + "timestamp": now.isoformat(), + } diff --git a/app/schemas.py b/app/schemas.py index 799aeb3..1834634 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -4,10 +4,10 @@ from __future__ import annotations from datetime import datetime from enum import Enum -from typing import Optional +from typing import Literal, Optional from uuid import UUID -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator # ─── Enums ─────────────────────────────────────────────────────────────── @@ -63,6 +63,17 @@ class FeedSourceCreate(BaseModel): config: Optional[dict] = None +class FeedSourceUpdate(BaseModel): + """PATCH /api/sources/{id} — only these keys may be set.""" + + model_config = ConfigDict(extra="forbid") + + name: Optional[str] = None + url: Optional[str] = None + config: Optional[dict] = None + enabled: Optional[bool] = None + + class FeedSourceOut(BaseModel): id: UUID name: str @@ -303,6 +314,26 @@ 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.""" @@ -386,3 +417,24 @@ class GeofenceUpdate(BaseModel): geojson: Optional[dict] = None active: Optional[bool] = None + +class ConflictZoneOut(BaseModel): + """One curated conflict theatre as exposed by GET /api/conflicts.""" + + id: str + label: str + severity: Literal["war", "high", "elevated"] + lat: float + lon: float + description: str + eventCount: int + lastUpdated: Optional[datetime] = None + + +class ConflictsOut(BaseModel): + """Response envelope for GET /api/conflicts.""" + + zones: list[ConflictZoneOut] + timestamp: datetime + + diff --git a/app/sources.py b/app/sources.py index c12c303..115b55c 100644 --- a/app/sources.py +++ b/app/sources.py @@ -2,9 +2,15 @@ from __future__ import annotations +import html +import io import json import logging -from datetime import datetime, timezone +import os +import re +import time +import zipfile +from datetime import datetime, timedelta, timezone from email.utils import parsedate_to_datetime import httpx @@ -55,6 +61,35 @@ def event_dedup_key(msg: dict) -> str | None: return url or None +async def existing_event_urls(urls: list[str]) -> set[str]: + """URLs already claimed in event_dedup. Empty input -> empty set.""" + if not urls: + return set() + from sqlalchemy import select + + from database import async_session + from models import event_dedup as event_dedup_table + + async with async_session() as session: + result = await session.execute( + select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls)) + ) + return {row[0] for row in result} + + +async def _publish_unknown(subject: str, events: list[dict]) -> int: + """Publish only events whose URL is not already in event_dedup.""" + keys = [event_dedup_key(e) for e in events] + known = await existing_event_urls([k for k in keys if k]) + published = 0 + for event, key in zip(events, keys): + if key and key in known: + continue + await publish_event(subject, event) + published += 1 + return published + + def _ua_headers() -> dict[str, str]: return {"User-Agent": OSINT_USER_AGENT} @@ -114,6 +149,61 @@ 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: @@ -146,25 +236,59 @@ def parse_gdelt_articles(data: dict) -> list[dict]: return events -async def ingest_gdelt(query: str = "", max_articles: int = 50): - """Fetch articles from the GDELT DOC 2.0 API.""" +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 + 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) - resp.raise_for_status() - data = resp.json() - except (httpx.TransportError, httpx.HTTPStatusError) as exc: + except httpx.TransportError as exc: # gdeltproject.org certs have expired in the wild; HTTP fallback. - logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc) + # 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 + _gdelt_clear_backoff() events = parse_gdelt_articles(data if isinstance(data, dict) else {}) for event in events: await publish_event("events.gdelt", event) @@ -172,6 +296,240 @@ async def ingest_gdelt(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: @@ -283,10 +641,9 @@ async def ingest_eonet(): resp.raise_for_status() data = resp.json() events = parse_eonet_events(data if isinstance(data, dict) else {}) - for event in events: - await publish_event("events.disaster", event) - logger.info("Ingested %d EONET events", len(events)) - return len(events) + published = await _publish_unknown("events.disaster", events) + logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published) + return published # ─── CISA KEV ─────────────────────────────────────────────────────────── @@ -330,10 +687,9 @@ async def ingest_cisa_kev(): resp.raise_for_status() data = resp.json() events = parse_cisa_kev(data if isinstance(data, dict) else {}) - for event in events: - await publish_event("events.disaster", event) - logger.info("Ingested %d CISA KEV rows", len(events)) - return len(events) + published = await _publish_unknown("events.disaster", events) + logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published) + return published # ─── Social Signals (Twitter/X-like placeholder) ──────────────────────── diff --git a/app/static/index.html b/app/static/index.html index 38d1849..28b058a 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -3,10 +3,10 @@ - OSINT//DASHBOARD — Global Situational Awareness Terminal + OSINT// - + @@ -35,12 +35,12 @@ --text: #c8e6f2; --muted: #5f7d95; --topbar-h: 46px; - --dock-h: 62px; + --dock-h: 32px; /* one NEWS ticker; MKT hidden until live */ } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; } body { - font-family: 'Rajdhani', 'Segoe UI', system-ui, sans-serif; + font-family: 'IBM Plex Sans', '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: 'Share Tech Mono', ui-monospace, SFMono-Regular, Menlo, monospace; } + .mono, code, kbd { font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-variant-numeric: tabular-nums; } .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: 'Rajdhani', sans-serif; font-weight: 600; + font-family: 'IBM Plex Sans', 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: 'Orbitron', sans-serif; color: var(--cyan); + font-family: 'IBM Plex Sans', 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: 'Orbitron', sans-serif; font-weight: 700; font-size: 0.95rem; + font-family: 'IBM Plex Sans', 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: 'Share Tech Mono', monospace; font-size: 0.58rem; + font-family: 'IBM Plex 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: 'Share Tech Mono', monospace; font-size: 0.72rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.72rem; color: var(--muted); white-space: nowrap; } .sys-status .sep { opacity: 0.35; } @@ -112,6 +112,10 @@ .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; } } @@ -121,7 +125,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: 'Orbitron', sans-serif; font-size: 0.72rem; font-weight: 700; + font-family: 'IBM Plex Sans', 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; } @@ -143,7 +147,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: 'Rajdhani', sans-serif; font-weight: 600; font-size: 0.88rem; + font-family: 'IBM Plex Sans', 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; @@ -153,6 +157,20 @@ .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 */ @@ -174,11 +192,15 @@ border: 1px solid var(--line-hi); box-shadow: 0 0 16px rgba(53,224,255,0.10); clip-path: polygon(0 6px, 6px 0, calc(100% - 6px) 0, 100% 6px, 100% calc(100% - 6px), calc(100% - 6px) 100%, 6px 100%, 0 calc(100% - 6px)); + 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; } .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: 'Share Tech Mono', monospace; color-scheme: dark; + font-family: 'IBM Plex 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; } @@ -197,7 +219,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: 'Share Tech Mono', monospace !important; font-size: 10px !important; + font-family: 'IBM Plex Mono', monospace !important; font-size: 10px !important; } .leaflet-control-attribution a { color: var(--cyan) !important; } .leaflet-popup-content-wrapper, .leaflet-popup-tip { @@ -227,6 +249,16 @@ filter: drop-shadow(0 0 4px currentColor) drop-shadow(0 1px 2px rgba(0,0,0,0.8)); } .hdg-glyph svg { width: 100%; height: 100%; display: block; } + .hdg-emerg { + animation: emerg-pulse 1.15s ease-in-out infinite; + } + @keyframes emerg-pulse { + 0%, 100% { filter: drop-shadow(0 0 4px #ff5d5d); } + 50% { filter: drop-shadow(0 0 12px #ff5d5d) drop-shadow(0 0 18px #ff5d5d); } + } + @media (prefers-reduced-motion: reduce) { + .hdg-emerg, .role-badge.emergency { animation: none; } + } /* ── Camera marker clusters (neon green, matches the dots) ──── */ .marker-cluster-small, .marker-cluster-medium, .marker-cluster-large { @@ -242,10 +274,25 @@ .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: 'Share Tech Mono', monospace; font-size: 0.68rem; color: var(--muted); + font-family: 'IBM Plex 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); @@ -256,7 +303,7 @@ } .hud-chip { display: flex; align-items: center; gap: 0.45rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'IBM Plex 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); @@ -267,13 +314,14 @@ .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: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'IBM Plex 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); } @@ -284,7 +332,7 @@ } #dvr-toast .gf-alert { background: rgba(255,46,151,0.16); border: 1px solid var(--magenta); - color: var(--text); font-family: 'Share Tech Mono', monospace; + color: var(--text); font-family: 'IBM Plex Mono', monospace; font-size: 0.68rem; padding: 0.4rem 0.6rem; margin-bottom: 0.35rem; border-radius: 4px; } @@ -292,17 +340,19 @@ /* ── Layer control panel (dark HUD) ── */ #layer-panel { position: absolute; top: 58px; left: 12px; z-index: 600; - width: 268px; max-height: calc(100% - 74px); overflow: hidden; + width: min(320px, calc(100% - 24px)); max-width: 320px; + 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: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; + font-family: 'IBM Plex Sans', 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); @@ -322,24 +372,33 @@ .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(--magenta); box-shadow: 0 0 7px var(--magenta); border-radius: 1px; transform: rotate(45deg); } + .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.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; } .lp-dot.vessels { background: #2dd4bf; box-shadow: 0 0 7px #2dd4bf; } .lp-dot.radar { background: #38bdf8; box-shadow: 0 0 7px #38bdf8; } .lp-dot.thermal { background: #f97316; box-shadow: 0 0 7px #f97316; } + .lp-dot.sar { background: #86efac; box-shadow: 0 0 7px #86efac; } .lp-dot.wfigs { background: #ef4444; box-shadow: 0 0 7px #ef4444; } .lp-dot.trains { background: #c084fc; box-shadow: 0 0 7px #c084fc; } .lp-dot.storms { background: #f472b6; box-shadow: 0 0 7px #f472b6; } - .lp-count { font-family: 'Share Tech Mono', monospace; font-size: 0.7rem; color: var(--cyan); } + .lp-dot.night { + background: linear-gradient(90deg, #0b1c33 50%, #ffb454 50%); + 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-sub { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; } - .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 { 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 input[type="range"] { flex: 1; accent-color: var(--cyan); height: 4px; cursor: pointer; } - .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-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-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: 'Rajdhani', 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: 'IBM Plex Sans', 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; } @@ -348,6 +407,111 @@ .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-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 { + position: absolute; top: 50%; left: 50%; + transform: translate(-50%, -50%); + z-index: 640; + width: min(420px, calc(100% - 96px)); + max-height: calc(100% - 88px); + overflow: auto; + background: rgba(6,11,20,0.94); backdrop-filter: blur(10px); + border: 1px solid var(--line-hi); border-radius: 6px; + box-shadow: 0 0 28px rgba(53,224,255,0.18); + padding: 0.85rem 1rem 1rem; + 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)); + } + .cheat-sheet[hidden] { display: none !important; } + .cheat-sheet h3 { + font-family: 'IBM Plex Sans', 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; } + .cheat-sheet dt kbd { + display: inline-block; min-width: 1.4em; text-align: center; + border: 1px solid var(--line-hi); border-radius: 3px; padding: 0.12rem 0.4rem; + color: var(--cyan); font-size: 0.72rem; background: var(--bg-1); + } + .cheat-sheet dd { margin: 0; font-size: 0.78rem; color: var(--muted); } + #swpc-chip { color: var(--text); letter-spacing: 0.08em; } + #swpc-chip.swpc-storm { color: var(--amber); text-shadow: 0 0 8px rgba(255,180,84,0.45); } + /* ── Place dossier (“What’s here?”) ── */ + #place-dossier { + position: absolute; top: 58px; right: 54px; z-index: 650; + width: 280px; max-height: calc(100% - 90px); overflow: hidden; + background: rgba(6,11,20,0.90); 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: none; 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)); + } + #place-dossier.open { display: flex; } + .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; + 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; + 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.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-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; + text-transform: uppercase; color: var(--muted); margin-top: 0.15rem; + } + .pd-list { display: flex; flex-direction: column; gap: 0.18rem; } + .pd-item { + 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; + } + .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-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; } /* ── Camera / blip popup thumbnails ── */ .cam-pop { min-width: 210px; max-width: 260px; } @@ -356,7 +520,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: 'Share Tech 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: 'IBM Plex 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; } @@ -369,7 +533,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: 'Share Tech Mono', monospace; + display: inline-block; font-family: 'IBM Plex 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; @@ -378,9 +542,14 @@ .role-badge.civilian { color: #7dd3fc; border: 1px solid #38bdf8; background: rgba(56,189,248,0.1); } .role-badge.government { color: #facc15; border: 1px solid #facc15; background: rgba(250,204,21,0.12); } .role-badge.firefighter { color: #fb923c; border: 1px solid #fb923c; background: rgba(251,146,60,0.12); } + .role-badge.emergency { + color: #ff5d5d; border: 1px solid #ff5d5d; background: rgba(255,93,93,0.16); + animation: emerg-pulse 1.4s ease-in-out infinite; + } .blip-pop { min-width: 200px; max-width: 260px; } - .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-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-desc { font-size: 0.72rem; color: var(--text); line-height: 1.35; margin-top: 0.15rem; } /* ── Sub-views (News / Events / Alerts / ... ) ── */ .subview { @@ -388,7 +557,7 @@ max-width: 1280px; margin: 0 auto; } .subview > h2 { - font-family: 'Orbitron', sans-serif; font-size: 0.95rem; font-weight: 700; + font-family: 'IBM Plex Sans', 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; } @@ -400,13 +569,13 @@ box-shadow: 0 0 18px rgba(53,224,255,0.05); } .panel h3 { - font-size: 0.68rem; font-family: 'Orbitron', sans-serif; font-weight: 700; + font-size: 0.68rem; font-family: 'IBM Plex Sans', 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: 'Rajdhani', sans-serif; } + 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; } 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); } @@ -419,7 +588,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: 'Orbitron', sans-serif; font-size: 1.5rem; font-weight: 700; color: var(--text); letter-spacing: 0.04em; } + .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.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 { @@ -432,14 +601,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: 'Rajdhani', sans-serif; + font-size: 0.88rem; font-family: 'IBM Plex Sans', 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: 'Share Tech Mono', monospace; } + .news-updated { font-size: 0.7rem; color: var(--muted); font-family: 'IBM Plex 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; @@ -450,19 +619,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: '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-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-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: 'Rajdhani', 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: 'IBM Plex Sans', 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: 'Share Tech 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: 'IBM Plex 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: '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-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 { 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; } @@ -471,10 +640,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: '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-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-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: 'Share Tech Mono', monospace; white-space: nowrap; flex-shrink: 0; } + .news-time { font-size: 0.68rem; color: var(--muted); font-family: 'IBM Plex 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); } @@ -486,14 +655,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: '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-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-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: 'Share Tech Mono', monospace; } + .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'IBM Plex 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: 'Share Tech 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: 'IBM Plex 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); } @@ -509,17 +678,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: 'Share Tech Mono', monospace; color-scheme: dark; + font-family: 'IBM Plex 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: 'Share Tech Mono', monospace; min-height: 1.1rem; } + .set-saved { color: var(--green); font-size: 0.75rem; font-family: 'IBM Plex 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: 'Share Tech Mono', monospace; } + .sys-row .v { font-family: 'IBM Plex Mono', monospace; } /* ═══════════════ BOTTOM DOCK: tickers ═══════════════ */ .dock { @@ -536,19 +705,22 @@ .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: 'Orbitron', sans-serif; font-size: 0.62rem; font-weight: 700; + font-family: 'IBM Plex Sans', 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(--magenta); color: #1c0311; } + .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%; } .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: 90s; } + .ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */ .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; } @@ -557,29 +729,31 @@ font-size: 0.82rem; padding: 0 1rem; color: var(--text); text-decoration: none; font-weight: 500; } - .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 .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 .chg.up { color: var(--green); } .tick-item .chg.down { color: var(--red); } .tick-item .chg.flat { 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 .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 .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: '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 { 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.critical { background: var(--red); } .tick-item .b-tag.high { background: var(--amber); } + .tick-item .b-tag.medium { background: var(--cyan); color: #041018; } + .tick-item .b-tag.low { background: var(--muted); color: #041018; } .tick-item.brief:hover { color: var(--magenta); } .tick-item.standby { color: var(--muted); opacity: 0.75; } .tick-item.standby .price { color: var(--muted); } .tick-sep { color: var(--line-hi); } .tick-tag { display: flex; align-items: center; flex-shrink: 0; padding: 0 0.8rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); border-left: 1px solid var(--line); } @@ -595,16 +769,16 @@ } .boot.gone { opacity: 0; pointer-events: none; } .boot-inner { text-align: center; } - .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-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-title span { color: var(--cyan); } - .boot-sub { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); letter-spacing: 0.3em; margin-top: 0.5rem; } + .boot-sub { font-family: 'IBM Plex 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: 56px; } + :root { --topbar-h: 42px; --dock-h: 32px; } .tick-label { min-width: 56px; padding: 0 0.5rem; } .tick-tag { display: none; } .hud-chips { display: none; } @@ -640,6 +814,8 @@ flex: 1 1 8rem; min-width: 0; } + #chokepoint-label, .chokepoint-btns { display: none; } + #chokepoint-select { display: block; } .map-stage { flex: 1 1 auto; height: auto; @@ -670,11 +846,26 @@ 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; margin-right: 8px; } + #place-dossier { + top: auto; + right: 8px; + left: 8px; + bottom: 56px; + width: auto; + max-height: 36vh; + } } @media (prefers-reduced-motion: reduce) { .tick-track { animation: none; } @@ -701,8 +892,7 @@
◢◤
-
OSINT//DASHBOARD
-
GLOBAL SITUATIONAL AWARENESS TERMINAL
+
OSINT//
@@ -713,7 +903,10 @@ --:--:-- UTC | — + +
+ SIGN IN @@ -748,13 +941,18 @@ + Strait + +
-
-
+ @@ -766,6 +964,21 @@
Opacity 100%
+
+
+ + + +
+
+
+
+
+
+ + off +
+
@@ -793,14 +1006,14 @@
- + 0
Opacity 100%
- + 0
@@ -814,27 +1027,30 @@
-
Geolocated events from the ingest pipeline. Color = source type.
- + 0
-
LLM-estimated locations from the 15-min brief. Pins only for critical/high.
+
+
+
+ + 0 +
- + IEM
Opacity 70%
-
IEM NEXRAD over CONUS, RainViewer elsewhere. Tiles load in the browser.
- + 0
@@ -844,9 +1060,16 @@ VIIRS
+
+
+ + 7d +
+
Opacity 80%
+
- + 0
@@ -858,37 +1081,38 @@
- + 0
-
Magenta = military · orange = firefighting · 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.
- -
-
No Leaflet.Draw — click vertices, double-click to close. Saved to POST /api/geofences.
-
-
-
- + 0
+
+
+ + 0 +
+

Fire heat intensity

@@ -899,18 +1123,48 @@
+
Initializing…
FIRMS —
CAMS —
BLIPS —
NEWS —
+
ARTICLES —
+
+
live
+
@@ -1023,7 +1277,7 @@ -
+

⇪ Data Ingestion

Manually trigger feed pulls & NATS processing

@@ -1056,7 +1310,7 @@
-
+

⚿ API Keys

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

@@ -1083,7 +1337,7 @@
-
+

News Summarizer

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

@@ -1134,8 +1388,8 @@
- - + +
@@ -1166,8 +1420,8 @@ -