Compare commits

...
Author SHA1 Message Date
Antigravity AI 7f587b5e36 docs(plugin): add bundle footguns -- CSP/CSS, inlineDynamicImports, process.env, CORS 2026-05-29 10:40:16 +12:00
Antigravity AI ee0559a52f fix(sync): add process.env replacement, inlineDynamicImports, and CSS copy to syncToPublic
- Inline replace-process-env Rollup plugin transforms process.env.NODE_ENV to "production"
  to prevent ReferenceError in browser bundles that lack a Node.js environment
- Switch codeSplitting to inlineDynamicImports: true so the build produces a single
  self-contained ES module with no bare chunk specifiers that the browser cannot resolve
- Add rollup-plugin-external-globals to remap shared host deps (react, cesium, zustand, SDK)
  to globalThis.__WWV_HOST__.* at bundle time
- syncToPublic now copies any .css files emitted alongside the .mjs bundle (e.g. from
  gridstack or other CSS-importing libs) into public/plugins-local/<id>/
2026-05-29 10:40:16 +12:00
dependabot[bot]andAntigravity AI aef92c1d58 build(deps): bump the dependencies group across 1 directory with 13 updates (#202)
* build(deps): bump the dependencies group across 1 directory with 13 updates

Bumps the dependencies group with 13 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@sentry/nextjs](https://github.com/getsentry/sentry-javascript) | `10.53.1` | `10.54.0` |
| [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js) | `2.106.0` | `2.106.2` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.16.0` | `1.17.0` |
| [stripe](https://github.com/stripe/stripe-node) | `22.1.1` | `22.2.0` |
| [ws](https://github.com/websockets/ws) | `8.20.1` | `8.21.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.7.0` | `25.9.1` |
| [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) | `19.2.14` | `19.2.15` |
| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) | `8.59.4` | `8.60.0` |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `8.59.4` | `8.60.0` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.6` | `4.1.7` |
| [tsx](https://github.com/privatenumber/tsx) | `4.22.2` | `4.22.3` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.13` | `8.0.14` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.6` | `4.1.7` |



Updates `@sentry/nextjs` from 10.53.1 to 10.54.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.53.1...10.54.0)

Updates `@supabase/supabase-js` from 2.106.0 to 2.106.2
- [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.106.2/packages/core/supabase-js)

Updates `lucide-react` from 1.16.0 to 1.17.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.17.0/packages/lucide-react)

