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 upstream main into ChatGPT Realtime OAuth

devv-shayan6c88b781401a
diff --cc docs/CURRENT-STATE.md
index 410e648aa,7c06724e2..e768be94e
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -3835,14 -4134,14 +4134,14 @@@ are omitted rather than framing the wro
- GBFS proxy refuses upstream redirects (`redirect: 'manual'`; any 3xx becomes a 502 and the redirect target is logged server-side only) and enforces its 5 MB response cap while the body streams, cancelling the upstream read past the cap; CCTV health map is bounded.
- Proxy error payloads are sanitized (no internal error details returned to clients).
- That holds for the OpenAI and CCTV media paths too: `/api/openai/hud-summary` never relays OpenAI's own `error.message`, `/api/realtime/token` passes successful ephemeral-token responses through but answers with a fixed error when minting fails or upstream rejects the request, and a failed CCTV media fetch stores a fixed camera health `message` — `GET /api/cctv/health` serializes that field and the CCTV panel renders it as a status label, so it is a client surface as much as the response body is.
-- `OPENAI_API_KEY` is server-side only; the browser receives ephemeral Realtime client secrets from `/api/realtime/token`.
+- `OPENAI_API_KEY` remains server-side only and remains the default voice credential. The optional OAuth mode reads the local ChatGPT/Codex access token server-side on loopback only; the browser receives only ephemeral Realtime client secrets from `/api/realtime/token`.
- - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/ais-live` cache.
+ - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache.
- `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context.
- `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution.
- - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, mirror fallback, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded.
- - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation/traffic capacity.
+ - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded.
+ - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity.
- `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors.
- - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI).
+ - Track endpoints: `/api/vessels/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/flights/track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/military/track?hex=` (60s cache, 5MB cap, ODbL attribution required in UI).
- Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped.
- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message.
diff --cc server/providers/openai.js
index ac1fcd1a7,e5d84e0a9..6e8c65281
--- a/server/providers/openai.js
+++ b/server/providers/openai.js
@@@ -1,11 -1,8 +1,12 @@@
import { defaultSourceRoot } from './common/source-root.js';
import { handleHudSummary } from './openai/hud-summary.js';
import { createDebugLogHandler } from './openai/debug-log.js';
-import { createRealtimeTokenHandler } from './openai/realtime.js';
+import {
+ createRealtimeOAuthLoginHandler,
+ createRealtimeOAuthStatusHandler,
+ createRealtimeTokenHandler,
+} from './openai/realtime.js';
+ import { sameSiteGated } from './common/same-site.js';
/**
* Vite plugin: OpenAI Realtime ephemeral client secret.
@@@ -28,18 -27,10 +31,20 @@@ function openAiRealtimeProxy(
middlewares.use(
'/api/realtime/token',
- createRealtimeTokenHandler({ ...realtime, annotationGuidance }),
+ sameSiteGated(
+ createRealtimeTokenHandler({ ...realtime, annotationGuidance }),
+ ),
);
+
+ middlewares.use(
+ '/api/realtime/oauth-status',
+ createRealtimeOAuthStatusHandler(realtime),
+ );
+
+ middlewares.use(
+ '/api/realtime/oauth-login',
+ createRealtimeOAuthLoginHandler(realtime),
+ );
}
return {
diff --cc server/providers/openai/realtime.js
index 1869ebd24,2f513b7e2..44f0f9529
--- a/server/providers/openai/realtime.js
+++ b/server/providers/openai/realtime.js
@@@ -174,9 -19,8 +174,10 @@@ function createRealtimeTokenHandler(
endpoint = 'https://api.openai.com/v1/realtime/client_secrets',
fetchImpl = (...args) => fetch(...args),
resolveApiKey = () => process.env.OPENAI_API_KEY,
+ resolveOAuthAccessToken = () => readCodexOAuthAccessToken(),
+ environment = process.env,
models = {},
+ tools = GEV_REALTIME_TOOLS,
} = {}) {
return async (req, res) => {
res.setHeader('Cache-Control', 'no-store');
@@@ -187,85 -31,16 +188,85 @@@
return;
}
- // Per-IP throttle (GEV_RATELIMIT_OPENAI_PER_MIN). On by default; 0 disables.
- if (!enforceRateLimit(openAiRateLimiter(), req, res)) return;
+ const query = requestQuery(req);
+ const authMode = resolveRealtimeAuthMode(query);
+ if (!authMode) {
+ res.statusCode = 400;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(JSON.stringify({ error: 'Unsupported cloud voice auth mode' }));
+ return;
+ }
- const apiKey = resolveApiKey();
- if (!apiKey) {
+ let oauthPinned;
+ try {
+ oauthPinned = preferCodexOAuth(environment);
+ } catch (error) {
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
- res.end(JSON.stringify({ error: 'OPENAI_API_KEY is not set' }));
+ res.end(JSON.stringify({ error: error.message }));
return;
}
+ if (oauthPinned && authMode !== 'oauth') {
+ res.statusCode = 503;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({
+ error:
+ 'ChatGPT OAuth is required by GEV_PREFER_CODEX_OAUTH. Select USE CHATGPT OAUTH in Provider Settings.',
+ code: 'CODEX_OAUTH_REQUIRED',
+ }),
+ );
+ return;
+ }
+
- // Opt-in per-IP throttle (GEV_RATELIMIT_OPENAI_PER_MIN). No-op when unset.
- if (!enforceOptInRateLimit(openAiRateLimiter(), req, res)) return;
++ // Per-IP throttle (GEV_RATELIMIT_OPENAI_PER_MIN). On by default; 0 disables.
++ if (!enforceRateLimit(openAiRateLimiter(), req, res)) return;
+
+ let bearer;
+ if (authMode === 'oauth') {
+ if (!isLoopbackRequest(req)) {
+ res.statusCode = 403;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({
+ error: 'ChatGPT OAuth voice is available only from this machine',
+ }),
+ );
+ return;
+ }
+ try {
+ bearer = resolveOAuthAccessToken();
+ } catch (error) {
+ res.statusCode = 503;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({
+ error: error?.message || 'ChatGPT sign-in is unavailable',
+ code: 'CODEX_OAUTH_UNAVAILABLE',
+ }),
+ );
+ return;
+ }
+ if (!bearer) {
+ res.statusCode = 503;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({
+ error: 'ChatGPT sign-in is unavailable',
+ code: 'CODEX_OAUTH_UNAVAILABLE',
+ }),
+ );
+ return;
+ }
+ } else {
+ bearer = resolveApiKey();
+ if (!bearer) {
+ res.statusCode = 503;
+ res.setHeader('Content-Type', 'application/json');
+ res.end(JSON.stringify({ error: 'OPENAI_API_KEY is not set' }));
+ return;
+ }
+ }
// Voice model tier, requested by the client as ?tier=standard|mini.
// resolveVoiceModel is total: an unknown, empty, or hostile value
diff --cc src/tooling/localServices.test.mjs
index 408dbbbc3,6533f1011..05296ec7e
--- a/src/tooling/localServices.test.mjs
+++ b/src/tooling/localServices.test.mjs
@@@ -196,176 -196,40 +197,210 @@@ test('Realtime handler preserves tools
assert.equal(sent[0].session.instructions, sent[2].session.instructions);
});
+test('Realtime handler keeps API key as default and uses OAuth only when requested', async (t) => {
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ let oauthReads = 0;
+ const authorizations = [];
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveApiKey: () => 'fixture-api-key',
+ resolveOAuthAccessToken: () => {
+ oauthReads += 1;
+ return 'fixture-oauth-token';
+ },
+ fetchImpl: async (_url, options) => {
+ authorizations.push(options.headers.Authorization);
+ return Response.json({ value: 'fixture-ephemeral' });
+ },
+ },
+ }),
+ );
+ const token = routes.get('/api/realtime/token');
+
+ const apiResponse = await request(token);
+ assert.equal(apiResponse.status, 200);
+ assert.equal(apiResponse.headers['x-gev-voice-auth'], 'env');
+ assert.equal(oauthReads, 0, 'default cloud voice does not read OAuth');
+ assert.equal(authorizations.at(-1), 'Bearer fixture-api-key');
+
+ const oauthResponse = await request(token, { url: '/?auth=oauth' });
+ assert.equal(oauthResponse.status, 200);
+ assert.equal(oauthResponse.headers['x-gev-voice-auth'], 'codex-oauth');
+ assert.equal(oauthReads, 1);
+ assert.equal(authorizations.at(-1), 'Bearer fixture-oauth-token');
+});
+
+test('a Codex OAuth pin refuses API-key minting without silently switching modes', async (t) => {
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ const authorizations = [];
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ environment: { GEV_PREFER_CODEX_OAUTH: 'true' },
+ resolveApiKey: () => assert.fail('pinned OAuth cannot read an API key'),
+ resolveOAuthAccessToken: () => 'fixture-oauth-token',
+ fetchImpl: async (_url, options) => {
+ authorizations.push(options.headers.Authorization);
+ return Response.json({ value: 'fixture-ephemeral' });
+ },
+ },
+ }),
+ );
+ const token = routes.get('/api/realtime/token');
+ const refused = await request(token);
+ assert.equal(refused.status, 503);
+ assert.equal(refused.json().code, 'CODEX_OAUTH_REQUIRED');
+ assert.equal(authorizations.length, 0);
+ assert.equal((await request(token, { url: '/?auth=oauth' })).status, 200);
+ assert.deepEqual(authorizations, ['Bearer fixture-oauth-token']);
+});
+
+test('OAuth status and token minting never expose local OAuth to remote clients', async () => {
+ let oauthReads = 0;
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => {
+ oauthReads += 1;
+ return 'must-not-be-read-remotely';
+ },
+ fetchImpl: () =>
+ assert.fail('remote OAuth request must not reach OpenAI'),
+ },
+ }),
+ );
+ const remote = { remoteAddress: '192.168.1.20' };
+ assert.equal(
+ (await request(routes.get('/api/realtime/oauth-status'), remote)).status,
+ 403,
+ );
+ assert.equal(
+ (
+ await request(routes.get('/api/realtime/token'), {
+ ...remote,
+ url: '/?auth=oauth',
+ })
+ ).status,
+ 403,
+ );
+ assert.equal(oauthReads, 0);
+});
+
+test('OAuth status reports local sign-in availability without returning the token', async () => {
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: { resolveOAuthAccessToken: () => 'fixture-oauth-secret' },
+ }),
+ );
+ const response = await request(routes.get('/api/realtime/oauth-status'));
+ assert.equal(response.status, 200);
+ assert.deepEqual(response.json(), { available: true });
+ assert.equal(response.body.includes('fixture-oauth-secret'), false);
+});
+
+test('OAuth login endpoint launches local Codex sign-in once and never exposes credentials', async () => {
+ let starts = 0;
+ let clock = 1_000;
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => {
+ throw new Error('not signed in');
+ },
+ startOAuthLogin: async () => {
+ starts += 1;
+ },
+ now: () => clock,
+ },
+ }),
+ );
+ const handler = routes.get('/api/realtime/oauth-login');
+
+ const started = await request(handler, { method: 'POST' });
+ assert.equal(started.status, 202);
+ assert.deepEqual(started.json(), {
+ available: false,
+ started: true,
+ pending: true,
+ });
+ assert.equal(starts, 1);
+
+ clock += 1_000;
+ const duplicate = await request(handler, { method: 'POST' });
+ assert.equal(duplicate.status, 202);
+ assert.equal(duplicate.json().pending, true);
+ assert.equal(starts, 1, 'rapid retries must not spawn another login');
+
+ const remote = await request(handler, {
+ method: 'POST',
+ remoteAddress: '192.168.1.20',
+ });
+ assert.equal(remote.status, 403);
+ assert.equal(starts, 1);
+
+ const crossOrigin = await request(handler, {
+ method: 'POST',
+ origin: 'https://example.com',
+ });
+ assert.equal(crossOrigin.status, 403);
+ assert.equal(starts, 1);
+});
+
+test('OAuth login endpoint selects an existing local sign-in without launching Codex', async () => {
+ const handler = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => 'fixture-existing-secret',
+ startOAuthLogin: () =>
+ assert.fail('existing auth must not launch login'),
+ },
+ }),
+ ).get('/api/realtime/oauth-login');
+ const response = await request(handler, { method: 'POST' });
+ assert.equal(response.status, 200);
+ assert.deepEqual(response.json(), {
+ available: true,
+ started: false,
+ pending: false,
+ });
+ assert.equal(response.body.includes('fixture-existing-secret'), false);
+});
+
+ test('Realtime sessions carry supplied tools, and the standalone voice adds the catalog queries', async (t) => {
+ env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ const sent = [];
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
+ sent.push(JSON.parse(options.body));
+ return Response.json({ value: 'fixture-ephemeral' });
+ });
+ const tools = standaloneVoiceTools();
+ const response = await request(
+ install(openAiRealtimeProxy({ realtime: { tools } })).get(
+ '/api/realtime/token',
+ ),
+ );
+ assert.equal(response.status, 200);
+ assert.deepEqual(sent.at(-1).session.tools, tools);
+ const names = tools.map((tool) => tool.name);
+ assert.equal(new Set(names).size, names.length);
+ assert.deepEqual(
+ tools.slice(0, GEV_REALTIME_TOOLS.length),
+ GEV_REALTIME_TOOLS,
+ );
+ assert.ok(names.includes('get_weather'));
+ assert.ok(names.includes('military_awareness'));
+ assert.ok(!names.includes('show_in_gods_eye_view'));
+ assert.ok(!names.includes('aircraft_in_area'));
+ assert.ok(!names.includes('get_weather_map'));
+ // The action of the same name answers satellite passes.
+ assert.equal(
+ tools.findLast((tool) => tool.name === 'next_satellite_pass'),
+ GEV_REALTIME_TOOLS.find((tool) => tool.name === 'next_satellite_pass'),
+ );
+ });
+
test('debug logging resolves each supplied application directory independently', async (t) => {
const first = root(t),
second = root(t);