Compare commits

..
Author SHA1 Message Date
Antigravity AI 8134e2b890 docs(v1.3): mark Location Intelligence milestone complete
All 4 phases (22-25) shipped: geocoding+favorites, entity filtering,
route wiring + MCP_SERVER_VERSION 1.3.0, and documentation.
Milestone audit: SHIP (18/18 requirements). Browser UAT: PASS (8/8 tools).

Bump 2.46.5 -> 2.46.6.
2026-05-31 14:04:55 +12:00
Antigravity AI f1405bd313 docs(25-01): add v1.3.0 changelog entry (DOC-04)
- lists all 8 new MCP tools, search_entities filters enhancement, MCP_SERVER_VERSION 1.3.0 bump
- bump 2.46.4 -> 2.46.5
2026-05-31 13:38:05 +12:00
Antigravity AI 2eec714912 docs(25-01): list v1.3 tools in ConnectAgentHelper prompt (DOC-03)
- agent capabilities prompt now enumerates all 12 callable MCP tools with one-line descriptions
- links plugin authors to docs/plugin-filter-guide.md
- bump 2.46.3 -> 2.46.4
2026-05-31 13:37:40 +12:00
Antigravity AI 26d2063a1e docs(25-01): add plugin filter guide with flights worked example (DOC-02)
- explains getFilterDefinitions, FilterDefinition/FilterValue shapes, get_plugin_filters/set_filter flow
- bump 2.46.2 -> 2.46.3
2026-05-31 13:37:06 +12:00
Antigravity AI 84f8ade70c docs(25-01): enrich v1.3 MCP tool descriptions (DOC-01)
- geocode_location/fly_to/save_favorite/list_favorites/remove_favorite/set_filter/clear_filter/get_plugin_filters now document inputs, output shape, and a usage example
- bump 2.46.1 -> 2.46.2
2026-05-31 13:36:29 +12:00
Antigravity AI 5ea7855e02 test(24-01): verify MCP 1.3.0 version and v1.3 tool surface
- Assert MCP_SERVER_VERSION === 1.3.0 (INTG-02)
- Assert all 8 v1.3 tools register (INTG-01)
- Assert search_entities exposes optional filters param
- package.json 2.46.0 -> 2.46.1 (patch)
2026-05-31 13:31:43 +12:00
Antigravity AI 5201ae32c8 feat(24-01): bump MCP_SERVER_VERSION to 1.3.0
- Advertise MCP protocol server version 1.3.0 on initialize handshake
- Reflects the v1.3 tool surface (geocoding, favorites, filtering)
- package.json 2.45.1 -> 2.46.0 (minor)
2026-05-31 13:29:04 +12:00
Antigravity AI ca8c6ad940 refactor: remove dead readSessionCatalog re-export breaking route type gen
- Drop trailing export { readSessionCatalog } from catalog/route.ts (Next.js App Router rejects non-route-handler exports -> TS2344 in generated route types)
- Trim now-unused readSessionCatalog import (only existed to support the re-export)
- All consumers already import readSessionCatalog from @/lib/mcpSessionCatalog
- Bump 2.45.0 -> 2.45.1
2026-05-31 13:26:35 +12:00
Antigravity AI ac9aa64ddb feat(23-03): wire registerFilterTools into MCP route
- import registerFilterTools from ./filterTools
- call registerFilterTools(server, { userId }) after registerFavoritesTools, before registerPluginTools
- inherits isDemo gate + Bearer auth SAFE envelope
- update registration seam comment for Phase 23
- bump semver 2.44.0 -> 2.45.0
2026-05-31 13:16:41 +12:00
Antigravity AI 7a055f6bb8 feat(23-02): publish plugin filterDefinitions through catalog publisher and route
- collectCatalog gathers getFilterDefinitions() from each loaded plugin (D-05)
- filter-only plugins now publish (early-return guards on tools AND filterDefinitions empty)
- catalog route validates and forwards optional filterDefinitions, identity still from auth only
- gives get_plugin_filters a data source
2026-05-31 13:14:16 +12:00
Antigravity AI 45594304f8 feat(23-02): add inline filters param to searchEntities and search_entities tool
- searchEntities applies filters on full GeoEntity.properties via matchFilterValue before SearchResult conversion (D-07/D-08)
- limit counts only matching entities; missing property key fails filter
- search_entities MCP tool exposes optional filters inputSchema via filterValueSchema
- SearchOptions type gains optional filters field
- 4 new filters tests GREEN, no regression
2026-05-31 13:12:50 +12:00
Antigravity AI 1b67e70bf9 feat(23-02): add set_filter, clear_filter, get_plugin_filters MCP tools
- Create registerFilterTools registrar mirroring globeCommandTools/favoritesTools
- set_filter/clear_filter enqueue GlobeCommand via enqueueGlobeCommand
- get_plugin_filters reads filterDefinitions from session catalog, returns [] when absent
- Makes filterTools.test.ts GREEN (7 tests)
2026-05-31 13:11:05 +12:00
Antigravity AI 5535673f8d feat(23-01): extend SessionCatalog, wire bridge filter dispatch, RED tool stubs
- SessionCatalog gains optional filterDefinitions (D-05); type guard stays backward compatible
- useGlobeCommandBridge dispatches setFilter/clearFilter to filterSlice (D-04)
- Add RED filterTools.test.ts locking set_filter/clear_filter/get_plugin_filters contract
- Bump semver 2.40.0 -> 2.41.0
2026-05-31 13:07:56 +12:00
Antigravity AI f0e658b4c2 feat(23-01): extract matchFilterValue + add shared filterValueSchema
- Extract pure matchFilterValue from filterEngine (D-08, behavior identical)
- filterEngine imports the shared helper; tests still GREEN
- Add filterValueSchema zod discriminated union (D-02, T-23-01-02 mitigation)
- Bump semver 2.39.0 -> 2.40.0
2026-05-31 13:06:36 +12:00
Antigravity AI 053a916ada feat(23-01): add setFilter/clearFilter GlobeCommand variants + validator
- Add setFilter and clearFilter union members (per D-01)
- Add isValidFilterValue discriminating text/select/range/boolean
- Validate pluginId + every FilterValue for setFilter; optional string for clearFilter
- 12 new GREEN validator tests (T-23-01-01 tampering mitigation)
- Bump semver 2.38.0 -> 2.39.0
2026-05-31 13:05:27 +12:00
Antigravity AI f2cc303b0c feat(22-04): register geocoding and favorites MCP tools
- Import and call registerGeocodingTools + registerFavoritesTools in handleMcpRequest registration seam
- SAFE-01 confirmed: isDemo gate (line 144) fires before createMcpServer and all registrars
- Full test suite GREEN (715 tests), tsc clean
- Bump version to 2.38.0
2026-05-31 12:50:10 +12:00
Antigravity AI a8ed51d1a7 feat(22-04): wire flyTo command to Cesium camera
- Add flyTo case to useGlobeCommandBridge dispatchCommand: bbox emits cameraFlyToBbox, point emits cameraGoTo with lon:cmd.lng mapping and 15000m default alt
- Subscribe to cameraFlyToBbox in useCameraActions, flying to Rectangle.fromDegrees
- Bump version to 2.37.0
2026-05-31 12:49:11 +12:00
Antigravity AI 12e5ba818e feat(22-04): add cameraFlyToBbox to DataBusEvents
- Add cameraFlyToBbox {west, south, east, north} event to DataBusEvents in wwv-plugin-sdk
- Bump version to 2.36.0
2026-05-31 12:48:26 +12:00
Antigravity AI 066618dea5 feat(22-03): implement favorites MCP tools (save/list/remove) with liveness
- Add registerFavoritesTools registrar: save_favorite, list_favorites, remove_favorite
- save_favorite upserts prisma.favorite; pluginName defaults to pluginId (FAV-01)
- list_favorites reports per-entity live/stale via readActiveSessions + getEntityDetails; all stale when no session (FAV-02, D-04/D-05)
- remove_favorite deletes row scoped to ctx userId (FAV-03)
- userId sourced exclusively from ctx, never tool args; direct prisma, no HTTP (SAFE-02)
- Add @/lib/prisma re-export and manual test mock; align RED test session mock shape
- Bump 2.34.0 -> 2.35.0
2026-05-31 12:45:48 +12:00
Antigravity AI 1c175e7e8e feat(22-02): register geocode_location and fly_to MCP tools
- geocode_location: 24h Redis cache (fail-open), per-user rate limit, Nominatim fetch + normalize (GEO-01, GEO-03)
- fly_to: resolves session, enqueues flyTo GlobeCommand with optional bbox (GEO-02)
- userId sourced only from ctx; query injected via URLSearchParams (SSRF-safe)
- fix RED test stub: enqueueGlobeCommand asserted with (userId, sessionId, cmd) to match real signature
- makes geocodingTools.test.ts GREEN; bump 2.33.0 -> 2.34.0
2026-05-31 12:39:57 +12:00
Antigravity AI b42c1e7e06 feat(22-02): add per-user Redis sliding-window geocoding rate limiter
- checkRateLimit(userId) prunes via zremrangebyscore(key,-inf,now-WINDOW)
- records request via zadd, bounds key with expire(key,5), counts via zcard
- returns { error: rate_limited, retryAfterMs } when count > MAX_REQUESTS=1
- fails open on Redis error (best-effort, advisory limit)
- makes geocodingRateLimit.test.ts GREEN; bump 2.32.0 -> 2.33.0
2026-05-31 12:39:38 +12:00
Antigravity AI d6ffec3f41 feat(22-02): add Nominatim geocoding HTTP wrapper
- fetchGeocode({query,limit}) hits hardcoded Nominatim /search via URLSearchParams
- User-Agent + Accept-Language:en headers, AbortSignal.timeout(8000)
- normalizeNominatimResult remaps boundingbox [S,N,W,E] -> bbox [W,S,E,N]
- name_en from namedetails['name:en'] with fallback to name
- bump 2.31.4 -> 2.32.0
2026-05-31 12:39:16 +12:00
Antigravity AI a34cf4cf8a docs(22-01): complete foundation plan summary and update planning state
- 22-01-SUMMARY.md: TDD Wave 0 foundation complete (3 tasks, 4 files)
- STATE.md: advanced to plan 2 of 4, 25% progress
- ROADMAP.md: plan 22 progress updated (1/4 SUMMARY files present)
- REQUIREMENTS.md: GEO-02, GEO-03, SAFE-01 marked complete
2026-05-31 12:32:05 +12:00
Antigravity AI df1d6a72f6 test(22-01): add RED test stubs for geocodingTools, favoritesTools, geocodingRateLimit
- geocodingTools.test.ts: 7 cases for geocode_location and fly_to handlers
- favoritesTools.test.ts: 6 cases for save/list/remove favorites
- geocodingRateLimit.test.ts: 5 cases for sliding window rate limiter
- all three fail RED (missing module imports) as required by TDD Wave 0
2026-05-31 12:29:50 +12:00
Antigravity AI 7583b4cac1 feat(22-01): add flyTo variant to GlobeCommand union + isValidGlobeCommand case
- Add flyTo member: { type: "flyTo"; lat; lng; alt?; bbox? }
- Add flyTo case to isValidGlobeCommand with lat/lng/alt/bbox validation
- bbox must be 4-element array of finite numbers within valid WGS84 bounds
- Add 8 RED->GREEN test cases in flyTo validator describe block
2026-05-31 12:26:54 +12:00
Antigravity AI fc5aa7860b feat(22-01): extend RedisClient interface with zremrangebyscore and zcard
- Add zremrangebyscore(key, min, max): Promise<number> after zrem
- Add zcard(key): Promise<number> for sorted-set cardinality
- ioredis implements both natively; cast picks them up at runtime
2026-05-31 12:25:20 +12:00
Antigravity AI 2438ae7e9d docs: define v1.3 requirements and roadmap (4 phases, 18 requirements)
Phases 22-25: Geocoding+Favorites, Entity Filtering, Route Wiring,
Documentation. Adds DOC-01..04 requirements for MCP tool docs, plugin
filter guide, user capability summary, and release notes.
2026-05-31 11:23:24 +12:00
Antigravity AI bd1de5ac7a docs: start milestone v1.3 Location Intelligence
Reset STATE.md for v1.3; update PROJECT.md with current milestone goals
(geocoding, entity filtering, entity favorites). Phase numbering continues
from v1.2 last phase -- v1.3 starts at Phase 22.
2026-05-31 10:58:45 +12:00
Antigravity AI fdf733c686 fix(auth,api-keys): resolve POST /api/api-keys 500 and persist session users
- Auth: add ensureLocalUserPersisted() (idempotent upsert in authorize())
  and persistDemoAdminIfNeeded() (upsert in jwt callback) so session userId
  always has a DB row before FK-constrained inserts
- api-keys POST: map Prisma P2003 on user_api_keys_userId_fkey to 401
  session_user_not_found instead of 500; other FK violations still 500
- api-keys GET/POST: add isDemo gate returning 403 before auth
- Tests: full coverage for all new paths (16 tests, 2 files)
2026-05-30 21:59:53 +12:00
Antigravity AI 12445a01fb docs(18-05): complete gap-closure plan summary and update STATE.md
- 18-05-SUMMARY.md: isDemo gate on POST /api/globe/state, GAP-01 closed
- STATE.md: gap-closure entry with commit hash, test counts, deviation note
2026-05-30 21:55:40 +12:00
Antigravity AI ee16ec0542 fix(18-05): add isDemo gate to POST /api/globe/state
- Import isDemo from @/core/edition in route.ts
- Gate executes after rate limiter and before userId resolution
- 403 { error: "Not available in demo edition" } returned for demo edition
- Test: vi.hoisted editionMock pattern for mutable isDemo toggle
- All 6 tests green (5 pre-existing + 1 new demo-gate case)
- useGlobeStateSync confirmed to handle 403 silently (no code change needed)
2026-05-30 21:53:57 +12:00
Antigravity AI cd80ba130e feat(mcp): document session workflow + harden coordinate validation
Add the MCP server `instructions` block so a connecting agent learns the
session-discovery workflow up front: read the globe://sessions resource to
list active tabs, then pass an optional sessionId to target one specific
tab (omit to target the most-recently-active tab). Enrich the four globe
command tools' sessionId descriptions and the data-query tool descriptions
(empty result means no match or no live data, not an error). Bump the
advertised MCP server version to 1.2.0.

Harden coordinate validation across every MCP coordinate surface via a new
shared coordinateSchemas module: latitude [-90,90], longitude [-180,180],
altitude > 0, rejecting NaN/Infinity. Applied to pan_globe, focus_entity,
get_entities_in_region, and the /api/v1/entities/region route, with a
defense-in-depth runtime guard in isValidGlobeCommand. Fixes a UAT finding
where pan_globe accepted lat=999.

Quiet the useGlobeCommandBridge SSE onerror handler so it logs only on a
terminal close (readyState CLOSED, e.g. an unauthenticated tab), not on the
designed ~16s stream reconnect.
2026-05-30 18:18:38 +12:00
Antigravity AI dc1e802922 fix(mcp): close v1.2 milestone-audit tech debt
Addresses tech debt surfaced by the v1.2 milestone audit and the
code/security reviews of the fixes:

- mcpRelay: make enqueueToolInvocation atomic via multi().rpush().expire().set()
  and apply the same atomicity to postToolResult's result write (was two
  separate non-atomic writes that could leak on partial failure)
- redis: add set() to the RedisMultiChain interface to support the above
- v1 entities (search + region): add dual-auth (NextAuth session primary,
  Bearer fallback) matching globe/commands route; add isDemo 403 gate before
  auth; guard limit against NaN from non-numeric ?limit input; document that
  entity data is global/public so userId gates access but is not a query filter
- useGlobeStateSync: fire one immediate pushState on mount (ran-once ref guard)
  to close the session-registration race where resolveActiveSessionId returned
  null before the first heartbeat
- useMcpCatalogPublisher: wire getNamespacedTools instead of inline pluginId__name
  string building (DRY); catalog payload shape unchanged
- remove dead export pluginToolsList.ts (composePluginToolsList had zero
  production callers; McpServer auto-generates tools/list from registered tools)

643/643 tests pass, tsc clean, lint clean.
2026-05-30 16:44:09 +12:00
Antigravity AI 7fd1d7ebf8 feat(19b): SSE push transport for globe commands
Replace 1500ms setInterval poll loop in useGlobeCommandBridge with a
persistent EventSource (Server-Sent Events) connection. Commands are
pushed within 200ms of enqueue instead of up to 1500ms.

- New GET /api/globe/commands/stream route: ReadableStream with poll-
  with-deadline loop, 15s keepalive, 16s max duration, cancel callback
  for client-disconnect cleanup, same dual-auth + isDemo gate order
- useGlobeCommandBridge: replaced setInterval/fetch with EventSource;
  dispatchCommand unchanged; envelope shape validation in onmessage
- globeCommandsStreamLimiter: 10 req/60s for the SSE endpoint
- GET /api/globe/commands poll route: added missing isDemo 403 gate
- 654/654 tests pass, 0 regressions
2026-05-30 15:35:23 +12:00
Antigravity AI 3661ef4fe3 fix(e2e): use pointer capture for bottom panel resize drag
Replaced the window-level mousemove/mouseup/pointermove/pointerup
listeners (gated on an isDragging state flag) with element-level
pointer capture on the resize handle. setPointerCapture routes all
subsequent pointermove/pointerup events to the element regardless of
where the pointer travels, which is required for webkit: without
capture, webkit drops synthetic pointermove events during Playwright
drags and during fast real-user drags that leave the element bounds.

This was a pre-existing failure on main (run 26639956515) reproduced
identically on this branch. The fix is correct production behaviour,
not a test workaround.

