Elffuss BraidHub

kikocis/osiris public

Merge PRs #164, #162, and #161 with bug fixes

This commit merges:
- PR #164 (Maritime tracking via aisstream.io) by Iida
- PR #162 (CasaOS icon/thumbnail fix) by Lorenzo Argentieri
- PR #161 (Australia CCTV camera functionality) by Beckam White

Includes additional fixes:
- Resolved 'ws' module compilation error in edge runtime by adding serverExternalPackages
- Fixed LayerPanel counter incorrectly displaying 0 for Maritime layer before WebSocket initialization
- Updated VULN SWEEP backend validation to safely permit single-host (/32) CIDR sweeps
Changesetc867dff8b92ffcf70fbcc6f736f200fc1c9d76123e3fe0306bf5f7b895d920f4
AuthorGemini CLI <gemini@example.com> · 2026-05-23 13:56 -04:00
CommitterGemini CLI <gemini@example.com> · 2026-05-23 13:56 -04:00
Parents35361bd0a86f

Browse the files at this changeset

14 files changed

added .dockerignore +34 −0
@@ -0,0 +1,34 @@
1+# Dependencies & build output (rebuilt inside image)
2+node_modules
3+.next
4+out
5+build
6+
7+# Local env / secrets
8+.env
9+.env.local
10+.env*.local
11+
12+# VCS & tooling
13+.git
14+.gitignore
15+.github
16+
17+# Large fork artifacts not needed at runtime
18+*.diff
19+fork.diff
20+ito69_fork.diff
21+
22+# Docs / meta
23+README.md
24+AGENTS.md
25+CLAUDE.md
26+DO_NOT_PUSH.md
27+LICENSE
28+
29+# OS / editor noise
30+.DS_Store
31+*.log
32+npm-debug.log*
33+.vscode
34+.idea
added .env.template +72 −0
@@ -0,0 +1,72 @@
1+# ═══════════════════════════════════════════════════════════════════════════
2+# OSIRIS — Environment Template
3+# Copy this file to `.env` (or `.env.local`) and fill in values as needed.
4+#
5+# IMPORTANT — read before filling anything in:
6+# OSIRIS works fully WITHOUT any third-party API keys. Aviation, maritime,
7+# satellites, fires, earthquakes, weather, news, CVEs, etc. all use public
8+# keyless feeds (adsb.lol, celestrak.org, NASA FIRMS open CSV, USGS, …).
9+#
10+# As of this revision the application code only actually reads SCANNER_URL
11+# and SCANNER_KEY. The other keys below are OPTIONAL and reserved for higher
12+# rate limits / future data sources — set them only if you extend the code or
13+# hit rate limits on the public feeds.
14+# ═══════════════════════════════════════════════════════════════════════════
15+
16+
17+# ─────────────────────────────────────────────────────────────────────────
18+# RECON SCANNER BACKEND ── the ONLY keys the current code consumes ──
19+# Powers the RECON toolkit (quick/ssl/headers/rdns/subdomains/tech/whois/
20+# geoloc/vuln scans). Requires running the separate OSIRIS scanner backend.
21+# SCANNER_KEY here MUST equal the backend's OSIRIS_KEY. Generate one with:
22+# openssl rand -hex 32
23+# Leave both empty to simply disable the RECON features (UI returns 503).
24+# ─────────────────────────────────────────────────────────────────────────
25+SCANNER_URL=
26+SCANNER_KEY=
27+
28+
29+# ─────────────────────────────────────────────────────────────────────────
30+# OPTIONAL DATA-SOURCE KEYS (not read by current code — future / upgrades)
31+# ─────────────────────────────────────────────────────────────────────────
32+
33+# NASA FIRMS — active wildfire hotspots.
34+# Free, instant. Enter an email at the page below and the MAP_KEY is emailed
35+# to you (looks like 'abcdef1234567890abcdef1234567890'). Limit: 5000 req /
36+# 10 min. The app already uses the keyless FIRMS CSV; a key only matters if
37+# you switch to the per-area FIRMS API.
38+# Get it: https://firms.modaps.eosdis.nasa.gov/api/map_key/
39+FIRMS_API_KEY=
40+
41+# OpenSky Network — aviation (higher rate limits than the keyless feed).
42+# Free account. Since March 2025 OpenSky uses OAuth2 (username/password auth
43+# is dropped). Create an account, open the Account page, create a new API
44+# client, and copy the client_id / client_secret.
45+# Get it: https://opensky-network.org/ (Account → API client)
46+OPENSKY_CLIENT_ID=
47+OPENSKY_CLIENT_SECRET=
48+
49+# N2YO — satellite tracking / pass predictions.
50+# Free. Register, then Profile page → scroll down → "generate API key".
51+# The key cannot be changed once issued. Limit: 1000 req / hour.
52+# Get it: https://www.n2yo.com/login/register/ (then Profile)
53+N2YO_API_KEY=
54+
55+# aisstream.io — live maritime AIS vessel positions via WebSocket.
56+# Free. Register, then create a key on the API Keys page. Used in the
57+# subscription message to wss://stream.aisstream.io/v0/stream.
58+# Get it: https://aisstream.io/ (sign up → API Keys)
59+AIS_API_KEY=
60+
61+
62+# ─────────────────────────────────────────────────────────────────────────
63+# RUNTIME
64+# ─────────────────────────────────────────────────────────────────────────
65+# Host port the web UI is published on (container always listens on 3000).
66+# Change this if 3000 is already taken on your host.
67+OSIRIS_PORT=3000
68+
69+# Set by the Docker image already — override only if needed.
70+# NODE_ENV=production
71+# PORT=3000
72+# HOSTNAME=0.0.0.0
added DOCKER.md +149 −0
@@ -0,0 +1,149 @@
1+# Self-Hosting OSIRIS with Docker
2+
3+OSIRIS ships as a self-contained Next.js standalone build. This guide covers
4+running it with Docker / Docker Compose, deploying it as a [CasaOS](https://casaos.io)
5+app, and configuring the optional API keys.
6+
7+> **TL;DR:** OSIRIS runs fully **without any API keys**. All core feeds
8+> (aviation, satellites, fires, earthquakes, weather, news, CVEs) use public
9+> keyless sources. Keys only matter for the optional RECON scanner backend and
10+> for raising rate limits on a few feeds.
11+
12+---
13+
14+## 1. Docker Compose (recommended)
15+
16+```bash
17+git clone https://github.com/simplifaisoul/osiris.git
18+cd osiris
19+
20+# optional: configure keys / scanner backend
21+cp .env.template .env # then edit .env
22+
23+docker compose up -d
24+```
25+
26+Open <http://localhost:3000>.
27+
28+What the compose file does:
29+
30+- **`image:` + `build:`** — `image:` points at a prebuilt registry image; the
31+ `build:` block is a fallback. `docker compose up -d` uses the registry image
32+ if it's available locally or pullable, otherwise builds from the local
33+ `Dockerfile`. Run `docker compose pull` to fetch the latest published image.
34+- **`env_file: .env` (`required: false`)** — if a `.env` file exists its
35+ values are injected into the container; if it's missing, OSIRIS still starts
36+ with the keyless feeds.
37+- **`ports: ${OSIRIS_PORT:-3000}:3000`** — the web UI. The container always
38+ listens on 3000; the published **host** port is `OSIRIS_PORT` (default
39+ `3000`). Set `OSIRIS_PORT` in `.env` to remap it, e.g. `OSIRIS_PORT=3005`
40+ when 3000 is already in use — no need to edit the compose file.
41+- **`restart: unless-stopped`** — survives reboots.
42+
43+Common commands:
44+
45+```bash
46+docker compose pull # fetch latest published image
47+docker compose logs -f # follow logs
48+docker compose up -d --build # rebuild locally after pulling new code
49+docker compose down # stop & remove
50+```
51+
52+### Pull the prebuilt image from GHCR
53+
54+A prebuilt multi-arch-friendly image is published to the GitHub Container
55+Registry, so you can run OSIRIS without building anything:
56+
57+```bash
58+docker pull ghcr.io/aiacos/osiris:latest # or a pinned tag, e.g. :0.1.0
59+docker run -d --name osiris \
60+ -p 3005:3000 --env-file .env --restart unless-stopped \
61+ ghcr.io/aiacos/osiris:latest
62+```
63+
64+> If the package is **private**, authenticate first with a GitHub token that
65+> has `read:packages`:
66+> `echo $TOKEN | docker login ghcr.io -u <github-user> --password-stdin`.
67+> Make it public from the package's **Settings → Danger Zone → Change
68+> visibility** to allow anonymous pulls.
69+
70+### Plain `docker run`
71+
72+```bash
73+docker build -t osiris:latest .
74+docker run -d --name osiris -p 3000:3000 --env-file .env --restart unless-stopped osiris:latest
75+```
76+
77+### Image details
78+
79+Multi-stage build on `node:22-alpine`, runs as a non-root user (`nextjs`,
80+uid 1001), serves Next.js standalone via `node server.js` on port 3000.
81+Final image is ~220 MB. Build excludes `node_modules`, `.next`, `.git` and the
82+repo's large `*.diff` artifacts via `.dockerignore`.
83+
84+---
85+
86+## 2. CasaOS
87+
88+The compose file includes an `x-casaos:` metadata block (title, description,
89+icon, port map, env descriptions) that plain Docker Compose ignores but CasaOS
90+reads.
91+
92+**Install:**
93+
94+1. On the CasaOS host, clone the repo somewhere persistent (e.g.
95+ `/DATA/AppData/osiris`).
96+2. CasaOS dashboard → **`+`** → **Install a customized app** → paste the
97+ contents of `docker-compose.yml`.
98+ *(or simply run `docker compose up -d` from the cloned directory).*
99+3. OSIRIS appears on the dashboard with its icon, reachable on host port
100+ `3000` (or whatever `OSIRIS_PORT` you set in `.env`).
101+
102+The app icon is the gold Eye-of-Horus mark in
103+`public/casaos-icon.png` (512×512 PNG), referenced by the `icon:` URL in the
104+metadata.
105+
106+> CasaOS stores imported compose files under `/var/lib/casaos/apps/`, so a
107+> relative `build:` context may not resolve there. If importing the YAML
108+> directly, either build/tag `osiris:latest` first
109+> (`docker build -t osiris:latest /path/to/osiris`) or set `image:` to a
110+> prebuilt registry image.
111+
112+---
113+
114+## 3. API keys & data sources
115+
116+Copy `.env.template` to `.env` and fill in only what you need.
117+
118+### What the code actually reads today
119+
120+| Variable | Purpose | Required for |
121+|----------|---------|--------------|
122+| `SCANNER_URL` | RECON scanner backend base URL (e.g. `http://scanner:7700`) | RECON toolkit (quick/ssl/headers/rdns/subdomains/tech/whois/geoloc/vuln) |
123+| `SCANNER_KEY` | Shared secret; **must equal the backend's `OSIRIS_KEY`** | RECON toolkit |
124+
125+Without `SCANNER_URL`/`SCANNER_KEY` the RECON endpoints return `503` and the
126+rest of OSIRIS works normally. Generate a key with `openssl rand -hex 32`.
127+
128+### Optional keys (reserved / for higher rate limits)
129+
130+These are documented for completeness and forward-compatibility. The current
131+data routes use **keyless** public feeds, so these are not consumed yet — set
132+them only if you extend the relevant route or hit rate limits.
133+
134+| Variable | Service | How to get it (all free) |
135+|----------|---------|--------------------------|
136+| `FIRMS_API_KEY` | NASA FIRMS active fires | Enter an email at <https://firms.modaps.eosdis.nasa.gov/api/map_key/> — the `MAP_KEY` is emailed instantly. Limit 5000 req / 10 min. |
137+| `OPENSKY_CLIENT_ID` / `OPENSKY_CLIENT_SECRET` | OpenSky aviation | Create an account at <https://opensky-network.org/>, open **Account → API client**, create a client and copy id/secret. **OAuth2 only since March 2025** (username/password auth removed). |
138+| `N2YO_API_KEY` | N2YO satellites | Register at <https://www.n2yo.com/login/register/>, then **Profile → generate API key**. Limit 1000 req / hour; key can't be regenerated. |
139+| `AIS_API_KEY` | aisstream.io maritime | Sign up at <https://aisstream.io/>, create a key on the **API Keys** page. Used over `wss://stream.aisstream.io/v0/stream`. |
140+
141+> Keep `.env` out of version control — it is already in `.gitignore`. Only
142+> `.env.template` (no secrets) is committed.
143+
144+### Keyless sources (no configuration needed)
145+
146+Aviation → `adsb.lol` · Satellites → `celestrak.org` (TLE) · Fires →
147+NASA FIRMS open-data CSV · Earthquakes → USGS · Weather → NASA EONET · Space
148+weather → NOAA SWPC · CVEs → NVD · News → public RSS / HLS streams · CCTV →
149+public traffic-authority feeds.
modified README.md +45 −8
@@ -111,20 +111,57 @@
111111
112112 Open [http://localhost:3000](http://localhost:3000)
113113
114+### Docker / Self-Hosting
115+
116+```bash
117+git clone https://github.com/simplifaisoul/osiris.git
118+cd osiris
119+cp .env.template .env # optional — configure keys / port
120+docker compose up -d
121+```
122+
123+Open [http://localhost:3000](http://localhost:3000). The image is a multi-stage
124+`node:22-alpine` standalone build (~220 MB, non-root). The compose file also
125+carries CasaOS app metadata (`x-casaos:`) for one-click install on
126+[CasaOS](https://casaos.io). See **[DOCKER.md](DOCKER.md)** for the full Docker,
127+CasaOS and API-key guide.
128+
129+**Prebuilt image (GHCR)** — skip the build and pull it directly:
130+
131+```bash
132+docker pull ghcr.io/aiacos/osiris:latest
133+docker run -d -p 3000:3000 --env-file .env ghcr.io/aiacos/osiris:latest
134+```
135+
136+**Custom port** — the container always listens on `3000`; set `OSIRIS_PORT` in
137+`.env` to change the published host port (e.g. `OSIRIS_PORT=3005`) without
138+editing the compose file.
139+
114140 ### Environment Variables
115141
116-Create a `.env.local` file:
142+OSIRIS works **fully without any API keys** — all core feeds use public,
143+keyless sources. Copy [`.env.template`](.env.template) to `.env` and set only
144+what you need:
117145
118146 ```env
119-# Optional — enhances flight data
120-OPENSKY_USERNAME=your_username
121-OPENSKY_PASSWORD=your_password
122-
123-# Optional — satellite tracking
124-N2YO_API_KEY=your_key
147+# Published host port (container always listens on 3000). Default: 3000
148+OSIRIS_PORT=3000
149+
150+# RECON scanner backend (the only vars the current code reads).
151+# SCANNER_KEY must match the backend's OSIRIS_KEY — generate with: openssl rand -hex 32
152+SCANNER_URL=
153+SCANNER_KEY=
154+
155+# Optional, for higher rate limits / future sources (see DOCKER.md for signup links)
156+FIRMS_API_KEY= # NASA FIRMS — firms.modaps.eosdis.nasa.gov/api/map_key/
157+OPENSKY_CLIENT_ID= # OpenSky OAuth2 (since Mar 2025) — opensky-network.org
158+OPENSKY_CLIENT_SECRET=
159+N2YO_API_KEY= # N2YO satellites — n2yo.com (Profile → API key)
160+AIS_API_KEY= # aisstream.io maritime
125161 ```
126162
127-> Most features work without any API keys. The platform is designed to be functional out of the box.
163+> Without `SCANNER_URL`/`SCANNER_KEY` the RECON toolkit returns `503`; every
164+> other layer works out of the box. `.env` is gitignored — only the template is committed.
128165
129166 ---
130167
modified docker-compose.yml +73 −6
@@ -1,15 +1,82 @@
1+name: osiris
12 services:
23 osiris:
4+ # Pulls the prebuilt image from GitHub Container Registry. The `build:`
5+ # block is kept as a fallback: `docker compose up -d` uses the registry
6+ # image if present/pullable, otherwise builds locally from the Dockerfile.
7+ # Run `docker compose pull` to fetch the latest published image.
8+ image: ghcr.io/aiacos/osiris:latest
39 build:
410 context: .
511 dockerfile: Dockerfile
12+ container_name: osiris
13+ # Host port is configurable via OSIRIS_PORT in .env (defaults to 3000).
614 ports:
7- - "3000:3000"
15+ - "${OSIRIS_PORT:-3000}:3000"
16+ # Optional API keys / scanner backend — copy .env.template to .env and
17+ # fill in what you need. Missing file is ignored (keyless feeds still work).
18+ env_file:
19+ - path: .env
20+ required: false
821 environment:
922 - NODE_ENV=production
10- # Optional — uncomment and fill in to enhance data sources
11- # - OPENSKY_USERNAME=your_username
12- # - OPENSKY_PASSWORD=your_password
13- # - N2YO_API_KEY=your_key
14- # - AIS_API_KEY=your_key
23+ - PORT=3000
24+ - HOSTNAME=0.0.0.0
1525 restart: unless-stopped
26+
27+# ── CasaOS app-store metadata (ignored by plain Docker Compose) ──
28+x-casaos:
29+ architectures:
30+ - amd64
31+ - arm64
32+ main: osiris
33+ author: simplifaisoul
34+ developer: simplifaisoul
35+ category: Network
36+ description:
37+ en_us: >-
38+ OSIRIS is a production-grade open-source OSINT situational-awareness
39+ dashboard. It aggregates real-time global intelligence across aviation,
40+ maritime, CCTV networks, seismic activity, wildfires, news feeds,
41+ weather, space weather, cyber threats (CVEs) and conflict zones into a
42+ single GPU-accelerated MapLibre interface. Most features work with no
43+ API keys.
44+ tagline:
45+ en_us: Real-time global OSINT intelligence dashboard
46+ title:
47+ en_us: OSIRIS
48+ icon: https://raw.githubusercontent.com/Aiacos/osiris/master/public/casaos-icon.png
49+ thumbnail: https://raw.githubusercontent.com/Aiacos/osiris/master/public/og-image.png
50+ screenshot_link:
51+ - https://raw.githubusercontent.com/Aiacos/osiris/master/public/og-image.png
52+ scheme: http
53+ hostname: ""
54+ port_map: "3000"
55+ index: /
56+ webui_port: 3000
57+ envs:
58+ - container: SCANNER_URL
59+ description:
60+ en_us: "(Optional) RECON scanner backend URL, e.g. http://scanner:7700"
61+ - container: SCANNER_KEY
62+ description:
63+ en_us: "(Optional) RECON scanner shared secret (must match backend OSIRIS_KEY)."
64+ - container: FIRMS_API_KEY
65+ description:
66+ en_us: "(Optional) NASA FIRMS API key for active-fire data."
67+ - container: AIS_API_KEY
68+ description:
69+ en_us: "(Optional) aisstream.io key for maritime vessel tracking."
70+ - container: OPENSKY_CLIENT_ID
71+ description:
72+ en_us: "(Optional) OpenSky OAuth2 client id for higher aircraft rate limits."
73+ - container: OPENSKY_CLIENT_SECRET
74+ description:
75+ en_us: "(Optional) OpenSky OAuth2 client secret."
76+ - container: N2YO_API_KEY
77+ description:
78+ en_us: "(Optional) N2YO key for satellite tracking."
79+ ports:
80+ - container: "3000"
81+ description:
82+ en_us: "Web UI (HTTP)."
modified next.config.ts +17 −16
@@ -1,16 +1,17 @@
1-import type { NextConfig } from "next";
2-
3-const nextConfig: NextConfig = {
4- output: 'standalone',
5- transpilePackages: ['react-map-gl', 'mapbox-gl', 'maplibre-gl'],
6- typescript: {
7- ignoreBuildErrors: true,
8- },
9- images: {
10- remotePatterns: [
11- { protocol: 'https', hostname: '**' },
12- ],
13- },
14-};
15-
16-export default nextConfig;
1+import type { NextConfig } from "next";
2+
3+const nextConfig: NextConfig = {
4+ output: 'standalone',
5+ serverExternalPackages: ['ws'],
6+ transpilePackages: ['react-map-gl', 'mapbox-gl', 'maplibre-gl'],
7+ typescript: {
8+ ignoreBuildErrors: true,
9+ },
10+ images: {
11+ remotePatterns: [
12+ { protocol: 'https', hostname: '**' },
13+ ],
14+ },
15+};
16+
17+export default nextConfig;
modified package-lock.json +34 −1
@@ -19,13 +19,15 @@
1919 "react-map-gl": "^8.1.1",
2020 "rss-parser": "^3.13.0",
2121 "satellite.js": "^7.0.0",
22- "sharp": "^0.34.5"
22+ "sharp": "^0.34.5",
23+ "ws": "^8.21.0"
2324 },
2425 "devDependencies": {
2526 "@tailwindcss/postcss": "^4",
2627 "@types/node": "^20",
2728 "@types/react": "^19",
2829 "@types/react-dom": "^19",
30+ "@types/ws": "^8.18.1",
2931 "eslint": "^9",
3032 "eslint-config-next": "16.2.6",
3133 "tailwindcss": "^4",
@@ -1718,6 +1720,16 @@
17181720 "@types/geojson": "*"
17191721 }
17201722 },
1723+ "node_modules/@types/ws": {
1724+ "version": "8.18.1",
1725+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
1726+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
1727+ "dev": true,
1728+ "license": "MIT",
1729+ "dependencies": {
1730+ "@types/node": "*"
1731+ }
1732+ },
17211733 "node_modules/@typescript-eslint/eslint-plugin": {
17221734 "version": "8.59.3",
17231735 "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.3.tgz",
@@ -7220,6 +7232,27 @@
72207232 "node": ">=0.10.0"
72217233 }
72227234 },
7235+ "node_modules/ws": {
7236+ "version": "8.21.0",
7237+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
7238+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
7239+ "license": "MIT",
7240+ "engines": {
7241+ "node": ">=10.0.0"
7242+ },
7243+ "peerDependencies": {
7244+ "bufferutil": "^4.0.1",
7245+ "utf-8-validate": ">=5.0.2"
7246+ },
7247+ "peerDependenciesMeta": {
7248+ "bufferutil": {
7249+ "optional": true
7250+ },
7251+ "utf-8-validate": {
7252+ "optional": true
7253+ }
7254+ }
7255+ },
72237256 "node_modules/xml2js": {
72247257 "version": "0.5.0",
72257258 "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz",
modified package.json +3 −1
@@ -20,13 +20,15 @@
2020 "react-map-gl": "^8.1.1",
2121 "rss-parser": "^3.13.0",
2222 "satellite.js": "^7.0.0",
23- "sharp": "^0.34.5"
23+ "sharp": "^0.34.5",
24+ "ws": "^8.21.0"
2425 },
2526 "devDependencies": {
2627 "@tailwindcss/postcss": "^4",
2728 "@types/node": "^20",
2829 "@types/react": "^19",
2930 "@types/react-dom": "^19",
31+ "@types/ws": "^8.18.1",
3032 "eslint": "^9",
3133 "eslint-config-next": "16.2.6",
3234 "tailwindcss": "^4",
added public/casaos-icon.png +0 −0

Binary content is not shown. View the file.

modified src/app/api/maritime/route.ts +103 −3
@@ -1,9 +1,9 @@
11 import { NextResponse } from 'next/server';
2+import WebSocket from 'ws';
23
34 /**
45 * OSIRIS — Maritime Intelligence
5- * Major global ports, naval bases, and shipping chokepoints.
6- * Static dataset — zero external API calls.
6+ * Real-time AIS vessel tracking via aisstream.io + Static global ports.
77 */
88
99 const PORTS = [
@@ -66,14 +66,114 @@
6666 { name: 'Lombok Strait', lat: -8.47, lng: 115.72, traffic: 'Alt Malacca', risk: 'LOW' },
6767 ];
6868
69+// --- Global AIS Stream Client (In-Memory Cache) ---
70+// Note: In a true serverless environment, this state would reset per invocation.
71+// For Next.js dev server or Node.js Docker container, this will persist.
72+
73+const globalForAis = globalThis as unknown as {
74+ shipsCache: Map<number, any>;
75+ isAisConnecting: boolean;
76+};
77+
78+if (!globalForAis.shipsCache) {
79+ globalForAis.shipsCache = new Map();
80+ globalForAis.isAisConnecting = false;
81+}
82+
83+const shipsCache = globalForAis.shipsCache;
84+
85+function connectAisStream() {
86+ if (globalForAis.isAisConnecting) return;
87+ const apiKey = process.env.AIS_API_KEY;
88+ if (!apiKey) return;
89+
90+ globalForAis.isAisConnecting = true;
91+ let ws: WebSocket;
92+
93+ try {
94+ ws = new WebSocket("wss://stream.aisstream.io/v0/stream");
95+ } catch (e) {
96+ globalForAis.isAisConnecting = false;
97+ return;
98+ }
99+
100+ ws.on("open", () => {
101+ globalForAis.isAisConnecting = false;
102+ const subscriptionMessage = {
103+ APIKey: apiKey,
104+ // Global bounding box to catch major movement
105+ BoundingBoxes: [[[-90, -180], [90, 180]]],
106+ FilterMessageTypes: ["PositionReport"]
107+ };
108+ ws.send(JSON.stringify(subscriptionMessage));
109+ });
110+
111+ ws.on("message", (data) => {
112+ try {
113+ const parsed = JSON.parse(data.toString());
114+ if (parsed.MessageType === "PositionReport" && parsed.Message?.PositionReport) {
115+ const report = parsed.Message.PositionReport;
116+ const mmsi = parsed.MetaData?.MMSI || report.UserID;
117+
118+ if (!mmsi) return;
119+
120+ shipsCache.set(mmsi, {
121+ id: mmsi,
122+ mmsi: mmsi,
123+ lat: report.Latitude,
124+ lng: report.Longitude,
125+ speed: report.Sog,
126+ heading: report.TrueHeading || report.Cog,
127+ timestamp: Date.now()
128+ });
129+
130+ // Limit cache size to prevent memory leak (latest 5000 ships)
131+ if (shipsCache.size > 5000) {
132+ const firstKey = shipsCache.keys().next().value;
133+ if (firstKey) shipsCache.delete(firstKey);
134+ }
135+ }
136+ } catch (e) {
137+ // ignore parse errors
138+ }
139+ });
140+
141+ ws.on("close", () => {
142+ globalForAis.isAisConnecting = false;
143+ setTimeout(connectAisStream, 5000); // Reconnect
144+ });
145+
146+ ws.on("error", () => {
147+ ws.close();
148+ });
149+}
150+
151+// Start connection process asynchronously
152+connectAisStream();
153+
69154 export async function GET() {
155+ // Clean up stale ships (older than 10 minutes)
156+ const now = Date.now();
157+ for (const [mmsi, ship] of shipsCache.entries()) {
158+ if (now - ship.timestamp > 10 * 60 * 1000) {
159+ shipsCache.delete(mmsi);
160+ }
161+ }
162+
163+ const ships = Array.from(shipsCache.values());
164+
70165 return NextResponse.json({
71166 ports: PORTS,
72167 chokepoints: CHOKEPOINTS,
168+ ships: ships,
73169 total_ports: PORTS.length,
74170 total_chokepoints: CHOKEPOINTS.length,
171+ total_ships: ships.length,
75172 timestamp: new Date().toISOString(),
76173 }, {
77- headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=172800' },
174+ headers: {
175+ 'Cache-Control': 'no-store, no-cache, must-revalidate',
176+ 'Pragma': 'no-cache'
177+ },
78178 });
79179 }
modified src/app/api/osint/sweep/route.ts +2 −2
@@ -331,9 +331,9 @@
331331 let cidr = 24;
332332 if (cidrParam) {
333333 cidr = parseInt(cidrParam, 10);
334- if (isNaN(cidr) || cidr < 24 || cidr > 28) {
334+ if (isNaN(cidr) || cidr < 24 || cidr > 32) {
335335 return NextResponse.json(
336- { error: 'CIDR must be between 24 and 28' },
336+ { error: 'CIDR must be between 24 and 32' },
337337 { status: 400 },
338338 );
339339 }
modified src/app/page.tsx +2 −2
@@ -113,7 +113,7 @@
113113 private: false,
114114 jets: false,
115115 military: false,
116- maritime: false,
116+ maritime: true,
117117 satellites: false,
118118 balloons: false,
119119 cctv: true,
@@ -365,7 +365,7 @@
365365 intervals.push(setInterval(() => fetchEndpoint('/api/radiation', d => ({ radiation: d.stations })), 60000)); // 1m
366366 }
367367 if (activeLayers.maritime) {
368- intervals.push(setInterval(() => fetchEndpoint('/api/maritime', d => ({ maritime_ports: d.ports, maritime_chokepoints: d.chokepoints, maritime_ships: d.ships })), 60000)); // 1m
368+ intervals.push(setInterval(() => fetchEndpoint('/api/maritime', d => ({ maritime_ports: d.ports, maritime_chokepoints: d.chokepoints, maritime_ships: d.ships })), 10000)); // 10s
369369 }
370370 // Fires: no polling needed (data changes very slowly, initial fetch is enough)
371371 return () => intervals.forEach(clearInterval);
modified src/components/LayerPanel.tsx +11 −3
@@ -32,7 +32,7 @@
3232 icon: Ship,
3333 color: '#00BCD4',
3434 layers: [
35- { key: 'maritime', label: 'Maritime / Naval', icon: Ship, color: '#00BCD4', dataKey: 'maritime_ships' },
35+ { key: 'maritime', label: 'Maritime / Naval', icon: Ship, color: '#00BCD4', dataKey: 'maritime_ships,maritime_ports,maritime_chokepoints' },
3636 { key: 'satellites', label: 'Satellites', icon: Satellite, color: '#D4AF37', dataKey: 'satellites' },
3737 ],
3838 },
@@ -88,8 +88,16 @@
8888
8989 const toggle = (key: string) => setActiveLayers((prev: any) => ({ ...prev, [key]: !prev[key] }));
9090 const getCount = (dk: string): number | null => {
91- if (!dk || !data[dk]) return null;
92- return Array.isArray(data[dk]) ? data[dk].length : null;
91+ if (!dk) return null;
92+ let total = 0;
93+ let found = false;
94+ for (const k of dk.split(',')) {
95+ if (data[k] && Array.isArray(data[k])) {
96+ total += data[k].length;
97+ found = true;
98+ }
99+ }
100+ return found ? total : null;
93101 };
94102 const totalEntities = ALL_LAYERS.reduce((s: number, l: any) => s + (getCount(l.dataKey) || 0), 0);
95103 const activeCount = Object.values(activeLayers).filter(Boolean).length;
modified src/components/OsirisMap.tsx +1 −1
@@ -851,7 +851,7 @@
851851 if (!mapReady) return;
852852 setGeo('maritime', activeLayers.maritime && data.maritime_ports ? data.maritime_ports.map((p: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [p.lng, p.lat] }, properties: { name: p.name, country: p.country, type: p.type, volume: p.volume, fleet: p.fleet, rank: p.rank } })) : []);
853853 setGeo('maritime-choke', activeLayers.maritime && data.maritime_chokepoints ? data.maritime_chokepoints.map((c: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [c.lng, c.lat] }, properties: { name: c.name, traffic: c.traffic, risk: c.risk } })) : []);
854- setGeo('maritime-ships', activeLayers.maritime && data.maritime_ships ? data.maritime_ships.map((s: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [s.lng, s.lat] }, properties: { name: s.name, type: s.type, speed: s.speed, heading: s.heading, destination: s.destination, flag: s.flag } })) : []);
854+ setGeo('maritime-ships', activeLayers.maritime && data.maritime_ships ? data.maritime_ships.map((s: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [s.lng, s.lat] }, properties: { name: s.name || s.mmsi?.toString(), type: s.type || 'cargo', speed: s.speed, heading: s.heading, destination: s.destination, flag: s.flag } })) : []);
855855 }, [mapReady, data.maritime_ports, data.maritime_chokepoints, data.maritime_ships, activeLayers.maritime, setGeo]);
856856
857857 useEffect(() => {