Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e04d904eb7 | ||
|
|
8ca4bdd9fa | ||
|
|
54541ba62c | ||
|
|
4e2c30a942 | ||
|
|
524394c251 | ||
|
|
15b1f1caf0 | ||
|
|
6d5a85dfd4 | ||
|
|
3ff9309caf | ||
|
|
b638fc91b2 | ||
|
|
abb8ecb28f | ||
|
|
d71aac8268 | ||
|
|
5de306c346 | ||
|
|
d93c497f0a | ||
|
|
bfe64faade | ||
|
|
aa3984eb21 | ||
|
|
a0bb4b7e74 | ||
|
|
98ae79fe9b | ||
|
|
b850e84334 | ||
|
|
a5fade9783 | ||
|
|
0f860185cd | ||
|
|
b95ff5d580 | ||
|
|
813d2b28c2 | ||
|
|
3fd234736e | ||
|
|
121f7b22fe | ||
|
|
f297d0e96a |
No files matched your search
@@ -45,10 +45,10 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
git config user.email '[email protected]'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
--days-comment=${{ env.DAYS_COMMENT }}
|
||||
|
||||
- name: Upload findings artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: gc-findings-${{ github.run_id }}
|
||||
path: gc-findings.json
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
fetch-depth: 0 # Required for Stryker's incremental mode.
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v3
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 9
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
|
||||
- name: Upload mutation report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: stryker-report
|
||||
path: reports/mutation/
|
||||
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 9.15.4
|
||||
|
||||
@@ -71,7 +71,7 @@ jobs:
|
||||
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
|
||||
run: pnpm test:e2e --project=${{ matrix.browser }}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v7
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
name: playwright-report-${{ matrix.browser }}
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
+24
-25
@@ -21,23 +21,19 @@ A single globe that shows everything happening in the world right now, extensibl
|
||||
|
||||
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
|
||||
|
||||
## Current Milestone: v1.4 Agentic Intelligence
|
||||
## Current Milestone: v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Goal:** Transform the WWV MCP server from a collection of atomic tools into a well-instructed, investigation-capable AI assistant -- one that knows what it has, reasons over the globe, and delivers both globe actions and prose reports.
|
||||
**Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to the public -- a robust error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Target features:**
|
||||
- Server `instructions` field + workflow sequences (agent oriented from first connection)
|
||||
- MCP Prompts for named workflows (`orient-globe`, `investigate`)
|
||||
- Full 6-component tool description rewrite across all 15+ existing tools
|
||||
- `emptyReason` field in all query responses (distinguishes "no data" from "plugin not loaded")
|
||||
- `list_available_plugins` tool (agent checks before querying)
|
||||
- `get_globe_context` tool (full orientation snapshot in one call)
|
||||
- `investigate_area` compound tool (geocode + check + query + act + report)
|
||||
- `update_favorite` tool (completes full CRUD lifecycle for favorites)
|
||||
**Target features (Phases 31-36):**
|
||||
- Transport resilience: well-formed JSON-RPC errors (no bare 500s), DB-outage-safe auth, explicit maxDuration, honest listChanged
|
||||
- Security and abuse-resistance: dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, input/length caps
|
||||
- Tool honesty: accurate emptyReason, validated ids (no success-on-no-op), honest region coverage, output caps, corrected server instructions
|
||||
- Observability: /api/health probes Redis + DB + data engine
|
||||
- Deployment wiring: prod compose Redis + WWV_DATA_ENGINE_URL + global geocoding throttle + infra checklist
|
||||
- Onboarding and framing: public quickstart, ConnectAgentHelper prerequisites, command tools documented as "requires an open globe session"
|
||||
|
||||
**Backlog (deferred):**
|
||||
- PLG-01/PLG-02: list_plugins() + install_plugin() marketplace tools (backlog 999.1/999.2)
|
||||
- UX-01: ConnectAgentHelper upgrade CTA in demo edition (backlog 999.3)
|
||||
**Locked decisions:** command tools keep current behavior (they require a live signed-in browser session to control the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -63,17 +59,19 @@ A single globe that shows everything happening in the world right now, extensibl
|
||||
- Data query tools across all active plugins - v1.2
|
||||
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
|
||||
|
||||
### Active (v1.4 Agentic Intelligence)
|
||||
**v1.4 Agentic Intelligence (Phases 26-30, shipped 2026-06-02)**
|
||||
- Server instructions + orientation prompts, 6-component tool description rewrite
|
||||
- emptyReason response contract, list_available_plugins / get_globe_context / investigate_area, update_favorite CRUD
|
||||
- Phase 30 LocalDataSource bridge (static/client-side plugins queryable server-side)
|
||||
|
||||
- [ ] Server `instructions` field with role-framing and canonical workflow sequences
|
||||
- [ ] MCP Prompts: `orient-globe` and `investigate` named workflow templates
|
||||
- [ ] 6-component tool description rewrite for all command, query, and v1.3 tools
|
||||
- [ ] `emptyReason` field on all query tool responses
|
||||
- [ ] `get_plugin_filters` returns explicit `{available: false}` when plugin not active
|
||||
- [ ] `list_available_plugins` MCP tool (streaming plugins + entity counts)
|
||||
- [ ] `get_globe_context` MCP tool (full orientation snapshot)
|
||||
- [ ] `investigate_area` compound MCP tool (geocode + check + query + act + prose report)
|
||||
- [ ] `update_favorite` MCP tool (complete CRUD lifecycle for favorites)
|
||||
### Active (v1.5 MCP Public-Launch Hardening)
|
||||
|
||||
- [ ] Transport: top-level JSON-RPC error contract, DB-outage-safe auth, explicit maxDuration, honest listChanged + re-poll docs
|
||||
- [ ] Security: dedicated API_KEY_HMAC_SECRET enforcement (cloud/demo), Redis-backed per-key rate limiting, trusted-proxy IP, favorites cap + identifier/string length+charset bounds
|
||||
- [ ] Tool honesty: session-independent emptyReason, validated layer/filter ids + focus_entity wiring, get_entities_in_region count/truncated + tighter bbox, investigate_area/get_plugin_data output caps, corrected MCP_SERVER_INSTRUCTIONS, engine_unreachable vs no_active_plugins
|
||||
- [ ] Observability: /api/health probes Redis + DB + data engine
|
||||
- [ ] Deployment: prod compose Redis + REDIS_URL, WWV_DATA_ENGINE_URL REST base, global Nominatim throttle, infra checklist
|
||||
- [ ] Onboarding: public quickstart doc, ConnectAgentHelper prerequisites, command-tool open-session requirement documented
|
||||
|
||||
### Out of Scope
|
||||
|
||||
@@ -84,6 +82,7 @@ A single globe that shows everything happening in the world right now, extensibl
|
||||
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
|
||||
- API key scopes/permissions and rotation/grace-period flows -- revisit later
|
||||
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
|
||||
- Headless / render-on-demand globe (v1.5) -- command tools require a live signed-in browser session; building a serverless globe is deferred
|
||||
|
||||
## Context
|
||||
|
||||
@@ -112,4 +111,4 @@ A single globe that shows everything happening in the world right now, extensibl
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-31 after v1.4 milestone start*
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
+61
-65
@@ -1,94 +1,90 @@
|
||||
# Requirements: WorldWideView v1.4 Agentic Intelligence
|
||||
# Requirements: WorldWideView -- v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Defined:** 2026-05-31
|
||||
**Core Value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
|
||||
**Defined:** 2026-06-03
|
||||
**Core Value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
|
||||
## v1.3 Requirements (shipped)
|
||||
Derived from the public-launch premortem. Closes the blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
|
||||
All v1.3 requirements are complete. See archive for details.
|
||||
## v1 Requirements
|
||||
|
||||
## v1.4 Requirements
|
||||
### Transport Resilience (Phase 31)
|
||||
|
||||
### INST -- Server Instructions & Orientation
|
||||
- [x] **TRANS-01**: Every MCP failure path (auth throw, malformed JSON-RPC, tool throw, Redis/DB down during request handling) returns a well-formed JSON-RPC error (-32603, id:null, HTTP 500) instead of a bare 500 / empty body.
|
||||
- [x] **TRANS-02**: A database outage during API-key auth returns a clean 401 (authenticateApiKey returns null) rather than throwing.
|
||||
- [x] **TRANS-03**: The MCP route declares an explicit maxDuration above the 10s plugin-relay blpop so platform timeouts never truncate a blocked plugin call into a non-JSON-RPC error.
|
||||
- [x] **TRANS-04**: The server no longer advertises tools.listChanged unless it emits the notification; the stateless "re-call tools/list after enabling plugins" contract is documented in the server instructions.
|
||||
|
||||
- [x] **INST-01**: MCP server returns a populated `instructions` field in InitializeResult containing a role-framing markdown document that tells agents who WWV is, what tools are available, and the mental model for using them
|
||||
- [x] **INST-02**: The `instructions` document embeds canonical workflow sequences: geocode-first before fly_to, check plugin availability before querying entities, read globe://sessions before sending any command tool
|
||||
- [x] **INST-03**: MCP server registers an `orient-globe` Prompt that agents can invoke to get a structured snapshot of current sessions, active layers, and loaded plugins in one response
|
||||
- [x] **INST-04**: MCP server registers an `investigate` Prompt that accepts a place name and guides the agent step-by-step through geocode -> plugin availability check -> region query -> globe action
|
||||
### Security and Abuse-Resistance (Phase 32)
|
||||
|
||||
### DESC -- Tool Description Rewrite (6-component standard)
|
||||
- [x] **SEC-01**: In cloud/demo editions the server requires a dedicated API_KEY_HMAC_SECRET and fails startup if it is unset or equal to AUTH_SECRET; local dev preserves the AUTH_SECRET fallback.
|
||||
- [x] **SEC-02**: MCP tool calls are rate-limited per-userId/per-key via Redis (not only per-IP).
|
||||
- [x] **SEC-03**: Client IP is derived from a trusted-proxy source so rate limiters cannot be bypassed via a spoofed X-Forwarded-For header.
|
||||
- [x] **SEC-04**: Favorites are capped per user and all identifier/string tool inputs (entityId, pluginId, layerId, name, notes) have max-length and charset bounds in the Zod schemas and in isValidGlobeCommand.
|
||||
|
||||
Tool descriptions must include: (1) purpose verb+object front-loaded, (2) when-to-use vs. alternatives, (3) limitations and empty-result meaning, (4) parameter format + ranges, (5) concrete examples, (6) appropriate length (not truncated at the key sentence).
|
||||
### Tool Honesty and Agent UX (Phase 33)
|
||||
|
||||
- [x] **DESC-01**: All globe command tools rewritten to 6-component standard: `pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline` -- each includes sessions precondition inline and distinguishes from its nearest alternative
|
||||
- [x] **DESC-02**: All data query tools rewritten to 6-component standard: `search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data` -- each includes plugin-availability note and explanation of what empty results mean
|
||||
- [x] **DESC-03**: All v1.3 tools rewritten to 6-component standard: `geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`
|
||||
- [x] **TOOL-01**: Session-independent data-query tools never report emptyReason "no_session_active"; they return the true reason (no_data_matches, engine_unreachable, or no_active_plugins).
|
||||
- [x] **TOOL-02**: toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text; focus_entity resolves entityId to coordinates server-side.
|
||||
- [x] **TOOL-03**: get_entities_in_region returns count and a truncated flag, tightens the radiusKmToBbox bounds, and documents that capped results are an unordered sample.
|
||||
- [x] **TOOL-04**: investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow client context.
|
||||
- [x] **TOOL-05**: MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}), and list_available_plugins distinguishes engine_unreachable from no_active_plugins.
|
||||
|
||||
### RESP -- Smart Response Contracts
|
||||
### Observability (Phase 34)
|
||||
|
||||
- [x] **RESP-01**: All query tools (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) include an `emptyReason` field when results are empty: `"plugin_not_streaming"` | `"no_data_matches"` | `"no_session_active"`
|
||||
- [x] **RESP-02**: `get_plugin_filters` returns `{ available: false, reason: "plugin not loaded" }` (not an empty array) when the requested plugin is not active in the engine
|
||||
- [x] **OBS-01**: /api/health actively probes Redis, the database, and the data-engine manifest, returning a degraded status when any dependency is down.
|
||||
|
||||
### TOOL -- New Compound & Discovery Tools
|
||||
### Deployment Wiring (Phase 35)
|
||||
|
||||
- [x] **TOOL-01**: `list_available_plugins` MCP tool returns which plugins are currently streaming data to the engine, including entity counts and queryable entity types per plugin -- agents call this before attempting any data query
|
||||
- [x] **TOOL-02**: `get_globe_context` MCP tool returns a full orientation snapshot in one call: active session count, camera position, active layers, applied filters, loaded plugin list -- replaces reading multiple resources separately
|
||||
- [x] **TOOL-03**: `investigate_area(place_name, entity_type, radius_km?)` compound MCP tool that internally geocodes the place, checks which plugins are streaming the entity type, queries the bounding region, positions the globe camera, and returns both the entity list and a prose situation summary
|
||||
- [x] **DEPLOY-01**: The production compose template provisions/wires Redis via REDIS_URL so sessions, command queue, geocode cache, and rate limiters work in production.
|
||||
- [x] **DEPLOY-02**: WWV_DATA_ENGINE_URL is set to the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in compose/env templates so MCP data tools reach /manifest.
|
||||
- [x] **DEPLOY-03**: A single global Nominatim throttle (<=1 rps) protects the shared geocoder, and the geocode cache path is confirmed live.
|
||||
- [x] **DEPLOY-04**: An INFRA-CHECKLIST.md documents the Coolify actions the operator must apply (managed Redis rediss://, REDIS_URL, WWV_DATA_ENGINE_URL, API_KEY_HMAC_SECRET distinct from AUTH_SECRET).
|
||||
|
||||
### CRUD -- Full Favorites Lifecycle
|
||||
### Onboarding and Framing (Phase 36)
|
||||
|
||||
- [x] **CRUD-01**: `update_favorite(favoriteId, { name?, notes? })` MCP tool allows agents to rename or annotate a saved bookmark without deleting and re-creating it -- completes Create/Read/Update/Delete lifecycle for favorites
|
||||
|
||||
## Future Requirements (deferred)
|
||||
|
||||
### Plugin Marketplace Integration
|
||||
|
||||
- PLG-01: `list_plugins` MCP tool showing available marketplace plugins
|
||||
- PLG-02: `install_plugin` MCP tool to install a plugin from the marketplace
|
||||
- UX-01: ConnectAgentHelper upgrade CTA in demo edition
|
||||
|
||||
### Advanced Investigation
|
||||
|
||||
- Multi-turn investigation memory (agent remembers prior findings across sessions)
|
||||
- Proactive monitoring (agent watches for changes and alerts)
|
||||
- Saved investigation reports (persistent CRUD for investigation outputs)
|
||||
- Filter presets (save/apply named filter configurations)
|
||||
- [x] **ONBRD-01**: A public quickstart doc walks a new user from sign-up to a working MCP connection (generate key, paste JSON, open the globe tab).
|
||||
- [x] **ONBRD-02**: ConnectAgentHelper states the hard prerequisites: signed-in account, a browser tab open for command tools, cloud edition.
|
||||
- [x] **ONBRD-03**: Every command-tool description states the live-open-session requirement unmissably.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
| Feature | Reason |
|
||||
|---------|--------|
|
||||
| Embedding AI chat UI in the globe | MCP is server-only; chat is the client's job |
|
||||
| Browser-side MCP client | Globe is an MCP server target, not client |
|
||||
| Playwright / computer-use control | SSE command bridge is the pattern |
|
||||
| Stdio MCP transport | HTTP/SSE for production deployability |
|
||||
| OAuth 2.1 for MCP auth | Personal API keys sufficient |
|
||||
| API key scopes/permissions/rotation | Revisit post-v1.4 |
|
||||
| Proactive monitoring / push alerts | Agent-pulls model only in v1.4 |
|
||||
| Headless / render-on-demand globe | Command tools require a live signed-in browser session; building a serverless globe is a large effort, deferred. Command tools keep current behavior. |
|
||||
| API key scopes / rotation flows | Carried over from prior milestones; not a public-launch blocker. |
|
||||
| Self-hosted geocoder | Global throttle is sufficient for launch; self-hosting Nominatim is a later option. |
|
||||
|
||||
## Traceability
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| INST-01 | Phase 26 | Complete |
|
||||
| INST-02 | Phase 26 | Complete |
|
||||
| INST-03 | Phase 26 | Complete |
|
||||
| INST-04 | Phase 26 | Complete |
|
||||
| DESC-01 | Phase 27 | Complete |
|
||||
| DESC-02 | Phase 27 | Complete |
|
||||
| DESC-03 | Phase 27 | Complete |
|
||||
| RESP-01 | Phase 28 | Complete |
|
||||
| RESP-02 | Phase 28 | Complete |
|
||||
| CRUD-01 | Phase 28 | Complete |
|
||||
| TOOL-01 | Phase 29 | Complete |
|
||||
| TOOL-02 | Phase 29 | Complete |
|
||||
| TOOL-03 | Phase 29 | Complete |
|
||||
| TRANS-01 | Phase 31 | Done |
|
||||
| TRANS-02 | Phase 31 | Done |
|
||||
| TRANS-03 | Phase 31 | Done |
|
||||
| TRANS-04 | Phase 31 | Done |
|
||||
| SEC-01 | Phase 32 | Done |
|
||||
| SEC-02 | Phase 32 | Done |
|
||||
| SEC-03 | Phase 32 | Done |
|
||||
| SEC-04 | Phase 32 | Done |
|
||||
| TOOL-01 | Phase 33 | Done |
|
||||
| TOOL-02 | Phase 33 | Done |
|
||||
| TOOL-03 | Phase 33 | Done |
|
||||
| TOOL-04 | Phase 33 | Done |
|
||||
| TOOL-05 | Phase 33 | Done |
|
||||
| OBS-01 | Phase 34 | Done |
|
||||
| DEPLOY-01 | Phase 35 | Done |
|
||||
| DEPLOY-02 | Phase 35 | Done |
|
||||
| DEPLOY-03 | Phase 35 | Done |
|
||||
| DEPLOY-04 | Phase 35 | Done |
|
||||
| ONBRD-01 | Phase 36 | Done |
|
||||
| ONBRD-02 | Phase 36 | Done |
|
||||
| ONBRD-03 | Phase 36 | Done |
|
||||
|
||||
**Coverage:**
|
||||
- v1.4 requirements: 13 total
|
||||
- Mapped to phases: 13
|
||||
- Unmapped: 0 ✓
|
||||
- v1 requirements: 21 total
|
||||
- Mapped to phases: 21
|
||||
- Unmapped: 0
|
||||
|
||||
---
|
||||
*Requirements defined: 2026-05-31*
|
||||
*Last updated: 2026-05-31 after initial v1.4 definition*
|
||||
*Requirements defined: 2026-06-03*
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
+86
-133
@@ -4,7 +4,8 @@
|
||||
|
||||
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
|
||||
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
|
||||
- [ ] **v1.4 Agentic Intelligence** - Phases 26-29 (active)
|
||||
- [x] **v1.4 Agentic Intelligence** - Phases 26-30 (shipped 2026-06-02) - [archive](milestones/v1.4-ROADMAP.md)
|
||||
- [ ] **v1.5 MCP Public-Launch Hardening** - Phases 31-36 (planning, started 2026-06-03)
|
||||
|
||||
## Phases
|
||||
|
||||
@@ -33,115 +34,98 @@ Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
### v1.4 Agentic Intelligence
|
||||
<details>
|
||||
<summary>v1.4 Agentic Intelligence (Phases 26-30) - SHIPPED 2026-06-02</summary>
|
||||
|
||||
- [x] **Phase 26: Server Instructions + Orientation** - Agent arrives oriented with role framing, canonical workflows, and named MCP Prompts baked into the server (completed 2026-05-31)
|
||||
- [x] **Phase 27: Tool Description Rewrite** - All 15+ existing tools rewritten to the 6-component standard so agents select and invoke them correctly on the first try (completed 2026-05-31)
|
||||
- [x] **Phase 28: Smart Response Contracts + Favorites CRUD** - Query responses carry semantic empty reasons, get_plugin_filters signals unavailable plugins, and favorites gain full update support (completed 2026-05-31)
|
||||
- [x] **Phase 29: Compound and Discovery Tools** - Three new tools let agents self-orient and investigate in one call rather than assembling multi-step pipelines manually (completed 2026-05-31)
|
||||
- [x] **Phase 30: Local Data-Source Bridge** - Server-reachable static/client-side plugins become MCP-queryable via a generalized LocalDataSource registry (4/4 plans, completed 2026-06-02)
|
||||
|
||||
Full details: [milestones/v1.4-ROADMAP.md](milestones/v1.4-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
### v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Milestone Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to untrusted, authenticated public users -- a robust JSON-RPC error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope.
|
||||
|
||||
- [ ] **Phase 31: Transport Resilience** - Every MCP failure path returns a well-formed JSON-RPC error, auth survives a DB outage, and timeouts/listChanged are honest
|
||||
- [ ] **Phase 32: Security and Abuse-Resistance** - Dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, and input/length/charset caps
|
||||
- [ ] **Phase 33: Tool Honesty and Agent UX** - Tools report the true reason for empty results, validate ids, bound region/output size, and ship corrected server instructions
|
||||
- [ ] **Phase 34: Observability** - /api/health actively probes Redis, the database, and the data engine and reports a degraded status when any is down
|
||||
- [ ] **Phase 35: Deployment Wiring** - Production compose wires Redis + the data-engine REST base, a global geocoder throttle protects Nominatim, and an infra checklist documents operator actions
|
||||
- [ ] **Phase 36: Onboarding and Framing** - A public quickstart, ConnectAgentHelper prerequisites, and command-tool descriptions make the live-open-session requirement unmissable
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 22: Geocoding + Favorites
|
||||
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
|
||||
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
|
||||
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
|
||||
### Phase 31: Transport Resilience
|
||||
**Goal**: Every MCP failure path -- auth throw, malformed JSON-RPC, tool throw, Redis/DB outage during request handling, or platform timeout -- surfaces to the client as a well-formed JSON-RPC error rather than a bare 500, an empty body, or a non-JSON-RPC truncation
|
||||
**Depends on**: Phase 30 (v1.4 complete; stable MCP route, authenticateApiKey, plugin-relay blpop bridge)
|
||||
**Requirements**: TRANS-01, TRANS-02, TRANS-03, TRANS-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
|
||||
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
|
||||
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
|
||||
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
|
||||
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
|
||||
1. Forcing any failure mode (invalid auth, malformed JSON-RPC body, a tool that throws, Redis/DB down mid-request) returns a well-formed JSON-RPC error object (code -32603, id:null, HTTP 500) with a non-empty body -- never a bare 500 or empty response
|
||||
2. With the database unavailable, calling an authenticated MCP endpoint returns a clean 401 (authenticateApiKey resolves to null) instead of throwing an unhandled exception
|
||||
3. The MCP route declares an explicit maxDuration greater than the 10s plugin-relay blpop window, so a blocked plugin call still returns a JSON-RPC error rather than a platform-truncated non-JSON-RPC response
|
||||
4. The server's advertised capabilities no longer claim tools.listChanged unless the notification is actually emitted, and the server instructions document the stateless "re-call tools/list after enabling plugins" contract
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 23: Entity Filtering
|
||||
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
|
||||
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
|
||||
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
|
||||
### Phase 32: Security and Abuse-Resistance
|
||||
**Goal**: An authenticated but untrusted public user cannot bypass auth hardening, exhaust shared resources, spoof their identity to defeat rate limiting, or smuggle oversized/malformed input through the tool schemas
|
||||
**Depends on**: Phase 31 (clean error contract in place so rejected/limited requests return well-formed errors)
|
||||
**Requirements**: SEC-01, SEC-02, SEC-03, SEC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
|
||||
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
|
||||
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
|
||||
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
|
||||
**Plans**: 3 plans (ships atomically per STATE.md)
|
||||
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
|
||||
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
|
||||
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
|
||||
|
||||
### Phase 24: Route Wiring + Version Bump
|
||||
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
|
||||
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
|
||||
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
|
||||
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
|
||||
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
|
||||
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
|
||||
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN, build OK. Commits 5201ae3, 5ea7855.
|
||||
|
||||
### Phase 25: Documentation
|
||||
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
|
||||
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
|
||||
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
|
||||
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
|
||||
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
|
||||
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
|
||||
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
|
||||
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
|
||||
|
||||
### Phase 26: Server Instructions + Orientation
|
||||
**Goal**: A fresh AI agent connecting to the WWV MCP server for the first time receives a complete orientation -- who WWV is, what tools exist, and the canonical workflows to follow -- without the user having to explain anything
|
||||
**Depends on**: Phase 25 (v1.3 complete; stable tool set as orientation baseline)
|
||||
**Requirements**: INST-01, INST-02, INST-03, INST-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. The MCP `initialize` response contains a non-empty `instructions` field with a role-framing header, a mental model for the globe/plugins/sessions, and at least two explicit "do X before Y" rules (read sessions before commanding; check plugin availability before querying)
|
||||
2. A fresh agent that has only read `instructions` correctly answers: "What do I need to do before calling pan_globe?" without having read any individual tool description
|
||||
3. Calling `prompts/list` returns both `orient-globe` and `investigate` prompt names; calling `prompts/get` on each returns a structured, step-numbered template with no placeholder text
|
||||
4. An agent invoking the `orient-globe` prompt receives a single response containing active sessions, loaded plugin layers, and current camera state -- no follow-up resource reads needed to get oriented
|
||||
1. In cloud/demo editions the server fails to start when API_KEY_HMAC_SECRET is unset or equal to AUTH_SECRET, while local dev still boots using the AUTH_SECRET fallback
|
||||
2. Repeated MCP tool calls from the same userId/key are throttled by a Redis-backed limiter (per-user/per-key, not only per-IP), and an over-limit call returns a clean rate-limit error
|
||||
3. A spoofed X-Forwarded-For header cannot reset or bypass the rate limiter -- the client IP is derived only from a trusted-proxy source
|
||||
4. Favorites are capped per user, and every identifier/string tool input (entityId, pluginId, layerId, name, notes) is rejected when it exceeds max-length or violates charset bounds, enforced in both the Zod schemas and isValidGlobeCommand
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 27: Tool Description Rewrite
|
||||
**Goal**: Every existing MCP tool description satisfies the 6-component standard so an agent selects the right tool, passes correct arguments, and correctly interprets empty results on the first attempt
|
||||
**Depends on**: Phase 26 (instructions written first; tool descriptions must align with the canonical workflows stated there)
|
||||
**Requirements**: DESC-01, DESC-02, DESC-03
|
||||
### Phase 33: Tool Honesty and Agent UX
|
||||
**Goal**: Every tool response tells the agent the truth -- the real reason a result is empty, whether an id was actually recognized, whether results were truncated -- so an agent never reports a false success or a misleading cause to its user
|
||||
**Depends on**: Phase 31 (error contract), Phase 32 (validated/bounded inputs so honesty checks operate on sanitized ids)
|
||||
**Requirements**: TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Every command tool description (`pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline`) contains inline: the sessions precondition, what "no active session" means, and when to prefer this tool over its nearest alternative
|
||||
2. Every data query tool description (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) states explicitly what an empty result means -- distinguishing "plugin not loaded" from "no matching data"
|
||||
3. Every v1.3 tool description (`geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`) passes the 6-component checklist: purpose, when-to-use, limitations, parameter format, example, complete length
|
||||
4. No tool description is truncated at a critical constraint; each fits within MCP client display limits while retaining all mandatory guidance
|
||||
**Plans**: 3 plans (all wave 1, parallel -- no file overlap)
|
||||
- [x] 27-01-PLAN.md — DESC-01: rewrite 4 globe command tool descriptions (pan_globe, focus_entity, toggle_layer, set_timeline) + assertion tests
|
||||
- [x] 27-02-PLAN.md — DESC-02: rewrite 4 data query tool descriptions with empty-result semantics + new tools.test.ts
|
||||
- [x] 27-03-PLAN.md — DESC-03: conform 8 v1.3 tool descriptions across geocoding/filter/favorites (fly_to gets the sessions precondition) + assertion tests
|
||||
1. Session-independent data-query tools never return emptyReason "no_session_active"; an empty result reports the true cause -- no_data_matches, engine_unreachable, or no_active_plugins
|
||||
2. toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text, and focus_entity resolves entityId to coordinates server-side rather than silently no-op'ing
|
||||
3. get_entities_in_region returns a count and a truncated flag, applies tightened radiusKmToBbox bounds, and documents that capped results are an unordered sample
|
||||
4. investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow the client's context window
|
||||
5. MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}) and list_available_plugins distinguishes engine_unreachable from no_active_plugins
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 28: Smart Response Contracts + Favorites CRUD
|
||||
**Goal**: Query tools communicate WHY results are empty rather than returning identical empty arrays for unrelated failure modes, and agents can update a saved favorite without deleting and recreating it
|
||||
**Depends on**: Phase 27 (tool descriptions must reference emptyReason semantics described there)
|
||||
**Requirements**: RESP-01, RESP-02, CRUD-01
|
||||
### Phase 34: Observability
|
||||
**Goal**: An operator (or uptime monitor) can tell at a glance whether the MCP server's critical dependencies are healthy, with /api/health actively probing them rather than returning a hardcoded OK
|
||||
**Depends on**: Phase 31 (shared Redis/DB access patterns and error handling reused by the probes)
|
||||
**Requirements**: OBS-01
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `search_entities` with a plugin that has no active streaming session returns `{ success: true, entities: [], count: 0, emptyReason: "plugin_not_streaming" }` -- distinct from a query that returns `"no_data_matches"` when the plugin is streaming but nothing matches the filter
|
||||
2. Calling `search_entities` when no globe session is active returns `emptyReason: "no_session_active"` -- the agent can distinguish this from a data absence without guessing
|
||||
3. Calling `get_plugin_filters("flights")` when the flights plugin is not loaded returns `{ available: false, reason: "plugin not loaded" }` rather than an empty array, allowing the agent to report the real cause to the user
|
||||
4. Calling `update_favorite(id, { name: "New Name", notes: "Updated note" })` persists the change and is reflected in the next `list_favorites` response without requiring `remove_favorite` + `save_favorite`
|
||||
**Plans**: 3 plans
|
||||
- [x] 28-01-PLAN.md — RESP-01: emptyReason discriminated service results + userId threading into registerDataQueryTools + 4-tool passthrough with session-first precedence + tests (wave 1)
|
||||
- [x] 28-02-PLAN.md — RESP-02: get_plugin_filters availability wrapper (4 shapes) + Phase 27 description/test updates (wave 2, depends on 28-01 for route.ts seam)
|
||||
- [x] 28-03-PLAN.md — CRUD-01: [BLOCKING] notes String? migration + update_favorite tool + list_favorites notes surfacing + tests (wave 1, independent files)
|
||||
1. GET /api/health actively probes Redis, the database, and the data-engine manifest on each request rather than returning a static OK
|
||||
2. When any one dependency is unreachable, /api/health returns a degraded status identifying which dependency is down, while a fully healthy stack returns a healthy status
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 29: Compound and Discovery Tools
|
||||
**Goal**: Agents can answer "what is happening near X?" in a single tool call, check which plugins are active before querying, and orient themselves completely without reading multiple resources
|
||||
**Depends on**: Phase 28 (emptyReason contracts and CRUD-01 must be complete; investigate_area depends on emptyReason to characterize its sub-query results)
|
||||
**Requirements**: TOOL-01, TOOL-02, TOOL-03
|
||||
### Phase 35: Deployment Wiring
|
||||
**Goal**: The production deployment has every dependency the MCP server needs actually provisioned and correctly wired -- Redis, the data-engine REST base, and a protected shared geocoder -- with an operator checklist so a real launch does not silently run on missing infrastructure
|
||||
**Depends on**: Phase 32 (API_KEY_HMAC_SECRET requirement), Phase 34 (health probes confirm the wired dependencies are reachable)
|
||||
**Requirements**: DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `list_available_plugins` returns a list of currently streaming plugins with entity counts and queryable entity types; an agent that calls this before `search_entities` never receives a `plugin_not_streaming` emptyReason it did not anticipate
|
||||
2. Calling `get_globe_context` returns in one response: active session count, camera position, active layers, applied filters, and loaded plugin list -- an agent that reads this resource needs no additional `globe://sessions`, `globe://state`, or `globe://layers` reads to be fully oriented
|
||||
3. Calling `investigate_area("Auckland", "flights")` internally geocodes the place, checks which plugins stream flights, queries the bounding region, positions the globe camera over Auckland, and returns both the entity list and a prose situation summary describing what is happening in that area
|
||||
4. `investigate_area` returns a meaningful prose report even when no entities match -- the summary explains why (e.g., no active flight plugin) rather than returning an empty structure
|
||||
**UI hint**: no
|
||||
**Plans**: 1 plan
|
||||
- [x] 29-01-PLAN.md — All three discovery tools (list_available_plugins, get_globe_context, investigate_area) in discoveryTools.ts + shared discoveryHelpers.ts + route wiring + tests
|
||||
1. The production compose template provisions and wires Redis via REDIS_URL so sessions, the command queue, the geocode cache, and the rate limiters all function in production
|
||||
2. WWV_DATA_ENGINE_URL points at the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in the compose/env templates, so MCP data tools can reach /manifest
|
||||
3. A single global Nominatim throttle (<=1 rps) protects the shared geocoder and the geocode cache path is confirmed live in production configuration
|
||||
4. An INFRA-CHECKLIST.md documents the exact Coolify actions an operator must apply: managed Redis (rediss://), REDIS_URL, WWV_DATA_ENGINE_URL, and an API_KEY_HMAC_SECRET distinct from AUTH_SECRET
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 36: Onboarding and Framing
|
||||
**Goal**: A new public user can go from sign-up to a working MCP connection without hidden prerequisites, and the live-open-session requirement of command tools is stated unmissably everywhere an agent or user encounters it
|
||||
**Depends on**: Phase 33 (final tool descriptions and instructions stable), Phase 35 (deployment wiring known so the quickstart documents the real path)
|
||||
**Requirements**: ONBRD-01, ONBRD-02, ONBRD-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. A public quickstart doc walks a brand-new user end to end: sign up, generate an API key, paste the connection JSON, and open the globe tab to reach a working MCP connection
|
||||
2. ConnectAgentHelper states the hard prerequisites up front: a signed-in account, a browser tab open for command tools, and cloud edition
|
||||
3. Every command-tool description states the live-open-session requirement unmissably, so an agent never attempts a command tool expecting it to work without an open globe session
|
||||
**Plans**: TBD
|
||||
**UI hint**: yes
|
||||
|
||||
## Progress Table
|
||||
|
||||
@@ -151,45 +135,14 @@ Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
|
||||
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
|
||||
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
|
||||
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
|
||||
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
|
||||
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
|
||||
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
|
||||
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
|
||||
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
|
||||
|
||||
## Backlog
|
||||
|
||||
Per the 21-REPLAN locked decision ("NO marketplace" in v1.2 scope), the two marketplace
|
||||
plugin-management MCP tools were deferred. They require the marketplace JWT install bridge,
|
||||
which was descoped to keep v1.2 worldwideview-only.
|
||||
|
||||
- **999.1 -- PLG-01: `list_plugins()` MCP tool** -- returns all marketplace plugins with
|
||||
install status for the authenticated user. Depends on marketplace API + JWT bridge.
|
||||
- **999.2 -- PLG-02: `install_plugin({ pluginSlug })` MCP tool** -- triggers installation via
|
||||
the existing marketplace JWT install bridge flow. Depends on PLG-01 + marketplace install endpoint.
|
||||
|
||||
- **999.3 -- UX-01: Show MCP / ConnectAgentHelper as "Cloud edition" upgrade CTA in demo** --
|
||||
Currently `!isDemo` in Header.tsx:449 hides the entire ConnectAgentHelper section in demo.
|
||||
UX improvement: surface it as a locked/teaser CTA that explains the feature and links to
|
||||
upgrade. Pairs with v1.3 MCP-OBSERVATIONS.md scope (geocoding, OSM search, basemap control,
|
||||
entity filtering, enhanced search, favorites, plugin-tool discovery).
|
||||
|
||||
Also tracked as partials (functional, refinement deferred):
|
||||
- **CTRL-02** focus_entity entityId-only resolution -- currently a no-op without lat/lng;
|
||||
needs entity-id -> coordinate lookup wired into the command dispatch.
|
||||
- **MCP-QA-03** explicit Redis reconnect test -- stateless SSE arch makes the original
|
||||
WebSocket-subscriber spec N/A; ioredis auto-reconnects. Add a reconnect test if reliability
|
||||
concerns arise.
|
||||
|
||||
### Phase 30: Local Data-Source Bridge: make server-reachable client-side and static plugins (camera GeoJSON, OSM-static plugins) queryable via MCP through a generalized LocalDataSource registry. Closes the MCP coverage gap where browser-loaded plugins return plugin_not_streaming. Camera is the first consumer.
|
||||
|
||||
**Goal:** Server-reachable client-side/static plugins (camera GeoJSON + traffic route) are MCP-queryable through a generalized manifest-declared LocalDataSource registry, with NO browser session -- closing the plugin_not_streaming coverage gap. Acceptance: a Russia-bbox `get_entities_in_region(pluginId:"camera")` returns the in-box cameras and `list_available_plugins` lists camera as `source:"local"` with a non-zero count.
|
||||
**Requirements**: D-01..D-08 (CONTEXT decisions), RESP-01 (emptyReason contract preserved), TOOL-01/TOOL-02 (discovery surface)
|
||||
**Depends on:** Phase 29
|
||||
**Plans:** 4/4 plans complete
|
||||
|
||||
Plans:
|
||||
- [x] 30-01-PLAN.md — Foundation: SDK LocalDataSourceDeclaration type + camera package.json localData declaration + sync-local-plugins passthrough + validateManifest localData validator (wave 1, TDD)
|
||||
- [x] 30-02-PLAN.md — localSources module: manifest-driven registry + server-side GeoJSON normalizer + per-source TTL cache (wave 2, TDD)
|
||||
- [x] 30-03-PLAN.md — Integration seam: fetchPluginSnapshot engine->local->null fallback + getAllPluginSnapshots local-id union; Russia-bbox demo + D-06 emptyReason cases (wave 3, TDD)
|
||||
- [x] 30-04-PLAN.md — Discovery surface: StreamingPlugin source:"engine"|"local" tag in listStreamingPlugins; camera surfaced in list_available_plugins/get_globe_context (wave 4, TDD)
|
||||
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
|
||||
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
|
||||
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
|
||||
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
|
||||
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
|
||||
| 31. Transport Resilience | 0/TBD | Not started | - |
|
||||
| 32. Security and Abuse-Resistance | 0/TBD | Not started | - |
|
||||
| 33. Tool Honesty and Agent UX | 0/TBD | Not started | - |
|
||||
| 34. Observability | 0/TBD | Not started | - |
|
||||
| 35. Deployment Wiring | 0/TBD | Not started | - |
|
||||
| 36. Onboarding and Framing | 0/TBD | Not started | - |
|
||||
+75
-47
@@ -1,38 +1,63 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.4
|
||||
milestone_name: Agentic Intelligence
|
||||
status: verifying
|
||||
last_updated: "2026-06-02T04:43:48.134Z"
|
||||
last_activity: 2026-06-02
|
||||
milestone: v1.5
|
||||
milestone_name: MCP Public-Launch Hardening
|
||||
status: complete
|
||||
last_updated: "2026-06-03T16:05:00.000Z"
|
||||
last_activity: 2026-06-03
|
||||
progress:
|
||||
total_phases: 9
|
||||
completed_phases: 8
|
||||
total_plans: 22
|
||||
completed_plans: 21
|
||||
percent: 89
|
||||
total_phases: 6
|
||||
completed_phases: 6
|
||||
total_plans: 0
|
||||
completed_plans: 0
|
||||
percent: 100
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
See: .planning/PROJECT.md (updated 2026-05-31)
|
||||
See: .planning/PROJECT.md (updated 2026-06-03)
|
||||
|
||||
**Core value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
|
||||
**Current focus:** Phase 30 — local-data-source-bridge-make-server-reachable-client-side-a
|
||||
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
**Current focus:** v1.5 MCP Public-Launch Hardening (Phases 31-36) -- closing premortem blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
|
||||
## Current Position
|
||||
|
||||
Phase: 30 (local-data-source-bridge-make-server-reachable-client-side-a) — EXECUTING
|
||||
Plan: 4 of 4
|
||||
Status: Phase complete — ready for verification
|
||||
Last activity: 2026-06-02
|
||||
Resume file: None
|
||||
Phase: 36 — Onboarding and Framing (complete)
|
||||
Plan: —
|
||||
Status: All 6 phases (31-36) complete and committed; milestone v1.5 done
|
||||
Last activity: 2026-06-03 — Phase 36 Onboarding and Framing shipped (ONBRD-01..03), gate green (1004 tests), v2.48.9
|
||||
|
||||
Progress: [██████████] 95%
|
||||
## Completed Phases (v1.5)
|
||||
|
||||
## v1.4 Phase Map
|
||||
| Phase | Result | Commit |
|
||||
|-------|--------|--------|
|
||||
| 31 Transport Resilience | tsc + 916 tests + build green; security SAFE | 121f7b22 |
|
||||
| 32 Security and Abuse-Resistance | tsc + 967 tests + build green; security MERGE-WITH-FIXES resolved | 3fd23473 |
|
||||
| 33 Tool Honesty and Agent UX | tsc + 983 tests + build green; TOOL-01 live-verified (no_data_matches) | 813d2b28 |
|
||||
| 34 Observability | tsc + tests + build green; /api/health probes redis/db/engine/config | b95ff5d5 |
|
||||
| 35 Deployment Wiring | tsc + 1004 tests + build green; security MERGE-WITH-FIXES resolved (Redis auth, AUTH_SECRET, pg loopback) | 0f860185 |
|
||||
| 36 Onboarding and Framing | tsc + 1004 tests + build green; quickstart + prerequisites + SESSION_REQUIRED_PREAMBLE on all 7 command tools | a5fade97 |
|
||||
|
||||
## v1.5 Phase Map
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 31 | Transport Resilience | TRANS-01, TRANS-02, TRANS-03, TRANS-04 |
|
||||
| 32 | Security and Abuse-Resistance | SEC-01, SEC-02, SEC-03, SEC-04 |
|
||||
| 33 | Tool Honesty and Agent UX | TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05 |
|
||||
| 34 | Observability | OBS-01 |
|
||||
| 35 | Deployment Wiring | DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04 |
|
||||
| 36 | Onboarding and Framing | ONBRD-01, ONBRD-02, ONBRD-03 |
|
||||
|
||||
**Coverage:** 21/21 v1.5 requirements mapped, 0 orphaned.
|
||||
|
||||
**Phase numbering:** v1.5 starts at Phase 31 (v1.4 ended at Phase 30).
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## v1.4 Phase Map (archived reference)
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
@@ -40,26 +65,19 @@ Progress: [██████████] 95%
|
||||
| 27 | Tool Description Rewrite | DESC-01, DESC-02, DESC-03 |
|
||||
| 28 | Smart Response Contracts + Favorites CRUD | RESP-01, RESP-02, CRUD-01 |
|
||||
| 29 | Compound and Discovery Tools | TOOL-01, TOOL-02, TOOL-03 |
|
||||
| 30 | Local Data-Source Bridge | D-01..D-08, RESP-01, TOOL-01, TOOL-02 |
|
||||
|
||||
## Key Decisions (carried from v1.2/v1.3)
|
||||
## Key Decisions (carried from v1.2/v1.3/v1.4)
|
||||
|
||||
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
|
||||
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
|
||||
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream). Reuse for fly_to in v1.3.
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern.
|
||||
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream).
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern; plugin-relay blpop has a 10s window (relevant to TRANS-03 maxDuration).
|
||||
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
|
||||
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all new MCP tools.
|
||||
- **LocalDataSource registry (Phase 30-02):** Scans public/plugins-local/<id>/plugin.json at startup; memoized once per process. Per-source TTL cache: TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s. geojson sources read from disk (no self-HTTP); route sources fetched via internal base URL.
|
||||
- **LocalDataSourceDeclaration SDK export:** Added to wwv-plugin-sdk/src/index.ts re-exports (was absent from Plan 30-01 manifest.ts addition).
|
||||
|
||||
## v1.3 Phase Map (archived reference)
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 22 | Geocoding + Favorites | GEO-01..03, FAV-01..03, SAFE-01..02 |
|
||||
| 23 | Entity Filtering | FILT-01..04 |
|
||||
| 24 | Route Wiring + Version Bump | INTG-01, INTG-02 |
|
||||
| 25 | Documentation | DOC-01..04 |
|
||||
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all MCP tools.
|
||||
- **LocalDataSource registry (Phase 30):** Manifest-declared registry making server-reachable static/client-side plugins MCP-queryable; per-source TTL cache (TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s).
|
||||
- **emptyReason enum (evolving in v1.5):** v1.4 contract was "plugin_not_streaming" | "no_data_matches" | "no_session_active". v1.5 TOOL-01/TOOL-05 require session-independent tools to return no_data_matches | engine_unreachable | no_active_plugins instead of no_session_active. Lock the revised enum in Phase 33 before rewriting MCP_SERVER_INSTRUCTIONS.
|
||||
- **Nominatim rate limiting:** server-side Redis sliding window (1 req/sec) + 24h cache already live (v1.3 GEO-03). DEPLOY-03 elevates this to a single GLOBAL throttle (<=1 rps) protecting the shared geocoder -- do not re-implement per-request limiting.
|
||||
|
||||
## Blockers
|
||||
|
||||
@@ -69,15 +87,25 @@ None.
|
||||
|
||||
### Roadmap Evolution
|
||||
|
||||
- Phase 30 added: Local Data-Source Bridge (Option A): generalized LocalDataSource registry to make server-reachable static/client-side plugins MCP-queryable; camera first consumer
|
||||
- v1.2 archived at .planning/milestones/v1.2-* and tagged v1.2 in git.
|
||||
- PR #215 (feat/mcp-support) open on GitHub, awaiting merge.
|
||||
- v1.3 complete 2026-05-31. All 4 phases shipped, tsc clean, 750 tests GREEN.
|
||||
- Phase numbering: v1.4 starts at Phase 26 (v1.3 ended at Phase 25).
|
||||
- Phase 26 is pure configuration/server-init work -- no new tool implementations. McpServer `instructions` string + two MCP Prompt registrations.
|
||||
- Phase 27 is pure description text rewriting across 15+ existing tools -- no schema changes, no new tools. Lowest risk phase.
|
||||
- Phase 28 requires code changes to query handler return shapes (emptyReason field) and one new Prisma mutation (update_favorite). Coordinate with prisma.favorite model in Phase 28 plan.
|
||||
- Phase 29 is the most complex: investigate_area is a compound tool that chains geocode -> plugin check -> region query -> SSE command -> prose generation internally. Design the internal chain carefully; it must not expose intermediate tool results to the caller.
|
||||
- Nominatim integration: server-side rate limiter (1 req/sec Redis sliding window) + 24h result cache are already live (GEO-03, Phase 22). investigate_area (TOOL-03) reuses this path -- do not re-implement.
|
||||
- Favorites use prisma.favorite directly -- never proxy through /api/user/favorites (cookie auth incompatible with API key sessions, SAFE-02). update_favorite (CRUD-01) must follow same pattern.
|
||||
- emptyReason values are an enum contract: "plugin_not_streaming" | "no_data_matches" | "no_session_active". Agree on this enum in Phase 28 and reference it in Phase 27 tool description rewrites -- do Phase 27 after Phase 26 but the enum must be locked before DESC-02 is written.
|
||||
- v1.5 derived from a public-launch premortem of the MCP server. One phase per REQUIREMENTS.md category, 1:1 mapping.
|
||||
- Phase numbering: v1.5 starts at Phase 31 (v1.4 ended at Phase 30). Do NOT renumber or reset.
|
||||
- Dependency note: Phase 31 (clean error contract) is foundational -- Phases 32/33/34 surface their rejections/limits/probe failures through it. Phase 35 depends on SEC-01 (HMAC secret) and OBS-01 (probes confirm wiring). Phase 36 depends on Phase 33 (final tool text) and Phase 35 (real deployment path).
|
||||
- Phase 36 is the only UI-touching phase (ConnectAgentHelper prerequisites + command-tool description framing) -- flagged UI hint: yes.
|
||||
- v1.4 (Phases 26-30) shipped 2026-06-02; archived reference retained above.
|
||||
|
||||
## Deferred Items
|
||||
|
||||
Items deferred at v1.5 milestone start (carried from v1.4 close on 2026-06-02):
|
||||
|
||||
| Category | Item | Status |
|
||||
|----------|------|--------|
|
||||
| uat_gap | Phase 29 v1.4-UAT.md — 25 pending scenarios | diagnosed (manual acceptance testing not completed; automated gate green) |
|
||||
| todo | 2026-05-30-system-default-common-plugin-tools.md [mcp] | pending (future idea — system-default common plugin tools) |
|
||||
| out_of_scope | Headless / render-on-demand globe | deferred (command tools keep live-session behavior; serverless globe is a large effort) |
|
||||
| out_of_scope | API key scopes / rotation flows | deferred (not a public-launch blocker) |
|
||||
| out_of_scope | Self-hosted geocoder | deferred (global throttle sufficient for launch) |
|
||||
|
||||
## Operator Next Steps
|
||||
|
||||
- Plan Phase 31 with /gsd:plan-phase 31 (Transport Resilience -- foundational error contract).
|
||||
- Phases execute in numeric order 31 → 32 → 33 → 34 → 35 → 36; dependencies allow some parallelism after Phase 31.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Production Infrastructure Checklist
|
||||
|
||||
Actions an operator must apply in Coolify (or equivalent) before public launch.
|
||||
Complete every item and verify the /api/health response before opening traffic.
|
||||
|
||||
---
|
||||
|
||||
## 1. AUTH_SECRET
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `AUTH_SECRET` on the `wwv` service. This value MUST be distinct from
|
||||
`API_KEY_HMAC_SECRET`. The app fails closed (auth broken) if this is unset.
|
||||
|
||||
---
|
||||
|
||||
## 2. Redis
|
||||
|
||||
- [ ] Generate a Redis password:
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set `REDIS_PASSWORD` on both the `wwv` and `wwv-redis` services to this value.
|
||||
- [ ] For a co-located `wwv-redis`: the compose default uses this password automatically
|
||||
via `REDIS_URL=redis://:<password>@wwv-redis:6379`. No further URL override is needed.
|
||||
- [ ] For a managed Redis provider (e.g. Upstash, Redis Cloud): set `REDIS_URL` to the
|
||||
provider's TLS endpoint instead:
|
||||
```
|
||||
REDIS_URL=rediss://:<password>@<host>:<port>
|
||||
```
|
||||
Use `rediss://` (double-s) for TLS. Remove the co-located `wwv-redis` service when
|
||||
using a managed provider.
|
||||
- [ ] Verify Redis is reachable: `GET /api/health` should return `200` with
|
||||
`"redis": "ok"` (not `"degraded"`).
|
||||
|
||||
**What breaks without Redis:** MCP sessions, globe command queue, geocode cache,
|
||||
all per-user and global rate limiters, and API key session tracking silently no-op
|
||||
or degrade. The app stays up but MCP data tools report errors and OSM rate limits
|
||||
are unenforceable.
|
||||
|
||||
---
|
||||
|
||||
## 3. Data Engine REST URL
|
||||
|
||||
- [ ] Set `WWV_DATA_ENGINE_URL` on the `wwv` service to the engine's REST base URL.
|
||||
This is the HTTP base (scheme + host + port). Do NOT include the `/stream` path:
|
||||
```
|
||||
# Correct: REST base only
|
||||
WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002
|
||||
|
||||
# Wrong: do not include /stream
|
||||
# WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002/stream
|
||||
```
|
||||
The engine's published REST port is **5002** (maps to internal port 5000 in
|
||||
`deploy/production/docker-compose.engine.yml`).
|
||||
Replace `<engine-host-ip>` with the actual engine host IP or hostname visible from
|
||||
the `wwv` container.
|
||||
- [ ] If the app and engine containers share a Docker network, use the service name:
|
||||
```
|
||||
WWV_DATA_ENGINE_URL=http://wwv-data-engine:5000
|
||||
```
|
||||
- [ ] Verify reachability: `GET /api/health` should return `"engine": "ok"`.
|
||||
A value of `"degraded"` means the URL is wrong or the engine is not running.
|
||||
|
||||
**What breaks without this:** All MCP data query tools (e.g. `query_plugin_data`)
|
||||
report "engine unreachable" and return no data.
|
||||
|
||||
---
|
||||
|
||||
## 4. API Key HMAC Secret
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `API_KEY_HMAC_SECRET` on the `wwv` service. This value MUST be
|
||||
distinct from `AUTH_SECRET`. They serve different cryptographic purposes.
|
||||
- [ ] cloud and demo editions fail closed without this value. The app will refuse to
|
||||
issue or validate API keys, blocking all MCP authentication.
|
||||
|
||||
---
|
||||
|
||||
## 5. Trusted IP Header (Cloudflare / CDN)
|
||||
|
||||
- [ ] If a CDN or second reverse proxy (e.g. Cloudflare) sits in front of your
|
||||
Nginx/Traefik reverse proxy, set:
|
||||
```
|
||||
WWV_TRUSTED_IP_HEADER=cf-connecting-ip
|
||||
```
|
||||
Without this, all clients share the proxy's IP address and collapse into a single
|
||||
rate-limit bucket. One user's burst exhausts the quota for all users.
|
||||
- [ ] If you are NOT behind Cloudflare, leave `WWV_TRUSTED_IP_HEADER` unset (the
|
||||
default reads from `x-forwarded-for` via `x-real-ip`).
|
||||
- [ ] Verify the correct client IP is visible in request logs or the
|
||||
`X-Client-IP` debug header (if enabled) after applying the setting.
|
||||
|
||||
---
|
||||
|
||||
## 6. Health Check Semantics
|
||||
|
||||
Configure your uptime monitor or Coolify health check against `GET /api/health`.
|
||||
|
||||
| Response | Meaning | Action required |
|
||||
|---|---|---|
|
||||
| `503` | Database or required config broken | Page on-call immediately |
|
||||
| `200` with any `"degraded"` field | Redis or engine unreachable | Investigate; MCP features are impaired but core app is up |
|
||||
| `200` all `"ok"` | Fully healthy | No action |
|
||||
|
||||
Recommended alert rule: alert on any `503` immediately; alert on `200` degraded
|
||||
after 5 consecutive checks (transient restarts are normal).
|
||||
|
||||
---
|
||||
|
||||
## Verification Sequence
|
||||
|
||||
Run these checks in order after applying all settings:
|
||||
|
||||
1. `GET /api/health` returns `200` with all fields `"ok"`.
|
||||
2. Sign in as an admin user, generate an MCP API key, and confirm the key is issued
|
||||
(cloud/demo: requires `API_KEY_HMAC_SECRET`).
|
||||
3. Run `geocode_location({ query: "Paris" })` via the MCP endpoint and confirm
|
||||
results are returned (requires Redis + Nominatim reachability).
|
||||
4. Run `query_plugin_data` for a live plugin and confirm data is returned (requires
|
||||
`WWV_DATA_ENGINE_URL`).
|
||||
@@ -6,7 +6,32 @@ services:
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
# Bound to loopback only so Postgres is not reachable from the host network.
|
||||
# The app service reaches db via the internal Docker network.
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry below when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
wwv-cloud:
|
||||
build:
|
||||
@@ -21,7 +46,16 @@ services:
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
|
||||
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
AUTH_SECRET: ${AUTH_SECRET}
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis should set REDIS_URL=rediss://:<password>@<host>:6380 in .env.
|
||||
REDIS_URL: "redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Set to the actual engine host IP/hostname visible from this container.
|
||||
WWV_DATA_ENGINE_URL: ${WWV_DATA_ENGINE_URL:-http://<engine-host-ip>:5002}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
labels:
|
||||
@@ -31,7 +65,10 @@ services:
|
||||
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
|
||||
depends_on:
|
||||
- db
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
@@ -45,3 +82,6 @@ services:
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
|
||||
volumes:
|
||||
wwv-redis-data:
|
||||
@@ -10,16 +10,29 @@ services:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
- "AUTH_SECRET=${AUTH_SECRET}"
|
||||
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
|
||||
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use.
|
||||
- "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=http://192.168.68.69:5002/stream"
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Default assumes the engine runs on the same host, published on port 5002.
|
||||
# Operators using a separate engine host must override to http://<engine-host>:5002
|
||||
- "WWV_DATA_ENGINE_URL=${WWV_DATA_ENGINE_URL:-http://192.168.68.69:5002}"
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis (e.g. Upstash) should set REDIS_URL to their
|
||||
# rediss:// endpoint in .env and remove the wwv-redis service and depends_on below.
|
||||
- "REDIS_URL=redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
@@ -39,6 +52,24 @@ services:
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry above when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
wwv-redis-data:
|
||||
@@ -0,0 +1,206 @@
|
||||
# MCP Quickstart: Connect an AI Agent to WorldWideView
|
||||
|
||||
Connect Claude Desktop, Cursor, or any MCP-compatible client to your own WorldWideView
|
||||
globe. MCP is available in the **local (self-hosted) edition** that you run yourself.
|
||||
|
||||
> Cloud edition (hosted at worldmonitor.app) is not yet available. When it launches, the
|
||||
> same steps apply but you will use your cloud account and the cloud endpoint instead of
|
||||
> localhost. See "Cloud edition (coming soon)" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- The WorldWideView repository, run locally (this is the **local edition**, the default).
|
||||
- Node.js 20+, pnpm 9+, and Docker (Docker is needed for Postgres, and for Redis + the
|
||||
data engine if you want command tools and live data).
|
||||
- An MCP-compatible client: Claude Desktop, Cursor, VS Code with an MCP extension, or any
|
||||
client that supports the Streamable HTTP MCP transport.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Install and configure
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm setup # generates AUTH_SECRET and your local .env (required for API keys to work)
|
||||
```
|
||||
|
||||
`pnpm setup` writes a random `AUTH_SECRET` into `.env`. In the local edition that same
|
||||
secret signs your MCP API keys, so this step is required before key generation will work.
|
||||
The edition defaults to `local` (`NEXT_PUBLIC_WWV_EDITION=local`).
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Run the app
|
||||
|
||||
Two ways to run it, depending on which tools you need:
|
||||
|
||||
```bash
|
||||
pnpm dev # frontend + Postgres only. Read/query tools work. Command tools and live
|
||||
# data do NOT (no Redis, no data engine).
|
||||
|
||||
pnpm dev:all # frontend + data engine + Redis (via Docker Compose). Everything works:
|
||||
# read tools, command tools (open-tab control), geocoding, and live data.
|
||||
```
|
||||
|
||||
Use `pnpm dev:all` for the full MCP experience. The app comes up at
|
||||
**http://localhost:3000** (it will pick another port if 3000 is taken; check the startup log).
|
||||
|
||||
| You want... | Run | Why |
|
||||
|---|---|---|
|
||||
| `search_entities`, `get_plugin_data`, `list_available_plugins`, favorites | `pnpm dev` is enough | served from Postgres + the local data-source registry |
|
||||
| `geocode_location`, command tools (`pan_globe`, `fly_to`, `toggle_layer`, ...) | `pnpm dev:all` | need Redis (sessions, command queue, geocode cache) |
|
||||
| Live plugin data on the globe and in data tools | `pnpm dev:all` | needs the data engine |
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Sign in and generate an API key
|
||||
|
||||
1. Open **http://localhost:3000** and sign in. On a first run, create the initial account
|
||||
via the app's setup flow (see the project README for first-user setup).
|
||||
2. Open **Settings -> API and MCP Access**.
|
||||
3. Click **Generate new key**, give it a name, and **copy the key immediately** (it is shown
|
||||
only once). Your key looks like `wwv_abc123.<long-secret>`.
|
||||
|
||||
The same panel ("Connect your agent") shows a ready-to-paste config block with your local
|
||||
endpoint already filled in (`http://localhost:3000/api/mcp`).
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Add the MCP server to your client
|
||||
|
||||
Paste this into your client's MCP configuration (e.g. `claude_desktop_config.json` for
|
||||
Claude Desktop, or the Cursor MCP settings). The endpoint is your local app:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"worldwideview": {
|
||||
"url": "http://localhost:3000/api/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer wwv_<your-key-here>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Replace `wwv_<your-key-here>` with the key from step 3. The key goes in the `Authorization`
|
||||
header, never in the URL.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Restart your client and verify
|
||||
|
||||
Restart your MCP client (Claude Desktop needs a full app restart; Cursor reloads
|
||||
automatically). Ask the agent: "List the available WorldWideView plugins" - it should call
|
||||
`list_available_plugins`. If you started with `pnpm dev:all` and have plugins streaming, you
|
||||
will see them; otherwise see the troubleshooting notes about `engine_unreachable` /
|
||||
`no_active_plugins` below (those mean the connection works but the engine is down or idle).
|
||||
|
||||
---
|
||||
|
||||
## Two capability tiers
|
||||
|
||||
WorldWideView MCP tools split into two tiers based on whether a browser globe session is
|
||||
required.
|
||||
|
||||
### Read / query tools (no open tab required)
|
||||
|
||||
These run server-side and return data using only your API key. You do not need the globe open.
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `search_entities` | Search entities by name across active plugins |
|
||||
| `get_entities_in_region` | Find entities inside a lat/lng bounding box |
|
||||
| `get_entity_details` | Get full details for one entity |
|
||||
| `get_plugin_data` | Get the current snapshot of all entities for a plugin |
|
||||
| `list_available_plugins` | List streaming plugins and their status |
|
||||
| `geocode_location` | Resolve a place name or address to coordinates (needs Redis) |
|
||||
| `save_favorite` | Bookmark an entity |
|
||||
| `list_favorites` | List your bookmarks |
|
||||
| `update_favorite` | Rename or annotate a bookmark |
|
||||
| `remove_favorite` | Delete a bookmark |
|
||||
| `get_plugin_filters` | List filterable fields a plugin declares |
|
||||
|
||||
### Command / control tools (open globe tab required)
|
||||
|
||||
These control the live 3D globe in your browser. **You must keep a WorldWideView browser tab
|
||||
open and signed in as the same account.** Without an open tab, the command is accepted but has
|
||||
no visible effect and the tool returns `"no active globe session to control"`. These also need
|
||||
Redis (run `pnpm dev:all`).
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `pan_globe` | Fly the camera to a coordinate |
|
||||
| `fly_to` | Fly the camera to a geocoded coordinate or bounding box |
|
||||
| `focus_entity` | Centre the camera on a known entity |
|
||||
| `toggle_layer` | Enable or disable a plugin data layer |
|
||||
| `set_timeline` | Set playback time, window, or mode |
|
||||
| `set_filter` | Apply filters to a plugin's live layer |
|
||||
| `clear_filter` | Clear filters on one or all plugins |
|
||||
|
||||
---
|
||||
|
||||
## Recommended agent prompt
|
||||
|
||||
Paste this into your agent's system prompt to give it immediate context:
|
||||
|
||||
```
|
||||
You have access to WorldWideView (WWV) via MCP -- a live 3D globe streaming real-world data
|
||||
(aviation, shipping, earthquakes, weather, and more). Use the MCP tools to query entities,
|
||||
move the camera, toggle layers, and filter data. Command tools require the user to have the
|
||||
WWV globe open in a browser tab. Read/query tools work without a browser tab.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"no active globe session to control"**
|
||||
A command tool (pan_globe, fly_to, toggle_layer, etc.) ran but no globe tab is open. Open
|
||||
http://localhost:3000 in a browser tab, sign in as the same account that owns the API key,
|
||||
and keep the tab open while you use the agent. Also make sure you started with `pnpm dev:all`
|
||||
(command tools need Redis).
|
||||
|
||||
**"engine_unreachable" from list_available_plugins**
|
||||
The data engine is not running or `WWV_DATA_ENGINE_URL` is not set. Start it with
|
||||
`pnpm dev:all`. The MCP connection itself is working.
|
||||
|
||||
**"no_active_plugins" from list_available_plugins**
|
||||
The data engine is up but no plugins are currently streaming. Enable a plugin from the
|
||||
Plugins panel in the globe app.
|
||||
|
||||
**401 Unauthorized**
|
||||
Your API key is invalid or revoked, or `pnpm setup` was never run (no `AUTH_SECRET`).
|
||||
Confirm `.env` has `AUTH_SECRET`, then generate a fresh key in Settings > API and MCP Access.
|
||||
|
||||
**Tools do not appear in my client**
|
||||
Restart the client after editing the config file. For Claude Desktop, a full app
|
||||
quit-and-relaunch is required.
|
||||
|
||||
---
|
||||
|
||||
## Cloud edition (coming soon)
|
||||
|
||||
A hosted cloud edition is planned at worldmonitor.app. It is **not yet available**. When it
|
||||
launches, the flow is the same as above except:
|
||||
|
||||
- You sign in to your cloud account at worldmonitor.app instead of running the app locally.
|
||||
- The MCP endpoint is `https://api.worldmonitor.app/api/mcp` instead of `http://localhost:3000/api/mcp`.
|
||||
- Infrastructure (Redis, the data engine, secrets) is operated for you, so there is no
|
||||
`pnpm setup` / `pnpm dev:all` step.
|
||||
|
||||
Everything else - generating a key, the Authorization header, the two capability tiers, and
|
||||
the open-tab requirement for command tools - is identical.
|
||||
|
||||
---
|
||||
|
||||
## Next steps
|
||||
|
||||
- See [plugin-filter-guide.md](plugin-filter-guide.md) to learn how to use `get_plugin_filters`
|
||||
and `set_filter` to filter live plugin data.
|
||||
- See [plugin-quickstart.md](plugin-quickstart.md) to build your own data plugin.
|
||||
+17
-16
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.48.4",
|
||||
"version": "2.48.15",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -32,37 +32,37 @@
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@prisma/client-runtime-utils": "7.8.0",
|
||||
"@sentry/nextjs": "^10.54.0",
|
||||
"@sentry/nextjs": "^10.56.0",
|
||||
"@supabase/ssr": "^0.10.3",
|
||||
"@supabase/supabase-js": "^2.106.2",
|
||||
"@supabase/supabase-js": "^2.107.0",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@worldwideview/wwv-lib-aviation": "workspace:*",
|
||||
"@worldwideview/wwv-lib-incidents": "workspace:*",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cesium": "^1.141.0",
|
||||
"cesium": "^1.142.0",
|
||||
"cheerio": "^1.2.0",
|
||||
"hls.js": "^1.6.16",
|
||||
"insecam-api": "^0.0.3",
|
||||
"ioredis": "^5.4.1",
|
||||
"jose": "^6.2.3",
|
||||
"lucide-react": "^1.17.0",
|
||||
"next": "16.2.6",
|
||||
"next": "16.2.7",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"openid-client": "^6.8.4",
|
||||
"pg": "^8.21.0",
|
||||
"prisma": "^7.8.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.21.1",
|
||||
"resium": "1.22.0",
|
||||
"satellite.js": "^7.0.1",
|
||||
"stripe": "^22.2.0",
|
||||
"tslib": "^2.8.1",
|
||||
"undici": "^8.3.0",
|
||||
"ws": "^8.21.0",
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^5.0.13"
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.1.0",
|
||||
@@ -78,16 +78,16 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.0",
|
||||
"@typescript-eslint/parser": "^8.60.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.1",
|
||||
"@typescript-eslint/parser": "^8.60.1",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "4.1.7",
|
||||
"@vitest/coverage-v8": "4.1.8",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^18.0.0",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"eslint-config-next": "^16.2.7",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
@@ -96,9 +96,9 @@
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tree-kill": "^1.2.2",
|
||||
"tsx": "^4.22.3",
|
||||
"tsx": "^4.22.4",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.14",
|
||||
"vite": "^8.0.16",
|
||||
"vitest": "^4.1.7"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -107,7 +107,8 @@
|
||||
"form-data@<2.5.4": "^2.5.5",
|
||||
"form-data@>=3.0.0 <3.0.4": "^3.0.4",
|
||||
"form-data@>=4.0.0 <4.0.4": "^4.0.5",
|
||||
"fast-uri@<3.1.2": "^3.1.2"
|
||||
"fast-uri@<3.1.2": "^3.1.2",
|
||||
"vitest@<4.1.0": "^4.1.8"
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"@prisma/engines",
|
||||
|
||||
Generated
+820
-953
File diff suppressed because it is too large.
Load diff
+36
@@ -0,0 +1,36 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "marketplace_credentials" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"version" TEXT NOT NULL,
|
||||
"salt" TEXT NOT NULL,
|
||||
"nonce" TEXT NOT NULL,
|
||||
"ciphertext" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "marketplace_credentials_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "user_api_keys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"prefix" TEXT NOT NULL,
|
||||
"hashedSecret" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastUsedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "user_api_keys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "marketplace_credentials_tenantId_key" ON "marketplace_credentials"("tenantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "user_api_keys_prefix_key" ON "user_api_keys"("prefix");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_api_keys" ADD CONSTRAINT "user_api_keys_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable: add nullable notes column to favorites
|
||||
-- This is a non-destructive additive change. Existing rows receive NULL.
|
||||
ALTER TABLE "favorites" ADD COLUMN IF NOT EXISTS "notes" TEXT;
|
||||
@@ -14,6 +14,10 @@ model User {
|
||||
name String
|
||||
hashedPassword String
|
||||
role String @default("user")
|
||||
// Bumping this invalidates all of the user's existing JWT sessions.
|
||||
// The JWT embeds the value at sign-in; the auth jwt callback rejects any
|
||||
// token whose value no longer matches the DB (logout-everywhere / revoke).
|
||||
sessionVersion Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth, signOut } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* POST /api/auth/revoke: "sign out everywhere".
|
||||
*
|
||||
* Increments the authenticated user's `sessionVersion`, which invalidates every
|
||||
* existing JWT issued for that user: the auth `jwt` callback compares each
|
||||
* token's embedded version against the DB on its next use and rejects stale
|
||||
* ones. Also clears the caller's own session cookie.
|
||||
*
|
||||
* Requires an authenticated session. Same-origin only in practice: the session
|
||||
* cookie is `sameSite=lax`, so a cross-site POST carries no credentials.
|
||||
*/
|
||||
export async function POST() {
|
||||
const session = await auth();
|
||||
const userId = session?.user?.id;
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Cloud identities are managed by Supabase; there is no local users row to bump.
|
||||
if (!isCloud) {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { sessionVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
|
||||
await signOut({ redirect: false });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -7,6 +7,18 @@ import { safeFetch } from "@/lib/security/ssrf";
|
||||
|
||||
const MAX_IFRAME_DURATION_MS = 10 * 1000; // 10 seconds timeout for HTML
|
||||
|
||||
/**
|
||||
* Escape a string for safe inclusion in an HTML attribute value.
|
||||
*/
|
||||
function escapeHtmlAttr(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy for iframe HTML pages.
|
||||
* Fetches the target HTML, strips X-Frame-Options and CSP, and injects a <base href="...">
|
||||
@@ -62,7 +74,8 @@ export async function GET(req: NextRequest) {
|
||||
let html = await upstream.text();
|
||||
|
||||
// Inject <base href="..."> right after <head> or at the very beginning of the document
|
||||
const baseTag = `<base href="${targetUrl}">\n`;
|
||||
const escapedUrl = escapeHtmlAttr(targetUrl);
|
||||
const baseTag = `<base href="${escapedUrl}">\n`;
|
||||
if (html.includes("<head>")) {
|
||||
html = html.replace("<head>", `<head>\n${baseTag}`);
|
||||
} else if (html.includes("<HEAD>")) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { GET } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Module mocks -- declared before any imports of the SUT so Vitest hoists them.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/healthProbes", () => ({
|
||||
probeRedis: vi.fn(),
|
||||
probeDb: vi.fn(),
|
||||
probeEngine: vi.fn(),
|
||||
probeConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
edition: "local",
|
||||
}));
|
||||
|
||||
import {
|
||||
probeRedis,
|
||||
probeDb,
|
||||
probeEngine,
|
||||
probeConfig,
|
||||
} from "@/lib/healthProbes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function setProbes(opts: {
|
||||
redis?: boolean;
|
||||
db?: boolean;
|
||||
engine?: boolean;
|
||||
config?: boolean;
|
||||
}): void {
|
||||
vi.mocked(probeRedis).mockResolvedValue(opts.redis ?? true);
|
||||
vi.mocked(probeDb).mockResolvedValue(opts.db ?? true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(opts.engine ?? true);
|
||||
// probeConfig is synchronous in the real impl; mock as a plain return value.
|
||||
vi.mocked(probeConfig).mockReturnValue(opts.config ?? true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/health", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("returns 200 healthy when all probes pass (OBS-01 happy path)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("healthy");
|
||||
expect(body.checks).toEqual({ redis: true, db: true, engine: true, config: true });
|
||||
expect(body).toHaveProperty("edition");
|
||||
expect(body).toHaveProperty("timestamp");
|
||||
});
|
||||
|
||||
it("returns 200 degraded with checks.redis=false when redis probe fails (OBS-01 redis-down)", async () => {
|
||||
setProbes({ redis: false, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.redis).toBe(false);
|
||||
expect(body.checks.db).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when db probe fails (OBS-01 db-down)", async () => {
|
||||
setProbes({ redis: true, db: false, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.db).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 200 degraded when engine probe fails (OBS-01 engine-down)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: false, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.engine).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when config probe fails in cloud edition (OBS-01 config-misconfigured)", async () => {
|
||||
// Simulate cloud edition with getSigningKey() having thrown (probeConfig returns false).
|
||||
vi.mocked(probeConfig).mockReturnValue(false);
|
||||
vi.mocked(probeRedis).mockResolvedValue(true);
|
||||
vi.mocked(probeDb).mockResolvedValue(true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(true);
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.config).toBe(false);
|
||||
});
|
||||
|
||||
it("includes edition and ISO timestamp in every response (OBS-01 shape)", async () => {
|
||||
setProbes({});
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(typeof body.edition).toBe("string");
|
||||
expect(typeof body.timestamp).toBe("string");
|
||||
// ISO 8601 basic check
|
||||
expect(body.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,66 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { edition } from "@/core/edition";
|
||||
import { probeRedis, probeDb, probeEngine, probeConfig } from "@/lib/healthProbes";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({ status: "healthy" }, { status: 200 });
|
||||
// ---------------------------------------------------------------------------
|
||||
// Status + HTTP code policy:
|
||||
// db down OR config misconfigured (cloud/demo) -> "unhealthy", 503
|
||||
// Rationale: the app is either unable to authenticate requests or
|
||||
// fundamentally broken. A load balancer or container orchestrator should
|
||||
// stop routing traffic and alert the operator.
|
||||
// redis down OR engine down (but db + config ok) -> "degraded", 200
|
||||
// Rationale: auth/session reads still work; only streaming data or
|
||||
// rate-limiting is impaired. 200 avoids container restarts for transient
|
||||
// upstream outages.
|
||||
// all ok -> "healthy", 200
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type HealthStatus = "healthy" | "degraded" | "unhealthy";
|
||||
|
||||
interface HealthBody {
|
||||
status: HealthStatus;
|
||||
checks: {
|
||||
redis: boolean;
|
||||
db: boolean;
|
||||
engine: boolean;
|
||||
config: boolean;
|
||||
};
|
||||
edition: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<NextResponse<HealthBody>> {
|
||||
// Run all probes in parallel. probeConfig is sync but wrapped in
|
||||
// Promise.resolve so all four settle together with Promise.all.
|
||||
const [redis, db, engine, config] = await Promise.all([
|
||||
probeRedis(),
|
||||
probeDb(),
|
||||
probeEngine(),
|
||||
Promise.resolve(probeConfig()),
|
||||
]);
|
||||
|
||||
const checks = { redis, db, engine, config };
|
||||
|
||||
let status: HealthStatus;
|
||||
let httpStatus: 200 | 503;
|
||||
|
||||
if (!db || !config) {
|
||||
status = "unhealthy";
|
||||
httpStatus = 503;
|
||||
} else if (!redis || !engine) {
|
||||
status = "degraded";
|
||||
httpStatus = 200;
|
||||
} else {
|
||||
status = "healthy";
|
||||
httpStatus = 200;
|
||||
}
|
||||
|
||||
const body: HealthBody = {
|
||||
status,
|
||||
checks,
|
||||
edition,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return NextResponse.json(body, { status: httpStatus });
|
||||
}
|
||||
@@ -76,6 +76,21 @@ describe("radiusKmToBbox", () => {
|
||||
expect(bbox.east).toBeCloseTo(11, 1);
|
||||
expect(bbox.west).toBeCloseTo(9, 1);
|
||||
});
|
||||
|
||||
it("globe-spanning radius (30000 km) produces full-longitude box, not antimeridian strip", () => {
|
||||
// Without the lonDelta cap a 30000 km radius produces lonDelta >> 180,
|
||||
// and wrapLon(lon + lonDelta) collapses to a tiny strip near the antimeridian.
|
||||
// With the cap, lonDelta = 180, so east and west both map to the antimeridian
|
||||
// (+180 and -180 are the same line). The key invariant is that the longitude
|
||||
// span equals 360 degrees (east - west mod 360 = 0 = full globe).
|
||||
const bbox = radiusKmToBbox(0, 0, 30000);
|
||||
// Both east and west land on the antimeridian (180 = -180 in wrapped coords).
|
||||
const normalise = (v: number) => Math.abs(Math.abs(v) - 180);
|
||||
expect(normalise(bbox.east)).toBeCloseTo(0, 4);
|
||||
expect(normalise(bbox.west)).toBeCloseTo(0, 4);
|
||||
expect(bbox.north).toBeCloseTo(90, 0);
|
||||
expect(bbox.south).toBeCloseTo(-90, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -147,11 +162,28 @@ describe("listStreamingPlugins", () => {
|
||||
expect(result.plugins[0].entityCount).toBe(1);
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine unreachable' } when no snapshots", async () => {
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when no snapshots and engine not reachable (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so engineReachable=false -> engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine unreachable");
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
|
||||
it("returns no_active_plugins when engine reachable but zero snapshots (TOOL-05)", async () => {
|
||||
// Mock fetch to simulate engine responding OK (reachable, but no plugins).
|
||||
const savedFetch = global.fetch;
|
||||
global.fetch = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ plugins: [] }), { status: 200 }),
|
||||
);
|
||||
try {
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("no_active_plugins");
|
||||
} finally {
|
||||
global.fetch = savedFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -263,15 +295,15 @@ describe("listStreamingPlugins -- source tagging", () => {
|
||||
expect(byId["camera"]).toBe("local");
|
||||
});
|
||||
|
||||
it("engine-unreachable passthrough: empty snapshots still returns { plugins: [], reason: 'engine unreachable' }", async () => {
|
||||
it("engine-unreachable passthrough: empty snapshots returns engine_unreachable when probe fails (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
// localIds irrelevant when snapshots list is empty
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine unreachable");
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -41,7 +41,9 @@ export function radiusKmToBbox(lat: number, lon: number, radiusKm: number): Regi
|
||||
const latDelta = radiusKm / 111;
|
||||
const cosLat = Math.cos((lat * Math.PI) / 180);
|
||||
const clampedCos = Math.max(cosLat, 0.01);
|
||||
const lonDelta = radiusKm / (111 * clampedCos);
|
||||
// Cap lonDelta at 180 so a globe-spanning radius yields the full longitude
|
||||
// range [-180, 180] rather than wrapping to a thin antimeridian strip.
|
||||
const lonDelta = Math.min(radiusKm / (111 * clampedCos), 180);
|
||||
const wrapLon = (v: number): number => ((((v + 180) % 360) + 360) % 360) - 180;
|
||||
return {
|
||||
north: Math.min(lat + latDelta, 90),
|
||||
@@ -102,17 +104,48 @@ export interface ListStreamingPluginsResult {
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes whether the data engine manifest endpoint is reachable.
|
||||
* Returns true when the engine responds with 2xx, false on network error or non-2xx.
|
||||
*
|
||||
* Timeout is intentionally short (2000ms) so callers on the empty-snapshot path
|
||||
* are not blocked waiting for a slow engine.
|
||||
*/
|
||||
async function probeEngineReachable(): Promise<boolean> {
|
||||
const engineUrl = (process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001") + "/manifest";
|
||||
try {
|
||||
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(2000) });
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the engine manifest and per-plugin snapshots to build a summary list.
|
||||
* Returns `{ plugins: [], reason: "engine unreachable" }` when no snapshots are
|
||||
* available (engine down or no active plugins).
|
||||
*
|
||||
* Reasons when plugins array is empty:
|
||||
* engine_unreachable -- manifest fetch failed or engine returned non-2xx.
|
||||
* no_active_plugins -- engine reachable but zero plugins active right now.
|
||||
*
|
||||
* Local sources (e.g. camera) are tagged source:'local' and are surfaced
|
||||
* even when the engine is down (getAllPluginSnapshots includes local sources).
|
||||
*
|
||||
* The probe runs only on the empty-snapshot path to avoid the double-manifest
|
||||
* hit on every happy-path call.
|
||||
*/
|
||||
export async function listStreamingPlugins(): Promise<ListStreamingPluginsResult> {
|
||||
const snapshots = await getAllPluginSnapshots();
|
||||
const [snapshots, localIds] = await Promise.all([
|
||||
getAllPluginSnapshots(),
|
||||
getLocalSourceIds(),
|
||||
]);
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
return { plugins: [], reason: "engine unreachable" };
|
||||
const engineReachable = await probeEngineReachable();
|
||||
const reason = engineReachable ? "no_active_plugins" : "engine_unreachable";
|
||||
return { plugins: [], reason };
|
||||
}
|
||||
const localIds = await getLocalSourceIds();
|
||||
|
||||
const plugins: StreamingPlugin[] = snapshots.map((snap) => ({
|
||||
pluginId: snap.pluginId,
|
||||
pluginName: snap.pluginId, // manifest exposes ids only
|
||||
|
||||
@@ -114,14 +114,15 @@ describe("list_available_plugins", () => {
|
||||
expect(parsed.plugins[0].entityTypes).toContain("status");
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine unreachable' } when engine is down", async () => {
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when engine is down (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_available_plugins"]({});
|
||||
const parsed = parsedOf(result) as { plugins: unknown[]; reason: string };
|
||||
|
||||
expect(parsed.plugins).toHaveLength(0);
|
||||
expect(parsed.reason).toBe("engine unreachable");
|
||||
expect(parsed.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -262,4 +263,42 @@ describe("investigate_area", () => {
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary).toContain("ZZZ_NONEXISTENT");
|
||||
});
|
||||
|
||||
it("truncation (TOOL-04/P33): returns truncated:true and cappedTotal when result exceeds 200 cap", async () => {
|
||||
// Two plugins both named with "vessel" substring so entity_type:"vessel" matches both.
|
||||
// Each returns 110 entities = 220 total, exceeding INVESTIGATE_AREA_CAP (200).
|
||||
const makeEntities = (pluginId: string, count: number) =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: `${pluginId}-${i}`,
|
||||
pluginId,
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
}));
|
||||
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "vessel-ais", entities: [], timestamp: new Date() },
|
||||
{ pluginId: "vessel-cargo", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-ais", 110) })
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-cargo", 110) });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["investigate_area"]({
|
||||
place_name: "Auckland",
|
||||
entity_type: "vessel",
|
||||
});
|
||||
const parsed = parsedOf(result) as {
|
||||
entities: unknown[];
|
||||
count: number;
|
||||
truncated?: boolean;
|
||||
cappedTotal?: number;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
expect(parsed.entities).toHaveLength(200);
|
||||
expect(parsed.count).toBe(200);
|
||||
expect(parsed.truncated).toBe(true);
|
||||
expect(parsed.cappedTotal).toBe(220);
|
||||
});
|
||||
});
|
||||
@@ -46,6 +46,9 @@ const DEFAULT_RADIUS_KM = 50;
|
||||
/** Altitude (metres) used for camera pan commands from investigate_area. */
|
||||
const INVESTIGATE_PAN_ALT = 300_000;
|
||||
|
||||
/** Maximum total entities returned across all plugins by investigate_area (TOOL-04). */
|
||||
const INVESTIGATE_AREA_CAP = 200;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -125,6 +128,7 @@ export function registerDiscoveryTools(
|
||||
"Use this tool when an agent asks 'what is near X?' or 'show me Y around Z'. Prefer this over manual geocode + search_entities sequences. " +
|
||||
"When no matching plugin streams the given entity_type, the summary explains this and suggests list_available_plugins. " +
|
||||
"When no active session is found, entities are still returned but the summary notes the camera pan was skipped. " +
|
||||
"Response is capped at 200 entities total across all matched plugins. When 'truncated' is true, 'cappedTotal' holds the sum of per-plugin results before the global cap (not the true global count, because each plugin is itself queried with its own 100-entity limit). " +
|
||||
"Parameters: place_name (required), entity_type (required, case-insensitive substring match against plugin ids/names), radius_km (optional, default 50). " +
|
||||
"Example: investigate_area({place_name:\"Auckland\",entity_type:\"flights\",radius_km:100})",
|
||||
inputSchema: {
|
||||
@@ -195,18 +199,31 @@ export function registerDiscoveryTools(
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
}
|
||||
|
||||
// Step 5: Build prose summary using first matched plugin as representative.
|
||||
// Step 5: Apply overall cap and record truncation metadata.
|
||||
// cappedTotal is the sum of per-plugin results before the global cap.
|
||||
// It is NOT the true global count because each plugin is queried with
|
||||
// its own 100-entity limit before reaching here.
|
||||
const cappedTotal = allEntities.length;
|
||||
const truncated = cappedTotal > INVESTIGATE_AREA_CAP;
|
||||
const entities = truncated ? allEntities.slice(0, INVESTIGATE_AREA_CAP) : allEntities;
|
||||
|
||||
// Step 6: Build prose summary using first matched plugin as representative.
|
||||
const representativePlugin = matched[0].pluginId;
|
||||
const summary = buildInvestigateProse({
|
||||
displayName: geo.display_name,
|
||||
entityType: entity_type,
|
||||
matchedPlugin: representativePlugin,
|
||||
entityCount: allEntities.length,
|
||||
entityCount: entities.length,
|
||||
sessionPresent,
|
||||
emptyReason: lastEmptyReason,
|
||||
});
|
||||
|
||||
return textResult({ entities: allEntities, summary });
|
||||
return textResult({
|
||||
entities,
|
||||
count: entities.length,
|
||||
...(truncated && { truncated: true, cappedTotal }),
|
||||
summary,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] investigate_area failed:", err);
|
||||
return textResult({
|
||||
|
||||
@@ -53,6 +53,9 @@ describe("favoritesTools tool descriptions (DESC-03)", () => {
|
||||
|
||||
describe("save_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
|
||||
// findUnique returns null -> new row, count returns 0 -> below cap
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
@@ -73,6 +76,8 @@ describe("save_favorite tool handler", () => {
|
||||
});
|
||||
|
||||
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
|
||||
@@ -83,6 +88,34 @@ describe("save_favorite tool handler", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects when user is at the 500-favorite cap and entity is new", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(500 as never);
|
||||
|
||||
const result = await handlers["save_favorite"]({
|
||||
entityId: "newship:999",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalled();
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("favorite limit of 500 reached");
|
||||
});
|
||||
|
||||
it("allows upsert when entity already exists (no count check needed)", async () => {
|
||||
// findUnique returns an existing row -> cap check is skipped
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue({ id: "existing" } as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.count).not.toHaveBeenCalled();
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("list_favorites tool handler", () => {
|
||||
|
||||
@@ -25,6 +25,9 @@ import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
import type { Prisma } from "@/generated/prisma";
|
||||
import { pluginIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
|
||||
const FAVORITES_CAP = 500;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
@@ -74,16 +77,31 @@ export function registerFavoritesTools(
|
||||
"Output: 'Saved favorite: <label>'. " +
|
||||
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
|
||||
inputSchema: {
|
||||
entityId: z.string().min(1).describe("Unique entity identifier"),
|
||||
pluginId: z.string().min(1).describe("Plugin that owns this entity"),
|
||||
entityId: entityIdSchema.describe("Unique entity identifier"),
|
||||
pluginId: pluginIdSchema.describe("Plugin that owns this entity"),
|
||||
name: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(120)
|
||||
.optional()
|
||||
.describe("Human-readable label for the bookmark (defaults to entityId)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
// Cap: reject new rows when the user already has FAVORITES_CAP favorites.
|
||||
// Upserts that update an existing row are always allowed.
|
||||
const existing = await prisma.favorite.findUnique({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) {
|
||||
const count = await prisma.favorite.count({ where: { userId } });
|
||||
if (count >= FAVORITES_CAP) {
|
||||
return textResult(`favorite limit of ${FAVORITES_CAP} reached`);
|
||||
}
|
||||
}
|
||||
|
||||
const label = args.name ?? args.entityId;
|
||||
await prisma.favorite.upsert({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
@@ -162,9 +180,9 @@ export function registerFavoritesTools(
|
||||
"Output: 'Updated favorite: <label>' on success, or an error string. " +
|
||||
"Example: update_favorite({ favoriteId: 'AFR123', name: 'Air France 123', notes: 'Check weekly' }).",
|
||||
inputSchema: {
|
||||
favoriteId: z.string().min(1).describe("The entityId of the favorite to update"),
|
||||
name: z.string().optional().describe("New display label for the bookmark"),
|
||||
notes: z.string().optional().describe("Free-text annotation to store with the bookmark"),
|
||||
favoriteId: entityIdSchema.describe("The entityId of the favorite to update"),
|
||||
name: z.string().min(1).max(120).optional().describe("New display label for the bookmark"),
|
||||
notes: z.string().max(2000).optional().describe("Free-text annotation to store with the bookmark"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
@@ -203,7 +221,7 @@ export function registerFavoritesTools(
|
||||
"Output: 'Removed favorite: <entityId>'. " +
|
||||
"Example: remove_favorite({ entityId: 'AFR123' }).",
|
||||
inputSchema: {
|
||||
entityId: z.string().min(1).describe("Entity identifier to remove from favorites"),
|
||||
entityId: entityIdSchema.describe("Entity identifier to remove from favorites"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
|
||||
@@ -22,6 +22,9 @@ import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQ
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { pluginIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { listStreamingPlugins } from "@/app/api/mcp/discoveryHelpers";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
@@ -64,14 +67,16 @@ export function registerFilterTools(
|
||||
"set_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Apply one or more filters to a plugin's live globe layer (no page reload). " +
|
||||
"Use after get_plugin_filters to discover valid filter ids; affects the live globe layer, not data query tools. " +
|
||||
"Limitations: filter ids are plugin-specific; invalid ids are silently ignored by the browser. " +
|
||||
"Use list_available_plugins to confirm valid pluginIds before calling. " +
|
||||
"Limitations: filter ids are plugin-specific; unknown pluginIds produce a warning in the response. " +
|
||||
"Parameters: pluginId (string, required); filters (object, required) -- filterId -> { type: 'text', value } | { type: 'select', values } | { type: 'range', min, max } | { type: 'boolean', value }; sessionId (optional). " +
|
||||
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or 'no active globe session to control'. " +
|
||||
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or a warning when the pluginId is unrecognized. " +
|
||||
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
|
||||
inputSchema: {
|
||||
pluginId: z.string().min(1).describe("Plugin whose layer to filter, e.g. 'flights'"),
|
||||
pluginId: pluginIdSchema.describe("Plugin whose layer to filter, e.g. 'flights'"),
|
||||
filters: z
|
||||
.record(z.string(), filterValueSchema)
|
||||
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
|
||||
@@ -83,12 +88,23 @@ export function registerFilterTools(
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Validate the pluginId against the live streaming plugin set.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.pluginId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setFilter",
|
||||
pluginId: args.pluginId,
|
||||
filters: args.filters,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but pluginId '${args.pluginId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(
|
||||
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
|
||||
);
|
||||
@@ -104,6 +120,7 @@ export function registerFilterTools(
|
||||
"clear_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Clear active filters on the live globe. " +
|
||||
"Prefer clear_filter over re-setting filters to empty values; omit pluginId to clear ALL filters across every plugin at once. " +
|
||||
"Limitations: requires an active globe session; returns 'no active globe session to control' when no tab is live. " +
|
||||
@@ -111,7 +128,7 @@ export function registerFilterTools(
|
||||
"Output: 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins'. " +
|
||||
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
|
||||
inputSchema: {
|
||||
pluginId: z.string().optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
|
||||
pluginId: pluginIdSchema.optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
@@ -149,7 +166,7 @@ export function registerFilterTools(
|
||||
"Output: { available: true, filters: FilterDefinition[] } when the plugin is loaded, where each FilterDefinition is { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?, range? }; or { available: false, reason: 'plugin not loaded' | 'no_session_active' } when unavailable. " +
|
||||
"Example: get_plugin_filters({ pluginId: 'flights' }) -> { available: true, filters: [{ id: 'status', label: 'Status', type: 'select', options: [...] }] }.",
|
||||
inputSchema: {
|
||||
pluginId: z.string().min(1).describe("Plugin to inspect for declared filterable fields"),
|
||||
pluginId: pluginIdSchema.describe("Plugin to inspect for declared filterable fields"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim");
|
||||
vi.mock("@/lib/nominatim", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
|
||||
return {
|
||||
...actual,
|
||||
fetchGeocode: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* MCP Geocoding Tool registrar (Phase 22 Wave 2 -- 22-02).
|
||||
* MCP Geocoding Tool registrar (Phase 22 Wave 2, 22-02).
|
||||
*
|
||||
* Registers two MCP tools:
|
||||
* geocode_location -- resolve a place name/address to coordinates via Nominatim
|
||||
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
|
||||
* fly_to -- enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
|
||||
* geocode_location: resolve a place name/address to coordinates via Nominatim
|
||||
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
|
||||
* fly_to: enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (verified auth result), never from tool
|
||||
* arguments. The Nominatim URL is hardcoded; the user query is injected via
|
||||
@@ -15,11 +15,12 @@ import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
|
||||
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
@@ -33,29 +34,6 @@ function textResult(text: string): McpTextResult {
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
|
||||
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
|
||||
* only stub fetchGeocode -- do not stub out the normalization step.
|
||||
* Nominatim boundingbox is ["south","north","west","east"]; remap to
|
||||
* [west, south, east, north] numbers.
|
||||
*/
|
||||
function normalizeResult(r: RawNominatimItem): NominatimResult {
|
||||
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
|
||||
return {
|
||||
lat: parseFloat(r.lat ?? "0"),
|
||||
lng: parseFloat(r.lon ?? "0"),
|
||||
name: r.name ?? "",
|
||||
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
|
||||
type: r.type ?? "",
|
||||
addresstype: r.addresstype ?? "",
|
||||
country: r.address?.country ?? "",
|
||||
display_name: r.display_name ?? "",
|
||||
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
|
||||
importance: r.importance ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
|
||||
async function cacheGet(key: string): Promise<string | null> {
|
||||
try {
|
||||
@@ -112,7 +90,7 @@ export function registerGeocodingTools(
|
||||
"Resolve a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
|
||||
"Use before fly_to to obtain lat/lng from a name; do not guess coordinates. " +
|
||||
"Limitations: Nominatim is rate-limited per user; results are cached 24h; returns 'no results found' when nothing matches. " +
|
||||
"Parameters: query (string, required) -- place name or address; limit (integer 1-20, optional, default 5). " +
|
||||
"Parameters: query (string, required) - place name or address; limit (integer 1-20, optional, default 5). " +
|
||||
"Output: JSON array sorted by importance, each { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west,south,east,north], importance }. " +
|
||||
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...] }].",
|
||||
inputSchema: {
|
||||
@@ -140,7 +118,7 @@ export function registerGeocodingTools(
|
||||
const raw = await fetchGeocode({ query: args.query, limit });
|
||||
if (raw.length === 0) return textResult("no results found");
|
||||
|
||||
const results = raw.map(normalizeResult);
|
||||
const results = (raw as RawNominatimItem[]).map(normalizeNominatimResult);
|
||||
const json = JSON.stringify(results);
|
||||
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
|
||||
return textResult(json);
|
||||
@@ -156,11 +134,12 @@ export function registerGeocodingTools(
|
||||
"fly_to",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the live globe camera to a geocoded coordinate, optionally fitting a bounding box in view. " +
|
||||
"Requires an active globe session (read globe://sessions first); returns 'no active globe session to control' when no tab is live. " +
|
||||
"Prefer pan_globe for relative panning or focus_entity to snap to a known entity; use fly_to when you have explicit lat/lng (e.g. from geocode_location). " +
|
||||
"Parameters: lat (-90..90, required), lng (-180..180, required), altitude (metres, optional, default 15000), " +
|
||||
"bbox ([west,south,east,north], optional -- fit this region in view), sessionId (optional -- omit for most-recently-active tab). " +
|
||||
"bbox ([west,south,east,north], optional - fit this region in view), sessionId (optional - omit for most-recently-active tab). " +
|
||||
"Example: fly_to({ lat: 48.85, lng: 2.35 }) or fly_to({ lat: 0, lng: 0, bbox: [2.2,48.8,2.5,48.9] }).",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude [-90, 90]"),
|
||||
|
||||
@@ -22,9 +22,11 @@ import { latSchema as sharedLatSchema, lonSchema as sharedLonSchema } from "@/li
|
||||
// declared with vi.hoisted() to be accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueue, mockResolveSessionId } = vi.hoisted(() => ({
|
||||
const { mockEnqueue, mockResolveSessionId, mockListStreamingPlugins, mockGetEntityDetails } = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
|
||||
mockListStreamingPlugins: vi.fn().mockResolvedValue({ plugins: [] }),
|
||||
mockGetEntityDetails: vi.fn().mockResolvedValue({ data: null, emptyReason: "no_data_matches" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
@@ -32,6 +34,14 @@ vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
resolveActiveSessionId: mockResolveSessionId,
|
||||
}));
|
||||
|
||||
vi.mock("./discoveryHelpers", () => ({
|
||||
listStreamingPlugins: mockListStreamingPlugins,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
getEntityDetails: mockGetEntityDetails,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake McpServer — records registered tools
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -56,6 +66,8 @@ beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueue.mockResolvedValue(undefined);
|
||||
mockResolveSessionId.mockResolvedValue("resolved-session");
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [] });
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -435,3 +447,133 @@ describe("get_entities_in_region coordinate schema bounds (TOOL-09)", () => {
|
||||
expect(sharedLonSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): toggle_layer unrecognized id warning
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("toggle_layer -- unrecognized layerId warning (TOOL-02/P33)", () => {
|
||||
it("enqueues command and returns warning when layerId is not a known plugin", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "unknown-layer-xyz" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("unknown-layer-xyz");
|
||||
});
|
||||
|
||||
it("enqueues command and returns plain success when layerId is recognized", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "flights" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).not.toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("flights");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): focus_entity server-side entity-id resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("focus_entity -- server-side entity resolution (TOOL-02/P33)", () => {
|
||||
it("resolves lat/lon from entityId+pluginId when coordinates are absent", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({
|
||||
data: {
|
||||
id: "ship-1",
|
||||
pluginId: "ais",
|
||||
latitude: 35.68,
|
||||
longitude: 139.69,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
},
|
||||
});
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "ship-1",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ type: "focusEntity", lat: 35.68, lon: 139.69 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("35.68");
|
||||
});
|
||||
|
||||
it("returns honest failure when entityId cannot be resolved (no pluginId provided)", async () => {
|
||||
// Without pluginId the resolver path is skipped and resolution fails.
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({ entityId: "unknown-entity" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
expect(result.content[0].text).toContain("unknown-entity");
|
||||
});
|
||||
|
||||
it("returns honest failure when entity not found in plugin snapshot", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "missing-entity",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
});
|
||||
|
||||
it("uses provided lat/lon directly without calling getEntityDetails", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "e1",
|
||||
lat: 10,
|
||||
lon: 20,
|
||||
});
|
||||
|
||||
expect(mockGetEntityDetails).not.toHaveBeenCalled();
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ lat: 10, lon: 20 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("10");
|
||||
});
|
||||
});
|
||||
@@ -21,9 +21,13 @@ import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQ
|
||||
import { TIME_WINDOW_VALUES } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { latSchema, lonSchema, altSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { layerIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
import { listStreamingPlugins } from "./discoveryHelpers";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
|
||||
// Re-export so existing tests that import from this module continue to work.
|
||||
export { latSchema, lonSchema, altSchema };
|
||||
export { latSchema, lonSchema, altSchema, layerIdSchema };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
@@ -66,6 +70,7 @@ export function registerGlobeCommandTools(
|
||||
"pan_globe",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the globe camera to an explicit coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer pan_globe over focus_entity when you have a lat/lon and no entity id, or when focus_entity entity-id resolution is not needed. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180], altitude > 0 metres; out-of-range values are rejected. " +
|
||||
@@ -109,13 +114,18 @@ export function registerGlobeCommandTools(
|
||||
"focus_entity",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Point the globe camera at a known entity or coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it; note entity-id-to-coordinate resolution is not yet wired, so always include lat/lon for a reliable camera move. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180]; entityId alone will not move the camera until resolution is wired. " +
|
||||
"Parameters: entityId (optional, informational), lat (recommended), lon (recommended), sessionId (optional). " +
|
||||
"Example: focus_entity({entityId:\"ship-123\",lat:35.68,lon:139.69})",
|
||||
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it. " +
|
||||
"When lat/lon are provided they are used directly. " +
|
||||
"When only entityId is provided (no lat/lon), the server resolves coordinates via pluginId + entityId lookup -- include pluginId for a faster, scoped lookup. " +
|
||||
"Returns an error string when entityId cannot be resolved to coordinates. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180]. " +
|
||||
"Parameters: entityId (optional), pluginId (optional, scopes entity lookup), lat (optional), lon (optional), sessionId (optional). " +
|
||||
"Example: focus_entity({entityId:\"ship-123\",pluginId:\"ais\",lat:35.68,lon:139.69})",
|
||||
inputSchema: {
|
||||
entityId: z.string().optional().describe("Entity id (informational; coordinate resolution not yet supported -- also provide lat/lon)"),
|
||||
entityId: entityIdSchema.optional().describe("Entity id to focus on"),
|
||||
pluginId: z.string().optional().describe("Plugin that owns this entity -- narrows the id lookup when lat/lon are not provided"),
|
||||
lat: latSchema.optional().describe("Latitude to focus on [-90, 90]"),
|
||||
lon: lonSchema.optional().describe("Longitude to focus on [-180, 180]"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
@@ -126,14 +136,39 @@ export function registerGlobeCommandTools(
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
let resolvedLat = args.lat;
|
||||
let resolvedLon = args.lon;
|
||||
|
||||
// When coordinates are absent but entityId is present, resolve server-side.
|
||||
if (resolvedLat === undefined && resolvedLon === undefined && args.entityId !== undefined) {
|
||||
if (args.pluginId !== undefined) {
|
||||
const detail = await getEntityDetails(args.pluginId, args.entityId);
|
||||
if (detail.data !== null) {
|
||||
resolvedLat = detail.data.latitude;
|
||||
resolvedLon = detail.data.longitude;
|
||||
}
|
||||
}
|
||||
|
||||
if (resolvedLat === undefined) {
|
||||
// entityId could not be resolved -- return an honest failure instead of
|
||||
// enqueuing a command the browser cannot execute.
|
||||
return textResult(
|
||||
`Could not resolve entityId '${args.entityId}' to coordinates. ` +
|
||||
`Provide pluginId to scope the lookup, or include lat/lon directly.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "focusEntity",
|
||||
...(args.entityId !== undefined && { entityId: args.entityId }),
|
||||
...(args.lat !== undefined && { lat: args.lat }),
|
||||
...(args.lon !== undefined && { lon: args.lon }),
|
||||
...(resolvedLat !== undefined && { lat: resolvedLat }),
|
||||
...(resolvedLon !== undefined && { lon: resolvedLon }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${args.lat ?? "none"}, lon=${args.lon ?? "none"})`);
|
||||
return textResult(
|
||||
`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${resolvedLat ?? "none"}, lon=${resolvedLon ?? "none"})`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] focus_entity failed:", err);
|
||||
return textResult("focus_entity command failed");
|
||||
@@ -146,13 +181,15 @@ export function registerGlobeCommandTools(
|
||||
"toggle_layer",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Enable or disable a plugin data layer on the globe. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer toggle_layer over pan_globe or set_timeline when changing layer visibility, not camera position or playback time. " +
|
||||
"Limitations: layerId must match an installed plugin id; unknown ids are silently ignored by the browser. " +
|
||||
"Parameters: layerId (required), enabled (true/false, optional — omit to toggle current state), sessionId (optional). " +
|
||||
"Use list_available_plugins to confirm valid layerIds before calling. " +
|
||||
"Limitations: layerId must match an installed plugin id. When the id is not recognized a warning is included in the response. " +
|
||||
"Parameters: layerId (required), enabled (true/false, optional -- omit to toggle current state), sessionId (optional). " +
|
||||
"Example: toggle_layer({layerId:\"ais\",enabled:true})",
|
||||
inputSchema: {
|
||||
layerId: z.string().describe("The plugin/layer identifier to toggle"),
|
||||
layerId: layerIdSchema.describe("The plugin/layer identifier to toggle"),
|
||||
enabled: z.boolean().optional().describe("True to enable, false to disable, omit to toggle"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
},
|
||||
@@ -162,12 +199,23 @@ export function registerGlobeCommandTools(
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Check whether the layerId matches a known streaming plugin.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.layerId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "toggleLayer",
|
||||
layerId: args.layerId,
|
||||
...(args.enabled !== undefined && { enabled: args.enabled }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but layerId '${args.layerId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(`Layer '${args.layerId}' toggle command enqueued`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] toggle_layer failed:", err);
|
||||
@@ -181,6 +229,7 @@ export function registerGlobeCommandTools(
|
||||
"set_timeline",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Set the globe timeline position, time window, or playback mode. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer set_timeline over toggle_layer or pan_globe when adjusting time or playback, not layer visibility or camera position. " +
|
||||
"Limitations: currentTime must be ISO 8601; timeWindow must be one of '1h','6h','24h','48h','7d'. " +
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* SEC-02: Redis per-key rate limiting in /api/mcp route tests.
|
||||
*
|
||||
* Verifies the post-auth Redis sliding-window gate behavior.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks (same surface as route.test.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/geocodingRateLimit", () => ({
|
||||
redisSlidingWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
const McpServer = vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn(),
|
||||
};
|
||||
});
|
||||
const ResourceTemplate = vi.fn(function ResourceTemplateMock(this: unknown, uriTemplate: string) {
|
||||
return { uriTemplate };
|
||||
});
|
||||
return { McpServer, ResourceTemplate };
|
||||
});
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js", () => {
|
||||
const WebStandardStreamableHTTPServerTransport = vi.fn().mockImplementation(() => ({
|
||||
handleRequest: vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"X-Accel-Buffering": "no",
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
),
|
||||
}));
|
||||
return { WebStandardStreamableHTTPServerTransport };
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Imports (after mocks)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { POST } from "./route";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makePost(authorization?: string): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (authorization) headers["authorization"] = authorization;
|
||||
return new Request("http://localhost:3000/api/mcp", { method: "POST", headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-02: per-key Redis rate limit gate", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
});
|
||||
|
||||
it("passes through when Redis allows the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
expect(res.status).not.toBe(429);
|
||||
});
|
||||
|
||||
it("returns 429 JSON-RPC -32000 when Redis rejects the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: false, retryAfterMs: 60_000 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
expect(body).toMatchObject({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32000, message: "rate limit exceeded" },
|
||||
id: null,
|
||||
});
|
||||
expect(res.headers.get("Retry-After")).toBe("60");
|
||||
});
|
||||
|
||||
it("rate limit check uses the authenticated keyId, not userId or raw header", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-abc", keyId: "key-xyz" });
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
await POST(makePost("Bearer wwv_valid.token"));
|
||||
|
||||
expect(vi.mocked(redisSlidingWindow)).toHaveBeenCalledWith(
|
||||
expect.stringContaining("key-xyz"),
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("rate limit is not checked when auth fails (no authenticated keyId available)", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const res = await POST(makePost("Bearer bogus.token"));
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(vi.mocked(redisSlidingWindow)).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -246,6 +246,31 @@ describe("MCP-01/MCP-02: Valid auth + non-demo -> request passes both gates", ()
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-04: tools.listChanged must NOT be advertised as true
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-04: McpServer is not created with tools.listChanged: true", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("capabilities passed to McpServer constructor have listChanged false or absent (never true)", async () => {
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
const mcpCtor = vi.mocked(McpServer);
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
await POST(req);
|
||||
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(1);
|
||||
// second arg is the options object: { instructions, capabilities }
|
||||
const options = mcpCtor.mock.calls[0][1] as { capabilities?: { tools?: { listChanged?: boolean } } } | undefined;
|
||||
const listChanged = options?.capabilities?.tools?.listChanged;
|
||||
expect(listChanged).not.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-06: Streaming headers — X-Accel-Buffering: no must be present (Pitfall 1)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -271,6 +296,93 @@ describe("MCP-06: Streaming response headers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-01: Top-level error boundary — unexpected throws -> JSON-RPC -32603
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-01: unhandled error during request handling yields JSON-RPC -32603", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("POST returns HTTP 500 with JSON-RPC -32603 body when a registrar throws", async () => {
|
||||
// Simulate an unexpected failure after auth succeeds (e.g. Redis down).
|
||||
// We make authenticateApiKey succeed but then make registerOrientationPrompts
|
||||
// throw by having McpServer.registerPrompt throw.
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
vi.mocked(McpServer).mockImplementationOnce(function (this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn().mockImplementation(() => {
|
||||
throw new Error("Redis connection refused");
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("GET returns HTTP 500 with JSON-RPC -32603 body when transport.handleRequest throws", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
vi.mocked(WebStandardStreamableHTTPServerTransport).mockImplementationOnce(() => ({
|
||||
handleRequest: vi.fn().mockRejectedValue(new Error("stream error")),
|
||||
}));
|
||||
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
// Defense-in-depth: if authenticateApiKey ever regresses and throws instead
|
||||
// of returning null, the boundary must still catch it and return -32603.
|
||||
// In practice TRANS-02 makes authenticateApiKey return null on DB outage,
|
||||
// so this path is hypothetical, not a real DB-outage scenario.
|
||||
it("-32603 response carries streaming headers (X-Accel-Buffering: no) [defense-in-depth: hypothetical auth throw]", async () => {
|
||||
vi.mocked(authenticateApiKey).mockRejectedValue(new Error("DB down"));
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
|
||||
it("existing 401 path is NOT affected by the error boundary", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest("POST");
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error.code).toBe(-32600);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-05: Stateless freshness — per-request construction (Pitfall 2)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+47
-32
@@ -31,6 +31,13 @@ import { isDemo } from "@/core/edition";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { createMcpServer, registerOrientationPrompts } from "@/lib/mcp/server";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
import {
|
||||
demoBlockedResponse,
|
||||
unauthorizedResponse,
|
||||
rateLimitedResponse,
|
||||
internalErrorResponse,
|
||||
} from "@/lib/mcp/mcpResponseHelpers";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import { registerDataQueryTools } from "@/lib/mcp/tools";
|
||||
import { registerGlobeCommandTools } from "./globeCommandTools";
|
||||
@@ -42,38 +49,16 @@ import { registerFilterTools } from "./filterTools";
|
||||
import { registerDiscoveryTools } from "./discoveryTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JSON-RPC 2.0 error response helpers
|
||||
// Route segment config (TRANS-03)
|
||||
// 30 s is comfortably above the 10 s blpop ceiling in RELAY_DEADLINE_MS so the
|
||||
// function never times out mid-relay. Vercel/Coolify honour this value.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns 403 + JSON-RPC 2.0 body for the demo edition gate (MCP-04).
|
||||
* Runs BEFORE auth so the demo-admin FK write path is never reached.
|
||||
*/
|
||||
function demoBlockedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
export const maxDuration = 30;
|
||||
|
||||
/**
|
||||
* Returns 401 + JSON-RPC 2.0 body for missing / invalid Bearer token (MCP-03).
|
||||
* Content-Type is application/json (not plain text — Pitfall 3).
|
||||
*/
|
||||
function unauthorizedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
// Per-key rate-limit budget (SEC-02): 120 requests per 60-second window.
|
||||
const MCP_KEY_LIMIT = 120;
|
||||
const MCP_WINDOW_MS = 60_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Header merge helper
|
||||
@@ -159,6 +144,18 @@ async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 3: Redis per-key rate limit (SEC-02).
|
||||
// 120 req / 60s per authenticated key, complementing the coarse IP
|
||||
// gate above. Fails OPEN on Redis outage so a broken Redis never
|
||||
// blocks legit users.
|
||||
// ------------------------------------------------------------------
|
||||
const keyRateKey = `mcp:ratelimit:key:${authResult.keyId}`;
|
||||
const keyLimit = await redisSlidingWindow(keyRateKey, MCP_KEY_LIMIT, MCP_WINDOW_MS);
|
||||
if (!keyLimit.allowed) {
|
||||
return rateLimitedResponse(keyLimit.retryAfterMs);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build a FRESH server + transport per request (D-17-04, MCP-05).
|
||||
// STATELESS INVARIANT: never hoist these to module scope.
|
||||
@@ -230,14 +227,32 @@ async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
// Route exports (App Router)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Top-level error boundary (TRANS-01).
|
||||
* Any throw between auth and transport (DB outage, Redis rejection, unexpected
|
||||
* SDK error) is caught here so MCP clients always receive a well-formed
|
||||
* JSON-RPC -32603 frame instead of a bare HTML 500.
|
||||
* The bearer token/secret is never logged.
|
||||
*/
|
||||
async function safeHandleMcpRequest(request: Request): Promise<Response> {
|
||||
try {
|
||||
return await handleMcpRequest(request);
|
||||
} catch (err: unknown) {
|
||||
const name = err instanceof Error ? err.name : "unknown";
|
||||
const detail = process.env.NODE_ENV !== "production" && err instanceof Error ? ` ${err.message}` : "";
|
||||
console.error(`[mcp] unhandled error in request handler: ${name}${detail}`);
|
||||
return internalErrorResponse();
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ export function BottomPanelManager() {
|
||||
);
|
||||
|
||||
const isCoveredRef = useRef(false);
|
||||
const isDraggingRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeBottomPanel) {
|
||||
@@ -39,17 +40,18 @@ export function BottomPanelManager() {
|
||||
}, [activeBottomPanel]);
|
||||
|
||||
// Pointer-capture drag handlers — attached directly to the resize handle element.
|
||||
// Using setPointerCapture ensures pointermove/pointerup are delivered to the
|
||||
// element even when the pointer leaves it, which is required for webkit
|
||||
// (without capture, webkit drops synthetic pointermove events from Playwright
|
||||
// and from fast real-user drags that leave the element bounds).
|
||||
// setPointerCapture ensures pointermove/pointerup are delivered to the element even
|
||||
// when the pointer leaves its bounds (required for fast real-user drags and Playwright).
|
||||
// isDraggingRef guards the move handler instead of hasPointerCapture, which has
|
||||
// inconsistent behaviour across webkit versions in CI for repeated drag sequences.
|
||||
const handleResizePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
isDraggingRef.current = true;
|
||||
document.body.classList.add("is-dragging-bottom-panel");
|
||||
};
|
||||
|
||||
const handleResizePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
|
||||
if (!isDraggingRef.current) return;
|
||||
const newHeight = window.innerHeight - e.clientY;
|
||||
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
@@ -57,6 +59,7 @@ export function BottomPanelManager() {
|
||||
|
||||
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
isDraggingRef.current = false;
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Copy, Check } from "lucide-react";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared style tokens (mirror PersonalApiKeysSection to keep visual parity)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
fontSize: 12,
|
||||
width: "100%",
|
||||
outline: "none",
|
||||
fontFamily: "var(--font-mono)",
|
||||
};
|
||||
|
||||
const buttonStyle: React.CSSProperties = {
|
||||
background: "none",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
fontSize: 12,
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
};
|
||||
|
||||
export const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
|
||||
|
||||
export const subHeaderStyle: React.CSSProperties = {
|
||||
fontSize: 11,
|
||||
fontWeight: 600,
|
||||
color: "var(--text-secondary)",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.08em",
|
||||
marginBottom: "var(--space-xs)",
|
||||
marginTop: "var(--space-md)",
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CopyField sub-component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
interface CopyFieldProps {
|
||||
value: string;
|
||||
label: string;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
export function CopyField({ value, label, multiline = false }: CopyFieldProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function handleCopy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
} catch {
|
||||
// Clipboard access denied -- user must copy manually.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "var(--space-sm)" }}>
|
||||
<div style={mutedMicro}>{label}</div>
|
||||
<div style={{ display: "flex", gap: "var(--space-xs)", marginTop: "var(--space-xs)" }}>
|
||||
{multiline ? (
|
||||
<textarea
|
||||
readOnly
|
||||
value={value}
|
||||
rows={value.split("\n").length + 1}
|
||||
style={{
|
||||
...inputStyle,
|
||||
resize: "vertical",
|
||||
minHeight: 80,
|
||||
}}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={value}
|
||||
style={inputStyle}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
style={{
|
||||
...buttonStyle,
|
||||
color: copied ? "#22c55e" : "var(--text-primary)",
|
||||
flexShrink: 0,
|
||||
alignSelf: "flex-start",
|
||||
}}
|
||||
title={copied ? "Copied!" : `Copy ${label}`}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { Copy, Check, Terminal } from "lucide-react";
|
||||
import { Terminal, Info } from "lucide-react";
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { CopyField, mutedMicro, subHeaderStyle } from "./ConnectAgentCopyField";
|
||||
import { AGENT_PROMPT } from "./connectAgentPrompt";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
const PLACEHOLDER_TOKEN = "wwv_<prefix>.<secret>";
|
||||
|
||||
/**
|
||||
@@ -49,156 +49,6 @@ function resolveMcpUrl(): string {
|
||||
return "http://localhost:3000/api/mcp";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared style tokens (mirror PersonalApiKeysSection to keep visual parity)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
fontSize: 12,
|
||||
width: "100%",
|
||||
outline: "none",
|
||||
fontFamily: "var(--font-mono)",
|
||||
};
|
||||
|
||||
const buttonStyle: React.CSSProperties = {
|
||||
background: "none",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
fontSize: 12,
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
};
|
||||
|
||||
const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
|
||||
|
||||
const subHeaderStyle: React.CSSProperties = {
|
||||
fontSize: 11,
|
||||
fontWeight: 600,
|
||||
color: "var(--text-secondary)",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.08em",
|
||||
marginBottom: "var(--space-xs)",
|
||||
marginTop: "var(--space-md)",
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CopyField sub-component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface CopyFieldProps {
|
||||
value: string;
|
||||
label: string;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
function CopyField({ value, label, multiline = false }: CopyFieldProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function handleCopy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
} catch {
|
||||
// Clipboard access denied -- user must copy manually.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "var(--space-sm)" }}>
|
||||
<div style={mutedMicro}>{label}</div>
|
||||
<div style={{ display: "flex", gap: "var(--space-xs)", marginTop: "var(--space-xs)" }}>
|
||||
{multiline ? (
|
||||
<textarea
|
||||
readOnly
|
||||
value={value}
|
||||
rows={value.split("\n").length + 1}
|
||||
style={{
|
||||
...inputStyle,
|
||||
resize: "vertical",
|
||||
minHeight: 80,
|
||||
}}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={value}
|
||||
style={inputStyle}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
style={{
|
||||
...buttonStyle,
|
||||
color: copied ? "#22c55e" : "var(--text-primary)",
|
||||
flexShrink: 0,
|
||||
alignSelf: "flex-start",
|
||||
}}
|
||||
title={copied ? "Copied!" : `Copy ${label}`}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Agent-capabilities prompt (CONNECT-03)
|
||||
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
|
||||
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
|
||||
// documented in docs/plugin-filter-guide.md.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
|
||||
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
|
||||
incidents, weather, and custom data plugins.
|
||||
|
||||
This MCP connection is live and authenticated. You can call these tools:
|
||||
|
||||
Data query:
|
||||
- search_entities: search entities by name across active plugins; supports optional inline filters.
|
||||
- get_entities_in_region: find entities inside a lat/lng bounding box.
|
||||
- get_entity_details: get full details for one entity by pluginId + entityId.
|
||||
- get_plugin_data: get the current snapshot of all entities for a plugin.
|
||||
|
||||
Location (geocoding + camera):
|
||||
- geocode_location: resolve a place name or address to coordinates and a bounding box.
|
||||
- fly_to: fly the live globe camera to a coordinate or bounding box.
|
||||
|
||||
Favorites:
|
||||
- save_favorite: bookmark an entity so the user can return to it later.
|
||||
- list_favorites: list the user's bookmarks, each with a live/stale status.
|
||||
- remove_favorite: delete a bookmarked entity.
|
||||
|
||||
Live filtering:
|
||||
- get_plugin_filters: list the filterable fields a plugin declares.
|
||||
- set_filter: apply filters to a plugin's layer on the live globe.
|
||||
- clear_filter: clear one plugin's filters, or all filters.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
|
||||
to find places, move the camera, search and filter live entities, and manage their bookmarks.`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main component
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -246,6 +96,47 @@ export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
|
||||
Use the URL and token below to connect Claude Desktop, Cursor, or VS Code to this globe.
|
||||
</div>
|
||||
|
||||
{/* Prerequisites callout (ONBRD-02) */}
|
||||
<div style={{
|
||||
display: "flex",
|
||||
gap: "var(--space-sm)",
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-sm) var(--space-md)",
|
||||
marginTop: "var(--space-sm)",
|
||||
}}
|
||||
>
|
||||
<Info size={13} style={{ color: "var(--text-muted)", flexShrink: 0, marginTop: 1 }} />
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-xs)" }}>
|
||||
<div style={{ ...mutedMicro, fontWeight: 600, color: "var(--text-secondary)" }}>
|
||||
Before connecting
|
||||
</div>
|
||||
<ul style={{ ...mutedMicro, margin: 0, paddingLeft: "var(--space-md)", lineHeight: 1.6 }}>
|
||||
<li>
|
||||
You must be <strong>signed in</strong> to WorldWideView. Your API key is tied to your account.
|
||||
</li>
|
||||
{isCloud && (
|
||||
<li>
|
||||
MCP access is a <strong>cloud edition</strong> feature. It is not available on the demo edition.
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<strong>Read/query tools</strong> (search, geocode, favorites, plugin data) work with just
|
||||
your API key and do not require an open browser tab.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Command/control tools</strong> (pan_globe, fly_to, toggle_layer, set_filter, etc.)
|
||||
require this WorldWideView tab to stay open and signed in. Without an open globe tab the
|
||||
command is accepted but has no visible effect.
|
||||
</li>
|
||||
</ul>
|
||||
<div style={mutedMicro}>
|
||||
New here? Follow the MCP quickstart guide in the project docs (docs/mcp-quickstart.md) for step-by-step setup.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Section: mcpServers JSON (CONNECT-02) */}
|
||||
<div style={subHeaderStyle}>Claude Desktop / Cursor / VS Code</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Agent-capabilities prompt (CONNECT-03).
|
||||
* Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
|
||||
* with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
|
||||
* documented in docs/plugin-filter-guide.md.
|
||||
*/
|
||||
export const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
|
||||
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
|
||||
incidents, weather, and custom data plugins.
|
||||
|
||||
This MCP connection is live and authenticated. You can call these tools:
|
||||
|
||||
Data query:
|
||||
- search_entities: search entities by name across active plugins; supports optional inline filters.
|
||||
- get_entities_in_region: find entities inside a lat/lng bounding box.
|
||||
- get_entity_details: get full details for one entity by pluginId + entityId.
|
||||
- get_plugin_data: get the current snapshot of all entities for a plugin.
|
||||
|
||||
Location (geocoding + camera):
|
||||
- geocode_location: resolve a place name or address to coordinates and a bounding box.
|
||||
- fly_to: fly the live globe camera to a coordinate or bounding box.
|
||||
|
||||
Favorites:
|
||||
- save_favorite: bookmark an entity so the user can return to it later.
|
||||
- list_favorites: list the user's bookmarks, each with a live/stale status.
|
||||
- remove_favorite: delete a bookmarked entity.
|
||||
|
||||
Live filtering:
|
||||
- get_plugin_filters: list the filterable fields a plugin declares.
|
||||
- set_filter: apply filters to a plugin's layer on the live globe.
|
||||
- clear_filter: clear one plugin's filters, or all filters.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
|
||||
to find places, move the camera, search and filter live entities, and manage their bookmarks.
|
||||
|
||||
Note: fly_to, set_filter, and clear_filter control the live globe and only take visible effect while you have a signed-in WorldWideView browser tab open. The read and query tools work with just your API key.`;
|
||||
@@ -48,6 +48,24 @@ export const isCloud: boolean = edition === "cloud";
|
||||
/** True when running as the public demo instance. */
|
||||
export const isDemo: boolean = edition === "demo";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Secure-context detection (https)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* True when the deployment serves over https, derived from the configured auth
|
||||
* URL or a production NODE_ENV. This is the request-independent half of the
|
||||
* secure-context check: the NextAuth cookie WRITER (auth.ts) uses it to decide
|
||||
* the secure flag / __Secure- cookie prefix, and the edge proxy READER (proxy.ts)
|
||||
* ORs it with per-request X-Forwarded-Proto / protocol when reading the token.
|
||||
* Centralised here so the writer and reader can never disagree on which cookie
|
||||
* name is in play behind a TLS-terminating reverse proxy.
|
||||
*/
|
||||
export function isHttpsDeployment(): boolean {
|
||||
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
|
||||
return authUrl.startsWith("https://") || process.env.NODE_ENV === "production";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Demo admin secret (must be before feature flags so they can reference it)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* SEC-04: isValidGlobeCommand input cap tests.
|
||||
*
|
||||
* Verifies that toggleLayer, setFilter, and clearFilter enforce the
|
||||
* layerId/pluginId charset and length bounds introduced in SEC-04.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isValidGlobeCommand } from "./GlobeCommand";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// toggleLayer -- layerId caps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- toggleLayer layerId caps (SEC-04)", () => {
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ais" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "wwv-flights-2" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "plugin.v2" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects layerId longer than 64 chars", () => {
|
||||
const long = "a".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts layerId of exactly 64 chars", () => {
|
||||
const exact = "a".repeat(64);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: exact })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects layerId with spaces", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "bad id" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects layerId with colons (reserved for entityId)", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ship:123" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects empty layerId", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects null layerId", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// setFilter -- pluginId caps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- setFilter pluginId caps (SEC-04)", () => {
|
||||
const validFilters = { status: { type: "text", value: "live" } };
|
||||
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: validFilters })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects pluginId longer than 64 chars", () => {
|
||||
const long = "a".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: long, filters: validFilters })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pluginId with special chars outside the allowed set", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "bad id!", filters: validFilters })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects empty pluginId", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: validFilters })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// clearFilter -- pluginId caps (optional)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- clearFilter pluginId caps (SEC-04)", () => {
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts absent pluginId (clear all)", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects oversized pluginId", () => {
|
||||
const long = "x".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pluginId with disallowed chars", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "a b" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// focusEntity -- entityId caps (MUST-FIX #1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- focusEntity entityId caps (SEC-04)", () => {
|
||||
it("accepts a normal entity id", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship:123" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight/AFR123" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts absent entityId (coordinate-only focus)", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 35.68, lon: 139.69 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts entityId of exactly 256 chars", () => {
|
||||
const exact = "a".repeat(256);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: exact })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects entityId longer than 256 chars", () => {
|
||||
const long = "a".repeat(257);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects entityId with control characters", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship\x00123" })).toBe(false);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight\n456" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
import { PLUGIN_ID_MAX, PLUGIN_ID_RE, ENTITY_ID_MAX } from "@/lib/mcp/identifierSchemas";
|
||||
|
||||
// Must stay in sync with the TimeWindow union in @worldwideview/wwv-plugin-sdk.
|
||||
export const TIME_WINDOW_VALUES = ["1h", "6h", "24h", "48h", "7d"] as const;
|
||||
@@ -29,18 +30,27 @@ function isValidAlt(v: unknown): v is number {
|
||||
return isNumber(v) && v > 0;
|
||||
}
|
||||
|
||||
function isString(v: unknown): v is string {
|
||||
return typeof v === "string";
|
||||
// SEC-04: bounds come from identifierSchemas.ts (single source of truth)
|
||||
function isValidPluginOrLayerId(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= PLUGIN_ID_MAX && PLUGIN_ID_RE.test(v);
|
||||
}
|
||||
|
||||
function isValidEntityId(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= ENTITY_ID_MAX && !/[\x00-\x1F\x7F]/.test(v);
|
||||
}
|
||||
|
||||
function isOptionalEntityId(v: unknown): boolean {
|
||||
return v === undefined || isValidEntityId(v);
|
||||
}
|
||||
|
||||
function isOptionalPluginOrLayerId(v: unknown): boolean {
|
||||
return v === undefined || isValidPluginOrLayerId(v);
|
||||
}
|
||||
|
||||
function isOptionalNumber(v: unknown): boolean {
|
||||
return v === undefined || isNumber(v);
|
||||
}
|
||||
|
||||
function isOptionalString(v: unknown): boolean {
|
||||
return v === undefined || isString(v);
|
||||
}
|
||||
|
||||
function isOptionalBoolean(v: unknown): boolean {
|
||||
return v === undefined || typeof v === "boolean";
|
||||
}
|
||||
@@ -100,14 +110,14 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
|
||||
case "focusEntity":
|
||||
return (
|
||||
isOptionalString(cmd["entityId"]) &&
|
||||
isOptionalEntityId(cmd["entityId"]) &&
|
||||
(cmd["lat"] === undefined || isValidLat(cmd["lat"])) &&
|
||||
(cmd["lon"] === undefined || isValidLon(cmd["lon"]))
|
||||
);
|
||||
|
||||
case "toggleLayer":
|
||||
return (
|
||||
isString(cmd["layerId"]) &&
|
||||
isValidPluginOrLayerId(cmd["layerId"]) &&
|
||||
isOptionalBoolean(cmd["enabled"])
|
||||
);
|
||||
|
||||
@@ -136,14 +146,14 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
}
|
||||
|
||||
case "setFilter": {
|
||||
if (typeof cmd["pluginId"] !== "string" || cmd["pluginId"] === "") return false;
|
||||
if (!isValidPluginOrLayerId(cmd["pluginId"])) return false;
|
||||
const filters = cmd["filters"];
|
||||
if (filters === null || typeof filters !== "object" || Array.isArray(filters)) return false;
|
||||
return Object.values(filters as Record<string, unknown>).every(isValidFilterValue);
|
||||
}
|
||||
|
||||
case "clearFilter":
|
||||
return isOptionalString(cmd["pluginId"]);
|
||||
return isOptionalPluginOrLayerId(cmd["pluginId"]);
|
||||
|
||||
default:
|
||||
return false;
|
||||
|
||||
@@ -13,6 +13,8 @@ export const prisma = {
|
||||
favorite: {
|
||||
upsert: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* SEC-01: getSigningKey() enforcement tests.
|
||||
*
|
||||
* Each describe block uses vi.resetModules() + vi.doMock() to control
|
||||
* the edition and environment independently -- the module-level mocks in
|
||||
* apiKeyAuth.test.ts cannot be re-used here because they are static.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
// Restore env before each test so mutations do not bleed
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
vi.resetModules();
|
||||
vi.doUnmock("@/core/edition");
|
||||
});
|
||||
|
||||
async function importGenerateApiKey() {
|
||||
// Dynamic import after resetModules + doMock so the edition mock is picked up
|
||||
const mod = await import("./apiKeyAuth");
|
||||
return mod.generateApiKey;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Local edition: AUTH_SECRET fallback must still work (dev DX)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: local edition -- AUTH_SECRET fallback is allowed", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
isDemo: false,
|
||||
}));
|
||||
});
|
||||
|
||||
it("succeeds when only AUTH_SECRET is set (no API_KEY_HMAC_SECRET)", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET equals AUTH_SECRET in local edition", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "shared-secret";
|
||||
process.env.AUTH_SECRET = "shared-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
|
||||
it("throws only when neither key is set", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
delete process.env.AUTH_SECRET;
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cloud edition: dedicated key required, must differ from AUTH_SECRET
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: cloud edition -- API_KEY_HMAC_SECRET required and distinct", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "cloud",
|
||||
isLocal: false,
|
||||
isCloud: true,
|
||||
isDemo: false,
|
||||
}));
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "shared-secret";
|
||||
process.env.AUTH_SECRET = "shared-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-cloud";
|
||||
process.env.AUTH_SECRET = "different-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Demo edition: same enforcement as cloud
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: demo edition -- API_KEY_HMAC_SECRET required and distinct", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "demo",
|
||||
isLocal: false,
|
||||
isCloud: false,
|
||||
isDemo: true,
|
||||
}));
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "same";
|
||||
process.env.AUTH_SECRET = "same";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-demo";
|
||||
process.env.AUTH_SECRET = "different-auth-secret-demo";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,9 @@ vi.mock("@/lib/db", () => ({
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
}));
|
||||
|
||||
// AUTH_SECRET must be set so getSigningKey() does not throw in the test env
|
||||
@@ -156,6 +159,17 @@ describe("authenticateApiKey", () => {
|
||||
// compare is well-defined and does not throw.
|
||||
});
|
||||
|
||||
it("returns null (does not throw) when Prisma findUnique rejects (DB outage — TRANS-02)", async () => {
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockRejectedValue(
|
||||
new Error("Connection refused")
|
||||
);
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX.fakesecret" },
|
||||
});
|
||||
// Must resolve to null, not reject
|
||||
await expect(authenticateApiKey(req)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("hashedSecret is never returned to callers — result only contains userId and keyId", async () => {
|
||||
const { prefix, secret, hashedSecret } = generateApiKey();
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue({
|
||||
|
||||
+38
-6
@@ -1,14 +1,38 @@
|
||||
import { randomBytes, createHmac, timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { edition } from "@/core/edition";
|
||||
import { isSigningKeyValid } from "@/lib/signingKeyConfig";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Signing key for HMAC-SHA256 hashing of API key secrets.
|
||||
// API_KEY_HMAC_SECRET is the preferred dedicated variable.
|
||||
// Falls back to AUTH_SECRET so local dev works without adding a new .env entry.
|
||||
// Falls back to AUTH_SECRET in local edition only, so dev works without a
|
||||
// separate .env entry.
|
||||
//
|
||||
// Lazy enforcement (not a bare module-level throw): Next.js evaluates module
|
||||
// code at build time and during edge prerender. A top-level throw would break
|
||||
// `next build` in environments where these env vars are not yet populated.
|
||||
// Throwing inside the function means the check fires only on the first real
|
||||
// auth call, where a missing/shared key is an actual runtime problem.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function getSigningKey(): string {
|
||||
const key = process.env.API_KEY_HMAC_SECRET ?? process.env.AUTH_SECRET;
|
||||
const dedicated = process.env.API_KEY_HMAC_SECRET;
|
||||
const fallback = process.env.AUTH_SECRET;
|
||||
|
||||
if (edition === "cloud" || edition === "demo") {
|
||||
if (!isSigningKeyValid()) {
|
||||
throw new Error(
|
||||
`API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in ${edition} edition`,
|
||||
);
|
||||
}
|
||||
// isSigningKeyValid() returning true guarantees dedicated is set and
|
||||
// distinct from AUTH_SECRET for cloud/demo editions.
|
||||
return dedicated as string;
|
||||
}
|
||||
|
||||
// local edition: allow AUTH_SECRET fallback for convenience
|
||||
const key = dedicated ?? fallback;
|
||||
if (!key) throw new Error("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
|
||||
return key;
|
||||
}
|
||||
@@ -116,10 +140,18 @@ export async function authenticateApiKey(
|
||||
const prefix = token.substring(0, dotIdx);
|
||||
const secret = token.substring(dotIdx + 1);
|
||||
|
||||
const row = await prisma.userApiKey.findUnique({
|
||||
where: { prefix },
|
||||
select: { id: true, userId: true, hashedSecret: true },
|
||||
});
|
||||
// DB outage guard (TRANS-02): a rejected Prisma call is treated as a miss
|
||||
// so the caller receives null (-> 401) rather than an unhandled rejection.
|
||||
let row: { id: string; userId: string; hashedSecret: string } | null;
|
||||
try {
|
||||
row = await prisma.userApiKey.findUnique({
|
||||
where: { prefix },
|
||||
select: { id: true, userId: true, hashedSecret: true },
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn("[apiKeyAuth] DB error during key lookup:", err instanceof Error ? err.name : "unknown");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Compute HMAC of the supplied secret, then compare with timingSafeEqual.
|
||||
// On a prefix miss we compare against a dummy digest — constant-work on
|
||||
|
||||
+45
-1
@@ -18,8 +18,9 @@ vi.unmock("@/lib/auth");
|
||||
// vi.hoisted() runs before all vi.mock() factories, so the variable is
|
||||
// defined before the hoisted factory closure captures it.
|
||||
// ---------------------------------------------------------------------------
|
||||
const { mockUpsert } = vi.hoisted(() => ({
|
||||
const { mockUpsert, mockFindUnique } = vi.hoisted(() => ({
|
||||
mockUpsert: vi.fn().mockResolvedValue(undefined),
|
||||
mockFindUnique: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
@@ -27,6 +28,7 @@ vi.mock("@/lib/db", () => ({
|
||||
user: {
|
||||
upsert: mockUpsert,
|
||||
findFirst: vi.fn(),
|
||||
findUnique: mockFindUnique,
|
||||
},
|
||||
},
|
||||
}));
|
||||
@@ -54,6 +56,7 @@ vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
getDemoAdminSecret: vi.fn(() => undefined),
|
||||
DEMO_ADMIN_ROLE: "demo-admin",
|
||||
isHttpsDeployment: vi.fn(() => false),
|
||||
}));
|
||||
vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
|
||||
|
||||
@@ -61,6 +64,7 @@ vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
|
||||
import {
|
||||
persistDemoAdminIfNeeded,
|
||||
ensureLocalUserPersisted,
|
||||
revalidateSession,
|
||||
DEMO_ADMIN_ID,
|
||||
DEMO_ADMIN_EMAIL,
|
||||
DEMO_ADMIN_NAME,
|
||||
@@ -148,3 +152,43 @@ describe("persistDemoAdminIfNeeded -- jwt callback guard", () => {
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// revalidateSession -- authoritative JWT revocation check
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("revalidateSession -- jwt revocation check", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns null when the token carries no user id", async () => {
|
||||
const result = await revalidateSession({});
|
||||
expect(result).toBeNull();
|
||||
expect(mockFindUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null when the user no longer exists in the DB (deleted / cross-database token)", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
const result = await revalidateSession({ id: "missing-user", sessionVersion: 0 });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the token sessionVersion is stale (revoked / logout-everywhere)", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 3, role: "user" });
|
||||
const result = await revalidateSession({ id: "u1", sessionVersion: 2 });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the token with role refreshed when the version matches", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 5, role: "admin" });
|
||||
const result = await revalidateSession({ id: "u1", sessionVersion: 5, role: "user" });
|
||||
expect(result).not.toBeNull();
|
||||
expect((result as { role?: string }).role).toBe("admin");
|
||||
});
|
||||
|
||||
it("treats a missing token sessionVersion as 0", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 0, role: "user" });
|
||||
const result = await revalidateSession({ id: "u1" });
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
+75
-5
@@ -3,8 +3,9 @@ import Credentials from "next-auth/providers/credentials";
|
||||
import { compareSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import {
|
||||
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE
|
||||
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE, isHttpsDeployment
|
||||
} from "@/core/edition";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
@@ -91,6 +92,7 @@ const localCredentialsProvider = Credentials({
|
||||
name: "Demo Admin",
|
||||
email: "admin",
|
||||
role: DEMO_ADMIN_ROLE,
|
||||
sessionVersion: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,15 +122,72 @@ const localCredentialsProvider = Credentials({
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
sessionVersion: user.sessionVersion,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// True when the deployment serves over https (session cookie gets the secure
|
||||
// flag / __Secure- prefix). Shared with the edge proxy reader via
|
||||
// isHttpsDeployment() so the cookie writer and reader never disagree on the
|
||||
// __Secure- prefix behind a TLS-terminating reverse proxy.
|
||||
const isSecureDeploy = isHttpsDeployment();
|
||||
|
||||
/**
|
||||
* Authoritative session revocation check, run from the jwt callback on every
|
||||
* non-sign-in request (local/demo editions). Returns the token unchanged when
|
||||
* still valid, or `null` to invalidate the session when:
|
||||
* - the user row no longer exists (deleted, or the token was minted against a
|
||||
* different database, e.g. another worktree/instance even with a shared
|
||||
* AUTH_SECRET), or
|
||||
* - the user's sessionVersion was bumped (logout-everywhere / credential
|
||||
* rotation), making the token's embedded version stale.
|
||||
*/
|
||||
export async function revalidateSession(token: JWT): Promise<JWT | null> {
|
||||
const userId = token.id;
|
||||
if (typeof userId !== "string" || !userId) return null;
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { sessionVersion: true, role: true },
|
||||
});
|
||||
if (!dbUser) return null;
|
||||
|
||||
const tokenVersion = typeof token.sessionVersion === "number" ? token.sessionVersion : 0;
|
||||
if (dbUser.sessionVersion !== tokenVersion) return null;
|
||||
|
||||
// Keep role fresh in case it changed server-side since the token was issued.
|
||||
token.role = dbUser.role;
|
||||
return token;
|
||||
}
|
||||
|
||||
export const {
|
||||
handlers, auth, signIn, signOut
|
||||
} = NextAuth({
|
||||
...authConfig,
|
||||
session: { strategy: "jwt" },
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
// Bound the lifetime of the signature-only token. The edge proxy gate
|
||||
// verifies the JWT signature but cannot reach the DB (no Prisma on the
|
||||
// edge runtime), so a shorter maxAge limits how long a leaked-but-
|
||||
// unexpired token can reach pages before the authoritative revocation
|
||||
// check (revalidateSession) rejects it on any auth() call.
|
||||
maxAge: 7 * 24 * 60 * 60, // 7 days
|
||||
updateAge: 24 * 60 * 60, // sliding refresh, at most once per day
|
||||
},
|
||||
// Explicit, hardened cookie options. These pin NextAuth's secure defaults so
|
||||
// they cannot silently regress: httpOnly blocks JS access (XSS token theft),
|
||||
// sameSite=lax blocks cross-site sends (CSRF), secure requires https in prod.
|
||||
cookies: {
|
||||
sessionToken: {
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
secure: isSecureDeploy,
|
||||
},
|
||||
},
|
||||
},
|
||||
adapter: isCloud ? SupabaseAdapter({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
|
||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
|
||||
@@ -137,21 +196,32 @@ export const {
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
async jwt({ token, user }) {
|
||||
// Initial sign-in: copy identity claims from the authorized user.
|
||||
if (user) {
|
||||
token.role = (user as { role?: string }).role ?? "user";
|
||||
token.role = user.role ?? "user";
|
||||
token.id = user.id;
|
||||
// Embed the user's current sessionVersion so the token can be
|
||||
// compared against the DB on later requests and revoked.
|
||||
token.sessionVersion = user.sessionVersion ?? 0;
|
||||
// Persist the demo-admin synthetic identity on first sign-in so
|
||||
// that the `users` FK target exists for API key creation. Runs
|
||||
// only when `user` is present (initial sign-in, not token refresh).
|
||||
// All values inside come from server-controlled constants.
|
||||
await persistDemoAdminIfNeeded(user.id!, isCloud);
|
||||
return token;
|
||||
}
|
||||
return token;
|
||||
|
||||
// Every subsequent request re-validates the token against the DB so
|
||||
// that deleted users, cross-database tokens, and bumped
|
||||
// sessionVersions are rejected. Cloud identities live in Supabase
|
||||
// (no local `users` row), so they skip the Prisma comparison.
|
||||
if (isCloud) return token;
|
||||
return revalidateSession(token);
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = token.id as string;
|
||||
(session.user as { role?: string }).role = token.role as string;
|
||||
session.user.role = token.role as string | undefined;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ import { matchFilterValue } from "@/core/filters/matchFilterValue";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
import { hasLocalSource, resolveLocalSnapshot, getLocalSourceIds } from "./localSources";
|
||||
|
||||
function getEngineUrl(): string {
|
||||
export function getEngineUrl(): string {
|
||||
return process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001";
|
||||
}
|
||||
|
||||
@@ -211,27 +211,32 @@ export async function getEntitiesInRegion(bounds: RegionOptions): Promise<QueryR
|
||||
}
|
||||
}
|
||||
|
||||
const results: SearchResult[] = [];
|
||||
// Collect all matches first to get a totalMatched count, then cap.
|
||||
const allMatched: SearchResult[] = [];
|
||||
for (const snapshot of snapshots) {
|
||||
for (const entity of snapshot.entities) {
|
||||
if (results.length >= effectiveLimit) break;
|
||||
const { latitude: lat, longitude: lon } = entity;
|
||||
if (lat < south || lat > north) continue;
|
||||
const inLon = isAntimeridian
|
||||
? lon >= west || lon <= east
|
||||
: lon >= west && lon <= east;
|
||||
if (inLon) results.push(entityToSearchResult(entity));
|
||||
if (inLon) allMatched.push(entityToSearchResult(entity));
|
||||
}
|
||||
if (results.length >= effectiveLimit) break;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
if (allMatched.length === 0) {
|
||||
return {
|
||||
entities: [],
|
||||
emptyReason: snapshotNotStreaming ? "plugin_not_streaming" : "no_data_matches",
|
||||
};
|
||||
}
|
||||
return { entities: results };
|
||||
|
||||
const truncated = allMatched.length > effectiveLimit;
|
||||
const results = truncated ? allMatched.slice(0, effectiveLimit) : allMatched;
|
||||
return {
|
||||
entities: results,
|
||||
...(truncated && { totalMatched: allMatched.length }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getEntityDetails(
|
||||
|
||||
@@ -11,16 +11,23 @@ import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
* - no_session_active: the authenticated user has no active globe session.
|
||||
* This value is emitted by the tool layer (which has access to userId),
|
||||
* NEVER by the service layer.
|
||||
*
|
||||
* NOTE: data-query tools (search_entities, get_entities_in_region, get_entity_details,
|
||||
* get_plugin_data) must NEVER emit no_session_active -- they are session-independent.
|
||||
* Only session-required command/filter tools may produce this reason.
|
||||
*/
|
||||
export type EmptyReason = "plugin_not_streaming" | "no_data_matches" | "no_session_active";
|
||||
|
||||
/**
|
||||
* Discriminated result carrying a list of entities and an optional emptyReason.
|
||||
* emptyReason is ONLY present when entities.length === 0.
|
||||
* totalMatched is set when results were capped (entities.length < totalMatched).
|
||||
*/
|
||||
export interface QueryResult<T> {
|
||||
entities: T[];
|
||||
emptyReason?: EmptyReason;
|
||||
/** Total entities that matched before the cap was applied. Present only when the result set was truncated. */
|
||||
totalMatched?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Per-user sliding-window rate limiter for geocoding (Phase 22 Wave 2 -- 22-02).
|
||||
* Per-user sliding-window rate limiter for geocoding (Phase 22 Wave 2, 22-02).
|
||||
*
|
||||
* Implements a Redis ZSET sliding window keyed per user. Each call prunes
|
||||
* entries older than WINDOW_MS, records the current request, bounds the key
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* Best-effort (T-22-02-05): on any Redis error we fail OPEN (return undefined)
|
||||
* so a broken rate-limit check never causes a permanent geocoding outage. The
|
||||
* 1 req/sec limit is advisory, not a hard security boundary.
|
||||
* 1 req/sec limit is advisory rather than a hard security boundary.
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
@@ -26,6 +26,11 @@ function rateKey(userId: string): string {
|
||||
return `nominatim:ratelimit:${userId}`;
|
||||
}
|
||||
|
||||
/** Returns a unique ZSET member string for the current timestamp. */
|
||||
function uniqueMember(now: number): string {
|
||||
return `${now}:${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `undefined` when the request is allowed, or a `rate_limited` result
|
||||
* object when the per-user window limit is exceeded.
|
||||
@@ -35,7 +40,7 @@ export async function checkRateLimit(userId: string): Promise<RateLimitExceeded
|
||||
try {
|
||||
const now = Date.now();
|
||||
await redis.zremrangebyscore(key, "-inf", now - WINDOW_MS);
|
||||
await redis.zadd(key, now, String(now));
|
||||
await redis.zadd(key, now, uniqueMember(now));
|
||||
await redis.expire(key, KEY_TTL_SECONDS);
|
||||
const count = await redis.zcard(key);
|
||||
if (count > MAX_REQUESTS) {
|
||||
@@ -47,3 +52,113 @@ export async function checkRateLimit(userId: string): Promise<RateLimitExceeded
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Generic ZSET sliding-window helper (SEC-02)
|
||||
//
|
||||
// Reusable across any endpoint that needs per-identity Redis-backed limiting.
|
||||
// Fails OPEN on Redis errors. A broken rate limiter should never block legit
|
||||
// traffic. It is advisory rather than a hard security boundary.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface SlidingWindowResult {
|
||||
/** true when the request is within the allowed window */
|
||||
allowed: boolean;
|
||||
/** milliseconds until the oldest request ages out; meaningful only when !allowed */
|
||||
retryAfterMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* ZSET sliding-window check.
|
||||
*
|
||||
* Uses unique members (timestamp + random suffix) so same-millisecond calls
|
||||
* each occupy their own slot rather than collapsing into one (undercount fix).
|
||||
*
|
||||
* retryAfterMs is computed from the oldest in-window entry's score rather than
|
||||
* the full windowMs, giving callers an accurate wait time.
|
||||
*
|
||||
* @param key Redis key (must be unique per identity + endpoint)
|
||||
* @param limit Maximum requests allowed inside the window
|
||||
* @param windowMs Window duration in milliseconds
|
||||
*/
|
||||
export async function redisSlidingWindow(
|
||||
key: string,
|
||||
limit: number,
|
||||
windowMs: number,
|
||||
): Promise<SlidingWindowResult> {
|
||||
try {
|
||||
const now = Date.now();
|
||||
const windowStart = now - windowMs;
|
||||
const ttlSeconds = Math.ceil(windowMs / 1_000) + 1;
|
||||
|
||||
await redis.zremrangebyscore(key, "-inf", windowStart);
|
||||
await redis.zadd(key, now, uniqueMember(now));
|
||||
await redis.expire(key, ttlSeconds);
|
||||
const count = await redis.zcard(key);
|
||||
|
||||
if (count > limit) {
|
||||
// Compute time until the oldest in-window member ages out.
|
||||
const oldest = await redis.zrange(key, 0, 0, "WITHSCORES");
|
||||
const oldestScore = oldest.length >= 2 ? Number(oldest[1]) : now;
|
||||
const retryAfterMs = Math.max(1, oldestScore + windowMs - now);
|
||||
return { allowed: false, retryAfterMs };
|
||||
}
|
||||
return { allowed: true, retryAfterMs: 0 };
|
||||
} catch (err) {
|
||||
console.warn("[redisSlidingWindow] Redis error, failing open:", err);
|
||||
return { allowed: true, retryAfterMs: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DEPLOY-03: peek helper for the global Nominatim throttle poll loop.
|
||||
//
|
||||
// Counts how many requests are currently in the window WITHOUT adding a new
|
||||
// entry. Used by waitForGlobalSlot to poll for slot availability without
|
||||
// inflating the ZSET on every iteration of the wait loop. The committing
|
||||
// add happens only once, via redisSlidingWindow, when the slot is taken.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface SlidingWindowPeekResult {
|
||||
/** Number of entries currently inside the window. */
|
||||
count: number;
|
||||
/** Milliseconds until the oldest in-window entry ages out (0 when count is 0). */
|
||||
retryAfterMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only ZSET sliding-window count.
|
||||
*
|
||||
* Prunes expired entries then counts, but does NOT add a new member.
|
||||
* Fails OPEN (count: 0) on Redis errors so a Redis outage never stalls the
|
||||
* wait loop indefinitely.
|
||||
*
|
||||
* @param key Redis key (same key passed to redisSlidingWindow)
|
||||
* @param windowMs Window duration in milliseconds
|
||||
*/
|
||||
export async function redisSlidingWindowPeek(
|
||||
key: string,
|
||||
windowMs: number,
|
||||
): Promise<SlidingWindowPeekResult> {
|
||||
try {
|
||||
const now = Date.now();
|
||||
const windowStart = now - windowMs;
|
||||
const ttlSeconds = Math.ceil(windowMs / 1_000) + 1;
|
||||
|
||||
await redis.zremrangebyscore(key, "-inf", windowStart);
|
||||
await redis.expire(key, ttlSeconds);
|
||||
const count = await redis.zcard(key);
|
||||
|
||||
if (count === 0) {
|
||||
return { count: 0, retryAfterMs: 0 };
|
||||
}
|
||||
|
||||
const oldest = await redis.zrange(key, 0, 0, "WITHSCORES");
|
||||
const oldestScore = oldest.length >= 2 ? Number(oldest[1]) : now;
|
||||
const retryAfterMs = Math.max(1, oldestScore + windowMs - now);
|
||||
return { count, retryAfterMs };
|
||||
} catch (err) {
|
||||
console.warn("[redisSlidingWindowPeek] Redis error, failing open:", err);
|
||||
return { count: 0, retryAfterMs: 0 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* SEC-03: getClientIp() tests.
|
||||
*
|
||||
* Verifies rightmost x-forwarded-for extraction and WWV_TRUSTED_IP_HEADER
|
||||
* override behavior.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { getClientIp } from "./rateLimit";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
delete process.env.WWV_TRUSTED_IP_HEADER;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
});
|
||||
|
||||
function makeRequest(headers: Record<string, string>): Request {
|
||||
return new Request("http://localhost/test", { headers });
|
||||
}
|
||||
|
||||
describe("getClientIp -- rightmost x-forwarded-for (SEC-03)", () => {
|
||||
it("returns the RIGHTMOST entry of x-forwarded-for (proxy-appended real IP)", () => {
|
||||
const req = makeRequest({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 3.3.3.3" });
|
||||
expect(getClientIp(req)).toBe("3.3.3.3");
|
||||
});
|
||||
|
||||
it("handles single-entry x-forwarded-for correctly", () => {
|
||||
const req = makeRequest({ "x-forwarded-for": "4.4.4.4" });
|
||||
expect(getClientIp(req)).toBe("4.4.4.4");
|
||||
});
|
||||
|
||||
it("trims whitespace from the rightmost entry", () => {
|
||||
const req = makeRequest({ "x-forwarded-for": "1.1.1.1, 5.5.5.5 " });
|
||||
expect(getClientIp(req)).toBe("5.5.5.5");
|
||||
});
|
||||
|
||||
it("falls back to x-real-ip when x-forwarded-for is absent", () => {
|
||||
const req = makeRequest({ "x-real-ip": "6.6.6.6" });
|
||||
expect(getClientIp(req)).toBe("6.6.6.6");
|
||||
});
|
||||
|
||||
it("returns 'unknown' when no IP header is present", () => {
|
||||
const req = makeRequest({});
|
||||
expect(getClientIp(req)).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClientIp -- WWV_TRUSTED_IP_HEADER override (SEC-03)", () => {
|
||||
it("uses the override header when WWV_TRUSTED_IP_HEADER is set", () => {
|
||||
process.env.WWV_TRUSTED_IP_HEADER = "cf-connecting-ip";
|
||||
const req = makeRequest({
|
||||
"cf-connecting-ip": "7.7.7.7",
|
||||
"x-forwarded-for": "attacker-ip",
|
||||
});
|
||||
expect(getClientIp(req)).toBe("7.7.7.7");
|
||||
});
|
||||
|
||||
it("falls back to x-forwarded-for when override header is missing from request", () => {
|
||||
process.env.WWV_TRUSTED_IP_HEADER = "cf-connecting-ip";
|
||||
const req = makeRequest({ "x-forwarded-for": "1.0.0.1, 8.8.8.8" });
|
||||
expect(getClientIp(req)).toBe("8.8.8.8");
|
||||
});
|
||||
|
||||
it("override header lookup is case-insensitive (HTTP headers are case-insensitive)", () => {
|
||||
process.env.WWV_TRUSTED_IP_HEADER = "CF-Connecting-IP";
|
||||
const req = makeRequest({ "cf-connecting-ip": "9.9.9.9" });
|
||||
expect(getClientIp(req)).toBe("9.9.9.9");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Health probe helpers for GET /api/health.
|
||||
*
|
||||
* Each probe catches its own errors and resolves to a boolean.
|
||||
* A probe must never throw out to the caller.
|
||||
* All probes use short timeouts so a hung dependency cannot stall the response.
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getEngineUrl } from "@/lib/data-query/service";
|
||||
import { isSigningKeyValid } from "@/lib/signingKeyConfig";
|
||||
|
||||
// Shared probe timeout in milliseconds.
|
||||
const PROBE_TIMEOUT_MS = 2000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Timeout utility
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Races a promise against a timer. The timer handle is always cleared in
|
||||
* a finally block so no setTimeout handle dangles after the race resolves.
|
||||
*
|
||||
* Returns the fallback value when the timer fires first.
|
||||
*/
|
||||
function withTimeout<T>(op: Promise<T>, fallback: T, ms: number): Promise<T> {
|
||||
let handle: ReturnType<typeof setTimeout>;
|
||||
const timer = new Promise<T>((resolve) => {
|
||||
handle = setTimeout(() => resolve(fallback), ms);
|
||||
});
|
||||
return Promise.race([op, timer]).finally(() => clearTimeout(handle));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Redis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Returns true when ioredis can execute PING within the timeout. */
|
||||
export async function probeRedis(): Promise<boolean> {
|
||||
try {
|
||||
const result = await withTimeout(redis.ping(), "TIMEOUT", PROBE_TIMEOUT_MS);
|
||||
return result === "PONG";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Database
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Returns true when Prisma can execute SELECT 1 within the timeout. */
|
||||
export async function probeDb(): Promise<boolean> {
|
||||
try {
|
||||
// db.ts wraps PrismaClient in an `as unknown as PrismaClient` cast, so
|
||||
// $queryRaw is present at runtime but absent from the inferred type.
|
||||
const query = (prisma as unknown as { $queryRaw: (tpl: TemplateStringsArray) => Promise<unknown> })
|
||||
.$queryRaw`SELECT 1`
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
return await withTimeout(query, false, PROBE_TIMEOUT_MS);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Data engine
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns true when the data engine manifest endpoint responds with 2xx.
|
||||
* Uses getEngineUrl() from the data-query service so both resolve the same URL.
|
||||
*/
|
||||
export async function probeEngine(): Promise<boolean> {
|
||||
const engineUrl = getEngineUrl() + "/manifest";
|
||||
try {
|
||||
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config / HMAC signing key
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns true when the HMAC signing-key preconditions are satisfied.
|
||||
* Delegates to isSigningKeyValid() -- single source of truth for the rule.
|
||||
*/
|
||||
export function probeConfig(): boolean {
|
||||
return isSigningKeyValid();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Shared Zod identifier schemas for MCP tool input validation (SEC-04).
|
||||
*
|
||||
* Single source of truth for plugin/layer id and entity id bounds.
|
||||
* GlobeCommand.ts keeps its own runtime validator but imports the constants
|
||||
* from here so the bounds are defined in exactly one place.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Regex and max-length for plugin/layer identifiers.
|
||||
* Exported so GlobeCommand.ts can reference the same values without
|
||||
* importing Zod (a client-side module that should stay out of core types).
|
||||
*/
|
||||
export const PLUGIN_ID_MAX = 64;
|
||||
export const PLUGIN_ID_RE = /^[a-zA-Z0-9_.-]+$/;
|
||||
|
||||
/** Entity identifier max length. */
|
||||
export const ENTITY_ID_MAX = 256;
|
||||
|
||||
/**
|
||||
* Plugin and layer identifiers: kebab/dotted ids, max 64 chars.
|
||||
* Allows letters, digits, underscores, dots, and hyphens only.
|
||||
*/
|
||||
export const pluginIdSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(PLUGIN_ID_MAX)
|
||||
.regex(PLUGIN_ID_RE, "must contain only letters, digits, underscores, dots, or hyphens");
|
||||
|
||||
/** Alias; same bounds as pluginIdSchema. */
|
||||
export const layerIdSchema = pluginIdSchema;
|
||||
|
||||
/**
|
||||
* Entity identifiers: permissive charset (allows colons, slashes, etc. used by
|
||||
* real plugin entity ids such as "ship:123" or "flight/AFR123"), but rejects
|
||||
* ASCII control characters (0x00-0x1F) and DEL (0x7F) which could corrupt logs
|
||||
* or database queries.
|
||||
*/
|
||||
export const entityIdSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(ENTITY_ID_MAX)
|
||||
.regex(/^[^\x00-\x1F\x7F]+$/, "must not contain control characters");
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* JSON-RPC 2.0 response helpers for the MCP route.
|
||||
*
|
||||
* Centralised here so route.ts stays under the ~300-line guideline and the
|
||||
* same error shapes can be reused by future route handlers without duplication.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns 403 + JSON-RPC 2.0 body for the demo edition gate (MCP-04).
|
||||
* Runs BEFORE auth so the demo-admin FK write path is never reached.
|
||||
*/
|
||||
export function demoBlockedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 401 + JSON-RPC 2.0 body for missing/invalid Bearer token (MCP-03).
|
||||
* Content-Type is application/json (not plain text, Pitfall 3).
|
||||
*/
|
||||
export function unauthorizedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 429 + JSON-RPC 2.0 body when the authenticated key exceeds its
|
||||
* per-window request budget (SEC-02). Code -32000 is the server-defined range.
|
||||
*/
|
||||
export function rateLimitedResponse(retryAfterMs: number): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32000, message: "rate limit exceeded" },
|
||||
id: null,
|
||||
},
|
||||
{
|
||||
status: 429,
|
||||
headers: { "Retry-After": String(Math.ceil(retryAfterMs / 1_000)) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 500 + JSON-RPC 2.0 body for unexpected server errors (TRANS-01).
|
||||
* Used by the top-level try/catch so MCP clients always receive a well-formed
|
||||
* JSON-RPC error frame instead of a bare HTML 500 from Next.js.
|
||||
*/
|
||||
export function internalErrorResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
},
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
"X-Accel-Buffering": "no",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
+41
-22
@@ -32,7 +32,7 @@ const SERVER_NAME = "worldwideview" as const;
|
||||
export const MCP_SERVER_VERSION = "1.3.0" as const;
|
||||
|
||||
export const MCP_SERVER_INSTRUCTIONS = `\
|
||||
You are a geospatial intelligence assistant connected to WorldWideView -- a live 3D globe that streams real-world data in real time. You control the globe and query its data on behalf of the authenticated user. All state is scoped to your API key: you only ever see and control your own sessions and data.
|
||||
You are a geospatial intelligence assistant connected to WorldWideView, a live 3D globe that streams real-world data in real time. You control the globe and query its data on behalf of the authenticated user. All state is scoped to your API key: you only ever see and control your own sessions and data.
|
||||
|
||||
MENTAL MODEL
|
||||
- Globe: a 3D interactive viewer running in the user's browser. Think of it as a live map you can steer.
|
||||
@@ -40,28 +40,45 @@ MENTAL MODEL
|
||||
- Sessions: open browser tabs showing the globe. Each tab is an independent session identified by a UUID.
|
||||
|
||||
CAPABILITIES
|
||||
- Globe command tools (write/steer a live browser tab): pan_globe, focus_entity, toggle_layer, set_timeline.
|
||||
- Data query tools (read shared engine data): search_entities, get_entities_in_region, get_entity_details, get_plugin_data.
|
||||
- Globe command tools (require a live browser session): pan_globe, focus_entity, toggle_layer, set_timeline.
|
||||
- Data query tools (server-side, NO session required): search_entities, get_entities_in_region, get_entity_details, get_plugin_data.
|
||||
- Discovery tools: list_available_plugins, get_globe_context, investigate_area.
|
||||
- Filter tools: set_filter, clear_filter, get_plugin_filters.
|
||||
- Resources (read): globe://sessions, globe://state/{sessionId}, globe://layers.
|
||||
- Plugin tools (dynamic): extra tools named "<pluginId>__<toolName>" appear only after a browser tab has loaded that plugin and published its catalog. Re-call tools/list after the relevant plugin is loaded.
|
||||
- Plugin tools (dynamic): extra tools named "<pluginId>__<toolName>" appear after a browser tab loads that plugin. This server is stateless; re-call tools/list to discover them after enabling a plugin.
|
||||
|
||||
WORKFLOWS (follow these sequences -- order matters)
|
||||
Rule 1 -- Before any command tool (pan_globe, toggle_layer, focus_entity, set_timeline): READ globe://sessions first to discover active sessions and their sessionIds. Calling a command without knowing the active session may target the wrong tab or fail silently.
|
||||
Rule 2 -- Before calling get_plugin_data or get_entities_in_region for a specific plugin: CHECK tools/list for "<pluginId>__<toolName>" entries first. Plugin tools only appear after the relevant browser tab has loaded that plugin. If the tool is not listed, the plugin is not active yet.
|
||||
Rule 3 -- Before calling fly_to or focus_entity for a named place: GEOCODE the place name first using the geocode tool to obtain precise coordinates. Do not guess lat/lon values.
|
||||
|
||||
SESSIONS (read before using any command tool)
|
||||
- A session is one open browser tab showing the globe, identified by a UUID sessionId.
|
||||
- To discover sessions, READ the resource globe://sessions. It returns the tabs active in the last ~45 seconds; a tab that goes quiet drops off the list.
|
||||
- Every command tool takes an optional sessionId. Omit it to target your most-recently-active tab. Pass a sessionId from globe://sessions to target one specific tab. Commands are isolated per session and are never broadcast to other tabs.
|
||||
- To see what a specific tab currently shows (camera, layers, timeline), read globe://state/{sessionId}.
|
||||
- If no tab is active, command tools return "no active globe session to control" -- the user must open the app in a browser first.
|
||||
|
||||
COORDINATES
|
||||
- latitude must be in [-90, 90], longitude in [-180, 180], altitude greater than 0 metres. Out-of-range values are rejected with a validation error.
|
||||
TWO TOOL CATEGORIES
|
||||
1. Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data) run on the server and return real data WITHOUT a browser session. emptyReason values: "plugin_not_streaming" (plugin not active), "no_data_matches" (query ran, nothing matched).
|
||||
2. Command tools (pan_globe, focus_entity, toggle_layer, set_timeline, set_filter, clear_filter) enqueue browser commands. They require an active globe session and return "no active globe session to control" when none exists.
|
||||
|
||||
DATA AVAILABILITY
|
||||
- Data query tools return {"success": true, "entities": [], "count": 0} when nothing matches OR when the live data engine is not currently feeding that plugin. An empty result is normal, not an error.`;
|
||||
- list_available_plugins returns { "plugins": [] } with reason "engine_unreachable" when the data engine is down, or reason "no_active_plugins" when the engine is up but no plugins are streaming.
|
||||
- Data query tools return emptyReason "plugin_not_streaming" when the plugin is not loaded, and "no_data_matches" when the plugin is streaming but no entities matched.
|
||||
- Large result sets from get_entities_in_region or get_plugin_data are capped and return "truncated": true plus "totalMatched" for the full count.
|
||||
- investigate_area uses "cappedTotal" instead of "totalMatched" because each matched plugin is itself capped at 100 entities, so the summed value is not the true global total.
|
||||
|
||||
RESPONSE SHAPES
|
||||
- Data tool success: { "success": true, "entities": [...], "count": N }
|
||||
- Data tool empty: { "success": true, "entities": [], "count": 0, "emptyReason": "..." }
|
||||
- Truncated result (region/snapshot capped): adds "truncated": true, "totalMatched": N
|
||||
- investigate_area truncated: adds "truncated": true, "cappedTotal": N (sum of per-plugin capped results)
|
||||
- Discovery (list_available_plugins): { "plugins": [...] } or { "plugins": [], "reason": "engine_unreachable" | "no_active_plugins" }
|
||||
- Command success: plain text confirmation
|
||||
- Command no-session: plain text "no active globe session to control"
|
||||
- Command unknown id: plain text warning including "is not a recognized plugin"
|
||||
|
||||
WORKFLOWS (follow these sequences, order matters)
|
||||
Rule 1: Before any command tool, READ globe://sessions to discover active sessions. Calling a command without knowing the active session may target the wrong tab.
|
||||
Rule 2: Before calling get_plugin_data or get_entities_in_region, call list_available_plugins to confirm the plugin is active.
|
||||
Rule 3: Before focus_entity or pan_globe for a named place, geocode the place name first.
|
||||
|
||||
SESSIONS
|
||||
- To discover sessions, READ globe://sessions. It returns tabs active in the last ~45 seconds.
|
||||
- Every command tool takes an optional sessionId. Omit to target the most-recently-active tab.
|
||||
- To see what a tab currently shows, read globe://state/{sessionId}.
|
||||
|
||||
COORDINATES
|
||||
- latitude in [-90, 90], longitude in [-180, 180], altitude greater than 0 metres.`;
|
||||
|
||||
/**
|
||||
* Returns a fresh, empty-capability McpServer per call.
|
||||
@@ -75,9 +92,11 @@ export function createMcpServer(): McpServer {
|
||||
{
|
||||
instructions: MCP_SERVER_INSTRUCTIONS,
|
||||
capabilities: {
|
||||
// tools.listChanged: required so Phase 21 can push live tool
|
||||
// list updates to clients (RECONCILIATION R-1).
|
||||
tools: { listChanged: true },
|
||||
// tools.listChanged is false: this stateless server constructs a
|
||||
// fresh McpServer per request and cannot push notifications to
|
||||
// connected clients. Clients must re-call tools/list to pick up
|
||||
// plugin tools added after the browser loads a new plugin (TRANS-04).
|
||||
tools: { listChanged: false },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Shared MCP tool-description fragments.
|
||||
*
|
||||
* SESSION_REQUIRED_PREAMBLE is prepended to every command/control tool
|
||||
* description so the live-open-tab requirement (ONBRD-03) is stated identically
|
||||
* everywhere. Command tools enqueue to a per-session Redis queue that only a
|
||||
* live, signed-in browser tab drains; without an open tab the command is
|
||||
* accepted but has no visible effect.
|
||||
*/
|
||||
export const SESSION_REQUIRED_PREAMBLE =
|
||||
"Requires a live, signed-in WorldWideView browser tab; without an open globe tab the command is accepted but has no visible effect. ";
|
||||
+119
-4
@@ -4,10 +4,16 @@ vi.mock("@/lib/data-query/service");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
|
||||
import { registerDataQueryTools } from "./tools";
|
||||
import { searchEntities } from "@/lib/data-query/service";
|
||||
import {
|
||||
searchEntities,
|
||||
getEntitiesInRegion,
|
||||
getPluginData,
|
||||
} from "@/lib/data-query/service";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
const mockSearchEntities = vi.mocked(searchEntities);
|
||||
const mockGetEntitiesInRegion = vi.mocked(getEntitiesInRegion);
|
||||
const mockGetPluginData = vi.mocked(getPluginData);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
|
||||
const schemas: Record<string, unknown> = {};
|
||||
@@ -104,9 +110,11 @@ describe("search_entities emptyReason (RESP-01)", () => {
|
||||
expect(body.emptyReason).toBe("no_data_matches");
|
||||
});
|
||||
|
||||
it("returns emptyReason no_session_active when no active session (overrides plugin reason)", async () => {
|
||||
it("returns the TRUE service reason (plugin_not_streaming) even when no active session (TOOL-01)", async () => {
|
||||
// TOOL-01: data-query tools must NEVER return no_session_active because they do
|
||||
// not require a browser session. The true service reason must propagate regardless.
|
||||
mockSearchEntities.mockResolvedValue({ entities: [], emptyReason: "plugin_not_streaming" });
|
||||
// No active session -- no_session_active wins regardless of service reason
|
||||
// No active session -- must NOT override the service reason for data-query tools.
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["search_entities"]({ query: "test", pluginId: "flights" });
|
||||
@@ -114,7 +122,21 @@ describe("search_entities emptyReason (RESP-01)", () => {
|
||||
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.count).toBe(0);
|
||||
expect(body.emptyReason).toBe("no_session_active");
|
||||
// The true reason must be returned, not no_session_active.
|
||||
expect(body.emptyReason).toBe("plugin_not_streaming");
|
||||
});
|
||||
|
||||
it("returns no_data_matches when service emptyReason is absent and session is missing (TOOL-01)", async () => {
|
||||
// A data-query tool with undefined serviceReason and no session must default
|
||||
// to no_data_matches, not no_session_active.
|
||||
mockSearchEntities.mockResolvedValue({ entities: [], emptyReason: undefined });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["search_entities"]({ query: "empty", pluginId: "flights" });
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.emptyReason).toBe("no_data_matches");
|
||||
expect(body.emptyReason).not.toBe("no_session_active");
|
||||
});
|
||||
|
||||
it("does NOT include emptyReason in envelope when results are non-empty", async () => {
|
||||
@@ -131,3 +153,96 @@ describe("search_entities emptyReason (RESP-01)", () => {
|
||||
expect(Object.prototype.hasOwnProperty.call(body, "emptyReason")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-03 -- get_entities_in_region count, truncated, totalMatched
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("get_entities_in_region count/truncated (TOOL-03)", () => {
|
||||
const makeEntity = (id: string) => ({ id, pluginId: "quakes", latitude: 10, longitude: 20 });
|
||||
|
||||
it("returns count and no truncated flag when result fits in cap", async () => {
|
||||
const entities = [makeEntity("e1"), makeEntity("e2")];
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities });
|
||||
|
||||
const result = await handlers["get_entities_in_region"]({
|
||||
north: 20, south: 0, east: 30, west: 10,
|
||||
});
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.count).toBe(2);
|
||||
expect(Object.prototype.hasOwnProperty.call(body, "truncated")).toBe(false);
|
||||
expect(Object.prototype.hasOwnProperty.call(body, "totalMatched")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns truncated:true and totalMatched when service signals truncation", async () => {
|
||||
const entities = Array.from({ length: 100 }, (_, i) => makeEntity(`e${i}`));
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities, totalMatched: 350 });
|
||||
|
||||
const result = await handlers["get_entities_in_region"]({
|
||||
north: 20, south: 0, east: 30, west: 10,
|
||||
});
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.count).toBe(100);
|
||||
expect(body.truncated).toBe(true);
|
||||
expect(body.totalMatched).toBe(350);
|
||||
});
|
||||
|
||||
it("returns emptyReason no_data_matches (not no_session_active) when no session (TOOL-01)", async () => {
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities: [], emptyReason: "no_data_matches" });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["get_entities_in_region"]({
|
||||
north: 20, south: 0, east: 30, west: 10,
|
||||
});
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.emptyReason).toBe("no_data_matches");
|
||||
expect(body.emptyReason).not.toBe("no_session_active");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-04 -- get_plugin_data cap and truncation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("get_plugin_data cap and truncation (TOOL-04)", () => {
|
||||
it("returns all entities when below cap", async () => {
|
||||
const entities = Array.from({ length: 50 }, (_, i) => ({
|
||||
id: `e${i}`, pluginId: "quakes", latitude: 0, longitude: 0, timestamp: new Date(), properties: {},
|
||||
}));
|
||||
mockGetPluginData.mockResolvedValue({ data: { pluginId: "quakes", entities, timestamp: new Date() } });
|
||||
|
||||
const result = await handlers["get_plugin_data"]({ pluginId: "quakes" });
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.count).toBe(50);
|
||||
expect(Object.prototype.hasOwnProperty.call(body, "truncated")).toBe(false);
|
||||
});
|
||||
|
||||
it("truncates to 200 and sets truncated:true when snapshot exceeds cap", async () => {
|
||||
const entities = Array.from({ length: 250 }, (_, i) => ({
|
||||
id: `e${i}`, pluginId: "quakes", latitude: 0, longitude: 0, timestamp: new Date(), properties: {},
|
||||
}));
|
||||
mockGetPluginData.mockResolvedValue({ data: { pluginId: "quakes", entities, timestamp: new Date() } });
|
||||
|
||||
const result = await handlers["get_plugin_data"]({ pluginId: "quakes" });
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.count).toBe(200);
|
||||
expect(body.truncated).toBe(true);
|
||||
expect(body.totalMatched).toBe(250);
|
||||
});
|
||||
|
||||
it("returns emptyReason plugin_not_streaming (not no_session_active) when no session (TOOL-01)", async () => {
|
||||
mockGetPluginData.mockResolvedValue({ data: null, emptyReason: "plugin_not_streaming" });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["get_plugin_data"]({ pluginId: "missing" });
|
||||
const body = parseResult(result);
|
||||
|
||||
expect(body.emptyReason).toBe("plugin_not_streaming");
|
||||
expect(body.emptyReason).not.toBe("no_session_active");
|
||||
});
|
||||
});
|
||||
+58
-28
@@ -2,13 +2,14 @@
|
||||
* MCP Data Query Tool registrar (Phase 20 Wave 3 -- 20-04).
|
||||
*
|
||||
* Registers four read-only MCP tools that expose the data-query service to
|
||||
* MCP clients. Phase 28 (28-01): emptyReason discrimination added; userId
|
||||
* threaded in for no_session_active detection.
|
||||
* MCP clients. Phase 28 (28-01): emptyReason discrimination added.
|
||||
* Phase 33 (TOOL-01): data-query tools never return no_session_active because
|
||||
* they do not require a browser session.
|
||||
*
|
||||
* TOOL-01 search_entities -- full-text search across active plugins
|
||||
* TOOL-02 get_entities_in_region -- bounding-box spatial query
|
||||
* TOOL-03 get_entity_details -- single entity lookup by pluginId + entityId
|
||||
* TOOL-04 get_plugin_data -- full snapshot for a named plugin
|
||||
* TOOL-04 get_plugin_data -- full snapshot for a named plugin (cap 200)
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
@@ -21,9 +22,11 @@ import {
|
||||
getEntityDetails,
|
||||
getPluginData,
|
||||
} from "@/lib/data-query/service";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import type { EmptyReason } from "@/lib/data-query/types";
|
||||
|
||||
/** Maximum entities returned by get_plugin_data in a single response (TOOL-04). */
|
||||
const GET_PLUGIN_DATA_CAP = 200;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helper
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -34,17 +37,14 @@ function toolError(msg: string): { content: [{ type: "text"; text: string }] } {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply session-first precedence for emptyReason.
|
||||
* Returns the emptyReason for data-query tools.
|
||||
*
|
||||
* Precedence: no_session_active > plugin_not_streaming > no_data_matches.
|
||||
* Only called when the result is empty (count === 0).
|
||||
* Data-query tools run server-side and do NOT require a browser session.
|
||||
* They must NEVER return no_session_active. The service layer returns the
|
||||
* true reason (plugin_not_streaming or no_data_matches); this function
|
||||
* provides a safe default when the service omits it.
|
||||
*/
|
||||
async function resolveEmptyReason(
|
||||
userId: string,
|
||||
serviceReason: EmptyReason | undefined,
|
||||
): Promise<EmptyReason> {
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
if (sessionId === null) return "no_session_active";
|
||||
function resolveDataQueryEmptyReason(serviceReason: EmptyReason | undefined): EmptyReason {
|
||||
return serviceReason ?? "no_data_matches";
|
||||
}
|
||||
|
||||
@@ -52,15 +52,18 @@ async function resolveEmptyReason(
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerDataQueryTools(server: McpServer, ctx: { userId: string }): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
export function registerDataQueryTools(server: McpServer, _ctx: { userId: string }): void {
|
||||
// TOOL-01: search_entities
|
||||
server.registerTool(
|
||||
"search_entities",
|
||||
{
|
||||
description:
|
||||
"Full-text search for geospatial entities by name across active plugins. Use when you need entities matching a keyword. Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming -- re-call tools/list after the plugin loads), 'no_data_matches' (no entities matched the query), or 'no_session_active' (no active globe session). Returns up to 20 results (id, name, lat, lon, pluginId). Optional 'filters' apply inline property filters independent of set_filter state. Example: search_entities({ query: 'flight', pluginId: 'flights' })",
|
||||
"Full-text search for geospatial entities by name across active plugins. " +
|
||||
"This is a READ-ONLY data tool -- it does NOT require an active globe session. " +
|
||||
"Before calling, verify the plugin is active via tools/list. " +
|
||||
"Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming), 'no_data_matches' (query ran but nothing matched). " +
|
||||
"Returns up to 20 results (id, name, lat, lon, pluginId). Optional 'filters' apply inline property filters independent of set_filter state. " +
|
||||
"Example: search_entities({ query: 'flight', pluginId: 'flights' })",
|
||||
inputSchema: {
|
||||
query: z.string().describe("Search query string"),
|
||||
pluginId: z.string().optional().describe("Restrict search to a specific plugin"),
|
||||
@@ -80,7 +83,7 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
input.filters,
|
||||
);
|
||||
if (result.entities.length === 0) {
|
||||
const emptyReason = await resolveEmptyReason(userId, result.emptyReason);
|
||||
const emptyReason = resolveDataQueryEmptyReason(result.emptyReason);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -110,7 +113,13 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
"get_entities_in_region",
|
||||
{
|
||||
description:
|
||||
"Spatial query returning entities within a bounding box (north/south/east/west lat-lon bounds). Use when you need entities in a geographic area. Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming -- re-call tools/list after the plugin loads), 'no_data_matches' (no entities matched the region), or 'no_session_active' (no active globe session). Returns up to 100 results. Example: get_entities_in_region({ north: 52, south: 51, east: 0, west: -1, pluginId: 'flights' })",
|
||||
"Spatial query returning entities within a bounding box (north/south/east/west lat-lon bounds). " +
|
||||
"This is a READ-ONLY data tool -- it does NOT require an active globe session. " +
|
||||
"Before calling, verify the plugin is active via tools/list. " +
|
||||
"Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming), 'no_data_matches' (no entities matched the region). " +
|
||||
"Returns up to 100 results per call. IMPORTANT: when 'truncated' is true the returned list is an UNORDERED SAMPLE (not nearest-first). " +
|
||||
"Check 'count' (returned) and 'totalMatched' (total in region, when truncated) to understand coverage. " +
|
||||
"Example: get_entities_in_region({ north: 52, south: 51, east: 0, west: -1, pluginId: 'flights' })",
|
||||
inputSchema: {
|
||||
north: latSchema.describe("Northern latitude bound"),
|
||||
south: latSchema.describe("Southern latitude bound"),
|
||||
@@ -131,7 +140,7 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
limit: Math.min(input.limit ?? 100, 100),
|
||||
});
|
||||
if (result.entities.length === 0) {
|
||||
const emptyReason = await resolveEmptyReason(userId, result.emptyReason);
|
||||
const emptyReason = resolveDataQueryEmptyReason(result.emptyReason);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -141,11 +150,18 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
],
|
||||
};
|
||||
}
|
||||
const count = result.entities.length;
|
||||
const truncated = result.totalMatched !== undefined;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ success: true, entities: result.entities, count: result.entities.length }),
|
||||
text: JSON.stringify({
|
||||
success: true,
|
||||
entities: result.entities,
|
||||
count,
|
||||
...(truncated && { truncated: true, totalMatched: result.totalMatched }),
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -161,7 +177,12 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
"get_entity_details",
|
||||
{
|
||||
description:
|
||||
"Single entity lookup returning full detail by pluginId + entityId. Use after search_entities or get_entities_in_region to retrieve complete properties for one entity. Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming -- re-call tools/list after the plugin loads), 'no_data_matches' (no entities matched -- entity not found in snapshot), or 'no_session_active' (no active globe session). Example: get_entity_details({ pluginId: 'flights', entityId: 'BA123' })",
|
||||
"Single entity lookup returning full detail by pluginId + entityId. " +
|
||||
"This is a READ-ONLY data tool -- it does NOT require an active globe session. " +
|
||||
"Use after search_entities or get_entities_in_region to retrieve complete properties for one entity. " +
|
||||
"Before calling, verify the plugin is active via tools/list. " +
|
||||
"Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming), 'no_data_matches' (nothing matched -- entity not found in snapshot). " +
|
||||
"Example: get_entity_details({ pluginId: 'flights', entityId: 'BA123' })",
|
||||
inputSchema: {
|
||||
pluginId: z.string().describe("The plugin that owns this entity"),
|
||||
entityId: z.string().describe("The entity identifier"),
|
||||
@@ -171,7 +192,7 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
try {
|
||||
const result = await getEntityDetails(input.pluginId, input.entityId);
|
||||
if (result.data === null) {
|
||||
const emptyReason = await resolveEmptyReason(userId, result.emptyReason);
|
||||
const emptyReason = resolveDataQueryEmptyReason(result.emptyReason);
|
||||
return { content: [{ type: "text", text: JSON.stringify({ success: true, data: null, emptyReason }) }] };
|
||||
}
|
||||
return {
|
||||
@@ -194,7 +215,13 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
"get_plugin_data",
|
||||
{
|
||||
description:
|
||||
"Full data snapshot returning all current entities for one plugin by pluginId. Use to bulk-read a plugin's live state. Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming -- re-call tools/list after the plugin loads), 'no_data_matches' (no entities matched -- plugin loaded but no entities streamed yet), or 'no_session_active' (no active globe session). Includes a capturedAt timestamp when the plugin has streamed data (absent for the not-loaded case). Example: get_plugin_data({ pluginId: 'earthquakes' })",
|
||||
"Full data snapshot returning current entities for one plugin by pluginId. " +
|
||||
"This is a READ-ONLY data tool -- it does NOT require an active globe session. " +
|
||||
"Use to bulk-read a plugin's live state. Before calling, verify the plugin is active via tools/list. " +
|
||||
"Returns emptyReason on empty results: 'plugin_not_streaming' (plugin not loaded or not streaming), 'no_data_matches' (nothing matched -- plugin loaded but no entities streamed yet). " +
|
||||
"Response is capped at 200 entities. When 'truncated' is true, check 'totalMatched' for the full count. " +
|
||||
"Includes a capturedAt timestamp when the plugin has streamed data (absent for the not-loaded case). " +
|
||||
"Example: get_plugin_data({ pluginId: 'earthquakes' })",
|
||||
inputSchema: {
|
||||
pluginId: z.string().describe("The plugin identifier"),
|
||||
},
|
||||
@@ -203,7 +230,7 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
try {
|
||||
const result = await getPluginData(input.pluginId);
|
||||
if (result.data === null) {
|
||||
const emptyReason = await resolveEmptyReason(userId, result.emptyReason);
|
||||
const emptyReason = resolveDataQueryEmptyReason(result.emptyReason);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -214,9 +241,9 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
};
|
||||
}
|
||||
// Plugin is streaming; check if entities are empty
|
||||
const entities = result.data.entities ?? [];
|
||||
if (entities.length === 0) {
|
||||
const emptyReason = await resolveEmptyReason(userId, result.emptyReason);
|
||||
const allEntities = result.data.entities ?? [];
|
||||
if (allEntities.length === 0) {
|
||||
const emptyReason = resolveDataQueryEmptyReason(result.emptyReason);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -232,6 +259,8 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
],
|
||||
};
|
||||
}
|
||||
const truncated = allEntities.length > GET_PLUGIN_DATA_CAP;
|
||||
const entities = truncated ? allEntities.slice(0, GET_PLUGIN_DATA_CAP) : allEntities;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
@@ -240,6 +269,7 @@ export function registerDataQueryTools(server: McpServer, ctx: { userId: string
|
||||
success: true,
|
||||
entities,
|
||||
count: entities.length,
|
||||
...(truncated && { truncated: true, totalMatched: allEntities.length }),
|
||||
capturedAt: result.data.timestamp,
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* DEPLOY-03: Global Nominatim throttle tests.
|
||||
*
|
||||
* Verifies that:
|
||||
* - fetchGeocode calls redisSlidingWindowPeek to poll and redisSlidingWindow
|
||||
* to commit (only one committing ZADD per request)
|
||||
* - when the slot is available immediately, the fetch proceeds
|
||||
* - when Redis fails open (allowed:true), the fetch still proceeds
|
||||
* - the peek loop retries until a slot opens, then commits exactly once
|
||||
* - proceeds after the deadline even if the slot never opens (no indefinite blocking)
|
||||
* - returns empty array immediately when the queue-depth cap is exceeded
|
||||
* - the 24h cache in geocodingTools.ts is checked BEFORE fetchGeocode (caller
|
||||
* responsibility; this file only tests fetchGeocode itself)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Must mock before importing the module under test so the import picks up the mock.
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/redis");
|
||||
|
||||
import { fetchGeocode } from "./nominatim";
|
||||
import { redisSlidingWindow, redisSlidingWindowPeek } from "@/lib/geocodingRateLimit";
|
||||
|
||||
const mockRedisSlidingWindow = vi.mocked(redisSlidingWindow);
|
||||
const mockRedisSlidingWindowPeek = vi.mocked(redisSlidingWindowPeek);
|
||||
|
||||
const MOCK_ITEMS = [
|
||||
{
|
||||
lat: "48.8566",
|
||||
lon: "2.3522",
|
||||
name: "Paris",
|
||||
display_name: "Paris, France",
|
||||
type: "city",
|
||||
addresstype: "city",
|
||||
importance: 0.9,
|
||||
boundingbox: ["48.815", "48.902", "2.224", "2.470"] as [string, string, string, string],
|
||||
},
|
||||
];
|
||||
|
||||
function mockFetch(items: unknown[] = MOCK_ITEMS): void {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => items,
|
||||
} as unknown as Response);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: slot is immediately available (peek returns count 0 = slot free).
|
||||
mockRedisSlidingWindowPeek.mockResolvedValue({ count: 0, retryAfterMs: 0 });
|
||||
// Committing call also succeeds.
|
||||
mockRedisSlidingWindow.mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
mockFetch();
|
||||
});
|
||||
|
||||
describe("fetchGeocode global throttle (DEPLOY-03)", () => {
|
||||
it("calls redisSlidingWindowPeek with the nominatim:global key before fetching", async () => {
|
||||
await fetchGeocode({ query: "Paris", limit: 5 });
|
||||
|
||||
expect(mockRedisSlidingWindowPeek).toHaveBeenCalledWith("nominatim:global", 1000);
|
||||
});
|
||||
|
||||
it("calls redisSlidingWindow exactly once to commit the slot when slot is available", async () => {
|
||||
await fetchGeocode({ query: "Paris", limit: 5 });
|
||||
|
||||
// Only one committing add, regardless of how many peek iterations occurred.
|
||||
expect(mockRedisSlidingWindow).toHaveBeenCalledTimes(1);
|
||||
expect(mockRedisSlidingWindow).toHaveBeenCalledWith("nominatim:global", 1, 1000);
|
||||
});
|
||||
|
||||
it("proceeds to fetch when slot is immediately available", async () => {
|
||||
mockRedisSlidingWindowPeek.mockResolvedValue({ count: 0, retryAfterMs: 0 });
|
||||
|
||||
const result = await fetchGeocode({ query: "Paris", limit: 5 });
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledOnce();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Paris");
|
||||
});
|
||||
|
||||
it("peeks multiple times before committing when slot is initially occupied", async () => {
|
||||
// First peek: slot occupied; second peek: slot free.
|
||||
mockRedisSlidingWindowPeek
|
||||
.mockResolvedValueOnce({ count: 1, retryAfterMs: 10 })
|
||||
.mockResolvedValue({ count: 0, retryAfterMs: 0 });
|
||||
|
||||
const result = await fetchGeocode({ query: "Tokyo", limit: 2 });
|
||||
|
||||
expect(mockRedisSlidingWindowPeek).toHaveBeenCalledTimes(2);
|
||||
// Exactly one commit, after the slot opened.
|
||||
expect(mockRedisSlidingWindow).toHaveBeenCalledTimes(1);
|
||||
expect(global.fetch).toHaveBeenCalledOnce();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does NOT call redisSlidingWindow during peek-wait iterations (no slot-burn)", async () => {
|
||||
// Slot occupied for two polls, then opens.
|
||||
mockRedisSlidingWindowPeek
|
||||
.mockResolvedValueOnce({ count: 1, retryAfterMs: 10 })
|
||||
.mockResolvedValueOnce({ count: 1, retryAfterMs: 10 })
|
||||
.mockResolvedValue({ count: 0, retryAfterMs: 0 });
|
||||
|
||||
await fetchGeocode({ query: "Berlin", limit: 1 });
|
||||
|
||||
// redisSlidingWindow is the committing write. It must be called exactly once,
|
||||
// not once per peek iteration.
|
||||
expect(mockRedisSlidingWindow).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("proceeds after deadline even if slot never opens (no indefinite blocking)", async () => {
|
||||
// Always occupied. fetchGeocode must resolve within a reasonable time.
|
||||
mockRedisSlidingWindowPeek.mockResolvedValue({ count: 1, retryAfterMs: 50 });
|
||||
|
||||
const start = Date.now();
|
||||
const result = await fetchGeocode({ query: "London", limit: 1 });
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledOnce();
|
||||
expect(result).toHaveLength(1);
|
||||
// Must resolve after the deadline (~1100ms) but well under 3 seconds.
|
||||
expect(elapsed).toBeLessThan(3_000);
|
||||
}, 6_000);
|
||||
|
||||
it("returns empty array immediately when the queue-depth cap is exceeded", async () => {
|
||||
// Slot always occupied so _activeWaiters would accumulate.
|
||||
// We test the cap by checking that after 10 concurrent pending calls,
|
||||
// additional calls return [] without hanging.
|
||||
// Since we cannot truly run 10 concurrent async calls here, we simulate
|
||||
// by checking the exported behavior: if _activeWaiters >= 10 the function
|
||||
// returns [] without fetching.
|
||||
// We use a slow peek (10ms delay) to give concurrent calls time to queue up.
|
||||
let resolveFirst: () => void;
|
||||
const firstPeekGate = new Promise<void>((res) => { resolveFirst = res; });
|
||||
|
||||
mockRedisSlidingWindowPeek.mockImplementation(async () => {
|
||||
await firstPeekGate;
|
||||
return { count: 0, retryAfterMs: 0 };
|
||||
});
|
||||
|
||||
// Start 11 calls. The first 10 block on the gate; the 11th should return [].
|
||||
const calls = Array.from({ length: 11 }, (_, i) =>
|
||||
fetchGeocode({ query: `city${i}`, limit: 1 }),
|
||||
);
|
||||
|
||||
// Give the calls time to queue up before releasing the gate.
|
||||
await new Promise<void>((res) => setTimeout(res, 20));
|
||||
|
||||
// Release all blocked callers.
|
||||
resolveFirst!();
|
||||
|
||||
const results = await Promise.all(calls);
|
||||
const emptyResults = results.filter((r) => r.length === 0);
|
||||
// At least one call was shed (the 11th or beyond the cap).
|
||||
expect(emptyResults.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("still fetches when redisSlidingWindow fails open (Redis error returns allowed:true)", async () => {
|
||||
// redisSlidingWindow already handles Redis errors internally and returns allowed:true.
|
||||
mockRedisSlidingWindow.mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
const result = await fetchGeocode({ query: "Berlin", limit: 3 });
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledOnce();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns empty array when Nominatim returns non-array JSON", async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ error: "bad query" }),
|
||||
} as unknown as Response);
|
||||
|
||||
const result = await fetchGeocode({ query: "!!!invalid", limit: 1 });
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("throws when Nominatim returns a non-OK HTTP status", async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 429,
|
||||
} as unknown as Response);
|
||||
|
||||
await expect(fetchGeocode({ query: "Paris", limit: 5 })).rejects.toThrow("HTTP 429");
|
||||
});
|
||||
|
||||
it("injects query via URLSearchParams (not string concatenation)", async () => {
|
||||
await fetchGeocode({ query: "Paris & Rome", limit: 1 });
|
||||
|
||||
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as URL;
|
||||
expect(calledUrl.searchParams.get("q")).toBe("Paris & Rome");
|
||||
});
|
||||
});
|
||||
+124
-3
@@ -1,21 +1,116 @@
|
||||
/**
|
||||
* Nominatim geocoding HTTP wrapper (Phase 22 Wave 2 -- 22-02).
|
||||
* Nominatim geocoding HTTP wrapper (Phase 22 Wave 2, 22-02).
|
||||
*
|
||||
* Wraps the public OpenStreetMap Nominatim /search endpoint. The query is the
|
||||
* only user-controlled value and is injected exclusively via URLSearchParams
|
||||
* (no string concatenation into the URL) to prevent SSRF / parameter injection.
|
||||
* The base URL and header values are hardcoded constants.
|
||||
*
|
||||
* `fetchGeocode` returns the RAW Nominatim items; callers normalize them via
|
||||
* `normalizeNominatimResult` to the public `NominatimResult` shape (D-06).
|
||||
* fetchGeocode returns the RAW Nominatim items; callers normalize them via
|
||||
* normalizeNominatimResult to the public NominatimResult shape (D-06).
|
||||
* Nominatim returns boundingbox as ["south_lat","north_lat","west_lon","east_lon"]
|
||||
* (strings); the normalizer remaps to [west, south, east, north] numbers.
|
||||
*
|
||||
* DEPLOY-03: A single GLOBAL throttle (max 1 req/s across all users) is applied
|
||||
* immediately before the outbound fetch. This respects OSM's 1 req/s policy
|
||||
* regardless of how many concurrent users are geocoding. The 24h cache (in
|
||||
* geocodingTools.ts) is checked by callers BEFORE calling fetchGeocode, so
|
||||
* cache hits never touch the throttle.
|
||||
*
|
||||
* Throttle strategy: Redis-backed sliding window (key "nominatim:global", limit 1,
|
||||
* window 1000ms). On Redis failure, falls back to an in-process last-call gate
|
||||
* enforcing >=1s spacing. If the window is already consumed, the call waits up
|
||||
* to GLOBAL_THROTTLE_MAX_WAIT_MS then proceeds (so a single user is not rejected
|
||||
* for transient global contention, just briefly delayed).
|
||||
*
|
||||
* Slot-burn fix: the wait loop uses redisSlidingWindowPeek (read-only count)
|
||||
* rather than redisSlidingWindow (write + count) so only ONE committing ZADD
|
||||
* is performed per outbound request, regardless of how many poll iterations
|
||||
* occur while waiting.
|
||||
*
|
||||
* Queue-depth cap: if GLOBAL_THROTTLE_MAX_WAITERS or more callers are already
|
||||
* queued inside waitForGlobalSlot, additional callers receive an immediate
|
||||
* "geocoder busy" empty result rather than joining a growing pile of waiters.
|
||||
* This caps worst-case memory and OSM burst surface under concurrency spikes.
|
||||
*/
|
||||
|
||||
import { redisSlidingWindow, redisSlidingWindowPeek } from "@/lib/geocodingRateLimit";
|
||||
|
||||
const NOMINATIM_SEARCH_URL = "https://nominatim.openstreetmap.org/search";
|
||||
const USER_AGENT = "WorldWideView-MCP/1.3 ([email protected])";
|
||||
const REQUEST_TIMEOUT_MS = 8_000;
|
||||
|
||||
/** Redis key for the global 1 req/s Nominatim throttle. */
|
||||
const GLOBAL_THROTTLE_KEY = "nominatim:global";
|
||||
const GLOBAL_THROTTLE_WINDOW_MS = 1_000;
|
||||
const GLOBAL_THROTTLE_LIMIT = 1;
|
||||
/** Maximum time (ms) fetchGeocode will wait for a global slot before proceeding. */
|
||||
const GLOBAL_THROTTLE_MAX_WAIT_MS = 1_100;
|
||||
/** Maximum concurrent callers allowed inside waitForGlobalSlot at once. */
|
||||
const GLOBAL_THROTTLE_MAX_WAITERS = 10;
|
||||
|
||||
/**
|
||||
* In-process fallback gate used when Redis is unreachable.
|
||||
* Tracks the timestamp of the last outbound Nominatim request and enforces
|
||||
* at least GLOBAL_THROTTLE_WINDOW_MS spacing, preventing an unthrottled
|
||||
* burst toward OSM if Redis goes down.
|
||||
*/
|
||||
let _lastNominatimCallMs = 0;
|
||||
|
||||
/** Current number of callers waiting inside waitForGlobalSlot. */
|
||||
let _activeWaiters = 0;
|
||||
|
||||
/**
|
||||
* Wait until the global 1 req/s slot is available, then claim it with a
|
||||
* single committing redisSlidingWindow call.
|
||||
*
|
||||
* The poll loop uses redisSlidingWindowPeek (read-only) so each iteration
|
||||
* does NOT add to the ZSET. Only the final claim adds one entry.
|
||||
*
|
||||
* Waits at most GLOBAL_THROTTLE_MAX_WAIT_MS before proceeding regardless,
|
||||
* so a single user's request is not hung for a long time during contention.
|
||||
*/
|
||||
async function waitForGlobalSlot(): Promise<void> {
|
||||
const deadline = Date.now() + GLOBAL_THROTTLE_MAX_WAIT_MS;
|
||||
|
||||
for (;;) {
|
||||
// Peek at the current occupancy without writing to the ZSET.
|
||||
const peek = await redisSlidingWindowPeek(GLOBAL_THROTTLE_KEY, GLOBAL_THROTTLE_WINDOW_MS);
|
||||
|
||||
if (peek.count < GLOBAL_THROTTLE_LIMIT) {
|
||||
// Slot available: commit the single add and return.
|
||||
await redisSlidingWindow(GLOBAL_THROTTLE_KEY, GLOBAL_THROTTLE_LIMIT, GLOBAL_THROTTLE_WINDOW_MS);
|
||||
_lastNominatimCallMs = Date.now();
|
||||
return;
|
||||
}
|
||||
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) {
|
||||
// Deadline reached. Proceed without a Redis commit so we do not
|
||||
// write to a window that is already full.
|
||||
_lastNominatimCallMs = Date.now();
|
||||
return;
|
||||
}
|
||||
|
||||
const waitMs = Math.min(peek.retryAfterMs, remaining, GLOBAL_THROTTLE_WINDOW_MS);
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, waitMs));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In-process fallback gate: enforces >= GLOBAL_THROTTLE_WINDOW_MS between
|
||||
* outbound Nominatim calls when Redis is unavailable.
|
||||
*/
|
||||
async function inProcessGate(): Promise<void> {
|
||||
const elapsed = Date.now() - _lastNominatimCallMs;
|
||||
if (elapsed < GLOBAL_THROTTLE_WINDOW_MS) {
|
||||
await new Promise<void>((resolve) =>
|
||||
setTimeout(resolve, GLOBAL_THROTTLE_WINDOW_MS - elapsed),
|
||||
);
|
||||
}
|
||||
_lastNominatimCallMs = Date.now();
|
||||
}
|
||||
|
||||
/** Raw Nominatim /search response item shape. */
|
||||
export interface RawNominatimItem {
|
||||
lat?: string;
|
||||
@@ -71,9 +166,35 @@ export function normalizeNominatimResult(r: RawNominatimItem): NominatimResult {
|
||||
/**
|
||||
* Geocode a free-text query via Nominatim. Returns the RAW response items.
|
||||
*
|
||||
* Applies the global 1 req/s throttle before each outbound request. Callers
|
||||
* must check the 24h Redis cache BEFORE calling this function so cached
|
||||
* responses bypass the throttle entirely.
|
||||
*
|
||||
* Returns an empty array immediately when the queue-depth cap is exceeded,
|
||||
* so callers should surface a "geocoder busy, try again" message to users.
|
||||
*
|
||||
* @throws on network failure / timeout (AbortSignal.timeout) or non-OK status.
|
||||
*/
|
||||
export async function fetchGeocode({ query, limit }: FetchGeocodeArgs): Promise<RawNominatimItem[]> {
|
||||
// Queue-depth cap: shed load immediately rather than stacking up waiters.
|
||||
if (_activeWaiters >= GLOBAL_THROTTLE_MAX_WAITERS) {
|
||||
return [];
|
||||
}
|
||||
|
||||
_activeWaiters += 1;
|
||||
try {
|
||||
// Global 1 req/s OSM policy gate. Falls back to in-process gate on error.
|
||||
try {
|
||||
await waitForGlobalSlot();
|
||||
} catch {
|
||||
// redisSlidingWindow/Peek already handle their own errors internally.
|
||||
// This outer catch is a safety net for unexpected throws from the loop.
|
||||
await inProcessGate();
|
||||
}
|
||||
} finally {
|
||||
_activeWaiters -= 1;
|
||||
}
|
||||
|
||||
const url = new URL(NOMINATIM_SEARCH_URL);
|
||||
url.searchParams.set("q", query);
|
||||
url.searchParams.set("format", "json");
|
||||
|
||||
@@ -84,10 +84,18 @@ describe("RateLimiter", () => {
|
||||
});
|
||||
|
||||
describe("getClientIp", () => {
|
||||
it("extracts IP from x-forwarded-for (first entry)", () => {
|
||||
it("extracts the rightmost IP from x-forwarded-for (proxy-appended real IP)", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-forwarded-for": "1.2.3.4, 5.6.7.8" },
|
||||
});
|
||||
// 5.6.7.8 is the rightmost — appended by the trusted reverse proxy
|
||||
expect(getClientIp(req)).toBe("5.6.7.8");
|
||||
});
|
||||
|
||||
it("handles a single-entry x-forwarded-for", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-forwarded-for": "1.2.3.4" },
|
||||
});
|
||||
expect(getClientIp(req)).toBe("1.2.3.4");
|
||||
});
|
||||
|
||||
@@ -103,7 +111,7 @@ describe("getClientIp", () => {
|
||||
expect(getClientIp(req)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("property test: x-forwarded-for always returns the first IP in a list", () => {
|
||||
it("property test: x-forwarded-for always returns the LAST IP in a list", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.array(fc.ipV4(), { minLength: 1, maxLength: 10 }),
|
||||
@@ -112,7 +120,7 @@ describe("getClientIp", () => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-forwarded-for": headerValue },
|
||||
});
|
||||
expect(getClientIp(req)).toBe(ips[0]);
|
||||
expect(getClientIp(req)).toBe(ips[ips.length - 1]);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
+29
-11
@@ -61,17 +61,35 @@ export class RateLimiter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract client IP from request headers.
|
||||
* WARNING: When deploying directly without a reverse proxy, 'x-forwarded-for'
|
||||
* and 'x-real-ip' can be spoofed by the client, bypassing rate limits.
|
||||
* In a production architecture with a load balancer (Cloudflare, AWS ALB),
|
||||
* this is safe as the LB overwrites the header. Consider verifying against
|
||||
* trusted proxy subnets if direct access is possible.
|
||||
* Extract the real client IP from request headers.
|
||||
*
|
||||
* Reverse-proxy assumption: this app is always behind a trusted reverse proxy
|
||||
* (Traefik on Coolify, or Cloudflare). The proxy appends the real client IP as
|
||||
* the RIGHTMOST entry in x-forwarded-for. Using the leftmost entry is unsafe
|
||||
* because an attacker can inject arbitrary IPs at the front of that header
|
||||
* before the request reaches the proxy.
|
||||
*
|
||||
* Override: set WWV_TRUSTED_IP_HEADER to a platform-specific header that
|
||||
* carries the guaranteed client IP (e.g. "cf-connecting-ip" for Cloudflare,
|
||||
* "x-real-ip" for Nginx). When set, that header is used directly.
|
||||
*
|
||||
* Falls back to "unknown" when no header is present (e.g. in unit tests).
|
||||
*/
|
||||
export function getClientIp(request: Request): string {
|
||||
return (
|
||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|
||||
|| request.headers.get("x-real-ip")
|
||||
|| "unknown"
|
||||
);
|
||||
const override = process.env.WWV_TRUSTED_IP_HEADER?.trim().toLowerCase();
|
||||
if (override) {
|
||||
const val = request.headers.get(override)?.trim();
|
||||
if (val) return val;
|
||||
}
|
||||
|
||||
// Use the rightmost (proxy-appended) entry from x-forwarded-for, not the
|
||||
// leftmost (client-controlled) entry.
|
||||
const xff = request.headers.get("x-forwarded-for");
|
||||
if (xff) {
|
||||
const entries = xff.split(",");
|
||||
const rightmost = entries[entries.length - 1]?.trim();
|
||||
if (rightmost) return rightmost;
|
||||
}
|
||||
|
||||
return request.headers.get("x-real-ip")?.trim() || "unknown";
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export interface RedisMultiChain {
|
||||
}
|
||||
|
||||
export interface RedisClient {
|
||||
ping(): Promise<string>;
|
||||
set(key: string, value: string, exFlag: "EX", ttlSeconds: number): Promise<string | null>;
|
||||
get(key: string): Promise<string | null>;
|
||||
zadd(key: string, score: number, member: string): Promise<number>;
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* SEC-02: redisSlidingWindow helper tests.
|
||||
*
|
||||
* The helper lives in geocodingRateLimit.ts. Tests cover:
|
||||
* - allows requests within the window
|
||||
* - rejects requests over the limit (boundary: limit allowed, limit+1 rejected)
|
||||
* - fails OPEN when Redis throws
|
||||
* - two same-instant calls each occupy their own ZSET slot (unique members)
|
||||
* - retryAfterMs is computed from the oldest in-window entry, not the full window
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: {
|
||||
zremrangebyscore: vi.fn(),
|
||||
zadd: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
zcard: vi.fn(),
|
||||
zrange: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { redisSlidingWindow } from "./geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
const mockRedis = vi.mocked(redis, true);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockRedis.zremrangebyscore.mockResolvedValue(0 as never);
|
||||
mockRedis.zadd.mockResolvedValue(1 as never);
|
||||
mockRedis.expire.mockResolvedValue(1 as never);
|
||||
// Default: no oldest entry (empty zrange result)
|
||||
(mockRedis as unknown as { zrange: ReturnType<typeof vi.fn> }).zrange.mockResolvedValue([] as never);
|
||||
});
|
||||
|
||||
describe("redisSlidingWindow", () => {
|
||||
it("allows request when count is within limit", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(5 as never);
|
||||
|
||||
const result = await redisSlidingWindow("test:key", 10, 60_000);
|
||||
expect(result.allowed).toBe(true);
|
||||
expect(result.retryAfterMs).toBe(0);
|
||||
});
|
||||
|
||||
it("allows the limit-th request (boundary: exactly limit is allowed)", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(10 as never);
|
||||
|
||||
const result = await redisSlidingWindow("test:key", 10, 60_000);
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects the (limit+1)-th request (boundary: one over limit is rejected)", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(11 as never);
|
||||
// Oldest entry was added 10 seconds ago inside a 60s window
|
||||
const now = Date.now();
|
||||
const oldestScore = now - 10_000;
|
||||
(mockRedis as unknown as { zrange: ReturnType<typeof vi.fn> }).zrange.mockResolvedValue(
|
||||
[`${oldestScore}:abc`, String(oldestScore)] as never,
|
||||
);
|
||||
|
||||
const result = await redisSlidingWindow("test:key", 10, 60_000);
|
||||
expect(result.allowed).toBe(false);
|
||||
// retryAfterMs should be ~50s (oldestScore + 60000 - now), not the full 60000
|
||||
expect(result.retryAfterMs).toBeGreaterThan(0);
|
||||
expect(result.retryAfterMs).toBeLessThan(60_000);
|
||||
});
|
||||
|
||||
it("computes retryAfterMs from the oldest entry score, not the full window", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(11 as never);
|
||||
// Oldest entry was added 55 seconds ago in a 60s window; should expire in ~5s
|
||||
const now = Date.now();
|
||||
const oldestScore = now - 55_000;
|
||||
(mockRedis as unknown as { zrange: ReturnType<typeof vi.fn> }).zrange.mockResolvedValue(
|
||||
[`${oldestScore}:xyz`, String(oldestScore)] as never,
|
||||
);
|
||||
|
||||
const result = await redisSlidingWindow("test:key", 10, 60_000);
|
||||
expect(result.allowed).toBe(false);
|
||||
// Expected: oldestScore + 60000 - now = ~5000ms
|
||||
expect(result.retryAfterMs).toBeGreaterThanOrEqual(1);
|
||||
expect(result.retryAfterMs).toBeLessThanOrEqual(6_000);
|
||||
});
|
||||
|
||||
it("fails OPEN when Redis throws (never blocks legit users on Redis outage)", async () => {
|
||||
mockRedis.zremrangebyscore.mockRejectedValue(new Error("ECONNREFUSED"));
|
||||
|
||||
const result = await redisSlidingWindow("test:key", 10, 60_000);
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("calls zremrangebyscore, zadd, expire, and zcard once each on allowed request", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(1 as never);
|
||||
|
||||
await redisSlidingWindow("mcp:ratelimit:key:k1", 120, 60_000);
|
||||
|
||||
expect(mockRedis.zremrangebyscore).toHaveBeenCalledTimes(1);
|
||||
expect(mockRedis.zadd).toHaveBeenCalledTimes(1);
|
||||
expect(mockRedis.expire).toHaveBeenCalledTimes(1);
|
||||
expect(mockRedis.zcard).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses unique ZSET members so two same-instant calls each occupy their own slot", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(1 as never);
|
||||
|
||||
await redisSlidingWindow("test:key", 10, 60_000);
|
||||
await redisSlidingWindow("test:key", 10, 60_000);
|
||||
|
||||
// zadd must have been called twice with different member values
|
||||
expect(mockRedis.zadd).toHaveBeenCalledTimes(2);
|
||||
const [call1, call2] = mockRedis.zadd.mock.calls as [unknown, unknown, string][];
|
||||
const member1 = call1[2];
|
||||
const member2 = call2[2];
|
||||
expect(member1).not.toBe(member2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Unit tests for isSigningKeyValid().
|
||||
*
|
||||
* signingKeyConfig imports `edition` from @/core/edition, which is a module-level
|
||||
* constant evaluated at import time. We use vi.resetModules() + vi.stubEnv() and
|
||||
* dynamic imports per test so each case gets a fresh module evaluation.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
// Restore env to a clean baseline before each test.
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
delete process.env.AUTH_SECRET;
|
||||
});
|
||||
|
||||
async function getCheck(): Promise<() => boolean> {
|
||||
const mod = await import("./signingKeyConfig");
|
||||
return mod.isSigningKeyValid;
|
||||
}
|
||||
|
||||
describe("isSigningKeyValid", () => {
|
||||
it("returns true for local edition regardless of missing env vars", async () => {
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "local");
|
||||
const check = await getCheck();
|
||||
expect(check()).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for cloud edition when API_KEY_HMAC_SECRET is not set", async () => {
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "cloud");
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
const check = await getCheck();
|
||||
expect(check()).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for cloud edition when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "cloud");
|
||||
process.env.API_KEY_HMAC_SECRET = "shared-secret";
|
||||
process.env.AUTH_SECRET = "shared-secret";
|
||||
const check = await getCheck();
|
||||
expect(check()).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true for cloud edition when API_KEY_HMAC_SECRET is set and distinct from AUTH_SECRET", async () => {
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "cloud");
|
||||
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-secret-value";
|
||||
process.env.AUTH_SECRET = "different-auth-secret-value";
|
||||
const check = await getCheck();
|
||||
expect(check()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Pure, side-effect-free predicate for the HMAC signing-key configuration rule.
|
||||
*
|
||||
* Single source of truth for the cloud/demo guard that also lives in
|
||||
* apiKeyAuth.getSigningKey() and was previously duplicated in healthProbes.
|
||||
* No crypto operations, no I/O, no imports beyond the edition constant.
|
||||
*/
|
||||
|
||||
import { edition } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* Returns true when the HMAC signing-key preconditions are satisfied for the
|
||||
* current edition.
|
||||
*
|
||||
* Local edition: always true. AUTH_SECRET fallback is intentional and the
|
||||
* dedicated key is optional.
|
||||
*
|
||||
* Cloud/demo edition: API_KEY_HMAC_SECRET must be present and must differ from
|
||||
* AUTH_SECRET. Either absence is an operator misconfiguration.
|
||||
*/
|
||||
export function isSigningKeyValid(): boolean {
|
||||
if (edition === "local") return true;
|
||||
|
||||
const dedicated = process.env.API_KEY_HMAC_SECRET;
|
||||
const fallback = process.env.AUTH_SECRET;
|
||||
|
||||
return !!dedicated && dedicated !== fallback;
|
||||
}
|
||||
+97
-25
@@ -2,11 +2,62 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { isDemo, isHttpsDeployment } from "@/core/edition";
|
||||
|
||||
const workspaceCache = new Map<string, { status: string; expiresAt: number }>();
|
||||
const CACHE_TTL = 60_000; // 60 seconds
|
||||
|
||||
// Anchored static-asset allowlist. Only requests ending in a real asset
|
||||
// extension bypass the auth gate. This replaces the former `path.includes(".")`
|
||||
// check, which let ANY dotted path (e.g. `/secret.page`, `/globe.config`)
|
||||
// skip authentication entirely.
|
||||
const STATIC_ASSET_RE = /\.(?:js|mjs|cjs|css|map|json|txt|xml|webmanifest|ico|png|jpe?g|gif|svg|webp|avif|bmp|woff2?|ttf|otf|eot|wasm|mp4|webm|glb|gltf)$/i;
|
||||
|
||||
// API routes that must stay reachable WITHOUT a logged-in session cookie.
|
||||
// Everything else under /api is deny-by-default (requires a valid session JWT).
|
||||
// - auth/internal/health/billing-webhook: pre-login, server-to-server, infra, or external callers.
|
||||
// - mcp/globe/v1-entities: dual-auth routes that self-guard via Bearer API key
|
||||
// (programmatic clients send no session cookie, so the gate must not block them).
|
||||
// - marketplace/*: every marketplace route self-guards. validateMarketplaceAuth
|
||||
// accepts a cross-origin Bearer marketplace JWT (callers send no session cookie),
|
||||
// auth() guards the same-origin routes, and sideload is NODE_ENV-gated to dev.
|
||||
// Gating the prefix here would 401 those cross-origin Bearer/preflight requests
|
||||
// before their own auth runs, breaking install/manage from the marketplace origin.
|
||||
// - glitchtip-tunnel/build/dev: telemetry/diagnostics (dev/* is NODE_ENV-gated to 403 in prod).
|
||||
const PUBLIC_API_PREFIXES = [
|
||||
"/api/auth",
|
||||
"/api/internal/workspace",
|
||||
"/api/health",
|
||||
"/api/billing/webhook",
|
||||
"/api/mcp",
|
||||
"/api/globe",
|
||||
"/api/v1/entities",
|
||||
"/api/marketplace",
|
||||
"/api/glitchtip-tunnel",
|
||||
"/api/build",
|
||||
"/api/dev",
|
||||
];
|
||||
|
||||
function isPublicApiPath(path: string): boolean {
|
||||
return PUBLIC_API_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));
|
||||
}
|
||||
|
||||
// Resolve the Auth.js session token, handling the __Secure- cookie prefix used
|
||||
// behind a TLS-terminating reverse proxy (the public URL is https but the
|
||||
// request reaching us may be plain http). Detect via X-Forwarded-Proto / AUTH_URL.
|
||||
async function getSessionToken(req: NextRequest) {
|
||||
// Request-aware OR the deploy-wide https signal (isHttpsDeployment), so the
|
||||
// reader agrees with the cookie writer (auth.ts) on the __Secure- prefix.
|
||||
const isSecure = req.headers.get("x-forwarded-proto") === "https"
|
||||
|| isHttpsDeployment()
|
||||
|| req.nextUrl.protocol === "https:";
|
||||
return getToken({
|
||||
req,
|
||||
secret: process.env.AUTH_SECRET,
|
||||
secureCookie: isSecure,
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveWorkspace(subdomain: string) {
|
||||
const cached = workspaceCache.get(subdomain);
|
||||
if (cached && Date.now() < cached.expiresAt) return cached;
|
||||
@@ -62,16 +113,49 @@ export default async function proxy(req: NextRequest) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// Static assets, API routes, data files — always pass through.
|
||||
// Strip any client-supplied x-tenant-subdomain on /api/* before forwarding,
|
||||
// then re-inject only the server-resolved value (H2: tenant-header spoof prevention).
|
||||
// A forged header must never reach the Prisma tenant extension.
|
||||
// API routes: DENY BY DEFAULT. Evaluated BEFORE the static-asset allowlist so
|
||||
// that no `/api/...` path ending in an asset-like extension (e.g. a catch-all
|
||||
// segment such as `/api/x/y.json`) can match the static fast-path and skip the
|
||||
// gate. Public/self-guarded routes pass through; every other /api route requires
|
||||
// a valid session JWT (else 401 JSON). This closes the former blanket `/api`
|
||||
// pass-through that left unauthenticated data proxies (places/*, camera/test,
|
||||
// earthquake, iss*, weather*, ...) open and burning server-held upstream keys.
|
||||
if (path.startsWith("/api")) {
|
||||
const res = NextResponse.next();
|
||||
// Always drop a client-supplied tenant header; only the server-resolved
|
||||
// value may be forwarded (H2: tenant-header spoof prevention).
|
||||
res.headers.delete("x-tenant-subdomain");
|
||||
|
||||
// CORS preflight is credential-less by design (no cookie, no Authorization
|
||||
// header), so gating it would 401 the preflight and break every cross-origin
|
||||
// API route before its real request is ever sent. Let OPTIONS through; the
|
||||
// route's own OPTIONS/CORS handler answers it (no body, nothing to leak).
|
||||
if (req.method === "OPTIONS") return res;
|
||||
|
||||
if (isPublicApiPath(path)) {
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
const apiToken = await getSessionToken(req);
|
||||
if (apiToken) {
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Unauthorized" },
|
||||
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
|
||||
);
|
||||
}
|
||||
|
||||
// Static assets and internal data dirs always pass through (no auth).
|
||||
// Static files match an explicit extension allowlist instead of the old,
|
||||
// bypass-prone `path.includes(".")` (which let any dotted path skip the gate).
|
||||
if (
|
||||
path.startsWith("/_next")
|
||||
|| path.startsWith("/api")
|
||||
|| path.startsWith("/data")
|
||||
|| path.startsWith("/cesium")
|
||||
|| path.includes(".")
|
||||
|| STATIC_ASSET_RE.test(path)
|
||||
) {
|
||||
const res = NextResponse.next();
|
||||
res.headers.delete("x-tenant-subdomain");
|
||||
@@ -91,7 +175,7 @@ export default async function proxy(req: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Auth pages — always accessible
|
||||
// Auth pages: always accessible
|
||||
if (path.startsWith("/setup") || path.startsWith("/login")) {
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
@@ -106,30 +190,18 @@ export default async function proxy(req: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check JWT session from Auth.js cookie.
|
||||
// Behind a TLS-terminating reverse proxy, the cookie was set with the
|
||||
// `__Secure-` prefix (because the public URL is https), but the request
|
||||
// reaching us is plain http, so getToken's auto-detection looks for the
|
||||
// unprefixed name and misses it. Detect via X-Forwarded-Proto / AUTH_URL.
|
||||
const xfProto = req.headers.get("x-forwarded-proto");
|
||||
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
|
||||
const isSecure = xfProto === "https"
|
||||
|| authUrl.startsWith("https://")
|
||||
|| req.nextUrl.protocol === "https:";
|
||||
const token = await getToken({
|
||||
req,
|
||||
secret: process.env.AUTH_SECRET,
|
||||
secureCookie: isSecure,
|
||||
});
|
||||
// Check the Auth.js session cookie for page requests (the helper handles the
|
||||
// __Secure- cookie prefix used behind a TLS-terminating reverse proxy).
|
||||
const token = await getSessionToken(req);
|
||||
|
||||
if (token) {
|
||||
// User is logged in — allow through
|
||||
// User is logged in, allow through
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Not logged in — check if first-run (no users)
|
||||
// Not logged in: check if first-run (no users)
|
||||
try {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || `http://127.0.0.1:${process.env.PORT || "3000"}`;
|
||||
const url = new URL("/api/auth/setup-status", appUrl);
|
||||
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
import type { DefaultSession } from "next-auth";
|
||||
|
||||
/**
|
||||
* Module augmentation for NextAuth/Auth.js. The app carries a per-user `role`
|
||||
* and a `sessionVersion` (used for session revocation) on the authorized user,
|
||||
* the session, and the JWT. Declaring them here makes those fields first-class
|
||||
* and removes the need for `as { role?: string }` casts throughout auth.ts.
|
||||
*/
|
||||
declare module "next-auth" {
|
||||
interface User {
|
||||
role?: string;
|
||||
sessionVersion?: number;
|
||||
}
|
||||
|
||||
interface Session {
|
||||
user: {
|
||||
id: string;
|
||||
role?: string;
|
||||
} & DefaultSession["user"];
|
||||
}
|
||||
}
|
||||
|
||||
declare module "next-auth/jwt" {
|
||||
interface JWT {
|
||||
id?: string;
|
||||
role?: string;
|
||||
sessionVersion?: number;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user