Bumps version 2.29.2 -> 2.29.3.
2026-05-30 14:53:14 +12:00
Antigravity AI 6374f2fa1c fix(security): validate pluginId to prevent SSRF and format string injection
CodeQL flagged two alerts in src/lib/data-query/service.ts: user-controlled
pluginId was interpolated directly into a fetch URL (SSRF, critical) and into
console.error template literals (format string, high). Added validatePluginId()
which enforces an alphanumeric+hyphen+underscore allowlist, uses URL constructor
to build safe paths, and removed user-controlled values from log template strings.
2026-05-30 14:29:18 +12:00
Antigravity AI 4118708967 fix: update pnpm-lock.yaml to include ioredis (CI frozen-lockfile fix) 2026-05-30 14:19:19 +12:00
Antigravity AI 7ab7fe8b05 fix: resolve merge conflicts and CI failures (v2.29.1)
- Merge origin/main (resolved package.json version conflict, kept 2.29.x)
- Fix Next.js 15 async params: api-keys/[id]/route.ts DELETE now awaits params
- Update api-keys/[id]/route.test.ts to pass Promise.resolve({id}) for params
- Fix TypeScript errors in globeResources.test.ts: cast mock.calls to typed tuples
- Fix TypeScript errors in globe/commands/route.test.ts: cast auth mock to session getter signature, add Session type imports
- Fix TypeScript error in mcp/route.test.ts: replace invalid query-string imports (./route?demo-post) with vi.resetModules() + plain ./route re-import
- Add public/plugins-local/** to eslint ignore: compiled bundles are not source
2026-05-30 14:14:48 +12:00
Antigravity AI 1aba01e40f Merge remote-tracking branch 'origin/main' into feat/mcp-support 2026-05-30 14:00:00 +12:00
Antigravity AI 9c28d5170f feat(21): plugin tools via frontend-relay (v2.29.0)
- McpToolDeclaration type in SDK (no execution field - server stays plugin-agnostic)
- WorldPlugin.executeMcpTool? browser-side hook
- validateManifest rules for mcpTools + mcpCapabilities
- getNamespacedTools ({pluginId}__{name}) + hand-rolled input validator
- Per-session catalog: browser publishes loaded plugins' tools to Redis
- POST /api/mcp/catalog + useMcpCatalogPublisher browser hook
- Dynamic tools/list: system tools + per-session namespaced plugin tools
- Request/response relay: enqueue invocation, blpop wait (10s deadline), graceful timeout
- GET /api/mcp/invocations + POST /api/mcp/results browser-facing relay routes
- useMcpRelayBridge: polls invocations, calls executeMcpTool, posts result
- All relay routes: dual-auth, UUID guard, isDemo 403, ownership check, size caps
- useMcpCatalogPublisher + useMcpRelayBridge wired into GlobeView
- README MCP config block
2026-05-30 13:42:56 +12:00
Antigravity AI 6cb86e0352 feat(21-04): add useMcpRelayBridge browser relay hook (PLUG-03)
- Polls GET /api/mcp/invocations every 1500ms (mirrors useGlobeCommandBridge cadence)
- For each invocation: strips {pluginId}__ prefix -> resolves plugin -> calls executeMcpTool
- On plugin error or missing executeMcpTool: posts sanitized error result so server blpop resolves
- inFlightRef prevents overlapping polls; activeRef prevents post-unmount state updates
- console.error in catch only; no any; no ts-ignore
2026-05-30 12:58:09 +12:00
Antigravity AI 45410df6e7 feat(21-04): add plugin tool dispatch + invocations/results routes (PLUG-03)
- pluginToolDispatch.ts: registerPluginToolDispatch reads catalog, registers relay handler per tool
  - validateToolArgs BEFORE enqueue (MCP-QA-03); unknown tool never enqueued (MCP-QA-02)
  - waitForToolResult with 10s deadline; graceful timeout text result on expiry (MCP-QA-04)
  - userId from auth context only, never from tool args (SEC-06)
- GET /api/mcp/invocations: dual-auth, UUID sessionId guard, rate-limited; drains invocations
- POST /api/mcp/results: dual-auth, ownership check, size cap; writes via postToolResult
- route.ts: wire registerPluginToolDispatch at registrar seam; remove Wave 2 stub handler
- rateLimiters.ts: add mcpInvocationsLimiter + mcpResultsLimiter
2026-05-30 12:58:00 +12:00
Antigravity AI fc53c68fee feat(21-04): add mcpRelay request/response machinery (PLUG-03)
- enqueueToolInvocation: RPUSH invocation to session-scoped list + ownership record
- waitForToolResult: blpop with bounded deadline; returns { timedOut: true } on expiry, never throws
- postToolResult: ownership check via EXISTS + result size cap; RPUSH to result list
- drainToolInvocations: atomic multi().lrange().del() drain (mirrors drainGlobeCommands)
- All Redis keys scoped {userId}:{sessionId}; result key also includes requestId (SEC-01..05 green)
2026-05-30 12:57:35 +12:00
Antigravity AI 23b893cf9f feat(21-03): composePluginToolsList + dynamic tools/list in route.ts
- composePluginToolsList merges system tools with per-session plugin tools
- De-duplicates by namespaced name; capability-coverage copy in descriptions
- route.ts registerPluginTools reads catalog via resolveActiveSessionId+readSessionCatalog
- Plugin tool stub handlers registered (Wave 3 will wire relay)
- No DB/tenantId enumeration -- browser-published discovery only
- LIST-01..05 tests GREEN
2026-05-30 12:40:02 +12:00
Antigravity AI cbd48e52fd feat(21-03): browser catalog-publisher hook useMcpCatalogPublisher
- Reads loaded plugins + manifests from pluginManager on mount and interval
- POSTs {tools, capabilities} to /api/mcp/catalog to keep catalog TTL fresh
- No-op when no plugins declare mcpTools
- sessionId from caller (useSessionId) -- no new identity source invented
- PLUG-04 browser-side catalog publishing
2026-05-30 12:33:11 +12:00
Antigravity AI 6779921cd6 feat(21-03): mcpSessionCatalog Redis store + catalog POST route
- publishSessionCatalog/readSessionCatalog with {userId}:{sessionId} key scoping and TTL
- POST /api/mcp/catalog with dual-auth, UUID guard, size cap, isDemo 403 gate
- userId from auth result only -- never from request body
- CAT-01..06 tests GREEN
2026-05-30 12:31:44 +12:00
Antigravity AI bda235f354 feat(21-02): make Wave 1 SDK tests GREEN
- Add McpToolDeclaration interface to wwv-plugin-sdk manifest.ts (NO execution field - v3 invariant)
- Add mcpTools? and mcpCapabilities? optional fields to PluginManifest
- Add executeMcpTool? hook to WorldPlugin interface in index.ts
- Re-export McpToolDeclaration from sdk index.ts and src/core/plugins/PluginManifest.ts
- Extend validateManifest to validate mcpTools entries (name presence + safe identifier check) and mcpCapabilities (string array)
- Create src/lib/mcp/pluginTools.ts with getNamespacedTools (auto-namespaces to {pluginId}__name) and validateToolArgs (hand-rolled type/required/enum validator, no external schema library)
2026-05-30 12:25:41 +12:00
Antigravity AI 5930bc7b25 test(21-01): RED tests for plugin-tools quality phase (Wave 0)
- validateManifest.test.ts: MAN-01..08 for mcpTools/mcpCapabilities validation
- pluginTools.test.ts: PT-01..08 for getNamespacedTools + minimal input validator
- mcpSessionCatalog.test.ts: CAT-01..06 for per-session catalog publish/read + key scoping
- pluginToolsList.test.ts: LIST-01..05 for dynamic tools/list composition
- mcpRelay.test.ts: RELAY-01 + SEC-01..05 for request/response relay + security invariants
- pluginToolDispatch.test.ts: MCP-QA-01..04 + SEC-01/06 for auth/dispatch QA
2026-05-30 12:14:38 +12:00
Antigravity AI ef8decc892 feat(19a): globe command system tools via Redis queue + HTTP polling
Add MCP "globe command" system tools so an authenticated agent can act on
an open globe: pan, focus an entity, toggle a layer, and scrub the timeline.

Transport is poll-based (no WebSocket, no custom server.ts): tools RPUSH a
validated command to a per-session Redis list (TTL 60s), the browser polls
GET /api/globe/commands on an interval, drains atomically (MULTI lrange+del),
re-validates, and dispatches to the Cesium camera (DataBus) and Zustand store.
This is the durable transport; WebSocket push (19b) can layer on later without
rewriting the type guard, tools, sessionId resolution, or browser dispatch.

Covers CTRL-04 + CTRL-05. 19b (WS push) remains deferred.

- GlobeCommand discriminated union + isValidGlobeCommand guard (never throws;
  validates timeWindow against the literal set and currentTime as a real date)
- globeCommandQueue: atomic enqueue (multi.rpush.expire) + drain + session resolve
- registerGlobeCommandTools: 4 MCP tools, userId from auth ctx only, graceful
  no-session result, z.enum for timeWindow
- GET /api/globe/commands: dual-auth (session primary, Bearer fallback),
  UUID sessionId 400 guard, dedicated globeCommandsLimiter
- useGlobeCommandBridge: 1500ms poll with in-flight guard + unmount cleanup
- route.ts: third per-request registrar call (R-1)

Reviewed by code-reviewer + security-reviewer (no Critical/High; auth provenance,
gate ordering, and tenant isolation verified). Suite 573/0.
2026-05-30 10:56:24 +12:00
Antigravity AI a5b4b627a6 feat(mcp): add Globe State Sync + Data Query MCP tools (Phases 18 + 20)
Phase 18 - Globe State Sync (v2.27.0):
- ioredis singleton (src/lib/redis.ts), GlobeStateSnapshot type, globeStateStore ZSET session registry
- POST /api/globe/state with dual auth (NextAuth session primary, Bearer fallback per R-2)
- useSessionId + useGlobeStateSync browser hooks with 500ms debounce + 10s heartbeat
- GlobeView wiring for real-time state push
- registerGlobeResources MCP module: RSRC-02 (globe://state/{sessionId}), RSRC-03 (globe://sessions), RSRC-04 (globe://layers)
- Route.ts first R-1 serialized edit

Phase 20 - Data Query Tools:
- Transport-neutral service layer (src/lib/data-query/service.ts): searchEntities, getEntitiesInRegion, getEntityDetails, getPluginData
- REST routes: GET /api/v1/entities/search, GET /api/v1/entities/region
- registerDataQueryTools MCP module: TOOL-01 search_entities, TOOL-02 get_entities_in_region, TOOL-03 get_entity_details, TOOL-04 get_plugin_data
- Route.ts second R-1 serialized edit
- vitest global setup (src/test/setup.ts) for next-auth jsdom compatibility

498/498 tests GREEN. Zero new TypeScript errors.
2026-05-30 01:52:25 +12:00
Silvertakana 7da3741fe2 feat(plugins): plugin management UX overhaul (#214)
- feat: wrench icon on local plugin layers in Data Layers panel
- fix: plugin disable/enable lifecycle without page reload
- fix: localStorage-only disable persistence (wwv-disabled-plugins key)
- fix: hot-load plugin script on enable when disabled at startup
- fix: disable shows reload banner; enable clears it
- fix: enable no longer auto-turns layer on
- fix: PluginIcon fallback for renamed/unknown Lucide icon names
- fix: market-tracker icon LineChart -> ChartLine (Lucide rename)
- style: GeoJSON importer fully themed via CSS variables (no hardcoded cyan)
- style: Import GeoJSON button matches panel theme
- style: Browse Plugins text centered
2026-05-30 01:26:38 +12:00
SilvertakanaandClaude 28d284046f chore: run playwright and docker CI conditionally on app code changes (#212)
Switch playwright.yml and docker-publish.yml from broad paths-ignore to
positive paths filters so the expensive 3-browser E2E matrix and Docker
multi-stage build only trigger when application code actually changes.
ci.yml gains additional paths-ignore entries for .agents/**, markdown
files, and issue templates so doc-only PRs skip the full test suite.

Skipped workflow runs are neutral passes on GitHub, so required status
checks are not affected.

https://claude.ai/code/session_01CvJ6u5bP3efXHWsGAMvgx7

Co-authored-by: Claude <[email protected]>
2026-05-30 01:25:45 +12:00
Silvertakana c08f25e0b8 feat(sdk,panel): add tagged property type helpers and Intel panel renderers (#213)
* feat(sdk,panel): add tagged property type helpers and Intel panel renderers

Adds four null-safe tag helpers to wwv-plugin-sdk (dtProp, urlProp,
imageProp, videoProp) that encode typed values as prefixed strings.
Adds DatetimePropertyRow (collapse/expand with UTC + relative time)
and VideoProperty (Watch link with PlayCircle icon). Updates
DynamicPropertiesRender to dispatch on all four prefixes before
existing heuristic checks. Bumps version 2.24.5 -> 2.25.0.

* docs: add property tag helper documentation to SDK and plugin guides
2026-05-30 01:25:03 +12:00
Antigravity AI 6f77495f29 feat(17-03): connect-agent helper UI + nginx runbook + version 2.26.0
- Add ConnectAgentHelper component: per-edition /api/mcp URL, mcpServers
  JSON block (Bearer in Authorization header, never in URL), Manual block,
  agent-capabilities prompt, deferred CLI "coming soon" note
- Mount ConnectAgentHelper in PersonalApiKeysSection replacing TODO placeholder
- Create .agents/context/server-management.md: Coolify/Nginx streaming
  runbook (X-Accel-Buffering: no, proxy_read_timeout 120s, Coolify UI steps)
- Bump version 2.25.0 -> 2.26.0 (feat: new MCP connect-helper surface)
2026-05-30 00:50:47 +12:00
Antigravity AI 61186648da feat(16): security hardening - rate limits, TOCTOU fix, header spoof, name length
H1 - Rate limiting:
- Add mcpLimiter (60 req/min/IP) at Gate 0 in /api/mcp, runs before edition
  check and auth so scanners never reach the DB layer
- Add apiKeyManagementLimiter (10 req/min/IP) on GET/POST/DELETE api-keys handlers
- Both limiters exported from rateLimiters.ts with getClientIp re-export
- TODO comment: move to @upstash/ratelimit for multi-replica deployments
- Tests: route.test.ts mocks the limiter module; new MCP 429 tests would live
  in mcp/route.test.ts (existing suite passes; limiter tested in rateLimit.test.ts)

H2 - Tenant-header spoof prevention:
- proxy.ts: delete x-tenant-subdomain before NextResponse.next() on /api/*,
  then re-inject only the server-resolved value so a forged header cannot
  drive the Prisma tenant extension

M1 - TOCTOU on max-3:
- Wrap count + create in prisma.$transaction(..., { isolationLevel: "Serializable" })
  so concurrent POSTs cannot both read count < 3 and both succeed
- Route test updated to mock $transaction inline execution

M2 - Name length:
- Reject name > 64 chars server-side with 422 name_too_long before the transaction
- Tests added for > 64 (reject) and exactly 64 (accept)

L2 - Log flooding:
- Downgrade console.error to console.warn on /api/mcp auth failure
2026-05-30 00:42:19 +12:00
Antigravity AI d8ef6956f8 refactor(16): replace bcrypt with HMAC-SHA256 key hashing
Switch API key secret storage from bcrypt (200-400ms per auth) to
HMAC-SHA256(signingKey, secret) with timingSafeEqual comparison.

- Signing key: API_KEY_HMAC_SECRET env var, falls back to AUTH_SECRET
- Timing-oracle defense preserved: miss path computes dummy HMAC digest
  (same 32-byte length) before timingSafeEqual so both paths are constant-work
- Removes DUMMY_HASH literal, async bcrypt re-hash, and bcryptjs dependency use
- generateApiKey is now synchronous (no bcrypt await)
- M3 fix included: lastUsedAtThrottle TTL-evicts at 2x window to prevent
  unbounded Map growth; note added that it is per-replica
- Tests updated: timing-oracle test asserts behavioral contract not elapsed
  time (HMAC is microsecond-fast); added hex-format and randomness assertions

NOTE: existing bcrypt-hashed keys in the DB will fail authentication after
this change. Acceptable pre-launch; no live keys to migrate.
2026-05-30 00:41:56 +12:00
Antigravity AI 0053f1d609 feat(17-02): stateless /api/mcp route handler (Wave 0 RED tests GREEN)
- Create src/app/api/mcp/route.ts: GET/POST/DELETE delegates to
  handleMcpRequest(); exports for Next.js App Router
- Gate ordering: isDemo -> 403 JSON-RPC FIRST (before auth); then
  authenticateApiKey() -> 401 JSON-RPC on failure (MCP-03/04/D-17-05)
- Fresh McpServer + WebStandardStreamableHTTPServerTransport per request
  (sessionIdGenerator: undefined); stateless guard-rail comment (D-17-04)
- AuthInfo injected via closure: { token: "", clientId: userId, scopes: [],
  extra: { userId, keyId } } for Phase 18/20/21 resource scoping (R-1)
- X-Accel-Buffering: no + Cache-Control: no-cache merged on streamed
  response without buffering body (D-17-06, MCP-06, Pitfall 1)
- All 12 Wave 0 route tests GREEN; transport spike GREEN; 416 tests pass
2026-05-30 00:02:05 +12:00
Antigravity AI e0ad832034 feat(17-02): install @modelcontextprotocol/sdk + createMcpServer() factory
- Add @modelcontextprotocol/sdk@^1.29.0 to dependencies (SDK legitimacy
  gate cleared by orchestrator; official Anthropic MCP SDK, MIT license)
- Create src/lib/mcp/server.ts: createMcpServer() returns a fresh McpServer
  per call with capabilities: { tools: { listChanged: true } } per R-1
- Add stateless/never-cache guard-rail comment + Phase 18/20/21 seam docs
- Add vitest.config.ts clearMocks: true to fix mock isolation between
  describe blocks (required for Wave 0 MCP-04 demo-gate tests to pass)
- Transport spike (17-01 Task 3) now PASSES green with SDK installed
2026-05-30 00:01:45 +12:00
Antigravity AI 505be6e986 fix(16): surface auth failures in PersonalApiKeysSection fetch; rename section header to "Service Keys"
- PersonalApiKeysSection: check r.ok before consuming response JSON; a 401
  (e.g. AUTH_URL domain mismatch on local dev) was silently producing
  data.keys === undefined which fell through the ?? [] guard and rendered
  "No API keys yet" instead of the error message. Fixes KEY-03 reload symptom.
- route.test.ts: add assertion that 401 response body must not contain a
  `keys` field, locking in the invariant that callers must check r.ok.
- ApiKeysTab: rename "Your API Keys" section header to "Service Keys" per
  16-UI-SPEC.md Copywriting Contract (line 261).
2026-05-29 23:42:55 +12:00
Antigravity AI fcb7a5ee07 test(17-01): RED scaffold for /api/mcp route + transport spike
- route.test.ts: locks 401 JSON-RPC auth gate (MCP-03), 403 demo gate
  before auth (MCP-04), happy-path gate passage (MCP-01/02), X-Accel-Buffering
  streaming header (MCP-06), per-request stateless construction (MCP-05)
- transport-spike.test.ts: skips cleanly (SDK absent); proves
  WebStandardStreamableHTTPServerTransport + McpServer instantiate/connect
  outside a custom server when SDK is installed (de-risks D-17-02)
- route.ts absent by design -- these are Wave 0 RED baselines
2026-05-29 23:23:33 +12:00
Antigravity AI 90dfb6869e fix(test): narrow overloaded NextAuth auth export for vi.mocked typing
The 16-03 api-keys route tests called vi.mocked(auth), which resolved the
NextAuth v5 NextMiddleware overload and rejected the Session/null mock value
(TS2345 x7, breaking tsc/pnpm build while vitest stayed green). Narrow auth to
its no-arg session-getter signature via a typed mockAuth helper so vi.mocked
picks the correct overload. Test-only; no runtime change (10/10 still pass).
2026-05-29 22:38:33 +12:00
Antigravity AI 5f3fe69d7e feat(16-04): personal API keys section + Keys & Access wiring
- Add PersonalApiKeysSection client component (API & MCP Access)
  consuming GET/POST/DELETE /api/api-keys: list, generate with
  one-time reveal, inline-confirm revoke, max-3 disabled state
- Rename Header settings modal title to 'Keys & Access' and render
  the section below ApiKeysTab behind an !isDemo edition gate
- Harden secret/name inputs against password-manager capture
  (autoComplete=off, data-lpignore, data-form-type=other)
- Phase 17 connect-your-agent helper left as a code-comment placeholder
2026-05-29 22:33:59 +12:00
Antigravity AI 1b250e0a1c docs(16-03): complete api-key CRUD routes plan summary + state update
- 16-03-SUMMARY.md: GET+POST+DELETE route handlers, 403/403 tests green
- STATE.md: current position advanced to plan 4 of 4, wave 2 decisions recorded
- ROADMAP.md: phase 16 progress updated (3/4 summaries)
2026-05-29 21:54:34 +12:00
Antigravity AI 4e6ff0704f feat(16-03): implement DELETE /api/api-keys/[id] ownership-scoped revoke
- deleteMany where { id, userId } — atomic BOLA prevention (T-16-06)
- count 0 -> 404 not_found; count 1 -> 200 success: true
- isDemo gate (403) before session check
- All 4 [id]/route.test.ts tests GREEN (KEY-03)
- Full suite 403/403 tests green, no regressions
2026-05-29 21:52:33 +12:00
Antigravity AI 476befe4b4 feat(16-03): implement GET + POST /api/api-keys route handlers
- GET lists user's keys selecting only { id, name, prefix, createdAt, lastUsedAt } (hashedSecret never returned)
- POST enforces max-3 limit (422 max_keys_reached), calls generateApiKey(), returns fullToken once in 201 response
- P2002 prefix-collision handled with single retry
- isDemo gate (403) runs before session check on both handlers
- All 6 route.test.ts tests GREEN (KEY-01, KEY-03, KEY-04)
2026-05-29 21:51:42 +12:00
Antigravity AI debfdc5410 feat(16-02): implement apiKeyAuth.ts - timing-safe API key primitive
- generateApiKey(): prefix "wwv_" + 8 base64url chars, secret = 32-byte
  base64url, hashedSecret = bcrypt(secret, 12), fullToken = prefix.secret
- authenticateApiKey(): parses Bearer header, splits on first ".", findUnique
  by prefix, always runs bcrypt compare (DUMMY_HASH on miss for T-16-01),
  fire-and-forget throttled lastUsedAt update (1/min/key)
- DUMMY_HASH: pre-baked cost-12 literal eliminates cold-start gap (Pitfall 1)
- Uses async hash/compare from bcryptjs (never compareSync - Pitfall 2)
- Exports GeneratedKey + AuthenticatedKey interfaces (API-01)
- All 11 tests GREEN including timing-oracle test (elapsed > 100ms)
2026-05-29 21:45:36 +12:00
Antigravity AI d10c15e6d3 feat(16-02): add UserApiKey model to schema.prisma
- Add model UserApiKey with uuid PK, userId FK (Cascade), tenantId String?,
  prefix String @unique, hashedSecret, name, createdAt, lastUsedAt DateTime?
- Add @@map("user_api_keys") following project snake_case convention
- Add apiKeys UserApiKey[] relation to User model
- Bump version 2.24.6 -> 2.25.0 (minor: new feature)
2026-05-29 21:42:32 +12:00
Antigravity AI abded9c5b1 test(16-01): add failing RED test scaffolds for api-keys route handlers
- route.test.ts imports GET/POST from ./route (does not exist -- intentional RED)
- [id]/route.test.ts imports DELETE from ./route (does not exist -- intentional RED)
- Mocks @/lib/auth, @/lib/db (userApiKey), @/core/edition, @/lib/apiKeyAuth
- KEY-03: GET returns 200+{keys} with session, 401 without; response never contains hashedSecret
- KEY-04: POST returns 422 max_keys_reached at count>=3; returns 201+fullToken when under limit
- KEY-03 DELETE: 200 on owned key (count:1), 404 on foreign (count:0), 401 with no session
- Ownership: asserts deleteMany called with where containing both id and userId
2026-05-29 21:37:29 +12:00
Antigravity AI b270ca81fc test(16-01): add failing RED test scaffold for apiKeyAuth helper
- Imports generateApiKey + authenticateApiKey from ./apiKeyAuth (does not exist -- intentional RED)
- Mocks @/lib/db userApiKey (findUnique/create/findMany/count/deleteMany/update) and @/core/edition
- KEY-01: prefix starts with wwv_, fullToken = prefix.secret, secret != hashedSecret
- KEY-02/API-01: null on missing header, no-dot token, unknown prefix, wrong secret; { userId, keyId } on valid token
- T-16-01 timing oracle: // [slow] test brackets authenticateApiKey with performance.now() asserting elapsed > 100ms
2026-05-29 21:37:16 +12:00
Silvertakana 6f265e7267 docs(agent): make plugin-implementer use the CLI correctly (#211)
Phase 2 now gives two explicit, copy-paste invocations — polling (no
--seeder-tier) and websocket (with --seeder-tier) — instead of one combined
example that wrongly showed --seeder-tier for every plugin. Adds the
build-CLI-first step, the >= 1.3.1 requirement (the version that fixed the
polling+--yes guard), and a note that a non-zero CLI exit is a hard stop, not
a cue to scaffold by hand.

Phase 4 no longer tells the agent to create the seeder files from scratch:
the websocket scaffold already emits package.json + tsup.config.ts +
src/index.ts, so Phase 4 is reframed as implementing the generated stub. The
reference snippets are kept as the target shape to verify against.
2026-05-29 20:13:09 +12:00
Silvertakana e9a908840d fix(cli): polling plugins with --yes no longer require --seeder-tier (#210)
The --yes guard counted the conditionally-skipped seederTier prompt as a
missing required value, so `create <id> --architecture polling ... --yes`
failed even though seeders only apply to websocket plugins. The guard now
only requires seederTier when the resolved architecture is websocket.

This bug shipped in 1.3.0 and was missed in manual UAT (the polling case
was exercised interactively, not with --yes). The new test suite caught it.

Also in this change:
- Add packages/wwv-cli/test/create.test.mjs: 9 integration tests that spawn
  the built CLI into temp dirs and assert the scaffolded tree (polling vs
  websocket, community vs private seeder tier, billboard/model/point render,
  --core, kebab-id naming, icon mapping, and the --yes / invalid-flag /
  duplicate-dir failure guards). Uses Node's built-in test runner, no new deps.
- Add .github/workflows/cli.yml: path-scoped to packages/wwv-cli, runs
  build (tsc) + the integration tests. Fast versus the full app suite.
- Add paths-ignore for packages/wwv-cli to the heavy app workflows (ci,
  playwright, docker-publish, test-setup-scripts, test-local-dev push) so a
  CLI-only change runs just cli.yml instead of the whole suite.
- Bump CLI to 1.3.1 and add a test script.
2026-05-29 20:08:42 +12:00
Silvertakana a2917536e4 feat(cli): accept flags for non-interactive plugin scaffolding (#209)
The 'wwv create' command was fully interactive (prompts-only) and the
plugin-implementer agent's documented '--local' flag did not exist, so
agents fell back to slow manual scaffolding.

- Add a positional [pluginId] arg plus a flag for every prompt
  (--display-name, --description, --category, --architecture,
  --seeder-tier, --render-style) and a --yes guard that fails fast
  instead of hanging when a required value is missing. Any omitted
  flag still prompts, so interactive use is unchanged.
- Fix seeder output to the real community/private layout:
  local-seeders/<tier>/packages/<name>/{package.json,tsup.config.ts,
  src/index.ts}, exporting the canonical { name, cron, fn } shape with
  name === plugin id (kebab-case) per ADR-0002. Previously it wrote a
  bare seeder.mjs to the wrong path with an unusable context.emit stub.
- Update plugin-implementer.md: drop the bogus --local flag, document
  the flag-based invocation and the correct seeder location, and note
  the CLI build step for fresh worktrees.
- Bump CLI to 1.3.0 and fix the stale hardcoded --version string.
2026-05-29 19:29:30 +12:00
Silvertakana 41c42c0ca1 fix(worktree): make git-wt link-planning hook create real isolated .planning (#207)
The link_planning pre-start hook created a JUNCTION from each new worktree's
.planning to the shared root, which caused GSD phase bleed across simultaneous
worktree sessions. Rewrite it to create a REAL isolated .planning directory
(phases/debug/surveys + config.json + WORKSPACE/STATE/SHARED-DOCS manifests),
idempotently: preserve an existing real dir, only replace a leftover junction.

Update unlink-planning (pre-remove) to remove only a leftover junction and never
recurse into a real dir; phase history is archived by /branch-cleanup before removal.

Closes the gap flagged in WORKSPACE-OPTIMIZATION-BACKLOG.md. Verified with an
18-check harness (fresh create, idempotency, junction replacement, unlink behavior).
2026-05-29 17:09:15 +12:00
133 changed files with 15335 additions and 251 deletions

No files matched your search

+42 -17
View File
@@ -28,32 +28,55 @@ If any are missing, ask the user or tell them to run plugin-researcher first.
## Phase 2 — Scaffold
From the project root (`C:\dev\wwv\worldwideview`):
Always scaffold with the CLI, never by hand. From the project root (`C:\dev\wwv\worldwideview`).
**Step 1 — build the CLI if `dist/` is missing** (`dist` is gitignored, so fresh worktrees lack it):
```bash
# Build the CLI first if dist/ is missing (dist is gitignored; fresh worktrees lack it):
# pnpm --filter @worldwideview/wwv-cli build
#
# The CLI accepts flags for every prompt. Pass them all + --yes for a fully
# non-interactive scaffold (omit any flag to be prompted for just that value):
pnpm --filter @worldwideview/wwv-cli build
```
**Step 2 — run `create` non-interactively.** The CLI accepts a flag for every prompt;
pass them all plus `--yes` so it never blocks on a prompt. Use the variant that matches
the architecture — `--seeder-tier` is **websocket-only** (passing it with `polling` does
nothing). Requires `@worldwideview/wwv-cli` **≥ 1.3.1** (earlier versions wrongly demanded
`--seeder-tier` for polling under `--yes`).
```bash
# Polling / static (frontend only — NO seeder, so NO --seeder-tier):
node packages/wwv-cli/dist/index.js create <name> \
--display-name "<Display Name>" \
--description "<short description>" \
--category <aviation|maritime|space|weather|custom> \
--architecture <polling|websocket> \
--architecture polling \
--render-style <billboard|model|point> \
--yes
# Real-time / WebSocket (also scaffolds a backend seeder — REQUIRES --seeder-tier):
node packages/wwv-cli/dist/index.js create <name> \
--display-name "<Display Name>" \
--description "<short description>" \
--category <aviation|maritime|space|weather|custom> \
--architecture websocket \
--seeder-tier <community|private> \
--render-style <billboard|model|point> \
--yes
pnpm install
```
This creates `local-plugins/wwv-plugin-<name>/`. With `--architecture websocket` it also
creates the seeder at `local-seeders/<tier>/packages/<name>/` (correct community/private
layout: `package.json` + `tsup.config.ts` + `src/index.ts`). Verify both exist before proceeding.
This creates `local-plugins/wwv-plugin-<name>/`. The `websocket` variant also creates the
seeder at `local-seeders/<tier>/packages/<name>/` in the correct community/private layout
(`package.json` + `tsup.config.ts` + `src/index.ts`, exporting `{ name, cron, fn }` with
`name` === the plugin id). Verify the expected directories exist before proceeding.
> The CLI scaffolds the seeder into `local-seeders/<tier>/packages/<name>/` already —
> no post-CLI move is required. (Older CLI versions dropped a bare `seeder.mjs` at
> `local-seeders/<tier>/<name>/`; if you ever see that, the CLI is out of date — rebuild it.)
> No post-CLI move is required — the CLI already targets `local-seeders/<tier>/packages/<name>/`.
> (Pre-1.3.0 CLI dropped a bare `seeder.mjs` at `local-seeders/<tier>/<name>/`; if you ever see
> that shape, the CLI is stale — rebuild it with the Step 1 command.)
>
> The CLI exits non-zero with a clear message on a bad `--category`/`--architecture`/etc., a
> missing required value under `--yes`, or an existing target directory. Treat a non-zero exit
> as a hard stop — fix the inputs and re-run; do not fall back to manual scaffolding.
**NEVER:**
- Scaffold manually (always use the CLI)
@@ -134,13 +157,15 @@ export class MyPlugin implements WorldPlugin {
---
## Phase 4 — Implement the Seeder (skip for static plugins)
## Phase 4 — Implement the Seeder (skip for static / polling-only plugins)
Seeders live in `local-seeders/community/` — **this is an independent git repo** (`github.com/silvertakana/wwv-seeders`). Never commit seeder files to the worldwideview repo.
Seeders live in `local-seeders/<tier>/` — **independent git repos** (`github.com/silvertakana/wwv-seeders` for community, `wwv-seeders-private` for private). Never commit seeder files to the worldwideview repo.
### Create `local-seeders/community/packages/<name>/`
If you scaffolded with `--architecture websocket`, **the CLI already created the seeder skeleton** at `local-seeders/<tier>/packages/<name>/` (`package.json` + `tsup.config.ts` + `src/index.ts` with a `{ name, cron, fn }` stub). Do **not** recreate those files — open the generated `src/index.ts` and replace the stub body with real fetch + map logic. The snippets below are the target shapes the CLI emits; use them to verify/adjust what was generated, not to create files from scratch.
**`package.json`:**
### Generated layout: `local-seeders/<tier>/packages/<name>/`
**`package.json`** (CLI-generated — only adjust `dependencies` for what your seeder imports):
```json
{
"name": "@wwv-seeders/<name>",
+17
View File
@@ -72,6 +72,23 @@ 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)
+155 -2
View File
@@ -1,8 +1,161 @@
param([string]$worktreePath)
# git-wt (Worktrunk) pre-start hook.
# Per the per-worktree isolation model, each worktree gets its OWN real, isolated
# .planning directory -- NEVER a junction to the shared root. A shared junction caused
# GSD phase bleed across simultaneous worktree sessions. See worktree-bootstrap SKILL Step 5
# and C:\dev\wwv\.planning\WORKSPACE-OPTIMIZATION-BACKLOG.md.
#
# This hook is idempotent:
# - existing REAL .planning with a WORKSPACE.md -> left untouched (preserve phase history)
# - existing REAL .planning missing manifests -> manifests seeded, contents preserved
# - existing JUNCTION (old-model leftover) -> junction removed, real dir created
# - nothing there -> real isolated dir created
$ErrorActionPreference = 'Stop'
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
}
$sharedRoot = 'C:\dev\wwv\.planning'
$target = Join-Path $worktreePath '.planning'
if (Test-Path $target) { Remove-Item $target -Force }
New-Item -ItemType Junction -Path $target -Target 'C:\dev\wwv\.planning' | Out-Null
# If a junction/symlink leftover from the old model exists, remove only the reparse
# point (never recurse into the shared root it points at).
if (Test-Path $target) {
$item = Get-Item -LiteralPath $target -Force
$isReparse = ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq [IO.FileAttributes]::ReparsePoint
if ($isReparse) {
[System.IO.Directory]::Delete($target, $false)
} elseif (Test-Path (Join-Path $target 'WORKSPACE.md')) {
# Already a fully set-up real isolated dir -- preserve it, do nothing.
exit 0
}
}
# Resolve the branch name (fall back to the worktree folder leaf).
$branch = $null
try { $branch = (& git -C $worktreePath rev-parse --abbrev-ref HEAD 2>$null) } catch {}
if (-not $branch) { $branch = Split-Path $worktreePath -Leaf }
$branch = $branch.Trim()
$date = (Get-Date).ToString('yyyy-MM-dd')
$isoDate = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.000Z')
# Create the isolated structure.
foreach ($d in @('phases', 'debug', 'surveys')) {
New-Item -ItemType Directory -Force -Path (Join-Path $target $d) | Out-Null
}
# Copy the GSD config from the shared root if present.
$sharedConfig = Join-Path $sharedRoot 'config.json'
$localConfig = Join-Path $target 'config.json'
if ((Test-Path $sharedConfig) -and -not (Test-Path $localConfig)) {
Copy-Item $sharedConfig $localConfig -Force
}
# Seed the three manifest files (only if missing -- never overwrite existing).
$workspaceFile = Join-Path $target 'WORKSPACE.md'
if (-not (Test-Path $workspaceFile)) {
$workspace = @"
# Workspace: $branch
Created: $date
Strategy: worktree (git-wt)
Branch: $branch
Repo: $worktreePath
## Isolation
This ``.planning`` is a REAL, isolated directory (not a junction to the shared root).
Phases and STATE.md here are private to this worktree. Changes do NOT bleed into
other worktrees or the shared root. Created automatically by the git-wt pre-start
hook (link-planning.ps1), per the per-worktree isolation model.
## Member Repos
| Repo | Source | Branch | Strategy |
|------|--------|--------|----------|
| worldwideview | C:\dev\wwv\worldwideview | $branch | worktree |
## Notes
Cross-feature docs are NOT duplicated here. See SHARED-DOCS.md.
"@
Set-Content -LiteralPath $workspaceFile -Value $workspace -Encoding UTF8
}
$stateFile = Join-Path $target 'STATE.md'
if (-not (Test-Path $stateFile)) {
$state = @"
---
gsd_state_version: 1.0
milestone: none
milestone_name: $branch
status: idle
last_updated: "$isoDate"
last_activity: $date -- isolated .planning created (git-wt pre-start hook)
progress:
total_phases: 0
completed_phases: 0
total_plans: 0
completed_plans: 0
percent: 0
---
# Project State
## Project Reference
This is an ISOLATED worktree workspace. Its planning state is private to the
``$branch`` worktree and intentionally distinct from the shared root
(C:\dev\wwv\.planning).
Cross-feature docs (ROADMAP, MILESTONES, research) are NOT duplicated here.
See SHARED-DOCS.md for how to reach them.
## Current Position
No active milestone. Workspace is idle.
"@
Set-Content -LiteralPath $stateFile -Value $state -Encoding UTF8
}
$sharedDocsFile = Join-Path $target 'SHARED-DOCS.md'
if (-not (Test-Path $sharedDocsFile)) {
$sharedDocs = @"
# Shared Cross-Feature Docs
This worktree's ``.planning`` is isolated (phases + STATE are private). But some
documents are cross-feature and must stay authoritative in ONE place rather than
being copied per worktree (copies drift out of sync).
## Where they live
Shared root: ``C:\dev\wwv\.planning``
| Doc | Purpose |
|-----|---------|
| ROADMAP.md | Cross-milestone roadmap |
| MILESTONES.md | Milestone definitions and ship status |
| research/ | ARCHITECTURE / FEATURES / PITFALLS / STACK |
| PROJECT.md | Project identity |
| REQUIREMENTS.md | Cross-cutting requirements |
## How to reach them
A ``WWV_SHARED_PLANNING`` env var in each worktree's ``.env.local`` points at the
shared root, and GSD skills that need a cross-feature doc read
``\$WWV_SHARED_PLANNING/<doc>`` instead of the local ``.planning/<doc>``.
Do NOT copy these docs into this worktree. Single source of truth lives at the
shared root.
"@
Set-Content -LiteralPath $sharedDocsFile -Value $sharedDocs -Encoding UTF8
}
# Always report success: the internal git probe above may set a non-zero $LASTEXITCODE,
# which would otherwise be propagated as this hook's exit code and read as a failure.
exit 0
+23 -1
View File
@@ -1,7 +1,29 @@
param([string]$worktreePath)
# git-wt (Worktrunk) pre-remove hook.
# Per the per-worktree isolation model, a worktree's .planning is a REAL isolated
# directory (its phase history is archived by /branch-cleanup before removal, and the
# directory itself is deleted along with the worktree by `git-wt remove`).
#
# This hook therefore ONLY cleans up a leftover JUNCTION from the old shared-link model.
# It must NEVER recursively delete a real .planning directory -- doing so would destroy
# phase history that /branch-cleanup is responsible for archiving.
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
}
$target = Join-Path $worktreePath '.planning'
if (Test-Path $target) { Remove-Item $target -Force }
if (Test-Path $target) {
$item = Get-Item -LiteralPath $target -Force
$isReparse = ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq [IO.FileAttributes]::ReparsePoint
if ($isReparse) {
# Old-model junction: remove only the reparse point (do not follow into the target).
[System.IO.Directory]::Delete($target, $false)
}
# Real directory: leave it. git-wt remove deletes the worktree (and this dir) anyway;
# /branch-cleanup is responsible for archiving its phase history first.
}
exit 0
@@ -202,7 +202,40 @@ import { Plane } from "lucide-react";
const iconUrl = createSvgIconUrl(Plane, { color: "#3b82f6" });
```
### 1.5 Registration (3 Paths)
### 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)
**A. Built-in (monorepo package):**
@@ -224,7 +257,7 @@ await pluginManager.registerPlugin(plugin);
**C. Dynamic import (runtime):**
For user-imported GeoJSON layers, call `pluginManager.loadFromManifest(manifest)` directly.
### 1.6 Build Configuration (Core Monorepo Packages Only)
### 1.7 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:
@@ -652,6 +685,10 @@ 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
+16
View File
@@ -1,10 +1,26 @@
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
+36
View File
@@ -0,0 +1,36 @@
name: CLI
# Scoped to the plugin CLI package only. Heavy app workflows (ci.yml,
# playwright.yml, docker-publish.yml, ...) exclude this path, so a CLI-only
# change runs just this fast build + test instead of the full suite.
on:
push:
branches: [main]
paths:
- "packages/wwv-cli/**"
- ".github/workflows/cli.yml"
pull_request:
branches: [main]
paths:
- "packages/wwv-cli/**"
- ".github/workflows/cli.yml"
permissions:
contents: read
jobs:
build-and-test:
name: Build & Test CLI
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
# `build` runs tsc — this also type-checks the CLI source.
- run: pnpm --filter @worldwideview/wwv-cli build
# Integration tests spawn the built CLI and assert the scaffolded tree.
- run: pnpm --filter @worldwideview/wwv-cli test
+23
View File
@@ -1,10 +1,33 @@
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).
on:
push:
branches: [ "main" ]
paths:
- "src/**"
- "prisma/**"
- "packages/**"
- "scripts/**"
- "Dockerfile"
- "package.json"
- "pnpm-lock.yaml"
- "next.config.ts"
- ".github/workflows/docker-publish.yml"
pull_request:
branches: [ "main" ]
paths:
- "src/**"
- "prisma/**"
- "packages/**"
- "scripts/**"
- "Dockerfile"
- "package.json"
- "pnpm-lock.yaml"
- "next.config.ts"
- ".github/workflows/docker-publish.yml"
env:
REGISTRY: ghcr.io
+23
View File
@@ -1,9 +1,32 @@
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).
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"
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"
permissions:
contents: read
jobs:
+2
View File
@@ -3,6 +3,8 @@ name: Test Local Dev Environment
on:
push:
branches: [main]
paths-ignore:
- "packages/wwv-cli/**"
pull_request:
branches: [main]
paths:
+5
View File
@@ -1,10 +1,15 @@
name: Test Setup Scripts
# CLI-only changes are covered by cli.yml; skip setup-script tests for them.
on:
push:
branches: [ "main" ]
paths-ignore:
- "packages/wwv-cli/**"
pull_request:
branches: [ "main" ]
paths-ignore:
- "packages/wwv-cli/**"
permissions:
contents: read
+10
View File
@@ -157,3 +157,13 @@ 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
+106
View File
@@ -0,0 +1,106 @@
# WorldWideView
## What This Is
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe -- controllable by any AI agent via a production MCP server. Built for power users, researchers, and developers who need a live, plugin-extensible view of the world and want to connect their AI tools directly to it.
## Core Value
A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
## Current State (v1.2 shipped 2026-05-30)
**What shipped in v1.2:**
- Transport-agnostic personal API keys (wwv_prefix.secret bearer tokens)
- Production MCP server at /api/mcp (Streamable HTTP, stateless, Bearer auth)
- ConnectAgentHelper UI for one-copy-paste agent setup
- Globe state MCP resources (globe://state, globe://sessions, globe://layers)
- Globe control tools (pan_globe, focus_entity, toggle_layer, set_timeline) via SSE push
- Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data)
- Plugin-contributed MCP tools via SDK manifest extension + frontend relay bridge
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
## Current Milestone: v1.3 Location Intelligence
**Goal:** Extend the MCP server with geocoding, rich entity filtering, and entity favorites so AI agents can find places, drill into plugin data, and bookmark tracked objects.
**Target features:**
- Geocoding + fly-to (2 new MCP tools: `geocode_location` + `fly_to`)
- Entity filtering via MCP (generic baseline + plugin-declared filter extensions)
- Entity favorites: `save_favorite`, `list_favorites`, `remove_favorite` (per-user, PostgreSQL-backed)
**Backlog (deferred):**
- PLG-01/PLG-02: list_plugins() + install_plugin() marketplace tools (backlog 999.1/999.2)
- UX-01: ConnectAgentHelper upgrade CTA in demo edition (backlog 999.3)
## Requirements
### Validated (Shipped)
**v1.0 Unified Auth Account System (Phases 1-11, shipped 2026-05-28)**
- Supabase shared-cookie auth federation across worldwideview, marketplace, and web
- OAuth (GitHub, Google) and email+password auth with NextAuth v5
- Shared user identity via `NEXT_PUBLIC_WWV_COOKIE_DOMAIN` across three apps
- JWT session persistence, auth callback redirect fix, linked accounts page
- Legal/privacy compliance (ToS, cookie consent, GDPR data deletion flow)
**v1.1 Plugin Install Auth Gate (Phase 12 shipped 2026-05-28)**
- PluginInstall model + migration + Plugin.installs counter
- Fire-and-forget install tracking upsert in GET /api/install/start
**v1.2 Full MCP Support (Phases 16-21, shipped 2026-05-30)**
- Transport-agnostic API keys with bcrypt storage and timing-oracle prevention - v1.2
- Stateless MCP server (Streamable HTTP) with Bearer auth - v1.2
- ConnectAgentHelper per-client setup UI; secret only in Authorization header - v1.2
- Globe state as MCP resources backed by Redis with heartbeat TTL - v1.2
- Globe command bridge via SSE push (< 100ms latency) - v1.2
- Data query tools across all active plugins - v1.2
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
### Active (v1.3 Location Intelligence)
- [ ] geocode_location(query) MCP tool returning {lat, lng, name, bbox} via Nominatim/OSM
- [ ] fly_to(lat, lng, altitude?) MCP tool panning globe camera via SSE command bridge
- [ ] Generic entity filters (type, region, timeRange, status) via MCP set_filter/clear_filter
- [ ] Plugin-declared filter manifest extension + get_plugin_filters(pluginId) MCP tool
- [ ] UserFavorite Prisma model + save_favorite / list_favorites / remove_favorite MCP tools
### Out of Scope
- Embedding an AI chat UI inside the globe -- MCP is server-only
- Browser-side MCP client -- globe is an MCP server target, not client
- Playwright/computer-use globe control -- using SSE command bridge
- Stdio-only MCP transport -- HTTP/SSE for production deployability
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
- API key scopes/permissions and rotation/grace-period flows -- revisit later
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
## Context
- **Three apps**: worldwideview (Next.js globe), worldwideview-marketplace (plugin store), worldwideview-web (marketing)
- **Auth**: NextAuth v5 + Supabase shared cookies, auth host at worldwideview.dev
- **State**: 9 Zustand slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson)
- **MCP**: Stateless Streamable HTTP at /api/mcp; Redis for state/commands/catalog; 8 tools + 3 resources
- **Data pipeline**: wwv-data-engine (Fastify + Redis) + plugin seeders
- **Plugin SDK**: `@worldwideview/wwv-plugin-sdk` with mcpTools manifest extension
## Key Decisions
| Decision | Rationale | Outcome |
|----------|-----------|---------|
| Supabase shared-cookie auth federation | Single sign-on across 3 Next.js apps | ✓ Good |
| JWT install bridge for plugin installs | Instance-level auth keeps globe secure | ✓ Good |
| HTTP/SSE Streamable HTTP for MCP | Production deployable, any AI client | ✓ Good |
| Redis for all MCP state (no in-process) | Scales to multi-user cloud deployment | ✓ Good |
| SSE push over WebSocket | Zero infra change, App Router native, MCP spec-first | ✓ Good |
| Plugin tools via frontend relay | worldwideview-only, no engine endpoint, composable | ✓ Good |
| Generic transport-agnostic API keys | One bearer key for MCP + future REST | ✓ Good |
| Marketplace tools deferred to v1.3 | Kept v1.2 worldwideview-only; clean scope | ✓ Good |
## Evolution
This document evolves at phase transitions and milestone boundaries.
---
*Last updated: 2026-05-31 after v1.3 milestone start*
+96
View File
@@ -0,0 +1,96 @@
# Requirements: WorldWideView v1.3
**Defined:** 2026-05-31
**Core Value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
## v1.3 Requirements
### Geocoding
- [ ] **GEO-01**: Agent can call `geocode_location(query)` and receive 2-5 ranked results with `{lat, lng, name, type, country, bbox, importance}` via Nominatim
- [x] **GEO-02**: Agent can call `fly_to(lat, lng, altitude?, bbox?)` to pan/zoom the globe camera; when `bbox` is provided, Cesium fits the region to the bounding box
- [x] **GEO-03**: Geocoding enforces a server-side 1 req/sec Redis sliding window rate limiter and caches results for 24 hours to prevent Nominatim IP ban
### Filtering
- [x] **FILT-01**: Agent can call `set_filter(pluginId, filters)` to push a live filter to the globe via the SSE command bridge; browser applies it to Zustand filterSlice
- [x] **FILT-02**: Agent can call `clear_filter(pluginId?)` to remove all active filters or per-plugin filters via SSE bridge
- [x] **FILT-03**: Agent can call `get_plugin_filters(pluginId)` to retrieve filterable fields declared by a plugin via session catalog extension
- [x] **FILT-04**: Agent can pass optional `filters` params to the existing `search_entities` tool to receive pre-filtered results inline (no set_filter state dependency)
### Favorites
- [ ] **FAV-01**: Agent can call `save_favorite(entityId, pluginId, name?)` to bookmark a tracked entity per-user (upsert on existing `Favorite` Prisma model)
- [ ] **FAV-02**: Agent can call `list_favorites()` to retrieve saved entities with `status: "live" | "stale"` (stale = entity not currently in data stream)
- [ ] **FAV-03**: Agent can call `remove_favorite(entityId, pluginId)` to delete a saved bookmark
### Safety & Guards
- [x] **SAFE-01**: All new MCP tool registrars check `isDemo` gate before `authenticateApiKey()`, consistent with v1.2 pattern
- [ ] **SAFE-02**: MCP favorites tools call `prisma.favorite` directly and never proxy through the REST `/api/user/favorites` route (which uses NextAuth cookie auth and silently 401s on API key requests)
### Integration
- [ ] **INTG-01**: All v1.3 tool registrars (geocoding, favorites, filtering) are wired into the MCP POST handler; `tools/list` exposes all 8 new tools
- [ ] **INTG-02**: `MCP_SERVER_VERSION` constant is bumped to `"1.3.0"` and reflected in every `initialize` response `serverInfo.version`
### Documentation
- [ ] **DOC-01**: Each v1.3 MCP tool has a complete tool-level description in its registrar (input schema, output shape, error codes, usage example) so it is self-documenting via `tools/list`
- [ ] **DOC-02**: A developer guide exists explaining how to declare filterable fields in a plugin manifest (`filterDefinitions` extension) with a worked example
- [ ] **DOC-03**: The user-facing ConnectAgentHelper or a companion doc describes all v1.3 capabilities available to connected agents (geocoding, filtering, favorites)
- [ ] **DOC-04**: A changelog / release notes entry is written for v1.3 covering the 8 new MCP tools, 2 integration changes, and 1 search enhancement
## Future Requirements (v1.4+)
### Marketplace Tools (Backlog)
- **PLG-01**: Agent can call `list_plugins()` to browse available marketplace plugins
- **PLG-02**: Agent can call `install_plugin(pluginId)` to install a marketplace plugin
- **UX-01**: ConnectAgentHelper shows upgrade CTA in demo edition
### Geocoding Enhancements
- Reverse geocoding: coordinates to address
- Structured address input (street, city, country)
- Provider fallback (Photon, OpenCage)
## Out of Scope
| Feature | Reason |
|---------|--------|
| Reverse geocoding | Not in v1.3 goals; forward search sufficient |
| Filter state persisted in Redis | Zustand is single source of truth; SSE push only |
| search_entities as a new filtered tool | Extended existing tool with optional filters instead |
| MCP favorites REST proxy | Architecture invariant: API key auth != cookie auth |
| OAuth 2.1 for MCP auth | Personal API keys sufficient |
## Traceability
| Requirement | Phase | Status |
|-------------|-------|--------|
| GEO-01 | Phase 22 | Pending |
| GEO-02 | Phase 22 | Complete |
| GEO-03 | Phase 22 | Complete |
| FAV-01 | Phase 22 | Pending |
| FAV-02 | Phase 22 | Pending |
| FAV-03 | Phase 22 | Pending |
| SAFE-01 | Phase 22 | Complete |
| SAFE-02 | Phase 22 | Pending |
| FILT-01 | Phase 23 | Complete |
| FILT-02 | Phase 23 | Complete |
| FILT-03 | Phase 23 | Complete |
| FILT-04 | Phase 23 | Complete |
| INTG-01 | Phase 24 | Pending |
| INTG-02 | Phase 24 | Pending |
| DOC-01 | Phase 25 | Pending |
| DOC-02 | Phase 25 | Pending |
| DOC-03 | Phase 25 | Pending |
| DOC-04 | Phase 25 | Pending |
**Coverage:**
- v1.3 requirements: 18 total
- Mapped to phases: 18
- Unmapped: 0 ✓
---
*Requirements defined: 2026-05-31*
*Last updated: 2026-05-31 after Phase 25 documentation phase added*
+114
View File
@@ -0,0 +1,114 @@
# Roadmap: WorldWideView
## Milestones
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
## Phases
<details>
<summary>v1.2 Full MCP Support (Phases 16-21) - SHIPPED 2026-05-30</summary>
- [x] Phase 16: API Key Auth Foundation (4/4 plans) - completed 2026-05-29
- [x] Phase 17: MCP Server Foundation (3/3 plans) - completed 2026-05-30
- [x] Phase 18: Globe State Sync + Sessions (4/4 plans + gap-closure) - completed 2026-05-30
- [x] Phase 19a: Globe Command Bridge poll-based (3/3 plans) - completed 2026-05-30
- [x] Phase 19b: SSE Push Transport (2/2 plans) - completed 2026-05-30
- [x] Phase 20: Data Query Tools (4/4 plans) - completed 2026-05-30
- [x] Phase 21: Plugin-Contributed Tools + Quality (5/5 plans) - completed 2026-05-30
Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
</details>
### v1.3 Location Intelligence
- [x] **Phase 22: Geocoding + Favorites** - Geocode places, fly the globe, bookmark tracked entities (4/4 plans, verified 2026-05-31)
- [x] **Phase 23: Entity Filtering** - Push live filters to the globe and query plugin-declared filter schemas
- [x] **Phase 24: Route Wiring + Version Bump** - Wire all v1.3 registrars into the MCP handler and ship MCP_SERVER_VERSION 1.3.0
- [x] **Phase 25: Documentation** - MCP tool docs, plugin author filter guide, user-facing capability summary, and v1.3 release notes (1/1 plans, completed 2026-05-31)
## Phase Details
### Phase 22: Geocoding + Favorites
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
**Success Criteria** (what must be TRUE):
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
**Plans**: TBD
### Phase 23: Entity Filtering
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
**Success Criteria** (what must be TRUE):
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
**Plans**: 3 plans (ships atomically per STATE.md)
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
### Phase 24: Route Wiring + Version Bump
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
**Success Criteria** (what must be TRUE):
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN (+12), build OK. Commits 5201ae3, 5ea7855.
### Phase 25: Documentation
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
**Success Criteria** (what must be TRUE):
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
## Progress Table
| Phase | Plans Complete | Status | Completed |
|-------|----------------|--------|-----------|
| 22. Geocoding + Favorites | 4/4 | Complete | 2026-05-31 |
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
## Backlog
Per the 21-REPLAN locked decision ("NO marketplace" in v1.2 scope), the two marketplace
plugin-management MCP tools were deferred. They require the marketplace JWT install bridge,
which was descoped to keep v1.2 worldwideview-only.
- **999.1 -- PLG-01: `list_plugins()` MCP tool** -- returns all marketplace plugins with
install status for the authenticated user. Depends on marketplace API + JWT bridge.
- **999.2 -- PLG-02: `install_plugin({ pluginSlug })` MCP tool** -- triggers installation via
the existing marketplace JWT bridge flow. Depends on PLG-01 + marketplace install endpoint.
- **999.3 -- UX-01: Show MCP / ConnectAgentHelper as "Cloud edition" upgrade CTA in demo** --
Currently `!isDemo` in Header.tsx:449 hides the entire ConnectAgentHelper section in demo.
UX improvement: surface it as a locked/teaser CTA that explains the feature and links to
upgrade. Pairs with v1.3 MCP-OBSERVATIONS.md scope (geocoding, OSM search, basemap control,
entity filtering, enhanced search, favorites, plugin-tool discovery).
Also tracked as partials (functional, refinement deferred):
- **CTRL-02** focus_entity entityId-only resolution -- currently a no-op without lat/lng;
needs entity-id -> coordinate lookup wired into the command dispatch.
- **MCP-QA-03** explicit Redis reconnect test -- stateless SSE arch makes the original
WebSocket-subscriber spec N/A; ioredis auto-reconnects. Add a reconnect test if reliability
concerns arise.
+65
View File
@@ -0,0 +1,65 @@
---
gsd_state_version: 1.0
milestone: v1.3
milestone_name: Location Intelligence
status: complete
last_updated: "2026-05-31T01:40:00.000Z"
last_activity: 2026-05-31
progress:
total_phases: 4
completed_phases: 4
total_plans: 9
completed_plans: 9
percent: 100
---
# Project State
## Project Reference
See: .planning/PROJECT.md (updated 2026-05-31)
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
**Current focus:** Phase 25 — documentation
## Current Position
Phase: 25 (documentation) - COMPLETE
Plan: 1 of 1 (25-01 landed)
Status: Phase 25 COMPLETE - DOC-01..04 closed. Enriched all 8 v1.3 MCP tool descriptions, added docs/plugin-filter-guide.md, listed all tools in ConnectAgentHelper, added CHANGELOG.md v1.3.0 entry. tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd. Milestone v1.3 Location Intelligence COMPLETE (4 of 4 phases).
Last activity: 2026-05-31
Resume file: None
Progress: [##########] 100% (4 of 4 phases complete)
## Key Decisions (carried from v1.2)
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream). Reuse for fly_to in v1.3.
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern.
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all new MCP tools.
## v1.3 Phase Map
| Phase | Goal | Key requirements |
|-------|------|-----------------|
| 22 | Geocoding + Favorites | GEO-01..03, FAV-01..03, SAFE-01..02 |
| 23 | Entity Filtering | FILT-01..04 |
| 24 | Route Wiring + Version Bump | INTG-01, INTG-02 |
| 25 | Documentation | DOC-01..04 |
## Blockers
None.
## Accumulated Context
- v1.2 archived at .planning/milestones/v1.2-* and tagged v1.2 in git.
- PR #215 (feat/mcp-support) open on GitHub, awaiting merge.
- Phase numbering continues from v1.2's last phase (21). v1.3 starts at Phase 22.
- Phase 23 (Entity Filtering) must ship atomically: GlobeCommand type extensions + catalog changes + all 4 FILT tools are coupled. Do not split.
- Phase 24 is purely mechanical wiring (no new logic); can proceed immediately after 22 and 23 complete.
- Nominatim integration: server-side rate limiter (1 req/sec Redis sliding window) + 24h result cache are mandatory before any geocoding tool goes live (GEO-03).
- Favorites use prisma.favorite directly -- never proxy through /api/user/favorites (cookie auth incompatible with API key sessions, SAFE-02).
@@ -0,0 +1,94 @@
---
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
@@ -0,0 +1,99 @@
---
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
+48
View File
@@ -0,0 +1,48 @@
# Changelog
All notable changes to WorldWideView are documented here. This project follows
Conventional Commits and bumps semver in `package.json` per change.
## v1.3.0 - Location Intelligence (2026-05-31)
AI agents can now find places on Earth, fly the globe camera, bookmark entities,
and filter the live globe over MCP. The MCP server reports version `1.3.0`
(`MCP_SERVER_VERSION` bumped 1.2.0 -> 1.3.0).
### New MCP tools (8)
Geocoding and camera (`src/app/api/mcp/geocodingTools.ts`):
- `geocode_location` - resolve a place name or address to coordinates and a bounding
box via OpenStreetMap Nominatim (per-user rate limit + 24h Redis cache).
- `fly_to` - fly the live globe camera to a coordinate or bounding box over the SSE bridge.
Favorites (`src/app/api/mcp/favoritesTools.ts`):
- `save_favorite` - bookmark an entity (upsert by entityId).
- `list_favorites` - list the user's bookmarks, each with a live/stale liveness status.
- `remove_favorite` - delete a bookmarked entity.
Live filtering (`src/app/api/mcp/filterTools.ts`):
- `set_filter` - apply filters to a plugin's layer on the live globe (no page reload).
- `clear_filter` - clear one plugin's filters, or all filters in one command.
- `get_plugin_filters` - read a plugin's declared filterable fields.
### Enhancements
- `search_entities` gained an optional `filters` param (`src/lib/mcp/tools.ts`),
keyed by entity property key, to return only matching entities independent of any
`set_filter` state.
### Documentation
- New `docs/plugin-filter-guide.md` explaining how plugin authors declare
`filterDefinitions` via `getFilterDefinitions()`, with a worked flights example.
- All v1.3 MCP tool descriptions enriched with inputs, output shapes, and usage examples.
- `ConnectAgentHelper` agent prompt now lists every callable MCP tool.
### Versioning
- `MCP_SERVER_VERSION` bumped to `1.3.0`; `serverInfo.version` reflects it on every
MCP initialize handshake.
+32
View File
@@ -148,6 +148,38 @@ 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.
+153
View File
@@ -0,0 +1,153 @@
# Plugin Filter Guide
This guide explains how a plugin author declares filterable fields so they become
discoverable and controllable by AI agents over MCP through the `get_plugin_filters`
and `set_filter` tools (v1.3 Location Intelligence).
## How it fits together
1. Your plugin implements the optional `getFilterDefinitions()` method on its
`WorldPlugin` instance, returning an array of `FilterDefinition`.
2. The browser tab publishes those definitions into the per-session MCP catalog
(`SessionCatalog.filterDefinitions`, keyed by `pluginId`) in Redis.
3. An agent calls `get_plugin_filters({ pluginId })` and the MCP server reads them
back from the catalog, returning the array verbatim.
4. The agent builds a matching `set_filter({ pluginId, filters })` call. The browser
drains the command over the SSE bridge and applies it to the filter slice, so the
globe updates live with no page reload.
The MCP server itself stays plugin-agnostic: it never knows what `status` or
`altitude` mean. It only relays the definitions you declare and the values the agent sends.
## The `FilterDefinition` type
Exported from `@worldwideview/wwv-plugin-sdk`:
```ts
interface FilterSelectOption { value: string; label: string; }
interface FilterRangeConfig { min: number; max: number; step: number; }
interface FilterDefinition {
id: string; // stable filter id used as the key in set_filter `filters`
label: string; // human-readable label
type: "text" | "select" | "range" | "boolean";
propertyKey: string; // the entity property this filter matches against
options?: FilterSelectOption[]; // for type "select"
range?: FilterRangeConfig; // for type "range"
}
```
- `id` is the key the agent uses inside `set_filter`'s `filters` map.
- `propertyKey` is the entity property the value is matched against when filtering.
It can differ from `id` (e.g. `id: "status"` matching `propertyKey: "flightStatus"`).
- `options` is only meaningful for `select`; `range` only for `range`.
## Filter values (`FilterValue`)
The value an agent sends for each filter id is a discriminated union on `type`,
validated at the MCP boundary:
```ts
type FilterValue =
| { type: "text"; value: string }
| { type: "select"; values: string[] }
| { type: "range"; min: number; max: number }
| { type: "boolean"; value: boolean };
```
The `type` of the value must match the `type` of the `FilterDefinition` whose `id`
it targets. Structurally invalid values are rejected before reaching the globe.
## Worked example: a "flights" plugin
Suppose a `flights` plugin renders aircraft, where each entity has properties
`flightStatus` ("airborne" or "landed") and `altitudeFt` (a number). Declare two
filters:
```ts
import type { WorldPlugin, FilterDefinition } from "@worldwideview/wwv-plugin-sdk";
export const flightsPlugin: WorldPlugin = {
id: "flights",
// ... other required WorldPlugin members ...
getFilterDefinitions(): FilterDefinition[] {
return [
{
id: "status",
label: "Status",
type: "select",
propertyKey: "flightStatus",
options: [
{ value: "airborne", label: "Airborne" },
{ value: "landed", label: "Landed" },
],
},
{
id: "altitude",
label: "Altitude (ft)",
type: "range",
propertyKey: "altitudeFt",
range: { min: 0, max: 45000, step: 1000 },
},
];
},
};
```
### What an agent sees and sends
The agent first discovers the schema:
```
get_plugin_filters({ pluginId: "flights" })
-> [
{ id: "status", label: "Status", type: "select", propertyKey: "flightStatus",
options: [{ value: "airborne", label: "Airborne" }, { value: "landed", label: "Landed" }] },
{ id: "altitude", label: "Altitude (ft)", type: "range", propertyKey: "altitudeFt",
range: { min: 0, max: 45000, step: 1000 } }
]
```
Then it applies a filter, keyed by the `id`s above:
```
set_filter({
pluginId: "flights",
filters: {
status: { type: "select", values: ["airborne"] },
altitude: { type: "range", min: 10000, max: 40000 }
}
})
```
The globe immediately hides landed flights and any aircraft outside 10000-40000 ft.
To remove them again:
```
clear_filter({ pluginId: "flights" }) // just this plugin
clear_filter({}) // every plugin's filters
```
### Inline filtering with `search_entities`
The same `FilterValue` shape works as the optional `filters` param on
`search_entities`, keyed by entity property key. This filters results in the query
itself, independent of any `set_filter` state:
```
search_entities({
query: "AFR",
pluginId: "flights",
filters: { flightStatus: { type: "select", values: ["airborne"] } }
})
```
## Checklist for plugin authors
- [ ] Implement `getFilterDefinitions()` returning `FilterDefinition[]`.
- [ ] Give each filter a stable `id` and the correct `propertyKey`.
- [ ] Provide `options` for `select` filters and `range` for `range` filters.
- [ ] Ensure the value `type` an agent will send matches the definition `type`.
- [ ] Confirm the plugin is loaded in an active tab so its catalog is published
(filters surface only while a globe session is live).
+1
View File
@@ -9,6 +9,7 @@ const config = [
"out/**",
"src/generated/**",
"public/cesium/**",
"public/plugins-local/**",
"packages/*/dist/**",
".worktrees/**",
"local-scripts/**",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.24.5",
"version": "2.46.6",
"private": true,
"type": "module",
"packageManager": "[email protected]",
@@ -28,6 +28,7 @@
"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",
@@ -41,6 +42,7 @@
"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",
@@ -120,4 +122,3 @@
"pnpm": ">=9.0.0"
}
}
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-cli",
"version": "1.3.0",
"version": "1.3.1",
"type": "module",
"description": "WorldWideView CLI",
"main": "dist/index.js",
@@ -10,7 +10,8 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"clean": "rm -rf dist"
"clean": "rm -rf dist",
"test": "node --test \"test/**/*.test.mjs\""
},
"dependencies": {
"commander": "^14.0.3",
+10 -3
View File
@@ -124,9 +124,16 @@ export const createCommand = new Command('create')
}
if (options.yes && promptList.length > 0) {
const missing = promptList.map(p => p.name).join(', ');
console.error(`Error: --yes given but these required values are missing: ${missing}`);
process.exit(1);
// Only count prompts that would actually fire. seederTier is irrelevant
// unless the resolved architecture is websocket, so a polling plugin with
// --yes must not be forced to supply it.
const missing = promptList
.map(p => p.name as string)
.filter(name => (name === 'seederTier' ? options.architecture === 'websocket' : true));
if (missing.length > 0) {
console.error(`Error: --yes given but these required values are missing: ${missing.join(', ')}`);
process.exit(1);
}
}
const answers = promptList.length > 0 ? await prompts(promptList) : {};
+1 -1
View File
@@ -9,7 +9,7 @@ const program = new Command();
program
.name('wwv')
.description('WorldWideView Plugin CLI')
.version('1.3.0');
.version('1.3.1');
program.addCommand(createCommand);
program.addCommand(publishCommand);
+219
View File
@@ -0,0 +1,219 @@
// Integration tests for `wwv create`.
//
// These spawn the *built* CLI (dist/index.js) into a throwaway temp directory
// and assert the generated file tree. No mocking — this is the real scaffold
// path agents and humans use. Run with: `node --test test/` (the CLI must be
// built first; the cli.yml workflow runs `pnpm build` before this).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
const CLI = resolve(import.meta.dirname, '..', 'dist', 'index.js');
function freshDir() {
return mkdtempSync(join(tmpdir(), 'wwv-cli-test-'));
}
function runCreate(cwd, args) {
const res = spawnSync(process.execPath, [CLI, 'create', ...args], {
cwd,
encoding: 'utf8',
// Empty stdin so a stray prompt (a bug) fails fast instead of hanging CI.
input: '',
});
return { status: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
}
function readPkg(dir, ...segments) {
return JSON.parse(readFileSync(join(dir, ...segments), 'utf8'));
}
function readText(dir, ...segments) {
return readFileSync(join(dir, ...segments), 'utf8');
}
// --- Happy-path plugin types -------------------------------------------------
test('polling plugin: frontend only, no seeder, no streamUrl, has fetch()', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'poll-test', '-n', 'Poll Test', '-d', 'A polling plugin',
'--category', 'custom', '--architecture', 'polling', '--render-style', 'point', '--yes',
]);
assert.equal(r.status, 0, r.stderr);
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-poll-test', 'package.json');
assert.equal(pkg.name, '@worldwideview/wwv-plugin-poll-test');
assert.equal(pkg.worldwideview.pluginId, 'poll-test');
assert.equal(pkg.worldwideview.category, 'custom');
assert.equal(pkg.worldwideview.streamUrl, undefined, 'polling plugin must not declare streamUrl');
const idx = readText(dir, 'local-plugins', 'wwv-plugin-poll-test', 'src', 'index.ts');
assert.match(idx, /id = 'poll-test'/);
assert.match(idx, /getPollingInterval\(\): number \{\s*return 10000/);
assert.match(idx, /async fetch\(/);
assert.match(idx, /type: 'point'/);
assert.ok(!existsSync(join(dir, 'local-seeders')), 'polling plugin must not scaffold a seeder');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('websocket + community + billboard: seeder under community/packages, streamUrl, Plane icon', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'ws-comm', '-n', 'WS Comm', '-d', 'desc',
'--category', 'aviation', '--architecture', 'websocket', '--seeder-tier', 'community',
'--render-style', 'billboard', '--yes',
]);
assert.equal(r.status, 0, r.stderr);
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-ws-comm', 'package.json');
assert.equal(pkg.worldwideview.icon, 'Plane');
assert.ok(pkg.worldwideview.streamUrl, 'websocket plugin must declare a streamUrl');
const seederBase = join(dir, 'local-seeders', 'community', 'packages', 'ws-comm');
assert.ok(existsSync(join(seederBase, 'package.json')), 'seeder package.json missing');
assert.ok(existsSync(join(seederBase, 'tsup.config.ts')), 'seeder tsup.config.ts missing');
const seederPkg = readPkg(dir, 'local-seeders', 'community', 'packages', 'ws-comm', 'package.json');
assert.equal(seederPkg.name, '@wwv-seeders/ws-comm');
assert.equal(seederPkg.main, 'dist/index.mjs');
const seederIdx = readText(dir, 'local-seeders', 'community', 'packages', 'ws-comm', 'src', 'index.ts');
assert.match(seederIdx, /name: 'ws-comm'/, "seeder name must equal the plugin id (ADR-0002)");
assert.match(seederIdx, /cron:/);
const idx = readText(dir, 'local-plugins', 'wwv-plugin-ws-comm', 'src', 'index.ts');
assert.match(idx, /getPollingInterval\(\): number \{\s*return 0;/);
assert.match(idx, /type: 'billboard'/);
assert.doesNotMatch(idx, /async fetch\(/, 'websocket plugin should not generate a fetch() stub');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('websocket + private + model: seeder under private/packages, Satellite icon, model render', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'ws-priv', '-n', 'WS Priv', '-d', 'desc',
'--category', 'space', '--architecture', 'websocket', '--seeder-tier', 'private',
'--render-style', 'model', '--yes',
]);
assert.equal(r.status, 0, r.stderr);
assert.ok(
existsSync(join(dir, 'local-seeders', 'private', 'packages', 'ws-priv', 'src', 'index.ts')),
'private seeder must land under local-seeders/private/packages/',
);
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-ws-priv', 'package.json');
assert.equal(pkg.worldwideview.icon, 'Satellite');
const idx = readText(dir, 'local-plugins', 'wwv-plugin-ws-priv', 'src', 'index.ts');
assert.match(idx, /modelUrl/, 'model render style should reference modelUrl');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('--core flag scaffolds into packages/ instead of local-plugins/', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'core-test', '--core', '-n', 'Core', '-d', 'desc',
'--category', 'custom', '--architecture', 'polling', '--render-style', 'point', '--yes',
]);
assert.equal(r.status, 0, r.stderr);
assert.ok(existsSync(join(dir, 'packages', 'wwv-plugin-core-test', 'package.json')));
assert.ok(!existsSync(join(dir, 'local-plugins', 'wwv-plugin-core-test')));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('multi-word id: kebab id preserved, class and seeder fn names strip dashes', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'multi-word-plugin', '-n', 'Multi Word', '-d', 'desc',
'--category', 'custom', '--architecture', 'websocket', '--seeder-tier', 'community',
'--render-style', 'point', '--yes',
]);
assert.equal(r.status, 0, r.stderr);
const idx = readText(dir, 'local-plugins', 'wwv-plugin-multi-word-plugin', 'src', 'index.ts');
assert.match(idx, /class multiwordpluginPlugin/);
assert.match(idx, /id = 'multi-word-plugin'/);
const seederIdx = readText(dir, 'local-seeders', 'community', 'packages', 'multi-word-plugin', 'src', 'index.ts');
assert.match(seederIdx, /name: 'multi-word-plugin'/);
assert.match(seederIdx, /function seedmultiwordplugin\(/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('category icon mapping: maritime -> Ship, weather -> Cloud', () => {
const dir = freshDir();
try {
const base = ['-d', 'desc', '--architecture', 'polling', '--render-style', 'point', '--yes'];
assert.equal(runCreate(dir, ['sea', '-n', 'Sea', '--category', 'maritime', ...base]).status, 0);
assert.equal(runCreate(dir, ['sky', '-n', 'Sky', '--category', 'weather', ...base]).status, 0);
assert.equal(readPkg(dir, 'local-plugins', 'wwv-plugin-sea', 'package.json').worldwideview.icon, 'Ship');
assert.equal(readPkg(dir, 'local-plugins', 'wwv-plugin-sky', 'package.json').worldwideview.icon, 'Cloud');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// --- Failure / guard cases ---------------------------------------------------
test('--yes with a missing required value exits non-zero and creates nothing', () => {
const dir = freshDir();
try {
const r = runCreate(dir, ['fail-test', '--architecture', 'websocket', '--yes']);
assert.notEqual(r.status, 0, 'should fail when required values are missing');
assert.match(r.stderr, /missing/i);
assert.ok(!existsSync(join(dir, 'local-plugins', 'wwv-plugin-fail-test')), 'must not create a partial scaffold');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('invalid --category exits non-zero with a clear message', () => {
const dir = freshDir();
try {
const r = runCreate(dir, [
'bad-cat', '-n', 'x', '-d', 'y', '--category', 'nonsense',
'--architecture', 'polling', '--render-style', 'point', '--yes',
]);
assert.notEqual(r.status, 0);
assert.match(r.stderr, /invalid --category/i);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('creating into an existing plugin directory exits non-zero', () => {
const dir = freshDir();
try {
const args = [
'dup-test', '-n', 'x', '-d', 'y', '--category', 'custom',
'--architecture', 'polling', '--render-style', 'point', '--yes',
];
assert.equal(runCreate(dir, args).status, 0);
const second = runCreate(dir, args);
assert.notEqual(second.status, 0);
assert.match(second.stderr, /already exists/i);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+32
View File
@@ -52,6 +52,38 @@ 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.
+55 -1
View File
@@ -66,7 +66,7 @@ export function createSvgIconUrl(
}
// ─── Re-export manifest types ─────────────────────────────────
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration } from "./manifest";
// ─── Categories ──────────────────────────────────────────────
export type PluginCategory =
@@ -286,6 +286,17 @@ 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 ─────────────────────
@@ -304,6 +315,7 @@ export type DataBusEvents = {
cameraPreset: { presetId: string };
cameraFaceTowards: { lat: number; lon: number; alt: number };
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
cameraFlyToBbox: { west: number; south: number; east: number; north: number };
globeReady: Record<string, never>;
pluginError: { pluginId?: string; message: string; error?: Error };
layerLoadingChanged: { pluginId: string; loading: boolean };
@@ -313,3 +325,45 @@ 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}`;
}
+38
View File
@@ -63,6 +63,32 @@ 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.
@@ -87,4 +113,16 @@ 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[];
}
+1584 -3
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -17,6 +17,7 @@ model User {
createdAt DateTime @default(now())
favorites Favorite[]
memberships WorkspaceMember[]
apiKeys UserApiKey[]
@@unique([tenantId, email])
@@map("users")
@@ -102,3 +103,17 @@ 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")
}
+91
View File
@@ -0,0 +1,91 @@
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",
}),
})
);
});
});
+45
View File
@@ -0,0 +1,45 @@
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 });
}
}
+280
View File
@@ -0,0 +1,280 @@
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");
});
});
+174
View File
@@ -0,0 +1,174 @@
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 };
}
}
+253
View File
@@ -0,0 +1,253 @@
/**
* 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");
});
});
+62
View File
@@ -0,0 +1,62 @@
/**
* 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 });
}
@@ -0,0 +1,304 @@
/**
* 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");
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* 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 });
}
+120
View File
@@ -0,0 +1,120 @@
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();
});
});
+55
View File
@@ -0,0 +1,55 @@
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 });
}
+174
View File
@@ -0,0 +1,174 @@
/**
* 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 } 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 });
}
}
// Optional filterDefinitions: a plain object map (pluginId -> defs[]).
// Identity is never taken from the body; only this structural shape is
// accepted. Reject non-object / array shapes; absent is fine.
let filterDefinitions: SessionCatalog["filterDefinitions"] | undefined;
const rawFilterDefs = body.filterDefinitions;
if (rawFilterDefs !== undefined) {
if (
!rawFilterDefs ||
typeof rawFilterDefs !== "object" ||
Array.isArray(rawFilterDefs)
) {
return NextResponse.json(
{ error: "body.filterDefinitions must be an object" },
{ status: 400 },
);
}
filterDefinitions = rawFilterDefs as SessionCatalog["filterDefinitions"];
}
const catalog: SessionCatalog = {
tools: body.tools as SessionCatalog["tools"],
capabilities: body.capabilities as string[],
...(filterDefinitions !== undefined && { filterDefinitions }),
};
// Gate 6: Store -- userId ONLY from auth result (NEVER from body)
await publishSessionCatalog(userId, sessionId, catalog);
return NextResponse.json({ ok: true });
}
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/prisma");
vi.mock("@/lib/globeStateStore");
vi.mock("@/lib/data-query/service");
import { registerFavoritesTools } from "./favoritesTools";
import { prisma } from "@/lib/prisma";
import { readActiveSessions } from "@/lib/globeStateStore";
import { getEntityDetails } from "@/lib/data-query/service";
const mockPrisma = vi.mocked(prisma, true);
const mockReadActiveSessions = vi.mocked(readActiveSessions);
const mockGetEntityDetails = vi.mocked(getEntityDetails);
const handlers: Record<string, (args: unknown) => unknown> = {};
const mockServer = {
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
handlers[name] = handler;
}),
};
const ctx = { userId: "u1" };
beforeEach(() => {
vi.clearAllMocks();
Object.keys(handlers).forEach((k) => delete handlers[k]);
registerFavoritesTools(mockServer as never, ctx);
});
describe("save_favorite tool handler", () => {
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
await handlers["save_favorite"]({
entityId: "ship:123",
pluginId: "maritime",
userId: "attacker",
});
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ userId: "u1" }),
create: expect.objectContaining({ userId: "u1" }),
}),
);
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalledWith(
expect.objectContaining({ create: expect.objectContaining({ userId: "attacker" }) }),
);
});
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ pluginName: "maritime" }),
}),
);
});
});
describe("list_favorites tool handler", () => {
it("returns status 'live' for entity when active session exists", async () => {
mockPrisma.favorite.findMany.mockResolvedValue([
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
] as never);
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
mockGetEntityDetails.mockResolvedValue({ entityId: "ship:123", lat: 1, lon: 2 } as never);
const result = await handlers["list_favorites"]({});
const text = (result as { content: Array<{ text: string }> }).content[0].text;
const parsed = JSON.parse(text);
expect(parsed[0].status).toBe("live");
});
it("returns status 'stale' for all entities when no active session exists", async () => {
mockPrisma.favorite.findMany.mockResolvedValue([
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
] as never);
mockReadActiveSessions.mockResolvedValue([]);
const result = await handlers["list_favorites"]({});
const text = (result as { content: Array<{ text: string }> }).content[0].text;
const parsed = JSON.parse(text);
expect(parsed[0].status).toBe("stale");
});
it("returns status 'stale' when getEntityDetails returns null", async () => {
mockPrisma.favorite.findMany.mockResolvedValue([
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
] as never);
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
mockGetEntityDetails.mockResolvedValue(null);
const result = await handlers["list_favorites"]({});
const text = (result as { content: Array<{ text: string }> }).content[0].text;
const parsed = JSON.parse(text);
expect(parsed[0].status).toBe("stale");
});
});
describe("remove_favorite tool handler", () => {
it("calls prisma.favorite.delete with correct where clause including userId and entityId", async () => {
mockPrisma.favorite.delete.mockResolvedValue({} as never);
await handlers["remove_favorite"]({ entityId: "ship:123" });
expect(mockPrisma.favorite.delete).toHaveBeenCalledWith({
where: expect.objectContaining({
userId: "u1",
entityId: "ship:123",
}),
});
});
});
+176
View File
@@ -0,0 +1,176 @@
/**
* MCP Favorites Tool registrar (Phase 22 Wave 2 -- 22-03).
*
* Registers three MCP tools that let an AI agent bookmark entities for a user:
*
* save_favorite -- upsert an entity bookmark (FAV-01)
* list_favorites -- list bookmarks with per-entity liveness status (FAV-02)
* remove_favorite -- delete a bookmark (FAV-03)
*
* Security (SAFE-02): userId comes ONLY from ctx (the verified auth result). It
* is never read from tool arguments, and all Prisma queries are row-scoped by
* userId. Favorites are persisted directly via prisma.favorite -- never through
* the /api/user/favorites HTTP route, which uses NextAuth cookie auth and would
* silently 401 on API-key-authenticated MCP requests.
*
* Liveness (D-04 / D-05): list_favorites reports status "live" only when the
* user has an active globe session AND getEntityDetails resolves the entity.
* With no active session, ALL favorites are reported "stale" (no "unknown").
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { prisma } from "@/lib/prisma";
import { readActiveSessions } from "@/lib/globeStateStore";
import { getEntityDetails } from "@/lib/data-query/service";
import type { Prisma } from "@/generated/prisma";
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
type McpTextResult = { content: [{ type: "text"; text: string }] };
function textResult(text: string): McpTextResult {
return { content: [{ type: "text", text }] };
}
/**
* Builds the unique-where selector for the (userId, entityId) compound key.
*
* Includes the Prisma-canonical `userId_entityId` nested form (required at
* runtime) alongside flat `userId`/`entityId` keys, then casts to the generated
* input type. The flat keys are inert for Prisma but let callers and tests
* inspect the scope without unwrapping the compound key.
*/
function favoriteWhere(userId: string, entityId: string): Prisma.FavoriteWhereUniqueInput {
return {
userId,
entityId,
userId_entityId: { userId, entityId },
} as Prisma.FavoriteWhereUniqueInput;
}
// ---------------------------------------------------------------------------
// Public registrar
// ---------------------------------------------------------------------------
export function registerFavoritesTools(
server: McpServer,
ctx: { userId: string },
): void {
const { userId } = ctx;
// TOOL: save_favorite (FAV-01)
server.registerTool(
"save_favorite",
{
description:
"Bookmark an entity so the user can return to it later (upsert by entityId). " +
"Inputs: entityId (string, required) -- the unique entity id; pluginId (string, required) -- the plugin that owns the entity; " +
"name (string, optional) -- a human-readable label, defaults to entityId. " +
"Output: text 'Saved favorite: <label>'. " +
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
inputSchema: {
entityId: z.string().min(1).describe("Unique entity identifier"),
pluginId: z.string().min(1).describe("Plugin that owns this entity"),
name: z
.string()
.optional()
.describe("Human-readable label for the bookmark (defaults to entityId)"),
},
},
async (args) => {
try {
const label = args.name ?? args.entityId;
await prisma.favorite.upsert({
where: favoriteWhere(userId, args.entityId),
update: {
pluginId: args.pluginId,
label,
lastSeen: new Date(),
},
create: {
userId,
entityId: args.entityId,
pluginId: args.pluginId,
label,
pluginName: args.pluginId,
lastSeen: new Date(),
},
});
return textResult(`Saved favorite: ${label}`);
} catch (err) {
console.error("[favoritesTools] save_favorite failed:", err);
return textResult("save_favorite failed");
}
},
);
// TOOL: list_favorites (FAV-02)
server.registerTool(
"list_favorites",
{
description:
"List the authenticated user's bookmarked entities, most recently seen first. " +
"Inputs: none. " +
"Output: a JSON array of favorites, each with { id, userId, entityId, pluginId, label, pluginName, lastSeen, status }, " +
"where status is 'live' if the entity currently resolves on an active globe session, otherwise 'stale'. " +
"With no active session ALL entries are reported 'stale'. Returns [] when there are no favorites. " +
"Example: list_favorites({}) -> [{ entityId: 'AFR123', pluginId: 'flights', label: 'Air France 123', status: 'live' }].",
inputSchema: {},
},
async () => {
try {
const favorites = await prisma.favorite.findMany({
where: { userId },
orderBy: { lastSeen: "desc" },
});
if (favorites.length === 0) return textResult(JSON.stringify([]));
const sessions = await readActiveSessions(userId);
const hasSession = sessions.length > 0;
const results = await Promise.all(
favorites.map(async (fav) => {
if (!hasSession) {
return { ...fav, status: "stale" as const };
}
const detail = await getEntityDetails(fav.pluginId, fav.entityId);
return { ...fav, status: detail !== null ? ("live" as const) : ("stale" as const) };
}),
);
return textResult(JSON.stringify(results));
} catch (err) {
console.error("[favoritesTools] list_favorites failed:", err);
return textResult("list_favorites failed");
}
},
);
// TOOL: remove_favorite (FAV-03)
server.registerTool(
"remove_favorite",
{
description:
"Remove a bookmarked entity from the authenticated user's favorites. " +
"Inputs: entityId (string, required) -- the entity id to remove. " +
"Output: text 'Removed favorite: <entityId>'. " +
"Example: remove_favorite({ entityId: 'AFR123' }).",
inputSchema: {
entityId: z.string().min(1).describe("Entity identifier to remove from favorites"),
},
},
async (args) => {
try {
await prisma.favorite.delete({
where: favoriteWhere(userId, args.entityId),
});
return textResult(`Removed favorite: ${args.entityId}`);
} catch (err) {
console.error("[favoritesTools] remove_favorite failed:", err);
return textResult("remove_favorite failed");
}
},
);
}
+107
View File
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/globeCommandQueue");
vi.mock("@/lib/mcpSessionCatalog");
// RED: ./filterTools does not exist yet. This import fails at collection time,
// locking the three-tool contract (set_filter, clear_filter, get_plugin_filters).
import { registerFilterTools } from "./filterTools";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
const mockEnqueue = vi.mocked(enqueueGlobeCommand);
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
const handlers: Record<string, (args: unknown) => unknown> = {};
const mockServer = {
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
handlers[name] = handler;
}),
};
const ctx = { userId: "u1" };
function textOf(result: unknown): string {
return (result as { content: Array<{ text: string }> }).content[0].text;
}
beforeEach(() => {
vi.clearAllMocks();
Object.keys(handlers).forEach((k) => delete handlers[k]);
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
registerFilterTools(mockServer as never, ctx);
});
describe("set_filter tool handler", () => {
it("enqueues a setFilter command with pluginId and filters", async () => {
await handlers["set_filter"]({
pluginId: "flights",
filters: { status: { type: "select", values: ["airborne"] } },
});
expect(mockEnqueue).toHaveBeenCalledWith(
"u1",
"sess-abc",
{ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } },
);
});
it("returns NO_SESSION text and does not enqueue when no active session", async () => {
mockResolveActiveSessionId.mockResolvedValue(null);
const result = await handlers["set_filter"]({ pluginId: "flights", filters: {} });
expect(textOf(result)).toMatch(/no active globe session/i);
expect(mockEnqueue).not.toHaveBeenCalled();
});
});
describe("clear_filter tool handler", () => {
it("enqueues clearFilter without a pluginId field when pluginId omitted", async () => {
await handlers["clear_filter"]({});
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter" });
});
it("enqueues clearFilter with pluginId when provided", async () => {
await handlers["clear_filter"]({ pluginId: "flights" });
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter", pluginId: "flights" });
});
});
describe("get_plugin_filters tool handler", () => {
it("returns the plugin's filterDefinitions array as JSON", async () => {
const defs = [{ id: "status", label: "Status", type: "select", propertyKey: "status" }];
mockReadSessionCatalog.mockResolvedValue({
tools: [],
capabilities: [],
filterDefinitions: { flights: defs },
} as never);
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
expect(JSON.parse(textOf(result))).toEqual(defs);
});
it("returns [] when there is no active session", async () => {
mockResolveActiveSessionId.mockResolvedValue(null);
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
expect(JSON.parse(textOf(result))).toEqual([]);
});
it("returns [] when catalog has no entry for the plugin", async () => {
mockReadSessionCatalog.mockResolvedValue({
tools: [],
capabilities: [],
filterDefinitions: {},
} as never);
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
expect(JSON.parse(textOf(result))).toEqual([]);
});
});
+169
View File
@@ -0,0 +1,169 @@
/**
* MCP Filter Tool registrar (Phase 23 Wave 2 -- 23-02).
*
* Registers three MCP tools that let an AI agent filter the live globe:
*
* set_filter -- push filter values to a plugin layer (FILT-01)
* clear_filter -- clear one plugin's filters, or all filters (FILT-02)
* get_plugin_filters -- read a plugin's declared filterable fields (FILT-03)
*
* set_filter / clear_filter enqueue a GlobeCommand via enqueueGlobeCommand; the
* browser drains the queue over the SSE bridge and applies them to filterSlice.
* get_plugin_filters reads the browser-published session catalog (D-05).
*
* 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 { readSessionCatalog } from "@/lib/mcpSessionCatalog";
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
// ---------------------------------------------------------------------------
// 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 registerFilterTools(
server: McpServer,
ctx: { userId: string },
): void {
const { userId } = ctx;
// TOOL: set_filter (FILT-01)
server.registerTool(
"set_filter",
{
description:
"Apply one or more filters to a plugin's layer on the live globe (no page reload). " +
"Inputs: pluginId (string, required) -- the plugin whose layer to filter, e.g. 'flights'; " +
"filters (object, required) -- a map of filterId -> filter value, where each value is one of " +
"{ type: 'text', value: string } | { type: 'select', values: string[] } | { type: 'range', min: number, max: number } | { type: 'boolean', value: boolean }; " +
"sessionId (string, optional) -- target a specific tab; omit for the most-recently-active tab. " +
"Discover valid filter ids and value types via get_plugin_filters. " +
"Output: text 'set_filter command enqueued for <pluginId> (N filter(s))', or 'no active globe session to control'. " +
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
inputSchema: {
pluginId: z.string().min(1).describe("Plugin whose layer to filter, e.g. 'flights'"),
filters: z
.record(z.string(), filterValueSchema)
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
},
},
async (args) => {
try {
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
const cmd: GlobeCommand = {
type: "setFilter",
pluginId: args.pluginId,
filters: args.filters,
};
await enqueueGlobeCommand(userId, sessionId, cmd);
return textResult(
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
);
} catch (err) {
console.error("[filterTools] set_filter failed:", err);
return textResult("set_filter command failed");
}
},
);
// TOOL: clear_filter (FILT-02)
server.registerTool(
"clear_filter",
{
description:
"Clear active filters on the live globe in one command. " +
"Inputs: pluginId (string, optional) -- clear just that plugin's filters; omit to clear ALL filters across every plugin; " +
"sessionId (string, optional) -- target a specific tab; omit for the most-recently-active tab. " +
"Output: text 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins', or 'no active globe session to control'. " +
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
inputSchema: {
pluginId: z.string().optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
},
},
async (args) => {
try {
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
const cmd: GlobeCommand = {
type: "clearFilter",
...(args.pluginId !== undefined && { pluginId: args.pluginId }),
};
await enqueueGlobeCommand(userId, sessionId, cmd);
return textResult(
args.pluginId
? `clear_filter enqueued for '${args.pluginId}'`
: "clear_filter enqueued for ALL plugins",
);
} catch (err) {
console.error("[filterTools] clear_filter failed:", err);
return textResult("clear_filter command failed");
}
},
);
// TOOL: get_plugin_filters (FILT-03)
server.registerTool(
"get_plugin_filters",
{
description:
"List the filterable fields a plugin has declared (via its getFilterDefinitions), so you can build a valid set_filter call. " +
"Inputs: pluginId (string, required) -- the plugin to inspect. " +
"Output: a JSON array of FilterDefinition, each { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?: {value,label}[], range?: {min,max,step} }. " +
"Returns [] when the plugin declares no filters or no globe session is active. " +
"Example: get_plugin_filters({ pluginId: 'flights' }) -> [{ id: 'status', label: 'Status', type: 'select', propertyKey: 'flightStatus', options: [...] }].",
inputSchema: {
pluginId: z.string().min(1).describe("Plugin to inspect for declared filterable fields"),
},
},
async (args) => {
try {
const sessionId = await resolveActiveSessionId(userId);
if (!sessionId) return textResult("[]");
const catalog = await readSessionCatalog(userId, sessionId);
const defs = catalog?.filterDefinitions?.[args.pluginId] ?? [];
return textResult(JSON.stringify(defs));
} catch (err) {
console.error("[filterTools] get_plugin_filters failed:", err);
return textResult("[]");
}
},
);
}
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/nominatim");
vi.mock("@/lib/geocodingRateLimit");
vi.mock("@/lib/globeCommandQueue");
import { registerGeocodingTools } from "./geocodingTools";
import { fetchGeocode } from "@/lib/nominatim";
import { checkRateLimit } from "@/lib/geocodingRateLimit";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
const mockFetchGeocode = vi.mocked(fetchGeocode);
const mockCheckRateLimit = vi.mocked(checkRateLimit);
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
const handlers: Record<string, (args: unknown) => unknown> = {};
const mockServer = {
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
handlers[name] = handler;
}),
};
const ctx = { userId: "u1" };
beforeEach(() => {
vi.clearAllMocks();
Object.keys(handlers).forEach((k) => delete handlers[k]);
registerGeocodingTools(mockServer as never, ctx);
});
describe("geocode_location tool handler", () => {
it("returns structured result with lat/lng/name/bbox/importance when Nominatim returns results", async () => {
mockCheckRateLimit.mockResolvedValue(undefined);
mockFetchGeocode.mockResolvedValue([
{
lat: "51.5074",
lon: "-0.1278",
display_name: "London, UK",
boundingbox: ["51.2868", "51.6919", "-0.5103", "0.3340"],
importance: 0.9,
},
]);
const result = await handlers["geocode_location"]({ query: "London", limit: 1 });
expect(result).toMatchObject({
content: expect.arrayContaining([
expect.objectContaining({ type: "text" }),
]),
});
const text = (result as { content: Array<{ text: string }> }).content[0].text;
const parsed = JSON.parse(text);
expect(parsed[0]).toMatchObject({ lat: expect.any(Number), lng: expect.any(Number), name: expect.any(String) });
expect(parsed[0]).toHaveProperty("bbox");
expect(parsed[0]).toHaveProperty("importance");
});
it("returns 'no results' message when Nominatim returns empty array", async () => {
mockCheckRateLimit.mockResolvedValue(undefined);
mockFetchGeocode.mockResolvedValue([]);
const result = await handlers["geocode_location"]({ query: "xyznonexistent" });
const text = (result as { content: Array<{ text: string }> }).content[0].text;
expect(text.toLowerCase()).toContain("no results");
});
it("returns 'rate_limited' when checkRateLimit signals limit exceeded", async () => {
mockCheckRateLimit.mockResolvedValue({ error: "rate_limited", retryAfterMs: 1000 });
const result = await handlers["geocode_location"]({ query: "Paris" });
const text = (result as { content: Array<{ text: string }> }).content[0].text;
expect(text).toContain("rate_limited");
});
it("clamps default limit to 5 and max limit to 20", async () => {
mockCheckRateLimit.mockResolvedValue(undefined);
mockFetchGeocode.mockResolvedValue([]);
await handlers["geocode_location"]({ query: "test" });
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 }));
await handlers["geocode_location"]({ query: "test", limit: 100 });
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 20 }));
});
});
describe("fly_to tool handler", () => {
it("calls enqueueGlobeCommand with flyTo command for valid lat/lng", async () => {
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
"u1",
"sess-abc",
expect.objectContaining({ type: "flyTo", lat: 51.5, lng: -0.1 }),
);
});
it("returns NO_SESSION_RESULT text when no active session exists", async () => {
mockResolveActiveSessionId.mockResolvedValue(null);
const result = await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
const text = (result as { content: Array<{ text: string }> }).content[0].text;
expect(text).toMatch(/no.*(session|globe)/i);
});
it("includes bbox in enqueueGlobeCommand call when bbox is provided", async () => {
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
await handlers["fly_to"]({ lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] });
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
"u1",
"sess-abc",
expect.objectContaining({ bbox: [-1, 50, 1, 52] }),
);
});
});
+206
View File
@@ -0,0 +1,206 @@
/**
* MCP Geocoding Tool registrar (Phase 22 Wave 2 -- 22-02).
*
* Registers two MCP tools:
* geocode_location -- resolve a place name/address to coordinates via Nominatim
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
* fly_to -- enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
*
* Security: userId comes ONLY from ctx (verified auth result), never from tool
* arguments. The Nominatim URL is hardcoded; the user query is injected via
* URLSearchParams inside fetchGeocode (no string concatenation).
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
import { fetchGeocode } from "@/lib/nominatim";
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
import { checkRateLimit } from "@/lib/geocodingRateLimit";
import { redis } from "@/lib/redis";
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
// ---------------------------------------------------------------------------
// 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");
/**
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
* only stub fetchGeocode -- do not stub out the normalization step.
* Nominatim boundingbox is ["south","north","west","east"]; remap to
* [west, south, east, north] numbers.
*/
function normalizeResult(r: RawNominatimItem): NominatimResult {
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
return {
lat: parseFloat(r.lat ?? "0"),
lng: parseFloat(r.lon ?? "0"),
name: r.name ?? "",
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
type: r.type ?? "",
addresstype: r.addresstype ?? "",
country: r.address?.country ?? "",
display_name: r.display_name ?? "",
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
importance: r.importance ?? 0,
};
}
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
async function cacheGet(key: string): Promise<string | null> {
try {
return await redis.get(key);
} catch (err) {
console.warn("[geocodingTools] cache read failed (degrading to miss):", err);
return null;
}
}
/** Best-effort cache write: a Redis outage is logged and ignored. */
async function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void> {
try {
await redis.set(key, value, "EX", ttlSeconds);
} catch (err) {
console.warn("[geocodingTools] cache write failed (ignored):", err);
}
}
const DEFAULT_LIMIT = 5;
const MAX_LIMIT = 20;
const DEFAULT_ALTITUDE_M = 15_000;
const CACHE_TTL_SECONDS = 86_400; // 24h
/**
* 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 registerGeocodingTools(
server: McpServer,
ctx: { userId: string },
): void {
const { userId } = ctx;
// GEO-01 + GEO-03: geocode_location
server.registerTool(
"geocode_location",
{
description:
"Geocode a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
"Inputs: query (string, required) -- the place name or address; limit (integer 1-20, optional, default 5) -- max results. " +
"Output: a JSON array of results sorted by importance, each with { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west, south, east, north], importance }. " +
"Returns the literal text 'no results found' when nothing matches. " +
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...], ... }].",
inputSchema: {
query: z.string().min(1).describe("Location name or address to geocode"),
limit: z
.number()
.int()
.min(1)
.max(MAX_LIMIT)
.optional()
.describe("Max results to return (default 5, max 20)"),
},
},
async (args) => {
try {
const limit = Math.min(args.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
const cacheKey = `geocode:${args.query.toLowerCase().trim()}:${limit}`;
const cached = await cacheGet(cacheKey);
if (cached) return textResult(cached);
const rateLimitResult = await checkRateLimit(userId);
if (rateLimitResult) return textResult(JSON.stringify(rateLimitResult));
const raw = await fetchGeocode({ query: args.query, limit });
if (raw.length === 0) return textResult("no results found");
const results = raw.map(normalizeResult);
const json = JSON.stringify(results);
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
return textResult(json);
} catch (err) {
console.error("[geocodingTools] geocode_location failed:", err);
return textResult("geocode_location command failed");
}
},
);
// GEO-02: fly_to
server.registerTool(
"fly_to",
{
description:
"Fly the live globe camera to a coordinate, optionally fitting a bounding box in view. " +
"Inputs: lat (number -90..90, required), lng (number -180..180, required), altitude (positive number metres, optional, default 15000), " +
"bbox ([west, south, east, north] tuple, optional -- fit this box in view), sessionId (string, optional -- target a specific browser tab; omit for the most-recently-active tab). " +
"Output: text 'fly_to command enqueued (...)' on success, or 'no active globe session to control' when no tab is live. " +
"The camera moves over the SSE bridge with no page reload. " +
"Example: fly_to({ lat: 48.85, lng: 2.35 }) or fly_to({ lat: 0, lng: 0, bbox: [2.2, 48.8, 2.5, 48.9] }).",
inputSchema: {
lat: latSchema.describe("Latitude [-90, 90]"),
lng: lonSchema.describe("Longitude [-180, 180]"),
altitude: z
.number()
.positive()
.optional()
.describe("Altitude in metres above ellipsoid (default 15000)"),
bbox: z
.tuple([z.number(), z.number(), z.number(), z.number()])
.optional()
.describe("[west, south, east, north] bounding box to fit in view"),
sessionId: z
.string()
.optional()
.describe("Target globe session id. Omit to target most-recently-active tab."),
},
},
async (args) => {
try {
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
const cmd: GlobeCommand = {
type: "flyTo",
lat: args.lat,
lng: args.lng,
alt: args.altitude ?? DEFAULT_ALTITUDE_M,
...(args.bbox ? { bbox: args.bbox } : {}),
};
await enqueueGlobeCommand(userId, sessionId, cmd);
const label = args.bbox
? `bbox=[${args.bbox.join(",")}]`
: `lat=${args.lat}, lng=${args.lng}, alt=${args.altitude ?? DEFAULT_ALTITUDE_M}`;
return textResult(`fly_to command enqueued (${label})`);
} catch (err) {
console.error("[geocodingTools] fly_to failed:", err);
return textResult("fly_to command failed");
}
},
);
}
+381
View File
@@ -0,0 +1,381 @@
/**
* 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);
});
});
+200
View File
@@ -0,0 +1,200 @@
/**
* 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");
}
},
);
}
+266
View File
@@ -0,0 +1,266 @@
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");
});
});
+98
View File
@@ -0,0 +1,98 @@
/**
* 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 ?? {}),
},
],
};
},
);
}
+63
View File
@@ -0,0 +1,63 @@
/**
* 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 });
}
+286
View File
@@ -0,0 +1,286 @@
/**
* 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();
});
});
+179
View File
@@ -0,0 +1,179 @@
/**
* @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),
},
],
};
},
);
}
}
+95
View File
@@ -0,0 +1,95 @@
/**
* 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 });
}
+332
View File
@@ -0,0 +1,332 @@
/**
* 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 })
);
});
});
+238
View File
@@ -0,0 +1,238 @@
/**
* 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";
import { registerGeocodingTools } from "./geocodingTools";
import { registerFavoritesTools } from "./favoritesTools";
import { registerFilterTools } from "./filterTools";
// ---------------------------------------------------------------------------
// 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)
// Phase 22: registerGeocodingTools, registerFavoritesTools
// Phase 23: registerFilterTools (set_filter, clear_filter, get_plugin_filters)
registerGlobeResources(server, { userId: authResult.userId });
registerDataQueryTools(server);
registerGlobeCommandTools(server, { userId: authResult.userId });
registerGeocodingTools(server, { userId: authResult.userId });
registerFavoritesTools(server, { userId: authResult.userId });
registerFilterTools(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);
}
+122
View File
@@ -0,0 +1,122 @@
/**
* 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();
}
);
});
@@ -0,0 +1,86 @@
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" }),
);
});
});
+82
View File
@@ -0,0 +1,82 @@
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 });
}
}
@@ -0,0 +1,88 @@
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);
});
});
+58
View File
@@ -0,0 +1,58 @@
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 });
}
}
+3 -2
View File
@@ -38,8 +38,9 @@ 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} />;
// Treat as emoji or text fallback
return <span>{icon}</span>;
// 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} />;
}
const IconComponent = icon;
+1 -1
View File
@@ -249,7 +249,7 @@ export function ApiKeysTab() {
<div style={{ marginBottom: "var(--space-lg)" }}>
<div style={sectionHeaderStyle}>
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
Your API Keys
Service 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.
+2 -11
View File
@@ -36,6 +36,7 @@ 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";
@@ -88,17 +89,7 @@ export function AppShell() {
await injectHostGlobals();
setHostReady(true);
// 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
}
const disabledIds = getDisabledPluginIds();
// Setup demo defaults
const demoDefaultPlugins = new Set<string>();
+24 -37
View File
@@ -15,7 +15,6 @@ 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
@@ -39,41 +38,27 @@ export function BottomPanelManager() {
}
}, [activeBottomPanel]);
// Handle mouse drag for resizing the panel
useEffect(() => {
if (!isDragging) {
document.body.classList.remove("is-dragging-bottom-panel");
return;
}
// 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);
document.body.classList.add("is-dragging-bottom-panel");
};
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 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 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]);
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.releasePointerCapture(e.pointerId);
document.body.classList.remove("is-dragging-bottom-panel");
};
// Dynamically push sidebars up based on bottom panel height
useEffect(() => {
@@ -182,12 +167,14 @@ export function BottomPanelManager() {
>
{mountedPanel && (
<>
<div
className="bottom-panel-resize-handle"
<div
className="bottom-panel-resize-handle"
data-testid="bottom-panel-resize-handle"
ref={resizeRef}
onMouseDown={() => setIsDragging(true)}
onPointerDown={() => setIsDragging(true)}
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerUp}
onPointerCancel={handleResizePointerUp}
>
<div className="resize-grip" />
</div>
@@ -0,0 +1,310 @@
"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)
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
// documented in docs/plugin-filter-guide.md.
// ---------------------------------------------------------------------------
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
incidents, weather, and custom data plugins.
This MCP connection is live and authenticated. You can call these tools:
Data query:
- search_entities: search entities by name across active plugins; supports optional inline filters.
- get_entities_in_region: find entities inside a lat/lng bounding box.
- get_entity_details: get full details for one entity by pluginId + entityId.
- get_plugin_data: get the current snapshot of all entities for a plugin.
Location (geocoding + camera):
- geocode_location: resolve a place name or address to coordinates and a bounding box.
- fly_to: fly the live globe camera to a coordinate or bounding box.
Favorites:
- save_favorite: bookmark an entity so the user can return to it later.
- list_favorites: list the user's bookmarks, each with a live/stale status.
- remove_favorite: delete a bookmarked entity.
Live filtering:
- get_plugin_filters: list the filterable fields a plugin declares.
- set_filter: apply filters to a plugin's layer on the live globe.
- clear_filter: clear one plugin's filters, or all filters.
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
to find places, move the camera, search and filter live entities, and manage their bookmarks.`;
// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
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&apos;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&apos;s system prompt or first message to describe WWV.
</div>
<CopyField label="Capabilities prompt" value={AGENT_PROMPT} multiline />
<div style={{ ...mutedMicro, marginTop: "var(--space-xs)" }}>
Plugin authors: see docs/plugin-filter-guide.md to declare filterable fields for set_filter / get_plugin_filters.
</div>
{/* 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>
);
}
+8 -1
View File
@@ -21,6 +21,7 @@ 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 = [
@@ -433,7 +434,7 @@ export function Header() {
marginBottom: "16px",
}}
>
<h2 style={{ margin: 0 }}>API Keys</h2>
<h2 style={{ margin: 0 }}>Keys &amp; Access</h2>
<button
type="button"
@@ -445,6 +446,12 @@ export function Header() {
</div>
<ApiKeysTab />
{!isDemo && (
<>
<hr style={{ border: "none", borderTop: "1px solid var(--border-subtle)", margin: "var(--space-lg) 0" }} />
<PersonalApiKeysSection />
</>
)}
</div>
</div>
)}
@@ -0,0 +1,354 @@
"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 &amp; 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&apos;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&apos;ve saved it
</button>
</div>
)}
<ConnectAgentHelper token={revealToken} />
</div>
);
}
+13
View File
@@ -74,6 +74,19 @@
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;
+37 -22
View File
@@ -7,7 +7,7 @@
* @module src/components/panels
*/
import { ShieldAlert } from "lucide-react";
import { ShieldAlert, Wrench } from "lucide-react";
import { PluginIcon } from "@/components/common/PluginIcon";
import { Tooltip } from "@/components/ui/Tooltip";
import { pluginManager } from "@/core/plugins/PluginManager";
@@ -27,29 +27,46 @@ const CATEGORY_LABELS: Record<string, string> = {
custom: "Custom",
};
// ─── Trust Helpers ──────────────────────────────────────────
// ─── Source / Trust Helpers ─────────────────────────────────
type TrustTier = "built-in" | "verified" | "unverified";
function getTrust(pluginId: string): TrustTier {
function isLocalPlugin(pluginId: string): boolean {
const manifest = pluginManager.getManifest(pluginId);
return manifest?.trust ?? "unverified";
if (!manifest) return true;
const entry = manifest.entry ?? "";
return entry.startsWith("/plugins-local/") || entry.startsWith("http://localhost") || entry.startsWith("http://127.0.0.1");
}
function TrustIcon({ trust }: { trust: TrustTier }) {
if (trust !== "unverified") return null;
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>
);
}
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>
);
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;
}
// ─── LayerItem Component ────────────────────────────────────
@@ -88,8 +105,6 @@ export function LayerItem({
onToggle,
onSelect,
}: LayerItemProps) {
const trust = getTrust(plugin.id);
return (
<div
className={`layer-item ${isSelected ? "layer-item--selected" : ""}`}
@@ -102,7 +117,7 @@ export function LayerItem({
<div className="layer-item__info">
<div className="layer-item__header">
<span className="layer-item__name">{plugin.name}</span>
<TrustIcon trust={trust} />
<TrustIcon pluginId={plugin.id} pluginName={plugin.name} />
</div>
<div className="layer-item__desc">{plugin.description}</div>
<div className="layer-item__footer">
+3 -3
View File
@@ -69,6 +69,7 @@
.plugin-item__header {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 1px;
}
@@ -77,9 +78,7 @@
font-size: 13px;
font-weight: 500;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
}
.plugin-item__version {
@@ -184,6 +183,7 @@
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%;
+65 -34
View File
@@ -11,12 +11,16 @@
import { useState, useEffect, useCallback } from "react";
import {
Trash2, ExternalLink, RefreshCw, Download, PowerOff, Power,
ShieldCheck, ShieldAlert, Shield
ShieldCheck, ShieldAlert, HardDrive
} 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 ──────────────────────────────────────────────────
@@ -35,9 +39,9 @@ function TrustBadge({ trust }: { trust: string }) {
if (trust === "built-in") {
return (
<span className="trust-badge trust-badge--builtin">
<Shield size={9} />
<HardDrive size={9} />
{' '}
Built-in
Local
</span>
);
}
@@ -96,13 +100,9 @@ function getTrust(record: PluginRecord): string {
}
}
function getIcon(record: PluginRecord): string {
function getIcon(record: PluginRecord): string | ComponentType<{ size?: number; color?: string }> {
const managed = pluginManager.getPlugin(record.pluginId);
if (managed) {
return typeof managed.plugin.icon === "string"
? managed.plugin.icon
: "📦";
}
if (managed) return managed.plugin.icon ?? "📦";
try {
return JSON.parse(record.config).icon ?? "📦";
} catch {
@@ -120,6 +120,11 @@ 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 ─────────────────────────────────────────────
/**
@@ -145,7 +150,8 @@ 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 (enabled by default)
// Add built-in and local plugins that don't have a DB record yet
const disabledIds = getDisabledPluginIds();
const allManaged = pluginManager.getAllPlugins();
for (const managed of allManaged) {
if (!dbPluginMap.has(managed.plugin.id)) {
@@ -154,11 +160,16 @@ export function PluginsTab() {
version: "built-in",
config: "{}",
installedAt: new Date().toISOString(),
enabled: true
enabled: !disabledIds.has(managed.plugin.id)
});
}
}
// 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);
@@ -192,32 +203,48 @@ export function PluginsTab() {
const handleDisable = async (pluginId: string) => {
setRemoving(pluginId);
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);
}
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);
};
const handleEnable = async (pluginId: string) => {
setRemoving(pluginId);
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);
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);
}
}
// Layer stays off — user controls it via the Data Layers toggle.
trackEvent("plugin-enable", { plugin: pluginId });
await loadPlugins();
setRemoving(null);
};
const handleCheckUpdates = async () => {
@@ -352,10 +379,12 @@ export function PluginsTab() {
<span className="plugin-item__name">
{getName(record)}
</span>
{getVersion(record) && (
<span className="plugin-item__version">
v
{record.version}
{getVersion(record)}
</span>
)}
</div>
<div className="plugin-item__meta">
<TrustBadge trust={getTrust(record)} />
@@ -415,10 +444,12 @@ export function PluginsTab() {
<span className="plugin-item__name">
{getName(record)}
</span>
{getVersion(record) && (
<span className="plugin-item__version">
v
{record.version}
{getVersion(record)}
</span>
)}
</div>
<div className="plugin-item__meta">
<TrustBadge trust={getTrust(record)} />
@@ -0,0 +1,66 @@
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,6 +11,8 @@ 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
@@ -37,6 +39,52 @@ 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);
@@ -0,0 +1,24 @@
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>
);
}
+2 -26
View File
@@ -3,6 +3,7 @@ import type {
FilterDefinition,
FilterValue,
} from "@/core/plugins/PluginTypes";
import { matchFilterValue } from "./matchFilterValue";
/**
* Apply active filters to a list of entities.
@@ -27,35 +28,10 @@ export function applyFilters(
const propValue = entity.properties[def.propertyKey];
if (!matchesFilter(propValue, filterVal)) {
if (!matchFilterValue(propValue, filterVal)) {
return false;
}
}
return true;
});
}
function matchesFilter(propValue: unknown, filter: FilterValue): boolean {
switch (filter.type) {
case "text": {
if (!filter.value) return true; // empty text = no filter
const str = String(propValue ?? "").toLowerCase();
return str.includes(filter.value.toLowerCase());
}
case "select": {
if (filter.values.length === 0) return true; // no selection = no filter
const pVal = String(propValue ?? "").toLowerCase();
return filter.values.some((v) => v.toLowerCase() === pVal);
}
case "range": {
const num = Number(propValue ?? 0);
if (isNaN(num)) return false;
return num >= filter.min && num <= filter.max;
}
case "boolean": {
return Boolean(propValue) === filter.value;
}
default:
return true;
}
}
+31
View File
@@ -0,0 +1,31 @@
import type { FilterValue } from "@/core/plugins/PluginTypes";
/**
* Pure per-value filter matching shared by the client filterEngine and the
* server-side search_entities filter (Phase 23, D-08). Behavior must remain
* identical to the original inline filterEngine.matchesFilter.
*/
export function matchFilterValue(propValue: unknown, filter: FilterValue): boolean {
switch (filter.type) {
case "text": {
if (!filter.value) return true; // empty text = no filter
const str = String(propValue ?? "").toLowerCase();
return str.includes(filter.value.toLowerCase());
}
case "select": {
if (filter.values.length === 0) return true; // no selection = no filter
const pVal = String(propValue ?? "").toLowerCase();
return filter.values.some((v) => v.toLowerCase() === pVal);
}
case "range": {
const num = Number(propValue ?? 0);
if (isNaN(num)) return false;
return num >= filter.min && num <= filter.max;
}
case "boolean": {
return Boolean(propValue) === filter.value;
}
default:
return true;
}
}
+10
View File
@@ -34,6 +34,11 @@ 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;
@@ -120,6 +125,11 @@ 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);
+13 -1
View File
@@ -1,7 +1,7 @@
import { useEffect } from "react";
import type { Viewer as CesiumViewer } from "cesium";
import {
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4, Rectangle
} from "cesium";
import { dataBus } from "@/core/data/DataBus";
import { showSearchPin } from "./searchPinAnimation";
@@ -140,9 +140,21 @@ export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean)
}, 50);
});
const unsubFlyToBbox = dataBus.on("cameraFlyToBbox", ({ west, south, east, north }) => {
setTimeout(() => {
if (!viewer || viewer.isDestroyed()) return;
viewer.camera.flyTo({
destination: Rectangle.fromDegrees(west, south, east, north),
duration: 1.5,
easingFunction: EasingFunction.QUINTIC_IN_OUT,
});
}, 50);
});
return () => {
unsubFace();
unsubGoTo();
unsubFlyToBbox();
};
}, [viewer, isReady]);
}
@@ -0,0 +1,249 @@
/**
* 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
});
});
@@ -0,0 +1,143 @@
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 "flyTo":
if (cmd.bbox) {
const [west, south, east, north] = cmd.bbox;
dataBus.emit("cameraFlyToBbox", { west, south, east, north });
} else {
dataBus.emit("cameraGoTo", {
lat: cmd.lat,
lon: cmd.lng, // flyTo uses "lng"; cameraGoTo expects "lon" -- explicit mapping per D-03
alt: cmd.alt ?? 15_000,
});
}
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;
}
case "setFilter": {
const state = useStore.getState();
for (const [filterId, value] of Object.entries(cmd.filters)) {
state.setFilter(cmd.pluginId, filterId, value);
}
break;
}
case "clearFilter": {
const state = useStore.getState();
if (cmd.pluginId !== undefined) {
state.clearFilters(cmd.pluginId);
} else {
state.clearAllFilters();
}
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]);
}
@@ -0,0 +1,125 @@
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); });
});
});
+60
View File
@@ -0,0 +1,60 @@
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]);
}
@@ -0,0 +1,167 @@
/**
* @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";
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
/** 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[];
filterDefinitions?: Record<string, FilterDefinition[]>;
}
/**
* Collects mcpTools, mcpCapabilities, and declared filterDefinitions from all
* loaded plugins. Only includes plugins whose manifests declare at least one
* mcpTool (tools); filterDefinitions includes only plugins that returned a
* non-empty array from getFilterDefinitions() (D-05).
*/
function collectCatalog(): {
tools: CatalogTool[];
capabilities: string[];
filterDefinitions: Record<string, FilterDefinition[]>;
} {
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,
};
});
// Collect declared filterable fields from each loaded plugin instance.
// Only include plugins that returned a non-empty definitions array (D-05).
const filterDefinitions: Record<string, FilterDefinition[]> = {};
for (const managed of allPlugins) {
const defs = managed.plugin.getFilterDefinitions?.();
if (defs && defs.length > 0) {
filterDefinitions[managed.plugin.id] = defs;
}
}
return { tools, capabilities: Array.from(capabilitySet), filterDefinitions };
}
// ---------------------------------------------------------------------------
// Publish helper
// ---------------------------------------------------------------------------
async function publishCatalog(
sessionId: string,
active: { current: boolean },
): Promise<void> {
const { tools, capabilities, filterDefinitions } = collectCatalog();
// No-op only when nothing is publishable: no MCP tools AND no declared
// filters. A filter-only plugin still publishes so get_plugin_filters works.
if (tools.length === 0 && Object.keys(filterDefinitions).length === 0) return;
if (!active.current) return;
const payload: CatalogPayload = {
sessionId,
tools,
capabilities,
...(Object.keys(filterDefinitions).length > 0 && { filterDefinitions }),
};
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]);
}
+199
View File
@@ -0,0 +1,199 @@
/**
* @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]);
}
+57
View File
@@ -0,0 +1,57 @@
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);
});
});
+26
View File
@@ -0,0 +1,26 @@
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;
}
+266
View File
@@ -0,0 +1,266 @@
/**
* 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);
});
});
describe("flyTo validator", () => {
it("accepts valid point command with lat and lng only", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1 })).toBe(true);
});
it("accepts valid point command with lat, lng, and alt", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, alt: 15000 })).toBe(true);
});
it("accepts valid command with a 4-element bbox [west,south,east,north]", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] })).toBe(true);
});
it("rejects bbox with wrong length (3 elements)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1] })).toBe(false);
});
it("rejects lat out of range (>90)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 91, lng: 0 })).toBe(false);
});
it("rejects lng out of range (>180)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 181 })).toBe(false);
});
it("rejects negative alt (alt must be > 0 if provided)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, alt: -1 })).toBe(false);
});
it("rejects bbox with non-numeric element", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, bbox: ["west", 50, 1, 52] })).toBe(false);
});
});
describe("setFilter / clearFilter validator", () => {
it("accepts setFilter with a select filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } })
).toBe(true);
});
it("accepts setFilter with a range filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { alt: { type: "range", min: 0, max: 1000 } } })
).toBe(true);
});
it("accepts setFilter with a boolean filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { live: { type: "boolean", value: true } } })
).toBe(true);
});
it("accepts setFilter with a text filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { name: { type: "text", value: "ba" } } })
).toBe(true);
});
it("rejects setFilter with an empty pluginId", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: {} })
).toBe(false);
});
it("rejects setFilter when select values is not an array", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "select", values: "nope" } } })
).toBe(false);
});
it("rejects setFilter when range min is not a number", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "range", min: "0", max: 1 } } })
).toBe(false);
});
it("rejects setFilter with an unknown filter type", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "bogus" } } })
).toBe(false);
});
it("rejects setFilter when filters is not an object", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: null })
).toBe(false);
});
it("accepts clearFilter with no pluginId (clear all)", () => {
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
});
it("accepts clearFilter with a pluginId", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
});
it("rejects clearFilter when pluginId is not a string", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: 123 })).toBe(false);
});
});
+151
View File
@@ -0,0 +1,151 @@
import type { FilterValue } from "@/core/plugins/PluginTypes";
// 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 }
| { type: "flyTo"; lat: number; lng: number; alt?: number; bbox?: [number, number, number, number] }
| { type: "setFilter"; pluginId: string; filters: Record<string, FilterValue> }
| { type: "clearFilter"; pluginId?: string };
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);
}
function isValidFilterValue(v: unknown): v is FilterValue {
if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
const fv = v as Record<string, unknown>;
switch (fv["type"]) {
case "text":
return typeof fv["value"] === "string";
case "select":
return Array.isArray(fv["values"]) && fv["values"].every((x) => typeof x === "string");
case "range":
return isNumber(fv["min"]) && isNumber(fv["max"]);
case "boolean":
return typeof fv["value"] === "boolean";
default:
return false;
}
}
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"])
);
case "flyTo": {
if (!isValidLat(cmd["lat"])) return false;
if (!(isNumber(cmd["lng"]) && (cmd["lng"] as number) >= -180 && (cmd["lng"] as number) <= 180)) return false;
if (!(isOptionalNumber(cmd["alt"]) && (cmd["alt"] === undefined || isValidAlt(cmd["alt"])))) return false;
if (cmd["bbox"] !== undefined) {
const bbox = cmd["bbox"];
if (!Array.isArray(bbox) || bbox.length !== 4) return false;
if (!bbox.every((v: unknown) => isNumber(v))) return false;
const [west, south, east, north] = bbox as number[];
if (west < -180 || west > 180) return false;
if (south < -90 || south > 90) return false;
if (east < -180 || east > 180) return false;
if (north < -90 || north > 90) return false;
}
return true;
}
case "setFilter": {
if (typeof cmd["pluginId"] !== "string" || cmd["pluginId"] === "") return false;
const filters = cmd["filters"];
if (filters === null || typeof filters !== "object" || Array.isArray(filters)) return false;
return Object.values(filters as Record<string, unknown>).every(isValidFilterValue);
}
case "clearFilter":
return isOptionalString(cmd["pluginId"]);
default:
return false;
}
}
+2
View File
@@ -10,6 +10,7 @@ import {
getApprovedUnverifiedIds,
approveUnverifiedPlugin,
} from "@/lib/marketplace/trustedPlugins";
import { getDisabledPluginIds } from "@/core/plugins/pluginPreferences";
import { isDemo } from "@/core/edition";
/**
@@ -66,6 +67,7 @@ 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;
+1
View File
@@ -13,4 +13,5 @@ export type {
FieldMapping,
RenderingConfig,
PluginManifest,
McpToolDeclaration,
} from "@worldwideview/wwv-plugin-sdk";
+25
View File
@@ -0,0 +1,25 @@
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
}
}
+285 -52
View File
@@ -1,59 +1,292 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* 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
*/
import { describe, it, expect } from "vitest";
import { validateManifest } from "./validateManifest";
import type { PluginManifest } from "./PluginManifest";
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);
});
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
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");
});
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 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");
});
// ---------------------------------------------------------------------------
// Existing base tests (preserved, no `any`)
// ---------------------------------------------------------------------------
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");
});
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);
});
});
+50
View File
@@ -19,6 +19,9 @@ 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.
@@ -76,5 +79,52 @@ 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 };
}
+19
View File
@@ -0,0 +1,19 @@
import { vi } from "vitest";
/**
* Manual mock for `@/lib/prisma`.
*
* The real module re-exports a Prisma client whose underlying singleton
* (`@/lib/db`) throws on any property access when DATABASE_URL is unset (the
* test environment). That makes vitest's automock unusable here, so this manual
* mock supplies a deep-mocked `prisma.favorite` surface that tests can drive
* via `vi.mocked(prisma, true)`.
*/
export const prisma = {
favorite: {
upsert: vi.fn(),
findMany: vi.fn(),
delete: vi.fn(),
deleteMany: vi.fn(),
},
};
+178
View File
@@ -0,0 +1,178 @@
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"]);
});
});
+136
View File
@@ -0,0 +1,136 @@
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 };
}
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more