Compare commits

..
Author SHA1 Message Date
Silvertakana b74bb4dfa6 Merge branch 'main' into fix/base-incident-plugin-payload 2026-05-25 00:35:34 +12:00
Antigravity AI e3df4fc7aa 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:27:24 +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
Antigravity AI 56d6ae352e 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 19:37:03 +12:00
Antigravity AI abbef0c212 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.
2026-05-24 14:10:56 +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
10 changed files with 676 additions and 19 deletions

No files matched your search

+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`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.18.1",
"version": "2.18.3",
"private": true,
"type": "module",
"packageManager": "[email protected]",
+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,
};
}
}
+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
});
+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/);
});
+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) {
+58 -11
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", () => {
@@ -68,23 +83,55 @@ 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("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("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("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");
});
});
});