Updates `stripe` from 22.1.1 to 22.2.0
- [Release notes](https://github.com/stripe/stripe-node/releases)
- [Changelog](https://github.com/stripe/stripe-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-node/compare/v22.1.1...v22.2.0)

Updates `ws` from 8.20.1 to 8.21.0
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.20.1...8.21.0)

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

Updates `@types/react` from 19.2.14 to 19.2.15
- [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.59.4 to 8.60.0
- [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.0/packages/eslint-plugin)

Updates `@typescript-eslint/parser` from 8.59.4 to 8.60.0
- [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.0/packages/parser)

Updates `@vitest/coverage-v8` from 4.1.6 to 4.1.7
- [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.7/packages/coverage-v8)

Updates `tsx` from 4.22.2 to 4.22.3
- [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.2...v4.22.3)

Updates `vite` from 8.0.13 to 8.0.14
- [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.14/packages/vite)

Updates `vitest` from 4.1.6 to 4.1.7
- [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.7/packages/vitest)

---
updated-dependencies:
- dependency-name: "@sentry/nextjs"
  dependency-version: 10.54.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.106.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: lucide-react
  dependency-version: 1.17.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: stripe
  dependency-version: 22.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: ws
  dependency-version: 8.21.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@types/node"
  dependency-version: 25.9.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@types/react"
  dependency-version: 19.2.15
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.60.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.60.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: tsx
  dependency-version: 4.22.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vite
  dependency-version: 8.0.14
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vitest
  dependency-version: 4.1.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>

* fix(stripe): update apiVersion to 2026-05-27.dahlia for [email protected]

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Antigravity AI <[email protected]>
2026-05-29 10:38:08 +12:00
b5f8c9ff32 feat(globe): add weather radar overlay with OpenWeatherMap tile proxy (#153)
* feat(globe): add weather radar overlay with OpenWeatherMap tile proxy

Adds a complete weather overlay system: server-side tile proxy that
hides the OWM API key, Cesium imagery layer integration at 60% opacity,
and a dropdown in Graphics settings to toggle between clouds,
precipitation, temperature, wind, and pressure layers.

Closes #10.

* fix(weather): address PR #153 review feedback

- Remove console.error from tile proxy catch block
- Validate tile x/y against zoom-level upper bound (2^z) and cap zoom at 18
- Fix useEffect race condition in weather overlay with cancelled flag
- Replace stale enableFxaa/msaaSamples in DEFAULT_GRAPHICS with antiAliasing
- Extract shared WEATHER_LAYERS constant into src/lib/weatherLayers.ts
- Normalize indentation in GraphicsSettings.tsx

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

* fix(globe): consolidate weather overlay cleanup into return function

Remove eager top-of-body removal of weatherLayerRef that created a
double-removal pattern. The cleanup function already handled removal
via a local layer variable with a ref guard; the eager removal was
redundant and fragile under React 18 concurrent scheduling.

Also drop the unused cancelled flag (UrlTemplateImageryProvider is
synchronous, so the flag could never flip true inside the effect body).

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Antigravity AI <[email protected]>
2026-05-29 10:34:14 +12:00
Silvertakana a7d96f208f feat: Phase 2 install auth gate (ADR-003 closeout) (#192)
* fix(e2e): guard marketplace webServer and exclude per-app tests from main Playwright config

Root cause: playwright.config.ts unconditionally started the marketplace dev server at
../worldwideview-marketplace. In CI only worldwideview is checked out, so spawn() received
a non-existent cwd which Node.js surfaces as "spawn /bin/sh ENOENT", crashing the entire
test run before any browser launched.

Two targeted fixes:
1. Wrap the marketplace webServer entry in fs.existsSync(MARKETPLACE_DIR) so CI skips it
   gracefully. Use playwright.marketplace.config.ts to run cross-app marketplace tests locally.
2. Add testIgnore for web-auth.spec.ts and marketplace-from-instance.spec.ts — both target
   sibling repos (worldwideview-web / worldwideview-marketplace) and have their own dedicated
   configs (playwright.web.config.ts / playwright.marketplace.config.ts). The main config
   should only exercise the worldwideview app itself.

* feat(09-02): add playwright.cross-app.config.ts and .env.test for cross-origin specs

- Add playwright.cross-app.config.ts with dual webServer array (wwv.local:3001 + marketplace.wwv.local:3002)
- testMatch targets both upcoming cross-app spec files; baseURL set to marketplace.wwv.local:3002
- Create worldwideview/.env.test with PLAYWRIGHT_TEST_EMAIL + PLAYWRIGHT_TEST_PASSWORD (gitignored)
- Add explicit .env.test entry to .gitignore (was not covered by existing .env/.env.local patterns)
- Bump version 2.20.2 -> 2.21.0 (feat: minor)

* feat(09-02): add cross-app Playwright specs for redirect handshake and sign-out (REQ-16)

- Add marketplace-redirect-handshake.spec.ts: 2 tests verifying next= param construction and login-then-redirect-back flow
- Add marketplace-sign-out.spec.ts: 1 test verifying avatar dropdown sign-out clears session and returns to marketplace home
- Update playwright.cross-app.config.ts to load .env.test credentials via fs (no dotenv package required)
- All specs target https://marketplace.wwv.local:3002 (never localhost:3002) for correct .wwv.local cookie domain
- 3 tests total listed by playwright --list

* feat: add planning-sync hook script for .planning branch isolation

* fix: guard planning-sync against missing .planning, wrong repo, and silent checkout failures

- Exit early if .planning/.git doesn't exist (avoids false-success on machines without the private repo)
- Exit early if CWD is not a worldwideview repo or worktree (prevents syncing from wwv-data-engine etc.)
- Wrap both checkout calls in exit-code checks so failures emit WARNING messages instead of false success

* feat: add post-checkout hook for .planning auto-sync

* fix: add existence guard to post-checkout hook before calling planning-sync

* docs: add .planning branch convention to worktree-bootstrap skill

* feat(11-01): add LegalFooter component and .legal-footer CSS class

- Create src/components/layout/LegalFooter.tsx as a Server Component
- Export named function LegalFooter with two external anchors
- Both anchors use target="_blank" rel="noopener noreferrer" (T-11-01)
- Links target locked URLs: privacy-policy and cloud-terms-of-service
- Append .legal-footer + a + a:hover rules to globals.css
- position:fixed bottom:0 z-index:10 per UI-SPEC
- Bump version 2.23.2 -> 2.23.3

* feat(11-01): remove Vercel Analytics, mount LegalFooter in root layout

- Remove @vercel/analytics/next import from layout.tsx (D-02)
- Remove {process.env.VERCEL && <Analytics />} JSX (D-02, T-11-02)
- Add import { LegalFooter } from @/components/layout/LegalFooter
- Render <LegalFooter /> as last child of <body> (D-04)
- Remove @vercel/analytics from dependencies in package.json
- Regenerate pnpm-lock.yaml after dependency removal
- AdSense block (lines 27-37) untouched per D-03
- Bump version 2.23.3 -> 2.23.4

* fix(worktree): fix link_planning hook path conversion for Windows

Worktrunk substitutes {{ worktree_path }} as a Unix-style path
(/c/dev/...) which cmd.exe cannot resolve. It also strips $ sigils
from variable names before executing hook commands, making inline
PowerShell variables unusable.

Extract junction logic to .agents/scripts/link-planning.ps1 and
unlink-planning.ps1. The hooks now call powershell -File with
the path as an argument, avoiding both issues entirely.

* docs: add ADR-004 and phase-2 implementation plans

Adds the Supabase session cookies httponly ADR alongside the six
implementation plan documents produced during the auth gate phase.

* feat(auth): implement Phase 2 cloud auth gate (ADR-003 closeout)

- Cloud edition login page redirects to NEXT_PUBLIC_AUTH_HOST_URL;
  local/demo editions keep the NextAuth credentials form
- Delete signup pages and Supabase PKCE callback route from worldwideview
  (auth host owns them per ADR-003)
- Add Supabase SSR helpers (cookieOptions, server, client) with
  httpOnly:true cookies per ADR-004
- Dual-dispatch install-redirect and grant-token: Supabase on cloud,
  NextAuth on local/demo; redirect param unified to ?next=
- Add streaming mode to safeFetch for MJPEG camera proxy streams
- Extract LoginForm into its own component
- Update Playwright config to conditionally start marketplace dev server

* fix(types): cast undici ReadableStream body to BodyInit to satisfy DOM types

node:stream/web ReadableStream is structurally incompatible with the DOM
ReadableStream expected by the Response constructor -- the pipeThrough
signature differs on the T | undefined generic bound. Cast to BodyInit
(which is the correct type for the streaming pass-through) to resolve
the TS2345 error in ssrf.ts line 112.

* fix(e2e): exclude cross-app marketplace specs from default Playwright run

marketplace-redirect-handshake.spec.ts and marketplace-sign-out.spec.ts
require a running marketplace.wwv.local:3002 instance (cross-app
environment). They were being picked up by playwright.config.ts in CI
where that host does not exist, causing ERR_NAME_NOT_RESOLVED failures.
Added both files to testIgnore alongside the existing exclusions; they
should be run via playwright.cross-app.config.ts only.

* fix: add pointer event support to bottom panel resize for webkit

Playwright's webkit engine dispatches pointermove/pointerup reliably
during synthetic drags but mousemove sometimes does not fire. Add
pointermove and pointerup listeners alongside the existing mouse
listeners, and add onPointerDown to the drag handle, so the resize
test passes across all three browser engines.
2026-05-28 21:03:14 +12:00
devangpratap eeec748d41 fix(globe): enable Cesium World Terrain for non-Google 3D mode (#167) (#174) 2026-05-28 11:27:48 +12:00
Silvertakana 08308f2588 fix(gc): narrow mdc-ref detector to eliminate false positives (#199)
* feat(marketplace): pass from_instance origin when opening marketplace

BrowseLink in PluginsTab now appends ?from_instance=<origin> so the
marketplace can silently capture the instance URL into localStorage,
skipping the manual InstanceConfig modal for users arriving from the app.

* test(e2e): add marketplace instance auto-discovery E2E tests

- playwright.marketplace.config.ts: standalone config that starts only
  the marketplace on port 3002, no Docker/Postgres required
- tests/marketplace-from-instance.spec.ts: 4 marketplace-side tests
  (capture valid URL, reject javascript: protocol, reject self-origin,
  skip when no param) + 1 full-flow test (worldwideview -> marketplace,
  auto-skipped when running under marketplace-only config)
- NEXT_PUBLIC_MARKETPLACE_URL env var in BrowseLink lets tests point
  to localhost:3002 instead of the production marketplace
- data-testid="browse-plugins-btn" for stable Playwright selector
- playwright.config.ts updated with both webServers for full E2E

Run marketplace tests (no Docker): pnpm exec playwright test --config=playwright.marketplace.config.ts
Run full E2E (Docker required):    pnpm test:e2e

* feat: implement Phase 2 install auth gate (ADR-003 closeout)

Closes the three foundational auth gaps that blocked a proper install gate:

2A - SSR session persistence:
- Add @supabase/ssr; create src/lib/supabase/{cookieOptions,server,client}.ts
  mirroring the marketplace recipe so both repos issue the same cookie type
- Migrate login/actions.ts from @supabase/supabase-js to createServerClient
  (previously the Supabase session was discarded; no cookie was ever set)
- Fix getSafeRedirect to allow trusted subdomain callbacks via
  NEXT_PUBLIC_WWV_COOKIE_DOMAIN so marketplace ?callbackUrl= round-trips work
- Add NEXT_PUBLIC_WWV_COOKIE_DOMAIN and NEXT_PUBLIC_AUTH_HOST_URL to .env.example

2B - Signup route at auth host:
- Add /signup page and server action (supabase.auth.signUp with emailRedirectTo)
- Add /auth/callback route to handle Supabase PKCE email verification exchange
- Add "Sign up" link to login page preserving ?callbackUrl=

2C - Install auth gate:
- Swap NextAuth auth() for Supabase getSupabaseUser() in install-redirect route
  (local/demo edition still uses NextAuth)

2D - Sweep:
- httpOnly: true added to buildCookieOptions()
- cloud-auth-architecture.md superseded section collapsed to forward-pointer
- ADR-003 status updated to Accepted with implementation notes

* chore: exclude .planning from git (moved to private repo)

* chore(05-01): add Playwright config and E2E specs for worldwideview-web auth UI

- playwright.web.config.ts: targets https://wwv.local:3001 with ignoreHTTPSErrors
- tests/web-auth.spec.ts: 4 describe groups covering reset-password form, /accounts redirect, /auth/verify no-code error, /auth/reset-password/confirm no-hash timeout
- bump version 2.20.0 -> 2.20.1

* fix(gc): narrow mdc-ref detector to eliminate false positives

Pattern now requires a quoted string context (['\"].*\.mdc['\"]) and
only scans .ts/.tsx files, excluding scripts/. Prevents the scanner
from flagging its own source code and rule documentation that explain
the anti-pattern rather than violating it.
2026-05-28 11:27:21 +12:00
Silvertakana 14909a3504 fix(security): remove allow-popups from iframe sandbox and drop iframe proxy CORS (#197)
- CameraStream.tsx: drop allow-popups from proxied iframe sandbox — third-party
  camera pages have no legitimate reason to open new windows; eliminates a
  phishing popup vector from compromised or malicious camera providers
- iframe/route.ts: remove Access-Control-Allow-Origin: * and delete the OPTIONS
  handler — the iframe proxy is only consumed same-origin so CORS headers served
  no purpose and only advertised unnecessary cross-origin access
2026-05-26 22:54:17 +12:00
SilvertakanaandClaude 6a3484e1a3 fix: transliterate diacritical characters in place and airport names (#196)
Special characters (Š, Č, Ž, Đ, etc.) were rendering as garbled glyphs
in the UI because the display environment lacks font coverage for those
code points. Adds a shared transliterate() utility that decomposes
characters via NFD and strips combining diacritical marks, with a
supplemental map for characters that don't decompose cleanly (Đ, Ø, Ł,
ß, etc.). Applied at both Places API routes (search + details) and the
GeoJSON entity converter so all place/airport name sources are covered.

Fixes: [email protected] report – May 13-14 2026 Discord.

Co-authored-by: Claude <[email protected]>
2026-05-26 22:44:17 +12:00
Silvertakana 0400dc56b4 fix(camera): bypass proxy for youtube-nocookie.com embeds (#195)
* fix(camera): fix camera stream not displaying — CSP frame-ancestors and HTTP SSRF block

- next.config.ts: add path-scoped header override for /api/camera/proxy/:path*
  setting frame-ancestors 'self' and X-Frame-Options SAMEORIGIN so proxy iframe
  responses are not blocked by the global frame-ancestors 'none' policy
- ssrf.ts: extend validateOrigin to accept http:// URLs; the stream proxy is a
  server-side bridge that must fetch plain-HTTP camera feeds before re-serving
  them over HTTPS to the browser to avoid mixed-content blocks
- ssrf.spec.ts: update validateOrigin tests to match new HTTP-allowed behaviour;
  add explicit rejection tests for ftp://, file://, data://, javascript://
- scripts/boot-db.mjs: create .env from .env.example in worktrees when missing
  so DATABASE_URL injection block is never silently skipped

* fix(camera): sandbox proxied iframes and unblock external stylesheets

The CSP override for /api/camera/proxy/:path* still inherited the app's
restrictive style-src/script-src, which blocked external stylesheets and
scripts inside proxied iframes (YouTube, third-party players, etc).
Relax proxy CSP to default-src * while keeping frame-ancestors 'self'.

Because the proxy iframe is same-origin with the host app, this widened
CSP would have let upstream HTML reach window.parent.localStorage / DOM.
Add sandbox="allow-scripts allow-popups allow-presentation" (no
allow-same-origin) to proxied iframes so they run in an opaque origin
and cannot touch the host app. Major-platform iframes (YouTube/Twitch/
Vimeo) bypass the proxy and remain unsandboxed since the browser already
isolates them via cross-origin.

- next.config.ts: proxy CSP -> default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; frame-ancestors 'self'
- CameraStream.tsx: add sandbox attribute to proxied (non-major-platform) iframes

* fix(camera): add youtube-nocookie.com to major-platform bypass list

getYouTubeEmbedUrl() converts youtube.com watch URLs to youtube-nocookie.com
embed URLs, but the majorPlatformHosts allowlist in CameraStream.tsx was
missing youtube-nocookie.com. This caused YouTube embeds to be routed
through the iframe proxy + sandbox, which broke the YouTube player (Cache
Storage disabled, RUM analytics blocked, writeEmbed not defined).

youtube-nocookie.com is now treated the same as youtube.com: loaded
cross-origin directly without proxying, relying on the browser's same-origin
policy for isolation.
2026-05-26 17:13:52 +12:00
Silvertakana 8a8165eeea fix(camera): camera proxy display + iframe sandbox hardening (#194)
* fix(camera): fix camera stream not displaying — CSP frame-ancestors and HTTP SSRF block

- next.config.ts: add path-scoped header override for /api/camera/proxy/:path*
  setting frame-ancestors 'self' and X-Frame-Options SAMEORIGIN so proxy iframe
  responses are not blocked by the global frame-ancestors 'none' policy
- ssrf.ts: extend validateOrigin to accept http:// URLs; the stream proxy is a
  server-side bridge that must fetch plain-HTTP camera feeds before re-serving
  them over HTTPS to the browser to avoid mixed-content blocks
- ssrf.spec.ts: update validateOrigin tests to match new HTTP-allowed behaviour;
  add explicit rejection tests for ftp://, file://, data://, javascript://
- scripts/boot-db.mjs: create .env from .env.example in worktrees when missing
  so DATABASE_URL injection block is never silently skipped

* fix(camera): sandbox proxied iframes and unblock external stylesheets

The CSP override for /api/camera/proxy/:path* still inherited the app's
restrictive style-src/script-src, which blocked external stylesheets and
scripts inside proxied iframes (YouTube, third-party players, etc).
Relax proxy CSP to default-src * while keeping frame-ancestors 'self'.

Because the proxy iframe is same-origin with the host app, this widened
CSP would have let upstream HTML reach window.parent.localStorage / DOM.
Add sandbox="allow-scripts allow-popups allow-presentation" (no
allow-same-origin) to proxied iframes so they run in an opaque origin
and cannot touch the host app. Major-platform iframes (YouTube/Twitch/
Vimeo) bypass the proxy and remain unsandboxed since the browser already
isolates them via cross-origin.

- next.config.ts: proxy CSP -> default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; frame-ancestors 'self'
- CameraStream.tsx: add sandbox attribute to proxied (non-major-platform) iframes
2026-05-26 16:43:24 +12:00
Silvertakana 02336e6a0a fix(security): Phase 3 audit blockers — PKCE cookie path + WsClient subscribe race (#190)
* fix(incidents): add mapWebsocketPayload default to BaseIncidentPlugin

Default unwraps three WsClient-visible payload shapes:
- scheduler envelope { source, fetchedAt, items, totalCount } -> items
- GeoJSON FeatureCollection { features: [...] } -> normalised GeoEntity[]
- flat GeoEntity[] -> passthrough (with timestamp normalisation)

Resolves the silent-drop bug that left the earthquakes plugin showing an empty
layer when the scheduler's standard wrapping was used. Subclasses can still
override mapWebsocketPayload for domain-specific shapes (iranwarlive pattern
preserved by 2 override tests).

Test deltas:
- 2 it.fails tests flipped to passing (scheduler-wrap, GeoJSON unwrap).
- 2 'currently drops' companion tests deleted (bug is fixed, companions obsolete).
- 1 structural test updated: 'does NOT have mapWebsocketPayload' -> 'has mapWebsocketPayload defined'.
- Net: 12 tests -> 10 tests, all passing.

* test(ssrf): replace placeholder assertions with real tests for DNS pinning and size limits

The two expect(true).toBe(true) stubs in ssrf.spec.ts are replaced with
assertions that verify actual SSRF guard behavior:

- "enforces maxSize" — mocks undici.fetch to return an 11-byte body with a
  10-byte limit; verifies response.text() rejects with "size exceeded"
- "does not follow redirects" — mocks dns.lookup + undici.fetch; verifies
  redirect:manual is passed, fetch is called once, and the 301 is returned
  without being followed; also asserts dispatcher is set (DNS pinning)

Uses vi.hoisted + vi.mock to patch dns/promises and undici at module level.
360/360 tests pass.

* fix(security): close Phase 3 audit blockers and unregistered flags

- WsClient.ts: guard subscribe() against sending frames while awaitingWelcome=true;
  prevents pre-auth subscribe race when a second plugin subscribes mid-handshake
- connect/route.ts + callback/route.ts: set PKCE cookie path="/" to satisfy
  RFC 6265bis __Host- prefix requirement (Chromium silently rejects __Host- + path!=/)
- pkce.spec.ts: update assertion to match corrected path="/"
- docs/plans/03-SECURITY.md: security audit report (13 closed, 1 fixed, 3 flags filed)
2026-05-25 00:58:13 +12:00
Silvertakana d4d259cd23 fix(incidents): add mapWebsocketPayload default to BaseIncidentPlugin (#189)
* fix(incidents): add mapWebsocketPayload default to BaseIncidentPlugin

Default unwraps three WsClient-visible payload shapes:
- scheduler envelope { source, fetchedAt, items, totalCount } -> items
- GeoJSON FeatureCollection { features: [...] } -> normalised GeoEntity[]
- flat GeoEntity[] -> passthrough (with timestamp normalisation)

Resolves the silent-drop bug that left the earthquakes plugin showing an empty
layer when the scheduler's standard wrapping was used. Subclasses can still
override mapWebsocketPayload for domain-specific shapes (iranwarlive pattern
preserved by 2 override tests).

Test deltas:
- 2 it.fails tests flipped to passing (scheduler-wrap, GeoJSON unwrap).
- 2 'currently drops' companion tests deleted (bug is fixed, companions obsolete).
- 1 structural test updated: 'does NOT have mapWebsocketPayload' -> 'has mapWebsocketPayload defined'.
- Net: 12 tests -> 10 tests, all passing.

* test(ssrf): replace placeholder assertions with real tests for DNS pinning and size limits

The two expect(true).toBe(true) stubs in ssrf.spec.ts are replaced with
assertions that verify actual SSRF guard behavior:

- "enforces maxSize" — mocks undici.fetch to return an 11-byte body with a
  10-byte limit; verifies response.text() rejects with "size exceeded"
- "does not follow redirects" — mocks dns.lookup + undici.fetch; verifies
  redirect:manual is passed, fetch is called once, and the 301 is returned
  without being followed; also asserts dispatcher is set (DNS pinning)

Uses vi.hoisted + vi.mock to patch dns/promises and undici at module level.
360/360 tests pass.
2026-05-24 21:38:44 +12:00
Silvertakana 175ed5c4e2 test(incidents): guard tests for BaseIncidentPlugin WebSocket payload contract (#188)
12 tests across 4 describe blocks document the WsClient payload contract:
- 2 it.fails tests assert the DESIRED post-fix unwrap behaviour for the canonical
  scheduler envelope { source, fetchedAt, items, totalCount } and GeoJSON
  FeatureCollection { features: [...] } shapes — currently fail because
  BaseIncidentPlugin has no mapWebsocketPayload.
- 2 companion 'currently drops' tests explicitly document the live silent-drop
  behaviour so anyone reading the file understands the failure mode.
- 4 working-behaviour tests assert flat GeoEntity[] passthrough, timestamp
  normalisation, and subclass override precedence — must stay green.
- 4 structural-contract tests document missing mapWebsocketPayload, required
  lifecycle methods, polling interval, and layer config defaults.

The it.fails tests will flip to passing in the follow-up fix PR, at which point
the 2 'currently drops' companions are deleted and the 'does NOT have
mapWebsocketPayload' assertion is updated.
2026-05-24 13:55:35 +12:00
Silvertakana dc83f97be4 feat(auth): ADR-001 Workstream C — ticket auth, SSRF, and WebSocket first-message auth (#180)
* docs: add ADR-003 document and update cloud-auth-architecture superseded notice

* chore: bump version for ADR-001 Workstream C

* fix: remove stray 'r' prefix on import in places/details route

rimport typo on line 1 of src/app/api/places/details/route.ts caused
TS1435 (unknown keyword), ESLint parse error, and a webpack build failure
in Docker CI. Corrected to a valid import statement.
2026-05-23 16:16:31 +12:00
Silvertakana 7f7d7588f3 fix(docker): auto-baseline Prisma P3005 on container startup (#181)
* fix: add id-token write permission and fix invalid inputs in GC workflow

The claude-code-action@v1 uses OIDC for OAuth token auth, which requires
id-token: write in workflow permissions. Without it ACTIONS_ID_TOKEN_REQUEST_URL
is not set and the action fails after 3 retry attempts.

Also moves model and allowed_tools from unsupported top-level inputs into
claude_args where they are valid CLI flags for claude-code-action@v1.

* fix(gc): show agent output and explicit dry-run issue posting

- Add show_full_output: true so Claude responses appear in CI logs
- Replace vague dry-run instruction with explicit gh issue create/comment
  commands so output has a concrete destination (tracking issue)
- Bake DRY_RUN value into prompt at workflow-expansion time to eliminate
  ambiguity about env var reading

* docs: mark cloud-auth-architecture.md as superseded by ADR-003

* fix(docker): guard community seeder cd and add ENCRYPTION_MASTER_KEY default

- Wrap `cd $SEEDERS_DIR/community` in an existence check so the
  data-engine container no longer crashes when local-seeders/community/
  is an empty or uncloned nested git repo. The container was entering
  Docker's exponential-backoff restart loop (2s→60s) on every boot.
- Add ENCRYPTION_MASTER_KEY to the wwv environment block with a
  local-dev fallback, matching the AUTH_SECRET pattern. Without it the
  Next.js instrumentation hook throws at startup and the app never
  serves a request.

* fix(docker): auto-baseline P3005 when schema exists without migration history

Wraps prisma migrate deploy in the container entrypoint to detect P3005
(schema populated by pnpm dev / prisma db push before the Docker stack was
started). When detected, runs prisma migrate diff to confirm zero schema
drift, then marks each migration as applied via migrate resolve --applied
and retries deploy. Exits with a clear error if drift is found.

Also documents the auto-baseline behavior in database-migrations.md and
fixes duplicate section numbering in that file.
2026-05-23 16:11:13 +12:00
Silvertakana b9c6d193a4 fix(docker): guard community seeder cd and add ENCRYPTION_MASTER_KEY default (#179)
* fix: add id-token write permission and fix invalid inputs in GC workflow

The claude-code-action@v1 uses OIDC for OAuth token auth, which requires
id-token: write in workflow permissions. Without it ACTIONS_ID_TOKEN_REQUEST_URL
is not set and the action fails after 3 retry attempts.

Also moves model and allowed_tools from unsupported top-level inputs into
claude_args where they are valid CLI flags for claude-code-action@v1.

* fix(gc): show agent output and explicit dry-run issue posting

- Add show_full_output: true so Claude responses appear in CI logs
- Replace vague dry-run instruction with explicit gh issue create/comment
  commands so output has a concrete destination (tracking issue)
- Bake DRY_RUN value into prompt at workflow-expansion time to eliminate
  ambiguity about env var reading

* docs: mark cloud-auth-architecture.md as superseded by ADR-003

* fix(docker): guard community seeder cd and add ENCRYPTION_MASTER_KEY default

- Wrap `cd $SEEDERS_DIR/community` in an existence check so the
  data-engine container no longer crashes when local-seeders/community/
  is an empty or uncloned nested git repo. The container was entering
  Docker's exponential-backoff restart loop (2s→60s) on every boot.
- Add ENCRYPTION_MASTER_KEY to the wwv environment block with a
  local-dev fallback, matching the AUTH_SECRET pattern. Without it the
  Next.js instrumentation hook throws at startup and the app never
  serves a request.
2026-05-23 15:17:31 +12:00
Silvertakana 062adaf9d3 fix: add id-token write permission and fix invalid inputs in GC workflow (#177)
The claude-code-action@v1 uses OIDC for OAuth token auth, which requires
id-token: write in workflow permissions. Without it ACTIONS_ID_TOKEN_REQUEST_URL
is not set and the action fails after 3 retry attempts.

Also moves model and allowed_tools from unsupported top-level inputs into
claude_args where they are valid CLI flags for claude-code-action@v1.
2026-05-23 01:28:38 +12:00
Silvertakana 1cf4074eb3 fix: remove hardcoded pnpm version from GC workflow (#176) 2026-05-23 01:23:41 +12:00
79 changed files with 6821 additions and 1336 deletions

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Syncs .planning git branch to match the active worldwideview branch.
# Called by: Claude Code SessionStart hook, git post-checkout hook.
# Convention: .planning branch name == worldwideview branch name.
# Falls back to main if no matching .planning branch exists.
PLANNING_DIR="C:/dev/wwv/.planning"
# Exit silently if .planning repo doesn't exist on this machine
if [ ! -d "$PLANNING_DIR/.git" ]; then
exit 0
fi
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
# Exit if not in a git repo or in detached HEAD state
if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
exit 0
fi
# Only sync if CWD is worldwideview or a worktree of it
GIT_COMMON=$(git rev-parse --git-common-dir 2>/dev/null)
if ! echo "$GIT_COMMON" | grep -qi "worldwideview"; then
exit 0
fi
# Skip if .planning is already on the right branch
PLANNING_CURRENT=$(git -C "$PLANNING_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ "$PLANNING_CURRENT" = "$CURRENT_BRANCH" ]; then
exit 0
fi
# Skip if .planning has uncommitted changes (don't clobber in-progress work)
if ! git -C "$PLANNING_DIR" diff --quiet 2>/dev/null || ! git -C "$PLANNING_DIR" diff --cached --quiet 2>/dev/null; then
echo "{\"continue\":true,\"suppressOutput\":false,\"message\":\"[planning-sync] Skipping: .planning has uncommitted changes\"}"
exit 0
fi
# Switch to matching branch, or fall back to main
if git -C "$PLANNING_DIR" branch --list "$CURRENT_BRANCH" | grep -q .; then
if git -C "$PLANNING_DIR" checkout "$CURRENT_BRANCH" --quiet 2>/dev/null; then
echo "{\"continue\":true,\"suppressOutput\":false,\"message\":\"[planning-sync] .planning -> $CURRENT_BRANCH\"}"
else
echo "{\"continue\":true,\"suppressOutput\":false,\"message\":\"[planning-sync] WARNING: checkout of '$CURRENT_BRANCH' failed\"}"
fi
else
if git -C "$PLANNING_DIR" checkout main --quiet 2>/dev/null; then
echo "{\"continue\":true,\"suppressOutput\":false,\"message\":\"[planning-sync] No branch '$CURRENT_BRANCH' in .planning; staying on main\"}"
else
echo "{\"continue\":true,\"suppressOutput\":false,\"message\":\"[planning-sync] WARNING: fallback checkout to main failed\"}"
fi
fi
+13 -19
View File
@@ -8,6 +8,9 @@ paths:
- "src/core/tenant.ts"
---
> **SUPERSEDED by ADR-003** (`docs/architecture/decisions/adr-0003-shared-identity-and-ecosystem-auth-host.md`).
> The auth host is `worldwideview.dev` (worldwideview-web repo), not `app.worldwideview.dev`. Read ADR-003 first.
# WorldWideView — Cloud & Auth Architecture
@@ -19,25 +22,16 @@ paths:
## Auth Strategy
**Auth.js (NextAuth)** is the single auth API across all editions. `app.worldwideview.dev` owns **all auth UI** — login, registration, password reset. No other subdomain ever shows a login or registration form.
```typescript
// src/lib/auth.ts
const providers = isCloud
? [SupabaseProvider({ /* delegates to Supabase Auth (GoTrue) */ })]
: [Credentials({ /* local bcrypt + PostgreSQL */ })];
export const { auth, signIn, signOut } = NextAuth({ providers });
```
Application code is **identical** across editions — always calls `auth()`, `signIn()`, `signOut()`.
**One account for the entire ecosystem:**
- Cloud instance (`[user].app.worldwideview.dev`)
- Marketplace (browse, install, publish) — via SSO redirect
- Local instance Bridge API connection
**Marketplace never owns auth UI** — it redirects to `app.worldwideview.dev/login?redirect_to=marketplace...` for all sign-in.
> [!NOTE]
> **See [ADR-003](../../docs/architecture/decisions/adr-0003-shared-identity-and-ecosystem-auth-host.md) for the canonical auth architecture.**
> The implementation described below (NextAuth as ecosystem IdP, `app.worldwideview.dev` as auth host) was superseded on 2026-05-22. Phase 2A-D (completed 2026-05-25) implemented the ADR-003 architecture:
> - **Supabase Auth** is the identity provider for the cloud edition
> - **`worldwideview.dev`** owns login, signup, and auth callback routes (`/login`, `/signup`, `/auth/callback`)
> - **NextAuth** (Credentials provider) remains active for the local and demo editions only
> - Session cookies use `@supabase/ssr` `createServerClient` scoped to `NEXT_PUBLIC_WWV_COOKIE_DOMAIN`
> - Both worldwideview and worldwideview-marketplace use the same `buildCookieOptions()` recipe
>
> The multi-tenant RLS, tier matrix, license key, and CI/CD sections below remain valid.
---
+14 -2
View File
@@ -13,10 +13,22 @@ When making database schema changes, you must ensure that generated migrations a
- **Add "IF EXISTS" clauses**: Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs, manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
- **Data Preservation**: When dropping columns or renaming, carefully review the migration to ensure data is correctly mapped. In PostgreSQL, ensure that cascaded drops don't accidentally remove required data.
## 2. Managing Failed Migrations
## 2. P3005 Auto-Baseline (Handled in `docker-entrypoint.sh`)
`docker-entrypoint.sh` automatically recovers from Prisma **P3005** ("schema not empty, no migration history"). This happens when `pnpm dev` (which runs `prisma db push`) populates the database before the Docker stack is started.
The entrypoint only auto-baselines when **both** conditions hold:
1. The error is exactly P3005.
2. `prisma migrate diff` reports zero schema drift between the live DB and `prisma/schema.prisma`.
If drift is detected the container exits with a clear error message directing you to `pnpm db:reset`.
> **Never add manual `migrate resolve --applied` calls** unless you are outside the container and have independently verified the above two conditions. The entrypoint already handles the common case.
## 3. Managing Failed Migrations
If a migration fails in production:
- **Never blindly mark as resolved**: Do not run `prisma migrate resolve --applied <migration_name>` unless you have explicitly verified that the database schema precisely matches the expected state.
- If you use `resolve --applied`, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
## 3. Backups Before DDL
## 4. Backups Before DDL
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database without first confirming an automated backup exists, or manually taking a `pg_dump` backup of the database.
+93
View File
@@ -486,3 +486,96 @@ Seeders in `wwv-data-engine/src/seeders/` provide the backend data.
- **Cron Seeder**: Uses `registerSeeder({ name: "plugin-id", cron: "..." })` and pushes to Redis via `setLiveSnapshot()`.
- **Init Seeder**: High-frequency or persistent websockets via `init: () => void`.
- **Constraint**: Seeder `name` MUST exactly match the frontend plugin `id`. Do not bundle workspace dependencies like `ws` or `zod` into the seeder `dist`.
---
## Plugin Bundle Footguns
### 1. CSP blocks CDN stylesheets -- use `?inline` + `<style>` injection
The host app's `style-src` policy includes `'unsafe-inline'` but does **not** include external CDN origins like `unpkg.com` or `cdn.jsdelivr.net`. Any plugin that loads CSS via a runtime `<link href="https://unpkg.com/...">` will have that stylesheet **silently blocked** by the browser -- no console error, just broken styling and broken layout (elements fall back to `position: static`).
**Wrong:**
```typescript
// In useEffect:
link.href = "https://unpkg.com/gridstack@11/dist/gridstack.min.css";
document.head.appendChild(link);
```
**Correct -- bundle CSS as inline string and inject via `<style>` tag:**
```typescript
import gridstackCSS from "gridstack/dist/gridstack.min.css?inline";
// In useEffect:
const style = document.createElement("style");
style.textContent = gridstackCSS;
document.head.appendChild(style);
```
Vite's `?inline` suffix imports CSS as a plain string. The `<style>` tag is allowed by `'unsafe-inline'`. This is the only CSP-safe pattern for third-party CSS in plugin bundles.
---
### 2. `inlineDynamicImports: true` -- not `codeSplitting: false`
`codeSplitting: false` is **not a valid Rollup option**. It is silently ignored, and Rollup will still produce code-split chunks. The host can only load a single `frontend.mjs` -- any sibling chunk (e.g. `gridstack-XXXXX.js`) will 404.
**Wrong:**
```js
rollupOptions: {
output: { codeSplitting: false } // silently ignored
}
```
**Correct:**
```js
rollupOptions: {
output: { inlineDynamicImports: true } // prevents all code splitting
}
```
Both `vite.config.ts` (for manual `pnpm build`) and `scripts/sync-local-plugins.mjs` must use `inlineDynamicImports: true`.
---
### 3. `process.env.NODE_ENV` in CJS deps -- needs inline Rollup transform, not Vite `define`
CJS dependencies like `recharts`, `prop-types`, and `react-is` reference `process.env.NODE_ENV` inside their CommonJS module body. Vite's top-level `define: { 'process.env.NODE_ENV': '"production"' }` does NOT reach inside Rollup's `__commonJSMin()` wrappers -- those run after the `define` substitution phase.
**Wrong:**
```js
// In vite.config.ts or sync-local-plugins.mjs:
define: { 'process.env.NODE_ENV': '"production"' } // doesn't reach CJS wrappers
```
**Correct -- add an inline Rollup transform plugin inside `rollupOptions.plugins`:**
```js
rollupOptions: {
plugins: [
{
name: 'replace-process-env',
transform(code) {
if (!code.includes('process.env.NODE_ENV')) return null;
return {
code: code.replace(/process\.env\.NODE_ENV/g, '"production"'),
map: null,
};
},
},
// ... other plugins
]
}
```
This plugin runs on each module source before Rollup wraps it, so it correctly replaces `process.env.NODE_ENV` in CJS sub-dependencies.
---
### 4. Yahoo Finance and third-party data APIs -- CORS from the browser
Yahoo Finance's chart API (`query1.finance.yahoo.com`) does **not** return `Access-Control-Allow-Origin` headers. Direct `fetch()` from a plugin bundle running in the browser will be CORS-blocked.
**Architectural preference (in order):**
1. **Best:** Have the wwv-data-engine seeder fetch the data server-side and stream it to the plugin via WebSocket -- no CORS issue.
2. **Acceptable stopgap:** Use `corsproxy.io` relay: `fetch('https://corsproxy.io/?url=' + encodeURIComponent(apiUrl))`. This adds a third-party relay dependency.
3. **Do not do:** Assume browser `fetch()` to third-party financial APIs will work -- most do not send CORS headers.
+8
View File
@@ -0,0 +1,8 @@
param([string]$worktreePath)
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
}
$target = Join-Path $worktreePath '.planning'
if (Test-Path $target) { Remove-Item $target -Force }
New-Item -ItemType Junction -Path $target -Target 'C:\dev\wwv\.planning' | Out-Null
+7
View File
@@ -0,0 +1,7 @@
param([string]$worktreePath)
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
}
$target = Join-Path $worktreePath '.planning'
if (Test-Path $target) { Remove-Item $target -Force }
+2 -1
View File
@@ -5,7 +5,8 @@
"permissions": {
"allow": [
"Read(src/**)",
"Bash(npm test)"
"Bash(npm test)",
"Bash(node \"C:/Users/silve/.claude/hooks/claude-dir-guard.js\")"
],
"deny": [
"Read(.env)",
+121
View File
@@ -0,0 +1,121 @@
---
name: worktree-bootstrap
description: Create and fully bootstrap a WWV git worktree for isolated feature/debug work. Copies env vars, installs deps, generates Prisma client, and verifies the dev server boots before reporting ready.
---
# Worktree Bootstrap
Use this skill when creating a new worktree for isolated debugging or feature work. Eliminates the repeated "missing .env.local" / "Prisma client not generated" failures.
## Steps
### 1. Create the worktree
From `C:\dev\wwv\worldwideview\`:
```powershell
git-wt switch --create <branch-name> --yes
```
This places the worktree at `C:\dev\wwv\worldwideview.<branch-name>\`.
### 2. Copy environment file
`.env` contains shared secrets (AUTH_SECRET, DATABASE_URL, etc.) that are gitignored and not present in new worktrees. Copy it:
```powershell
Copy-Item C:\dev\wwv\worldwideview\.env C:\dev\wwv\worldwideview.<branch-name>\.env
```
Verify required vars are present:
```powershell
Select-String -Path C:\dev\wwv\worldwideview.<branch-name>\.env -Pattern "^AUTH_SECRET=|^DATABASE_URL="
```
If you need worktree-specific overrides (different port, DB name, feature flags), create a `.env.local` alongside it - Next.js loads `.env.local` on top of `.env`.
Both must match. If either is missing, copy from a teammate or the main `.env.local`.
### 3. Install dependencies
```powershell
Set-Location C:\dev\wwv\worldwideview.<branch-name>
pnpm install
```
### 4. Generate Prisma client
```powershell
npx prisma generate
```
### 5. (Optional) Sync with main
If the branch is behind main:
```powershell
git merge main
# or
git rebase main
```
### 6. Verify the dev server boots
```powershell
pnpm dev
```
Watch for the "Ready" line. If it fails, check:
- Docker is running (needed for PostgreSQL): `docker compose up -d`
- No port conflict on 3000: `netstat -ano | Select-String ":3000"`
### 7. Report ready
Once the dev server returns HTTP 200 on `http://localhost:3000`, the worktree is ready for use.
## .planning Branch Convention
Each feature worktree needs a matching branch in the `.planning` repo. The `SessionStart` and `post-checkout` hooks auto-switch `.planning` to that branch every time you open a session or switch branches in the worktree.
### When starting a new feature worktree
After Step 1 above, create the matching `.planning` branch (one-time per feature):
```powershell
git -C C:\dev\wwv\.planning checkout -b <branch-name>
git -C C:\dev\wwv\.planning push -u origin <branch-name>
git -C C:\dev\wwv\.planning checkout main
```
The `post-checkout` hook and `core.hooksPath` are applied automatically via `git init.templateDir` - no manual config step needed.
After this, every Claude Code session opened inside `worldwideview.<branch-name>` automatically switches `.planning` to `<branch-name>`. GSD agents see only that feature's phases.
Verify the sync is working after your first branch switch or session open:
```powershell
git -C C:\dev\wwv\.planning rev-parse --abbrev-ref HEAD
# Should output: <branch-name>
```
### When finishing a feature
Merge the feature planning back to main before cleaning up the worktree:
```powershell
git -C C:\dev\wwv\.planning checkout main
git -C C:\dev\wwv\.planning merge <branch-name>
git -C C:\dev\wwv\.planning push
git -C C:\dev\wwv\.planning branch -d <branch-name>
git -C C:\dev\wwv\.planning push origin --delete <branch-name>
```
## Teardown
When done, remove the worktree cleanly (never `rm -rf` — orphans the Docker volume):
```powershell
Set-Location C:\dev\wwv\worldwideview
git-wt remove
```
+9 -3
View File
@@ -2,13 +2,19 @@
install_deps = "pnpm install"
[[pre-start]]
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }""""
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }; if (Test-Path '../worldwideview/.env.local') { Copy-Item '../worldwideview/.env.local' '.env.local' -Force }""""
[[pre-start]]
copy_local_plugins = """powershell -Command "if (Test-Path '../worldwideview/local-plugins') { robocopy '../worldwideview/local-plugins' 'local-plugins' /E /XD node_modules dist .next coverage /XF '*.log' /NFL /NDL /NJH /NJS | Out-Null }""""
copy_local_plugins = """powershell -Command "if (Test-Path '../worldwideview/local-plugins') { robocopy '../worldwideview/local-plugins' 'local-plugins' /E /XD node_modules dist .next coverage /XF '*.log' /NFL /NDL /NJH /NJS | Out-Null }; exit 0""""
[[pre-start]]
copy_local_seeders = """powershell -Command "if (Test-Path '../worldwideview/local-seeders') { robocopy '../worldwideview/local-seeders' 'local-seeders' /E /XD .pnpm-store node_modules /NFL /NDL /NJH /NJS | Out-Null }""""
copy_local_seeders = """powershell -Command "if (Test-Path '../worldwideview/local-seeders') { robocopy '../worldwideview/local-seeders' 'local-seeders' /E /XD .pnpm-store node_modules /NFL /NDL /NJH /NJS | Out-Null }; exit 0""""
[[pre-start]]
link_planning = "powershell -File 'C:/dev/wwv/worldwideview/.agents/scripts/link-planning.ps1' '{{ worktree_path }}'"
[[pre-remove]]
unlink_planning = "powershell -File 'C:/dev/wwv/worldwideview/.agents/scripts/unlink-planning.ps1' '{{ worktree_path }}'"
[[pre-remove]]
docker_clean = "docker compose down -v"
+19
View File
@@ -35,15 +35,34 @@ NEXT_PUBLIC_BING_MAPS_KEY=
# Supabase Configuration (Optional — cloud-only features)
# Found in your Supabase Project Settings > API
NEXT_PUBLIC_SUPABASE_URL=
# Preferred name for the Supabase anon/publishable key (matches worldwideview-marketplace).
# NEXT_PUBLIC_SUPABASE_ANON_KEY is still accepted as a backwards-compat alias.
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
SUPABASE_DATABASE_URL=
# Cross-subdomain cookie domain (ADR-003).
# Local dev with hosts-file trick: .wwv.local
# Production: .worldwideview.dev
# Leave empty when running on plain localhost (cookies cannot share across ports).
NEXT_PUBLIC_WWV_COOKIE_DOMAIN=
# Auth host URL — the public URL of this WorldWideView instance when acting as auth host.
# Used to build emailRedirectTo in signup and OAuth flows.
# Local dev: http://wwv.local:3000
# Production: https://worldwideview.dev
NEXT_PUBLIC_AUTH_HOST_URL=
# OpenSky Network — multi-account credential rotation
# Comma-separated clientId:clientSecret pairs.
# Example: OPENSKY_CREDENTIALS=acct1-id:acct1-secret,acct2-id:acct2-secret
OPENSKY_CREDENTIALS=
# OpenWeatherMap — Weather radar tile overlays (free tier: 1,000 calls/day)
# Sign up at https://openweathermap.org/api and copy your API key.
OPENWEATHERMAP_API_KEY=
# ACLED API — Civil Unrest & Conflict data (free for non-commercial use)
# Register at https://developer.acleddata.com/ to obtain credentials.
# Data is updated weekly (Mondays) with global protest, riot, and violence events.
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# post-checkout hook: $1=prev HEAD, $2=new HEAD, $3=1 if branch checkout, 0 if file checkout
# Only sync .planning on branch switches, not file restores.
if [ "$3" = "1" ]; then
SYNC_SCRIPT="C:/dev/wwv/.claude/hooks/planning-sync.sh"
if [ -f "$SYNC_SCRIPT" ]; then
bash "$SYNC_SCRIPT"
fi
fi
+26 -6
View File
@@ -28,6 +28,7 @@ permissions:
contents: write
pull-requests: write
issues: write
id-token: write
jobs:
collect:
@@ -53,8 +54,6 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -83,14 +82,35 @@ jobs:
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
model: claude-haiku-4-5-20251001
show_full_output: true
prompt: |
You are the WorldWideView Garbage Collector agent running headless in GitHub Actions.
Read `.agents/rules/garbage-collection.md` for your charter and all guard rails.
Read `gc-findings.json` for the pre-scanned findings produced by `scripts/gc-scan.mjs`.
Check the DRY_RUN environment variable — if "true", post a dry-run summary only (no PRs or Issues).
Execute the full sweep procedure described in `.agents/agents/garbage-collector.md`.
The DRY_RUN environment variable is: ${{ env.DRY_RUN }}
## If DRY_RUN is "true":
Do NOT create any PRs or Issues.
Instead, find or create the tracking Issue titled "[gc-bot] Daily Scan Reports" (label: gc-bot) in
the silvertakana/worldwideview repository using the gh CLI:
# Find existing tracking issue
gh issue list --repo silvertakana/worldwideview --label gc-bot --search "[gc-bot] Daily Scan Reports" --json number,title
# If it exists, add a comment:
gh issue comment <number> --repo silvertakana/worldwideview --body "..."
# If it doesn't exist, create it:
gh issue create --repo silvertakana/worldwideview --title "[gc-bot] Daily Scan Reports" --label gc-bot --body "..."
The comment body must list every finding with: tier, file, line, description.
Include the run ID (${{ github.run_id }}) and timestamp at the top.
## If DRY_RUN is "false":
Execute the full sweep procedure described in `.claude/agents/garbage-collector.md`.
Create Tier A draft PRs and Tier B Issues per the guard rails in `.agents/rules/garbage-collection.md`.
Do not scan the codebase yourself. Work only from gc-findings.json.
allowed_tools: 'Bash,Read,Edit,Write,Grep,Glob'
claude_args: '--model claude-haiku-4-5-20251001 --allowedTools Bash,Read,Edit,Write,Grep,Glob'
+4
View File
@@ -23,6 +23,9 @@ node_modules/
/.agents/context/
/.agents/settings.local.json
# planning (private repo: github.com/silvertakana/wwv-planning)
.planning/
# performance
/performance/
@@ -66,6 +69,7 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env
.env.local
.env.test
# vercel
.vercel
+2 -1
View File
@@ -131,6 +131,7 @@ See `.agents/context/INDEX.md` for the full navigation table. Key files:
| `/debugging-coolify` | Troubleshoot deployed apps on Coolify via MCP/SSH | `.agents/workflows/debugging-coolify.md` |
| `/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` |
---
@@ -153,7 +154,7 @@ See `.agents/context/INDEX.md` for the full navigation table. Key files:
- **Commit format**: Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`). Use `/commit` workflow.
- **Required checks**: `pnpm test` and `pnpm build` must pass before merge.
- **Review**: Use `/pr-review` for comprehensive multi-role review.
- **Worktrees**: Use `git-wt switch --create <branch>` and `git-wt remove` (never `rm -rf` a worktree — orphans the PostgreSQL Docker volume).
- **Worktrees**: Use `git-wt switch --create <branch>` and `git-wt remove` (never `rm -rf` a worktree — orphans the PostgreSQL Docker volume). After a PR merges, use `/branch-cleanup` to commit leftovers, delete the plan file, and remove the worktree in one flow.
---
+2 -1
View File
@@ -21,6 +21,7 @@ services:
required: false
environment:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
- "ENCRYPTION_MASTER_KEY=${ENCRYPTION_MASTER_KEY:-local_dev_encryption_key_change_in_prod}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
- "DATABASE_URL=postgresql://postgres:postgres@db:5432/worldwideview?schema=public"
@@ -58,7 +59,7 @@ services:
command: >
sh -c "
echo 'Syncing workspace dependencies...' &&
cd $$SEEDERS_DIR/community && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild &&
if [ -d \"$$SEEDERS_DIR/community\" ]; then cd $$SEEDERS_DIR/community && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild; fi &&
if [ -d \"$$SEEDERS_DIR/private\" ]; then cd $$SEEDERS_DIR/private && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild; fi &&
cd /app && node dist/server.js"
ports:
+54 -2
View File
@@ -29,8 +29,60 @@ if [ -z "$DATABASE_URL" ]; then
fi
echo "[entrypoint] Running database migrations..."
prisma migrate deploy
echo "[entrypoint] Migrations complete."
set +e
MIGRATE_OUT=$(prisma migrate deploy 2>&1)
MIGRATE_CODE=$?
set -e
if [ $MIGRATE_CODE -eq 0 ]; then
echo "[entrypoint] Migrations complete."
elif echo "$MIGRATE_OUT" | grep -q "P3005"; then
# P3005: schema exists but _prisma_migrations has no history.
# Happens when 'prisma db push' (pnpm dev) ran before 'prisma migrate deploy' (docker).
# Safe to auto-baseline only if there is zero schema drift.
echo "[entrypoint] P3005: schema exists without migration history."
echo "[entrypoint] Verifying schema matches migrations before auto-baselining..."
set +e
DIFF_OUT=$(prisma migrate diff \
--from-url "$DATABASE_URL" \
--to-schema-datamodel prisma/schema.prisma \
--script 2>&1)
DIFF_CODE=$?
set -e
if [ $DIFF_CODE -ne 0 ]; then
echo "[entrypoint] Could not verify schema state — aborting." >&2
echo "$DIFF_OUT" >&2
exit 1
fi
# Positive-match for DDL keywords: any real drift emits at least one of these.
# Checking for presence is safer than checking for absence of content.
if echo "$DIFF_OUT" | grep -qiE "^(CREATE|ALTER|DROP|INSERT|UPDATE|DELETE|TRUNCATE)"; then
echo "[entrypoint] Schema drift detected — cannot auto-baseline." >&2
echo "[entrypoint] Run 'pnpm db:reset' to wipe and re-migrate, or resolve drift manually." >&2
echo "$MIGRATE_OUT" >&2
exit 1
fi
echo "[entrypoint] No drift detected. Baselining existing schema..."
for migration_dir in prisma/migrations/*/; do
if [ -f "${migration_dir}migration.sql" ]; then
migration_name=$(basename "$migration_dir")
echo "[entrypoint] Marking as applied: $migration_name"
set +e
prisma migrate resolve --applied "$migration_name"
RESOLVE_CODE=$?
set -e
if [ $RESOLVE_CODE -ne 0 ]; then
echo "[entrypoint] Failed to baseline $migration_name — aborting." >&2
exit 1
fi
fi
done
prisma migrate deploy
echo "[entrypoint] Migrations complete."
else
echo "$MIGRATE_OUT" >&2
exit $MIGRATE_CODE
fi
# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist
if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then
@@ -75,9 +75,11 @@ For legacy plugins (e.g., Webcams) that *cannot* use WebSockets, the local proxy
## Operational Implementation Details
### 1. Library Selection
* **`jose`:** The industry-standard library for modern JS. Used by the Marketplace to generate Ed25519 keys, sign JWTs, and expose the JWKS endpoint.
* **`jose`:** The industry-standard library for modern JS. Used by the Marketplace to generate Ed25519 keys, sign JWTs, and expose the JWKS endpoint. **Also used by Data Engines** to verify tickets — `createRemoteJWKSet` handles remote fetching, caching, and `kid` selection, and `jwtVerify` validates the signature plus `iss`/`aud`/`exp` in one call, with native OKP/Ed25519 support.
* **`openid-client`:** The RFC-compliant library used by the Local App to execute the PKCE Authorization Code flow securely.
* **`@fastify/jwt` + `get-jwks`:** Used by Data Engines. `@fastify/jwt` provides the middleware, while `get-jwks` (built by the Fastify core team) handles remote fetching, local LRU caching, and OKP-to-PEM conversion for Ed25519 keys.
> [!NOTE]
> **Amendment (2026-05-22):** The original draft specified `@fastify/jwt` + `get-jwks` for Data Engines. This was found to be incorrect during local integration testing: `get-jwks.getPublicKey()` converts JWKs via `jwk-to-pem`, which **does not support OKP/Ed25519 keys** (throws `Unsupported key type "OKP"`). `@fastify/jwt`'s standalone `verify()` is also incompatible with a remote-JWKS async key resolver. Data Engines now use `jose` — the same library already mandated for the Marketplace — which supports Ed25519 natively.
### 2. Hardened First-Message Auth
Data Engines MUST enforce strict WebSocket handshake rules:
@@ -145,8 +147,8 @@ sequenceDiagram
M->>L: 5-min JWT (aud: Engine A)
L->>U: JWT
U->>E: wss://engine (Origin validation)
U->>E: { type: "auth", jwt: "..." }
E->>E: Verify with get-jwks cache
U->>E: { type: "auth", v: 1, token: "..." }
E->>E: Verify JWT via jose (cached JWKS)
E->>U: Stream
end
```
@@ -0,0 +1,188 @@
# ADR-0003: Shared Identity & Ecosystem Authentication Host
## Status
Accepted *(Phase 2A-D implementation complete 2026-05-25)*
### Implementation notes (Phase 2 closeout)
- `worldwideview/src/lib/supabase/cookieOptions.ts`, `server.ts`, `client.ts` added — mirrors marketplace recipe
- `worldwideview/src/app/login/actions.ts` migrated from `@supabase/supabase-js` to `@supabase/ssr` `createServerClient` so login actually persists a Supabase session cookie
- `getSafeRedirect` updated to allow trusted subdomains via `NEXT_PUBLIC_WWV_COOKIE_DOMAIN`
- `/auth/callback` route added to handle Supabase PKCE email verification flow
- `/signup` page and server action added at the auth host
- `worldwideview-marketplace/src/app/api/install/start/route.ts` — new server-side auth gate for plugin installs
- `InstallButton.handleInstall` retargeted to `/api/install/start` (was building WWV URL client-side with no auth check)
- `requireSupabaseUser` redirect param renamed `?next=` to `?callbackUrl=` to match WWV login page
- `install-redirect/route.ts` updated to use Supabase auth for cloud edition, NextAuth for local/demo
- `httpOnly: true` added to `buildCookieOptions()` in both repos
- NextAuth (Credentials provider) retained for local and demo editions
## Date
2026-05-22
## Related
- **Builds on:** ADR-001 (Decentralized Plugin Auth & SSRF Mitigation) — specifically the PKCE flow that lets the Local App acquire tokens from the Marketplace
- **Supersedes:** `.agents/rules/cloud-auth-architecture.md` (which incorrectly states that `app.worldwideview.dev` owns all login UI — this ADR reverses that)
---
## Context
WorldWideView is growing into a multi-product ecosystem:
| Product | URL | Purpose |
|---|---|---|
| Landing / Auth | `worldwideview.dev` | Marketing, login, signup, cloud plan registration |
| Marketplace | `marketplace.worldwideview.dev` | Browse, install, and manage plugins |
| Cloud App | `app.worldwideview.dev` (or `[tenant].app.worldwideview.dev`) | Hosted geospatial intelligence instance |
| Local App | Self-hosted | User's own instance, authenticated locally |
Four interrelated problems required a unified decision:
1. **No Marketplace identity system exists.** Users have nowhere to create an account, log in, or manage subscriptions.
2. **Fragmented account experience.** Without a plan, a user would need separate accounts for the Marketplace and the Cloud App — unacceptable for a single-vendor ecosystem.
3. **Cookie domain fragmentation.** If each product hosts its own login page, sessions cannot be shared across subdomains. A user logged into the Marketplace would need to log in again at the Cloud App.
4. **The `worldwideview-web` repo is a static export** (`output: "export"`). It has a `/login` page backed by client-side Supabase but cannot support server-side sessions, API routes, or cross-subdomain cookie management.
---
## Decisions
### ADR-003A: Federated Identity — One Account Across All Products
All WorldWideView products share a **single identity**. A user who creates an account anywhere in the ecosystem (Marketplace, Cloud App, or the landing site) has that same identity available everywhere else.
This is the standard industry pattern for multi-product SaaS — used by GitHub (one account → GitHub, Marketplace, Actions, Packages), Atlassian (one account → Jira, Confluence, Marketplace), and Stripe (one account → Dashboard, Atlas, Stripe Apps).
The shared identity store is a **single Supabase project**. All products point to the same `NEXT_PUBLIC_SUPABASE_URL` and read from the same `auth.users` table. No synchronisation jobs, no duplicate user records.
### ADR-003B: Supabase Auth as the Identity Provider
**Supabase Auth** is the identity layer for the entire ecosystem. It was chosen over:
- **Better Auth** — excellent self-hosted option, but requires a Postgres database to be provisioned separately. Since the Marketplace and `worldwideview-web` have no existing database, Supabase provides auth + Postgres in a single managed service with zero extra infrastructure.
- **NextAuth v5** — already present in the Local App for local access control, but it is not a full identity platform. Missing 2FA, RBAC, and a proper OAuth server model. Not suitable as an ecosystem-wide IdP.
- **Clerk** — fastest setup and best Stripe integration, but ~$25–50/month at low user counts, per-MAU pricing at scale, and user data is stored on Clerk's servers. Vendor lock-in is unacceptable for a product that holds plugin and subscription data.
Supabase Auth provides:
- Email + password, Google OAuth, GitHub OAuth, and magic link — all configured in the Supabase dashboard with no provider code
- `@supabase/ssr` package with first-class Next.js App Router support (server components, middleware, server actions)
- Cookie-based sessions that can be scoped to the parent domain
- Free tier is sufficient for early-stage Marketplace; Pro plan ($25/month) unlocks unlimited MAU
### ADR-003C: `worldwideview.dev` (worldwideview-web repo) is the Ecosystem Auth Host
The login and account registration UI lives at **`worldwideview.dev`** — the apex domain, served by the `worldwideview-web` repository. Three alternatives were considered:
**Option A — Each app has its own login page**
Rejected. Each product renders its own login form against the shared Supabase project. Browser `localStorage` (used by client-side Supabase) is domain-scoped and cannot be shared across subdomains. This means a user logged in at `marketplace.worldwideview.dev` would not be recognised at `app.worldwideview.dev`. Solving this in each app separately creates duplicated middleware and fragile cookie coordination.
**Option B — Marketplace owns the login page**
Rejected. The Cloud App would be permanently subordinate to the Marketplace for authentication. If the Marketplace is down, Cloud App users cannot log in. Also creates a confusing UX: users navigate to `app.worldwideview.dev` and are immediately bounced to `marketplace.worldwideview.dev` just to authenticate.
**Option C — Dedicated `accounts.worldwideview.dev` subdomain**
Seriously considered. A neutral auth subdomain is the cleanest long-term architecture. Rejected for now because it requires a third Next.js deployment and a third Coolify application. The same result is achieved by hosting auth on the apex domain itself (`worldwideview.dev`), which is already managed by `worldwideview-web` and is the identity host by virtue of owning the root domain.
**Chosen: Apex domain as auth host.** The `worldwideview-web` repo becomes the auth surface for the whole ecosystem:
| Path | Type | Purpose |
|---|---|---|
| `/` | Static | Landing page (marketing) |
| `/about`, `/docs`, `/plugins` | Static | Marketing content |
| `/login` | Dynamic (SSR) | Shared login for all products |
| `/signup` | Dynamic (SSR) | New account creation |
| `/cloud` | Dynamic (SSR) | Cloud plan registration and subscription |
| `/accounts/*` | Dynamic (SSR) | Account management, billing, API keys |
| `/api/auth/callback` | Dynamic (SSR) | OAuth redirect handler (Google, GitHub) |
**Why the apex domain is correct:** A session cookie set on `worldwideview.dev` is automatically inherited by all subdomains (`marketplace.worldwideview.dev`, `app.worldwideview.dev`, and any future product). This is the same mechanism used by Stripe — `stripe.com/login` sets the session that `dashboard.stripe.com` reads.
### ADR-003D: Cross-Subdomain Session Sharing via Parent Domain Cookie
Supabase Auth session cookies are explicitly scoped to the parent domain so that all products share the same session without additional coordination:
```typescript
// Applied in worldwideview-web middleware and all Supabase server clients
cookieOptions: {
domain: '.worldwideview.dev', // leading dot = all subdomains inherit
path: '/',
sameSite: 'lax',
secure: true, // HTTPS required — see local dev below
}
```
Each product (Marketplace, Cloud App) reads this cookie to get the authenticated user, then calls `supabase.auth.getUser()` server-side to validate the session. No cross-app API calls for authentication.
**Logout** must clear the cookie on the parent domain, not the subdomain, or the session will persist across products.
### ADR-003E: `worldwideview-web` Converts from Static Export to Mixed Static/SSR
The current `worldwideview-web` uses `output: "export"` in `next.config.ts`, forcing every page to be a static HTML file served by Nginx. This is removed.
Without `output: "export"`, Next.js App Router applies per-route rendering:
- Pages that do not call `cookies()`, `headers()`, or other dynamic functions are **statically generated at build time** — marketing pages remain fast and CDN-cached with no change required.
- Pages that call `cookies()` (all auth pages using `@supabase/ssr`) are **server-rendered on request**.
The Docker deployment changes from an Nginx static image to a Node.js runtime image. The Coolify application is updated in-place — no new Coolify application is needed.
### ADR-003F: `wwv.local` Local Development Environment
Because the parent-domain cookie requires `secure: true` (HTTPS only), local development using `localhost` will not replicate production session-sharing behaviour. A local HTTPS domain is required.
The project adopts `wwv.local` as the local development TLD with a self-signed certificate:
| Local URL | Maps to | Purpose |
|---|---|---|
| `wwv.local` | worldwideview-web on port 3001 | Landing + auth |
| `marketplace.wwv.local` | worldwideview-marketplace on port 3002 | Marketplace |
| `app.wwv.local` | worldwideview main app on port 3000 | Local App / Cloud App |
This setup is a deliberate investment: it ensures that cross-subdomain auth, redirect flows, and cookie behaviour can be tested locally before production deployment. The setup cost is a one-time `mkcert` install and hosts file edit per developer machine.
Setup (documented in each repo's README):
```bash
# Install mkcert (once per machine)
# macOS: brew install mkcert && mkcert -install
# Windows: choco install mkcert && mkcert -install
mkcert "*.wwv.local" wwv.local
# Add to hosts: 127.0.0.1 wwv.local marketplace.wwv.local app.wwv.local
```
---
## Security Constraints (from Pre-Mortem Review)
The following risks were identified and mitigated before implementation:
| Risk | Mitigation |
|---|---|
| Supabase anon key can read all rows if RLS is disabled | Row Level Security (RLS) MUST be enabled on all app-specific tables (`MarketplaceUser`, `InstalledPlugin`). Policy: `using (id = auth.uid())`. Server routes use `SUPABASE_SERVICE_ROLE_KEY` which bypasses RLS by design. |
| PKCE authorization code replay attack | The authorization code is deleted from the database transactionally at the moment of redemption. Any subsequent attempt receives `400 invalid_grant`. |
| Supabase free tier limits magic link email to 2/hour per address | A custom SMTP provider (Resend) is configured in Supabase project settings before magic link is enabled in production. |
| `MarketplaceUser` becomes orphaned when `auth.users` row is deleted | A Postgres trigger on `auth.users` DELETE cascades to `MarketplaceUser` and all related rows. |
| Ed25519 signing key rotation causes token rejection at Data Engines | Signing keys are stored in a `SigningKey` DB table, not env vars. The JWKS endpoint serves all non-revoked keys simultaneously. During rotation, the old key is marked `retiring` and kept in JWKS for 10 minutes before being marked `revoked`. |
---
## Marketplace PKCE OAuth Server (Relation to ADR-001)
The Marketplace acts as the **OAuth 2.0 Authorization Server** in the ADR-001 PKCE flow. Supabase Auth handles user identity; a thin custom layer handles the code exchange:
1. Local App redirects user to `marketplace.worldwideview.dev/api/oauth/authorize`
2. Marketplace validates the Supabase session (or redirects to `worldwideview.dev/login`)
3. User sees consent screen and approves
4. Marketplace issues a short-lived authorization code (60s TTL), redirects to Local App
5. Local App exchanges code + `code_verifier` for a long-lived API Key
6. Subsequent plugin connections use the API Key to request 5-minute EdDSA JWTs (ADR-001B)
This is not a new Supabase feature — it is custom Next.js API routes sitting on top of the existing Supabase Auth session.
---
## Consequences
- **One Supabase project** is a shared dependency across `worldwideview-web`, `worldwideview-marketplace`, and `worldwideview` (Cloud App). A Supabase outage affects all products simultaneously. This is an accepted tradeoff at current scale; the mitigation is Supabase's SLA and free-tier generous limits.
- **`worldwideview-web` must run as a Node.js server**, not a static Nginx container. This increases Coolify resource usage marginally but enables all auth functionality.
- **Local development requires `mkcert` setup** (one-time, ~5 minutes). This is a deliberate decision to prevent a class of production bugs that cannot be caught with `localhost`.
- **The old `cloud-auth-architecture.md` rule is invalidated.** That rule stated `app.worldwideview.dev` owns all login UI and the Marketplace redirects there. The reverse is now true. That rules file must be updated to reference this ADR.
- **Upgrade path is clear:** If the Marketplace matures into a platform that third-party developers build against (issuing OAuth tokens to external apps), the existing PKCE layer is extended without changing the user table or Supabase project. The identity layer is already decoupled from the token exchange layer.
@@ -0,0 +1,88 @@
# ADR-0004: Supabase Session Cookies Are httpOnly Across the Ecosystem
## Status
Accepted *(2026-05-25)*
## Date
2026-05-25
## Related
- **Builds on:** ADR-0003 (Shared Identity & Ecosystem Auth Host) — defines the parent-domain cookie scoping (`.worldwideview.dev` prod, `.wwv.local` dev) that this ADR hardens.
---
## Context
ADR-0003 established that a single Supabase session cookie scoped to the parent domain is inherited by every product subdomain (`marketplace.*`, `app.*`, the apex). The cookie carries a base64-encoded access token, refresh token, and the full user record. By default `@supabase/ssr` does NOT set `httpOnly` on this cookie because the browser client (`createBrowserClient`) needs to read it via `document.cookie` to compute `getSession()` synchronously without a network round-trip.
That default is fine for apps that perform their auth reads on the client. It is **not fine for this ecosystem.** Three observations forced the decision:
1. The `worldwideview-marketplace` repo already shipped with `httpOnly: true` in `buildCookieOptions()`. Its install gate (`requireSupabaseUser` in `src/lib/auth/requireSession.ts`) and every API route read the session through the server client (`createServerClient`), so a non-readable cookie costs nothing.
2. The `worldwideview-web` repo originally omitted `httpOnly` and had a single client-side reader: `src/app/hub/layout.tsx` ran `supabase.auth.getSession()` inside a `useEffect`. During audit (2026-05-25), this was discovered as the *only* JS path that needed cookie readability — and it was an anti-pattern (auth gate via `useEffect` introduces a flash-of-unauthenticated-content and is replaceable with a server component).
3. With the cookie readable to JS, an XSS payload on **any** subdomain (`marketplace.*`, `app.*`, the apex itself) can exfiltrate the full session token. Given marketplace renders user-submitted plugin metadata, this is a real attack surface.
The choice was: keep client-side `getSession()` calls and accept the XSS exfiltration risk, or refactor reads to server-side and harden the cookie.
---
## Decision
**All Supabase session cookies in the WorldWideView ecosystem are set with `httpOnly: true`.** This is enforced in each app's `buildCookieOptions()` helper:
- `worldwideview-web/src/lib/supabase/cookieOptions.ts`
- `worldwideview-marketplace/src/lib/supabase/cookieOptions.ts`
- `worldwideview/src/lib/supabase/cookieOptions.ts` (cloud edition only — file is gated by `isCloud`)
Companion hard constraint: **client-side `supabase.auth.getSession()` / `getUser()` / `getClaims()` is forbidden everywhere in the ecosystem.** All auth reads happen server-side via:
- Server components / pages — call `createClient()` from `src/lib/supabase/server.ts`, then `auth.getClaims()` (validates against the auth server, doesn't trust the cookie).
- API routes — same pattern, typically through a wrapper like `requireSupabaseUser(returnTo)`.
- Middleware / proxy — Next.js 16's `proxy.ts` refreshes the session on every matched request and propagates rotated cookies onto the response.
If a future feature requires reading the session on the client, it MUST go through a server-rendered prop or a fetch to an internal API route that performs the read server-side. Adding a new client-side auth read is a regression.
### Implementation details
```ts
// Shared shape across all three apps:
export function buildCookieOptions() {
return {
domain: resolveCookieDomain(process.env.NEXT_PUBLIC_WWV_COOKIE_DOMAIN),
path: '/',
sameSite: 'lax' as const,
secure: true,
httpOnly: true, // ← this ADR
}
}
```
The `proxy.ts` middleware in worldwideview-web (and the equivalent server-client invocations everywhere else) passes `cookieOptions: buildCookieOptions()` into `createServerClient` so token refreshes inherit the flag automatically.
---
## Consequences
**Positive:**
- XSS on any subdomain can no longer read the session token. The auth server still validates each request, so even a forged cookie has no value.
- Auth state is server-rendered, removing the flash-of-unauthenticated-content on protected routes (previously visible at `/hub`).
- Codebase is consistent — three apps, one cookie configuration, one set of read patterns.
**Negative / accepted tradeoffs:**
- Client-side `supabase.auth.*` reads are dead. Any contributor who has worked with `@supabase/supabase-js` will instinctively reach for `getSession()` in a `useEffect`. Code review must catch this.
- Token refresh on stale tabs requires a server round-trip through `proxy.ts` rather than a client-side refresh. Adds ~10-50ms to the first request after expiry; acceptable.
- Browser-side debugging is slightly harder — you can't paste `await supabase.auth.getUser()` into the devtools console. Use server logs or a dedicated `/api/debug/whoami` route instead.
**Verification at adoption (2026-05-25):**
- `worldwideview-web/src/app/hub/layout.tsx` refactored from client useEffect to server component (`getClaims()` + `redirect()`); test rewritten accordingly.
- Browser confirmation: after sign-out + sign-in, `document.cookie` no longer contains `sb-<ref>-auth-token.0/.1`; only the dev-mode `__next_hmr_refresh_hash__` cookie remains visible to JS.
- Marketplace and WWV cloud edition were already compliant; no behavior change for them.
---
## Enforcement
- Code review must flag any import of `createBrowserClient` from `@supabase/ssr` if the call site is in a `"use client"` component and invokes `auth.*` directly.
- Future ESLint rule: ban `createBrowserClient` + `auth.getUser|getSession|getClaims` combinations. (Not implemented yet — follow-up.)
- The marketplace browser client (`worldwideview-marketplace/src/lib/supabase/client.ts`) exists but is unused; consider deleting it in a future cleanup pass.
+258
View File
@@ -0,0 +1,258 @@
# SECURITY.md -- Phase 3: Local App PKCE + SSRF Proxy Hardening
**Audit date:** 2026-05-24
**Phase:** 3 -- Local App PKCE + SSRF Proxy Hardening
**ASVS Level:** 2
**Audit mode:** Retroactive-STRIDE (no formal threat model at plan time; register constructed from implementation)
**block_on:** open
---
## Threat Register
| ID | Category | Description | Disposition | Status |
|----|----------|-------------|-------------|--------|
| T01 | SSRF | Proxy endpoints use raw `fetch` instead of `safeFetch` | mitigate | CLOSED |
| T02 | SSRF | `PROXY_HOST_ALLOWLIST` not enforced | mitigate | CLOSED |
| T03 | SSRF | Private IP ranges not blocked | mitigate | CLOSED |
| T04 | SSRF/DNS-rebinding | DNS resolved multiple times; IP not pinned between lookup and connect | mitigate | CLOSED |
| T05 | SSRF/Open-redirect | Proxy follows 3xx redirects, enabling open-redirect chains | mitigate | CLOSED |
| T06 | SSRF | iframe proxy previously used raw `fetch` with no size cap | mitigate | CLOSED |
| T07 | Spoofing | PKCE state not validated; forged state accepted | mitigate | CLOSED |
| T08 | Spoofing | PKCE state cookie not `__Host-` prefixed on HTTPS | mitigate | CLOSED |
| T09 | Spoofing | PKCE state/verifier cookies not `httpOnly`, missing `SameSite` | mitigate | CLOSED |
| T10 | Spoofing | PKCE state/verifier cookies too long-lived (>10 min) | mitigate | CLOSED |
| T11 | Elevation | `code_verifier` cookie reusable after exchange (replay) | mitigate | CLOSED |
| T12 | Tampering | `ENCRYPTION_MASTER_KEY` unset falls back to zero-key silently | mitigate | CLOSED |
| T13 | Elevation | WsClient sends `subscribe` before auth (`onopen` path) | mitigate | CLOSED |
| T14 | Elevation | WsClient sends `subscribe` before auth (`subscribe()` method -- race, already-open connection) | mitigate | OPEN (BLOCKER) |
---
## Verification Evidence
### T01 -- Proxy endpoints use `safeFetch`
All three user-facing proxy routes import and call `safeFetch`, not raw `fetch`:
- `src/app/api/camera/proxy/route.ts:6,27` -- `import { safeFetch }` + `await safeFetch(targetUrl, ...)`
- `src/app/api/camera/proxy/iframe/route.ts:6,32` -- `import { safeFetch }` + `await safeFetch(targetUrl, ...)`
- `src/app/api/camera/proxy/stream/route.ts:6,31` -- `import { safeFetch }` + `await safeFetch(targetUrl, ...)`
**Status: CLOSED**
---
### T02 -- `PROXY_HOST_ALLOWLIST` enforced
`src/lib/security/ssrf.ts:25-42` -- `checkHostAllowlist()` is called at the top of `safeFetch` before any network I/O. Behavior:
- Unset env var: throws `SSRF Error: PROXY_HOST_ALLOWLIST is not configured`
- Empty string: throws same error
- `"*"`: warns and permits (permissive mode, documented)
- Specific list: rejects unlisted hostnames
Covered by unit tests in `src/lib/security/ssrf.spec.ts:63-82`.
**Status: CLOSED**
---
### T03 -- Private IP ranges blocked
`src/lib/security/ssrf.ts:4-9` -- `isPrivateIP()` covers:
- `127.*`, `10.*`, `192.168.*`, `169.254.*` (AWS/GCP metadata), `0.*`
- `172.16-31.*`
- IPv6: `::1`, `fc*`, `fd*`, `fe80*`
Called twice: once against the literal URL hostname (line 56) and once against the resolved IP (line 66).
**Status: CLOSED**
---
### T04 -- DNS pinning via undici Agent
`src/lib/security/ssrf.ts:60-80` -- Single `dns.lookup()` call stores `resolvedIp` and `resolvedFamily`. A custom undici `Agent` is constructed with a `connect.lookup` override that always returns the pre-resolved address, preventing a second DNS resolution during TCP connect.
**Status: CLOSED**
---
### T05 -- Redirect following disabled
`src/lib/security/ssrf.ts:92` -- `redirect: "manual" as const` is passed to undici `fetch`. Verified by test at `ssrf.spec.ts:117-135` which asserts `callOpts.redirect === "manual"` and that only one fetch call is made when a 301 is returned.
**Status: CLOSED**
---
### T06 -- iframe proxy uses `safeFetch` with size cap
`src/app/api/camera/proxy/iframe/route.ts:6,32,39` -- Uses `safeFetch` with `maxSize: 5 * 1024 * 1024` and `timeout: MAX_IFRAME_DURATION_MS` (10 s). The previous raw-fetch vulnerability is no longer present.
**Status: CLOSED**
---
### T07 -- PKCE state validated in callback
`src/app/api/marketplace/callback/route.ts:10-15`:
```
const stateCookie = req.cookies.get(`${cookiePrefix}pkce_state`)?.value;
const urlState = req.nextUrl.searchParams.get("state");
if (!stateCookie || urlState !== stateCookie) {
return NextResponse.json({ error: "State mismatch" }, { status: 400 });
}
```
Both missing cookie and value mismatch are rejected.
**Status: CLOSED**
---
### T08 -- `__Host-` cookie prefix on HTTPS
`src/app/api/marketplace/connect/route.ts:22-23`:
```
const isHttps = req.nextUrl.protocol === "https:";
const cookiePrefix = isHttps ? "__Host-" : "";
```
Same logic mirrored in `src/app/api/marketplace/callback/route.ts:7-8`. On HTTPS the cookies are named `__Host-pkce_state` and `__Host-pkce_verifier`, which browsers enforce must be `Secure`, `Path=/`, and no `Domain` attribute.
Note: the cookies use `path: "/api/marketplace/callback"`, not `path: "/"`. The `__Host-` prefix specification (RFC 6265bis) requires `Path=/`. This is a partial inconsistency -- the `__Host-` prefix technically requires `Path=/` to be valid per browsers that enforce the prefix spec strictly. In practice Chromium enforces `Path=/` for `__Host-` cookies and will silently reject the Set-Cookie header. This is flagged as an unregistered finding below but does not affect current HTTP (dev) deployments. **Treat as unregistered flag UF-01.**
**Status: CLOSED** (state validation logic present; see UF-01 for prefix/path mismatch)
---
### T09 -- `httpOnly` + `SameSite` on PKCE cookies
`src/app/api/marketplace/connect/route.ts:26-38`:
- `httpOnly: true` -- set on both cookies
- `sameSite: "lax"` -- set on both cookies
- `secure: isHttps` -- conditional on protocol
**Status: CLOSED**
---
### T10 -- PKCE cookies short-lived (10 min)
`src/app/api/marketplace/connect/route.ts:30,38`: `maxAge: 60 * 10` (600 seconds = 10 minutes) on both state and verifier cookies.
**Status: CLOSED**
---
### T11 -- `code_verifier` cookie deleted post-exchange (single-use)
`src/app/api/marketplace/callback/route.ts:66-82` -- After successful token exchange, both `pkce_state` and `pkce_verifier` cookies are explicitly cleared by setting `maxAge: 0` with empty string values. This invalidates the cookies immediately on the response, preventing replay.
**Status: CLOSED**
---
### T12 -- `ENCRYPTION_MASTER_KEY` fails hard when unset
`src/lib/auth/encryption.ts:8-11`:
```
function getMasterKey(): string {
const key = process.env.ENCRYPTION_MASTER_KEY;
if (!key) throw new Error('[encryption] ENCRYPTION_MASTER_KEY env var is required');
return key;
}
```
No fallback. No zero-key. Both `encryptCredential` and `decryptCredential` call `getMasterKey()`.
**Status: CLOSED**
---
### T13 -- WsClient `onopen` sends auth before subscribe (ticket-auth path)
`src/core/data/WsClient.ts:84-107`:
- When any subscription requires ticket auth, `engine.awaitingWelcome = true` is set and `subscribe` messages are NOT sent on `onopen`
- Subscribes are deferred until `data.type === "welcome"` is received (lines 118-124)
- A 3-second auth timeout closes the connection if welcome never arrives (lines 91-96)
**Status: CLOSED** (for the `onopen` path)
---
### T14 -- WsClient `subscribe()` method sends `subscribe` on already-open connection while `awaitingWelcome = true` (OPEN BLOCKER)
`src/core/data/WsClient.ts:198-211`:
```typescript
public subscribe(pluginId: string, engineUrl: string) {
engine.subscriptions.add(pluginId);
this.connectEngine(engineUrl);
this.send(engine, { action: "subscribe", pluginId }); // line 210
}
```
`this.send()` at line 210 checks only `ws.readyState === WebSocket.OPEN` before sending. It does **not** check `engine.awaitingWelcome`. If:
1. Plugin A connects and triggers ticket auth (`awaitingWelcome = true`)
2. Before the `welcome` arrives, Plugin B calls `subscribe()` on the same engine
3. The WS is already OPEN, so `send()` fires -- Plugin B's `subscribe` message is sent to the server before auth is complete
This allows an unauthenticated subscribe frame to reach the data engine server. Whether the server accepts it depends on server-side enforcement, but the client does not enforce the auth-first guarantee for late joiners.
The `onopen` path (T13) is correctly gated. The `subscribe()` entry point is not.
**Impact:** A second plugin subscribing to an engine in the window between connection open and welcome receipt bypasses the client-side auth gate. The data engine must reject unauthenticated subscriptions server-side for defense in depth, but the ADR-001 intent was client-enforced first-message auth.
**Required fix:** In `subscribe()`, check `engine.awaitingWelcome` before calling `this.send()`. If `awaitingWelcome` is true, skip the early send -- the subscription is already in `engine.subscriptions` and will be sent when `welcome` is received in `onmessage`.
**Status: OPEN (BLOCKER)**
---
## Unregistered Flags
### UF-01 -- `__Host-` prefix with `path: "/api/marketplace/callback"` violates prefix spec
**File:** `src/app/api/marketplace/connect/route.ts:29,37`
The `__Host-` cookie prefix per RFC 6265bis requires `Path=/`. The implementation sets `path: "/api/marketplace/callback"`. Chromium-based browsers enforce this and will silently reject the `Set-Cookie` header when `__Host-` is combined with a non-root path. In practice this means on HTTPS deployments the PKCE cookies may not be set at all, breaking the OAuth flow entirely -- or the browser falls back to setting them without the prefix, losing the security guarantee.
This is a functional correctness issue as well as a security regression. Recommend changing `path` to `"/"` or switching the cookie name to `pkce_state` / `pkce_verifier` without the `__Host-` prefix (accepting the loss of the prefix guarantee).
**Not a declared threat -- flagged as unregistered surface. Does not count as BLOCKER per config, but should be fixed before HTTPS deployment.**
---
### UF-02 -- `src/app/api/camera/extract/route.ts` uses raw `fetch` against user-supplied URL
**File:** `src/app/api/camera/extract/route.ts:17,29`
This route accepts a user-supplied `url` query parameter and passes it directly to `fetch()` without going through `safeFetch`. Current code only executes the fetch if `targetUrl.includes("balticlivecam.com")`, which provides weak host filtering via substring match rather than proper hostname validation. This is outside the declared Phase 3 scope but represents new SSRF attack surface that was not mitigated. A crafted URL like `https://evil.com?x=balticlivecam.com` would pass the check.
**Not a declared threat -- flagged as unregistered surface.**
---
### UF-03 -- `src/app/api/camera/test/route.ts` uses raw `fetch` against user-supplied URL
**File:** `src/app/api/camera/test/route.ts:45,56,68` (confirmed by grep)
The test route uses raw `fetch` with a user-supplied URL. Its auth posture was not reviewed in this phase. Flagged for completeness.
**Not a declared threat -- flagged as unregistered surface.**
---
## Summary
| Metric | Count |
|--------|-------|
| Total threats | 14 |
| CLOSED | 13 |
| OPEN (BLOCKER) | 1 |
| Unregistered flags | 3 |
**Phase 3 MUST NOT SHIP until T14 is resolved.**
The fix is mechanical: add an `awaitingWelcome` guard in the `public subscribe()` method before the `this.send()` call at `WsClient.ts:210`.
@@ -0,0 +1,212 @@
# ADR-001 Consolidation Plan: Dual-Issue Path to Decentralized Plugin Auth
## Context
ADR-001 (`docs/architecture/decisions/adr-0001-decentralized-plugin-auth-and-ssrf-mitigation.md`, still marked **Proposed**) defines a decentralized auth model for plugin data streams: Ed25519-signed, 5-minute, audience-bound JWT tickets issued by the Marketplace and verified offline by each Data Engine using JWKS.
The current state is a partial, incoherent implementation across three repos. A recent attempt to land the Data-Engine half landed broken, took production down, and was rolled back. This plan consolidates everything required so the next attempt is **once-and-done** with a feature-flagged dual-issue strategy — the existing HS256 marketplace-session token keeps working untouched while a new Ed25519 data-plane ticket system is built end-to-end and flipped on per-plugin.
**Scope:** all three deployables — Local App (this repo), Marketplace (`marketplace.worldwideview.dev`), Data Engine (`wwv-data-engine-public`).
**Honest framing on "once and done":** this plan delivers **zero-downtime** but is **4–5 sequenced deploys across 3 repos**, not literally one deploy. Compressing the steps is exactly what caused the previous outage. Sequenced + dormant-flagged is the safest path that meets the no-downtime intent.
---
## Current State (what we found)
### ✅ Already in place
- **AES-256-GCM at rest** for credentials — `src/lib/auth/encryption.ts` (PBKDF2 100k, v1 versioning, nonce+salt in DB). Schema `MarketplaceCredential` at `prisma/schema.prisma:92-104`.
- **PKCE initiation** — `src/app/api/marketplace/connect/route.ts` (openid-client v6, S256, `__Host-` cookies).
- **PKCE callback** — `src/app/api/marketplace/callback/route.ts` (state check, encrypted persist). Tests at `src/app/api/marketplace/pkce.spec.ts`.
- **JWT claims type contract** — `packages/wwv-plugin-sdk/src/auth-contracts.ts` (`PluginJwtClaims`, `WebSocketAuthMessage`).
- **SSRF partial defenses** in the JSON proxy — `src/lib/security/ssrf.ts` (post-DNS private-IP block, pinned-IP agent, size/time limits) used by `src/app/api/camera/proxy/route.ts` and `stream/route.ts`.
### ⚠️ Half-finished / risky (must be resolved before any deploy)
1. `src/lib/marketplace/marketplaceToken.ts` — HS256, 4h, hard-coded `aud`. **Acceptable as the marketplace-session bridge token only**; must NOT be used as a data-plane ticket. C1 enforces this via branded types (`MarketplaceSessionToken` vs `PluginTicket`) so the compiler refuses misuse.
2. `src/app/api/marketplace/callback/route.ts:27-29` — currently calls a non-existent `/api/tickets/exchange` endpoint and casts `openid-client` config as `any`. A4 ships the correct endpoint as `/api/oauth/token`; C1 updates the callback URL and removes the cast. Suspected source of the previous deploy break.
3. `src/lib/auth/encryption.ts:9` — silent fallback to a zeroed key if `ENCRYPTION_MASTER_KEY` env var unset. Must throw at startup.
4. `src/app/api/camera/proxy/iframe/route.ts` — bypasses `safeFetch` entirely; raw `fetch` with default redirect-follow and no size cap.
5. No host allowlist on any proxy route (ADR-001D constraint 1) — accepts any HTTPS host.
6. `src/core/data/WsClient.ts:67-69` — sends `subscribe` immediately on `onopen`; no first-message auth, contract `WebSocketAuthMessage` is defined but unused.
### ❌ Missing entirely
- **Ed25519 keypair** + **JWKS endpoint** on the Marketplace.
- **Ticket-issuance endpoint** on the Marketplace (`POST /api/tickets/exchange` → returns 5-min EdDSA JWT for a named audience).
- **JWT verification** on the Data Engine (`@fastify/jwt` + `get-jwks`, audience binding, unknown-`kid` re-fetch, fail-closed cold start).
- **First-message auth handshake** on the Data Engine WebSocket (3s timeout, close code 4003, no re-auth, log redaction).
- **Marketplace-side PKCE token endpoint** that the Local App callback expects.
- **Origin / Host / TLS-state validation** on the Data Engine WS upgrade.
- ADR doc still `Proposed`; never moved to `Accepted`.
---
## Strategy: Dual-Issue, Feature-Flagged, Coordinated Cutover
Two token systems live side by side. **Nothing existing is removed in this phase.**
| Token | Algo | Lifetime | Issued by | Verified by | Purpose |
|---|---|---|---|---|---|
| Marketplace-session (existing) | HS256 | 4h | Marketplace | Marketplace API only | UI login session. **Unchanged.** |
| Plugin-ticket (new) | EdDSA / Ed25519 | 5 min | Marketplace | Each Data Engine via JWKS | Data-plane WebSocket auth. **New, flag-gated.** |
Canonical flag names used throughout this plan:
- **Client (Local App), per-plugin opt-in:** `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` (comma-separated plugin IDs).
- **Engine (Data Engine), per-plugin enforcement:** `REQUIRE_TICKET_AUTH_PLUGINS` (comma-separated).
- **Engine, global default-deny:** `REQUIRE_TICKET_AUTH` (boolean, default `false`).
- **Engine, Origin allowlist enforcement:** `ENFORCE_ORIGIN_ALLOWLIST` (boolean, default `false`).
- **Local App SSRF allowlist:** `PROXY_HOST_ALLOWLIST` (`*` sentinel, empty/unset = deny, or concrete list).
When all three engine flags are off, Data Engine accepts unauthenticated connections (today's behavior). When `REQUIRE_TICKET_AUTH_PLUGINS` includes a plugin, the client must send `{type:"auth", v:1, token}` first message and engine validates.
This means each repo can be deployed independently in the safe order below; the new code is dormant until the flag is flipped per-plugin.
---
## Workstreams
### A. Marketplace repo (separate codebase — produce a hand-off spec from this plan)
Deliverables the Marketplace team must ship:
1. **Ed25519 keypair generation + storage**, with overlap support (current + next `kid`).
2. `GET /.well-known/jwks.json` — public keys array, `Cache-Control: public, max-age=300`.
3. **Data-plane ticket exchange** — `POST /api/tickets/exchange` — body `{ api_key, audience, plugin_id }`; returns `{ token, expires_in: 300 }`. Claims per ADR-001B: `iss, sub, aud, exp, iat, jti, tier, scope`. Redis-backed `jti` issuance counter for rate-limiting; Postgres fallback per ADR failure-mode table.
4. Library: `jose` for sign + JWKS publication.
### A4. Marketplace API-Key sub-spec (gating workstream — must complete BEFORE step 2)
Pulled out of Workstream A because it is not a one-endpoint change. The Marketplace does not currently have an "API Key" concept — today's PKCE callback stores the OAuth `access_token` directly. A4 invents the API-Key end-to-end:
- New DB table for API Keys (device-bound, manually rotated per ADR-001C).
- `POST /api/oauth/token` — the PKCE token endpoint consumed by `src/app/api/marketplace/callback/route.ts:27`. Renamed from `/api/tickets/exchange` to avoid path collision with A3.
- API-Key issuance and rotation API.
- Rotation UI in the Marketplace (per ADR-001C).
- A4 is treated as its own workstream with its own sub-plan; do not bundle it into the A1–A3 deploy.
### B. Data Engine repo (`wwv-data-engine-public` — hand-off spec)
**SDK delivery mechanism (decide before B starts):** the Data Engine must consume the same `PluginJwtClaims` and `WebSocketAuthMessage` types that live in `packages/wwv-plugin-sdk` here. Pick one:
- **(Recommended)** Publish `wwv-plugin-sdk` to a private npm registry (or GitHub Packages) with a SemVer tag; Data Engine pins `^x.y.z`.
- Vendor a copy in Data Engine and add a CI check that diffs against the upstream SDK on push.
- Git submodule pointing at a tagged commit.
Drift between repos = silent audience-binding mismatches. Pick one before any Workstream B code lands.
Deliverables:
1. `@fastify/jwt` + `get-jwks` integration; LRU JWKS cache 5 min; unknown-`kid` triggers single background re-fetch then reject.
2. **Fail-closed cold start** — if JWKS unreachable on boot, refuse all connections. **Gated by `REQUIRE_TICKET_AUTH || REQUIRE_TICKET_AUTH_PLUGINS !== "" || ENFORCE_ORIGIN_ALLOWLIST`** — when no ticket auth is active (the dormant-deploy state), JWKS unreachable is non-fatal at boot; engine boots, retries fetch in background. Today's engine has no Marketplace boot dependency, and the dormant deploy must preserve that.
3. WS upgrade handler validates `Origin` (allowlist via env), `Host`, TLS state, expected tenant/plugin metadata. **Flag-gated by `ENFORCE_ORIGIN_ALLOWLIST` (default `false`)** so first deploy does not reject existing production clients. Flipped to `true` only after the allowlist has been populated and observed in logs (step 7).
4. **First-message auth state machine** — connection state `AWAITING_AUTH`; 3s timer; reject any non-auth frame; close 4003 on failure; promote to `AUTHENTICATED` on success; no re-auth.
5. Audience binding — reject if `aud !== process.env.ENGINE_ID`.
6. Log redaction — JWT payloads never serialized to logs.
7. Feature flag `REQUIRE_TICKET_AUTH` defaults `false`; production cuts over per-plugin. Separate from `ENFORCE_ORIGIN_ALLOWLIST` so the two protections can be rolled out independently.
### C. Local App (this repo — concrete file changes)
**C1. Cleanup & safety (must land first, no behavior change)**
- `src/lib/auth/encryption.ts:9` — throw on missing **`ENCRYPTION_MASTER_KEY`** (correct var name; not `MASTER_KEY`) instead of zero fallback. **Pre-deploy gate:** verify `ENCRYPTION_MASTER_KEY` is set in every Coolify environment (local-self-host template, cloud, demo) and in `.env.example` before merging this change — otherwise next deploy fails on boot.
- `src/app/api/marketplace/callback/route.ts:29` — replace `config as any` with proper `client.discovery()` once Marketplace publishes its discovery doc; until then, type the config explicitly.
- **Type-level separation instead of runtime guard:** Introduce branded types in `packages/wwv-plugin-sdk/src/auth-contracts.ts`:
- `type MarketplaceSessionToken = string & { __brand: "marketplace-session" }`
- `type PluginTicket = string & { __brand: "plugin-ticket" }`
- `marketplaceToken.ts` signs/returns `MarketplaceSessionToken`; new `ticketClient.ts` returns `PluginTicket`; `WsClient`'s auth message accepts only `PluginTicket`. Compiler enforces the separation — no fragile runtime detection.
- Add doc comment to `marketplaceToken.ts`: "Marketplace UI session only — NOT a data-plane ticket."
- Existing consumers ([src/lib/marketplace/auth.ts](src/lib/marketplace/auth.ts), [install-redirect/route.ts](src/app/api/marketplace/install-redirect/route.ts), [grant-token/route.ts](src/app/api/marketplace/grant-token/route.ts)) continue to receive `MarketplaceSessionToken` — no behavior change.
**C2. SSRF hardening (ADR-001D)**
- Add `PROXY_HOST_ALLOWLIST` env var (comma-separated). Enforce in `src/lib/security/ssrf.ts` before scheme/IP checks. **Default behavior:**
- `PROXY_HOST_ALLOWLIST="*"` → permissive (current behavior), logs a `WARN` per request naming the host so operators can populate the list from observed traffic. **Sentinel-based instead of relying on unset-vs-empty** because Coolify and similar PaaS UIs may send `""` for "unset."
- `PROXY_HOST_ALLOWLIST=""` or unset → deny all (safe default).
- `PROXY_HOST_ALLOWLIST="a.example,b.example"` → only those hosts allowed.
Ship C2 with the var set to `*` in all environments; populate over a week of log observation; flip to a concrete allowlist in step 7c.
- `src/app/api/camera/proxy/iframe/route.ts` — route through `safeFetch`; add 5 MB size cap; reject redirects to non-allowlisted hosts (don't follow by default).
- Document the allowlist procedure in `.agents/context/environment-config.md`.
**C3. Ticket client (new, dormant behind flag)**
- New module `src/lib/auth/ticketClient.ts`: given a `pluginId` and the encrypted API Key from `MarketplaceCredential`, POSTs to Marketplace `/api/tickets/exchange`, caches the 5-min JWT in memory keyed by `(pluginId, audience)`, refreshes at 4.5 min.
- New hook `src/core/data/useTicket.ts` consumed by `WsClient`.
**C4. WebSocket first-message auth (client side)**
- `src/core/data/WsClient.ts:67-69` — when `ticketAuth` enabled for plugin, on `onopen` send `WebSocketAuthMessage` (from `auth-contracts.ts`) *before* any subscribe; queue subscribes until server `ack`.
- Add 3 s client-side auth timeout that closes and reconnects.
**C5. Feature flag**
- `src/core/edition.ts` — new flag `ticketAuthEnabledForPlugin(pluginId): boolean`, sourced from `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` (comma list) so we can enable one plugin at a time.
**C6. ADR status**
- Move `docs/architecture/decisions/adr-0001-...md:4` from `Proposed` to `Accepted` once Workstreams A/B/C land in their repos but BEFORE any plugin is flag-flipped.
---
## Parallelization: what runs concurrently vs sequentially
**Code writing — fully parallel.** Three agents can work in three repos simultaneously with zero file conflicts:
- Agent 1: Marketplace (`worldwideview-marketplace`, `feat/adr-001-marketplace`) — A1, A2, A3 fixes.
- Agent 2: Data Engine (`wwv-data-engine`, `feat/adr-001-data-engine`) — B1-B5 fixes.
- Agent 3: Local App (`worldwideview.feat-adr-001-local-app`, `feat/adr-001-local-app`) — C1, C2 first; then C3, C4, C5 once contract is confirmed.
The wire contract (POST body shape for `/api/auth/exchange`, JWT claim shape, WS first-message format) is already defined in `packages/wwv-plugin-sdk/src/auth-contracts.ts` and the existing Marketplace/Data Engine code — agents don't need to coordinate on it.
**Workstream A4 (Marketplace PKCE / API Key invention) can also run in parallel** with the other three, since it touches new files (`/api/oauth/token`, new Prisma model) and doesn't conflict with A1-A3. Treat it as a 4th parallel track.
**Deploys — must be sequenced** (this is the part that took down the previous attempt by compressing it). The order in the next section enforces that.
**Bottom line:** parallelize the *writing*, sequence the *shipping*.
## Deploy Order (zero-downtime sequenced choreography)
Steps 1–5 are individually deployable and dormant for the new ticket flow. **Step 1 introduces a hard `ENCRYPTION_MASTER_KEY` requirement** that the step-0 audit must confirm is satisfied — that is the riskiest item in the pre-ticket-cutover phase. Production behavior for ticket auth does not change until step 6.
0. **Pre-flight audit (before any code lands).** The previous failed deploy may have left debris. Audit and reconcile, producing an artifact at `docs/deploys/2026-MM-DD-adr-001-preflight.md` (use today's date) that records:
- Coolify env vars on the Local App, Marketplace, and Data Engine services — list every `JWT_*`, `TICKET_*`, `JWKS_*`, `AUTH_*` var and decide keep/remove.
- `wwv-data-engine-public` `main` branch — confirm the rolled-back state is clean (no half-merged `@fastify/jwt` wiring, no env-gated bypass middleware).
- Any feature flags or dormant routes already in production from the prior attempt.
- Confirm `ENCRYPTION_MASTER_KEY` is set on every environment (gate for C1).
- Confirm decision on SDK delivery mechanism (gate for B).
- Create `docs/feature-flags.md` listing all 5 flags introduced by this plan (`NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS`, `REQUIRE_TICKET_AUTH`, `REQUIRE_TICKET_AUTH_PLUGINS`, `ENFORCE_ORIGIN_ALLOWLIST`, `PROXY_HOST_ALLOWLIST`) with: which repo, default value, what each setting means, and a per-environment table (dev/staging/prod) the operator keeps current. Drift between staging and prod is a known paper-cut; the doc is the single source of truth.
- Confirm A4 sub-spec (Marketplace API-Key invention) has its own plan and is on track — A4 must ship before step 2.
1. **Local App** ships C1 + C2 (cleanup + SSRF). Pure hardening, no protocol change. Verify and deploy.
2. **Marketplace** ships A1–A3 (Ed25519 keys, JWKS endpoint, data-plane ticket-exchange). **A4 must already be shipped** as a prerequisite (see Workstream A4 above) — confirmed in step 0. New endpoints only, no existing endpoint changes. Verify JWKS reachable.
3. **Local App** ships C3 + C4 + C5 (ticket client, first-message auth, flag) with flag set to `""` (empty = nothing enabled). Dormant. Deploy.
4. **Data Engine** ships B1–B7 with `REQUIRE_TICKET_AUTH=false` **and** `ENFORCE_ORIGIN_ALLOWLIST=false`. Both new verification paths exist but are dormant. Deploy.
5. **Smoke test in staging** — flip flag for one synthetic plugin only; verify end-to-end ticket → WS auth → stream → 5-min refresh → revocation latency.
6. **Cut over one real plugin at a time** by adding it to `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` and the engine's `REQUIRE_TICKET_AUTH_PLUGINS`. Monitor each for 24h before adding the next.
7. **Default-deny rollout — split into three independent steps with 24h soak between each** so attribution is clear if anything breaks:
- **7a.** Set `REQUIRE_TICKET_AUTH=true` on the Data Engine. Soak 24h.
- **7b.** Set `ENFORCE_ORIGIN_ALLOWLIST=true` on the Data Engine (after populating the Origin allowlist from observed connections). Soak 24h.
- **7c.** Replace `PROXY_HOST_ALLOWLIST="*"` with the concrete observed list on the Local App. Soak 24h.
Each step is independently revertable by flipping its single flag back.
8. **Accept** the ADR; schedule HS256 marketplace-session token review as a follow-up (out of scope here).
**Re-verification rule (anti-dormant-code rot):** between steps 3 and 5, run the staging smoke test (step 5) **weekly** if the cutover is paused. Dormant feature-flagged code rots — catching it weekly in staging beats finding it broken on cutover day.
Rollback at any step: remove the plugin from the env list. Old path is still wired up because we never removed it.
---
## Critical Files (this repo)
- `src/lib/auth/encryption.ts` — fix silent fallback (C1)
- `src/lib/security/ssrf.ts` — add host allowlist (C2)
- `src/app/api/camera/proxy/iframe/route.ts` — route via safeFetch (C2)
- `src/app/api/marketplace/callback/route.ts` — remove `as any` cast (C1)
- `src/lib/marketplace/marketplaceToken.ts` — guard against data-plane misuse (C1)
- `src/lib/auth/ticketClient.ts` — **new** (C3)
- `src/core/data/WsClient.ts` — first-message auth (C4)
- `src/core/edition.ts` — per-plugin flag accessor (C5)
- `packages/wwv-plugin-sdk/src/auth-contracts.ts` — already has the types, reuse
- `docs/architecture/decisions/adr-0001-...md` — status flip (C6)
---
## Verification
End-to-end (run in staging, gated by `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS=test-synthetic`):
1. `pnpm test` — Vitest suite green including new tests for `ticketClient` and `WsClient` first-message flow.
2. `pnpm build` — no TS errors after removing the `as any` cast.
3. Manual: with engine `REQUIRE_TICKET_AUTH_PLUGINS=test-synthetic`, connect WS without auth message → engine closes with 4003 within 3 s.
4. Manual: valid ticket → stream flows; wait 4.5 min → client transparently refreshes; revoke API Key on Marketplace → next refresh fails, current stream finishes its 5-min window then disconnects (matches ADR revocation table).
5. Stop Marketplace → Data Engine cold-start refuses connections (fail-closed); restart Marketplace → connections resume.
6. SSRF: attempt `POST /api/camera/proxy` to a host not in `PROXY_HOST_ALLOWLIST` → 403. Attempt to a host resolving to 127.0.0.1 → 403.
7. Encryption fallback: unset `ENCRYPTION_MASTER_KEY`, start app → process refuses to start.
Deploy gate: all of the above pass in staging before step 6 of the deploy order touches any production plugin.
@@ -0,0 +1,264 @@
# ADR-001 Workstream A: Marketplace Hardening (A1–A3)
## Context
The Marketplace already ships two stubbed JWT endpoints from a prior attempt:
- `GET /api/auth/jwks` — Ed25519 JWKS publication
- `POST /api/auth/exchange` — issues 5-min audience-bound EdDSA tickets
Both are functional but wrong in production-critical ways: the JWKS cache is set to 24h (mismatched against the 5-min ticket lifetime), the API-key check is a hardcoded string, and the JWT claims (`sub`, `aud`, `tier`, `scope`) are stubs.
ADR-001 (`C:\dev\worldwideview\docs\architecture\decisions\adr-0001-decentralized-plugin-auth-and-ssrf-mitigation.md`) makes this the foundation of decentralized plugin auth: each Data Engine verifies tickets offline via JWKS, with no Marketplace DB roundtrip per frame. A wrong cache TTL or missing `kid` silently breaks every consumer.
This plan delivers **A1 + A2 + A3 only** — the bounded hardening of the two existing endpoints, plus the minimum schema needed to back A3 with real DB lookups. **A4 (PKCE token endpoint + API-Key issuance UI) is deferred** to its own branch/PR per the master plan's explicit instruction: *"Treat it as its own workstream with its own sub-plan; do not bundle it into the A1–A3 deploy."*
A4 also depends on design decisions outside this scope (how a user authenticates to the Marketplace, whether there's a consent screen, how `openid-client` on the Local App expects the token response shaped) that should not be force-fit into a hardening pass.
---
## Decisions (with rationale)
### D1. Separate `User` table (vs. denormalize onto API key)
- Per ADR-001B, `sub` is "the user's unique ID" and `tier` is subscription-scoped. These are identity facts, not credential facts. A user with two devices (two API keys) shares one tier.
- Denormalizing tier onto each `MarketplaceApiKey` row creates multi-row update consistency problems on tier change.
### D2. SHA-256 for `keyHash` (vs. bcrypt per HANDOFF)
- The HANDOFF says "bcrypt of the raw key," but bcrypt is non-deterministic — `WHERE keyHash = bcrypt(input)` is impossible. The exchange endpoint would have to load every row and `bcrypt.compare` each, which is O(n) per request.
- API keys here are **32 bytes of CSPRNG output** (256 bits of entropy). Slow hashing is for low-entropy passwords; for high-entropy secrets, SHA-256 with constant-time compare is the standard (GitHub, AWS, Stripe all use deterministic hashes for API keys).
- No new dependency. Uses `node:crypto` (already a Node built-in).
### D3. Defer A4 entirely
- Master plan: A4 is its own workstream.
- A4 is gated by product decisions (Marketplace auth/login, consent UI) that don't exist yet.
- A1–A3 deliver real value independently — they make the existing JWT issuance pipeline production-correct.
- The Local App's PKCE callback is already broken (calls `/api/tickets/exchange` which doesn't exist); deferring A4 doesn't regress anything.
### D4. Scope derivation from tier (not stored)
- ADR-001B says `scope` is "specific entitlements." If stored separately from tier, the two can drift.
- Derive at JWT issuance: `free → "plugins:read"`, `pro → "plugins:read plugins:write"`, `enterprise → "plugins:read plugins:write plugins:admin"`. Single function, easy to extend.
---
## Implementation
### A1. Fix JWKS cache TTL
**File:** `src/app/api/auth/jwks/route.ts:26`
Change `max-age=86400, stale-while-revalidate=86400` → `max-age=300, stale-while-revalidate=60`.
Rationale: ticket lifetime is 5 min (300s) per ADR-001B. Cache TTL matching the ticket lifetime means a Data Engine can never have stale JWKS during a valid ticket's lifetime. `swr=60` lets engines tolerate brief Marketplace downtime — matches the ADR's "JWKS cache expires (Marketplace down) → grace period" failure mode row.
### A2. Ensure `kid` present in JWK
**File:** `src/app/api/auth/jwks/route.ts`
Currently relies on the env-var JWK having a `kid` field, which the spread `{ ...privateJwk }` carries through. But there's no defensive check — if `MARKETPLACE_JWK_PRIVATE` was generated without `kid`, the endpoint silently publishes a key with no identifier, and `get-jwks` on the Data Engine can't cache it.
Fix: after parsing, throw if `privateJwk.kid` is falsy. Return 500 with a clear error log (`MARKETPLACE_JWK_PRIVATE is missing 'kid' field — regenerate per README`).
Also: ensure `alg: "EdDSA"` is present on the published JWK so JWKS consumers can pre-validate algorithm. The spread carries it through if set; add the same defensive check.
> **Pre-mortem mitigation (TIGER, medium):** this check is fail-closed — if the *current production* `MARKETPLACE_JWK_PRIVATE` lacks `kid`, this deploy turns "JWKS works without kid" into "JWKS 500s every Data Engine fetch." **Before merging**, audit the env var in every environment (local-self-host, cloud, demo):
> ```
> node -e "const j=JSON.parse(process.env.MARKETPLACE_JWK_PRIVATE);console.log('kid:',j.kid,'alg:',j.alg)"
> ```
> If any environment prints `kid: undefined`, regenerate the keypair per the HANDOFF README *before* this code reaches that environment.
### A3. Harden the token exchange endpoint
#### A3a. Schema additions
**File:** `prisma/schema.prisma`
Add two models:
```prisma
model User {
id String @id @default(cuid())
email String @unique
tier String @default("free") // "free" | "pro" | "enterprise"
createdAt DateTime @default(now())
apiKeys MarketplaceApiKey[]
}
model MarketplaceApiKey {
id String @id @default(cuid())
userId String
keyHash String @unique // SHA-256 hex of raw key, used for O(1) lookup
deviceId String?
name String? // user-given label, e.g. "Home Server"
createdAt DateTime @default(now())
lastUsedAt DateTime?
revokedAt DateTime?
user User @relation(fields: [userId], references: [id])
@@index([userId])
}
```
Run `pnpm prisma migrate dev --name add_user_and_marketplace_api_key`.
Note: `MarketplaceApiKey` model is added here even though A4 (issuance) is deferred — A3's DB lookup needs the model to exist. A4 will add the *issuance path*; A3 only consumes the table.
#### A3b. Add a `scopeFor(tier)` helper
**File (new):** `src/lib/auth/tierScope.ts`
```ts
export function scopeFor(tier: string): string {
switch (tier) {
case "enterprise": return "plugins:read plugins:write plugins:admin";
case "pro": return "plugins:read plugins:write";
case "free":
default: return "plugins:read";
}
}
```
Single source of truth; A4 will also use this.
#### A3c. Add a key-hashing helper
**File (new):** `src/lib/auth/apiKeyHash.ts`
```ts
import { createHash, timingSafeEqual } from "node:crypto";
/** Deterministic SHA-256 hex of an API key. Use for DB lookup. */
export function hashApiKey(rawKey: string): string {
return createHash("sha256").update(rawKey, "utf8").digest("hex");
}
/** Constant-time compare of two hex strings. */
export function timingSafeEqualHex(a: string, b: string): boolean {
if (a.length !== b.length) return false;
return timingSafeEqual(Buffer.from(a, "hex"), Buffer.from(b, "hex"));
}
```
#### A3d. Rewrite the exchange endpoint
**File:** `src/app/api/auth/exchange/route.ts`
- Parse body as `{ apiKey, audience?, plugin_id? }`.
- Reject if `apiKey` missing (400).
- Hash the apiKey via `hashApiKey()` and look up `prisma.marketplaceApiKey.findUnique({ where: { keyHash }, include: { user: true } })`.
- If not found, or `revokedAt != null` → 401.
- Update `lastUsedAt = new Date()` (fire-and-forget: `prisma.marketplaceApiKey.update(...).catch(err => console.warn("lastUsedAt update failed:", err.message))` — never await, never let it fail the request).
- JWT claims:
- `iss`: `"https://marketplace.worldwideview.dev"` (unchanged)
- `sub`: `apiKeyRecord.userId` (was: `"user-id-stub"`)
- `aud`: `audience ?? "wwv-data-engine"` (default for backwards-compat per HANDOFF)
- `tier`: `apiKeyRecord.user.tier` (was: `"pro"`)
- `scope`: `scopeFor(apiKeyRecord.user.tier)` (was: `"plugins:read"`)
- `exp`, `iat`, `nbf`, `jti`: unchanged
- Header `kid`: unchanged
- Return `{ token }` as before.
#### A3e. Update tests
**File:** `src/app/api/auth/exchange/route.spec.ts`
- Mock `@/lib/prisma` with `vi.mock`. Provide a fake `prisma.marketplaceApiKey.findUnique` that returns a fixture user/key for one specific hashed key, and `null` otherwise.
- Test: invalid key → 401.
- Test: valid key → 200, JWT contains `sub` matching user id, `aud` matching request body, `tier`/`scope` matching user fixture.
- Test: revoked key (revokedAt set) → 401.
- Test: `aud` defaults to `"wwv-data-engine"` when `audience` omitted from body.
- Keep the existing claim-shape assertions.
**File:** `src/app/api/auth/jwks/route.spec.ts`
- Add: when env JWK has no `kid` → 500.
- Add: response has `Cache-Control` with `max-age=300`.
### Seed data
**File:** `prisma/seed.ts`
Add a test user + API key (only run in dev/test) so the exchange endpoint can be exercised by `curl`:
```ts
// Add to existing seed
const testUser = await prisma.user.upsert({
where: { email: "[email protected]" },
update: {},
create: { email: "[email protected]", tier: "pro" }
});
await prisma.marketplaceApiKey.upsert({
where: { keyHash: hashApiKey("dev-key-do-not-use-in-prod") },
update: {},
create: {
userId: testUser.id,
keyHash: hashApiKey("dev-key-do-not-use-in-prod"),
name: "dev seed key"
}
});
```
Raw key `dev-key-do-not-use-in-prod` is committed intentionally — it only works against a local dev DB seeded with it.
---
## Critical files
| File | Change | Task |
|---|---|---|
| `src/app/api/auth/jwks/route.ts` | Cache header + kid defensive check | A1, A2 |
| `src/app/api/auth/jwks/route.spec.ts` | New tests for kid + cache | A1, A2 |
| `prisma/schema.prisma` | Add User + MarketplaceApiKey models | A3a |
| `src/lib/auth/tierScope.ts` | **NEW** — scope derivation | A3b |
| `src/lib/auth/apiKeyHash.ts` | **NEW** — SHA-256 + constant-time compare | A3c |
| `src/app/api/auth/exchange/route.ts` | Real DB lookup, real claims | A3d |
| `src/app/api/auth/exchange/route.spec.ts` | Prisma-mocked tests | A3e |
| `prisma/seed.ts` | Dev seed user + key | (dev only) |
Existing utilities reused:
- `src/lib/prisma.ts` — singleton Prisma client.
- `jose` (already installed) — JWT signing.
- `node:crypto` — SHA-256, timing-safe compare.
---
## Verification
1. `pnpm prisma migrate dev` — migration applies cleanly to a fresh DB.
2. `pnpm test` — vitest suite green: new + updated exchange tests, jwks tests.
3. `pnpm lint && pnpm build` — no TS errors.
4. Manual end-to-end (dev):
- `pnpm prisma db seed` — seeds dev user + key.
- `curl http://localhost:3000/api/auth/jwks` — returns `{ keys: [{ kty:"OKP", crv:"Ed25519", x, kid, alg:"EdDSA" }] }`, no `d`, `Cache-Control: public, max-age=300, stale-while-revalidate=60`.
- `curl -X POST http://localhost:3000/api/auth/exchange -d '{"apiKey":"dev-key-do-not-use-in-prod","audience":"wwv-aviation-engine","plugin_id":"aviation"}' -H 'Content-Type: application/json'` — returns `{ token }`.
- Decode the JWT at jwt.io: `iss === "https://marketplace.worldwideview.dev"`, `sub` is the seeded user id, `aud === "wwv-aviation-engine"`, `tier === "pro"`, `scope === "plugins:read plugins:write"`, `exp - iat === 300`, header has `kid`.
- Same curl with `apiKey: "valid-key-for-testing"` (the old stub) → 401.
- Same curl with `apiKey` omitted → 400.
---
## Deployment checklist (pre-mortem mitigations)
1. **Pre-deploy env audit** — before this code reaches any environment, run:
```
node -e "const j=JSON.parse(process.env.MARKETPLACE_JWK_PRIVATE);console.log('kid:',j.kid,'alg:',j.alg)"
```
Both must be non-null. If `kid` is missing, regenerate the keypair (the HANDOFF README has the Node script). Do this in every environment (local-self-host, cloud, demo) before merging.
2. **Production migration** — the deploy pipeline must run `pnpm prisma migrate deploy` (not `migrate dev`) on boot before the app starts. Verify this is wired into the Coolify start command or Dockerfile CMD. The new `User` and `MarketplaceApiKey` tables must exist before any request reaches the exchange endpoint.
3. **Empty-table gap** — after A3 deploys and until A4 ships, the exchange endpoint requires a real `MarketplaceApiKey` row to issue a JWT. There are no such rows in production until A4's issuance path lands. This is acceptable because: (a) the Local App's callback is already broken today (`/api/tickets/exchange` 404s), so no real traffic is hitting this endpoint, and (b) the `dev-key-do-not-use-in-prod` seed entry gives a working dev/staging test path through the real code. Document this gap in the PR description so the next person isn't confused by a blank table.
---
## Out of scope (explicit deferrals)
- **A4 — PKCE token endpoint, OAuth authorize page, API-Key issuance UI.** Its own workstream. The `MarketplaceApiKey` model is added in A3 so A4 can plug straight in without a schema migration.
- **Key rotation overlap** (multi-key JWKS array). The JWKS endpoint already returns an array of one key; multi-key rotation is a separate concern.
---
## Risk Mitigations (Pre-Mortem)
**Pre-mortem run:** 2026-05-21 | Mode: quick | Tigers: 3 | Elephants: 1
### Tigers addressed
1. **Production migration path unclear** (medium) — Mitigation: Deployment checklist item 2 above. Plan explicitly requires `prisma migrate deploy` step.
2. **`kid` defensive check fails-closed on deploy** (medium) — Mitigation: Deployment checklist item 1 above. Mandatory pre-deploy env audit.
3. **Fire-and-forget `lastUsedAt` unhandled rejection** (low) — Mitigation: Added `.catch(warn)` to A3d spec.
### Elephant addressed
- **No user creation path until A4** — Mitigation: dev seed provides a working test path; prod gap documented in deployment checklist item 3. Acceptable because the endpoint has zero real traffic today.
### Accepted risks (none — all addressed)
- **Redis-backed `jti` counter / rate limiting.** Per ADR-001 failure-mode table, this is part of issuance hardening — not bundled here.
- **`/api/tickets/exchange` legacy path.** The Local App currently points there but it doesn't exist. Renaming the callback URL is a Local App change (workstream C1), not Marketplace.
@@ -0,0 +1,173 @@
# ADR-001 Production Auth Rollout — Two-Track Strategy
## Context
PR #9 (`wwv-data-engine`) merged + deployed. Auth is bypassed (`WWV_SKIP_WS_AUTH=true`).
`WWV_SKIP_WS_AUTH` lives on the **engine** — flipping it affects every app connecting
to that engine (demo, local, future cloud). The demo has anonymous visitors with no
user session. It needs a **service credential** (machine-to-machine API key) so
`/api/auth/ticket` can issue JWTs on behalf of visitors with no session.
ADR-003 (Supabase identity) is not yet implemented and blocks the full PKCE user
flow. It must not block the demo deployment.
**Strategy:**
- **Track A (demo, immediate):** Seed a service credential into production DBs → flip
auth on → zero user-facing change. No PKCE needed.
- **Track B (local/self-hosted, medium-term):** Implement the PKCE OAuth server on
the marketplace using admin-password auth (no Supabase). When ADR-003 lands,
replace the password check with Supabase session check — same OAuth interface,
no client changes.
---
## Track A — Demo Service Credential (Production)
### Why this works
**`src/core/edition.ts` line 70:** `export const isAuthEnabled: boolean = !isDemo;`
`isAuthEnabled = false` in demo edition → `/api/auth/ticket` skips the session
gate entirely and calls `getTicket()` directly. The admin's "special login page"
uses `WWV_DEMO_ADMIN_SECRET` — a completely separate mechanism unrelated to the
ticket flow. Every anonymous visitor can call `/api/auth/ticket` and get a JWT,
provided `MarketplaceCredential { tenantId: "local" }` exists in the demo DB.
Also confirmed: `ticketAuthEnabledForPlugin()` parses `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS`
as CSV. The current `"\"\""` bug in Coolify makes it parse to no valid IDs → all
plugins skip ticket auth → they connect unauthenticated → `WWV_SKIP_WS_AUTH=true`
lets them in. Fixing the env var + adding the credential + flipping auth is the
complete transition.
### Prerequisites (Coolify → `worldwideview-demo` → Environment)
```
ENCRYPTION_MASTER_KEY=<generate: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))">
MARKETPLACE_URL=https://marketplace.worldwideview.dev
```
Set these before running the seed script. The master key is used to encrypt the
credential at seed time and decrypt it at runtime.
### Step A1 — Write seed script
**File:** `local-scripts/seed-demo-credential.mjs`
One idempotent run does:
1. Connects to marketplace SQLite on the server (SSH + direct file access or
Prisma with `DATABASE_URL=file:<path>`)
- Upserts `User { email: "[email protected]", tier: "pro" }`
- Generates raw API key: `crypto.randomBytes(32).toString('hex')`
- SHA256-hashes it → upserts `MarketplaceApiKey { userId, keyHash, revokedAt: null }`
2. Connects to demo PostgreSQL
- AES-256-GCM encrypts the raw API key using `ENCRYPTION_MASTER_KEY`
(matching the format in `src/lib/auth/encryption.ts`:
`pbkdf2Sync(key, salt, 100000, 32, 'sha256')` → cipher → `base64(ct).base64(tag)`)
- Upserts `marketplace_credentials { tenantId: "local", version:"v1", salt, nonce, ciphertext }`
3. Prints `[seed] ✅ Demo service credential installed`
### Step A2 — Fix env var + rebuild demo
Coolify → `worldwideview-demo` → Environment:
- `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` → `aviation,maritime` (remove literal quotes)
- Trigger **rebuild** (build-time env var — restart alone doesn't pick it up)
### Step A3 — Verify ticket route
```bash
curl https://<demo-fqdn>/api/auth/ticket?pluginId=aviation
# expect: { "token": "eyJ..." }
```
- 500 → `ENCRYPTION_MASTER_KEY` mismatch or credential not seeded
- 200 with no `token` field → `ticketClient` returned wrong shape
- 401 → `isAuthEnabled` is true (shouldn't happen in demo edition — check `NEXT_PUBLIC_WWV_EDITION=demo`)
### Step A4 — Flip auth on engine
Coolify → `wwv-engine-stack` → Environment → `WWV_SKIP_WS_AUTH=false` → Deploy.
### Step A5 — Smoke test
```bash
node local-scripts/local-smoke-test.mjs # pointed at production URLs
# Step 1: JWKS ✅ Step 2: Exchange ✅ Step 3: WS welcome ✅
```
---
## Track B — PKCE OAuth Server on Marketplace (Local/Self-Hosted)
Implements the missing `GET /oauth/authorize` (consent page) and
`POST /api/oauth/token` (code exchange) on the marketplace. Uses admin-password
auth for now — Supabase replaces the password check when ADR-003 lands. Same
OAuth interface; no client-side changes needed during that migration.
### Files to create/modify in `c:/dev/worldwideview-marketplace/`
**`prisma/schema.prisma`** — add:
```prisma
model OAuthCode {
id String @id @default(cuid())
code String @unique
userId String
user User @relation(fields: [userId], references: [id])
codeChallenge String
redirectUri String
clientId String
scope String
state String
expiresAt DateTime
usedAt DateTime?
@@index([code])
}
```
Add `oauthCodes OAuthCode[]` to `User`. Run `npx prisma db push` (SQLite, local).
**`src/app/oauth/authorize/page.tsx`** — consent UI:
- Reads URL params: `client_id`, `code_challenge`, `state`, `redirect_uri`, `scope`
- Renders form: "Local App is requesting access to your data. Enter your admin password."
- Stores params in hidden fields, POSTs to `/api/oauth/authorize`
**`src/app/api/oauth/authorize/route.ts`** (POST):
- Validates `password === process.env.ADMIN_PASSWORD`
- Finds or creates `User { email: "local@marketplace", tier: "pro" }`
- Creates `OAuthCode { code: randomBytes(32).hex, expiresAt: now+10min, ... }`
- Redirects to `redirectUri?code=<code>&state=<state>`
- **ADR-003 migration point:** swap password check for `supabase.auth.getUser()` session check
**`src/app/api/oauth/token/route.ts`** (POST, `application/x-www-form-urlencoded`):
- Parses `{ grant_type, code, code_verifier, client_id, redirect_uri }`
- Finds `OAuthCode`; verifies not expired, not used, clientId + redirectUri match
- PKCE: `createHash('sha256').update(code_verifier).digest('base64url') === codeChallenge`
- Marks `usedAt = now` (replay protection)
- Generates raw API key: `randomBytes(32).hex`
- SHA256-hash → creates `MarketplaceApiKey { userId, keyHash }`
- Returns `{ access_token: rawApiKey, token_type: "bearer" }`
**Note:** `connect/route.ts` in local app redirects to `/oauth/authorize` (no `/api/` prefix)
— the consent page is at that path. The POST handler is at `/api/oauth/authorize`.
### Local app env (`.env.local`):
```
NEXT_PUBLIC_WWV_MARKETPLACE_URL=http://localhost:3001
ENCRYPTION_MASTER_KEY=<any-32+-char-string>
```
### Verification (Track B)
1. Start all 3 services locally
2. Browser: `http://localhost:3000/api/marketplace/connect`
→ redirects to `http://localhost:3001/oauth/authorize?...`
→ enter admin password → redirects back to local app
3. `GET http://localhost:3000/api/auth/ticket?pluginId=aviation` → `{ token: "eyJ..." }`
4. Check WebSocket in devtools → `{ type: "welcome" }`
---
## ADR-003 Migration Path (future, no client changes needed)
When Supabase Auth is wired into the marketplace:
- `/api/oauth/authorize` replaces `password === ADMIN_PASSWORD` with `supabase.auth.getUser()`
- If no session → redirect to `worldwideview.dev/login?redirect_to=marketplace.../oauth/authorize?...`
- Everything else stays identical — same code format, same token endpoint, same local app callback
---
## Order of Execution
1. **Track A first** (demo service credential + auth flip) — unblocks production
2. **Track B in parallel or after** (PKCE for local instances) — enables proper self-hosted UX
3. **ADR-003 later** — migrates marketplace auth internals without touching clients
@@ -0,0 +1,874 @@
# WorldWideView Auth Rollout — ADR-001 + ADR-003
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:executing-plans` to implement
> this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Get ADR-001 (decentralized plugin auth) and ADR-003 (shared ecosystem identity)
into production with the least possible downtime. `/cloud` plan registration and billing
are deferred.
**Architecture:** One shared Supabase project is the identity store. `worldwideview.dev`
(the `worldwideview-web` repo) becomes the SSR auth host; a parent-domain cookie
(`.worldwideview.dev`) is inherited by every subdomain. The Marketplace becomes a PKCE
OAuth server on top of that session. The Local App is the PKCE client. The Data Engine
validates 5-minute JWTs on its WebSocket.
**Tech Stack:** Next.js 16 App Router, `@supabase/ssr`, Supabase Auth, Ed25519 JWTs
(`jose`), Prisma, Docker + Coolify.
---
## Northstar Sequence (the map)
Build everything locally on `wwv.local` HTTPS first, then deploy production one repo at a
time in this dependency order. Each deploy is independently revertible.
1. **Phase 0** — Provision Supabase + local HTTPS dev (human setup — see checklist below).
2. **Phase 1** — `worldwideview-web` becomes the SSR auth host. ← **detailed below**
3. **Phase 2** — Marketplace consumes the session + adds the PKCE OAuth server.
4. **Phase 3** — Merge the ADR-001 Local App worktree.
5. **Phase 4** — Data Engine WebSocket first-message JWT auth (report-only → enforcing).
6. **Phase 5** — Final cutover, link the nav, update docs, mark ADRs Accepted.
Phases 2–5 are detailed once Phase 1 lands and Assumption #2 (below) is confirmed.
---
## Phase 0 — Human Setup Checklist (do this while Phase 1 code is written)
These cannot be automated — they need accounts, browsers, admin rights, or a DNS panel.
- [ ] **0.1 Create the Supabase project.** supabase.com → New project. Pick a region close
to the Coolify host. Save the DB password. Copy three values: Project URL, `anon` public
key, `service_role` secret key.
- [ ] **0.2 Enable auth providers** (Supabase dashboard → Authentication → Providers):
- Email: enable, "Confirm email" ON.
- Google: create an OAuth Client in Google Cloud Console (APIs & Services → Credentials →
OAuth client ID → Web app). Authorized redirect URI:
`https://<project-ref>.supabase.co/auth/v1/callback`. Paste Client ID + Secret into
Supabase.
- GitHub: GitHub → Settings → Developer settings → OAuth Apps → New. Authorization
callback URL: `https://<project-ref>.supabase.co/auth/v1/callback`. Paste Client ID +
Secret into Supabase.
- [ ] **0.3 Set URL configuration** (Authentication → URL Configuration):
- Site URL: `https://worldwideview.dev`
- Redirect URLs (add all): `https://worldwideview.dev/**`,
`https://*.worldwideview.dev/**`, `https://wwv.local/**`, `https://*.wwv.local/**`
- [ ] **0.4 Install mkcert** (one-time, per dev machine). PowerShell as admin:
`choco install mkcert` then `mkcert -install`.
- [ ] **0.5 Generate the local TLS cert.** In `c:\dev\wwv`:
`mkcert "*.wwv.local" wwv.local` — produces a `.pem` cert + key pair.
- [ ] **0.6 Edit the hosts file** (admin). Add to `C:\Windows\System32\drivers\etc\hosts`:
`127.0.0.1 wwv.local marketplace.wwv.local app.wwv.local`
- [ ] **0.7 Confirm production DNS.** `worldwideview.dev`, `marketplace.worldwideview.dev`,
`app.worldwideview.dev` (and a `*.worldwideview.dev` wildcard) must point at the Coolify
host. Check the DNS provider; add records if missing.
- [ ] **0.8 Decide Assumption #2** — Marketplace keeps SQLite, or migrates to Supabase
Postgres? (See "Assumptions" at the end. This unblocks the Phase 2 detailed plan.)
- [ ] **0.9 Hand me the Supabase values** (or paste them yourself) so they can go into the
local `.env` files and the Coolify env vars — never committed to git. Needed:
`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`.
- [ ] **0.10 (Optional) Resend SMTP** — only if launching with magic-link login. Create a
Resend account, verify a sending domain, paste SMTP creds into Supabase → Project
Settings → Auth → SMTP. Skip if launching with email+password + OAuth only.
---
# Phase 1 Implementation Plan — `worldwideview-web` Auth Host
**Repo:** `c:\dev\wwv\worldwideview-web`
**Outcome:** `worldwideview.dev` serves the landing site (static) plus working SSR
`/login`, `/signup`, `/accounts`, and `/api/auth/callback`, with sessions written to a
parent-domain cookie. The container runs as Node, not Nginx.
### File Structure
| File | Responsibility |
|---|---|
| `next.config.ts` | Drop static export, switch to `standalone`, add headers |
| `vitest.config.ts` (new) | Unit test runner config |
| `src/lib/supabase/cookieOptions.ts` (new) | Pure helper: resolve cookie domain from env |
| `src/lib/supabase/cookieOptions.test.ts` (new) | Unit tests for the helper |
| `src/lib/supabase/client.ts` | Browser client via `@supabase/ssr` |
| `src/lib/supabase/server.ts` (new) | Server client via `@supabase/ssr` |
| `middleware.ts` (new) | Refresh the session on every request |
| `src/app/api/health/route.ts` (new) | Health endpoint for Coolify deploy gating |
| `src/app/login/page.tsx` | SSR login: email+password + OAuth |
| `src/app/login/actions.ts` (new) | Server action: password sign-in |
| `src/app/login/oauth-buttons.tsx` (new) | Client component: Google/GitHub buttons |
| `src/app/signup/page.tsx` (new) | SSR signup |
| `src/app/signup/actions.ts` (new) | Server action: account creation |
| `src/app/accounts/page.tsx` (new) | Account view + logout |
| `src/app/accounts/actions.ts` (new) | Server action: sign out |
| `src/app/api/auth/callback/route.ts` (new) | OAuth code → session exchange |
| `Dockerfile` | Node standalone runtime instead of Nginx |
| `docker-compose.yml` | Port mapping for the Node container |
| `.env.local` (new, not committed) | Local Supabase + cookie-domain vars |
---
### Task 1: Add dependencies and the test runner
**Files:** Modify `package.json`; Create `vitest.config.ts`; Create `.env.local`.
- [ ] **Step 1: Install `@supabase/ssr`.**
Run in `c:\dev\wwv\worldwideview-web`:
```bash
pnpm add @supabase/ssr
```
Expected: `@supabase/ssr` appears under `dependencies` in `package.json`.
- [ ] **Step 2: Add a `test` script.** In `package.json` `scripts`, add:
```json
"test": "vitest run"
```
- [ ] **Step 3: Create `vitest.config.ts`.**
```ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
},
})
```
- [ ] **Step 4: Create `.env.local`** (NOT committed — confirm it is in `.gitignore`):
```
NEXT_PUBLIC_SUPABASE_URL=<from Phase 0.1>
NEXT_PUBLIC_SUPABASE_ANON_KEY=<from Phase 0.1>
NEXT_PUBLIC_WWV_COOKIE_DOMAIN=.wwv.local
```
- [ ] **Step 5: Verify the `@supabase/ssr` API.** Use context7 (`resolve-library-id`
→ `query-docs` for `@supabase/ssr` "Next.js App Router server client middleware") to
confirm `createServerClient` / `createBrowserClient` signatures match the installed
version before writing Tasks 3–4. The `getAll`/`setAll` cookie pattern below is the
stable pattern; adjust only if the installed version differs.
- [ ] **Step 6: Commit.**
```bash
git add package.json pnpm-lock.yaml vitest.config.ts
git commit -m "chore: add @supabase/ssr and vitest runner"
```
---
### Task 2: Cookie-domain resolver helper (TDD)
The cookie `domain` must be `.worldwideview.dev` in production, `.wwv.local` in dev, and
**unset** when running on plain `localhost` (browsers reject a `domain` on `localhost`).
This is the one piece of pure logic worth a unit test.
**Files:** Create `src/lib/supabase/cookieOptions.ts`,
`src/lib/supabase/cookieOptions.test.ts`.
- [ ] **Step 1: Write the failing test.** `src/lib/supabase/cookieOptions.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { resolveCookieDomain } from './cookieOptions'
describe('resolveCookieDomain', () => {
it('returns undefined when nothing is configured', () => {
expect(resolveCookieDomain(undefined)).toBeUndefined()
})
it('returns undefined for an empty string', () => {
expect(resolveCookieDomain('')).toBeUndefined()
})
it('returns the configured domain', () => {
expect(resolveCookieDomain('.worldwideview.dev')).toBe('.worldwideview.dev')
})
it('trims surrounding whitespace', () => {
expect(resolveCookieDomain(' .wwv.local ')).toBe('.wwv.local')
})
})
```
- [ ] **Step 2: Run the test, confirm it fails.**
Run: `pnpm test`
Expected: FAIL — `resolveCookieDomain` is not exported / file not found.
- [ ] **Step 3: Implement `src/lib/supabase/cookieOptions.ts`.**
```ts
export function resolveCookieDomain(raw: string | undefined): string | undefined {
const trimmed = raw?.trim()
return trimmed ? trimmed : undefined
}
export function buildCookieOptions() {
return {
domain: resolveCookieDomain(process.env.NEXT_PUBLIC_WWV_COOKIE_DOMAIN),
path: '/',
sameSite: 'lax' as const,
secure: true,
}
}
```
- [ ] **Step 4: Run the test, confirm it passes.**
Run: `pnpm test`
Expected: PASS — 4 passing.
- [ ] **Step 5: Commit.**
```bash
git add src/lib/supabase/cookieOptions.ts src/lib/supabase/cookieOptions.test.ts
git commit -m "feat: add cookie-domain resolver for cross-subdomain sessions"
```
---
### Task 3: Supabase browser + server clients
**Files:** Modify `src/lib/supabase/client.ts`; Create `src/lib/supabase/server.ts`.
- [ ] **Step 1: Rewrite `src/lib/supabase/client.ts`** (browser client — now a factory):
```ts
import { createBrowserClient } from '@supabase/ssr'
import { buildCookieOptions } from './cookieOptions'
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookieOptions: buildCookieOptions() },
)
}
```
- [ ] **Step 2: Create `src/lib/supabase/server.ts`** (server client):
```ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { buildCookieOptions } from './cookieOptions'
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookieOptions: buildCookieOptions(),
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
)
} catch {
// Called from a Server Component — middleware refreshes instead.
}
},
},
},
)
}
```
- [ ] **Step 3: Migrate existing importers of the old `supabase` singleton.**
Run: `grep -rn "lib/supabase/client" src/` — every hit that did `import { supabase }`
must change to `import { createClient }` + `const supabase = createClient()`. The `hub/`
page is a known importer. Update each.
- [ ] **Step 4: Verify the build typechecks.**
Run: `pnpm build`
Expected: build proceeds past type-checking (it may still fail later on `output: export`
+ middleware — that is fixed in Task 5; a clean `tsc` pass here is the goal).
- [ ] **Step 5: Commit.**
```bash
git add src/lib/supabase/client.ts src/lib/supabase/server.ts src/app/hub
git commit -m "feat: add @supabase/ssr browser and server clients"
```
---
### Task 4: Session-refresh middleware
**Files:** Create `middleware.ts` (repo root, sibling of `src/`).
- [ ] **Step 1: Create `middleware.ts`.**
```ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
import { buildCookieOptions } from './src/lib/supabase/cookieOptions'
export async function middleware(request: NextRequest) {
let response = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookieOptions: buildCookieOptions(),
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
)
response = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options),
)
},
},
},
)
// Refreshes the session cookie if expired. Do NOT add logic between
// createServerClient and getUser().
await supabase.auth.getUser()
return response
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
}
```
- [ ] **Step 2: Verify it compiles.**
Run: `pnpm build`
Expected: no type errors from `middleware.ts`.
- [ ] **Step 3: Commit.**
```bash
git add middleware.ts
git commit -m "feat: add session-refresh middleware"
```
---
### Task 5: Convert `next.config.ts` from static export to SSR
**Files:** Modify `next.config.ts`.
- [ ] **Step 1: Replace `next.config.ts` entirely.**
```ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
images: {
unoptimized: true,
},
async headers() {
return [
{
source: "/:path*",
headers: [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
],
},
];
},
};
export default nextConfig;
```
Note: any custom headers currently in `nginx.conf` should be folded into the `headers()`
array. Keep CSP out for now unless `nginx.conf` already had one — an over-strict CSP
silently breaks Supabase XHR calls.
- [ ] **Step 2: Build and confirm SSR mode.**
Run: `pnpm build`
Expected: build output lists routes as a mix of `○ (Static)` and `ƒ (Dynamic)`; auth
routes appear as Dynamic. No `out/` directory is produced; `.next/standalone` is.
- [ ] **Step 3: Commit.**
```bash
git add next.config.ts
git commit -m "feat: switch worldwideview-web from static export to standalone SSR"
```
---
### Task 6: Health endpoint
**Files:** Create `src/app/api/health/route.ts`.
- [ ] **Step 1: Create the route.**
```ts
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export function GET() {
return NextResponse.json({ status: 'ok' })
}
```
- [ ] **Step 2: Verify.**
Run: `pnpm build && pnpm start` then in another shell: `curl -i http://localhost:3000/api/health`
Expected: `200 OK`, body `{"status":"ok"}`.
- [ ] **Step 3: Commit.**
```bash
git add src/app/api/health/route.ts
git commit -m "feat: add health endpoint for deploy gating"
```
---
### Task 7: Login page (email+password + OAuth)
**Files:** Modify `src/app/login/page.tsx`; Create `src/app/login/actions.ts`,
`src/app/login/oauth-buttons.tsx`.
- [ ] **Step 1: Create `src/app/login/actions.ts`.**
```ts
'use server'
import { redirect } from 'next/navigation'
import { createClient } from '../../lib/supabase/server'
export async function signInWithPassword(formData: FormData) {
const email = String(formData.get('email') ?? '')
const password = String(formData.get('password') ?? '')
const next = String(formData.get('next') ?? '/accounts')
const supabase = await createClient()
const { error } = await supabase.auth.signInWithPassword({ email, password })
if (error) {
redirect(`/login?error=${encodeURIComponent(error.message)}&next=${encodeURIComponent(next)}`)
}
redirect(next)
}
```
- [ ] **Step 2: Create `src/app/login/oauth-buttons.tsx`.**
```tsx
'use client'
import { createClient } from '../../lib/supabase/client'
import styles from '../hub/hub.module.css'
export function OAuthButtons({ next }: { next: string }) {
const signIn = async (provider: 'google' | 'github') => {
const supabase = createClient()
await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/api/auth/callback?next=${encodeURIComponent(next)}`,
},
})
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-sm)' }}>
<button className={styles.submitButton} onClick={() => signIn('google')} type="button">
Continue with Google
</button>
<button className={styles.submitButton} onClick={() => signIn('github')} type="button">
Continue with GitHub
</button>
</div>
)
}
```
- [ ] **Step 3: Rewrite `src/app/login/page.tsx`** as a server component:
```tsx
import { signInWithPassword } from './actions'
import { OAuthButtons } from './oauth-buttons'
import styles from '../hub/hub.module.css'
export default async function LoginPage({
searchParams,
}: {
searchParams: Promise<{ error?: string; next?: string }>
}) {
const { error, next = '/accounts' } = await searchParams
return (
<div className={styles.hubContainer}>
<div className={styles.glassCard} style={{ maxWidth: '400px', marginTop: '10vh' }}>
<h1 className={styles.title}>Welcome Back</h1>
<p style={{ textAlign: 'center', marginBottom: 'var(--space-lg)', color: 'var(--text-secondary)' }}>
Sign in to your WorldWideView account
</p>
<form action={signInWithPassword}>
<input type="hidden" name="next" value={next} />
<input className={styles.inputField} type="email" name="email"
placeholder="Email address" required />
<input className={styles.inputField} type="password" name="password"
placeholder="Password" required />
<button className={styles.submitButton} type="submit">Sign In</button>
</form>
<div style={{ textAlign: 'center', margin: 'var(--space-md) 0', color: 'var(--text-secondary)' }}>
or
</div>
<OAuthButtons next={next} />
{error && (
<p style={{ marginTop: 'var(--space-md)', textAlign: 'center', fontSize: '0.9rem',
color: 'var(--color-accent)' }}>
{error}
</p>
)}
<p style={{ marginTop: 'var(--space-md)', textAlign: 'center', fontSize: '0.9rem' }}>
No account? <a href={`/signup?next=${encodeURIComponent(next)}`}>Create one</a>
</p>
</div>
</div>
)
}
```
- [ ] **Step 4: Verify.**
Run: `pnpm build`
Expected: `/login` builds as a Dynamic route, no type errors.
- [ ] **Step 5: Commit.**
```bash
git add src/app/login
git commit -m "feat: SSR login with email/password and OAuth"
```
---
### Task 8: Signup page
**Files:** Create `src/app/signup/page.tsx`, `src/app/signup/actions.ts`.
- [ ] **Step 1: Create `src/app/signup/actions.ts`.**
```ts
'use server'
import { redirect } from 'next/navigation'
import { createClient } from '../../lib/supabase/server'
export async function signUp(formData: FormData) {
const email = String(formData.get('email') ?? '')
const password = String(formData.get('password') ?? '')
const next = String(formData.get('next') ?? '/accounts')
const supabase = await createClient()
const { error } = await supabase.auth.signUp({
email,
password,
options: { emailRedirectTo: `${process.env.NEXT_PUBLIC_SITE_URL ?? ''}/api/auth/callback?next=${encodeURIComponent(next)}` },
})
if (error) {
redirect(`/signup?error=${encodeURIComponent(error.message)}&next=${encodeURIComponent(next)}`)
}
redirect(`/login?message=${encodeURIComponent('Check your email to confirm your account.')}&next=${encodeURIComponent(next)}`)
}
```
Note: add `NEXT_PUBLIC_SITE_URL` to `.env.local` (`https://wwv.local`) and to Coolify
(`https://worldwideview.dev`).
- [ ] **Step 2: Create `src/app/signup/page.tsx`.**
```tsx
import { signUp } from './actions'
import styles from '../hub/hub.module.css'
export default async function SignupPage({
searchParams,
}: {
searchParams: Promise<{ error?: string; next?: string }>
}) {
const { error, next = '/accounts' } = await searchParams
return (
<div className={styles.hubContainer}>
<div className={styles.glassCard} style={{ maxWidth: '400px', marginTop: '10vh' }}>
<h1 className={styles.title}>Create Account</h1>
<form action={signUp}>
<input type="hidden" name="next" value={next} />
<input className={styles.inputField} type="email" name="email"
placeholder="Email address" required />
<input className={styles.inputField} type="password" name="password"
placeholder="Password (8+ characters)" minLength={8} required />
<button className={styles.submitButton} type="submit">Sign Up</button>
</form>
{error && (
<p style={{ marginTop: 'var(--space-md)', textAlign: 'center', fontSize: '0.9rem',
color: 'var(--color-accent)' }}>
{error}
</p>
)}
<p style={{ marginTop: 'var(--space-md)', textAlign: 'center', fontSize: '0.9rem' }}>
Already have an account? <a href={`/login?next=${encodeURIComponent(next)}`}>Sign in</a>
</p>
</div>
</div>
)
}
```
- [ ] **Step 3: Verify.** Run: `pnpm build` — `/signup` builds as Dynamic.
- [ ] **Step 4: Commit.**
```bash
git add src/app/signup
git commit -m "feat: SSR signup page"
```
---
### Task 9: OAuth callback route
**Files:** Create `src/app/api/auth/callback/route.ts`.
- [ ] **Step 1: Create the route.**
```ts
import { NextResponse } from 'next/server'
import { createClient } from '../../../../lib/supabase/server'
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get('code')
const next = searchParams.get('next') ?? '/accounts'
if (code) {
const supabase = await createClient()
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (!error) {
return NextResponse.redirect(`${origin}${next}`)
}
}
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent('Authentication failed')}`)
}
```
- [ ] **Step 2: Verify.** Run: `pnpm build` — route compiles.
- [ ] **Step 3: Commit.**
```bash
git add src/app/api/auth/callback/route.ts
git commit -m "feat: OAuth callback route for code-to-session exchange"
```
---
### Task 10: Accounts page + logout
**Files:** Create `src/app/accounts/page.tsx`, `src/app/accounts/actions.ts`.
- [ ] **Step 1: Create `src/app/accounts/actions.ts`.**
```ts
'use server'
import { redirect } from 'next/navigation'
import { createClient } from '../../lib/supabase/server'
export async function signOut() {
const supabase = await createClient()
await supabase.auth.signOut()
redirect('/login')
}
```
- [ ] **Step 2: Create `src/app/accounts/page.tsx`** (guards unauthenticated users):
```tsx
import { redirect } from 'next/navigation'
import { createClient } from '../../lib/supabase/server'
import { signOut } from './actions'
import styles from '../hub/hub.module.css'
export default async function AccountsPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login?next=/accounts')
}
return (
<div className={styles.hubContainer}>
<div className={styles.glassCard} style={{ maxWidth: '480px', marginTop: '10vh' }}>
<h1 className={styles.title}>Your Account</h1>
<p style={{ textAlign: 'center', color: 'var(--text-secondary)' }}>{user.email}</p>
<form action={signOut}>
<button className={styles.submitButton} type="submit">Sign Out</button>
</form>
</div>
</div>
)
}
```
- [ ] **Step 3: Verify.** Run: `pnpm build` — `/accounts` builds as Dynamic.
- [ ] **Step 4: Commit.**
```bash
git add src/app/accounts
git commit -m "feat: account page with parent-domain logout"
```
---
### Task 11: Dockerfile → Node standalone runtime
**Files:** Modify `Dockerfile`; verify `.dockerignore`; modify `docker-compose.yml`.
- [ ] **Step 1: Replace `Dockerfile` entirely.**
```dockerfile
# Stage 1: Build
FROM node:22-alpine AS builder
WORKDIR /app
RUN corepack enable pnpm
COPY package.json pnpm-lock.yaml* ./
RUN pnpm i --frozen-lockfile
COPY . .
# NEXT_PUBLIC_* vars are inlined at build time — must be present as build args.
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ARG NEXT_PUBLIC_WWV_COOKIE_DOMAIN
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL
ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY
ENV NEXT_PUBLIC_WWV_COOKIE_DOMAIN=$NEXT_PUBLIC_WWV_COOKIE_DOMAIN
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
RUN pnpm run build
# Stage 2: Runtime
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs \
&& adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000 HOSTNAME=0.0.0.0
CMD ["node", "server.js"]
```
- [ ] **Step 2: Confirm `.dockerignore` excludes `node_modules`, `.next`, `out`.**
If missing, create `.dockerignore` with: `node_modules`, `.next`, `out`, `.git`.
- [ ] **Step 3: Update `docker-compose.yml`** so the web service maps a host port to
container `3000` (was Nginx `80`), e.g. `ports: - "3001:3000"`, and passes the four
`NEXT_PUBLIC_*` build args.
- [ ] **Step 4: Build the image locally.**
Run: `docker build -t wwv-web-test .`
Expected: build completes; the final image runs `node server.js`.
- [ ] **Step 5: Commit.**
```bash
git add Dockerfile .dockerignore docker-compose.yml
git commit -m "feat: run worldwideview-web as a Node standalone container"
```
Note: `nginx.conf` is now unused — delete it in Phase 5 cleanup once production is verified.
---
### Task 12: Bump version
**Files:** Modify `package.json`.
- [ ] **Step 1:** Bump `version` `0.5.0` → `0.6.0` (a feature release — new auth surface).
- [ ] **Step 2: Commit.**
```bash
git add package.json
git commit -m "chore: bump version to 0.6.0"
```
---
## Phase 1 Verification
**Local (on `wwv.local` HTTPS — requires Phase 0.4–0.6 done):**
1. Run the dev server bound to `wwv.local` over HTTPS (via the mkcert cert or a local TLS
proxy). Open `https://wwv.local/signup`.
2. Create an account → confirm the email → land back authenticated.
3. Sign out, then `https://wwv.local/login` with email+password → reach `/accounts`.
4. In DevTools → Application → Cookies: the Supabase `sb-*` cookies have
`Domain = .wwv.local`.
5. Test Google and GitHub buttons → provider → `/api/auth/callback` → `/accounts`.
6. `https://wwv.local/accounts` while logged out → redirect to `/login?next=/accounts`.
7. Sign out → cookies cleared on `.wwv.local`.
8. `curl -k https://wwv.local/api/health` → `{"status":"ok"}`.
9. Marketing pages (`/`, `/about`, `/docs`) still load and are statically generated.
**Production deploy (the one downtime-sensitive cutover):**
1. Push the branch, open a PR, run `/pr-review`.
2. In Coolify: update the `worldwideview-web` app — new Dockerfile build, set the four
`NEXT_PUBLIC_*` build args + runtime env vars, set the health check to `/api/health`.
3. **Safest:** deploy first to a temporary domain (`web-next.worldwideview.dev`), smoke-test
the full flow, then repoint `worldwideview.dev` (blue-green). Otherwise rely on Coolify's
health-check-gated deploy so traffic only switches after `/api/health` passes.
4. After cutover: smoke-test `worldwideview.dev` landing + `/login` + `/signup`.
---
## Assumptions / Open Questions
1. **No Supabase project exists yet** — Phase 0 creates one.
2. **Marketplace keeps SQLite (Option A)** — recommended: the Marketplace consumes the
Supabase *session* for identity but keeps plugin/API-key data in SQLite. If you want a
full SQLite → Supabase-Postgres migration instead, Phase 2 is much larger. **This is the
one decision that changes scope — please confirm (Phase 0.8).**
3. **`/cloud` + billing deferred** — `/accounts` is minimal (profile + logout), no Stripe.
4. **API-key management UI lives in the Marketplace** (ADR-001C wording), not in `/accounts`.
5. **`SigningKey` rotation table** treated as a fast-follow, not a launch blocker.
6. **The ADR-001 worktree branch needs consolidation** before merge (messy branch name,
uncommitted changes) — handled in Phase 3.
7. **`hub.module.css` is reused** for auth page styling to avoid new CSS scope. If you want
dedicated auth styling, that is an easy add but not assumed here.
8. **No Playwright in `worldwideview-web`** — Phase 1 verification is browser-manual. Adding
a Playwright E2E suite is a reasonable but separate follow-up.
---
## Phase 1 — Implemented & Verified (2026-05-22)
All 12 implementation tasks done. `pnpm test` 16/16 green; `pnpm build` green (marketing
pages Static, the 5 auth routes Dynamic, middleware active). `.env.local` verified against
the live Supabase project `kvlnzjtcstnaqkpqrquf` — URL + publishable key match. The new
API-key system is used throughout (`NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`); `getClaims()`
for session checks.
### Discovered at commit time: pre-existing uncommitted work (NOT Phase 1)
The `worldwideview-web` working tree already held a separate, coherent change —
**"consolidate docs off the `docs.` subdomain back onto `/docs`"**:
- `src/proxy.ts` — **deleted** (was the `docs.` subdomain rewrite middleware; used Next 16's
`proxy.ts` convention with `export function proxy`)
- `src/app/docs/layout.tsx` — dropped the `NEXT_PUBLIC_IS_DOCS_SUBDOMAIN` branching
- `src/components/Footer.tsx` — docs links `docs.worldwideview.dev` → `/docs`
- `vercel.json` — removed the docs-subdomain redirects (now `{}`)
- `.vscode/settings.json` — new untracked file
This is unrelated to the auth host. **Decision (user, 2026-05-22): commit the
docs-consolidation work first as its own commit, then Phase 1.**
### Finalized commit sequence (branch `feat/auth-host` off `main`)
1. **Commit 1 — docs consolidation.** Stage only: `src/proxy.ts` (deletion),
`src/app/docs/layout.tsx`, `src/components/Footer.tsx`, `vercel.json`. Message:
`refactor(docs): serve docs from /docs instead of the docs. subdomain`.
2. **Rename** Phase 1's root `middleware.ts` → `src/proxy.ts` (`export function proxy`).
Clean now — Commit 1 removed the old `src/proxy.ts`, so Commit 2 just adds the new auth
one. Matches the repo's Next-16 `proxy.ts` convention.
3. **Commit 2 — Phase 1.** Version bump `0.5.0 → 0.6.0`; stage all Phase 1 files. Message:
`feat: add SSR auth host with shared Supabase identity (ADR-003)`.
4. Push `feat/auth-host`, open the PR (remote: `github.com/silvertakana/worldwideview-web`).
`.vscode/settings.json` (stray untracked file) is left out of both commits.
@@ -0,0 +1,306 @@
# Plan: Marketplace Authentication (Supabase Auth — Shared Identity)
## Context
The Marketplace (`marketplace.worldwideview.dev`, repo: `c:/dev/worldwideview-marketplace`) and the Cloud App (`app.worldwideview.dev`) share one identity ecosystem. A user who creates an account on the Marketplace can use that same account to access the Cloud App, and vice versa — no second signup required. This is called **Federated Identity / Single Sign-On (SSO)** and is the same model used by GitHub (one account → GitHub + GitHub Marketplace + GitHub Actions), Atlassian (one account → Jira + Confluence + Marketplace), and Stripe (one account → Dashboard + Stripe Apps).
The Marketplace has no database yet, so Supabase is the right choice: one Supabase project serves as the **shared identity store** for all WorldWideView products. Both the Marketplace and the Cloud App point at the same Supabase project URL — the same `auth.users` table — so a user is one entity across the entire ecosystem.
The Marketplace also acts as the **OAuth 2.0 Authorization Server** in the ADR-001 PKCE flow — when a Local App user clicks "Connect to Marketplace," they are redirected here to authorize, and the Marketplace issues a short-lived code that the Local App exchanges for an API Key.
> **⚠️ Rule conflict to resolve:** `.agents/rules/cloud-auth-architecture.md` currently says `app.worldwideview.dev` owns all login UI and the Marketplace redirects there. This plan reverses that — **Marketplace is the identity source**, and the Cloud App will defer to it. That rule file must be updated after this plan is approved.
---
## Decision: Shared Supabase Auth + Supabase Postgres
**Why:**
- **One user table for the whole ecosystem** — `auth.users` is shared. A user created on Marketplace is immediately valid on Cloud App. No sync job, no duplication.
- No database to spin up — Supabase project gives you Postgres + Auth in one dashboard click
- Google OAuth, GitHub OAuth, magic link, email+password all configured in the Supabase dashboard (no code for provider setup)
- Prisma connects to Supabase Postgres via standard `DATABASE_URL` — app data (plugins, installs, etc.) lives alongside auth tables
- Well-trodden Stripe + Supabase integration path via the [Vercel subscription payments starter](https://github.com/vercel/nextjs-subscription-payments)
- Free tier covers early-stage Marketplace comfortably
- `@supabase/ssr` package has first-class Next.js App Router support (server components, middleware, server actions)
**Accepted tradeoff:** Supabase vendor dependency — if pricing changes at scale, migration to self-hosted Postgres + Better Auth is straightforward because Prisma abstracts the DB layer.
**Known gotcha — cookie domain across subdomains:** Supabase session cookies are scoped per-app by default. A session from `marketplace.worldwideview.dev` does not automatically carry over to `app.worldwideview.dev`. Fix: after login on either app, set a shared JWT cookie on the parent domain `worldwideview.dev` (via custom middleware) that both subdomains can read and validate against the shared Supabase public key. This is the only custom plumbing required — both apps still use the same Supabase JWT secret for validation.
**Upgrade path:** If the Marketplace later needs to support third-party app integrations (external developers building plugins), flip to the **Marketplace-as-OAuth-Provider** model — the user table stays the same, you add the PKCE authorization layer on top. No user migration needed.
---
## What to Build
### Step 1 — Create Supabase Project
1. Go to supabase.com → New project → name it `wwv-marketplace`
2. In **Authentication → Providers**, enable:
- **Email** (email+password + magic link)
- **Google** (add Client ID + Secret from Google Cloud Console)
- **GitHub** (add Client ID + Secret from GitHub OAuth App)
3. Save the project URL and anon key (go into `.env.local`)
### Step 2 — Install Packages
```bash
pnpm add @supabase/supabase-js @supabase/ssr
pnpm add -D prisma @prisma/client
```
### Step 3 — Configure Environment Variables
```env
# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://xxxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ... # server-only, never expose to client
# Prisma (Supabase Postgres — use the "Transaction" pooler URL)
DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?pgbouncer=true
DIRECT_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres
# Ed25519 key for plugin ticket signing (ADR-001B)
MARKETPLACE_ED25519_PRIVATE_KEY= # base64 PEM
MARKETPLACE_ED25519_KID= # key ID (for JWKS rotation)
# OAuth server (PKCE for Local App)
OAUTH_CLIENT_REDIRECT_URI_ALLOWLIST=http://localhost:3000/api/marketplace/callback,https://app.worldwideview.dev/api/marketplace/callback
```
### Step 4 — Supabase Client Helpers
**`src/lib/supabase/server.ts`** — server-side client (server components, server actions, API routes):
```ts
import { createServerClient } from "@supabase/ssr"
import { cookies } from "next/headers"
export function createClient() {
const cookieStore = cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { getAll: () => cookieStore.getAll(), setAll: (c) => c.forEach(({ name, value, options }) => cookieStore.set(name, value, options)) } }
)
}
```
**`src/lib/supabase/client.ts`** — browser client:
```ts
import { createBrowserClient } from "@supabase/ssr"
export const supabase = createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
```
### Step 5 — Auth Middleware (session refresh)
**`src/middleware.ts`** — refreshes Supabase session on every request:
```ts
import { createServerClient } from "@supabase/ssr"
import { NextResponse, type NextRequest } from "next/server"
export async function middleware(request: NextRequest) {
let response = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { getAll: () => request.cookies.getAll(), setAll: (c) => c.forEach(({ name, value, options }) => response.cookies.set(name, value, options)) } }
)
await supabase.auth.getUser() // refreshes session token
return response
}
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] }
```
### Step 6 — Auth Callback Route
**`src/app/auth/callback/route.ts`** — Supabase redirects here after social login to exchange the code for a session:
```ts
import { createClient } from "@/lib/supabase/server"
import { NextResponse } from "next/server"
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get("code")
const next = searchParams.get("next") ?? "/"
if (code) {
const supabase = createClient()
await supabase.auth.exchangeCodeForSession(code)
}
return NextResponse.redirect(`${origin}${next}`)
}
```
### Step 7 — Login UI
**`src/app/login/page.tsx`** — single page with four auth methods:
- Email + password (`supabase.auth.signInWithPassword()`)
- Google (`supabase.auth.signInWithOAuth({ provider: "google" })`)
- GitHub (`supabase.auth.signInWithOAuth({ provider: "github" })`)
- Magic link (`supabase.auth.signInWithOtp({ email })`)
All OAuth redirects must include `redirectTo: "${origin}/auth/callback"`.
### Step 8 — Prisma Schema for App Data
Supabase manages the `auth.users` table internally. For app-specific data, add to `prisma/schema.prisma`:
```prisma
// References Supabase auth.users UUID — do NOT store password/session data here
model MarketplaceUser {
id String @id // matches auth.users.id (UUID)
email String @unique
plan String @default("free") // "free" | "pro" | "team"
stripeCustomerId String?
createdAt DateTime @default(now())
plugins InstalledPlugin[]
}
model InstalledPlugin {
id String @id @default(cuid())
userId String
pluginId String
installedAt DateTime @default(now())
user MarketplaceUser @relation(fields: [userId], references: [id])
@@unique([userId, pluginId])
}
```
Run `prisma migrate dev` pointing at the Supabase Postgres URL.
### Step 9 — OAuth 2.0 PKCE Authorization Server (for Local App)
This is the custom layer that lets the Local App "connect" to the Marketplace. Supabase handles user identity; these routes handle the code exchange.
**`src/app/api/oauth/authorize/route.ts`**
- Validates: `client_id`, `redirect_uri` (must match allowlist), `code_challenge`, `code_challenge_method=S256`, `state`
- Calls `supabase.auth.getUser()` — if not logged in, redirects to `/login?redirect_to=...`
- Shows a consent screen ("Allow WorldWideView Local App to access your account?")
- On approval: stores `{ code, code_challenge, user_id, expires: now+60s }` in Supabase DB, redirects to `redirect_uri?code=...&state=...`
**`src/app/api/oauth/token/route.ts`**
- Validates `code` + `code_verifier` (SHA-256(`code_verifier`) must equal stored `code_challenge`)
- Issues a long-lived API Key (random 32-byte token), stores hashed in DB
- Returns `{ access_token, token_type: "Bearer" }` — this is what the Local App encrypts and stores
**`src/app/api/auth/exchange/route.ts`** *(ADR-001B)*
- Accepts API Key + `audience` (plugin ID)
- Verifies API Key against DB, checks subscription tier
- Issues a 5-minute EdDSA JWT signed with the Marketplace Ed25519 key, scoped to the requested plugin
- Data Engines verify this JWT via the public JWKS endpoint
**`src/app/.well-known/jwks.json/route.ts`**
- Returns the Marketplace's Ed25519 public key in JWKS format
- Data Engines call this on startup and cache it (ADR-001A)
---
## Critical Files (Marketplace repo: `c:/dev/worldwideview-marketplace`)
| File | Purpose |
|---|---|
| `src/lib/supabase/server.ts` | Server-side Supabase client |
| `src/lib/supabase/client.ts` | Browser-side Supabase client |
| `src/middleware.ts` | Session refresh on every request |
| `src/app/auth/callback/route.ts` | OAuth callback from Supabase (social login) |
| `src/app/login/page.tsx` | Login UI (all 4 methods) |
| `prisma/schema.prisma` | App data schema (MarketplaceUser, InstalledPlugin) |
| `src/app/api/oauth/authorize/route.ts` | PKCE auth endpoint (Local App connects here) |
| `src/app/api/oauth/token/route.ts` | PKCE token exchange |
| `src/app/api/auth/exchange/route.ts` | API Key → 5-min EdDSA JWT (ADR-001B) |
| `src/app/.well-known/jwks.json/route.ts` | Public JWKS for Data Engine JWT verification |
| `.env.local` | Supabase + Prisma + Ed25519 keys |
---
## Stripe Integration Path (Future)
When ready to add payments:
1. Install `stripe` + `@stripe/stripe-js`
2. On user signup (Supabase `auth.onAuthStateChange`), create a Stripe customer and save `stripeCustomerId` to `MarketplaceUser`
3. Use Stripe Billing for subscriptions — webhook updates `MarketplaceUser.plan`
4. The `exchange` endpoint reads `plan` to enforce tier in the issued JWT (`tier` claim per ADR-001B)
Reference: [Vercel Next.js + Supabase + Stripe starter](https://github.com/vercel/nextjs-subscription-payments)
---
---
## Risk Mitigations (Pre-Mortem — 2026-05-22)
### Tigers Addressed
**[HIGH] RLS not configured on app tables**
- All tables that contain user-scoped data (`MarketplaceUser`, `InstalledPlugin`) MUST have Row Level Security enabled in Supabase before going live.
- Add to `prisma/migrations/` as a raw SQL migration (Prisma doesn't support RLS natively):
```sql
ALTER TABLE "MarketplaceUser" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can only access own row" ON "MarketplaceUser"
USING (id = auth.uid());
ALTER TABLE "InstalledPlugin" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can only access own plugins" ON "InstalledPlugin"
USING ("userId" = auth.uid());
```
- Server-side routes that need full access use `SUPABASE_SERVICE_ROLE_KEY` (bypasses RLS by design — keep it server-only, never expose to client).
**[HIGH] Authorization code not invalidated after use**
- In `/api/oauth/token/route.ts`, wrap the validation and API Key issuance in a transaction:
1. `SELECT` the code row (validate `code_challenge`)
2. `DELETE` the code row
3. Issue the API Key
4. Commit
- If the DELETE fails or the row is already gone, return `400 invalid_grant`. This prevents replay attacks within the 60s window.
### Medium Risks Addressed
**[MEDIUM] Supabase email rate limit breaks magic link**
- Configure a custom SMTP provider in Supabase Dashboard → Project Settings → Auth → SMTP Settings before enabling magic link in production.
- Recommended: Resend (free tier = 3,000 emails/month, 100/day). Add `RESEND_API_KEY` to env and configure in Supabase dashboard — no code change needed.
**[MEDIUM] MarketplaceUser orphan on auth.users delete**
- Add a Postgres trigger via raw SQL migration:
```sql
CREATE OR REPLACE FUNCTION handle_deleted_user()
RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER AS $$
BEGIN
DELETE FROM "MarketplaceUser" WHERE id = OLD.id;
RETURN OLD;
END;
$$;
CREATE TRIGGER on_auth_user_deleted
AFTER DELETE ON auth.users
FOR EACH ROW EXECUTE PROCEDURE handle_deleted_user();
```
**[MEDIUM] Ed25519 key rotation — no zero-downtime strategy**
- Do not store the Ed25519 key only in an env var. Add a `SigningKey` table to Prisma schema:
```prisma
model SigningKey {
kid String @id
publicKey String // PEM, served in JWKS
privateKey String // encrypted at rest
status String // "active" | "retiring" | "revoked"
expiresAt DateTime?
createdAt DateTime @default(now())
}
```
- The JWKS endpoint serves ALL `status != "revoked"` keys. During rotation: add a new key (`active`), flip the old key to `retiring`, wait 10 minutes for Data Engine caches to expire, then flip old key to `revoked`.
### Accepted Risks
- None — all identified risks have been mitigated in plan.
---
## Verification
1. **Social login:** Click "Continue with Google" → Google OAuth flow → redirects to `/auth/callback` → lands on dashboard logged in
2. **Magic link:** Enter email → receive email → click link → logged in
3. **PKCE flow (end-to-end):** From Local App, click "Connect to Marketplace" → redirected to `/api/oauth/authorize` → must log in first if not logged in → consent screen → approve → back to Local App with `code` → Local App calls `/api/oauth/token` → receives API Key → stored encrypted in Local App DB
4. **Plugin ticket:** Local App POSTs API Key + `audience` to `/api/auth/exchange` → receives 5-min JWT → browser sends as WebSocket first message to Data Engine → engine verifies via JWKS → stream opens
5. **Unauthenticated protection:** Hit `/api/oauth/authorize` without a session → must redirect to login, not error
@@ -0,0 +1,578 @@
# Phase 4 Coolify Cutover Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Flip the production WorldWideView data engine from "auth disabled" (`WWV_SKIP_WS_AUTH=true`) to "auth enforced" (`JWKS_URL` set + ticket-auth plugin allowlist enumerated) in a single atomic redeploy window, with smoke tests proving every plugin still works.
**Architecture:** Pure ops change — no source code modifications. Two Coolify services receive env-var updates (`wwv-data-engine` and `wwv` frontend), both are redeployed near-simultaneously, smoke-tested through the live UI. Rollback is a single env-var revert + redeploy.
**Tech Stack:** Coolify CLI (context `wwv` pre-configured), `curl` for registry/JWKS probing, optional SSH to the host for low-level diagnostics. No code, no tests, no commits — only env config + deploy actions.
---
## Context — why this plan exists
Phase 4 of the Northstar Sequence shipped the data engine's WebSocket JWT enforcement code (engine-side: PR #10 merged on `wwv-data-engine`; frontend ticket-issuance and PKCE flow merged earlier in worldwideview/marketplace). The enforcement is currently **dormant** in production because the Coolify env still has `WWV_SKIP_WS_AUTH=true`, which the engine reads at boot to bypass first-message auth.
Local end-to-end testing in the prior session proved the full chain works:
- PKCE → marketplace API key (encrypted in `MarketplaceCredential`)
- `/api/auth/ticket` → 5-min EdDSA JWT signed by marketplace
- WebSocket first frame: `{type:"auth", v:1, token}` → engine validates against marketplace JWKS → `welcome` → subscribe → data flows
The pre-mortem identified four tigers blocking the cutover. The companion plan (`joyful-napping-gizmo.md`) addresses three via CI hardening and the `BaseIncidentPlugin` payload fix. **This plan handles the remaining tiger (T3 — production JWKS reachability never verified) and the elephants (E1 — plugin enumeration never done, E2 — current Coolify state unknown), then performs the actual flip.**
**Prerequisites — the companion plan must be fully landed:**
- PR1 `feat/ci-coverage-phase4` merged on `wwv-data-engine` main (CI guards live)
- PR2 `test/base-incident-plugin-payload` merged on `worldwideview` main (test guards live)
- PR3 `fix/base-incident-plugin-payload` merged on `worldwideview` main (earthquakes data fix live)
- Worldwideview Coolify service has redeployed since PR3 landed (so the new frontend bundle contains the `mapWebsocketPayload` fix)
Without PR3 deployed, enabling Earthquakes in the cutover allowlist will show an empty layer — the test we ran locally would re-occur in production.
---
## File Structure
This plan modifies **zero source files**. All changes are Coolify env-var updates plus the documents created during audit:
| Path | Role | Lifecycle |
|---|---|---|
| `C:\Users\silve\.claude\plans\coolify-baseline-<timestamp>.md` | Captured baseline of current Coolify env state (rollback reference) | created in Task 3 |
| `C:\Users\silve\.claude\plans\coolify-cutover-allowlist-<timestamp>.md` | Computed plugin allowlist (CSV + rationale) | created in Task 4 |
| `worldwideview/docs/architecture/decisions/adr-0001b-status.md` *(optional)* | ADR-001B status update — Proposed → Accepted | Task 13 (post-success only) |
The Coolify services touched:
- **`wwv-data-engine`** — set `JWKS_URL`, remove `WWV_SKIP_WS_AUTH`
- **`wwv`** (the worldwideview frontend) — set `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS`
---
## Task 1: Confirm prerequisites are live in production
**Files:** none. Read-only verification.
- [ ] **Step 1: Verify all three companion-plan PRs are merged**
```powershell
gh pr list --repo silvertakana/wwv-data-engine --state merged --limit 5
gh pr list --repo silvertakana/worldwideview --state merged --limit 5
```
Expected: see merged PRs titled `test(auth): Phase 4 WebSocket auth + port-contract CI guards` (wwv-data-engine), `test(incidents): guard BaseIncidentPlugin WebSocket payload contract` and `fix(incidents): add mapWebsocketPayload default to BaseIncidentPlugin` (worldwideview). If any is missing, STOP — return to the companion plan.
- [ ] **Step 2: Verify the worldwideview Coolify deploy includes PR3**
```powershell
coolify deploy status wwv
```
Expected: `last deploy` timestamp is AFTER PR3 merge. If older, trigger a redeploy first:
```powershell
coolify deploy trigger wwv
```
Wait for completion (`coolify deploy status wwv --watch`). The cutover later will trigger this again, but verifying the fix is deployed BEFORE the cutover ensures we can isolate any failure to env vs. code.
- [ ] **Step 3: Confirm the data engine code already has Phase 4 (PR #10)**
```powershell
curl https://dataenginev2.worldwideview.dev/health
```
Expected: JSON with `version: "1.7.3"` (or newer if CI tests bumped further). If `1.7.1` or earlier, PR #10 is not deployed — STOP.
---
## Task 2: Verify the marketplace JWKS endpoint is reachable from the public internet
**Files:** none.
- [ ] **Step 1: Curl from the local workstation**
```powershell
curl -v https://marketplace.worldwideview.dev/api/auth/jwks
```
Expected: HTTP 200, body is JSON like `{"keys":[{"kty":"OKP","crv":"Ed25519","x":"...","kid":"marketplace-key-v1","alg":"EdDSA"}]}`. If 404/500/timeout → STOP, fix the marketplace before continuing.
- [ ] **Step 2: Validate the JWK shape**
The response must include at least one key with `kty: "OKP"`, `crv: "Ed25519"`, `alg: "EdDSA"`, and a non-empty `kid`. If any of those are missing, the engine's `verifyEngineToken` will reject every token with "no applicable key found" — same symptom as our local test isolation bug. STOP if shape is wrong.
---
## Task 3: Capture Coolify baseline (rollback reference)
**Files:**
- Create: `C:\Users\silve\.claude\plans\coolify-baseline-<YYYYMMDD-HHMMSS>.md`
- [ ] **Step 1: Dump current data engine env vars**
```powershell
coolify env list wwv-data-engine
```
- [ ] **Step 2: Dump current frontend env vars**
```powershell
coolify env list wwv
```
- [ ] **Step 3: Save baseline to file**
Create `C:\Users\silve\.claude\plans\coolify-baseline-<YYYYMMDD-HHMMSS>.md` with the exact current values of these keys (copy from the `coolify env list` output):
```markdown
# Coolify baseline — captured <ISO timestamp>
## wwv-data-engine
- JWKS_URL: <current value or "(unset)">
- WWV_SKIP_WS_AUTH: <current value or "(unset)">
- ENGINE_ID: <current value or "(unset)">
- REDIS_URL: <redacted — confirm present>
- SENTRY_DSN: <redacted — confirm present>
## wwv (frontend)
- NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS: <current value or "(unset)">
- NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL: <current value>
- NEXT_PUBLIC_WWV_MARKETPLACE_URL: <current value>
- NEXT_PUBLIC_WWV_EDITION: <current value>
## Rollback procedure
If anything breaks during/after cutover:
1. coolify env set wwv-data-engine WWV_SKIP_WS_AUTH=true
2. coolify env unset wwv-data-engine JWKS_URL (or set to "(unset)" value above)
3. coolify env unset wwv NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS (or restore "(unset)" value above)
4. coolify deploy trigger wwv-data-engine
5. coolify deploy trigger wwv
6. curl https://dataenginev2.worldwideview.dev/health — confirm version unchanged, engine running
```
This file is the **single source of truth** for rollback. Do not skip it.
---
## Task 4: Compute the plugin allowlist from the live data engine manifest
**Files:**
- Create: `C:\Users\silve\.claude\plans\coolify-cutover-allowlist-<YYYYMMDD-HHMMSS>.md`
- [ ] **Step 1: Fetch the live manifest from production**
```powershell
curl https://dataenginev2.worldwideview.dev/manifest
```
Expected: JSON like `{"engine":"wwv-data-engine","version":"1.7.3","plugins":["earthquakes","wildfires","sanctions","conflict-events","gps-jamming","cyber-attacks","civil-unrest","iss","satellites","aviation-history","maritime-history","iranwar-events"],"websocket":"/stream","timestamp":...}`. The exact list will vary — capture whatever is returned.
- [ ] **Step 2: Build the CSV**
Take the `plugins` array from the response and join with commas (no spaces). Example:
```
earthquakes,wildfires,sanctions,conflict-events,gps-jamming,cyber-attacks,civil-unrest,iss,satellites,aviation-history,maritime-history,iranwar-events
```
- [ ] **Step 3: Cross-check against the marketplace verified registry (sanity)**
```powershell
curl https://marketplace.worldwideview.dev/api/registry
```
Compare the engine manifest's plugin IDs against the registry's verified IDs. Note any discrepancies:
- Manifest plugins NOT in registry → in-house seeders not advertised on marketplace (fine, still need auth)
- Registry plugins NOT in manifest → marketplace-only or static plugins (fine, don't need auth)
The **engine manifest is authoritative** for the allowlist — anything that streams from this engine needs to be there.
- [ ] **Step 4: Save the computed allowlist**
Create `C:\Users\silve\.claude\plans\coolify-cutover-allowlist-<YYYYMMDD-HHMMSS>.md`:
```markdown
# Phase 4 Coolify cutover — plugin allowlist
Captured from: https://dataenginev2.worldwideview.dev/manifest at <ISO timestamp>
## Allowlist (CSV form for NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS)
<the CSV from Step 2>
## Per-plugin rationale
| Plugin | In manifest | In registry | Action |
|---|---|---|---|
| earthquakes | yes | yes | include |
| wildfires | yes | yes | include |
| <one row per plugin> | | | |
## Notes
- Engine manifest is authoritative.
- Registry sanity-checked at Step 3 — discrepancies noted above.
```
---
## Task 5: Smoke-test JWKS reachability FROM the production data engine container
**Files:** none.
The engine's startup check (`startup-checks.ts`) verifies JWKS is reachable at boot — but a one-shot check at boot doesn't catch transient network policy issues that appear later. Pre-flight this from inside the actual container to catch firewall/DNS surprises.
- [ ] **Step 1: Exec into the container via Coolify**
```powershell
coolify exec wwv-data-engine -- curl -v https://marketplace.worldwideview.dev/api/auth/jwks
```
If `coolify exec` is not available, fall back to SSH:
```bash
ssh root@<coolify-host>
docker exec -it $(docker ps --filter "name=wwv-data-engine" -q) curl -v https://marketplace.worldwideview.dev/api/auth/jwks
```
The Coolify host IP is in your server-dev memory; if unsure, run `coolify host info`.
- [ ] **Step 2: Verify the response**
Expected: HTTP 200, same JWKS body as Task 2 Step 1. If the local workstation can reach JWKS but the container cannot, you have a Coolify network policy issue (egress firewall, DNS) — STOP and fix the network before continuing.
---
## Task 6: Set the new env vars on Coolify (no redeploy yet)
**Files:** none. Coolify state-only.
Setting env vars in Coolify does NOT trigger a deploy by default — the new values take effect at the next start. We set BOTH services' new env vars first, then trigger redeploys near-simultaneously so the atomic-flip window is small.
- [ ] **Step 1: Set `JWKS_URL` on the data engine**
```powershell
coolify env set wwv-data-engine JWKS_URL=https://marketplace.worldwideview.dev/api/auth/jwks
```
Expected: confirmation message. Verify with `coolify env get wwv-data-engine JWKS_URL`.
- [ ] **Step 2: Remove (or set false) `WWV_SKIP_WS_AUTH` on the data engine**
```powershell
coolify env unset wwv-data-engine WWV_SKIP_WS_AUTH
```
(If `unset` is not supported, use `coolify env set wwv-data-engine WWV_SKIP_WS_AUTH=false` — the engine reads `=== 'true'` so anything else is treated as enforcement-on.)
Verify with `coolify env get wwv-data-engine WWV_SKIP_WS_AUTH` — should return empty/false.
- [ ] **Step 3: Set `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` on the frontend**
Use the CSV from Task 4 Step 2. Example:
```powershell
coolify env set wwv NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS=earthquakes,wildfires,sanctions,conflict-events,gps-jamming,cyber-attacks,civil-unrest,iss,satellites,aviation-history,maritime-history,iranwar-events
```
Verify with `coolify env get wwv NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` — should return the CSV verbatim.
- [ ] **Step 4: Cross-check the saved values against the baseline file**
Open `C:\Users\silve\.claude\plans\coolify-baseline-<...>.md` and confirm the three values you just changed are different from baseline. This is the "I really did change them" sanity check.
---
## Task 7: Trigger redeploys for both services
**Files:** none.
Both redeploys should be triggered as close together as possible (within ~1 minute) so the user-facing flip is single-window. Coolify deploys are non-blocking; we trigger both then watch both.
- [ ] **Step 1: Trigger data engine deploy**
```powershell
coolify deploy trigger wwv-data-engine
```
Capture the deploy ID printed.
- [ ] **Step 2: Trigger frontend deploy**
```powershell
coolify deploy trigger wwv
```
Capture the deploy ID printed.
- [ ] **Step 3: Watch both deploys complete**
In one terminal:
```powershell
coolify deploy status wwv-data-engine --watch
```
In another (parallel):
```powershell
coolify deploy status wwv --watch
```
Expected: both reach `running` state within ~3-5 minutes. The data engine log will show `[Server] JWKS reachable at https://marketplace.worldwideview.dev/api/auth/jwks` — that is the moment enforcement goes live.
- [ ] **Step 4: STOP and rollback if either deploy fails**
If `wwv-data-engine` startup fails with `FATAL: JWKS unreachable at startup`, the network/JWKS smoke (Task 5) gave a false positive. Rollback immediately (Task 12) and investigate before retrying.
If `wwv` build fails, the env var format may be wrong (Coolify can sometimes mangle commas) — check the build log and re-set the env var with proper escaping.
---
## Task 8: Post-deploy smoke — engine endpoints
**Files:** none.
- [ ] **Step 1: Health check**
```powershell
curl https://dataenginev2.worldwideview.dev/health
```
Expected: `{"status":"ok","engine":"wwv-data-engine","timestamp":<recent>,"seeders":{...}}`. The `seeders` object should list every plugin in the manifest with a recent `lastSuccess` timestamp.
- [ ] **Step 2: Manifest check**
```powershell
curl https://dataenginev2.worldwideview.dev/manifest
```
Expected: same plugin list as Task 4 Step 1 (no regression). If a plugin dropped out, a seeder failed to load — investigate before continuing.
---
## Task 9: Post-deploy smoke — WebSocket auth handshake (curl-based)
**Files:** none.
Confirms enforcement is actually ON before testing the UI.
- [ ] **Step 1: Attempt unauthenticated WebSocket connection**
```powershell
# Use websocat or wscat — install via: pnpm dlx wscat
pnpm dlx wscat -c wss://dataenginev2.worldwideview.dev/stream
```
Then send (paste into the open prompt):
```
{"action":"subscribe","pluginId":"earthquakes"}
```
Expected: connection closes immediately with code `4003`. If the connection stays open and you receive data, **enforcement is NOT active** — the env var didn't apply, restart the data engine via `coolify deploy trigger wwv-data-engine` and retry.
---
## Task 10: Post-deploy smoke — UI walkthrough (the real test)
**Files:** none.
- [ ] **Step 1: Open the production app in a browser**
Navigate to `https://worldwideview.dev` (or whatever the production frontend URL is). Sign in if not already.
- [ ] **Step 2: Open browser DevTools — Network tab, filter "WS"**
You'll see WebSocket connections appear as you enable plugins.
- [ ] **Step 3: Enable EACH plugin in the allowlist, one at a time**
For each plugin in the CSV from Task 4:
1. Enable it via the UI control (sidebar, search, etc.)
2. Observe the new `wss://dataenginev2.worldwideview.dev/stream` WebSocket in the Network tab
3. Click it → Messages tab → confirm:
- First **outbound** message: `{"type":"auth","v":1,"token":"<long EdDSA JWT>"}`
- First **inbound** message: `{"type":"welcome","engine":"wwv-data-engine","plugins":[...]}`
- Subsequent inbound: `{"type":"data","pluginId":"<this plugin>","payload":...}`
4. Confirm visible markers/data appear on the globe
5. **If any plugin closes with `4003`** in the Network tab → that plugin is broken under enforcement. Capture the plugin ID, then either:
- Continue smoke-testing remaining plugins (note all failures)
- OR rollback immediately if it's a high-traffic plugin (your call)
- [ ] **Step 4: Specific check — Earthquakes**
This is the plugin we expected to break before PR3 landed. Confirm:
- WebSocket connects with auth handshake
- `data` messages arrive
- Earthquake markers appear on the globe (NOT an empty layer)
If markers don't appear but the auth handshake succeeded and `data` messages are arriving, PR3 didn't deploy — re-trigger the worldwideview deploy.
- [ ] **Step 5: Negative smoke — sign out, retry**
Sign out of the app. Try to enable a cloud plugin. Expected: WebSocket either doesn't connect or closes with `4003`/`4001` quickly. The frontend's `/api/auth/ticket` route should return 401 because no NextAuth session exists. If unauthenticated users CAN still get data, the ticket route's session check is broken — file an issue.
---
## Task 11: Decision point — happy path OR rollback
**Files:** none.
- [ ] **Step 1: Evaluate smoke results**
| Outcome | Action |
|---|---|
| All plugins green, all WebSockets auth-handshake-then-data | Skip to Task 13 (mark Phase 4 done) |
| 1-2 minor plugins break (low-traffic, niche) | Document failures, keep enforcement on, file fix issues — Task 13 with caveats |
| Earthquakes or any high-traffic plugin breaks | EXECUTE TASK 12 (rollback), then debug |
| Engine won't stay up (crashloop) | EXECUTE TASK 12 immediately, investigate logs |
The threshold for rollback is qualitative — your call. The intent is enforcement-on by default; rollback should be the exception.
---
## Task 12: Rollback procedure (conditional — only if Task 11 says so)
**Files:** none. Coolify state restoration.
- [ ] **Step 1: Re-enable bypass on the data engine**
```powershell
coolify env set wwv-data-engine WWV_SKIP_WS_AUTH=true
```
- [ ] **Step 2: Restore (or unset) `JWKS_URL` to baseline value**
Open `C:\Users\silve\.claude\plans\coolify-baseline-<...>.md` and use the recorded value:
```powershell
# If baseline value was "(unset)":
coolify env unset wwv-data-engine JWKS_URL
# If baseline had a value:
coolify env set wwv-data-engine JWKS_URL=<baseline value>
```
- [ ] **Step 3: Restore (or unset) `NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS` to baseline value**
```powershell
# If baseline was "(unset)":
coolify env unset wwv NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS
# If baseline had a value:
coolify env set wwv NEXT_PUBLIC_WWV_TICKET_AUTH_PLUGINS=<baseline value>
```
- [ ] **Step 4: Trigger both redeploys**
```powershell
coolify deploy trigger wwv-data-engine
coolify deploy trigger wwv
coolify deploy status wwv-data-engine --watch
coolify deploy status wwv --watch
```
- [ ] **Step 5: Confirm rollback via the same smoke as Task 9**
```powershell
pnpm dlx wscat -c wss://dataenginev2.worldwideview.dev/stream
# Send: {"action":"subscribe","pluginId":"earthquakes"}
```
Expected: connection stays open, data arrives WITHOUT sending an auth message. That's the pre-cutover bypass behavior restored.
- [ ] **Step 6: Document the rollback**
Append to the baseline file:
```markdown
## Rollback executed <ISO timestamp>
- Trigger: <what broke — e.g. "Earthquakes 4003 close in production browser test">
- Plugins broken: <list>
- Next steps: <e.g. "Investigate WsClient auth path for plugin X — file issue">
```
STOP. Do not retry the cutover until the root cause is fixed and re-tested locally.
---
## Task 13: Mark Phase 4 complete (happy path only)
**Files:**
- Modify: `worldwideview/docs/architecture/decisions/adr-0001-decentralized-plugin-auth.md` (or wherever ADR-001B lives)
- Modify: any Northstar Sequence tracker doc (likely in `worldwideview/docs/` or `.agents/context/`)
- [ ] **Step 1: Find the ADR**
```powershell
cd C:\dev\wwv\worldwideview
cymbal search --text "ADR-001B"
# OR
Get-ChildItem -Recurse docs/architecture -Filter "adr-0001*.md"
```
- [ ] **Step 2: Update the ADR status from "Proposed" to "Accepted"**
Edit the relevant ADR — typically there's a status block near the top:
```diff
-Status: Proposed
+Status: Accepted (cutover completed <YYYY-MM-DD>)
```
- [ ] **Step 3: Find and update the Northstar Sequence tracker**
```powershell
cymbal search --text "Northstar Sequence"
# OR
Grep --pattern "Phase 4" docs/
```
Update Phase 4's status from in-progress to complete. Add a one-line note referencing the cutover date.
- [ ] **Step 4: Commit on a new branch**
```powershell
git checkout main
git pull --ff-only origin main
git checkout -b docs/phase4-cutover-complete
git add docs/
git commit -m "docs: mark ADR-001B accepted and Northstar Phase 4 complete
Production data engine cutover completed <YYYY-MM-DD>. WebSocket JWT
enforcement active for: <list from allowlist>. Local + production E2E
verified. Baseline + allowlist files retained in personal notes."
git push -u origin docs/phase4-cutover-complete
gh pr create --title "docs: mark Phase 4 Coolify cutover complete" --body "Status update only — production cutover landed <YYYY-MM-DD>. See plan at .claude/plans/2026-05-24-phase4-coolify-cutover.md."
```
---
## Verification — end-to-end
After Task 13 (or Task 12 if rolled back):
1. **If happy path:** the WebSocket `/stream` endpoint rejects unauthenticated connections with `4003` (proven via wscat in Task 9), accepts authenticated UI sessions (proven in Task 10), shows earthquake markers and every other allowlisted plugin's data on the globe.
2. **If rolled back:** the baseline file documents what broke. A follow-up plan is needed to fix the broken plugin(s) before re-attempting cutover. The system is back to "auth disabled" — same security posture as before this plan started, no production regression.
The Coolify dashboard should show both services healthy and the deploy timestamps should match the cutover window.
---
## Out of scope (separate plans / future work)
- **Port-5000 codification** (engine startup warning + ADR) — purely local DX, not cutover-blocking.
- **`better-sqlite3` → `node:sqlite` refactor of `seeder-sdk`** — Docker prebuilt binaries make this non-urgent for production; local-dev DX only.
- **Silent auth logging fixes** — engine should log `[WS] Closing unauthenticated connection from <ip>: <reason>` and use a more specific close reason than `"Invalid auth message"`. Improves operator UX; track as a small follow-up issue.
- **Plugin `streamUrl` hardcoding sweep** — plugins still hardcode `wss://dataenginev2.worldwideview.dev/stream`; saved today by local-first routing in `resolveEngineUrl.ts`. Worth a sweep, not cutover-blocking.
- **Northstar Sequence Phase 5** — final cutover (link nav, docs, marketing) — starts after Phase 4 is stable in production for ~1 week.
- **Multi-engine audience separation** — currently every JWT has audience `wwv-data-engine` (broadcast). Per-engine audiences are a future ADR-001 follow-up.
---
## Assumptions
1. The Coolify CLI is installed and the `wwv` context is pre-configured (per personal memory). If not, fall back to the Coolify web dashboard for the same actions — the env-set + deploy-trigger workflow is identical, just clicked instead of typed.
2. The production data engine URL is `https://dataenginev2.worldwideview.dev`. If it's something different, substitute throughout.
3. The production marketplace URL is `https://marketplace.worldwideview.dev`. Confirmed in Task 2.
4. The production frontend URL is `https://worldwideview.dev`. If it's `app.worldwideview.dev` or similar, substitute in Task 10.
5. The data engine reads `JWKS_URL` at boot — confirmed via `startup-checks.ts` in PR #10. The cutover redeploy triggers a fresh boot.
6. The frontend reads `NEXT_PUBLIC_*` vars at BUILD time — Coolify's `deploy trigger wwv` does a rebuild, so the new env var is baked into the bundle.
7. The PKCE flow has already been used at least once on the production marketplace by an actual user, so `MarketplaceCredential` rows exist for that user. If you're testing as a fresh user, you'll need to complete `/api/marketplace/connect` once before Task 10 Step 3 — otherwise `/api/auth/ticket` will fail with "no marketplace credential."
8. Coolify deploys complete in under ~5 minutes typical. If much longer, check the Coolify host disk space — per deployment rules, builds silently die when disk fills up.
+25
View File
@@ -19,6 +19,7 @@ const nextConfig: NextConfig = {
async headers() {
return [
{
// Global security headers for all routes
source: "/(.*)",
headers: [
{
@@ -51,6 +52,30 @@ const nextConfig: NextConfig = {
},
],
},
{
// Camera proxy routes serve content that must be embeddable in an <iframe>
// within the same origin. Override the global frame-ancestors 'none' and
// X-Frame-Options: DENY so the browser allows the proxy response to be
// framed by our own app (localhost:3000 / production domain).
// The upstream camera HTML already had its own X-Frame-Options stripped by
// the iframe proxy route; this override ensures our response headers don't
// re-block it.
source: "/api/camera/proxy/:path*",
headers: [
{
key: "Content-Security-Policy",
// Proxy routes serve arbitrary external HTML (YouTube embeds, camera feeds, etc.).
// Restricting style-src/script-src here would break the proxied content since we
// cannot predict which CDN domains it loads from. The meaningful security boundary
// is frame-ancestors 'self' — only our own origin can embed these proxy responses.
value: "default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; frame-ancestors 'self'",
},
// Remove the DENY override — SAMEORIGIN allows our app to frame this response
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
],
},
];
},
+14 -13
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.17.4",
"version": "2.24.4",
"private": true,
"type": "module",
"packageManager": "[email protected]",
@@ -31,10 +31,10 @@
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@prisma/client-runtime-utils": "7.8.0",
"@sentry/nextjs": "^10.53.1",
"@supabase/supabase-js": "^2.106.0",
"@sentry/nextjs": "^10.54.0",
"@supabase/ssr": "^0.10.3",
"@supabase/supabase-js": "^2.106.2",
"@types/pg": "^8.20.0",
"@vercel/analytics": "^1.6.1",
"@worldwideview/wwv-plugin-sdk": "workspace:*",
"bcryptjs": "^3.0.3",
"cesium": "^1.141.0",
@@ -42,7 +42,7 @@
"hls.js": "^1.6.16",
"insecam-api": "^0.0.3",
"jose": "^6.2.3",
"lucide-react": "^1.16.0",
"lucide-react": "^1.17.0",
"next": "16.2.6",
"next-auth": "^5.0.0-beta.30",
"openid-client": "^6.8.4",
@@ -53,10 +53,10 @@
"react-player": "^3.4.0",
"resium": "1.21.1",
"satellite.js": "^7.0.1",
"stripe": "^22.1.1",
"stripe": "^22.2.0",
"tslib": "^2.8.1",
"undici": "^8.3.0",
"ws": "^8.20.1",
"ws": "^8.21.0",
"zod": "^4.4.3",
"zustand": "^5.0.13"
},
@@ -74,10 +74,10 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.59.4",
"@typescript-eslint/parser": "^8.59.4",
"@typescript-eslint/eslint-plugin": "^8.60.0",
"@typescript-eslint/parser": "^8.60.0",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "4.1.6",
"@vitest/coverage-v8": "4.1.7",
"concurrently": "^9.2.1",
"copy-webpack-plugin": "^14.0.0",
"eslint": "^9",
@@ -92,10 +92,10 @@
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tree-kill": "^1.2.2",
"tsx": "^4.22.2",
"tsx": "^4.22.3",
"typescript": "^5",
"vite": "^8.0.13",
"vitest": "^4.1.6"
"vite": "^8.0.14",
"vitest": "^4.1.7"
},
"pnpm": {
"overrides": {
@@ -120,3 +120,4 @@
"pnpm": ">=9.0.0"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-lib-incidents",
"version": "1.0.2",
"version": "1.0.4",
"description": "Shared abstract base classes for WorldWideView incident plugins (earthquakes, wildfires, conflicts)",
"main": "src/index.ts",
"types": "src/index.ts",
@@ -0,0 +1,283 @@
/**
* Guard tests for the BaseIncidentPlugin WebSocket payload contract.
*
* CONTEXT — The bug this suite guards against (now fixed):
* WsClient.handleDataMessage (src/core/data/WsClient.ts, lines 166-190) has three branches:
* 1. Plugin has `mapWebsocketPayload` → called with raw payload → must return GeoEntity[]
* 2. No handler AND payload IS a flat array → used directly (timestamps normalised)
* 3. No handler AND payload is ANY OTHER object → silently dropped (console.warn + return)
*
* BaseIncidentPlugin now provides a default `mapWebsocketPayload` that unwraps the three
* common payload shapes (scheduler envelope, GeoJSON FeatureCollection, flat array).
* Subclasses may override for domain-specific shapes.
*/
import { describe, it, expect } from "vitest";
import { BaseIncidentPlugin } from "./index";
import type {
GeoEntity,
TimeRange,
ServerPluginConfig,
FilterDefinition,
PluginCategory,
CesiumEntityOptions,
} from "@worldwideview/wwv-plugin-sdk";
// ─── Minimal GeoEntity factory ────────────────────────────────────────────────
function makeEntity(id: string, overrides: Partial<GeoEntity> = {}): GeoEntity {
return {
id,
pluginId: "test-incident-plugin",
latitude: 35.6762,
longitude: 139.6503,
timestamp: new Date("2025-01-01T00:00:00Z"),
properties: {},
...overrides,
};
}
// ─── Minimal concrete subclass ────────────────────────────────────────────────
// We keep it as bare-bones as possible — only the abstract members required to
// instantiate the class. We do NOT add mapWebsocketPayload here, so we're testing
// the BaseIncidentPlugin base behaviour exactly.
class MinimalIncidentPlugin extends BaseIncidentPlugin {
id = "test-incident-plugin";
name = "Test Incident Plugin";
description = "Test";
icon = null;
category: PluginCategory = "natural-disaster";
version = "0.0.1";
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
return [];
}
getServerConfig(): ServerPluginConfig {
return {
apiBasePath: "/api/test-incident-plugin",
streamUrl: "ws://localhost:5001/stream",
pollingIntervalMs: 0,
};
}
getFilterDefinitions(): FilterDefinition[] {
return [];
}
getLegend(): { label: string; color: string; filterId?: string; filterValue?: string }[] {
return [];
}
protected getSeverityValue(_entity: GeoEntity): number {
return 0;
}
protected getSeverityColor(_value: number): string {
return "#ef4444";
}
protected getSeveritySize(_value: number): number {
return 10;
}
}
// ─── Subclass that DOES override mapWebsocketPayload ─────────────────────────
const FIXED_ENTITIES = [makeEntity("override-1"), makeEntity("override-2")];
class OverridingIncidentPlugin extends MinimalIncidentPlugin {
id = "overriding-incident-plugin";
mapWebsocketPayload(_payload: unknown, _existingEntities?: GeoEntity[]): GeoEntity[] {
return FIXED_ENTITIES;
}
}
// ─── Helpers that mimic WsClient.handleDataMessage branching logic ────────────
// We test the plugin method in isolation (unit test), not the full WsClient,
// because WsClient has DOM/Zustand/DataBus dependencies. This mirrors the exact
// logic from WsClient lines 172-182.
function simulateWsClientDispatch(
plugin: BaseIncidentPlugin,
rawPayload: unknown
): GeoEntity[] | null {
if (typeof (plugin as any).mapWebsocketPayload === "function") {
return (plugin as any).mapWebsocketPayload(rawPayload, []);
}
if (!Array.isArray(rawPayload)) {
// This is the silent-drop branch — return null to signal "dropped"
return null;
}
return (rawPayload as GeoEntity[]).map((e) => ({
...e,
timestamp: new Date(e.timestamp || Date.now()),
}));
}
// ─── Test suite ───────────────────────────────────────────────────────────────
describe("BaseIncidentPlugin — WebSocket payload contract", () => {
describe("scheduler-wrapped payload { source, fetchedAt, items, totalCount }", () => {
it(
"unwraps { source, fetchedAt, items, totalCount } and returns items as GeoEntity[]",
() => {
const plugin = new MinimalIncidentPlugin();
const entity1 = makeEntity("eq-1");
const entity2 = makeEntity("eq-2");
const wrappedPayload = {
source: "usgs-earthquake-feed",
fetchedAt: "2025-01-01T00:00:00Z",
items: [entity1, entity2],
totalCount: 2,
};
// After the fix: mapWebsocketPayload should exist and return both entities
const result = simulateWsClientDispatch(plugin, wrappedPayload);
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(2);
expect(result![0].id).toBe("eq-1");
expect(result![1].id).toBe("eq-2");
}
);
});
describe("flat GeoEntity[] payload", () => {
/**
* Flat arrays bypass mapWebsocketPayload entirely in WsClient — they work today.
* This test MUST stay green before and after the fix.
*/
it("passes flat GeoEntity[] through unchanged (current working behaviour)", () => {
const plugin = new MinimalIncidentPlugin();
const entities = [makeEntity("eq-flat-1"), makeEntity("eq-flat-2")];
const result = simulateWsClientDispatch(plugin, entities);
expect(result).not.toBeNull();
expect(result).toHaveLength(2);
expect(result![0].id).toBe("eq-flat-1");
expect(result![1].id).toBe("eq-flat-2");
});
it("normalises timestamp strings to Date objects for flat array payloads", () => {
const plugin = new MinimalIncidentPlugin();
const raw = [{
...makeEntity("eq-ts-1"),
// Simulate a timestamp that arrives over the wire as a string
timestamp: "2025-06-01T12:00:00Z" as unknown as Date,
}];
const result = simulateWsClientDispatch(plugin, raw);
expect(result).not.toBeNull();
expect(result![0].timestamp).toBeInstanceOf(Date);
});
});
describe("GeoJSON { features: [...] } payload", () => {
it(
"normalises a GeoJSON FeatureCollection into GeoEntity[]",
() => {
const plugin = new MinimalIncidentPlugin();
const geojsonPayload = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: { type: "Point", coordinates: [139.65, 35.68] },
properties: { id: "gj-1", magnitude: 4.5 },
},
{
type: "Feature",
geometry: { type: "Point", coordinates: [135.50, 34.69] },
properties: { id: "gj-2", magnitude: 3.1 },
},
],
};
const result = simulateWsClientDispatch(plugin, geojsonPayload);
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(2);
// Each feature should have been converted to a GeoEntity with lat/lon
expect(result![0].latitude).toBeCloseTo(35.68, 2);
expect(result![0].longitude).toBeCloseTo(139.65, 2);
}
);
});
describe("subclass override of mapWebsocketPayload", () => {
/**
* A subclass that implements mapWebsocketPayload is handled correctly TODAY.
* This covers the "conflict-events" / "iranwarlive" pattern and must stay green.
*/
it("calls the subclass override and returns its result regardless of payload shape", () => {
const plugin = new OverridingIncidentPlugin();
// Even if the payload is an object (which would normally be dropped), the
// subclass override is respected.
const wrappedPayload = {
source: "conflict-api",
fetchedAt: "2025-01-01T00:00:00Z",
items: [makeEntity("conflict-1")],
totalCount: 1,
};
const result = simulateWsClientDispatch(plugin, wrappedPayload);
// Should return the overriding subclass's fixed result, not the raw items
expect(result).toStrictEqual(FIXED_ENTITIES);
});
it("override is also called for flat array payloads, taking precedence over default handling", () => {
const plugin = new OverridingIncidentPlugin();
const flatPayload = [makeEntity("flat-1"), makeEntity("flat-2"), makeEntity("flat-3")];
const result = simulateWsClientDispatch(plugin, flatPayload);
// The override always wins — result is FIXED_ENTITIES, not the 3-element flat array
expect(result).toStrictEqual(FIXED_ENTITIES);
expect(result).toHaveLength(2);
});
});
describe("BaseIncidentPlugin structural contract", () => {
it("has mapWebsocketPayload defined", () => {
const plugin = new MinimalIncidentPlugin();
expect(typeof (plugin as any).mapWebsocketPayload).toBe("function");
});
it("implements the required WorldPlugin lifecycle methods", () => {
const plugin = new MinimalIncidentPlugin();
expect(typeof plugin.initialize).toBe("function");
expect(typeof plugin.destroy).toBe("function");
expect(typeof plugin.fetch).toBe("function");
expect(typeof plugin.getPollingInterval).toBe("function");
expect(typeof plugin.getLayerConfig).toBe("function");
expect(typeof plugin.renderEntity).toBe("function");
});
it("returns polling interval of 0 (WebSocket-only mode)", () => {
const plugin = new MinimalIncidentPlugin();
expect(plugin.getPollingInterval()).toBe(0);
});
it("returns default layer config with clustering enabled", () => {
const plugin = new MinimalIncidentPlugin();
const config = plugin.getLayerConfig();
expect(config.clusterEnabled).toBe(true);
expect(config.color).toBe("#ef4444");
expect(typeof config.clusterDistance).toBe("number");
});
});
});
+65
View File
@@ -80,4 +80,69 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
labelFont: "11px JetBrains Mono, monospace" // Adds optional label standard
};
}
/**
* Default WebSocket payload normaliser. WsClient calls this when a data message
* arrives; if absent, WsClient silently drops anything that isn't a flat array.
*
* Handles three shapes:
* - Scheduler envelope: { source, fetchedAt, items: GeoEntity[], totalCount } → items
* - GeoJSON FeatureCollection: { features: [{geometry, properties}, ...] } → normalised
* - Flat array: passes through (with timestamp normalisation)
*
* Subclasses may override for domain-specific shapes; this default covers
* the common scheduler-wrapped and GeoJSON cases so the bug doesn't recur.
*
* @param payload - Raw payload received from the WebSocket message
* @param _existingEntities - Current entities in the layer (unused by default; available for subclass merging logic)
* @returns Normalised GeoEntity[] ready for the layer renderer
*/
mapWebsocketPayload(payload: any, _existingEntities?: GeoEntity[]): GeoEntity[] {
const items = this.extractIncidentItems(payload);
return items.map((e) => ({
...e,
timestamp: e.timestamp instanceof Date ? e.timestamp : new Date(e.timestamp ?? Date.now()),
}));
}
/**
* Extracts a raw GeoEntity array from the three common payload shapes:
* scheduler envelope, GeoJSON FeatureCollection, or flat array.
*
* @param payload - The raw WebSocket payload
* @returns Unnormalised array of GeoEntity-like objects (timestamps not yet coerced)
*/
protected extractIncidentItems(payload: any): GeoEntity[] {
if (Array.isArray(payload)) {
return payload as GeoEntity[];
}
if (payload && Array.isArray(payload.items)) {
return payload.items as GeoEntity[];
}
if (payload && Array.isArray(payload.features)) {
return payload.features.map((f: any, i: number) => this.geoJsonFeatureToEntity(f, i));
}
return [];
}
/**
* Converts a GeoJSON Feature object into a GeoEntity.
*
* @param feature - GeoJSON Feature with geometry.coordinates and optional properties
* @param index - Position in the parent features array, used to generate a fallback id
* @returns A GeoEntity with lat/lon extracted from the feature geometry
*/
protected geoJsonFeatureToEntity(feature: any, index: number): GeoEntity {
const coords = feature?.geometry?.coordinates ?? [0, 0];
const props = feature?.properties ?? {};
return {
id: props.id ?? `${this.id}-${index}`,
pluginId: this.id,
latitude: coords[1],
longitude: coords[0],
timestamp: props.timestamp ? new Date(props.timestamp) : new Date(),
properties: props,
label: props.label,
};
}
}
+40 -8
View File
@@ -1,4 +1,11 @@
import { defineConfig, devices } from '@playwright/test';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dir = path.dirname(fileURLToPath(import.meta.url));
const MARKETPLACE_DIR = path.resolve(__dir, '../worldwideview-marketplace');
const hasMarketplace = fs.existsSync(MARKETPLACE_DIR);
/**
* See https://playwright.dev/docs/test-configuration.
@@ -11,6 +18,16 @@ export default defineConfig({
globalSetup: './tests/global.setup.ts',
globalTeardown: './tests/global.teardown.ts',
testDir: './tests',
// web-auth.spec.ts targets worldwideview-web (https://wwv.local:3001) — use playwright.web.config.ts
// marketplace-from-instance.spec.ts uses playwright.marketplace.config.ts; full-flow requires marketplace repo
// marketplace-redirect-handshake.spec.ts and marketplace-sign-out.spec.ts require marketplace.wwv.local:3002
// — use playwright.cross-app.config.ts for these cross-origin handshake tests
testIgnore: [
'**/web-auth.spec.ts',
'**/marketplace-from-instance.spec.ts',
'**/marketplace-redirect-handshake.spec.ts',
'**/marketplace-sign-out.spec.ts',
],
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
@@ -61,12 +78,27 @@ export default defineConfig({
},
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'pnpm dev',
env: { PORT: '3001' },
url: 'http://localhost:3001',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
/* Run dev servers before starting the tests */
webServer: [
{
command: 'pnpm dev',
env: {
PORT: '3001',
NEXT_PUBLIC_MARKETPLACE_URL: 'http://localhost:3002',
},
url: 'http://localhost:3001',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
// Only start marketplace when the repo is checked out alongside worldwideview.
// In CI the marketplace dir does not exist — omitting it prevents spawn ENOENT.
...(hasMarketplace ? [{
command: 'pnpm dev',
cwd: MARKETPLACE_DIR,
env: { PORT: '3002' },
url: 'http://localhost:3002',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
}] : []),
],
});
+85
View File
@@ -0,0 +1,85 @@
/**
* Cross-app E2E config.
* Starts both worldwideview-web (3001) and worldwideview-marketplace (3002)
* and runs specs that exercise the shared Supabase cookie handshake across
* the .wwv.local cookie domain.
*
* The marketplace MUST be reachable at https://marketplace.wwv.local:3002
* (not localhost:3002) because the Supabase auth cookie is scoped to .wwv.local.
*
* Loads .env.test credentials via Node fs so specs can read them from
* process.env without requiring a dotenv package install.
*
* Usage:
* pnpm exec playwright test --config=playwright.cross-app.config.ts
*/
import { defineConfig, devices } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
const __dir = path.dirname(fileURLToPath(import.meta.url));
const WEB_DIR = path.resolve(__dir, '../worldwideview-web');
const MARKETPLACE_DIR = path.resolve(__dir, '../worldwideview-marketplace');
// Load .env.test credentials into process.env so specs can read them.
// Uses fs directly to avoid a dotenv dependency.
const envTestPath = path.resolve(__dir, '.env.test');
if (fs.existsSync(envTestPath)) {
const lines = fs.readFileSync(envTestPath, 'utf8').split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx === -1) continue;
const key = trimmed.slice(0, eqIdx).trim();
const val = trimmed.slice(eqIdx + 1).trim();
if (key && !(key in process.env)) process.env[key] = val;
}
}
export default defineConfig({
timeout: 60000,
expect: { timeout: 10000 },
testDir: './tests',
testMatch: [
'**/marketplace-redirect-handshake.spec.ts',
'**/marketplace-sign-out.spec.ts',
],
fullyParallel: false,
retries: 0,
workers: 1,
reporter: 'list',
use: {
baseURL: 'https://marketplace.wwv.local:3002',
ignoreHTTPSErrors: true,
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
webServer: [
{
command: 'pnpm dev',
cwd: WEB_DIR,
url: 'https://wwv.local:3001',
reuseExistingServer: true,
timeout: 90 * 1000,
ignoreHTTPSErrors: true,
},
{
command: 'pnpm dev',
cwd: MARKETPLACE_DIR,
url: 'https://marketplace.wwv.local:3002',
reuseExistingServer: true,
timeout: 90 * 1000,
ignoreHTTPSErrors: true,
},
],
});
+46
View File
@@ -0,0 +1,46 @@
/**
* Marketplace-only E2E config.
* Runs against the marketplace dev server on port 3002 only.
* No worldwideview auth or Docker/Postgres required.
*
* Usage:
* pnpm exec playwright test --config=playwright.marketplace.config.ts
*/
import { defineConfig, devices } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';
const __dir = path.dirname(fileURLToPath(import.meta.url));
const MARKETPLACE_DIR = path.resolve(__dir, '../worldwideview-marketplace');
export default defineConfig({
timeout: 30000,
expect: { timeout: 10000 },
testDir: './tests',
testMatch: '**/marketplace-from-instance.spec.ts',
fullyParallel: false,
retries: 0,
workers: 1,
reporter: 'list',
use: {
baseURL: 'http://localhost:3002',
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
command: 'pnpm dev',
cwd: MARKETPLACE_DIR,
env: { PORT: '3002' },
url: 'http://localhost:3002',
reuseExistingServer: true,
timeout: 90 * 1000,
},
});
+47
View File
@@ -0,0 +1,47 @@
/**
* worldwideview-web E2E config.
* Runs against the web dev server on https://wwv.local:3001.
* Requires mkcert cert at worldwideview-web/certs/wwv.local+2.pem.
*
* Usage:
* pnpm exec playwright test --config=playwright.web.config.ts
*/
import { defineConfig, devices } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';
const __dir = path.dirname(fileURLToPath(import.meta.url));
const WEB_DIR = path.resolve(__dir, '../worldwideview-web');
export default defineConfig({
timeout: 30000,
expect: { timeout: 10000 },
testDir: './tests',
testMatch: '**/web-auth.spec.ts',
fullyParallel: false,
retries: 0,
workers: 1,
reporter: 'list',
use: {
baseURL: 'https://wwv.local:3001',
ignoreHTTPSErrors: true,
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
command: 'pnpm dev',
cwd: WEB_DIR,
url: 'https://wwv.local:3001',
reuseExistingServer: true,
timeout: 90 * 1000,
ignoreHTTPSErrors: true,
},
});
+1416 -1043
View File
File diff suppressed because it is too large. Load diff
+18 -3
View File
@@ -63,7 +63,22 @@ console.log(`🔌 Assigned deterministic database port: ${port}`);
// Robust rewrite of DATABASE_URL in .env
const envPath = path.resolve(cwd, '.env');
if (fs.existsSync(envPath)) {
// Ensure .env exists — worktrees only have .env.local, not .env.
// Without this, the DATABASE_URL injection block below is silently skipped
// and safe-db-push.mjs fails with "DATABASE_URL is missing".
if (!fs.existsSync(envPath)) {
const examplePath = path.resolve(cwd, '.env.example');
if (fs.existsSync(examplePath)) {
fs.copyFileSync(examplePath, envPath);
console.log('📄 Created .env from .env.example (worktree first-run).');
} else {
fs.writeFileSync(envPath, '');
console.log('📄 Created empty .env (worktree first-run).');
}
}
{
const envContent = fs.readFileSync(envPath, 'utf8');
const lines = envContent.split(/\r?\n/);
@@ -96,7 +111,7 @@ if (fs.existsSync(envPath)) {
if (linesModified) {
const newContent = newLines.join('\n');
// File write with retries and telemetry
const maxRetries = 3;
let attempt = 0;
@@ -121,7 +136,7 @@ if (fs.existsSync(envPath)) {
}
}
}
}
} // end DATABASE_URL injection block
console.log('🚀 Checking local PostgreSQL database...');
+3 -2
View File
@@ -130,8 +130,9 @@ const ANTI_PATTERNS = [
{
id: 'mdc-ref',
tier: 'A',
globs: ['*.ts', '*.tsx', '*.md', '*.mjs'],
pattern: '\\.mdc',
globs: ['*.ts', '*.tsx'],
pattern: '[\'"].*\\.mdc[\'"]',
excludePrefix: 'scripts/',
desc: '.mdc file reference — must be .md (project invariant: never .mdc files)',
},
{
+21 -2
View File
@@ -251,10 +251,22 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
external: Object.keys(EXTERNAL_GLOBALS),
output: {
globals: EXTERNAL_GLOBALS,
codeSplitting: false,
inlineDynamicImports: true,
banner: '"use client";',
},
plugins: [(await import("rollup-plugin-external-globals")).default(EXTERNAL_GLOBALS)],
plugins: [
{
name: 'replace-process-env',
transform(code) {
if (!code.includes('process.env.NODE_ENV')) return null;
return {
code: code.replace(/process\.env\.NODE_ENV/g, '"production"'),
map: null,
};
},
},
(await import("rollup-plugin-external-globals")).default(EXTERNAL_GLOBALS),
],
onwarn(warning, warn) {
if (warning.code === 'MODULE_LEVEL_DIRECTIVE' && warning.message.includes('"use client"')) {
return;
@@ -292,6 +304,13 @@ export function syncToPublic({ dir, manifest, pluginDir }, { quiet = false } = {
if (fs.existsSync(distMap)) {
fs.copyFileSync(distMap, path.join(targetDir, "frontend.mjs.map"));
}
// Copy any CSS files emitted alongside the bundle (e.g. from gridstack imports)
const distDir = path.join(pluginDir, "dist");
for (const f of fs.readdirSync(distDir)) {
if (f.endsWith(".css")) {
fs.copyFileSync(path.join(distDir, f), path.join(targetDir, f));
}
}
// Generate plugin.json manifest for the marketplace load route
const pluginJson = {
-15
View File
@@ -55,7 +55,6 @@ export async function GET(req: NextRequest) {
headers: {
"Content-Type": contentType,
"Cache-Control": "no-store",
"Access-Control-Allow-Origin": "*",
},
});
}
@@ -78,8 +77,6 @@ export async function GET(req: NextRequest) {
"Content-Type": contentType,
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
},
});
} catch (error: unknown) {
@@ -91,15 +88,3 @@ export async function GET(req: NextRequest) {
);
}
}
export async function OPTIONS() {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "86400",
},
});
}
+1 -1
View File
@@ -31,7 +31,7 @@ export async function GET(req: NextRequest) {
const upstream = await safeFetch(targetUrl, {
headers: { "User-Agent": "WorldWideView/1.0" },
timeout: MAX_STREAM_DURATION_MS,
maxSize: 100 * 1024 * 1024, // 100MB for streams
streaming: true,
});
if (!upstream.ok) {
+2 -2
View File
@@ -67,7 +67,7 @@ export async function GET(req: NextRequest) {
httpOnly: true,
secure: isHttps,
sameSite: "lax",
path: "/api/marketplace/callback",
path: "/", // must match the path used at Set-Cookie time
maxAge: 0
});
@@ -75,7 +75,7 @@ export async function GET(req: NextRequest) {
httpOnly: true,
secure: isHttps,
sameSite: "lax",
path: "/api/marketplace/callback",
path: "/", // must match the path used at Set-Cookie time
maxAge: 0
});
+2 -2
View File
@@ -26,7 +26,7 @@ export async function GET(req: NextRequest) {
httpOnly: true,
secure: isHttps,
sameSite: "lax",
path: "/api/marketplace/callback",
path: "/", // __Host- prefix requires path="/" per RFC 6265bis
maxAge: 60 * 10 // 10 minutes
});
@@ -34,7 +34,7 @@ export async function GET(req: NextRequest) {
httpOnly: true,
secure: isHttps,
sameSite: "lax",
path: "/api/marketplace/callback",
path: "/", // __Host- prefix requires path="/" per RFC 6265bis
maxAge: 60 * 10 // 10 minutes
});
+3 -3
View File
@@ -55,9 +55,9 @@ export async function GET(request: NextRequest) {
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
// Construct a relative path for callback to ensure it redirects back to the identical host
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("callbackUrl", callbackPath);
// Construct a relative path for `next` to ensure it redirects back to the identical host
const nextPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("next", nextPath);
return NextResponse.redirect(loginUrl);
}
@@ -1,6 +1,8 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { auth } from "@/lib/auth";
import { getSupabaseUser } from "@/lib/supabase/server";
import { isCloud, isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition";
import { upsertPlugin } from "@/lib/marketplace/repository";
import { issueMarketplaceToken } from "@/lib/marketplace/marketplaceToken";
import type { MarketplaceSessionToken } from "@worldwideview/wwv-plugin-sdk";
@@ -8,7 +10,6 @@ import type { PluginManifest } from "@/core/plugins/PluginManifest";
import { validateManifest } from "@/core/plugins/validateManifest";
import { installLimiter } from "@/lib/rateLimiters";
import { getClientIp } from "@/lib/rateLimit";
import { isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition";
import { getVerifiedPluginIds } from "@/lib/marketplace/registryClient";
import { getRequestOrigin } from "@/lib/origin";
@@ -51,23 +52,38 @@ export async function GET(request: NextRequest) {
const rateLimited = installLimiter.check(getClientIp(request));
if (rateLimited) return rateLimited;
const session = await auth();
// Auth: cloud edition uses Supabase session; local/demo uses NextAuth.
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const isDummyUrl = !supabaseUrl || supabaseUrl.includes("dummy") || supabaseUrl.includes("xyz.supabase.co");
const useSupabaseAuth = isCloud && !isDummyUrl;
// Not logged in — send to login with this URL as callbackUrl
if (!session?.user) {
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("callbackUrl", callbackPath);
return NextResponse.redirect(loginUrl);
}
if (isDemo && !isDemoAdmin(session)) {
return NextResponse.json(
{ error: "Admin access required on Demo edition" },
{ status: 403 }
);
let userId: string;
if (useSupabaseAuth) {
const supabaseUser = await getSupabaseUser();
if (!supabaseUser) {
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
const nextPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("next", nextPath);
return NextResponse.redirect(loginUrl);
}
userId = supabaseUser.id;
} else {
const session = await auth();
if (!session?.user) {
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
const nextPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("next", nextPath);
return NextResponse.redirect(loginUrl);
}
if (isDemo && !isDemoAdmin(session)) {
return NextResponse.json(
{ error: "Admin access required on Demo edition" },
{ status: 403 }
);
}
userId = session.user.id ?? "";
}
const pluginId = searchParams.get("pluginId");
@@ -114,7 +130,7 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: "Install failed" }, { status: 500 });
}
const token: MarketplaceSessionToken = await issueMarketplaceToken(session.user.id ?? "");
const token: MarketplaceSessionToken = await issueMarketplaceToken(userId);
const successUrl = new URL(redirectTo);
// Unverified plugins need user confirmation on the WWV client side
+1 -1
View File
@@ -56,7 +56,7 @@ describe("PKCE Flow", () => {
expect(cookies).toContain("HttpOnly");
expect(cookies).toContain("Secure");
expect(cookies).toContain("SameSite=lax");
expect(cookies).toContain("Path=/api/marketplace/callback");
expect(cookies).toContain("Path=/"); // __Host- prefix requires Path=/ per RFC 6265bis
// Check __Host- prefix if in production (assuming https testing context)
expect(cookies).toMatch(/__Host-pkce_verifier/);
});
+2 -1
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { transliterate } from "@/lib/utils/transliterate";
// Server-side cache: keyed by place_id, 24-hour TTL (place geometry is stable)
const cache = new Map<string, { data: unknown; expiresAt: number }>();
@@ -50,7 +51,7 @@ export async function GET(request: Request) {
const result = {
lat: location.lat,
lon: location.lng,
name: data.result.name,
name: transliterate(data.result.name ?? ""),
types: data.result.types || [],
viewport: data.result.geometry?.viewport || null,
};
+4 -3
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { transliterate } from "@/lib/utils/transliterate";
// Server-side cache: keyed by normalised input, 1-hour TTL
const cache = new Map<string, { data: unknown; expiresAt: number }>();
@@ -44,10 +45,10 @@ export async function GET(request: Request) {
}
const predictions = data.predictions.map((p: any) => ({
description: p.description,
description: transliterate(p.description ?? ""),
placeId: p.place_id,
mainText: p.structured_formatting?.main_text || p.description,
secondaryText: p.structured_formatting?.secondary_text || "",
mainText: transliterate(p.structured_formatting?.main_text || p.description),
secondaryText: transliterate(p.structured_formatting?.secondary_text || ""),
types: p.types,
}));
+24
View File
@@ -0,0 +1,24 @@
import { NextResponse } from "next/server";
import { WEATHER_LAYERS, type WeatherLayer } from "@/lib/weatherLayers";
export const revalidate = 3600;
const LAYER_META: Record<WeatherLayer, { name: string; description: string }> = {
clouds_new: { name: "Clouds", description: "Cloud coverage" },
precipitation_new: { name: "Precipitation", description: "Rain and snow" },
pressure_new: { name: "Sea Level Pressure", description: "Atmospheric pressure" },
wind_new: { name: "Wind Speed", description: "Wind speed and direction" },
temp_new: { name: "Temperature", description: "Surface temperature" },
};
const LAYERS = WEATHER_LAYERS.map((id) => ({ id, ...LAYER_META[id] }));
export async function GET() {
const configured = !!process.env.OPENWEATHERMAP_API_KEY;
return NextResponse.json({
configured,
tileUrlTemplate: configured ? "/api/weather/tile/{z}/{x}/{y}?layer={layer}" : null,
layers: LAYERS,
});
}
@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from "next/server";
import { WEATHER_LAYERS, isValidWeatherLayer } from "@/lib/weatherLayers";
export const revalidate = 600;
const MAX_ZOOM = 18;
function isValidTileCoord(value: string, zoom?: number): boolean {
const n = Number(value);
if (!Number.isInteger(n) || n < 0) return false;
if (zoom !== undefined) {
if (n >= Math.pow(2, zoom)) return false;
}
return true;
}
function isValidZoom(value: string): boolean {
const n = Number(value);
return Number.isInteger(n) && n >= 0 && n <= MAX_ZOOM;
}
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ z: string; x: string; y: string }> },
) {
const { z, x, y } = await params;
const layer = req.nextUrl.searchParams.get("layer");
if (!layer || !isValidWeatherLayer(layer)) {
return NextResponse.json(
{ error: `Invalid layer. Must be one of: ${WEATHER_LAYERS.join(", ")}` },
{ status: 400 },
);
}
if (!isValidZoom(z)) {
return NextResponse.json(
{ error: "Invalid tile coordinates" },
{ status: 400 },
);
}
const zNum = Number(z);
if (!isValidTileCoord(x, zNum) || !isValidTileCoord(y, zNum)) {
return NextResponse.json(
{ error: "Invalid tile coordinates" },
{ status: 400 },
);
}
const apiKey = process.env.OPENWEATHERMAP_API_KEY;
if (!apiKey) {
return NextResponse.json(
{ error: "Weather API not configured" },
{ status: 503 },
);
}
const tileUrl = `https://tile.openweathermap.org/map/${layer}/${z}/${x}/${y}.png?appid=${apiKey}`;
try {
const response = await fetch(tileUrl, {
headers: { "User-Agent": "WorldWideView/1.0" },
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch weather tile" },
{ status: 502 },
);
}
const buffer = await response.arrayBuffer();
return new Response(buffer, {
status: 200,
headers: {
"Content-Type": "image/png",
"Cache-Control": "public, max-age=600, stale-while-revalidate=300",
},
});
} catch {
return NextResponse.json(
{ error: "Failed to fetch weather tile" },
{ status: 502 },
);
}
}
+27
View File
@@ -2134,3 +2134,30 @@ body.is-dragging-bottom-panel .bottom-panel {
gap: 12px;
height: 100%;
}
/* ─── Legal Footer ────────────────────────────────────────── */
.legal-footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
padding: 4px var(--space-lg, 1.5rem);
background: rgba(9, 9, 11, 0.7);
border-top: 1px solid var(--border-subtle);
display: flex;
gap: var(--space-lg, 1.5rem);
justify-content: center;
font-size: 11px;
color: var(--text-muted);
}
.legal-footer a {
color: var(--text-muted);
text-decoration: none;
}
.legal-footer a:hover {
color: var(--text-secondary);
text-decoration: underline;
}
+2 -2
View File
@@ -1,8 +1,8 @@
import type { Metadata, Viewport } from "next";
import Script from "next/script";
import { Analytics } from "@vercel/analytics/next";
import "./globals.css";
import "@/styles/hud-animations.css";
import { LegalFooter } from "@/components/layout/LegalFooter";
export const viewport: Viewport = {
width: "device-width",
@@ -53,7 +53,6 @@ export default function RootLayout({
</head>
<body suppressHydrationWarning>
{children}
{process.env.VERCEL && <Analytics />}
{process.env.NEXT_PUBLIC_WWV_ANALYTICS === "true" && (
<Script
src="https://analytics.worldwideview.dev/script.js"
@@ -61,6 +60,7 @@ export default function RootLayout({
strategy="afterInteractive"
/>
)}
<LegalFooter />
</body>
</html>
);
+89
View File
@@ -0,0 +1,89 @@
"use client";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { isDemo } from "@/core/edition";
import { loginAction } from "./actions";
import styles from "../setup/setup.module.css";
/** Allow relative paths or same-origin URLs only (local edition is self-contained). */
function getSafeRedirect(url: string | null): string {
if (!url) return "/";
if (url.startsWith("/") && url[1] !== "/" && url[1] !== "\\") return url;
try {
const parsed = new URL(url);
if (parsed.origin === window.location.origin) return url;
} catch { /* invalid URL — fall through */ }
return "/";
}
export default function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const next = searchParams.get("next");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setError("");
setLoading(true);
const formData = new FormData(e.currentTarget);
const result = await loginAction(formData);
if (result.success) {
const target = getSafeRedirect(next);
if (target === "/") {
router.push("/");
router.refresh();
} else {
window.location.href = target;
}
} else {
setError(result.error ?? "Login failed.");
setLoading(false);
}
}
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Sign in to WorldWideView</h1>
<p className={styles.subtitle}>Enter your credentials to continue</p>
<form onSubmit={handleSubmit} method="post" className={styles.form}>
<label className={styles.label} htmlFor="email">
{isDemo ? "Username" : "Email"}
<input
id="email"
name="email"
type={isDemo ? "text" : "email"}
required
className={styles.input}
placeholder={isDemo ? "admin" : "[email protected]"}
/>
</label>
<label className={styles.label} htmlFor="password">
Password
<input
id="password"
name="password"
type="password"
required
className={styles.input}
/>
</label>
{error && <p className={styles.error}>{error}</p>}
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Signing in..." : "Sign In"}
</button>
</form>
</div>
</div>
);
}
+13 -32
View File
@@ -2,8 +2,6 @@
import { signIn } from "@/lib/auth";
import { AuthError } from "next-auth";
import { isCloud } from "@/core/edition";
import { createClient } from "@supabase/supabase-js";
interface LoginResult {
success: boolean;
@@ -14,39 +12,22 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const isDummyUrl = !supabaseUrl || supabaseUrl.includes("dummy") || supabaseUrl.includes("xyz.supabase.co");
if (isCloud && !isDummyUrl) {
// Use Supabase GoTrue
const supabase = createClient(
supabaseUrl,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
const { error } = await supabase.auth.signInWithPassword({
try {
await signIn("credentials", {
email,
password,
redirect: false,
});
if (error) return { success: false, error: error.message };
return { success: true };
}
try {
await signIn("credentials", {
email,
password,
redirect: false,
});
return { success: true };
} catch (error) {
if (error instanceof AuthError) {
return {
success: false,
error: error.type === "CredentialsSignin"
? "Invalid email or password."
: "Something went wrong.",
};
}
throw error;
} catch (error) {
if (error instanceof AuthError) {
return {
success: false,
error: error.type === "CredentialsSignin"
? "Invalid email or password."
: "Something went wrong.",
};
}
throw error;
}
}
+19 -88
View File
@@ -1,98 +1,29 @@
"use client";
import { Suspense } from "react";
import { redirect } from "next/navigation";
import { isCloud } from "@/core/edition";
import LoginForm from "./LoginForm";
import { Suspense, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { isDemo } from "@/core/edition";
import { loginAction } from "./actions";
import styles from "../setup/setup.module.css";
/** Allow relative paths or absolute URLs on the same origin. */
function getSafeRedirect(url: string | null): string {
if (!url) return "/";
if (url.startsWith("/")) return url;
try {
const parsed = new URL(url);
if (parsed.origin === window.location.origin) return url;
} catch { /* invalid URL — fall through */ }
return "/";
interface LoginPageProps {
searchParams: Promise<{ next?: string }>;
}
function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const callbackUrl = searchParams.get("callbackUrl");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
export default async function LoginPage({ searchParams }: LoginPageProps) {
const { next } = await searchParams;
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setError("");
setLoading(true);
const formData = new FormData(e.currentTarget);
const result = await loginAction(formData);
if (result.success) {
const target = getSafeRedirect(callbackUrl);
if (target === "/") {
router.push("/");
router.refresh();
} else {
// Full navigation for API routes / external same-origin paths
window.location.href = target;
}
} else {
setError(result.error ?? "Login failed.");
setLoading(false);
// Cloud edition delegates auth to the ecosystem auth host (ADR-0003).
// Local edition keeps the inline NextAuth Credentials form.
if (isCloud) {
const authHost = process.env.NEXT_PUBLIC_AUTH_HOST_URL;
if (authHost) {
const url = new URL("/login", authHost);
if (next) url.searchParams.set("next", next);
redirect(url.toString());
}
}
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Sign in to WorldWideView</h1>
<p className={styles.subtitle}>Enter your credentials to continue</p>
<form onSubmit={handleSubmit} method="post" className={styles.form}>
<label className={styles.label} htmlFor="email">
{isDemo ? "Username" : "Email"}
<input
id="email"
name="email"
type={isDemo ? "text" : "email"}
required
className={styles.input}
placeholder={isDemo ? "admin" : "[email protected]"}
/>
</label>
<label className={styles.label} htmlFor="password">
Password
<input
id="password"
name="password"
type="password"
required
className={styles.input}
/>
</label>
{error && <p className={styles.error}>{error}</p>}
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Signing in..." : "Sign In"}
</button>
</form>
</div>
</div>
);
}
export default function LoginPage() {
return (
<Suspense>
<LoginForm />
</Suspense>
<Suspense>
<LoginForm />
</Suspense>
);
}
+14
View File
@@ -103,3 +103,17 @@
.button:hover { opacity: 0.9; }
.button:disabled { opacity: 0.5; cursor: not-allowed; }
.footer {
margin-top: 1.25rem;
font-size: 0.8rem;
color: var(--text-secondary, #888);
text-align: center;
}
.link {
color: rgb(200, 30, 30);
text-decoration: none;
}
.link:hover { text-decoration: underline; }
+14 -8
View File
@@ -48,24 +48,29 @@ export function BottomPanelManager() {
document.body.classList.add("is-dragging-bottom-panel");
const handleMouseMove = (e: MouseEvent) => {
const handleMove = (clientY: number) => {
// Calculate new height based on distance from bottom of window
const newHeight = window.innerHeight - e.clientY;
const newHeight = window.innerHeight - clientY;
// Clamp between min 120px and max window height - 100px
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
setBottomPanelHeight(clampedHeight);
};
const handleMouseUp = () => {
setIsDragging(false);
};
const handleMouseMove = (e: MouseEvent) => handleMove(e.clientY);
const handlePointerMove = (e: PointerEvent) => handleMove(e.clientY);
const handleEnd = () => setIsDragging(false);
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);
window.addEventListener("mouseup", handleEnd);
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handleEnd);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
window.removeEventListener("mouseup", handleEnd);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handleEnd);
document.body.classList.remove("is-dragging-bottom-panel");
};
}, [isDragging, setBottomPanelHeight]);
@@ -182,6 +187,7 @@ export function BottomPanelManager() {
data-testid="bottom-panel-resize-handle"
ref={resizeRef}
onMouseDown={() => setIsDragging(true)}
onPointerDown={() => setIsDragging(true)}
>
<div className="resize-grip" />
</div>
+20
View File
@@ -0,0 +1,20 @@
export function LegalFooter() {
return (
<footer className="legal-footer">
<a
href="https://worldwideview.dev/legal/privacy-policy"
target="_blank"
rel="noopener noreferrer"
>
Privacy Policy
</a>
<a
href="https://worldwideview.dev/legal/cloud-terms-of-service"
target="_blank"
rel="noopener noreferrer"
>
Terms of Service
</a>
</footer>
);
}
+52 -24
View File
@@ -11,6 +11,7 @@
import React, { useEffect } from "react";
import { useStore } from "@/core/state/store";
import { trackEvent } from "@/lib/analytics";
import { WEATHER_LAYERS } from "@/lib/weatherLayers";
import "./graphics-settings.css";
/**
@@ -19,13 +20,21 @@ import "./graphics-settings.css";
*/
const DEFAULT_GRAPHICS = {
resolutionScale: 1.0,
enableFxaa: false,
msaaSamples: 1,
antiAliasing: "fxaa" as const,
maxScreenSpaceError: 16,
shadowsEnabled: false,
enableLighting: false,
showFps: false,
showOsmBuildings: true,
weatherOverlay: null as string | null,
};
const WEATHER_LABEL: Record<string, string> = {
clouds_new: "Clouds",
precipitation_new: "Precipitation",
temp_new: "Temperature",
wind_new: "Wind Speed",
pressure_new: "Pressure",
};
const RESOLUTION_OPTIONS = [
@@ -57,10 +66,10 @@ export function GraphicsSettings() {
// Save to cookie on change
useEffect(() => {
const { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings } = mapConfig;
const graphicsToSave = { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings };
const { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings, weatherOverlay } = mapConfig;
const graphicsToSave = { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings, weatherOverlay };
document.cookie = `wwv_graphics=${encodeURIComponent(JSON.stringify(graphicsToSave))}; path=/; max-age=31536000`; // 1 year
}, [mapConfig.resolutionScale, mapConfig.antiAliasing, mapConfig.maxScreenSpaceError, mapConfig.shadowsEnabled, mapConfig.enableLighting, mapConfig.showFps, mapConfig.showOsmBuildings]);
}, [mapConfig.resolutionScale, mapConfig.antiAliasing, mapConfig.maxScreenSpaceError, mapConfig.shadowsEnabled, mapConfig.enableLighting, mapConfig.showFps, mapConfig.showOsmBuildings, mapConfig.weatherOverlay]);
const toggle = (key: string, current: boolean) => {
update({ [key]: !current });
@@ -76,14 +85,14 @@ export function GraphicsSettings() {
className="gfx-settings__select"
value={mapConfig.resolutionScale}
onChange={(e) => {
const v = parseFloat(e.target.value);
update({ resolutionScale: v });
trackEvent("graphics-setting", { key: "resolutionScale", value: v });
}}
const v = parseFloat(e.target.value);
update({ resolutionScale: v });
trackEvent("graphics-setting", { key: "resolutionScale", value: v });
}}
>
{RESOLUTION_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
))}
</select>
</div>
@@ -94,14 +103,14 @@ export function GraphicsSettings() {
className="gfx-settings__select"
value={mapConfig.antiAliasing}
onChange={(e) => {
const v = e.target.value as "none" | "fxaa" | "msaa2x" | "msaa4x" | "msaa8x";
update({ antiAliasing: v });
trackEvent("graphics-setting", { key: "antiAliasing", value: v });
}}
const v = e.target.value as "none" | "fxaa" | "msaa2x" | "msaa4x" | "msaa8x";
update({ antiAliasing: v });
trackEvent("graphics-setting", { key: "antiAliasing", value: v });
}}
>
{AA_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
))}
</select>
</div>
@@ -117,13 +126,13 @@ export function GraphicsSettings() {
step={1}
value={mapConfig.maxScreenSpaceError}
onChange={(e) => {
const v = parseInt(e.target.value, 10);
update({ maxScreenSpaceError: v });
}}
const v = parseInt(e.target.value, 10);
update({ maxScreenSpaceError: v });
}}
onPointerUp={() => trackEvent("graphics-setting", {
key: "maxScreenSpaceError",
value: mapConfig.maxScreenSpaceError,
})}
key: "maxScreenSpaceError",
value: mapConfig.maxScreenSpaceError,
})}
/>
<span className="gfx-settings__slider-value">{mapConfig.maxScreenSpaceError}</span>
</div>
@@ -159,6 +168,25 @@ export function GraphicsSettings() {
/>
</div>
{/* Weather Overlay */}
<div className="gfx-settings__row">
<span className="gfx-settings__label">Weather</span>
<select
className="gfx-settings__select"
value={mapConfig.weatherOverlay || ""}
onChange={(e) => {
const v = e.target.value || null;
update({ weatherOverlay: v });
trackEvent("graphics-setting", { key: "weatherOverlay", value: v || "off" });
}}
>
<option value="">Off</option>
{WEATHER_LAYERS.map((id) => (
<option key={id} value={id}>{WEATHER_LABEL[id] ?? id}</option>
))}
</select>
</div>
{/* Show FPS */}
<div className="gfx-settings__row">
<span className="gfx-settings__label">Show FPS</span>
@@ -174,9 +202,9 @@ export function GraphicsSettings() {
className="btn"
style={{ width: "100%", height: 32 }}
onClick={() => {
update({ ...DEFAULT_GRAPHICS });
trackEvent("graphics-setting-reset");
}}
update({ ...DEFAULT_GRAPHICS });
trackEvent("graphics-setting-reset");
}}
>
Reset to Defaults
</button>
+12 -3
View File
@@ -61,17 +61,26 @@ function TrustBadge({ trust }: { trust: string }) {
// ─── Browse Link ────────────────────────────────────────────
const MARKETPLACE_BASE = process.env.NEXT_PUBLIC_MARKETPLACE_URL ?? "https://marketplace.worldwideview.dev";
function BrowseLink() {
function handleClick(e: React.MouseEvent<HTMLAnchorElement>) {
e.preventDefault();
trackEvent("marketplace-browse-click");
const url = `${MARKETPLACE_BASE}?from_instance=${encodeURIComponent(window.location.origin)}`;
window.open(url, "_blank", "noopener,noreferrer");
}
return (
<a
href="https://marketplace.worldwideview.dev"
href={MARKETPLACE_BASE}
target="_blank"
rel="noopener noreferrer"
className="plugins-tab__browse"
onClick={() => trackEvent("marketplace-browse-click")}
data-testid="browse-plugins-btn"
onClick={handleClick}
>
<ExternalLink size={14} />
Marketplace
Browse Plugins
</a>
);
}
+9 -1
View File
@@ -146,7 +146,7 @@ label: label || "Camera Stream",
// For random third-party iframe providers, proxy their HTML to bypass X-Frame-Options/CSP restrictions.
// We exclude major platforms (YouTube, Twitch, Vimeo) because they officially support embedding
// and their complex players might break if HTML is proxied.
const majorPlatformHosts = ["youtube.com", "youtu.be", "twitch.tv", "vimeo.com"];
const majorPlatformHosts = ["youtube.com", "youtu.be", "youtube-nocookie.com", "twitch.tv", "vimeo.com"];
let isMajorPlatformHost = false;
try {
const { hostname } = new URL(embedUrl);
@@ -163,9 +163,17 @@ label: label || "Camera Stream",
embedUrl = getProxiedIframeUrl(embedUrl);
}
// Proxied iframes are served from our own origin, so without sandboxing the
// upstream HTML could reach window.parent and exfiltrate localStorage / DOM.
// Omit allow-same-origin so the iframe gets a unique opaque origin; scripts
// still run (video players keep working) but cannot touch the host app.
// Major platforms (YouTube/Twitch/Vimeo) bypass the proxy and load from their
// own cross-origin host, where the browser's same-origin policy already isolates them.
const isProxiedIframe = !isMajorPlatformHost;
return (
<iframe
src={embedUrl}
sandbox={isProxiedIframe ? "allow-scripts allow-presentation" : undefined}
style={{
position: "absolute", inset: 0, width: "100%", height: "100%", border: "none"
}}
+5 -1
View File
@@ -207,7 +207,11 @@ class WebSocketClient {
engine.subscriptions.add(pluginId);
this.connectEngine(engineUrl);
this.send(engine, { action: "subscribe", pluginId });
// Only send immediately if auth is not in-flight; the welcome handler will
// replay all pending subscriptions once auth succeeds (see onmessage:121-124).
if (!engine.awaitingWelcome) {
this.send(engine, { action: "subscribe", pluginId });
}
}
public unsubscribe(pluginId: string, engineUrl: string) {
+53 -2
View File
@@ -6,6 +6,8 @@ import {
SceneMode,
Cesium3DTileset,
Cesium3DTileStyle,
Terrain,
UrlTemplateImageryProvider,
createOsmBuildingsAsync
} from "cesium";
import { useStore } from "@/core/state/store";
@@ -17,13 +19,15 @@ export function useImageryManager(viewerInstance: CesiumViewer | null, viewerRea
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
const sceneMode = useStore((s) => s.mapConfig.sceneMode);
const showOsmBuildings = useStore((s) => s.mapConfig.showOsmBuildings);
const weatherOverlay = useStore((s) => s.mapConfig.weatherOverlay);
// Resolve runtime truth:
const activeLayerId = fallbackLayerId || baseLayerId;
const currentImageryLayerRef = useRef<ImageryLayer | null>(null);
// const googleTilesetRef = useRef<Cesium3DTileset | null>(null);
const osmBuildingsRef = useRef<Cesium3DTileset | null>(null);
const terrainActiveRef = useRef(false);
const weatherLayerRef = useRef<ImageryLayer | null>(null);
// 1. Manage Scene Mode (2D / 3D / Columbus)
useEffect(() => {
@@ -112,9 +116,24 @@ export function useImageryManager(viewerInstance: CesiumViewer | null, viewerRea
updateImagery();
}, [viewer, viewerReady, baseLayerId, fallbackLayerId]);
// 3. Manage OSM 3D Buildings (only in 3D mode, not with Google Photorealistic tiles)
// 3. Enable Cesium World Terrain for non-Google 3D mode.
// depthTestAgainstTerrain is already true (useViewerInitialization) and OSM 3D
// Buildings store absolute WGS84 heights including terrain elevation — both need
// real terrain. Without it the globe is a smooth ellipsoid, buildings float, and
// depth clipping is inaccurate. In Google 3D mode globe.show is false so the
// terrain provider is irrelevant; no need to tear it down on mode switch.
const isGoogle3D = activeLayerId === "google-3d";
const is3DMode = sceneMode === 3;
useEffect(() => {
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
if (isGoogle3D || !is3DMode || terrainActiveRef.current) return;
viewer.scene.setTerrain(Terrain.fromWorldTerrain());
terrainActiveRef.current = true;
}, [viewer, viewerReady, isGoogle3D, is3DMode]);
// 4. Manage OSM 3D Buildings (only in 3D mode, not with Google Photorealistic tiles)
useEffect(() => {
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
@@ -148,6 +167,38 @@ export function useImageryManager(viewerInstance: CesiumViewer | null, viewerRea
}
}, [viewer, viewerReady, isGoogle3D, is3DMode, showOsmBuildings]);
// 4. Manage Weather Overlay (semi-transparent tile layer on top of base imagery)
useEffect(() => {
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
if (!weatherOverlay) return;
let layer: ImageryLayer | null = null;
try {
const provider = new UrlTemplateImageryProvider({
url: `/api/weather/tile/{z}/{x}/{y}?layer=${weatherOverlay}`,
});
layer = new ImageryLayer(provider, { alpha: 0.6 });
} catch (err) {
console.warn("[useImageryManager] Failed to load weather overlay:", err);
return;
}
if (viewer.isDestroyed()) return;
viewer.imageryLayers.add(layer);
weatherLayerRef.current = layer;
return () => {
if (layer && !viewer.isDestroyed()) {
viewer.imageryLayers.remove(layer);
if (weatherLayerRef.current === layer) {
weatherLayerRef.current = null;
}
}
};
}, [viewer, viewerReady, weatherOverlay]);
return {
isGoogle3D
};
+3
View File
@@ -63,6 +63,8 @@ export interface MapConfig {
sceneMode: 1 | 2 | 3;
/** Whether OSM 3D Buildings are shown on non-Google imagery layers. */
showOsmBuildings: boolean;
/** Active weather overlay layer ID, or null if disabled. */
weatherOverlay: string | null;
}
/**
@@ -111,6 +113,7 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
fallbackLayerId: null,
sceneMode: 3,
showOsmBuildings: true,
weatherOverlay: null,
},
updateDataConfig: (config) => set((state) => ({
dataConfig: { ...state.dataConfig, ...config },
+79 -14
View File
@@ -1,4 +1,19 @@
import { describe, it, expect, afterEach } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
const { mockUndiciF, mockDnsLookup } = vi.hoisted(() => ({
mockUndiciF: vi.fn(),
mockDnsLookup: vi.fn(),
}));
vi.mock("dns/promises", () => ({
default: { lookup: mockDnsLookup },
}));
vi.mock("undici", async (importOriginal) => {
const original = await importOriginal<typeof import("undici")>();
return { ...original, fetch: mockUndiciF };
});
import { safeFetch, validateOrigin, isPrivateIP } from "./ssrf";
describe("SSRF Protection Utility", () => {
@@ -23,14 +38,19 @@ describe("SSRF Protection Utility", () => {
});
describe("validateOrigin", () => {
it("should allow valid https origins", () => {
it("should allow https origins", () => {
expect(validateOrigin("https://api.github.com/v1")).toBe(true);
});
it("should reject non-https protocols", () => {
expect(validateOrigin("http://api.github.com")).toBe(false);
it("should allow http origins (StreamProxy fetches HTTP camera feeds server-side)", () => {
expect(validateOrigin("http://camera.example.com/stream")).toBe(true);
});
it("should reject dangerous non-web protocols", () => {
expect(validateOrigin("ftp://api.github.com")).toBe(false);
expect(validateOrigin("file:///etc/passwd")).toBe(false);
expect(validateOrigin("data:text/html,<h1>xss</h1>")).toBe(false);
expect(validateOrigin("javascript:alert(1)")).toBe(false);
});
});
@@ -68,23 +88,68 @@ describe("SSRF Protection Utility", () => {
});
describe("safeFetch", () => {
const PUBLIC_IP = "93.184.216.34";
beforeEach(() => {
vi.clearAllMocks();
process.env.PROXY_HOST_ALLOWLIST = "*";
});
afterEach(() => {
delete process.env.PROXY_HOST_ALLOWLIST;
});
it("should reject private IPs immediately", async () => {
process.env.PROXY_HOST_ALLOWLIST = "*"; // bypass allowlist for these tests
await expect(safeFetch("https://127.0.0.1/data")).rejects.toThrow(/SSRF/);
await expect(safeFetch("https://169.254.169.254/latest/meta-data")).rejects.toThrow(/SSRF/);
});
it("should enforce size limits", async () => {
// Because safeFetch will attempt DNS lookup, we'd need to mock it if we wanted to test this in isolation.
// But since this is a unit test, we can trust the return is a standard fetch wrapped with size enforcement.
// The size limits are enforced on the stream pull.
const result = safeFetch;
expect(typeof result).toBe("function");
it("should reject dangerous protocols (ftp, file, etc.)", async () => {
await expect(safeFetch("ftp://camera.example.com/stream")).rejects.toThrow(/SSRF.*protocol/i);
await expect(safeFetch("file:///etc/passwd")).rejects.toThrow(/SSRF.*protocol/i);
});
it("should use undici dispatcher to pin the DNS resolution", async () => {
// Again, a full mock is complex, but we know it now uses undici.
expect(true).toBe(true);
it("should accept HTTP URLs (StreamProxy use case — camera feeds)", async () => {
mockDnsLookup.mockResolvedValue({ address: PUBLIC_IP, family: 4 });
mockUndiciF.mockResolvedValueOnce(new Response("stream-data", { status: 200 }));
const response = await safeFetch("http://camera.example.com/stream");
expect(response.status).toBe(200);
});
it("enforces maxSize — responses exceeding the limit error on body read", async () => {
mockDnsLookup.mockResolvedValue({ address: PUBLIC_IP, family: 4 });
const oversized = new Uint8Array(11); // 11 bytes > 10-byte limit
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(oversized);
controller.close();
},
});
mockUndiciF.mockResolvedValueOnce(new Response(stream, { status: 200 }));
const response = await safeFetch("https://example.com/feed", { maxSize: 10 });
await expect(response.text()).rejects.toThrow(/size exceeded/);
});
it("uses undici dispatcher pinned to the resolved IP and does not follow redirects", async () => {
mockDnsLookup.mockResolvedValue({ address: PUBLIC_IP, family: 4 });
// safeFetch uses redirect:"manual" -- this 301 must not be followed
mockUndiciF.mockResolvedValueOnce(
new Response(null, { status: 301, headers: { Location: "https://evil-rebind.example.com" } })
);
const response = await safeFetch("https://example.com/feed");
// DNS resolved exactly once; redirect was NOT followed (fetch still once)
expect(mockDnsLookup).toHaveBeenCalledOnce();
expect(mockUndiciF).toHaveBeenCalledOnce();
expect(response.status).toBe(301);
// fetch was called with a dispatcher (undici Agent) and redirect:"manual"
const callOpts = mockUndiciF.mock.calls[0][1] as Record<string, unknown>;
expect(callOpts.dispatcher).toBeDefined();
expect(callOpts.redirect).toBe("manual");
});
});
});
+22 -2
View File
@@ -8,10 +8,19 @@ export function isPrivateIP(ip: string): boolean {
return false;
}
/**
* Validates that a URL uses a safe web protocol for server-side proxying.
* Both http: and https: are allowed -- the StreamProxy is a server-side bridge
* that fetches HTTP camera feeds and serves them over HTTPS to the browser,
* converting them to avoid browser mixed-content blocks. Blocking HTTP here
* would defeat the proxy's purpose. Real SSRF protection is provided by the
* private-IP check, DNS pinning, and the PROXY_HOST_ALLOWLIST below.
* Dangerous protocols (file://, ftp://, data://, javascript://, etc.) are rejected.
*/
export function validateOrigin(urlStr: string): boolean {
try {
const url = new URL(urlStr);
return url.protocol === "https:";
return url.protocol === "https:" || url.protocol === "http:";
} catch {
return false;
}
@@ -20,6 +29,8 @@ export function validateOrigin(urlStr: string): boolean {
interface FetchOptions extends RequestInit {
maxSize?: number;
timeout?: number;
/** Skip size accumulation for infinite streams (e.g. MJPEG). Duration is still bounded by `timeout`. */
streaming?: boolean;
}
function checkHostAllowlist(hostname: string): void {
@@ -48,7 +59,7 @@ export async function safeFetch(urlStr: string, options: FetchOptions = {}): Pro
checkHostAllowlist(hostForCheck);
if (!validateOrigin(urlStr)) {
throw new Error("SSRF Error: Invalid protocol. Only HTTPS is allowed.");
throw new Error("SSRF Error: Invalid protocol. Only HTTP and HTTPS are allowed.");
}
const url = new URL(urlStr);
@@ -95,6 +106,15 @@ export async function safeFetch(urlStr: string, options: FetchOptions = {}): Pro
const response = await fetch(urlStr, fetchOptions);
if (response.body) {
// For infinite streams (e.g. MJPEG), skip size accumulation — pipe directly.
// Duration is already bounded by the AbortController timeout above.
if (options.streaming) {
return new Response(response.body as unknown as BodyInit, {
status: response.status,
headers: response.headers as unknown as HeadersInit
});
}
let totalSize = 0;
const reader = response.body.getReader();
const stream = new ReadableStream({
+1 -1
View File
@@ -1,5 +1,5 @@
import Stripe from "stripe";
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "dummy_key", {
apiVersion: "2026-04-22.dahlia",
apiVersion: "2026-05-27.dahlia",
});
+17
View File
@@ -0,0 +1,17 @@
import { createBrowserClient } from '@supabase/ssr'
import { buildCookieOptions } from './cookieOptions'
/**
* Supabase client for browser/client-component code.
* `createBrowserClient` is a singleton by default, so repeated calls are cheap.
*
* Supports both NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY (preferred) and the legacy
* NEXT_PUBLIC_SUPABASE_ANON_KEY name for backwards compatibility.
*/
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookieOptions: buildCookieOptions() },
)
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Cross-subdomain session cookies (ADR-003).
*
* The cookie `domain` must be `.worldwideview.dev` in production and `.wwv.local`
* in local dev (with hosts-file entries) so every subdomain shares the Supabase
* session. When no domain is configured the attribute is omitted — browsers reject
* an explicit `domain` on a bare `localhost` host.
*/
export function resolveCookieDomain(raw: string | undefined): string | undefined {
const trimmed = raw?.trim()
return trimmed ? trimmed : undefined
}
export function buildCookieOptions() {
return {
domain: resolveCookieDomain(process.env.NEXT_PUBLIC_WWV_COOKIE_DOMAIN),
path: '/',
sameSite: 'lax' as const,
secure: true,
httpOnly: true,
}
}
+44
View File
@@ -0,0 +1,44 @@
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { buildCookieOptions } from './cookieOptions'
/**
* Supabase client for Server Components, Server Actions, and Route Handlers.
* A fresh client is created per request — never share it across requests.
*
* Supports both NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY (preferred) and the legacy
* NEXT_PUBLIC_SUPABASE_ANON_KEY name for backwards compatibility.
*/
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookieOptions: buildCookieOptions(),
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
)
} catch {
// setAll throws when called from a Server Component render —
// the middleware refreshes and writes the session cookie instead.
}
},
},
},
)
}
/** Returns the authenticated Supabase user, or null if not signed in. */
export async function getSupabaseUser() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
return user
}
+28
View File
@@ -0,0 +1,28 @@
// Characters that don't decompose to a base ASCII letter via NFD normalization.
const SUPPLEMENTAL_MAP: Record<string, string> = {
"Đ": "D", "đ": "d", // Đ đ
"Ø": "O", "ø": "o", // Ø ø
"Ł": "L", "ł": "l", // Ł ł
"Ð": "D", "ð": "d", // Ð ð
"Þ": "Th", "þ": "th", // Þ þ
"ß": "ss", // ß
"Æ": "AE", "æ": "ae", // Æ æ
"Œ": "OE", "œ": "oe", // Œ œ
};
/**
* Replaces diacritical characters with their closest ASCII equivalents so that
* place and airport names remain readable even in environments where the font
* or encoding does not support the original glyphs (e.g. Š→S, Č→C, Ž→Z).
*/
export function transliterate(text: string): string {
return (
text
// Decompose characters like Š into base letter + combining mark (e.g. S + caron)
.normalize("NFD")
// Strip all Unicode combining diacritical marks (U+0300–U+036F)
.replace(/[̀-ͯ]/g, "")
// Replace any remaining non-ASCII characters using the supplemental map
.replace(/[^\x00-\x7F]/g, (ch) => SUPPLEMENTAL_MAP[ch] ?? ch)
);
}
+13
View File
@@ -0,0 +1,13 @@
export const WEATHER_LAYERS = [
"clouds_new",
"precipitation_new",
"pressure_new",
"wind_new",
"temp_new",
] as const;
export type WeatherLayer = (typeof WEATHER_LAYERS)[number];
export function isValidWeatherLayer(layer: string): layer is WeatherLayer {
return (WEATHER_LAYERS as readonly string[]).includes(layer);
}
+2 -1
View File
@@ -6,6 +6,7 @@
import type { GeoEntity } from "@/core/plugins/PluginTypes";
import type { GeoJsonFeature, GeoJsonGeometry } from "@/types/geojson";
import { transliterate } from "@/lib/utils/transliterate";
/** Extract a representative [lat, lon, alt?] from any geometry. */
function representativePoint(
@@ -50,7 +51,7 @@ export function featuresToEntities(
longitude: point.lon,
altitude: point.alt,
timestamp: new Date(),
label: (feature.properties.name as string) ?? undefined,
label: feature.properties.name ? transliterate(feature.properties.name as string) : undefined,
properties: {
...feature.properties,
_layerId: layerId,
+64
View File
@@ -0,0 +1,64 @@
// @vitest-environment node
import {
beforeEach, describe, expect, it, vi
} from "vitest";
import { GET } from "@/app/api/weather/layers/route";
describe("/api/weather/layers", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("returns available layers with tile URL when configured", async () => {
vi.stubEnv("OPENWEATHERMAP_API_KEY", "test-key-123");
const response = await GET();
const json = await response.json();
expect(response.status).toBe(200);
expect(json.configured).toBe(true);
expect(json.tileUrlTemplate).toBe("/api/weather/tile/{z}/{x}/{y}?layer={layer}");
expect(json.layers).toHaveLength(5);
});
it("returns all expected layer IDs", async () => {
vi.stubEnv("OPENWEATHERMAP_API_KEY", "test-key-123");
const response = await GET();
const json = await response.json();
const ids = json.layers.map((l: any) => l.id);
expect(ids).toEqual([
"clouds_new",
"precipitation_new",
"pressure_new",
"wind_new",
"temp_new",
]);
});
it("each layer has id, name, and description", async () => {
vi.stubEnv("OPENWEATHERMAP_API_KEY", "test-key-123");
const response = await GET();
const json = await response.json();
for (const layer of json.layers) {
expect(typeof layer.id).toBe("string");
expect(typeof layer.name).toBe("string");
expect(typeof layer.description).toBe("string");
}
});
it("returns configured=false and null tile URL when key is missing", async () => {
vi.stubEnv("OPENWEATHERMAP_API_KEY", "");
const response = await GET();
const json = await response.json();
expect(response.status).toBe(200);
expect(json.configured).toBe(false);
expect(json.tileUrlTemplate).toBeNull();
expect(json.layers).toHaveLength(5);
});
});
+201
View File
@@ -0,0 +1,201 @@
// @vitest-environment node
import {
beforeEach, describe, expect, it, vi
} from "vitest";
import { GET } from "@/app/api/weather/tile/[z]/[x]/[y]/route";
import { NextRequest } from "next/server";
function makeRequest(layer: string | null, z = "3", x = "4", y = "2") {
const url = new URL(`http://localhost/api/weather/tile/${z}/${x}/${y}`);
if (layer !== null) url.searchParams.set("layer", layer);
const req = new NextRequest(url);
const params = Promise.resolve({ z, x, y });
return { req, params };
}
const fakePng = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
describe("/api/weather/tile/[z]/[x]/[y]", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.stubEnv("OPENWEATHERMAP_API_KEY", "test-key-123");
});
it("proxies a valid tile request and returns PNG", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => fakePng.buffer,
}));
const { req, params } = makeRequest("precipitation_new");
const response = await GET(req, { params });
expect(response.status).toBe(200);
expect(response.headers.get("Content-Type")).toBe("image/png");
const body = new Uint8Array(await response.arrayBuffer());
expect(body[0]).toBe(0x89);
expect(body[1]).toBe(0x50);
});
it("passes correct URL to upstream", async () => {
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => fakePng.buffer,
});
vi.stubGlobal("fetch", mockFetch);
const { req, params } = makeRequest("wind_new", "5", "10", "12");
await GET(req, { params });
expect(mockFetch).toHaveBeenCalledWith(
"https://tile.openweathermap.org/map/wind_new/5/10/12.png?appid=test-key-123",
expect.objectContaining({
headers: { "User-Agent": "WorldWideView/1.0" },
}),
);
});
it("returns 400 when layer param is missing", async () => {
const { req, params } = makeRequest(null);
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toContain("Invalid layer");
});
it("returns 400 for an invalid layer name", async () => {
const { req, params } = makeRequest("invalid_layer");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toContain("Invalid layer");
});
it("returns 400 for negative tile coordinates", async () => {
const { req, params } = makeRequest("clouds_new", "-1", "0", "0");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toBe("Invalid tile coordinates");
});
it("returns 400 for non-integer tile coordinates", async () => {
const { req, params } = makeRequest("clouds_new", "1.5", "0", "0");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toBe("Invalid tile coordinates");
});
it("returns 400 for non-numeric tile coordinates", async () => {
const { req, params } = makeRequest("clouds_new", "abc", "0", "0");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toBe("Invalid tile coordinates");
});
it("returns 400 when x/y exceed max for zoom level", async () => {
// At zoom 0, only tile (0,0) is valid (2^0 = 1)
const { req, params } = makeRequest("clouds_new", "0", "1", "0");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toBe("Invalid tile coordinates");
});
it("returns 400 when zoom exceeds max supported level", async () => {
const { req, params } = makeRequest("clouds_new", "19", "0", "0");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(400);
expect(json.error).toBe("Invalid tile coordinates");
});
it("accepts max valid tile coordinates for zoom level", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => fakePng.buffer,
}));
// At zoom 2, valid range is 0..3 (2^2 = 4)
const { req, params } = makeRequest("clouds_new", "2", "3", "3");
const response = await GET(req, { params });
expect(response.status).toBe(200);
});
it("returns 503 when API key is not configured", async () => {
vi.stubEnv("OPENWEATHERMAP_API_KEY", "");
const { req, params } = makeRequest("clouds_new");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(503);
expect(json.error).toBe("Weather API not configured");
});
it("returns 502 when upstream returns non-ok status", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: false,
status: 500,
}));
const { req, params } = makeRequest("temp_new");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(502);
expect(json.error).toBe("Failed to fetch weather tile");
});
it("returns 502 when fetch throws a network error", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(
new Error("Network error"),
));
const { req, params } = makeRequest("pressure_new");
const response = await GET(req, { params });
const json = await response.json();
expect(response.status).toBe(502);
expect(json.error).toBe("Failed to fetch weather tile");
});
it("sets correct cache headers on success", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => fakePng.buffer,
}));
const { req, params } = makeRequest("clouds_new");
const response = await GET(req, { params });
expect(response.headers.get("Cache-Control")).toBe(
"public, max-age=600, stale-while-revalidate=300",
);
});
it("accepts all valid layer names", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => fakePng.buffer,
}));
const layers = ["clouds_new", "precipitation_new", "pressure_new", "wind_new", "temp_new"];
for (const layer of layers) {
const { req, params } = makeRequest(layer);
const response = await GET(req, { params });
expect(response.status).toBe(200);
}
});
});
+208
View File
@@ -0,0 +1,208 @@
import { test, expect } from '@playwright/test';
/**
* Marketplace instance auto-discovery E2E tests.
*
* Two test groups:
*
* 1. "capture side" — navigates directly to the marketplace with
* ?from_instance=... and verifies InstanceCapture stores it.
* Runs with playwright.marketplace.config.ts (no worldwideview / Docker needed).
*
* 2. "full flow" — opens worldwideview, clicks Browse Plugins, and verifies
* the marketplace receives the param. Needs the main playwright.config.ts
* (Docker + Postgres required for auth).
*/
const MARKETPLACE_URL = 'http://localhost:3002';
const WWV_ORIGIN = 'http://localhost:3001';
const FROM_INSTANCE_PARAM = `from_instance=${encodeURIComponent(WWV_ORIGIN)}`;
// ─── Marketplace capture side (no worldwideview auth needed) ────────────────
test.describe('InstanceCapture — marketplace receives from_instance', () => {
test('captures valid origin, writes localStorage, cleans URL', async ({ page }) => {
// Navigate as the marketplace would be opened by worldwideview.
// InstanceCapture runs during React hydration (useEffect), so by the time
// page.goto() resolves the URL may already be clean — that is correct behavior.
await page.goto(`${MARKETPLACE_URL}/?${FROM_INSTANCE_PARAM}`);
// Wait for InstanceCapture to write to localStorage (may already be set)
await page.waitForFunction(
() => localStorage.getItem('wwv_instance_url') !== null,
{ timeout: 15000 }
);
// localStorage has the correct origin-only value
const stored = await page.evaluate(() => localStorage.getItem('wwv_instance_url'));
expect(stored).toBe(WWV_ORIGIN);
// from_instance param was stripped by history.replaceState
expect(page.url()).not.toContain('from_instance');
});
test('rejects javascript: protocol and leaves localStorage empty', async ({ page }) => {
// Clear any prior localStorage from the same origin
await page.goto(MARKETPLACE_URL);
await page.evaluate(() => localStorage.removeItem('wwv_instance_url'));
await page.goto(`${MARKETPLACE_URL}/?from_instance=${encodeURIComponent('javascript:alert(1)')}`);
// Give InstanceCapture time to run
await page.waitForTimeout(1500);
const stored = await page.evaluate(() => localStorage.getItem('wwv_instance_url'));
expect(stored).toBeNull();
});
test('rejects self-referential origin and leaves localStorage empty', async ({ page }) => {
await page.goto(MARKETPLACE_URL);
await page.evaluate(() => localStorage.removeItem('wwv_instance_url'));
// from_instance points at the marketplace itself — should be rejected
await page.goto(`${MARKETPLACE_URL}/?from_instance=${encodeURIComponent(MARKETPLACE_URL)}`);
await page.waitForTimeout(1500);
const stored = await page.evaluate(() => localStorage.getItem('wwv_instance_url'));
expect(stored).toBeNull();
});
test('direct navigation without param leaves localStorage unchanged', async ({ page }) => {
await page.goto(MARKETPLACE_URL);
await page.evaluate(() => localStorage.removeItem('wwv_instance_url'));
await page.reload();
await page.waitForLoadState('load');
await page.waitForTimeout(1000);
const stored = await page.evaluate(() => localStorage.getItem('wwv_instance_url'));
expect(stored).toBeNull();
});
});
// ─── Linked-instance API surface (anonymous, marketplace-only) ──────────────
test.describe('linked-instance API — anonymous surface', () => {
test('GET /api/instances returns 401 when no session cookie', async ({ request }) => {
const res = await request.get(`${MARKETPLACE_URL}/api/instances`);
expect(res.status()).toBe(401);
const body = await res.json();
expect(body).toEqual({ error: 'unauthenticated' });
});
test('POST /api/instances/link returns 401 when anonymous (fire-and-forget safe)', async ({ request }) => {
const res = await request.post(`${MARKETPLACE_URL}/api/instances/link`, {
data: { url: WWV_ORIGIN },
headers: { 'content-type': 'application/json' },
});
expect(res.status()).toBe(401);
});
test('GET /api/install/start with no session 302s to AUTH_HOST/login?next=...', async ({ request }) => {
const installUrl = new URL(`${MARKETPLACE_URL}/api/install/start`);
installUrl.searchParams.set('pluginId', 'aviation');
installUrl.searchParams.set('version', '1.0.0');
installUrl.searchParams.set('manifest', 'eyJpZCI6ImF2aWF0aW9uIn0='); // {"id":"aviation"}
installUrl.searchParams.set('instanceUrl', WWV_ORIGIN);
installUrl.searchParams.set('redirectTo', `${MARKETPLACE_URL}/browse/aviation`);
const res = await request.get(installUrl.toString(), { maxRedirects: 0 });
expect(res.status()).toBe(307);
const location = res.headers().location ?? '';
expect(location).toMatch(/\/login\?next=/);
// The next param should round-trip the entire install/start URL
const next = new URL(location).searchParams.get('next');
expect(next).toContain('/api/install/start');
expect(next).toContain('pluginId=aviation');
});
test('POST /api/install/start with javascript: scheme returns 400 before auth check', async ({ request }) => {
// The validator runs before the auth gate, so this should 400 even anonymous
const installUrl = new URL(`${MARKETPLACE_URL}/api/install/start`);
installUrl.searchParams.set('pluginId', 'aviation');
installUrl.searchParams.set('version', '1.0.0');
installUrl.searchParams.set('manifest', 'eyJpZCI6ImF2aWF0aW9uIn0=');
installUrl.searchParams.set('instanceUrl', 'javascript:alert(1)');
installUrl.searchParams.set('redirectTo', `${MARKETPLACE_URL}/browse/aviation`);
const res = await request.get(installUrl.toString(), { maxRedirects: 0 });
expect(res.status()).toBe(400);
});
});
// ─── InstanceCapture → server-link fire-and-forget ──────────────────────────
test.describe('InstanceCapture also POSTs to /api/instances/link', () => {
test('fires a link POST after writing localStorage', async ({ page }) => {
// Spy on the outgoing POST. The server will 401 (we're anonymous) and
// the InstanceCapture promise swallows that — we just want to confirm
// the request was made, not that it succeeded.
const linkPromise = page.waitForRequest(
(req) => req.url().endsWith('/api/instances/link') && req.method() === 'POST',
{ timeout: 10000 },
);
await page.goto(`${MARKETPLACE_URL}/?${FROM_INSTANCE_PARAM}`);
const req = await linkPromise;
const body = JSON.parse(req.postData() ?? '{}');
expect(body).toEqual({ url: WWV_ORIGIN });
});
});
// ─── Full flow (worldwideview → marketplace, requires Docker + auth) ─────────
test.describe('Full flow — Browse Plugins in worldwideview opens marketplace', () => {
test.beforeEach(async ({ page, baseURL }) => {
// Skip when running with the marketplace-only config (baseURL = 3002)
test.skip(baseURL !== WWV_ORIGIN, 'Requires worldwideview running (main config + Docker)');
await page.goto('/');
await page.waitForSelector('[data-testid="app-ready"]', { state: 'attached', timeout: 45000 });
// Dismiss unverified plugin dialog if it appears
try {
const installBtn = page.getByRole('button', { name: /Install Selected/ });
await installBtn.waitFor({ state: 'visible', timeout: 2000 });
await installBtn.click();
} catch { /* not present */ }
// Ensure left panel is open
const leftToggle = page.locator('[data-testid="panel-toggle-left"]');
const isOpen = await leftToggle.evaluate((el) => el.classList.contains('panel-toggle-btn--open'));
if (!isOpen) await leftToggle.click();
});
test('Browse Plugins appends from_instance and marketplace captures it', async ({ page }) => {
// Navigate to Plugins tab
const pluginsTab = page.locator('button.panel-tab[title="Plugins"]');
await expect(pluginsTab).toBeVisible({ timeout: 10000 });
await pluginsTab.click();
const browseBtn = page.locator('[data-testid="browse-plugins-btn"]');
await expect(browseBtn).toBeVisible({ timeout: 5000 });
// Click and capture the popup
const popupPromise = page.waitForEvent('popup');
await browseBtn.click();
const popup = await popupPromise;
// Initial URL has from_instance
expect(popup.url()).toContain(FROM_INSTANCE_PARAM);
// InstanceCapture writes to localStorage
await popup.waitForFunction(
() => localStorage.getItem('wwv_instance_url') !== null,
{ timeout: 15000 }
);
const stored = await popup.evaluate(() => localStorage.getItem('wwv_instance_url'));
expect(stored).toBe(WWV_ORIGIN);
// URL cleaned up
expect(popup.url()).not.toContain('from_instance');
await popup.close();
});
});
@@ -0,0 +1,55 @@
import { test, expect } from '@playwright/test';
/**
* Cross-origin redirect handshake specs (REQ-16).
*
* Verifies that unauthenticated marketplace visitors are redirected to the
* auth host with the correct next= param, and that after login they are
* returned to the exact marketplace page they started from.
*
* Requires:
* - worldwideview-web running on https://wwv.local:3001
* - worldwideview-marketplace running on https://marketplace.wwv.local:3002
* - .env.test with PLAYWRIGHT_TEST_EMAIL and PLAYWRIGHT_TEST_PASSWORD
*
* Run with:
* pnpm exec playwright test --config=playwright.cross-app.config.ts
*/
const WEB_URL = 'https://wwv.local:3001';
const MARKETPLACE_URL = 'https://marketplace.wwv.local:3002';
const TEST_EMAIL = process.env.PLAYWRIGHT_TEST_EMAIL!;
const TEST_PASSWORD = process.env.PLAYWRIGHT_TEST_PASSWORD!;
test.describe('marketplace redirect handshake', () => {
test('Sign in from /browse preserves current page as next= param', async ({ page }) => {
await page.goto(`${MARKETPLACE_URL}/browse`);
// Click the Sign in link in the marketplace header
await page.getByRole('link', { name: 'Sign in' }).click();
// Must land on the auth host login page
await page.waitForURL(`${WEB_URL}/**`, { timeout: 15000 });
// The next= param must encode the full /browse URL
expect(page.url()).toContain(`next=${encodeURIComponent(`${MARKETPLACE_URL}/browse`)}`);
});
test('Login redirects back to original marketplace page', async ({ page }) => {
// Start on /browse and click Sign in (same as first test)
await page.goto(`${MARKETPLACE_URL}/browse`);
await page.getByRole('link', { name: 'Sign in' }).click();
await page.waitForURL(`${WEB_URL}/**`, { timeout: 15000 });
// Fill and submit the login form on the auth host
await page.fill('input[name="email"]', TEST_EMAIL);
await page.fill('input[name="password"]', TEST_PASSWORD);
await page.click('button[type="submit"]');
// Must be redirected back to the original marketplace page
await page.waitForURL(`${MARKETPLACE_URL}/browse**`, { timeout: 15000 });
// Sign in link must no longer be visible (indicates authenticated state)
await expect(page.getByRole('link', { name: 'Sign in' })).not.toBeVisible();
});
});
+53
View File
@@ -0,0 +1,53 @@
import { test, expect } from '@playwright/test';
/**
* Marketplace sign-out spec (REQ-16).
*
* Verifies that signing out from the marketplace avatar dropdown:
* 1. Redirects the user to marketplace home
* 2. Makes the Sign in link visible again
* 3. Clears the Supabase session (GET /api/instances returns 401)
*
* Requires:
* - worldwideview-web running on https://wwv.local:3001
* - worldwideview-marketplace running on https://marketplace.wwv.local:3002
* - .env.test with PLAYWRIGHT_TEST_EMAIL and PLAYWRIGHT_TEST_PASSWORD
*
* Run with:
* pnpm exec playwright test --config=playwright.cross-app.config.ts
*/
const WEB_URL = 'https://wwv.local:3001';
const MARKETPLACE_URL = 'https://marketplace.wwv.local:3002';
const TEST_EMAIL = process.env.PLAYWRIGHT_TEST_EMAIL!;
const TEST_PASSWORD = process.env.PLAYWRIGHT_TEST_PASSWORD!;
test.describe('marketplace sign-out', () => {
test('sign out from avatar dropdown returns to marketplace home and clears session', async ({ page }) => {
// ── Establish authenticated session ──────────────────────────────────
await page.goto(`${MARKETPLACE_URL}/`);
await page.getByRole('link', { name: 'Sign in' }).click();
await page.waitForURL(`${WEB_URL}/**`, { timeout: 15000 });
await page.fill('input[name="email"]', TEST_EMAIL);
await page.fill('input[name="password"]', TEST_PASSWORD);
await page.click('button[type="submit"]');
// Wait for redirect back to marketplace after login
await page.waitForURL(`${MARKETPLACE_URL}/**`, { timeout: 15000 });
// ── Open avatar dropdown and click Sign Out ──────────────────────────
await page.locator('[aria-haspopup="true"]').click();
await page.getByRole('menuitem', { name: 'Sign Out' }).click();
// ── Assert redirect to marketplace home ──────────────────────────────
await page.waitForURL(`${MARKETPLACE_URL}/`, { timeout: 10000 });
// Sign in link must be visible again (session cleared on client)
await expect(page.getByRole('link', { name: 'Sign in' })).toBeVisible();
// ── Assert session is cleared on the server ──────────────────────────
const res = await page.request.get(`${MARKETPLACE_URL}/api/instances`);
expect(res.status()).toBe(401);
});
});
+72
View File
@@ -0,0 +1,72 @@
import { test, expect } from '@playwright/test';
// baseURL is set to https://wwv.local:3001 in playwright.web.config.ts.
// All page.goto() calls use relative paths.
// ─── /auth/reset-password ────────────────────────────────────────────────────
test.describe('/auth/reset-password', () => {
test('page renders the request form', async ({ page }) => {
await page.goto('/auth/reset-password');
await expect(page.getByRole('heading', { name: 'Reset Password' })).toBeVisible();
await expect(page.getByRole('textbox', { name: /email/i })).toBeVisible();
await expect(page.getByRole('button', { name: 'Send Reset Link' })).toBeVisible();
});
test('submit transitions to inline success state on same page', async ({ page }) => {
await page.goto('/auth/reset-password');
await page.getByRole('textbox', { name: /email/i }).fill('[email protected]');
await page.getByRole('button', { name: 'Send Reset Link' }).click();
// The server action calls Supabase resetPasswordForEmail; this will likely error in
// the test environment (no real Supabase creds). Handle both outcomes:
// - If success: heading changes to "Check Your Email"
// - If error: inline error message appears (not a crash / blank page)
const successHeading = page.getByRole('heading', { name: 'Check Your Email' });
const errorText = page.locator('[role="alert"]');
await expect(successHeading.or(errorText)).toBeVisible({ timeout: 10000 });
});
});
// ─── /accounts unauthenticated redirect ──────────────────────────────────────
test.describe('/accounts', () => {
test('unauthenticated visit redirects to /login', async ({ page }) => {
// Navigate to /accounts with no session cookie.
// The page.tsx server component calls getClaims() and redirects if no session.
await page.goto('/accounts');
// Wait for navigation to settle; allow up to 10 seconds for the redirect chain.
await page.waitForURL('**/login**', { timeout: 10000 });
expect(page.url()).toContain('/login');
});
});
// ─── /auth/verify without a code ─────────────────────────────────────────────
test.describe('/auth/verify', () => {
test('visiting without a code param shows Verification Failed state', async ({ page }) => {
await page.goto('/auth/verify');
// The VerifyContent useEffect checks for searchParams.get('code').
// With no code, it immediately sets status to 'error'.
await expect(page.getByRole('heading', { name: 'Verification Failed' })).toBeVisible({ timeout: 10000 });
});
});
// ─── /auth/reset-password/confirm without a hash ─────────────────────────────
test.describe('/auth/reset-password/confirm', () => {
test('visiting without a recovery hash shows Link Expired after timeout', async ({ page }) => {
await page.goto('/auth/reset-password/confirm');
// The page waits up to 3 seconds for onAuthStateChange PASSWORD_RECOVERY.
// With no hash, the event never fires, so the 3s timer triggers setLinkError(true).
// Allow up to 8 seconds total (3s timer + render time + margin).
await expect(page.getByRole('heading', { name: 'Link Expired' })).toBeVisible({ timeout: 8000 });
});
});