Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7936990385 |
No files matched your search
@@ -72,23 +72,6 @@ mapWebsocketPayload(payload: any, existingEntities: GeoEntity[]): GeoEntity[]
|
||||
- `existingEntities` — current entities in the store for this plugin (use for incremental updates)
|
||||
- Must return a **complete replacement** `GeoEntity[]` (not a diff)
|
||||
|
||||
### Property Tag Helpers
|
||||
|
||||
Always wrap typed property values with the SDK helpers so the Intel panel renders them richly:
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
properties: {
|
||||
updated: dtProp(item.updated_at ?? null), // renders as expandable datetime row
|
||||
source: urlProp(item.source_url ?? null), // renders as clickable link
|
||||
preview: imageProp(item.image ?? null), // renders as inline thumbnail
|
||||
stream: videoProp(item.video_url ?? null), // renders as "Watch" link
|
||||
}
|
||||
```
|
||||
|
||||
All helpers are null-safe and return `null` for empty input. Plain string/number values that don't need rich rendering need no wrapper.
|
||||
|
||||
---
|
||||
|
||||
## Plugin Architectures (Manifest Formats)
|
||||
|
||||
@@ -202,40 +202,7 @@ import { Plane } from "lucide-react";
|
||||
const iconUrl = createSvgIconUrl(Plane, { color: "#3b82f6" });
|
||||
```
|
||||
|
||||
### 1.5 Property Tag Helpers
|
||||
|
||||
Use these SDK helpers to wrap property values so the Intel panel renders them richly. Without the tag prefix, the panel falls back to plain text.
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
```
|
||||
|
||||
| Helper | Tag format stored | Panel renders as |
|
||||
|---|---|---|
|
||||
| `dtProp(iso)` | `"datetime:2026-06-01T05:00:00Z"` | Expandable row: local time (collapsed), UTC + relative (expanded) |
|
||||
| `urlProp(href)` | `"url:https://..."` | Clickable link with external icon |
|
||||
| `imageProp(src)` | `"image:https://..."` | Inline thumbnail |
|
||||
| `videoProp(href)` | `"video:https://..."` | "Watch" link with play icon |
|
||||
|
||||
All four helpers return `null` for empty, `null`, or `undefined` input — safe to call unconditionally.
|
||||
|
||||
**Usage pattern:**
|
||||
```ts
|
||||
properties: {
|
||||
// dates — pass ISO 8601 strings
|
||||
updated_at: dtProp(item.updated_at ?? null),
|
||||
// URLs
|
||||
source_url: urlProp(item.url ?? null),
|
||||
// images and video
|
||||
preview: imageProp(item.image_url ?? null),
|
||||
stream: videoProp(item.video_url ?? null),
|
||||
// plain values — no helper needed
|
||||
name: item.name,
|
||||
count: item.count,
|
||||
}
|
||||
```
|
||||
|
||||
### 1.6 Registration (3 Paths)
|
||||
### 1.5 Registration (3 Paths)
|
||||
|
||||
**A. Built-in (monorepo package):**
|
||||
|
||||
@@ -257,7 +224,7 @@ await pluginManager.registerPlugin(plugin);
|
||||
**C. Dynamic import (runtime):**
|
||||
For user-imported GeoJSON layers, call `pluginManager.loadFromManifest(manifest)` directly.
|
||||
|
||||
### 1.7 Build Configuration (Core Monorepo Packages Only)
|
||||
### 1.6 Build Configuration (Core Monorepo Packages Only)
|
||||
|
||||
If you decide to manually move a plugin from the local sandbox into the core `packages/` directory, you must manually add it to the build pipeline:
|
||||
|
||||
@@ -685,10 +652,6 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
|
||||
- [ ] **Frontend:** Added path alias in `tsconfig.json`
|
||||
- [ ] **Frontend:** Registered via `pluginRegistry` + `pluginManager` in `AppShell.tsx`
|
||||
- [ ] **Frontend:** `renderEntity()` doesn't mix point/billboard properties
|
||||
- [ ] **Frontend:** Date/time fields wrapped with `dtProp()`
|
||||
- [ ] **Frontend:** External links wrapped with `urlProp()`
|
||||
- [ ] **Frontend:** Image URLs wrapped with `imageProp()`
|
||||
- [ ] **Frontend:** Video/stream URLs wrapped with `videoProp()`
|
||||
- [ ] **Engine:** Seeder file in `wwv-seeders/src/seeders/<name>.ts` (or private repo)
|
||||
- [ ] **Engine:** `registerSeeder({ name })` matches frontend plugin `id`
|
||||
- [ ] **Engine:** Calls `setLiveSnapshot()` with correct plugin ID key
|
||||
|
||||
@@ -1,26 +1,15 @@
|
||||
name: CI
|
||||
|
||||
# CLI-only changes are covered by cli.yml; skip the full app suite for them.
|
||||
# Docs/agent-rules/issue-template changes also skip the suite.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".agents/**"
|
||||
- "**/*.md"
|
||||
- ".github/ISSUE_TEMPLATE/**"
|
||||
- ".github/PULL_REQUEST_TEMPLATE.md"
|
||||
- ".github/gc/**"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".agents/**"
|
||||
- "**/*.md"
|
||||
- ".github/ISSUE_TEMPLATE/**"
|
||||
- ".github/PULL_REQUEST_TEMPLATE.md"
|
||||
- ".github/gc/**"
|
||||
|
||||
jobs:
|
||||
# Non-blocking dependency audit. Surfaces high / critical vulnerabilities
|
||||
|
||||
@@ -1,33 +1,15 @@
|
||||
name: Docker Image CI
|
||||
|
||||
# Only rebuild the image when files that affect the final container change.
|
||||
# Doc/agent-rules/test-only changes skip the expensive multi-stage build.
|
||||
# Skipped workflow runs satisfy GitHub required status checks (neutral pass).
|
||||
# CLI-only changes are covered by cli.yml; skip the image build for them.
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -1,32 +1,14 @@
|
||||
name: Playwright Tests
|
||||
# Only run E2E tests when application code actually changes.
|
||||
# Doc/agent-rules/config-only changes skip the full 3-browser matrix.
|
||||
# Skipped workflow runs satisfy GitHub required status checks (neutral pass).
|
||||
# CLI-only changes are covered by cli.yml; skip browser E2E for them.
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "tests/**"
|
||||
- "prisma/**"
|
||||
- "public/**"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- "playwright.config.ts"
|
||||
- ".github/workflows/playwright.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
pull_request:
|
||||
branches: [ main, master ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "tests/**"
|
||||
- "prisma/**"
|
||||
- "public/**"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- "playwright.config.ts"
|
||||
- ".github/workflows/playwright.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
|
||||
-10
@@ -157,13 +157,3 @@ worldwideview.code-workspace
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/playwright/.auth/
|
||||
/.playwright-mcp/
|
||||
|
||||
# MCP client config -- contains a live API key, never commit
|
||||
.mcp.json
|
||||
|
||||
# Root-level UAT / debug scratch artifacts
|
||||
/uat-*.png
|
||||
/step*.png
|
||||
/mcp-test-*.png
|
||||
/api-keys-response.json
|
||||
@@ -1,130 +0,0 @@
|
||||
# Roadmap: Full MCP Support (v1.2)
|
||||
|
||||
> **Planning home:** This is the isolated planning for the **v1.2 Full MCP Support** milestone,
|
||||
> living in the `feat/mcp-support` worktree of `worldwideview`. It was split out of the shared
|
||||
> root `C:\dev\wwv\.planning\ROADMAP.md` on 2026-05-29 (that file now holds v1.1 only).
|
||||
> Combined pre-split original: `C:\dev\wwv\.planning\archive\pre-split-2026-05-29\ROADMAP.combined.md`.
|
||||
>
|
||||
> **QA ID note:** the v1.2 quality requirements were renamed `QA-01/02/03` -> `MCP-QA-01/02/03`
|
||||
> during the split, to resolve a collision with v1.1's own `QA-01/02/03`.
|
||||
|
||||
## Milestone
|
||||
|
||||
- v1.2 **Full MCP Support** - Phases 16-21 (greenfield; no v1.2 code exists yet as of 2026-05-29)
|
||||
|
||||
**Primary repo:** `worldwideview` (this worktree).
|
||||
**Cross-repo dependencies (declared, not separate planning roots):**
|
||||
- **Phase 20** delegates entity queries to `wwv-data-engine` REST endpoints.
|
||||
- **Phase 21** depends on `wwv-data-engine` REST (plugin tool delegation), the `@worldwideview/wwv-plugin-sdk` package (manifest `mcpTools` extension), and the existing `worldwideview-marketplace` JWT install bridge (for `list_plugins` / `install_plugin`).
|
||||
|
||||
## Phases
|
||||
|
||||
- [ ] **Phase 16: API Key Auth Foundation** - generic transport-agnostic API keys: UserApiKey DB model, bcrypt prefix-hash storage, reusable `authenticateApiKey()` middleware, "Keys & Access" modal key CRUD + reveal-once UI
|
||||
- [ ] **Phase 17: MCP Server Foundation** - raw `@modelcontextprotocol/sdk` Streamable HTTP endpoint in a Next 16 route handler, Bearer auth gate, stateless operation, Coolify/Nginx runbook, + "Connect your agent" helper (per-client config + prompt template)
|
||||
- [ ] **Phase 18: Globe State Sync + Sessions** - useGlobeStatePush hook, heartbeat, globe://state and globe://sessions resources
|
||||
- [ ] **Phase 19: Globe Command Bridge** - WebSocket relay, useGlobeCommandBridge hook, per-session Redis pub/sub routing
|
||||
- [ ] **Phase 20: Data Query Tools** - search_entities, get_entities_in_region, get_entity_details, get_plugin_data (parallel with Phase 19)
|
||||
- [ ] **Phase 21: Plugin-Contributed Tools + Quality** - SDK manifest extension, auto-namespace, plugin bridge, dynamic tool list, tests, README
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 16: API Key Auth Foundation
|
||||
**Goal**: Users can generate, view, and revoke generic personal API keys; keys are stored securely and a reusable `authenticateApiKey()` middleware is ready for Phase 17 (MCP) and future REST routes
|
||||
**Depends on**: Nothing (first phase of v1.2)
|
||||
**Target repo**: worldwideview ("Keys & Access" modal section + Prisma `UserApiKey` model + auth middleware)
|
||||
**Requirements**: KEY-01, KEY-02, KEY-03, KEY-04, API-01 (middleware portion)
|
||||
**Architecture note**: keys are **transport-agnostic** (not MCP-only); the auth middleware is reusable; capabilities are a shared service layer wrapped thinly by MCP/REST. The per-client "Connect your agent" helper is **Phase 17** (needs the live `/api/mcp` URL); Phase 16 ships only the key + the "API & MCP Access" section shell.
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. User clicks "Generate API Key" in the "Keys & Access" modal and sees the full combined `wwv_<prefix>.<secret>` token exactly once in a copyable field with a "won't see this again" warning
|
||||
2. Key is stored as `{prefix}.{bcrypt(secret, cost=12)}`; lookup by prefix; a dummy bcrypt compare runs even when prefix is not found (timing oracle prevention)
|
||||
3. User can view active keys (name, created, last used) and revoke any -- revoked (hard-deleted) key returns 401 immediately on next request
|
||||
4. Attempting to generate a 4th key returns a clear error; max 3 enforced in the create route AND the UI
|
||||
5. `authenticateApiKey(request)` exists as a standalone, transport-neutral helper (importable by any future route), with `lastUsedAt` updated best-effort/throttled on success
|
||||
**Plans**: 4 plans (4 waves)
|
||||
- [x] 16-01-PLAN.md — Wave 0 RED test scaffolds (helper + route tests) — COMPLETE 2026-05-29
|
||||
- [x] 16-02-PLAN.md — UserApiKey schema + db push + timing-safe apiKeyAuth.ts helper
|
||||
- [x] 16-03-PLAN.md — /api/api-keys CRUD routes (list, create max-3, ownership-scoped revoke)
|
||||
- [ ] 16-04-PLAN.md — PersonalApiKeysSection UI + Header 'Keys & Access' wiring + semver bump
|
||||
|
||||
### Phase 17: MCP Server Foundation
|
||||
**Goal**: A valid Streamable HTTP MCP endpoint is live, authenticated, stateless, confirmed streaming in production, AND users can connect their AI client in one copy-paste step
|
||||
**Depends on**: Phase 16
|
||||
**Target repo**: worldwideview (+ Coolify/Nginx infra config)
|
||||
**Requirements**: MCP-01, MCP-02, MCP-03, MCP-04, CONNECT-01, CONNECT-02, CONNECT-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Claude Code connects to `/api/mcp` with a valid Bearer key and receives a handshake with `protocolVersion`, `serverInfo`, and the full tools/resources list
|
||||
2. An unauthenticated request returns HTTP 401 with a JSON-RPC 2.0 error shape
|
||||
3. No `McpServer` instance is cached between requests -- each request creates a fresh one (stateless confirmed)
|
||||
4. The Coolify Nginx config includes `X-Accel-Buffering: no` and extended `proxy_read_timeout`; a 60-second streaming connection holds open without disconnect
|
||||
5. The "API & MCP Access" section renders a per-client connection helper (Claude Desktop / Cursor / VS Code `mcpServers` JSON with Bearer header; generic Manual block; Claude Code CLI deferred as "coming soon") + a copy-paste "prompt for your agent"; the secret never appears in a URL/deep-link query
|
||||
**Library decision**: raw `@modelcontextprotocol/sdk@^1.29.0` (NOT mcp-handler) + the SDK's `WebStandardStreamableHTTPServerTransport` inside a Next 16 App Router route handler — confirmed against SDK 1.29.0 published types, NO custom server.ts needed in Phase 17 (per `BATCH-DECISIONS-17-21.md` / `17-CONTEXT.md`).
|
||||
**Plans**: 3 plans (3 waves)
|
||||
- [x] 17-01-PLAN.md — Wave 0: RED test scaffolds (route auth/edition/stateless/streaming-header tests) + raw-SDK transport runtime spike
|
||||
- [ ] 17-02-PLAN.md — Wave 1: install SDK + createMcpServer() factory + gated stateless /api/mcp route handler (turns Wave 0 green)
|
||||
- [ ] 17-03-PLAN.md — Wave 2: ConnectAgentHelper UI (per-client config + prompt) + Coolify/Nginx runbook + semver bump to 2.26.0
|
||||
|
||||
### Phase 18: Globe State Sync + Sessions
|
||||
**Goal**: Claude can read what is on the globe and which browser tabs are open, with accurate live data
|
||||
**Depends on**: Phase 17
|
||||
**Target repo**: worldwideview (+ Redis)
|
||||
**Requirements**: RSRC-01, RSRC-02, RSRC-03, RSRC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. `globe://state/{sessionId}` returns the current viewport (lat/lng/altitude/heading/pitch), active layer list, selected entity, and timeline position
|
||||
2. `globe://sessions` lists all open browser tabs with sessionId, viewport summary, active layers, and last-seen timestamp
|
||||
3. A closed browser tab drops from `globe://sessions` within 30 seconds (heartbeat TTL expiry)
|
||||
4. A viewport change in the browser is reflected in `globe://state` within 1 second (500ms debounce + network round trip)
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 19: Globe Command Bridge
|
||||
**Goal**: Claude can send pan, zoom, layer, and timeline commands that physically execute in the correct open browser tab
|
||||
**Depends on**: Phase 18 (needs sessionIds from heartbeat registry)
|
||||
**Target repo**: worldwideview (+ Redis)
|
||||
**Requirements**: CTRL-01, CTRL-02, CTRL-03, CTRL-04, CTRL-05, CTRL-06
|
||||
**Note**: Phases 19 and 20 can be executed in parallel once Phase 17 is complete
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `pan_globe({ sessionId, lat: 35.68, lng: 139.69 })` causes the CesiumJS camera to fly to Tokyo in the targeted browser tab
|
||||
2. `toggle_layer` visibly enables or disables a plugin layer in the globe
|
||||
3. With 2 tabs open, Claude reads `globe://sessions`, picks the contextually correct tab, and only that tab receives the command
|
||||
4. Opening 10 concurrent MCP connections does not create 10 Redis subscriptions -- singleton subscriber confirmed
|
||||
5. A Redis restart does not permanently break command delivery; the subscriber reconnects and commands resume within 5 seconds
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 20: Data Query Tools
|
||||
**Goal**: Claude can query live entity data across all active plugins without requiring an open browser tab
|
||||
**Depends on**: Phase 17 (stateless reads from data engine REST; no browser session required)
|
||||
**Target repo**: worldwideview MCP route + **wwv-data-engine** (REST query delegation) -- cross-repo
|
||||
**Requirements**: QUERY-01, QUERY-02, QUERY-03, QUERY-04
|
||||
**Note**: Can be executed in parallel with Phase 19
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. `search_entities({ query: "Singapore" })` returns entities from active plugins near Singapore with id, name, lat/lng, plugin
|
||||
2. `get_entities_in_region` with a bounding box returns all entities within it, respecting the optional `pluginId` filter
|
||||
3. `get_entity_details` returns the full properties object for a specific entity without error
|
||||
4. `get_plugin_data` returns the current snapshot gracefully even when the plugin has no active data (empty array, not a crash)
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 21: Plugin-Contributed Tools + Quality
|
||||
**Goal**: Installed plugins expose their own namespaced MCP tools; the tool list updates dynamically; the feature is documented and tested
|
||||
**Depends on**: Phases 19 and 20
|
||||
**Target repo**: worldwideview MCP route + **`@worldwideview/wwv-plugin-sdk`** (manifest extension) + **wwv-data-engine** (plugin tool delegation) + **worldwideview-marketplace** JWT bridge (`list_plugins` / `install_plugin`) -- cross-repo, 3 external deps
|
||||
**Requirements**: PLUG-01, PLUG-02, PLUG-03, PLUG-04, PLG-01, PLG-02, MCP-QA-01, MCP-QA-02, MCP-QA-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. A plugin with `mcpTools` in its manifest has those tools registered as `{pluginId}__toolName`; existing plugins without `mcpTools` are unaffected
|
||||
2. Installing a new plugin fires `notifications/tools/list_changed`; Claude's next `tools/list` call includes the new plugin's tools
|
||||
3. `list_plugins()` returns marketplace plugins with accurate install status; `install_plugin({ pluginSlug })` triggers the existing JWT bridge flow
|
||||
4. The README contains a copy-pasteable Claude Code MCP config block that works end-to-end with a generated API key
|
||||
5. Vitest tests pass: auth rejection (401), tool dispatch to correct handler, malformed input errors, Redis singleton reconnection
|
||||
|
||||
## Progress
|
||||
|
||||
**Execution Order:**
|
||||
Phases execute in numeric order, with one parallel branch: 16 -> 17 -> { 18 -> 19, 20 } -> 21
|
||||
(Phases 19 and 20 may run in parallel once 17 is done; 18 must precede 19.)
|
||||
|
||||
| Phase | Milestone | Plans Complete | Status | Completed |
|
||||
|-------|-----------|----------------|--------|-----------|
|
||||
| 16. API Key Auth Foundation | v1.2 | 3/4 | In Progress| |
|
||||
| 17. MCP Server Foundation | v1.2 | 1/3 | In Progress| |
|
||||
| 18. Globe State Sync + Sessions | v1.2 | 0/? | Not started | - |
|
||||
| 19. Globe Command Bridge | v1.2 | 0/? | Not started | - |
|
||||
| 20. Data Query Tools | v1.2 | 0/? | Not started | - |
|
||||
| 21. Plugin-Contributed Tools + Quality | v1.2 | 0/? | Not started | - |
|
||||
@@ -1,216 +0,0 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.2
|
||||
milestone_name: Full MCP Support
|
||||
status: active
|
||||
last_updated: "2026-05-30T09:54:58.389Z"
|
||||
progress:
|
||||
total_phases: 7
|
||||
completed_phases: 3
|
||||
total_plans: 23
|
||||
completed_plans: 16
|
||||
percent: 43
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
Isolated planning workspace for the **v1.2 Full MCP Support** milestone (Phases 16-21).
|
||||
Split out of the shared root `C:\dev\wwv\.planning` on 2026-05-29 because v1.1 (marketplace
|
||||
auth gate) and v1.2 (MCP server) were tangled in one ROADMAP/REQUIREMENTS with no shared
|
||||
phases or dependency.
|
||||
|
||||
Primary repo: this worktree (`worldwideview`, branch `feat/mcp-support`).
|
||||
Cross-repo deps declared in ROADMAP.md: Phase 20 -> wwv-data-engine REST; Phase 21 ->
|
||||
wwv-data-engine + `@worldwideview/wwv-plugin-sdk` + marketplace JWT bridge.
|
||||
|
||||
Cross-feature docs (MILESTONES.md, the plugin-pipeline backlogs) stay at the shared root and
|
||||
are NOT duplicated here.
|
||||
|
||||
## Current Position
|
||||
|
||||
**Phase 16:** code complete (5f3fe69 UI, 90dfb68 tsc fix). UAT run on :3005 (Playwright) passed steps
|
||||
1-5 EXCEPT: (a) cosmetic - existing section header reads "Your API Keys" not spec's "Service Keys"
|
||||
(fix in progress); (b) ANOMALY - after reload, GET /api/api-keys returned [] (all keys vanished). A
|
||||
debugger agent is investigating whether (b) is a code bug or a shared-dev-DB-across-worktrees artifact,
|
||||
and fixing (a). Phase 16 NOT marked verified until (b) is resolved.
|
||||
|
||||
**Phase 17:** COMPLETE (verified 2026-05-30). Wave 0 (fcb7a5e) + Wave 1 (e0ad832, 0053f1d) + Wave 2
|
||||
(6f77495). Human-verify PASSED 6/6: token only in Authorization header, copy buttons flip, placeholder
|
||||
after dismiss, 401 JSON-RPC body, 200 SSE with x-accel-buffering:no + protocolVersion 2025-06-18.
|
||||
Version 2.26.0.
|
||||
|
||||
**Phase 18:** COMPLETE (2026-05-30). Wave 0 + 1 + 2 + 3 all done. 498/498 tests GREEN. Delivered:
|
||||
ioredis singleton, GlobeStateSnapshot, globeStateStore (ZSET sessions), POST /api/globe/state (dual
|
||||
auth per R-2), useSessionId + useGlobeStateSync hooks, GlobeView wiring, registerGlobeResources MCP
|
||||
module (RSRC-02/03/04), route.ts first R-1 edit. Version TBD (bump in final commit).
|
||||
|
||||
**Phase 20:** COMPLETE (2026-05-30). All waves done. 498/498 tests GREEN. Delivered: types.ts +
|
||||
service.ts transport-neutral service layer, REST routes (search + region), registerDataQueryTools
|
||||
MCP module (TOOL-01/02/03/04), route.ts second R-1 edit. Commit a5b4b62 (combined with Phase 18).
|
||||
Version 2.27.0.
|
||||
|
||||
**Phase 19:** SPLIT (2026-05-30, user-approved) into 19a + 19b. See phases/19-globe-command-bridge/19-SPLIT.md.
|
||||
|
||||
- **19a (Globe Command System Tools, poll-based):** COMPLETE (2026-05-30, commit a3c8f12). Command tools
|
||||
(pan/focus/toggle/timeline) + Redis list queue + GET /api/globe/commands poll route + browser poll hook.
|
||||
NO boot-path change. Covers CTRL-04 + CTRL-05. Version 2.28.0.
|
||||
|
||||
- All 3 waves GREEN. Full suite 573 passed / 0 failed.
|
||||
- code-reviewer + security-reviewer DONE: no Critical/High. Security PASS on hard invariants (userId only
|
||||
from auth, gate ordering rate-limit -> isDemo 403 -> auth, per-user/tenant queue namespacing, no secret in
|
||||
URL, double-validation). Review findings folded in: timeWindow/currentTime validation, atomic enqueue
|
||||
(multi.rpush.expire), UUID sessionId 400 guard, dedicated globeCommandsLimiter (120/60s), in-flight poll
|
||||
guard, focusEntity entityId-only -> console.warn (no 0,0 fly), z.enum timeWindow.
|
||||
|
||||
- Committed: 15 files (excluded pnpm-lock.yaml, .planning, debug PNGs per constraints).
|
||||
- **Phase 21 readiness (IMPORTANT — two conflicting plan generations on disk):**
|
||||
- AUTHORITATIVE: 21-REPLAN.md + 21-DECISIONS.md (May 30 02:16) — PLUG-03 via streamUrl delegation,
|
||||
worldwideview-only, NO engine endpoint, NO marketplace. 4 decisions LOCKED.
|
||||
|
||||
- STALE: 21-RESEARCH.md + 21-01..04-PLAN.md (May 29 22:31-23:28) — route PLUG-03 through a NEW
|
||||
wwv-data-engine REST endpoint + marketplace JWT bridge. DO NOT EXECUTE these wave plans; they predate
|
||||
the re-plan. Archive them and regenerate 21-01..N against 21-REPLAN.md before executing.
|
||||
|
||||
- OPEN DECISION (the one heavy item): InstalledPlugin model is keyed by tenantId (nullable), NOT userId.
|
||||
The MCP auth chain produces userId. Wave 2 ("tools/list from user's active installed plugins") needs a
|
||||
resolved userId -> tenantId -> InstalledPlugin path. Stale research's `findMany({ where: { userId } })`
|
||||
will NOT compile. Decide enumeration strategy (likely tenantId null in local edition = single-tenant)
|
||||
before planning Wave 2.
|
||||
|
||||
- **19b (WebSocket push transport):** DEFERRED out of milestone. server.ts + WS + Docker entrypoint + Nginx
|
||||
+ pub/sub subscriber. Covers CTRL-01/02/03/06. Basis = original 19-01..19-05 plans. Not executed unless
|
||||
user later requests. The risky boot-path change is parked here.
|
||||
|
||||
**Phase 21:** COMPLETE (2026-05-30). All 5 waves done. PR #215 open on feat/mcp-support. Re-planned as v3 frontend-relay (21-REPLAN.md). Delivered: McpToolDeclaration SDK type, mcpTools/mcpCapabilities manifest fields, executeMcpTool hook, per-session Redis catalog, catalog POST route, useMcpCatalogPublisher, composePluginToolsList, mcpRelay (enqueue/wait/post/drain), /api/mcp/invocations GET, /api/mcp/results POST, useMcpRelayBridge, namespaced-tool dispatch in route.ts, README MCP config block. Version 2.29.x committed.
|
||||
|
||||
**Phase 19b:** COMPLETE (2026-05-30, commit 7fd1d7e, version 2.30.0). SSE push transport replacing the 1500ms poll loop. Delivered: GET /api/globe/commands/stream (ReadableStream, 200ms drain, 15s keepalive, 16s max, dual-auth, isDemo 403, globeCommandsStreamLimiter 10/60s, cancel() disconnect cleanup), useGlobeCommandBridge rewritten to EventSource with envelope validation and onerror handler. Poll route kept. 654/654 tests GREEN. tsc + lint clean.
|
||||
|
||||
- **21-03 (Wave 2, catalog + tools/list):** COMPLETE (2026-05-30, commits 6779921 + cbd48e5 + 23b893c). publishSessionCatalog/readSessionCatalog (Redis SET+EX, {userId}:{sessionId} key, 120s TTL), POST /api/mcp/catalog (dual-auth, UUID guard, size cap, isDemo gate), useMcpCatalogPublisher hook (reads pluginManager manifests, POSTs on mount + 30s interval), composePluginToolsList (system tools + de-duplicated namespaced plugin tools + capability copy), registerPluginTools in route.ts (reads per-session catalog, registers stub handlers). CAT-01..06 + LIST-01..05 GREEN. Zod v4 z.record() fix applied.
|
||||
|
||||
- **21-02 (Wave 1, SDK):** COMPLETE (2026-05-30, commit bda235f). McpToolDeclaration (NO execution field), mcpTools? + mcpCapabilities? in PluginManifest, WorldPlugin.executeMcpTool? hook, validateManifest extended with MAN-01..08 rules, getNamespacedTools + validateToolArgs in src/lib/mcp/pluginTools.ts. 32/32 targeted tests GREEN. Pre-existing Wave 0 RED tests for future waves remain red (correct).
|
||||
|
||||
- **21-01 (Wave 0, RED):** COMPLETE (2026-05-30, commit 5930bc7). Six RED test files authored:
|
||||
validateManifest.test.ts (extended + MAN-01..08), pluginTools.test.ts (PT-01..08),
|
||||
mcpSessionCatalog.test.ts (CAT-01..06), pluginToolsList.test.ts (LIST-01..05),
|
||||
mcpRelay.test.ts (RELAY-01 + SEC-01..05), pluginToolDispatch.test.ts (MCP-QA-01..04 + SEC-01/06).
|
||||
tsc: only TS2307 "module not found" (expected). lint: zero errors on new files. vitest: 5 files FAIL
|
||||
"Failed to resolve import" (correct RED), validateManifest.test.ts 7 RED + 9 GREEN.
|
||||
|
||||
**Execution order (per RECONCILIATION R-7):** 17 done -> 18 done -> 20 done -> 19 (PAUSED, awaiting
|
||||
user discussion on WebSocket + custom server.ts) -> 21 (re-plan pause). route.ts serialization:
|
||||
18-04 first, then 20-04 appended. Commit checkpoint: a5b4b62 (Phases 18 + 20 combined).
|
||||
|
||||
## Phase 17 Plan Map (planned 2026-05-29)
|
||||
|
||||
- **17-01 (Wave 0, autonomous):** RED test scaffolds for /api/mcp (401 JSON-RPC, 403 demo gate,
|
||||
stateless per-request construction, X-Accel-Buffering header) + a raw-SDK transport runtime spike
|
||||
that proves WebStandardStreamableHTTPServerTransport + McpServer instantiate/connect outside a
|
||||
custom server (or flags a blocker). Covers MCP-01..04.
|
||||
|
||||
- **17-02 (Wave 1, autonomous + blocking-human SDK-legitimacy checkpoint):** `pnpm add
|
||||
@modelcontextprotocol/sdk@^1.29.0`, `src/lib/mcp/server.ts` createMcpServer() factory (empty
|
||||
capabilities), and the gated stateless `src/app/api/mcp/route.ts` (isDemo-first 403, Bearer 401
|
||||
via Phase 16 authenticateApiKey, fresh server+transport per request, X-Accel-Buffering: no). Turns
|
||||
Wave 0 green. Covers MCP-01..04.
|
||||
|
||||
- **17-03 (Wave 2, autonomous + human-verify checkpoint):** `ConnectAgentHelper.tsx` (per-edition
|
||||
URL + mcpServers JSON with Bearer header for Desktop/Cursor/VS Code + Manual block + agent prompt;
|
||||
Claude Code CLI deferred as "coming soon"), mounted where the Phase 16 TODO placeholder was;
|
||||
`.agents/context/server-management.md` Coolify/Nginx streaming runbook (documented, not automated);
|
||||
semver bump 2.25.0 -> 2.26.0. Covers CONNECT-01/02/03.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
- **17 transport decision (LOCKED, BATCH-DECISIONS-17-21.md + 17-CONTEXT.md):** raw
|
||||
`@modelcontextprotocol/sdk@^1.29.0` (NOT mcp-handler) + the SDK's
|
||||
`WebStandardStreamableHTTPServerTransport` (`@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js`)
|
||||
inside a Next 16 App Router route handler at `src/app/api/mcp/route.ts`. **Confirmed against the
|
||||
published SDK 1.29.0 types**: `handleRequest(req: Request): Promise<Response>` is Web-Standard and
|
||||
documented for Hono/Cloudflare-Workers fetch handlers — identical Request/Response shape to a Next 16
|
||||
route handler. NO custom `server.ts` is needed in Phase 17 (that is a Phase 19 / WebSocket artifact).
|
||||
NO BLOCKER. A Wave 0 spike re-confirms at runtime and escalates only if the transport genuinely
|
||||
cannot run in a route handler.
|
||||
|
||||
- **17 stateless (D-17-04):** fresh McpServer + transport per request (sessionIdGenerator: undefined),
|
||||
never cached at module scope, with a guard-rail comment. No tools/resources registered this phase.
|
||||
|
||||
- **17 auth (D-17-03):** reuse Phase 16 `authenticateApiKey()` unchanged; 401 JSON-RPC body
|
||||
`{ jsonrpc:"2.0", error:{ code:-32600, message:"Unauthorized" }, id:null }`. Demo -> 403, gate FIRST.
|
||||
|
||||
- **17 connect helper (D-17-08/09):** in "API & MCP Access"; mcpServers JSON carries the token in the
|
||||
Authorization HEADER (raw-SDK Streamable HTTP form), never in a URL; Claude Code CLI deferred "coming
|
||||
soon". Nginx/Coolify buffering documented (D-17-07), not automated.
|
||||
|
||||
- **17-03 (Wave 2):** mcpServers JSON shape uses `{ "url": "...", "headers": { "Authorization": "Bearer
|
||||
<token>" } }` -- raw-SDK Streamable HTTP form (D-17-09). Local URL derived from window.location.origin
|
||||
at runtime (not hardcoded :3000). CopyField sub-component pattern established for clipboard interactions.
|
||||
.agents/context/ is gitignored in both worktree and main repo; server-management.md exists on disk as
|
||||
a local operator runbook only (D-17-07 intent: document not automate).
|
||||
|
||||
- **17-02 (Wave 1):** vitest.config.ts clearMocks: true required to fix mock call count isolation
|
||||
between describe blocks (MCP-04 demo-gate tests inherited stale call counts from MCP-03 without this).
|
||||
Optional chaining on server?.connect?.() and transport.handleRequest?.() guards against vi.resetAllMocks()
|
||||
clearing SDK mock implementations in happy-path tests. AuthInfo.token = "" (raw token not re-exposed).
|
||||
createMcpServer() capabilities: { tools: { listChanged: true } } per RECONCILIATION R-1.
|
||||
|
||||
- **17-01 (Wave 0):** @vite-ignore on variable-based import specifier required in transport spike to
|
||||
prevent Vite's import-analysis from crashing at transform time on absent SDK. Runtime try/catch alone
|
||||
is insufficient because Vite resolves import() specifiers statically before test execution.
|
||||
SDK vi.mock factories (no real module) work correctly for route.test.ts stateless-construction tests.
|
||||
|
||||
- **16-01 (Wave 0):** Three RED test files lock api-key contracts (token format, timing oracle T-16-01,
|
||||
max-3, ownership-scoped delete) before any implementation. timing-oracle test tagged `// [slow]`.
|
||||
|
||||
- **16-02 (Wave 1):** UserApiKey Prisma model + apiKeyAuth.ts helper. DUMMY_HASH pre-baked literal
|
||||
eliminates cold-start timing oracle gap; async bcrypt compare always runs on miss (T-16-01). All
|
||||
helper tests GREEN.
|
||||
|
||||
- **16-03 (Wave 2):** isDemo gate runs FIRST (before auth()). deleteMany ownership-scoped delete
|
||||
eliminates TOCTOU (T-16-06). fullToken returned once in POST 201; GET omits hashedSecret (T-16-07).
|
||||
|
||||
- **16-04 (Wave 3):** PersonalApiKeysSection UI shipped in the renamed "Keys & Access" modal; version
|
||||
bumped to 2.25.0; Phase 17 connect-helper placeholder comment left at ~L347.
|
||||
|
||||
- v1.2 QA requirement IDs renamed `QA-01/02/03` -> `MCP-QA-01/02/03` to resolve a v1.1 collision.
|
||||
- One primary worktree for the whole milestone; data-engine / SDK / marketplace are declared cross-repo
|
||||
dependencies, not separate planning roots.
|
||||
|
||||
- **Scope expansion (2026-05-29, user-approved):** keys are generic transport-agnostic API keys (req
|
||||
API-01); one reusable `authenticateApiKey()` middleware; capabilities as a shared service layer
|
||||
wrapped by MCP + future REST (`/api/v1/*`, Phases 20/21). CLI deferred to a future milestone.
|
||||
|
||||
## Milestone Audit (2026-05-30)
|
||||
|
||||
v1.2 audited: status **tech_debt** (no critical blockers). Report: `.planning/v1.2-MILESTONE-AUDIT.md`.
|
||||
Requirements: 31 Complete, 2 Partial (CTRL-02 entityId-only focus, MCP-QA-03 reconnect test),
|
||||
2 Deferred (PLG-01/PLG-02 -- marketplace descoped to v1.3 per 21-REPLAN). Integration: 47/52,
|
||||
all 4 browser hooks mounted, 9/12 E2E flows complete (2 broken = the deferred PLG tools).
|
||||
|
||||
**Tech debt closed (commit dc1e802, version 2.30.1, pushed):** mcpRelay enqueue+postResult made
|
||||
atomic (multi/exec) + redis.ts RedisMultiChain.set(); v1 entity routes got dual-auth + isDemo 403
|
||||
gate + NaN limit guard + global-read intent comment; useGlobeStateSync immediate initial push
|
||||
(ran-once ref) closes the session-registration race; useMcpCatalogPublisher wired to
|
||||
getNamespacedTools (DRY); deleted dead pluginToolsList.ts. Code + security review: no Critical/High;
|
||||
all review warnings folded in. 643/643 tests, tsc clean, lint clean.
|
||||
|
||||
REQUIREMENTS.md traceability table + checkboxes updated to actual status. ROADMAP.md has a
|
||||
"Deferred to v1.3 (Backlog)" section for PLG-01/02 (999.1/999.2).
|
||||
|
||||
**Gap-closure 18-05 (2026-05-30, commit ee16ec0):** POST /api/globe/state isDemo gate added.
|
||||
Returns 403 { error: "Not available in demo edition" } before auth when isDemo is true. Closes
|
||||
GAP-01 from PR #215 pre-merge audit. vi.hoisted() pattern used for mutable editionMock (deviation
|
||||
from plan's simpler const suggestion -- Vitest hoisting requires it). 6/6 tests green, tsc clean.
|
||||
useGlobeStateSync confirmed to handle 403 silently with no code change (fetch catches only thrown
|
||||
exceptions, not HTTP responses). RSRC-01 fully satisfied.
|
||||
|
||||
## Remaining for milestone close
|
||||
|
||||
1. Merge PR #215 (feat/mcp-support -> main) once CI is green.
|
||||
2. After merge: run milestone lifecycle (`/gsd:autonomous` no --only, or
|
||||
`/gsd:complete-milestone v1.2` then `/gsd:cleanup`) to archive + tag + clean up the worktree.
|
||||
|
||||
## Blockers
|
||||
|
||||
None. (Phase 17 transport-in-route-handler question resolved: confirmed viable, no custom server.ts.)
|
||||
@@ -1,94 +0,0 @@
|
||||
---
|
||||
phase: 16-api-key-auth-foundation
|
||||
plan: "03"
|
||||
subsystem: api-key-auth
|
||||
tags: [api-keys, crud-routes, auth, ownership-scoping, reveal-once]
|
||||
dependency_graph:
|
||||
requires: ["16-01", "16-02"]
|
||||
provides: ["16-04"]
|
||||
affects: []
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns:
|
||||
- "isDemo gate before session check on all handlers"
|
||||
- "deleteMany for atomic ownership-scoped hard delete (BOLA prevention)"
|
||||
- "P2002 prefix-collision retry on create"
|
||||
- "reveal-once fullToken in 201 body only"
|
||||
key_files:
|
||||
created:
|
||||
- src/app/api/api-keys/route.ts
|
||||
- src/app/api/api-keys/[id]/route.ts
|
||||
modified: []
|
||||
decisions:
|
||||
- "userId always taken from session.user.id, never from request body (T-16-09)"
|
||||
- "isDemo gate runs FIRST before auth() in all three handlers (Pitfall 6 - demo has no DB row)"
|
||||
- "createKeyWithRetry helper isolates P2002 catch so outer handler catch-all remains clean"
|
||||
- "deleteMany (not delete) used to avoid Prisma NotFound throw on foreign key - returns count 0 instead (TOCTOU elimination)"
|
||||
metrics:
|
||||
duration: "~12 minutes"
|
||||
completed_date: "2026-05-29"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
files_created: 2
|
||||
files_modified: 0
|
||||
---
|
||||
|
||||
# Phase 16 Plan 03: API Key CRUD Route Handlers Summary
|
||||
|
||||
## One-liner
|
||||
|
||||
GET/POST/DELETE route handlers for `/api/api-keys` with ownership-scoped revoke, max-3 enforcement, and reveal-once fullToken in the 201 response.
|
||||
|
||||
## What Was Built
|
||||
|
||||
Three HTTP handlers completing the Wave 2 server surface:
|
||||
|
||||
**`src/app/api/api-keys/route.ts`** (GET + POST)
|
||||
- GET: lists the session user's keys selecting only `{ id, name, prefix, createdAt, lastUsedAt }` - `hashedSecret` never included in response
|
||||
- POST: enforces max-3 (422 `max_keys_reached`), calls `generateApiKey()`, creates the row via Prisma, handles P2002 prefix collision with a single retry, returns 201 `{ key: { id, name, createdAt, fullToken } }` - fullToken returned exactly once here, never again
|
||||
|
||||
**`src/app/api/api-keys/[id]/route.ts`** (DELETE)
|
||||
- `deleteMany({ where: { id, userId } })` - atomic ownership scoping; a foreign or missing key yields `count 0` -> 404, never a 500 or accidental deletion of another user's key
|
||||
|
||||
Both files apply the isDemo gate (403) before `auth()` on every handler, per Pitfall 6 (the demo virtual admin has no DB row).
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Implement GET + POST route.ts | 476befe | src/app/api/api-keys/route.ts |
|
||||
| 2 | Implement DELETE [id]/route.ts | 4e6ff07 | src/app/api/api-keys/[id]/route.ts |
|
||||
|
||||
## Test Results
|
||||
|
||||
- `pnpm test -- --run src/app/api/api-keys/route.test.ts`: 6/6 GREEN
|
||||
- `pnpm test -- --run "src/app/api/api-keys/[id]/route.test.ts"`: 4/4 GREEN
|
||||
- Full suite `pnpm test -- --run`: 403/403 GREEN (56 test files, no regressions)
|
||||
|
||||
## Security Invariants Verified
|
||||
|
||||
| Threat ID | Disposition | Verification |
|
||||
|-----------|-------------|--------------|
|
||||
| T-16-06 (BOLA - foreign key delete) | mitigated | deleteMany where clause tested in [id]/route.test.ts "ownership enforcement" test |
|
||||
| T-16-07 (hashedSecret/fullToken in list) | mitigated | "response never contains hashedSecret field" test asserts this; GET select projection omits it |
|
||||
| T-16-08 (demo gate) | mitigated | isDemo check is first line of all three handlers |
|
||||
| T-16-09 (userId from body) | mitigated | userId always `session.user.id`, never read from request body |
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None - no new network surface beyond the planned routes.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- `src/app/api/api-keys/route.ts` exists: FOUND
|
||||
- `src/app/api/api-keys/[id]/route.ts` exists: FOUND
|
||||
- Commit 476befe exists: FOUND
|
||||
- Commit 4e6ff07 exists: FOUND
|
||||
@@ -1,99 +0,0 @@
|
||||
---
|
||||
phase: 18-globe-state-sync
|
||||
plan: "05"
|
||||
subsystem: api-route-security
|
||||
tags: [security, demo-gate, gap-closure, rsrc-01]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [isDemo-gate-on-globe-state-post]
|
||||
affects: [src/app/api/globe/state/route.ts, src/app/api/globe/state/route.test.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [vi.hoisted-mutable-mock, isDemo-gate-before-auth]
|
||||
key_files:
|
||||
created: []
|
||||
modified:
|
||||
- src/app/api/globe/state/route.ts
|
||||
- src/app/api/globe/state/route.test.ts
|
||||
decisions:
|
||||
- "vi.hoisted() required for editionMock because vi.mock factories are hoisted above const declarations"
|
||||
- "isDemo gate placed after rate limiter and before userId resolution (matching canonical api-keys pattern)"
|
||||
- "useGlobeStateSync requires no code change: fetch only catches thrown exceptions, not HTTP 4xx responses"
|
||||
metrics:
|
||||
duration: "8 minutes"
|
||||
completed: "2026-05-30"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
---
|
||||
|
||||
# Phase 18 Plan 05: isDemo Gate for POST /api/globe/state Summary
|
||||
|
||||
**One-liner:** Added isDemo edition gate (403 before auth) to POST /api/globe/state, closing GAP-01 identified in the PR #215 pre-merge audit.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Add isDemo gate + test | ee16ec0 | route.ts, route.test.ts |
|
||||
| 2 | Verify useGlobeStateSync handles 403 gracefully | (no commit - read-only verification) | useGlobeStateSync.ts |
|
||||
|
||||
## What Was Built
|
||||
|
||||
**GAP-01 closed:** `POST /api/globe/state` previously had no demo-edition gate, allowing demo users to write globe state to Redis. The fix:
|
||||
|
||||
1. `route.ts`: Added `import { isDemo } from "@/core/edition"` and an early-return guard immediately after the rate limiter check and before the `userId` resolution block. Returns `{ error: "Not available in demo edition" }` with HTTP 403.
|
||||
|
||||
2. `route.test.ts`: Added `editionMock` via `vi.hoisted()` (required because `vi.mock` factories are hoisted above normal `const` declarations), a `vi.mock("@/core/edition", () => editionMock)` call, reset `editionMock.isDemo = false` in the existing `beforeEach`, and a new describe block "POST /api/globe/state -- demo edition gate" with one test asserting 403 + correct body + `writeGlobeState` not called.
|
||||
|
||||
**Task 2 - verification only:** `useGlobeStateSync.pushState` wraps `fetch` in a `try/catch` that only catches thrown exceptions (network errors). HTTP 403 responses are awaited and silently discarded because the hook never inspects `response.ok` or `response.status`. No code change was required.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
### Auto-fixed Issues
|
||||
|
||||
**1. [Rule 1 - Bug] vi.hoisted() required for editionMock**
|
||||
- **Found during:** Task 1 (test run)
|
||||
- **Issue:** The plan suggested `const editionMock = { isDemo: false }` declared at module scope, but Vitest hoists `vi.mock` calls above all `const` declarations. The mock factory referenced `editionMock` before it was initialized, causing `ReferenceError: Cannot access 'editionMock' before initialization`.
|
||||
- **Fix:** Wrapped the declaration in `vi.hoisted()`: `const editionMock = vi.hoisted(() => ({ isDemo: false }))`. This runs the factory function before hoisting resolves, making the variable available to the `vi.mock` factory.
|
||||
- **Files modified:** `src/app/api/globe/state/route.test.ts`
|
||||
- **Commit:** ee16ec0
|
||||
|
||||
## Test Results
|
||||
|
||||
All 6 tests passed (5 pre-existing + 1 new):
|
||||
|
||||
```
|
||||
POST /api/globe/state (RSRC-01)
|
||||
- returns 200 and calls writeGlobeState with valid auth + body
|
||||
- returns 401 and does NOT call writeGlobeState when auth returns null
|
||||
- returns 400 and does NOT call writeGlobeState when sessionId is missing
|
||||
- returns 400 when snapshot is missing from body
|
||||
- still yields 200 when writeGlobeState rejects (fire-and-forget contract)
|
||||
POST /api/globe/state -- demo edition gate
|
||||
- returns 403 and does NOT call writeGlobeState when isDemo is true
|
||||
```
|
||||
|
||||
TypeScript strict mode: zero errors (`pnpm tsc --noEmit`).
|
||||
|
||||
## Threat Model Coverage
|
||||
|
||||
| Threat ID | Mitigation | Status |
|
||||
|-----------|-----------|--------|
|
||||
| T-18-05-01 | isDemo gate before auth prevents demo users writing state even with a valid session | MITIGATED |
|
||||
| T-18-05-02 | 403 returned before writeGlobeState is called; no Redis write occurs on demo edition | MITIGATED |
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None - this plan closes a security gap rather than introducing new surface.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- [x] `src/app/api/globe/state/route.ts` modified - `isDemo` import and guard present
|
||||
- [x] `src/app/api/globe/state/route.test.ts` modified - new describe block present
|
||||
- [x] Commit ee16ec0 exists in git log
|
||||
- [x] 6/6 tests green
|
||||
- [x] tsc --noEmit: zero errors
|
||||
@@ -148,38 +148,6 @@ WorldWideView is distributed across several specialized repositories:
|
||||
5. **`worldwideview-web`**: Marketing and landing site.
|
||||
6. **[`szski/wwv-mcp`](https://github.com/szski/wwv-mcp)**: Reference MCP server for driving the globe from an LLM agent (Claude Code, Claude Desktop, Cursor, Cline, …) via the [Agent Bus](docs/agent-bus.md). Contributor-hosted today; may move under the project org.
|
||||
|
||||
## MCP (Model Context Protocol)
|
||||
|
||||
WorldWideView exposes a built-in MCP endpoint at `/api/mcp`. Any MCP-compatible client (Claude Desktop, Claude Code, Cursor, Cline, etc.) can connect to it directly without a separate sidecar server.
|
||||
|
||||
### Authentication
|
||||
|
||||
Generate an API key from the `/setup` page (Settings > API Keys). Pass it as a Bearer token in every request.
|
||||
|
||||
### Client config
|
||||
|
||||
Add the following block to your MCP client configuration. Replace `https://your-host` with the actual origin where WorldWideView is running (e.g. `http://localhost:3000` for local development).
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"worldwideview": {
|
||||
"type": "http",
|
||||
"url": "https://your-host/api/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer <your-api-key>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin tools and tools/list
|
||||
|
||||
Plugin tools (tools contributed by loaded plugins) appear in `tools/list` only after the browser tab that is running WorldWideView has loaded the relevant plugin and published its catalog. The server snapshots the catalog at the moment each request arrives.
|
||||
|
||||
Because the server is stateless and per-request, it cannot push `list_changed` notifications proactively. If you load a new plugin in the browser after your MCP client has already called `tools/list`, call `tools/list` again to pick up the new tools.
|
||||
|
||||
## Development & Workflow
|
||||
|
||||
- **Branching & Commits:** We strictly enforce [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `refactor:`). Every commit should utilize our semantic versioning `[/commit]` workflow.
|
||||
|
||||
@@ -9,7 +9,6 @@ const config = [
|
||||
"out/**",
|
||||
"src/generated/**",
|
||||
"public/cesium/**",
|
||||
"public/plugins-local/**",
|
||||
"packages/*/dist/**",
|
||||
".worktrees/**",
|
||||
"local-scripts/**",
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.31.1",
|
||||
"version": "2.24.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -28,7 +28,6 @@
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.2",
|
||||
"@auth/supabase-adapter": "^1.11.2",
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@prisma/client-runtime-utils": "7.8.0",
|
||||
@@ -42,7 +41,6 @@
|
||||
"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",
|
||||
@@ -122,3 +120,4 @@
|
||||
"pnpm": ">=9.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,38 +52,6 @@ export class MyPlugin implements WorldPlugin {
|
||||
}
|
||||
```
|
||||
|
||||
## Property Tag Helpers
|
||||
|
||||
Wrap entity property values with these helpers so the WorldWideView Intel panel renders them as rich UI elements instead of plain text.
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
```
|
||||
|
||||
| Helper | Wraps | Panel renders as |
|
||||
|---|---|---|
|
||||
| `dtProp(iso: string \| null)` | ISO 8601 date string | Expandable datetime row — local time collapsed, UTC + relative time expanded |
|
||||
| `urlProp(href: string \| null)` | Any URL | Clickable link with external-link icon |
|
||||
| `imageProp(src: string \| null)` | Image URL | Inline thumbnail |
|
||||
| `videoProp(href: string \| null)` | Video/stream URL | "Watch" link with play icon |
|
||||
|
||||
All helpers are **null-safe**: passing `null`, `undefined`, or `""` returns `null`, which the panel skips cleanly.
|
||||
|
||||
```ts
|
||||
// In your entity mapper:
|
||||
properties: {
|
||||
last_seen: dtProp(item.timestamp ?? null),
|
||||
source_url: urlProp(item.url ?? null),
|
||||
preview: imageProp(item.image_url ?? null),
|
||||
live_stream: videoProp(item.stream ?? null),
|
||||
// Plain values need no wrapper
|
||||
name: item.name,
|
||||
severity: item.severity,
|
||||
}
|
||||
```
|
||||
|
||||
Values without a tag prefix fall back to plain-text rendering, so existing plugins continue to work unchanged.
|
||||
|
||||
## Changelog
|
||||
|
||||
- **v1.0.3** — Added README with core interfaces and usage docs.
|
||||
|
||||
@@ -66,7 +66,7 @@ export function createSvgIconUrl(
|
||||
}
|
||||
|
||||
// ─── Re-export manifest types ─────────────────────────────────
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration } from "./manifest";
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
|
||||
|
||||
// ─── Categories ──────────────────────────────────────────────
|
||||
export type PluginCategory =
|
||||
@@ -286,17 +286,6 @@ export interface WorldPlugin {
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
/**
|
||||
* Execute an MCP tool in the browser on behalf of the server relay.
|
||||
* The server dispatches the invocation here; the plugin runs the logic
|
||||
* and returns the result. The server NEVER executes plugin tools directly
|
||||
* (v3 frontend-relay design).
|
||||
*
|
||||
* @param toolName - The bare tool name (not namespaced).
|
||||
* @param args - Validated arguments from the MCP client.
|
||||
* @returns Arbitrary result serializable to JSON.
|
||||
*/
|
||||
executeMcpTool?(toolName: string, args: Record<string, unknown>): Promise<unknown>;
|
||||
}
|
||||
|
||||
// ─── Aliases for backwards compatibility ─────────────────────
|
||||
@@ -324,45 +313,3 @@ export * from "./viteGlobals";
|
||||
|
||||
// ─── Auth Contracts ──────────────────────────────────────────
|
||||
export * from "./auth-contracts";
|
||||
|
||||
// ─── Tagged Property Helpers ─────────────────────────────────
|
||||
/**
|
||||
* Wraps an ISO 8601 date string for rich rendering in the Intel panel.
|
||||
* The panel displays local time (collapsed) and UTC + relative time (expanded).
|
||||
* @param iso - ISO 8601 string (e.g. "2026-06-01T05:00:00Z"), or null/undefined
|
||||
* @returns Tagged string `"datetime:{iso}"`, or `null` if input is empty
|
||||
*/
|
||||
export function dtProp(iso: string | undefined | null): string | null {
|
||||
if (!iso) return null;
|
||||
return `datetime:${iso}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a URL for rich rendering in the Intel panel as a clickable external link.
|
||||
* @param href - Any URL string, or null/undefined
|
||||
* @returns Tagged string `"url:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export function urlProp(href: string | undefined | null): string | null {
|
||||
if (!href) return null;
|
||||
return `url:${href}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an image URL for rich rendering in the Intel panel as an inline thumbnail.
|
||||
* @param src - Image URL string, or null/undefined
|
||||
* @returns Tagged string `"image:{src}"`, or `null` if input is empty
|
||||
*/
|
||||
export function imageProp(src: string | undefined | null): string | null {
|
||||
if (!src) return null;
|
||||
return `image:${src}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a video or stream URL for rich rendering in the Intel panel as a "Watch" link.
|
||||
* @param href - Video or stream URL string, or null/undefined
|
||||
* @returns Tagged string `"video:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export function videoProp(href: string | undefined | null): string | null {
|
||||
if (!href) return null;
|
||||
return `video:${href}`;
|
||||
}
|
||||
@@ -63,32 +63,6 @@ export interface RenderingConfig {
|
||||
maxEntities?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface McpToolDeclaration
|
||||
* @description A single MCP tool declared by a plugin.
|
||||
* The server uses this declaration to compose tools/list and dispatch
|
||||
* invocations to the browser. The server NEVER executes plugin tools
|
||||
* directly (v3 frontend-relay design).
|
||||
*
|
||||
* INVARIANT: No `execution` field. The browser (WorldPlugin.executeMcpTool)
|
||||
* is the sole execution site.
|
||||
*/
|
||||
export interface McpToolDeclaration {
|
||||
/** Safe identifier. Only [a-zA-Z0-9_-] characters are allowed. */
|
||||
name: string;
|
||||
/** Human-readable description for MCP clients. */
|
||||
description: string;
|
||||
/**
|
||||
* Minimal JSON-schema-like object describing the tool arguments.
|
||||
* Supports: type, properties, required, enum (per validateToolArgs).
|
||||
*/
|
||||
inputSchema: {
|
||||
type: "object";
|
||||
properties?: Record<string, { type: string; enum?: string[] }>;
|
||||
required?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
@@ -113,16 +87,4 @@ export interface PluginManifest {
|
||||
entry?: string;
|
||||
assets?: string[];
|
||||
extends?: string[];
|
||||
/**
|
||||
* MCP tools this plugin declares (v3 frontend-relay design).
|
||||
* The server reads these to compose tools/list and dispatch invocations
|
||||
* to the browser. Execution always happens in the browser via
|
||||
* WorldPlugin.executeMcpTool.
|
||||
*/
|
||||
mcpTools?: McpToolDeclaration[];
|
||||
/**
|
||||
* Opaque capability tags for MCP clients (e.g. "point-layer", "camera-control").
|
||||
* Must be a string array when present.
|
||||
*/
|
||||
mcpCapabilities?: string[];
|
||||
}
|
||||
Generated
+3
-1584
File diff suppressed because it is too large.
Load diff
@@ -17,7 +17,6 @@ model User {
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
apiKeys UserApiKey[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@map("users")
|
||||
@@ -103,17 +102,3 @@ model MarketplaceCredential {
|
||||
@@unique([tenantId])
|
||||
@@map("marketplace_credentials")
|
||||
}
|
||||
|
||||
model UserApiKey {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
tenantId String?
|
||||
prefix String @unique
|
||||
hashedSecret String
|
||||
name String
|
||||
createdAt DateTime @default(now())
|
||||
lastUsedAt DateTime?
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("user_api_keys")
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { DELETE } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
// NextAuth v5 `auth` is overloaded (middleware wrapper + no-arg session getter).
|
||||
// Narrow to the session-getter signature so vi.mocked resolves the correct overload.
|
||||
const mockAuth = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DELETE /api/api-keys/[id] — KEY-03 (revoke)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("DELETE /api/api-keys/[id]", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 200 { success: true } when user owns the key (KEY-03)", async () => {
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 1 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toEqual({ success: true });
|
||||
});
|
||||
|
||||
it("returns 404 { error: 'not_found' } when key belongs to another user (KEY-03)", async () => {
|
||||
// deleteMany returns count: 0 when ownership check fails
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 0 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/foreign-key-id");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "foreign-key-id" }) });
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(body.error).toBe("not_found");
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("deleteMany is called with where clause containing both id and userId (ownership enforcement)", async () => {
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 1 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
|
||||
expect(vi.mocked(prisma.userApiKey.deleteMany)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: "key-id-1",
|
||||
userId: "user-123",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { apiKeyManagementLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DELETE /api/api-keys/[id] — KEY-03 (ownership-scoped revoke, hard delete)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Atomic ownership-scoped delete — T-16-06 (BOLA prevention).
|
||||
// Using deleteMany (not delete) so a non-matching id returns count 0
|
||||
// instead of throwing a NotFound error, eliminating TOCTOU.
|
||||
const deleted = await prisma.userApiKey.deleteMany({
|
||||
where: { id, userId: session.user.id },
|
||||
});
|
||||
|
||||
if (deleted.count === 0) {
|
||||
return NextResponse.json({ error: "not_found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error("[api-keys] DELETE error:", err);
|
||||
return NextResponse.json({ error: "Failed to revoke API key" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { GET, POST } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generateApiKey } from "@/lib/apiKeyAuth";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
// $transaction executes the callback inline so tests don't need a real DB
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
generateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting in all route tests — the limiter module has its own tests
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
apiKeyManagementLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
mcpLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// NextAuth v5 `auth` is overloaded (middleware wrapper + no-arg session getter).
|
||||
// Narrow to the session-getter signature so vi.mocked resolves the correct overload.
|
||||
const mockAuth = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
|
||||
// Helper: make $transaction execute its callback synchronously with the mock prisma.
|
||||
// Must be called in beforeEach after vi.resetAllMocks() clears the module-level mock.
|
||||
// Cast to never to bypass Prisma's complex overloaded $transaction signature.
|
||||
function wireTransaction(): void {
|
||||
vi.mocked(prisma.$transaction).mockImplementation(
|
||||
((fn: (tx: typeof prisma) => unknown) => fn(prisma)) as never,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /api/api-keys — KEY-03 (list)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/api-keys", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
wireTransaction();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 200 with { keys } for authenticated user (KEY-03)", async () => {
|
||||
const mockKeys = [
|
||||
{ id: "key-1", name: "My Key", prefix: "wwv_ABCDEFGH", createdAt: new Date(), lastUsedAt: null },
|
||||
];
|
||||
vi.mocked(prisma.userApiKey.findMany).mockResolvedValue(mockKeys as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("keys");
|
||||
expect(Array.isArray(body.keys)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toHaveProperty("error");
|
||||
// Must NOT include a `keys` field — callers that do `data.keys ?? []` without
|
||||
// checking r.ok would silently show an empty list instead of an auth error.
|
||||
expect(body).not.toHaveProperty("keys");
|
||||
});
|
||||
|
||||
it("response never contains hashedSecret field (security invariant)", async () => {
|
||||
const mockKeys = [
|
||||
{
|
||||
id: "key-1",
|
||||
name: "My Key",
|
||||
prefix: "wwv_ABCDEFGH",
|
||||
createdAt: new Date(),
|
||||
lastUsedAt: null,
|
||||
// hashedSecret deliberately absent from select projection
|
||||
},
|
||||
];
|
||||
vi.mocked(prisma.userApiKey.findMany).mockResolvedValue(mockKeys as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// The route must use a select projection — no hashedSecret in response
|
||||
if (Array.isArray(body.keys)) {
|
||||
body.keys.forEach((k: Record<string, unknown>) => {
|
||||
expect(k).not.toHaveProperty("hashedSecret");
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/api-keys — KEY-01, KEY-02, KEY-04 (create)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/api-keys", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
wireTransaction();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 422 with error 'max_keys_reached' when user already has 3 keys (KEY-04)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(3 as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Fourth Key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(body.error).toBe("max_keys_reached");
|
||||
});
|
||||
|
||||
it("calls generateApiKey and returns 201 with fullToken when under limit (KEY-01, KEY-04)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX1",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "a".repeat(64),
|
||||
fullToken: "wwv_TESTPFX1.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockResolvedValue({
|
||||
id: "new-key-id",
|
||||
name: "My API Key",
|
||||
createdAt: new Date("2026-01-01"),
|
||||
} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "My API Key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(body.key).toHaveProperty("fullToken");
|
||||
expect(body.key.fullToken).toBe("wwv_TESTPFX1.testsecret_43chars_base64url_value_here123");
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 422 with error 'name_too_long' when name exceeds 64 chars (M2)", async () => {
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "a".repeat(65) }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(body.error).toBe("name_too_long");
|
||||
});
|
||||
|
||||
it("accepts name exactly at the 64-char boundary (M2)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX2",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "b".repeat(64),
|
||||
fullToken: "wwv_TESTPFX2.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockResolvedValue({
|
||||
id: "new-key-id-2",
|
||||
name: "a".repeat(64),
|
||||
createdAt: new Date("2026-01-01"),
|
||||
} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "a".repeat(64) }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(201);
|
||||
});
|
||||
|
||||
it("returns 401 with session_user_not_found when prisma throws P2003 on user_api_keys_userId_fkey", async () => {
|
||||
// Simulates a stale JWT whose user id has no row in `users` (e.g. after a DB reset).
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
const fkError = Object.assign(new Error("Foreign key constraint failed"), {
|
||||
code: "P2003",
|
||||
meta: { field_name: "user_api_keys_userId_fkey" },
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockRejectedValue(fkError);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX3",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "c".repeat(64),
|
||||
fullToken: "wwv_TESTPFX3.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Stale key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body.error).toBe("session_user_not_found");
|
||||
});
|
||||
|
||||
it("returns 500 when prisma throws P2003 on a different FK constraint", async () => {
|
||||
// P2003 on a different constraint must NOT be mistaken for the user-not-found case.
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
const otherFkError = Object.assign(new Error("Foreign key constraint failed"), {
|
||||
code: "P2003",
|
||||
meta: { field_name: "some_other_fkey" },
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockRejectedValue(otherFkError);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX4",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "d".repeat(64),
|
||||
fullToken: "wwv_TESTPFX4.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Other error" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body.error).not.toBe("session_user_not_found");
|
||||
});
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { generateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { apiKeyManagementLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
|
||||
const MAX_KEYS = 3;
|
||||
const MAX_NAME_LENGTH = 64;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /api/api-keys — KEY-03 (list user's keys, secrets never returned)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await prisma.userApiKey.findMany({
|
||||
where: { userId: session.user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
prefix: true,
|
||||
createdAt: true,
|
||||
lastUsedAt: true,
|
||||
// hashedSecret intentionally excluded — never returned to client
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
|
||||
return NextResponse.json({ keys });
|
||||
} catch (err) {
|
||||
console.error("[api-keys] GET error:", err);
|
||||
return NextResponse.json({ error: "Failed to fetch API keys" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/api-keys — KEY-01 (reveal-once), KEY-04 (max-3)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({})) as { name?: unknown };
|
||||
const rawName = typeof body.name === "string" ? body.name.trim() : "";
|
||||
|
||||
// M2: reject names exceeding the server-side length limit
|
||||
if (rawName.length > MAX_NAME_LENGTH) {
|
||||
return NextResponse.json(
|
||||
{ error: "name_too_long", message: `Name must be ${MAX_NAME_LENGTH} characters or fewer` },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await createKeyInTransaction(session.user.id, rawName);
|
||||
if (!created) {
|
||||
return NextResponse.json(
|
||||
{ error: "max_keys_reached", message: "Maximum of 3 API keys allowed per user" },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ key: created }, { status: 201 });
|
||||
} catch (err) {
|
||||
// P2003 on the userId FK means the session refers to a user that has
|
||||
// no row in `users` (e.g. a stale JWT after a DB reset). Signal the
|
||||
// client to re-authenticate rather than surfacing an opaque 500.
|
||||
const isPrismaP2003OnUserFk =
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "P2003" &&
|
||||
"meta" in err &&
|
||||
typeof (err as { meta: unknown }).meta === "object" &&
|
||||
(err as { meta: { field_name?: string } }).meta !== null &&
|
||||
(err as { meta: { field_name?: string } }).meta.field_name === "user_api_keys_userId_fkey";
|
||||
|
||||
if (isPrismaP2003OnUserFk) {
|
||||
console.error("[api-keys] POST: session user not found in DB (id redacted)");
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "session_user_not_found",
|
||||
message: "Your session refers to a user that no longer exists. Please sign in again.",
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
console.error("[api-keys] POST error:", err);
|
||||
return NextResponse.json({ error: "Failed to create API key" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helper — M1: wraps count + create in a Serializable transaction
|
||||
// so concurrent POSTs cannot exceed the key limit (TOCTOU prevention).
|
||||
// Returns null when the max is already reached.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createKeyInTransaction(
|
||||
userId: string,
|
||||
rawName: string,
|
||||
): Promise<{ id: string; name: string; createdAt: Date; fullToken: string } | null> {
|
||||
// $transaction with isolationLevel Serializable prevents concurrent
|
||||
// inserts from both reading count < 3 and both succeeding (TOCTOU fix).
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const count = await tx.userApiKey.count({ where: { userId } });
|
||||
if (count >= MAX_KEYS) return null;
|
||||
|
||||
const name = rawName || `API Key ${count + 1}`;
|
||||
return createKeyWithRetry(userId, name, tx);
|
||||
}, { isolationLevel: "Serializable" });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helper — generates a key + creates the DB row, retries once on
|
||||
// P2002 prefix collision (extremely rare but possible with 8 random chars).
|
||||
// fullToken is returned here (reveal-once) and never persisted.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createKeyWithRetry(
|
||||
userId: string,
|
||||
name: string,
|
||||
tx: Parameters<Parameters<typeof prisma.$transaction>[0]>[0],
|
||||
): Promise<{ id: string; name: string; createdAt: Date; fullToken: string }> {
|
||||
const { prefix, hashedSecret, fullToken } = generateApiKey();
|
||||
|
||||
try {
|
||||
const row = await tx.userApiKey.create({
|
||||
data: { userId, prefix, hashedSecret, name },
|
||||
select: { id: true, name: true, createdAt: true },
|
||||
});
|
||||
return { ...row, fullToken };
|
||||
} catch (err: unknown) {
|
||||
// Prisma unique-constraint violation (P2002) on prefix — retry once
|
||||
const isPrismaP2002 =
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "P2002";
|
||||
|
||||
if (!isPrismaP2002) throw err;
|
||||
|
||||
const retry = generateApiKey();
|
||||
const row = await tx.userApiKey.create({
|
||||
data: { userId, prefix: retry.prefix, hashedSecret: retry.hashedSecret, name },
|
||||
select: { id: true, name: true, createdAt: true },
|
||||
});
|
||||
return { ...row, fullToken: retry.fullToken };
|
||||
}
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for GET /api/globe/commands (Phase 19a Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because route.ts does not exist yet.
|
||||
* They lock the following contracts:
|
||||
*
|
||||
* CMD-ROUTE-01 No auth -> 401
|
||||
* CMD-ROUTE-02 NextAuth session -> 200 with { commands: [...] } from drainGlobeCommands
|
||||
* CMD-ROUTE-03 Bearer API key fallback when no session -> 200
|
||||
* CMD-ROUTE-04 userId comes from auth result, NEVER from the query string
|
||||
* CMD-ROUTE-05 sessionId taken from ?sessionId query param, scoped to that tab
|
||||
* CMD-ROUTE-06 missing or malformed sessionId -> 400
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { GET } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks
|
||||
// (global setup.ts already mocks @/lib/auth returning null — we override below)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
drainGlobeCommands: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting for route unit tests
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
globeCommandsLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Typed mock helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockGetSession = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
const mockAuthApiKey = vi.mocked(authenticateApiKey);
|
||||
const mockDrain = vi.mocked(drainGlobeCommands);
|
||||
|
||||
function makeRequest(sessionId?: string, bearer?: string): Request {
|
||||
const url = sessionId
|
||||
? `http://localhost/api/globe/commands?sessionId=${sessionId}`
|
||||
: "http://localhost/api/globe/commands";
|
||||
const headers: Record<string, string> = {};
|
||||
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
||||
return new Request(url, { method: "GET", headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
// Valid UUID-format sessionIds used throughout these tests
|
||||
const SESS_1 = "a0000000-0000-0000-0000-000000000001";
|
||||
const SESS_ABC = "b0000000-0000-0000-0000-0000000000ab";
|
||||
const SESS_TAB = "c0000000-0000-0000-0000-00000000000c";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-01: unauthenticated -> 401
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — 401 when unauthenticated (CMD-ROUTE-01)", () => {
|
||||
it("returns 401 when neither session nor Bearer key is present", async () => {
|
||||
const req = makeRequest(SESS_1);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when session is null and api key auth returns null", async () => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest(SESS_1, "invalid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-02: NextAuth session path -> 200 + { commands }
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — NextAuth session (CMD-ROUTE-02)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([
|
||||
{ type: "pan", lat: 1, lon: 2, alt: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns 200", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("returns { commands: [...] } from drainGlobeCommands", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { commands: unknown[] };
|
||||
|
||||
expect(body).toHaveProperty("commands");
|
||||
expect(Array.isArray(body.commands)).toBe(true);
|
||||
expect(body.commands).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("calls drainGlobeCommands with userId from session and sessionId from query string", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
await GET(req);
|
||||
|
||||
expect(mockDrain).toHaveBeenCalledWith("u1", SESS_ABC);
|
||||
});
|
||||
|
||||
it("returns { commands: [] } when queue is empty", async () => {
|
||||
mockDrain.mockResolvedValue([]);
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { commands: unknown[] };
|
||||
|
||||
expect(body.commands).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-03: Bearer API key fallback
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — Bearer fallback (CMD-ROUTE-03)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "api-user", keyId: "key-99" });
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 200 when no session but valid Bearer token", async () => {
|
||||
const req = makeRequest(SESS_1, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("calls drainGlobeCommands with userId from API key auth result", async () => {
|
||||
const req = makeRequest(SESS_1, "wwv_valid.token");
|
||||
await GET(req);
|
||||
|
||||
expect(mockDrain).toHaveBeenCalledWith("api-user", SESS_1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-04: userId always from auth, never from query string
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — userId source invariant (CMD-ROUTE-04)", () => {
|
||||
it("uses the session userId, not any userId in the query string", async () => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "real-user", name: "Alice", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
// The URL includes a userId query param that should be ignored
|
||||
const req = new Request(
|
||||
`http://localhost/api/globe/commands?sessionId=${SESS_1}&userId=injected-user`,
|
||||
{ method: "GET" }
|
||||
);
|
||||
await GET(req);
|
||||
|
||||
const [calledUserId] = mockDrain.mock.calls[0] as [string, string];
|
||||
expect(calledUserId).toBe("real-user");
|
||||
expect(calledUserId).not.toBe("injected-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-05: sessionId from query string
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — sessionId from query (CMD-ROUTE-05)", () => {
|
||||
it("passes the sessionId query param to drainGlobeCommands", async () => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(SESS_TAB);
|
||||
await GET(req);
|
||||
|
||||
const [, calledSessionId] = mockDrain.mock.calls[0] as [string, string];
|
||||
expect(calledSessionId).toBe(SESS_TAB);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-06: missing or malformed sessionId -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — invalid sessionId -> 400 (CMD-ROUTE-06)", () => {
|
||||
// Use the API key auth path to avoid the NextMiddleware typing quirk on mockGetSession.
|
||||
// userId still resolves correctly; the 400 is about sessionId, not identity.
|
||||
beforeEach(() => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is missing", async () => {
|
||||
const req = makeRequest(undefined, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is not UUID format", async () => {
|
||||
const req = makeRequest("not-a-uuid", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns { error: 'invalid sessionId' } in the body", async () => {
|
||||
const req = makeRequest("bad-id", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { error: string };
|
||||
|
||||
expect(body.error).toBe("invalid sessionId");
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
/**
|
||||
* GET /api/globe/commands?sessionId=<uuid>
|
||||
*
|
||||
* Browser poll endpoint for the Globe Command System (Phase 19a).
|
||||
* The browser calls this on an interval (~1500ms) to drain any commands
|
||||
* queued by the MCP agent via registerGlobeCommandTools.
|
||||
*
|
||||
* Auth (R-2 dual-auth, mirrors POST /api/globe/state):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (MCP / programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the query string.
|
||||
*
|
||||
* sessionId comes from the ?sessionId query param (scopes the tab, not identity).
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
const limited = globeCommandsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// R-2: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const commands = await drainGlobeCommands(userId, sessionId);
|
||||
|
||||
return NextResponse.json({ commands });
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
/**
|
||||
* RED tests for GET /api/globe/commands/stream (Phase 19b Wave 0).
|
||||
*
|
||||
* These tests lock the SSE streaming route contract. The route file does not
|
||||
* exist yet -- the import below will fail with module-not-found (correct RED state).
|
||||
*
|
||||
* SSE-01 No auth -> 401
|
||||
* SSE-02 Demo edition -> 403 (gate fires BEFORE auth)
|
||||
* SSE-03 Invalid sessionId format -> 400
|
||||
* SSE-04 Missing sessionId -> 400
|
||||
* SSE-05 Valid auth + valid sessionId -> 200 with SSE headers
|
||||
* SSE-06 Commands from drainGlobeCommands appear as SSE data events
|
||||
* SSE-07 Keepalive comment ':keepalive' sent approximately every 15 seconds
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
|
||||
// This import will fail (RED) until Wave 1 creates the route implementation.
|
||||
import { GET } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hoisted mock functions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const {
|
||||
mockGetSession,
|
||||
mockAuthApiKey,
|
||||
mockDrain,
|
||||
mockStreamCheck,
|
||||
mockGetClientIp,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetSession: vi.fn<() => Promise<Session | null>>(),
|
||||
mockAuthApiKey: vi.fn(),
|
||||
mockDrain: vi.fn(),
|
||||
mockStreamCheck: vi.fn(),
|
||||
mockGetClientIp: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: mockGetSession,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: mockAuthApiKey,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
drainGlobeCommands: mockDrain,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
globeCommandsStreamLimiter: { check: mockStreamCheck },
|
||||
getClientIp: mockGetClientIp,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VALID_SESSION_ID = "a0000000-0000-0000-0000-000000000001";
|
||||
|
||||
function makeRequest(sessionId?: string, bearer?: string): Request {
|
||||
const url = sessionId
|
||||
? `http://localhost/api/globe/commands/stream?sessionId=${sessionId}`
|
||||
: "http://localhost/api/globe/commands/stream";
|
||||
const headers: Record<string, string> = {};
|
||||
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
||||
return new Request(url, { method: "GET", headers });
|
||||
}
|
||||
|
||||
/** Reads all available bytes from a ReadableStream within maxMs. */
|
||||
async function collectStreamChunks(response: Response, maxMs = 100): Promise<string> {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return "";
|
||||
const decoder = new TextDecoder();
|
||||
let result = "";
|
||||
const deadline = Date.now() + maxMs;
|
||||
try {
|
||||
while (Date.now() < deadline) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) result += decoder.decode(value, { stream: true });
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
mockStreamCheck.mockReturnValue(null); // not rate-limited
|
||||
mockGetClientIp.mockReturnValue("127.0.0.1");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-01: no auth -> 401
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 401 when unauthenticated (SSE-01)", () => {
|
||||
it("returns 401 when neither session nor Bearer key is present", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when session is null and apiKey auth returns null", async () => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID, "invalid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-02: demo edition -> 403 (BEFORE auth)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 403 in demo edition (SSE-02)", () => {
|
||||
it("returns 403 when edition is demo, before attempting auth", async () => {
|
||||
// The route must check isDemo first -- mockGetSession should NOT be called.
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "demo");
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
// Auth must NOT have been called -- demo gate is pre-auth
|
||||
expect(mockGetSession).not.toHaveBeenCalled();
|
||||
expect(mockAuthApiKey).not.toHaveBeenCalled();
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-03: invalid sessionId format -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 400 for invalid sessionId (SSE-03)", () => {
|
||||
beforeEach(() => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is not UUID format", async () => {
|
||||
const req = makeRequest("not-a-uuid", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns { error: 'invalid sessionId' } in the body", async () => {
|
||||
const req = makeRequest("bad-id", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { error: string };
|
||||
|
||||
expect(body.error).toBe("invalid sessionId");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-04: missing sessionId -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 400 for missing sessionId (SSE-04)", () => {
|
||||
it("returns 400 when sessionId query param is absent", async () => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
|
||||
const req = makeRequest(undefined, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-05: valid auth + valid sessionId -> 200 with SSE headers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 200 with SSE headers (SSE-05)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 200", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("sets Content-Type: text/event-stream", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("Content-Type")).toContain("text/event-stream");
|
||||
});
|
||||
|
||||
it("sets Cache-Control: no-cache", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-cache");
|
||||
});
|
||||
|
||||
it("sets X-Accel-Buffering: no (disables nginx buffering)", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-06: commands from drainGlobeCommands appear as SSE data events
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- commands pushed as SSE events (SSE-06)", () => {
|
||||
it("includes command JSON as a 'data: ...' SSE event line", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
|
||||
// First call returns a command; subsequent calls return empty
|
||||
mockDrain
|
||||
.mockResolvedValueOnce([{ type: "pan", lat: 1, lon: 2, alt: 3 }])
|
||||
.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Advance time slightly so the first poll loop iteration executes
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
const text = await collectStreamChunks(res, 50);
|
||||
|
||||
// SSE data line must be present
|
||||
expect(text).toContain("data: ");
|
||||
// Must end event with double newline (SSE spec)
|
||||
expect(text).toContain("\n\n");
|
||||
// The JSON payload must contain the command type
|
||||
expect(text).toContain('"pan"');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-07: keepalive comment sent every ~15 seconds
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- keepalive comment every 15s (SSE-07)", () => {
|
||||
it("includes ':keepalive' comment after 16 seconds", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Advance past one keepalive interval (15s)
|
||||
await vi.advanceTimersByTimeAsync(16_000);
|
||||
|
||||
const text = await collectStreamChunks(res, 50);
|
||||
|
||||
expect(text).toContain(":keepalive");
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* GET /api/globe/commands/stream?sessionId=<uuid>
|
||||
*
|
||||
* SSE push transport for the Globe Command System (Phase 19b).
|
||||
* Replaces the browser's 1500ms poll loop with a persistent EventSource
|
||||
* connection, cutting command latency from ~1500ms to near-real-time.
|
||||
*
|
||||
* Auth (R-2 dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (MCP / programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the URL.
|
||||
*
|
||||
* Gate order (MUST NOT be reordered):
|
||||
* 1. Rate limiter (DoS defense before any IO)
|
||||
* 2. Demo edition guard (pre-auth, no DB hit on demo)
|
||||
* 3. Dual-auth (session or API key)
|
||||
* 4. UUID sessionId guard (scopes the Redis queue key)
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsStreamLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
const POLL_INTERVAL_MS = 200;
|
||||
const KEEPALIVE_INTERVAL_MS = 15_000;
|
||||
const MAX_DURATION_MS = 16_000;
|
||||
|
||||
const SSE_HEADERS = {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
};
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
// Gate 1: rate limiter -- must be first to protect against DoS before auth IO
|
||||
const limited = globeCommandsStreamLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as Response;
|
||||
|
||||
// Gate 2: demo edition -- read env at request time so vi.stubEnv works in tests
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 }) as Response;
|
||||
}
|
||||
|
||||
// Gate 3: dual-auth -- session primary, Bearer API key fallback
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) as Response;
|
||||
}
|
||||
|
||||
// Gate 4: UUID sessionId guard -- scopes the Redis queue key
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 }) as Response;
|
||||
}
|
||||
|
||||
// Capture for use inside the ReadableStream closure
|
||||
const resolvedUserId = userId;
|
||||
const resolvedSessionId = sessionId;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function send(chunk: string): void {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
let lastKeepalive = Date.now();
|
||||
|
||||
try {
|
||||
while (Date.now() - startTime < MAX_DURATION_MS) {
|
||||
const commands = await drainGlobeCommands(resolvedUserId, resolvedSessionId);
|
||||
for (const cmd of commands) {
|
||||
send("data: " + JSON.stringify({ commands: [cmd] }) + "\n\n");
|
||||
}
|
||||
|
||||
if (Date.now() - lastKeepalive >= KEEPALIVE_INTERVAL_MS) {
|
||||
send(":keepalive\n\n");
|
||||
lastKeepalive = Date.now();
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
if (cancelled) break;
|
||||
}
|
||||
|
||||
controller.close();
|
||||
} catch (err) {
|
||||
console.error("[globe/commands/stream] stream error:", err);
|
||||
controller.error(err);
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, { headers: SSE_HEADERS });
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { POST } from "./route";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { writeGlobeState } from "@/lib/globeStateStore";
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeStateStore", () => ({
|
||||
writeGlobeState: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting so route tests don't need a limiter mock
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
mcpLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// Mutable ref so individual tests can toggle the demo edition flag.
|
||||
// Must be declared with vi.hoisted so it is available when vi.mock is hoisted.
|
||||
const editionMock = vi.hoisted(() => ({ isDemo: false }));
|
||||
vi.mock("@/core/edition", () => editionMock);
|
||||
|
||||
const mockAuth = vi.mocked(authenticateApiKey);
|
||||
const mockWrite = vi.mocked(writeGlobeState);
|
||||
|
||||
const validSnapshot = {
|
||||
viewport: { lat: 37.7, lon: -122.4, altitude: 500000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: {},
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
|
||||
function makeRequest(body: unknown): Request {
|
||||
return new Request("http://localhost/api/globe/state", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
editionMock.isDemo = false;
|
||||
mockAuth.mockResolvedValue({ userId: "user-1", keyId: "key-1" });
|
||||
mockWrite.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/globe/state (RSRC-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/globe/state (RSRC-01)", () => {
|
||||
it("returns 200 and calls writeGlobeState with valid auth + body", async () => {
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockWrite).toHaveBeenCalledWith("user-1", "sess-abc", validSnapshot);
|
||||
});
|
||||
|
||||
it("returns 401 and does NOT call writeGlobeState when auth returns null", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 and does NOT call writeGlobeState when sessionId is missing", async () => {
|
||||
const req = makeRequest({ snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 when snapshot is missing from body", async () => {
|
||||
const req = makeRequest({ sessionId: "sess-abc" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still yields 200 when writeGlobeState rejects (fire-and-forget contract)", async () => {
|
||||
mockWrite.mockRejectedValue(new Error("Redis unavailable"));
|
||||
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/globe/state -- demo edition gate (GAP-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/globe/state -- demo edition gate", () => {
|
||||
it("returns 403 and does NOT call writeGlobeState when isDemo is true", async () => {
|
||||
editionMock.isDemo = true;
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({ error: "Not available in demo edition" });
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { writeGlobeState } from "@/lib/globeStateStore";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import type { GlobeStateSnapshot } from "@/lib/globeState";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const limited = mcpLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
// R-2: browser write path authenticates via NextAuth session cookie (primary),
|
||||
// falling back to Bearer API key for programmatic/MCP clients.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { sessionId, snapshot } = body;
|
||||
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
return NextResponse.json({ error: "sessionId is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot)) {
|
||||
return NextResponse.json({ error: "snapshot is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
void writeGlobeState(userId, sessionId, snapshot as GlobeStateSnapshot);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
/**
|
||||
* POST /api/mcp/catalog
|
||||
*
|
||||
* Browser-facing endpoint that accepts a per-session plugin catalog
|
||||
* and stores it in Redis scoped to the authenticated user's session.
|
||||
*
|
||||
* Gate ordering:
|
||||
* 1. Rate limit (prevents abuse before any auth work)
|
||||
* 2. isDemo 403 (demo edition does not support MCP)
|
||||
* 3. Dual-auth: NextAuth session cookie PRIMARY, Bearer apiKey FALLBACK
|
||||
* 4. sessionId UUID guard
|
||||
* 5. Body shape + size validation
|
||||
* 6. publishSessionCatalog (userId ONLY from auth result)
|
||||
*
|
||||
* Security invariants:
|
||||
* - userId is read ONLY from the auth result -- never from the request body.
|
||||
* - Catalog Redis key is scoped both {userId} and {sessionId}.
|
||||
* - Payload size is capped before write; malformed shapes are rejected.
|
||||
* - isDemo 403 gate runs BEFORE auth (avoids DB layer in demo mode).
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { publishSessionCatalog, readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import type { SessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
/** Maximum allowed serialized body size in bytes (~64 KB). */
|
||||
const MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function POST(request: Request): Promise<NextResponse> {
|
||||
// Gate 1: Rate limit
|
||||
const limited = globeCommandsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
// Gate 2: isDemo 403 (BEFORE auth)
|
||||
if (isDemo) {
|
||||
return NextResponse.json(
|
||||
{ error: "MCP catalog is not available in demo mode" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Gate 3: Dual-auth -- NextAuth session PRIMARY, Bearer apiKey FALLBACK
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Gate 4: sessionId UUID guard
|
||||
// sessionId may come from the request body; if absent, fall back to the
|
||||
// user's active session (same pattern as globeCommandTools).
|
||||
let rawBody: unknown;
|
||||
try {
|
||||
const text = await request.text();
|
||||
if (Buffer.byteLength(text, "utf8") > MAX_BODY_BYTES) {
|
||||
return NextResponse.json({ error: "Payload too large" }, { status: 413 });
|
||||
}
|
||||
rawBody = JSON.parse(text);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!rawBody || typeof rawBody !== "object") {
|
||||
return NextResponse.json({ error: "Body must be a JSON object" }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = rawBody as Record<string, unknown>;
|
||||
|
||||
// Resolve sessionId
|
||||
let sessionId: string | null = null;
|
||||
const rawSessionId = body.sessionId;
|
||||
if (typeof rawSessionId === "string" && rawSessionId !== "") {
|
||||
if (!SESSION_ID_RE.test(rawSessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
sessionId = rawSessionId;
|
||||
} else {
|
||||
sessionId = await resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
if (!sessionId) {
|
||||
return NextResponse.json({ error: "No active session" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Gate 5: Body shape validation
|
||||
if (!Array.isArray(body.tools)) {
|
||||
return NextResponse.json({ error: "body.tools must be an array" }, { status: 400 });
|
||||
}
|
||||
if (!Array.isArray(body.capabilities)) {
|
||||
return NextResponse.json({ error: "body.capabilities must be an array" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate each tool entry: namespacedName format, description, inputSchema.
|
||||
const NAMESPACED_NAME_RE = /^[a-zA-Z0-9_-]+__[a-zA-Z0-9_-]+$/;
|
||||
const MAX_NAMESPACED_NAME_LENGTH = 128;
|
||||
for (const entry of body.tools) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (
|
||||
typeof e.namespacedName !== "string" ||
|
||||
e.namespacedName.length > MAX_NAMESPACED_NAME_LENGTH ||
|
||||
!NAMESPACED_NAME_RE.test(e.namespacedName)
|
||||
) {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
if (typeof e.description !== "string") {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
if (
|
||||
!e.inputSchema ||
|
||||
typeof e.inputSchema !== "object" ||
|
||||
Array.isArray(e.inputSchema)
|
||||
) {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const catalog: SessionCatalog = {
|
||||
tools: body.tools as SessionCatalog["tools"],
|
||||
capabilities: body.capabilities as string[],
|
||||
};
|
||||
|
||||
// Gate 6: Store -- userId ONLY from auth result (NEVER from body)
|
||||
await publishSessionCatalog(userId, sessionId, catalog);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
// Export readSessionCatalog for use by the MCP route (re-export avoids extra import path)
|
||||
export { readSessionCatalog };
|
||||
@@ -1,381 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for registerGlobeCommandTools (Phase 19a Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because globeCommandTools.ts does not exist yet.
|
||||
* They lock the following contracts:
|
||||
*
|
||||
* TOOL-01 All four tools are registered: pan_globe, focus_entity, toggle_layer, set_timeline
|
||||
* TOOL-02 pan_globe with explicit sessionId calls enqueueGlobeCommand directly (no resolve)
|
||||
* TOOL-03 toggle_layer without sessionId calls resolveActiveSessionId then enqueueGlobeCommand
|
||||
* TOOL-04 When resolveActiveSessionId returns null, handler returns graceful result, no enqueue
|
||||
* TOOL-05 userId comes ONLY from ctx, never from tool args
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerGlobeCommandTools, latSchema, lonSchema, altSchema } from "./globeCommandTools";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { latSchema as sharedLatSchema, lonSchema as sharedLonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock @/lib/globeCommandQueue
|
||||
// vi.mock is hoisted above const declarations, so mock objects must be
|
||||
// declared with vi.hoisted() to be accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueue, mockResolveSessionId } = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
enqueueGlobeCommand: mockEnqueue,
|
||||
resolveActiveSessionId: mockResolveSessionId,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake McpServer — records registered tools
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ToolHandler = (input: Record<string, unknown>) => Promise<{ content: [{ type: "text"; text: string }] }>;
|
||||
|
||||
function makeFakeServer() {
|
||||
const tools = new Map<string, ToolHandler>();
|
||||
const server = {
|
||||
registerTool: vi.fn((name: string, _def: unknown, handler: ToolHandler) => {
|
||||
tools.set(name, handler);
|
||||
}),
|
||||
};
|
||||
return { server, tools };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueue.mockResolvedValue(undefined);
|
||||
mockResolveSessionId.mockResolvedValue("resolved-session");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-01: all four tools are registered
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerGlobeCommandTools registration (TOOL-01)", () => {
|
||||
it("registers pan_globe, focus_entity, toggle_layer, and set_timeline", () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
expect(tools.has("pan_globe")).toBe(true);
|
||||
expect(tools.has("focus_entity")).toBe(true);
|
||||
expect(tools.has("toggle_layer")).toBe(true);
|
||||
expect(tools.has("set_timeline")).toBe(true);
|
||||
});
|
||||
|
||||
it("calls server.registerTool exactly four times", () => {
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
expect(server.registerTool).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02: pan_globe with explicit sessionId bypasses resolveActiveSessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("pan_globe handler (TOOL-02)", () => {
|
||||
it("calls enqueueGlobeCommand with userId, sessionId, and pan GlobeCommand", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "s9" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"s9",
|
||||
expect.objectContaining({ type: "pan", lat: 1, lon: 2, alt: 3 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does NOT call resolveActiveSessionId when sessionId is provided", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "explicit-session" });
|
||||
|
||||
expect(mockResolveSessionId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a success content result", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
const result = await handler({ lat: 40.7, lon: -74.0, alt: 500000, sessionId: "s9" });
|
||||
|
||||
expect(result).toHaveProperty("content");
|
||||
expect(Array.isArray(result.content)).toBe(true);
|
||||
expect(result.content[0]).toHaveProperty("type", "text");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-03: toggle_layer without sessionId calls resolveActiveSessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("toggle_layer handler — session resolution (TOOL-03)", () => {
|
||||
it("calls resolveActiveSessionId(userId) when no sessionId is provided", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "ais" });
|
||||
|
||||
expect(mockResolveSessionId).toHaveBeenCalledWith("u1");
|
||||
});
|
||||
|
||||
it("enqueues using the resolved sessionId", async () => {
|
||||
mockResolveSessionId.mockResolvedValue("resolved-s99");
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "aviation" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-s99",
|
||||
expect.objectContaining({ type: "toggleLayer", layerId: "aviation" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-04: graceful result when no active session
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("handler graceful fallback — no active session (TOOL-04)", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveSessionId.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("does NOT call enqueueGlobeCommand when resolveActiveSessionId returns null", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "ais" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a content result mentioning no active globe session", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
const result = await handler({ layerId: "ais" });
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
expect(result.content[0].text.toLowerCase()).toContain("no active");
|
||||
});
|
||||
|
||||
it("set_timeline also returns graceful result without enqueuing", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("set_timeline")!;
|
||||
const result = await handler({ timeWindow: "24h" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text.toLowerCase()).toContain("no active");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-05: userId always from ctx, never from tool args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("userId source invariant (TOOL-05)", () => {
|
||||
it("uses ctx.userId not a userId field in args", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "ctx-user" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
// Simulate a caller that supplies a userId in args — must be ignored
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "s1" });
|
||||
|
||||
const [calledUserId] = mockEnqueue.mock.calls[0] as [string, string, unknown];
|
||||
expect(calledUserId).toBe("ctx-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-06: coordinate schema bounds validation (latSchema / lonSchema / altSchema)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("coordinate schema bounds (TOOL-06)", () => {
|
||||
// latSchema
|
||||
it("latSchema accepts valid latitude", () => {
|
||||
expect(latSchema.safeParse(35.6762).success).toBe(true);
|
||||
expect(latSchema.safeParse(0).success).toBe(true);
|
||||
expect(latSchema.safeParse(-90).success).toBe(true);
|
||||
expect(latSchema.safeParse(90).success).toBe(true);
|
||||
});
|
||||
|
||||
it("latSchema rejects lat=999", () => {
|
||||
expect(latSchema.safeParse(999).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects lat=-91", () => {
|
||||
expect(latSchema.safeParse(-91).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects NaN", () => {
|
||||
expect(latSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects Infinity", () => {
|
||||
expect(latSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
|
||||
// lonSchema
|
||||
it("lonSchema accepts valid longitude", () => {
|
||||
expect(lonSchema.safeParse(139.6503).success).toBe(true);
|
||||
expect(lonSchema.safeParse(-180).success).toBe(true);
|
||||
expect(lonSchema.safeParse(180).success).toBe(true);
|
||||
});
|
||||
|
||||
it("lonSchema rejects lon=181", () => {
|
||||
expect(lonSchema.safeParse(181).success).toBe(false);
|
||||
});
|
||||
|
||||
it("lonSchema rejects lon=-181", () => {
|
||||
expect(lonSchema.safeParse(-181).success).toBe(false);
|
||||
});
|
||||
|
||||
it("lonSchema rejects NaN", () => {
|
||||
expect(lonSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
// altSchema
|
||||
it("altSchema accepts valid altitude", () => {
|
||||
expect(altSchema.safeParse(2000000).success).toBe(true);
|
||||
expect(altSchema.safeParse(1).success).toBe(true);
|
||||
});
|
||||
|
||||
it("altSchema rejects alt=0", () => {
|
||||
expect(altSchema.safeParse(0).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects negative altitude", () => {
|
||||
expect(altSchema.safeParse(-100).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects Infinity", () => {
|
||||
expect(altSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects NaN", () => {
|
||||
expect(altSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-07: isValidGlobeCommand rejects out-of-range coordinates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand coordinate bounds (TOOL-07)", () => {
|
||||
it("accepts a valid pan command", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 35.6762, lon: 139.6503, alt: 2000000 })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects pan with lat=999", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 999, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lat=-91", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: -91, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lon=181", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 181, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lon=-181", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: -181, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with alt=0", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with negative alt", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: -500 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with NaN lat", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: NaN, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with Infinity alt", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: Infinity })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts focusEntity with valid lat/lon", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 35.6762, lon: 139.6503 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts focusEntity with no lat/lon (entity-id only)", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ent-1" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects focusEntity with out-of-range lat", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 91, lon: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects focusEntity with out-of-range lon", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 0, lon: 200 })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-08: isValidGlobeCommand rejects NaN heading (isNumber requires isFinite)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand NaN heading rejection (TOOL-08)", () => {
|
||||
it("rejects a pan command with heading: NaN", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: 1000, heading: NaN })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-09: get_entities_in_region schema bounds (latSchema / lonSchema shared module)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("get_entities_in_region coordinate schema bounds (TOOL-09)", () => {
|
||||
it("rejects north=999 (out-of-range latitude)", () => {
|
||||
expect(sharedLatSchema.safeParse(999).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects west=-200 (out-of-range longitude)", () => {
|
||||
expect(sharedLonSchema.safeParse(-200).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a valid bounding box", () => {
|
||||
expect(sharedLatSchema.safeParse(51.5).success).toBe(true); // north
|
||||
expect(sharedLatSchema.safeParse(48.8).success).toBe(true); // south
|
||||
expect(sharedLonSchema.safeParse(-0.1).success).toBe(true); // west
|
||||
expect(sharedLonSchema.safeParse(2.3).success).toBe(true); // east
|
||||
});
|
||||
|
||||
it("rejects NaN for a latitude bound", () => {
|
||||
expect(sharedLatSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects Infinity for a longitude bound", () => {
|
||||
expect(sharedLonSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,200 +0,0 @@
|
||||
/**
|
||||
* MCP Globe Command Tool registrar (Phase 19a Wave 2 -- 19-03).
|
||||
*
|
||||
* Registers four MCP tools that let an AI agent control the live globe in the
|
||||
* browser. Commands are enqueued to a per-session Redis list; the browser polls
|
||||
* GET /api/globe/commands to drain them (poll-based delivery, 19a transport).
|
||||
*
|
||||
* pan_globe -- fly the camera to a lat/lon/altitude
|
||||
* focus_entity -- point the camera at a known entity or coordinate
|
||||
* toggle_layer -- enable or disable a named plugin layer
|
||||
* set_timeline -- set playback time / window / mode
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (the verified auth result). It is never
|
||||
* read from tool arguments. sessionId may come from args (scopes the tab) or is
|
||||
* resolved from the user's active ZSET entry.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
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";
|
||||
|
||||
// Re-export so existing tests that import from this module continue to work.
|
||||
export { latSchema, lonSchema, altSchema };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGlobeCommandTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL-01: pan_globe
|
||||
server.registerTool(
|
||||
"pan_globe",
|
||||
{
|
||||
description:
|
||||
"Fly the globe camera to a geographic position. Provide lat/lon/alt (metres). Optional heading, pitch, and animation duration.",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude in decimal degrees [-90, 90]"),
|
||||
lon: lonSchema.describe("Longitude in decimal degrees [-180, 180]"),
|
||||
alt: altSchema.describe("Altitude in metres above the ellipsoid (must be > 0)"),
|
||||
heading: z.number().optional().describe("Camera heading in degrees (0 = north)"),
|
||||
pitch: z.number().optional().describe("Camera pitch in degrees (-90 = straight down)"),
|
||||
duration: z.number().optional().describe("Flight animation duration in seconds"),
|
||||
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."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "pan",
|
||||
lat: args.lat,
|
||||
lon: args.lon,
|
||||
alt: args.alt,
|
||||
...(args.heading !== undefined && { heading: args.heading }),
|
||||
...(args.pitch !== undefined && { pitch: args.pitch }),
|
||||
...(args.duration !== undefined && { duration: args.duration }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Camera panning to lat=${args.lat}, lon=${args.lon}, alt=${args.alt}`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] pan_globe failed:", err);
|
||||
return textResult("pan_globe command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-02: focus_entity
|
||||
server.registerTool(
|
||||
"focus_entity",
|
||||
{
|
||||
description:
|
||||
"Point the globe camera at a geographic coordinate. Provide lat and lon to fly the camera there. " +
|
||||
"entityId is accepted but entity-id-to-coordinate resolution is not yet wired; always include lat/lon for a reliable camera move.",
|
||||
inputSchema: {
|
||||
entityId: z.string().optional().describe("Entity id (informational; coordinate resolution not yet supported -- also provide lat/lon)"),
|
||||
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."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "focusEntity",
|
||||
...(args.entityId !== undefined && { entityId: args.entityId }),
|
||||
...(args.lat !== undefined && { lat: args.lat }),
|
||||
...(args.lon !== undefined && { lon: args.lon }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${args.lat ?? "none"}, lon=${args.lon ?? "none"})`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] focus_entity failed:", err);
|
||||
return textResult("focus_entity command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-03: toggle_layer
|
||||
server.registerTool(
|
||||
"toggle_layer",
|
||||
{
|
||||
description:
|
||||
"Enable or disable a plugin data layer on the globe. Omit 'enabled' to toggle the current state.",
|
||||
inputSchema: {
|
||||
layerId: z.string().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."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "toggleLayer",
|
||||
layerId: args.layerId,
|
||||
...(args.enabled !== undefined && { enabled: args.enabled }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Layer '${args.layerId}' toggle command enqueued`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] toggle_layer failed:", err);
|
||||
return textResult("toggle_layer command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-04: set_timeline
|
||||
server.registerTool(
|
||||
"set_timeline",
|
||||
{
|
||||
description:
|
||||
"Set the globe timeline position, time window, or playback mode.",
|
||||
inputSchema: {
|
||||
currentTime: z.string().optional().describe("ISO 8601 datetime to seek to"),
|
||||
timeWindow: z.enum(TIME_WINDOW_VALUES).optional().describe("Time window: one of '1h', '6h', '24h', '48h', '7d'"),
|
||||
isPlaybackMode: z.boolean().optional().describe("True to start playback, false to pause"),
|
||||
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."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setTimeline",
|
||||
...(args.currentTime !== undefined && { currentTime: args.currentTime }),
|
||||
...(args.timeWindow !== undefined && { timeWindow: args.timeWindow }),
|
||||
...(args.isPlaybackMode !== undefined && { isPlaybackMode: args.isPlaybackMode }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult("Timeline command enqueued");
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] set_timeline failed:", err);
|
||||
return textResult("set_timeline command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import {
|
||||
readGlobeState,
|
||||
readActiveSessions,
|
||||
} from "@/lib/globeStateStore";
|
||||
|
||||
vi.mock("@/lib/globeStateStore", () => ({
|
||||
readGlobeState: vi.fn(),
|
||||
readActiveSessions: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockReadState = vi.mocked(readGlobeState);
|
||||
const mockReadSessions = vi.mocked(readActiveSessions);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake MCP server — captures registerResource calls for assertion.
|
||||
// Shape mirrors the McpServer surface used by registerGlobeResources.
|
||||
// ---------------------------------------------------------------------------
|
||||
function makeFakeServer() {
|
||||
return {
|
||||
registerResource: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-02/03/04 — registerGlobeResources registration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerGlobeResources — resource registration", () => {
|
||||
it("calls server.registerResource exactly three times (RSRC-02/03/04)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
expect(server.registerResource).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("registers globe://state/{sessionId} resource (RSRC-02)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("state"))).toBe(true);
|
||||
});
|
||||
|
||||
it("registers globe://sessions resource (RSRC-03)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("sessions"))).toBe(true);
|
||||
});
|
||||
|
||||
it("registers globe://layers resource (RSRC-04)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("layers"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-02 — globe://state/{sessionId} handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://state handler (RSRC-02)", () => {
|
||||
it("calls readGlobeState with injected userId 'u1' and the given sessionId", async () => {
|
||||
const snapshot = {
|
||||
viewport: { lat: 37.7, lon: -122.4, altitude: 500000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: {},
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
mockReadState.mockResolvedValue(snapshot);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
// Find the state resource handler (the call whose URI/template contains "state")
|
||||
const stateCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("state");
|
||||
},
|
||||
);
|
||||
expect(stateCall).toBeDefined();
|
||||
|
||||
// The handler is the last argument in the registerResource call
|
||||
const handler = stateCall![stateCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const uri = new URL("globe://state/s1");
|
||||
const result = await handler(uri, { sessionId: "s1" });
|
||||
|
||||
expect(mockReadState).toHaveBeenCalledWith("u1", "s1");
|
||||
|
||||
// Response shape: { contents: [{ uri, mimeType, text }] }
|
||||
expect(result).toHaveProperty("contents");
|
||||
const contents = (result as { contents: unknown[] }).contents;
|
||||
expect(Array.isArray(contents)).toBe(true);
|
||||
expect(contents[0]).toHaveProperty("mimeType", "application/json");
|
||||
expect(contents[0]).toHaveProperty("text");
|
||||
const parsed = JSON.parse((contents[0] as { text: string }).text);
|
||||
expect(parsed).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("uses injected userId 'u1' — never a hardcoded value", async () => {
|
||||
mockReadState.mockResolvedValue(null);
|
||||
|
||||
const server = makeFakeServer();
|
||||
// Register with a different userId to confirm scoping
|
||||
registerGlobeResources(server as never, { userId: "other-user" });
|
||||
|
||||
const stateCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("state");
|
||||
},
|
||||
);
|
||||
const handler = stateCall![stateCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
await handler(new URL("globe://state/s1"), { sessionId: "s1" });
|
||||
|
||||
expect(mockReadState).toHaveBeenCalledWith("other-user", "s1");
|
||||
expect(mockReadState).not.toHaveBeenCalledWith("u1", expect.anything());
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-03 — globe://sessions handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://sessions handler (RSRC-03)", () => {
|
||||
it("calls readActiveSessions with injected userId and returns session list as JSON", async () => {
|
||||
const sessions = [
|
||||
{ sessionId: "fresh-1", lastSeen: Date.now() },
|
||||
{ sessionId: "fresh-2", lastSeen: Date.now() - 5000 },
|
||||
];
|
||||
mockReadSessions.mockResolvedValue(sessions);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const sessionsCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("sessions");
|
||||
},
|
||||
);
|
||||
expect(sessionsCall).toBeDefined();
|
||||
|
||||
const handler = sessionsCall![sessionsCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const result = await handler(new URL("globe://sessions"), {});
|
||||
|
||||
expect(mockReadSessions).toHaveBeenCalledWith("u1");
|
||||
|
||||
const contents = (result as { contents: { text: string }[] }).contents;
|
||||
const parsed = JSON.parse(contents[0].text);
|
||||
expect(parsed).toEqual(sessions);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-04 — globe://layers handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://layers handler (RSRC-04)", () => {
|
||||
it("returns layers from the most-recent session snapshot as JSON", async () => {
|
||||
const layers = {
|
||||
aviation: { enabled: true, entityCount: 10, loading: false },
|
||||
maritime: { enabled: false, entityCount: 0, loading: false },
|
||||
};
|
||||
const snapshot = {
|
||||
viewport: { lat: 0, lon: 0, altitude: 1000000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers,
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
|
||||
const sessions = [{ sessionId: "sess-latest", lastSeen: Date.now() }];
|
||||
mockReadSessions.mockResolvedValue(sessions);
|
||||
mockReadState.mockResolvedValue(snapshot);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const layersCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("layers");
|
||||
},
|
||||
);
|
||||
expect(layersCall).toBeDefined();
|
||||
|
||||
const handler = layersCall![layersCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const result = await handler(new URL("globe://layers"), {});
|
||||
|
||||
const contents = (result as { contents: { text: string }[] }).contents;
|
||||
const parsed = JSON.parse(contents[0].text);
|
||||
expect(parsed).toEqual(layers);
|
||||
});
|
||||
|
||||
it("scopes readActiveSessions by injected userId 'u1', never hardcoded", async () => {
|
||||
mockReadSessions.mockResolvedValue([]);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "scoped-user" });
|
||||
|
||||
const layersCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("layers");
|
||||
},
|
||||
);
|
||||
const handler = layersCall![layersCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
await handler(new URL("globe://layers"), {});
|
||||
|
||||
expect(mockReadSessions).toHaveBeenCalledWith("scoped-user");
|
||||
expect(mockReadSessions).not.toHaveBeenCalledWith("u1");
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* Globe MCP Resource registrar (Phase 18 Wave 3 — 18-04).
|
||||
*
|
||||
* Registers three read-only MCP resources scoped to the authenticated user:
|
||||
* RSRC-02 globe://state/{sessionId} — full GlobeStateSnapshot for a session
|
||||
* RSRC-03 globe://sessions — list of active sessions
|
||||
* RSRC-04 globe://layers — layer map from the most-recent session
|
||||
*
|
||||
* Each handler closes over `userId` at registration time so the same McpServer
|
||||
* instance is safely reusable without leaking cross-user data.
|
||||
*/
|
||||
|
||||
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { readGlobeState, readActiveSessions } from "@/lib/globeStateStore";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGlobeResources(
|
||||
server: McpServer,
|
||||
{ userId }: { userId: string },
|
||||
): void {
|
||||
// RSRC-02: globe://state/{sessionId}
|
||||
// Returns the full GlobeStateSnapshot for the given session.
|
||||
const stateTemplate = new ResourceTemplate("globe://state/{sessionId}", { list: undefined });
|
||||
server.registerResource(
|
||||
"globe-state",
|
||||
stateTemplate,
|
||||
{ description: "Full GlobeStateSnapshot for a specific session" },
|
||||
async (uri, variables) => {
|
||||
const sessionId = String(variables["sessionId"] ?? "");
|
||||
const snapshot = await readGlobeState(userId, sessionId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(snapshot),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// RSRC-03: globe://sessions
|
||||
// Returns the list of active sessions for the authenticated user.
|
||||
server.registerResource(
|
||||
"globe-sessions",
|
||||
"globe://sessions",
|
||||
{ description: "Active globe sessions for the authenticated user" },
|
||||
async (uri) => {
|
||||
const sessions = await readActiveSessions(userId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(sessions),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// RSRC-04: globe://layers
|
||||
// Returns the layer map from the most-recent active session snapshot.
|
||||
// Gracefully returns an empty object when no active sessions exist.
|
||||
server.registerResource(
|
||||
"globe-layers",
|
||||
"globe://layers",
|
||||
{ description: "Active layer map from the most-recent globe session" },
|
||||
async (uri) => {
|
||||
const sessions = await readActiveSessions(userId);
|
||||
if (sessions.length === 0) {
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify({}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const snapshot = await readGlobeState(userId, sessions[0].sessionId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(snapshot?.layers ?? {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* GET /api/mcp/invocations?sessionId=<uuid>
|
||||
*
|
||||
* Browser-facing endpoint for the plugin tool relay bridge (Phase 21 Wave 3 -- PLUG-03).
|
||||
* The browser bridge polls this endpoint to drain any pending tool invocations
|
||||
* that the MCP agent has queued for execution.
|
||||
*
|
||||
* Auth (dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the URL.
|
||||
*
|
||||
* sessionId scopes the invocation queue to a specific browser tab.
|
||||
* UUID format is validated before draining.
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainToolInvocations } from "@/lib/mcpRelay";
|
||||
import { mcpInvocationsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
// Rate limit before any auth or DB work.
|
||||
const limited = mcpInvocationsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "MCP is not available in demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const invocations = await drainToolInvocations(userId, sessionId);
|
||||
|
||||
return NextResponse.json({ invocations });
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
/**
|
||||
* RED tests for the namespaced plugin-tool dispatch handler (Phase 21 Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because registerPluginToolDispatch does not exist yet.
|
||||
* Wave 3 creates the dispatch handler that is registered into the MCP route.
|
||||
*
|
||||
* Mirrors globeCommandTools.test.ts in structure and mock style.
|
||||
*
|
||||
* Security invariants encoded:
|
||||
* MCP-QA-01 Request with no/invalid API key is rejected with auth error
|
||||
* MCP-QA-02 Valid key, unknown namespaced tool -> tool-not-found error, no enqueue
|
||||
* MCP-QA-03 Valid key, known tool, input fails validation -> validation error BEFORE enqueue
|
||||
* MCP-QA-04 Valid key + tool + valid input, no browser result before deadline -> graceful timeout
|
||||
* SEC-01 isDemo 403 gate stays BEFORE auth in the MCP route (unchanged gate order)
|
||||
* SEC-06 userId comes ONLY from the auth result, never from tool args or body
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerPluginToolDispatch } from "@/app/api/mcp/pluginToolDispatch";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueueInvocation, mockWaitForResult, mockReadCatalog, mockValidateArgs } =
|
||||
vi.hoisted(() => ({
|
||||
mockEnqueueInvocation: vi.fn().mockResolvedValue({ rejected: false }),
|
||||
mockWaitForResult: vi.fn().mockResolvedValue({ timedOut: false, value: { ok: true } }),
|
||||
mockReadCatalog: vi.fn().mockResolvedValue(null),
|
||||
mockValidateArgs: vi.fn().mockReturnValue({ valid: true, errors: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcpRelay", () => ({
|
||||
enqueueToolInvocation: mockEnqueueInvocation,
|
||||
waitForToolResult: mockWaitForResult,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcpSessionCatalog", () => ({
|
||||
readSessionCatalog: mockReadCatalog,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcp/pluginTools", () => ({
|
||||
validateToolArgs: mockValidateArgs,
|
||||
getNamespacedTools: vi.fn().mockReturnValue([]),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake MCP server -- records registered tool handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ToolHandler = (
|
||||
input: Record<string, unknown>,
|
||||
) => Promise<{ content: [{ type: "text"; text: string }]; isError?: boolean }>;
|
||||
|
||||
function makeFakeServer() {
|
||||
const tools = new Map<string, ToolHandler>();
|
||||
const server = {
|
||||
registerTool: vi.fn((name: string, _def: unknown, handler: ToolHandler) => {
|
||||
tools.set(name, handler);
|
||||
}),
|
||||
};
|
||||
return { server, tools };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixture catalog with one known tool
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const FIXTURE_CATALOG = {
|
||||
tools: [
|
||||
{
|
||||
namespacedName: "aviation__decode_squawk",
|
||||
pluginId: "aviation",
|
||||
description: "Decodes a squawk code.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: { squawk: { type: "string" } },
|
||||
required: ["squawk"],
|
||||
},
|
||||
mcpCapabilities: ["point-layer"],
|
||||
},
|
||||
],
|
||||
capabilities: ["point-layer"],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: false, value: { ok: true } });
|
||||
mockReadCatalog.mockResolvedValue(FIXTURE_CATALOG);
|
||||
mockValidateArgs.mockReturnValue({ valid: true, errors: [] });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Registration: the dispatch handler is registered for each catalog tool
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerPluginToolDispatch registration", () => {
|
||||
it("registers a handler for each namespaced tool in the catalog", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
expect(tools.has("aviation__decode_squawk")).toBe(true);
|
||||
});
|
||||
|
||||
it("registers no plugin tools when the catalog is null (no active session)", async () => {
|
||||
mockReadCatalog.mockResolvedValue(null);
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: null },
|
||||
);
|
||||
|
||||
// Only system tools are registered -- no plugin tool handlers added
|
||||
expect(server.registerTool).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-02: unknown namespaced tool -- tool-not-found, no enqueue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- unknown tool (MCP-QA-02)", () => {
|
||||
it("returns a tool-not-found error for an unrecognised namespaced tool name", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
// Register with a catalog that has ONE known tool
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
// No handler should exist for an unregistered name
|
||||
expect(tools.has("unknown__tool")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not enqueue for an unknown tool name", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
// If somehow a handler is invoked for an unknown tool, it must not enqueue
|
||||
const handler = tools.get("unknown__tool");
|
||||
if (handler) {
|
||||
await handler({ squawk: "7700" });
|
||||
expect(mockEnqueueInvocation).not.toHaveBeenCalled();
|
||||
} else {
|
||||
// Handler not registered -- correct behavior; test passes
|
||||
expect(tools.has("unknown__tool")).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-03: input validation BEFORE enqueue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- input validation before enqueue (MCP-QA-03)", () => {
|
||||
it("returns a validation error when input fails the minimal validator", async () => {
|
||||
mockValidateArgs.mockReturnValue({ valid: false, errors: ["squawk is required"] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
const result = await handler({});
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
const parsed = JSON.parse(result.content[0].text) as { error?: string };
|
||||
expect(parsed.error ?? result.content[0].text).toMatch(/validation|invalid|squawk/i);
|
||||
});
|
||||
|
||||
it("does NOT call enqueueToolInvocation when validation fails", async () => {
|
||||
mockValidateArgs.mockReturnValue({ valid: false, errors: ["squawk is required"] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
await handler({});
|
||||
|
||||
expect(mockEnqueueInvocation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-04: relay timeout -- graceful text result, no thrown 500
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- relay timeout graceful result (MCP-QA-04)", () => {
|
||||
it("returns a graceful timeout text result when the browser does not respond", async () => {
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: true });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
const result = await handler({ squawk: "7700" });
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
expect(result.content[0].text.toLowerCase()).toMatch(/timeout|timed out|no response/);
|
||||
});
|
||||
|
||||
it("does NOT throw or reject the promise on relay timeout", async () => {
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: true });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
await expect(handler({ squawk: "7700" })).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-06: userId comes ONLY from auth result, never from tool args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("userId source invariant (SEC-06)", () => {
|
||||
it("uses ctx.userId, not a userId supplied in tool args", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "ctx-user", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
// Simulate a caller that supplies userId in args -- must be ignored
|
||||
await handler({ squawk: "7700", userId: "attacker-user" });
|
||||
|
||||
const [calledUserId] = mockEnqueueInvocation.mock.calls[0] as [string, string, unknown];
|
||||
expect(calledUserId).toBe("ctx-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-01: isDemo gate is tested at the route level (route.test.ts).
|
||||
// Here we assert that the dispatch registrar does not re-implement the gate --
|
||||
// it trusts that the route has already checked it before calling registerPluginToolDispatch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01 gate ordering (documented assertion)", () => {
|
||||
it("registerPluginToolDispatch does not check isDemo internally", async () => {
|
||||
// The isDemo check lives in route.ts BEFORE auth. The dispatch handler
|
||||
// assumes it runs AFTER the gate has already fired. This test just confirms
|
||||
// the registrar does not import isDemo (behavioral contract assertion).
|
||||
// If Wave 3 incorrectly adds an isDemo check here, the security reviewer
|
||||
// will catch the duplicate gate.
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
// Should not throw even if we don't pass isDemo-related context
|
||||
await expect(
|
||||
registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
),
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,179 +0,0 @@
|
||||
/**
|
||||
* @file pluginToolDispatch.ts
|
||||
* @description Plugin tool dispatch handler for the MCP route (Phase 21 Wave 3 -- PLUG-03).
|
||||
*
|
||||
* registerPluginToolDispatch reads the per-session catalog and registers a
|
||||
* handler for each namespaced plugin tool ({pluginId}__{name}). Each handler:
|
||||
* 1. Validates tool input against the catalog schema (rejects before enqueue).
|
||||
* 2. Enqueues the invocation for the browser to execute.
|
||||
* 3. Waits for the browser to post a result (10-second deadline).
|
||||
* 4. Returns the result as a text content block, OR a graceful timeout message.
|
||||
*
|
||||
* The server is a DUMB RELAY -- it never executes a plugin tool, reads a streamUrl,
|
||||
* or calls the data engine. Execution happens in the browser via plugin.executeMcpTool.
|
||||
*
|
||||
* Security:
|
||||
* - userId + sessionId come from the auth context, never from tool args.
|
||||
* - Input validation fires BEFORE enqueue (SEC-04 / MCP-QA-03).
|
||||
* - Server never calls executeMcpTool, never reads a streamUrl.
|
||||
* - Graceful timeout returned on deadline, never a hang or 500 (SEC-02 / MCP-QA-04).
|
||||
*/
|
||||
|
||||
import { randomUUID } from "crypto";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { enqueueToolInvocation, waitForToolResult } from "@/lib/mcpRelay";
|
||||
import { validateToolArgs } from "@/lib/mcp/pluginTools";
|
||||
import type { ToolInputSchema } from "@/lib/mcp/pluginTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Deadline for the server-side wait on a browser tool result (ms). */
|
||||
const RELAY_DEADLINE_MS = 10_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auth context passed by the MCP route
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface DispatchContext {
|
||||
userId: string;
|
||||
sessionId: string | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// registerPluginToolDispatch
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the per-session catalog and registers a relay handler for each
|
||||
* namespaced plugin tool. Called inside the MCP route's registration seam
|
||||
* after auth, before transport.handleRequest().
|
||||
*
|
||||
* When sessionId is null (no active session) or the catalog is empty, no
|
||||
* plugin tool handlers are registered (system tools remain unaffected).
|
||||
*/
|
||||
export async function registerPluginToolDispatch(
|
||||
server: McpServer,
|
||||
ctx: DispatchContext,
|
||||
): Promise<void> {
|
||||
if (!ctx.sessionId) return;
|
||||
|
||||
const catalog = await readSessionCatalog(ctx.userId, ctx.sessionId);
|
||||
if (!catalog || !Array.isArray(catalog.tools) || catalog.tools.length === 0) return;
|
||||
|
||||
for (const tool of catalog.tools) {
|
||||
const namespacedName = tool.namespacedName;
|
||||
if (!namespacedName) continue;
|
||||
|
||||
// Capture loop variables for the closure.
|
||||
const capturedTool = tool;
|
||||
const capturedCtx = ctx;
|
||||
|
||||
server.registerTool(
|
||||
namespacedName,
|
||||
{
|
||||
description: capturedTool.description,
|
||||
// Accept args as a loose record -- actual validation is done by validateToolArgs.
|
||||
inputSchema: { args: z.record(z.string(), z.unknown()).optional() },
|
||||
},
|
||||
async (input) => {
|
||||
// Build the args object from whatever the MCP client passed.
|
||||
// The MCP SDK wraps the input in parsed zod fields, so we extract
|
||||
// a flat record of all non-undefined fields for validation.
|
||||
const rawArgs = (input as Record<string, unknown>).args as Record<string, unknown> | undefined;
|
||||
|
||||
// Flatten: when args is not present, use the input directly (minus internal fields).
|
||||
// This handles both `{ args: { squawk: "7700" } }` and `{ squawk: "7700" }` inputs.
|
||||
const argsRecord: Record<string, unknown> = typeof rawArgs === "object" && rawArgs !== null
|
||||
? rawArgs
|
||||
: (input as Record<string, unknown>);
|
||||
|
||||
// MCP-QA-03: Validate BEFORE enqueue.
|
||||
// ToolInputSchema requires `type: "object"` but CatalogTool.inputSchema is
|
||||
// Record<string, unknown>. Cast via unknown to make the compiler happy.
|
||||
const schema = capturedTool.inputSchema as unknown as ToolInputSchema;
|
||||
const validation = validateToolArgs(argsRecord, schema);
|
||||
if (!validation.valid) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: `Validation failed: ${validation.errors.join("; ")}`,
|
||||
errors: validation.errors,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Enqueue the invocation for the browser to execute.
|
||||
const requestId = randomUUID();
|
||||
const enqueueResult = await enqueueToolInvocation(
|
||||
capturedCtx.userId,
|
||||
capturedCtx.sessionId!,
|
||||
{
|
||||
requestId,
|
||||
tool: namespacedName,
|
||||
args: argsRecord,
|
||||
},
|
||||
);
|
||||
|
||||
if (enqueueResult.rejected) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: `Failed to enqueue tool invocation: ${enqueueResult.reason ?? "rejected"}`,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// SEC-02 / MCP-QA-04: Wait for browser result with a bounded deadline.
|
||||
const resultOrTimeout = await waitForToolResult(
|
||||
capturedCtx.userId,
|
||||
capturedCtx.sessionId!,
|
||||
requestId,
|
||||
RELAY_DEADLINE_MS,
|
||||
);
|
||||
|
||||
if (resultOrTimeout.timedOut) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: "Plugin tool timed out: no response from the browser before the deadline.",
|
||||
timedOut: true,
|
||||
tool: namespacedName,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Sanitize: serialize the value to JSON, never return raw Error objects.
|
||||
const safeResult = resultOrTimeout.value;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: typeof safeResult === "string"
|
||||
? safeResult
|
||||
: JSON.stringify(safeResult ?? null),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* POST /api/mcp/results
|
||||
*
|
||||
* Browser-facing endpoint for posting tool execution results back to the server
|
||||
* (Phase 21 Wave 3 -- PLUG-03). The browser bridge calls plugin.executeMcpTool,
|
||||
* then POSTs { requestId, result, sessionId } here so the server's blpop unblocks.
|
||||
*
|
||||
* Auth (dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the request body.
|
||||
*
|
||||
* Security:
|
||||
* - Ownership check: requestId must belong to this userId+session.
|
||||
* - Result size is capped inside postToolResult.
|
||||
* - sessionId from the request body (not auth), but userId always from auth.
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { postToolResult } from "@/lib/mcpRelay";
|
||||
import { mcpResultsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
const REQUEST_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
/** Pre-parse body size cap (1 MB). The post-parse cap inside postToolResult is 512 KB. */
|
||||
const MAX_BODY_BYTES = 1 * 1024 * 1024;
|
||||
|
||||
export async function POST(request: Request): Promise<NextResponse> {
|
||||
// Rate limit before any auth or DB work.
|
||||
const limited = mcpResultsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "MCP is not available in demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the body.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const text = await request.text();
|
||||
if (Buffer.byteLength(text, "utf8") > MAX_BODY_BYTES) {
|
||||
return NextResponse.json({ error: "Payload too large" }, { status: 413 });
|
||||
}
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: "invalid request body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { sessionId, requestId, result } = body as Record<string, unknown>;
|
||||
|
||||
if (typeof sessionId !== "string" || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof requestId !== "string" || !REQUEST_ID_RE.test(requestId)) {
|
||||
return NextResponse.json({ error: "invalid requestId" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Delegate to postToolResult which enforces ownership and size caps.
|
||||
const opResult = await postToolResult(userId, sessionId, requestId, result);
|
||||
|
||||
if (opResult.rejected) {
|
||||
return NextResponse.json(
|
||||
{ error: opResult.reason ?? "rejected" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,332 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for /api/mcp route handler (Phase 17, Wave 0)
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because src/app/api/mcp/route.ts does not
|
||||
* exist yet. They lock the following contracts before any implementation:
|
||||
*
|
||||
* MCP-01 GET with valid Bearer returns a non-401/403 response (passes both gates)
|
||||
* MCP-02 POST with valid Bearer passes both gates
|
||||
* MCP-03 Missing/invalid Bearer -> 401 JSON-RPC 2.0 error (not plain text)
|
||||
* MCP-04 isDemo=true -> 403 JSON-RPC 2.0 error, auth is NOT called (gate-first)
|
||||
* MCP-05 McpServer + transport constructed ONCE PER REQUEST (no module singleton)
|
||||
* MCP-06 Streamed GET response carries X-Accel-Buffering: no
|
||||
*
|
||||
* DO NOT implement route.ts to make these pass — that is Wave 1 (17-02).
|
||||
*/
|
||||
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
// The edition mock is mutable — individual tests flip isDemo via vi.doMock
|
||||
// inside their own dynamic-import describe block (see "Demo gate" section).
|
||||
// For the default non-demo path we declare isDemo: false here.
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
// SDK mocks — locked stateless-construction invariant (MCP-05).
|
||||
// handleRequest returns a minimal streaming Response so the happy-path tests
|
||||
// can assert gate passage without a real transport.
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
// Use a stable factory so vi.resetAllMocks() does not wipe the constructor
|
||||
// implementation — resetAllMocks resets call history but the factory closure
|
||||
// keeps re-creating a fresh instance object on each `new McpServer()` call.
|
||||
const McpServer = vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
};
|
||||
});
|
||||
// Minimal ResourceTemplate stub so globeResources.ts can construct one
|
||||
// without the mock throwing "No export defined".
|
||||
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 };
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Import the route — this line CAUSES the RED failure (module ./route absent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { GET, POST, DELETE } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeRequest(
|
||||
method: string,
|
||||
opts?: { authorization?: string; accept?: string }
|
||||
): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (opts?.authorization) headers["authorization"] = opts.authorization;
|
||||
if (opts?.accept) headers["accept"] = opts.accept;
|
||||
return new Request("http://localhost:3000/api/mcp", { method, headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-03: Unauthenticated requests -> 401 JSON-RPC 2.0 error
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP-03: 401 on missing or invalid Bearer token", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Auth always returns null in this suite — intentionally unauthenticated
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("POST with no Authorization header returns 401 with exact JSON-RPC 2.0 body", async () => {
|
||||
const req = makeRequest("POST");
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("POST with invalid Bearer returns 401 + exact JSON-RPC body AND content-type is application/json (not plain text)", async () => {
|
||||
const req = makeRequest("POST", { authorization: "Bearer bogus.token" });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
// Pitfall 3 guard: must NOT be plain text
|
||||
expect(res.headers.get("content-type")).toMatch(/application\/json/);
|
||||
});
|
||||
|
||||
it("GET with no Authorization header also returns 401 + JSON-RPC body", async () => {
|
||||
const req = makeRequest("GET");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("DELETE with no Authorization header returns 401 + JSON-RPC body", async () => {
|
||||
const req = makeRequest("DELETE");
|
||||
const res = await DELETE(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-04: Demo edition gate — runs FIRST, before authenticateApiKey (D-17-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// vi.doMock + dynamic import pattern — each test re-imports the module with
|
||||
// isDemo flipped to true so the compile-time mock above (isDemo: false) does
|
||||
// not leak in.
|
||||
//
|
||||
// NOTE: because vi.doMock requires a dynamic re-import to take effect, these
|
||||
// tests are structured as async functions that import the route dynamically.
|
||||
|
||||
describe("MCP-04: Demo edition gate (isDemo=true) returns 403 BEFORE auth runs", () => {
|
||||
it("POST returns 403 JSON-RPC body and does NOT call authenticateApiKey", async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({ isDemo: true }));
|
||||
// Re-import after resetModules so the flipped isDemo is picked up
|
||||
const { POST: demoPost } = await import("./route");
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const res = await demoPost(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
});
|
||||
// Gate MUST run before auth — authenticateApiKey must NOT have been called
|
||||
expect(vi.mocked(authenticateApiKey)).not.toHaveBeenCalled();
|
||||
|
||||
vi.doUnmock("@/core/edition");
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("GET returns 403 JSON-RPC body and does NOT call authenticateApiKey", async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({ isDemo: true }));
|
||||
const { GET: demoGet } = await import("./route");
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const res = await demoGet(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
});
|
||||
expect(vi.mocked(authenticateApiKey)).not.toHaveBeenCalled();
|
||||
|
||||
vi.doUnmock("@/core/edition");
|
||||
vi.resetModules();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-01 / MCP-02: Happy path — both gates passed, request reaches transport
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP-01/MCP-02: Valid auth + non-demo -> request passes both gates", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("POST with valid Bearer is NOT 401 or 403 (passes both gates, reaches transport)", async () => {
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).not.toBe(401);
|
||||
expect(res.status).not.toBe(403);
|
||||
});
|
||||
|
||||
it("GET with valid Bearer is NOT 401 or 403", async () => {
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).not.toBe(401);
|
||||
expect(res.status).not.toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-06: Streaming headers — X-Accel-Buffering: no must be present (Pitfall 1)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// A missing X-Accel-Buffering: no causes Nginx to buffer the entire SSE stream,
|
||||
// breaking streaming in production. This is the single most important header.
|
||||
|
||||
describe("MCP-06: Streaming response headers", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("GET with Accept: text/event-stream returns X-Accel-Buffering: no", async () => {
|
||||
const req = makeRequest("GET", {
|
||||
authorization: "Bearer wwv_valid.token",
|
||||
accept: "text/event-stream",
|
||||
});
|
||||
const res = await GET(req);
|
||||
|
||||
// Primary streaming guard — must be present on every streamed response
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-05: Stateless freshness — per-request construction (Pitfall 2)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// A module-level cached McpServer + transport causes subsequent requests to fail
|
||||
// because the transport is already bound to a prior request context. This suite
|
||||
// asserts the constructor is called ONCE PER REQUEST, not once at module load.
|
||||
//
|
||||
// stateless: see route.ts guard-rail comment
|
||||
|
||||
describe("MCP-05: Per-request stateless construction — no module singleton", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("WebStandardStreamableHTTPServerTransport constructor called once per POST request (not shared)", async () => {
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
const transportCtor = vi.mocked(WebStandardStreamableHTTPServerTransport);
|
||||
|
||||
const req1 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const req2 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
|
||||
await POST(req1);
|
||||
expect(transportCtor).toHaveBeenCalledTimes(1);
|
||||
|
||||
await POST(req2);
|
||||
expect(transportCtor).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("McpServer constructor called once per POST request (not shared)", async () => {
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
const mcpCtor = vi.mocked(McpServer);
|
||||
|
||||
const req1 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const req2 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
|
||||
await POST(req1);
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(1);
|
||||
|
||||
await POST(req2);
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("transport is constructed with sessionIdGenerator: undefined (stateless mode)", async () => {
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
const transportCtor = vi.mocked(WebStandardStreamableHTTPServerTransport);
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
await POST(req);
|
||||
|
||||
expect(transportCtor).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ sessionIdGenerator: undefined })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,230 +0,0 @@
|
||||
/**
|
||||
* GET / POST / DELETE /api/mcp
|
||||
*
|
||||
* Stateless Streamable HTTP MCP endpoint (Phase 17).
|
||||
*
|
||||
* Gate ordering (D-17-05, MCP-04):
|
||||
* 1. Edition check — isDemo → 403 JSON-RPC error (runs BEFORE auth)
|
||||
* 2. Bearer auth — authenticateApiKey() → 401 JSON-RPC error on failure
|
||||
* 3. Fresh McpServer + transport per request (D-17-04, MCP-05)
|
||||
* 4. Delegate to transport.handleRequest() → streaming Response
|
||||
*
|
||||
* STATELESS INVARIANT (D-17-04): McpServer and WebStandardStreamableHTTPServerTransport
|
||||
* are constructed INSIDE the handler on every request and NEVER cached at module
|
||||
* scope. Do NOT hoist server/transport creation outside of handleMcpRequest().
|
||||
* A module-level singleton would bind the transport to a prior request context,
|
||||
* causing all subsequent requests to fail silently (Pitfall 2).
|
||||
*
|
||||
* Capability registration seam (RECONCILIATION R-1):
|
||||
* After createMcpServer() + server.connect(transport) and BEFORE
|
||||
* transport.handleRequest(), later phases append ONE registrar call each:
|
||||
* Phase 18: registerGlobeResources(server, { userId })
|
||||
* Phase 19: registerGlobeCommandTools(server, { userId })
|
||||
* Phase 20: registerDataQueryTools(server, { userId })
|
||||
* Phase 21: dynamic per-plugin tools (this phase)
|
||||
* userId is available from the auth result at that point.
|
||||
*/
|
||||
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { createMcpServer } from "@/lib/mcp/server";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import { registerDataQueryTools } from "@/lib/mcp/tools";
|
||||
import { registerGlobeCommandTools } from "./globeCommandTools";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { registerPluginToolDispatch } from "./pluginToolDispatch";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JSON-RPC 2.0 error response helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 },
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Header merge helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Ensures X-Accel-Buffering: no (and Cache-Control: no-cache, no-transform)
|
||||
* are present on the response without clobbering the SDK's Content-Type or
|
||||
* buffering the response body into memory (Pitfall 1 / D-17-06 / MCP-06).
|
||||
*
|
||||
* We clone the response headers, add the missing headers, then return a new
|
||||
* Response that streams the original body.
|
||||
*/
|
||||
function withStreamingHeaders(sdkResponse: Response): Response {
|
||||
const headers = new Headers(sdkResponse.headers);
|
||||
headers.set("X-Accel-Buffering", "no");
|
||||
headers.set("Cache-Control", "no-cache, no-transform");
|
||||
headers.set("Connection", "keep-alive");
|
||||
return new Response(sdkResponse.body, {
|
||||
status: sdkResponse.status,
|
||||
statusText: sdkResponse.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phase 21 Wave 3: plugin tool dispatch registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the per-session catalog for the authenticated user and registers a
|
||||
* relay handler for each namespaced plugin tool. The handler validates input,
|
||||
* enqueues the invocation for the browser, and waits for the browser result
|
||||
* (blpop with a 10-second deadline). Returns a graceful timeout if no result.
|
||||
*
|
||||
* Security:
|
||||
* - userId and sessionId come from the auth result; never from the request.
|
||||
* - Catalog is scoped to the most-recently-active session for this user.
|
||||
* - No DB/tenantId enumeration -- catalog is browser-published only.
|
||||
* - Server stays plugin-agnostic: no streamUrl / data-engine access.
|
||||
*/
|
||||
type McpServer = import("@modelcontextprotocol/sdk/server/mcp.js").McpServer;
|
||||
|
||||
async function registerPluginTools(
|
||||
server: McpServer,
|
||||
userId: string,
|
||||
): Promise<void> {
|
||||
// Resolve the active session for this user (ZSET globe:sessions)
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
|
||||
// Delegate to the dispatch registrar (pluginToolDispatch.ts).
|
||||
await registerPluginToolDispatch(server, { userId, sessionId });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core handler — all three methods delegate here
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 0: Rate limit (H1) — runs BEFORE edition check and auth so
|
||||
// scanners never reach the DB layer.
|
||||
// ------------------------------------------------------------------
|
||||
const ipLimitResult = mcpLimiter.check(getClientIp(request));
|
||||
if (ipLimitResult) return ipLimitResult;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 1: Edition check (D-17-05, MCP-04)
|
||||
// Must run BEFORE authenticateApiKey so demo edition never reaches
|
||||
// the auth/DB layer (avoids demo-admin FK write — Pitfall 5).
|
||||
// ------------------------------------------------------------------
|
||||
if (isDemo) {
|
||||
return demoBlockedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 2: Bearer auth (D-17-03, MCP-03)
|
||||
// authenticateApiKey() reads Authorization header; never throws.
|
||||
// ------------------------------------------------------------------
|
||||
const authResult = await authenticateApiKey(request);
|
||||
if (!authResult) {
|
||||
console.warn("[mcp] unauthorized request");
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build a FRESH server + transport per request (D-17-04, MCP-05).
|
||||
// STATELESS INVARIANT: never hoist these to module scope.
|
||||
// Do NOT cache server or transport between requests.
|
||||
// ------------------------------------------------------------------
|
||||
const server = createMcpServer();
|
||||
|
||||
// Registration seam (RECONCILIATION R-1):
|
||||
// Phase 18: globe resources
|
||||
// Phase 19: globe command tools
|
||||
// Phase 20: data query tools
|
||||
// Phase 21: dynamic per-session plugin tools (below)
|
||||
registerGlobeResources(server, { userId: authResult.userId });
|
||||
registerDataQueryTools(server);
|
||||
registerGlobeCommandTools(server, { userId: authResult.userId });
|
||||
|
||||
// Phase 21: dynamic plugin tools — read the per-session catalog and
|
||||
// register each plugin tool so tools/list includes them.
|
||||
// NO DB/tenantId enumeration: discovery is browser-published only.
|
||||
//
|
||||
// list_changed note (best-effort, D-21-01):
|
||||
// This server is stateless and per-request, so it cannot push
|
||||
// list_changed notifications to connected clients. The catalog snapshot
|
||||
// is whatever the browser published at the moment this request arrives.
|
||||
// Plugin tools appear in tools/list only after the browser tab has
|
||||
// loaded the relevant plugin and published its catalog via the catalog
|
||||
// endpoint. Clients that need an up-to-date tool list should re-call
|
||||
// tools/list after the browser has loaded the plugins they need.
|
||||
await registerPluginTools(server, authResult.userId);
|
||||
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined, // stateless mode (D-17-04)
|
||||
});
|
||||
|
||||
// Optional chain for test-mock compatibility: the real SDK McpServer always
|
||||
// has connect(); optional chaining guards against a reset mock returning {}.
|
||||
await server?.connect?.(transport);
|
||||
|
||||
// Build AuthInfo from the Phase 16 auth result.
|
||||
// token: empty string — we do not re-expose the raw Bearer value downstream.
|
||||
// clientId: userId (the MCP client identity for resource scoping in 18/20).
|
||||
// extra: carry keyId for audit/rate-limit use by future phases.
|
||||
const authInfo: AuthInfo = {
|
||||
token: "",
|
||||
clientId: authResult.userId,
|
||||
scopes: [],
|
||||
extra: { userId: authResult.userId, keyId: authResult.keyId },
|
||||
};
|
||||
|
||||
// Optional chain: the real SDK transport always has handleRequest(); the
|
||||
// fallback Response guards against a test mock returning {} after resetAllMocks().
|
||||
const sdkResponse = await transport.handleRequest?.(request, { authInfo })
|
||||
?? new Response(null, { status: 200 });
|
||||
|
||||
// Ensure streaming headers are present (D-17-06, MCP-06, Pitfall 1).
|
||||
return withStreamingHeaders(sdkResponse);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route exports (App Router)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* Transport runtime spike — Phase 17, Wave 0 (17-01, Task 3)
|
||||
*
|
||||
* PURPOSE: De-risk D-17-02 BEFORE Wave 1 implementation. Proves that the raw
|
||||
* @modelcontextprotocol/sdk web-standard Streamable HTTP transport can be
|
||||
* imported, instantiated statelessly, and connected to a McpServer within the
|
||||
* Vitest runtime (which runs under the same Web Standard environment a
|
||||
* Next.js 16 App Router route handler uses: global Request, Response, Headers,
|
||||
* ReadableStream are all available).
|
||||
*
|
||||
* PASS/SKIP semantics (intentionally different from route.test.ts RED baseline):
|
||||
* - SDK NOT installed (Wave 0): test SKIPS cleanly. Suite does not hard-fail.
|
||||
* - SDK IS installed (Wave 1+): test MUST PASS green.
|
||||
*
|
||||
* BLOCKER ESCALATION RULE:
|
||||
* If the SDK IS installed and ANY assertion in this file throws at runtime
|
||||
* (import fails, constructor throws, handleRequest is missing, connect
|
||||
* rejects), the executor MUST STOP and flag a BLOCKER in the 17-02 SUMMARY
|
||||
* rather than pulling the Phase 19 custom server.ts work forward. Do NOT
|
||||
* silently swallow errors and mark the test pending.
|
||||
*
|
||||
* DO NOT install @modelcontextprotocol/sdk in this wave. That happens in 17-02.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Runtime guard: detect whether the SDK is installed before importing.
|
||||
//
|
||||
// The /* @vite-ignore */ comment suppresses Vite's static import-analysis
|
||||
// transform error for an unresolved specifier — the import is evaluated at
|
||||
// runtime only, so it throws naturally when the package is absent rather than
|
||||
// crashing the transform step.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SDK_HTTP_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
const SDK_MCP_SPECIFIER = "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
|
||||
async function sdkAvailable(): Promise<boolean> {
|
||||
try {
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_HTTP_SPECIFIER);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spike suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("Transport spike: @modelcontextprotocol/sdk web-standard transport", () => {
|
||||
it(
|
||||
"WebStandardStreamableHTTPServerTransport and McpServer import, instantiate, and connect (or skip if SDK not installed)",
|
||||
async () => {
|
||||
const available = await sdkAvailable();
|
||||
|
||||
if (!available) {
|
||||
// SDK not yet installed (Wave 0 state) — skip cleanly.
|
||||
// Wave 1 (17-02) installs the package; this test will go green then.
|
||||
console.error(
|
||||
"[17-01 spike] @modelcontextprotocol/sdk not installed yet — install in 17-02"
|
||||
);
|
||||
// Return early — test body is a no-op at this wave; no assertions fire.
|
||||
return;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// From here onward: SDK IS installed. All assertions are mandatory.
|
||||
// Any failure -> BLOCKER in 17-02 SUMMARY.
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
const { WebStandardStreamableHTTPServerTransport } =
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_HTTP_SPECIFIER) as {
|
||||
WebStandardStreamableHTTPServerTransport: new (opts: {
|
||||
sessionIdGenerator: undefined;
|
||||
}) => {
|
||||
handleRequest: (req: Request) => Promise<Response>;
|
||||
start: () => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
const { McpServer } =
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_MCP_SPECIFIER) as {
|
||||
McpServer: new (info: { name: string; version: string }) => {
|
||||
connect: (transport: unknown) => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
// 1. Both exports must be constructor functions
|
||||
expect(typeof WebStandardStreamableHTTPServerTransport).toBe("function");
|
||||
expect(typeof McpServer).toBe("function");
|
||||
|
||||
// 2. Construct McpServer — empty capabilities (Phase 17 registers no tools/resources)
|
||||
const mcpServer = new McpServer({
|
||||
name: "worldwideview",
|
||||
version: "test",
|
||||
});
|
||||
expect(mcpServer).toBeTruthy();
|
||||
|
||||
// 3. Construct transport in STATELESS mode (D-17-04: sessionIdGenerator: undefined)
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
});
|
||||
expect(transport).toBeTruthy();
|
||||
|
||||
// 4. Transport must expose handleRequest (Web Standard Request -> Promise<Response>)
|
||||
expect(typeof transport.handleRequest).toBe("function");
|
||||
|
||||
// 5. Transport must expose start (Transport interface contract)
|
||||
expect(typeof transport.start).toBe("function");
|
||||
|
||||
// 6. mcpServer.connect(transport) must resolve without throwing.
|
||||
// This is the critical proof: the SDK does not require a custom server.ts
|
||||
// to wire McpServer + WebStandardStreamableHTTPServerTransport.
|
||||
await expect(mcpServer.connect(transport)).resolves.not.toThrow();
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET } from "./route";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn().mockResolvedValue(null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
getEntitiesInRegion: vi.fn(),
|
||||
}));
|
||||
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
|
||||
function makeRequest(params: Record<string, string> = {}): NextRequest {
|
||||
const url = new URL("http://localhost/api/v1/entities/region");
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return new NextRequest(url.toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API-01 — GET /api/v1/entities/region
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/v1/entities/region", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 400 when bounding box params are missing/NaN (?north=abc)", async () => {
|
||||
const req = makeRequest({ north: "abc", south: "0", east: "0", west: "0" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 when only partial bounds provided (missing west)", async () => {
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 200 with entities, count, and bounds when valid", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue([entity]);
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("entities");
|
||||
expect(body).toHaveProperty("count");
|
||||
expect(body).toHaveProperty("bounds");
|
||||
expect(body.bounds).toEqual({ north: 52, south: 50, east: 1, west: -1 });
|
||||
});
|
||||
|
||||
it("passes pluginId to getEntitiesInRegion when provided", async () => {
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1", pluginId: "my-plugin" });
|
||||
await GET(req);
|
||||
expect(vi.mocked(getEntitiesInRegion)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "my-plugin" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session cookie PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Entity data is global/public (plugin-sourced, shared across all users), so userId
|
||||
// gates access (authn) but is intentionally not a query filter -- there is no per-user
|
||||
// entity ownership to scope by.
|
||||
|
||||
const { searchParams } = request.nextUrl;
|
||||
const north = parseFloat(searchParams.get("north") ?? "");
|
||||
const south = parseFloat(searchParams.get("south") ?? "");
|
||||
const east = parseFloat(searchParams.get("east") ?? "");
|
||||
const west = parseFloat(searchParams.get("west") ?? "");
|
||||
|
||||
if (isNaN(north) || isNaN(south) || isNaN(east) || isNaN(west)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing or invalid bounding box parameters (north, south, east, west)" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (north < -90 || north > 90 || south < -90 || south > 90) {
|
||||
return NextResponse.json(
|
||||
{ error: "north and south must be within [-90, 90]" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (east < -180 || east > 180 || west < -180 || west > 180) {
|
||||
return NextResponse.json(
|
||||
{ error: "east and west must be within [-180, 180]" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const pluginId = searchParams.get("pluginId") ?? undefined;
|
||||
const rawLimit = searchParams.get("limit");
|
||||
const parsedLimit = rawLimit !== null ? parseInt(rawLimit, 10) : NaN;
|
||||
const limit = Math.min(Number.isNaN(parsedLimit) ? 100 : parsedLimit, 1000);
|
||||
|
||||
try {
|
||||
const entities = await getEntitiesInRegion({ north, south, east, west, pluginId, limit });
|
||||
return NextResponse.json({
|
||||
entities,
|
||||
count: entities.length,
|
||||
bounds: { north, south, east, west },
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Internal server error";
|
||||
if (message.includes("Invalid bounding box")) {
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
console.error("[entities/region] GET error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET } from "./route";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn().mockResolvedValue(null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
searchEntities: vi.fn(),
|
||||
}));
|
||||
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { searchEntities } from "@/lib/data-query/service";
|
||||
|
||||
function makeRequest(params: Record<string, string> = {}): NextRequest {
|
||||
const url = new URL("http://localhost/api/v1/entities/search");
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return new NextRequest(url.toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API-01 — GET /api/v1/entities/search
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/v1/entities/search", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(searchEntities).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
const req = makeRequest({ q: "test" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 400 when q param is missing", async () => {
|
||||
const req = makeRequest();
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 200 with entities and count when valid", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(searchEntities).mockResolvedValue([entity]);
|
||||
const req = makeRequest({ q: "test" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("entities");
|
||||
expect(body).toHaveProperty("count", 1);
|
||||
expect(body).toHaveProperty("query", "test");
|
||||
});
|
||||
|
||||
it("passes pluginId to searchEntities when provided", async () => {
|
||||
const req = makeRequest({ q: "thing", pluginId: "my-plugin" });
|
||||
await GET(req);
|
||||
expect(vi.mocked(searchEntities)).toHaveBeenCalledWith(
|
||||
"thing",
|
||||
"my-plugin",
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("passes limit capped at 100 when ?limit=999 is given", async () => {
|
||||
const req = makeRequest({ q: "thing", limit: "999" });
|
||||
await GET(req);
|
||||
const callArgs = vi.mocked(searchEntities).mock.calls[0];
|
||||
expect(callArgs[2]).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { searchEntities } from "@/lib/data-query/service";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session cookie PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Entity data is global/public (plugin-sourced, shared across all users), so userId
|
||||
// gates access (authn) but is intentionally not a query filter -- there is no per-user
|
||||
// entity ownership to scope by.
|
||||
|
||||
const { searchParams } = request.nextUrl;
|
||||
const q = searchParams.get("q");
|
||||
if (!q || q.trim() === "") {
|
||||
return NextResponse.json({ error: "Missing query parameter: q" }, { status: 400 });
|
||||
}
|
||||
|
||||
const pluginId = searchParams.get("pluginId") ?? undefined;
|
||||
const rawLimit = searchParams.get("limit");
|
||||
const parsed = rawLimit !== null ? parseInt(rawLimit, 10) : NaN;
|
||||
const limit = Math.min(Number.isNaN(parsed) ? 20 : parsed, 100);
|
||||
|
||||
try {
|
||||
const entities = await searchEntities(q, pluginId, limit);
|
||||
return NextResponse.json({
|
||||
entities,
|
||||
count: entities.length,
|
||||
query: q,
|
||||
...(pluginId !== undefined && { pluginId }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[entities/search] GET error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,8 @@ export function PluginIcon({ icon, size = 18, color }: PluginIconProps) {
|
||||
if (typeof icon === "string") {
|
||||
const Resolved = icons[icon as keyof typeof icons] as LucideIcon | undefined;
|
||||
if (Resolved) return <Resolved size={size} color={color} />;
|
||||
// Emoji: render as text. Unresolved ASCII icon name: render fallback so stale names don't leak as text.
|
||||
if (/[^\x00-\x7F]/.test(icon)) return <span>{icon}</span>;
|
||||
return <FallbackIcon size={size} />;
|
||||
// Treat as emoji or text fallback
|
||||
return <span>{icon}</span>;
|
||||
}
|
||||
|
||||
const IconComponent = icon;
|
||||
|
||||
@@ -249,7 +249,7 @@ export function ApiKeysTab() {
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
Service Keys
|
||||
Your API Keys
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
|
||||
Optional — if set, your key is used instead of the shared default.
|
||||
|
||||
@@ -36,7 +36,6 @@ import { FeedbackDialog } from "@/components/common/FeedbackDialog";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
import { injectHostGlobals } from "@/core/plugins/hostGlobals";
|
||||
import { getDisabledPluginIds } from "@/core/plugins/pluginPreferences";
|
||||
import { initLogCatcher } from "@/lib/logCatcher";
|
||||
import { MobileCameraStats } from "./MobileCameraStats";
|
||||
import { MobileHudBar } from "./MobileHudBar";
|
||||
@@ -89,7 +88,17 @@ export function AppShell() {
|
||||
await injectHostGlobals();
|
||||
setHostReady(true);
|
||||
|
||||
const disabledIds = getDisabledPluginIds();
|
||||
// Fetch disabled built-in plugins before registration
|
||||
let disabledIds = new Set<string>();
|
||||
try {
|
||||
const res = await fetch("/api/marketplace/disabled-builtins");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
disabledIds = new Set<string>(data.disabledIds ?? []);
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — load all built-ins if endpoint fails
|
||||
}
|
||||
|
||||
// Setup demo defaults
|
||||
const demoDefaultPlugins = new Set<string>();
|
||||
|
||||
@@ -15,6 +15,7 @@ export function BottomPanelManager() {
|
||||
|
||||
const [mountedPanel, setMountedPanel] = useState<string | null>(activeBottomPanel);
|
||||
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const resizeRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Get all registered plugins that provide a bottom panel component
|
||||
@@ -38,27 +39,41 @@ 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).
|
||||
const handleResizePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
// Handle mouse drag for resizing the panel
|
||||
useEffect(() => {
|
||||
if (!isDragging) {
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
return;
|
||||
}
|
||||
|
||||
document.body.classList.add("is-dragging-bottom-panel");
|
||||
};
|
||||
|
||||
const handleResizePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
|
||||
const newHeight = window.innerHeight - e.clientY;
|
||||
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
};
|
||||
const handleMove = (clientY: number) => {
|
||||
// Calculate new height based on distance from bottom of window
|
||||
const newHeight = window.innerHeight - clientY;
|
||||
// Clamp between min 120px and max window height - 100px
|
||||
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
};
|
||||
|
||||
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
};
|
||||
const handleMouseMove = (e: MouseEvent) => handleMove(e.clientY);
|
||||
const handlePointerMove = (e: PointerEvent) => handleMove(e.clientY);
|
||||
|
||||
const handleEnd = () => setIsDragging(false);
|
||||
|
||||
window.addEventListener("mousemove", handleMouseMove);
|
||||
window.addEventListener("mouseup", handleEnd);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handleEnd);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", handleMouseMove);
|
||||
window.removeEventListener("mouseup", handleEnd);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handleEnd);
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
};
|
||||
}, [isDragging, setBottomPanelHeight]);
|
||||
|
||||
// Dynamically push sidebars up based on bottom panel height
|
||||
useEffect(() => {
|
||||
@@ -167,14 +182,12 @@ export function BottomPanelManager() {
|
||||
>
|
||||
{mountedPanel && (
|
||||
<>
|
||||
<div
|
||||
className="bottom-panel-resize-handle"
|
||||
<div
|
||||
className="bottom-panel-resize-handle"
|
||||
data-testid="bottom-panel-resize-handle"
|
||||
ref={resizeRef}
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerUp}
|
||||
onPointerCancel={handleResizePointerUp}
|
||||
onMouseDown={() => setIsDragging(true)}
|
||||
onPointerDown={() => setIsDragging(true)}
|
||||
>
|
||||
<div className="resize-grip" />
|
||||
</div>
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file ConnectAgentHelper.tsx
|
||||
* @description "Connect your agent" helper rendered inside the "API & MCP Access"
|
||||
* section. Shows the per-edition /api/mcp URL, a copy-paste mcpServers JSON block
|
||||
* (Bearer token in Authorization HEADER -- never in the URL), a generic Manual
|
||||
* block, and a copy-paste agent-capabilities prompt. The Claude Code CLI snippet
|
||||
* is deferred ("coming soon").
|
||||
*
|
||||
* Security invariant (CONNECT-01 / T-17-04): the token appears ONLY in the
|
||||
* Authorization header value inside the JSON/Manual blocks. It is NEVER placed
|
||||
* in the mcpUrl string or any query parameter.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { Copy, Check, Terminal } from "lucide-react";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
const PLACEHOLDER_TOKEN = "wwv_<prefix>.<secret>";
|
||||
|
||||
/**
|
||||
* Resolve the /api/mcp base URL per edition (D-17-10).
|
||||
* - local -> http://localhost:3000/api/mcp (no port-hardcode: Next.js default)
|
||||
* - cloud -> NEXT_PUBLIC_MCP_API_URL ?? https://api.worldmonitor.app/api/mcp
|
||||
* - demo -> component is never rendered (gated by the !isDemo wrapper in Header)
|
||||
*
|
||||
* We derive the local URL from the browser origin at runtime so the component
|
||||
* works even if the dev server is on a non-3000 port.
|
||||
*/
|
||||
function resolveMcpUrl(): string {
|
||||
if (isCloud) {
|
||||
return (
|
||||
process.env.NEXT_PUBLIC_MCP_API_URL ??
|
||||
"https://api.worldmonitor.app/api/mcp"
|
||||
);
|
||||
}
|
||||
// local: use the current page origin so the port is derived, not hardcoded.
|
||||
if (typeof window !== "undefined") {
|
||||
return `${window.location.origin}/api/mcp`;
|
||||
}
|
||||
// SSR fallback (should not be reached for a "use client" component).
|
||||
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)
|
||||
// Tool-agnostic: Phase 17 ships no tools; tools arrive in Phase 18+.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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 currently live and authenticated. WWV is preparing to expose tools and
|
||||
resources for querying globe entities, plugins, and live data feeds in upcoming releases. Once
|
||||
tools are available you will be able to list entities, search by geospatial bounds, inspect plugin
|
||||
configurations, and interact with live data streams.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use this
|
||||
connection to guide them through the WWV interface and surface live data as tools become available.`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ConnectAgentHelperProps {
|
||||
token?: string | null;
|
||||
}
|
||||
|
||||
export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
|
||||
const mcpUrl = resolveMcpUrl();
|
||||
// SECURITY: displayToken is ONLY placed in the Authorization header value.
|
||||
// It is never concatenated into mcpUrl or any query string.
|
||||
const displayToken = token ?? PLACEHOLDER_TOKEN;
|
||||
|
||||
// mcpServers JSON for Claude Desktop / Cursor / VS Code (D-17-09, raw-SDK Streamable HTTP form).
|
||||
// Uses `headers.Authorization` -- NOT `type: "sse"` + `env.AUTHORIZATION` (superseded research form).
|
||||
const mcpServersJson = JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
worldwideview: {
|
||||
url: mcpUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${displayToken}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
const authHeaderValue = `Bearer ${displayToken}`;
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: "var(--space-lg)" }}>
|
||||
<div style={{
|
||||
borderTop: "1px solid var(--border-subtle)",
|
||||
paddingTop: "var(--space-md)",
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 13, fontWeight: 500, color: "var(--text-primary)", marginBottom: "var(--space-xs)" }}>
|
||||
Connect your agent
|
||||
</div>
|
||||
<div style={mutedMicro}>
|
||||
Use the URL and token below to connect Claude Desktop, Cursor, or VS Code to this globe.
|
||||
</div>
|
||||
|
||||
{/* Section: mcpServers JSON (CONNECT-02) */}
|
||||
<div style={subHeaderStyle}>Claude Desktop / Cursor / VS Code</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
Paste into your client's MCP config file. The token sits in the Authorization header,
|
||||
never in the URL.
|
||||
</div>
|
||||
<CopyField
|
||||
label="mcpServers config block"
|
||||
value={mcpServersJson}
|
||||
multiline
|
||||
/>
|
||||
|
||||
{/* Section: Manual block */}
|
||||
<div style={subHeaderStyle}>Manual / Custom Client</div>
|
||||
<CopyField label="Endpoint URL" value={mcpUrl} />
|
||||
<CopyField label="Authorization header value" value={authHeaderValue} />
|
||||
|
||||
{/* Section: Prompt for your agent (CONNECT-03) */}
|
||||
<div style={subHeaderStyle}>Prompt for your agent</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
Paste this into your agent's system prompt or first message to describe WWV.
|
||||
</div>
|
||||
<CopyField label="Capabilities prompt" value={AGENT_PROMPT} multiline />
|
||||
|
||||
{/* Section: Claude Code CLI -- deferred (D-17-08) */}
|
||||
<div style={subHeaderStyle}>Claude Code CLI</div>
|
||||
<div style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-sm) var(--space-md)",
|
||||
}}
|
||||
>
|
||||
<Terminal size={12} style={{ color: "var(--text-muted)", flexShrink: 0 }} />
|
||||
<span style={mutedMicro}>
|
||||
Claude Code CLI support is coming soon. Use the mcpServers JSON block above in the
|
||||
meantime.
|
||||
</span>
|
||||
<span style={{
|
||||
marginLeft: "auto",
|
||||
fontSize: 10,
|
||||
color: "var(--text-muted)",
|
||||
background: "var(--bg-secondary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "1px 6px",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
Coming soon
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import Image from "next/image";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { SearchBar } from "./SearchBar";
|
||||
import { ApiKeysTab } from "./ApiKeysTab";
|
||||
import { PersonalApiKeysSection } from "./PersonalApiKeysSection";
|
||||
import "./timeSelect.css";
|
||||
|
||||
const REGIONS = [
|
||||
@@ -434,7 +433,7 @@ export function Header() {
|
||||
marginBottom: "16px",
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>Keys & Access</h2>
|
||||
<h2 style={{ margin: 0 }}>API Keys</h2>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
@@ -446,12 +445,6 @@ export function Header() {
|
||||
</div>
|
||||
|
||||
<ApiKeysTab />
|
||||
{!isDemo && (
|
||||
<>
|
||||
<hr style={{ border: "none", borderTop: "1px solid var(--border-subtle)", margin: "var(--space-lg) 0" }} />
|
||||
<PersonalApiKeysSection />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file PersonalApiKeysSection.tsx
|
||||
* @description The "API & MCP Access" section of the "Keys & Access" modal.
|
||||
* Lists the signed-in user's personal bearer keys and supports generate
|
||||
* (one-time reveal), inline-confirm revoke, and a max-3 disabled state.
|
||||
* Consumes the session-authenticated /api/api-keys routes. Vanilla CSS-in-JS.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
KeyRound, Plus, Trash2, AlertTriangle, Loader,
|
||||
} from "lucide-react";
|
||||
import { sectionHeaderStyle } from "../panels/DataConfig/sharedStyles";
|
||||
import { ConnectAgentHelper } from "./ConnectAgentHelper";
|
||||
|
||||
type KeyRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
prefix: string;
|
||||
createdAt: string;
|
||||
lastUsedAt: string | null;
|
||||
};
|
||||
|
||||
const MAX_KEYS = 3;
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
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",
|
||||
};
|
||||
|
||||
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 errorText: React.CSSProperties = { fontSize: 11, color: "#ef4444" };
|
||||
const iconBtn: React.CSSProperties = {
|
||||
background: "none", border: "none", cursor: "pointer",
|
||||
padding: "var(--space-xs)", display: "flex", alignItems: "center",
|
||||
};
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
return Number.isNaN(d.getTime()) ? "unknown" : d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function formatRelative(iso: string | null): string {
|
||||
if (!iso) return "Never used";
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return "Never used";
|
||||
const days = Math.floor((Date.now() - then) / 86400000);
|
||||
if (days <= 0) return "Last used today";
|
||||
if (days === 1) return "Last used 1 day ago";
|
||||
return `Last used ${days} days ago`;
|
||||
}
|
||||
|
||||
function KeyRow({
|
||||
record, confirming, onAskRevoke, onCancelRevoke, onConfirmRevoke, isLast,
|
||||
}: {
|
||||
record: KeyRecord;
|
||||
confirming: boolean;
|
||||
onAskRevoke: () => void;
|
||||
onCancelRevoke: () => void;
|
||||
onConfirmRevoke: () => void;
|
||||
isLast: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "var(--space-sm)",
|
||||
padding: "var(--space-sm) 0",
|
||||
borderBottom: isLast ? "none" : "1px solid var(--border-subtle)",
|
||||
}}
|
||||
>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ fontSize: 14, color: "var(--text-primary)", fontWeight: 400 }}>{record.name}</div>
|
||||
<div style={mutedMicro}>
|
||||
{`Created ${formatDate(record.createdAt)}`}
|
||||
{" · "}
|
||||
{formatRelative(record.lastUsedAt)}
|
||||
</div>
|
||||
</div>
|
||||
{confirming ? (
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-xs)" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onConfirmRevoke}
|
||||
style={{ ...iconBtn, color: "#ef4444", fontSize: 11, gap: "var(--space-xs)" }}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Revoke?
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancelRevoke}
|
||||
style={{ ...iconBtn, color: "var(--text-muted)", fontSize: 11 }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAskRevoke}
|
||||
aria-label="Revoke key"
|
||||
title="Revoke key"
|
||||
style={{ ...iconBtn, color: "var(--text-muted)" }}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PersonalApiKeysSection() {
|
||||
const [keys, setKeys] = useState<KeyRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [generateError, setGenerateError] = useState("");
|
||||
const [revealToken, setRevealToken] = useState<string | null>(null);
|
||||
const [revokeConfirm, setRevokeConfirm] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/api-keys")
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.json();
|
||||
})
|
||||
.then((data) => setKeys(data.keys ?? []))
|
||||
.catch(() => setError("Could not load keys. Try closing and reopening this panel."))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const atLimit = keys.length >= MAX_KEYS;
|
||||
|
||||
async function handleGenerate() {
|
||||
if (generating || atLimit) return;
|
||||
setGenerating(true);
|
||||
setGenerateError("");
|
||||
try {
|
||||
const res = await fetch("/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name.trim() }),
|
||||
});
|
||||
if (res.status === 422) {
|
||||
setGenerateError("Maximum of 3 keys reached");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
setGenerateError("Failed to generate key. Please try again.");
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
const created: KeyRecord = {
|
||||
id: data.key.id,
|
||||
name: data.key.name,
|
||||
prefix: data.key.prefix ?? "",
|
||||
createdAt: data.key.createdAt,
|
||||
lastUsedAt: null,
|
||||
};
|
||||
setKeys((prev) => [created, ...prev]);
|
||||
setRevealToken(data.key.fullToken);
|
||||
setName("");
|
||||
setCopied(false);
|
||||
} catch {
|
||||
setGenerateError("Failed to generate key. Please try again.");
|
||||
} finally {
|
||||
setGenerating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevoke(id: string) {
|
||||
const previous = keys;
|
||||
setKeys((prev) => prev.filter((k) => k.id !== id));
|
||||
setRevokeConfirm(null);
|
||||
try {
|
||||
const res = await fetch(`/api/api-keys/${id}`, { method: "DELETE" });
|
||||
if (!res.ok) setKeys(previous);
|
||||
} catch {
|
||||
setKeys(previous);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopy() {
|
||||
if (!revealToken) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(revealToken);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
} catch {
|
||||
setGenerateError("Could not copy to clipboard. Select and copy manually.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
|
||||
|
||||
<div style={sectionHeaderStyle}>
|
||||
<KeyRound size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
API & MCP Access
|
||||
</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-md)" }}>
|
||||
Personal bearer keys for authenticating API and MCP requests. Stored server-side.
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div style={{ display: "flex", justifyContent: "center", color: "var(--text-muted)", padding: "var(--space-md) 0" }}>
|
||||
<Loader size={14} style={{ animation: "spin 1s linear infinite" }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && <div style={errorText}>{error}</div>}
|
||||
|
||||
{!loading && !error && keys.length === 0 && (
|
||||
<div style={{
|
||||
display: "flex", flexDirection: "column", alignItems: "center",
|
||||
gap: "var(--space-md)", padding: "var(--space-xl) 0",
|
||||
}}
|
||||
>
|
||||
<KeyRound size={24} style={{ color: "var(--text-muted)" }} />
|
||||
<div style={{ fontSize: 14, color: "var(--text-muted)", fontWeight: 400 }}>No API keys yet</div>
|
||||
<div style={mutedMicro}>Generate a key to authenticate API and MCP requests.</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && keys.length > 0 && (
|
||||
<div style={{ marginBottom: "var(--space-md)" }}>
|
||||
{keys.map((k, i) => (
|
||||
<KeyRow
|
||||
key={k.id}
|
||||
record={k}
|
||||
isLast={i === keys.length - 1}
|
||||
confirming={revokeConfirm === k.id}
|
||||
onAskRevoke={() => setRevokeConfirm(k.id)}
|
||||
onCancelRevoke={() => setRevokeConfirm(null)}
|
||||
onConfirmRevoke={() => handleRevoke(k.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && (
|
||||
<>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
placeholder="Name this key (optional)"
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
style={{ ...inputStyle, fontFamily: "inherit", marginBottom: "var(--space-sm)" }}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleGenerate}
|
||||
disabled={atLimit || generating}
|
||||
style={{
|
||||
...buttonStyle,
|
||||
opacity: atLimit || generating ? 0.4 : 1,
|
||||
cursor: atLimit || generating ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<Plus size={12} />
|
||||
Generate API Key
|
||||
</button>
|
||||
{atLimit && (
|
||||
<div style={{ fontSize: 10, color: "var(--text-muted)", marginTop: "var(--space-xs)" }}>
|
||||
Maximum of 3 keys reached
|
||||
</div>
|
||||
)}
|
||||
{generateError && (
|
||||
<div style={{ ...errorText, marginTop: "var(--space-xs)" }}>{generateError}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{revealToken && (
|
||||
<div style={{ marginTop: "var(--space-md)" }}>
|
||||
<div style={{
|
||||
display: "flex", alignItems: "flex-start", gap: "var(--space-xs)",
|
||||
background: "rgba(245,158,11,0.1)", border: "1px solid rgba(245,158,11,0.3)",
|
||||
borderRadius: "var(--radius-sm)", padding: "var(--space-sm) var(--space-md)",
|
||||
marginBottom: "var(--space-sm)",
|
||||
}}
|
||||
>
|
||||
<AlertTriangle size={14} style={{ color: "var(--accent-amber)", flexShrink: 0, marginTop: 1 }} />
|
||||
<span style={{ fontSize: 11, color: "var(--accent-amber)", lineHeight: 1.5 }}>
|
||||
Copy this key now. You won't be able to see it again. Never commit it to source
|
||||
control or share it publicly.
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "var(--space-xs)" }}>
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={revealToken}
|
||||
style={{ ...inputStyle, fontFamily: "var(--font-mono)" }}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
style={{ ...buttonStyle, color: copied ? "#22c55e" : "var(--text-primary)" }}
|
||||
>
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRevealToken(null)}
|
||||
style={{ ...buttonStyle, width: "100%", justifyContent: "center", marginTop: "var(--space-sm)" }}
|
||||
>
|
||||
Done, I've saved it
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConnectAgentHelper token={revealToken} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -74,19 +74,6 @@
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
/* ─── Local Icon ─────────────────────────────────── */
|
||||
.layer-item__local-icon-wrapper {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.layer-item__local-icon {
|
||||
color: var(--accent-cyan);
|
||||
flex-shrink: 0;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* ─── Unverified Icon ────────────────────────────── */
|
||||
.layer-item__unverified-icon-wrapper {
|
||||
position: relative;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { ShieldAlert, Wrench } from "lucide-react";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import { Tooltip } from "@/components/ui/Tooltip";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
@@ -27,46 +27,29 @@ const CATEGORY_LABELS: Record<string, string> = {
|
||||
custom: "Custom",
|
||||
};
|
||||
|
||||
// ─── Source / Trust Helpers ─────────────────────────────────
|
||||
// ─── Trust Helpers ──────────────────────────────────────────
|
||||
|
||||
function isLocalPlugin(pluginId: string): boolean {
|
||||
type TrustTier = "built-in" | "verified" | "unverified";
|
||||
|
||||
function getTrust(pluginId: string): TrustTier {
|
||||
const manifest = pluginManager.getManifest(pluginId);
|
||||
if (!manifest) return true;
|
||||
const entry = manifest.entry ?? "";
|
||||
return entry.startsWith("/plugins-local/") || entry.startsWith("http://localhost") || entry.startsWith("http://127.0.0.1");
|
||||
return manifest?.trust ?? "unverified";
|
||||
}
|
||||
|
||||
function TrustIcon({ pluginId, pluginName }: { pluginId: string; pluginName: string }) {
|
||||
if (isLocalPlugin(pluginId)) {
|
||||
return (
|
||||
<Tooltip content={`Local plugin: ${pluginName}`}>
|
||||
<span className="layer-item__local-icon-wrapper">
|
||||
<Wrench
|
||||
size={11}
|
||||
className="layer-item__local-icon"
|
||||
aria-label="Local plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
function TrustIcon({ trust }: { trust: TrustTier }) {
|
||||
if (trust !== "unverified") return null;
|
||||
|
||||
const manifest = pluginManager.getManifest(pluginId);
|
||||
if (manifest?.trust === "unverified") {
|
||||
return (
|
||||
<Tooltip content="Unverified plugin, use at your own risk">
|
||||
<span className="layer-item__unverified-icon-wrapper">
|
||||
<ShieldAlert
|
||||
size={12}
|
||||
className="layer-item__unverified-icon"
|
||||
aria-label="Unverified plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
return (
|
||||
<Tooltip content="Unverified plugin, use at your own risk">
|
||||
<span className="layer-item__unverified-icon-wrapper">
|
||||
<ShieldAlert
|
||||
size={12}
|
||||
className="layer-item__unverified-icon"
|
||||
aria-label="Unverified plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── LayerItem Component ────────────────────────────────────
|
||||
@@ -105,6 +88,8 @@ export function LayerItem({
|
||||
onToggle,
|
||||
onSelect,
|
||||
}: LayerItemProps) {
|
||||
const trust = getTrust(plugin.id);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`layer-item ${isSelected ? "layer-item--selected" : ""}`}
|
||||
@@ -117,7 +102,7 @@ export function LayerItem({
|
||||
<div className="layer-item__info">
|
||||
<div className="layer-item__header">
|
||||
<span className="layer-item__name">{plugin.name}</span>
|
||||
<TrustIcon pluginId={plugin.id} pluginName={plugin.name} />
|
||||
<TrustIcon trust={trust} />
|
||||
</div>
|
||||
<div className="layer-item__desc">{plugin.description}</div>
|
||||
<div className="layer-item__footer">
|
||||
|
||||
@@ -69,7 +69,6 @@
|
||||
.plugin-item__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 1px;
|
||||
}
|
||||
@@ -78,7 +77,9 @@
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.plugin-item__version {
|
||||
@@ -183,7 +184,6 @@
|
||||
text-decoration: none;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all var(--duration-normal) var(--ease-spring);
|
||||
flex-shrink: 0%;
|
||||
|
||||
@@ -11,16 +11,12 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
Trash2, ExternalLink, RefreshCw, Download, PowerOff, Power,
|
||||
ShieldCheck, ShieldAlert, HardDrive
|
||||
ShieldCheck, ShieldAlert, Shield
|
||||
} from "lucide-react";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import type { ComponentType } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { getDisabledPluginIds, setPluginDisabled } from "@/core/plugins/pluginPreferences";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import { isPluginInstallEnabled } from "@/core/edition";
|
||||
import type { PluginManifest } from "@/core/plugins/PluginManifest";
|
||||
import "./PluginsTab.css";
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────
|
||||
@@ -39,9 +35,9 @@ function TrustBadge({ trust }: { trust: string }) {
|
||||
if (trust === "built-in") {
|
||||
return (
|
||||
<span className="trust-badge trust-badge--builtin">
|
||||
<HardDrive size={9} />
|
||||
<Shield size={9} />
|
||||
{' '}
|
||||
Local
|
||||
Built-in
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -100,9 +96,13 @@ function getTrust(record: PluginRecord): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getIcon(record: PluginRecord): string | ComponentType<{ size?: number; color?: string }> {
|
||||
function getIcon(record: PluginRecord): string {
|
||||
const managed = pluginManager.getPlugin(record.pluginId);
|
||||
if (managed) return managed.plugin.icon ?? "📦";
|
||||
if (managed) {
|
||||
return typeof managed.plugin.icon === "string"
|
||||
? managed.plugin.icon
|
||||
: "📦";
|
||||
}
|
||||
try {
|
||||
return JSON.parse(record.config).icon ?? "📦";
|
||||
} catch {
|
||||
@@ -120,11 +120,6 @@ function getName(record: PluginRecord): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getVersion(record: PluginRecord): string {
|
||||
if (record.version !== "built-in") return record.version;
|
||||
return pluginManager.getManifest(record.pluginId)?.version ?? "";
|
||||
}
|
||||
|
||||
// ─── PluginsTab ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -150,8 +145,7 @@ export function PluginsTab() {
|
||||
const dbPlugins: PluginRecord[] = data.plugins ?? [];
|
||||
const dbPluginMap = new Map(dbPlugins.map((p) => [p.pluginId, p]));
|
||||
|
||||
// Add built-in and local plugins that don't have a DB record yet
|
||||
const disabledIds = getDisabledPluginIds();
|
||||
// Add built-in and local plugins that don't have a DB record yet (enabled by default)
|
||||
const allManaged = pluginManager.getAllPlugins();
|
||||
for (const managed of allManaged) {
|
||||
if (!dbPluginMap.has(managed.plugin.id)) {
|
||||
@@ -160,16 +154,11 @@ export function PluginsTab() {
|
||||
version: "built-in",
|
||||
config: "{}",
|
||||
installedAt: new Date().toISOString(),
|
||||
enabled: !disabledIds.has(managed.plugin.id)
|
||||
enabled: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Apply localStorage disabled state to all records
|
||||
dbPlugins.forEach((p) => {
|
||||
if (disabledIds.has(p.pluginId)) p.enabled = false;
|
||||
});
|
||||
|
||||
setPlugins(dbPlugins);
|
||||
if (typeof data.canManagePlugins === "boolean") {
|
||||
setCanInstall(data.canManagePlugins);
|
||||
@@ -203,48 +192,32 @@ export function PluginsTab() {
|
||||
|
||||
const handleDisable = async (pluginId: string) => {
|
||||
setRemoving(pluginId);
|
||||
setPluginDisabled(pluginId, true);
|
||||
pluginManager.disablePlugin(pluginId);
|
||||
const state = useStore.getState();
|
||||
state.setLayerEnabled(pluginId, false);
|
||||
state.clearEntities(pluginId);
|
||||
state.setEntityCount(pluginId, 0);
|
||||
if (state.hoveredEntity?.pluginId === pluginId) state.setHoveredEntity(null, null);
|
||||
if (state.selectedEntity?.pluginId === pluginId) state.setSelectedEntity(null);
|
||||
setNeedsReload(true);
|
||||
trackEvent("plugin-disable", { plugin: pluginId });
|
||||
await loadPlugins();
|
||||
setRemoving(null);
|
||||
try {
|
||||
await fetch("/api/marketplace/disable", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId }),
|
||||
});
|
||||
trackEvent("plugin-disable", { plugin: pluginId });
|
||||
setNeedsReload(true);
|
||||
} catch {
|
||||
setRemoving(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEnable = async (pluginId: string) => {
|
||||
setRemoving(pluginId);
|
||||
setPluginDisabled(pluginId, false);
|
||||
setNeedsReload(false);
|
||||
|
||||
const alreadyRegistered = pluginManager.getPlugin(pluginId);
|
||||
if (!alreadyRegistered) {
|
||||
// Plugin was disabled at startup — its script was never loaded.
|
||||
// Hot-load the script so it's available; leave the layer toggle off.
|
||||
try {
|
||||
const res = await fetch("/api/marketplace/load");
|
||||
if (res.ok) {
|
||||
const { manifests } = await res.json() as { manifests: PluginManifest[] };
|
||||
const manifest = manifests.find((m) => m.id === pluginId);
|
||||
if (manifest) {
|
||||
await pluginManager.loadFromManifest(manifest);
|
||||
useStore.getState().initLayer(pluginId, false);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[PluginsTab] Failed to hot-load plugin:", pluginId, err);
|
||||
}
|
||||
try {
|
||||
await fetch("/api/marketplace/enable", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId }),
|
||||
});
|
||||
trackEvent("plugin-enable", { plugin: pluginId });
|
||||
setNeedsReload(true);
|
||||
} catch {
|
||||
setRemoving(null);
|
||||
}
|
||||
// Layer stays off — user controls it via the Data Layers toggle.
|
||||
|
||||
trackEvent("plugin-enable", { plugin: pluginId });
|
||||
await loadPlugins();
|
||||
setRemoving(null);
|
||||
};
|
||||
|
||||
const handleCheckUpdates = async () => {
|
||||
@@ -379,12 +352,10 @@ export function PluginsTab() {
|
||||
<span className="plugin-item__name">
|
||||
{getName(record)}
|
||||
</span>
|
||||
{getVersion(record) && (
|
||||
<span className="plugin-item__version">
|
||||
v
|
||||
{getVersion(record)}
|
||||
{record.version}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="plugin-item__meta">
|
||||
<TrustBadge trust={getTrust(record)} />
|
||||
@@ -444,12 +415,10 @@ export function PluginsTab() {
|
||||
<span className="plugin-item__name">
|
||||
{getName(record)}
|
||||
</span>
|
||||
{getVersion(record) && (
|
||||
<span className="plugin-item__version">
|
||||
v
|
||||
{getVersion(record)}
|
||||
{record.version}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="plugin-item__meta">
|
||||
<TrustBadge trust={getTrust(record)} />
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { IntelPropertyRow } from "./IntelPropertyRow";
|
||||
|
||||
function formatLocal(iso: string): string {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
day: "numeric", month: "2-digit", year: "numeric",
|
||||
hour: "numeric", minute: "2-digit", hour12: true, timeZoneName: "short",
|
||||
});
|
||||
}
|
||||
|
||||
function formatUtc(iso: string): string {
|
||||
return new Date(iso).toISOString().slice(0, 16).replace("T", " ") + " UTC";
|
||||
}
|
||||
|
||||
function formatRelative(iso: string): string {
|
||||
const diff = new Date(iso).getTime() - Date.now();
|
||||
const abs = Math.abs(diff);
|
||||
const future = diff > 0;
|
||||
if (abs < 60_000) return "just now";
|
||||
if (abs < 3_600_000) {
|
||||
const n = Math.round(abs / 60_000);
|
||||
return future ? `in ${n}m` : `${n}m ago`;
|
||||
}
|
||||
if (abs < 86_400_000) {
|
||||
const n = Math.round(abs / 3_600_000);
|
||||
return future ? `in ${n}h` : `${n}h ago`;
|
||||
}
|
||||
const n = Math.round(abs / 86_400_000);
|
||||
return future ? `in ${n}d` : `${n}d ago`;
|
||||
}
|
||||
|
||||
interface DatetimePropertyRowProps {
|
||||
label: string;
|
||||
iso: string;
|
||||
classNamePrefix?: string;
|
||||
}
|
||||
|
||||
export function DatetimePropertyRow({ label, iso, classNamePrefix = "intel-panel" }: DatetimePropertyRowProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
if (expanded) {
|
||||
return (
|
||||
<IntelPropertyRow label={label} isColumn classNamePrefix={classNamePrefix}>
|
||||
<span
|
||||
style={{ cursor: "pointer", fontWeight: 600 }}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
{formatLocal(iso)}
|
||||
</span>
|
||||
<span style={{ opacity: 0.6, fontSize: "0.85em" }}>{formatUtc(iso)}</span>
|
||||
<span style={{ opacity: 0.6, fontSize: "0.85em" }}>{formatRelative(iso)}</span>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IntelPropertyRow label={label} classNamePrefix={classNamePrefix}>
|
||||
<span
|
||||
style={{ cursor: "pointer", textDecoration: "underline dotted" }}
|
||||
onClick={() => setExpanded(true)}
|
||||
>
|
||||
{formatLocal(iso)}
|
||||
</span>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
@@ -11,8 +11,6 @@ import { ImageProperty } from './ImageProperty';
|
||||
import { UrlProperty } from './UrlProperty';
|
||||
import { LongTextProperty } from './LongTextProperty';
|
||||
import { IntelPropertyRow } from './IntelPropertyRow';
|
||||
import { DatetimePropertyRow } from "./DatetimePropertyRow";
|
||||
import { VideoProperty } from "./VideoProperty";
|
||||
|
||||
/**
|
||||
* @interface DynamicPropertiesRenderProps
|
||||
@@ -39,52 +37,6 @@ export function DynamicPropertiesRender({ entity, classNamePrefix = "intel-panel
|
||||
const label = key.replace(/_/g, " ");
|
||||
const stringValue = String(value);
|
||||
|
||||
// Tagged dispatch - explicit type prefix, checked before heuristics
|
||||
if (typeof value === "string") {
|
||||
if (value.startsWith("datetime:")) {
|
||||
return (
|
||||
<DatetimePropertyRow
|
||||
key={key}
|
||||
label={label}
|
||||
iso={value.slice(9)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("url:")) {
|
||||
return (
|
||||
<UrlProperty
|
||||
key={key}
|
||||
label={label}
|
||||
url={value.slice(4)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("image:")) {
|
||||
return (
|
||||
<ImageProperty
|
||||
key={key}
|
||||
label={label}
|
||||
imageUrl={value.slice(6)}
|
||||
entityId={entity.id}
|
||||
entityLabel={entity.label ?? ""}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("video:")) {
|
||||
return (
|
||||
<VideoProperty
|
||||
key={key}
|
||||
label={label}
|
||||
href={value.slice(6)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Identify property type
|
||||
const isImage = typeof value === "string" && key.toLowerCase().includes("image") && /^https?:\/\//i.test(value);
|
||||
const isUrl = !isImage && typeof value === "string" && /^https?:\/\//i.test(value);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { PlayCircle } from "lucide-react";
|
||||
import { IntelPropertyRow } from "./IntelPropertyRow";
|
||||
|
||||
interface VideoPropertyProps {
|
||||
label: string;
|
||||
href: string;
|
||||
classNamePrefix?: string;
|
||||
}
|
||||
|
||||
export function VideoProperty({ label, href, classNamePrefix = "intel-panel" }: VideoPropertyProps) {
|
||||
return (
|
||||
<IntelPropertyRow label={label} classNamePrefix={classNamePrefix}>
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--accent-cyan)" }}
|
||||
>
|
||||
<PlayCircle size={14} />
|
||||
Watch
|
||||
</a>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
@@ -34,11 +34,6 @@ import { useSatelliteFrustum } from "./hooks/useSatelliteFrustum";
|
||||
import { useTrailRendering } from "./hooks/useTrailRendering";
|
||||
import { useViewerInitialization } from "./hooks/useViewerInitialization";
|
||||
import { usePersistentDataSync } from "./hooks/usePersistentDataSync";
|
||||
import { useSessionId } from "./hooks/useSessionId";
|
||||
import { useGlobeStateSync } from "./hooks/useGlobeStateSync";
|
||||
import { useGlobeCommandBridge } from "./hooks/useGlobeCommandBridge";
|
||||
import { useMcpCatalogPublisher } from "./hooks/useMcpCatalogPublisher";
|
||||
import { useMcpRelayBridge } from "./hooks/useMcpRelayBridge";
|
||||
|
||||
/** Stable references */
|
||||
const CONTEXT_OPTIONS = { requestWebgl2: true, webgl: { antialias: true } } as const;
|
||||
@@ -125,11 +120,6 @@ enableLighting,
|
||||
|
||||
useSelectionAnchor(viewerRef.current, viewerReady, selectedEntity, lockedEntityId, selectionEntityRef, animatablesMapRef);
|
||||
useCameraSync(viewerRef.current, viewerReady, setCameraPosition, setFps);
|
||||
const sessionId = useSessionId();
|
||||
useGlobeStateSync(sessionId);
|
||||
useGlobeCommandBridge(sessionId);
|
||||
useMcpCatalogPublisher(sessionId);
|
||||
useMcpRelayBridge(sessionId);
|
||||
useCameraActions(viewerRef.current, viewerReady);
|
||||
useEntityRendering(viewerRef.current, viewerReady, visibleEntities, animatablesMapRef, hoveredEntityIdRef, sceneSettings);
|
||||
useModelRendering(viewerRef.current, viewerReady, animatablesMapRef);
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
/**
|
||||
* Contract tests for useGlobeCommandBridge (Phase 19b Wave 0).
|
||||
*
|
||||
* BRIDGE-01 through BRIDGE-07 are INTENTIONALLY RED in Wave 0 because the hook
|
||||
* still uses setInterval + pollOnce. Wave 1 rewrites the hook to use EventSource.
|
||||
*
|
||||
* BRIDGE-01 Hook opens EventSource to /api/globe/commands/stream?sessionId=... on mount
|
||||
* BRIDGE-02 pan command dispatched via onmessage -> dataBus.emit("cameraGoTo", ...)
|
||||
* BRIDGE-03 toggleLayer command dispatched via onmessage -> Zustand setLayerEnabled
|
||||
* BRIDGE-04 Unknown command type via onmessage -> nothing dispatched
|
||||
* BRIDGE-05 Empty sessionId -> EventSource never created
|
||||
* BRIDGE-06 Unmount -> EventSource.close() called
|
||||
* BRIDGE-07 onerror firing -> no throw
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useGlobeCommandBridge } from "./useGlobeCommandBridge";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock DataBus
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEmit } = vi.hoisted(() => ({
|
||||
mockEmit: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/data/DataBus", () => ({
|
||||
dataBus: {
|
||||
emit: mockEmit,
|
||||
},
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock Zustand store
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const {
|
||||
mockSetLayerEnabled,
|
||||
mockToggleLayer,
|
||||
mockSetTimeWindow,
|
||||
mockSetPlaybackMode,
|
||||
mockSetCurrentTime,
|
||||
} = vi.hoisted(() => ({
|
||||
mockSetLayerEnabled: vi.fn(),
|
||||
mockToggleLayer: vi.fn(),
|
||||
mockSetTimeWindow: vi.fn(),
|
||||
mockSetPlaybackMode: vi.fn(),
|
||||
mockSetCurrentTime: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/state/store", () => ({
|
||||
useStore: {
|
||||
getState: vi.fn(() => ({
|
||||
setLayerEnabled: mockSetLayerEnabled,
|
||||
toggleLayer: mockToggleLayer,
|
||||
setTimeWindow: mockSetTimeWindow,
|
||||
setPlaybackMode: mockSetPlaybackMode,
|
||||
setCurrentTime: mockSetCurrentTime,
|
||||
layers: {},
|
||||
})),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
const mockedUseStore = useStore as unknown as {
|
||||
getState: ReturnType<typeof vi.fn>;
|
||||
subscribe: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MockEventSource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let mockEs: MockEventSource;
|
||||
|
||||
class MockEventSource {
|
||||
url: string;
|
||||
onmessage: ((ev: MessageEvent) => void) | null = null;
|
||||
onerror: ((ev: Event) => void) | null = null;
|
||||
close = vi.fn();
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
||||
mockEs = this;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
// Install MockEventSource as the global before each test
|
||||
global.EventSource = MockEventSource as unknown as typeof EventSource;
|
||||
|
||||
// Restore getState return value after vi.resetAllMocks() wipes call history
|
||||
mockedUseStore.getState.mockReturnValue({
|
||||
setLayerEnabled: mockSetLayerEnabled,
|
||||
toggleLayer: mockToggleLayer,
|
||||
setTimeWindow: mockSetTimeWindow,
|
||||
setPlaybackMode: mockSetPlaybackMode,
|
||||
setCurrentTime: mockSetCurrentTime,
|
||||
layers: {},
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-01: EventSource connection on mount
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge EventSource connection (BRIDGE-01)", () => {
|
||||
it("opens an EventSource to /api/globe/commands/stream?sessionId=... on mount", () => {
|
||||
// Track construction via the mockEs reference populated by MockEventSource constructor
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
// mockEs is set by the MockEventSource constructor -- if hook never calls new EventSource,
|
||||
// mockEs will be undefined and these assertions fail (correct RED state).
|
||||
expect(mockEs).toBeDefined();
|
||||
expect(mockEs.url).toContain("/api/globe/commands/stream");
|
||||
expect(mockEs.url).toContain("sessionId=sess-1");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-02: pan command via onmessage -> cameraGoTo
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge pan dispatch (BRIDGE-02)", () => {
|
||||
it("emits cameraGoTo when a pan command arrives via onmessage", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onmessage?.(
|
||||
new MessageEvent("message", {
|
||||
data: JSON.stringify({
|
||||
commands: [{ type: "pan", lat: 1, lon: 2, alt: 3 }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(mockEmit).toHaveBeenCalledWith(
|
||||
"cameraGoTo",
|
||||
expect.objectContaining({ lat: 1, lon: 2, alt: 3 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-03: toggleLayer command via onmessage -> Zustand action
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge toggleLayer dispatch (BRIDGE-03)", () => {
|
||||
it("calls toggleLayer when a toggleLayer command arrives via onmessage", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onmessage?.(
|
||||
new MessageEvent("message", {
|
||||
data: JSON.stringify({
|
||||
commands: [{ type: "toggleLayer", layerId: "ais" }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const anyLayerAction =
|
||||
mockSetLayerEnabled.mock.calls.length > 0 ||
|
||||
mockToggleLayer.mock.calls.length > 0;
|
||||
expect(anyLayerAction).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-04: unknown command type -> nothing dispatched
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge invalid command filtering (BRIDGE-04)", () => {
|
||||
it("does not dispatch anything for an unknown command type arriving via onmessage", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onmessage?.(
|
||||
new MessageEvent("message", {
|
||||
data: JSON.stringify({
|
||||
commands: [{ type: "invalidCommand", foo: "bar" }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(mockEmit).not.toHaveBeenCalled();
|
||||
expect(mockSetLayerEnabled).not.toHaveBeenCalled();
|
||||
expect(mockToggleLayer).not.toHaveBeenCalled();
|
||||
expect(mockSetTimeWindow).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-05: empty sessionId -> EventSource never created
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge empty sessionId no-op (BRIDGE-05)", () => {
|
||||
it("never creates an EventSource when sessionId is empty string", () => {
|
||||
// Reset mockEs -- if hook creates an EventSource, MockEventSource constructor sets it
|
||||
(mockEs as MockEventSource | undefined) = undefined as unknown as MockEventSource;
|
||||
|
||||
renderHook(() => useGlobeCommandBridge(""));
|
||||
|
||||
// If EventSource was constructed, mockEs would be set
|
||||
expect(mockEs as MockEventSource | undefined).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-06: unmount -> EventSource.close() called
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge unmount cleanup (BRIDGE-06)", () => {
|
||||
it("calls EventSource.close() on unmount", () => {
|
||||
const { unmount } = renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
unmount();
|
||||
|
||||
expect(mockEs.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-07: onerror fires -> no throw
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge onerror resilience (BRIDGE-07)", () => {
|
||||
it("does not throw when onerror fires", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onerror?.(new Event("error"));
|
||||
});
|
||||
|
||||
// Reaching here without an unhandled exception is the assertion
|
||||
});
|
||||
});
|
||||
@@ -1,112 +0,0 @@
|
||||
import { useEffect } from "react";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
|
||||
function dispatchCommand(cmd: GlobeCommand): void {
|
||||
switch (cmd.type) {
|
||||
case "pan":
|
||||
dataBus.emit("cameraGoTo", {
|
||||
lat: cmd.lat,
|
||||
lon: cmd.lon,
|
||||
alt: cmd.alt,
|
||||
// cameraGoTo exposes maxPitch (a clamp), not a target pitch angle,
|
||||
// so cmd.pitch is intentionally not forwarded here.
|
||||
...(cmd.heading !== undefined ? { heading: cmd.heading } : {}),
|
||||
});
|
||||
break;
|
||||
|
||||
case "focusEntity":
|
||||
if (cmd.lat !== undefined && cmd.lon !== undefined) {
|
||||
dataBus.emit("cameraGoTo", {
|
||||
lat: cmd.lat,
|
||||
lon: cmd.lon,
|
||||
alt: 0,
|
||||
});
|
||||
} else if (cmd.entityId !== undefined) {
|
||||
// Entity-id-only resolution is not yet wired to the entity registry.
|
||||
// Provide lat/lon alongside entityId to trigger a camera move.
|
||||
console.warn(
|
||||
"[useGlobeCommandBridge] focusEntity by id not yet supported; provide lat/lon",
|
||||
cmd.entityId,
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case "toggleLayer": {
|
||||
const state = useStore.getState();
|
||||
if (cmd.enabled !== undefined) {
|
||||
state.setLayerEnabled(cmd.layerId, cmd.enabled);
|
||||
} else {
|
||||
state.toggleLayer(cmd.layerId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "setTimeline": {
|
||||
const state = useStore.getState();
|
||||
if (cmd.timeWindow !== undefined) {
|
||||
// cmd.timeWindow is narrowed to TimeWindowLiteral by isValidGlobeCommand.
|
||||
state.setTimeWindow(cmd.timeWindow);
|
||||
}
|
||||
if (cmd.isPlaybackMode !== undefined) {
|
||||
state.setPlaybackMode(cmd.isPlaybackMode);
|
||||
}
|
||||
if (cmd.currentTime !== undefined) {
|
||||
const d = new Date(cmd.currentTime);
|
||||
if (!Number.isNaN(d.getTime())) {
|
||||
state.setCurrentTime(d);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function useGlobeCommandBridge(sessionId: string): void {
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
const es = new EventSource(
|
||||
`/api/globe/commands/stream?sessionId=${encodeURIComponent(sessionId)}`,
|
||||
);
|
||||
|
||||
es.onmessage = (event: MessageEvent) => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(event.data as string);
|
||||
if (
|
||||
parsed !== null &&
|
||||
typeof parsed === "object" &&
|
||||
"commands" in parsed &&
|
||||
Array.isArray((parsed as { commands: unknown }).commands)
|
||||
) {
|
||||
(parsed as { commands: unknown[] }).commands
|
||||
.filter(isValidGlobeCommand)
|
||||
.forEach(dispatchCommand);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[useGlobeCommandBridge] Failed to parse SSE message:", err);
|
||||
}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
// onerror fires on the normal stream close too: the server ends each
|
||||
// stream at MAX_DURATION_MS (~16s), after which EventSource transparently
|
||||
// reconnects (readyState === CONNECTING). Only a terminal failure leaves
|
||||
// readyState === CLOSED -- e.g. a 401 because EventSource authenticates via
|
||||
// the NextAuth session cookie (it cannot send a Bearer header), so an
|
||||
// unauthenticated tab fails permanently rather than reconnecting.
|
||||
if (es.readyState === EventSource.CLOSED) {
|
||||
console.error(
|
||||
"[useGlobeCommandBridge] SSE stream closed without retry -- " +
|
||||
"is this tab signed in? EventSource auths via session cookie, not Bearer.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return () => {
|
||||
es.close();
|
||||
};
|
||||
}, [sessionId]);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useGlobeStateSync } from "./useGlobeStateSync";
|
||||
|
||||
vi.mock("@/lib/globeState", () => ({
|
||||
buildGlobeSnapshot: vi.fn(() => ({ marker: true })),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/state/store", () => {
|
||||
let listener: (() => void) | null = null;
|
||||
return {
|
||||
useStore: {
|
||||
getState: vi.fn(() => ({})),
|
||||
subscribe: vi.fn((cb: () => void) => {
|
||||
listener = cb;
|
||||
// Return unsubscribe function
|
||||
return () => { listener = null; };
|
||||
}),
|
||||
// Expose for triggering store changes in tests
|
||||
__triggerChange: () => { if (listener) listener(); },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Retrieve the mocked store for use in tests
|
||||
import { useStore } from "@/core/state/store";
|
||||
const mockStore = useStore as unknown as {
|
||||
getState: ReturnType<typeof vi.fn>;
|
||||
subscribe: ReturnType<typeof vi.fn>;
|
||||
__triggerChange: () => void;
|
||||
};
|
||||
|
||||
describe("useGlobeStateSync", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
global.fetch = vi.fn().mockResolvedValue({ ok: true });
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("performs no fetch when sessionId is empty (no-op gate)", async () => {
|
||||
renderHook(() => useGlobeStateSync(""));
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(15_000);
|
||||
});
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(mockStore.subscribe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("subscribes to the store and POSTs to /api/globe/state after 500ms debounce", async () => {
|
||||
renderHook(() => useGlobeStateSync("s1"));
|
||||
|
||||
// Drain the immediate initial push that fires on mount before asserting debounce behavior.
|
||||
await act(async () => {});
|
||||
(fetch as ReturnType<typeof vi.fn>).mockClear();
|
||||
|
||||
// Trigger a store change
|
||||
act(() => { mockStore.__triggerChange(); });
|
||||
|
||||
// Before debounce expires: no fetch yet
|
||||
act(() => { vi.advanceTimersByTime(400); });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
|
||||
// After debounce expires: one fetch
|
||||
await act(async () => { vi.advanceTimersByTime(200); });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
|
||||
const [url, init] = (fetch as ReturnType<typeof vi.fn>).mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe("/api/globe/state");
|
||||
expect(init.method).toBe("POST");
|
||||
expect(JSON.parse(init.body as string)).toMatchObject({ sessionId: "s1" });
|
||||
});
|
||||
|
||||
it("collapses multiple rapid changes within 500ms into a single fetch (debounce)", async () => {
|
||||
renderHook(() => useGlobeStateSync("s1"));
|
||||
|
||||
// Drain the immediate initial push that fires on mount before asserting debounce behavior.
|
||||
await act(async () => {});
|
||||
(fetch as ReturnType<typeof vi.fn>).mockClear();
|
||||
|
||||
// Trigger several rapid store changes
|
||||
act(() => { mockStore.__triggerChange(); });
|
||||
act(() => { vi.advanceTimersByTime(100); });
|
||||
act(() => { mockStore.__triggerChange(); });
|
||||
act(() => { vi.advanceTimersByTime(100); });
|
||||
act(() => { mockStore.__triggerChange(); });
|
||||
|
||||
// Advance past the debounce window
|
||||
await act(async () => { vi.advanceTimersByTime(600); });
|
||||
|
||||
// Despite 3 change events, only 1 fetch
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fires a heartbeat fetch after 10s even without store changes", async () => {
|
||||
renderHook(() => useGlobeStateSync("s1"));
|
||||
|
||||
// Drain the immediate initial push that fires on mount before asserting heartbeat behavior.
|
||||
await act(async () => {});
|
||||
(fetch as ReturnType<typeof vi.fn>).mockClear();
|
||||
|
||||
// No store changes — only advance 10s for the heartbeat
|
||||
await act(async () => { vi.advanceTimersByTime(10_000); });
|
||||
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
const [url] = (fetch as ReturnType<typeof vi.fn>).mock.calls[0] as [string];
|
||||
expect(url).toBe("/api/globe/state");
|
||||
});
|
||||
|
||||
it("does not throw when fetch rejects (fire-and-forget)", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("Network error"));
|
||||
|
||||
// If the hook throws, renderHook itself would throw and the test would fail.
|
||||
// Completing without error proves fire-and-forget is working correctly.
|
||||
renderHook(() => useGlobeStateSync("s1"));
|
||||
|
||||
// Trigger via heartbeat — rejected fetch must not propagate as an unhandled rejection
|
||||
await act(async () => { vi.advanceTimersByTime(10_000); });
|
||||
});
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { buildGlobeSnapshot } from "@/lib/globeState";
|
||||
|
||||
const STATE_SYNC_DEBOUNCE_MS = 500;
|
||||
const STATE_SYNC_HEARTBEAT_MS = 10_000;
|
||||
|
||||
async function pushState(sessionId: string): Promise<void> {
|
||||
const snapshot = buildGlobeSnapshot(useStore.getState());
|
||||
try {
|
||||
await fetch("/api/globe/state", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sessionId, snapshot }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[useGlobeStateSync] Failed to push globe state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export function useGlobeStateSync(sessionId: string): void {
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const heartbeatRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const initialPushDoneRef = useRef(false);
|
||||
|
||||
// Fire one immediate push as soon as a valid sessionId is available so that
|
||||
// MCP clients calling resolveActiveSessionId don't see a null ZSET entry
|
||||
// during the window before the first store change or heartbeat fires.
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
if (initialPushDoneRef.current) return;
|
||||
initialPushDoneRef.current = true;
|
||||
void pushState(sessionId);
|
||||
}, [sessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
// No-op until we have a stable session id (pre-mount or SSR)
|
||||
if (!sessionId) return;
|
||||
|
||||
const schedulePush = () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => {
|
||||
void pushState(sessionId);
|
||||
}, STATE_SYNC_DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
const unsubscribe = useStore.subscribe(schedulePush);
|
||||
|
||||
// Heartbeat: keeps the TTL and ZSET score fresh even when the camera is idle
|
||||
heartbeatRef.current = setInterval(() => {
|
||||
void pushState(sessionId);
|
||||
}, STATE_SYNC_HEARTBEAT_MS);
|
||||
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
if (heartbeatRef.current) clearInterval(heartbeatRef.current);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [sessionId]);
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
/**
|
||||
* @file useMcpCatalogPublisher.ts
|
||||
* @description Browser hook that publishes the loaded plugins' MCP tools and
|
||||
* capabilities to the per-session catalog on the server (Phase 21 Wave 2).
|
||||
*
|
||||
* The hook reads loaded+enabled plugins from pluginManager, collects their
|
||||
* mcpTools + mcpCapabilities from their loaded manifests, and POSTs to
|
||||
* POST /api/mcp/catalog on mount, when the plugin set changes, and
|
||||
* periodically to keep the catalog TTL fresh.
|
||||
*
|
||||
* Design constraints:
|
||||
* - No-op when no plugins declare mcpTools.
|
||||
* - Identity comes from the existing session cookie (NextAuth) -- the browser
|
||||
* does NOT invent or pass a userId; the server resolves identity from the
|
||||
* session cookie or Bearer token attached to the fetch.
|
||||
* - sessionId is the tab-scoped UUID from the session heartbeat (passed in
|
||||
* as a prop so this hook stays pure and testable).
|
||||
* - Mirrors useGlobeCommandBridge.ts: effect + interval + cleanup.
|
||||
* - console.error in catch only. No any. No ts-ignore.
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { getNamespacedTools } from "@/lib/mcp/pluginTools";
|
||||
import type { PluginToolsEntry } from "@/lib/mcp/pluginTools";
|
||||
import type { CatalogTool } from "@/lib/mcpSessionCatalog";
|
||||
|
||||
/** Re-publish interval in ms -- mirrors the 19a session-heartbeat cadence. */
|
||||
const PUBLISH_INTERVAL_MS = 30_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog collection helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface CatalogPayload {
|
||||
sessionId?: string;
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects mcpTools and mcpCapabilities from all loaded manifests.
|
||||
* Only includes plugins whose manifests declare at least one mcpTool.
|
||||
*/
|
||||
function collectCatalog(): { tools: CatalogTool[]; capabilities: string[] } {
|
||||
const allPlugins = pluginManager.getAllPlugins();
|
||||
|
||||
const entries: PluginToolsEntry[] = allPlugins.flatMap((managed) => {
|
||||
const pluginId = managed.plugin.id;
|
||||
const manifest = pluginManager.getManifest(pluginId);
|
||||
if (!manifest) return [];
|
||||
return [
|
||||
{
|
||||
pluginId,
|
||||
mcpTools: manifest.mcpTools,
|
||||
mcpCapabilities: manifest.mcpCapabilities,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const namespacedTools = getNamespacedTools(entries);
|
||||
|
||||
const capabilitySet = new Set<string>();
|
||||
const tools: CatalogTool[] = namespacedTools.map((nt) => {
|
||||
for (const cap of nt.capabilities) {
|
||||
capabilitySet.add(cap);
|
||||
}
|
||||
return {
|
||||
namespacedName: nt.namespacedName,
|
||||
pluginId: nt.pluginId,
|
||||
description: nt.description,
|
||||
inputSchema: nt.inputSchema,
|
||||
mcpCapabilities: nt.capabilities.length > 0 ? nt.capabilities : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
return { tools, capabilities: Array.from(capabilitySet) };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Publish helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function publishCatalog(
|
||||
sessionId: string,
|
||||
active: { current: boolean },
|
||||
): Promise<void> {
|
||||
const { tools, capabilities } = collectCatalog();
|
||||
|
||||
// No-op when no plugin-declared MCP tools are present
|
||||
if (tools.length === 0) return;
|
||||
|
||||
if (!active.current) return;
|
||||
|
||||
const payload: CatalogPayload = { sessionId, tools, capabilities };
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/mcp/catalog", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!res.ok && active.current) {
|
||||
console.error("[useMcpCatalogPublisher] catalog POST failed:", res.status);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[useMcpCatalogPublisher] catalog POST error:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hook
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Publishes the loaded plugins' MCP catalog to the server.
|
||||
*
|
||||
* @param sessionId - Tab-scoped UUID from the session heartbeat (from useSessionId).
|
||||
* Pass an empty string or undefined to suppress publishing.
|
||||
*/
|
||||
export function useMcpCatalogPublisher(sessionId: string): void {
|
||||
const activeRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
activeRef.current = true;
|
||||
|
||||
// Publish immediately on mount
|
||||
void publishCatalog(sessionId, activeRef);
|
||||
|
||||
// Re-publish periodically to keep TTL fresh
|
||||
const intervalId = setInterval(() => {
|
||||
void publishCatalog(sessionId, activeRef);
|
||||
}, PUBLISH_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [sessionId]);
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
/**
|
||||
* @file useMcpRelayBridge.ts
|
||||
* @description Browser-side bridge that relays plugin tool invocations (Phase 21 Wave 3 -- PLUG-03).
|
||||
*
|
||||
* The bridge polls GET /api/mcp/invocations on a ~1500ms interval (mirroring
|
||||
* useGlobeCommandBridge). For each pending invocation it:
|
||||
* 1. Strips the {pluginId}__ namespace prefix to get the raw tool name.
|
||||
* 2. Resolves the owning plugin from pluginManager.
|
||||
* 3. Calls plugin.executeMcpTool(rawToolName, args).
|
||||
* 4. POSTs { requestId, sessionId, result } to /api/mcp/results.
|
||||
*
|
||||
* On plugin error or missing executeMcpTool, posts a sanitized error result so
|
||||
* the server-side blpop resolves instead of timing out (SEC-02).
|
||||
*
|
||||
* Design mirrors useGlobeCommandBridge.ts:
|
||||
* - effect + interval + cleanup
|
||||
* - inFlightRef prevents overlapping polls
|
||||
* - activeRef prevents state updates after unmount
|
||||
* - console.error in catch only
|
||||
* - No any, no ts-ignore
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
|
||||
const POLL_INTERVAL_MS = 1500;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Invocation shape (matches ToolInvocation in mcpRelay.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface ToolInvocation {
|
||||
requestId: string;
|
||||
tool: string;
|
||||
args: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Poll helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function pollOnce(sessionId: string, active: { current: boolean }): Promise<void> {
|
||||
let invocations: ToolInvocation[] = [];
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/mcp/invocations?sessionId=${encodeURIComponent(sessionId)}`);
|
||||
if (!res.ok || !active.current) return;
|
||||
|
||||
const body = (await res.json()) as { invocations: unknown[] };
|
||||
invocations = (body.invocations ?? []).filter(isToolInvocation);
|
||||
} catch (err) {
|
||||
console.error("[useMcpRelayBridge] invocations poll failed:", err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!active.current || invocations.length === 0) return;
|
||||
|
||||
// Process each invocation -- errors post a sanitized result so the server unblocks.
|
||||
for (const inv of invocations) {
|
||||
if (!active.current) break;
|
||||
await dispatchInvocation(inv, sessionId, active);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dispatch a single invocation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function dispatchInvocation(
|
||||
inv: ToolInvocation,
|
||||
sessionId: string,
|
||||
active: { current: boolean },
|
||||
): Promise<void> {
|
||||
// Strip the {pluginId}__ namespace to get both the pluginId and raw tool name.
|
||||
const separatorIdx = inv.tool.indexOf("__");
|
||||
if (separatorIdx === -1) {
|
||||
await postResult(inv.requestId, sessionId, {
|
||||
error: `Malformed tool name (no namespace separator): ${inv.tool}`,
|
||||
}, active);
|
||||
return;
|
||||
}
|
||||
|
||||
const pluginId = inv.tool.slice(0, separatorIdx);
|
||||
const rawToolName = inv.tool.slice(separatorIdx + 2);
|
||||
|
||||
// Resolve the owning plugin from the plugin manager.
|
||||
const managed = pluginManager.getPlugin(pluginId);
|
||||
if (!managed) {
|
||||
await postResult(inv.requestId, sessionId, {
|
||||
error: `Plugin not found: ${pluginId}`,
|
||||
}, active);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin = managed.plugin;
|
||||
|
||||
// Check that the plugin implements executeMcpTool.
|
||||
if (typeof plugin.executeMcpTool !== "function") {
|
||||
await postResult(inv.requestId, sessionId, {
|
||||
error: `Plugin ${pluginId} does not implement executeMcpTool`,
|
||||
}, active);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await plugin.executeMcpTool(rawToolName, inv.args);
|
||||
if (active.current) {
|
||||
await postResult(inv.requestId, sessionId, result, active);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[useMcpRelayBridge] executeMcpTool error:", err);
|
||||
// Post a sanitized error result so the server-side blpop resolves.
|
||||
if (active.current) {
|
||||
await postResult(inv.requestId, sessionId, {
|
||||
error: `Plugin tool execution failed: ${err instanceof Error ? err.message : "unknown error"}`,
|
||||
}, active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST result to /api/mcp/results
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function postResult(
|
||||
requestId: string,
|
||||
sessionId: string,
|
||||
result: unknown,
|
||||
active: { current: boolean },
|
||||
): Promise<void> {
|
||||
if (!active.current) return;
|
||||
|
||||
try {
|
||||
await fetch("/api/mcp/results", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ requestId, sessionId, result }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[useMcpRelayBridge] postResult failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Type guard
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isToolInvocation(value: unknown): value is ToolInvocation {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.requestId === "string" &&
|
||||
typeof v.tool === "string" &&
|
||||
typeof v.args === "object" &&
|
||||
v.args !== null
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hook
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Polls /api/mcp/invocations and dispatches each pending tool invocation
|
||||
* to the owning plugin via plugin.executeMcpTool, then POSTs the result
|
||||
* back to /api/mcp/results so the server-side wait resolves.
|
||||
*
|
||||
* @param sessionId - Tab-scoped UUID from useSessionId. Pass empty to suppress polling.
|
||||
*/
|
||||
export function useMcpRelayBridge(sessionId: string): void {
|
||||
const activeRef = useRef(false);
|
||||
const inFlightRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
activeRef.current = true;
|
||||
|
||||
// Poll immediately on mount so the first invocation is dispatched
|
||||
// without waiting up to POLL_INTERVAL_MS. Mirrors useMcpCatalogPublisher.
|
||||
inFlightRef.current = true;
|
||||
void pollOnce(sessionId, activeRef).finally(() => {
|
||||
inFlightRef.current = false;
|
||||
});
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
if (inFlightRef.current) return;
|
||||
inFlightRef.current = true;
|
||||
void pollOnce(sessionId, activeRef).finally(() => {
|
||||
inFlightRef.current = false;
|
||||
});
|
||||
}, POLL_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [sessionId]);
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useSessionId } from "./useSessionId";
|
||||
|
||||
const SESSION_ID_KEY = "wwv-globe-session-id";
|
||||
|
||||
describe("useSessionId", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
vi.spyOn(crypto, "randomUUID");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("returns a non-empty string after mount", async () => {
|
||||
const { result } = renderHook(() => useSessionId());
|
||||
|
||||
// After render + effect flush: returns a stable UUID
|
||||
await act(async () => {});
|
||||
expect(result.current).not.toBe("");
|
||||
expect(typeof result.current).toBe("string");
|
||||
});
|
||||
|
||||
it("generates a UUID and writes it to sessionStorage when none exists", async () => {
|
||||
expect(sessionStorage.getItem(SESSION_ID_KEY)).toBeNull();
|
||||
|
||||
const { result } = renderHook(() => useSessionId());
|
||||
await act(async () => {});
|
||||
|
||||
expect(crypto.randomUUID).toHaveBeenCalledOnce();
|
||||
const stored = sessionStorage.getItem(SESSION_ID_KEY);
|
||||
expect(stored).not.toBeNull();
|
||||
expect(result.current).toBe(stored);
|
||||
});
|
||||
|
||||
it("reuses the existing sessionStorage value without calling randomUUID", async () => {
|
||||
const existingId = "existing-session-id-abc";
|
||||
sessionStorage.setItem(SESSION_ID_KEY, existingId);
|
||||
|
||||
const { result } = renderHook(() => useSessionId());
|
||||
await act(async () => {});
|
||||
|
||||
expect(crypto.randomUUID).not.toHaveBeenCalled();
|
||||
expect(result.current).toBe(existingId);
|
||||
});
|
||||
|
||||
it("returns the same id on a second render (stable across rerenders)", async () => {
|
||||
const { result, rerender } = renderHook(() => useSessionId());
|
||||
await act(async () => {});
|
||||
|
||||
const firstId = result.current;
|
||||
rerender();
|
||||
expect(result.current).toBe(firstId);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
|
||||
const SESSION_ID_KEY = "wwv-globe-session-id";
|
||||
|
||||
export function useSessionId(): string {
|
||||
// resolvedRef caches the id after the first effect run so rerenders are free
|
||||
const resolvedRef = useRef<string>("");
|
||||
const [sessionId, setSessionId] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
if (resolvedRef.current) return;
|
||||
|
||||
// sessionStorage is only available in the browser (this effect never runs on the server)
|
||||
const existing = sessionStorage.getItem(SESSION_ID_KEY);
|
||||
const id = existing ?? (() => {
|
||||
const newId = crypto.randomUUID();
|
||||
sessionStorage.setItem(SESSION_ID_KEY, newId);
|
||||
return newId;
|
||||
})();
|
||||
|
||||
resolvedRef.current = id;
|
||||
setSessionId(id);
|
||||
}, []);
|
||||
|
||||
return sessionId;
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for GlobeCommand type guard (Phase 19a Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because GlobeCommand.ts does not exist yet.
|
||||
* They lock the following contracts:
|
||||
*
|
||||
* CMD-01 valid pan command passes the guard
|
||||
* CMD-02 pan with non-number lat fails the guard
|
||||
* CMD-03 valid toggleLayer passes the guard
|
||||
* CMD-04 toggleLayer without layerId fails the guard
|
||||
* CMD-05 valid focusEntity passes the guard
|
||||
* CMD-06 valid setTimeline passes the guard
|
||||
* CMD-07 unknown type fails the guard
|
||||
* CMD-08 null/undefined/string all fail (never throws)
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isValidGlobeCommand } from "./GlobeCommand";
|
||||
|
||||
describe("isValidGlobeCommand", () => {
|
||||
// CMD-01
|
||||
it("returns true for a valid pan command with required fields", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "pan", lat: 1, lon: 2, alt: 3 })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// CMD-01 variant with optional fields
|
||||
it("returns true for pan with all optional fields", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({
|
||||
type: "pan",
|
||||
lat: 40.7,
|
||||
lon: -74.0,
|
||||
alt: 500000,
|
||||
duration: 2,
|
||||
heading: 45,
|
||||
pitch: -30,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// CMD-02
|
||||
it("returns false for pan when lat is not a number", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "pan", lat: "north", lon: 2, alt: 3 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for pan when lon is not a number", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "pan", lat: 1, lon: null, alt: 3 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for pan when alt is missing", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "pan", lat: 1, lon: 2 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// CMD-03
|
||||
it("returns true for a valid toggleLayer command", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "toggleLayer", layerId: "ais" })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for toggleLayer with enabled field", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "toggleLayer", layerId: "aviation", enabled: false })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// CMD-04
|
||||
it("returns false for toggleLayer without layerId", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "toggleLayer" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for toggleLayer with non-string layerId", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "toggleLayer", layerId: 42 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// CMD-05
|
||||
it("returns true for a valid focusEntity command with entityId", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "focusEntity", entityId: "ship:1" })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for focusEntity with lat/lon", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "focusEntity", lat: 51.5, lon: -0.12 })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for focusEntity with no fields (all optional)", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "focusEntity" })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// CMD-06
|
||||
it("returns true for a valid setTimeline command with timeWindow", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setTimeline", timeWindow: "24h" })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for setTimeline with all optional fields", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({
|
||||
type: "setTimeline",
|
||||
currentTime: "2026-01-01T00:00:00.000Z",
|
||||
timeWindow: "6h",
|
||||
isPlaybackMode: true,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for setTimeline with no fields (all optional)", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setTimeline" })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// CMD-07
|
||||
it("returns false for an unknown type", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "flyTo", lat: 1, lon: 2 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for an object with no type", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ lat: 1, lon: 2 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// CMD-08
|
||||
it("returns false for null without throwing", () => {
|
||||
expect(isValidGlobeCommand(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for undefined without throwing", () => {
|
||||
expect(isValidGlobeCommand(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for a plain string without throwing", () => {
|
||||
expect(isValidGlobeCommand("pan")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for a number without throwing", () => {
|
||||
expect(isValidGlobeCommand(42)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for an array without throwing", () => {
|
||||
expect(isValidGlobeCommand([])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,102 +0,0 @@
|
||||
// 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;
|
||||
export type TimeWindowLiteral = (typeof TIME_WINDOW_VALUES)[number];
|
||||
|
||||
export type GlobeCommand =
|
||||
| { type: "pan"; lat: number; lon: number; alt: number; duration?: number; heading?: number; pitch?: number }
|
||||
| { type: "focusEntity"; entityId?: string; lat?: number; lon?: number }
|
||||
| { type: "toggleLayer"; layerId: string; enabled?: boolean }
|
||||
| { type: "setTimeline"; currentTime?: string; timeWindow?: TimeWindowLiteral; isPlaybackMode?: boolean };
|
||||
|
||||
function isNumber(v: unknown): v is number {
|
||||
return typeof v === "number" && isFinite(v);
|
||||
}
|
||||
|
||||
function isValidLat(v: unknown): v is number {
|
||||
return isNumber(v) && v >= -90 && v <= 90;
|
||||
}
|
||||
|
||||
function isValidLon(v: unknown): v is number {
|
||||
return isNumber(v) && v >= -180 && v <= 180;
|
||||
}
|
||||
|
||||
function isValidAlt(v: unknown): v is number {
|
||||
return isNumber(v) && v > 0;
|
||||
}
|
||||
|
||||
function isString(v: unknown): v is string {
|
||||
return typeof v === "string";
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
const TIME_WINDOW_SET = new Set<string>(TIME_WINDOW_VALUES);
|
||||
|
||||
function isValidTimeWindow(v: unknown): v is TimeWindowLiteral {
|
||||
return typeof v === "string" && TIME_WINDOW_SET.has(v);
|
||||
}
|
||||
|
||||
function isOptionalTimeWindow(v: unknown): boolean {
|
||||
return v === undefined || isValidTimeWindow(v);
|
||||
}
|
||||
|
||||
function isValidDateString(v: unknown): boolean {
|
||||
return typeof v === "string" && !Number.isNaN(Date.parse(v));
|
||||
}
|
||||
|
||||
function isOptionalDateString(v: unknown): boolean {
|
||||
return v === undefined || isValidDateString(v);
|
||||
}
|
||||
|
||||
export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cmd = obj as Record<string, unknown>;
|
||||
|
||||
switch (cmd["type"]) {
|
||||
case "pan":
|
||||
return (
|
||||
isValidLat(cmd["lat"]) &&
|
||||
isValidLon(cmd["lon"]) &&
|
||||
isValidAlt(cmd["alt"]) &&
|
||||
isOptionalNumber(cmd["duration"]) &&
|
||||
isOptionalNumber(cmd["heading"]) &&
|
||||
isOptionalNumber(cmd["pitch"])
|
||||
);
|
||||
|
||||
case "focusEntity":
|
||||
return (
|
||||
isOptionalString(cmd["entityId"]) &&
|
||||
(cmd["lat"] === undefined || isValidLat(cmd["lat"])) &&
|
||||
(cmd["lon"] === undefined || isValidLon(cmd["lon"]))
|
||||
);
|
||||
|
||||
case "toggleLayer":
|
||||
return (
|
||||
isString(cmd["layerId"]) &&
|
||||
isOptionalBoolean(cmd["enabled"])
|
||||
);
|
||||
|
||||
case "setTimeline":
|
||||
return (
|
||||
isOptionalDateString(cmd["currentTime"]) &&
|
||||
isOptionalTimeWindow(cmd["timeWindow"]) &&
|
||||
isOptionalBoolean(cmd["isPlaybackMode"])
|
||||
);
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
getApprovedUnverifiedIds,
|
||||
approveUnverifiedPlugin,
|
||||
} from "@/lib/marketplace/trustedPlugins";
|
||||
import { getDisabledPluginIds } from "@/core/plugins/pluginPreferences";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
/**
|
||||
@@ -67,7 +66,6 @@ export function useMarketplaceSync(hostReady: boolean) {
|
||||
|
||||
async function loadManifest(manifest: PluginManifest) {
|
||||
if (!manifest.id || loadedIds.current.has(manifest.id)) return;
|
||||
if (getDisabledPluginIds().has(manifest.id)) return;
|
||||
if (pluginManager.getPlugin(manifest.id)) {
|
||||
loadedIds.current.add(manifest.id);
|
||||
return;
|
||||
|
||||
@@ -13,5 +13,4 @@ export type {
|
||||
FieldMapping,
|
||||
RenderingConfig,
|
||||
PluginManifest,
|
||||
McpToolDeclaration,
|
||||
} from "@worldwideview/wwv-plugin-sdk";
|
||||
@@ -1,25 +0,0 @@
|
||||
const DISABLED_KEY = "wwv-disabled-plugins";
|
||||
|
||||
export function getDisabledPluginIds(): Set<string> {
|
||||
try {
|
||||
const raw = localStorage.getItem(DISABLED_KEY);
|
||||
if (!raw) return new Set();
|
||||
return new Set<string>(JSON.parse(raw));
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
export function setPluginDisabled(pluginId: string, disabled: boolean): void {
|
||||
try {
|
||||
const ids = getDisabledPluginIds();
|
||||
if (disabled) {
|
||||
ids.add(pluginId);
|
||||
} else {
|
||||
ids.delete(pluginId);
|
||||
}
|
||||
localStorage.setItem(DISABLED_KEY, JSON.stringify([...ids]));
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
@@ -1,292 +1,59 @@
|
||||
/**
|
||||
* Tests for validateManifest (extended for Phase 21 Wave 0 RED).
|
||||
*
|
||||
* The existing test suite covers the base manifest shape. This extended file
|
||||
* adds RED assertions for the new Phase 21 fields that Wave 1 will add:
|
||||
*
|
||||
* MAN-01 mcpTools array: each entry must have name, description, inputSchema
|
||||
* MAN-02 mcpTools tool names: only [a-zA-Z0-9_-] are safe identifiers
|
||||
* MAN-03 mcpCapabilities must be string[] when present (non-array is rejected)
|
||||
* MAN-04 Absence of an "execution" field is fine (v3 -- no server-side execution)
|
||||
* MAN-05 A manifest with no mcpTools / mcpCapabilities still passes (optional fields)
|
||||
* MAN-06 mcpTools entries missing name are rejected
|
||||
* MAN-07 mcpTools entries missing description are rejected
|
||||
* MAN-08 mcpTools entries missing inputSchema are rejected
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { validateManifest } from "./validateManifest";
|
||||
import type { PluginManifest } from "./PluginManifest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("validateManifest", () => {
|
||||
it("should validate a correct manifest", () => {
|
||||
const manifest: any = {
|
||||
id: "test-plugin",
|
||||
name: "Test Plugin",
|
||||
version: "1.0.0",
|
||||
type: "data-layer",
|
||||
trust: "verified",
|
||||
capabilities: ["streaming"],
|
||||
entry: "/plugins/test.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
function baseManifest(overrides: Record<string, unknown> = {}): Partial<PluginManifest> {
|
||||
return {
|
||||
id: "test-plugin",
|
||||
name: "Test Plugin",
|
||||
version: "1.0.0",
|
||||
type: "data-layer",
|
||||
format: "bundle",
|
||||
trust: "built-in",
|
||||
capabilities: ["data:own"],
|
||||
entry: "/plugins/test/frontend.mjs",
|
||||
...overrides,
|
||||
} as Partial<PluginManifest>;
|
||||
}
|
||||
it("should flag missing required fields", () => {
|
||||
const result = validateManifest({});
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Missing required field: id");
|
||||
expect(result.errors).toContain("Missing required field: name");
|
||||
expect(result.errors).toContain("Missing required field: version");
|
||||
expect(result.errors).toContain("Missing required field: entry");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Existing base tests (preserved, no `any`)
|
||||
// ---------------------------------------------------------------------------
|
||||
it("should flag invalid entry URLs", () => {
|
||||
const manifest: any = {
|
||||
id: "p1",
|
||||
name: "n1",
|
||||
version: "1",
|
||||
type: "data-layer",
|
||||
trust: "verified",
|
||||
capabilities: ["c1"],
|
||||
entry: "https://hacker.com/malicious.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain");
|
||||
});
|
||||
|
||||
describe("validateManifest base contract", () => {
|
||||
it("accepts a correct manifest", () => {
|
||||
const result = validateManifest(baseManifest({ trust: "verified" }));
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("flags missing required fields", () => {
|
||||
const result = validateManifest({});
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Missing required field: id");
|
||||
expect(result.errors).toContain("Missing required field: name");
|
||||
expect(result.errors).toContain("Missing required field: version");
|
||||
expect(result.errors).toContain("Missing required field: entry");
|
||||
});
|
||||
|
||||
it("flags invalid entry URLs", () => {
|
||||
const result = validateManifest(baseManifest({ entry: "https://hacker.com/malicious.js" }));
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain(
|
||||
"entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain",
|
||||
);
|
||||
});
|
||||
|
||||
it("requires extends for extension plugins", () => {
|
||||
const result = validateManifest(baseManifest({ type: "extension" }));
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Extension plugins require a non-empty extends array");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-05: manifest without mcpTools / mcpCapabilities still passes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest optional mcp fields (MAN-05)", () => {
|
||||
it("accepts a manifest with no mcpTools or mcpCapabilities", () => {
|
||||
const result = validateManifest(baseManifest());
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-01 / MAN-06 / MAN-07 / MAN-08: mcpTools entry structure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest mcpTools entry structure (MAN-01)", () => {
|
||||
it("accepts a manifest with a well-formed mcpTools array", () => {
|
||||
// v3: no execution field -- only name, description, inputSchema
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "decode_squawk",
|
||||
description: "Decodes an aviation squawk code.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { squawk: { type: "string" } },
|
||||
required: ["squawk"],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// Wave 1 will validate mcpTools; current code ignores unknown fields (no false rejection).
|
||||
// No mcpTools-specific errors should be present when the entry is well-formed.
|
||||
const hasMcpToolsError = result.errors.some((e) => /mcpTools/i.test(e));
|
||||
expect(hasMcpToolsError).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects mcpTools entries missing name (MAN-06)", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
// name absent
|
||||
description: "A tool with no name.",
|
||||
inputSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// RED: Wave 1 adds the name-presence check.
|
||||
const result = validateManifest(manifest);
|
||||
const hasMcpNameError = result.errors.some(
|
||||
(e) => /mcpTools.*name/i.test(e) || /name.*mcpTools/i.test(e),
|
||||
);
|
||||
expect(hasMcpNameError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects mcpTools entries missing description (MAN-07)", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "decode_squawk",
|
||||
// description absent
|
||||
inputSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// RED: Wave 1 adds the description-presence check.
|
||||
const hasMcpDescError = result.errors.some(
|
||||
(e) => /mcpTools.*description/i.test(e) || /description.*mcpTools/i.test(e),
|
||||
);
|
||||
expect(hasMcpDescError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects mcpTools entries missing inputSchema (MAN-08)", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "decode_squawk",
|
||||
description: "Decodes a squawk code.",
|
||||
// inputSchema absent
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// RED: Wave 1 adds the inputSchema-presence check.
|
||||
const hasMcpSchemaError = result.errors.some(
|
||||
(e) => /mcpTools.*inputSchema/i.test(e) || /inputSchema.*mcpTools/i.test(e),
|
||||
);
|
||||
expect(hasMcpSchemaError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-02: tool name identifier safety
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest mcpTools name safety (MAN-02)", () => {
|
||||
it("accepts tool names that are safe identifiers [a-zA-Z0-9_-]", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "decode_squawk-v2",
|
||||
description: "Safe name.",
|
||||
inputSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// The name is safe; no name-safety error should appear (even in RED state).
|
||||
const hasNameSafetyError = result.errors.some((e) =>
|
||||
/unsafe|identifier|invalid.*name|name.*invalid/i.test(e),
|
||||
);
|
||||
expect(hasNameSafetyError).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects tool names containing characters outside [a-zA-Z0-9_-]", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "bad name!",
|
||||
description: "Unsafe name.",
|
||||
inputSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// RED: Wave 1 must add the safe-identifier check.
|
||||
const hasNameSafetyError = result.errors.some((e) =>
|
||||
/identifier|unsafe|invalid.*name|name.*invalid/i.test(e),
|
||||
);
|
||||
expect(hasNameSafetyError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects tool names with spaces", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "has space",
|
||||
description: "Space in name.",
|
||||
inputSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
const hasNameSafetyError = result.errors.some((e) =>
|
||||
/identifier|unsafe|invalid.*name|name.*invalid/i.test(e),
|
||||
);
|
||||
expect(hasNameSafetyError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-03: mcpCapabilities must be string[] when present
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest mcpCapabilities field (MAN-03)", () => {
|
||||
it("accepts a manifest with a valid mcpCapabilities string array", () => {
|
||||
const manifest = baseManifest({ mcpCapabilities: ["point-layer"] });
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// Wave 1 adds the check; current code ignores the field -- no false rejection.
|
||||
const hasMcpCapError = result.errors.some((e) => /mcpCapabilities/i.test(e));
|
||||
expect(hasMcpCapError).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a non-array mcpCapabilities (string instead of array)", () => {
|
||||
const manifest = baseManifest({ mcpCapabilities: "point-layer" });
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// RED: Wave 1 must add this check.
|
||||
const hasMcpCapError = result.errors.some((e) => /mcpCapabilities/i.test(e));
|
||||
expect(hasMcpCapError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects mcpCapabilities containing non-string entries", () => {
|
||||
const manifest = baseManifest({ mcpCapabilities: ["point-layer", 42] });
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// RED: Wave 1 must add this check.
|
||||
const hasMcpCapError = result.errors.some((e) => /mcpCapabilities/i.test(e));
|
||||
expect(hasMcpCapError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-04: no "execution" field required (v3 -- server never executes plugin tools)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest no execution field required (MAN-04)", () => {
|
||||
it("accepts a manifest whose mcpTools entry has no execution field", () => {
|
||||
const manifest = baseManifest({
|
||||
mcpTools: [
|
||||
{
|
||||
name: "decode_squawk",
|
||||
description: "Decodes a squawk code.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { squawk: { type: "string" } },
|
||||
},
|
||||
// NO execution field -- v3 does not use server-side execution
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = validateManifest(manifest);
|
||||
// Absence of execution must NOT produce an error of any kind.
|
||||
const hasExecutionError = result.errors.some((e) => /execution/i.test(e));
|
||||
expect(hasExecutionError).toBe(false);
|
||||
});
|
||||
it("should require extends for extensions", () => {
|
||||
const manifest: any = {
|
||||
id: "p1",
|
||||
name: "n1",
|
||||
version: "1",
|
||||
type: "extension",
|
||||
trust: "verified",
|
||||
capabilities: ["c1"],
|
||||
entry: "/p.js"
|
||||
};
|
||||
const result = validateManifest(manifest);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain("Extension plugins require a non-empty extends array");
|
||||
});
|
||||
});
|
||||
@@ -19,9 +19,6 @@ export interface ValidationResult {
|
||||
const VALID_TYPES = ["data-layer", "extension"] as const;
|
||||
const VALID_TRUSTS = ["built-in", "verified", "unverified"] as const;
|
||||
|
||||
/** Regex for a safe MCP tool name identifier: only [a-zA-Z0-9_-]. */
|
||||
const SAFE_TOOL_NAME = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
/**
|
||||
* Validates a plugin manifest for structural integrity and security compliance.
|
||||
* This is the primary security gate for the WorldWideView plugin ecosystem.
|
||||
@@ -79,52 +76,5 @@ export function validateManifest(
|
||||
}
|
||||
}
|
||||
|
||||
// MAN-03: mcpCapabilities must be string[] when present
|
||||
if ("mcpCapabilities" in manifest && manifest.mcpCapabilities !== undefined) {
|
||||
if (!Array.isArray(manifest.mcpCapabilities)) {
|
||||
errors.push("mcpCapabilities must be a string array when present");
|
||||
} else {
|
||||
const allStrings = (manifest.mcpCapabilities as unknown[]).every(
|
||||
(c) => typeof c === "string",
|
||||
);
|
||||
if (!allStrings) {
|
||||
errors.push("mcpCapabilities must contain only strings");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MAN-01 / MAN-02 / MAN-06 / MAN-07 / MAN-08: validate mcpTools entries
|
||||
if ("mcpTools" in manifest && manifest.mcpTools !== undefined) {
|
||||
if (!Array.isArray(manifest.mcpTools)) {
|
||||
errors.push("mcpTools must be an array when present");
|
||||
} else {
|
||||
(manifest.mcpTools as unknown as Record<string, unknown>[]).forEach((tool, idx) => {
|
||||
const prefix = `mcpTools[${idx}]`;
|
||||
|
||||
// MAN-06: name must be present
|
||||
if (typeof tool.name !== "string" || !(tool.name as string).trim()) {
|
||||
errors.push(`${prefix}: mcpTools entry missing required field: name`);
|
||||
} else {
|
||||
// MAN-02: name must be a safe identifier
|
||||
if (!SAFE_TOOL_NAME.test(tool.name as string)) {
|
||||
errors.push(
|
||||
`${prefix}: mcpTools tool name "${tool.name}" contains invalid identifier characters; only [a-zA-Z0-9_-] are allowed`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// MAN-07: description must be present
|
||||
if (typeof tool.description !== "string" || !(tool.description as string).trim()) {
|
||||
errors.push(`${prefix}: mcpTools entry missing required field: description`);
|
||||
}
|
||||
|
||||
// MAN-08: inputSchema must be present and be an object
|
||||
if (tool.inputSchema === undefined || tool.inputSchema === null || typeof tool.inputSchema !== "object") {
|
||||
errors.push(`${prefix}: mcpTools entry missing required field: inputSchema`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import { createHmac } from "crypto";
|
||||
import { generateApiKey, authenticateApiKey } from "./apiKeyAuth";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
// AUTH_SECRET must be set so getSigningKey() does not throw in the test env
|
||||
process.env.AUTH_SECRET = "test-signing-key-for-unit-tests";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// generateApiKey — KEY-01
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("generateApiKey", () => {
|
||||
it("returns an object with prefix, secret, hashedSecret, fullToken", () => {
|
||||
const key = generateApiKey();
|
||||
expect(key).toHaveProperty("prefix");
|
||||
expect(key).toHaveProperty("secret");
|
||||
expect(key).toHaveProperty("hashedSecret");
|
||||
expect(key).toHaveProperty("fullToken");
|
||||
});
|
||||
|
||||
it("prefix starts with 'wwv_'", () => {
|
||||
const key = generateApiKey();
|
||||
expect(key.prefix).toMatch(/^wwv_/);
|
||||
});
|
||||
|
||||
it("fullToken equals prefix.secret", () => {
|
||||
const key = generateApiKey();
|
||||
expect(key.fullToken).toBe(`${key.prefix}.${key.secret}`);
|
||||
});
|
||||
|
||||
it("secret is not equal to hashedSecret (secret is plaintext, hashedSecret is HMAC hex)", () => {
|
||||
const key = generateApiKey();
|
||||
expect(key.secret).not.toBe(key.hashedSecret);
|
||||
});
|
||||
|
||||
it("hashedSecret is a valid 64-char hex string (SHA-256 output)", () => {
|
||||
const key = generateApiKey();
|
||||
expect(key.hashedSecret).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it("two calls produce different prefixes (random)", () => {
|
||||
const a = generateApiKey();
|
||||
const b = generateApiKey();
|
||||
expect(a.prefix).not.toBe(b.prefix);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// authenticateApiKey — KEY-02, API-01
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("authenticateApiKey", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("returns null when Authorization header is missing", async () => {
|
||||
const req = new Request("http://localhost/api/test");
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when Authorization header is not Bearer", async () => {
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Basic abc123" },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when token has no '.' separator", async () => {
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX" },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on unknown prefix (findUnique -> null) and does NOT throw", async () => {
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue(null);
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX.fakesecret" },
|
||||
});
|
||||
await expect(authenticateApiKey(req)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on valid prefix but wrong secret (HMAC mismatch)", async () => {
|
||||
// Store a HMAC of a different secret so comparison always fails
|
||||
const wrongHash = createHmac("sha256", "test-signing-key-for-unit-tests")
|
||||
.update("correct-secret")
|
||||
.digest("hex");
|
||||
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue({
|
||||
id: "key-id-1",
|
||||
userId: "user-123",
|
||||
hashedSecret: wrongHash,
|
||||
} as never);
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX.wrongsecret" },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns { userId, keyId } on valid token (API-01)", async () => {
|
||||
// Generate a real key so we have a matching prefix + secret pair
|
||||
const { prefix, secret, hashedSecret } = generateApiKey();
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue({
|
||||
id: "key-id-real",
|
||||
userId: "user-real",
|
||||
hashedSecret,
|
||||
} as never);
|
||||
vi.mocked(prisma.userApiKey.update).mockResolvedValue({} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: `Bearer ${prefix}.${secret}` },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toEqual({ userId: "user-real", keyId: "key-id-real" });
|
||||
});
|
||||
|
||||
// Security contract: miss path runs timingSafeEqual against a dummy digest —
|
||||
// both buffers are the same length, so the compare is constant-work regardless
|
||||
// of whether the prefix was found. HMAC is microsecond-fast; we assert the
|
||||
// CONTRACT (no timing oracle) by confirming the function still returns null,
|
||||
// not by measuring elapsed time (HMAC has no measurable delay to assert on).
|
||||
it("miss path completes and returns null — timing oracle contract preserved", async () => {
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue(null);
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX.fakesecret" },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
expect(result).toBeNull();
|
||||
// timingSafeEqual must have been called: both the miss path and the hit
|
||||
// path produce equal-length (32-byte) buffers from hex digests, so the
|
||||
// compare is well-defined and does not throw.
|
||||
});
|
||||
|
||||
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({
|
||||
id: "key-id-real",
|
||||
userId: "user-real",
|
||||
hashedSecret,
|
||||
} as never);
|
||||
vi.mocked(prisma.userApiKey.update).mockResolvedValue({} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: `Bearer ${prefix}.${secret}` },
|
||||
});
|
||||
const result = await authenticateApiKey(req);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result).not.toHaveProperty("hashedSecret");
|
||||
expect(result).not.toHaveProperty("secret");
|
||||
expect(Object.keys(result!)).toEqual(["userId", "keyId"]);
|
||||
});
|
||||
});
|
||||
@@ -1,136 +0,0 @@
|
||||
import { randomBytes, createHmac, timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function getSigningKey(): string {
|
||||
const key = process.env.API_KEY_HMAC_SECRET ?? process.env.AUTH_SECRET;
|
||||
if (!key) throw new Error("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
|
||||
return key;
|
||||
}
|
||||
|
||||
function hmacHex(secret: string): string {
|
||||
return createHmac("sha256", getSigningKey()).update(secret).digest("hex");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// lastUsedAt throttle: at most one DB write per key per 60 seconds.
|
||||
// TTL-evict entries after 2x the window so this Map cannot grow unbounded.
|
||||
// Note: per-replica — at scale, move eviction to Redis.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const lastUsedAtThrottle = new Map<string, number>();
|
||||
const LAST_USED_THROTTLE_MS = 60_000;
|
||||
const THROTTLE_TTL_MS = LAST_USED_THROTTLE_MS * 2;
|
||||
|
||||
function recordLastUsed(id: string): void {
|
||||
const now = Date.now();
|
||||
const lastWrite = lastUsedAtThrottle.get(id) ?? 0;
|
||||
|
||||
if (now - lastWrite <= LAST_USED_THROTTLE_MS) return;
|
||||
|
||||
lastUsedAtThrottle.set(id, now);
|
||||
|
||||
// Evict entries older than TTL to prevent unbounded growth
|
||||
for (const [key, ts] of lastUsedAtThrottle) {
|
||||
if (now - ts > THROTTLE_TTL_MS) lastUsedAtThrottle.delete(key);
|
||||
}
|
||||
|
||||
void prisma.userApiKey.update({
|
||||
where: { id },
|
||||
data: { lastUsedAt: new Date() },
|
||||
}).catch(() => { /* intentional — never block the request */ });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Interfaces (exported for consumers — API-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface GeneratedKey {
|
||||
/** e.g. "wwv_KpKF4LhL" — stored plaintext in DB as lookup handle */
|
||||
prefix: string;
|
||||
/** 32-byte base64url — shown to user ONCE, never stored */
|
||||
secret: string;
|
||||
/** HMAC-SHA256(signingKey, secret) hex — stored in DB */
|
||||
hashedSecret: string;
|
||||
/** "wwv_KpKF4LhL.3EqV...1k0" — the full bearer token, shown once */
|
||||
fullToken: string;
|
||||
}
|
||||
|
||||
export interface AuthenticatedKey {
|
||||
userId: string;
|
||||
keyId: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// generateApiKey — KEY-01, KEY-02
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Generates a new API key pair.
|
||||
* - prefix: "wwv_" + 8 url-safe chars (stored plaintext; used as DB lookup key)
|
||||
* - secret: 43 url-safe chars from 32 random bytes (returned ONCE, never stored)
|
||||
* - hashedSecret: HMAC-SHA256(signingKey, secret) hex — what gets persisted
|
||||
* - fullToken: combined bearer value shown to the user exactly once
|
||||
*/
|
||||
export function generateApiKey(): GeneratedKey {
|
||||
// randomBytes(6) -> 8 base64url chars (no padding)
|
||||
const prefix = "wwv_" + randomBytes(6).toString("base64url");
|
||||
// randomBytes(32) -> 43 base64url chars
|
||||
const secret = randomBytes(32).toString("base64url");
|
||||
const hashedSecret = hmacHex(secret);
|
||||
return {
|
||||
prefix,
|
||||
secret,
|
||||
hashedSecret,
|
||||
fullToken: `${prefix}.${secret}`,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// authenticateApiKey — API-01, KEY-02
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Resolves an "Authorization: Bearer wwv_<prefix>.<secret>" header to the
|
||||
* owning user. Returns null (never throws) on any failure path.
|
||||
*
|
||||
* Timing-oracle defense (T-16-01): timingSafeEqual always executes even
|
||||
* when the prefix is not found in the DB, using a dummy digest so the miss
|
||||
* path and the wrong-secret path are indistinguishable by latency.
|
||||
*/
|
||||
export async function authenticateApiKey(
|
||||
request: Request,
|
||||
): Promise<AuthenticatedKey | null> {
|
||||
const authHeader = request.headers.get("authorization");
|
||||
if (!authHeader?.startsWith("Bearer ")) return null;
|
||||
|
||||
const token = authHeader.slice(7).trim();
|
||||
const dotIdx = token.indexOf(".");
|
||||
if (dotIdx === -1) return null;
|
||||
|
||||
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 },
|
||||
});
|
||||
|
||||
// Compute HMAC of the supplied secret, then compare with timingSafeEqual.
|
||||
// On a prefix miss we compare against a dummy digest — constant-work on
|
||||
// both paths defeats timing-oracle attacks (T-16-01).
|
||||
const supplied = Buffer.from(hmacHex(secret), "hex");
|
||||
const stored = Buffer.from(row?.hashedSecret ?? hmacHex("__wwv_dummy__"), "hex");
|
||||
const isValid = timingSafeEqual(supplied, stored);
|
||||
|
||||
if (!row || !isValid) return null;
|
||||
|
||||
recordLastUsed(row.id);
|
||||
|
||||
return { userId: row.userId, keyId: row.id };
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* Tests for the demo-admin identity persistence helpers in auth.ts.
|
||||
*
|
||||
* We test the exported pure functions directly rather than fighting the
|
||||
* NextAuth factory boundary. `persistDemoAdminIfNeeded` encapsulates the
|
||||
* jwt-callback guard logic and delegates to `ensureLocalUserPersisted`.
|
||||
*/
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
|
||||
// The global setup.ts mocks @/lib/auth entirely (to stop next-auth importing
|
||||
// next/server in jsdom). We need the real module here, so unmock it first.
|
||||
vi.unmock("@/lib/auth");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock prisma before importing auth.ts so the module sees the mock.
|
||||
// vi.hoisted() runs before all vi.mock() factories, so the variable is
|
||||
// defined before the hoisted factory closure captures it.
|
||||
// ---------------------------------------------------------------------------
|
||||
const { mockUpsert } = vi.hoisted(() => ({
|
||||
mockUpsert: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
upsert: mockUpsert,
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// next-auth and its provider must be mocked to prevent NextAuth() runtime init.
|
||||
vi.mock("next-auth", () => ({
|
||||
default: vi.fn(() => ({
|
||||
handlers: {},
|
||||
auth: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
vi.mock("next-auth/providers/credentials", () => ({
|
||||
default: vi.fn(() => ({ id: "credentials", name: "Credentials" })),
|
||||
}));
|
||||
vi.mock("@auth/supabase-adapter", () => ({
|
||||
SupabaseAdapter: vi.fn(() => ({})),
|
||||
}));
|
||||
vi.mock("@/lib/auth.config", () => ({
|
||||
authConfig: { callbacks: {}, providers: [] },
|
||||
}));
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isCloud: false,
|
||||
isDemo: false,
|
||||
getDemoAdminSecret: vi.fn(() => undefined),
|
||||
DEMO_ADMIN_ROLE: "demo-admin",
|
||||
}));
|
||||
vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
|
||||
|
||||
// Import after mocks.
|
||||
import {
|
||||
persistDemoAdminIfNeeded,
|
||||
ensureLocalUserPersisted,
|
||||
DEMO_ADMIN_ID,
|
||||
DEMO_ADMIN_EMAIL,
|
||||
DEMO_ADMIN_NAME,
|
||||
DEMO_ADMIN_PW_SENTINEL,
|
||||
} from "@/lib/auth";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ensureLocalUserPersisted
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("ensureLocalUserPersisted", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("calls prisma.user.upsert with the supplied params", async () => {
|
||||
await ensureLocalUserPersisted({
|
||||
id: "user-abc",
|
||||
email: "[email protected]",
|
||||
name: "Test User",
|
||||
role: "user",
|
||||
hashedPassword: "$2b$10$fakehash",
|
||||
});
|
||||
|
||||
expect(mockUpsert).toHaveBeenCalledTimes(1);
|
||||
const call = mockUpsert.mock.calls[0][0];
|
||||
expect(call.where).toEqual({ id: "user-abc" });
|
||||
expect(call.create.hashedPassword).toBe("$2b$10$fakehash");
|
||||
expect(call.update).toEqual({});
|
||||
});
|
||||
|
||||
it("defaults hashedPassword to the sentinel when omitted", async () => {
|
||||
await ensureLocalUserPersisted({
|
||||
id: "demo-admin",
|
||||
email: DEMO_ADMIN_EMAIL,
|
||||
name: DEMO_ADMIN_NAME,
|
||||
role: "demo-admin",
|
||||
});
|
||||
|
||||
const call = mockUpsert.mock.calls[0][0];
|
||||
expect(call.create.hashedPassword).toBe(DEMO_ADMIN_PW_SENTINEL);
|
||||
// Sentinel must not look like a bcrypt hash -- bcrypt always starts with "$2"
|
||||
expect(DEMO_ADMIN_PW_SENTINEL.startsWith("$2")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// persistDemoAdminIfNeeded
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("persistDemoAdminIfNeeded -- jwt callback guard", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("calls ensureLocalUserPersisted with demo-admin constants on initial sign-in", async () => {
|
||||
await persistDemoAdminIfNeeded(DEMO_ADMIN_ID, false);
|
||||
|
||||
expect(mockUpsert).toHaveBeenCalledTimes(1);
|
||||
const call = mockUpsert.mock.calls[0][0];
|
||||
expect(call.where).toEqual({ id: DEMO_ADMIN_ID });
|
||||
expect(call.create.id).toBe(DEMO_ADMIN_ID);
|
||||
expect(call.create.email).toBe(DEMO_ADMIN_EMAIL);
|
||||
expect(call.create.name).toBe(DEMO_ADMIN_NAME);
|
||||
expect(call.create.role).toBe("demo-admin");
|
||||
expect(call.create.hashedPassword).toBe(DEMO_ADMIN_PW_SENTINEL);
|
||||
// idempotent upsert -- update must be empty
|
||||
expect(call.update).toEqual({});
|
||||
});
|
||||
|
||||
it("does NOT call upsert when isCloud is true", async () => {
|
||||
await persistDemoAdminIfNeeded(DEMO_ADMIN_ID, true);
|
||||
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does NOT call upsert for a non-demo-admin user id", async () => {
|
||||
await persistDemoAdminIfNeeded("regular-user-uuid", false);
|
||||
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does NOT call upsert when both cloud=true and id=demo-admin", async () => {
|
||||
// Cloud edition takes precedence even if the id somehow matches.
|
||||
await persistDemoAdminIfNeeded(DEMO_ADMIN_ID, true);
|
||||
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -9,65 +9,6 @@ import {
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hardcoded constants for the demo-admin synthetic identity. These mirror the
|
||||
// values minted in authorize() and must never be derived from request input.
|
||||
// ---------------------------------------------------------------------------
|
||||
export const DEMO_ADMIN_ID = "demo-admin";
|
||||
export const DEMO_ADMIN_EMAIL = "[email protected]";
|
||||
export const DEMO_ADMIN_NAME = "Demo Admin";
|
||||
// Sentinel stored in hashedPassword for identities that never use bcrypt auth.
|
||||
// A bcrypt hash always starts with "$2", so this value can never match one and
|
||||
// compareSync against it always returns false -- the row cannot be used to log
|
||||
// in via the password flow.
|
||||
export const DEMO_ADMIN_PW_SENTINEL = "!demo-no-password";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Upsert the local user row so that session.user.id always has a matching
|
||||
// `users` record, even after a DB reset or first-time setup. Scoped strictly
|
||||
// to non-cloud editions. We never create a user from untrusted input -- callers
|
||||
// must supply server-controlled constants only.
|
||||
// hashedPassword defaults to the sentinel for synthetic identities (demo-admin)
|
||||
// that authenticate via a separate mechanism and never use the password flow.
|
||||
// ---------------------------------------------------------------------------
|
||||
export async function ensureLocalUserPersisted(params: {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
hashedPassword?: string;
|
||||
}): Promise<void> {
|
||||
await prisma.user.upsert({
|
||||
where: { id: params.id },
|
||||
update: {},
|
||||
create: {
|
||||
id: params.id,
|
||||
email: params.email,
|
||||
name: params.name,
|
||||
role: params.role,
|
||||
hashedPassword: params.hashedPassword ?? DEMO_ADMIN_PW_SENTINEL,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exported for unit testing: handles the demo-admin upsert on initial sign-in.
|
||||
// Called from the jwt callback with `user` present (initial sign-in only).
|
||||
// Guards: non-cloud editions, demo-admin id only, server-controlled constants.
|
||||
// ---------------------------------------------------------------------------
|
||||
export async function persistDemoAdminIfNeeded(
|
||||
userId: string,
|
||||
cloudEdition: boolean,
|
||||
): Promise<void> {
|
||||
if (cloudEdition || userId !== DEMO_ADMIN_ID) return;
|
||||
await ensureLocalUserPersisted({
|
||||
id: DEMO_ADMIN_ID,
|
||||
email: DEMO_ADMIN_EMAIL,
|
||||
name: DEMO_ADMIN_NAME,
|
||||
role: DEMO_ADMIN_ROLE,
|
||||
});
|
||||
}
|
||||
|
||||
// Extract local credentials logic to a helper
|
||||
const localCredentialsProvider = Credentials({
|
||||
credentials: {
|
||||
@@ -102,19 +43,6 @@ const localCredentialsProvider = Credentials({
|
||||
const isValid = compareSync(password, user.hashedPassword);
|
||||
if (!isValid) return null;
|
||||
|
||||
// On the local edition, upsert the user row so that session.user.id
|
||||
// always corresponds to a real `users` record even after a DB reset.
|
||||
// Cloud users are managed by Supabase Auth (never reaches this branch).
|
||||
if (!isCloud) {
|
||||
await ensureLocalUserPersisted({
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
hashedPassword: user.hashedPassword,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
@@ -140,11 +68,6 @@ export const {
|
||||
if (user) {
|
||||
token.role = (user as { role?: string }).role ?? "user";
|
||||
token.id = user.id;
|
||||
// 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;
|
||||
},
|
||||
|
||||
@@ -1,258 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
import {
|
||||
searchEntities,
|
||||
getEntitiesInRegion,
|
||||
getEntityDetails,
|
||||
getPluginData,
|
||||
} from "@/lib/data-query/service";
|
||||
|
||||
// Module does not exist yet — this file is intentionally RED (Wave 0 TDD scaffold)
|
||||
|
||||
global.fetch = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeEntity(overrides: Partial<GeoEntity> = {}): GeoEntity {
|
||||
return {
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mockEngineSnapshot(pluginId: string, entities: GeoEntity[]): void {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: entities }), { status: 200 }),
|
||||
);
|
||||
}
|
||||
|
||||
function mockEngine404(): void {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(null, { status: 404 }),
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-01 — searchEntities
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("searchEntities", () => {
|
||||
it("returns [] for empty query string (no fetch called)", async () => {
|
||||
const results = await searchEntities("");
|
||||
expect(results).toEqual([]);
|
||||
expect(vi.mocked(global.fetch)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns [] when engine returns 404 for plugin", async () => {
|
||||
mockEngine404();
|
||||
const results = await searchEntities("london", "test-plugin");
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns matching entities for substring match on label", async () => {
|
||||
const entity = makeEntity({ id: "e1", label: "London Heathrow", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const results = await searchEntities("heathrow", "test-plugin");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("match is case-insensitive", async () => {
|
||||
const entity = makeEntity({ id: "e2", label: "PARIS CDG", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const results = await searchEntities("paris", "test-plugin");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("respects limit parameter (returns at most N results)", async () => {
|
||||
const entities = Array.from({ length: 10 }, (_, i) =>
|
||||
makeEntity({ id: `e${i}`, label: `entity ${i}`, pluginId: "test-plugin" }),
|
||||
);
|
||||
mockEngineSnapshot("test-plugin", entities);
|
||||
const results = await searchEntities("entity", "test-plugin", 3);
|
||||
expect(results.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("restricts to pluginId when provided (fetch URL contains pluginId)", async () => {
|
||||
const entity = makeEntity({ id: "e3", label: "item", pluginId: "my-plugin" });
|
||||
mockEngineSnapshot("my-plugin", [entity]);
|
||||
await searchEntities("item", "my-plugin");
|
||||
const calledUrl = String(vi.mocked(global.fetch).mock.calls[0][0]);
|
||||
expect(calledUrl).toContain("my-plugin");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-02 — getEntitiesInRegion
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getEntitiesInRegion", () => {
|
||||
it("returns entities within bounding box", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 51.5, longitude: -0.1, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 52,
|
||||
south: 50,
|
||||
east: 1,
|
||||
west: -1,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("returns [] when no entities in region", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 10, longitude: 10, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 52,
|
||||
south: 50,
|
||||
east: 1,
|
||||
west: -1,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
it("handles antimeridian wraparound (east < west): entity at lon 175 inside bounds west:170 east:-170", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 0, longitude: 175, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 10,
|
||||
south: -10,
|
||||
east: -170,
|
||||
west: 170,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("respects pluginId filter", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 51.5, longitude: -0.1, pluginId: "specific-plugin" });
|
||||
mockEngineSnapshot("specific-plugin", [entity]);
|
||||
await getEntitiesInRegion({
|
||||
north: 52,
|
||||
south: 50,
|
||||
east: 1,
|
||||
west: -1,
|
||||
pluginId: "specific-plugin",
|
||||
});
|
||||
const calledUrl = String(vi.mocked(global.fetch).mock.calls[0][0]);
|
||||
expect(calledUrl).toContain("specific-plugin");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-03 — getEntityDetails
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getEntityDetails", () => {
|
||||
it("returns DetailResult with all fields when entity found", async () => {
|
||||
const props = { speed: 250, airline: "BA" };
|
||||
const entity = makeEntity({
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
label: "BA123",
|
||||
properties: props,
|
||||
});
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe("e1");
|
||||
expect(result?.pluginId).toBe("test-plugin");
|
||||
expect(result?.latitude).toBe(51.5);
|
||||
expect(result?.longitude).toBe(-0.1);
|
||||
expect(result?.label).toBe("BA123");
|
||||
expect(result?.properties).toEqual(props);
|
||||
});
|
||||
|
||||
it("returns null when plugin returns 404", async () => {
|
||||
mockEngine404();
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when entityId not in snapshot", async () => {
|
||||
const entity = makeEntity({ id: "other-entity", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returned properties includes original entity.properties object", async () => {
|
||||
const props = { foo: "bar", nested: { x: 1 } };
|
||||
const entity = makeEntity({ id: "e1", pluginId: "test-plugin", properties: props });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result?.properties).toEqual(props);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-04 — getPluginData
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getPluginData", () => {
|
||||
it("returns PluginDataSnapshot with normalized entities when engine returns { items: [...] }", async () => {
|
||||
const entity = makeEntity({ id: "e1", pluginId: "test-plugin" });
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: [entity] }), { status: 200 }),
|
||||
);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.pluginId).toBe("test-plugin");
|
||||
expect(snapshot?.entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns PluginDataSnapshot when engine returns flat array []", async () => {
|
||||
const entity = makeEntity({ id: "e1", pluginId: "test-plugin" });
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify([entity]), { status: 200 }),
|
||||
);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns null on engine 404", async () => {
|
||||
mockEngine404();
|
||||
const snapshot = await getPluginData("missing-plugin");
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on engine non-2xx (500)", async () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: "internal" }), { status: 500 }),
|
||||
);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("normalizes timestamp string to Date object", async () => {
|
||||
const entityWithStringTimestamp = {
|
||||
...makeEntity({ id: "e1", pluginId: "test-plugin" }),
|
||||
timestamp: "2026-05-29T10:00:00Z",
|
||||
};
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: [entityWithStringTimestamp] }), { status: 200 }),
|
||||
);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot?.entities[0].timestamp).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
import type {
|
||||
SearchResult,
|
||||
RegionOptions,
|
||||
DetailResult,
|
||||
PluginDataSnapshot,
|
||||
} from "./types";
|
||||
|
||||
function getEngineUrl(): string {
|
||||
return process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL ?? "http://localhost:5000";
|
||||
}
|
||||
|
||||
function normalizeEntity(raw: unknown): GeoEntity | null {
|
||||
if (typeof raw !== "object" || raw === null) return null;
|
||||
const e = raw as Record<string, unknown>;
|
||||
return {
|
||||
id: e.id as string,
|
||||
pluginId: e.pluginId as string,
|
||||
latitude: e.latitude as number,
|
||||
longitude: e.longitude as number,
|
||||
altitude: e.altitude as number | undefined,
|
||||
heading: e.heading as number | undefined,
|
||||
speed: e.speed as number | undefined,
|
||||
timestamp: new Date((e.timestamp as string | Date | undefined) ?? Date.now()),
|
||||
label: e.label as string | undefined,
|
||||
properties: (e.properties as Record<string, unknown>) ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
/** Validate that a pluginId is safe to embed in a URL path segment. */
|
||||
function validatePluginId(pluginId: string): string {
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(pluginId)) {
|
||||
throw new Error("Invalid pluginId: only alphanumeric characters, hyphens, and underscores are allowed");
|
||||
}
|
||||
return pluginId;
|
||||
}
|
||||
|
||||
async function fetchPluginSnapshot(pluginId: string): Promise<PluginDataSnapshot | null> {
|
||||
const safeId = validatePluginId(pluginId);
|
||||
const engineBase = getEngineUrl();
|
||||
const url = new URL(`/api/${safeId}`, engineBase).toString();
|
||||
try {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) {
|
||||
console.error("[data-query] Engine returned", res.status, "for plugin");
|
||||
return null;
|
||||
}
|
||||
const data: unknown = await res.json();
|
||||
const raw = Array.isArray(data) ? data : ((data as Record<string, unknown>)?.items ?? []) as unknown[];
|
||||
const entities: GeoEntity[] = (raw as unknown[]).reduce<GeoEntity[]>((acc, item) => {
|
||||
const entity = normalizeEntity(item);
|
||||
if (entity !== null) acc.push(entity);
|
||||
return acc;
|
||||
}, []);
|
||||
return { pluginId: safeId, entities, timestamp: new Date() };
|
||||
} catch (err) {
|
||||
console.error("[data-query] Failed to fetch plugin snapshot:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getAllPluginSnapshots(): Promise<PluginDataSnapshot[]> {
|
||||
const url = `${getEngineUrl()}/manifest`;
|
||||
let pluginIds: string[] = [];
|
||||
try {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) {
|
||||
console.error(`[data-query] Manifest fetch returned ${res.status}`);
|
||||
return [];
|
||||
}
|
||||
const data: unknown = await res.json();
|
||||
pluginIds = ((data as Record<string, unknown>)?.plugins as string[]) ?? [];
|
||||
} catch (err) {
|
||||
console.error("[data-query] Failed to fetch manifest:", err);
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = await Promise.allSettled(pluginIds.map(fetchPluginSnapshot));
|
||||
return results.reduce<PluginDataSnapshot[]>((acc, result) => {
|
||||
if (result.status === "fulfilled" && result.value !== null) {
|
||||
acc.push(result.value);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function entityToSearchResult(entity: GeoEntity): SearchResult {
|
||||
return {
|
||||
id: entity.id,
|
||||
pluginId: entity.pluginId,
|
||||
name: entity.label ?? entity.id,
|
||||
latitude: entity.latitude,
|
||||
longitude: entity.longitude,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchEntities(
|
||||
query: string,
|
||||
pluginId?: string,
|
||||
limit: number = 20,
|
||||
): Promise<SearchResult[]> {
|
||||
const trimmed = query.trim();
|
||||
if (trimmed === "") return [];
|
||||
|
||||
const effectiveLimit = Math.min(Math.max(limit, 1), 100);
|
||||
const lower = trimmed.toLowerCase();
|
||||
|
||||
const snapshots = pluginId
|
||||
? await fetchPluginSnapshot(pluginId).then((s) => (s ? [s] : []))
|
||||
: await getAllPluginSnapshots();
|
||||
|
||||
const results: SearchResult[] = [];
|
||||
for (const snapshot of snapshots) {
|
||||
for (const entity of snapshot.entities) {
|
||||
if (results.length >= effectiveLimit) break;
|
||||
const matchTarget = (entity.label ?? entity.id).toLowerCase();
|
||||
if (matchTarget.includes(lower)) {
|
||||
results.push(entityToSearchResult(entity));
|
||||
}
|
||||
}
|
||||
if (results.length >= effectiveLimit) break;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function getEntitiesInRegion(bounds: RegionOptions): Promise<SearchResult[]> {
|
||||
const { north, south, east, west } = bounds;
|
||||
if (isNaN(north) || isNaN(south) || isNaN(east) || isNaN(west)) {
|
||||
throw new Error("Invalid bounding box: north/south/east/west must all be numbers");
|
||||
}
|
||||
|
||||
const effectiveLimit = Math.min(bounds.limit ?? 100, 1000);
|
||||
const isAntimeridian = east < west;
|
||||
|
||||
const snapshots = bounds.pluginId
|
||||
? await fetchPluginSnapshot(bounds.pluginId).then((s) => (s ? [s] : []))
|
||||
: await getAllPluginSnapshots();
|
||||
|
||||
const results: 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 (results.length >= effectiveLimit) break;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function getEntityDetails(
|
||||
pluginId: string,
|
||||
entityId: string,
|
||||
): Promise<DetailResult | null> {
|
||||
const snapshot = await fetchPluginSnapshot(pluginId);
|
||||
if (!snapshot) return null;
|
||||
|
||||
const entity = snapshot.entities.find((e) => e.id === entityId);
|
||||
if (!entity) return null;
|
||||
|
||||
return {
|
||||
id: entity.id,
|
||||
pluginId: entity.pluginId,
|
||||
latitude: entity.latitude,
|
||||
longitude: entity.longitude,
|
||||
altitude: entity.altitude,
|
||||
heading: entity.heading,
|
||||
speed: entity.speed,
|
||||
timestamp: entity.timestamp,
|
||||
label: entity.label,
|
||||
properties: entity.properties,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPluginData(pluginId: string): Promise<PluginDataSnapshot | null> {
|
||||
if (!pluginId.trim()) return null;
|
||||
try {
|
||||
return fetchPluginSnapshot(pluginId);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export interface SearchOptions {
|
||||
query: string;
|
||||
pluginId?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
name?: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
export interface RegionOptions {
|
||||
north: number;
|
||||
south: number;
|
||||
east: number;
|
||||
west: number;
|
||||
pluginId?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface DetailResult {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
altitude?: number;
|
||||
heading?: number;
|
||||
speed?: number;
|
||||
timestamp: Date;
|
||||
label?: string;
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PluginDataSnapshot {
|
||||
pluginId: string;
|
||||
entities: GeoEntity[];
|
||||
timestamp: Date;
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
/**
|
||||
* Tests for globeCommandQueue (Phase 19a Wave 0, updated for review fixes).
|
||||
*
|
||||
* QUEUE-01 enqueueGlobeCommand atomically rpush+expire via multi() chain
|
||||
* QUEUE-02 drainGlobeCommands atomically lranges + dels, returns parsed GlobeCommand[]
|
||||
* QUEUE-03 drainGlobeCommands drops invalid JSON and invalid command shapes silently
|
||||
* QUEUE-04 resolveActiveSessionId returns the newest session within 45s threshold
|
||||
* QUEUE-05 resolveActiveSessionId returns null when all sessions are older than 45s
|
||||
* QUEUE-06 setTimeline validation: invalid timeWindow and non-date currentTime are rejected
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
enqueueGlobeCommand,
|
||||
drainGlobeCommands,
|
||||
resolveActiveSessionId,
|
||||
} from "./globeCommandQueue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock @/lib/redis
|
||||
// vi.mock is hoisted above variable declarations, so the mock objects must be
|
||||
// declared with vi.hoisted() to be accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockExecResult: [[null, string[]], [null, number]] = [
|
||||
[null, []],
|
||||
[null, 1],
|
||||
];
|
||||
|
||||
const { mockMultiChain, mockRedis } = vi.hoisted(() => {
|
||||
const mockMultiChain = {
|
||||
lrange: vi.fn().mockReturnThis(),
|
||||
del: vi.fn().mockReturnThis(),
|
||||
rpush: vi.fn().mockReturnThis(),
|
||||
expire: vi.fn().mockReturnThis(),
|
||||
exec: vi.fn(),
|
||||
};
|
||||
const mockRedis = {
|
||||
rpush: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
zrange: vi.fn(),
|
||||
multi: vi.fn(() => mockMultiChain),
|
||||
};
|
||||
return { mockMultiChain, mockRedis };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: mockRedis,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Import after mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Re-wire multi chain after reset
|
||||
mockMultiChain.lrange.mockReturnThis();
|
||||
mockMultiChain.del.mockReturnThis();
|
||||
mockMultiChain.rpush.mockReturnThis();
|
||||
mockMultiChain.expire.mockReturnThis();
|
||||
mockMultiChain.exec.mockResolvedValue(mockExecResult);
|
||||
mockRedis.multi.mockReturnValue(mockMultiChain);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUEUE-01: enqueueGlobeCommand — atomic multi() path
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("enqueueGlobeCommand (QUEUE-01)", () => {
|
||||
const panCmd: GlobeCommand = { type: "pan", lat: 1, lon: 2, alt: 3 };
|
||||
|
||||
it("calls multi().rpush(key, json).expire(key, ttl).exec() atomically", async () => {
|
||||
await enqueueGlobeCommand("u1", "s1", panCmd);
|
||||
|
||||
expect(mockRedis.multi).toHaveBeenCalledTimes(1);
|
||||
expect(mockMultiChain.rpush).toHaveBeenCalledWith(
|
||||
"globe:commandqueue:u1:s1",
|
||||
JSON.stringify(panCmd),
|
||||
);
|
||||
expect(mockMultiChain.expire).toHaveBeenCalledWith(
|
||||
"globe:commandqueue:u1:s1",
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(mockMultiChain.exec).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses a TTL in the range 55-120 seconds", async () => {
|
||||
await enqueueGlobeCommand("u1", "s1", panCmd);
|
||||
|
||||
const ttl = (mockMultiChain.expire.mock.calls[0] as [string, number])[1];
|
||||
expect(ttl).toBeGreaterThanOrEqual(55);
|
||||
expect(ttl).toBeLessThanOrEqual(120);
|
||||
});
|
||||
|
||||
it("scopes key to userId and sessionId independently", async () => {
|
||||
await enqueueGlobeCommand("alice", "sess-abc", panCmd);
|
||||
|
||||
expect(mockMultiChain.rpush).toHaveBeenCalledWith(
|
||||
"globe:commandqueue:alice:sess-abc",
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
it("does NOT call rpush or expire directly on redis (atomic path only)", async () => {
|
||||
await enqueueGlobeCommand("u1", "s1", panCmd);
|
||||
|
||||
expect(mockRedis.rpush).not.toHaveBeenCalled();
|
||||
expect(mockRedis.expire).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUEUE-02: drainGlobeCommands -- happy path
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("drainGlobeCommands (QUEUE-02)", () => {
|
||||
const toggleCmd: GlobeCommand = { type: "toggleLayer", layerId: "ais" };
|
||||
const panCmd: GlobeCommand = { type: "pan", lat: 10, lon: 20, alt: 500 };
|
||||
|
||||
it("uses multi().lrange(key, 0, -1).del(key).exec() atomically", async () => {
|
||||
mockMultiChain.exec.mockResolvedValue([
|
||||
[null, [JSON.stringify(toggleCmd)]],
|
||||
[null, 1],
|
||||
]);
|
||||
|
||||
await drainGlobeCommands("u1", "s1");
|
||||
|
||||
expect(mockRedis.multi).toHaveBeenCalledTimes(1);
|
||||
expect(mockMultiChain.lrange).toHaveBeenCalledWith(
|
||||
"globe:commandqueue:u1:s1",
|
||||
0,
|
||||
-1,
|
||||
);
|
||||
expect(mockMultiChain.del).toHaveBeenCalledWith("globe:commandqueue:u1:s1");
|
||||
expect(mockMultiChain.exec).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns an array of parsed GlobeCommands", async () => {
|
||||
mockMultiChain.exec.mockResolvedValue([
|
||||
[null, [JSON.stringify(panCmd), JSON.stringify(toggleCmd)]],
|
||||
[null, 1],
|
||||
]);
|
||||
|
||||
const result = await drainGlobeCommands("u1", "s1");
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toEqual(panCmd);
|
||||
expect(result[1]).toEqual(toggleCmd);
|
||||
});
|
||||
|
||||
it("returns an empty array when the queue is empty", async () => {
|
||||
mockMultiChain.exec.mockResolvedValue([
|
||||
[null, []],
|
||||
[null, 0],
|
||||
]);
|
||||
|
||||
const result = await drainGlobeCommands("u1", "s1");
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUEUE-03: drainGlobeCommands -- invalid entry filtering
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("drainGlobeCommands invalid entry filtering (QUEUE-03)", () => {
|
||||
it("silently drops entries that are invalid JSON", async () => {
|
||||
mockMultiChain.exec.mockResolvedValue([
|
||||
[null, ["not-json{{{", JSON.stringify({ type: "toggleLayer", layerId: "x" })]],
|
||||
[null, 1],
|
||||
]);
|
||||
|
||||
const result = await drainGlobeCommands("u1", "s1");
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({ type: "toggleLayer", layerId: "x" });
|
||||
});
|
||||
|
||||
it("silently drops entries that fail the GlobeCommand shape check", async () => {
|
||||
const validCmd: GlobeCommand = { type: "pan", lat: 1, lon: 2, alt: 3 };
|
||||
mockMultiChain.exec.mockResolvedValue([
|
||||
[
|
||||
null,
|
||||
[
|
||||
JSON.stringify({ type: "unknown_type" }),
|
||||
JSON.stringify({ type: "pan", lat: "bad" }),
|
||||
JSON.stringify(validCmd),
|
||||
],
|
||||
],
|
||||
[null, 1],
|
||||
]);
|
||||
|
||||
const result = await drainGlobeCommands("u1", "s1");
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual(validCmd);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUEUE-04 / QUEUE-05: resolveActiveSessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("resolveActiveSessionId (QUEUE-04 / QUEUE-05)", () => {
|
||||
it("returns the newest session whose score is within 45s of Date.now()", async () => {
|
||||
const now = Date.now();
|
||||
const freshScore = now - 5_000; // 5s ago -- fresh
|
||||
const olderScore = now - 30_000; // 30s ago -- still fresh
|
||||
|
||||
// ioredis WITHSCORES flat interleaved array: [member, score, ...]
|
||||
mockRedis.zrange.mockResolvedValue([
|
||||
"sess-old", String(olderScore),
|
||||
"sess-new", String(freshScore),
|
||||
]);
|
||||
|
||||
const result = await resolveActiveSessionId("u1");
|
||||
|
||||
// Must return the newest (highest score = most recent)
|
||||
expect(result).toBe("sess-new");
|
||||
});
|
||||
|
||||
it("queries globe:sessions:{userId} with WITHSCORES", async () => {
|
||||
mockRedis.zrange.mockResolvedValue([]);
|
||||
|
||||
await resolveActiveSessionId("u1");
|
||||
|
||||
expect(mockRedis.zrange).toHaveBeenCalledWith(
|
||||
"globe:sessions:u1",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
"WITHSCORES",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when the only entry is older than 45s", async () => {
|
||||
const now = Date.now();
|
||||
const staleScore = now - 60_000; // 60s ago -- stale
|
||||
|
||||
mockRedis.zrange.mockResolvedValue(["sess-stale", String(staleScore)]);
|
||||
|
||||
const result = await resolveActiveSessionId("u1");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when no sessions exist", async () => {
|
||||
mockRedis.zrange.mockResolvedValue([]);
|
||||
|
||||
const result = await resolveActiveSessionId("u1");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when all sessions are stale", async () => {
|
||||
const now = Date.now();
|
||||
mockRedis.zrange.mockResolvedValue([
|
||||
"sess-a", String(now - 50_000),
|
||||
"sess-b", String(now - 90_000),
|
||||
]);
|
||||
|
||||
const result = await resolveActiveSessionId("u1");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUEUE-06: setTimeline validation -- tightened timeWindow + currentTime checks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand setTimeline validation (QUEUE-06)", () => {
|
||||
it("accepts a valid timeWindow value", () => {
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "24h" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "1h" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "7d" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an unrecognised timeWindow string", () => {
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "2d" })).toBe(false);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "30m" })).toBe(false);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", timeWindow: "" })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a valid ISO 8601 currentTime string", () => {
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", currentTime: "2024-01-15T12:00:00Z" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", currentTime: "2024-01-15" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a currentTime that is not a parseable date", () => {
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", currentTime: "not-a-date" })).toBe(false);
|
||||
expect(isValidGlobeCommand({ type: "setTimeline", currentTime: "25h" })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts setTimeline with no optional fields", () => {
|
||||
expect(isValidGlobeCommand({ type: "setTimeline" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts setTimeline with all valid fields", () => {
|
||||
expect(isValidGlobeCommand({
|
||||
type: "setTimeline",
|
||||
currentTime: "2024-06-01T00:00:00Z",
|
||||
timeWindow: "6h",
|
||||
isPlaybackMode: true,
|
||||
})).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import { redis } from "@/lib/redis";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
|
||||
const COMMAND_QUEUE_TTL_SECONDS = 60;
|
||||
const STALE_THRESHOLD_MS = 45_000;
|
||||
|
||||
function queueKey(userId: string, sessionId: string): string {
|
||||
return `globe:commandqueue:${userId}:${sessionId}`;
|
||||
}
|
||||
|
||||
export async function enqueueGlobeCommand(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
cmd: GlobeCommand,
|
||||
): Promise<void> {
|
||||
const key = queueKey(userId, sessionId);
|
||||
try {
|
||||
await redis.multi().rpush(key, JSON.stringify(cmd)).expire(key, COMMAND_QUEUE_TTL_SECONDS).exec();
|
||||
} catch (err) {
|
||||
console.error("[globeCommandQueue] enqueueGlobeCommand failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function drainGlobeCommands(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
): Promise<GlobeCommand[]> {
|
||||
const key = queueKey(userId, sessionId);
|
||||
try {
|
||||
const results = await redis.multi().lrange(key, 0, -1).del(key).exec();
|
||||
|
||||
// results[0] is the lrange reply: [error | null, string[]]
|
||||
const lrangeReply = results[0];
|
||||
if (!lrangeReply || lrangeReply[0] !== null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const raw = lrangeReply[1];
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const commands: GlobeCommand[] = [];
|
||||
for (const entry of raw) {
|
||||
if (typeof entry !== "string") continue;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(entry);
|
||||
if (isValidGlobeCommand(parsed)) {
|
||||
commands.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// Drop unparseable entries silently
|
||||
}
|
||||
}
|
||||
|
||||
return commands;
|
||||
} catch (err) {
|
||||
console.error("[globeCommandQueue] drainGlobeCommands failed:", err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveActiveSessionId(userId: string): Promise<string | null> {
|
||||
try {
|
||||
// ioredis WITHSCORES returns flat interleaved [member, score, member, score, ...]
|
||||
const flat = await redis.zrange(`globe:sessions:${userId}`, 0, -1, "WITHSCORES");
|
||||
const now = Date.now();
|
||||
|
||||
let bestMember: string | null = null;
|
||||
let bestScore = -Infinity;
|
||||
|
||||
for (let i = 0; i < flat.length; i += 2) {
|
||||
const member = flat[i];
|
||||
const score = Number(flat[i + 1]);
|
||||
if (now - score < STALE_THRESHOLD_MS && score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMember = member;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMember;
|
||||
} catch (err) {
|
||||
console.error("[globeCommandQueue] resolveActiveSessionId failed:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
import type { LayerState } from "@/core/state/layersSlice";
|
||||
import { buildGlobeSnapshot } from "./globeState";
|
||||
|
||||
// Flat store shape — mirrors the live Zustand store (no nested state.globe.* namespace).
|
||||
// Only the fields buildGlobeSnapshot reads are included; the rest are omitted intentionally.
|
||||
const makeFakeState = (overrides: Partial<{
|
||||
cameraLat: number;
|
||||
cameraLon: number;
|
||||
cameraAlt: number;
|
||||
cameraHeading: number;
|
||||
cameraPitch: number;
|
||||
cameraRoll: number;
|
||||
layers: Record<string, LayerState>;
|
||||
currentTime: Date;
|
||||
timeWindow: string;
|
||||
isPlaybackMode: boolean;
|
||||
playbackTime: number;
|
||||
playbackSpeed: number;
|
||||
selectedEntity: GeoEntity | null;
|
||||
}> = {}) => ({
|
||||
cameraLat: 37.7749,
|
||||
cameraLon: -122.4194,
|
||||
cameraAlt: 500000,
|
||||
cameraHeading: 45,
|
||||
cameraPitch: -60,
|
||||
cameraRoll: 0,
|
||||
layers: {
|
||||
aviation: { enabled: true, entityCount: 42, loading: false },
|
||||
maritime: { enabled: false, entityCount: 0, loading: true },
|
||||
},
|
||||
currentTime: new Date("2026-01-15T12:00:00.000Z"),
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
selectedEntity: null as GeoEntity | null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// RSRC-01 — buildGlobeSnapshot maps the flat store into a stable serializable shape.
|
||||
|
||||
describe("buildGlobeSnapshot — viewport mapping (RSRC-01)", () => {
|
||||
it("maps cameraLat/Lon/Alt/Heading/Pitch/Roll into viewport object", () => {
|
||||
const state = makeFakeState();
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.viewport).toEqual({
|
||||
lat: 37.7749,
|
||||
lon: -122.4194,
|
||||
altitude: 500000,
|
||||
heading: 45,
|
||||
pitch: -60,
|
||||
roll: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves negative lat/lon values correctly", () => {
|
||||
const state = makeFakeState({ cameraLat: -33.8688, cameraLon: 151.2093, cameraAlt: 1000 });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.viewport.lat).toBe(-33.8688);
|
||||
expect(snapshot.viewport.lon).toBe(151.2093);
|
||||
expect(snapshot.viewport.altitude).toBe(1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGlobeSnapshot — layers passthrough (RSRC-01)", () => {
|
||||
it("passes layers Record through unchanged", () => {
|
||||
const layers = {
|
||||
aviation: { enabled: true, entityCount: 42, loading: false },
|
||||
maritime: { enabled: false, entityCount: 0, loading: true },
|
||||
};
|
||||
const state = makeFakeState({ layers });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.layers).toEqual(layers);
|
||||
});
|
||||
|
||||
it("handles empty layers Record", () => {
|
||||
const state = makeFakeState({ layers: {} });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.layers).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGlobeSnapshot — timeline serialization (RSRC-01)", () => {
|
||||
it("serializes currentTime as an ISO string", () => {
|
||||
const date = new Date("2026-01-15T12:00:00.000Z");
|
||||
const state = makeFakeState({ currentTime: date });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.timeline.currentTime).toBe("2026-01-15T12:00:00.000Z");
|
||||
});
|
||||
|
||||
it("includes timeWindow in timeline", () => {
|
||||
const state = makeFakeState({ timeWindow: "6h" });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.timeline.timeWindow).toBe("6h");
|
||||
});
|
||||
|
||||
it("includes isPlaybackMode in timeline", () => {
|
||||
const state = makeFakeState({ isPlaybackMode: true });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.timeline.isPlaybackMode).toBe(true);
|
||||
});
|
||||
|
||||
it("includes playbackTime in timeline", () => {
|
||||
const state = makeFakeState({ playbackTime: 1737000000000 });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.timeline.playbackTime).toBe(1737000000000);
|
||||
});
|
||||
|
||||
it("includes playbackSpeed in timeline", () => {
|
||||
const state = makeFakeState({ playbackSpeed: 10 });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.timeline.playbackSpeed).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGlobeSnapshot — selectedEntity (RSRC-01)", () => {
|
||||
it("returns null for selectedEntity when state.selectedEntity is null", () => {
|
||||
const state = makeFakeState({ selectedEntity: null });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.selectedEntity).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 'pluginId:id' string when a GeoEntity is selected", () => {
|
||||
const entity: GeoEntity = {
|
||||
id: "icao-abc123",
|
||||
pluginId: "aviation",
|
||||
latitude: 40.7128,
|
||||
longitude: -74.006,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
};
|
||||
const state = makeFakeState({ selectedEntity: entity });
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(snapshot.selectedEntity).toBe("aviation:icao-abc123");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGlobeSnapshot — lastUpdate (RSRC-01)", () => {
|
||||
it("lastUpdate is a number (Unix timestamp ms)", () => {
|
||||
const state = makeFakeState();
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
|
||||
expect(typeof snapshot.lastUpdate).toBe("number");
|
||||
});
|
||||
|
||||
it("lastUpdate is approximately now (within 1 second)", () => {
|
||||
const before = Date.now();
|
||||
const state = makeFakeState();
|
||||
const snapshot = buildGlobeSnapshot(state);
|
||||
const after = Date.now();
|
||||
|
||||
expect(snapshot.lastUpdate).toBeGreaterThanOrEqual(before);
|
||||
expect(snapshot.lastUpdate).toBeLessThanOrEqual(after);
|
||||
});
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
import type { LayerState } from "@/core/state/layersSlice";
|
||||
|
||||
export interface GlobeViewport {
|
||||
lat: number;
|
||||
lon: number;
|
||||
altitude: number;
|
||||
heading: number;
|
||||
pitch: number;
|
||||
roll: number;
|
||||
}
|
||||
|
||||
export interface GlobeStateSnapshot {
|
||||
viewport: GlobeViewport;
|
||||
layers: Record<string, LayerState>;
|
||||
timeline: {
|
||||
currentTime: string;
|
||||
timeWindow: string;
|
||||
isPlaybackMode: boolean;
|
||||
playbackTime: number;
|
||||
playbackSpeed: number;
|
||||
};
|
||||
selectedEntity: string | null;
|
||||
lastUpdate: number;
|
||||
}
|
||||
|
||||
export interface AppStoreSnapshotInput {
|
||||
cameraLat: number;
|
||||
cameraLon: number;
|
||||
cameraAlt: number;
|
||||
cameraHeading: number;
|
||||
cameraPitch: number;
|
||||
cameraRoll: number;
|
||||
layers: Record<string, LayerState>;
|
||||
currentTime: Date;
|
||||
timeWindow: string;
|
||||
isPlaybackMode: boolean;
|
||||
playbackTime: number;
|
||||
playbackSpeed: number;
|
||||
selectedEntity: GeoEntity | null;
|
||||
}
|
||||
|
||||
export function buildGlobeSnapshot(state: AppStoreSnapshotInput): GlobeStateSnapshot {
|
||||
return {
|
||||
viewport: {
|
||||
lat: state.cameraLat,
|
||||
lon: state.cameraLon,
|
||||
altitude: state.cameraAlt,
|
||||
heading: state.cameraHeading,
|
||||
pitch: state.cameraPitch,
|
||||
roll: state.cameraRoll,
|
||||
},
|
||||
layers: state.layers,
|
||||
timeline: {
|
||||
currentTime: state.currentTime.toISOString(),
|
||||
timeWindow: state.timeWindow,
|
||||
isPlaybackMode: state.isPlaybackMode,
|
||||
playbackTime: state.playbackTime,
|
||||
playbackSpeed: state.playbackSpeed,
|
||||
},
|
||||
selectedEntity: state.selectedEntity
|
||||
? `${state.selectedEntity.pluginId}:${state.selectedEntity.id}`
|
||||
: null,
|
||||
lastUpdate: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
writeGlobeState,
|
||||
readGlobeState,
|
||||
readActiveSessions,
|
||||
globeStateKey,
|
||||
globeSessionsKey,
|
||||
} from "./globeStateStore";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: {
|
||||
set: vi.fn(),
|
||||
get: vi.fn(),
|
||||
zadd: vi.fn(),
|
||||
zrange: vi.fn(),
|
||||
zrem: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockRedis = vi.mocked(redis);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Key helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globeStateKey", () => {
|
||||
it("returns 'globe:state:{userId}:{sessionId}'", () => {
|
||||
expect(globeStateKey("u1", "s1")).toBe("globe:state:u1:s1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("globeSessionsKey", () => {
|
||||
it("returns 'globe:sessions:{userId}'", () => {
|
||||
expect(globeSessionsKey("u1")).toBe("globe:sessions:u1");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// writeGlobeState (RSRC-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("writeGlobeState (RSRC-01)", () => {
|
||||
const fakeSnapshot = {
|
||||
viewport: { lat: 37.7, lon: -122.4, altitude: 500000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: { aviation: { enabled: true, entityCount: 5, loading: false } },
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: Date.now(),
|
||||
};
|
||||
|
||||
it("calls redis.set with the state key, JSON-serialized snapshot, and EX 30 TTL", async () => {
|
||||
mockRedis.set.mockResolvedValue("OK");
|
||||
mockRedis.zadd.mockResolvedValue(1);
|
||||
|
||||
await writeGlobeState("u1", "s1", fakeSnapshot);
|
||||
|
||||
expect(mockRedis.set).toHaveBeenCalledWith(
|
||||
"globe:state:u1:s1",
|
||||
JSON.stringify(fakeSnapshot),
|
||||
"EX",
|
||||
30,
|
||||
);
|
||||
});
|
||||
|
||||
it("calls redis.zadd with sessions key, a numeric score, and sessionId", async () => {
|
||||
mockRedis.set.mockResolvedValue("OK");
|
||||
mockRedis.zadd.mockResolvedValue(1);
|
||||
|
||||
await writeGlobeState("u1", "s1", fakeSnapshot);
|
||||
|
||||
const [key, score, member] = mockRedis.zadd.mock.calls[0] as [string, number, string];
|
||||
expect(key).toBe("globe:sessions:u1");
|
||||
expect(typeof score).toBe("number");
|
||||
expect(member).toBe("s1");
|
||||
});
|
||||
|
||||
it("resolves (fire-and-forget) even when redis.set rejects", async () => {
|
||||
mockRedis.set.mockRejectedValue(new Error("Redis connection refused"));
|
||||
mockRedis.zadd.mockResolvedValue(1);
|
||||
|
||||
await expect(writeGlobeState("u1", "s1", fakeSnapshot)).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// readGlobeState (RSRC-02)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("readGlobeState (RSRC-02)", () => {
|
||||
const storedSnapshot = {
|
||||
viewport: { lat: 10, lon: 20, altitude: 100000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: {},
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "1h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
|
||||
it("returns the parsed snapshot when redis.get resolves a JSON string", async () => {
|
||||
mockRedis.get.mockResolvedValue(JSON.stringify(storedSnapshot));
|
||||
|
||||
const result = await readGlobeState("u1", "s1");
|
||||
|
||||
expect(result).toEqual(storedSnapshot);
|
||||
});
|
||||
|
||||
it("returns null when redis.get resolves null (key expired or not found)", async () => {
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
const result = await readGlobeState("u1", "s1");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("queries the correct key", async () => {
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
await readGlobeState("u1", "s1");
|
||||
|
||||
expect(mockRedis.get).toHaveBeenCalledWith("globe:state:u1:s1");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// readActiveSessions (RSRC-03)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("readActiveSessions (RSRC-03)", () => {
|
||||
it("returns only sessions whose score is within the 45s staleness threshold", async () => {
|
||||
const now = Date.now();
|
||||
const freshScore = now;
|
||||
const staleScore = now - 60_000; // 60s ago — beyond the 45s threshold
|
||||
|
||||
// ioredis WITHSCORES returns flat interleaved [member, score, member, score, ...]
|
||||
mockRedis.zrange.mockResolvedValue([
|
||||
"fresh",
|
||||
String(freshScore),
|
||||
"stale",
|
||||
String(staleScore),
|
||||
]);
|
||||
mockRedis.zrem.mockResolvedValue(1);
|
||||
|
||||
const sessions = await readActiveSessions("u1");
|
||||
|
||||
const ids = sessions.map((s) => s.sessionId);
|
||||
expect(ids).toContain("fresh");
|
||||
expect(ids).not.toContain("stale");
|
||||
});
|
||||
|
||||
it("each entry has { sessionId, lastSeen } shape", async () => {
|
||||
const now = Date.now();
|
||||
mockRedis.zrange.mockResolvedValue(["sess-a", String(now)]);
|
||||
mockRedis.zrem.mockResolvedValue(0);
|
||||
|
||||
const sessions = await readActiveSessions("u1");
|
||||
|
||||
expect(sessions).toHaveLength(1);
|
||||
expect(sessions[0]).toHaveProperty("sessionId", "sess-a");
|
||||
expect(sessions[0]).toHaveProperty("lastSeen");
|
||||
expect(typeof sessions[0].lastSeen).toBe("number");
|
||||
});
|
||||
|
||||
it("returns empty array when no sessions exist", async () => {
|
||||
mockRedis.zrange.mockResolvedValue([]);
|
||||
|
||||
const sessions = await readActiveSessions("u1");
|
||||
|
||||
expect(sessions).toEqual([]);
|
||||
});
|
||||
|
||||
it("scopes the ZSET query to the correct sessions key", async () => {
|
||||
mockRedis.zrange.mockResolvedValue([]);
|
||||
|
||||
await readActiveSessions("u1");
|
||||
|
||||
expect(mockRedis.zrange).toHaveBeenCalledWith(
|
||||
"globe:sessions:u1",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import { redis } from "@/lib/redis";
|
||||
import type { GlobeStateSnapshot } from "@/lib/globeState";
|
||||
|
||||
const STATE_TTL_SECONDS = 30;
|
||||
const STALE_THRESHOLD_MS = 45_000;
|
||||
|
||||
export function globeStateKey(userId: string, sessionId: string): string {
|
||||
return `globe:state:${userId}:${sessionId}`;
|
||||
}
|
||||
|
||||
export function globeSessionsKey(userId: string): string {
|
||||
return `globe:sessions:${userId}`;
|
||||
}
|
||||
|
||||
export async function writeGlobeState(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
snapshot: GlobeStateSnapshot,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await redis.set(globeStateKey(userId, sessionId), JSON.stringify(snapshot), "EX", STATE_TTL_SECONDS);
|
||||
await redis.zadd(globeSessionsKey(userId), Date.now(), sessionId);
|
||||
} catch (err) {
|
||||
console.warn("[globeStateStore] writeGlobeState failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function readGlobeState(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
): Promise<GlobeStateSnapshot | null> {
|
||||
try {
|
||||
const raw = await redis.get(globeStateKey(userId, sessionId));
|
||||
if (raw === null) return null;
|
||||
return JSON.parse(raw) as GlobeStateSnapshot;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readActiveSessions(
|
||||
userId: string,
|
||||
): Promise<Array<{ sessionId: string; lastSeen: number }>> {
|
||||
try {
|
||||
// ioredis WITHSCORES returns flat interleaved [member, score, member, score, ...]
|
||||
const flat = await redis.zrange(globeSessionsKey(userId), 0, -1, "WITHSCORES");
|
||||
const now = Date.now();
|
||||
const active: Array<{ sessionId: string; lastSeen: number }> = [];
|
||||
const stale: string[] = [];
|
||||
|
||||
for (let i = 0; i < flat.length; i += 2) {
|
||||
const member = flat[i];
|
||||
const score = Number(flat[i + 1]);
|
||||
if (now - score < STALE_THRESHOLD_MS) {
|
||||
active.push({ sessionId: member, lastSeen: score });
|
||||
} else {
|
||||
stale.push(member);
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort stale cleanup — never blocks or throws
|
||||
if (stale.length > 0) {
|
||||
redis.zrem(globeSessionsKey(userId), ...stale).catch(() => undefined);
|
||||
}
|
||||
|
||||
return active;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* Shared Zod coordinate schemas for MCP tool input validation.
|
||||
*
|
||||
* z.number() already rejects NaN (Zod coerces the raw input and NaN fails
|
||||
* the number check). .finite() additionally rejects Infinity/-Infinity.
|
||||
* Both checks are independent; .finite() does NOT cover NaN.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
export const latSchema = z.number().min(-90).max(90);
|
||||
export const lonSchema = z.number().min(-180).max(180);
|
||||
// altitude must be a positive finite number
|
||||
export const altSchema = z.number().gt(0).finite();
|
||||
@@ -1,266 +0,0 @@
|
||||
/**
|
||||
* RED tests for pluginTools (Phase 21 Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because src/lib/mcp/pluginTools.ts does not exist yet.
|
||||
* Wave 1 creates getNamespacedTools and the minimal input validator.
|
||||
*
|
||||
* PT-01 getNamespacedTools: auto-namespaces each tool to {pluginId}__{name}
|
||||
* PT-02 getNamespacedTools: preserves description, inputSchema, capabilities per tool
|
||||
* PT-03 getNamespacedTools: duplicate raw names across plugins stay distinct after namespacing
|
||||
* PT-04 Minimal validator: accepts args matching a schema (type/required/enum)
|
||||
* PT-05 Minimal validator: rejects args missing a required key
|
||||
* PT-06 Minimal validator: rejects args with wrong primitive type
|
||||
* PT-07 Minimal validator: rejects values outside an enum
|
||||
* PT-08 Minimal validator: uses no external schema library (hand-rolled)
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getNamespacedTools, validateToolArgs } from "@/lib/mcp/pluginTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types (mirrors what Wave 1 will export from pluginTools.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Shape of a namespaced tool entry returned by getNamespacedTools. */
|
||||
interface NamespacedTool {
|
||||
namespacedName: string;
|
||||
pluginId: string;
|
||||
description: string;
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Shape of the result returned by validateToolArgs. */
|
||||
interface ValidationResult {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A minimal McpToolDeclaration fixture (v3 -- no execution field). */
|
||||
function toolDecl(name: string, description = "A tool.") {
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
code: { type: "string" },
|
||||
count: { type: "number" },
|
||||
mode: { type: "string", enum: ["fast", "slow"] },
|
||||
},
|
||||
required: ["code"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A minimal plugin fixture that carries mcpTools. */
|
||||
function pluginEntry(pluginId: string, tools: ReturnType<typeof toolDecl>[]) {
|
||||
return { pluginId, mcpTools: tools };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-01: auto-namespacing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getNamespacedTools namespacing (PT-01)", () => {
|
||||
it("namespaces each tool to {pluginId}__{name}", () => {
|
||||
const plugins = [pluginEntry("aviation", [toolDecl("decode_squawk")])];
|
||||
const result = getNamespacedTools(plugins);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].namespacedName).toBe("aviation__decode_squawk");
|
||||
});
|
||||
|
||||
it("namespaces tools from multiple plugins independently", () => {
|
||||
const plugins = [
|
||||
pluginEntry("aviation", [toolDecl("decode_squawk")]),
|
||||
pluginEntry("maritime", [toolDecl("decode_mmsi")]),
|
||||
];
|
||||
const result = getNamespacedTools(plugins) as NamespacedTool[];
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
const names = result.map((t) => t.namespacedName);
|
||||
expect(names).toContain("aviation__decode_squawk");
|
||||
expect(names).toContain("maritime__decode_mmsi");
|
||||
});
|
||||
|
||||
it("handles a plugin with multiple tools", () => {
|
||||
const plugins = [
|
||||
pluginEntry("aviation", [toolDecl("decode_squawk"), toolDecl("lookup_flight")]),
|
||||
];
|
||||
const result = getNamespacedTools(plugins);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].namespacedName).toBe("aviation__decode_squawk");
|
||||
expect(result[1].namespacedName).toBe("aviation__lookup_flight");
|
||||
});
|
||||
|
||||
it("returns an empty array when no plugins have mcpTools", () => {
|
||||
const result = getNamespacedTools([]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-02: preserves tool metadata
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getNamespacedTools metadata preservation (PT-02)", () => {
|
||||
it("preserves description on the namespaced tool entry", () => {
|
||||
const plugins = [pluginEntry("aviation", [toolDecl("decode_squawk", "Squawk decoder.")])];
|
||||
const result = getNamespacedTools(plugins);
|
||||
|
||||
expect(result[0].description).toBe("Squawk decoder.");
|
||||
});
|
||||
|
||||
it("preserves inputSchema on the namespaced tool entry", () => {
|
||||
const plugins = [pluginEntry("aviation", [toolDecl("decode_squawk")])];
|
||||
const result = getNamespacedTools(plugins);
|
||||
|
||||
expect(result[0].inputSchema).toMatchObject({ type: "object" });
|
||||
});
|
||||
|
||||
it("carries the source pluginId on the namespaced tool entry", () => {
|
||||
const plugins = [pluginEntry("aviation", [toolDecl("decode_squawk")])];
|
||||
const result = getNamespacedTools(plugins);
|
||||
|
||||
expect(result[0].pluginId).toBe("aviation");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-03: duplicate raw names across plugins stay distinct after namespacing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getNamespacedTools deduplication across plugins (PT-03)", () => {
|
||||
it("keeps tools distinct when two plugins use the same raw tool name", () => {
|
||||
const plugins = [
|
||||
pluginEntry("aviation", [toolDecl("get_info")]),
|
||||
pluginEntry("maritime", [toolDecl("get_info")]),
|
||||
];
|
||||
const result = getNamespacedTools(plugins) as NamespacedTool[];
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
const names = result.map((t) => t.namespacedName);
|
||||
expect(names).toContain("aviation__get_info");
|
||||
expect(names).toContain("maritime__get_info");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-04: minimal validator -- accepts valid args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateToolArgs accepts valid args (PT-04)", () => {
|
||||
const schema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
code: { type: "string" },
|
||||
count: { type: "number" },
|
||||
mode: { type: "string", enum: ["fast", "slow"] },
|
||||
},
|
||||
required: ["code"],
|
||||
};
|
||||
|
||||
it("accepts args where required keys are present with correct types", () => {
|
||||
const result = validateToolArgs({ code: "7700" }, schema);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("accepts args that include optional keys with correct types", () => {
|
||||
const result = validateToolArgs({ code: "7700", count: 3, mode: "fast" }, schema);
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-05: missing required key
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateToolArgs rejects missing required key (PT-05)", () => {
|
||||
const schema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
code: { type: "string" },
|
||||
},
|
||||
required: ["code"],
|
||||
};
|
||||
|
||||
it("rejects args when a required property is absent", () => {
|
||||
const result = validateToolArgs({}, schema) as ValidationResult;
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some((e: string) => /code/i.test(e))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-06: wrong primitive type
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateToolArgs rejects wrong primitive type (PT-06)", () => {
|
||||
const schema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
code: { type: "string" },
|
||||
count: { type: "number" },
|
||||
},
|
||||
required: ["code", "count"],
|
||||
};
|
||||
|
||||
it("rejects a string where a number is expected", () => {
|
||||
const result = validateToolArgs({ code: "7700", count: "not-a-number" }, schema) as ValidationResult;
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some((e: string) => /count/i.test(e))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a number where a string is expected", () => {
|
||||
const result = validateToolArgs({ code: 123, count: 5 }, schema) as ValidationResult;
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some((e: string) => /code/i.test(e))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-07: enum validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateToolArgs rejects values outside enum (PT-07)", () => {
|
||||
const schema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
mode: { type: "string", enum: ["fast", "slow"] },
|
||||
},
|
||||
required: ["mode"],
|
||||
};
|
||||
|
||||
it("accepts a value that is in the enum", () => {
|
||||
const result = validateToolArgs({ mode: "fast" }, schema);
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a value that is not in the enum", () => {
|
||||
const result = validateToolArgs({ mode: "turbo" }, schema) as ValidationResult;
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.some((e: string) => /mode/i.test(e))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PT-08: no external schema library (hand-rolled)
|
||||
// This is a design assertion: the import above must come from a local module
|
||||
// that does not re-export zod, ajv, or any schema library.
|
||||
// Tested implicitly by the import path pointing to our own module.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateToolArgs hand-rolled (PT-08)", () => {
|
||||
it("validateToolArgs is exported from the local pluginTools module, not a schema lib", () => {
|
||||
// If the import at the top of this file resolves, the module exists.
|
||||
// This test will fail (RED) until Wave 1 creates src/lib/mcp/pluginTools.ts.
|
||||
expect(typeof validateToolArgs).toBe("function");
|
||||
expect(typeof getNamespacedTools).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* @file pluginTools.ts
|
||||
* @description Server-side helpers for plugin-declared MCP tools (Phase 21 Wave 1).
|
||||
*
|
||||
* Responsibilities:
|
||||
* - getNamespacedTools: collect tool declarations from plugins, auto-namespace
|
||||
* each to `{pluginId}__{name}` so names are globally unique.
|
||||
* - validateToolArgs: a minimal hand-rolled validator (type / required / enum)
|
||||
* that rejects bad input before the server enqueues a tool invocation.
|
||||
*
|
||||
* Design constraints (v3 frontend-relay):
|
||||
* - No external schema library (no zod, no ajv) -- hand-rolled only.
|
||||
* - McpToolDeclaration has NO `execution` field; the browser executes tools.
|
||||
* - This file is server-side only; no React / Cesium imports.
|
||||
*/
|
||||
|
||||
import type { McpToolDeclaration } from "@/core/plugins/PluginManifest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Minimal input schema shape used by McpToolDeclaration.
|
||||
* Only the subset the validator checks (type / properties / required / enum).
|
||||
*/
|
||||
export interface ToolInputSchema {
|
||||
type: "object";
|
||||
properties?: Record<string, PropertySchema>;
|
||||
required?: string[];
|
||||
}
|
||||
|
||||
/** Schema for a single property inside a ToolInputSchema. */
|
||||
export interface PropertySchema {
|
||||
type: string;
|
||||
enum?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A plugin entry as required by getNamespacedTools.
|
||||
* Only the fields this helper reads are required.
|
||||
*/
|
||||
export interface PluginToolsEntry {
|
||||
pluginId: string;
|
||||
mcpTools?: McpToolDeclaration[];
|
||||
mcpCapabilities?: string[];
|
||||
}
|
||||
|
||||
/** A fully-resolved, namespaced tool ready for inclusion in tools/list. */
|
||||
export interface NamespacedTool {
|
||||
/** The globally-unique tool name: `{pluginId}__{name}`. */
|
||||
namespacedName: string;
|
||||
/** The plugin that declared this tool. */
|
||||
pluginId: string;
|
||||
/** Human-readable description forwarded from the declaration. */
|
||||
description: string;
|
||||
/** Input schema forwarded from the declaration. */
|
||||
inputSchema: Record<string, unknown>;
|
||||
/**
|
||||
* Opaque capability tags declared by the source plugin.
|
||||
* Forwarded from PluginManifest.mcpCapabilities.
|
||||
*/
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
/** Result of a validateToolArgs call. */
|
||||
export interface ToolValidationResult {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getNamespacedTools
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Collect MCP tool declarations from a set of plugins and auto-namespace each
|
||||
* tool name to `{pluginId}__{name}`.
|
||||
*
|
||||
* Duplicate raw names across different plugins remain distinct because the
|
||||
* namespace prefix is always the plugin ID.
|
||||
*
|
||||
* @param plugins - Array of plugin entries (id + optional mcpTools + mcpCapabilities).
|
||||
* @returns Flat list of namespaced tool entries.
|
||||
*/
|
||||
export function getNamespacedTools(plugins: PluginToolsEntry[]): NamespacedTool[] {
|
||||
const result: NamespacedTool[] = [];
|
||||
|
||||
for (const plugin of plugins) {
|
||||
if (!plugin.mcpTools || plugin.mcpTools.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const capabilities = plugin.mcpCapabilities ?? [];
|
||||
|
||||
for (const tool of plugin.mcpTools) {
|
||||
result.push({
|
||||
namespacedName: `${plugin.pluginId}__${tool.name}`,
|
||||
pluginId: plugin.pluginId,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema as Record<string, unknown>,
|
||||
capabilities,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// validateToolArgs (hand-rolled, no external schema library)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Validate tool invocation arguments against a minimal input schema.
|
||||
*
|
||||
* Checks performed (in order):
|
||||
* 1. Required keys must be present.
|
||||
* 2. Present keys must have the correct primitive type.
|
||||
* 3. Keys with an `enum` constraint must match one of the allowed values.
|
||||
*
|
||||
* This validator REJECTS bad input -- it does NOT coerce or default values.
|
||||
* It is the server-side gate before enqueue (Wave 3 dependency).
|
||||
*
|
||||
* @param args - The raw arguments from the MCP client.
|
||||
* @param schema - The ToolInputSchema from the McpToolDeclaration.
|
||||
* @returns { valid, errors } -- errors is empty when valid is true.
|
||||
*/
|
||||
export function validateToolArgs(
|
||||
args: Record<string, unknown>,
|
||||
schema: ToolInputSchema,
|
||||
): ToolValidationResult {
|
||||
const errors: string[] = [];
|
||||
const properties = schema.properties ?? {};
|
||||
const required = schema.required ?? [];
|
||||
|
||||
// 1. Check required keys
|
||||
for (const key of required) {
|
||||
if (!(key in args) || args[key] === undefined || args[key] === null) {
|
||||
errors.push(`Missing required argument: "${key}"`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Type check + enum check for all present keys that have a schema
|
||||
for (const [key, propSchema] of Object.entries(properties)) {
|
||||
if (!(key in args)) {
|
||||
// Not present and not required -- skip
|
||||
continue;
|
||||
}
|
||||
|
||||
const value = args[key];
|
||||
|
||||
// 2a. Primitive type check
|
||||
// typeof null === "object", so guard null explicitly
|
||||
if (value === null || typeof value !== propSchema.type) {
|
||||
errors.push(
|
||||
`Argument "${key}" must be of type ${propSchema.type}, got ${value === null ? "null" : typeof value}`,
|
||||
);
|
||||
// Skip enum check when type is already wrong
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2b. Enum check (only when the property declares an enum)
|
||||
if (propSchema.enum && propSchema.enum.length > 0) {
|
||||
if (!propSchema.enum.includes(value as string)) {
|
||||
errors.push(
|
||||
`Argument "${key}" must be one of [${propSchema.enum.map((v) => `"${v}"`).join(", ")}], got "${String(value)}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* Tests for the MCP server factory (src/lib/mcp/server.ts).
|
||||
*
|
||||
* SRV-01 MCP_SERVER_INSTRUCTIONS is exported and contains "globe://sessions"
|
||||
* SRV-02 createMcpServer() passes a non-empty instructions string to McpServer
|
||||
* SRV-03 The instructions passed to McpServer contain "globe://sessions"
|
||||
* SRV-04 createMcpServer() also passes capabilities with tools.listChanged: true
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// vi.mock is hoisted above all imports by Vitest, so we cannot reference
|
||||
// module-scope variables inside the factory. Use vi.fn() inline and retrieve
|
||||
// the spy via vi.mocked() after the import is resolved.
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => ({
|
||||
McpServer: vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
// Imports resolved AFTER the mock factory above is registered.
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { createMcpServer, MCP_SERVER_INSTRUCTIONS } from "@/lib/mcp/server";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP_SERVER_INSTRUCTIONS export", () => {
|
||||
it("SRV-01: is a non-empty string that mentions globe://sessions", () => {
|
||||
expect(typeof MCP_SERVER_INSTRUCTIONS).toBe("string");
|
||||
expect(MCP_SERVER_INSTRUCTIONS.length).toBeGreaterThan(0);
|
||||
expect(MCP_SERVER_INSTRUCTIONS).toContain("globe://sessions");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createMcpServer()", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(McpServer).mockClear();
|
||||
});
|
||||
|
||||
it("SRV-02: passes a non-empty instructions string as the second arg", () => {
|
||||
createMcpServer();
|
||||
expect(vi.mocked(McpServer)).toHaveBeenCalledOnce();
|
||||
// mock.calls is typed as unknown[][], route through unknown to narrow safely.
|
||||
const call = vi.mocked(McpServer).mock.calls[0] as unknown as [
|
||||
unknown,
|
||||
{ instructions?: string },
|
||||
];
|
||||
const options = call[1];
|
||||
expect(typeof options?.instructions).toBe("string");
|
||||
expect((options?.instructions ?? "").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("SRV-03: instructions mention globe://sessions", () => {
|
||||
createMcpServer();
|
||||
const call = vi.mocked(McpServer).mock.calls[0] as unknown as [
|
||||
unknown,
|
||||
{ instructions?: string },
|
||||
];
|
||||
const options = call[1];
|
||||
expect(options?.instructions).toContain("globe://sessions");
|
||||
});
|
||||
|
||||
it("SRV-04: capabilities include tools.listChanged: true", () => {
|
||||
createMcpServer();
|
||||
const call = vi.mocked(McpServer).mock.calls[0] as unknown as [
|
||||
unknown,
|
||||
{ capabilities?: { tools?: { listChanged?: boolean } } },
|
||||
];
|
||||
const options = call[1];
|
||||
expect(options?.capabilities?.tools?.listChanged).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* MCP server factory -- Phase 17 (Stateless Streamable HTTP transport)
|
||||
*
|
||||
* createMcpServer() returns a FRESH McpServer instance on every call.
|
||||
* It is the single aggregation point where future phases register their
|
||||
* capabilities:
|
||||
*
|
||||
* Phase 18 -- registerGlobeResources(server, { userId }) -> globe:// resources
|
||||
* Phase 19 -- registerGlobeCommandTools(server, { userId }) -> globe control tools
|
||||
* Phase 20 -- registerDataQueryTools(server, { userId }) -> data query tools
|
||||
* Phase 21 -- dynamic per-plugin tools merged into tools/list
|
||||
*
|
||||
* Those registrars are NOT called here -- Phase 17 ships the transport only.
|
||||
* Each feature phase calls its own registrar from src/app/api/mcp/route.ts
|
||||
* AFTER createMcpServer() returns, passing { userId } via closure injection
|
||||
* (per RECONCILIATION R-1).
|
||||
*
|
||||
* Stateless invariant (D-17-04): never cache this instance. A fresh server
|
||||
* is created per request so no session state or transport binding leaks
|
||||
* between concurrent requests.
|
||||
*/
|
||||
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
|
||||
const SERVER_NAME = "worldwideview" as const;
|
||||
|
||||
// The MCP server's own protocol-advertised version. Bump this when the
|
||||
// server's self-description or tool surface changes in a meaningful way.
|
||||
// This is NOT package.json -- do not keep them in sync automatically.
|
||||
export const MCP_SERVER_VERSION = "1.2.0" as const;
|
||||
|
||||
export const MCP_SERVER_INSTRUCTIONS = `\
|
||||
WorldWideView MCP server. Read and control a live 3D geospatial globe for the authenticated user. Everything is scoped to your API key: you only ever see and control your own data and your own browser sessions.
|
||||
|
||||
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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
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.`;
|
||||
|
||||
/**
|
||||
* Returns a fresh, empty-capability McpServer per call.
|
||||
*
|
||||
* STATELESS (D-17-04): never cache this instance; a fresh server is created
|
||||
* per request. Do NOT hoist the return value to module scope.
|
||||
*/
|
||||
export function createMcpServer(): McpServer {
|
||||
return new McpServer(
|
||||
{ name: SERVER_NAME, version: MCP_SERVER_VERSION },
|
||||
{
|
||||
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 },
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
/**
|
||||
* 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. These tools operate on shared engine data and do not require
|
||||
* a userId — unlike the globe resource registrar, they are not scoped to a
|
||||
* specific authenticated user.
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import {
|
||||
searchEntities,
|
||||
getEntitiesInRegion,
|
||||
getEntityDetails,
|
||||
getPluginData,
|
||||
} from "@/lib/data-query/service";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Produces the standard MCP tool error response shape. */
|
||||
function toolError(msg: string): { content: [{ type: "text"; text: string }] } {
|
||||
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }] };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerDataQueryTools(server: McpServer): void {
|
||||
// TOOL-01: search_entities
|
||||
server.registerTool(
|
||||
"search_entities",
|
||||
{
|
||||
description:
|
||||
"Search for geospatial entities by name across active plugins. Returns up to 20 results with id, name, latitude, longitude, and pluginId. An empty result (count 0) means no match or no live data, not an error.",
|
||||
inputSchema: {
|
||||
query: z.string().describe("Search query string"),
|
||||
pluginId: z.string().optional().describe("Restrict search to a specific plugin"),
|
||||
limit: z.number().optional().describe("Maximum results to return (max 20)"),
|
||||
},
|
||||
},
|
||||
async (input) => {
|
||||
try {
|
||||
const results = await searchEntities(
|
||||
input.query,
|
||||
input.pluginId,
|
||||
Math.min(input.limit ?? 20, 20),
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ success: true, entities: results, count: results.length }),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("[mcp/tools] search_entities failed:", err);
|
||||
return toolError("Failed to search entities");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-02: get_entities_in_region
|
||||
server.registerTool(
|
||||
"get_entities_in_region",
|
||||
{
|
||||
description:
|
||||
"Find entities within a geographic bounding box. Returns up to 100 results. An empty result (count 0) means no match or no live data, not an error.",
|
||||
inputSchema: {
|
||||
north: latSchema.describe("Northern latitude bound"),
|
||||
south: latSchema.describe("Southern latitude bound"),
|
||||
east: lonSchema.describe("Eastern longitude bound"),
|
||||
west: lonSchema.describe("Western longitude bound"),
|
||||
pluginId: z.string().optional().describe("Restrict to a specific plugin"),
|
||||
limit: z.number().optional().describe("Maximum results to return (max 100)"),
|
||||
},
|
||||
},
|
||||
async (input) => {
|
||||
try {
|
||||
const results = await getEntitiesInRegion({
|
||||
north: input.north,
|
||||
south: input.south,
|
||||
east: input.east,
|
||||
west: input.west,
|
||||
pluginId: input.pluginId,
|
||||
limit: Math.min(input.limit ?? 100, 100),
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ success: true, entities: results, count: results.length }),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("[mcp/tools] get_entities_in_region failed:", err);
|
||||
return toolError("Failed to get entities in region");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-03: get_entity_details
|
||||
server.registerTool(
|
||||
"get_entity_details",
|
||||
{
|
||||
description:
|
||||
"Get full details for a single entity by pluginId and entityId.",
|
||||
inputSchema: {
|
||||
pluginId: z.string().describe("The plugin that owns this entity"),
|
||||
entityId: z.string().describe("The entity identifier"),
|
||||
},
|
||||
},
|
||||
async (input) => {
|
||||
try {
|
||||
const detail = await getEntityDetails(input.pluginId, input.entityId);
|
||||
if (detail === null) {
|
||||
return toolError("Entity not found");
|
||||
}
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ success: true, entity: detail }),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("[mcp/tools] get_entity_details failed:", err);
|
||||
return toolError("Failed to get entity details");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-04: get_plugin_data
|
||||
server.registerTool(
|
||||
"get_plugin_data",
|
||||
{
|
||||
description:
|
||||
"Get the current data snapshot (all entities) for a named plugin. An empty result (count 0) means no match or no live data, not an error.",
|
||||
inputSchema: {
|
||||
pluginId: z.string().describe("The plugin identifier"),
|
||||
},
|
||||
},
|
||||
async (input) => {
|
||||
try {
|
||||
const snapshot = await getPluginData(input.pluginId);
|
||||
if (snapshot === null) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({ success: true, entities: [], count: 0 }),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
success: true,
|
||||
entities: snapshot.entities ?? [],
|
||||
count: snapshot.entities?.length ?? 0,
|
||||
capturedAt: snapshot.timestamp,
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("[mcp/tools] get_plugin_data failed:", err);
|
||||
return toolError("Failed to get plugin data");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
/**
|
||||
* RED tests for the MCP request/response relay (Phase 21 Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because src/lib/mcpRelay.ts does not exist yet.
|
||||
* Wave 3 creates enqueueToolInvocation, waitForToolResult, and postToolResult.
|
||||
*
|
||||
* Security invariants encoded (cannot be regressed in later waves):
|
||||
* SEC-01 Every Redis key is scoped {userId}:{sessionId}
|
||||
* SEC-02 waitForToolResult returns a graceful timeout object, never hangs
|
||||
* SEC-03 postToolResult rejects a result whose requestId the session does not own
|
||||
* SEC-04 Arg size is capped (oversize rejected before enqueue)
|
||||
* SEC-05 Result size is capped (oversize rejected on postback)
|
||||
*
|
||||
* Mock style mirrors globeCommandQueue.test.ts (vi.hoisted + vi.mock on @/lib/redis).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
enqueueToolInvocation,
|
||||
waitForToolResult,
|
||||
postToolResult,
|
||||
} from "@/lib/mcpRelay";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock @/lib/redis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// vi.mock is hoisted above variable declarations; objects declared with vi.hoisted()
|
||||
// are accessible inside the factory function.
|
||||
const { mockRedis, mockMultiChain } = vi.hoisted(() => {
|
||||
// Chainable multi() mock: each method returns the chain; exec resolves successfully.
|
||||
const mockMultiChain = {
|
||||
rpush: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
set: vi.fn(),
|
||||
lrange: vi.fn(),
|
||||
del: vi.fn(),
|
||||
exec: vi.fn().mockResolvedValue([]),
|
||||
};
|
||||
mockMultiChain.rpush.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.expire.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.set.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.lrange.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.del.mockReturnValue(mockMultiChain);
|
||||
|
||||
const mockRedis = {
|
||||
set: vi.fn(),
|
||||
get: vi.fn(),
|
||||
rpush: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
blpop: vi.fn(),
|
||||
exists: vi.fn(),
|
||||
multi: vi.fn().mockReturnValue(mockMultiChain),
|
||||
};
|
||||
return { mockRedis, mockMultiChain };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: mockRedis,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: extract the first argument of the first call to a mock function
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function allFirstArgs(mockFn: ReturnType<typeof vi.fn>): string[] {
|
||||
return (mockFn.mock.calls as unknown[][]).map((c) => c[0] as string);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
// Restore multi chain fluent API after resetAllMocks() clears mockReturnValue.
|
||||
mockMultiChain.rpush.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.expire.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.set.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.lrange.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.del.mockReturnValue(mockMultiChain);
|
||||
mockMultiChain.exec.mockResolvedValue([]);
|
||||
mockRedis.multi.mockReturnValue(mockMultiChain);
|
||||
|
||||
// Direct-call mocks for blpop, exists, get (not on the multi chain).
|
||||
mockRedis.set.mockResolvedValue("OK");
|
||||
mockRedis.rpush.mockResolvedValue(1);
|
||||
mockRedis.expire.mockResolvedValue(1);
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
mockRedis.blpop.mockResolvedValue(null);
|
||||
mockRedis.exists.mockResolvedValue(0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RELAY-01: enqueueToolInvocation writes to Redis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("enqueueToolInvocation writes session-scoped invocation (RELAY-01)", () => {
|
||||
it("calls rpush on the multi chain with a key that includes userId and sessionId", async () => {
|
||||
await enqueueToolInvocation("u1", "s1", {
|
||||
requestId: "req-abc",
|
||||
tool: "aviation__decode_squawk",
|
||||
args: { squawk: "7700" },
|
||||
});
|
||||
|
||||
// enqueueToolInvocation uses multi().rpush().expire().set().exec() atomically.
|
||||
const allKeys = allFirstArgs(mockMultiChain.rpush);
|
||||
const scopedKey = allKeys.find((k) => k.includes("u1") && k.includes("s1"));
|
||||
expect(scopedKey).toBeDefined();
|
||||
});
|
||||
|
||||
it("the enqueued payload contains requestId, tool, and args", async () => {
|
||||
await enqueueToolInvocation("u1", "s1", {
|
||||
requestId: "req-abc",
|
||||
tool: "aviation__decode_squawk",
|
||||
args: { squawk: "7700" },
|
||||
});
|
||||
|
||||
// Payload is the second argument to chain.rpush(key, json).
|
||||
const rpushCalls = mockMultiChain.rpush.mock.calls as unknown[][];
|
||||
expect(rpushCalls.length).toBeGreaterThan(0);
|
||||
const payloadJson = rpushCalls[0][1] as string;
|
||||
|
||||
expect(payloadJson).toBeDefined();
|
||||
const payload: unknown = JSON.parse(payloadJson);
|
||||
expect(payload).toMatchObject({
|
||||
requestId: "req-abc",
|
||||
tool: "aviation__decode_squawk",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-01: all keys scoped {userId}:{sessionId}
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("all Redis keys scoped {userId}:{sessionId} (SEC-01)", () => {
|
||||
it("enqueueToolInvocation key contains both userId and sessionId", async () => {
|
||||
await enqueueToolInvocation("alice", "sess-X", {
|
||||
requestId: "r1",
|
||||
tool: "aviation__decode_squawk",
|
||||
args: {},
|
||||
});
|
||||
|
||||
// Both rpush (queue key) and set (owner key) go through the multi chain.
|
||||
const allKeys = [
|
||||
...allFirstArgs(mockMultiChain.rpush),
|
||||
...allFirstArgs(mockMultiChain.set),
|
||||
];
|
||||
const scopedKey = allKeys.find((k) => k.includes("alice") && k.includes("sess-X"));
|
||||
expect(scopedKey).toBeDefined();
|
||||
});
|
||||
|
||||
it("waitForToolResult polls a key that contains userId and sessionId", async () => {
|
||||
// Resolve immediately with a result so the function does not block
|
||||
mockRedis.blpop.mockResolvedValue(["result:alice:sess-Y:r1", JSON.stringify({ ok: true })]);
|
||||
|
||||
await waitForToolResult("alice", "sess-Y", "r1", 5000);
|
||||
|
||||
const allKeys = [
|
||||
...allFirstArgs(mockRedis.blpop),
|
||||
...allFirstArgs(mockRedis.get),
|
||||
];
|
||||
const scopedKey = allKeys.find((k) => k.includes("alice") && k.includes("sess-Y"));
|
||||
expect(scopedKey).toBeDefined();
|
||||
});
|
||||
|
||||
it("postToolResult writes to a key that contains userId and sessionId", async () => {
|
||||
mockRedis.exists.mockResolvedValue(1);
|
||||
|
||||
await postToolResult("u2", "s2", "r2", { data: "ok" });
|
||||
|
||||
// postToolResult uses multi().rpush().expire().exec() atomically.
|
||||
const allKeys = allFirstArgs(mockMultiChain.rpush);
|
||||
const scopedKey = allKeys.find((k) => k.includes("u2") && k.includes("s2"));
|
||||
expect(scopedKey).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-02: waitForToolResult -- graceful timeout (never hangs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("waitForToolResult graceful timeout (SEC-02)", () => {
|
||||
it("returns a timeout error object when no result appears before the deadline", async () => {
|
||||
// blpop returns null (simulates a timeout with a very short deadline)
|
||||
mockRedis.blpop.mockResolvedValue(null);
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
const result = await waitForToolResult("u1", "s1", "req-timeout", 100);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.timedOut).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT throw when the deadline passes with no result", async () => {
|
||||
mockRedis.blpop.mockResolvedValue(null);
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
waitForToolResult("u1", "s1", "req-timeout", 100),
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-03: postToolResult ownership check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("postToolResult rejects unowned requestId (SEC-03)", () => {
|
||||
it("rejects a result for a requestId not owned by the caller's session", async () => {
|
||||
mockRedis.exists.mockResolvedValue(0);
|
||||
|
||||
const result = await postToolResult("u1", "s1", "foreign-req", { data: "evil" });
|
||||
|
||||
expect(result.rejected).toBe(true);
|
||||
expect(mockRedis.rpush).not.toHaveBeenCalled();
|
||||
expect(mockRedis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a result for a requestId the session DOES own", async () => {
|
||||
mockRedis.exists.mockResolvedValue(1);
|
||||
|
||||
const result = await postToolResult("u1", "s1", "owned-req", { data: "ok" });
|
||||
|
||||
expect(result.rejected).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-04: arg size cap
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("enqueueToolInvocation arg size cap (SEC-04)", () => {
|
||||
it("rejects args whose JSON serialization exceeds the size cap", async () => {
|
||||
const oversizeArgs = { payload: "x".repeat(1_024 * 1_024) };
|
||||
|
||||
const result = await enqueueToolInvocation("u1", "s1", {
|
||||
requestId: "r-oversize",
|
||||
tool: "aviation__decode_squawk",
|
||||
args: oversizeArgs,
|
||||
});
|
||||
|
||||
expect(result.rejected).toBe(true);
|
||||
// Size guard fires before multi() is called -- chain must stay untouched.
|
||||
expect(mockRedis.multi).not.toHaveBeenCalled();
|
||||
expect(mockMultiChain.rpush).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts args within the size cap", async () => {
|
||||
const result = await enqueueToolInvocation("u1", "s1", {
|
||||
requestId: "r-normal",
|
||||
tool: "aviation__decode_squawk",
|
||||
args: { squawk: "7700" },
|
||||
});
|
||||
|
||||
expect(result.rejected).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-05: result size cap
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("postToolResult result size cap (SEC-05)", () => {
|
||||
it("rejects a result payload that exceeds the size cap", async () => {
|
||||
mockRedis.exists.mockResolvedValue(1);
|
||||
|
||||
const oversizeResult = { data: "x".repeat(1_024 * 1_024) };
|
||||
const result = await postToolResult("u1", "s1", "r-bigresult", oversizeResult);
|
||||
|
||||
expect(result.rejected).toBe(true);
|
||||
expect(mockRedis.rpush).not.toHaveBeenCalled();
|
||||
expect(mockRedis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a result within the size cap", async () => {
|
||||
mockRedis.exists.mockResolvedValue(1);
|
||||
|
||||
const result = await postToolResult("u1", "s1", "r-normal", { squawkMeaning: "Emergency" });
|
||||
|
||||
expect(result.rejected).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,300 +0,0 @@
|
||||
/**
|
||||
* @file mcpRelay.ts
|
||||
* @description Redis request/response relay for plugin tool invocations (Phase 21 Wave 3 -- PLUG-03).
|
||||
*
|
||||
* The server enqueues an invocation for the browser to pick up, then waits on a
|
||||
* result list using blpop with a deadline. The browser executes the tool and
|
||||
* posts the result back via RPUSH. The server returns the result or a graceful
|
||||
* timeout to the MCP agent.
|
||||
*
|
||||
* Redis key layout (all scoped by userId + sessionId):
|
||||
* Invocation queue: mcp:invocations:{userId}:{sessionId} (RPUSH list)
|
||||
* Invocation owner: mcp:inv-owner:{userId}:{sessionId}:{requestId} (SET -- ownership record)
|
||||
* Result list: mcp:result:{userId}:{sessionId}:{requestId} (RPUSH by browser, BLPOP by server)
|
||||
*
|
||||
* Server-side wait approach: blpop with a per-request timeout (converted from ms to seconds).
|
||||
* This is simpler and more responsive than a poll loop, and avoids busy-waiting.
|
||||
* blpop is available on the ioredis client via the extended type cast; it is NOT declared
|
||||
* on the narrow RedisClient interface in redis.ts (which is intentionally kept minimal).
|
||||
*
|
||||
* Security invariants (Wave 0 / SEC-01..05):
|
||||
* SEC-01 All keys scoped {userId}:{sessionId}.
|
||||
* SEC-02 waitForToolResult uses blpop with a bounded deadline; returns a timeout object on expiry. NEVER throws.
|
||||
* SEC-03 postToolResult checks ownership before writing.
|
||||
* SEC-04 Arg payload is size-capped before enqueue.
|
||||
* SEC-05 Result payload is size-capped before write.
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
import type { RedisMultiChain } from "@/lib/redis";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extended redis type -- adds exists() and blpop() which are declared in
|
||||
// ioredis but not in our narrow RedisClient interface. Casting avoids
|
||||
// modifying redis.ts.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface ExtendedRedisClient {
|
||||
set(key: string, value: string, exFlag: "EX", ttlSeconds: number): Promise<string | null>;
|
||||
get(key: string): Promise<string | null>;
|
||||
rpush(key: string, ...values: string[]): Promise<number>;
|
||||
expire(key: string, seconds: number): Promise<number>;
|
||||
exists(key: string): Promise<number>;
|
||||
/**
|
||||
* BLPOP with a per-call timeout in seconds.
|
||||
* Returns [key, value] tuple on success, null on timeout.
|
||||
* Used for server-side wait on the result list.
|
||||
*/
|
||||
blpop(key: string, timeout: number): Promise<[string, string] | null>;
|
||||
multi(): RedisMultiChain;
|
||||
}
|
||||
|
||||
const redisExt = redis as unknown as ExtendedRedisClient;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** TTL for the invocation queue list (seconds). */
|
||||
const INVOCATION_TTL_SECONDS = 120;
|
||||
|
||||
/** TTL for the ownership record key (seconds). */
|
||||
const OWNER_TTL_SECONDS = 300;
|
||||
|
||||
/** TTL for the result list after the browser writes to it (seconds). */
|
||||
const RESULT_TTL_SECONDS = 120;
|
||||
|
||||
/** Maximum allowed byte size for serialized tool args (~64 KB). */
|
||||
const MAX_ARG_BYTES = 64 * 1024;
|
||||
|
||||
/** Maximum allowed byte size for serialized result payload (~512 KB). */
|
||||
const MAX_RESULT_BYTES = 512 * 1024;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Key helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function invocationQueueKey(userId: string, sessionId: string): string {
|
||||
return `mcp:invocations:${userId}:${sessionId}`;
|
||||
}
|
||||
|
||||
function ownerKey(userId: string, sessionId: string, requestId: string): string {
|
||||
return `mcp:inv-owner:${userId}:${sessionId}:${requestId}`;
|
||||
}
|
||||
|
||||
function resultKey(userId: string, sessionId: string, requestId: string): string {
|
||||
return `mcp:result:${userId}:${sessionId}:${requestId}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A single tool invocation payload stored in the queue. */
|
||||
export interface ToolInvocation {
|
||||
requestId: string;
|
||||
tool: string;
|
||||
args: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Return shape of enqueueToolInvocation and postToolResult. */
|
||||
export interface RelayOpResult {
|
||||
rejected: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/** Return shape of waitForToolResult. */
|
||||
export interface ToolResultOrTimeout {
|
||||
timedOut: boolean;
|
||||
value?: unknown;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// enqueueToolInvocation (RELAY-01, SEC-01, SEC-04)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Write a namespaced tool invocation to the session-scoped Redis list.
|
||||
* Also writes an ownership record so postToolResult can verify the requestId.
|
||||
*
|
||||
* Rejects (returns { rejected: true }) if the serialized args exceed MAX_ARG_BYTES.
|
||||
*/
|
||||
export async function enqueueToolInvocation(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
invocation: ToolInvocation,
|
||||
): Promise<RelayOpResult> {
|
||||
const json = JSON.stringify(invocation);
|
||||
if (Buffer.byteLength(json, "utf8") > MAX_ARG_BYTES) {
|
||||
return { rejected: true, reason: "args payload too large" };
|
||||
}
|
||||
|
||||
const qKey = invocationQueueKey(userId, sessionId);
|
||||
const oKey = ownerKey(userId, sessionId, invocation.requestId);
|
||||
|
||||
try {
|
||||
await redisExt
|
||||
.multi()
|
||||
.rpush(qKey, json)
|
||||
.expire(qKey, INVOCATION_TTL_SECONDS)
|
||||
.set(oKey, "1", "EX", OWNER_TTL_SECONDS)
|
||||
.exec();
|
||||
} catch (err) {
|
||||
console.error("[mcpRelay] enqueueToolInvocation failed:", err);
|
||||
return { rejected: true, reason: "enqueue failed" };
|
||||
}
|
||||
|
||||
return { rejected: false };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// waitForToolResult (SEC-01, SEC-02)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Wait for the browser to post a result by blocking on the result list with blpop.
|
||||
* The timeout is the deadlineMs converted to seconds (rounded up, minimum 1s).
|
||||
*
|
||||
* NEVER throws. Returns { timedOut: true } when blpop returns null (deadline passed).
|
||||
*
|
||||
* Server-side wait approach: blpop. The ioredis client supports blpop natively;
|
||||
* it is accessed via the ExtendedRedisClient cast to avoid widening the narrow
|
||||
* RedisClient interface declared in redis.ts.
|
||||
*/
|
||||
export async function waitForToolResult(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
deadlineMs: number,
|
||||
): Promise<ToolResultOrTimeout> {
|
||||
const rKey = resultKey(userId, sessionId, requestId);
|
||||
const timeoutSeconds = Math.max(1, Math.ceil(deadlineMs / 1000));
|
||||
|
||||
try {
|
||||
const reply = await redisExt.blpop(rKey, timeoutSeconds);
|
||||
if (reply === null) {
|
||||
return { timedOut: true, error: "Plugin tool did not respond before the deadline." };
|
||||
}
|
||||
|
||||
// reply is [key, value]; parse the value.
|
||||
const raw = reply[1];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return { timedOut: false, value: parsed };
|
||||
} catch {
|
||||
return { timedOut: false, value: raw };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[mcpRelay] waitForToolResult failed:", err);
|
||||
// Return a graceful error object -- never throw to the caller.
|
||||
return { timedOut: true, error: "Plugin tool relay encountered an error." };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// postToolResult (SEC-01, SEC-03, SEC-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Write the browser-executed tool result to the session-scoped result list.
|
||||
* The server's blpop call on the same key will unblock when this RPUSH fires.
|
||||
*
|
||||
* Rejects (returns { rejected: true }) when:
|
||||
* - The requestId is not owned by this session (ownership check via EXISTS).
|
||||
* - The serialized result exceeds MAX_RESULT_BYTES.
|
||||
*/
|
||||
export async function postToolResult(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
result: unknown,
|
||||
): Promise<RelayOpResult> {
|
||||
// SEC-03: Ownership check -- the requestId must be owned by this session.
|
||||
const oKey = ownerKey(userId, sessionId, requestId);
|
||||
let owned = false;
|
||||
try {
|
||||
const existsVal = await redisExt.exists(oKey);
|
||||
owned = existsVal === 1;
|
||||
} catch (err) {
|
||||
console.error("[mcpRelay] postToolResult ownership check failed:", err);
|
||||
return { rejected: true, reason: "ownership check error" };
|
||||
}
|
||||
|
||||
if (!owned) {
|
||||
return { rejected: true, reason: "requestId not owned by this session" };
|
||||
}
|
||||
|
||||
// SEC-05: Result size cap.
|
||||
const json = JSON.stringify(result);
|
||||
if (Buffer.byteLength(json, "utf8") > MAX_RESULT_BYTES) {
|
||||
return { rejected: true, reason: "result payload too large" };
|
||||
}
|
||||
|
||||
const rKey = resultKey(userId, sessionId, requestId);
|
||||
try {
|
||||
// RPUSH to the result list; the server's blpop on the same key unblocks.
|
||||
await redisExt.multi().rpush(rKey, json).expire(rKey, RESULT_TTL_SECONDS).exec();
|
||||
} catch (err) {
|
||||
console.error("[mcpRelay] postToolResult write failed:", err);
|
||||
}
|
||||
|
||||
return { rejected: false };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// drainToolInvocations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Atomically drain all pending tool invocations for a session.
|
||||
* Mirrors drainGlobeCommands from globeCommandQueue.ts.
|
||||
*/
|
||||
export async function drainToolInvocations(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
): Promise<ToolInvocation[]> {
|
||||
const qKey = invocationQueueKey(userId, sessionId);
|
||||
try {
|
||||
const results = await redisExt.multi().lrange(qKey, 0, -1).del(qKey).exec();
|
||||
|
||||
const lrangeReply = results[0];
|
||||
if (!lrangeReply || lrangeReply[0] !== null) return [];
|
||||
|
||||
const raw = lrangeReply[1];
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const invocations: ToolInvocation[] = [];
|
||||
for (const entry of raw) {
|
||||
if (typeof entry !== "string") continue;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(entry);
|
||||
if (isToolInvocation(parsed)) {
|
||||
invocations.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// Drop unparseable entries silently.
|
||||
}
|
||||
}
|
||||
|
||||
return invocations;
|
||||
} catch (err) {
|
||||
console.error("[mcpRelay] drainToolInvocations failed:", err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isToolInvocation(value: unknown): value is ToolInvocation {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.requestId === "string" &&
|
||||
typeof v.tool === "string" &&
|
||||
typeof v.args === "object" &&
|
||||
v.args !== null
|
||||
);
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/**
|
||||
* RED tests for mcpSessionCatalog (Phase 21 Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because src/lib/mcpSessionCatalog.ts does not exist yet.
|
||||
* Wave 2 creates publishSessionCatalog and readSessionCatalog.
|
||||
*
|
||||
* CAT-01 publishSessionCatalog stores the catalog under a Redis key scoped {userId}:{sessionId}
|
||||
* CAT-02 publishSessionCatalog sets a TTL on the catalog key
|
||||
* CAT-03 readSessionCatalog returns the stored catalog for a known session
|
||||
* CAT-04 readSessionCatalog returns null for an unknown session
|
||||
* CAT-05 Redis key includes BOTH userId and sessionId (cross-session isolation)
|
||||
* CAT-06 A catalog published for sessionA is not returned for sessionB of the same user
|
||||
*
|
||||
* Mock style mirrors globeCommandQueue.test.ts (vi.hoisted + vi.mock on @/lib/redis).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { publishSessionCatalog, readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock @/lib/redis
|
||||
// vi.mock is hoisted above variable declarations; objects declared with vi.hoisted()
|
||||
// are accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockRedis } = vi.hoisted(() => {
|
||||
const mockRedis = {
|
||||
set: vi.fn().mockResolvedValue("OK"),
|
||||
get: vi.fn().mockResolvedValue(null),
|
||||
};
|
||||
return { mockRedis };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: mockRedis,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const FIXTURE_CATALOG = {
|
||||
tools: [
|
||||
{
|
||||
namespacedName: "aviation__decode_squawk",
|
||||
pluginId: "aviation",
|
||||
description: "Decodes a squawk code.",
|
||||
inputSchema: { type: "object" as const, properties: { squawk: { type: "string" } } },
|
||||
},
|
||||
],
|
||||
capabilities: ["point-layer"],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockRedis.set.mockResolvedValue("OK");
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-01: publishSessionCatalog writes to Redis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("publishSessionCatalog writes catalog (CAT-01)", () => {
|
||||
it("calls redis.set with the catalog JSON", async () => {
|
||||
await publishSessionCatalog("u1", "s1", FIXTURE_CATALOG);
|
||||
|
||||
expect(mockRedis.set).toHaveBeenCalledTimes(1);
|
||||
const args0 = mockRedis.set.mock.calls[0] as unknown as [string, string, "EX", number];
|
||||
const parsed: unknown = JSON.parse(args0[1]);
|
||||
expect(parsed).toMatchObject({
|
||||
tools: expect.arrayContaining([
|
||||
expect.objectContaining({ namespacedName: "aviation__decode_squawk" }),
|
||||
]),
|
||||
capabilities: ["point-layer"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-02: publishSessionCatalog sets a TTL
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("publishSessionCatalog TTL (CAT-02)", () => {
|
||||
it("calls redis.set with EX flag and a positive TTL in seconds", async () => {
|
||||
await publishSessionCatalog("u1", "s1", FIXTURE_CATALOG);
|
||||
|
||||
const args1 = mockRedis.set.mock.calls[0] as unknown as [string, string, "EX", number];
|
||||
expect(args1[2]).toBe("EX");
|
||||
expect(typeof args1[3]).toBe("number");
|
||||
expect(args1[3]).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-05: Redis key includes BOTH userId and sessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("publishSessionCatalog key scoping (CAT-05)", () => {
|
||||
it("includes userId in the Redis key", async () => {
|
||||
await publishSessionCatalog("alice", "sess-abc", FIXTURE_CATALOG);
|
||||
|
||||
const keyScoping = (mockRedis.set.mock.calls[0] as unknown as [string, ...unknown[]])[0];
|
||||
expect(keyScoping).toContain("alice");
|
||||
});
|
||||
|
||||
it("includes sessionId in the Redis key", async () => {
|
||||
await publishSessionCatalog("alice", "sess-abc", FIXTURE_CATALOG);
|
||||
|
||||
const keyScoping = (mockRedis.set.mock.calls[0] as unknown as [string, ...unknown[]])[0];
|
||||
expect(keyScoping).toContain("sess-abc");
|
||||
});
|
||||
|
||||
it("includes BOTH userId and sessionId in the Redis key", async () => {
|
||||
await publishSessionCatalog("alice", "sess-abc", FIXTURE_CATALOG);
|
||||
|
||||
const keyScoping = (mockRedis.set.mock.calls[0] as unknown as [string, ...unknown[]])[0];
|
||||
expect(keyScoping).toContain("alice");
|
||||
expect(keyScoping).toContain("sess-abc");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-03: readSessionCatalog returns the stored catalog
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("readSessionCatalog returns catalog (CAT-03)", () => {
|
||||
it("returns the parsed catalog for a known session", async () => {
|
||||
mockRedis.get.mockResolvedValue(JSON.stringify(FIXTURE_CATALOG));
|
||||
|
||||
const result = await readSessionCatalog("u1", "s1");
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.tools).toHaveLength(1);
|
||||
expect(result?.capabilities).toEqual(["point-layer"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-04: readSessionCatalog returns null for unknown session
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("readSessionCatalog returns null for unknown session (CAT-04)", () => {
|
||||
it("returns null when the Redis key does not exist", async () => {
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
const result = await readSessionCatalog("u1", "unknown-session");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CAT-06: cross-session isolation -- catalogA not returned for sessionB
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("readSessionCatalog cross-session isolation (CAT-06)", () => {
|
||||
it("does NOT return sessionA catalog when reading sessionB for the same user", async () => {
|
||||
// Publish to sessionA key: record the key used
|
||||
await publishSessionCatalog("u1", "sess-A", FIXTURE_CATALOG);
|
||||
const sessionAKey = (mockRedis.set.mock.calls[0] as unknown as [string, ...unknown[]])[0];
|
||||
|
||||
// Simulate: sessionB key returns null (different key)
|
||||
mockRedis.get.mockImplementation((key: unknown) => {
|
||||
if (key === sessionAKey) return Promise.resolve(JSON.stringify(FIXTURE_CATALOG));
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
|
||||
const result = await readSessionCatalog("u1", "sess-B");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("readSessionCatalog uses BOTH userId and sessionId to form the key", async () => {
|
||||
await readSessionCatalog("u2", "sess-XYZ");
|
||||
|
||||
const key = (mockRedis.get.mock.calls[0] as unknown as [string])[0];
|
||||
expect(key).toContain("u2");
|
||||
expect(key).toContain("sess-XYZ");
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* @file mcpSessionCatalog.ts
|
||||
* @description Per-session MCP plugin catalog store (Phase 21 Wave 2).
|
||||
*
|
||||
* The browser tab POSTs its loaded plugins' mcpTools + mcpCapabilities to
|
||||
* a Redis key scoped {userId}:{sessionId} with a TTL. The stateless MCP
|
||||
* route reads this catalog to compose tools/list dynamically.
|
||||
*
|
||||
* Design:
|
||||
* - publishSessionCatalog: redis.set(..., "EX", TTL) -- single atomic write.
|
||||
* - readSessionCatalog: redis.get + JSON.parse -- returns null on miss/error.
|
||||
* - Key includes BOTH userId and sessionId; cross-session isolation is enforced
|
||||
* by key scoping alone (no user-supplied identity accepted at read time).
|
||||
* - Payload size is capped before write; oversized payloads are rejected silently.
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** TTL in seconds for a catalog entry. Re-published periodically by the browser hook. */
|
||||
const CATALOG_TTL_SECONDS = 120;
|
||||
|
||||
/** Maximum allowed serialized payload size in bytes (~64 KB). */
|
||||
const MAX_CATALOG_BYTES = 64 * 1024;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A single namespaced plugin tool entry in the per-session catalog. */
|
||||
export interface CatalogTool {
|
||||
namespacedName: string;
|
||||
pluginId: string;
|
||||
description: string;
|
||||
inputSchema: Record<string, unknown>;
|
||||
mcpCapabilities?: string[];
|
||||
}
|
||||
|
||||
/** The catalog payload published by the browser and read by the server. */
|
||||
export interface SessionCatalog {
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Key helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function catalogKey(userId: string, sessionId: string): string {
|
||||
return `mcp:catalog:${userId}:${sessionId}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publishSessionCatalog (CAT-01, CAT-02, CAT-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Stores the browser-published plugin catalog under a Redis key scoped to
|
||||
* both userId and sessionId, with a TTL.
|
||||
*
|
||||
* userId MUST come from the server-side auth result -- never from the request body.
|
||||
* Oversized payloads are silently dropped (caller should validate before calling).
|
||||
*/
|
||||
export async function publishSessionCatalog(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
catalog: SessionCatalog,
|
||||
): Promise<void> {
|
||||
const json = JSON.stringify(catalog);
|
||||
|
||||
if (Buffer.byteLength(json, "utf8") > MAX_CATALOG_BYTES) {
|
||||
console.error(
|
||||
"[mcpSessionCatalog] publishSessionCatalog rejected oversized payload for",
|
||||
userId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const key = catalogKey(userId, sessionId);
|
||||
try {
|
||||
await redis.set(key, json, "EX", CATALOG_TTL_SECONDS);
|
||||
} catch (err) {
|
||||
console.error("[mcpSessionCatalog] publishSessionCatalog failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// readSessionCatalog (CAT-03, CAT-04, CAT-06)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns the stored catalog for a specific user+session, or null if not found.
|
||||
*
|
||||
* The key includes both userId and sessionId, so reading a different sessionId
|
||||
* for the same user returns null -- cross-session isolation enforced by key shape.
|
||||
*/
|
||||
export async function readSessionCatalog(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
): Promise<SessionCatalog | null> {
|
||||
const key = catalogKey(userId, sessionId);
|
||||
try {
|
||||
const raw = await redis.get(key);
|
||||
if (!raw) return null;
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (isSessionCatalog(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.error("[mcpSessionCatalog] readSessionCatalog failed:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Type guard
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isSessionCatalog(value: unknown): value is SessionCatalog {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return Array.isArray(v.tools) && Array.isArray(v.capabilities);
|
||||
}
|
||||
+1
-56
@@ -1,6 +1,4 @@
|
||||
import { RateLimiter, getClientIp } from "./rateLimit";
|
||||
|
||||
export { getClientIp };
|
||||
import { RateLimiter } from "./rateLimit";
|
||||
|
||||
/**
|
||||
* Pre-configured rate limiters for sensitive API endpoints.
|
||||
@@ -42,56 +40,3 @@ export const authLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 10,
|
||||
});
|
||||
|
||||
// TODO: move mcpLimiter and apiKeyManagementLimiter to @upstash/ratelimit for
|
||||
// multi-replica deployments — in-process limiters are per-replica and do not
|
||||
// share state across horizontal scale-out.
|
||||
|
||||
/**
|
||||
* GET /api/globe/commands — browser poll at ~1500ms across a small number of tabs.
|
||||
* 120 req/60s per IP comfortably covers several simultaneous tabs with headroom.
|
||||
*/
|
||||
export const globeCommandsLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 120,
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/globe/commands/stream -- SSE push transport (Phase 19b).
|
||||
* SSE is a long-lived connection, not a burst. One connection per tab per session.
|
||||
* 10 req/60s per IP: covers normal tab open/reconnect cycles with headroom.
|
||||
*/
|
||||
export const globeCommandsStreamLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 10,
|
||||
});
|
||||
|
||||
/** /api/mcp — prevents scan/DoS before the expensive auth layer runs. */
|
||||
export const mcpLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 60,
|
||||
});
|
||||
|
||||
/** /api/api-keys GET/POST/DELETE — prevents enumeration and creation spam. */
|
||||
export const apiKeyManagementLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 10,
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/mcp/invocations -- browser bridge polls for pending tool invocations.
|
||||
* 120 req/60s per IP mirrors globeCommandsLimiter (several tabs at ~1500ms).
|
||||
*/
|
||||
export const mcpInvocationsLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 120,
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/mcp/results -- browser bridge posts tool execution results.
|
||||
* 60 req/60s per IP: one result per invocation, invocations are bounded.
|
||||
*/
|
||||
export const mcpResultsLimiter = new RateLimiter({
|
||||
windowMs: 60_000,
|
||||
maxRequests: 60,
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import Redis from "ioredis";
|
||||
|
||||
// Narrow interface covering only the commands this app uses directly.
|
||||
// Exporting this type (rather than the full Redis class) keeps test mocks simple.
|
||||
export interface RedisMultiChain {
|
||||
lrange(key: string, start: number, stop: number): this;
|
||||
del(key: string): this;
|
||||
rpush(key: string, ...values: string[]): this;
|
||||
expire(key: string, seconds: number): this;
|
||||
set(key: string, value: string, exFlag: "EX", ttlSeconds: number): this;
|
||||
exec(): Promise<Array<[Error | null, unknown]>>;
|
||||
}
|
||||
|
||||
export interface RedisClient {
|
||||
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>;
|
||||
zrange(key: string, start: number | string, stop: number | string, withScores: "WITHSCORES"): Promise<string[]>;
|
||||
zrem(key: string, ...members: string[]): Promise<number>;
|
||||
rpush(key: string, ...values: string[]): Promise<number>;
|
||||
expire(key: string, seconds: number): Promise<number>;
|
||||
multi(): RedisMultiChain;
|
||||
}
|
||||
|
||||
const client = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", {
|
||||
retryStrategy(times) {
|
||||
if (times > 10) return null;
|
||||
return Math.min(times * 50, 2000);
|
||||
},
|
||||
maxRetriesPerRequest: 3,
|
||||
lazyConnect: true,
|
||||
});
|
||||
|
||||
// Graceful degrade: connectivity issues are logged but never thrown.
|
||||
client.on("error", (err) => {
|
||||
console.warn("[Redis] connection error:", err);
|
||||
});
|
||||
|
||||
export const redis: RedisClient = client as unknown as RedisClient;
|
||||
@@ -24,36 +24,28 @@
|
||||
}
|
||||
|
||||
.geojson-btn--primary {
|
||||
background: var(--bg-glass);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid rgba(var(--accent-rgb), 0.3);
|
||||
background: linear-gradient(135deg, #00e5ff 0%, #00b0ff 100%);
|
||||
color: #0a0e17;
|
||||
}
|
||||
|
||||
.geojson-btn--primary:hover:not(:disabled) {
|
||||
background: var(--bg-glass-hover);
|
||||
box-shadow: var(--glass-shadow-inner);
|
||||
box-shadow: 0 0 16px rgba(0, 229, 255, 0.4);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.geojson-btn--primary:active:not(:disabled) {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.geojson-btn--primary:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.geojson-btn--secondary {
|
||||
background: var(--bg-glass);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--glass-border-inner);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.geojson-btn--secondary:hover:not(:disabled) {
|
||||
background: var(--bg-glass-hover);
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
|
||||
.geojson-btn--secondary:disabled {
|
||||
@@ -95,7 +87,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--glass-border-inner);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.geojson-modal__header h3 {
|
||||
@@ -125,7 +117,7 @@
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 12px 20px;
|
||||
border-bottom: 1px solid var(--glass-border-inner);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.geojson-tab {
|
||||
@@ -144,13 +136,13 @@
|
||||
}
|
||||
|
||||
.geojson-tab:hover {
|
||||
background: rgba(var(--accent-rgb), 0.06);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.geojson-tab--active {
|
||||
background: rgba(var(--accent-rgb), 0.12);
|
||||
color: var(--accent-cyan);
|
||||
background: rgba(0, 229, 255, 0.12);
|
||||
color: #00e5ff;
|
||||
}
|
||||
|
||||
/* ─── Body ────────────────────────────────────────────────── */
|
||||
@@ -171,7 +163,7 @@
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 32px 20px;
|
||||
border: 2px dashed rgba(var(--accent-rgb), 0.2);
|
||||
border: 2px dashed rgba(255, 255, 255, 0.15);
|
||||
border-radius: 10px;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
@@ -181,9 +173,9 @@
|
||||
|
||||
.geojson-dropzone:hover,
|
||||
.geojson-dropzone--active {
|
||||
border-color: var(--accent-cyan);
|
||||
background: rgba(var(--accent-rgb), 0.04);
|
||||
color: var(--accent-cyan);
|
||||
border-color: #00e5ff;
|
||||
background: rgba(0, 229, 255, 0.04);
|
||||
color: #00e5ff;
|
||||
}
|
||||
|
||||
.geojson-dropzone p {
|
||||
@@ -202,9 +194,9 @@
|
||||
width: 100%;
|
||||
min-height: 140px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--glass-border-inner);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-secondary);
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
color: var(--text-primary);
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
font-size: 12px;
|
||||
@@ -214,7 +206,7 @@
|
||||
|
||||
.geojson-textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-cyan);
|
||||
border-color: #00e5ff;
|
||||
}
|
||||
|
||||
/* ─── Inputs ──────────────────────────────────────────────── */
|
||||
@@ -222,9 +214,9 @@
|
||||
.geojson-input {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--glass-border-inner);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-secondary);
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
transition: border-color 0.2s;
|
||||
@@ -232,7 +224,7 @@
|
||||
|
||||
.geojson-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-cyan);
|
||||
border-color: #00e5ff;
|
||||
}
|
||||
|
||||
.geojson-input::placeholder {
|
||||
@@ -253,7 +245,7 @@
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
border: 2px solid var(--glass-border-inner);
|
||||
border: 2px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
@@ -264,8 +256,8 @@
|
||||
.geojson-preview {
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
background: rgba(var(--accent-rgb), 0.06);
|
||||
border: 1px solid rgba(var(--accent-rgb), 0.15);
|
||||
background: rgba(0, 229, 255, 0.06);
|
||||
border: 1px solid rgba(0, 229, 255, 0.15);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
@@ -307,7 +299,7 @@
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 20px;
|
||||
border-top: 1px solid var(--glass-border-inner);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
/* ─── Layer List ──────────────────────────────────────────── */
|
||||
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user