Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge remote-tracking branch 'upstream/main' into fix/363-geocode-proxy

Niccolò Saggesee2ce7fa38e5b
diff --cc SECURITY.md
index c8fa464e4,8a4256523..aae22d50f
--- a/SECURITY.md
+++ b/SECURITY.md
@@@ -18,9 -18,9 +18,9 @@@ The golden rule: **secret-bearing API k
| Key | Where it lives | How the browser uses it |
|-----|----------------|--------------------------|
| `OPENAI_API_KEY` | Server only | Browser fetches a short-lived **ephemeral** Realtime session token from `/api/realtime/token`; the real key never ships |
- | `AISSTREAM_API_KEY` | Server only | Server holds the AISStream websocket; browser polls the same-origin `/api/ais-live` cache |
- | OpenSky OAuth (`OPENSKY_CLIENT_ID/SECRET`) | Server only | Server mints + refreshes the token behind `/api/opensky` |
+ | `AISSTREAM_API_KEY` | Server only | Server holds the AISStream websocket; browser polls the same-origin `/api/vessels` cache |
+ | OpenSky OAuth (`OPENSKY_CLIENT_ID/SECRET`) | Server only | Server mints + refreshes the token behind `/api/flights` |
-| `GOOGLE_MAPS_SERVER_API_KEY` (optional, #33) | Server only | Server calls Places (`/api/google/nearby-places`, `/api/google/text-search`) and the Street View fallback with this key; falls back to `GOOGLE_MAPS_API_KEY` when unset |
+| `GOOGLE_MAPS_SERVER_API_KEY` (optional, #33) | Server only | Server calls Places (`/api/google/nearby-places`, `/api/google/text-search`), Geocoding (`/api/google/geocode`, `/api/google/reverse-geocode`) and the Street View fallback with this key; falls back to `GOOGLE_MAPS_API_KEY` when unset |
### Two deliberately client-side keys — restrict them
diff --cc server/providers/places/google.js
index a4aa48a78,a2225c606..1ddaa9593
--- a/server/providers/places/google.js
+++ b/server/providers/places/google.js
@@@ -1,24 -1,36 +1,38 @@@
import {
googleServerApiKey,
keylessGooglePlacesResponse,
+ keylessGoogleGeocodeResponse,
} from './google-key.js';
- import { makeOptInRateLimiter, clientKey } from '../common/rate-limit.js';
+ import { makeCostRateLimiter, clientKey } from '../common/rate-limit.js';
+ import { admitSameSite } from '../common/same-site.js';
+import { readResponseJsonCapped } from '../common/http.js';
import {
projectNearbyPlaces,
projectTextSearchPlaces,
} from '../../../src/data/placeProviderPayloads.js';
// Construct lazily after the standalone environment has loaded.
- // undefined = not built yet; null = unlimited; fn = active limiter
+ // undefined = not built yet; null = the explicit 0 opt-out; fn = active limiter
let _googleRateLimiter;
- /** Google cost endpoint (nearby-places). Null = unlimited (default). */
+ /**
+ * Requests/min/IP applied when GEV_RATELIMIT_GOOGLE_PER_MIN is unset. This is
+ * the value the Pinokio build already ships (pinokio/_ENVIRONMENT), so the
+ * packaged app keeps behaving exactly as it does today and only an
+ * unconfigured server changes — from unlimited to what the product already
+ * runs with. Places calls are user-driven (a search, a nearby lookup, an
+ * installation probe) rather than polled, so this sits far above what the app
+ * generates and bites only a caller enumerating the endpoint. `.env.example`
+ * suggests a tighter 60 when the host is not localhost; that still applies.
+ */
+ export const GOOGLE_DEFAULT_PER_MIN = 120;
+
-/** Google cost endpoints (nearby-places + text-search). Null only when set to 0. */
++/** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */
function googleRateLimiter() {
if (_googleRateLimiter === undefined)
- _googleRateLimiter = makeOptInRateLimiter(
+ _googleRateLimiter = makeCostRateLimiter(
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
+ GOOGLE_DEFAULT_PER_MIN,
);
return _googleRateLimiter;
}
@@@ -321,146 -293,6 +340,149 @@@ export function googlePlacesContextProx
);
}
});
+
+ /**
+ * Geocoding belongs on the server, not in the page. Google's Geocoding web
+ * service refuses referrer-restricted keys, so calling it from the browser
+ * forces GOOGLE_MAPS_API_KEY — which ships in the bundle by design — to be
+ * left unrestricted (#363). Here the request carries the server key, and
+ * the browser key no longer needs the Geocoding API at all.
+ *
+ * Unlike the two Places routes above, these answer in Google's own shape
+ * (`status` + `results`) rather than the `places: []` contract: the browser
+ * normalizers read that shape directly, and keeping it means the proxy adds
+ * a hop without adding a translation nobody asked for.
+ */
+ function installGeocodeRoute(path, readQuery) {
+ middlewares.use(path, async (req, res) => {
+ const refuse = (statusCode, error) => {
+ res.statusCode = statusCode;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({ status: 'REQUEST_DENIED', results: [], error }),
+ );
+ };
+
++ // Gate first, like the Places routes above: a cross-site caller learns
++ // nothing about this endpoint's method surface.
++ if (admitSameSite(req, res)) return;
+ if (req.method !== 'GET') {
+ refuse(405, 'Method not allowed');
+ return;
+ }
+
+ // A keyless geocode has no provider cost, so it resolves before the
+ // paid-endpoint limiter can consume or exhaust quota (mirrors the
+ // Places routes above).
+ const apiKey = resolveApiKey();
+ const keyless = keylessGoogleGeocodeResponse(apiKey);
+ if (keyless) {
+ res.statusCode = keyless.statusCode;
+ res.setHeader('Content-Type', 'application/json');
+ res.setHeader('Cache-Control', 'no-store');
+ res.end(JSON.stringify(keyless.payload));
+ return;
+ }
+
+ const requestUrl = new URL(req.url || '', 'http://localhost');
+ const query = readQuery(requestUrl.searchParams);
+ if (!query.ok) {
+ refuse(400, query.error);
+ return;
+ }
+
- // Opt-in per-IP throttle (GEV_RATELIMIT_GOOGLE_PER_MIN), shared with
- // the Places routes because both spend the same Google budget.
++ // Per-IP throttle (GEV_RATELIMIT_GOOGLE_PER_MIN), shared with the
++ // Places routes because both spend the same Google budget.
+ const _grl = googleRateLimiter();
+ if (_grl && !_grl(clientKey(req))) {
+ res.statusCode = 429;
+ res.setHeader('Content-Type', 'application/json');
+ res.setHeader('Retry-After', '5');
+ res.end(
+ JSON.stringify({
+ status: 'OVER_QUERY_LIMIT',
+ results: [],
+ error: 'Rate limit exceeded',
+ }),
+ );
+ return;
+ }
+
+ try {
+ const upstream = new URL(
+ endpoints.geocode ||
+ 'https://maps.googleapis.com/maps/api/geocode/json',
+ );
+ for (const [name, value] of Object.entries(query.params))
+ upstream.searchParams.set(name, value);
+ upstream.searchParams.set('key', apiKey);
+ const deadline = AbortSignal.timeout(GEOCODE_UPSTREAM_TIMEOUT_MS);
+ const response = await fetchImpl(upstream.toString(), {
+ redirect: 'error',
+ signal: deadline,
+ });
+ // An unreadable, oversized or timed-out body is not an answer: it
+ // falls through to the same shaped failure as a refusal below.
+ const data = await readResponseJsonCapped(
+ response,
+ GEOCODE_MAX_RESPONSE_BYTES,
+ deadline,
+ ).catch(() => null);
+
+ // A body we could not read is an upstream failure, not an answer with
+ // a status of its own, so it does not borrow the upstream's code.
+ if (!data) {
+ res.statusCode = 502;
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({
+ status: 'UNKNOWN_ERROR',
+ results: [],
+ error: 'Google Geocoding request failed',
+ }),
+ );
+ return;
+ }
+
+ res.statusCode = response.ok ? 200 : response.status;
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.setHeader('Cache-Control', 'private, max-age=300');
+ res.end(JSON.stringify(data));
+ } catch {
+ // Fixed public text: a transport, URL or runtime message would
+ // describe the server to the browser (SECURITY.md, sanitized errors).
+ res.statusCode = 502;
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({
+ status: 'UNKNOWN_ERROR',
+ results: [],
+ error: 'Google Geocoding request failed',
+ }),
+ );
+ }
+ });
+ }
+
+ installGeocodeRoute('/api/google/geocode', (searchParams) => {
+ const address = validateGeocodeAddress(searchParams);
+ if (!address.ok) return address;
+ const bounds = geocodeBounds(searchParams);
+ return {
+ ok: true,
+ params: {
+ address: address.address,
+ ...(bounds ? { bounds } : {}),
+ },
+ };
+ });
+
+ installGeocodeRoute('/api/google/reverse-geocode', (searchParams) => {
+ const coordinates = validatePlacesCoordinates(searchParams);
+ if (!coordinates.ok) return coordinates;
+ const { latitude, longitude } = coordinates;
+ return { ok: true, params: { latlng: `${latitude},${longitude}` } };
+ });
}
return {