Compare commits

...
Author SHA1 Message Date
Antigravity AI eccf952e6b fix(auth): add sessionVersion migration and harden login error handling
- Add missing ALTER TABLE migration for sessionVersion column; fresh
  self-hosted installs were failing with "column users.sessionVersion
  does not exist" because the column was in schema.prisma but had no
  migration file, so prisma migrate deploy never created it
- loginAction now catches all errors instead of re-throwing non-AuthError
  exceptions, preventing raw server errors reaching the client
- LoginForm wraps loginAction in try/catch so the loading state always
  resets and an error message is shown even on unexpected server failures
  (previously the button froze on "Signing in..." with no feedback)
2026-06-05 23:05:26 +12:00
Antigravity AI 673f4ec0b1 chore: add Tier 2+3 plugin smoke test script
Adds scripts/ci-plugin-smoke/smoke.mjs — a Node.js smoke test that loads
a plugin bundle and validates its WorldPlugin contract without a browser,
network, or Docker image.

Tier 2: verifies the bundle loads and the default export has all required
fields (id, name, description, category, version) and methods (initialize,
destroy, fetch, getPollingInterval, getLayerConfig, renderEntity).

Tier 3: calls the pure synchronous methods — getLayerConfig(), renderEntity(),
getPollingInterval() — and validates their return shapes. Also exercises
mapWebsocketPayload() when present, checking it returns a GeoEntity[].

Bundles expose externals via globalThis.__WWV_HOST__ (per wwvPluginGlobals()
Vite plugin), so no Node.js module hooks are needed — the mock host is set
up in a single assignment before import().
2026-06-05 19:42:23 +12:00
Antigravity AI f4e33f6588 fix(libs): pin SDK peer dep to workspace:* to fix stale nested resolution
wwv-lib-aviation and wwv-lib-incidents declared the SDK peer dep as
"^1.4.10" (registry version), causing pnpm to install 1.5.0 nested
inside each lib's node_modules. TypeScript resolved PluginContext from
the nested 1.5.0 (which lacked getEngineUrl), not the workspace version,
breaking CI type-checks for aviation and conflict-events plugins.

