A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.
JavaScript 3d-globecesiumflight-trackinggeospatialgeospatial-intelligencegisosintphotogrammetrysatellite-trackingspatial-intelligencewebglworldview
fix(gbfs): adapt redirect hardening to provider modules and bound body reads
Sameh Khamis4fae7fb2781b
diff --cc CHANGELOG.mdindex c89335375,cdd4f95f3..cffb5a7b4--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -13,161 -5,8 +13,167 @@@ of current runtime behavior, see [`docs## [Unreleased]+ ### Fixed+++- GBFS rejects upstream redirects, caps streamed responses at 5 MiB, and keeps++ its deadline active through body reads. Rejected downloads are cancelled.+++++- Split Overpass/installation search, regional briefing/weather, local voice+ handlers and standalone key setup into focused modules. Preserve routes,+ source behavior, tool schemas and credential restrictions.++- Restore data-provider routes under local build preview and return JSON 404s+ for unmatched API requests. Credential editing remains development-only.++- Extract CCTV catalog/media and Radio Browser directory providers into focused+ Node modules, preserving their routes and policies and isolating CCTV catalogs+ by provider instance and application root.++- Simplify POWER UP to one Google Maps entry. Keep the optional server key+ available through environment configuration without a second setup row or+ missing-key reminder.++- Separate terrain, traffic, FIRMS and GBFS middleware into focused provider+ modules, preserving local configuration, routes and cache/error behavior.++- Split satellite and launch-feed server providers into focused modules with+ portable request URL builders, preserving routes and cache/error behavior.++- Keep landmark names when geocoding returns only address components, preventing+ the United States Capitol annotation from moving to a Washington hotel.+ Unrelated outlines leave the valid geocoded marker in place.++- Split aircraft and vessel server providers into focused modules for source+ fetching, AIS records/tracks and shared request helpers; preserve existing+ routes, local setup, fallback behavior and rendering.+++### Changed+- Separate explicit browser build settings from standalone environment loading+ and local provider middleware. Preserve provider behavior and root named exports.+- Rename standalone browser startup to `src/standalone/` and add a Node-only+ `gods-eye-view/build/vite` export with checked package ownership.+++### Development++- Extract application lifecycle and viewer exports. Split standalone startup into+ scene setup, controls, layer registration, tools and loading UI. Startup failure+ and terminal shutdown release acquired resources and cancel delayed work.++- Adopt Prettier tooling contributed by RohanDaCoder (#227), with an explicit+ file scope, pinned formatter and Linux/Windows CI checks. Format the reusable+ infrastructure modules and their consumer tests. Package boundary checks keep+ those exports separate from app startup and local Node services.++### Fixed++- Reduce terrain-height timeouts when Re:Earth slows down. Batches are+ sized against measured response latency on both browser and server to reduce+ request timeouts, and a partial upstream failure now+ keeps the heights that did resolve rather than discarding them. A position+ the upstream answers with no height is reported as an absent reading instead+ of a failed refresh, so the log distinguishes a slow or broken upstream from+ one that simply has no value for a coordinate.++- Separate optional Google server credentials for Places and Street View from+ the browser key, contributed by Tom-Neverwinter (#110). Provider Settings,+ Pinokio's app-specific credential handling and setup diagnostics recognize+ both keys. The Street View tool prefers the server key across environment+ and `.env` sources. Existing single-key and keyless setups remain supported.++- Complete the first-run, view-target prewarm, cockpit-plates and floor-hold+ browser harness renderer portability fixes contributed by Tom-Neverwinter.+ macOS retains Metal; other platforms default to SwiftShader. Cockpit renderer+ assertions and evidence labels follow the actual selected mode. Floor-hold+ explicitly selects its measured 2D billboard mode and keeps its mesh and terrain assertions; software runs are not real-GPU evidence.+ First-run QA now checks the existing attribution Escape-close/focus-return+ behavior while preserving the launcher-underneath regression checks.+++- Datacenter and dam factories are available through scoped package exports with+ explicit context, overlay and render callbacks. The standalone app uses the+ same implementation and bundled datasets.++- Local GeoJSON layers share concurrent loads, cancel pending fetches on destruction,+ discard late results, and remove their entity-context records on teardown.++- Unchanged local infrastructure overlays no longer sustain idle rendering.+ Ground samples wait for visible terrain to settle and cannot place a marker+ below its loaded surface; roofs and valid below-sea-level heights are retained.+ Already sampled markers also follow higher terrain as close-up tiles refine.++- Datacenter and dam marker stems use bounded, zoom-dependent active sets with+ stable selection during camera motion. Close-up stems scale to the actual+ camera distance; source totals and submarine cables remain unchanged.++- Keyboard focus rings now survive active/selected button styles across the+ interface. Visual Styles, Location cities and points of interest, search,+ Context/mission actions, Cockpit utilities, and sliders retain a distinct+ focus indicator.+- A short Space press activates a focused control only on key release. Holding+ Space for 500 ms blurs that control before push-to-talk starts, and release is+ then consumed so it cannot also activate the old control. The same hold works+ from the map or page background; text-entry controls remain protected.+- The Location disclosure is reachable with Tab and shows keyboard focus;+ its city, point-of-interest, and search controls do too. Escape from inside+ the tray returns focus to its disclosure and discards any unfinished search;+ Escape on the disclosure itself closes the tray and clears that focus.+- Data Layers ON/OFF buttons show a keyboard focus ring independently of+ their enabled and feed-status colors.+- Display buttons, layout selectors, mode buttons, and sliders show a visible+ keyboard focus ring, including the controls used in Cockpit Display. Enabled+ CCTV camera dropdowns also show keyboard focus.+- Context tabs keep a distinct keyboard ring when selected. Their existing+ Left/Right arrow navigation continues to switch Contacts and Space Missions,+ and both choices remain reachable through ordinary Tab navigation.+- Tabbing through the Space Missions roster now drives the same temporary globe+ rotation and mission-marker highlight as pointer hover, without selecting the+ mission. Keyboard and pointer previews no longer cancel each other.+- Radio power controls, Search Nearby Sites, and Clear Selected Layers retain+ keyboard focus while their async work is busy. They expose that busy state to+ assistive technology and ignore repeated activation until the work settles.+- Live Contacts results retain keyboard focus by contact identity when counts,+ distance order, or pages refresh. If a focused contact departs or rotates off+ the visible page, focus moves to the named explanatory note at the end of the+ list and survives later refreshes there, so the next Tab proceeds beyond the+ list instead of restarting at Contacts or silently selecting another contact.+- Cockpit Live Signals retains keyboard focus during live updates and contact+ reordering, allowing Tab to continue to Display and Radio. If the focused+ contact leaves the list, focus moves to the current briefing tab.+- Cockpit-only Display and Radio launchers show complete inset focus rings.+- Escape collapses the nearest expanded panel containing keyboard focus and+ returns focus to that panel's disclosure when closing from its contents.+ Escape on the disclosure itself closes without leaving the collapsed control+ focused. Cockpit Contact and Live Signals panels follow the same nesting rule.+- Cesium's bottom-left Data attribution control and lightbox Close control are+ in the Tab order and support Enter and Space. Close, Escape, and backdrop+ dismissal restore focus and synchronize the disclosure state.++- CCTV testing uses the normal launcher for keyless startup, credential loading,+ localhost binding, and explicit LAN-exposure warnings while retaining its+ smaller source-pack limits.+- CelesTrak, Launch Library, terrain-height, and aircraft-enrichment failures+ return generic error messages. Related diagnostics omit raw exception details+ and upstream error bodies; response statuses and cache fallback remain intact.+ Includes the security fixes contributed by Tom-Neverwinter in PR #171.++### Fixed++- Map Source keyboard opening retries focus until the selected tile is visible.+ Leaving the disclosure, pointer interaction, or closing the tray cancels the+ pending handoff so delayed work cannot pull focus back.++- Scope, Bloom, Sharpen, location search and generated style sliders expose+ explicit accessible names. The first-run checkbox retains its native label.+- FIRMS records a source as successful only after appending its rows, avoiding+ contradictory success/failure status if aggregation throws.+- Radio country filtering and voice country requests now resolve common English+ names and exonyms that `Intl.DisplayNames`' primary label omits, so requests+ like "play radio in Turkey" no longer fail closed (Turkey → Türkiye, plus+ Myanmar/Burma, UAE, Holland, Swaziland, East Timor, Cabo Verde, Vatican).+ Ambiguous names such as a bare "Congo" or "Korea" still fail closed.- Mapped-site outages show their scheduled retry countdown and distinguishknown Overpass rate limits, timeouts, and query failures. Search feedback nolonger claims a refresh succeeded while the layer is unavailable or loading.diff --cc docs/CURRENT-STATE.mdindex dedc5b3de,1827f363b..0789e5623--- a/docs/CURRENT-STATE.md+++ b/docs/CURRENT-STATE.md@@@ -1,284 -1,7 +1,291 @@@# God's Eye View Current State++## GBFS upstream bounds++++GBFS refuses upstream redirects and enforces its 5 MiB response cap while++streaming. The 12-second deadline includes reading the body, and rejected or++stalled downloads are cancelled. Development and preview use the same handler.+++++## Remaining local service modules++Overpass query validation, geometry simplification, disk caching and upstream+transport now have separate modules; military-installation search reuses that+transport. Regional briefing combines separate place, news and weather sources,+while weather effects uses only the weather source. Existing process-scoped+caches, rate limits, stale fallbacks and route ordering are preserved.++Local voice has separate HUD-summary, debug-log and Realtime-token handlers,+with tool definitions and instructions in dedicated files. The factory accepts+an optional `annotationGuidance` paragraph; its default instructions and all 28+tool definitions remain unchanged. `sourceRoot` resolves debug logs against the+application directory. Standalone key setup accepts the same directory option+for its environment store and preserves boot provenance, loopback/origin guards,+atomic credential writes and development-only registration.++Node-only package entries expose Overpass, military installations, regional+services, local voice and standalone key setup. Importing them starts no network+acquisition. Browser layer lifecycle, rendering and voice execution stay in their+existing modules.++## Local build preview++After `npm run build`, `npm run preview` serves the built app with the same data+provider routes as development, including aircraft, satellites, terrain, traffic,+FIRMS, GBFS, Overpass and CCTV/media. Unmatched `/api` requests return a JSON 404+in both modes instead of the application HTML. Browser routes retain SPA fallback.+Credential editing (`/api/setup/*` and Provider Settings) is development-only;+preview returns JSON 404 for those endpoints. Server credentials come from the+local environment; browser keys are captured at build time. Rebuild after changing+a browser key. Preview is for local build verification, not a production server.+++## CCTV and radio provider modules++CCTV catalog acquisition, source normalization and frame/media delivery now live+in separate modules. Each CCTV factory owns its catalog and health state; its+`sourceRoot` option resolves relative source files against the application root.+Radio Browser station normalization, restricted outbound transport and directory+caching are separate modules. Node-only package entries expose both provider+factories. Routes, payloads, fallback behavior and existing dev/preview hook+registration are preserved; browser rendering is unchanged.++## Terrain, traffic, fire and bike-share provider modules++Local composition now imports separate Node modules for Re:Earth heights,+TomTom flow tiles, NASA FIRMS detections and GBFS station feeds. Existing routes,+plugin order, server-key selection, validation, disk caches, budgets, retries+and stale/error responses remain unchanged. Each has a Node-only package entry+under `gods-eye-view/server/providers/`. Portable terrain mechanics, traffic tile+math and GBFS source rules are available under `gods-eye-view/sources/`.+The browser layers and their rendering remain in their existing modules.++## Landmark annotation identity++When a landmark geocode contains only address components, annotations retain+its requested name for outline matching. A city or neighborhood address no+longer replaces the landmark's identity. Without a canonical feature name,+outline candidates must contain the geocoded anchor or closely match the+requested name; otherwise the annotation stays at its geocoded point.+Genuine feature-name components and existing administrative/monument matching+retain their established behavior.++## Satellite and launch provider modules++`server/providers/space/` owns the CelesTrak TLE and Launch Library 2 Node+proxies. Their routes, six-hour/15-minute caches, disk storage, stale fallback,+request coalescing and optional LL2 server token retain existing behavior.+The Node-only `gods-eye-view/server/providers/space` export supplies factories;+`sources/space` supplies fixed upstream URL builders with no I/O or environment+access. Callers retain validation, transport and response policy.++## Build configuration and local provider boundaries++`vite.config.js` delegates to `server/standalone/vite.config.js`, which loads+this checkout's environment and constructs the local providers in their existing+order. `server/providers/local.js` is the composition and compatibility entry;+provider families own their middleware and process state in focused modules.+Provider URLs, key selection, cache behavior, setup restrictions and routes are+unchanged.++`gods-eye-view/build/vite` is a Node-only export for explicit browser build+settings: Cesium assets, caller-supplied plugins, browser key defines, server+binding and document/credential protections. It never reads an environment file+or constructs providers. The standalone caller owns those choices.++Browser startup now lives in `src/standalone/`. That directory contains only+browser code; Node configuration remains under `server/`. Application lifecycle+and viewer export paths are unchanged.++## Application startup and shutdown++The standalone entry now composes scene setup, controls, layer registration and+tools through the reusable application lifecycle. Map defaults, layer order,+share restoration, voice setup and the running debug handle retain their behavior.+The welcome card still waits for restoration and the loading-cover transition.++Startup failure cleans up acquired resources. Explicit application destruction+aborts construction, cancels pending playback/annotations and delayed welcome UI,+then releases controls, layers and the viewer. Destruction is terminal; the+standalone page must be reloaded to start again. The exported lifecycle and viewer+helpers do not import the standalone entry or discover configuration. See+[application construction](APPLICATION.md).++## Scoped formatting and package checks++`npm run format` and `npm run format:check` operate on the explicit adopted-file+list. `npm run check:boundaries` checks the dependency graph of all+current package exports in their declared browser or Node runtime; infrastructure owns its three implementation modules+and takes Cesium from the consumer. CI runs both checks on Linux and Windows.+The standalone app, layer behavior and public export paths remain unchanged.+See [component ownership and adoption](CODE-BOUNDARIES.md).++## Google browser and server keys++Local Places nearby/text search and the CCTV Street View fallback prefer+`GOOGLE_MAPS_SERVER_API_KEY`, falling back to `GOOGLE_MAPS_API_KEY` when the+server key is blank or absent. Only the browser key is injected into client+code. POWER UP presents one Google Maps entry for the browser key. The optional+server key is configured manually in the same ignored root `.env`, or Pinokio's+ignored `pinokio/ENVIRONMENT`; it is omitted from Provider Settings and its+missing-key count. Existing server keys and the single-key fallback remain+supported. `.env.example` and `pinokio/_ENVIRONMENT` document both entries.+The Street View headings tool uses the same server-first selection after+resolving environment overrides per variable; its explicit `--key` wins.+++## Infrastructure marker visibility++Datacenter/dam registration uses fresh reusable factories with the application's+existing context, overlay and render functions. The scoped package exports do+not import standalone application globals; see+[the infrastructure interface](INFRASTRUCTURE-LAYERS.md) for lifecycle and asset+requirements.++Local GeoJSON layers coalesce concurrent enables into one load. Disabling while+loading keeps the result hidden; destruction aborts the fetch and rejects late+parse/add results. Destruction and failed setup remove owned context records,+so replacing a layer cannot retain stale entities or listeners.++Datacenters and dams retain their full datasets while limiting active marker+stems per layer: 80 at camera heights of 3,000 km or above, 200 from 200 km,+and 420 below 200 km. Selection favors existing label priority and nearby+features, retains stable choices across small camera movements, and refreshes+during continuous motion. Disable/re-enable resets selection cleanly.+Close-up stem sizing uses camera-to-feature distance without a 5 km minimum.+Unchanged overlay entries do not request another frame; moved positions,+changed membership and re-enabling still publish. Ground sampling waits for+visible globe tiles to settle and uses valid loaded terrain as a floor while+retaining rooftop and below-sea-level elevations. A hidden globe does not+constrain photoreal geometry, and retry work remains bounded. Already sampled+nearby markers follow higher settled terrain on existing bounded walks, without+additional GPU samples or timers, when close-up tile detail refines the floor.+The submarine-cable renderer is unchanged. These limits bound active stem work;+they do not reduce the materialized entity count or establish an FPS gain.++## Keyboard interaction and focus++- Enter on the map-source disclosure opens immediately. A short Space press+ opens it on key release. Either route focuses the selected source once visible;+ a bounded retry handles delayed opening transitions, and closing the tray or+ moving focus elsewhere cancels the handoff.+- Keyboard focus rings are a global interface state and stay visible when a+ button is active or selected. Visual Styles, Location suboptions, Context and+ mission actions, Cockpit utilities, native fields, and sliders use the same+ visible-ring contract.+- A short Space press on a focused control keeps its native key-release action.+ If it remains held for 500 ms, focus is checked again, the control is blurred,+ and push-to-talk starts; releasing a claimed hold cannot activate the old+ control. The same hold works on the map and page background. Text-entry+ controls remain protected.+- The Location disclosure is reachable with Tab or Shift+Tab and shows a+ keyboard focus ring. Its city, point-of-interest, search-toggle, and search+ field controls show inset rings, including selected items. Enter toggles its+ tray immediately, while Space does so on release; either route makes the revealed controls immediately reachable by Tab;+ Escape closes it and clears any unfinished search. Escape from a tray control+ returns focus to the disclosure; Escape on the disclosure clears focus after closing.+- Data Layers ON/OFF buttons show a visible keyboard focus ring without+ changing their enabled state or feed-status presentation.+- Display controls and shader-parameter sliders show keyboard focus in both+ the map panel and Cockpit Display. Arrow keys retain native range adjustment.+ The enabled CCTV camera dropdown shows keyboard focus as well.+- Tab reaches both Contacts and Space Missions in sequence in every Context+ state. Left/Right arrows also switch them; the focused tab has a distinct ring+ even when selected.+- Keyboard focus on a Space Missions roster item uses the same temporary globe+ rotation and mission-marker highlight as pointer hover. Focus alone does not+ select the mission; Enter or Space performs selection. Keyboard and pointer+ preview ownership remain independent when the pointer is parked over the list.+- Radio power controls in the full, compact, and Cockpit surfaces, Search Nearby+ Sites, and Clear Selected Layers remain focusable while lifecycle work is in+ progress. They announce busy/disabled semantics and ignore repeat activation+ until the operation settles, so async work cannot drop the keyboard ring.+- Normal-mode Contacts results preserve the focused action or contact by stable+ identity while live counts, distance order, and pages refresh. If that contact+ departs or rotates off the visible page, focus moves to a stable continuation+ point on the named explanatory note at the end of the list and remains there+ through later repaints. The following Tab proceeds beyond the results instead+ of restarting at Contacts or silently focusing another contact.+- Cockpit Live Signals updates existing contact buttons without replacing or+ disconnecting the focused one. Tab can continue through the briefing footer+ to Display and Radio. If the focused contact leaves the list, focus moves+ once to the current briefing tab; later refreshes do not reclaim it.+- Cockpit-only Display and Radio launcher icons show a complete inset keyboard+ ring in their collapsed and expanded states.+- Escape collapses the nearest expanded panel containing focus before any+ containing panel acts. Closing from panel content returns focus to that panel's+ disclosure; closing from the disclosure itself clears focus so the collapsed+ button does not retain its ring. This includes standard panels, nested+ Parameters, Cockpit Contact and Live Signals, and Cockpit Display/Radio utilities.+- The required bottom-left Data attribution control is a named popup button in+ the Tab order. Enter opens immediately and Space opens on release, then the+ credit lightbox focuses Close;+ Close, Escape, or backdrop dismissal restores focus to Data attribution.++## CCTV launcher and proxy failure responses++`scripts/dev-cctv.sh` delegates startup to `scripts/dev-fresh.sh`. It retains+its Austin source file, Austin preference, 36-camera Austin limit, and 48-camera+total limit, with environment overrides. Keys are optional; credential loading+and names-only provider provenance follow the normal launcher. The default+binding is localhost. An explicit `HOST=0.0.0.0` uses the same LAN warning as+normal startup.++The CelesTrak, Launch Library, terrain-height, and ADSBDB middleware return+fixed messages for unexpected failures. Launch Library retains its upstream+HTTP failure status and no-store policy but does not forward the upstream body.+Existing successful, in-flight, missing-data, and stale-cache behavior remains+in place. Failure diagnostics identify the service and, for Launch Library,+HTTP status without printing raw exception text or upstream bodies.++## Map Source keyboard focus++Keyboard opening focuses the selected map-source tile, falling back to the first+only when no source is selected. A bounded retry handles delayed tray visibility.+Moving focus away, pointer interaction, closing the tray, or disposing the UI+cancels pending work; a later reopening cannot inherit an old focus request.++## September 8, 2026++Earthquake refreshes validate the complete feed and construct replacement entities before clearing the previous snapshot. Malformed rows and duplicate rendered IDs retain the last good entities, overlays, count and timestamp and report a malformed response; unknown magnitude is excluded from M2.5+ rendering.++Non-object or array-valued properties reject the response instead of being treated as an unknown magnitude.++Launch payloads with missing records now say PAYLOAD DATA UNAVAILABLE. Missing names use Unnamed payload; absent or invalid mass stays unknown instead of appearing as 0 KG.+Updated: August 24, 2026+## Aircraft and vessel server modules++Standalone aircraft routes now live in `server/providers/aircraft/`: OpenSky+state vectors and regional fallback, adsb.lol military positions, ADSBDB+enrichment and track backfill. Vessel routes and websocket/watchdog setup live+in `server/providers/vessels/ais-live.js`; AIS records and recent tracks live+in `ais-store.js`. Common response caps, request coalescing and query parsing+have their own modules. `server/providers/local.js` composes these with the+remaining providers and retains existing named compatibility exports.++`gods-eye-view/server/providers/live` is a Node-only entry for the existing+plugins and shared request helpers. Importing it starts no sockets or timers.+The existing aircraft normalizer is separately available through the portable+`gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache+policy, fallback behavior, response shapes and rendering remain unchanged.+++## Control names for assistive technology++Scope, Bloom, Sharpen and location search have explicit accessible names.+Generated style sliders use the same name as their visible parameter label.+The first-run suppression checkbox keeps its native wrapping label, so its+accessible name remains "Don't show this again". Control behavior is unchanged.++## FIRMS source status++The FIRMS proxy records source success after appending its rows. If aggregation+throws, that source reports failure without a contradictory success entry.+The existing per-record append continues to support large feeds; sequential+fetching, trailing-24-hour filtering and partial-success caching are unchanged.+## Installations and map-source guidance- On an uncached Overpass failure, mapped installations keep their existingdiff --cc scripts/package-boundaries.jsonindex b8d2ac914,000000000..4e44a9f84mode 100644,000000..100644--- a/scripts/package-boundaries.json+++ b/scripts/package-boundaries.json@@@ -1,253 -1,0 +1,257 @@@+{+ "infrastructure": {+ "exports": [+ "./infrastructure",+ "./infrastructure/geojson",+ "./infrastructure/lod"+ ],+ "modules": [+ "src/data/infrastructure.js",+ "src/data/localGeojsonCore.js",+ "src/data/localGeojsonLod.js"+ ],+ "external": ["cesium"]+ },+ "application": {+ "exports": ["./application"],+ "modules": ["src/app/application.js"],+ "external": []+ },+ "viewer": {+ "exports": ["./application/viewer"],+ "modules": ["src/app/viewer.js"],+ "external": ["cesium"]+ },+ "vite-build": {+ "runtime": "node",+ "exports": ["./build/vite"],+ "modules": ["build/vite.js"],+ "external": ["vite-plugin-cesium"]+ },+ "live-providers": {+ "runtime": "node",+ "exports": ["./server/providers/live"],+ "modules": [+ "server/providers/live.js",+ "server/providers/common/http.js",+ "server/providers/common/query.js",+ "server/providers/aircraft/opensky.js",+ "server/providers/aircraft/adsb-lol.js",+ "server/providers/aircraft/enrichment.js",+ "server/providers/aircraft/tracks.js",+ "server/providers/vessels/ais-store.js",+ "server/providers/vessels/ais-live.js",+ "src/data/adsbLolFallback.js",+ "src/data/aisStreamAdapter.js",+ "src/data/aisWatchdog.js"+ ],+ "external": ["ws"]+ },+ "adsb-lol-source": {+ "exports": ["./sources/adsb-lol"],+ "modules": ["src/data/adsbLolFallback.js"],+ "external": []+ },+ "place-providers": {+ "runtime": "node",+ "exports": ["./server/providers/places"],+ "modules": [+ "server/providers/places.js",+ "server/providers/places/google.js",+ "server/providers/places/google-key.js",+ "server/providers/places/routes.js",+ "server/providers/common/rate-limit.js",+ "server/providers/common/geo.js",+ "server/providers/common/http.js",+ "scripts/google-server-key.mjs",+ "src/data/placeProviderPayloads.js"+ ],+ "external": []+ },+ "place-payloads": {+ "exports": ["./sources/places"],+ "modules": ["src/data/placeProviderPayloads.js"],+ "external": []+ },+ "space-providers": {+ "runtime": "node",+ "exports": ["./server/providers/space"],+ "modules": [+ "server/providers/space.js",+ "server/providers/space/celestrak.js",+ "server/providers/space/launch-library.js",+ "server/providers/common/http.js",+ "src/data/spaceProviderRequests.js"+ ],+ "external": []+ },+ "space-requests": {+ "exports": ["./sources/space"],+ "modules": ["src/data/spaceProviderRequests.js"],+ "external": []+ },+ "terrain-provider": {+ "runtime": "node",+ "exports": ["./server/providers/terrain"],+ "modules": [+ "server/providers/terrain.js",+ "src/data/terrainHeightsProxy.js"+ ],+ "external": []+ },+ "terrain-source": {+ "exports": ["./sources/terrain"],+ "modules": ["src/data/terrainHeightsProxy.js"],+ "external": []+ },+ "traffic-provider": {+ "runtime": "node",+ "exports": ["./server/providers/traffic"],+ "modules": ["server/providers/traffic.js", "src/data/tomtomTiles.js"],+ "external": []+ },+ "traffic-source": {+ "exports": ["./sources/traffic"],+ "modules": ["src/data/tomtomTiles.js"],+ "external": []+ },+ "firms-provider": {+ "runtime": "node",+ "exports": ["./server/providers/firms"],+ "modules": ["server/providers/firms.js", "src/data/firmsCsv.js"],+ "external": []+ },+ "gbfs-provider": {+ "runtime": "node",+ "exports": ["./server/providers/gbfs"],- "modules": ["server/providers/gbfs.js", "src/data/gbfsSource.js"],++ "modules": [++ "server/providers/gbfs.js",++ "server/providers/common/http.js",++ "src/data/gbfsSource.js"++ ],+ "external": []+ },+ "gbfs-source": {+ "exports": ["./sources/gbfs"],+ "modules": ["src/data/gbfsSource.js"],+ "external": []+ },+ "cctv-provider": {+ "runtime": "node",+ "exports": ["./server/providers/cctv"],+ "modules": [+ "server/providers/cctv.js",+ "server/providers/cctv/catalog.js",+ "server/providers/cctv/constants.js",+ "server/providers/cctv/media.js",+ "server/providers/cctv/normalize.js",+ "server/providers/cctv/sources.js",+ "src/data/directionText.js",+ "server/providers/common/geo.js",+ "server/providers/places/google-key.js",+ "scripts/google-server-key.mjs"+ ],+ "external": []+ },+ "radio-provider": {+ "runtime": "node",+ "exports": ["./server/providers/radio"],+ "modules": [+ "server/providers/radio.js",+ "server/providers/radio/catalog.js",+ "server/providers/radio/constants.js",+ "server/providers/radio/stations.js",+ "server/providers/radio/transport.js",+ "src/data/radioCountry.js",+ "server/providers/common/http.js"+ ],+ "external": []+ },+ "overpass-provider": {+ "runtime": "node",+ "exports": ["./server/providers/overpass"],+ "modules": [+ "server/providers/common/geo.js",+ "server/providers/common/http.js",+ "server/providers/common/rate-limit.js",+ "server/providers/common/request.js",+ "server/providers/overpass.js",+ "server/providers/overpass/cache.js",+ "server/providers/overpass/constants.js",+ "server/providers/overpass/geometry.js",+ "server/providers/overpass/query.js",+ "server/providers/overpass/transport.js",+ "server/providers/places/routes.js",+ "src/data/placeProviderPayloads.js"+ ],+ "external": []+ },+ "military-installations-provider": {+ "runtime": "node",+ "exports": ["./server/providers/military-installations"],+ "modules": [+ "server/providers/common/http.js",+ "server/providers/common/query.js",+ "server/providers/common/rate-limit.js",+ "server/providers/military-installations.js",+ "server/providers/military-installations/cache.js",+ "server/providers/military-installations/constants.js",+ "server/providers/military-installations/query.js",+ "server/providers/overpass/constants.js",+ "server/providers/overpass/geometry.js",+ "server/providers/overpass/transport.js"+ ],+ "external": []+ },+ "regional-provider": {+ "runtime": "node",+ "exports": ["./server/providers/regional"],+ "modules": [+ "server/providers/common/http.js",+ "server/providers/common/query.js",+ "server/providers/common/rate-limit.js",+ "server/providers/regional.js",+ "server/providers/regional/briefing.js",+ "server/providers/regional/http.js",+ "server/providers/regional/news.js",+ "server/providers/regional/place.js",+ "server/providers/regional/query.js",+ "server/providers/regional/weather-effects.js",+ "server/providers/regional/weather.js",+ "src/data/regionalBrief.js"+ ],+ "external": []+ },+ "openai-provider": {+ "runtime": "node",+ "exports": ["./server/providers/openai"],+ "modules": [+ "server/providers/common/rate-limit.js",+ "server/providers/common/request.js",+ "server/providers/common/source-root.js",+ "server/providers/openai.js",+ "server/providers/openai/constants.js",+ "server/providers/openai/debug-log.js",+ "server/providers/openai/hud-summary.js",+ "server/providers/openai/instructions.js",+ "server/providers/openai/rate-limit.js",+ "server/providers/openai/realtime.js",+ "server/providers/openai/tools.js",+ "src/hudSummaryResponse.js",+ "src/voice/voiceCost.js"+ ],+ "external": []+ },+ "standalone-key-setup": {+ "runtime": "node",+ "exports": ["./server/standalone/key-setup"],+ "modules": [+ "scripts/pinokio-environment.mjs",+ "server/providers/common/source-root.js",+ "server/standalone/key-setup.js",+ "src/keySetupCore.mjs",+ "src/keySetupHardening.mjs"+ ],+ "external": []+ }+}diff --cc server/providers/common/http.jsindex 67b985c22,000000000..561d19cf8mode 100644,000000..100644--- a/server/providers/common/http.js+++ b/server/providers/common/http.js@@@ -1,113 -1,0 +1,118 @@@+/**+ * Read a fetch() Response body as text with a hard byte cap. Rejects early on an+ * oversized Content-Length, then streams with a running cap so a chunked or+ * length-omitted response cannot blow past the limit. Throws { code:'RESPONSE_TOO_LARGE' }.+ */- export async function readResponseTextCapped(response, maxBytes) {++export async function readResponseTextCapped(response, maxBytes, signal) {++ const tooLarge = () =>++ Object.assign(new Error('Upstream response too large'), {++ code: 'RESPONSE_TOO_LARGE',++ });+ const declared = Number(response.headers.get('content-length'));+ if (Number.isFinite(declared) && declared > maxBytes) {- const err = new Error('Upstream response too large');- err.code = 'RESPONSE_TOO_LARGE';- throw err;++ void response.body?.cancel().catch(() => {});++ throw tooLarge();+ }++ signal?.throwIfAborted();+ const reader = response.body?.getReader?.();+ if (!reader) {+ const text = await response.text();- if (Buffer.byteLength(text) > maxBytes) {- const err = new Error('Upstream response too large');- err.code = 'RESPONSE_TOO_LARGE';- throw err;- }++ signal?.throwIfAborted();++ if (Buffer.byteLength(text) > maxBytes) throw tooLarge();+ return text;+ }++ const cancel = () => {++ void reader.cancel().catch(() => {});++ };++ signal?.addEventListener('abort', cancel, { once: true });+ const decoder = new TextDecoder();+ let out = '';+ let total = 0;- for (;;) {- const { done, value } = await reader.read();- if (done) break;- total += value.byteLength;- if (total > maxBytes) {- try {- await reader.cancel();- } catch {- /* no-op */- }- const err = new Error('Upstream response too large');- err.code = 'RESPONSE_TOO_LARGE';- throw err;++ try {++ for (;;) {++ signal?.throwIfAborted();++ const { done, value } = await reader.read();++ signal?.throwIfAborted();++ if (done) break;++ total += value.byteLength;++ if (total > maxBytes) throw tooLarge();++ out += decoder.decode(value, { stream: true });+ }- out += decoder.decode(value, { stream: true });++ return out + decoder.decode();++ } catch (error) {++ cancel();++ throw error;++ } finally {++ signal?.removeEventListener('abort', cancel);++ reader.releaseLock();+ }- out += decoder.decode();- return out;+}++/** Parse a fetch() JSON response only after enforcing a hard byte cap. */+export async function readResponseJsonCapped(response, maxBytes) {+ return JSON.parse(await readResponseTextCapped(response, maxBytes));+}++/**+ * Return the existing promise for a cache key, or create one and remove it+ * only when that exact promise settles.+ */+export function coalesceProxyRequest(inFlight, key, create) {+ const existing = inFlight.get(key);+ if (existing) return { promise: existing, shared: true };+ let promise;+ promise = Promise.resolve()+ .then(create)+ .finally(() => {+ if (inFlight.get(key) === promise) inFlight.delete(key);+ });+ inFlight.set(key, promise);+ return { promise, shared: false };+}++/**+ * Read a fetch Response body as text while enforcing a hard byte cap during+ * the read — so a malicious or buggy upstream that streams an unbounded body+ * (no/oversized Content-Length, chunked) can't OOM the proxy. Returns+ * { tooLarge, text }. Cancels the stream as soon as the cap is crossed.+ * @param {Response} upstream - fetch() response.+ * @param {number} maxBytes - hard ceiling on decoded bytes.+ * @returns {Promise<{tooLarge: boolean, text: string}>}+ */+export async function readCappedResponseText(upstream, maxBytes) {+ const declared = Number(upstream.headers.get('content-length'));+ if (Number.isFinite(declared) && declared > maxBytes) {+ try {+ await upstream.body?.cancel();+ } catch {+ /* no-op */+ }+ return { tooLarge: true, text: '' };+ }+ if (+ !upstream.body ||+ typeof upstream.body[Symbol.asyncIterator] !== 'function'+ ) {+ const text = await upstream.text();+ return text.length > maxBytes+ ? { tooLarge: true, text: '' }+ : { tooLarge: false, text };+ }+ const decoder = new TextDecoder();+ let text = '';+ let total = 0;+ for await (const chunk of upstream.body) {+ total += chunk.length;+ if (total > maxBytes) {+ try {+ await upstream.body.cancel();+ } catch {+ /* no-op */+ }+ return { tooLarge: true, text: '' };+ }+ text += decoder.decode(chunk, { stream: true });+ }+ text += decoder.decode();+ return { tooLarge: false, text };+}diff --cc server/providers/gbfs.jsindex 30575b973,000000000..9741bb4e6mode 100644,000000..100644--- a/server/providers/gbfs.js+++ b/server/providers/gbfs.js@@@ -1,183 -1,0 +1,249 @@@++import { readResponseTextCapped } from './common/http.js';+import {+ isAllowedGbfsHost,+ isAllowedGbfsPath,+ gbfsCacheControl,+} from '../../src/data/gbfsSource.js';++// ---------------------------------------------------------------------------+// GBFS (General Bikeshare Feed Specification) proxy constants+// ---------------------------------------------------------------------------+/** Upstream fetch timeout for GBFS requests (ms). */+const GBFS_PROXY_TIMEOUT_MS = 12000;+++export const GBFS_MAX_BODY_BYTES = 5 * 1024 * 1024; // 5 MB++++function gbfsRedirectHost(location, requestUrl) {++ if (!location) return '';++ try {++ return new URL(String(location), requestUrl).hostname;++ } catch {++ return '';++ }++}++++/**++ * Fetch one validated GBFS endpoint without following redirects and with the++ * body cap enforced while the response streams.++ *++ * The middleware validates the target before calling this; the network step++ * lives apart from it so a unit test can stand in for a hostile upstream — the++ * host allowlist keeps the real handler from being pointed at a local server.++ * `redirect: 'manual'` makes fetch() return a 3xx response instead of++ * following it, so an allowlisted operator that redirects cannot steer the++ * proxy to a destination the allowlist never saw; any 3xx is rejected with++ * { code:'GBFS_REDIRECT', redirectHost }. An oversized body surfaces as++ * { code:'RESPONSE_TOO_LARGE' } from readResponseTextCapped, which cancels the++ * upstream read the moment the running byte count passes the cap.++ *++ * @param {string} url - Validated https GBFS endpoint URL.++ * @param {object} [options]++ * @param {typeof fetch} [options.fetchImpl=fetch] - Fetch implementation.++ * @param {number} [options.timeoutMs=GBFS_PROXY_TIMEOUT_MS] - Upstream abort timeout.++ * @param {number} [options.maxBytes=GBFS_MAX_BODY_BYTES] - Body byte cap.++ * @returns {Promise<{status:number,contentType:string,body:string}>}++ */++export async function fetchGbfsUpstream(++ url,++ {++ fetchImpl = fetch,++ timeoutMs = GBFS_PROXY_TIMEOUT_MS,++ maxBytes = GBFS_MAX_BODY_BYTES,++ } = {},++) {++ const controller = new AbortController();++ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);++ let upstream;++ try {++ upstream = await fetchImpl(url, {++ method: 'GET',++ headers: {++ Accept: 'application/json',++ 'User-Agent': 'gods-eye-view-gbfs-proxy/1.0',++ },++ redirect: 'manual',++ signal: controller.signal,++ });++++ if (upstream.status >= 300 && upstream.status < 400) {++ try {++ void upstream.body?.cancel().catch(() => {});++ } catch {++ /* no-op */++ }++ const err = new Error(++ 'GBFS upstream redirected; redirects are not followed',++ );++ err.code = 'GBFS_REDIRECT';++ err.redirectHost = gbfsRedirectHost(++ upstream.headers.get('location'),++ url,++ );++ throw err;++ }++++ const body = await readResponseTextCapped(++ upstream,++ maxBytes,++ controller.signal,++ );++ return {++ status: upstream.status,++ contentType: upstream.headers.get('content-type') || 'application/json',++ body,++ };++ } catch (error) {++ controller.abort();++ if (upstream?.body && !upstream.body.locked) {++ void upstream.body.cancel().catch(() => {});++ }++ throw error;++ } finally {++ clearTimeout(timeoutId);++ }++}+++/**+ * Vite plugin: GBFS bike-share proxy with host allowlisting and size limits.+ *+ * Accepts GET /api/gbfs/<encoded-upstream-URL> and proxies the request+ * to the upstream GBFS provider. Validates hostname against an allowlist,+ * restricts to station_information/station_status paths, enforces HTTPS,+ * and caps response body at 5 MB.+ *+ * @returns {import('vite').Plugin}+ */+export function gbfsProxy() {+ const installMiddleware = (server) => {+ server.middlewares.use('/api/gbfs', async (req, res) => {+ try {+ if (req.method !== 'GET') {+ res.writeHead(405, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));+ return;+ }++ const url = new URL(req.url || '/', 'http://localhost');+ const encodedTarget = url.pathname.replace(/^\/+/, '');+ if (!encodedTarget) {+ res.writeHead(400, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'Missing GBFS upstream target' }));+ return;+ }++ let decodedTarget = '';+ try {+ decodedTarget = decodeURIComponent(encodedTarget);+ } catch {+ res.writeHead(400, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'Invalid GBFS target encoding' }));+ return;+ }++ let upstreamUrl = null;+ try {+ upstreamUrl = new URL(decodedTarget);+ } catch {+ res.writeHead(400, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'Invalid GBFS upstream URL' }));+ return;+ }++ if (upstreamUrl.protocol !== 'https:') {+ res.writeHead(400, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(+ JSON.stringify({ error: 'Only https GBFS targets are allowed' }),+ );+ return;+ }++ if (!isAllowedGbfsHost(upstreamUrl.hostname)) {+ res.writeHead(403, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'GBFS host not allowed' }));+ return;+ }++ if (!isAllowedGbfsPath(upstreamUrl.pathname)) {+ res.writeHead(400, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(+ JSON.stringify({+ error:+ 'Only station_information/station_status endpoints are allowed',+ }),+ );+ return;+ }+- const controller = new AbortController();- const timeoutId = setTimeout(- () => controller.abort(),- GBFS_PROXY_TIMEOUT_MS,- );- let upstream;- try {- upstream = await fetch(upstreamUrl.toString(), {- method: 'GET',- headers: {- Accept: 'application/json',- 'User-Agent': 'gods-eye-view-gbfs-proxy/1.0',- },- signal: controller.signal,- });- } finally {- clearTimeout(timeoutId);- }-- // Limit response size to prevent memory exhaustion from malicious upstream- const GBFS_MAX_BODY_BYTES = 5 * 1024 * 1024; // 5 MB- const contentLength = Number(upstream.headers.get('content-length'));- if (- Number.isFinite(contentLength) &&- contentLength > GBFS_MAX_BODY_BYTES- ) {- res.writeHead(502, {- 'Content-Type': 'application/json',- 'Cache-Control': 'no-store',- });- res.end(- JSON.stringify({ error: 'GBFS upstream response too large' }),- );- return;- }- const body = await upstream.text();- if (Buffer.byteLength(body, 'utf8') > GBFS_MAX_BODY_BYTES) {- res.writeHead(502, {- 'Content-Type': 'application/json',- 'Cache-Control': 'no-store',- });- res.end(- JSON.stringify({ error: 'GBFS upstream response too large' }),- );- return;- }- const contentType =- upstream.headers.get('content-type') || 'application/json';++ const upstream = await fetchGbfsUpstream(upstreamUrl.toString());+ res.writeHead(upstream.status, {- 'Content-Type': contentType,++ 'Content-Type': upstream.contentType,+ 'Cache-Control': gbfsCacheControl(upstreamUrl.pathname),+ 'X-GBFS-Upstream': upstreamUrl.hostname,+ 'X-GBFS-Cache': 'MISS',+ });- res.end(body);++ res.end(upstream.body);+ } catch (error) {+ if (error?.name === 'AbortError') {+ res.writeHead(504, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'GBFS upstream timeout' }));+ return;+ }++ if (++ error?.code === 'GBFS_REDIRECT' ||++ error?.code === 'RESPONSE_TOO_LARGE'++ ) {++ if (error.code === 'GBFS_REDIRECT')++ console.warn('[GBFS Proxy] Redirect refused', error.redirectHost);++ res.writeHead(502, {++ 'Content-Type': 'application/json',++ 'Cache-Control': 'no-store',++ });++ res.end(++ JSON.stringify({++ error:++ error.code === 'GBFS_REDIRECT'++ ? 'GBFS upstream redirect refused'++ : 'GBFS upstream response too large',++ }),++ );++ return;++ }+ console.error('[GBFS Proxy]', error?.message || String(error));+ res.writeHead(502, {+ 'Content-Type': 'application/json',+ 'Cache-Control': 'no-store',+ });+ res.end(JSON.stringify({ error: 'GBFS proxy error' }));+ }+ });+ };+ return {+ name: 'gbfs-proxy',+ configureServer: installMiddleware,+ configurePreviewServer: installMiddleware,+ };+}diff --cc src/data/gbfsProxy.test.mjsindex 000000000,4f00eb99e..191cb57bamode 000000,100644..100644--- a/src/data/gbfsProxy.test.mjs+++ b/src/data/gbfsProxy.test.mjs@@@ -1,0 -1,131 +1,270 @@@+ import { test } from 'node:test';+ import assert from 'node:assert/strict';+ import {+ GBFS_MAX_BODY_BYTES,+ fetchGbfsUpstream,-} from '../../vite.config.js';++} from '../../server/providers/gbfs.js';++ const STATION_URL = 'https://gbfs.lyft.com/gbfs/2.3/bay/en/station_status.json';+ const STATION_BODY = '{"data":{"stations":[]}}';++ /**+ * A Response whose body streams `chunk` forever until the reader cancels it.+ * A zero high-water mark keeps the stream from pulling eagerly at construction,+ * so `pulls()` counts only the chunks a reader actually asked for.+ */+ function endlessResponse(chunk, onCancel) {+ let pulls = 0;- const stream = new ReadableStream({- pull(controller) {- pulls += 1;- controller.enqueue(chunk);++ const stream = new ReadableStream(++ {++ pull(controller) {++ pulls += 1;++ controller.enqueue(chunk);++ },++ cancel: onCancel,+ },- cancel: onCancel,- }, { highWaterMark: 0 });- return { response: new Response(stream, { status: 200 }), pulls: () => pulls };++ { highWaterMark: 0 },++ );++ return {++ response: new Response(stream, { status: 200 }),++ pulls: () => pulls,++ };+ }++ test('GBFS upstream fetch passes a direct 200 through unchanged', async () => {+ let observedOptions = null;+ const result = await fetchGbfsUpstream(STATION_URL, {+ fetchImpl: async (_url, options) => {+ observedOptions = options;+ return new Response(STATION_BODY, {+ status: 200,+ headers: { 'Content-Type': 'application/json; charset=utf-8' },+ });+ },+ });+- assert.equal(observedOptions.redirect, 'manual', 'fetch must not follow redirects on its own');++ assert.equal(++ observedOptions.redirect,++ 'manual',++ 'fetch must not follow redirects on its own',++ );+ assert.ok(observedOptions.signal instanceof AbortSignal);+ assert.deepEqual(result, {+ status: 200,+ contentType: 'application/json; charset=utf-8',+ body: STATION_BODY,+ });+ });++ test('GBFS upstream fetch forwards a non-redirect error status for the middleware to relay', async () => {+ const result = await fetchGbfsUpstream(STATION_URL, {+ fetchImpl: async () => new Response(null, { status: 404 }),+ });+ assert.equal(result.status, 404);- assert.equal(result.contentType, 'application/json', 'a missing upstream content type defaults to JSON');++ assert.equal(++ result.contentType,++ 'application/json',++ 'a missing upstream content type defaults to JSON',++ );+ assert.equal(result.body, '');+ });++ test('GBFS upstream fetch rejects every redirect status and never fetches the target', async () => {+ for (const status of [301, 302, 303, 307, 308]) {+ let calls = 0;+ await assert.rejects(+ fetchGbfsUpstream(STATION_URL, {+ fetchImpl: async () => {+ calls += 1;+ return new Response('moved', {+ status,- headers: { Location: 'https://attacker.example/station_status.json' },++ headers: {++ Location: 'https://attacker.example/station_status.json',++ },+ });+ },+ }),- (error) => error?.code === 'GBFS_REDIRECT' && error.redirectHost === 'attacker.example',++ (error) =>++ error?.code === 'GBFS_REDIRECT' &&++ error.redirectHost === 'attacker.example',+ `status ${status} must be refused`,+ );- assert.equal(calls, 1, `status ${status}: the redirect target must not be requested`);++ assert.equal(++ calls,++ 1,++ `status ${status}: the redirect target must not be requested`,++ );+ }+ });++ test('GBFS upstream fetch names the host of a relative redirect', async () => {+ await assert.rejects(+ fetchGbfsUpstream(STATION_URL, {- fetchImpl: async () => new Response(null, { status: 302, headers: { Location: '/v2/station_status.json' } }),++ fetchImpl: async () =>++ new Response(null, {++ status: 302,++ headers: { Location: '/v2/station_status.json' },++ }),+ }),- (error) => error?.code === 'GBFS_REDIRECT' && error.redirectHost === 'gbfs.lyft.com',++ (error) =>++ error?.code === 'GBFS_REDIRECT' && error.redirectHost === 'gbfs.lyft.com',+ );+ });++ test('GBFS upstream fetch rejects an oversized Content-Length before reading the body', async () => {+ const { response, pulls } = endlessResponse(new Uint8Array(1024));+ response.headers.set('Content-Length', String(GBFS_MAX_BODY_BYTES + 1));+ await assert.rejects(+ fetchGbfsUpstream(STATION_URL, { fetchImpl: async () => response }),+ (error) => error?.code === 'RESPONSE_TOO_LARGE',+ );- assert.equal(pulls(), 0, 'the body must not be read when the declared length already exceeds the cap');++ assert.equal(++ pulls(),++ 0,++ 'the body must not be read when the declared length already exceeds the cap',++ );+ });++ test('GBFS upstream fetch cancels a length-less body the moment it passes the cap', async () => {+ let cancelled = false;+ const chunk = new Uint8Array(1024);- const { response, pulls } = endlessResponse(chunk, () => { cancelled = true; });++ const { response, pulls } = endlessResponse(chunk, () => {++ cancelled = true;++ });+ await assert.rejects(- fetchGbfsUpstream(STATION_URL, { fetchImpl: async () => response, maxBytes: 4 * chunk.byteLength }),++ fetchGbfsUpstream(STATION_URL, {++ fetchImpl: async () => response,++ maxBytes: 4 * chunk.byteLength,++ }),+ (error) => error?.code === 'RESPONSE_TOO_LARGE',+ );- assert.equal(cancelled, true, 'the upstream stream must be cancelled, not drained');- assert.ok(pulls() <= 8, `only a few chunks may be read past the cap, saw ${pulls()}`);++ assert.equal(++ cancelled,++ true,++ 'the upstream stream must be cancelled, not drained',++ );++ assert.ok(++ pulls() <= 8,++ `only a few chunks may be read past the cap, saw ${pulls()}`,++ );+ });++ test('GBFS upstream fetch measures the cap in bytes and accepts a body exactly at it', async () => {+ const body = 'é'.repeat(64);+ const result = await fetchGbfsUpstream(STATION_URL, {+ fetchImpl: async () => new Response(body, { status: 200 }),+ maxBytes: Buffer.byteLength(body),+ });+ assert.equal(result.body, body);+ assert.equal(GBFS_MAX_BODY_BYTES, 5 * 1024 * 1024);+ });++ test('GBFS upstream fetch aborts a stalled connection with the timeout signal', async () => {+ const startedAt = Date.now();+ await assert.rejects(+ fetchGbfsUpstream(STATION_URL, {+ timeoutMs: 20,- fetchImpl: (_url, options) => new Promise((_resolve, reject) => {- options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });- }),++ fetchImpl: (_url, options) =>++ new Promise((_resolve, reject) => {++ options.signal.addEventListener(++ 'abort',++ () => reject(options.signal.reason),++ { once: true },++ );++ }),+ }),+ (error) => error?.name === 'AbortError',+ );+ assert.ok(Date.now() - startedAt < 500, 'the timeout must settle promptly');+ });++++test('GBFS cancels an oversized declared body without pulling it', async () => {++ let cancelled = false;++ const { response, pulls } = endlessResponse(new Uint8Array(1), () => {++ cancelled = true;++ });++ response.headers.set('Content-Length', '100');++ await assert.rejects(++ fetchGbfsUpstream(STATION_URL, {++ maxBytes: 10,++ fetchImpl: async () => response,++ }),++ { code: 'RESPONSE_TOO_LARGE' },++ );++ assert.equal(cancelled, true);++ assert.equal(pulls(), 0);++});++++test('GBFS deadline includes a stalled body after successful headers', async () => {++ let cancelled = false;++ let signal;++ const response = new Response(++ new ReadableStream({++ pull() {},++ cancel() {++ cancelled = true;++ },++ }),++ );++ await assert.rejects(++ fetchGbfsUpstream(STATION_URL, {++ timeoutMs: 20,++ fetchImpl: async (_url, options) => {++ signal = options.signal;++ return response;++ },++ }),++ { name: 'AbortError' },++ );++ assert.equal(signal.aborted, true);++ assert.equal(cancelled, true);++ assert.equal(response.body.locked, false);++});++++test('GBFS rejects redirects and caps bodies through both server hooks', async () => {++ const { gbfsProxy } = await import('../../server/providers/gbfs.js');++ const originalFetch = globalThis.fetch;++ try {++ for (const hook of ['configureServer', 'configurePreviewServer']) {++ let handler;++ gbfsProxy()[hook]({++ middlewares: {++ use(path, callback) {++ assert.equal(path, '/api/gbfs');++ handler = callback;++ },++ },++ });++ for (const response of [++ new Response(null, { status: 302 }),++ new Response('x', {++ headers: { 'Content-Length': String(GBFS_MAX_BODY_BYTES + 1) },++ }),++ new Response(STATION_BODY),++ ]) {++ const expectedStatus =++ response.status === 302 || response.headers.has('content-length')++ ? 502++ : 200;++ globalThis.fetch = async () => response;++ let status, body;++ await handler(++ { method: 'GET', url: '/' + encodeURIComponent(STATION_URL) },++ {++ writeHead(code) {++ status = code;++ },++ end(value) {++ body = value;++ },++ },++ );++ assert.equal(status, expectedStatus);++ if (status === 200) assert.equal(body, STATION_BODY);++ else assert.equal(typeof JSON.parse(body).error, 'string');++ }++ }++ } finally {++ globalThis.fetch = originalFetch;++ }++});