Code review (27-REVIEW.md) found the Phase 26 investigate prompt template gave
schema-invalid example calls that an agent would follow literally:
- geocode -> geocode_location (correct tool name)
- toggle_layer({pluginId,visible}) -> ({layerId,enabled})
- get_entities_in_region({lat,lon,radiusKm}) -> bounding box ({north,south,east,west})
- get_entity_details({entityId}) -> ({pluginId,entityId})
Plus two descriptions that over-promised handler behavior:
- get_plugin_data: capturedAt is only present when data streamed
- remove_favorite: throws/returns failure on missing record, not silent success
Resolves CR-01, CR-02, WR-01, WR-02 from the Phase 27 code review.
The Phase 26 orient-globe prompt read snapshot.camera.{lat,lon,alt}, but
GlobeStateSnapshot exposes viewport.{lat,lon,altitude}. The impl failed tsc and
its test fixture hid the bug behind an 'as never' cast using the same wrong shape.
Also add the missing registerPrompt stub to route.test.ts's McpServer mock so the
Phase 26 prompt registration in route.ts no longer throws in the route suite.
Surfaced by the Phase 27 post-merge build/test gate.
- geocode_location: add When-to-use clause (use before fly_to; do not guess coords) and explicit Nominatim limitations
- fly_to: add globe://sessions precondition, 'no active globe session to control' outcome, Prefer pan_globe/focus_entity disambiguation
- Both descriptions end with Example: and are within 350-600 char target
- Distinguish plugin not loaded/not streaming from no entities matched in all four tools
- Add tools/list precondition and soft emptyReason reference to each description
- Add Example: inline in each description
- All four descriptions within 350-600 chars, under 1024 hard cap
- New describe block asserts length <= 1024, globe://sessions, no-active-session outcome,
Prefer disambiguation, and Example: call for each of pan_globe/focus_entity/toggle_layer/set_timeline
- set_timeline-specific assertion checks at least one timeWindow enum literal present
- Updated makeFakeServer to capture schema defs; all 65 tests pass
- pan_globe, focus_entity, toggle_layer, set_timeline descriptions rewritten
- Each contains globe://sessions precondition and no-active-session outcome
- Each has Prefer disambiguation line and Example: call
- All descriptions 574-687 chars, well under 1024 char hard cap
Resolved add/add conflicts from squash-merge of feat/mcp-support (PR #215).
All v1.3 Location Intelligence additions preserved as union over v1.2 baseline:
- MCP_SERVER_VERSION kept at 1.3.0
- flyTo, setFilter, clearFilter GlobeCommand variants and validators retained
- search_entities filters param retained in tools.ts and service.ts
- filterDefinitions on SessionCatalog and catalog publisher retained
- zremrangebyscore/zcard on RedisClient retained
- registerGeocodingTools/registerFavoritesTools/registerFilterTools in mcp route retained
- v1.3 agent prompt in ConnectAgentHelper retained
- package.json version kept at 2.46.6 (our higher value)
* 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
* 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
* 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)
* 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)
* 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)
* 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
* 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)
* 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
* 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).
* 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
* 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).
* 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
* 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
* 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.
* 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
* 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)
* 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.
* 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.
* 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
* 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)
* 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
* 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
* 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
* 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)
* 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
* 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
* 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
* 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
* fix: update pnpm-lock.yaml to include ioredis (CI frozen-lockfile fix)
* 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.
* 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.
* 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
* 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.
* 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.
* 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)
* 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
* 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)
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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)
- 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)
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.
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.
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
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.
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.
- 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
- 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)
- 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
- 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
- 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)