Also includes docs: add property tag helper examples to local-plugins/README.md.
2026-06-05 14:42:45 +12:00
Silvertakana cc3902cbbd fix(sdk): export prop helpers + add npm repository field (#244)
* fix(libs): add repository field so npm provenance validates on publish

Publishing wwv-lib-incidents/aviation with --provenance failed E422: the
sigstore bundle requires package.json repository.url to match the building repo,
and these two libs had none. Added the same repository block the SDK already
uses (which published fine). The SDK (1.7.1) is already live; this unblocks the
two libs.

* fix(sdk): export dtProp, urlProp, imageProp, videoProp from virtual module

The wwvPluginGlobals virtual module for @worldwideview/wwv-plugin-sdk only
destructured the original four exports (WorldPlugin, PluginManifest,
createSvgIconUrl, DEFAULT_ICON_SIZE). Plugins importing the newer prop
utility helpers (dtProp, urlProp, imageProp, videoProp) got a Rolldown
[MISSING_EXPORT] error at build time, failing CI for civil-unrest,
cyber-attacks, earthquakes, wildfire, and iranwarlive.

All four helpers are already present on globalThis.__WWV_HOST__.WWVPluginSDK
(the host does import * as WWVPluginSDK) so no host changes are needed.
2026-06-05 14:24:34 +12:00
Silvertakana 7d250b1f82 fix(libs): add repository field so npm provenance validates on publish (#243)
Publishing wwv-lib-incidents/aviation with --provenance failed E422: the
sigstore bundle requires package.json repository.url to match the building repo,
and these two libs had none. Added the same repository block the SDK already
uses (which published fine). The SDK (1.7.1) is already live; this unblocks the
two libs.
2026-06-05 01:56:03 +12:00
Silvertakana 4f4d5eb460 fix(ci): prefix npm publish paths with ./ so npm treats them as folders (#242)
npm parsed the bare path 'packages/wwv-plugin-sdk' as a GitHub <user>/<repo>
shorthand and tried 'git ls-remote github.com/packages/wwv-plugin-sdk' instead
of publishing the local folder (exit 128). Verified via npm publish --dry-run:
bare path reproduces the git error; ./packages/... packs and publishes.
2026-06-05 01:50:28 +12:00
Silvertakana 24e75a8f6c ci: auto-publish SDK/libs on version bump (Phase 0) (#241)
* ci: auto-publish SDK/libs on version bump; retire stale plugin publisher

Adds publish-packages.yml which triggers on merge to main and uses OIDC
trusted publishing (no npm token) to publish all three monorepo packages.
Each step checks npm for the exact local version first and skips if already
published, making the workflow idempotent on re-runs.

wwv-lib-incidents and wwv-lib-aviation are source-only packages (no build
script) so their publish steps skip the build phase. wwv-plugin-sdk has a
tsc build and is compiled before publishing.

Removes publish-plugin.yml: it targeted packages/<plugin> paths that no
longer exist (community plugins moved to local-plugins/), and it used npm
workspace flags that are incompatible with this pnpm monorepo.

* ci: harden publish-packages workflow per review

- scope id-token:write to the job (least privilege, per the .github rule)
- add concurrency guard so fast-follow merges can't race to publish (npm 403)
- --silent on npm view to keep version-equality check immune to stdout notices
  (kept equality semantics, not exit-code, so an unpublished new version of an
  existing package still publishes correctly)
- pnpm/action-setup@v6 (repo's dominant pin) reading packageManager
- comment: npm publish is intentional for OIDC; switch to pnpm publish only if a
  workspace:* dep is ever added. Kept actions @v6 (verified valid + in use repo-wide).

* ci: use single org NPM_TOKEN for publish auth (keep provenance)

Switch from per-package OIDC trusted publishing to a single org-level NPM_TOKEN
secret scoped to @worldwideview/*, so no per-package setup is needed across the
~36 packages (libs + plugins). Keep id-token:write + --provenance for signed
build attestation (works with token auth, needs no per-package config).
2026-06-05 01:46:48 +12:00
Silvertakana 9a5adb832e docs(rules): seeder authoring contract + close-context-gaps meta-directive (#240)
* docs(rules): add seeder authoring contract to data-engine-architecture rule

Adds section 8 documenting how to write a seeder: the auto-discovery model,
the three module shapes (interval+fetch, cron+fn, init), the { redis }-only
ctx, and publishing via @worldwideview/seeder-sdk. Includes good/bad examples
contrasting the ctx.setLiveSnapshot trap (which caused a silent CI failure)
against the two correct shapes. This rule auto-loads on local-seeders/** edits.

* docs(rules): add close-context-gaps AI meta-directive to AGENTS.md

When missing/wrong/undocumented context causes an error, a long struggle, or
slow understanding, agents must fix the doc/context (or add a guardrail) at its
source, or ask the user to; in autonomous mode, log the gap to revisit. Codifies
the lesson from the seeder ctx.setLiveSnapshot incident for all contributors.
2026-06-05 00:25:44 +12:00
Silvertakana f447bd7e72 fix(ci): stub seeder interval+fetch + drop redundant compose mount (#239)
Companion to wwv-data-engine fix/ci-stub-interval-fetch. The source-of-truth
stub (docker/ci/stub-seeder) used cron+fn and called ctx.setLiveSnapshot,
which the seeder ctx ({ redis }) does not expose — the snapshot never landed.
Switch to interval+fetch (return the array; scheduler auto-wraps + stores it).

Also remove the plugin-CI compose's ./stub-seeder volume mount and the stale
'Known foundation gap (deferred)' comment: the stub is now baked into the :ci
image at /app/seeders/stub, so the compose needs no host path and a consumer
repo can run it with only this YAML.
2026-06-04 23:58:20 +12:00
Silvertakana a833cf4790 fix(ci-probe): subscribe to pluginId on /stream + safe stub + plugin-CI auth bypass (#238) 2026-06-04 23:40:08 +12:00
SilvertakanaandClaude Sonnet 4.6 352fbce768 feat: CI smoke-test foundation (probe + mock-upstream + isolated docker CI) (#236)
* feat: CI smoke-test foundation (probe + docker compose + rule updates)

Phase 1 of multi-repo CI initiative for catching plugin/seeder integration
failures (ADR-0002 id drift, missing mapWebsocketPayload, namespace
collisions, BOM in package.json) that current CI misses.

- packages/wwv-ci-probe: shared CLI with `seeder`, `ws`, `id-contract`
  subcommands. README documents why no `plugin` subcommand (Playwright belongs
  in wwv-plugins, not coupled to this probe). `files` + `prepublishOnly`
  configured for clean npm publish.
- docker/ci/: reusable docker-compose stacks for plugin-CI and seeder-CI,
  plus mock-upstream HTTP fixture server and CI-only stub-seeder. Compose
  comments document scope boundary (consumer workflow owns user/plugin-row
  injection via Playwright globalSetup pattern) and the deferred stub-seeder
  bake-in for wwv-data-engine.
- .github/workflows/docker-publish.yml: adds `:ci` tag alias for downstream
  consumers (one-line edit).
- .agents/rules/*: rename worldwideview-plugins → wwv-plugins (4 files) to
  reflect repo rename + clarify it lives at local-plugins/ as its own git
  working tree.

Bump 2.15.16 → 2.16.0 (Minor — new ci-probe package + new docker/ci
infrastructure are net-new features for the CI ecosystem).

Foundation has NOT been booted end-to-end yet — ghcr.io/silvertakana/
worldwideview:ci doesn't exist until this lands on main and the workflow
publishes. Next session: validate via real compose-up, then mirror the :ci
tag in wwv-data-engine repo and wire consumer workflows in wwv-plugins.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(ci-probe): extract shared payload-shape validator with contract tests

* fix(ci): add /__health route to mock-upstream and gate engine on service_healthy

* chore: bump version to 2.48.18 for CI foundation landing

* chore: bump to 2.48.19 and reconcile lockfile after merging main (validateManifest fix)

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
2026-06-04 23:00:02 +12:00
Silvertakana ef669ec812 fix(security): host-match plugin entry URL allowlist (close CodeQL substring-sanitization bypass) (#237) 2026-06-04 22:34:08 +12:00
Silvertakana a64f73cf13 docs: fix stale path references in .agents/rules/ files (#234)
Update rule files to reflect current file locations and removed skills.
Closes #185.

- cloud-auth-architecture.md: frontmatter paths pointed to src/core/auth.ts,
  storage.ts, tenant.ts which were never created; update to actual
  src/lib/auth* paths and mark storage/tenant adapters as planned.
- deployment-and-testing.md: four stale skill links (osm-static-plugin-creation,
  npm-plugin-publishing, git-version-control, security-check) removed from
  .agents/skills/; replace each with the current equivalent reference.
- plugin-architecture.md: src/data/verifiedPlugins.ts replaced by database
  admin API; remove two stale skill links (osm-static-plugin-creation,
  data-engine-seeder-creation) and note current alternatives.
2026-06-04 22:14:13 +12:00
dependabot[bot] 038bdb7c62 build(deps): bump commander from 14.0.3 to 15.0.0 (#231)
Bumps [commander](https://github.com/tj/commander.js) from 14.0.3 to 15.0.0.
- [Release notes](https://github.com/tj/commander.js/releases)
- [Changelog](https://github.com/tj/commander.js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tj/commander.js/compare/v14.0.3...v15.0.0)

---
updated-dependencies:
- dependency-name: commander
  dependency-version: 15.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-04 22:13:56 +12:00
dependabot[bot] 915d1a006d build(deps-dev): bump concurrently from 9.2.1 to 10.0.3 (#230)
Bumps [concurrently](https://github.com/open-cli-tools/concurrently) from 9.2.1 to 10.0.3.
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.1...v10.0.3)

---
updated-dependencies:
- dependency-name: concurrently
  dependency-version: 10.0.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-04 22:13:29 +12:00
Antigravity AI f75b416aa8 docs(triage): add issue triage guide and /triage-issue command
- TRIAGE.md: plugin-request vs enhancement intake, #4 funnel, build/do-not-build rule
- /triage-issue command at .agents/workflows/triage-issue.md, registered in AGENTS.md
2026-06-04 20:06:26 +12:00
Antigravity AI d35e62857f fix(gc-scan): stop false-positive ts-ignore matches and fix outdated-dep parser
- ts-ignore/ts-nocheck detector now only flags real suppression directives
  (token immediately after the // or /* comment opener), not prose mentions
- outdated-dep detector now parses pnpm's Unicode box-drawing table, skipping
  header/separator rows; surfaces real outdated deps instead of one garbage row
2026-06-04 19:27:00 +12:00
Antigravity AI cf029fc88f Merge branch 'main' of https://github.com/silvertakana/worldwideview 2026-06-04 19:15:39 +12:00
Silvertakana 57a2dc74d6 fix(ui): stabilize bottom-panel resize drag on webkit (#233)
Guard the resize pointermove handler with an isDraggingRef flag instead of
hasPointerCapture(), which behaves inconsistently across webkit versions in
CI for repeated drag sequences. setPointerCapture still delivers move/up
events when the pointer leaves the handle bounds.

Salvaged from the retired feat/phase-2-auth-gate branch (orig d91cc429); the
setPointerCapture work it built on is already on main.
2026-06-04 18:47:04 +12:00
Antigravity AI b06c330d02 docs(17-01): complete instance data layer plan summary
- Task 1: SavedInstance lastUsedAt + GET route marketplace user fix
- Task 2 (TDD): validateInstanceUrl 8 Vitest cases (RED then GREEN)
- Task 3 (TDD): POST link + DELETE/PATCH [id] routes (RED then GREEN)
- Rule 1 auto-fix: updated me/instances route.test.ts for new auth flow
2026-06-04 18:41:40 +12:00
Silvertakana 8ca4bdd9fa fix(auth): harden globe login gate with revocable sessions and deny-by-default API (#232)
- User.sessionVersion + jwt-callback revalidation rejects deleted-user,
  cross-database, and stale-version tokens (fixes cross-worktree stay-logged-in)
- POST /api/auth/revoke ("sign out everywhere") bumps sessionVersion
- proxy: deny-by-default /api with public allowlist + CORS preflight passthrough;
  anchored static-asset allowlist closes the path.includes(".") bypass
- harden session cookie options (httpOnly/sameSite/secure) and cut maxAge to 7 days
- unify https/secure-context detection in isHttpsDeployment() so the cookie
  writer (auth) and edge reader (proxy) never disagree on the __Secure- prefix
- augment next-auth User/Session/JWT types

Verified: 1009/1009 tests, build exit 0, live HTTP reproduction of all gates.
2026-06-04 18:17:46 +12:00
dependabot[bot] 54541ba62c build(deps): bump the dependencies group with 15 updates (#229)
Bumps the dependencies group with 15 updates:

| Package | From | To |
| --- | --- | --- |
| [@sentry/nextjs](https://github.com/getsentry/sentry-javascript) | `10.54.0` | `10.56.0` |
| [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js) | `2.106.2` | `2.107.0` |
| [cesium](https://github.com/CesiumGS/cesium) | `1.141.0` | `1.142.0` |
| [next](https://github.com/vercel/next.js) | `16.2.6` | `16.2.7` |
| [react](https://github.com/facebook/react/tree/HEAD/packages/react) | `19.2.6` | `19.2.7` |
| [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) | `19.2.15` | `19.2.16` |
| [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) | `19.2.6` | `19.2.7` |
| [resium](https://github.com/reearth/resium) | `1.21.1` | `1.22.0` |
| [zustand](https://github.com/pmndrs/zustand) | `5.0.13` | `5.0.14` |
| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) | `8.60.0` | `8.60.1` |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `8.60.0` | `8.60.1` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.7` | `4.1.8` |
| [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) | `16.2.6` | `16.2.7` |
| [tsx](https://github.com/privatenumber/tsx) | `4.22.3` | `4.22.4` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.14` | `8.0.16` |


Updates `@sentry/nextjs` from 10.54.0 to 10.56.0
- [Release notes](https://github.com/getsentry/sentry-javascript/releases)
- [Changelog](https://github.com/getsentry/sentry-javascript/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-javascript/compare/10.54.0...10.56.0)

Updates `@supabase/supabase-js` from 2.106.2 to 2.107.0
- [Release notes](https://github.com/supabase/supabase-js/releases)
- [Changelog](https://github.com/supabase/supabase-js/blob/master/packages/core/supabase-js/CHANGELOG.md)
- [Commits](https://github.com/supabase/supabase-js/commits/v2.107.0/packages/core/supabase-js)

Updates `cesium` from 1.141.0 to 1.142.0
- [Release notes](https://github.com/CesiumGS/cesium/releases)
- [Changelog](https://github.com/CesiumGS/cesium/blob/main/CHANGES.md)
- [Commits](https://github.com/CesiumGS/cesium/compare/1.141...1.142)

Updates `next` from 16.2.6 to 16.2.7
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.2.6...v16.2.7)

Updates `react` from 19.2.6 to 19.2.7
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.7/packages/react)

Updates `@types/react` from 19.2.15 to 19.2.16
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `react-dom` from 19.2.6 to 19.2.7
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.7/packages/react-dom)

Updates `resium` from 1.21.1 to 1.22.0
- [Release notes](https://github.com/reearth/resium/releases)
- [Changelog](https://github.com/reearth/resium/blob/main/CHANGELOG.md)
- [Commits](https://github.com/reearth/resium/compare/v1.21.1...v1.22.0)

Updates `zustand` from 5.0.13 to 5.0.14
- [Release notes](https://github.com/pmndrs/zustand/releases)
- [Commits](https://github.com/pmndrs/zustand/compare/v5.0.13...v5.0.14)

Updates `@types/react` from 19.2.15 to 19.2.16
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `@typescript-eslint/eslint-plugin` from 8.60.0 to 8.60.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.60.1/packages/eslint-plugin)

Updates `@typescript-eslint/parser` from 8.60.0 to 8.60.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.60.1/packages/parser)

Updates `@vitest/coverage-v8` from 4.1.7 to 4.1.8
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.8/packages/coverage-v8)

Updates `eslint-config-next` from 16.2.6 to 16.2.7
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/commits/v16.2.7/packages/eslint-config-next)

Updates `tsx` from 4.22.3 to 4.22.4
- [Release notes](https://github.com/privatenumber/tsx/releases)
- [Changelog](https://github.com/privatenumber/tsx/blob/master/release.config.cjs)
- [Commits](https://github.com/privatenumber/tsx/compare/v4.22.3...v4.22.4)

Updates `vite` from 8.0.14 to 8.0.16
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.16/packages/vite)

---
updated-dependencies:
- dependency-name: "@sentry/nextjs"
  dependency-version: 10.56.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.107.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: cesium
  dependency-version: 1.142.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: next
  dependency-version: 16.2.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: react
  dependency-version: 19.2.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@types/react"
  dependency-version: 19.2.16
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: react-dom
  dependency-version: 19.2.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: resium
  dependency-version: 1.22.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: zustand
  dependency-version: 5.0.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@types/react"
  dependency-version: 19.2.16
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.60.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.60.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: eslint-config-next
  dependency-version: 16.2.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: tsx
  dependency-version: 4.22.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vite
  dependency-version: 8.0.16
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:31:35 +12:00
dependabot[bot] 4e2c30a942 build(deps): bump actions/upload-artifact from 4 to 7 (#227)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:24:31 +12:00
dependabot[bot] 524394c251 build(deps): bump docker/metadata-action from 5 to 6 (#226)
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:24:27 +12:00
dependabot[bot] 15b1f1caf0 build(deps): bump docker/login-action from 3 to 4 (#228)
Bumps [docker/login-action](https://github.com/docker/login-action) from 3 to 4.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:24:23 +12:00
dependabot[bot] 6d5a85dfd4 build(deps): bump docker/setup-buildx-action from 3 to 4 (#225)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3 to 4.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:23:59 +12:00
dependabot[bot] 3ff9309caf build(deps): bump pnpm/action-setup from 3 to 6 (#224)
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 3 to 6.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/v3.0.0...v6)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-03 22:23:20 +12:00
Silvertakana b638fc91b2 Merge pull request #221 from sebastiondev/fix/cwe79-route-reflected-2f25
fix(proxy): escape URL in base href to prevent reflected XSS
2026-06-03 22:20:42 +12:00
Silvertakana abb8ecb28f Merge pull request #223 from silvertakana/feat/mcp-public-hardening
feat(mcp): v1.5 public-launch hardening + local self-host MCP ship-readiness
2026-06-03 22:05:55 +12:00
Antigravity AI d71aac8268 fix(deps): add vitest override to keep audit clean after lockfile regen
A 'pnpm install --lockfile-only' re-resolved local-plugins/wwv-plugin-nz-traffic-cameras
back to the vulnerable [email protected] (GHSA-5xrq-8626-4rwp), undoing #219's pin and
failing the Dependency Audit. Pin it durably via a pnpm override so any future
regen stays clean (closes the recurrence behind #97).

Verified: [email protected] gone from lockfile, frozen-lockfile exit 0,
pnpm audit --audit-level high exit 0 (7 moderate, 0 high/critical).
2026-06-03 21:58:55 +12:00
Antigravity AI 5de306c346 merge: bring main (v1.4 via #217, #219, #222) into feat/mcp-public-hardening
# Conflicts:
#	.planning/ROADMAP.md
#	.planning/STATE.md
#	package.json
2026-06-03 21:47:17 +12:00
Silvertakana d93c497f0a Merge pull request #217 from silvertakana/gsd/v1.3-location-intelligence
feat(mcp): v1.4 Agentic Intelligence - tool description standards, response contracts, discovery tools
2026-06-03 21:44:29 +12:00
Antigravity AI bfe64faade fix(deps): restore wwv-lib-aviation/incidents workspace deps + sync lockfile
The main merge resolved package.json with --ours, dropping the two
workspace deps that main's #220 (per-plugin bundling) added. Restore them
and regenerate the lockfile so 'pnpm install --frozen-lockfile' (CI) passes.

Verified: frozen-lockfile install exits 0.
2026-06-03 21:36:00 +12:00
Antigravity AI aa3984eb21 fix(docs): make MCP quickstart local-first (self-host is the shipping target)
The quickstart was cloud-only: it told self-hosters MCP is a 'cloud-edition
feature', pointed them at worldmonitor.app, and used the cloud endpoint -
actively wrong for the local edition that actually ships MCP today.

- lead with the local self-host flow: pnpm install/setup/dev(:all) -> sign in
  at localhost:3000 -> generate key -> paste localhost:3000/api/mcp -> open tab
- document pnpm dev vs pnpm dev:all (Redis + engine needed for command tools,
  geocoding, and live data); clarify which tools need which
- add update_favorite + fly_to to the tier tables; localhost-ize troubleshooting
- preserve cloud guidance under 'Cloud edition (coming soon)' for the future
  hosted launch (not deleted)
2026-06-03 21:10:49 +12:00
Antigravity AI a0bb4b7e74 fix(db): add missing migrations for user_api_keys and marketplace_credentials
The migration history only contained 20260509061229_init (6 tables), but
schema.prisma declares UserApiKey (user_api_keys) and MarketplaceCredential
(marketplace_credentials). Those tables existed only via the dev-only
'prisma db push' hook, so a fresh production 'prisma migrate deploy' built a
DB missing user_api_keys -> all MCP API-key auth threw 'relation does not
exist' (DOA in production).

- add 20260510000000_add_marketplace_credentials_and_api_keys (slots between
  init and add_favorite_notes); columns/constraints/indexes/FK mirror schema
- track the previously-untracked 20260531214034_add_favorite_notes migration

Verified: 'migrate deploy' on a fresh DB yields all 8 tables, zero drift
(prisma migrate diff: No difference detected). Dev DB baselined via
'migrate resolve --applied'; prisma validate + generate + tsc clean.
2026-06-03 21:02:57 +12:00
Antigravity AI 98ae79fe9b merge: bring main bug fixes into feat/mcp-public-hardening (#218 OSM UTF-8, #220 plugin per-plugin bundling)
# Conflicts:
#	.planning/ROADMAP.md
#	.planning/STATE.md
#	package.json
2026-06-03 16:24:24 +12:00
Antigravity AI b850e84334 chore(planning): v1.5 milestone state - all 6 phases complete 2026-06-03 16:23:42 +12:00
Antigravity AI a5fade9783 feat(36): Onboarding and Framing - MCP public-launch quickstart, prerequisites, honest command-tool framing
Phase 36 of v1.5 MCP Public-Launch Hardening (ONBRD-01..03).

- docs/mcp-quickstart.md: public sign-up -> generate key -> paste JSON ->
  open globe tab walkthrough; two capability tiers (read vs command);
  troubleshooting incl. engine_unreachable / no_active_plugins (ONBRD-01).
- ConnectAgentHelper: prerequisites callout (signed-in, cloud edition,
  open-tab requirement for command tools); extracted AGENT_PROMPT and
  CopyField into separate modules (file 352 -> 201 lines) (ONBRD-02).
- Every command tool description now begins with a shared
  SESSION_REQUIRED_PREAMBLE stating the live-open-tab requirement
  unmissably (pan_globe, focus_entity, toggle_layer, set_timeline,
  set_filter, clear_filter, fly_to) (ONBRD-03).
- New src/lib/mcp/toolDescriptionFragments.ts dedups the 7 identical
  preambles into one constant.

Gate: tsc clean, 1004 tests pass, build green.
2026-06-03 16:00:28 +12:00
Antigravity AI 0f860185cd fix(mcp): wire production deployment and throttle the shared geocoder (Phase 35)
Phase 35 of v1.5 MCP Public-Launch Hardening (DEPLOY-01..04):
- DEPLOY-01: production and cloud compose now provision a co-located Redis
  (password-protected via REDIS_PASSWORD, internal-only) and wire REDIS_URL,
  so sessions, command queue, geocode cache, and rate limiters work in prod.
- DEPLOY-02: set WWV_DATA_ENGINE_URL to the engine REST base (not the
  NEXT_PUBLIC_.../stream WS URL) so MCP data tools reach /manifest.
- DEPLOY-03: a single global 1 req/s Nominatim throttle (peek/commit sliding
  window with a queued-waiter cap and an in-process fallback) protects the
  shared geocoder; the 24h cache is checked before the throttle.
- DEPLOY-04: deploy/INFRA-CHECKLIST.md documents the operator actions
  (managed Redis rediss://, WWV_DATA_ENGINE_URL, distinct API_KEY_HMAC_SECRET,
  AUTH_SECRET, WWV_TRUSTED_IP_HEADER for multi-proxy, health semantics).

Security hardening from review: require AUTH_SECRET (no weak committed
fallback), password the co-located Redis, bind cloud Postgres to loopback,
de-duplicate the geocode result normaliser. Patch.
2026-06-03 15:36:39 +12:00
Antigravity AI b95ff5d580 fix(mcp): make /api/health probe real dependencies (Phase 34)
Phase 34 of v1.5 MCP Public-Launch Hardening (OBS-01):
- /api/health now probes Redis (ping), the database (SELECT 1), the data
  engine (manifest reachable), and HMAC config in parallel with 2s timeouts,
  returning {status, checks, edition, timestamp}.
- HTTP 503 when the DB is down or the HMAC secret is misconfigured
  (cloud/demo); HTTP 200 'degraded' when Redis or the engine is down so a
  serving-but-degraded container is not killed.
- Extract isSigningKeyValid() (src/lib/signingKeyConfig.ts) as the single
  source of truth for the SEC-01 rule, reused by getSigningKey and the health
  config probe (closes the Phase 32 deferred 'surface misconfig at deploy').
- Add ping() to the RedisClient interface; reuse getEngineUrl() so the probe
  and data layer resolve the same engine URL.

Patch: turns the always-healthy stub into real dependency observability.
2026-06-03 15:14:14 +12:00
Antigravity AI 813d2b28c2 fix(mcp): make tool responses honest to agents (Phase 33)
Phase 33 of v1.5 MCP Public-Launch Hardening (TOOL-01..05):
- TOOL-01: data-query tools never report no_session_active; they return
  the true reason (no_data_matches / engine_unreachable / no_active_plugins).
  Verified live: an empty region query with no browser session now returns
  no_data_matches.
- TOOL-02: toggle_layer / set_filter validate the id against the live plugin
  set and warn instead of returning success for an unrecognized id;
  focus_entity resolves entityId+pluginId to coordinates server-side and
  returns an honest error when it cannot.
- TOOL-03: get_entities_in_region returns count + truncated + totalMatched and
  tightens radiusKmToBbox (cos(lat), clamped to a full-globe span).
- TOOL-04: investigate_area and get_plugin_data cap output (200) with a
  truncated flag so a single response cannot blow client context.
- TOOL-05: MCP_SERVER_INSTRUCTIONS match the real response shapes;
  list_available_plugins distinguishes engine_unreachable from
  no_active_plugins and surfaces local sources distinctly.

Patch: corrects misleading tool behavior, no API removal.
2026-06-03 15:00:00 +12:00
Antigravity AI 3fd234736e feat(mcp): abuse-resistance and input hardening for public launch (Phase 32)
Phase 32 of v1.5 MCP Public-Launch Hardening (SEC-01..04):
- SEC-01: require a dedicated API_KEY_HMAC_SECRET in cloud/demo editions;
  getSigningKey fails closed if it is unset or equal to AUTH_SECRET.
  Local dev keeps the AUTH_SECRET fallback.
- SEC-02: Redis-backed per-key sliding-window rate limit (120/60s) applied
  after auth, returns JSON-RPC -32000 / HTTP 429, fails open on Redis outage
  behind the existing per-IP pre-auth gate.
- SEC-03: derive client IP from the trusted-proxy (rightmost X-Forwarded-For)
  hop with an optional WWV_TRUSTED_IP_HEADER override, defeating spoofing.
- SEC-04: length + charset bounds on entityId/pluginId/layerId/name/notes
  (shared identifierSchemas) and in isValidGlobeCommand; favorites capped at
  500 per user.

Consolidates id schemas, extracts MCP response helpers, accurate Retry-After,
unique sliding-window members. Minor semver bump: adds new guardrails.
2026-06-03 14:26:47 +12:00
Antigravity AI 121f7b22fe fix(mcp): harden transport error contract for public launch (Phase 31)
Phase 31 of v1.5 MCP Public-Launch Hardening (TRANS-01..04):
- Wrap the MCP route handler in a top-level try/catch returning a
  well-formed JSON-RPC -32603 (id:null, 500) instead of bare HTTP 500s
  when auth/Redis/transport throws.
- authenticateApiKey now returns null (clean 401) on a DB outage instead
  of rejecting; logs only the error class name (no connection strings).
- Add explicit maxDuration=30 on the MCP route, above the 10s relay blpop.
- Stop advertising tools.listChanged (stateless server cannot push);
  document the re-call tools/list contract in server instructions.

Sanitize the catch-all log so a Redis/Prisma error message cannot leak
credentials to server logs. Patch: behavior-hardening, no API change.
2026-06-03 13:55:11 +12:00
Sebastion f297d0e96a fix: escape user-controlled URL in base href to prevent reflected XSS (CWE-79) 2026-06-02 03:31:39 +01:00
112 changed files with 7499 additions and 1812 deletions

No files matched your search

+7 -7
View File
@@ -2,10 +2,8 @@
description: Cloud edition implementation details, PostgreSQL Row-Level Security (RLS) isolation, cross-subdomain auth, and cryptographic license keys.
paths:
- "src/lib/auth*"
- "src/lib/auth/**/*"
- "src/app/api/auth/**/*"
- "src/core/auth.ts"
- "src/core/storage.ts"
- "src/core/tenant.ts"
---
> **SUPERSEDED by ADR-003** (`docs/architecture/decisions/adr-0003-shared-identity-and-ecosystem-auth-host.md`).
@@ -177,13 +175,15 @@ DATABASE_URL=postgresql://...
## Edition Adapters
Three thin files are all that differs between editions — everything else is edition-unaware:
Three thin adapter modules provide all edition-specific behaviour -- everything else is edition-unaware:
| Adapter | Local | Cloud | Demo |
|---|---|---|---|
| `src/core/auth.ts` | Auth.js `Credentials` (bcrypt + PostgreSQL) | Auth.js `@auth/supabase-adapter` | Disabled |
| `src/core/storage.ts` | `fs.writeFile()` to `data/` | Supabase Storage SDK | Read-only |
| `src/core/tenant.ts` | No-op (single tenant) | Sets `app.tenant_id` for RLS | No-op |
| `src/lib/auth.ts` | Auth.js `Credentials` (bcrypt + PostgreSQL) | Auth.js `@auth/supabase-adapter` | Disabled |
| Storage adapter (planned) | `fs.writeFile()` to `data/` | Supabase Storage SDK | Read-only |
| Tenant adapter (planned) | No-op (single tenant) | Sets `app.tenant_id` for RLS | No-op |
> The storage and tenant adapters listed above are planned for the Cloud edition build-out and are not yet implemented as separate files. Auth is fully implemented in `src/lib/auth.ts` and `src/lib/auth.config.ts`.
---
+57
View File
@@ -89,3 +89,60 @@ This means:
> [!CAUTION]
> The most common silent bug: seeder sends `{ items: [...] }` (an object), frontend plugin omits `mapWebsocketPayload`. Data arrives but WsClient drops it with a console warning. The globe stays empty. Always implement `mapWebsocketPayload` for any plugin whose seeder sends an object payload.
## 8. Seeder Authoring Contract — the module shape
§7 covers what a seeder **sends**. This covers how you **write** one. The engine
auto-discovers a seeder by scanning `SEEDERS_DIR` for any folder with
`dist/index.mjs` and importing its **default export**. The seeder's `id` is the
**folder name**, not the `name` field. You never call a register function — the
authoritative reference is `wwv-data-engine/README.md` → "Authoring a Seeder".
The default export is `{ name }` plus **one** of these shapes:
| Shape | You provide | How data is published |
|---|---|---|
| `interval` + `fetch(ctx)` | `fetch` **returns** the array | scheduler wraps + stores + broadcasts it for you |
| `cron` + `fn(ctx)` | `fn` publishes itself | `import { setLiveSnapshot } from '@worldwideview/seeder-sdk'` and call it |
| `init(ctx)` | a persistent listener | publish via the SDK as push data arrives |
**The trap (this caused a real, silent CI failure):** `ctx` is **only `{ redis }`**.
There is no `ctx.setLiveSnapshot`. Reaching for it throws at runtime and the
snapshot never lands. Publish helpers come from `@worldwideview/seeder-sdk`, not
from `ctx`. The engine now types `ctx` as `SeederContext { redis }`, so this is a
compile error for any typed seeder — but `.mjs` seeders without type-checking get
no such safety net, so know the contract.
<bad-example>
```ts
// cron + fn reaching for a method that does not exist on ctx
export default {
name: "earthquakes",
cron: "0 * * * *",
fn: async (ctx) => {
await ctx.setLiveSnapshot("earthquakes", items, 3600); // ❌ not a function — dies silently
},
};
```
</bad-example>
<good-example>
```ts
// Option A — cron + fn: publish via the SDK (dominant idiom)
import { setLiveSnapshot } from "@worldwideview/seeder-sdk";
export default {
name: "earthquakes",
cron: "0 * * * *",
fn: async () => {
await setLiveSnapshot("earthquakes", { source: "earthquakes", fetchedAt: new Date().toISOString(), items, totalCount: items.length }, 3600);
},
};
// Option B — interval + fetch: just return the array, scheduler does the rest
export default {
name: "earthquakes",
interval: 60_000,
fetch: async () => items, // ✅ no publishing call needed
};
```
</good-example>
+11 -16
View File
@@ -206,18 +206,10 @@ Hard refresh: `Ctrl+Shift+R`
## Creating Static OSM Plugins
See full guide: `.agents/skills/osm-static-plugin-creation.md`
Use the `plugin-new` skill (`.agents/skills/plugin-new/SKILL.md`) to scaffold new plugins, including OSM-based static data plugins. The old `scaffold-osm-plugin.mjs` script and `osm-static-plugin-creation.md` skill were removed; static OSM plugins are now built as standard `bundle` format plugins via the wwv-cli:
**Quick start:**
```bash
node scripts/scaffold-osm-plugin.mjs '{
"name": "volcanoes",
"displayName": "Volcanoes",
"osmTag": "natural=volcano",
"icon": "Mountain",
"color": "#ef4444",
"category": "Natural Disaster"
}'
node packages/wwv-cli/dist/index.js create <name> --local
```
**Manual Overpass API query (PowerShell):**
@@ -227,26 +219,29 @@ $body = "data=[out:json][timeout:300];(node[$tag];way[$tag];relation[$tag];);out
Invoke-RestMethod -Uri 'https://overpass-api.de/api/interpreter' -Method Post -Body $body -OutFile 'tmp/raw_data.json'
```
**Note:** OSM data is licensed under **ODbL** — include attribution in plugin READMEs.
**Note:** OSM data is licensed under **ODbL** - include attribution in plugin READMEs.
---
## npm Plugin Publishing
See full guide: `.agents/skills/version-control/npm-plugin-publishing.md`
The `npm-plugin-publishing.md` skill was removed. Use the wwv-cli publish command:
```bash
# First-time publish
# Publish a local plugin
node packages/wwv-cli/dist/index.js publish <name> [--org <your-org>]
# Or publish directly via pnpm (for packages/ workspace members)
pnpm publish --workspace=packages/wwv-plugin-<name> --access public
# Future versions — via Trusted Publishing (GitHub Actions CI/CD)
# Future versions via Trusted Publishing (GitHub Actions CI/CD)
```
---
## Git / Version Control
See full guide: `.agents/skills/version-control/git-version-control.md`
The `git-version-control.md` skill was removed. See `.agents/skills/using-git-worktrees/SKILL.md` for worktree workflows and `.agents/skills/branch-cleanup/SKILL.md` for the post-merge teardown flow.
**Commit convention:** `feat:`, `fix:`, `chore:`, `docs:` prefixes.
**Commit when:** A new feature is completed (per project rules).
@@ -255,7 +250,7 @@ See full guide: `.agents/skills/version-control/git-version-control.md`
## Security Checks
See full guide: `.agents/skills/security/security-check.md`
The `security-check.md` skill was removed. Security reviews are handled by the `security-reviewer` agent (`.agents/agents/security-reviewer.md`). Trigger it after any change touching auth routes, API routes, plugin loading, or marketplace flows.
---
+3 -3
View File
@@ -237,7 +237,7 @@ GET marketplace.worldwideview.dev/api/registry
- Trust is **always stamped server-side** — no client-side trust claims accepted
- Registry response cached for **5 minutes** (in-memory on each WWV instance)
- If registry unreachable, last cached result used; new unknowns default to `unverified`
- **Managing:** Edit `src/data/verifiedPlugins.ts` in marketplace repo and redeploy
- **Managing:** Use the marketplace admin API (`/api/admin/registry`) to manage the signed plugin registry. The old `src/data/verifiedPlugins.ts` static file was replaced by database-driven registry management.
- **Revoking:** Remove plugin ID and redeploy — WWV instances drop trust on next cache refresh
### Unverified Plugin Warning
@@ -437,7 +437,7 @@ This queries Overpass API, converts to GeoJSON, scaffolds the package, and print
| Power plants | `power=plant` | 15k |
| Wind farms | `generator:source=wind` | 50k |
See skill: `.agents/skills/osm-static-plugin-creation.md`
The `osm-static-plugin-creation.md` skill was removed. Use `node packages/wwv-cli/dist/index.js create <name> --local` to scaffold a new plugin, then populate it with OSM data fetched via the Overpass API.
---
@@ -462,7 +462,7 @@ To solve this friction and make third-party plugin hosting highly intuitive, the
2. **Backend SDK:** They write simple `.ts` fetch scripts returning `GeoEntity[]` and drop them into a mounted `/seeders` volume.
3. **Zero Configuration:** The Docker engine hot-reloads these seeders, handles the Redis caching, and exposes standardized REST or WebSocket endpoints automatically. The developer focuses only on fetching data, avoiding all backend infrastructure setup.
See skill: `.agents/skills/data-engine-seeder-creation.md`
The `data-engine-seeder-creation.md` skill was removed. Seeder implementation rules are documented inline in `.agents/rules/data-engine-architecture.md`. Seeders live in `local-seeders/community/` or `local-seeders/private/` (separate git clones).
---
+49
View File
@@ -0,0 +1,49 @@
# /triage-issue
Triage a single GitHub issue in `silvertakana/worldwideview` per the project's [TRIAGE.md](../../TRIAGE.md) intake rules. Classifies the issue, recommends a disposition, and executes it after explicit user confirmation.
**Usage:** `/triage-issue <issue-number>`
`$ARGUMENTS` = the issue number to triage.
## Procedure
### 1. Fetch the issue
```bash
gh issue view $ARGUMENTS --repo silvertakana/worldwideview --json number,title,body,labels,comments,author
```
### 2. Classify
Determine the type from the title prefix and body:
| Signal | Type |
|---|---|
| `[PLUGIN]`, "data source", "show X on the globe" | **plugin-request** |
| `[FEATURE]`, "feature request", capability not tied to a data source | **enhancement** |
| `[BUG]`, error, stack trace, "doesn't work" | **bug** |
| Open-ended question, no actionable ask | **question** |
### 3. Apply the TRIAGE.md rule
- **plugin-request:** vet the API first (dispatch the `plugin-researcher` agent if the source is unknown). Then apply the build/do-not-build rule (free API + renders something meaningful + fits the demo).
- Viable -> propose: add a checklist line to #4, label `plugin-request` + `good first issue` + `help wanted`, close standalone with "Tracked in #4."
- Not viable -> propose: close with the specific reason.
- **enhancement:** propose: label `enhancement`, add a one-line ROADMAP backlog entry, keep open.
- **bug:** propose: label `bug`, reproduce, then fix inline or route to the `debugger` agent.
- **question:** draft a reply; propose answer-then-close.
### 4. Confirm before any state change
Present the classification and proposed actions as a short summary. **Do not** comment, label, pin, close, or edit anything until the user explicitly approves (per the project's "explicit user authorization before any state-changing action" rule). Comments are posted from the owner account, so they read as owner triage notes - keep them accurate and neutral.
### 5. Execute
On approval, run the `gh` commands for the approved actions only. Report each result with its URL.
## Notes
- Issue #4 (Plugin Wishlist) is the canonical pinned funnel for plugin ideas - never create a competing wishlist.
- Never promise dates on `enhancement` issues.
- See [TRIAGE.md](../../TRIAGE.md) for the full rationale and the build/do-not-build test.
+4 -3
View File
@@ -45,10 +45,10 @@ jobs:
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Log in to the Container registry
uses: docker/login-action@v3
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -56,11 +56,12 @@ jobs:
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=raw,value=ci,enable={{is_default_branch}}
type=ref,event=branch
type=sha,format=short
+2 -2
View File
@@ -53,7 +53,7 @@ jobs:
git config user.email '[email protected]'
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -72,7 +72,7 @@ jobs:
--days-comment=${{ env.DAYS_COMMENT }}
- name: Upload findings artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: gc-findings-${{ github.run_id }}
path: gc-findings.json
+2 -2
View File
@@ -25,7 +25,7 @@ jobs:
fetch-depth: 0 # Required for Stryker's incremental mode.
- name: Setup pnpm
uses: pnpm/action-setup@v3
uses: pnpm/action-setup@v6
with:
version: 9
@@ -46,7 +46,7 @@ jobs:
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: stryker-report
path: reports/mutation/
+2 -2
View File
@@ -40,7 +40,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v6
with:
version: 9.15.4
@@ -71,7 +71,7 @@ jobs:
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
run: pnpm test:e2e --project=${{ matrix.browser }}
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: playwright-report-${{ matrix.browser }}
+93
View File
@@ -0,0 +1,93 @@
# Trigger model: merge to main with a version bump in the relevant package.json is the
# intended signal. This workflow checks npm for the exact version before publishing, so
# re-running on an already-published version is safe and idempotent.
#
# Auth: a single npm granular token scoped to @worldwideview/*, stored as the
# org-level GitHub secret NPM_TOKEN. One secret covers every @worldwideview package
# (these libs + all wwv-plugins), so no per-package setup is needed. `actions/setup-node`
# (with registry-url) writes an .npmrc that reads NODE_AUTH_TOKEN. We still request
# `id-token: write` and pass `--provenance` so npm records a signed build-provenance
# attestation (provenance works with token auth; it does NOT require per-package config).
#
# Publish tool: we use `npm publish` (not `pnpm publish`). Correct ONLY while these packages
# have no `workspace:*` dependencies (npm does not rewrite the workspace: protocol). The 3
# packages here have none (sdk -> react peer; libs -> sdk peer via a semver range). If any
# package later adds a `workspace:*` dependency, switch its publish step to
# `pnpm publish --no-git-checks`.
name: Publish Packages to npm
on:
push:
branches: [main]
workflow_dispatch:
# Serialize runs so two fast-follow merges can't both pass the version-check and then
# race to publish the same version (npm would 403 the loser). Never cancel an in-flight
# publish.
concurrency:
group: publish-packages
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-latest
# id-token: write is for build-provenance attestation (not auth); scope to this job.
permissions:
contents: read
id-token: write
# Auth for every npm publish step in this job (setup-node reads NODE_AUTH_TOKEN).
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 20
registry-url: https://registry.npmjs.org
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build wwv-plugin-sdk
run: pnpm --filter @worldwideview/wwv-plugin-sdk run build
- name: Publish @worldwideview/wwv-plugin-sdk
run: |
LOCAL_VERSION=$(node -p "require('./packages/wwv-plugin-sdk/package.json').version")
# Equality check (not exit-code): only skip when that EXACT version is already on
# npm. An unpublished-yet-existing package returns empty here -> we publish. --silent
# keeps npm notices off stdout so the comparison stays clean.
NPM_VERSION=$(npm view "@worldwideview/wwv-plugin-sdk@${LOCAL_VERSION}" version --silent 2>/dev/null || true)
if [ "$NPM_VERSION" = "$LOCAL_VERSION" ]; then
echo "@worldwideview/wwv-plugin-sdk@${LOCAL_VERSION} already published — skipping"
else
echo "Publishing @worldwideview/wwv-plugin-sdk@${LOCAL_VERSION}"
npm publish ./packages/wwv-plugin-sdk --provenance --access public
fi
- name: Publish @worldwideview/wwv-lib-incidents
run: |
LOCAL_VERSION=$(node -p "require('./packages/wwv-lib-incidents/package.json').version")
NPM_VERSION=$(npm view "@worldwideview/wwv-lib-incidents@${LOCAL_VERSION}" version --silent 2>/dev/null || true)
if [ "$NPM_VERSION" = "$LOCAL_VERSION" ]; then
echo "@worldwideview/wwv-lib-incidents@${LOCAL_VERSION} already published — skipping"
else
echo "Publishing @worldwideview/wwv-lib-incidents@${LOCAL_VERSION}"
npm publish ./packages/wwv-lib-incidents --provenance --access public
fi
- name: Publish @worldwideview/wwv-lib-aviation
run: |
LOCAL_VERSION=$(node -p "require('./packages/wwv-lib-aviation/package.json').version")
NPM_VERSION=$(npm view "@worldwideview/wwv-lib-aviation@${LOCAL_VERSION}" version --silent 2>/dev/null || true)
if [ "$NPM_VERSION" = "$LOCAL_VERSION" ]; then
echo "@worldwideview/wwv-lib-aviation@${LOCAL_VERSION} already published — skipping"
else
echo "Publishing @worldwideview/wwv-lib-aviation@${LOCAL_VERSION}"
npm publish ./packages/wwv-lib-aviation --provenance --access public
fi
-38
View File
@@ -1,38 +0,0 @@
name: Publish Plugin to NPM
on:
push:
tags:
- "wwv-plugin-*-v*" # e.g. wwv-plugin-aviation-v1.0.1
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # Required for OIDC trusted publishing (no NPM_TOKEN needed)
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
- name: Install dependencies
run: npm ci
- name: Detect package name from tag
id: pkg
run: |
TAG="${{ github.ref_name }}"
# Strips the -vX.Y.Z suffix: "wwv-plugin-aviation-v1.0.1" → "wwv-plugin-aviation"
PKG=$(echo "$TAG" | sed 's/-v[0-9].*//')
echo "package=$PKG" >> $GITHUB_OUTPUT
echo "Publishing: $PKG"
- name: Build package
run: npm run build -w packages/${{ steps.pkg.outputs.package }}
- name: Publish to NPM (OIDC)
run: npm publish packages/${{ steps.pkg.outputs.package }} --access public --provenance
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4
with:
@@ -97,7 +97,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4
with:
+24 -25
View File
@@ -21,23 +21,19 @@ A single globe that shows everything happening in the world right now, extensibl
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
## Current Milestone: v1.4 Agentic Intelligence
## Current Milestone: v1.5 MCP Public-Launch Hardening
**Goal:** Transform the WWV MCP server from a collection of atomic tools into a well-instructed, investigation-capable AI assistant -- one that knows what it has, reasons over the globe, and delivers both globe actions and prose reports.
**Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to the public -- a robust error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
**Target features:**
- Server `instructions` field + workflow sequences (agent oriented from first connection)
- MCP Prompts for named workflows (`orient-globe`, `investigate`)
- Full 6-component tool description rewrite across all 15+ existing tools
- `emptyReason` field in all query responses (distinguishes "no data" from "plugin not loaded")
- `list_available_plugins` tool (agent checks before querying)
- `get_globe_context` tool (full orientation snapshot in one call)
- `investigate_area` compound tool (geocode + check + query + act + report)
- `update_favorite` tool (completes full CRUD lifecycle for favorites)
**Target features (Phases 31-36):**
- Transport resilience: well-formed JSON-RPC errors (no bare 500s), DB-outage-safe auth, explicit maxDuration, honest listChanged
- Security and abuse-resistance: dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, input/length caps
- Tool honesty: accurate emptyReason, validated ids (no success-on-no-op), honest region coverage, output caps, corrected server instructions
- Observability: /api/health probes Redis + DB + data engine
- Deployment wiring: prod compose Redis + WWV_DATA_ENGINE_URL + global geocoding throttle + infra checklist
- Onboarding and framing: public quickstart, ConnectAgentHelper prerequisites, command tools documented as "requires an open globe session"
**Backlog (deferred):**
- PLG-01/PLG-02: list_plugins() + install_plugin() marketplace tools (backlog 999.1/999.2)
- UX-01: ConnectAgentHelper upgrade CTA in demo edition (backlog 999.3)
**Locked decisions:** command tools keep current behavior (they require a live signed-in browser session to control the globe); a headless/render-on-demand globe is out of scope (deferred).
## Requirements
@@ -63,17 +59,19 @@ A single globe that shows everything happening in the world right now, extensibl
- Data query tools across all active plugins - v1.2
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
### Active (v1.4 Agentic Intelligence)
**v1.4 Agentic Intelligence (Phases 26-30, shipped 2026-06-02)**
- Server instructions + orientation prompts, 6-component tool description rewrite
- emptyReason response contract, list_available_plugins / get_globe_context / investigate_area, update_favorite CRUD
- Phase 30 LocalDataSource bridge (static/client-side plugins queryable server-side)
- [ ] Server `instructions` field with role-framing and canonical workflow sequences
- [ ] MCP Prompts: `orient-globe` and `investigate` named workflow templates
- [ ] 6-component tool description rewrite for all command, query, and v1.3 tools
- [ ] `emptyReason` field on all query tool responses
- [ ] `get_plugin_filters` returns explicit `{available: false}` when plugin not active
- [ ] `list_available_plugins` MCP tool (streaming plugins + entity counts)
- [ ] `get_globe_context` MCP tool (full orientation snapshot)
- [ ] `investigate_area` compound MCP tool (geocode + check + query + act + prose report)
- [ ] `update_favorite` MCP tool (complete CRUD lifecycle for favorites)
### Active (v1.5 MCP Public-Launch Hardening)
- [ ] Transport: top-level JSON-RPC error contract, DB-outage-safe auth, explicit maxDuration, honest listChanged + re-poll docs
- [ ] Security: dedicated API_KEY_HMAC_SECRET enforcement (cloud/demo), Redis-backed per-key rate limiting, trusted-proxy IP, favorites cap + identifier/string length+charset bounds
- [ ] Tool honesty: session-independent emptyReason, validated layer/filter ids + focus_entity wiring, get_entities_in_region count/truncated + tighter bbox, investigate_area/get_plugin_data output caps, corrected MCP_SERVER_INSTRUCTIONS, engine_unreachable vs no_active_plugins
- [ ] Observability: /api/health probes Redis + DB + data engine
- [ ] Deployment: prod compose Redis + REDIS_URL, WWV_DATA_ENGINE_URL REST base, global Nominatim throttle, infra checklist
- [ ] Onboarding: public quickstart doc, ConnectAgentHelper prerequisites, command-tool open-session requirement documented
### Out of Scope
@@ -84,6 +82,7 @@ A single globe that shows everything happening in the world right now, extensibl
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
- API key scopes/permissions and rotation/grace-period flows -- revisit later
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
- Headless / render-on-demand globe (v1.5) -- command tools require a live signed-in browser session; building a serverless globe is deferred
## Context
@@ -112,4 +111,4 @@ A single globe that shows everything happening in the world right now, extensibl
This document evolves at phase transitions and milestone boundaries.
---
*Last updated: 2026-05-31 after v1.4 milestone start*
*Last updated: 2026-06-03 after v1.5 milestone start*
+61 -65
View File
@@ -1,94 +1,90 @@
# Requirements: WorldWideView v1.4 Agentic Intelligence
# Requirements: WorldWideView -- v1.5 MCP Public-Launch Hardening
**Defined:** 2026-05-31
**Core Value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
**Defined:** 2026-06-03
**Core Value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
## v1.3 Requirements (shipped)
Derived from the public-launch premortem. Closes the blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
All v1.3 requirements are complete. See archive for details.
## v1 Requirements
## v1.4 Requirements
### Transport Resilience (Phase 31)
### INST -- Server Instructions & Orientation
- [x] **TRANS-01**: Every MCP failure path (auth throw, malformed JSON-RPC, tool throw, Redis/DB down during request handling) returns a well-formed JSON-RPC error (-32603, id:null, HTTP 500) instead of a bare 500 / empty body.
- [x] **TRANS-02**: A database outage during API-key auth returns a clean 401 (authenticateApiKey returns null) rather than throwing.
- [x] **TRANS-03**: The MCP route declares an explicit maxDuration above the 10s plugin-relay blpop so platform timeouts never truncate a blocked plugin call into a non-JSON-RPC error.
- [x] **TRANS-04**: The server no longer advertises tools.listChanged unless it emits the notification; the stateless "re-call tools/list after enabling plugins" contract is documented in the server instructions.
- [x] **INST-01**: MCP server returns a populated `instructions` field in InitializeResult containing a role-framing markdown document that tells agents who WWV is, what tools are available, and the mental model for using them
- [x] **INST-02**: The `instructions` document embeds canonical workflow sequences: geocode-first before fly_to, check plugin availability before querying entities, read globe://sessions before sending any command tool
- [x] **INST-03**: MCP server registers an `orient-globe` Prompt that agents can invoke to get a structured snapshot of current sessions, active layers, and loaded plugins in one response
- [x] **INST-04**: MCP server registers an `investigate` Prompt that accepts a place name and guides the agent step-by-step through geocode -> plugin availability check -> region query -> globe action
### Security and Abuse-Resistance (Phase 32)
### DESC -- Tool Description Rewrite (6-component standard)
- [x] **SEC-01**: In cloud/demo editions the server requires a dedicated API_KEY_HMAC_SECRET and fails startup if it is unset or equal to AUTH_SECRET; local dev preserves the AUTH_SECRET fallback.
- [x] **SEC-02**: MCP tool calls are rate-limited per-userId/per-key via Redis (not only per-IP).
- [x] **SEC-03**: Client IP is derived from a trusted-proxy source so rate limiters cannot be bypassed via a spoofed X-Forwarded-For header.
- [x] **SEC-04**: Favorites are capped per user and all identifier/string tool inputs (entityId, pluginId, layerId, name, notes) have max-length and charset bounds in the Zod schemas and in isValidGlobeCommand.
Tool descriptions must include: (1) purpose verb+object front-loaded, (2) when-to-use vs. alternatives, (3) limitations and empty-result meaning, (4) parameter format + ranges, (5) concrete examples, (6) appropriate length (not truncated at the key sentence).
### Tool Honesty and Agent UX (Phase 33)
- [x] **DESC-01**: All globe command tools rewritten to 6-component standard: `pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline` -- each includes sessions precondition inline and distinguishes from its nearest alternative
- [x] **DESC-02**: All data query tools rewritten to 6-component standard: `search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data` -- each includes plugin-availability note and explanation of what empty results mean
- [x] **DESC-03**: All v1.3 tools rewritten to 6-component standard: `geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`
- [x] **TOOL-01**: Session-independent data-query tools never report emptyReason "no_session_active"; they return the true reason (no_data_matches, engine_unreachable, or no_active_plugins).
- [x] **TOOL-02**: toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text; focus_entity resolves entityId to coordinates server-side.
- [x] **TOOL-03**: get_entities_in_region returns count and a truncated flag, tightens the radiusKmToBbox bounds, and documents that capped results are an unordered sample.
- [x] **TOOL-04**: investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow client context.
- [x] **TOOL-05**: MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}), and list_available_plugins distinguishes engine_unreachable from no_active_plugins.
### RESP -- Smart Response Contracts
### Observability (Phase 34)
- [x] **RESP-01**: All query tools (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) include an `emptyReason` field when results are empty: `"plugin_not_streaming"` | `"no_data_matches"` | `"no_session_active"`
- [x] **RESP-02**: `get_plugin_filters` returns `{ available: false, reason: "plugin not loaded" }` (not an empty array) when the requested plugin is not active in the engine
- [x] **OBS-01**: /api/health actively probes Redis, the database, and the data-engine manifest, returning a degraded status when any dependency is down.
### TOOL -- New Compound & Discovery Tools
### Deployment Wiring (Phase 35)
- [x] **TOOL-01**: `list_available_plugins` MCP tool returns which plugins are currently streaming data to the engine, including entity counts and queryable entity types per plugin -- agents call this before attempting any data query
- [x] **TOOL-02**: `get_globe_context` MCP tool returns a full orientation snapshot in one call: active session count, camera position, active layers, applied filters, loaded plugin list -- replaces reading multiple resources separately
- [x] **TOOL-03**: `investigate_area(place_name, entity_type, radius_km?)` compound MCP tool that internally geocodes the place, checks which plugins are streaming the entity type, queries the bounding region, positions the globe camera, and returns both the entity list and a prose situation summary
- [x] **DEPLOY-01**: The production compose template provisions/wires Redis via REDIS_URL so sessions, command queue, geocode cache, and rate limiters work in production.
- [x] **DEPLOY-02**: WWV_DATA_ENGINE_URL is set to the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in compose/env templates so MCP data tools reach /manifest.
- [x] **DEPLOY-03**: A single global Nominatim throttle (<=1 rps) protects the shared geocoder, and the geocode cache path is confirmed live.
- [x] **DEPLOY-04**: An INFRA-CHECKLIST.md documents the Coolify actions the operator must apply (managed Redis rediss://, REDIS_URL, WWV_DATA_ENGINE_URL, API_KEY_HMAC_SECRET distinct from AUTH_SECRET).
### CRUD -- Full Favorites Lifecycle
### Onboarding and Framing (Phase 36)
- [x] **CRUD-01**: `update_favorite(favoriteId, { name?, notes? })` MCP tool allows agents to rename or annotate a saved bookmark without deleting and re-creating it -- completes Create/Read/Update/Delete lifecycle for favorites
## Future Requirements (deferred)
### Plugin Marketplace Integration
- PLG-01: `list_plugins` MCP tool showing available marketplace plugins
- PLG-02: `install_plugin` MCP tool to install a plugin from the marketplace
- UX-01: ConnectAgentHelper upgrade CTA in demo edition
### Advanced Investigation
- Multi-turn investigation memory (agent remembers prior findings across sessions)
- Proactive monitoring (agent watches for changes and alerts)
- Saved investigation reports (persistent CRUD for investigation outputs)
- Filter presets (save/apply named filter configurations)
- [x] **ONBRD-01**: A public quickstart doc walks a new user from sign-up to a working MCP connection (generate key, paste JSON, open the globe tab).
- [x] **ONBRD-02**: ConnectAgentHelper states the hard prerequisites: signed-in account, a browser tab open for command tools, cloud edition.
- [x] **ONBRD-03**: Every command-tool description states the live-open-session requirement unmissably.
## Out of Scope
| Feature | Reason |
|---------|--------|
| Embedding AI chat UI in the globe | MCP is server-only; chat is the client's job |
| Browser-side MCP client | Globe is an MCP server target, not client |
| Playwright / computer-use control | SSE command bridge is the pattern |
| Stdio MCP transport | HTTP/SSE for production deployability |
| OAuth 2.1 for MCP auth | Personal API keys sufficient |
| API key scopes/permissions/rotation | Revisit post-v1.4 |
| Proactive monitoring / push alerts | Agent-pulls model only in v1.4 |
| Headless / render-on-demand globe | Command tools require a live signed-in browser session; building a serverless globe is a large effort, deferred. Command tools keep current behavior. |
| API key scopes / rotation flows | Carried over from prior milestones; not a public-launch blocker. |
| Self-hosted geocoder | Global throttle is sufficient for launch; self-hosting Nominatim is a later option. |
## Traceability
| Requirement | Phase | Status |
|-------------|-------|--------|
| INST-01 | Phase 26 | Complete |
| INST-02 | Phase 26 | Complete |
| INST-03 | Phase 26 | Complete |
| INST-04 | Phase 26 | Complete |
| DESC-01 | Phase 27 | Complete |
| DESC-02 | Phase 27 | Complete |
| DESC-03 | Phase 27 | Complete |
| RESP-01 | Phase 28 | Complete |
| RESP-02 | Phase 28 | Complete |
| CRUD-01 | Phase 28 | Complete |
| TOOL-01 | Phase 29 | Complete |
| TOOL-02 | Phase 29 | Complete |
| TOOL-03 | Phase 29 | Complete |
| TRANS-01 | Phase 31 | Done |
| TRANS-02 | Phase 31 | Done |
| TRANS-03 | Phase 31 | Done |
| TRANS-04 | Phase 31 | Done |
| SEC-01 | Phase 32 | Done |
| SEC-02 | Phase 32 | Done |
| SEC-03 | Phase 32 | Done |
| SEC-04 | Phase 32 | Done |
| TOOL-01 | Phase 33 | Done |
| TOOL-02 | Phase 33 | Done |
| TOOL-03 | Phase 33 | Done |
| TOOL-04 | Phase 33 | Done |
| TOOL-05 | Phase 33 | Done |
| OBS-01 | Phase 34 | Done |
| DEPLOY-01 | Phase 35 | Done |
| DEPLOY-02 | Phase 35 | Done |
| DEPLOY-03 | Phase 35 | Done |
| DEPLOY-04 | Phase 35 | Done |
| ONBRD-01 | Phase 36 | Done |
| ONBRD-02 | Phase 36 | Done |
| ONBRD-03 | Phase 36 | Done |
**Coverage:**
- v1.4 requirements: 13 total
- Mapped to phases: 13
- Unmapped: 0 ✓
- v1 requirements: 21 total
- Mapped to phases: 21
- Unmapped: 0
---
*Requirements defined: 2026-05-31*
*Last updated: 2026-05-31 after initial v1.4 definition*
*Requirements defined: 2026-06-03*
*Last updated: 2026-06-03 after v1.5 milestone start*
+86 -133
View File
@@ -4,7 +4,8 @@
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
- [ ] **v1.4 Agentic Intelligence** - Phases 26-29 (active)
- [x] **v1.4 Agentic Intelligence** - Phases 26-30 (shipped 2026-06-02) - [archive](milestones/v1.4-ROADMAP.md)
- [ ] **v1.5 MCP Public-Launch Hardening** - Phases 31-36 (planning, started 2026-06-03)
## Phases
@@ -33,115 +34,98 @@ Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
</details>
### v1.4 Agentic Intelligence
<details>
<summary>v1.4 Agentic Intelligence (Phases 26-30) - SHIPPED 2026-06-02</summary>
- [x] **Phase 26: Server Instructions + Orientation** - Agent arrives oriented with role framing, canonical workflows, and named MCP Prompts baked into the server (completed 2026-05-31)
- [x] **Phase 27: Tool Description Rewrite** - All 15+ existing tools rewritten to the 6-component standard so agents select and invoke them correctly on the first try (completed 2026-05-31)
- [x] **Phase 28: Smart Response Contracts + Favorites CRUD** - Query responses carry semantic empty reasons, get_plugin_filters signals unavailable plugins, and favorites gain full update support (completed 2026-05-31)
- [x] **Phase 29: Compound and Discovery Tools** - Three new tools let agents self-orient and investigate in one call rather than assembling multi-step pipelines manually (completed 2026-05-31)
- [x] **Phase 30: Local Data-Source Bridge** - Server-reachable static/client-side plugins become MCP-queryable via a generalized LocalDataSource registry (4/4 plans, completed 2026-06-02)
Full details: [milestones/v1.4-ROADMAP.md](milestones/v1.4-ROADMAP.md)
</details>
### v1.5 MCP Public-Launch Hardening
**Milestone Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to untrusted, authenticated public users -- a robust JSON-RPC error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope.
- [ ] **Phase 31: Transport Resilience** - Every MCP failure path returns a well-formed JSON-RPC error, auth survives a DB outage, and timeouts/listChanged are honest
- [ ] **Phase 32: Security and Abuse-Resistance** - Dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, and input/length/charset caps
- [ ] **Phase 33: Tool Honesty and Agent UX** - Tools report the true reason for empty results, validate ids, bound region/output size, and ship corrected server instructions
- [ ] **Phase 34: Observability** - /api/health actively probes Redis, the database, and the data engine and reports a degraded status when any is down
- [ ] **Phase 35: Deployment Wiring** - Production compose wires Redis + the data-engine REST base, a global geocoder throttle protects Nominatim, and an infra checklist documents operator actions
- [ ] **Phase 36: Onboarding and Framing** - A public quickstart, ConnectAgentHelper prerequisites, and command-tool descriptions make the live-open-session requirement unmissable
## Phase Details
### Phase 22: Geocoding + Favorites
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
### Phase 31: Transport Resilience
**Goal**: Every MCP failure path -- auth throw, malformed JSON-RPC, tool throw, Redis/DB outage during request handling, or platform timeout -- surfaces to the client as a well-formed JSON-RPC error rather than a bare 500, an empty body, or a non-JSON-RPC truncation
**Depends on**: Phase 30 (v1.4 complete; stable MCP route, authenticateApiKey, plugin-relay blpop bridge)
**Requirements**: TRANS-01, TRANS-02, TRANS-03, TRANS-04
**Success Criteria** (what must be TRUE):
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
1. Forcing any failure mode (invalid auth, malformed JSON-RPC body, a tool that throws, Redis/DB down mid-request) returns a well-formed JSON-RPC error object (code -32603, id:null, HTTP 500) with a non-empty body -- never a bare 500 or empty response
2. With the database unavailable, calling an authenticated MCP endpoint returns a clean 401 (authenticateApiKey resolves to null) instead of throwing an unhandled exception
3. The MCP route declares an explicit maxDuration greater than the 10s plugin-relay blpop window, so a blocked plugin call still returns a JSON-RPC error rather than a platform-truncated non-JSON-RPC response
4. The server's advertised capabilities no longer claim tools.listChanged unless the notification is actually emitted, and the server instructions document the stateless "re-call tools/list after enabling plugins" contract
**Plans**: TBD
### Phase 23: Entity Filtering
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
### Phase 32: Security and Abuse-Resistance
**Goal**: An authenticated but untrusted public user cannot bypass auth hardening, exhaust shared resources, spoof their identity to defeat rate limiting, or smuggle oversized/malformed input through the tool schemas
**Depends on**: Phase 31 (clean error contract in place so rejected/limited requests return well-formed errors)
**Requirements**: SEC-01, SEC-02, SEC-03, SEC-04
**Success Criteria** (what must be TRUE):
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
**Plans**: 3 plans (ships atomically per STATE.md)
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
### Phase 24: Route Wiring + Version Bump
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
**Success Criteria** (what must be TRUE):
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN, build OK. Commits 5201ae3, 5ea7855.
### Phase 25: Documentation
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
**Success Criteria** (what must be TRUE):
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
### Phase 26: Server Instructions + Orientation
**Goal**: A fresh AI agent connecting to the WWV MCP server for the first time receives a complete orientation -- who WWV is, what tools exist, and the canonical workflows to follow -- without the user having to explain anything
**Depends on**: Phase 25 (v1.3 complete; stable tool set as orientation baseline)
**Requirements**: INST-01, INST-02, INST-03, INST-04
**Success Criteria** (what must be TRUE):
1. The MCP `initialize` response contains a non-empty `instructions` field with a role-framing header, a mental model for the globe/plugins/sessions, and at least two explicit "do X before Y" rules (read sessions before commanding; check plugin availability before querying)
2. A fresh agent that has only read `instructions` correctly answers: "What do I need to do before calling pan_globe?" without having read any individual tool description
3. Calling `prompts/list` returns both `orient-globe` and `investigate` prompt names; calling `prompts/get` on each returns a structured, step-numbered template with no placeholder text
4. An agent invoking the `orient-globe` prompt receives a single response containing active sessions, loaded plugin layers, and current camera state -- no follow-up resource reads needed to get oriented
1. In cloud/demo editions the server fails to start when API_KEY_HMAC_SECRET is unset or equal to AUTH_SECRET, while local dev still boots using the AUTH_SECRET fallback
2. Repeated MCP tool calls from the same userId/key are throttled by a Redis-backed limiter (per-user/per-key, not only per-IP), and an over-limit call returns a clean rate-limit error
3. A spoofed X-Forwarded-For header cannot reset or bypass the rate limiter -- the client IP is derived only from a trusted-proxy source
4. Favorites are capped per user, and every identifier/string tool input (entityId, pluginId, layerId, name, notes) is rejected when it exceeds max-length or violates charset bounds, enforced in both the Zod schemas and isValidGlobeCommand
**Plans**: TBD
### Phase 27: Tool Description Rewrite
**Goal**: Every existing MCP tool description satisfies the 6-component standard so an agent selects the right tool, passes correct arguments, and correctly interprets empty results on the first attempt
**Depends on**: Phase 26 (instructions written first; tool descriptions must align with the canonical workflows stated there)
**Requirements**: DESC-01, DESC-02, DESC-03
### Phase 33: Tool Honesty and Agent UX
**Goal**: Every tool response tells the agent the truth -- the real reason a result is empty, whether an id was actually recognized, whether results were truncated -- so an agent never reports a false success or a misleading cause to its user
**Depends on**: Phase 31 (error contract), Phase 32 (validated/bounded inputs so honesty checks operate on sanitized ids)
**Requirements**: TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05
**Success Criteria** (what must be TRUE):
1. Every command tool description (`pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline`) contains inline: the sessions precondition, what "no active session" means, and when to prefer this tool over its nearest alternative
2. Every data query tool description (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) states explicitly what an empty result means -- distinguishing "plugin not loaded" from "no matching data"
3. Every v1.3 tool description (`geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`) passes the 6-component checklist: purpose, when-to-use, limitations, parameter format, example, complete length
4. No tool description is truncated at a critical constraint; each fits within MCP client display limits while retaining all mandatory guidance
**Plans**: 3 plans (all wave 1, parallel -- no file overlap)
- [x] 27-01-PLAN.md — DESC-01: rewrite 4 globe command tool descriptions (pan_globe, focus_entity, toggle_layer, set_timeline) + assertion tests
- [x] 27-02-PLAN.md — DESC-02: rewrite 4 data query tool descriptions with empty-result semantics + new tools.test.ts
- [x] 27-03-PLAN.md — DESC-03: conform 8 v1.3 tool descriptions across geocoding/filter/favorites (fly_to gets the sessions precondition) + assertion tests
1. Session-independent data-query tools never return emptyReason "no_session_active"; an empty result reports the true cause -- no_data_matches, engine_unreachable, or no_active_plugins
2. toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text, and focus_entity resolves entityId to coordinates server-side rather than silently no-op'ing
3. get_entities_in_region returns a count and a truncated flag, applies tightened radiusKmToBbox bounds, and documents that capped results are an unordered sample
4. investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow the client's context window
5. MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}) and list_available_plugins distinguishes engine_unreachable from no_active_plugins
**Plans**: TBD
### Phase 28: Smart Response Contracts + Favorites CRUD
**Goal**: Query tools communicate WHY results are empty rather than returning identical empty arrays for unrelated failure modes, and agents can update a saved favorite without deleting and recreating it
**Depends on**: Phase 27 (tool descriptions must reference emptyReason semantics described there)
**Requirements**: RESP-01, RESP-02, CRUD-01
### Phase 34: Observability
**Goal**: An operator (or uptime monitor) can tell at a glance whether the MCP server's critical dependencies are healthy, with /api/health actively probing them rather than returning a hardcoded OK
**Depends on**: Phase 31 (shared Redis/DB access patterns and error handling reused by the probes)
**Requirements**: OBS-01
**Success Criteria** (what must be TRUE):
1. Calling `search_entities` with a plugin that has no active streaming session returns `{ success: true, entities: [], count: 0, emptyReason: "plugin_not_streaming" }` -- distinct from a query that returns `"no_data_matches"` when the plugin is streaming but nothing matches the filter
2. Calling `search_entities` when no globe session is active returns `emptyReason: "no_session_active"` -- the agent can distinguish this from a data absence without guessing
3. Calling `get_plugin_filters("flights")` when the flights plugin is not loaded returns `{ available: false, reason: "plugin not loaded" }` rather than an empty array, allowing the agent to report the real cause to the user
4. Calling `update_favorite(id, { name: "New Name", notes: "Updated note" })` persists the change and is reflected in the next `list_favorites` response without requiring `remove_favorite` + `save_favorite`
**Plans**: 3 plans
- [x] 28-01-PLAN.md — RESP-01: emptyReason discriminated service results + userId threading into registerDataQueryTools + 4-tool passthrough with session-first precedence + tests (wave 1)
- [x] 28-02-PLAN.md — RESP-02: get_plugin_filters availability wrapper (4 shapes) + Phase 27 description/test updates (wave 2, depends on 28-01 for route.ts seam)
- [x] 28-03-PLAN.md — CRUD-01: [BLOCKING] notes String? migration + update_favorite tool + list_favorites notes surfacing + tests (wave 1, independent files)
1. GET /api/health actively probes Redis, the database, and the data-engine manifest on each request rather than returning a static OK
2. When any one dependency is unreachable, /api/health returns a degraded status identifying which dependency is down, while a fully healthy stack returns a healthy status
**Plans**: TBD
### Phase 29: Compound and Discovery Tools
**Goal**: Agents can answer "what is happening near X?" in a single tool call, check which plugins are active before querying, and orient themselves completely without reading multiple resources
**Depends on**: Phase 28 (emptyReason contracts and CRUD-01 must be complete; investigate_area depends on emptyReason to characterize its sub-query results)
**Requirements**: TOOL-01, TOOL-02, TOOL-03
### Phase 35: Deployment Wiring
**Goal**: The production deployment has every dependency the MCP server needs actually provisioned and correctly wired -- Redis, the data-engine REST base, and a protected shared geocoder -- with an operator checklist so a real launch does not silently run on missing infrastructure
**Depends on**: Phase 32 (API_KEY_HMAC_SECRET requirement), Phase 34 (health probes confirm the wired dependencies are reachable)
**Requirements**: DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04
**Success Criteria** (what must be TRUE):
1. Calling `list_available_plugins` returns a list of currently streaming plugins with entity counts and queryable entity types; an agent that calls this before `search_entities` never receives a `plugin_not_streaming` emptyReason it did not anticipate
2. Calling `get_globe_context` returns in one response: active session count, camera position, active layers, applied filters, and loaded plugin list -- an agent that reads this resource needs no additional `globe://sessions`, `globe://state`, or `globe://layers` reads to be fully oriented
3. Calling `investigate_area("Auckland", "flights")` internally geocodes the place, checks which plugins stream flights, queries the bounding region, positions the globe camera over Auckland, and returns both the entity list and a prose situation summary describing what is happening in that area
4. `investigate_area` returns a meaningful prose report even when no entities match -- the summary explains why (e.g., no active flight plugin) rather than returning an empty structure
**UI hint**: no
**Plans**: 1 plan
- [x] 29-01-PLAN.md — All three discovery tools (list_available_plugins, get_globe_context, investigate_area) in discoveryTools.ts + shared discoveryHelpers.ts + route wiring + tests
1. The production compose template provisions and wires Redis via REDIS_URL so sessions, the command queue, the geocode cache, and the rate limiters all function in production
2. WWV_DATA_ENGINE_URL points at the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in the compose/env templates, so MCP data tools can reach /manifest
3. A single global Nominatim throttle (<=1 rps) protects the shared geocoder and the geocode cache path is confirmed live in production configuration
4. An INFRA-CHECKLIST.md documents the exact Coolify actions an operator must apply: managed Redis (rediss://), REDIS_URL, WWV_DATA_ENGINE_URL, and an API_KEY_HMAC_SECRET distinct from AUTH_SECRET
**Plans**: TBD
### Phase 36: Onboarding and Framing
**Goal**: A new public user can go from sign-up to a working MCP connection without hidden prerequisites, and the live-open-session requirement of command tools is stated unmissably everywhere an agent or user encounters it
**Depends on**: Phase 33 (final tool descriptions and instructions stable), Phase 35 (deployment wiring known so the quickstart documents the real path)
**Requirements**: ONBRD-01, ONBRD-02, ONBRD-03
**Success Criteria** (what must be TRUE):
1. A public quickstart doc walks a brand-new user end to end: sign up, generate an API key, paste the connection JSON, and open the globe tab to reach a working MCP connection
2. ConnectAgentHelper states the hard prerequisites up front: a signed-in account, a browser tab open for command tools, and cloud edition
3. Every command-tool description states the live-open-session requirement unmissably, so an agent never attempts a command tool expecting it to work without an open globe session
**Plans**: TBD
**UI hint**: yes
## Progress Table
@@ -151,45 +135,14 @@ Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
## Backlog
Per the 21-REPLAN locked decision ("NO marketplace" in v1.2 scope), the two marketplace
plugin-management MCP tools were deferred. They require the marketplace JWT install bridge,
which was descoped to keep v1.2 worldwideview-only.
- **999.1 -- PLG-01: `list_plugins()` MCP tool** -- returns all marketplace plugins with
install status for the authenticated user. Depends on marketplace API + JWT bridge.
- **999.2 -- PLG-02: `install_plugin({ pluginSlug })` MCP tool** -- triggers installation via
the existing marketplace JWT install bridge flow. Depends on PLG-01 + marketplace install endpoint.
- **999.3 -- UX-01: Show MCP / ConnectAgentHelper as "Cloud edition" upgrade CTA in demo** --
Currently `!isDemo` in Header.tsx:449 hides the entire ConnectAgentHelper section in demo.
UX improvement: surface it as a locked/teaser CTA that explains the feature and links to
upgrade. Pairs with v1.3 MCP-OBSERVATIONS.md scope (geocoding, OSM search, basemap control,
entity filtering, enhanced search, favorites, plugin-tool discovery).
Also tracked as partials (functional, refinement deferred):
- **CTRL-02** focus_entity entityId-only resolution -- currently a no-op without lat/lng;
needs entity-id -> coordinate lookup wired into the command dispatch.
- **MCP-QA-03** explicit Redis reconnect test -- stateless SSE arch makes the original
WebSocket-subscriber spec N/A; ioredis auto-reconnects. Add a reconnect test if reliability
concerns arise.
### Phase 30: Local Data-Source Bridge: make server-reachable client-side and static plugins (camera GeoJSON, OSM-static plugins) queryable via MCP through a generalized LocalDataSource registry. Closes the MCP coverage gap where browser-loaded plugins return plugin_not_streaming. Camera is the first consumer.
**Goal:** Server-reachable client-side/static plugins (camera GeoJSON + traffic route) are MCP-queryable through a generalized manifest-declared LocalDataSource registry, with NO browser session -- closing the plugin_not_streaming coverage gap. Acceptance: a Russia-bbox `get_entities_in_region(pluginId:"camera")` returns the in-box cameras and `list_available_plugins` lists camera as `source:"local"` with a non-zero count.
**Requirements**: D-01..D-08 (CONTEXT decisions), RESP-01 (emptyReason contract preserved), TOOL-01/TOOL-02 (discovery surface)
**Depends on:** Phase 29
**Plans:** 4/4 plans complete
Plans:
- [x] 30-01-PLAN.md — Foundation: SDK LocalDataSourceDeclaration type + camera package.json localData declaration + sync-local-plugins passthrough + validateManifest localData validator (wave 1, TDD)
- [x] 30-02-PLAN.md — localSources module: manifest-driven registry + server-side GeoJSON normalizer + per-source TTL cache (wave 2, TDD)
- [x] 30-03-PLAN.md — Integration seam: fetchPluginSnapshot engine->local->null fallback + getAllPluginSnapshots local-id union; Russia-bbox demo + D-06 emptyReason cases (wave 3, TDD)
- [x] 30-04-PLAN.md — Discovery surface: StreamingPlugin source:"engine"|"local" tag in listStreamingPlugins; camera surfaced in list_available_plugins/get_globe_context (wave 4, TDD)
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
| 31. Transport Resilience | 0/TBD | Not started | - |
| 32. Security and Abuse-Resistance | 0/TBD | Not started | - |
| 33. Tool Honesty and Agent UX | 0/TBD | Not started | - |
| 34. Observability | 0/TBD | Not started | - |
| 35. Deployment Wiring | 0/TBD | Not started | - |
| 36. Onboarding and Framing | 0/TBD | Not started | - |
+75 -47
View File
@@ -1,38 +1,63 @@
---
gsd_state_version: 1.0
milestone: v1.4
milestone_name: Agentic Intelligence
status: verifying
last_updated: "2026-06-02T04:43:48.134Z"
last_activity: 2026-06-02
milestone: v1.5
milestone_name: MCP Public-Launch Hardening
status: complete
last_updated: "2026-06-03T16:05:00.000Z"
last_activity: 2026-06-03
progress:
total_phases: 9
completed_phases: 8
total_plans: 22
completed_plans: 21
percent: 89
total_phases: 6
completed_phases: 6
total_plans: 0
completed_plans: 0
percent: 100
---
# Project State
## Project Reference
See: .planning/PROJECT.md (updated 2026-05-31)
See: .planning/PROJECT.md (updated 2026-06-03)
**Core value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
**Current focus:** Phase 30 — local-data-source-bridge-make-server-reachable-client-side-a
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
**Current focus:** v1.5 MCP Public-Launch Hardening (Phases 31-36) -- closing premortem blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
## Current Position
Phase: 30 (local-data-source-bridge-make-server-reachable-client-side-a) — EXECUTING
Plan: 4 of 4
Status: Phase complete — ready for verification
Last activity: 2026-06-02
Resume file: None
Phase: 36 — Onboarding and Framing (complete)
Plan: —
Status: All 6 phases (31-36) complete and committed; milestone v1.5 done
Last activity: 2026-06-03 — Phase 36 Onboarding and Framing shipped (ONBRD-01..03), gate green (1004 tests), v2.48.9
Progress: [██████████] 95%
## Completed Phases (v1.5)
## v1.4 Phase Map
| Phase | Result | Commit |
|-------|--------|--------|
| 31 Transport Resilience | tsc + 916 tests + build green; security SAFE | 121f7b22 |
| 32 Security and Abuse-Resistance | tsc + 967 tests + build green; security MERGE-WITH-FIXES resolved | 3fd23473 |
| 33 Tool Honesty and Agent UX | tsc + 983 tests + build green; TOOL-01 live-verified (no_data_matches) | 813d2b28 |
| 34 Observability | tsc + tests + build green; /api/health probes redis/db/engine/config | b95ff5d5 |
| 35 Deployment Wiring | tsc + 1004 tests + build green; security MERGE-WITH-FIXES resolved (Redis auth, AUTH_SECRET, pg loopback) | 0f860185 |
| 36 Onboarding and Framing | tsc + 1004 tests + build green; quickstart + prerequisites + SESSION_REQUIRED_PREAMBLE on all 7 command tools | a5fade97 |
## v1.5 Phase Map
| Phase | Goal | Key requirements |
|-------|------|-----------------|
| 31 | Transport Resilience | TRANS-01, TRANS-02, TRANS-03, TRANS-04 |
| 32 | Security and Abuse-Resistance | SEC-01, SEC-02, SEC-03, SEC-04 |
| 33 | Tool Honesty and Agent UX | TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05 |
| 34 | Observability | OBS-01 |
| 35 | Deployment Wiring | DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04 |
| 36 | Onboarding and Framing | ONBRD-01, ONBRD-02, ONBRD-03 |
**Coverage:** 21/21 v1.5 requirements mapped, 0 orphaned.
**Phase numbering:** v1.5 starts at Phase 31 (v1.4 ended at Phase 30).
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope (deferred).
## v1.4 Phase Map (archived reference)
| Phase | Goal | Key requirements |
|-------|------|-----------------|
@@ -40,26 +65,19 @@ Progress: [██████████] 95%
| 27 | Tool Description Rewrite | DESC-01, DESC-02, DESC-03 |
| 28 | Smart Response Contracts + Favorites CRUD | RESP-01, RESP-02, CRUD-01 |
| 29 | Compound and Discovery Tools | TOOL-01, TOOL-02, TOOL-03 |
| 30 | Local Data-Source Bridge | D-01..D-08, RESP-01, TOOL-01, TOOL-02 |
## Key Decisions (carried from v1.2/v1.3)
## Key Decisions (carried from v1.2/v1.3/v1.4)
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream). Reuse for fly_to in v1.3.
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern.
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream).
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern; plugin-relay blpop has a 10s window (relevant to TRANS-03 maxDuration).
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all new MCP tools.
- **LocalDataSource registry (Phase 30-02):** Scans public/plugins-local/<id>/plugin.json at startup; memoized once per process. Per-source TTL cache: TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s. geojson sources read from disk (no self-HTTP); route sources fetched via internal base URL.
- **LocalDataSourceDeclaration SDK export:** Added to wwv-plugin-sdk/src/index.ts re-exports (was absent from Plan 30-01 manifest.ts addition).
## v1.3 Phase Map (archived reference)
| Phase | Goal | Key requirements |
|-------|------|-----------------|
| 22 | Geocoding + Favorites | GEO-01..03, FAV-01..03, SAFE-01..02 |
| 23 | Entity Filtering | FILT-01..04 |
| 24 | Route Wiring + Version Bump | INTG-01, INTG-02 |
| 25 | Documentation | DOC-01..04 |
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all MCP tools.
- **LocalDataSource registry (Phase 30):** Manifest-declared registry making server-reachable static/client-side plugins MCP-queryable; per-source TTL cache (TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s).
- **emptyReason enum (evolving in v1.5):** v1.4 contract was "plugin_not_streaming" | "no_data_matches" | "no_session_active". v1.5 TOOL-01/TOOL-05 require session-independent tools to return no_data_matches | engine_unreachable | no_active_plugins instead of no_session_active. Lock the revised enum in Phase 33 before rewriting MCP_SERVER_INSTRUCTIONS.
- **Nominatim rate limiting:** server-side Redis sliding window (1 req/sec) + 24h cache already live (v1.3 GEO-03). DEPLOY-03 elevates this to a single GLOBAL throttle (<=1 rps) protecting the shared geocoder -- do not re-implement per-request limiting.
## Blockers
@@ -69,15 +87,25 @@ None.
### Roadmap Evolution
- Phase 30 added: Local Data-Source Bridge (Option A): generalized LocalDataSource registry to make server-reachable static/client-side plugins MCP-queryable; camera first consumer
- v1.2 archived at .planning/milestones/v1.2-* and tagged v1.2 in git.
- PR #215 (feat/mcp-support) open on GitHub, awaiting merge.
- v1.3 complete 2026-05-31. All 4 phases shipped, tsc clean, 750 tests GREEN.
- Phase numbering: v1.4 starts at Phase 26 (v1.3 ended at Phase 25).
- Phase 26 is pure configuration/server-init work -- no new tool implementations. McpServer `instructions` string + two MCP Prompt registrations.
- Phase 27 is pure description text rewriting across 15+ existing tools -- no schema changes, no new tools. Lowest risk phase.
- Phase 28 requires code changes to query handler return shapes (emptyReason field) and one new Prisma mutation (update_favorite). Coordinate with prisma.favorite model in Phase 28 plan.
- Phase 29 is the most complex: investigate_area is a compound tool that chains geocode -> plugin check -> region query -> SSE command -> prose generation internally. Design the internal chain carefully; it must not expose intermediate tool results to the caller.
- Nominatim integration: server-side rate limiter (1 req/sec Redis sliding window) + 24h result cache are already live (GEO-03, Phase 22). investigate_area (TOOL-03) reuses this path -- do not re-implement.
- Favorites use prisma.favorite directly -- never proxy through /api/user/favorites (cookie auth incompatible with API key sessions, SAFE-02). update_favorite (CRUD-01) must follow same pattern.
- emptyReason values are an enum contract: "plugin_not_streaming" | "no_data_matches" | "no_session_active". Agree on this enum in Phase 28 and reference it in Phase 27 tool description rewrites -- do Phase 27 after Phase 26 but the enum must be locked before DESC-02 is written.
- v1.5 derived from a public-launch premortem of the MCP server. One phase per REQUIREMENTS.md category, 1:1 mapping.
- Phase numbering: v1.5 starts at Phase 31 (v1.4 ended at Phase 30). Do NOT renumber or reset.
- Dependency note: Phase 31 (clean error contract) is foundational -- Phases 32/33/34 surface their rejections/limits/probe failures through it. Phase 35 depends on SEC-01 (HMAC secret) and OBS-01 (probes confirm wiring). Phase 36 depends on Phase 33 (final tool text) and Phase 35 (real deployment path).
- Phase 36 is the only UI-touching phase (ConnectAgentHelper prerequisites + command-tool description framing) -- flagged UI hint: yes.
- v1.4 (Phases 26-30) shipped 2026-06-02; archived reference retained above.
## Deferred Items
Items deferred at v1.5 milestone start (carried from v1.4 close on 2026-06-02):
| Category | Item | Status |
|----------|------|--------|
| uat_gap | Phase 29 v1.4-UAT.md — 25 pending scenarios | diagnosed (manual acceptance testing not completed; automated gate green) |
| todo | 2026-05-30-system-default-common-plugin-tools.md [mcp] | pending (future idea — system-default common plugin tools) |
| out_of_scope | Headless / render-on-demand globe | deferred (command tools keep live-session behavior; serverless globe is a large effort) |
| out_of_scope | API key scopes / rotation flows | deferred (not a public-launch blocker) |
| out_of_scope | Self-hosted geocoder | deferred (global throttle sufficient for launch) |
## Operator Next Steps
- Plan Phase 31 with /gsd:plan-phase 31 (Transport Resilience -- foundational error contract).
- Phases execute in numeric order 31 → 32 → 33 → 34 → 35 → 36; dependencies allow some parallelism after Phase 31.
@@ -0,0 +1,122 @@
---
phase: 17-instance-picker-ui-overhaul
plan: "01"
subsystem: marketplace-instance-data-layer
tags: [api, tdd, validation, prisma, auth]
dependency_graph:
requires: []
provides: [SavedInstance-lastUsedAt, GET-me-instances-fixed, validateInstanceUrl, POST-instances-link, DELETE-PATCH-instances-id]
affects: [InstancePicker, InstanceHydrator, InstanceCapture, InstanceConfig]
tech_stack:
added: []
patterns: [discriminated-union, idempotent-upsert, ownership-check-404, tdd-red-green]
key_files:
created:
- C:/dev/wwv/worldwideview-marketplace/src/lib/instanceValidation.ts
- C:/dev/wwv/worldwideview-marketplace/src/lib/instanceValidation.spec.ts
- C:/dev/wwv/worldwideview-marketplace/src/app/api/instances/link/route.ts
- C:/dev/wwv/worldwideview-marketplace/src/app/api/instances/[id]/route.ts
- C:/dev/wwv/worldwideview-marketplace/src/app/api/instances/link/route.test.ts
modified:
- C:/dev/wwv/worldwideview-marketplace/src/lib/instanceStore.ts
- C:/dev/wwv/worldwideview-marketplace/src/app/api/me/instances/route.ts
- C:/dev/wwv/worldwideview-marketplace/src/app/api/me/instances/route.test.ts
decisions:
- "GET /api/me/instances kept at current URL - not renamed to /api/instances"
- "Anon callers still receive 200 + empty array - no 401 switch"
- "SavedInstance gets lastUsedAt only - createdAt deliberately excluded per plan"
- "Route test mocks updated to reflect getOrCreateMarketplaceUser addition (Rule 1 fix)"
metrics:
duration: "~25 minutes"
completed: "2026-05-30"
tasks_completed: 3
files_changed: 8
---
# Phase 17 Plan 01: Instance Data Layer Summary
**One-liner:** Server-side instance sync data layer with idempotent upsert, URL validation discriminated union, and ownership-checked CRUD routes.
## Tasks Completed
| Task | Name | Commit | Files |
|------|------|--------|-------|
| 1 | Add lastUsedAt to SavedInstance + fix GET | 421a5b8 | instanceStore.ts, me/instances/route.ts |
| 2 (RED) | validateInstanceUrl failing tests | 269cad1 | instanceValidation.spec.ts |
| 2 (GREEN) | validateInstanceUrl implementation | 9a3fcb7 | instanceValidation.ts |
| 3 (RED) | link route failing tests | 20c7ea0 | instances/link/route.test.ts |
| 3 (GREEN) | link + [id] routes implementation | e69ebca | instances/link/route.ts, instances/[id]/route.ts, route.test.ts fix |
## What Was Built
**Task 1** fixed two issues in the existing GET route:
- `SavedInstance` interface now includes `lastUsedAt: string` (no `createdAt` per plan)
- GET route now calls `getOrCreateMarketplaceUser` to resolve the marketplace cuid before querying `LinkedInstance.userId`. The previous bug queried with the raw Supabase user id, so rows written by `/api/install/start` (which use the marketplace cuid) were never returned.
- `lastUsedAt` added to the SELECT
- Anonymous callers still receive `200 + { instances: [] }` - no auth-contract regression
**Task 2** ported `instanceValidation.ts` with full TDD:
- `InstanceValidationResult` discriminated union: `{ ok: true; url: string } | { ok: false; reason: string }`
- `validateInstanceUrl(raw, marketplaceOrigin)` normalises to `parsed.origin`, rejects non-http(s), self-loops, unparseable, empty/null
- 8 Vitest cases (split null/undefined case and empty-string into separate `it` blocks)
- RED commit preceded GREEN commit
**Task 3** ported both write routes with TDD:
- `POST /api/instances/link`: idempotent upsert via `userId_url` compound key, bumps `lastUsedAt` on repeat
- `DELETE /api/instances/[id]`: ownership check via `findFirst { id, userId }`; returns 404 (never 403)
- `PATCH /api/instances/[id]`: nickname trimmed to 80 chars, null clears field; 404 for non-owned
- Link route unit tests: 401 for anon + upsert called with correct `userId_url`
- RED commit preceded GREEN commit
## Deviations from Plan
### Auto-fixed Issues
**1. [Rule 1 - Bug] Existing route.test.ts for GET /api/me/instances broken by Task 1**
- **Found during:** Task 3 full test run
- **Issue:** The existing `src/app/api/me/instances/route.test.ts` mocked `prisma` without `user.findUnique` and did not mock `getOrCreateMarketplaceUser`. After Task 1 added `getOrCreateMarketplaceUser` to the route, the test threw `TypeError: Cannot read properties of undefined (reading 'findUnique')`.
- **Fix:** Updated the test to mock `getOrCreateMarketplaceUser`, updated prisma mock (no longer needs `user` table), and adjusted assertions to use marketplace user id (`mkt-456`) instead of raw supabase id.
- **Files modified:** `src/app/api/me/instances/route.test.ts`
- **Commit:** e69ebca (bundled with Task 3 GREEN)
### Pre-existing Failures (Out of Scope)
- `src/app/oauth/authorize/actions.spec.ts` has 1 failing test that existed before this plan. Verified by stash-and-test. Not caused by any change in this plan. Logged for deferred attention.
## TDD Gate Compliance
| Gate | Commit | Status |
|------|--------|--------|
| Task 2 RED | 269cad1 | test(17-01): add failing tests for validateInstanceUrl (RED) |
| Task 2 GREEN | 9a3fcb7 | feat(17-01): implement validateInstanceUrl (GREEN) |
| Task 3 RED | 20c7ea0 | test(17-01): add failing tests for POST /api/instances/link (RED) |
| Task 3 GREEN | e69ebca | feat(17-01): create POST /api/instances/link + DELETE/PATCH /api/instances/[id] (GREEN) |
Both TDD cycles satisfied: RED commit preceded GREEN commit for Tasks 2 and 3.
## Known Stubs
None. All routes are fully implemented and wired to live Prisma queries.
## Threat Surface Scan
All mitigations from the plan's threat model are present:
- T-17-01: `validateInstanceUrl` rejects non-http(s), unparseable, marketplace self-origin; only `parsed.origin` stored
- T-17-02: DELETE/PATCH use `findFirst { id, userId }` ownership check; return 404 (not 403)
- T-17-03: GET uses `getOrCreateMarketplaceUser` scoped to caller's marketplace cuid
- T-17-04: PATCH trims nickname to 80 chars before persist
No new security surface introduced beyond what the threat model covers.
## Self-Check: PASSED
- `src/lib/instanceStore.ts` - FOUND, contains `lastUsedAt: string`
- `src/app/api/me/instances/route.ts` - FOUND, uses `getOrCreateMarketplaceUser`
- `src/lib/instanceValidation.ts` - FOUND, exports `validateInstanceUrl`
- `src/lib/instanceValidation.spec.ts` - FOUND, 8 `it(` blocks
- `src/app/api/instances/link/route.ts` - FOUND, exports `POST`
- `src/app/api/instances/[id]/route.ts` - FOUND, exports `DELETE` and `PATCH`
- `src/app/api/instances/link/route.test.ts` - FOUND, 2 tests pass
- Commits 421a5b8, 269cad1, 9a3fcb7, 20c7ea0, e69ebca - all present in git log
- `npx tsc --noEmit` - no errors
- `pnpm test` - 75 passed, 1 pre-existing failure (oauth, out of scope)
+2
View File
@@ -60,6 +60,7 @@ Agents MUST respect these at all times:
> - **MUST** require explicit user authorization before any state-changing action that isn't simple/safe.
> - **MUST** ask clarifying questions rather than assume when requirements are unclear.
> - **MUST** update `.agents/rules/` files immediately whenever an architectural shift invalidates them.
> - **MUST** close context gaps: when missing/wrong/undocumented context made you err, struggle, or go slow, fix the relevant doc/context (or add a type/guardrail) at its source — or ask the user to update it when it depends on their knowledge. In autonomous mode, log the gap to revisit later. Never fix only the symptom and leave the trap armed for the next contributor.
---
@@ -132,6 +133,7 @@ See `.agents/context/INDEX.md` for the full navigation table. Key files:
| `/five` | Five Whys root cause analysis | `.agents/workflows/five.md` |
| `/stitch-to-nextjs` | Generate UI with Stitch MCP, port into Next.js | `.agents/workflows/stitch-to-nextjs.md` |
| `/branch-cleanup` | **Post-merge teardown** — commit leftovers, delete plan file, remove worktree via worktree-manager | `.agents/skills/branch-cleanup/SKILL.md` |
| `/triage-issue` | Triage a single issue (plugin/feature/bug/question) per `TRIAGE.md`; confirm before any state change | `.agents/workflows/triage-issue.md` |
---
+50
View File
@@ -0,0 +1,50 @@
# Issue Triage Guide
How incoming **plugin requests** and **feature requests** are handled in `silvertakana/worldwideview`. The goal is a consistent, low-effort intake so nothing rots and contributors always know where their idea stands.
Run `/triage-issue <number>` to apply this guide to a specific issue.
## 1. Intake types and labels
Every non-bug request is one of two types:
| Type | What it is | Label | Examples |
|---|---|---|---|
| **Plugin request** | A new data source to render on the globe | `plugin-request` | BirdNET (#148), ISS tracker, AIS ships |
| **Feature request** | A platform capability, not a data source | `enhancement` | GeoJSON editor (#84), ontology layer (#138) |
Community-buildable plugin requests also get `good first issue` + `help wanted`.
## 2. Plugin requests funnel into #4
[Issue #4 - Plugin Wishlist](https://github.com/silvertakana/worldwideview/issues/4) is the **single pinned funnel** for plugin ideas. When a `[PLUGIN]` issue arrives:
1. **Vet the data source.** Is there a free, public API? Check rate limits and CORS. The `plugin-researcher` agent does this in about a minute.
2. **If viable:** add it as a checklist line in #4, label the standalone `plugin-request` + `good first issue` + `help wanted`, then close the standalone with a note: "Tracked in the Plugin Wishlist #4." This keeps one canonical list instead of scattered duplicates.
3. **If not viable** (no free API, paywalled, or geofenced - e.g. aviation/OpenSky in #149): close with the reason stated, so nobody re-opens the same dead end.
## 3. Feature requests stay open as tracking threads
1. Label `enhancement`.
2. Add a one-line entry to the `.planning` ROADMAP backlog (shared root, see `WWV_SHARED_PLANNING`).
3. Leave the issue **open** as the canonical tracking thread. Reply with status, but **promise no dates**.
## 4. The build / do-not-build rule
Only build a plugin yourself (or kick off the `/plugin-new` pipeline) when **all three** hold:
1. **Free API exists** - no paywall, usable rate limits.
2. **Renders something meaningful** - points, paths, or regions on the globe, not just a number.
3. **Fits the demo** - relevant to the live `demo` edition, not a niche one-off.
If any one fails, it lives in the wishlist (#4) for community contributors. The same three-part test is why aviation was pulled from the demo (#149): the only free API was unreliable.
## 5. Quick reference
```
[PLUGIN] issue -> vet API -> viable? yes: add to #4, label, close standalone
no: close with reason
[FEATURE] issue -> label enhancement -> add to ROADMAP backlog -> keep open
bug -> reproduce -> label bug -> fix or route to debugger agent
question -> answer -> close
```
+126
View File
@@ -0,0 +1,126 @@
# Production Infrastructure Checklist
Actions an operator must apply in Coolify (or equivalent) before public launch.
Complete every item and verify the /api/health response before opening traffic.
---
## 1. AUTH_SECRET
- [ ] Generate a high-entropy secret (minimum 32 bytes):
```bash
openssl rand -hex 32
```
- [ ] Set it as `AUTH_SECRET` on the `wwv` service. This value MUST be distinct from
`API_KEY_HMAC_SECRET`. The app fails closed (auth broken) if this is unset.
---
## 2. Redis
- [ ] Generate a Redis password:
```bash
openssl rand -hex 32
```
- [ ] Set `REDIS_PASSWORD` on both the `wwv` and `wwv-redis` services to this value.
- [ ] For a co-located `wwv-redis`: the compose default uses this password automatically
via `REDIS_URL=redis://:<password>@wwv-redis:6379`. No further URL override is needed.
- [ ] For a managed Redis provider (e.g. Upstash, Redis Cloud): set `REDIS_URL` to the
provider's TLS endpoint instead:
```
REDIS_URL=rediss://:<password>@<host>:<port>
```
Use `rediss://` (double-s) for TLS. Remove the co-located `wwv-redis` service when
using a managed provider.
- [ ] Verify Redis is reachable: `GET /api/health` should return `200` with
`"redis": "ok"` (not `"degraded"`).
**What breaks without Redis:** MCP sessions, globe command queue, geocode cache,
all per-user and global rate limiters, and API key session tracking silently no-op
or degrade. The app stays up but MCP data tools report errors and OSM rate limits
are unenforceable.
---
## 3. Data Engine REST URL
- [ ] Set `WWV_DATA_ENGINE_URL` on the `wwv` service to the engine's REST base URL.
This is the HTTP base (scheme + host + port). Do NOT include the `/stream` path:
```
# Correct: REST base only
WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002
# Wrong: do not include /stream
# WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002/stream
```
The engine's published REST port is **5002** (maps to internal port 5000 in
`deploy/production/docker-compose.engine.yml`).
Replace `<engine-host-ip>` with the actual engine host IP or hostname visible from
the `wwv` container.
- [ ] If the app and engine containers share a Docker network, use the service name:
```
WWV_DATA_ENGINE_URL=http://wwv-data-engine:5000
```
- [ ] Verify reachability: `GET /api/health` should return `"engine": "ok"`.
A value of `"degraded"` means the URL is wrong or the engine is not running.
**What breaks without this:** All MCP data query tools (e.g. `query_plugin_data`)
report "engine unreachable" and return no data.
---
## 4. API Key HMAC Secret
- [ ] Generate a high-entropy secret (minimum 32 bytes):
```bash
openssl rand -hex 32
```
- [ ] Set it as `API_KEY_HMAC_SECRET` on the `wwv` service. This value MUST be
distinct from `AUTH_SECRET`. They serve different cryptographic purposes.
- [ ] cloud and demo editions fail closed without this value. The app will refuse to
issue or validate API keys, blocking all MCP authentication.
---
## 5. Trusted IP Header (Cloudflare / CDN)
- [ ] If a CDN or second reverse proxy (e.g. Cloudflare) sits in front of your
Nginx/Traefik reverse proxy, set:
```
WWV_TRUSTED_IP_HEADER=cf-connecting-ip
```
Without this, all clients share the proxy's IP address and collapse into a single
rate-limit bucket. One user's burst exhausts the quota for all users.
- [ ] If you are NOT behind Cloudflare, leave `WWV_TRUSTED_IP_HEADER` unset (the
default reads from `x-forwarded-for` via `x-real-ip`).
- [ ] Verify the correct client IP is visible in request logs or the
`X-Client-IP` debug header (if enabled) after applying the setting.
---
## 6. Health Check Semantics
Configure your uptime monitor or Coolify health check against `GET /api/health`.
| Response | Meaning | Action required |
|---|---|---|
| `503` | Database or required config broken | Page on-call immediately |
| `200` with any `"degraded"` field | Redis or engine unreachable | Investigate; MCP features are impaired but core app is up |
| `200` all `"ok"` | Fully healthy | No action |
Recommended alert rule: alert on any `503` immediately; alert on `200` degraded
after 5 consecutive checks (transient restarts are normal).
---
## Verification Sequence
Run these checks in order after applying all settings:
1. `GET /api/health` returns `200` with all fields `"ok"`.
2. Sign in as an admin user, generate an MCP API key, and confirm the key is issued
(cloud/demo: requires `API_KEY_HMAC_SECRET`).
3. Run `geocode_location({ query: "Paris" })` via the MCP endpoint and confirm
results are returned (requires Redis + Nominatim reachability).
4. Run `query_plugin_data` for a live plugin and confirm data is returned (requires
`WWV_DATA_ENGINE_URL`).
+43 -3
View File
@@ -6,7 +6,32 @@ services:
POSTGRES_PASSWORD: password
POSTGRES_DB: postgres
ports:
- "5432:5432"
# Bound to loopback only so Postgres is not reachable from the host network.
# The app service reaches db via the internal Docker network.
- "127.0.0.1:5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
interval: 5s
timeout: 5s
retries: 5
start_period: 30s
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
# Remove this service and the depends_on entry below when using a managed Redis
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
wwv-redis:
image: redis:7-alpine
restart: unless-stopped
command: redis-server --requirepass ${REDIS_PASSWORD:-}
environment:
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
volumes:
- wwv-redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
interval: 5s
timeout: 3s
retries: 5
wwv-cloud:
build:
@@ -21,7 +46,16 @@ services:
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
# The app fails closed (auth broken) if this is unset.
AUTH_SECRET: ${AUTH_SECRET}
# Redis session/cache/rate-limit store.
# Operators using a managed Redis should set REDIS_URL=rediss://:<password>@<host>:6380 in .env.
REDIS_URL: "redis://:${REDIS_PASSWORD}@wwv-redis:6379"
REDIS_PASSWORD: ${REDIS_PASSWORD}
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
# Set to the actual engine host IP/hostname visible from this container.
WWV_DATA_ENGINE_URL: ${WWV_DATA_ENGINE_URL:-http://<engine-host-ip>:5002}
ports:
- "3001:3000"
labels:
@@ -31,7 +65,10 @@ services:
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
depends_on:
- db
db:
condition: service_healthy
wwv-redis:
condition: service_healthy
traefik:
image: traefik:v3.0
@@ -45,3 +82,6 @@ services:
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
volumes:
wwv-redis-data:
+33 -2
View File
@@ -10,16 +10,29 @@ services:
- path: .env
required: false
environment:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
# The app fails closed (auth broken) if this is unset.
- "AUTH_SECRET=${AUTH_SECRET}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
# Provide the explicit public or host IP of the data engine for the frontend to use
# Provide the explicit public or host IP of the data engine for the frontend to use.
- "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=http://192.168.68.69:5002/stream"
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
# Default assumes the engine runs on the same host, published on port 5002.
# Operators using a separate engine host must override to http://<engine-host>:5002
- "WWV_DATA_ENGINE_URL=${WWV_DATA_ENGINE_URL:-http://192.168.68.69:5002}"
# Redis session/cache/rate-limit store.
# Operators using a managed Redis (e.g. Upstash) should set REDIS_URL to their
# rediss:// endpoint in .env and remove the wwv-redis service and depends_on below.
- "REDIS_URL=redis://:${REDIS_PASSWORD}@wwv-redis:6379"
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
restart: unless-stopped
depends_on:
db:
condition: service_healthy
wwv-redis:
condition: service_healthy
db:
image: postgres:15-alpine
@@ -39,6 +52,24 @@ services:
retries: 5
start_period: 60s
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
# Remove this service and the depends_on entry above when using a managed Redis
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
wwv-redis:
image: redis:7-alpine
restart: unless-stopped
command: redis-server --requirepass ${REDIS_PASSWORD:-}
environment:
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
volumes:
- wwv-redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
interval: 5s
timeout: 3s
retries: 5
volumes:
wwv-data:
postgres-data:
wwv-redis-data:
+97
View File
@@ -0,0 +1,97 @@
# Reusable compose for plugin smoke CI (consumed by wwv-plugins repo).
#
# Boots a full stack with a STUB seeder that emits known-good GeoEntity[]
# data under the plugin-under-test's id. This isolates "is the frontend
# wiring correct" from "is the real backend healthy" — a broken real seeder
# cannot fail plugin CI.
#
# ─── Scope boundary (what THIS compose does vs what the workflow does) ───
#
# This compose only boots services. The consuming workflow's Playwright
# `globalSetup` is responsible for:
# 1. Inserting the test user into `users` (for NextAuth credentials login)
# 2. Inserting the `InstalledPlugin` row with the plugin's manifest JSON
# (entry URL → http://localhost:3000/plugins-local/<PLUGIN_ID>/frontend.mjs)
# 3. UI login → save storageState.json
# 4. Running the smoke spec
#
# Reuse the pattern from worldwideview/tests/global.setup.ts. DB migrations
# are handled automatically by the wwv-app entrypoint at container start.
#
# ─── Stub seeder source ───
#
# The stub seeder is baked into the `wwv-data-engine:ci` image at
# /app/seeders/stub (see wwv-data-engine/Dockerfile.ci). The compose only needs
# to set STUB_PLUGIN_ID — no volume mount, so a consumer repo can download just
# this YAML and run it without the worldwideview source tree present.
#
# Expected env vars from consuming workflow:
# PLUGIN_ID — kebab-case id of the plugin under test (e.g. "aviation")
# PLUGIN_BUNDLE_DIR — host path to the plugin's compiled dist/ (mounted into wwv-app)
# CI_IMAGE_TAG — image tag to pull (default: ci)
services:
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
interval: 3s
timeout: 3s
retries: 20
wwv-redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 3s
timeout: 3s
retries: 10
wwv-data-engine:
image: ghcr.io/silvertakana/wwv-data-engine:${CI_IMAGE_TAG:-ci}
command: ["node", "dist/server.js"]
ports:
- "5000:5000"
environment:
PORT: 5000
REDIS_URL: redis://wwv-redis:6379
SEEDERS_DIR: /app/seeders
DB_PATH: /tmp/engine.db
# Stub seeder reads the target plugin id from this env var
STUB_PLUGIN_ID: ${PLUGIN_ID}
WWV_SKIP_WS_AUTH: "true"
NODE_ENV: ci
# No volume mount: the stub seeder is baked into the :ci image at
# /app/seeders/stub, so the engine discovers it as id "stub" with no host
# path dependency.
depends_on:
wwv-redis:
condition: service_healthy
wwv-app:
image: ghcr.io/silvertakana/worldwideview:${CI_IMAGE_TAG:-ci}
ports:
- "3000:3000"
environment:
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
DATABASE_URL: postgresql://postgres:postgres@db:5432/worldwideview?schema=public
NEXT_PUBLIC_WWV_EDITION: local
NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL: http://localhost:5000
volumes:
# Mount the plugin's compiled bundle so the app can load it locally
- ${PLUGIN_BUNDLE_DIR}:/app/public/plugins-local/${PLUGIN_ID}:ro
depends_on:
db:
condition: service_healthy
wwv-data-engine:
condition: service_started
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1"]
interval: 5s
timeout: 5s
retries: 30
start_period: 30s
+64
View File
@@ -0,0 +1,64 @@
# Reusable compose for seeder smoke CI (consumed by wwv-seeders-* repos).
#
# Runs the REAL seeder against a MOCK upstream HTTP server. This isolates
# "is the seeder code correct" from "is the upstream provider up" — a
# NASA FIRMS / OpenSky / Overpass outage cannot fail seeder CI.
#
# Expected env vars from consuming workflow:
# SEEDER_NAME — kebab-case name of the seeder under test
# SEEDER_DIST_DIR — host path to the seeder's compiled dist/ + package.json
# FIXTURE_DIR — host path to the seeder's __fixtures__ directory
# CI_IMAGE_TAG — image tag to pull (default: ci)
#
# Plus any seeder-specific upstream env vars (e.g. OPENSKY_API_BASE)
# already exported in the workflow shell, all pointing at http://mock-upstream:8080
services:
wwv-redis:
image: redis:7-alpine
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 3s
timeout: 3s
retries: 10
mock-upstream:
build:
context: ./mock-upstream
volumes:
- ${FIXTURE_DIR}:/fixtures:ro
environment:
FIXTURE_DIR: /fixtures
PORT: 8080
healthcheck:
test: ["CMD-SHELL", "wget -q -O- http://localhost:8080/__health || exit 1"]
interval: 5s
timeout: 3s
retries: 5
wwv-data-engine:
image: ghcr.io/silvertakana/wwv-data-engine:${CI_IMAGE_TAG:-ci}
command: ["node", "dist/server.js"]
ports:
- "5000:5000"
volumes:
# Mount ONLY this seeder under /app/seeders/community/<name> — isolates
# the test from any cross-seeder dependencies or collisions.
- ${SEEDER_DIST_DIR}:/app/seeders/community/${SEEDER_NAME}:ro
environment:
PORT: 5000
REDIS_URL: redis://wwv-redis:6379
SEEDERS_DIR: /app/seeders
DB_PATH: /tmp/engine.db
# Seeder-specific upstream env vars are injected by the consuming
# workflow via `environment:` overrides or `env_file:`.
env_file:
- path: ./.seeder.env
required: false
depends_on:
wwv-redis:
condition: service_healthy
mock-upstream:
condition: service_healthy
+5
View File
@@ -0,0 +1,5 @@
FROM node:22-alpine
WORKDIR /mock
COPY server.mjs ./
EXPOSE 8080
CMD ["node", "/mock/server.mjs"]
+48
View File
@@ -0,0 +1,48 @@
# mock-upstream
Tiny HTTP server used in CI to stand in for upstream data APIs (OpenSky, NASA FIRMS, Overpass, etc.) so seeder CI can run hermetically without real API keys or network flakiness.
## How it works
Mount a fixture directory at `/fixtures`. The directory must contain a `routes.json` mapping request paths → fixture filenames:
```json
{
"/api/states/all": "opensky-states.json",
"/api/v2/flights": "flights.json"
}
```
When the server receives `GET /api/states/all`, it serves the contents of `/fixtures/opensky-states.json`.
## Env vars
| Var | Default | Purpose |
|---|---|---|
| `FIXTURE_DIR` | `/fixtures` | Directory mounted from the seeder repo |
| `ROUTES_FILE` | `${FIXTURE_DIR}/routes.json` | Override the routes manifest path |
| `PORT` | `8080` | Listen port |
## Per-seeder convention
Each seeder ships its own `__fixtures__/` folder next to `src/`:
```
wwv-seeders-community/aviation/
├── src/index.ts
└── __fixtures__/
├── routes.json
└── opensky-states.json
```
In CI compose, that folder is mounted into the mock-upstream container at `/fixtures` for the duration of the seeder smoke test.
## Architectural contract
Seeders MUST read upstream URLs from documented env vars with the production URL as the default, e.g.:
```ts
const UPSTREAM = process.env.OPENSKY_API_BASE ?? "https://opensky-network.org";
```
The CI compose then overrides `OPENSKY_API_BASE=http://mock-upstream:8080`. Without this convention, CI mocking is impossible — hardcoded URLs cannot be intercepted.
+61
View File
@@ -0,0 +1,61 @@
import { createServer } from "node:http";
import { readFileSync, existsSync } from "node:fs";
import { resolve, join } from "node:path";
const FIXTURE_DIR = process.env.FIXTURE_DIR ?? "/fixtures";
const PORT = Number(process.env.PORT ?? 8080);
const ROUTES_FILE = process.env.ROUTES_FILE ?? join(FIXTURE_DIR, "routes.json");
if (!existsSync(ROUTES_FILE)) {
console.error(`[mock-upstream] no routes file at ${ROUTES_FILE}`);
process.exit(1);
}
let routes;
try {
routes = JSON.parse(readFileSync(ROUTES_FILE, "utf8"));
} catch (err) {
console.error(`[mock-upstream] failed to parse ${ROUTES_FILE}:`, err);
process.exit(1);
}
console.log(`[mock-upstream] loaded ${Object.keys(routes).length} routes from ${ROUTES_FILE}`);
createServer((req, res) => {
const path = req.url?.split("?")[0] ?? "/";
if (path === "/__health") {
res.statusCode = 200;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "ok" }));
return;
}
const file = routes[path];
if (!file) {
console.warn(`[mock-upstream] 404 ${req.method} ${path}`);
res.statusCode = 404;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ error: "no fixture", path }));
return;
}
const filePath = resolve(FIXTURE_DIR, file);
if (!filePath.startsWith(resolve(FIXTURE_DIR))) {
res.statusCode = 400;
res.end("bad fixture path");
return;
}
try {
const body = readFileSync(filePath);
res.statusCode = 200;
res.setHeader("content-type", file.endsWith(".json") ? "application/json" : "text/plain");
res.end(body);
console.log(`[mock-upstream] 200 ${req.method} ${path} -> ${file}`);
} catch (err) {
console.error(`[mock-upstream] 500 ${req.method} ${path}:`, err);
res.statusCode = 500;
res.end("fixture read failed");
}
}).listen(PORT, () => {
console.log(`[mock-upstream] listening on :${PORT}`);
});
+55
View File
@@ -0,0 +1,55 @@
// CI-only stub seeder. Emits a known-good GeoEntity[] payload under the
// plugin id provided via STUB_PLUGIN_ID. Used by plugin-CI to isolate
// frontend wiring from real backend health.
//
// NOTE: This bypasses ADR-0002's compile-time name rule on purpose — the
// data engine reads `name` once at load time, so an env-driven name is
// fine in CI. Do NOT copy this pattern into real seeders.
const pluginId = process.env.STUB_PLUGIN_ID;
// When unconfigured (e.g. seeder-CI, where this stub is baked into the shared
// :ci image but unused), export a nameless module so the seeder-loader skips
// it instead of crashing the engine.
//
// Uses the interval+fetch seeder contract: fetch() RETURNS the array and the
// scheduler auto-wraps it into a snapshot stored under the seeder id. The
// cron+fn contract would require the engine-internal setLiveSnapshot, which is
// NOT exposed on the seeder ctx (ctx is only { redis }).
function makeEntities() {
const now = new Date().toISOString();
return [
{
id: `${pluginId}-stub-1`,
pluginId,
latitude: 0,
longitude: 0,
altitude: 0,
timestamp: now,
label: "Stub entity 1",
properties: { source: "ci-stub" },
},
{
id: `${pluginId}-stub-2`,
pluginId,
latitude: 10,
longitude: 10,
altitude: 0,
timestamp: now,
label: "Stub entity 2",
properties: { source: "ci-stub" },
},
];
}
export default pluginId
? {
name: pluginId,
interval: 10000,
fetch: async () => {
const entities = makeEntities();
console.log(`[stub-seeder] emitting ${entities.length} entities for ${pluginId}`);
return entities;
},
}
: {};
+7
View File
@@ -0,0 +1,7 @@
{
"name": "stub-seeder",
"version": "0.1.0",
"type": "module",
"main": "dist/index.mjs",
"private": true
}
+206
View File
@@ -0,0 +1,206 @@
# MCP Quickstart: Connect an AI Agent to WorldWideView
Connect Claude Desktop, Cursor, or any MCP-compatible client to your own WorldWideView
globe. MCP is available in the **local (self-hosted) edition** that you run yourself.
> Cloud edition (hosted at worldmonitor.app) is not yet available. When it launches, the
> same steps apply but you will use your cloud account and the cloud endpoint instead of
> localhost. See "Cloud edition (coming soon)" at the end.
---
## Prerequisites
- The WorldWideView repository, run locally (this is the **local edition**, the default).
- Node.js 20+, pnpm 9+, and Docker (Docker is needed for Postgres, and for Redis + the
data engine if you want command tools and live data).
- An MCP-compatible client: Claude Desktop, Cursor, VS Code with an MCP extension, or any
client that supports the Streamable HTTP MCP transport.
---
## Step 1: Install and configure
From the repository root:
```bash
pnpm install
pnpm setup # generates AUTH_SECRET and your local .env (required for API keys to work)
```
`pnpm setup` writes a random `AUTH_SECRET` into `.env`. In the local edition that same
secret signs your MCP API keys, so this step is required before key generation will work.
The edition defaults to `local` (`NEXT_PUBLIC_WWV_EDITION=local`).
---
## Step 2: Run the app
Two ways to run it, depending on which tools you need:
```bash
pnpm dev # frontend + Postgres only. Read/query tools work. Command tools and live
# data do NOT (no Redis, no data engine).
pnpm dev:all # frontend + data engine + Redis (via Docker Compose). Everything works:
# read tools, command tools (open-tab control), geocoding, and live data.
```
Use `pnpm dev:all` for the full MCP experience. The app comes up at
**http://localhost:3000** (it will pick another port if 3000 is taken; check the startup log).
| You want... | Run | Why |
|---|---|---|
| `search_entities`, `get_plugin_data`, `list_available_plugins`, favorites | `pnpm dev` is enough | served from Postgres + the local data-source registry |
| `geocode_location`, command tools (`pan_globe`, `fly_to`, `toggle_layer`, ...) | `pnpm dev:all` | need Redis (sessions, command queue, geocode cache) |
| Live plugin data on the globe and in data tools | `pnpm dev:all` | needs the data engine |
---
## Step 3: Sign in and generate an API key
1. Open **http://localhost:3000** and sign in. On a first run, create the initial account
via the app's setup flow (see the project README for first-user setup).
2. Open **Settings -> API and MCP Access**.
3. Click **Generate new key**, give it a name, and **copy the key immediately** (it is shown
only once). Your key looks like `wwv_abc123.<long-secret>`.
The same panel ("Connect your agent") shows a ready-to-paste config block with your local
endpoint already filled in (`http://localhost:3000/api/mcp`).
---
## Step 4: Add the MCP server to your client
Paste this into your client's MCP configuration (e.g. `claude_desktop_config.json` for
Claude Desktop, or the Cursor MCP settings). The endpoint is your local app:
```json
{
"mcpServers": {
"worldwideview": {
"url": "http://localhost:3000/api/mcp",
"headers": {
"Authorization": "Bearer wwv_<your-key-here>"
}
}
}
}
```
Replace `wwv_<your-key-here>` with the key from step 3. The key goes in the `Authorization`
header, never in the URL.
---
## Step 5: Restart your client and verify
Restart your MCP client (Claude Desktop needs a full app restart; Cursor reloads
automatically). Ask the agent: "List the available WorldWideView plugins" - it should call
`list_available_plugins`. If you started with `pnpm dev:all` and have plugins streaming, you
will see them; otherwise see the troubleshooting notes about `engine_unreachable` /
`no_active_plugins` below (those mean the connection works but the engine is down or idle).
---
## Two capability tiers
WorldWideView MCP tools split into two tiers based on whether a browser globe session is
required.
### Read / query tools (no open tab required)
These run server-side and return data using only your API key. You do not need the globe open.
| Tool | What it does |
|---|---|
| `search_entities` | Search entities by name across active plugins |
| `get_entities_in_region` | Find entities inside a lat/lng bounding box |
| `get_entity_details` | Get full details for one entity |
| `get_plugin_data` | Get the current snapshot of all entities for a plugin |
| `list_available_plugins` | List streaming plugins and their status |
| `geocode_location` | Resolve a place name or address to coordinates (needs Redis) |
| `save_favorite` | Bookmark an entity |
| `list_favorites` | List your bookmarks |
| `update_favorite` | Rename or annotate a bookmark |
| `remove_favorite` | Delete a bookmark |
| `get_plugin_filters` | List filterable fields a plugin declares |
### Command / control tools (open globe tab required)
These control the live 3D globe in your browser. **You must keep a WorldWideView browser tab
open and signed in as the same account.** Without an open tab, the command is accepted but has
no visible effect and the tool returns `"no active globe session to control"`. These also need
Redis (run `pnpm dev:all`).
| Tool | What it does |
|---|---|
| `pan_globe` | Fly the camera to a coordinate |
| `fly_to` | Fly the camera to a geocoded coordinate or bounding box |
| `focus_entity` | Centre the camera on a known entity |
| `toggle_layer` | Enable or disable a plugin data layer |
| `set_timeline` | Set playback time, window, or mode |
| `set_filter` | Apply filters to a plugin's live layer |
| `clear_filter` | Clear filters on one or all plugins |
---
## Recommended agent prompt
Paste this into your agent's system prompt to give it immediate context:
```
You have access to WorldWideView (WWV) via MCP -- a live 3D globe streaming real-world data
(aviation, shipping, earthquakes, weather, and more). Use the MCP tools to query entities,
move the camera, toggle layers, and filter data. Command tools require the user to have the
WWV globe open in a browser tab. Read/query tools work without a browser tab.
```
---
## Troubleshooting
**"no active globe session to control"**
A command tool (pan_globe, fly_to, toggle_layer, etc.) ran but no globe tab is open. Open
http://localhost:3000 in a browser tab, sign in as the same account that owns the API key,
and keep the tab open while you use the agent. Also make sure you started with `pnpm dev:all`
(command tools need Redis).
**"engine_unreachable" from list_available_plugins**
The data engine is not running or `WWV_DATA_ENGINE_URL` is not set. Start it with
`pnpm dev:all`. The MCP connection itself is working.
**"no_active_plugins" from list_available_plugins**
The data engine is up but no plugins are currently streaming. Enable a plugin from the
Plugins panel in the globe app.
**401 Unauthorized**
Your API key is invalid or revoked, or `pnpm setup` was never run (no `AUTH_SECRET`).
Confirm `.env` has `AUTH_SECRET`, then generate a fresh key in Settings > API and MCP Access.
**Tools do not appear in my client**
Restart the client after editing the config file. For Claude Desktop, a full app
quit-and-relaunch is required.
---
## Cloud edition (coming soon)
A hosted cloud edition is planned at worldmonitor.app. It is **not yet available**. When it
launches, the flow is the same as above except:
- You sign in to your cloud account at worldmonitor.app instead of running the app locally.
- The MCP endpoint is `https://api.worldmonitor.app/api/mcp` instead of `http://localhost:3000/api/mcp`.
- Infrastructure (Redis, the data engine, secrets) is operated for you, so there is no
`pnpm setup` / `pnpm dev:all` step.
Everything else - generating a key, the Authorization header, the two capability tiers, and
the open-tab requirement for command tools - is identical.
---
## Next steps
- See [plugin-filter-guide.md](plugin-filter-guide.md) to learn how to use `get_plugin_filters`
and `set_filter` to filter live plugin data.
- See [plugin-quickstart.md](plugin-quickstart.md) to build your own data plugin.
+26
View File
@@ -20,6 +20,32 @@ pnpm dev
4. The marketplace load API auto-discovers them in dev mode
5. Everything in this directory is gitignored
## Property Conventions
Use the SDK property tag helpers to give the Intel panel rich rendering for dates, URLs, images, and video. Without them, values display as plain text.
```ts
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
properties: {
// Dates — pass ISO 8601 strings
updated_at: dtProp(item.timestamp ?? null),
// External links
source_url: urlProp(item.url ?? null),
// Images
preview: imageProp(item.image_url ?? null),
// Video/streams
live_stream: videoProp(item.stream_url ?? null),
// Plain values — no helper needed
name: item.name,
count: item.count,
}
```
All helpers are null-safe — passing `null` or `undefined` returns `null`, which the panel skips.
See the [SDK README](../worldwideview/packages/wwv-plugin-sdk/README.md) for the full reference.
## Publishing to NPM
When your plugin is ready to share, you can publish it directly to NPM from the root directory:
+18 -17
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.48.4",
"version": "2.48.30",
"private": true,
"type": "module",
"packageManager": "[email protected]",
@@ -32,37 +32,37 @@
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@prisma/client-runtime-utils": "7.8.0",
"@sentry/nextjs": "^10.54.0",
"@sentry/nextjs": "^10.56.0",
"@supabase/ssr": "^0.10.3",
"@supabase/supabase-js": "^2.106.2",
"@supabase/supabase-js": "^2.107.0",
"@types/pg": "^8.20.0",
"@worldwideview/wwv-lib-aviation": "workspace:*",
"@worldwideview/wwv-lib-incidents": "workspace:*",
"@worldwideview/wwv-plugin-sdk": "workspace:*",
"bcryptjs": "^3.0.3",
"cesium": "^1.141.0",
"cesium": "^1.142.0",
"cheerio": "^1.2.0",
"hls.js": "^1.6.16",
"insecam-api": "^0.0.3",
"ioredis": "^5.4.1",
"jose": "^6.2.3",
"lucide-react": "^1.17.0",
"next": "16.2.6",
"next": "16.2.7",
"next-auth": "^5.0.0-beta.30",
"openid-client": "^6.8.4",
"pg": "^8.21.0",
"prisma": "^7.8.0",
"react": "19.2.6",
"react-dom": "19.2.6",
"react": "19.2.7",
"react-dom": "19.2.7",
"react-player": "^3.4.0",
"resium": "1.21.1",
"resium": "1.22.0",
"satellite.js": "^7.0.1",
"stripe": "^22.2.0",
"tslib": "^2.8.1",
"undici": "^8.3.0",
"ws": "^8.21.0",
"zod": "^4.4.3",
"zustand": "^5.0.13"
"zustand": "^5.0.14"
},
"devDependencies": {
"@eslint/compat": "^2.1.0",
@@ -78,16 +78,16 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.60.0",
"@typescript-eslint/parser": "^8.60.0",
"@typescript-eslint/eslint-plugin": "^8.60.1",
"@typescript-eslint/parser": "^8.60.1",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "4.1.7",
"concurrently": "^9.2.1",
"@vitest/coverage-v8": "4.1.8",
"concurrently": "^10.0.3",
"copy-webpack-plugin": "^14.0.0",
"eslint": "^9",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^18.0.0",
"eslint-config-next": "^16.2.6",
"eslint-config-next": "^16.2.7",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react": "^7.37.5",
@@ -96,9 +96,9 @@
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tree-kill": "^1.2.2",
"tsx": "^4.22.3",
"tsx": "^4.22.4",
"typescript": "^5",
"vite": "^8.0.14",
"vite": "^8.0.16",
"vitest": "^4.1.7"
},
"pnpm": {
@@ -107,7 +107,8 @@
"form-data@<2.5.4": "^2.5.5",
"form-data@>=3.0.0 <3.0.4": "^3.0.4",
"form-data@>=4.0.0 <4.0.4": "^4.0.5",
"fast-uri@<3.1.2": "^3.1.2"
"fast-uri@<3.1.2": "^3.1.2",
"vitest@<4.1.0": "^4.1.8"
},
"onlyBuiltDependencies": [
"@prisma/engines",
+55
View File
@@ -0,0 +1,55 @@
# @worldwideview/wwv-ci-probe
CI probe — asserts plugin/seeder integration health for the WorldWideView ecosystem.
Used by the smoke-test workflows in [`wwv-plugins`](https://github.com/silvertakana/wwv-plugins), [`wwv-seeders-community`](https://github.com/silvertakana/wwv-seeders-community), and [`wwv-seeders-private`](https://github.com/silvertakana/wwv-seeders-private).
## Install
```bash
# Via npx (recommended in CI)
npx --yes @worldwideview/wwv-ci-probe <subcommand>
# Or as a dev dependency
pnpm add -D @worldwideview/wwv-ci-probe
```
## Subcommands
### `seeder <name>`
Polls Redis for `data:<name>:live` and validates the payload shape. Accepts `GeoEntity[]`, `{ items: [...] }`, or `{ <key>: [...] }`. Use this in seeder CI after booting the data engine against a mock upstream.
```bash
wwv-probe seeder aviation --redis redis://localhost:6379 --timeout 60000
```
### `ws <name>`
Connects to the data engine's `/stream` WebSocket and waits for a `data` message matching the given `pluginId`. Validates the same payload shapes as `seeder`. Use this when you want to assert the engine is broadcasting (not just persisting).
```bash
wwv-probe ws aviation --url ws://localhost:5000/stream --timeout 30000
```
### `id-contract <seederDist>`
Statically validates that a compiled seeder exports a kebab-case `name` (ADR-0002). Optionally checks the name matches an expected id.
```bash
wwv-probe id-contract ./dist/index.mjs --expect aviation
```
## Plugin smoke testing — not in this probe
The probe deliberately does **not** include a `plugin` subcommand. Plugin smoke tests need to exercise the full Next.js + Cesium frontend (plugin bundle loading, `mapWebsocketPayload`, DataBus wiring), which requires a real browser via Playwright.
The `wwv-plugins` repo writes its own Playwright spec for that — it reuses the auth bootstrap pattern from `worldwideview/tests/global.setup.ts` (insert test user + `InstalledPlugin` row, UI login to capture `storageState.json`, then run the plugin-toggle smoke).
Keeping that logic inside `wwv-plugins` avoids coupling this probe to `@playwright/test` and to the specific UI structure of the Next.js frontend.
## Exit codes
- `0` — assertion passed within the timeout
- `1` — assertion failed (timeout exceeded, invalid payload shape, or contract violation)
- `2` — fatal probe error (unhandled exception)
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@worldwideview/wwv-ci-probe",
"version": "0.1.0",
"type": "module",
"description": "CI probe — asserts plugin/seeder integration health (ADR-0002, WS payload contract, Redis snapshots)",
"main": "dist/index.js",
"bin": {
"wwv-probe": "dist/index.js"
},
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"clean": "rm -rf dist",
"prepublishOnly": "tsc"
},
"dependencies": {
"commander": "^14.0.3",
"ioredis": "^5.4.1",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^25.9.1",
"@types/ws": "^8.5.13",
"typescript": "^5.0.0"
}
}
+51
View File
@@ -0,0 +1,51 @@
import { pathToFileURL } from "node:url";
import { resolve } from "node:path";
const KEBAB_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
/**
* Validates ADR-0002: a seeder's exported `name` field must be kebab-case
* and (optionally) match an expected plugin id.
*
* @returns true if the contract holds; false (with stderr explanation) otherwise.
*/
export async function probeIdContract(opts: {
seederDist: string;
expectId?: string;
}): Promise<boolean> {
const absPath = resolve(opts.seederDist);
let mod: any;
try {
mod = await import(pathToFileURL(absPath).href);
} catch (err) {
console.error(`[id-contract] failed to import ${absPath}:`, err);
return false;
}
const seeder = mod.default ?? mod;
if (!seeder || typeof seeder !== "object") {
console.error(`[id-contract] ${absPath} has no default export (or export is not an object)`);
return false;
}
const name = seeder.name;
if (typeof name !== "string" || name.length === 0) {
console.error(`[id-contract] seeder default export missing required string field 'name'`);
return false;
}
if (!KEBAB_RE.test(name)) {
console.error(`[id-contract] seeder name "${name}" is not valid kebab-case (must match ${KEBAB_RE})`);
return false;
}
if (opts.expectId && opts.expectId !== name) {
console.error(
`[id-contract] seeder name "${name}" does not match expected plugin id "${opts.expectId}" (ADR-0002 violation)`,
);
return false;
}
console.log(`[id-contract] OK — seeder name "${name}"${opts.expectId ? ` matches expected id` : ""}`);
return true;
}
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env node
import { Command } from "commander";
import { probeSeeder } from "./seeder.js";
import { probeWs } from "./ws.js";
import { probeIdContract } from "./id-contract.js";
const program = new Command();
program
.name("wwv-probe")
.description("WorldWideView CI probe — asserts plugin/seeder integration health")
.version("0.1.0");
program
.command("seeder")
.description("Wait for Redis key data:<name>:live to be populated and validate payload shape")
.argument("<name>", "Canonical plugin id (kebab-case)")
.option("--redis <url>", "Redis URL", "redis://localhost:6379")
.option("--timeout <ms>", "Timeout in milliseconds", "60000")
.action(async (name: string, opts: { redis: string; timeout: string }) => {
const ok = await probeSeeder({
name,
redisUrl: opts.redis,
timeoutMs: Number(opts.timeout),
});
process.exit(ok ? 0 : 1);
});
program
.command("ws")
.description("Connect to engine /stream and wait for a data payload for the given pluginId")
.argument("<name>", "Canonical plugin id (kebab-case)")
.option("--url <url>", "WebSocket URL", "ws://localhost:5000/stream")
.option("--timeout <ms>", "Timeout in milliseconds", "30000")
.action(async (name: string, opts: { url: string; timeout: string }) => {
const ok = await probeWs({
name,
wsUrl: opts.url,
timeoutMs: Number(opts.timeout),
});
process.exit(ok ? 0 : 1);
});
program
.command("id-contract")
.description("Verify seeder dist exports a kebab-case name matching the expected plugin id (ADR-0002)")
.argument("<seederDist>", "Path to compiled seeder dist/index.mjs")
.option("--expect <id>", "Expected plugin id (if omitted, only validates kebab-case)")
.action(async (seederDist: string, opts: { expect?: string }) => {
const ok = await probeIdContract({
seederDist,
expectId: opts.expect,
});
process.exit(ok ? 0 : 1);
});
program.parseAsync().catch((err) => {
console.error("[wwv-probe] fatal:", err);
process.exit(2);
});
@@ -0,0 +1,38 @@
import { describe, it, expect } from "vitest";
import { validatePayloadValue, validatePayloadString } from "./payloadShape.js";
describe("validatePayloadValue", () => {
it("accepts a non-empty GeoEntity array", () => {
expect(validatePayloadValue([{ id: "a" }])).toEqual({ ok: true, shape: "geo-entity-array" });
});
it("rejects an empty array", () => {
expect(validatePayloadValue([])).toEqual({ ok: false, reason: "GeoEntity[] is empty" });
});
it("accepts a non-empty items object", () => {
expect(validatePayloadValue({ items: [1] })).toEqual({ ok: true, shape: "items-object" });
});
it("rejects an empty items array", () => {
expect(validatePayloadValue({ items: [] })).toEqual({ ok: false, reason: "items[] is empty" });
});
it("accepts a single named collection", () => {
expect(validatePayloadValue({ quakes: [1, 2] })).toEqual({ ok: true, shape: "named-collection" });
});
it("rejects an object with no array field", () => {
const r = validatePayloadValue({ a: 1, b: 2 });
expect(r.ok).toBe(false);
});
it("rejects a non-object, non-array value", () => {
const r = validatePayloadValue(42);
expect(r.ok).toBe(false);
});
});
describe("validatePayloadString", () => {
it("parses then validates", () => {
expect(validatePayloadString('[{"id":"x"}]')).toEqual({ ok: true, shape: "geo-entity-array" });
});
it("rejects invalid JSON", () => {
const r = validatePayloadString("{not json");
expect(r.ok).toBe(false);
});
});
+59
View File
@@ -0,0 +1,59 @@
/**
* Shared payload-shape validator for the WWV data contract (data-engine-architecture.md §7).
* A valid live payload is one of three non-empty shapes:
* - geo-entity-array: a top-level non-empty array
* - items-object: an object with a non-empty `items` array
* - named-collection: an object whose single array-valued key is non-empty
*/
export type PayloadShape = "geo-entity-array" | "items-object" | "named-collection";
export type PayloadValidation =
| { ok: true; shape: PayloadShape }
| { ok: false; reason: string };
/**
* Validate an already-parsed payload value.
* @param p - parsed JSON value
* @returns ok with the detected shape, or a reason for rejection
*/
export function validatePayloadValue(p: unknown): PayloadValidation {
if (Array.isArray(p)) {
return p.length > 0
? { ok: true, shape: "geo-entity-array" }
: { ok: false, reason: "GeoEntity[] is empty" };
}
if (p && typeof p === "object") {
const obj = p as Record<string, unknown>;
if (Array.isArray(obj.items)) {
return obj.items.length > 0
? { ok: true, shape: "items-object" }
: { ok: false, reason: "items[] is empty" };
}
const arrayKeys = Object.keys(obj).filter((k) => Array.isArray(obj[k]));
if (arrayKeys.length === 1) {
const arr = obj[arrayKeys[0]] as unknown[];
return arr.length > 0
? { ok: true, shape: "named-collection" }
: { ok: false, reason: `${arrayKeys[0]}[] is empty` };
}
return {
ok: false,
reason: `payload object has no recognizable array field (keys: ${Object.keys(obj).join(", ")})`,
};
}
return { ok: false, reason: `payload is neither array nor object (typeof=${typeof p})` };
}
/**
* Parse a raw JSON string, then validate the resulting value's shape.
* @param raw - raw JSON string from Redis
*/
export function validatePayloadString(raw: string): PayloadValidation {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (err) {
return { ok: false, reason: `not valid JSON (${(err as Error).message})` };
}
return validatePayloadValue(parsed);
}
+52
View File
@@ -0,0 +1,52 @@
import { Redis } from "ioredis";
import { validatePayloadString } from "./payloadShape.js";
/**
* Polls Redis for `data:<name>:live` and validates that the seeder produced a
* non-empty payload in one of the three accepted shapes (see
* data-engine-architecture.md §7).
*
* @returns true if a valid payload arrived within the timeout; false otherwise.
*/
export async function probeSeeder(opts: {
name: string;
redisUrl: string;
timeoutMs: number;
}): Promise<boolean> {
const redis = new Redis(opts.redisUrl, { lazyConnect: true, maxRetriesPerRequest: 1 });
const key = `data:${opts.name}:live`;
const deadline = Date.now() + opts.timeoutMs;
const pollIntervalMs = 1000;
try {
await redis.connect();
} catch (err) {
console.error(`[seeder] cannot connect to Redis at ${opts.redisUrl}:`, err);
return false;
}
console.log(`[seeder] waiting for ${key} (timeout ${opts.timeoutMs}ms)`);
while (Date.now() < deadline) {
const raw = await redis.get(key);
if (raw && raw.length > 0) {
const validation = validatePayloadString(raw);
await redis.quit();
if (!validation.ok) {
console.error(`[seeder] payload present but invalid: ${validation.reason}`);
return false;
}
console.log(`[seeder] OK — ${key} populated (shape: ${validation.shape}, bytes: ${raw.length})`);
return true;
}
await sleep(pollIntervalMs);
}
await redis.quit();
console.error(`[seeder] timed out — ${key} never populated within ${opts.timeoutMs}ms`);
return false;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect, afterEach } from "vitest";
import { WebSocketServer } from "ws";
import { probeWs } from "./ws.js";
let server: WebSocketServer | undefined;
afterEach(() => { server?.close(); server = undefined; });
function startEngine(opts: { pluginId: string; requireSubscribe: boolean }) {
server = new WebSocketServer({ port: 0 });
server.on("connection", (sock) => {
sock.send(JSON.stringify({ type: "welcome", engine: "test", plugins: [opts.pluginId] }));
const send = () =>
sock.send(JSON.stringify({ type: "data", pluginId: opts.pluginId, payload: [{ id: "x" }] }));
if (!opts.requireSubscribe) { setInterval(send, 20); return; }
sock.on("message", (raw) => {
const msg = JSON.parse(raw.toString());
if (msg.action === "subscribe" && msg.pluginId === opts.pluginId) send();
});
});
const addr = server.address();
const port = typeof addr === "object" && addr ? addr.port : 0;
return `ws://127.0.0.1:${port}/stream`;
}
describe("probeWs", () => {
it("receives data from a subscribe-required engine (sends subscribe frame)", async () => {
const url = startEngine({ pluginId: "stub", requireSubscribe: true });
const ok = await probeWs({ name: "stub", wsUrl: url, timeoutMs: 3000 });
expect(ok).toBe(true);
});
it("times out (false) when the plugin never produces data", async () => {
const url = startEngine({ pluginId: "other", requireSubscribe: true });
const ok = await probeWs({ name: "stub", wsUrl: url, timeoutMs: 800 });
expect(ok).toBe(false);
});
});
+74
View File
@@ -0,0 +1,74 @@
import WebSocket from "ws";
import { validatePayloadValue } from "./payloadShape.js";
/**
* Connects to the data-engine's /stream WebSocket and resolves when a
* `{ type: "data", pluginId: <name>, payload: ... }` message arrives for the
* given plugin id (see data-engine-architecture.md §7).
*
* Rejects with exit code 1 if no matching payload arrives within the timeout
* — which is the signature of an ADR-0002 id mismatch or a silently-dropped
* object payload.
*/
export async function probeWs(opts: {
name: string;
wsUrl: string;
timeoutMs: number;
}): Promise<boolean> {
return new Promise((resolve) => {
const ws = new WebSocket(opts.wsUrl);
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
console.error(
`[ws] timed out — no data message with pluginId="${opts.name}" in ${opts.timeoutMs}ms ` +
`(check ADR-0002 seeder.name vs plugin id, and that the seeder is producing data)`,
);
ws.terminate();
resolve(false);
}, opts.timeoutMs);
ws.on("open", () => {
// The engine is subscribe-required: it only broadcasts a plugin's data to
// connections that have subscribed to it (websocket.ts broadcastPluginData).
// Auth is bypassed in CI via WWV_SKIP_WS_AUTH=true, so no auth frame is sent.
ws.send(JSON.stringify({ action: "subscribe", pluginId: opts.name }));
console.log(`[ws] connected to ${opts.wsUrl}, subscribed to pluginId="${opts.name}"`);
});
ws.on("message", (raw) => {
let msg: any;
try {
msg = JSON.parse(raw.toString());
} catch {
return;
}
if (msg?.type !== "data" || msg.pluginId !== opts.name) return;
if (settled) return;
const payload = msg.payload;
const valid = validatePayloadValue(payload);
if (!valid.ok) {
console.error(`[ws] received message for "${opts.name}" but payload invalid: ${valid.reason}`);
// Keep waiting — a later message might be valid.
return;
}
settled = true;
clearTimeout(timer);
console.log(`[ws] OK — received valid payload for "${opts.name}" (shape: ${valid.shape})`);
ws.close();
resolve(true);
});
ws.on("error", (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
console.error(`[ws] connection error:`, err);
resolve(false);
});
});
}
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": false
},
"include": ["src/**/*"]
}
+1 -1
View File
@@ -14,7 +14,7 @@
"test": "node --test \"test/**/*.test.mjs\""
},
"dependencies": {
"commander": "^14.0.3",
"commander": "^15.0.0",
"prompts": "^2.4.2"
},
"devDependencies": {
+6 -1
View File
@@ -2,6 +2,11 @@
"name": "@worldwideview/wwv-lib-aviation",
"version": "1.0.2",
"description": "Shared abstract base classes for WorldWideView aviation plugins (commercial, military, specialized)",
"repository": {
"type": "git",
"url": "https://github.com/silvertakana/worldwideview.git",
"directory": "packages/wwv-lib-aviation"
},
"main": "src/index.ts",
"types": "src/index.ts",
"files": [
@@ -16,6 +21,6 @@
"author": "WorldWideView",
"license": "ISC",
"peerDependencies": {
"@worldwideview/wwv-plugin-sdk": "^1.4.10"
"@worldwideview/wwv-plugin-sdk": "workspace:*"
}
}
+6 -1
View File
@@ -2,6 +2,11 @@
"name": "@worldwideview/wwv-lib-incidents",
"version": "1.0.4",
"description": "Shared abstract base classes for WorldWideView incident plugins (earthquakes, wildfires, conflicts)",
"repository": {
"type": "git",
"url": "https://github.com/silvertakana/worldwideview.git",
"directory": "packages/wwv-lib-incidents"
},
"main": "src/index.ts",
"types": "src/index.ts",
"files": [
@@ -16,6 +21,6 @@
"author": "WorldWideView",
"license": "ISC",
"peerDependencies": {
"@worldwideview/wwv-plugin-sdk": "^1.4.10"
"@worldwideview/wwv-plugin-sdk": "workspace:*"
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ export interface IconUrlOptions extends Record<string, unknown> {
* Pass `{ background: false }` to opt out.
*/
export declare function createSvgIconUrl(Icon: ComponentType<any>, opts?: IconUrlOptions): string;
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration } from "./manifest";
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration, LocalDataSourceDeclaration } from "./manifest";
export type PluginCategory = "aviation" | "maritime" | "military" | "conflict" | "natural-disaster" | "infrastructure" | "space" | "cyber" | "economic" | "intelligence" | "custom";
export interface TimeRange {
start: Date;
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAG7K,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACtB,oEAAoE;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,sBAAsB;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,SAAS,EAAE,IAAI,CAAC;IAChB,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBALine truncated
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAGzM,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACtB,oEAAoE;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,sBAAsB;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,SAAS,EAAE,IAAI,CAAC;IAChB,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SLine truncated
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-sdk",
"version": "1.7.1",
"version": "1.7.2",
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
"main": "dist/index.js",
"types": "dist/index.d.ts",
+1 -1
View File
@@ -96,7 +96,7 @@ export function wwvPluginGlobals(): any {
return `
const SDK = globalThis.__WWV_HOST__.WWVPluginSDK;
export default SDK;
export const { WorldPlugin, PluginManifest, createSvgIconUrl, DEFAULT_ICON_SIZE } = SDK;
export const { WorldPlugin, PluginManifest, createSvgIconUrl, DEFAULT_ICON_SIZE, dtProp, urlProp, imageProp, videoProp } = SDK;
`;
}
if (originalId === "zustand") {
+2122 -1022
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
-- CreateTable
CREATE TABLE "marketplace_credentials" (
"id" TEXT NOT NULL,
"tenantId" TEXT,
"version" TEXT NOT NULL,
"salt" TEXT NOT NULL,
"nonce" TEXT NOT NULL,
"ciphertext" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "marketplace_credentials_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "user_api_keys" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"tenantId" TEXT,
"prefix" TEXT NOT NULL,
"hashedSecret" TEXT NOT NULL,
"name" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lastUsedAt" TIMESTAMP(3),
CONSTRAINT "user_api_keys_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "marketplace_credentials_tenantId_key" ON "marketplace_credentials"("tenantId");
-- CreateIndex
CREATE UNIQUE INDEX "user_api_keys_prefix_key" ON "user_api_keys"("prefix");
-- AddForeignKey
ALTER TABLE "user_api_keys" ADD CONSTRAINT "user_api_keys_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
-- AlterTable: add nullable notes column to favorites
-- This is a non-destructive additive change. Existing rows receive NULL.
ALTER TABLE "favorites" ADD COLUMN IF NOT EXISTS "notes" TEXT;
@@ -0,0 +1,5 @@
-- Add sessionVersion to users table.
-- Existing rows default to 0, which matches the @default(0) in schema.prisma.
-- This column is embedded in every JWT at sign-in; bumping it invalidates all
-- existing sessions for that user (logout-everywhere / credential rotation).
ALTER TABLE "users" ADD COLUMN "sessionVersion" INTEGER NOT NULL DEFAULT 0;
+4
View File
@@ -14,6 +14,10 @@ model User {
name String
hashedPassword String
role String @default("user")
// Bumping this invalidates all of the user's existing JWT sessions.
// The JWT embeds the value at sign-in; the auth jwt callback rejects any
// token whose value no longer matches the DB (logout-everywhere / revoke).
sessionVersion Int @default(0)
createdAt DateTime @default(now())
favorites Favorite[]
memberships WorkspaceMember[]
+247
View File
@@ -0,0 +1,247 @@
/**
* ci-plugin-smoke/smoke.mjs
* Tier 2: Load the bundle and verify WorldPlugin interface shape.
* Tier 3: Exercise pure methods — getLayerConfig, renderEntity, mapWebsocketPayload.
*
* Plugin bundles reference globalThis.__WWV_HOST__ for all externals (React, Cesium,
* wwv-plugin-sdk, etc.) via the wwvPluginGlobals() Vite plugin. No Node.js module
* hooks are needed — setting up __WWV_HOST__ before import() is sufficient.
*
* Usage: node scripts/ci-plugin-smoke/smoke.mjs <path-to-dist/frontend.mjs>
*/
import { pathToFileURL } from "node:url";
import path from "node:path";
// ── Args ─────────────────────────────────────────────────────────────────────
const [, , bundleArg] = process.argv;
if (!bundleArg) {
console.error("Usage: node scripts/ci-plugin-smoke/smoke.mjs <path-to-dist/frontend.mjs>");
process.exit(2);
}
const bundleAbs = path.resolve(bundleArg);
const bundleUrl = pathToFileURL(bundleAbs).href;
// ── Mock host globals ─────────────────────────────────────────────────────────
// Mirrors what the host app injects at runtime. All externals in the bundle
// resolve to these via globalThis.__WWV_HOST__.<name>.
const noop = () => {};
globalThis.__WWV_HOST__ = {
React: new Proxy(
{
createElement: () => null,
Fragment: Symbol("Fragment"),
memo: (c) => c,
forwardRef: (fn) => fn,
lazy: () => null,
createContext: () => ({ Provider: null, Consumer: null, _currentValue: null }),
Component: class Component {},
PureComponent: class PureComponent {},
},
{
get(target, key) {
if (key in target) return target[key];
if (["useState", "useRef", "useContext", "useReducer"].includes(key)) return () => [null, noop];
if (["useEffect", "useLayoutEffect", "useInsertionEffect"].includes(key)) return noop;
if (["useMemo", "useCallback"].includes(key)) return (fn) => (typeof fn === "function" ? fn() : fn);
return noop;
},
}
),
ReactDOM: { createPortal: () => null, flushSync: (fn) => fn(), render: noop },
jsxRuntime: { jsx: () => null, jsxs: () => null, Fragment: null },
Cesium: new Proxy(
{},
{
get(_, key) {
if (key === "Math") return Math;
if (key === Symbol.toPrimitive) return undefined;
return function MockCesium() {};
},
}
),
Resium: new Proxy({}, { get: () => function MockResium() {} }),
WWVPluginSDK: {
createSvgIconUrl: () => "data:image/svg+xml;base64,PHN2Zy8+",
DEFAULT_ICON_SIZE: 32,
dtProp: (v) => (v ? `datetime:${v}` : null),
urlProp: (v) => (v ? `url:${v}` : null),
imageProp: (v) => (v ? `image:${v}` : null),
videoProp: (v) => (v ? `video:${v}` : null),
},
zustand: {
create: () => Object.assign(() => ({}), { getState: () => ({}), setState: noop, subscribe: () => noop }),
createStore: () => ({ getState: () => ({}), setState: noop, subscribe: () => noop }),
},
useStore: () => ({}),
pluginManager: { getPlugin: () => null, registerPlugin: noop },
CameraStream: null,
};
// No-op fetch so any top-level module code that calls fetch() does not throw.
globalThis.fetch ??= async () => ({ ok: true, status: 200, json: async () => [], text: async () => "[]" });
// ── Load the bundle ───────────────────────────────────────────────────────────
let mod;
try {
mod = await import(bundleUrl);
} catch (err) {
console.error(`FAIL [Tier 2] Bundle failed to load: ${err.message}`);
process.exit(1);
}
// ── Instantiate (mirrors loadBundlePlugin logic) ──────────────────────────────
function tryInstantiate(maybeExport) {
if (!maybeExport) return null;
if (typeof maybeExport === "function") {
try {
const inst = new maybeExport();
if (inst && typeof inst.initialize === "function") return inst;
} catch {
return null;
}
}
if (typeof maybeExport === "object" && typeof maybeExport.initialize === "function") return maybeExport;
return null;
}
let plugin = null;
if (mod.default) {
plugin = typeof mod.default === "function"
? (tryInstantiate(mod.default) ?? new mod.default())
: mod.default;
}
if (!plugin) {
for (const k of Object.keys(mod)) {
plugin = tryInstantiate(mod[k]);
if (plugin) break;
}
}
if (!plugin) {
console.error("FAIL [Tier 2] No valid WorldPlugin export found in bundle.");
process.exit(1);
}
console.log("OK [Tier 2] Bundle loaded and plugin instantiated");
// ── Tier 2: Required interface fields ────────────────────────────────────────
const REQUIRED_STRINGS = ["id", "name", "description", "category", "version"];
const REQUIRED_METHODS = ["initialize", "destroy", "fetch", "getPollingInterval", "getLayerConfig", "renderEntity"];
let passed = true;
for (const field of REQUIRED_STRINGS) {
if (typeof plugin[field] !== "string" || !plugin[field]) {
console.error(`FAIL [Tier 2] Missing or empty string field: "${field}" (got ${JSON.stringify(plugin[field])})`);
passed = false;
} else {
console.log(` ok ${field} = ${JSON.stringify(plugin[field])}`);
}
}
for (const method of REQUIRED_METHODS) {
if (typeof plugin[method] !== "function") {
console.error(`FAIL [Tier 2] Missing required method: ${method}()`);
passed = false;
} else {
console.log(` ok ${method}()`);
}
}
if (!passed) {
console.error("FAIL [Tier 2] WorldPlugin shape validation failed — see above");
process.exit(1);
}
console.log("OK [Tier 2] WorldPlugin interface shape validated");
// ── Tier 3: Exercise pure methods ─────────────────────────────────────────────
// These methods must be callable without a real engine or network.
// getPollingInterval()
try {
const interval = plugin.getPollingInterval();
if (typeof interval !== "number" || interval < 0) {
console.error(`FAIL [Tier 3] getPollingInterval() returned invalid value: ${JSON.stringify(interval)}`);
passed = false;
} else {
console.log(` ok getPollingInterval() = ${interval}`);
}
} catch (err) {
console.error(`FAIL [Tier 3] getPollingInterval() threw: ${err.message}`);
passed = false;
}
// getLayerConfig()
let layerConfig;
try {
layerConfig = plugin.getLayerConfig();
if (!layerConfig || typeof layerConfig !== "object") {
console.error(`FAIL [Tier 3] getLayerConfig() returned non-object: ${JSON.stringify(layerConfig)}`);
passed = false;
} else if (typeof layerConfig.color !== "string") {
console.error(`FAIL [Tier 3] getLayerConfig().color is not a string: ${JSON.stringify(layerConfig.color)}`);
passed = false;
} else {
console.log(` ok getLayerConfig() color=${layerConfig.color}`);
}
} catch (err) {
console.error(`FAIL [Tier 3] getLayerConfig() threw: ${err.message}`);
passed = false;
}
// renderEntity() with a mock GeoEntity
const mockEntity = {
id: "ci-smoke-001",
pluginId: plugin.id,
latitude: 37.7749,
longitude: -122.4194,
altitude: 0,
timestamp: new Date(),
label: "Smoke Test",
properties: {},
};
try {
const opts = plugin.renderEntity(mockEntity);
if (!opts || typeof opts !== "object") {
console.error(`FAIL [Tier 3] renderEntity() returned non-object: ${JSON.stringify(opts)}`);
passed = false;
} else if (typeof opts.type !== "string") {
console.error(`FAIL [Tier 3] renderEntity().type is not a string (got ${JSON.stringify(opts.type)})`);
passed = false;
} else {
console.log(` ok renderEntity() type=${opts.type}`);
}
} catch (err) {
console.error(`FAIL [Tier 3] renderEntity() threw: ${err.message}`);
passed = false;
}
// mapWebsocketPayload() — optional but validated when present
if (typeof plugin.mapWebsocketPayload === "function") {
// A flat GeoEntity[] is the simplest payload shape. Plugins that receive
// object payloads from the seeder (e.g. { items: [...] }) must implement
// this method to map to GeoEntity[]. We test with the flat-array case first.
const mockPayload = [mockEntity];
try {
const result = plugin.mapWebsocketPayload(mockPayload, []);
if (!Array.isArray(result)) {
console.error(
`FAIL [Tier 3] mapWebsocketPayload([entity]) returned non-array: ${JSON.stringify(typeof result)}`
);
passed = false;
} else {
console.log(` ok mapWebsocketPayload([1 entity]) -> ${result.length} entities`);
}
} catch (err) {
console.error(`FAIL [Tier 3] mapWebsocketPayload() threw: ${err.message}`);
passed = false;
}
} else {
console.log(" -- mapWebsocketPayload not implemented (flat GeoEntity[] assumed — OK)");
}
if (!passed) {
console.error("FAIL [Tier 3] Method contract violations — see above");
process.exit(1);
}
console.log("OK [Tier 3] Method contracts validated");
console.log("PASS smoke test complete");
+40 -7
View File
@@ -148,6 +148,9 @@ const ANTI_PATTERNS = [
tier: 'A',
globs: ['*.ts', '*.tsx'],
pattern: '@ts-ignore',
// Only flag the actual suppression directive form (// @ts-ignore or /* @ts-ignore),
// not the token appearing in JSDoc prose (e.g. "No @ts-ignore used here").
directiveOnly: true,
desc: '@ts-ignore suppresses real type errors — remove and fix the underlying type',
},
{
@@ -155,6 +158,7 @@ const ANTI_PATTERNS = [
tier: 'A',
globs: ['*.ts', '*.tsx'],
pattern: '@ts-nocheck',
directiveOnly: true,
desc: '@ts-nocheck disables all type checking for the file — remove and fix types',
},
{
@@ -175,7 +179,7 @@ const ANTI_PATTERNS = [
];
function detectAntiPatterns() {
for (const { id, tier, globs, pattern, desc, excludePrefix } of ANTI_PATTERNS) {
for (const { id, tier, globs, pattern, desc, excludePrefix, directiveOnly } of ANTI_PATTERNS) {
const globArgs = globs.map(g => `"${g}"`).join(' ');
const raw = run(`git grep -En "${pattern}" -- ${globArgs}`);
if (!raw) continue;
@@ -189,13 +193,19 @@ function detectAntiPatterns() {
const m = line.match(/^([^:]+):(\d+):(.*)/);
if (!m) continue;
if (m[1].startsWith('node_modules/') || m[1].includes('public/cesium')) continue;
const content = m[3].trim();
// For directive-only patterns (e.g. @ts-ignore), skip lines where the token
// appears in prose rather than as a comment suppression directive.
// A real directive has @ts-ignore/@ts-nocheck immediately after the // or /*
// comment opener — not buried mid-sentence in a comment that mentions it.
if (directiveOnly && !/^\s*\/[/*]\s*@ts-(ignore|nocheck)/.test(m[3])) continue;
add({
type: 'anti-pattern',
patternId: id,
tier,
file: m[1],
line: parseInt(m[2], 10),
content: m[3].trim().slice(0, 200),
content: content.slice(0, 200),
description: desc,
});
}
@@ -306,13 +316,36 @@ function detectOutdatedDeps() {
if (!existsSync(join(ROOT, 'package.json'))) return;
const raw = run('pnpm outdated --no-color 2>/dev/null || true');
if (!raw) return;
const dataLines = raw
// pnpm outdated renders a Unicode box-drawing table. Data rows start with │ and
// contain pipe-separated columns; separator/border rows contain ─ or ┼ characters.
// We extract data rows by splitting on │ and discarding header/separator lines.
const SEPARATOR_CHARS = /[┌┐└┘├┤─]/;
const tableDataRows = raw
.split('\n')
.filter(l => l.trim() && !l.startsWith('Package') && !l.startsWith('Legend') && !l.startsWith(' '));
.filter(l => l.startsWith('│') && !SEPARATOR_CHARS.test(l));
// Fall back to plain whitespace-separated output (older pnpm / --no-color plain format)
const plainDataLines = !tableDataRows.length
? raw.split('\n').filter(l => l.trim() && !l.startsWith('Package') && !l.startsWith('Legend') && !l.startsWith(' '))
: [];
const dataLines = tableDataRows.length ? tableDataRows : plainDataLines;
for (const line of dataLines.slice(0, 12)) {
const cols = line.trim().split(/\s+/);
if (cols.length < 3) continue;
const [pkg, current, latest] = cols;
let pkg, current, latest;
if (tableDataRows.length) {
// Parse │ col1 │ col2 │ col3 │ format
const cols = line.split('│').map(c => c.trim()).filter(Boolean);
if (cols.length < 3) continue;
// Header row: first column is literally "Package"
if (cols[0] === 'Package') continue;
[pkg, current, latest] = cols;
// current may be "1.2.3 (wanted 1.2.4)" — extract just the installed version
current = current.split(' ')[0];
} else {
const cols = line.trim().split(/\s+/);
if (cols.length < 3) continue;
[pkg, current, latest] = cols;
}
if (!pkg || !current || !latest || current === latest) continue;
const isMajor = current.replace(/^[^0-9]*/, '').split('.')[0] !== latest.replace(/^[^0-9]*/, '').split('.')[0];
add({
+34
View File
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server";
import { auth, signOut } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { isCloud } from "@/core/edition";
/**
* POST /api/auth/revoke: "sign out everywhere".
*
* Increments the authenticated user's `sessionVersion`, which invalidates every
* existing JWT issued for that user: the auth `jwt` callback compares each
* token's embedded version against the DB on its next use and rejects stale
* ones. Also clears the caller's own session cookie.
*
* Requires an authenticated session. Same-origin only in practice: the session
* cookie is `sameSite=lax`, so a cross-site POST carries no credentials.
*/
export async function POST() {
const session = await auth();
const userId = session?.user?.id;
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Cloud identities are managed by Supabase; there is no local users row to bump.
if (!isCloud) {
await prisma.user.update({
where: { id: userId },
data: { sessionVersion: { increment: 1 } },
});
}
await signOut({ redirect: false });
return NextResponse.json({ ok: true });
}
+14 -1
View File
@@ -7,6 +7,18 @@ import { safeFetch } from "@/lib/security/ssrf";
const MAX_IFRAME_DURATION_MS = 10 * 1000; // 10 seconds timeout for HTML
/**
* Escape a string for safe inclusion in an HTML attribute value.
*/
function escapeHtmlAttr(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#x27;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
/**
* Proxy for iframe HTML pages.
* Fetches the target HTML, strips X-Frame-Options and CSP, and injects a <base href="...">
@@ -62,7 +74,8 @@ export async function GET(req: NextRequest) {
let html = await upstream.text();
// Inject <base href="..."> right after <head> or at the very beginning of the document
const baseTag = `<base href="${targetUrl}">\n`;
const escapedUrl = escapeHtmlAttr(targetUrl);
const baseTag = `<base href="${escapedUrl}">\n`;
if (html.includes("<head>")) {
html = html.replace("<head>", `<head>\n${baseTag}`);
} else if (html.includes("<HEAD>")) {
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { GET } from "./route";
// ---------------------------------------------------------------------------
// Module mocks -- declared before any imports of the SUT so Vitest hoists them.
// ---------------------------------------------------------------------------
vi.mock("@/lib/healthProbes", () => ({
probeRedis: vi.fn(),
probeDb: vi.fn(),
probeEngine: vi.fn(),
probeConfig: vi.fn(),
}));
vi.mock("@/core/edition", () => ({
edition: "local",
}));
import {
probeRedis,
probeDb,
probeEngine,
probeConfig,
} from "@/lib/healthProbes";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function setProbes(opts: {
redis?: boolean;
db?: boolean;
engine?: boolean;
config?: boolean;
}): void {
vi.mocked(probeRedis).mockResolvedValue(opts.redis ?? true);
vi.mocked(probeDb).mockResolvedValue(opts.db ?? true);
vi.mocked(probeEngine).mockResolvedValue(opts.engine ?? true);
// probeConfig is synchronous in the real impl; mock as a plain return value.
vi.mocked(probeConfig).mockReturnValue(opts.config ?? true);
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("GET /api/health", () => {
beforeEach(() => {
vi.resetAllMocks();
});
it("returns 200 healthy when all probes pass (OBS-01 happy path)", async () => {
setProbes({ redis: true, db: true, engine: true, config: true });
const res = await GET();
const body = await res.json();
expect(res.status).toBe(200);
expect(body.status).toBe("healthy");
expect(body.checks).toEqual({ redis: true, db: true, engine: true, config: true });
expect(body).toHaveProperty("edition");
expect(body).toHaveProperty("timestamp");
});
it("returns 200 degraded with checks.redis=false when redis probe fails (OBS-01 redis-down)", async () => {
setProbes({ redis: false, db: true, engine: true, config: true });
const res = await GET();
const body = await res.json();
expect(res.status).toBe(200);
expect(body.status).toBe("degraded");
expect(body.checks.redis).toBe(false);
expect(body.checks.db).toBe(true);
});
it("returns 503 unhealthy when db probe fails (OBS-01 db-down)", async () => {
setProbes({ redis: true, db: false, engine: true, config: true });
const res = await GET();
const body = await res.json();
expect(res.status).toBe(503);
expect(body.status).toBe("unhealthy");
expect(body.checks.db).toBe(false);
});
it("returns 200 degraded when engine probe fails (OBS-01 engine-down)", async () => {
setProbes({ redis: true, db: true, engine: false, config: true });
const res = await GET();
const body = await res.json();
expect(res.status).toBe(200);
expect(body.status).toBe("degraded");
expect(body.checks.engine).toBe(false);
});
it("returns 503 unhealthy when config probe fails in cloud edition (OBS-01 config-misconfigured)", async () => {
// Simulate cloud edition with getSigningKey() having thrown (probeConfig returns false).
vi.mocked(probeConfig).mockReturnValue(false);
vi.mocked(probeRedis).mockResolvedValue(true);
vi.mocked(probeDb).mockResolvedValue(true);
vi.mocked(probeEngine).mockResolvedValue(true);
const res = await GET();
const body = await res.json();
expect(res.status).toBe(503);
expect(body.status).toBe("unhealthy");
expect(body.checks.config).toBe(false);
});
it("includes edition and ISO timestamp in every response (OBS-01 shape)", async () => {
setProbes({});
const res = await GET();
const body = await res.json();
expect(typeof body.edition).toBe("string");
expect(typeof body.timestamp).toBe("string");
// ISO 8601 basic check
expect(body.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
});
+63 -2
View File
@@ -1,5 +1,66 @@
import { NextResponse } from "next/server";
import { edition } from "@/core/edition";
import { probeRedis, probeDb, probeEngine, probeConfig } from "@/lib/healthProbes";
export async function GET() {
return NextResponse.json({ status: "healthy" }, { status: 200 });
// ---------------------------------------------------------------------------
// Status + HTTP code policy:
// db down OR config misconfigured (cloud/demo) -> "unhealthy", 503
// Rationale: the app is either unable to authenticate requests or
// fundamentally broken. A load balancer or container orchestrator should
// stop routing traffic and alert the operator.
// redis down OR engine down (but db + config ok) -> "degraded", 200
// Rationale: auth/session reads still work; only streaming data or
// rate-limiting is impaired. 200 avoids container restarts for transient
// upstream outages.
// all ok -> "healthy", 200
// ---------------------------------------------------------------------------
type HealthStatus = "healthy" | "degraded" | "unhealthy";
interface HealthBody {
status: HealthStatus;
checks: {
redis: boolean;
db: boolean;
engine: boolean;
config: boolean;
};
edition: string;
timestamp: string;
}
export async function GET(): Promise<NextResponse<HealthBody>> {
// Run all probes in parallel. probeConfig is sync but wrapped in
// Promise.resolve so all four settle together with Promise.all.
const [redis, db, engine, config] = await Promise.all([
probeRedis(),
probeDb(),
probeEngine(),
Promise.resolve(probeConfig()),
]);
const checks = { redis, db, engine, config };
let status: HealthStatus;
let httpStatus: 200 | 503;
if (!db || !config) {
status = "unhealthy";
httpStatus = 503;
} else if (!redis || !engine) {
status = "degraded";
httpStatus = 200;
} else {
status = "healthy";
httpStatus = 200;
}
const body: HealthBody = {
status,
checks,
edition,
timestamp: new Date().toISOString(),
};
return NextResponse.json(body, { status: httpStatus });
}
+37 -5
View File
@@ -76,6 +76,21 @@ describe("radiusKmToBbox", () => {
expect(bbox.east).toBeCloseTo(11, 1);
expect(bbox.west).toBeCloseTo(9, 1);
});
it("globe-spanning radius (30000 km) produces full-longitude box, not antimeridian strip", () => {
// Without the lonDelta cap a 30000 km radius produces lonDelta >> 180,
// and wrapLon(lon + lonDelta) collapses to a tiny strip near the antimeridian.
// With the cap, lonDelta = 180, so east and west both map to the antimeridian
// (+180 and -180 are the same line). The key invariant is that the longitude
// span equals 360 degrees (east - west mod 360 = 0 = full globe).
const bbox = radiusKmToBbox(0, 0, 30000);
// Both east and west land on the antimeridian (180 = -180 in wrapped coords).
const normalise = (v: number) => Math.abs(Math.abs(v) - 180);
expect(normalise(bbox.east)).toBeCloseTo(0, 4);
expect(normalise(bbox.west)).toBeCloseTo(0, 4);
expect(bbox.north).toBeCloseTo(90, 0);
expect(bbox.south).toBeCloseTo(-90, 0);
});
});
// ---------------------------------------------------------------------------
@@ -147,11 +162,28 @@ describe("listStreamingPlugins", () => {
expect(result.plugins[0].entityCount).toBe(1);
});
it("returns { plugins: [], reason: 'engine unreachable' } when no snapshots", async () => {
it("returns { plugins: [], reason: 'engine_unreachable' } when no snapshots and engine not reachable (TOOL-05)", async () => {
// In the test environment the probe fetch fails, so engineReachable=false -> engine_unreachable.
mockGetAllSnapshots.mockResolvedValue([]);
const result = await listStreamingPlugins();
expect(result.plugins).toHaveLength(0);
expect(result.reason).toBe("engine unreachable");
expect(result.reason).toBe("engine_unreachable");
});
it("returns no_active_plugins when engine reachable but zero snapshots (TOOL-05)", async () => {
// Mock fetch to simulate engine responding OK (reachable, but no plugins).
const savedFetch = global.fetch;
global.fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ plugins: [] }), { status: 200 }),
);
try {
mockGetAllSnapshots.mockResolvedValue([]);
const result = await listStreamingPlugins();
expect(result.plugins).toHaveLength(0);
expect(result.reason).toBe("no_active_plugins");
} finally {
global.fetch = savedFetch;
}
});
});
@@ -263,15 +295,15 @@ describe("listStreamingPlugins -- source tagging", () => {
expect(byId["camera"]).toBe("local");
});
it("engine-unreachable passthrough: empty snapshots still returns { plugins: [], reason: 'engine unreachable' }", async () => {
it("engine-unreachable passthrough: empty snapshots returns engine_unreachable when probe fails (TOOL-05)", async () => {
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
mockGetAllSnapshots.mockResolvedValue([]);
// localIds irrelevant when snapshots list is empty
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
const result = await listStreamingPlugins();
expect(result.plugins).toHaveLength(0);
expect(result.reason).toBe("engine unreachable");
expect(result.reason).toBe("engine_unreachable");
});
});
+39 -6
View File
@@ -41,7 +41,9 @@ export function radiusKmToBbox(lat: number, lon: number, radiusKm: number): Regi
const latDelta = radiusKm / 111;
const cosLat = Math.cos((lat * Math.PI) / 180);
const clampedCos = Math.max(cosLat, 0.01);
const lonDelta = radiusKm / (111 * clampedCos);
// Cap lonDelta at 180 so a globe-spanning radius yields the full longitude
// range [-180, 180] rather than wrapping to a thin antimeridian strip.
const lonDelta = Math.min(radiusKm / (111 * clampedCos), 180);
const wrapLon = (v: number): number => ((((v + 180) % 360) + 360) % 360) - 180;
return {
north: Math.min(lat + latDelta, 90),
@@ -102,17 +104,48 @@ export interface ListStreamingPluginsResult {
reason?: string;
}
/**
* Probes whether the data engine manifest endpoint is reachable.
* Returns true when the engine responds with 2xx, false on network error or non-2xx.
*
* Timeout is intentionally short (2000ms) so callers on the empty-snapshot path
* are not blocked waiting for a slow engine.
*/
async function probeEngineReachable(): Promise<boolean> {
const engineUrl = (process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001") + "/manifest";
try {
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(2000) });
return res.ok;
} catch {
return false;
}
}
/**
* Fetches the engine manifest and per-plugin snapshots to build a summary list.
* Returns `{ plugins: [], reason: "engine unreachable" }` when no snapshots are
* available (engine down or no active plugins).
*
* Reasons when plugins array is empty:
* engine_unreachable -- manifest fetch failed or engine returned non-2xx.
* no_active_plugins -- engine reachable but zero plugins active right now.
*
* Local sources (e.g. camera) are tagged source:'local' and are surfaced
* even when the engine is down (getAllPluginSnapshots includes local sources).
*
* The probe runs only on the empty-snapshot path to avoid the double-manifest
* hit on every happy-path call.
*/
export async function listStreamingPlugins(): Promise<ListStreamingPluginsResult> {
const snapshots = await getAllPluginSnapshots();
const [snapshots, localIds] = await Promise.all([
getAllPluginSnapshots(),
getLocalSourceIds(),
]);
if (snapshots.length === 0) {
return { plugins: [], reason: "engine unreachable" };
const engineReachable = await probeEngineReachable();
const reason = engineReachable ? "no_active_plugins" : "engine_unreachable";
return { plugins: [], reason };
}
const localIds = await getLocalSourceIds();
const plugins: StreamingPlugin[] = snapshots.map((snap) => ({
pluginId: snap.pluginId,
pluginName: snap.pluginId, // manifest exposes ids only
+41 -2
View File
@@ -114,14 +114,15 @@ describe("list_available_plugins", () => {
expect(parsed.plugins[0].entityTypes).toContain("status");
});
it("returns { plugins: [], reason: 'engine unreachable' } when engine is down", async () => {
it("returns { plugins: [], reason: 'engine_unreachable' } when engine is down (TOOL-05)", async () => {
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
mockGetAllSnapshots.mockResolvedValue([]);
const result = await handlers["list_available_plugins"]({});
const parsed = parsedOf(result) as { plugins: unknown[]; reason: string };
expect(parsed.plugins).toHaveLength(0);
expect(parsed.reason).toBe("engine unreachable");
expect(parsed.reason).toBe("engine_unreachable");
});
});
@@ -262,4 +263,42 @@ describe("investigate_area", () => {
expect(parsed.entities).toHaveLength(0);
expect(parsed.summary).toContain("ZZZ_NONEXISTENT");
});
it("truncation (TOOL-04/P33): returns truncated:true and cappedTotal when result exceeds 200 cap", async () => {
// Two plugins both named with "vessel" substring so entity_type:"vessel" matches both.
// Each returns 110 entities = 220 total, exceeding INVESTIGATE_AREA_CAP (200).
const makeEntities = (pluginId: string, count: number) =>
Array.from({ length: count }, (_, i) => ({
id: `${pluginId}-${i}`,
pluginId,
latitude: 0,
longitude: 0,
}));
mockGetAllSnapshots.mockResolvedValue([
{ pluginId: "vessel-ais", entities: [], timestamp: new Date() },
{ pluginId: "vessel-cargo", entities: [], timestamp: new Date() },
]);
mockGetEntitiesInRegion
.mockResolvedValueOnce({ entities: makeEntities("vessel-ais", 110) })
.mockResolvedValueOnce({ entities: makeEntities("vessel-cargo", 110) });
mockResolveActiveSessionId.mockResolvedValue(null);
const result = await handlers["investigate_area"]({
place_name: "Auckland",
entity_type: "vessel",
});
const parsed = parsedOf(result) as {
entities: unknown[];
count: number;
truncated?: boolean;
cappedTotal?: number;
summary: string;
};
expect(parsed.entities).toHaveLength(200);
expect(parsed.count).toBe(200);
expect(parsed.truncated).toBe(true);
expect(parsed.cappedTotal).toBe(220);
});
});
+20 -3
View File
@@ -46,6 +46,9 @@ const DEFAULT_RADIUS_KM = 50;
/** Altitude (metres) used for camera pan commands from investigate_area. */
const INVESTIGATE_PAN_ALT = 300_000;
/** Maximum total entities returned across all plugins by investigate_area (TOOL-04). */
const INVESTIGATE_AREA_CAP = 200;
// ---------------------------------------------------------------------------
// Public registrar
// ---------------------------------------------------------------------------
@@ -125,6 +128,7 @@ export function registerDiscoveryTools(
"Use this tool when an agent asks 'what is near X?' or 'show me Y around Z'. Prefer this over manual geocode + search_entities sequences. " +
"When no matching plugin streams the given entity_type, the summary explains this and suggests list_available_plugins. " +
"When no active session is found, entities are still returned but the summary notes the camera pan was skipped. " +
"Response is capped at 200 entities total across all matched plugins. When 'truncated' is true, 'cappedTotal' holds the sum of per-plugin results before the global cap (not the true global count, because each plugin is itself queried with its own 100-entity limit). " +
"Parameters: place_name (required), entity_type (required, case-insensitive substring match against plugin ids/names), radius_km (optional, default 50). " +
"Example: investigate_area({place_name:\"Auckland\",entity_type:\"flights\",radius_km:100})",
inputSchema: {
@@ -195,18 +199,31 @@ export function registerDiscoveryTools(
await enqueueGlobeCommand(userId, sessionId, cmd);
}
// Step 5: Build prose summary using first matched plugin as representative.
// Step 5: Apply overall cap and record truncation metadata.
// cappedTotal is the sum of per-plugin results before the global cap.
// It is NOT the true global count because each plugin is queried with
// its own 100-entity limit before reaching here.
const cappedTotal = allEntities.length;
const truncated = cappedTotal > INVESTIGATE_AREA_CAP;
const entities = truncated ? allEntities.slice(0, INVESTIGATE_AREA_CAP) : allEntities;
// Step 6: Build prose summary using first matched plugin as representative.
const representativePlugin = matched[0].pluginId;
const summary = buildInvestigateProse({
displayName: geo.display_name,
entityType: entity_type,
matchedPlugin: representativePlugin,
entityCount: allEntities.length,
entityCount: entities.length,
sessionPresent,
emptyReason: lastEmptyReason,
});
return textResult({ entities: allEntities, summary });
return textResult({
entities,
count: entities.length,
...(truncated && { truncated: true, cappedTotal }),
summary,
});
} catch (err) {
console.error("[discoveryTools] investigate_area failed:", err);
return textResult({
+33
View File
@@ -53,6 +53,9 @@ describe("favoritesTools tool descriptions (DESC-03)", () => {
describe("save_favorite tool handler", () => {
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
// findUnique returns null -> new row, count returns 0 -> below cap
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
mockPrisma.favorite.count.mockResolvedValue(0 as never);
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
await handlers["save_favorite"]({
@@ -73,6 +76,8 @@ describe("save_favorite tool handler", () => {
});
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
mockPrisma.favorite.count.mockResolvedValue(0 as never);
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
@@ -83,6 +88,34 @@ describe("save_favorite tool handler", () => {
}),
);
});
it("rejects when user is at the 500-favorite cap and entity is new", async () => {
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
mockPrisma.favorite.count.mockResolvedValue(500 as never);
const result = await handlers["save_favorite"]({
entityId: "newship:999",
pluginId: "maritime",
});
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalled();
const text = (result as { content: Array<{ text: string }> }).content[0].text;
expect(text).toContain("favorite limit of 500 reached");
});
it("allows upsert when entity already exists (no count check needed)", async () => {
// findUnique returns an existing row -> cap check is skipped
mockPrisma.favorite.findUnique.mockResolvedValue({ id: "existing" } as never);
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
await handlers["save_favorite"]({
entityId: "ship:123",
pluginId: "maritime",
});
expect(mockPrisma.favorite.count).not.toHaveBeenCalled();
expect(mockPrisma.favorite.upsert).toHaveBeenCalled();
});
});
describe("list_favorites tool handler", () => {
+24 -6
View File
@@ -25,6 +25,9 @@ import { prisma } from "@/lib/prisma";
import { readActiveSessions } from "@/lib/globeStateStore";
import { getEntityDetails } from "@/lib/data-query/service";
import type { Prisma } from "@/generated/prisma";
import { pluginIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
const FAVORITES_CAP = 500;
// ---------------------------------------------------------------------------
// Shared helpers
@@ -74,16 +77,31 @@ export function registerFavoritesTools(
"Output: 'Saved favorite: <label>'. " +
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
inputSchema: {
entityId: z.string().min(1).describe("Unique entity identifier"),
pluginId: z.string().min(1).describe("Plugin that owns this entity"),
entityId: entityIdSchema.describe("Unique entity identifier"),
pluginId: pluginIdSchema.describe("Plugin that owns this entity"),
name: z
.string()
.min(1)
.max(120)
.optional()
.describe("Human-readable label for the bookmark (defaults to entityId)"),
},
},
async (args) => {
try {
// Cap: reject new rows when the user already has FAVORITES_CAP favorites.
// Upserts that update an existing row are always allowed.
const existing = await prisma.favorite.findUnique({
where: favoriteWhere(userId, args.entityId),
select: { id: true },
});
if (!existing) {
const count = await prisma.favorite.count({ where: { userId } });
if (count >= FAVORITES_CAP) {
return textResult(`favorite limit of ${FAVORITES_CAP} reached`);
}
}
const label = args.name ?? args.entityId;
await prisma.favorite.upsert({
where: favoriteWhere(userId, args.entityId),
@@ -162,9 +180,9 @@ export function registerFavoritesTools(
"Output: 'Updated favorite: <label>' on success, or an error string. " +
"Example: update_favorite({ favoriteId: 'AFR123', name: 'Air France 123', notes: 'Check weekly' }).",
inputSchema: {
favoriteId: z.string().min(1).describe("The entityId of the favorite to update"),
name: z.string().optional().describe("New display label for the bookmark"),
notes: z.string().optional().describe("Free-text annotation to store with the bookmark"),
favoriteId: entityIdSchema.describe("The entityId of the favorite to update"),
name: z.string().min(1).max(120).optional().describe("New display label for the bookmark"),
notes: z.string().max(2000).optional().describe("Free-text annotation to store with the bookmark"),
},
},
async (args) => {
@@ -203,7 +221,7 @@ export function registerFavoritesTools(
"Output: 'Removed favorite: <entityId>'. " +
"Example: remove_favorite({ entityId: 'AFR123' }).",
inputSchema: {
entityId: z.string().min(1).describe("Entity identifier to remove from favorites"),
entityId: entityIdSchema.describe("Entity identifier to remove from favorites"),
},
},
async (args) => {
+22 -5
View File
@@ -22,6 +22,9 @@ import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQ
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
import { pluginIdSchema } from "@/lib/mcp/identifierSchemas";
import { listStreamingPlugins } from "@/app/api/mcp/discoveryHelpers";
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
// ---------------------------------------------------------------------------
// Shared helpers
@@ -64,14 +67,16 @@ export function registerFilterTools(
"set_filter",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Apply one or more filters to a plugin's live globe layer (no page reload). " +
"Use after get_plugin_filters to discover valid filter ids; affects the live globe layer, not data query tools. " +
"Limitations: filter ids are plugin-specific; invalid ids are silently ignored by the browser. " +
"Use list_available_plugins to confirm valid pluginIds before calling. " +
"Limitations: filter ids are plugin-specific; unknown pluginIds produce a warning in the response. " +
"Parameters: pluginId (string, required); filters (object, required) -- filterId -> { type: 'text', value } | { type: 'select', values } | { type: 'range', min, max } | { type: 'boolean', value }; sessionId (optional). " +
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or 'no active globe session to control'. " +
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or a warning when the pluginId is unrecognized. " +
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
inputSchema: {
pluginId: z.string().min(1).describe("Plugin whose layer to filter, e.g. 'flights'"),
pluginId: pluginIdSchema.describe("Plugin whose layer to filter, e.g. 'flights'"),
filters: z
.record(z.string(), filterValueSchema)
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
@@ -83,12 +88,23 @@ export function registerFilterTools(
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
// Validate the pluginId against the live streaming plugin set.
const { plugins } = await listStreamingPlugins();
const knownIds = new Set(plugins.map((p) => p.pluginId));
const isKnown = knownIds.has(args.pluginId);
const cmd: GlobeCommand = {
type: "setFilter",
pluginId: args.pluginId,
filters: args.filters,
};
await enqueueGlobeCommand(userId, sessionId, cmd);
if (!isKnown) {
return textResult(
`Command enqueued, but pluginId '${args.pluginId}' is not a recognized plugin. It may be ignored.`,
);
}
return textResult(
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
);
@@ -104,6 +120,7 @@ export function registerFilterTools(
"clear_filter",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Clear active filters on the live globe. " +
"Prefer clear_filter over re-setting filters to empty values; omit pluginId to clear ALL filters across every plugin at once. " +
"Limitations: requires an active globe session; returns 'no active globe session to control' when no tab is live. " +
@@ -111,7 +128,7 @@ export function registerFilterTools(
"Output: 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins'. " +
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
inputSchema: {
pluginId: z.string().optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
pluginId: pluginIdSchema.optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
},
},
@@ -149,7 +166,7 @@ export function registerFilterTools(
"Output: { available: true, filters: FilterDefinition[] } when the plugin is loaded, where each FilterDefinition is { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?, range? }; or { available: false, reason: 'plugin not loaded' | 'no_session_active' } when unavailable. " +
"Example: get_plugin_filters({ pluginId: 'flights' }) -> { available: true, filters: [{ id: 'status', label: 'Status', type: 'select', options: [...] }] }.",
inputSchema: {
pluginId: z.string().min(1).describe("Plugin to inspect for declared filterable fields"),
pluginId: pluginIdSchema.describe("Plugin to inspect for declared filterable fields"),
},
},
async (args) => {
+7 -1
View File
@@ -1,6 +1,12 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/nominatim");
vi.mock("@/lib/nominatim", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
return {
...actual,
fetchGeocode: vi.fn(),
};
});
vi.mock("@/lib/geocodingRateLimit");
vi.mock("@/lib/globeCommandQueue");
+11 -32
View File
@@ -1,10 +1,10 @@
/**
* MCP Geocoding Tool registrar (Phase 22 Wave 2 -- 22-02).
* MCP Geocoding Tool registrar (Phase 22 Wave 2, 22-02).
*
* Registers two MCP tools:
* geocode_location -- resolve a place name/address to coordinates via Nominatim
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
* fly_to -- enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
* geocode_location: resolve a place name/address to coordinates via Nominatim
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
* fly_to: enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
*
* Security: userId comes ONLY from ctx (verified auth result), never from tool
* arguments. The Nominatim URL is hardcoded; the user query is injected via
@@ -15,11 +15,12 @@ import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
import { fetchGeocode } from "@/lib/nominatim";
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
import type { RawNominatimItem } from "@/lib/nominatim";
import { checkRateLimit } from "@/lib/geocodingRateLimit";
import { redis } from "@/lib/redis";
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
// ---------------------------------------------------------------------------
// Shared helpers
@@ -33,29 +34,6 @@ function textResult(text: string): McpTextResult {
const NO_SESSION_RESULT = textResult("no active globe session to control");
/**
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
* only stub fetchGeocode -- do not stub out the normalization step.
* Nominatim boundingbox is ["south","north","west","east"]; remap to
* [west, south, east, north] numbers.
*/
function normalizeResult(r: RawNominatimItem): NominatimResult {
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
return {
lat: parseFloat(r.lat ?? "0"),
lng: parseFloat(r.lon ?? "0"),
name: r.name ?? "",
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
type: r.type ?? "",
addresstype: r.addresstype ?? "",
country: r.address?.country ?? "",
display_name: r.display_name ?? "",
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
importance: r.importance ?? 0,
};
}
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
async function cacheGet(key: string): Promise<string | null> {
try {
@@ -112,7 +90,7 @@ export function registerGeocodingTools(
"Resolve a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
"Use before fly_to to obtain lat/lng from a name; do not guess coordinates. " +
"Limitations: Nominatim is rate-limited per user; results are cached 24h; returns 'no results found' when nothing matches. " +
"Parameters: query (string, required) -- place name or address; limit (integer 1-20, optional, default 5). " +
"Parameters: query (string, required) - place name or address; limit (integer 1-20, optional, default 5). " +
"Output: JSON array sorted by importance, each { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west,south,east,north], importance }. " +
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...] }].",
inputSchema: {
@@ -140,7 +118,7 @@ export function registerGeocodingTools(
const raw = await fetchGeocode({ query: args.query, limit });
if (raw.length === 0) return textResult("no results found");
const results = raw.map(normalizeResult);
const results = (raw as RawNominatimItem[]).map(normalizeNominatimResult);
const json = JSON.stringify(results);
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
return textResult(json);
@@ -156,11 +134,12 @@ export function registerGeocodingTools(
"fly_to",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Fly the live globe camera to a geocoded coordinate, optionally fitting a bounding box in view. " +
"Requires an active globe session (read globe://sessions first); returns 'no active globe session to control' when no tab is live. " +
"Prefer pan_globe for relative panning or focus_entity to snap to a known entity; use fly_to when you have explicit lat/lng (e.g. from geocode_location). " +
"Parameters: lat (-90..90, required), lng (-180..180, required), altitude (metres, optional, default 15000), " +
"bbox ([west,south,east,north], optional -- fit this region in view), sessionId (optional -- omit for most-recently-active tab). " +
"bbox ([west,south,east,north], optional - fit this region in view), sessionId (optional - omit for most-recently-active tab). " +
"Example: fly_to({ lat: 48.85, lng: 2.35 }) or fly_to({ lat: 0, lng: 0, bbox: [2.2,48.8,2.5,48.9] }).",
inputSchema: {
lat: latSchema.describe("Latitude [-90, 90]"),
+143 -1
View File
@@ -22,9 +22,11 @@ import { latSchema as sharedLatSchema, lonSchema as sharedLonSchema } from "@/li
// declared with vi.hoisted() to be accessible inside the factory function.
// ---------------------------------------------------------------------------
const { mockEnqueue, mockResolveSessionId } = vi.hoisted(() => ({
const { mockEnqueue, mockResolveSessionId, mockListStreamingPlugins, mockGetEntityDetails } = vi.hoisted(() => ({
mockEnqueue: vi.fn().mockResolvedValue(undefined),
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
mockListStreamingPlugins: vi.fn().mockResolvedValue({ plugins: [] }),
mockGetEntityDetails: vi.fn().mockResolvedValue({ data: null, emptyReason: "no_data_matches" }),
}));
vi.mock("@/lib/globeCommandQueue", () => ({
@@ -32,6 +34,14 @@ vi.mock("@/lib/globeCommandQueue", () => ({
resolveActiveSessionId: mockResolveSessionId,
}));
vi.mock("./discoveryHelpers", () => ({
listStreamingPlugins: mockListStreamingPlugins,
}));
vi.mock("@/lib/data-query/service", () => ({
getEntityDetails: mockGetEntityDetails,
}));
// ---------------------------------------------------------------------------
// Fake McpServer — records registered tools
// ---------------------------------------------------------------------------
@@ -56,6 +66,8 @@ beforeEach(() => {
vi.resetAllMocks();
mockEnqueue.mockResolvedValue(undefined);
mockResolveSessionId.mockResolvedValue("resolved-session");
mockListStreamingPlugins.mockResolvedValue({ plugins: [] });
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
});
// ---------------------------------------------------------------------------
@@ -435,3 +447,133 @@ describe("get_entities_in_region coordinate schema bounds (TOOL-09)", () => {
expect(sharedLonSchema.safeParse(Infinity).success).toBe(false);
});
});
// ---------------------------------------------------------------------------
// TOOL-02 (Phase 33): toggle_layer unrecognized id warning
// ---------------------------------------------------------------------------
describe("toggle_layer -- unrecognized layerId warning (TOOL-02/P33)", () => {
it("enqueues command and returns warning when layerId is not a known plugin", async () => {
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("toggle_layer")!({ layerId: "unknown-layer-xyz" });
expect(mockEnqueue).toHaveBeenCalledOnce();
expect(result.content[0].text).toContain("not a recognized plugin");
expect(result.content[0].text).toContain("unknown-layer-xyz");
});
it("enqueues command and returns plain success when layerId is recognized", async () => {
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("toggle_layer")!({ layerId: "flights" });
expect(mockEnqueue).toHaveBeenCalledOnce();
expect(result.content[0].text).not.toContain("not a recognized plugin");
expect(result.content[0].text).toContain("flights");
});
});
// ---------------------------------------------------------------------------
// TOOL-02 (Phase 33): focus_entity server-side entity-id resolution
// ---------------------------------------------------------------------------
describe("focus_entity -- server-side entity resolution (TOOL-02/P33)", () => {
it("resolves lat/lon from entityId+pluginId when coordinates are absent", async () => {
mockGetEntityDetails.mockResolvedValue({
data: {
id: "ship-1",
pluginId: "ais",
latitude: 35.68,
longitude: 139.69,
timestamp: new Date(),
properties: {},
},
});
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("focus_entity")!({
entityId: "ship-1",
pluginId: "ais",
});
expect(mockEnqueue).toHaveBeenCalledWith(
"u1",
"resolved-session",
expect.objectContaining({ type: "focusEntity", lat: 35.68, lon: 139.69 }),
);
expect(result.content[0].text).toContain("35.68");
});
it("returns honest failure when entityId cannot be resolved (no pluginId provided)", async () => {
// Without pluginId the resolver path is skipped and resolution fails.
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("focus_entity")!({ entityId: "unknown-entity" });
expect(mockEnqueue).not.toHaveBeenCalled();
expect(result.content[0].text).toContain("Could not resolve entityId");
expect(result.content[0].text).toContain("unknown-entity");
});
it("returns honest failure when entity not found in plugin snapshot", async () => {
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("focus_entity")!({
entityId: "missing-entity",
pluginId: "ais",
});
expect(mockEnqueue).not.toHaveBeenCalled();
expect(result.content[0].text).toContain("Could not resolve entityId");
});
it("uses provided lat/lon directly without calling getEntityDetails", async () => {
const { server, tools } = makeFakeServer();
registerGlobeCommandTools(
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
{ userId: "u1" },
);
const result = await tools.get("focus_entity")!({
entityId: "e1",
lat: 10,
lon: 20,
});
expect(mockGetEntityDetails).not.toHaveBeenCalled();
expect(mockEnqueue).toHaveBeenCalledWith(
"u1",
"resolved-session",
expect.objectContaining({ lat: 10, lon: 20 }),
);
expect(result.content[0].text).toContain("10");
});
});
+61 -12
View File
@@ -21,9 +21,13 @@ import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQ
import { TIME_WINDOW_VALUES } from "@/core/globe/types/GlobeCommand";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
import { latSchema, lonSchema, altSchema } from "@/lib/mcp/coordinateSchemas";
import { layerIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
import { listStreamingPlugins } from "./discoveryHelpers";
import { getEntityDetails } from "@/lib/data-query/service";
// Re-export so existing tests that import from this module continue to work.
export { latSchema, lonSchema, altSchema };
export { latSchema, lonSchema, altSchema, layerIdSchema };
// ---------------------------------------------------------------------------
// Shared helpers
@@ -66,6 +70,7 @@ export function registerGlobeCommandTools(
"pan_globe",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Fly the globe camera to an explicit coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
"Prefer pan_globe over focus_entity when you have a lat/lon and no entity id, or when focus_entity entity-id resolution is not needed. " +
"Limitations: latitude [-90, 90], longitude [-180, 180], altitude > 0 metres; out-of-range values are rejected. " +
@@ -109,13 +114,18 @@ export function registerGlobeCommandTools(
"focus_entity",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Point the globe camera at a known entity or coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it; note entity-id-to-coordinate resolution is not yet wired, so always include lat/lon for a reliable camera move. " +
"Limitations: latitude [-90, 90], longitude [-180, 180]; entityId alone will not move the camera until resolution is wired. " +
"Parameters: entityId (optional, informational), lat (recommended), lon (recommended), sessionId (optional). " +
"Example: focus_entity({entityId:\"ship-123\",lat:35.68,lon:139.69})",
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it. " +
"When lat/lon are provided they are used directly. " +
"When only entityId is provided (no lat/lon), the server resolves coordinates via pluginId + entityId lookup -- include pluginId for a faster, scoped lookup. " +
"Returns an error string when entityId cannot be resolved to coordinates. " +
"Limitations: latitude [-90, 90], longitude [-180, 180]. " +
"Parameters: entityId (optional), pluginId (optional, scopes entity lookup), lat (optional), lon (optional), sessionId (optional). " +
"Example: focus_entity({entityId:\"ship-123\",pluginId:\"ais\",lat:35.68,lon:139.69})",
inputSchema: {
entityId: z.string().optional().describe("Entity id (informational; coordinate resolution not yet supported -- also provide lat/lon)"),
entityId: entityIdSchema.optional().describe("Entity id to focus on"),
pluginId: z.string().optional().describe("Plugin that owns this entity -- narrows the id lookup when lat/lon are not provided"),
lat: latSchema.optional().describe("Latitude to focus on [-90, 90]"),
lon: lonSchema.optional().describe("Longitude to focus on [-180, 180]"),
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
@@ -126,14 +136,39 @@ export function registerGlobeCommandTools(
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
let resolvedLat = args.lat;
let resolvedLon = args.lon;
// When coordinates are absent but entityId is present, resolve server-side.
if (resolvedLat === undefined && resolvedLon === undefined && args.entityId !== undefined) {
if (args.pluginId !== undefined) {
const detail = await getEntityDetails(args.pluginId, args.entityId);
if (detail.data !== null) {
resolvedLat = detail.data.latitude;
resolvedLon = detail.data.longitude;
}
}
if (resolvedLat === undefined) {
// entityId could not be resolved -- return an honest failure instead of
// enqueuing a command the browser cannot execute.
return textResult(
`Could not resolve entityId '${args.entityId}' to coordinates. ` +
`Provide pluginId to scope the lookup, or include lat/lon directly.`,
);
}
}
const cmd: GlobeCommand = {
type: "focusEntity",
...(args.entityId !== undefined && { entityId: args.entityId }),
...(args.lat !== undefined && { lat: args.lat }),
...(args.lon !== undefined && { lon: args.lon }),
...(resolvedLat !== undefined && { lat: resolvedLat }),
...(resolvedLon !== undefined && { lon: resolvedLon }),
};
await enqueueGlobeCommand(userId, sessionId, cmd);
return textResult(`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${args.lat ?? "none"}, lon=${args.lon ?? "none"})`);
return textResult(
`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${resolvedLat ?? "none"}, lon=${resolvedLon ?? "none"})`,
);
} catch (err) {
console.error("[globeCommandTools] focus_entity failed:", err);
return textResult("focus_entity command failed");
@@ -146,13 +181,15 @@ export function registerGlobeCommandTools(
"toggle_layer",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Enable or disable a plugin data layer on the globe. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
"Prefer toggle_layer over pan_globe or set_timeline when changing layer visibility, not camera position or playback time. " +
"Limitations: layerId must match an installed plugin id; unknown ids are silently ignored by the browser. " +
"Parameters: layerId (required), enabled (true/false, optional — omit to toggle current state), sessionId (optional). " +
"Use list_available_plugins to confirm valid layerIds before calling. " +
"Limitations: layerId must match an installed plugin id. When the id is not recognized a warning is included in the response. " +
"Parameters: layerId (required), enabled (true/false, optional -- omit to toggle current state), sessionId (optional). " +
"Example: toggle_layer({layerId:\"ais\",enabled:true})",
inputSchema: {
layerId: z.string().describe("The plugin/layer identifier to toggle"),
layerId: layerIdSchema.describe("The plugin/layer identifier to toggle"),
enabled: z.boolean().optional().describe("True to enable, false to disable, omit to toggle"),
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
},
@@ -162,12 +199,23 @@ export function registerGlobeCommandTools(
const sessionId = await resolveSession(userId, args.sessionId);
if (sessionId === null) return NO_SESSION_RESULT;
// Check whether the layerId matches a known streaming plugin.
const { plugins } = await listStreamingPlugins();
const knownIds = new Set(plugins.map((p) => p.pluginId));
const isKnown = knownIds.has(args.layerId);
const cmd: GlobeCommand = {
type: "toggleLayer",
layerId: args.layerId,
...(args.enabled !== undefined && { enabled: args.enabled }),
};
await enqueueGlobeCommand(userId, sessionId, cmd);
if (!isKnown) {
return textResult(
`Command enqueued, but layerId '${args.layerId}' is not a recognized plugin. It may be ignored.`,
);
}
return textResult(`Layer '${args.layerId}' toggle command enqueued`);
} catch (err) {
console.error("[globeCommandTools] toggle_layer failed:", err);
@@ -181,6 +229,7 @@ export function registerGlobeCommandTools(
"set_timeline",
{
description:
SESSION_REQUIRED_PREAMBLE +
"Set the globe timeline position, time window, or playback mode. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
"Prefer set_timeline over toggle_layer or pan_globe when adjusting time or playback, not layer visibility or camera position. " +
"Limitations: currentTime must be ISO 8601; timeWindow must be one of '1h','6h','24h','48h','7d'. " +
+131
View File
@@ -0,0 +1,131 @@
/**
* SEC-02: Redis per-key rate limiting in /api/mcp route tests.
*
* Verifies the post-auth Redis sliding-window gate behavior.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
// ---------------------------------------------------------------------------
// Top-level mocks (same surface as route.test.ts)
// ---------------------------------------------------------------------------
vi.mock("@/lib/apiKeyAuth", () => ({
authenticateApiKey: vi.fn(),
}));
vi.mock("@/core/edition", () => ({
isDemo: false,
edition: "local",
isLocal: true,
isCloud: false,
}));
vi.mock("@/lib/geocodingRateLimit", () => ({
redisSlidingWindow: vi.fn(),
}));
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
const McpServer = vi.fn(function McpServerMock(this: unknown) {
return {
connect: vi.fn().mockResolvedValue(undefined),
registerResource: vi.fn(),
registerTool: vi.fn(),
registerPrompt: vi.fn(),
};
});
const ResourceTemplate = vi.fn(function ResourceTemplateMock(this: unknown, uriTemplate: string) {
return { uriTemplate };
});
return { McpServer, ResourceTemplate };
});
vi.mock("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js", () => {
const WebStandardStreamableHTTPServerTransport = vi.fn().mockImplementation(() => ({
handleRequest: vi.fn().mockResolvedValue(
new Response(null, {
status: 200,
headers: {
"X-Accel-Buffering": "no",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
})
),
}));
return { WebStandardStreamableHTTPServerTransport };
});
// ---------------------------------------------------------------------------
// Imports (after mocks)
// ---------------------------------------------------------------------------
import { POST } from "./route";
import { authenticateApiKey } from "@/lib/apiKeyAuth";
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makePost(authorization?: string): Request {
const headers: Record<string, string> = {};
if (authorization) headers["authorization"] = authorization;
return new Request("http://localhost:3000/api/mcp", { method: "POST", headers });
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("SEC-02: per-key Redis rate limit gate", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
});
it("passes through when Redis allows the request", async () => {
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
const res = await POST(makePost("Bearer wwv_valid.token"));
expect(res.status).not.toBe(429);
});
it("returns 429 JSON-RPC -32000 when Redis rejects the request", async () => {
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: false, retryAfterMs: 60_000 });
const res = await POST(makePost("Bearer wwv_valid.token"));
const body = await res.json();
expect(res.status).toBe(429);
expect(body).toMatchObject({
jsonrpc: "2.0",
error: { code: -32000, message: "rate limit exceeded" },
id: null,
});
expect(res.headers.get("Retry-After")).toBe("60");
});
it("rate limit check uses the authenticated keyId, not userId or raw header", async () => {
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-abc", keyId: "key-xyz" });
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
await POST(makePost("Bearer wwv_valid.token"));
expect(vi.mocked(redisSlidingWindow)).toHaveBeenCalledWith(
expect.stringContaining("key-xyz"),
expect.any(Number),
expect.any(Number),
);
});
it("rate limit is not checked when auth fails (no authenticated keyId available)", async () => {
vi.mocked(authenticateApiKey).mockResolvedValue(null);
const res = await POST(makePost("Bearer bogus.token"));
expect(res.status).toBe(401);
expect(vi.mocked(redisSlidingWindow)).not.toHaveBeenCalled();
});
});
+112
View File
@@ -246,6 +246,31 @@ describe("MCP-01/MCP-02: Valid auth + non-demo -> request passes both gates", ()
});
});
// ---------------------------------------------------------------------------
// TRANS-04: tools.listChanged must NOT be advertised as true
// ---------------------------------------------------------------------------
describe("TRANS-04: McpServer is not created with tools.listChanged: true", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
});
it("capabilities passed to McpServer constructor have listChanged false or absent (never true)", async () => {
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
const mcpCtor = vi.mocked(McpServer);
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
await POST(req);
expect(mcpCtor).toHaveBeenCalledTimes(1);
// second arg is the options object: { instructions, capabilities }
const options = mcpCtor.mock.calls[0][1] as { capabilities?: { tools?: { listChanged?: boolean } } } | undefined;
const listChanged = options?.capabilities?.tools?.listChanged;
expect(listChanged).not.toBe(true);
});
});
// ---------------------------------------------------------------------------
// MCP-06: Streaming headers — X-Accel-Buffering: no must be present (Pitfall 1)
// ---------------------------------------------------------------------------
@@ -271,6 +296,93 @@ describe("MCP-06: Streaming response headers", () => {
});
});
// ---------------------------------------------------------------------------
// TRANS-01: Top-level error boundary — unexpected throws -> JSON-RPC -32603
// ---------------------------------------------------------------------------
describe("TRANS-01: unhandled error during request handling yields JSON-RPC -32603", () => {
beforeEach(() => {
vi.resetAllMocks();
});
it("POST returns HTTP 500 with JSON-RPC -32603 body when a registrar throws", async () => {
// Simulate an unexpected failure after auth succeeds (e.g. Redis down).
// We make authenticateApiKey succeed but then make registerOrientationPrompts
// throw by having McpServer.registerPrompt throw.
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
vi.mocked(McpServer).mockImplementationOnce(function (this: unknown) {
return {
connect: vi.fn().mockResolvedValue(undefined),
registerResource: vi.fn(),
registerTool: vi.fn(),
registerPrompt: vi.fn().mockImplementation(() => {
throw new Error("Redis connection refused");
}),
};
});
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
const res = await POST(req);
const body = await res.json();
expect(res.status).toBe(500);
expect(body).toEqual({
jsonrpc: "2.0",
id: null,
error: { code: -32603, message: "Internal error" },
});
});
it("GET returns HTTP 500 with JSON-RPC -32603 body when transport.handleRequest throws", async () => {
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
const { WebStandardStreamableHTTPServerTransport } = await import(
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
);
vi.mocked(WebStandardStreamableHTTPServerTransport).mockImplementationOnce(() => ({
handleRequest: vi.fn().mockRejectedValue(new Error("stream error")),
}));
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
const res = await GET(req);
const body = await res.json();
expect(res.status).toBe(500);
expect(body).toEqual({
jsonrpc: "2.0",
id: null,
error: { code: -32603, message: "Internal error" },
});
});
// Defense-in-depth: if authenticateApiKey ever regresses and throws instead
// of returning null, the boundary must still catch it and return -32603.
// In practice TRANS-02 makes authenticateApiKey return null on DB outage,
// so this path is hypothetical, not a real DB-outage scenario.
it("-32603 response carries streaming headers (X-Accel-Buffering: no) [defense-in-depth: hypothetical auth throw]", async () => {
vi.mocked(authenticateApiKey).mockRejectedValue(new Error("DB down"));
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
const res = await POST(req);
expect(res.status).toBe(500);
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
});
it("existing 401 path is NOT affected by the error boundary", async () => {
vi.mocked(authenticateApiKey).mockResolvedValue(null);
const req = makeRequest("POST");
const res = await POST(req);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error.code).toBe(-32600);
});
});
// ---------------------------------------------------------------------------
// MCP-05: Stateless freshness — per-request construction (Pitfall 2)
// ---------------------------------------------------------------------------
+47 -32
View File
@@ -31,6 +31,13 @@ import { isDemo } from "@/core/edition";
import { authenticateApiKey } from "@/lib/apiKeyAuth";
import { createMcpServer, registerOrientationPrompts } from "@/lib/mcp/server";
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
import {
demoBlockedResponse,
unauthorizedResponse,
rateLimitedResponse,
internalErrorResponse,
} from "@/lib/mcp/mcpResponseHelpers";
import { registerGlobeResources } from "./globeResources";
import { registerDataQueryTools } from "@/lib/mcp/tools";
import { registerGlobeCommandTools } from "./globeCommandTools";
@@ -42,38 +49,16 @@ import { registerFilterTools } from "./filterTools";
import { registerDiscoveryTools } from "./discoveryTools";
// ---------------------------------------------------------------------------
// JSON-RPC 2.0 error response helpers
// Route segment config (TRANS-03)
// 30 s is comfortably above the 10 s blpop ceiling in RELAY_DEADLINE_MS so the
// function never times out mid-relay. Vercel/Coolify honour this value.
// ---------------------------------------------------------------------------
/**
* Returns 403 + JSON-RPC 2.0 body for the demo edition gate (MCP-04).
* Runs BEFORE auth so the demo-admin FK write path is never reached.
*/
function demoBlockedResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32600, message: "MCP is not available in demo mode" },
id: null,
},
{ status: 403 },
);
}
export const maxDuration = 30;
/**
* Returns 401 + JSON-RPC 2.0 body for missing / invalid Bearer token (MCP-03).
* Content-Type is application/json (not plain text — Pitfall 3).
*/
function unauthorizedResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32600, message: "Unauthorized" },
id: null,
},
{ status: 401 },
);
}
// Per-key rate-limit budget (SEC-02): 120 requests per 60-second window.
const MCP_KEY_LIMIT = 120;
const MCP_WINDOW_MS = 60_000;
// ---------------------------------------------------------------------------
// Header merge helper
@@ -159,6 +144,18 @@ async function handleMcpRequest(request: Request): Promise<Response> {
return unauthorizedResponse();
}
// ------------------------------------------------------------------
// Gate 3: Redis per-key rate limit (SEC-02).
// 120 req / 60s per authenticated key, complementing the coarse IP
// gate above. Fails OPEN on Redis outage so a broken Redis never
// blocks legit users.
// ------------------------------------------------------------------
const keyRateKey = `mcp:ratelimit:key:${authResult.keyId}`;
const keyLimit = await redisSlidingWindow(keyRateKey, MCP_KEY_LIMIT, MCP_WINDOW_MS);
if (!keyLimit.allowed) {
return rateLimitedResponse(keyLimit.retryAfterMs);
}
// ------------------------------------------------------------------
// Build a FRESH server + transport per request (D-17-04, MCP-05).
// STATELESS INVARIANT: never hoist these to module scope.
@@ -230,14 +227,32 @@ async function handleMcpRequest(request: Request): Promise<Response> {
// Route exports (App Router)
// ---------------------------------------------------------------------------
/**
* Top-level error boundary (TRANS-01).
* Any throw between auth and transport (DB outage, Redis rejection, unexpected
* SDK error) is caught here so MCP clients always receive a well-formed
* JSON-RPC -32603 frame instead of a bare HTML 500.
* The bearer token/secret is never logged.
*/
async function safeHandleMcpRequest(request: Request): Promise<Response> {
try {
return await handleMcpRequest(request);
} catch (err: unknown) {
const name = err instanceof Error ? err.name : "unknown";
const detail = process.env.NODE_ENV !== "production" && err instanceof Error ? ` ${err.message}` : "";
console.error(`[mcp] unhandled error in request handler: ${name}${detail}`);
return internalErrorResponse();
}
}
export async function GET(request: Request): Promise<Response> {
return handleMcpRequest(request);
return safeHandleMcpRequest(request);
}
export async function POST(request: Request): Promise<Response> {
return handleMcpRequest(request);
return safeHandleMcpRequest(request);
}
export async function DELETE(request: Request): Promise<Response> {
return handleMcpRequest(request);
return safeHandleMcpRequest(request);
}
+8 -1
View File
@@ -30,7 +30,14 @@ export default function LoginForm() {
setLoading(true);
const formData = new FormData(e.currentTarget);
const result = await loginAction(formData);
let result;
try {
result = await loginAction(formData);
} catch {
setError("Something went wrong. Please try again.");
setLoading(false);
return;
}
if (result.success) {
const target = getSafeRedirect(next);
+5 -1
View File
@@ -28,6 +28,10 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
: "Something went wrong.",
};
}
throw error;
// Non-AuthError (e.g. DB unavailable, missing column, network issue):
// log server-side and return a safe generic message so the client
// never receives raw stack traces and loading state always resets.
console.error("[loginAction] unexpected error:", error);
return { success: false, error: "Something went wrong. Please try again." };
}
}
+8 -5
View File
@@ -24,6 +24,7 @@ export function BottomPanelManager() {
);
const isCoveredRef = useRef(false);
const isDraggingRef = useRef(false);
useEffect(() => {
if (activeBottomPanel) {
@@ -39,17 +40,18 @@ export function BottomPanelManager() {
}, [activeBottomPanel]);
// Pointer-capture drag handlers — attached directly to the resize handle element.
// Using setPointerCapture ensures pointermove/pointerup are delivered to the
// element even when the pointer leaves it, which is required for webkit
// (without capture, webkit drops synthetic pointermove events from Playwright
// and from fast real-user drags that leave the element bounds).
// setPointerCapture ensures pointermove/pointerup are delivered to the element even
// when the pointer leaves its bounds (required for fast real-user drags and Playwright).
// isDraggingRef guards the move handler instead of hasPointerCapture, which has
// inconsistent behaviour across webkit versions in CI for repeated drag sequences.
const handleResizePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
isDraggingRef.current = true;
document.body.classList.add("is-dragging-bottom-panel");
};
const handleResizePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
if (!isDraggingRef.current) return;
const newHeight = window.innerHeight - e.clientY;
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
setBottomPanelHeight(clampedHeight);
@@ -57,6 +59,7 @@ export function BottomPanelManager() {
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.releasePointerCapture(e.pointerId);
isDraggingRef.current = false;
document.body.classList.remove("is-dragging-bottom-panel");
};
@@ -0,0 +1,120 @@
"use client";
import { useState } from "react";
import { Copy, Check } from "lucide-react";
// ---------------------------------------------------------------------------
// Shared style tokens (mirror PersonalApiKeysSection to keep visual parity)
// ---------------------------------------------------------------------------
const inputStyle: React.CSSProperties = {
background: "var(--bg-tertiary)",
border: "1px solid var(--border-subtle)",
color: "var(--text-primary)",
padding: "var(--space-xs) var(--space-sm)",
borderRadius: "var(--radius-sm)",
fontSize: 12,
width: "100%",
outline: "none",
fontFamily: "var(--font-mono)",
};
const buttonStyle: React.CSSProperties = {
background: "none",
border: "1px solid var(--border-subtle)",
color: "var(--text-primary)",
borderRadius: "var(--radius-sm)",
padding: "var(--space-xs) var(--space-sm)",
fontSize: 12,
cursor: "pointer",
display: "flex",
alignItems: "center",
gap: "var(--space-xs)",
};
export const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
export const subHeaderStyle: React.CSSProperties = {
fontSize: 11,
fontWeight: 600,
color: "var(--text-secondary)",
textTransform: "uppercase",
letterSpacing: "0.08em",
marginBottom: "var(--space-xs)",
marginTop: "var(--space-md)",
};
// ---------------------------------------------------------------------------
// CopyField sub-component
// ---------------------------------------------------------------------------
const COPIED_RESET_MS = 1500;
interface CopyFieldProps {
value: string;
label: string;
multiline?: boolean;
}
export function CopyField({ value, label, multiline = false }: CopyFieldProps) {
const [copied, setCopied] = useState(false);
async function handleCopy() {
try {
await navigator.clipboard.writeText(value);
setCopied(true);
setTimeout(() => setCopied(false), COPIED_RESET_MS);
} catch {
// Clipboard access denied -- user must copy manually.
}
}
return (
<div style={{ marginBottom: "var(--space-sm)" }}>
<div style={mutedMicro}>{label}</div>
<div style={{ display: "flex", gap: "var(--space-xs)", marginTop: "var(--space-xs)" }}>
{multiline ? (
<textarea
readOnly
value={value}
rows={value.split("\n").length + 1}
style={{
...inputStyle,
resize: "vertical",
minHeight: 80,
}}
autoComplete="off"
data-lpignore="true"
data-form-type="other"
spellCheck={false}
/>
) : (
<input
type="text"
readOnly
value={value}
style={inputStyle}
autoComplete="off"
data-lpignore="true"
data-form-type="other"
spellCheck={false}
/>
)}
<button
type="button"
onClick={handleCopy}
style={{
...buttonStyle,
color: copied ? "#22c55e" : "var(--text-primary)",
flexShrink: 0,
alignSelf: "flex-start",
}}
title={copied ? "Copied!" : `Copy ${label}`}
>
{copied ? <Check size={12} /> : <Copy size={12} />}
{copied ? "Copied!" : "Copy"}
</button>
</div>
</div>
);
}
+44 -153
View File
@@ -14,15 +14,15 @@
* @module src/components/layout
*/
import { useState } from "react";
import { Copy, Check, Terminal } from "lucide-react";
import { Terminal, Info } from "lucide-react";
import { isCloud } from "@/core/edition";
import { CopyField, mutedMicro, subHeaderStyle } from "./ConnectAgentCopyField";
import { AGENT_PROMPT } from "./connectAgentPrompt";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const COPIED_RESET_MS = 1500;
const PLACEHOLDER_TOKEN = "wwv_<prefix>.<secret>";
/**
@@ -49,156 +49,6 @@ function resolveMcpUrl(): string {
return "http://localhost:3000/api/mcp";
}
// ---------------------------------------------------------------------------
// Shared style tokens (mirror PersonalApiKeysSection to keep visual parity)
// ---------------------------------------------------------------------------
const inputStyle: React.CSSProperties = {
background: "var(--bg-tertiary)",
border: "1px solid var(--border-subtle)",
color: "var(--text-primary)",
padding: "var(--space-xs) var(--space-sm)",
borderRadius: "var(--radius-sm)",
fontSize: 12,
width: "100%",
outline: "none",
fontFamily: "var(--font-mono)",
};
const buttonStyle: React.CSSProperties = {
background: "none",
border: "1px solid var(--border-subtle)",
color: "var(--text-primary)",
borderRadius: "var(--radius-sm)",
padding: "var(--space-xs) var(--space-sm)",
fontSize: 12,
cursor: "pointer",
display: "flex",
alignItems: "center",
gap: "var(--space-xs)",
};
const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
const subHeaderStyle: React.CSSProperties = {
fontSize: 11,
fontWeight: 600,
color: "var(--text-secondary)",
textTransform: "uppercase",
letterSpacing: "0.08em",
marginBottom: "var(--space-xs)",
marginTop: "var(--space-md)",
};
// ---------------------------------------------------------------------------
// CopyField sub-component
// ---------------------------------------------------------------------------
interface CopyFieldProps {
value: string;
label: string;
multiline?: boolean;
}
function CopyField({ value, label, multiline = false }: CopyFieldProps) {
const [copied, setCopied] = useState(false);
async function handleCopy() {
try {
await navigator.clipboard.writeText(value);
setCopied(true);
setTimeout(() => setCopied(false), COPIED_RESET_MS);
} catch {
// Clipboard access denied -- user must copy manually.
}
}
return (
<div style={{ marginBottom: "var(--space-sm)" }}>
<div style={mutedMicro}>{label}</div>
<div style={{ display: "flex", gap: "var(--space-xs)", marginTop: "var(--space-xs)" }}>
{multiline ? (
<textarea
readOnly
value={value}
rows={value.split("\n").length + 1}
style={{
...inputStyle,
resize: "vertical",
minHeight: 80,
}}
autoComplete="off"
data-lpignore="true"
data-form-type="other"
spellCheck={false}
/>
) : (
<input
type="text"
readOnly
value={value}
style={inputStyle}
autoComplete="off"
data-lpignore="true"
data-form-type="other"
spellCheck={false}
/>
)}
<button
type="button"
onClick={handleCopy}
style={{
...buttonStyle,
color: copied ? "#22c55e" : "var(--text-primary)",
flexShrink: 0,
alignSelf: "flex-start",
}}
title={copied ? "Copied!" : `Copy ${label}`}
>
{copied ? <Check size={12} /> : <Copy size={12} />}
{copied ? "Copied!" : "Copy"}
</button>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Agent-capabilities prompt (CONNECT-03)
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
// documented in docs/plugin-filter-guide.md.
// ---------------------------------------------------------------------------
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
incidents, weather, and custom data plugins.
This MCP connection is live and authenticated. You can call these tools:
Data query:
- search_entities: search entities by name across active plugins; supports optional inline filters.
- get_entities_in_region: find entities inside a lat/lng bounding box.
- get_entity_details: get full details for one entity by pluginId + entityId.
- get_plugin_data: get the current snapshot of all entities for a plugin.
Location (geocoding + camera):
- geocode_location: resolve a place name or address to coordinates and a bounding box.
- fly_to: fly the live globe camera to a coordinate or bounding box.
Favorites:
- save_favorite: bookmark an entity so the user can return to it later.
- list_favorites: list the user's bookmarks, each with a live/stale status.
- remove_favorite: delete a bookmarked entity.
Live filtering:
- get_plugin_filters: list the filterable fields a plugin declares.
- set_filter: apply filters to a plugin's layer on the live globe.
- clear_filter: clear one plugin's filters, or all filters.
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
to find places, move the camera, search and filter live entities, and manage their bookmarks.`;
// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
@@ -246,6 +96,47 @@ export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
Use the URL and token below to connect Claude Desktop, Cursor, or VS Code to this globe.
</div>
{/* Prerequisites callout (ONBRD-02) */}
<div style={{
display: "flex",
gap: "var(--space-sm)",
background: "var(--bg-tertiary)",
border: "1px solid var(--border-subtle)",
borderRadius: "var(--radius-sm)",
padding: "var(--space-sm) var(--space-md)",
marginTop: "var(--space-sm)",
}}
>
<Info size={13} style={{ color: "var(--text-muted)", flexShrink: 0, marginTop: 1 }} />
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-xs)" }}>
<div style={{ ...mutedMicro, fontWeight: 600, color: "var(--text-secondary)" }}>
Before connecting
</div>
<ul style={{ ...mutedMicro, margin: 0, paddingLeft: "var(--space-md)", lineHeight: 1.6 }}>
<li>
You must be <strong>signed in</strong> to WorldWideView. Your API key is tied to your account.
</li>
{isCloud && (
<li>
MCP access is a <strong>cloud edition</strong> feature. It is not available on the demo edition.
</li>
)}
<li>
<strong>Read/query tools</strong> (search, geocode, favorites, plugin data) work with just
your API key and do not require an open browser tab.
</li>
<li>
<strong>Command/control tools</strong> (pan_globe, fly_to, toggle_layer, set_filter, etc.)
require this WorldWideView tab to stay open and signed in. Without an open globe tab the
command is accepted but has no visible effect.
</li>
</ul>
<div style={mutedMicro}>
New here? Follow the MCP quickstart guide in the project docs (docs/mcp-quickstart.md) for step-by-step setup.
</div>
</div>
</div>
{/* Section: mcpServers JSON (CONNECT-02) */}
<div style={subHeaderStyle}>Claude Desktop / Cursor / VS Code</div>
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
@@ -0,0 +1,36 @@
/**
* Agent-capabilities prompt (CONNECT-03).
* Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
* with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
* documented in docs/plugin-filter-guide.md.
*/
export const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
incidents, weather, and custom data plugins.
This MCP connection is live and authenticated. You can call these tools:
Data query:
- search_entities: search entities by name across active plugins; supports optional inline filters.
- get_entities_in_region: find entities inside a lat/lng bounding box.
- get_entity_details: get full details for one entity by pluginId + entityId.
- get_plugin_data: get the current snapshot of all entities for a plugin.
Location (geocoding + camera):
- geocode_location: resolve a place name or address to coordinates and a bounding box.
- fly_to: fly the live globe camera to a coordinate or bounding box.
Favorites:
- save_favorite: bookmark an entity so the user can return to it later.
- list_favorites: list the user's bookmarks, each with a live/stale status.
- remove_favorite: delete a bookmarked entity.
Live filtering:
- get_plugin_filters: list the filterable fields a plugin declares.
- set_filter: apply filters to a plugin's layer on the live globe.
- clear_filter: clear one plugin's filters, or all filters.
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
to find places, move the camera, search and filter live entities, and manage their bookmarks.
Note: fly_to, set_filter, and clear_filter control the live globe and only take visible effect while you have a signed-in WorldWideView browser tab open. The read and query tools work with just your API key.`;
+18
View File
@@ -48,6 +48,24 @@ export const isCloud: boolean = edition === "cloud";
/** True when running as the public demo instance. */
export const isDemo: boolean = edition === "demo";
// ---------------------------------------------------------------------------
// Secure-context detection (https)
// ---------------------------------------------------------------------------
/**
* True when the deployment serves over https, derived from the configured auth
* URL or a production NODE_ENV. This is the request-independent half of the
* secure-context check: the NextAuth cookie WRITER (auth.ts) uses it to decide
* the secure flag / __Secure- cookie prefix, and the edge proxy READER (proxy.ts)
* ORs it with per-request X-Forwarded-Proto / protocol when reading the token.
* Centralised here so the writer and reader can never disagree on which cookie
* name is in play behind a TLS-terminating reverse proxy.
*/
export function isHttpsDeployment(): boolean {
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
return authUrl.startsWith("https://") || process.env.NODE_ENV === "production";
}
// ---------------------------------------------------------------------------
// Demo admin secret (must be before feature flags so they can reference it)
// ---------------------------------------------------------------------------
@@ -0,0 +1,125 @@
/**
* SEC-04: isValidGlobeCommand input cap tests.
*
* Verifies that toggleLayer, setFilter, and clearFilter enforce the
* layerId/pluginId charset and length bounds introduced in SEC-04.
*/
import { describe, it, expect } from "vitest";
import { isValidGlobeCommand } from "./GlobeCommand";
// ---------------------------------------------------------------------------
// toggleLayer -- layerId caps
// ---------------------------------------------------------------------------
describe("isValidGlobeCommand -- toggleLayer layerId caps (SEC-04)", () => {
it("accepts a normal plugin id", () => {
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ais" })).toBe(true);
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "wwv-flights-2" })).toBe(true);
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "plugin.v2" })).toBe(true);
});
it("rejects layerId longer than 64 chars", () => {
const long = "a".repeat(65);
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: long })).toBe(false);
});
it("accepts layerId of exactly 64 chars", () => {
const exact = "a".repeat(64);
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: exact })).toBe(true);
});
it("rejects layerId with spaces", () => {
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "bad id" })).toBe(false);
});
it("rejects layerId with colons (reserved for entityId)", () => {
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ship:123" })).toBe(false);
});
it("rejects empty layerId", () => {
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "" })).toBe(false);
});
it("rejects null layerId", () => {
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: null })).toBe(false);
});
});
// ---------------------------------------------------------------------------
// setFilter -- pluginId caps
// ---------------------------------------------------------------------------
describe("isValidGlobeCommand -- setFilter pluginId caps (SEC-04)", () => {
const validFilters = { status: { type: "text", value: "live" } };
it("accepts a normal plugin id", () => {
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: validFilters })).toBe(true);
});
it("rejects pluginId longer than 64 chars", () => {
const long = "a".repeat(65);
expect(isValidGlobeCommand({ type: "setFilter", pluginId: long, filters: validFilters })).toBe(false);
});
it("rejects pluginId with special chars outside the allowed set", () => {
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "bad id!", filters: validFilters })).toBe(false);
});
it("rejects empty pluginId", () => {
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: validFilters })).toBe(false);
});
});
// ---------------------------------------------------------------------------
// clearFilter -- pluginId caps (optional)
// ---------------------------------------------------------------------------
describe("isValidGlobeCommand -- clearFilter pluginId caps (SEC-04)", () => {
it("accepts a normal plugin id", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
});
it("accepts absent pluginId (clear all)", () => {
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
});
it("rejects oversized pluginId", () => {
const long = "x".repeat(65);
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: long })).toBe(false);
});
it("rejects pluginId with disallowed chars", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "a b" })).toBe(false);
});
});
// ---------------------------------------------------------------------------
// focusEntity -- entityId caps (MUST-FIX #1)
// ---------------------------------------------------------------------------
describe("isValidGlobeCommand -- focusEntity entityId caps (SEC-04)", () => {
it("accepts a normal entity id", () => {
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship:123" })).toBe(true);
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight/AFR123" })).toBe(true);
});
it("accepts absent entityId (coordinate-only focus)", () => {
expect(isValidGlobeCommand({ type: "focusEntity", lat: 35.68, lon: 139.69 })).toBe(true);
});
it("accepts entityId of exactly 256 chars", () => {
const exact = "a".repeat(256);
expect(isValidGlobeCommand({ type: "focusEntity", entityId: exact })).toBe(true);
});
it("rejects entityId longer than 256 chars", () => {
const long = "a".repeat(257);
expect(isValidGlobeCommand({ type: "focusEntity", entityId: long })).toBe(false);
});
it("rejects entityId with control characters", () => {
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship\x00123" })).toBe(false);
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight\n456" })).toBe(false);
});
});
+20 -10
View File
@@ -1,4 +1,5 @@
import type { FilterValue } from "@/core/plugins/PluginTypes";
import { PLUGIN_ID_MAX, PLUGIN_ID_RE, ENTITY_ID_MAX } from "@/lib/mcp/identifierSchemas";
// Must stay in sync with the TimeWindow union in @worldwideview/wwv-plugin-sdk.
export const TIME_WINDOW_VALUES = ["1h", "6h", "24h", "48h", "7d"] as const;
@@ -29,18 +30,27 @@ function isValidAlt(v: unknown): v is number {
return isNumber(v) && v > 0;
}
function isString(v: unknown): v is string {
return typeof v === "string";
// SEC-04: bounds come from identifierSchemas.ts (single source of truth)
function isValidPluginOrLayerId(v: unknown): v is string {
return typeof v === "string" && v.length > 0 && v.length <= PLUGIN_ID_MAX && PLUGIN_ID_RE.test(v);
}
function isValidEntityId(v: unknown): v is string {
return typeof v === "string" && v.length > 0 && v.length <= ENTITY_ID_MAX && !/[\x00-\x1F\x7F]/.test(v);
}
function isOptionalEntityId(v: unknown): boolean {
return v === undefined || isValidEntityId(v);
}
function isOptionalPluginOrLayerId(v: unknown): boolean {
return v === undefined || isValidPluginOrLayerId(v);
}
function isOptionalNumber(v: unknown): boolean {
return v === undefined || isNumber(v);
}
function isOptionalString(v: unknown): boolean {
return v === undefined || isString(v);
}
function isOptionalBoolean(v: unknown): boolean {
return v === undefined || typeof v === "boolean";
}
@@ -100,14 +110,14 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
case "focusEntity":
return (
isOptionalString(cmd["entityId"]) &&
isOptionalEntityId(cmd["entityId"]) &&
(cmd["lat"] === undefined || isValidLat(cmd["lat"])) &&
(cmd["lon"] === undefined || isValidLon(cmd["lon"]))
);
case "toggleLayer":
return (
isString(cmd["layerId"]) &&
isValidPluginOrLayerId(cmd["layerId"]) &&
isOptionalBoolean(cmd["enabled"])
);
@@ -136,14 +146,14 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
}
case "setFilter": {
if (typeof cmd["pluginId"] !== "string" || cmd["pluginId"] === "") return false;
if (!isValidPluginOrLayerId(cmd["pluginId"])) return false;
const filters = cmd["filters"];
if (filters === null || typeof filters !== "object" || Array.isArray(filters)) return false;
return Object.values(filters as Record<string, unknown>).every(isValidFilterValue);
}
case "clearFilter":
return isOptionalString(cmd["pluginId"]);
return isOptionalPluginOrLayerId(cmd["pluginId"]);
default:
return false;
+50
View File
@@ -375,3 +375,53 @@ describe("validateManifest no execution field required (MAN-04)", () => {
expect(hasExecutionError).toBe(false);
});
});
// ---------------------------------------------------------------------------
// SEC-URL: entry URL allowlist must host-match the PARSED hostname.
// Substring checks (includes / startsWith on the raw string) are bypassable
// and would allow an attacker-controlled origin to serve the imported bundle.
// ---------------------------------------------------------------------------
describe("validateManifest entry URL allowlist (security)", () => {
const ERR =
"entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain";
const accepts = (entry: string) => {
const result = validateManifest(baseManifest({ entry }));
expect(result.errors, `expected "${entry}" to be accepted`).not.toContain(ERR);
};
const rejects = (entry: string) => {
const result = validateManifest(baseManifest({ entry }));
expect(result.errors, `expected "${entry}" to be rejected`).toContain(ERR);
};
it("accepts relative and exact known-host absolute entries", () => {
accepts("/plugins/test/frontend.mjs");
accepts("./frontend.mjs");
accepts("https://unpkg.com/@wwv/plugin/frontend.mjs");
accepts("https://cdn.jsdelivr.net/npm/@wwv/plugin/frontend.mjs");
accepts("https://marketplace.worldwideview.dev/p/frontend.mjs");
accepts("https://worldwideview.dev/p/frontend.mjs");
accepts("http://localhost:3000/plugins/x/frontend.mjs");
accepts("http://127.0.0.1:5000/plugins/x/frontend.mjs");
accepts("http://[::1]:5000/plugins/x/frontend.mjs");
});
it("rejects substring-bypass hostnames the old check allowed", () => {
rejects("https://unpkg.com.evil.com/frontend.mjs");
rejects("https://cdn.jsdelivr.net.evil.com/frontend.mjs");
rejects("https://sub.worldwideview.dev.evil.com/frontend.mjs");
rejects("https://evil.com/#.worldwideview.dev");
rejects("https://evil.com/?x=.worldwideview.dev");
rejects("http://localhost.evil.com/frontend.mjs");
rejects("https://hacker.com/malicious.js");
});
it("rejects protocol-relative, slash-backslash, userinfo and non-http(s) scheme tricks", () => {
rejects("//evil.com/frontend.mjs");
rejects("/\\evil.com/frontend.mjs");
rejects("https://[email protected]/frontend.mjs");
rejects("javascript:alert(1)");
rejects("data:text/javascript,alert(1)");
});
});
+29 -13
View File
@@ -86,25 +86,41 @@ export function validateManifest(
errors.push("Missing required field: entry");
} else {
const entry = manifest.entry.trim();
const isRelative = entry.startsWith("/") || entry.startsWith("./");
const isLocal = entry.startsWith("http://localhost") || entry.startsWith("http://127.0.0.1");
const isWWV = entry.includes(".worldwideview.dev");
const isCDN = entry.startsWith("https://cdn.jsdelivr.net") || entry.startsWith("https://unpkg.com");
// A relative path starts with "/" or "./". Reject protocol-relative
// ("//host") and slash-backslash ("/\\host") forms: they start with "/"
// but resolve to an EXTERNAL origin when import()-ed.
const isRelative =
entry.startsWith("./") ||
(entry.startsWith("/") && entry[1] !== "/" && entry[1] !== "\\");
// Accept bundles served from a configured marketplace/instance host
// (e.g. marketplace.wwv.local) derived from env, so custom deployment
// hostnames work without being hardcoded.
let isConfiguredHost = false;
if (ENV_ALLOWED_ENTRY_HOSTS.size > 0) {
// Absolute entry URLs are host-matched against an allowlist using the
// PARSED hostname. Substring checks on the raw string (includes /
// startsWith) are bypassable, e.g. "https://unpkg.com.evil.com/x.mjs"
// or "https://sub.worldwideview.dev.evil.com/x.mjs", which would let an
// attacker-controlled origin serve the dynamically imported bundle (RCE).
let isAllowedHost = false;
if (!isRelative) {
try {
isConfiguredHost = ENV_ALLOWED_ENTRY_HOSTS.has(new URL(entry).hostname);
const url = new URL(entry);
const host = url.hostname;
const isSecure = url.protocol === "https:";
const isLocalhost =
(url.protocol === "http:" || isSecure) &&
(host === "localhost" || host === "127.0.0.1" || host === "[::1]");
const isWWV =
isSecure &&
(host === "worldwideview.dev" || host.endsWith(".worldwideview.dev"));
const isCDN = isSecure && (host === "cdn.jsdelivr.net" || host === "unpkg.com");
// Operator-configured hosts (from NEXT_PUBLIC_*MARKETPLACE_URL) are an
// explicit deployment opt-in, so their protocol is trusted as set.
const isConfiguredHost = ENV_ALLOWED_ENTRY_HOSTS.has(host);
isAllowedHost = isLocalhost || isWWV || isCDN || isConfiguredHost;
} catch {
// Relative paths and other non-absolute entries aren't parseable
// as full URLs — they're already covered by `isRelative`.
// Not a parseable absolute URL and not relative: rejected below.
}
}
if (!isRelative && !isLocal && !isWWV && !isCDN && !isConfiguredHost) {
if (!isRelative && !isAllowedHost) {
errors.push("entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain");
}
}
+2
View File
@@ -13,6 +13,8 @@ export const prisma = {
favorite: {
upsert: vi.fn(),
findMany: vi.fn(),
findUnique: vi.fn(),
count: vi.fn(),
delete: vi.fn(),
deleteMany: vi.fn(),
update: vi.fn(),
+169
View File
@@ -0,0 +1,169 @@
/**
* SEC-01: getSigningKey() enforcement tests.
*
* Each describe block uses vi.resetModules() + vi.doMock() to control
* the edition and environment independently -- the module-level mocks in
* apiKeyAuth.test.ts cannot be re-used here because they are static.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
userApiKey: {
findUnique: vi.fn(),
update: vi.fn(),
},
},
}));
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const ORIGINAL_ENV = { ...process.env };
beforeEach(() => {
// Restore env before each test so mutations do not bleed
process.env = { ...ORIGINAL_ENV };
});
afterEach(() => {
process.env = { ...ORIGINAL_ENV };
vi.resetModules();
vi.doUnmock("@/core/edition");
});
async function importGenerateApiKey() {
// Dynamic import after resetModules + doMock so the edition mock is picked up
const mod = await import("./apiKeyAuth");
return mod.generateApiKey;
}
// ---------------------------------------------------------------------------
// Local edition: AUTH_SECRET fallback must still work (dev DX)
// ---------------------------------------------------------------------------
describe("SEC-01: local edition -- AUTH_SECRET fallback is allowed", () => {
beforeEach(() => {
vi.resetModules();
vi.doMock("@/core/edition", () => ({
edition: "local",
isLocal: true,
isCloud: false,
isDemo: false,
}));
});
it("succeeds when only AUTH_SECRET is set (no API_KEY_HMAC_SECRET)", async () => {
delete process.env.API_KEY_HMAC_SECRET;
process.env.AUTH_SECRET = "some-auth-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).not.toThrow();
});
it("succeeds when API_KEY_HMAC_SECRET equals AUTH_SECRET in local edition", async () => {
process.env.API_KEY_HMAC_SECRET = "shared-secret";
process.env.AUTH_SECRET = "shared-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).not.toThrow();
});
it("throws only when neither key is set", async () => {
delete process.env.API_KEY_HMAC_SECRET;
delete process.env.AUTH_SECRET;
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).toThrow("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
});
});
// ---------------------------------------------------------------------------
// Cloud edition: dedicated key required, must differ from AUTH_SECRET
// ---------------------------------------------------------------------------
describe("SEC-01: cloud edition -- API_KEY_HMAC_SECRET required and distinct", () => {
beforeEach(() => {
vi.resetModules();
vi.doMock("@/core/edition", () => ({
edition: "cloud",
isLocal: false,
isCloud: true,
isDemo: false,
}));
});
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
delete process.env.API_KEY_HMAC_SECRET;
process.env.AUTH_SECRET = "some-auth-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).toThrow(
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
);
});
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
process.env.API_KEY_HMAC_SECRET = "shared-secret";
process.env.AUTH_SECRET = "shared-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).toThrow(
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
);
});
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-cloud";
process.env.AUTH_SECRET = "different-auth-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).not.toThrow();
});
});
// ---------------------------------------------------------------------------
// Demo edition: same enforcement as cloud
// ---------------------------------------------------------------------------
describe("SEC-01: demo edition -- API_KEY_HMAC_SECRET required and distinct", () => {
beforeEach(() => {
vi.resetModules();
vi.doMock("@/core/edition", () => ({
edition: "demo",
isLocal: false,
isCloud: false,
isDemo: true,
}));
});
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
delete process.env.API_KEY_HMAC_SECRET;
process.env.AUTH_SECRET = "some-auth-secret";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).toThrow(
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
);
});
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
process.env.API_KEY_HMAC_SECRET = "same";
process.env.AUTH_SECRET = "same";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).toThrow(
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
);
});
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-demo";
process.env.AUTH_SECRET = "different-auth-secret-demo";
const generateApiKey = await importGenerateApiKey();
expect(() => generateApiKey()).not.toThrow();
});
});
+14
View File
@@ -20,6 +20,9 @@ vi.mock("@/lib/db", () => ({
vi.mock("@/core/edition", () => ({
isDemo: false,
edition: "local",
isLocal: true,
isCloud: false,
}));
// AUTH_SECRET must be set so getSigningKey() does not throw in the test env
@@ -156,6 +159,17 @@ describe("authenticateApiKey", () => {
// compare is well-defined and does not throw.
});
it("returns null (does not throw) when Prisma findUnique rejects (DB outage — TRANS-02)", async () => {
vi.mocked(prisma.userApiKey.findUnique).mockRejectedValue(
new Error("Connection refused")
);
const req = new Request("http://localhost/api/test", {
headers: { authorization: "Bearer wwv_XXXXXXXX.fakesecret" },
});
// Must resolve to null, not reject
await expect(authenticateApiKey(req)).resolves.toBeNull();
});
it("hashedSecret is never returned to callers — result only contains userId and keyId", async () => {
const { prefix, secret, hashedSecret } = generateApiKey();
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue({
+38 -6
View File
@@ -1,14 +1,38 @@
import { randomBytes, createHmac, timingSafeEqual } from "crypto";
import { prisma } from "@/lib/db";
import { edition } from "@/core/edition";
import { isSigningKeyValid } from "@/lib/signingKeyConfig";
// ---------------------------------------------------------------------------
// Signing key for HMAC-SHA256 hashing of API key secrets.
// API_KEY_HMAC_SECRET is the preferred dedicated variable.
// Falls back to AUTH_SECRET so local dev works without adding a new .env entry.
// Falls back to AUTH_SECRET in local edition only, so dev works without a
// separate .env entry.
//
// Lazy enforcement (not a bare module-level throw): Next.js evaluates module
// code at build time and during edge prerender. A top-level throw would break
// `next build` in environments where these env vars are not yet populated.
// Throwing inside the function means the check fires only on the first real
// auth call, where a missing/shared key is an actual runtime problem.
// ---------------------------------------------------------------------------
function getSigningKey(): string {
const key = process.env.API_KEY_HMAC_SECRET ?? process.env.AUTH_SECRET;
const dedicated = process.env.API_KEY_HMAC_SECRET;
const fallback = process.env.AUTH_SECRET;
if (edition === "cloud" || edition === "demo") {
if (!isSigningKeyValid()) {
throw new Error(
`API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in ${edition} edition`,
);
}
// isSigningKeyValid() returning true guarantees dedicated is set and
// distinct from AUTH_SECRET for cloud/demo editions.
return dedicated as string;
}
// local edition: allow AUTH_SECRET fallback for convenience
const key = dedicated ?? fallback;
if (!key) throw new Error("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
return key;
}
@@ -116,10 +140,18 @@ export async function authenticateApiKey(
const prefix = token.substring(0, dotIdx);
const secret = token.substring(dotIdx + 1);
const row = await prisma.userApiKey.findUnique({
where: { prefix },
select: { id: true, userId: true, hashedSecret: true },
});
// DB outage guard (TRANS-02): a rejected Prisma call is treated as a miss
// so the caller receives null (-> 401) rather than an unhandled rejection.
let row: { id: string; userId: string; hashedSecret: string } | null;
try {
row = await prisma.userApiKey.findUnique({
where: { prefix },
select: { id: true, userId: true, hashedSecret: true },
});
} catch (err) {
console.warn("[apiKeyAuth] DB error during key lookup:", err instanceof Error ? err.name : "unknown");
return null;
}
// Compute HMAC of the supplied secret, then compare with timingSafeEqual.
// On a prefix miss we compare against a dummy digest — constant-work on
+45 -1
View File
@@ -18,8 +18,9 @@ vi.unmock("@/lib/auth");
// vi.hoisted() runs before all vi.mock() factories, so the variable is
// defined before the hoisted factory closure captures it.
// ---------------------------------------------------------------------------
const { mockUpsert } = vi.hoisted(() => ({
const { mockUpsert, mockFindUnique } = vi.hoisted(() => ({
mockUpsert: vi.fn().mockResolvedValue(undefined),
mockFindUnique: vi.fn(),
}));
vi.mock("@/lib/db", () => ({
@@ -27,6 +28,7 @@ vi.mock("@/lib/db", () => ({
user: {
upsert: mockUpsert,
findFirst: vi.fn(),
findUnique: mockFindUnique,
},
},
}));
@@ -54,6 +56,7 @@ vi.mock("@/core/edition", () => ({
isDemo: false,
getDemoAdminSecret: vi.fn(() => undefined),
DEMO_ADMIN_ROLE: "demo-admin",
isHttpsDeployment: vi.fn(() => false),
}));
vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
@@ -61,6 +64,7 @@ vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
import {
persistDemoAdminIfNeeded,
ensureLocalUserPersisted,
revalidateSession,
DEMO_ADMIN_ID,
DEMO_ADMIN_EMAIL,
DEMO_ADMIN_NAME,
@@ -148,3 +152,43 @@ describe("persistDemoAdminIfNeeded -- jwt callback guard", () => {
expect(mockUpsert).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// revalidateSession -- authoritative JWT revocation check
// ---------------------------------------------------------------------------
describe("revalidateSession -- jwt revocation check", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns null when the token carries no user id", async () => {
const result = await revalidateSession({});
expect(result).toBeNull();
expect(mockFindUnique).not.toHaveBeenCalled();
});
it("returns null when the user no longer exists in the DB (deleted / cross-database token)", async () => {
mockFindUnique.mockResolvedValue(null);
const result = await revalidateSession({ id: "missing-user", sessionVersion: 0 });
expect(result).toBeNull();
});
it("returns null when the token sessionVersion is stale (revoked / logout-everywhere)", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 3, role: "user" });
const result = await revalidateSession({ id: "u1", sessionVersion: 2 });
expect(result).toBeNull();
});
it("returns the token with role refreshed when the version matches", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 5, role: "admin" });
const result = await revalidateSession({ id: "u1", sessionVersion: 5, role: "user" });
expect(result).not.toBeNull();
expect((result as { role?: string }).role).toBe("admin");
});
it("treats a missing token sessionVersion as 0", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 0, role: "user" });
const result = await revalidateSession({ id: "u1" });
expect(result).not.toBeNull();
});
});
+75 -5
View File
@@ -3,8 +3,9 @@ import Credentials from "next-auth/providers/credentials";
import { compareSync } from "bcryptjs";
import { timingSafeEqual } from "crypto";
import { prisma } from "@/lib/db";
import type { JWT } from "next-auth/jwt";
import {
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE, isHttpsDeployment
} from "@/core/edition";
import { authConfig } from "@/lib/auth.config";
import { SupabaseAdapter } from "@auth/supabase-adapter";
@@ -91,6 +92,7 @@ const localCredentialsProvider = Credentials({
name: "Demo Admin",
email: "admin",
role: DEMO_ADMIN_ROLE,
sessionVersion: 0,
};
}
@@ -120,15 +122,72 @@ const localCredentialsProvider = Credentials({
name: user.name,
email: user.email,
role: user.role,
sessionVersion: user.sessionVersion,
};
},
});
// True when the deployment serves over https (session cookie gets the secure
// flag / __Secure- prefix). Shared with the edge proxy reader via
// isHttpsDeployment() so the cookie writer and reader never disagree on the
// __Secure- prefix behind a TLS-terminating reverse proxy.
const isSecureDeploy = isHttpsDeployment();
/**
* Authoritative session revocation check, run from the jwt callback on every
* non-sign-in request (local/demo editions). Returns the token unchanged when
* still valid, or `null` to invalidate the session when:
* - the user row no longer exists (deleted, or the token was minted against a
* different database, e.g. another worktree/instance even with a shared
* AUTH_SECRET), or
* - the user's sessionVersion was bumped (logout-everywhere / credential
* rotation), making the token's embedded version stale.
*/
export async function revalidateSession(token: JWT): Promise<JWT | null> {
const userId = token.id;
if (typeof userId !== "string" || !userId) return null;
const dbUser = await prisma.user.findUnique({
where: { id: userId },
select: { sessionVersion: true, role: true },
});
if (!dbUser) return null;
const tokenVersion = typeof token.sessionVersion === "number" ? token.sessionVersion : 0;
if (dbUser.sessionVersion !== tokenVersion) return null;
// Keep role fresh in case it changed server-side since the token was issued.
token.role = dbUser.role;
return token;
}
export const {
handlers, auth, signIn, signOut
} = NextAuth({
...authConfig,
session: { strategy: "jwt" },
session: {
strategy: "jwt",
// Bound the lifetime of the signature-only token. The edge proxy gate
// verifies the JWT signature but cannot reach the DB (no Prisma on the
// edge runtime), so a shorter maxAge limits how long a leaked-but-
// unexpired token can reach pages before the authoritative revocation
// check (revalidateSession) rejects it on any auth() call.
maxAge: 7 * 24 * 60 * 60, // 7 days
updateAge: 24 * 60 * 60, // sliding refresh, at most once per day
},
// Explicit, hardened cookie options. These pin NextAuth's secure defaults so
// they cannot silently regress: httpOnly blocks JS access (XSS token theft),
// sameSite=lax blocks cross-site sends (CSRF), secure requires https in prod.
cookies: {
sessionToken: {
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: isSecureDeploy,
},
},
},
adapter: isCloud ? SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
@@ -137,21 +196,32 @@ export const {
callbacks: {
...authConfig.callbacks,
async jwt({ token, user }) {
// Initial sign-in: copy identity claims from the authorized user.
if (user) {
token.role = (user as { role?: string }).role ?? "user";
token.role = user.role ?? "user";
token.id = user.id;
// Embed the user's current sessionVersion so the token can be
// compared against the DB on later requests and revoked.
token.sessionVersion = user.sessionVersion ?? 0;
// Persist the demo-admin synthetic identity on first sign-in so
// that the `users` FK target exists for API key creation. Runs
// only when `user` is present (initial sign-in, not token refresh).
// All values inside come from server-controlled constants.
await persistDemoAdminIfNeeded(user.id!, isCloud);
return token;
}
return token;
// Every subsequent request re-validates the token against the DB so
// that deleted users, cross-database tokens, and bumped
// sessionVersions are rejected. Cloud identities live in Supabase
// (no local `users` row), so they skip the Prisma comparison.
if (isCloud) return token;
return revalidateSession(token);
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
(session.user as { role?: string }).role = token.role as string;
session.user.role = token.role as string | undefined;
}
return session;
},
+12 -7
View File
@@ -11,7 +11,7 @@ import { matchFilterValue } from "@/core/filters/matchFilterValue";
import type { FilterValue } from "@/core/plugins/PluginTypes";
import { hasLocalSource, resolveLocalSnapshot, getLocalSourceIds } from "./localSources";
function getEngineUrl(): string {
export function getEngineUrl(): string {
return process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001";
}
@@ -211,27 +211,32 @@ export async function getEntitiesInRegion(bounds: RegionOptions): Promise<QueryR
}
}
const results: SearchResult[] = [];
// Collect all matches first to get a totalMatched count, then cap.
const allMatched: SearchResult[] = [];
for (const snapshot of snapshots) {
for (const entity of snapshot.entities) {
if (results.length >= effectiveLimit) break;
const { latitude: lat, longitude: lon } = entity;
if (lat < south || lat > north) continue;
const inLon = isAntimeridian
? lon >= west || lon <= east
: lon >= west && lon <= east;
if (inLon) results.push(entityToSearchResult(entity));
if (inLon) allMatched.push(entityToSearchResult(entity));
}
if (results.length >= effectiveLimit) break;
}
if (results.length === 0) {
if (allMatched.length === 0) {
return {
entities: [],
emptyReason: snapshotNotStreaming ? "plugin_not_streaming" : "no_data_matches",
};
}
return { entities: results };
const truncated = allMatched.length > effectiveLimit;
const results = truncated ? allMatched.slice(0, effectiveLimit) : allMatched;
return {
entities: results,
...(truncated && { totalMatched: allMatched.length }),
};
}
export async function getEntityDetails(
+7
View File
@@ -11,16 +11,23 @@ import type { FilterValue } from "@/core/plugins/PluginTypes";
* - no_session_active: the authenticated user has no active globe session.
* This value is emitted by the tool layer (which has access to userId),
* NEVER by the service layer.
*
* NOTE: data-query tools (search_entities, get_entities_in_region, get_entity_details,
* get_plugin_data) must NEVER emit no_session_active -- they are session-independent.
* Only session-required command/filter tools may produce this reason.
*/
export type EmptyReason = "plugin_not_streaming" | "no_data_matches" | "no_session_active";
/**
* Discriminated result carrying a list of entities and an optional emptyReason.
* emptyReason is ONLY present when entities.length === 0.
* totalMatched is set when results were capped (entities.length < totalMatched).
*/
export interface QueryResult<T> {
entities: T[];
emptyReason?: EmptyReason;
/** Total entities that matched before the cap was applied. Present only when the result set was truncated. */
totalMatched?: number;
}
/**
+118 -3
View File
@@ -1,5 +1,5 @@
/**
* Per-user sliding-window rate limiter for geocoding (Phase 22 Wave 2 -- 22-02).
* Per-user sliding-window rate limiter for geocoding (Phase 22 Wave 2, 22-02).
*
* Implements a Redis ZSET sliding window keyed per user. Each call prunes
* entries older than WINDOW_MS, records the current request, bounds the key
@@ -7,7 +7,7 @@
*
* Best-effort (T-22-02-05): on any Redis error we fail OPEN (return undefined)
* so a broken rate-limit check never causes a permanent geocoding outage. The
* 1 req/sec limit is advisory, not a hard security boundary.
* 1 req/sec limit is advisory rather than a hard security boundary.
*/
import { redis } from "@/lib/redis";
@@ -26,6 +26,11 @@ function rateKey(userId: string): string {
return `nominatim:ratelimit:${userId}`;
}
/** Returns a unique ZSET member string for the current timestamp. */
function uniqueMember(now: number): string {
return `${now}:${Math.random().toString(36).slice(2, 8)}`;
}
/**
* Returns `undefined` when the request is allowed, or a `rate_limited` result
* object when the per-user window limit is exceeded.
@@ -35,7 +40,7 @@ export async function checkRateLimit(userId: string): Promise<RateLimitExceeded
try {
const now = Date.now();
await redis.zremrangebyscore(key, "-inf", now - WINDOW_MS);
await redis.zadd(key, now, String(now));
await redis.zadd(key, now, uniqueMember(now));
await redis.expire(key, KEY_TTL_SECONDS);
const count = await redis.zcard(key);
if (count > MAX_REQUESTS) {
@@ -47,3 +52,113 @@ export async function checkRateLimit(userId: string): Promise<RateLimitExceeded
return undefined;
}
}
// ---------------------------------------------------------------------------
// Generic ZSET sliding-window helper (SEC-02)
//
// Reusable across any endpoint that needs per-identity Redis-backed limiting.
// Fails OPEN on Redis errors. A broken rate limiter should never block legit
// traffic. It is advisory rather than a hard security boundary.
// ---------------------------------------------------------------------------
export interface SlidingWindowResult {
/** true when the request is within the allowed window */
allowed: boolean;
/** milliseconds until the oldest request ages out; meaningful only when !allowed */
retryAfterMs: number;
}
/**
* ZSET sliding-window check.
*
* Uses unique members (timestamp + random suffix) so same-millisecond calls
* each occupy their own slot rather than collapsing into one (undercount fix).
*
* retryAfterMs is computed from the oldest in-window entry's score rather than
* the full windowMs, giving callers an accurate wait time.
*
* @param key Redis key (must be unique per identity + endpoint)
* @param limit Maximum requests allowed inside the window
* @param windowMs Window duration in milliseconds
*/
export async function redisSlidingWindow(
key: string,
limit: number,
windowMs: number,
): Promise<SlidingWindowResult> {
try {
const now = Date.now();
const windowStart = now - windowMs;
const ttlSeconds = Math.ceil(windowMs / 1_000) + 1;
await redis.zremrangebyscore(key, "-inf", windowStart);
await redis.zadd(key, now, uniqueMember(now));
await redis.expire(key, ttlSeconds);
const count = await redis.zcard(key);
if (count > limit) {
// Compute time until the oldest in-window member ages out.
const oldest = await redis.zrange(key, 0, 0, "WITHSCORES");
const oldestScore = oldest.length >= 2 ? Number(oldest[1]) : now;
const retryAfterMs = Math.max(1, oldestScore + windowMs - now);
return { allowed: false, retryAfterMs };
}
return { allowed: true, retryAfterMs: 0 };
} catch (err) {
console.warn("[redisSlidingWindow] Redis error, failing open:", err);
return { allowed: true, retryAfterMs: 0 };
}
}
// ---------------------------------------------------------------------------
// DEPLOY-03: peek helper for the global Nominatim throttle poll loop.
//
// Counts how many requests are currently in the window WITHOUT adding a new
// entry. Used by waitForGlobalSlot to poll for slot availability without
// inflating the ZSET on every iteration of the wait loop. The committing
// add happens only once, via redisSlidingWindow, when the slot is taken.
// ---------------------------------------------------------------------------
export interface SlidingWindowPeekResult {
/** Number of entries currently inside the window. */
count: number;
/** Milliseconds until the oldest in-window entry ages out (0 when count is 0). */
retryAfterMs: number;
}
/**
* Read-only ZSET sliding-window count.
*
* Prunes expired entries then counts, but does NOT add a new member.
* Fails OPEN (count: 0) on Redis errors so a Redis outage never stalls the
* wait loop indefinitely.
*
* @param key Redis key (same key passed to redisSlidingWindow)
* @param windowMs Window duration in milliseconds
*/
export async function redisSlidingWindowPeek(
key: string,
windowMs: number,
): Promise<SlidingWindowPeekResult> {
try {
const now = Date.now();
const windowStart = now - windowMs;
const ttlSeconds = Math.ceil(windowMs / 1_000) + 1;
await redis.zremrangebyscore(key, "-inf", windowStart);
await redis.expire(key, ttlSeconds);
const count = await redis.zcard(key);
if (count === 0) {
return { count: 0, retryAfterMs: 0 };
}
const oldest = await redis.zrange(key, 0, 0, "WITHSCORES");
const oldestScore = oldest.length >= 2 ? Number(oldest[1]) : now;
const retryAfterMs = Math.max(1, oldestScore + windowMs - now);
return { count, retryAfterMs };
} catch (err) {
console.warn("[redisSlidingWindowPeek] Redis error, failing open:", err);
return { count: 0, retryAfterMs: 0 };
}
}
+74
View File
@@ -0,0 +1,74 @@
/**
* SEC-03: getClientIp() tests.
*
* Verifies rightmost x-forwarded-for extraction and WWV_TRUSTED_IP_HEADER
* override behavior.
*/
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { getClientIp } from "./rateLimit";
const ORIGINAL_ENV = { ...process.env };
beforeEach(() => {
process.env = { ...ORIGINAL_ENV };
delete process.env.WWV_TRUSTED_IP_HEADER;
});
afterEach(() => {
process.env = { ...ORIGINAL_ENV };
});
function makeRequest(headers: Record<string, string>): Request {
return new Request("http://localhost/test", { headers });
}
describe("getClientIp -- rightmost x-forwarded-for (SEC-03)", () => {
it("returns the RIGHTMOST entry of x-forwarded-for (proxy-appended real IP)", () => {
const req = makeRequest({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 3.3.3.3" });
expect(getClientIp(req)).toBe("3.3.3.3");
});
it("handles single-entry x-forwarded-for correctly", () => {
const req = makeRequest({ "x-forwarded-for": "4.4.4.4" });
expect(getClientIp(req)).toBe("4.4.4.4");
});
it("trims whitespace from the rightmost entry", () => {
const req = makeRequest({ "x-forwarded-for": "1.1.1.1, 5.5.5.5 " });
expect(getClientIp(req)).toBe("5.5.5.5");
});
it("falls back to x-real-ip when x-forwarded-for is absent", () => {
const req = makeRequest({ "x-real-ip": "6.6.6.6" });
expect(getClientIp(req)).toBe("6.6.6.6");
});
it("returns 'unknown' when no IP header is present", () => {
const req = makeRequest({});
expect(getClientIp(req)).toBe("unknown");
});
});
describe("getClientIp -- WWV_TRUSTED_IP_HEADER override (SEC-03)", () => {
it("uses the override header when WWV_TRUSTED_IP_HEADER is set", () => {
process.env.WWV_TRUSTED_IP_HEADER = "cf-connecting-ip";
const req = makeRequest({
"cf-connecting-ip": "7.7.7.7",
"x-forwarded-for": "attacker-ip",
});
expect(getClientIp(req)).toBe("7.7.7.7");
});
it("falls back to x-forwarded-for when override header is missing from request", () => {
process.env.WWV_TRUSTED_IP_HEADER = "cf-connecting-ip";
const req = makeRequest({ "x-forwarded-for": "1.0.0.1, 8.8.8.8" });
expect(getClientIp(req)).toBe("8.8.8.8");
});
it("override header lookup is case-insensitive (HTTP headers are case-insensitive)", () => {
process.env.WWV_TRUSTED_IP_HEADER = "CF-Connecting-IP";
const req = makeRequest({ "cf-connecting-ip": "9.9.9.9" });
expect(getClientIp(req)).toBe("9.9.9.9");
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* Health probe helpers for GET /api/health.
*
* Each probe catches its own errors and resolves to a boolean.
* A probe must never throw out to the caller.
* All probes use short timeouts so a hung dependency cannot stall the response.
*/
import { redis } from "@/lib/redis";
import { prisma } from "@/lib/db";
import { getEngineUrl } from "@/lib/data-query/service";
import { isSigningKeyValid } from "@/lib/signingKeyConfig";
// Shared probe timeout in milliseconds.
const PROBE_TIMEOUT_MS = 2000;
// ---------------------------------------------------------------------------
// Timeout utility
// ---------------------------------------------------------------------------
/**
* Races a promise against a timer. The timer handle is always cleared in
* a finally block so no setTimeout handle dangles after the race resolves.
*
* Returns the fallback value when the timer fires first.
*/
function withTimeout<T>(op: Promise<T>, fallback: T, ms: number): Promise<T> {
let handle: ReturnType<typeof setTimeout>;
const timer = new Promise<T>((resolve) => {
handle = setTimeout(() => resolve(fallback), ms);
});
return Promise.race([op, timer]).finally(() => clearTimeout(handle));
}
// ---------------------------------------------------------------------------
// Redis
// ---------------------------------------------------------------------------
/** Returns true when ioredis can execute PING within the timeout. */
export async function probeRedis(): Promise<boolean> {
try {
const result = await withTimeout(redis.ping(), "TIMEOUT", PROBE_TIMEOUT_MS);
return result === "PONG";
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// Database
// ---------------------------------------------------------------------------
/** Returns true when Prisma can execute SELECT 1 within the timeout. */
export async function probeDb(): Promise<boolean> {
try {
// db.ts wraps PrismaClient in an `as unknown as PrismaClient` cast, so
// $queryRaw is present at runtime but absent from the inferred type.
const query = (prisma as unknown as { $queryRaw: (tpl: TemplateStringsArray) => Promise<unknown> })
.$queryRaw`SELECT 1`
.then(() => true)
.catch(() => false);
return await withTimeout(query, false, PROBE_TIMEOUT_MS);
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// Data engine
// ---------------------------------------------------------------------------
/**
* Returns true when the data engine manifest endpoint responds with 2xx.
* Uses getEngineUrl() from the data-query service so both resolve the same URL.
*/
export async function probeEngine(): Promise<boolean> {
const engineUrl = getEngineUrl() + "/manifest";
try {
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
return res.ok;
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// Config / HMAC signing key
// ---------------------------------------------------------------------------
/**
* Returns true when the HMAC signing-key preconditions are satisfied.
* Delegates to isSigningKeyValid() -- single source of truth for the rule.
*/
export function probeConfig(): boolean {
return isSigningKeyValid();
}
+45
View File
@@ -0,0 +1,45 @@
/**
* Shared Zod identifier schemas for MCP tool input validation (SEC-04).
*
* Single source of truth for plugin/layer id and entity id bounds.
* GlobeCommand.ts keeps its own runtime validator but imports the constants
* from here so the bounds are defined in exactly one place.
*/
import { z } from "zod";
/**
* Regex and max-length for plugin/layer identifiers.
* Exported so GlobeCommand.ts can reference the same values without
* importing Zod (a client-side module that should stay out of core types).
*/
export const PLUGIN_ID_MAX = 64;
export const PLUGIN_ID_RE = /^[a-zA-Z0-9_.-]+$/;
/** Entity identifier max length. */
export const ENTITY_ID_MAX = 256;
/**
* Plugin and layer identifiers: kebab/dotted ids, max 64 chars.
* Allows letters, digits, underscores, dots, and hyphens only.
*/
export const pluginIdSchema = z
.string()
.min(1)
.max(PLUGIN_ID_MAX)
.regex(PLUGIN_ID_RE, "must contain only letters, digits, underscores, dots, or hyphens");
/** Alias; same bounds as pluginIdSchema. */
export const layerIdSchema = pluginIdSchema;
/**
* Entity identifiers: permissive charset (allows colons, slashes, etc. used by
* real plugin entity ids such as "ship:123" or "flight/AFR123"), but rejects
* ASCII control characters (0x00-0x1F) and DEL (0x7F) which could corrupt logs
* or database queries.
*/
export const entityIdSchema = z
.string()
.min(1)
.max(ENTITY_ID_MAX)
.regex(/^[^\x00-\x1F\x7F]+$/, "must not contain control characters");
+77
View File
@@ -0,0 +1,77 @@
/**
* JSON-RPC 2.0 response helpers for the MCP route.
*
* Centralised here so route.ts stays under the ~300-line guideline and the
* same error shapes can be reused by future route handlers without duplication.
*/
/**
* Returns 403 + JSON-RPC 2.0 body for the demo edition gate (MCP-04).
* Runs BEFORE auth so the demo-admin FK write path is never reached.
*/
export function demoBlockedResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32600, message: "MCP is not available in demo mode" },
id: null,
},
{ status: 403 },
);
}
/**
* Returns 401 + JSON-RPC 2.0 body for missing/invalid Bearer token (MCP-03).
* Content-Type is application/json (not plain text, Pitfall 3).
*/
export function unauthorizedResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32600, message: "Unauthorized" },
id: null,
},
{ status: 401 },
);
}
/**
* Returns 429 + JSON-RPC 2.0 body when the authenticated key exceeds its
* per-window request budget (SEC-02). Code -32000 is the server-defined range.
*/
export function rateLimitedResponse(retryAfterMs: number): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32000, message: "rate limit exceeded" },
id: null,
},
{
status: 429,
headers: { "Retry-After": String(Math.ceil(retryAfterMs / 1_000)) },
},
);
}
/**
* Returns 500 + JSON-RPC 2.0 body for unexpected server errors (TRANS-01).
* Used by the top-level try/catch so MCP clients always receive a well-formed
* JSON-RPC error frame instead of a bare HTML 500 from Next.js.
*/
export function internalErrorResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
id: null,
error: { code: -32603, message: "Internal error" },
},
{
status: 500,
headers: {
"X-Accel-Buffering": "no",
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
},
},
);
}
+41 -22
View File
@@ -32,7 +32,7 @@ const SERVER_NAME = "worldwideview" as const;
export const MCP_SERVER_VERSION = "1.3.0" as const;
export const MCP_SERVER_INSTRUCTIONS = `\
You are a geospatial intelligence assistant connected to WorldWideView -- a live 3D globe that streams real-world data in real time. You control the globe and query its data on behalf of the authenticated user. All state is scoped to your API key: you only ever see and control your own sessions and data.
You are a geospatial intelligence assistant connected to WorldWideView, a live 3D globe that streams real-world data in real time. You control the globe and query its data on behalf of the authenticated user. All state is scoped to your API key: you only ever see and control your own sessions and data.
MENTAL MODEL
- Globe: a 3D interactive viewer running in the user's browser. Think of it as a live map you can steer.
@@ -40,28 +40,45 @@ MENTAL MODEL
- Sessions: open browser tabs showing the globe. Each tab is an independent session identified by a UUID.
CAPABILITIES
- Globe command tools (write/steer a live browser tab): pan_globe, focus_entity, toggle_layer, set_timeline.
- Data query tools (read shared engine data): search_entities, get_entities_in_region, get_entity_details, get_plugin_data.
- Globe command tools (require a live browser session): pan_globe, focus_entity, toggle_layer, set_timeline.
- Data query tools (server-side, NO session required): search_entities, get_entities_in_region, get_entity_details, get_plugin_data.
- Discovery tools: list_available_plugins, get_globe_context, investigate_area.
- Filter tools: set_filter, clear_filter, get_plugin_filters.
- Resources (read): globe://sessions, globe://state/{sessionId}, globe://layers.
- Plugin tools (dynamic): extra tools named "<pluginId>__<toolName>" appear only after a browser tab has loaded that plugin and published its catalog. Re-call tools/list after the relevant plugin is loaded.
- Plugin tools (dynamic): extra tools named "<pluginId>__<toolName>" appear after a browser tab loads that plugin. This server is stateless; re-call tools/list to discover them after enabling a plugin.
WORKFLOWS (follow these sequences -- order matters)
Rule 1 -- Before any command tool (pan_globe, toggle_layer, focus_entity, set_timeline): READ globe://sessions first to discover active sessions and their sessionIds. Calling a command without knowing the active session may target the wrong tab or fail silently.
Rule 2 -- Before calling get_plugin_data or get_entities_in_region for a specific plugin: CHECK tools/list for "<pluginId>__<toolName>" entries first. Plugin tools only appear after the relevant browser tab has loaded that plugin. If the tool is not listed, the plugin is not active yet.
Rule 3 -- Before calling fly_to or focus_entity for a named place: GEOCODE the place name first using the geocode tool to obtain precise coordinates. Do not guess lat/lon values.
SESSIONS (read before using any command tool)
- A session is one open browser tab showing the globe, identified by a UUID sessionId.
- To discover sessions, READ the resource globe://sessions. It returns the tabs active in the last ~45 seconds; a tab that goes quiet drops off the list.
- Every command tool takes an optional sessionId. Omit it to target your most-recently-active tab. Pass a sessionId from globe://sessions to target one specific tab. Commands are isolated per session and are never broadcast to other tabs.
- To see what a specific tab currently shows (camera, layers, timeline), read globe://state/{sessionId}.
- If no tab is active, command tools return "no active globe session to control" -- the user must open the app in a browser first.
COORDINATES
- latitude must be in [-90, 90], longitude in [-180, 180], altitude greater than 0 metres. Out-of-range values are rejected with a validation error.
TWO TOOL CATEGORIES
1. Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data) run on the server and return real data WITHOUT a browser session. emptyReason values: "plugin_not_streaming" (plugin not active), "no_data_matches" (query ran, nothing matched).
2. Command tools (pan_globe, focus_entity, toggle_layer, set_timeline, set_filter, clear_filter) enqueue browser commands. They require an active globe session and return "no active globe session to control" when none exists.
DATA AVAILABILITY
- Data query tools return {"success": true, "entities": [], "count": 0} when nothing matches OR when the live data engine is not currently feeding that plugin. An empty result is normal, not an error.`;
- list_available_plugins returns { "plugins": [] } with reason "engine_unreachable" when the data engine is down, or reason "no_active_plugins" when the engine is up but no plugins are streaming.
- Data query tools return emptyReason "plugin_not_streaming" when the plugin is not loaded, and "no_data_matches" when the plugin is streaming but no entities matched.
- Large result sets from get_entities_in_region or get_plugin_data are capped and return "truncated": true plus "totalMatched" for the full count.
- investigate_area uses "cappedTotal" instead of "totalMatched" because each matched plugin is itself capped at 100 entities, so the summed value is not the true global total.
RESPONSE SHAPES
- Data tool success: { "success": true, "entities": [...], "count": N }
- Data tool empty: { "success": true, "entities": [], "count": 0, "emptyReason": "..." }
- Truncated result (region/snapshot capped): adds "truncated": true, "totalMatched": N
- investigate_area truncated: adds "truncated": true, "cappedTotal": N (sum of per-plugin capped results)
- Discovery (list_available_plugins): { "plugins": [...] } or { "plugins": [], "reason": "engine_unreachable" | "no_active_plugins" }
- Command success: plain text confirmation
- Command no-session: plain text "no active globe session to control"
- Command unknown id: plain text warning including "is not a recognized plugin"
WORKFLOWS (follow these sequences, order matters)
Rule 1: Before any command tool, READ globe://sessions to discover active sessions. Calling a command without knowing the active session may target the wrong tab.
Rule 2: Before calling get_plugin_data or get_entities_in_region, call list_available_plugins to confirm the plugin is active.
Rule 3: Before focus_entity or pan_globe for a named place, geocode the place name first.
SESSIONS
- To discover sessions, READ globe://sessions. It returns tabs active in the last ~45 seconds.
- Every command tool takes an optional sessionId. Omit to target the most-recently-active tab.
- To see what a tab currently shows, read globe://state/{sessionId}.
COORDINATES
- latitude in [-90, 90], longitude in [-180, 180], altitude greater than 0 metres.`;
/**
* Returns a fresh, empty-capability McpServer per call.
@@ -75,9 +92,11 @@ export function createMcpServer(): McpServer {
{
instructions: MCP_SERVER_INSTRUCTIONS,
capabilities: {
// tools.listChanged: required so Phase 21 can push live tool
// list updates to clients (RECONCILIATION R-1).
tools: { listChanged: true },
// tools.listChanged is false: this stateless server constructs a
// fresh McpServer per request and cannot push notifications to
// connected clients. Clients must re-call tools/list to pick up
// plugin tools added after the browser loads a new plugin (TRANS-04).
tools: { listChanged: false },
},
},
);
+11
View File
@@ -0,0 +1,11 @@
/**
* Shared MCP tool-description fragments.
*
* SESSION_REQUIRED_PREAMBLE is prepended to every command/control tool
* description so the live-open-tab requirement (ONBRD-03) is stated identically
* everywhere. Command tools enqueue to a per-session Redis queue that only a
* live, signed-in browser tab drains; without an open tab the command is
* accepted but has no visible effect.
*/
export const SESSION_REQUIRED_PREAMBLE =
"Requires a live, signed-in WorldWideView browser tab; without an open globe tab the command is accepted but has no visible effect. ";
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more