Compare commits

...
15 changed files with 492 additions and 48 deletions

No files matched your search

+9
View File
@@ -36,6 +36,15 @@ Application code is **identical** across editions — always calls `auth()`, `si
---
## Decentralized Plugin Authentication (Token Exchange)
For cross-domain plugin communication (Local App connecting to Marketplace or Data Engines), WWV uses an **Asymmetric JWT Token Exchange (PKCE)** model.
- **PKCE Flow**: The Local App uses standard OAuth 2.0 PKCE to exchange a `code` for a long-lived API key from the Marketplace.
- **Token Exchange**: The Local App exchanges its long-lived API key for a short-lived, audience-bound JWT before connecting to a decentralized Data Engine.
- **WebSocket First-Message Auth**: Data Engines enforce a "First-Message Auth" pattern over WebSockets. The client MUST immediately send a `{ type: "auth", v: 1, token: "..." }` message upon opening the connection to prevent SSRF vulnerabilities and credential leakage.
---
## Registration & Auto-Provisioning
Registration: `app.worldwideview.dev/register`
+1
View File
@@ -36,6 +36,7 @@ Frontend runs at `http://localhost:3000`.
- **Framework**: Vitest with jsdom environment
- **Coverage**: `src/lib/**`, `src/core/**`, `src/plugins/**`
- **Run**: `pnpm test` (or `vitest run`)
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
## Security Headers
+6
View File
@@ -191,6 +191,12 @@ Plugins declare auth type in the manifest:
**Recommended for scale:** `token-exchange` — your server is never in the hot path for data requests.
### Shared Auth Contracts & Security Branding
When implementing the `token-exchange` flow or communicating across domains, all plugins and endpoints MUST use the strictly defined shared auth contracts from `@worldwideview/wwv-plugin-sdk/src/auth-contracts.ts` (e.g., `TokenExchangeRequest`, `WebSocketAuthMessage`).
**Sensitive Credentials**: All long-lived secrets (like API keys and tokens) MUST use the `SensitiveString` branded type and be instantiated via the `sensitive(str)` factory function. This prevents accidental logging/serialization and creates a single grep target for security audits.
---
## Plugin Development Workflows
+121
View File
@@ -0,0 +1,121 @@
name: Test Setup Scripts
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
permissions:
contents: read
jobs:
test-bash:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Start local HTTP server
run: |
python3 -m http.server 8080 &
sleep 2 # Wait for server to start
- name: Patch setup.sh to use local server
run: |
sed -i 's|https://raw.githubusercontent.com/silvertakana/worldwideview/main|http://localhost:8080|g' self-host/setup.sh
- name: Run setup.sh
run: |
cd self-host
bash setup.sh
- name: Verify .env generation
run: |
cd self-host
if [ ! -f .env ]; then
echo ".env file was not created"
exit 1
fi
if ! grep -q "^AUTH_SECRET=[a-f0-9]\{64\}$" .env; then
echo "AUTH_SECRET was not generated correctly or is missing"
exit 1
fi
- name: Verify docker-compose.yml download
run: |
cd self-host
if [ ! -f docker-compose.yml ]; then
echo "docker-compose.yml was not downloaded"
exit 1
fi
- name: Verify Docker containers are running
run: |
cd self-host
docker compose ps
if ! docker compose ps | grep -q "Up"; then
echo "Docker containers failed to start"
exit 1
fi
test-powershell:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Start local HTTP server
run: |
python3 -m http.server 8080 &
sleep 2 # Wait for server to start
- name: Patch setup.ps1 to use local server
run: |
sed -i 's|https://raw.githubusercontent.com/silvertakana/worldwideview/main|http://localhost:8080|g' self-host/setup.ps1
- name: Run setup.ps1
run: |
cd self-host
pwsh ./setup.ps1
- name: Verify .env generation
run: |
cd self-host
if [ ! -f .env ]; then
echo ".env file was not created"
exit 1
fi
if ! grep -q "^AUTH_SECRET=[a-f0-9]\{64\}$" .env; then
echo "AUTH_SECRET was not generated correctly or is missing"
exit 1
fi
- name: Verify docker-compose.yml download
run: |
cd self-host
if [ ! -f docker-compose.yml ]; then
echo "docker-compose.yml was not downloaded"
exit 1
fi
- name: Verify Docker containers are running
run: |
cd self-host
docker compose ps
if ! docker compose ps | grep -q "Up"; then
echo "Docker containers failed to start"
exit 1
fi
+2 -2
View File
@@ -87,13 +87,13 @@ WorldWideView uses a multi-stage Dockerfile designed for standalone output. To d
**Mac/Linux:**
```bash
mkdir worldwideview && cd worldwideview
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.sh | bash
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/setup.sh | bash
```
**Windows (PowerShell):**
```powershell
mkdir worldwideview; cd worldwideview
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.ps1 -UseBasicParsing | Invoke-Expression
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/setup.ps1 -UseBasicParsing | Invoke-Expression
```
> [!NOTE]
-36
View File
@@ -1,36 +0,0 @@
services:
wwv:
build:
context: .
args:
- NEXT_PUBLIC_WWV_EDITION=${NEXT_PUBLIC_WWV_EDITION:-local}
- NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=${NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL:-}
- NEXT_PUBLIC_SUPABASE_URL=${NEXT_PUBLIC_SUPABASE_URL:-}
- NEXT_PUBLIC_SUPABASE_ANON_KEY=${NEXT_PUBLIC_SUPABASE_ANON_KEY:-}
- NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=${NEXT_PUBLIC_GOOGLE_MAPS_API_KEY:-}
- NEXT_PUBLIC_BING_MAPS_KEY=${NEXT_PUBLIC_BING_MAPS_KEY:-}
- NEXT_PUBLIC_CESIUM_ION_TOKEN=${NEXT_PUBLIC_CESIUM_ION_TOKEN:-}
- NEXT_PUBLIC_ADSENSE_CLIENT_ID=${NEXT_PUBLIC_ADSENSE_CLIENT_ID:-}
pull_policy: build
ports:
- "3000:3000"
db:
profiles:
- "${WWV_SKIP_LOCAL_DB:-}"
ports:
- "5432:5432"
wwv-data-engine:
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/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:
- "5000:5000"
networks:
coolify:
external: true
+12 -6
View File
@@ -1,6 +1,5 @@
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
build:
context: .
args:
@@ -16,6 +15,7 @@ services:
- "3000:3000"
volumes:
- wwv-data:/app/data
- ./public/plugins-local:/app/public/plugins-local:ro
env_file:
- path: .env
required: false
@@ -55,20 +55,22 @@ services:
wwv-data-engine:
image: ghcr.io/silvertakana/wwv-data-engine:latest
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/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:
- "5000:5000"
environment:
- PORT=5000
- REDIS_URL=redis://wwv-redis:6379
- SEEDERS_DIR=/mnt/host/c/dev/worldwideview/local-seeders
- SKIP_SEEDER_DOWNLOAD=true
- SEEDERS_DIR=/app/seeders
- DB_PATH=/app/data/engine.db
depends_on:
wwv-redis:
condition: service_healthy
volumes:
- ../wwv-seeders:/mnt/host/c/dev/worldwideview/local-seeders/community
- ../wwv-seeders-private:/mnt/host/c/dev/worldwideview/local-seeders/private
restart: unless-stopped
profiles:
- engine
@@ -83,6 +85,10 @@ services:
profiles:
- engine
networks:
coolify:
external: true
volumes:
wwv-data:
postgres-data:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.9.2",
"version": "2.9.3",
"private": true,
"type": "module",
"packageManager": "[email protected]",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-sdk",
"version": "1.5.1",
"version": "1.6.0",
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -0,0 +1,92 @@
import { describe, it, expectTypeOf } from "vitest";
import type {
TokenExchangeRequest,
TokenExchangeResponse,
WebSocketAuthMessage,
SensitiveString,
Tier,
PKCEConnectRequest,
PKCETokenExchange,
PKCETokenExchangeResponse,
PluginJwtClaims,
AuthErrorResponse,
JWK,
JWKSResponse,
WebSocketMessage
} from "./auth-contracts";
describe("Auth Contracts", () => {
it("TokenExchangeRequest has exact required properties", () => {
expectTypeOf<TokenExchangeRequest>().toHaveProperty("apiKey").toEqualTypeOf<SensitiveString>();
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
// @ts-expect-error - missing required apiKey
const badReq: TokenExchangeRequest = { audience: "engine-123" };
});
it("TokenExchangeResponse has exact required properties", () => {
expectTypeOf<TokenExchangeResponse>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("expiresAt").toEqualTypeOf<number>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("kid").toEqualTypeOf<string>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
// @ts-expect-error - missing required token
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
});
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("type").toEqualTypeOf<"auth">();
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("v").toEqualTypeOf<1>();
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
// @ts-expect-error - missing version
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
// @ts-expect-error - wrong version
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
});
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
expectTypeOf<WebSocketMessage>().extract<{ type: "auth" }>().toEqualTypeOf<WebSocketAuthMessage>();
});
it("PKCEConnectRequest has correct snake_case shape", () => {
expectTypeOf<PKCEConnectRequest>().toHaveProperty("state").toEqualTypeOf<string>();
expectTypeOf<PKCEConnectRequest>().toHaveProperty("code_challenge").toEqualTypeOf<string>();
expectTypeOf<PKCEConnectRequest>().toHaveProperty("code_challenge_method").toEqualTypeOf<"S256">();
});
it("PKCETokenExchange implements RFC 7636 fields", () => {
expectTypeOf<PKCETokenExchange>().toHaveProperty("grant_type").toEqualTypeOf<"authorization_code">();
expectTypeOf<PKCETokenExchange>().toHaveProperty("redirect_uri").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("client_id").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("code").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("code_verifier").toEqualTypeOf<string>();
});
it("PKCETokenExchangeResponse has exact required properties", () => {
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("apiKey").toEqualTypeOf<SensitiveString>();
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("issuedAt").toEqualTypeOf<number | undefined>();
});
it("PluginJwtClaims structure matches requirements", () => {
expectTypeOf<PluginJwtClaims>().toHaveProperty("iss").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("aud").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("exp").toEqualTypeOf<number>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("jti").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("tier").toEqualTypeOf<Tier>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("plugins").toEqualTypeOf<string[] | undefined>();
});
it("JWKSResponse conforms to RFC 7517", () => {
expectTypeOf<JWKSResponse>().toHaveProperty("keys").toEqualTypeOf<JWK[]>();
expectTypeOf<JWK>().toHaveProperty("kty").toEqualTypeOf<string>();
expectTypeOf<JWK>().toHaveProperty("kid").toEqualTypeOf<string>();
});
it("AuthErrorResponse has basic OAuth error fields", () => {
expectTypeOf<AuthErrorResponse>().toHaveProperty("error").toEqualTypeOf<string>();
expectTypeOf<AuthErrorResponse>().toHaveProperty("error_description").toEqualTypeOf<string>();
});
});
@@ -0,0 +1,168 @@
/**
* @file auth-contracts.ts
* @description Shared contracts for Decentralized Plugin Authentication.
*/
/**
* A branded string type for sensitive credentials to prevent accidental logging or serialization.
*/
export type SensitiveString = string & { readonly __brand: "SensitiveString" };
/**
* Factory function to safely cast a string to a SensitiveString.
* This provides a single grep target for every place a secret enters the system.
*/
export const sensitive = (s: string): SensitiveString => s as SensitiveString;
/**
* The authorization tier of the plugin client.
*/
export type Tier = "basic" | "pro";
/**
* Payload sent by the Local App to the Marketplace to exchange a long-lived
* API key for a short-lived, audience-bound JWT.
*
* @see ADR-001 §2 "Asymmetric JWT Token Exchange"
*/
export interface TokenExchangeRequest {
/**
* The long-lived API key securely stored by the Local App
* @security Sensitive credential — must not be logged.
*/
apiKey: SensitiveString;
/** The specific Data Engine (audience) the Local App wants to connect to */
audience: string;
}
/**
* Payload returned by the Marketplace after a successful token exchange.
*
* @see ADR-001 §2 "Asymmetric JWT Token Exchange"
*/
export interface TokenExchangeResponse {
/** The JWT to attach to the WebSocket auth message */
token: SensitiveString;
/** Unix timestamp (ms) indicating when the token expires — so the Local App can refresh pre-emptively */
expiresAt: number;
/** Key id used to sign — useful when JWKS has multiple keys during rotation */
kid: string;
/** The entitlement tier of the client */
tier?: Tier;
}
/**
* Scaffold for a discriminated union of all possible WebSocket messages.
*/
export type WebSocketMessage = WebSocketAuthMessage; // | WebSocketSubscribeMessage | ...
/**
* First message sent by the Local App over the WebSocket to authenticate with the Data Engine.
*
* @see ADR-001 §4 "WebSocket Authentication Gating"
*/
export interface WebSocketAuthMessage {
type: "auth";
/** Protocol version to allow future wire shape evolution */
v: 1;
/** The short-lived JWT obtained from the Token Exchange */
token: SensitiveString;
}
/**
* Standard PKCE request shape during the initial connect flow.
* Note: snake_case fields below match RFC 7636 / RFC 6749 wire format.
*/
export interface PKCEConnectRequest {
/** Randomly generated state to prevent CSRF */
state: string;
/** The S256 hash of the code verifier */
code_challenge: string;
/** The challenge method (always "S256" for our implementation) */
code_challenge_method: "S256";
}
/**
* Standard PKCE exchange payload.
* Implements strict PKCE-protected Authorization Code Grant per RFC 7636.
* Note: snake_case fields below match RFC 7636 / RFC 6749 wire format.
*/
export interface PKCETokenExchange {
grant_type: "authorization_code";
redirect_uri: string;
client_id: string;
/** The authorization code received from the callback */
code: string;
/** The original unhashed verifier to prove possession */
code_verifier: string;
}
/**
* Payload returned by the Marketplace after a successful PKCE token exchange.
*/
export interface PKCETokenExchangeResponse {
/** The long-lived API key issued to the Local App */
apiKey: SensitiveString;
/** Tier surfaced so the Local App can show "Connected to X tier" in the UI */
tier?: Tier;
/** Optional issuance timestamp for future rotation/expiration logic */
issuedAt?: number;
}
/**
* The expected structure of the JWT claims after signature verification.
*/
export interface PluginJwtClaims {
/** Issuer (Marketplace URL) */
iss: string;
/** Subject (The plugin identifier or tenant ID) */
sub: string;
/** Audience (The specific Data Engine URL or ID) */
aud: string;
/** Expiration Time (Unix seconds) */
exp: number;
/** Not Before (Unix seconds) */
nbf: number;
/** Issued At (Unix seconds) */
iat: number;
/** JWT ID (Unique identifier for the token to prevent replay) */
jti: string;
/** The entitlement tier */
tier: Tier;
/**
* Optional array of allowed plugin namespace prefixes.
* @example ["wwv-plugin-aviation", "wwv-plugin-maritime-*"]
*/
plugins?: string[];
}
/**
* Standard error response shape for the auth API.
*/
export interface AuthErrorResponse {
/** Short error code (e.g., "invalid_grant", "rate_limit_exceeded") */
error: string;
/** Human-readable error description */
error_description: string;
}
/**
* JSON Web Key representing a single public key used to verify signatures.
* Mirrors the RFC 7517 shape.
*/
export interface JWK {
kty: string;
kid: string;
use?: string;
alg?: string;
n?: string;
e?: string;
[key: string]: unknown;
}
/**
* Expected shape of the /.well-known/jwks.json endpoint.
*/
export interface JWKSResponse {
keys: JWK[];
}
+3
View File
@@ -299,3 +299,6 @@ export type DataBusEvents = {
};
export * from "./viteGlobals";
// ─── Auth Contracts ──────────────────────────────────────────
export * from "./auth-contracts";
+74
View File
@@ -0,0 +1,74 @@
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
- ./public/plugins-local:/app/public/plugins-local:ro
env_file:
- path: .env
required: false
environment:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
- "DATABASE_URL=postgresql://postgres:postgres@db:5432/worldwideview?schema=public"
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
restart: unless-stopped
db:
image: postgres:15-alpine
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
interval: 5s
timeout: 5s
retries: 5
start_period: 60s
wwv-data-engine:
image: ghcr.io/silvertakana/wwv-data-engine:latest
ports:
- "5000:5000"
environment:
- PORT=5000
- REDIS_URL=redis://wwv-redis:6379
- SEEDERS_DIR=/app/seeders
- DB_PATH=/app/data/engine.db
depends_on:
wwv-redis:
condition: service_healthy
restart: unless-stopped
profiles:
- engine
wwv-redis:
image: redis:7-alpine
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 5s
timeout: 3s
retries: 5
profiles:
- engine
volumes:
wwv-data:
postgres-data:
+1 -1
View File
@@ -21,7 +21,7 @@ try {
# Generate docker-compose.yml
Write-Host "[*] Downloading docker-compose.yml..."
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/docker-compose.yml" -OutFile docker-compose.yml
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml" -OutFile docker-compose.yml
# Generate .env
if (-Not (Test-Path .env)) {
Executable → Regular
+1 -1
View File
@@ -19,7 +19,7 @@ fi
# 1. Download docker-compose.yml
echo "📦 Downloading docker-compose.yml..."
curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/silvertakana/worldwideview/main/docker-compose.yml
curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml
# 2. Generate .env with a persistent secret
if [ ! -f .env ]; then