From 5738cdc45ce49d54d06ee6ce9a71614b001dac77 Mon Sep 17 00:00:00 2001 From: Denis Groshev Date: Wed, 4 Nov 2026 16:25:38 +0100 Subject: [PATCH 01/10] fix(cockpit): centre the phone Display/Radio row above the flight readouts On phones (<=760 px) the collapsed Display/Radio launcher row was right-anchored at bottom: 152px, off the Reset/Exit axis and on top of the ground speed and altitude readouts. Centre it and anchor it above the compass block through a shared --cockpit-compass-bottom variable; only the launchers take pointer input. Cyber's top row is centred too. --- docs/CURRENT-STATE.md | 7 ++++- scripts/qa-cockpit-utility.mjs | 50 ++++++++++++++++++++++++++++++++++ src/cockpitMarkup.test.mjs | 8 +++++- src/ui/styles/cockpit.css | 19 +++++++++++-- src/ui/styles/cyber.css | 4 +++ 5 files changed, 83 insertions(+), 5 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index c3e15ea4d2..11b2f28f6f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3255,7 +3255,12 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > stacking. Narrow mobile Cockpit > viewports suppress the legacy layer stack, peripheral HUD, and secondary > Context/briefing panes so the flight instruments and primary controls remain -> unobstructed. Outside Cockpit, Radio starts collapsed while off and lives +> unobstructed. There the collapsed Display and Radio launchers form one row +> centred on the Reset/Exit axis; the default theme anchors it above the +> compass block, clear of the ground speed and altitude telemetry it used to +> cover, while Cyber keeps the row at the top. `scripts/qa-cockpit-utility.mjs` +> checks the default row's centring and clearance at 390 and 360 px. Outside +> Cockpit, Radio starts collapsed while off and lives > only in its section inside Context; the detailed panel's normal accordion > control owns its disclosure and its Enable/Disable action owns power. > Radio volume in the full and Cockpit surfaces, plus Space Mission diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index c5a94018fa..7b1b860723 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -2321,6 +2321,56 @@ try { JSON.stringify(narrowViewActions), ); + // The collapsed Display/Radio row on a phone: centred on the Reset/Exit + // axis and clear of the ground speed and altitude telemetry it once covered. + for (const [width, height] of [[390, 844], [360, 740]]) { + await page.setViewport({ width, height, deviceScaleFactor: 1 }); + const phoneRow = await page.evaluate(async () => { + const manager = window.__godsEyeView.styleManager; + manager._setCockpitDisclosure('display', false); + manager._setCockpitDisclosure('radio', false); + await new Promise(requestAnimationFrame); + manager.cockpitView.syncSignalLayout(); + await new Promise(requestAnimationFrame); + const rect = (element) => element?.getBoundingClientRect().toJSON() || null; + const launchers = [...document.querySelectorAll( + '#cockpit-utility-controls .cockpit-utility-control', + )].map(rect); + return { + launchers, + speed: rect(document.querySelector('#cockpit-hud .cockpit-speed')), + altitude: rect(document.querySelector('#cockpit-hud .cockpit-altitude')), + switcher: rect(document.getElementById('view-switcher')), + viewport: { width: innerWidth, height: innerHeight }, + // Cyber parks its row at the top; this check is the default theme's. + theme: document.documentElement.dataset.uiTheme || 'default', + }; + }); + const overlaps = (a, b) => Boolean(a && b) + && a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; + const rowLeft = Math.min(...phoneRow.launchers.map((launcher) => launcher.left)); + const rowRight = Math.max(...phoneRow.launchers.map((launcher) => launcher.right)); + const switcherCentre = phoneRow.switcher + ? (phoneRow.switcher.left + phoneRow.switcher.right) / 2 + : NaN; + check( + `${width}px Cockpit Display/Radio row is centred and clear of the speed and altitude readouts`, + phoneRow.launchers.length === 2 + && phoneRow.launchers.every((launcher) => launcher.width > 0) + && phoneRow.theme !== 'cyber' + && phoneRow.speed?.width > 0 + && phoneRow.altitude?.width > 0 + && phoneRow.launchers.every((launcher) => ( + !overlaps(launcher, phoneRow.speed) && !overlaps(launcher, phoneRow.altitude) + )) + && Math.abs((rowLeft + rowRight) / 2 - switcherCentre) <= 2 + && rowLeft >= 0 + && rowRight <= phoneRow.viewport.width, + JSON.stringify(phoneRow), + ); + } + await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 1 }); + const resetResult = await page.evaluate(() => { // Both the UI and compatibility facade delegate to this navigation owner. const manager = window.__godsEyeView.styleManager._locationNavigation; diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 64d03914bd..3ce5918cb2 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -1137,10 +1137,16 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls' assert.match(mobileCockpit[1], /body\.cockpit-mode #intel-hud/); assert.match(mobileCockpit[1], /body\.cockpit-mode \.cockpit-context-window/); assert.match(mobileCockpit[1], /body\.cockpit-mode \.cockpit-signal-window/); + // The collapsed Display/Radio row is centred on the Reset/Exit axis and + // anchored above the compass block, not at a fixed offset that covered the + // ground speed and altitude readouts; the compass reads the same anchor. assert.match( mobileCockpit[1], - /body\.cockpit-mode \.cockpit-utility-controls[\s\S]*?bottom:\s*152px;/, + /body\.cockpit-mode \.cockpit-utility-controls \{[\s\S]*?bottom:\s*calc\(var\(--cockpit-compass-bottom\) \+ 182px\);[\s\S]*?left:\s*12px;[\s\S]*?justify-content:\s*center;/, ); + assert.doesNotMatch(mobileCockpit[1], /bottom:\s*152px;/); + assert.match(css, /\.cockpit-compass \{[\s\S]*?bottom:\s*var\(--cockpit-compass-bottom\);/); + assert.match(css, /--cockpit-compass-bottom:\s*clamp\(44px, 7vh, 72px\);/); assert.match( mobileCockpit[1], /body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/, diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index befbfbbff4..ae9e8025b0 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -48,6 +48,9 @@ --cockpit-side-panel-width: min(340px, 28vw); /* HUD bottom offset + tallest scaled telemetry block + 20px clear border. */ --cockpit-bottom-rail-safe: calc(clamp(84px, 11vh, 118px) + 100px); + /* The compass block's bottom edge; the phone Display/Radio row sits above + the telemetry it carries. */ + --cockpit-compass-bottom: clamp(44px, 7vh, 72px); position: fixed; inset: 0; z-index: 145; @@ -645,7 +648,7 @@ html:not([lang='en']) .cockpit-roll-token.is-separator { .cockpit-compass { position: absolute; left: 50%; - bottom: clamp(44px, 7vh, 72px); + bottom: var(--cockpit-compass-bottom); width: min(760px, 72vw); transform: translateX(-50%) rotateX(7deg) translateZ(18px); transform-style: preserve-3d; @@ -2076,15 +2079,25 @@ body.cockpit-mode #intel-hud .hud-right-edge { body.cockpit-mode #right-context-rail { display: none !important; } + /* A centred row above the compass block: its ground speed and altitude + telemetry tops out ~171px above the block's bottom edge on phones, so + the row clears it by ~10px and stays on the same axis as RESET/EXIT. + The row spans the width to centre its launchers; only they take input. */ body.cockpit-mode .cockpit-utility-controls { top: auto; right: 12px; - bottom: 152px; - max-width: calc(100vw - 24px); + bottom: calc(var(--cockpit-compass-bottom) + 182px); + left: 12px; + justify-content: center; + max-width: none; + pointer-events: none; } body.cockpit-mode .cockpit-utility-controls { flex-direction: row; } + body.cockpit-mode .cockpit-utility-control { + pointer-events: auto; + } body.cockpit-mode .cockpit-utility-launcher { width: min(150px, calc((100vw - 31px) / 2)); min-height: 42px; diff --git a/src/ui/styles/cyber.css b/src/ui/styles/cyber.css index 4957cd7697..d7c0c174ea 100644 --- a/src/ui/styles/cyber.css +++ b/src/ui/styles/cyber.css @@ -2892,10 +2892,14 @@ max-height: min(48vh, 440px); } + /* Centred like the default theme's phone row; the desktop panel width + would otherwise pin it left of the Reset/Exit axis. */ :root[data-ui-theme='cyber'] body.cockpit-mode .cockpit-utility-controls { top: 92px !important; right: 12px; bottom: auto; + left: 12px; + width: auto; } :root[data-ui-theme='cyber'] From 1165286c7bf0a9345b02d81842220f1afcb7c59f Mon Sep 17 00:00:00 2001 From: Denis Groshev Date: Wed, 4 Nov 2026 16:26:11 +0100 Subject: [PATCH 02/10] docs(changelog): add the phone Cockpit utility row fragment --- changelog.d/1549-cockpit-phone-utility-row.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/1549-cockpit-phone-utility-row.md diff --git a/changelog.d/1549-cockpit-phone-utility-row.md b/changelog.d/1549-cockpit-phone-utility-row.md new file mode 100644 index 0000000000..bccc2ea27f --- /dev/null +++ b/changelog.d/1549-cockpit-phone-utility-row.md @@ -0,0 +1,5 @@ +- Keep the phone Cockpit's Display and Radio launchers off the flight + readouts. At 760 px wide and below, the collapsed row now sits centred on the + Reset/Exit axis above the compass block instead of right-anchored over the + ground speed and altitude telemetry; Cyber's top row is centred too (Denis + Groshev, @ZloyS, #1549). From 7af0453f3460bc5b4c48f05df88dfda78ac34a7f Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 01:05:50 +0000 Subject: [PATCH 03/10] CCTV Street View fallback: catalog cameras only, at their catalog position, inside the Google budget --- server/providers/cctv.js | 33 +++++++++++++++-------------- server/providers/places/google.js | 4 ++-- src/data/cctvMediaFeedType.test.mjs | 27 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/server/providers/cctv.js b/server/providers/cctv.js index a977f4e753..64605b9852 100644 --- a/server/providers/cctv.js +++ b/server/providers/cctv.js @@ -19,6 +19,8 @@ import { admitSameSiteKeyless } from './common/same-site.js'; import { PROXY_SIGNALS } from '../../src/localRequestGate.mjs'; import { createHlsPuller } from './cctv/stream.js'; import { googleServerApiKey } from './places/google-key.js'; +import { googleRateLimiter } from './places/google.js'; +import { clientKey } from './common/rate-limit.js'; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; /** * Vite plugin: CCTV camera proxy with source registry, frame/media serving, @@ -509,13 +511,6 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { const source = sourceById.get(cameraId); const label = url.searchParams.get('label') || source?.name || cameraId; const city = url.searchParams.get('city') || source?.city || ''; - const lat = Number(url.searchParams.get('lat') || source?.lat); - const lon = Number(url.searchParams.get('lon') || source?.lon); - const heading = Number( - url.searchParams.get('heading') || source?.headingDeg, - ); - const fov = Number(url.searchParams.get('fov') || source?.fovDeg); - const pitch = Number(url.searchParams.get('pitch') || source?.pitchDeg); // Only use server-registered upstream URLs — never accept client-supplied URLs // (prevents SSRF via ?upstream= query parameter) @@ -549,18 +544,24 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { // request (whose client this server cannot see) gets the placeholder, // as if no key were configured. Any forwarding header counts, even an // empty one. + // It is also only for catalog cameras, framed from the catalog (never + // a spot the query names), within the per-IP Google budget. const forwarded = PROXY_SIGNALS.some( (name) => req.headers?.[name] !== undefined, ); - const sv = forwarded - ? null - : await streetViewFallback({ - lat, - lon, - heading, - fov, - pitch, - }); + const googleBudget = googleServerApiKey() ? googleRateLimiter() : null; + const sv = + forwarded || + !source || + (googleBudget && !googleBudget(clientKey(req))) + ? null + : await streetViewFallback({ + lat: Number(source.lat), + lon: Number(source.lon), + heading: Number(source.headingDeg), + fov: Number(source.fovDeg), + pitch: Number(source.pitchDeg ?? -10), + }); if (sv?.ok) { setHealth(cameraId, { status: 'degraded', diff --git a/server/providers/places/google.js b/server/providers/places/google.js index 1ddaa95939..5b034e7064 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -27,8 +27,8 @@ let _googleRateLimiter; */ export const GOOGLE_DEFAULT_PER_MIN = 120; -/** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */ -function googleRateLimiter() { +/** Google cost endpoints (nearby-places, text-search, geocoding, the CCTV Street View fallback). Null only when set to 0. */ +export function googleRateLimiter() { if (_googleRateLimiter === undefined) _googleRateLimiter = makeCostRateLimiter( process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, diff --git a/src/data/cctvMediaFeedType.test.mjs b/src/data/cctvMediaFeedType.test.mjs index 04dd77e284..0523c95f39 100644 --- a/src/data/cctvMediaFeedType.test.mjs +++ b/src/data/cctvMediaFeedType.test.mjs @@ -528,3 +528,30 @@ test('a forwarded same-origin request reaches every CCTV route but not the Stree assert.equal(direct.body, 'street-view'); assert.equal(streetViewCalls(), 1); }); + +test('the Street View fallback frames catalog cameras only, from the catalog position', async (t) => { + const app = mount(t, ({ url }) => + url.startsWith('https://maps.googleapis.com/') + ? trackedUpstream({ + headers: { 'content-type': 'image/jpeg' }, + body: 'street-view', + }).response + : upstreamResponse({ status: 503 }), + ); + process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; + const streetView = () => + app.requests.filter(({ url }) => + url.startsWith('https://maps.googleapis.com/'), + ); + + const unknown = await app.call('/frame/not-a-camera?lat=48.85&lon=2.29'); + assert.equal(unknown.headers['X-CCTV-Source'], 'synthetic'); + assert.deepEqual(streetView(), [], 'no Google call for an unknown id'); + + const steered = await app.call( + `/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90`, + ); + assert.equal(steered.headers['X-CCTV-Source'], 'streetview'); + const location = new URL(streetView()[0].url).searchParams.get('location'); + assert.equal(location, `${STILL.lat},${STILL.lon}`); +}); From 078a6c0db0288df57bd373ae28ca9948d94016aa Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 01:09:11 +0000 Subject: [PATCH 04/10] CCTV Street View fallback: own per-IP Google budget inside the cctv package boundary --- scripts/package-boundaries.json | 4 +++- server/providers/cctv.js | 21 ++++++++++++++++++--- server/providers/places/google.js | 4 ++-- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 20f6c0b85d..b764667f07 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -377,7 +377,9 @@ "src/data/cctvFootprint.js", "src/sources/cctvTypes.js", "src/sources/httpBody.js", - "src/i18n/marker.js" + "src/i18n/marker.js", + "server/providers/common/rate-limit.js", + "src/sources/rateLimit.js" ], "external": [] }, diff --git a/server/providers/cctv.js b/server/providers/cctv.js index 64605b9852..e8e18ad51e 100644 --- a/server/providers/cctv.js +++ b/server/providers/cctv.js @@ -19,9 +19,22 @@ import { admitSameSiteKeyless } from './common/same-site.js'; import { PROXY_SIGNALS } from '../../src/localRequestGate.mjs'; import { createHlsPuller } from './cctv/stream.js'; import { googleServerApiKey } from './places/google-key.js'; -import { googleRateLimiter } from './places/google.js'; -import { clientKey } from './common/rate-limit.js'; +import { clientKey, makeCostRateLimiter } from './common/rate-limit.js'; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; +let _streetViewRateLimiter; +/** + * Per-IP budget for the Street View fallback, on the same setting as the + * other Google routes (GEV_RATELIMIT_GOOGLE_PER_MIN; 0 disables it). + */ +function streetViewRateLimiter() { + if (_streetViewRateLimiter === undefined) + _streetViewRateLimiter = makeCostRateLimiter( + process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, + 120, + ); + return _streetViewRateLimiter; +} + /** * Vite plugin: CCTV camera proxy with source registry, frame/media serving, * fallback chain (upstream -> Street View -> synthetic SVG), and health tracking. @@ -549,7 +562,9 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { const forwarded = PROXY_SIGNALS.some( (name) => req.headers?.[name] !== undefined, ); - const googleBudget = googleServerApiKey() ? googleRateLimiter() : null; + const googleBudget = googleServerApiKey() + ? streetViewRateLimiter() + : null; const sv = forwarded || !source || diff --git a/server/providers/places/google.js b/server/providers/places/google.js index 5b034e7064..1ddaa95939 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -27,8 +27,8 @@ let _googleRateLimiter; */ export const GOOGLE_DEFAULT_PER_MIN = 120; -/** Google cost endpoints (nearby-places, text-search, geocoding, the CCTV Street View fallback). Null only when set to 0. */ -export function googleRateLimiter() { +/** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */ +function googleRateLimiter() { if (_googleRateLimiter === undefined) _googleRateLimiter = makeCostRateLimiter( process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, From f0d3db31646be8dd5b504b4f49922d71c07116bd Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 11:57:58 +0000 Subject: [PATCH 05/10] Docs: the CCTV Street View fallback serves catalog cameras only, inside the Google budget --- docs/CURRENT-STATE.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8ad23493a4..019e25704e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1276,7 +1276,10 @@ and follows redirects only on the camera's origin. Catalog image URLs, and redirects on those hosts, are pinned by parsed URL to the agency's image directory. Every `/api/cctv` route refuses cross-site browser requests but accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded -request skips the key-bearing Street View fallback and gets the placeholder. +request skips the key-bearing Street View fallback and gets the placeholder. The +Street View fallback serves only catalog cameras, at the catalog position, +heading, field of view and pitch, never coordinates a request supplies, and it +shares the per-client Google budget (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120). The CCTV layer draws only the cameras on or near the screen. Zoomed out, it keeps one camera per ground cell sized to the view, preferring a healthy feed, From f579b23f520a51e69b158222207088baa3f1b205 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 11:59:32 +0000 Subject: [PATCH 06/10] Changelog: 1602 fragment --- changelog.d/1602-cctv-streetview-fallback-catalog.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/1602-cctv-streetview-fallback-catalog.md diff --git a/changelog.d/1602-cctv-streetview-fallback-catalog.md b/changelog.d/1602-cctv-streetview-fallback-catalog.md new file mode 100644 index 0000000000..04574b9142 --- /dev/null +++ b/changelog.d/1602-cctv-streetview-fallback-catalog.md @@ -0,0 +1,5 @@ +- The CCTV Street View fallback serves only catalog cameras, at their catalog + position, heading, field of view and pitch, and ignores coordinates a + request supplies. It spends from the per-client Google budget + (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120), so the Google key can no + longer be used as an unmetered Street View service (asturksever, #1602). From 4b8a407ba27ca01053571bf2c33de32daad53189 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:54:59 +0400 Subject: [PATCH 07/10] fix(cockpit): keep the phone Display/Radio row clear of the DEST cue Above the compass block the centred row covered the DEST route-direction label and chevron at 320-390 px, and its fixed +182px offset pushed it off the top of short landscape screens. Place it between the roll scale and the reticle from a viewport-aware visor inset instead, keep it on screen below the vision controls on short landscape phones, and centre Cyber's expanded panel on the Reset/Exit axis. The unit test now asserts the pointer-events contract and Cyber centring; the browser QA adds the DEST cue to the clearance check, hit-tests each launcher glyph and covers 740x360 and 667x240. --- changelog.d/1549-cockpit-phone-utility-row.md | 7 ++- docs/CURRENT-STATE.md | 16 +++--- scripts/qa-cockpit-utility.mjs | 56 +++++++++++++++---- src/cockpitMarkup.test.mjs | 21 +++++-- src/ui/styles/cockpit.css | 20 +++---- src/ui/styles/cyber.css | 10 +++- 6 files changed, 87 insertions(+), 43 deletions(-) diff --git a/changelog.d/1549-cockpit-phone-utility-row.md b/changelog.d/1549-cockpit-phone-utility-row.md index bccc2ea27f..9e091467a1 100644 --- a/changelog.d/1549-cockpit-phone-utility-row.md +++ b/changelog.d/1549-cockpit-phone-utility-row.md @@ -1,5 +1,6 @@ - Keep the phone Cockpit's Display and Radio launchers off the flight - readouts. At 760 px wide and below, the collapsed row now sits centred on the - Reset/Exit axis above the compass block instead of right-anchored over the - ground speed and altitude telemetry; Cyber's top row is centred too (Denis + instruments. At 760 px wide and below, the collapsed row now sits centred on + the Reset/Exit axis between the roll scale and the reticle, instead of + right-anchored over the ground speed and altitude telemetry, and stays on + screen on short landscape phones. Cyber's top row is centred too (Denis Groshev, @ZloyS, #1549). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 11b2f28f6f..17d10e4d8b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3256,13 +3256,15 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > viewports suppress the legacy layer stack, peripheral HUD, and secondary > Context/briefing panes so the flight instruments and primary controls remain > unobstructed. There the collapsed Display and Radio launchers form one row -> centred on the Reset/Exit axis; the default theme anchors it above the -> compass block, clear of the ground speed and altitude telemetry it used to -> cover, while Cyber keeps the row at the top. `scripts/qa-cockpit-utility.mjs` -> checks the default row's centring and clearance at 390 and 360 px. Outside -> Cockpit, Radio starts collapsed while off and lives -> only in its section inside Context; the detailed panel's normal accordion -> control owns its disclosure and its Enable/Disable action owns power. +> centred on the Reset/Exit axis. The default theme places it between the roll +> scale and the reticle, clear of the destination cue and flight readouts. +> On short landscape screens it stays on screen below the vision controls. +> Cyber keeps the row at the top. `scripts/qa-cockpit-utility.mjs` checks the +> default row's centring, clearance and tap targets at 390×844, 360×740, +> 740×360 and 667×240. Outside Cockpit, Radio starts collapsed while off +> and lives only in its section inside Context; the detailed panel's normal +> accordion control owns its disclosure and its Enable/Disable action +> owns power. > Radio volume in the full and Cockpit surfaces, plus Space Mission > replay speed, use Display / Sharpen's muted 3px rail, circular cyan thumb, > glow, and mono value treatment. Their larger transparent hit areas, keyboard diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index 7b1b860723..9122c8c7e2 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -2321,9 +2321,14 @@ try { JSON.stringify(narrowViewActions), ); - // The collapsed Display/Radio row on a phone: centred on the Reset/Exit - // axis and clear of the ground speed and altitude telemetry it once covered. - for (const [width, height] of [[390, 844], [360, 740]]) { + // Short screens have no free band between instruments. The launchers still + // need to stay on screen, accept taps and clear the vision controls. + for (const [width, height, room] of [ + [390, 844, 'portrait'], + [360, 740, 'portrait'], + [740, 360, 'landscape'], + [667, 240, 'short'], + ]) { await page.setViewport({ width, height, deviceScaleFactor: 1 }); const phoneRow = await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; @@ -2333,19 +2338,41 @@ try { manager.cockpitView.syncSignalLayout(); await new Promise(requestAnimationFrame); const rect = (element) => element?.getBoundingClientRect().toJSON() || null; - const launchers = [...document.querySelectorAll( + const hud = (selector) => document.querySelector(`#cockpit-hud ${selector}`); + const route = document.getElementById('cockpit-route-direction'); + const routeShown = Boolean(route && !route.hidden); + const controls = [...document.querySelectorAll( '#cockpit-utility-controls .cockpit-utility-control', - )].map(rect); + )]; return { - launchers, - speed: rect(document.querySelector('#cockpit-hud .cockpit-speed')), - altitude: rect(document.querySelector('#cockpit-hud .cockpit-altitude')), + launchers: controls.map(rect), + hits: controls.map((control) => { + const glyph = control.querySelector('.cockpit-utility-glyph'); + const box = glyph?.getBoundingClientRect(); + const target = box && document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return Boolean(target && glyph.contains(target)); + }), + speed: rect(hud('.cockpit-speed')), + altitude: rect(hud('.cockpit-altitude')), + route: routeShown ? rect(route) : null, + chevron: routeShown ? rect(route.querySelector('.cockpit-route-chevron')) : null, + reticle: rect(hud('.cockpit-reticle')), + rollArc: rect(hud('.cockpit-roll-arc')), + vision: rect(hud('.cockpit-vision-controls')), switcher: rect(document.getElementById('view-switcher')), viewport: { width: innerWidth, height: innerHeight }, // Cyber parks its row at the top; this check is the default theme's. theme: document.documentElement.dataset.uiTheme || 'default', }; }); + const obstacles = { + portrait: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'rollArc', 'vision'], + landscape: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'vision'], + short: ['vision'], + }[room]; const overlaps = (a, b) => Boolean(a && b) && a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; const rowLeft = Math.min(...phoneRow.launchers.map((launcher) => launcher.left)); @@ -2354,18 +2381,23 @@ try { ? (phoneRow.switcher.left + phoneRow.switcher.right) / 2 : NaN; check( - `${width}px Cockpit Display/Radio row is centred and clear of the speed and altitude readouts`, + `${width}×${height} Cockpit Display/Radio row is centred, on screen, tappable and clear of ${obstacles.join(', ')}`, phoneRow.launchers.length === 2 && phoneRow.launchers.every((launcher) => launcher.width > 0) && phoneRow.theme !== 'cyber' && phoneRow.speed?.width > 0 && phoneRow.altitude?.width > 0 - && phoneRow.launchers.every((launcher) => ( - !overlaps(launcher, phoneRow.speed) && !overlaps(launcher, phoneRow.altitude) + && phoneRow.hits.length === 2 + && phoneRow.hits.every(Boolean) + && phoneRow.launchers.every((launcher) => obstacles.every( + (name) => !overlaps(launcher, phoneRow[name]), )) && Math.abs((rowLeft + rowRight) / 2 - switcherCentre) <= 2 && rowLeft >= 0 - && rowRight <= phoneRow.viewport.width, + && rowRight <= phoneRow.viewport.width + && phoneRow.launchers.every((launcher) => ( + launcher.top >= 0 && launcher.bottom <= phoneRow.viewport.height + )), JSON.stringify(phoneRow), ); } diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 3ce5918cb2..36eef2bf14 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -1137,16 +1137,25 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls' assert.match(mobileCockpit[1], /body\.cockpit-mode #intel-hud/); assert.match(mobileCockpit[1], /body\.cockpit-mode \.cockpit-context-window/); assert.match(mobileCockpit[1], /body\.cockpit-mode \.cockpit-signal-window/); - // The collapsed Display/Radio row is centred on the Reset/Exit axis and - // anchored above the compass block, not at a fixed offset that covered the - // ground speed and altitude readouts; the compass reads the same anchor. assert.match( mobileCockpit[1], - /body\.cockpit-mode \.cockpit-utility-controls \{[\s\S]*?bottom:\s*calc\(var\(--cockpit-compass-bottom\) \+ 182px\);[\s\S]*?left:\s*12px;[\s\S]*?justify-content:\s*center;/, + /body\.cockpit-mode \.cockpit-utility-controls \{[^}]*?top:\s*clamp\(\s*72px,\s*calc\(46% - 68px\),\s*calc\(var\(--cockpit-visor-top\) \+ 108px\)\s*\);[^}]*?left:\s*12px;[^}]*?justify-content:\s*center;[^}]*?pointer-events:\s*none;/, + ); + assert.match( + mobileCockpit[1], + /body\.cockpit-mode \.cockpit-utility-control \{\s*pointer-events:\s*auto;\s*\}/, ); assert.doesNotMatch(mobileCockpit[1], /bottom:\s*152px;/); - assert.match(css, /\.cockpit-compass \{[\s\S]*?bottom:\s*var\(--cockpit-compass-bottom\);/); - assert.match(css, /--cockpit-compass-bottom:\s*clamp\(44px, 7vh, 72px\);/); + assert.match(css, /--cockpit-visor-top:\s*clamp\(62px, 9vh, 90px\);/); + assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/); + assert.match( + css, + /:root\[data-ui-theme='cyber'\] body\.cockpit-mode \.cockpit-utility-controls \{[^}]*?top:\s*92px !important;[^}]*?width:\s*auto;/, + ); + assert.match( + css, + /:root\[data-ui-theme='cyber'\]\s+body\.cockpit-mode\s+\.cockpit-utility-control\.is-expanded \{\s*right:\s*auto;\s*\}/, + ); assert.match( mobileCockpit[1], /body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/, diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index ae9e8025b0..b3cc9b0862 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -48,9 +48,8 @@ --cockpit-side-panel-width: min(340px, 28vw); /* HUD bottom offset + tallest scaled telemetry block + 20px clear border. */ --cockpit-bottom-rail-safe: calc(clamp(84px, 11vh, 118px) + 100px); - /* The compass block's bottom edge; the phone Display/Radio row sits above - the telemetry it carries. */ - --cockpit-compass-bottom: clamp(44px, 7vh, 72px); + /* The phone Display/Radio row shares the visor inset with the roll scale. */ + --cockpit-visor-top: clamp(62px, 9vh, 90px); position: fixed; inset: 0; z-index: 145; @@ -68,7 +67,7 @@ } .cockpit-visor-shell { position: absolute; - inset: clamp(62px, 9vh, 90px) clamp(18px, 3vw, 48px) clamp(38px, 5vh, 56px); + inset: var(--cockpit-visor-top) clamp(18px, 3vw, 48px) clamp(38px, 5vh, 56px); transform-style: preserve-3d; perspective: 880px; } @@ -648,7 +647,7 @@ html:not([lang='en']) .cockpit-roll-token.is-separator { .cockpit-compass { position: absolute; left: 50%; - bottom: var(--cockpit-compass-bottom); + bottom: clamp(44px, 7vh, 72px); width: min(760px, 72vw); transform: translateX(-50%) rotateX(7deg) translateZ(18px); transform-style: preserve-3d; @@ -2079,17 +2078,14 @@ body.cockpit-mode #intel-hud .hud-right-edge { body.cockpit-mode #right-context-rail { display: none !important; } - /* A centred row above the compass block: its ground speed and altitude - telemetry tops out ~171px above the block's bottom edge on phones, so - the row clears it by ~10px and stays on the same axis as RESET/EXIT. - The row spans the width to centre its launchers; only they take input. */ + /* Place the row just below the roll arc (visor inset + 2px + 96px). + On shorter screens, leave 8px between the 42px row and the reticle + (46% - 18px), keeping the row below the vision controls at 72px. */ body.cockpit-mode .cockpit-utility-controls { - top: auto; + top: clamp(72px, calc(46% - 68px), calc(var(--cockpit-visor-top) + 108px)); right: 12px; - bottom: calc(var(--cockpit-compass-bottom) + 182px); left: 12px; justify-content: center; - max-width: none; pointer-events: none; } body.cockpit-mode .cockpit-utility-controls { diff --git a/src/ui/styles/cyber.css b/src/ui/styles/cyber.css index d7c0c174ea..fb78028056 100644 --- a/src/ui/styles/cyber.css +++ b/src/ui/styles/cyber.css @@ -2892,16 +2892,20 @@ max-height: min(48vh, 440px); } - /* Centred like the default theme's phone row; the desktop panel width - would otherwise pin it left of the Reset/Exit axis. */ + /* Centred like the default theme's phone row. */ :root[data-ui-theme='cyber'] body.cockpit-mode .cockpit-utility-controls { top: 92px !important; right: 12px; bottom: auto; - left: 12px; width: auto; } + :root[data-ui-theme='cyber'] + body.cockpit-mode + .cockpit-utility-control.is-expanded { + right: auto; + } + :root[data-ui-theme='cyber'] body.cockpit-mode .cockpit-utility-control:not(.is-expanded) From 11e1c9d26d879110ac87a24d4394e805f74ca714 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 19:06:53 +0400 Subject: [PATCH 08/10] CCTV Street View fallback: the browser's pose at the catalog position The fallback keeps the catalog position but takes heading, field of view and pitch from the request again, as before, clamped as before. A catalog camera with no pose (every world-cameras row on main) otherwise asked Google for heading 0, pitch 0, FOV 80 while the browser draws it at the id-hash heading, pitch -17 and FOV 74, and a calibrated camera lost its calibration. Cost and the per-IP budget are unchanged. - The Street View budget is built per proxy, so tests no longer depend on GEV_RATELIMIT_GOOGLE_PER_MIN in the shell; the fixture pins it. - New tests: a pose-less catalog camera, and the per-IP budget (no call without a key, the cap, a separate budget per address). - The client no longer sends lat/lon on /frame. - CURRENT-STATE, the changelog fragment and SECURITY.md say the fallback has its own per-client limit, and that unlisted (seed) cameras get the placeholder. --- SECURITY.md | 4 +- .../1602-cctv-streetview-fallback-catalog.md | 10 +- docs/CURRENT-STATE.md | 11 +- server/providers/cctv.js | 51 ++++--- src/data/cctvMediaFeedType.test.mjs | 48 +++++- src/data/cctvStreetViewPose.test.mjs | 141 ++++++++++++++++++ src/layers/cctv/source.js | 2 - src/layers/cctv/source.test.mjs | 4 +- 8 files changed, 235 insertions(+), 36 deletions(-) create mode 100644 src/data/cctvStreetViewPose.test.mjs diff --git a/SECURITY.md b/SECURITY.md index 7b894c346f..fb2890e174 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -68,7 +68,7 @@ browser-key fallback for existing single-key setups. The data proxies under `server/providers/` are written so the browser cannot turn the server into an open relay: -- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). Other proxies target fixed upstream hosts. +- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). The key-bearing Street View fallback likewise answers only for a registered camera, always at its catalog position: a request sets only the view direction, field of view (20–120°) and pitch (−40–20°), so it cannot buy Street View of a place of its choosing. Other proxies target fixed upstream hosts. - **Live HLS is bounded and origin-pinned.** Registered HTTP(S) HLS sources use a Node puller that rejects redirects and off-origin playlist references, bounds playlists and segment bodies while streaming, and aborts timed-out or released sessions. At most two sessions retain 12 segments/24 MiB each, plus bounded download buffers. Stores are memory-only and idle sessions expire after 15 seconds. RTMP/ffmpeg execution is not enabled. Locally configured source URLs remain an operator trust boundary. - **Radio is not an audio relay.** `/api/radio/stations` contacts only allowlisted Radio Browser HTTPS hosts and paths, rejects redirects, rejects any hostname with a loopback/private/link-local/metadata/non-public A or AAAA result, and pins each TLS connection to a validated address. It returns normalized public HTTPS stream URLs; `/api/radio/click/:uuid` applies the same destination policy and accepts only station IDs from the current bounded catalog. The browser then connects directly to the broadcaster after an explicit playback action, so the broadcaster sees the listener's IP address. GEV never proxies, caches, records, or redistributes audio. - **No verbatim client headers upstream.** The CCTV media route is the one route that relays a request header (`Range`, for video seeking). It is parsed and canonicalized before it is forwarded: one `bytes=` range only, with every accepted form — explicit span, open-ended and suffix — bounded to the same 64 MiB ceiling the relay applies to a declared response body. Multi-range, malformed, inverted and non-`bytes` values are dropped and the request proceeds without a `Range`, as RFC 7233 §3.1 prescribes. Bounding the request bounds what is asked for: a response that declares no length — live streamed media, or a chunked body from an upstream that ignores the `Range` — has no ceiling. An upstream request the browser has stopped waiting for is cancelled rather than left running, whether the viewer leaves before the headers arrive or during the body. @@ -95,7 +95,7 @@ The dev server is a **key broker**: every server-side key above is spendable by - **Local-only by default.** `./scripts/dev-fresh.sh` (and the Vite config itself) bind to `localhost`, so only your machine can reach the server — and only local names are accepted (`allowedHosts` stays restricted, which also blunts DNS-rebinding tricks). Binding to all interfaces keeps that restriction: IP addresses and `localhost` work, and LAN hostnames must be listed in `GEV_ALLOWED_HOSTS` (for example `GEV_ALLOWED_HOSTS=globe.lan`); suffix and wildcard entries are ignored. - **LAN exposure is an explicit opt-in**: `HOST=0.0.0.0 ./scripts/dev-fresh.sh`. The launcher prints a prominent warning plus your LAN URL. Understand what opting in means: **every device on that network can drive the proxies and spend your OpenAI / Google / OpenSky / AISStream / TomTom / FIRMS quota** for as long as the server runs. Do this only on networks you trust. -- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**. +- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). The CCTV Street View fallback has its own per-IP window on `GEV_RATELIMIT_GOOGLE_PER_MIN`, separate from the Places and Geocoding one; over it, a frame gets the placeholder instead of a `429`. Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**. - **Docker trusts one address, and only because the port is on loopback.** Docker delivers the host's own browser to the container from the container network's gateway, never from `127.0.0.1`, so a loopback-only Provider diff --git a/changelog.d/1602-cctv-streetview-fallback-catalog.md b/changelog.d/1602-cctv-streetview-fallback-catalog.md index 04574b9142..194923b264 100644 --- a/changelog.d/1602-cctv-streetview-fallback-catalog.md +++ b/changelog.d/1602-cctv-streetview-fallback-catalog.md @@ -1,5 +1,5 @@ -- The CCTV Street View fallback serves only catalog cameras, at their catalog - position, heading, field of view and pitch, and ignores coordinates a - request supplies. It spends from the per-client Google budget - (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120), so the Google key can no - longer be used as an unmetered Street View service (asturksever, #1602). +- The CCTV Street View fallback serves only catalog cameras, always at their + catalog position, and ignores coordinates a request supplies. It has its own + per-client limit on the Google setting (`GEV_RATELIMIT_GOOGLE_PER_MIN`, + default 120), so the Google key can no longer be used as an unmetered Street + View service (asturksever, #1602). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 019e25704e..d7f60479ed 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1277,9 +1277,14 @@ redirects on those hosts, are pinned by parsed URL to the agency's image directory. Every `/api/cctv` route refuses cross-site browser requests but accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The -Street View fallback serves only catalog cameras, at the catalog position, -heading, field of view and pitch, never coordinates a request supplies, and it -shares the per-client Google budget (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120). +Street View fallback serves only catalog cameras, always at the catalog +position; coordinates a request supplies are ignored. Heading, field of view +and pitch come from the request, the pose the browser draws with calibration +included, and fall back to the catalog pose. A camera the server does not list, +such as a bundled seed camera the browser shows when the server catalog is +empty, gets the placeholder. The fallback has its own per-client limit on the +Google setting (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120, `0` disables it); +a request over it gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, it keeps one camera per ground cell sized to the view, preferring a healthy feed, diff --git a/server/providers/cctv.js b/server/providers/cctv.js index e8e18ad51e..3eb94dbb2f 100644 --- a/server/providers/cctv.js +++ b/server/providers/cctv.js @@ -21,19 +21,6 @@ import { createHlsPuller } from './cctv/stream.js'; import { googleServerApiKey } from './places/google-key.js'; import { clientKey, makeCostRateLimiter } from './common/rate-limit.js'; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; -let _streetViewRateLimiter; -/** - * Per-IP budget for the Street View fallback, on the same setting as the - * other Google routes (GEV_RATELIMIT_GOOGLE_PER_MIN; 0 disables it). - */ -function streetViewRateLimiter() { - if (_streetViewRateLimiter === undefined) - _streetViewRateLimiter = makeCostRateLimiter( - process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, - 120, - ); - return _streetViewRateLimiter; -} /** * Vite plugin: CCTV camera proxy with source registry, frame/media serving, @@ -96,6 +83,22 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { }; }; + /** + * Per-IP budget for the Street View fallback, one per proxy, on the same + * setting as the other Google routes (GEV_RATELIMIT_GOOGLE_PER_MIN; 0 + * disables it). Built on first use, after the standalone env has loaded. + * undefined = not built yet; null = the explicit 0 opt-out. + */ + let streetViewBudget; + const streetViewRateLimiter = () => { + if (streetViewBudget === undefined) + streetViewBudget = makeCostRateLimiter( + process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, + 120, + ); + return streetViewBudget; + }; + /** * Fetch a Google Street View static image as a fallback frame. Server-side * call, never reaches the browser — prefers GOOGLE_MAPS_SERVER_API_KEY @@ -524,6 +527,13 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { const source = sourceById.get(cameraId); const label = url.searchParams.get('label') || source?.name || cameraId; const city = url.searchParams.get('city') || source?.city || ''; + // The view follows the pose the browser draws (calibration included); + // the position never comes from the query (see the Street View fallback). + const heading = Number( + url.searchParams.get('heading') || source?.headingDeg, + ); + const fov = Number(url.searchParams.get('fov') || source?.fovDeg); + const pitch = Number(url.searchParams.get('pitch') || source?.pitchDeg); // Only use server-registered upstream URLs — never accept client-supplied URLs // (prevents SSRF via ?upstream= query parameter) @@ -557,8 +567,9 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { // request (whose client this server cannot see) gets the placeholder, // as if no key were configured. Any forwarding header counts, even an // empty one. - // It is also only for catalog cameras, framed from the catalog (never - // a spot the query names), within the per-IP Google budget. + // It is also only for catalog cameras, at the catalog position (never a + // spot the query names; the query sets only the view), within the per-IP + // Google budget. const forwarded = PROXY_SIGNALS.some( (name) => req.headers?.[name] !== undefined, ); @@ -571,11 +582,11 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { (googleBudget && !googleBudget(clientKey(req))) ? null : await streetViewFallback({ - lat: Number(source.lat), - lon: Number(source.lon), - heading: Number(source.headingDeg), - fov: Number(source.fovDeg), - pitch: Number(source.pitchDeg ?? -10), + lat: source.lat, + lon: source.lon, + heading, + fov, + pitch, }); if (sv?.ok) { setHealth(cameraId, { diff --git a/src/data/cctvMediaFeedType.test.mjs b/src/data/cctvMediaFeedType.test.mjs index 0523c95f39..191b3015ed 100644 --- a/src/data/cctvMediaFeedType.test.mjs +++ b/src/data/cctvMediaFeedType.test.mjs @@ -111,6 +111,7 @@ function mount(t, respond) { austin: process.env.CCTV_FORCE_AUSTIN, serverKey: process.env.GOOGLE_MAPS_SERVER_API_KEY, browserKey: process.env.GOOGLE_MAPS_API_KEY, + rateLimit: process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, }; process.env.CCTV_SOURCES_JSON = JSON.stringify([ STILL, @@ -125,6 +126,8 @@ function mount(t, respond) { // than a network call this file does not model. delete process.env.GOOGLE_MAPS_SERVER_API_KEY; delete process.env.GOOGLE_MAPS_API_KEY; + // The default Google budget, whatever the shell sets. + delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN; const nativeFetch = globalThis.fetch; const requests = []; globalThis.fetch = async (url, init = {}) => { @@ -139,6 +142,7 @@ function mount(t, respond) { ['CCTV_FORCE_AUSTIN', before.austin], ['GOOGLE_MAPS_SERVER_API_KEY', before.serverKey], ['GOOGLE_MAPS_API_KEY', before.browserKey], + ['GEV_RATELIMIT_GOOGLE_PER_MIN', before.rateLimit], ]) { if (value === undefined) delete process.env[name]; else process.env[name] = value; @@ -155,9 +159,9 @@ function mount(t, respond) { }); assert.ok(handler, 'the CCTV provider must mount a middleware'); - const call = async (path, headers = {}) => { + const call = async (path, headers = {}, socket) => { const { res, done } = recordingResponse(); - await handler({ url: path, headers, method: 'GET', on() {} }, res); + await handler({ url: path, headers, method: 'GET', on() {}, socket }, res); await done; return res; }; @@ -554,4 +558,44 @@ test('the Street View fallback frames catalog cameras only, from the catalog pos assert.equal(steered.headers['X-CCTV-Source'], 'streetview'); const location = new URL(streetView()[0].url).searchParams.get('location'); assert.equal(location, `${STILL.lat},${STILL.lon}`); + assert.equal(new URL(streetView()[0].url).searchParams.get('heading'), '90'); +}); + +test('the Street View fallback spends a per-IP Google budget, and only with a key', async (t) => { + const app = mount(t, ({ url }) => + url.startsWith('https://maps.googleapis.com/') + ? trackedUpstream({ + headers: { 'content-type': 'image/jpeg' }, + body: 'street-view', + }).response + : upstreamResponse({ status: 503 }), + ); + // Read when the first keyed fallback builds the limiter, so after mount(). + process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '2'; + const streetViewCalls = () => + app.requests.filter(({ url }) => + url.startsWith('https://maps.googleapis.com/'), + ).length; + const first = { remoteAddress: '203.0.113.7' }; + const frameSource = async (socket) => + (await app.call(`/frame/${STILL.id}`, {}, socket)).headers['X-CCTV-Source']; + + // Without a key nothing is spent. + for (let i = 0; i < 3; i++) + assert.equal(await frameSource(first), 'synthetic'); + assert.equal(streetViewCalls(), 0); + + process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; + assert.deepEqual( + [await frameSource(first), await frameSource(first), await frameSource(first)], + ['streetview', 'streetview', 'synthetic'], + ); + assert.equal(streetViewCalls(), 2, 'no Google call over the budget'); + + // Another address has a budget of its own. + assert.equal( + await frameSource({ remoteAddress: '203.0.113.8' }), + 'streetview', + ); + assert.equal(streetViewCalls(), 3); }); diff --git a/src/data/cctvStreetViewPose.test.mjs b/src/data/cctvStreetViewPose.test.mjs new file mode 100644 index 0000000000..584fe8629d --- /dev/null +++ b/src/data/cctvStreetViewPose.test.mjs @@ -0,0 +1,141 @@ +// When a catalog camera has no pose, the browser sends /frame a heading derived +// from the camera ID, a pitch of -17°, and a field of view of 74°. Street View +// uses that pose at the camera's catalog coordinates. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { cctvProxy } from '../../server/providers/cctv.js'; + +// Same shape as a world-cameras row: an image URL, position, and no +// headingDeg / pitchDeg / fovDeg. +const POSELESS = { + id: 'world-or-fixture', + name: 'Pose-less fixture', + lat: 44.05, + lon: -123.09, + feedType: 'image', + url: 'https://cams.upstream.invalid/still.jpg', +}; + +/** The browser's id-hash heading (src/layers/cctv/model.js headingFromId). */ +function browserHeadingFromId(id) { + let acc = 0; + for (let i = 0; i < id.length; i++) acc = (acc * 33 + id.charCodeAt(i)) >>> 0; + return ((((acc % 16) * 22.5) % 360) + 360) % 360; +} + +function response({ status = 200, headers = {}, body = '' }) { + return new Response(status === 204 ? null : String(body), { + status, + headers, + }); +} + +function recording() { + const chunks = []; + let finished; + const done = new Promise((resolve) => (finished = resolve)); + const res = { + statusCode: 0, + headers: {}, + writableEnded: false, + writeHead(status, headers) { + res.statusCode = status; + res.headers = { ...res.headers, ...headers }; + }, + setHeader(name, value) { + res.headers[name] = value; + }, + write(chunk) { + chunks.push(Buffer.from(chunk)); + return true; + }, + end(chunk) { + if (chunk) chunks.push(Buffer.from(chunk)); + res.writableEnded = true; + res.body = Buffer.concat(chunks).toString('utf8'); + finished(); + }, + on() {}, + once() {}, + emit() {}, + destroy() {}, + }; + return { res, done }; +} + +test('the Street View fallback frames a pose-less catalog camera the way the browser draws it', async (t) => { + const saved = Object.fromEntries( + [ + 'CCTV_SOURCES_JSON', + 'CCTV_SOURCES_FILE', + 'CCTV_FORCE_AUSTIN', + 'GOOGLE_MAPS_SERVER_API_KEY', + 'GOOGLE_MAPS_API_KEY', + 'GEV_RATELIMIT_GOOGLE_PER_MIN', + ].map((name) => [name, process.env[name]]), + ); + process.env.CCTV_SOURCES_JSON = JSON.stringify([POSELESS]); + process.env.CCTV_SOURCES_FILE = 'absent-source-file.json'; + process.env.CCTV_FORCE_AUSTIN = '0'; + process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; + delete process.env.GOOGLE_MAPS_API_KEY; + delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN; + const nativeFetch = globalThis.fetch; + const streetView = []; + globalThis.fetch = async (url) => { + const href = String(url); + if (href.startsWith('https://maps.googleapis.com/')) { + streetView.push(new URL(href)); + return response({ + headers: { 'content-type': 'image/jpeg' }, + body: 'street-view', + }); + } + return response({ status: 503 }); // the camera's upstream is down + }; + t.after(() => { + globalThis.fetch = nativeFetch; + for (const [name, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + }); + + let handler; + cctvProxy().configureServer({ + middlewares: { use: (_route, fn) => (handler = fn) }, + }); + + // What src/layers/cctv/source.js sends for this camera with no calibration. + const heading = Math.round(browserHeadingFromId(POSELESS.id)); + const params = new URLSearchParams({ + label: POSELESS.name, + city: '', + lat: POSELESS.lat.toFixed(6), + lon: POSELESS.lon.toFixed(6), + heading: String(heading), + fov: '74', + pitch: '-17', + ts: '1', + }); + const { res, done } = recording(); + await handler( + { + url: `/frame/${POSELESS.id}?${params}`, + headers: {}, + method: 'GET', + on() {}, + }, + res, + ); + await done; + + assert.equal(res.headers['X-CCTV-Source'], 'streetview'); + assert.equal(streetView.length, 1); + const sv = streetView[0].searchParams; + assert.equal(sv.get('location'), `${POSELESS.lat},${POSELESS.lon}`); + assert.equal(Number(sv.get('heading')), heading, 'heading the browser draws'); + assert.equal(Number(sv.get('fov')), 74, 'FOV the browser draws'); + assert.equal(Number(sv.get('pitch')), -17, 'pitch the browser draws'); +}); diff --git a/src/layers/cctv/source.js b/src/layers/cctv/source.js index 3b628954b4..78fd5cb194 100644 --- a/src/layers/cctv/source.js +++ b/src/layers/cctv/source.js @@ -22,8 +22,6 @@ function frameUrlFor(camera, refreshMs = ACTIVE_FRAME_REFRESH_MS) { const params = new URLSearchParams({ label: camera.name, city: camera.city, - lat: camera.lat.toFixed(6), - lon: camera.lon.toFixed(6), heading: String(Math.round(camera.headingDeg)), fov: String(Math.round(camera.fovDeg)), pitch: String(Math.round(camera.pitchDeg || -10)), diff --git a/src/layers/cctv/source.test.mjs b/src/layers/cctv/source.test.mjs index a4b276d213..61e36c3321 100644 --- a/src/layers/cctv/source.test.mjs +++ b/src/layers/cctv/source.test.mjs @@ -81,8 +81,8 @@ test('frame and media URLs preserve registered camera identity and encoded metad ); assert.equal(frame.searchParams.get('label'), camera.name); assert.equal(frame.searchParams.get('city'), camera.city); - assert.equal(frame.searchParams.get('lat'), '30.267000'); - assert.equal(frame.searchParams.get('lon'), '-97.744000'); + assert.equal(frame.searchParams.has('lat'), false); + assert.equal(frame.searchParams.has('lon'), false); assert.equal(frame.searchParams.get('heading'), '45'); assert.equal(frame.searchParams.get('pitch'), '-12'); assert.deepEqual([...media.searchParams.keys()], ['ts']); From 01d4a3f454971ffe551954ebf6a9b159555bc4cf Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 11:31:14 +0400 Subject: [PATCH 09/10] CCTV Street View budget: key the client before the camera wait, share the default - The /frame handler reads the client's network key (IPv6 /64) before it awaits the camera, so a client that drops the connection is still charged to its own window instead of the shared fallback key. - The budget is charged only after the Google key and finite catalog coordinates are confirmed, and the key is read once. - Places and the CCTV window share one default (GOOGLE_DEFAULT_PER_MIN). - Tests: the catalog-only test checks heading/fov/pitch from the query at the catalog location; the budget test covers unknown ids, forwarded requests and /64 grouping; a real-socket test covers a dropped connection. The duplicate pose test is removed. - .env.example, SECURITY.md, CURRENT-STATE and the changelog fragment describe the separate per-IP window, the catalog position and the placeholder for seed cameras. --- .env.example | 2 + SECURITY.md | 2 +- .../1602-cctv-streetview-fallback-catalog.md | 10 +- docs/CURRENT-STATE.md | 17 ++- server/providers/cctv.js | 56 ++++--- server/providers/places/google-key.js | 8 + server/providers/places/google.js | 13 +- src/data/cctvMediaFeedType.test.mjs | 40 ++++- src/data/cctvStreetViewDisconnect.test.mjs | 87 +++++++++++ src/data/cctvStreetViewPose.test.mjs | 141 ------------------ 10 files changed, 175 insertions(+), 201 deletions(-) create mode 100644 src/data/cctvStreetViewDisconnect.test.mjs delete mode 100644 src/data/cctvStreetViewPose.test.mjs diff --git a/.env.example b/.env.example index a9819f100b..a3e2b48167 100644 --- a/.env.example +++ b/.env.example @@ -37,6 +37,8 @@ GOOGLE_MAPS_API_KEY= GOOGLE_MAPS_SERVER_API_KEY= # Per-IP rate limit for the Google Places cost endpoints # (/api/google/nearby-places + /api/google/text-search), in requests per minute. +# The CCTV Street View fallback counts in its own window with the same cap; +# over it, a frame gets the placeholder image instead of a 429. # DEFAULTS TO 120, the value the Pinokio build already ships. Raise or lower it # with a positive integer; 60 is a sensible tightening whenever HOST is not # localhost. Set it to exactly 0 to run unthrottled. An unreadable value (a diff --git a/SECURITY.md b/SECURITY.md index 296a610f35..4f55f80cdd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -68,7 +68,7 @@ browser-key fallback for existing single-key setups. The data proxies under `server/providers/` are written so the browser cannot turn the server into an open relay: -- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). The key-bearing Street View fallback likewise answers only for a registered camera, always at its catalog position: a request sets only the view direction, field of view (20–120°) and pitch (−40–20°), so it cannot buy Street View of a place of its choosing. Other proxies target fixed upstream hosts. +- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). The key-bearing Street View fallback likewise answers only for a registered camera, at its catalog position; a request sets only the heading, field of view and pitch, never the location. Other proxies target fixed upstream hosts. - **Live HLS is bounded and origin-pinned.** Registered HTTP(S) HLS sources use a Node puller that rejects redirects and off-origin playlist references, bounds playlists to 256 KiB and segment bodies to 8 MiB while streaming, and aborts timed-out or released sessions. At most two sessions retain 12 segments/24 MiB each, plus bounded download buffers. Stores are memory-only and idle sessions expire after 15 seconds. RTMP/ffmpeg execution is not enabled. Locally configured source URLs remain an operator trust boundary. - **Radio is not an audio relay.** `/api/radio/stations` contacts only allowlisted Radio Browser HTTPS hosts and paths, rejects redirects, rejects any hostname with a loopback/private/link-local/metadata/non-public A or AAAA result, and pins each TLS connection to a validated address. It returns normalized public HTTPS stream URLs; `/api/radio/click/:uuid` applies the same destination policy and accepts only station IDs from the current bounded catalog. The browser then connects directly to the broadcaster after an explicit playback action, so the broadcaster sees the listener's IP address. GEV never proxies, caches, records, or redistributes audio. - **Québec 511 video plays in the browser, opt-in and after Play.** With `CCTV_QUEBEC_VIDEO_ENABLED=1`, `/api/cctv/sources` lists, for each MTQ camera, one URL built server-side from its numeric id on `https://www.quebec511.info/Carte/Fenetres/camera.ashx`; the overlay accepts no other host, path or format. The browser loads that clip only after the viewer presses Play for the selected camera, so Québec 511 sees the viewer's IP address, and the panel says so before Play. Selecting a camera by click, auto-hop, a scene or voice never loads it, and switching cameras stops playback. GEV never proxies, caches or reads the video's pixels. With the flag unset (the default) the browser makes no request to Québec 511. diff --git a/changelog.d/1602-cctv-streetview-fallback-catalog.md b/changelog.d/1602-cctv-streetview-fallback-catalog.md index 194923b264..7180cd9c39 100644 --- a/changelog.d/1602-cctv-streetview-fallback-catalog.md +++ b/changelog.d/1602-cctv-streetview-fallback-catalog.md @@ -1,5 +1,5 @@ -- The CCTV Street View fallback serves only catalog cameras, always at their - catalog position, and ignores coordinates a request supplies. It has its own - per-client limit on the Google setting (`GEV_RATELIMIT_GOOGLE_PER_MIN`, - default 120), so the Google key can no longer be used as an unmetered Street - View service (asturksever, #1602). +- The CCTV Street View fallback answers only for cameras the server lists, at + their catalog position; a request sets only the view. Bundled seed cameras + get the placeholder. A per-IP limit on `GEV_RATELIMIT_GOOGLE_PER_MIN` + (default 120) keeps the Google key from serving as an unmetered Street View + service (asturksever, #1602). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 69164179c5..f5fbf45688 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1990,14 +1990,12 @@ redirects on those hosts, are pinned by parsed URL to the agency's image directory. Every `/api/cctv` route refuses cross-site browser requests but accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The -Street View fallback serves only catalog cameras, always at the catalog -position; coordinates a request supplies are ignored. Heading, field of view -and pitch come from the request, the pose the browser draws with calibration -included, and fall back to the catalog pose. A camera the server does not list, -such as a bundled seed camera the browser shows when the server catalog is -empty, gets the placeholder. The fallback has its own per-client limit on the -Google setting (`GEV_RATELIMIT_GOOGLE_PER_MIN`, default 120, `0` disables it); -a request over it gets the placeholder. +fallback answers only for cameras the server lists, at their catalog position, +so position calibration never reaches it. Heading, field of view (clamped to +20–120°) and pitch (clamped to −40–20°) come from the request, else from the +catalog pose. A bundled seed camera, shown when the server catalog is empty, +gets the placeholder. The fallback counts in its own per-IP Google window (see +the cost-bearing proxies below). The CCTV layer draws only the cameras on or near the screen. Zoomed out, it keeps one camera per ground cell sized to the view, preferring a healthy feed, @@ -3529,6 +3527,9 @@ unaffected. `GEV_RATELIMIT_OPENAI_PER_MIN` and `GEV_RATELIMIT_GOOGLE_PER_MIN` ov those; exactly `0` disables the limiter, while a value that cannot be read as a number falls back to the default rather than to unlimited. Over-limit requests receive a sanitized `429` with `Retry-After: 5` and never reach the provider. +The CCTV Street View fallback counts in a separate window with the Google cap. +An IPv6 /64 counts as one client. Over the cap, a frame gets the placeholder +image instead of a `429`. Typed chat (`/api/openai/chat`, `/api/gemini/chat`) counts in its own window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`. Left unset, each takes its provider's resolved cap — `GEV_RATELIMIT_OPENAI_PER_MIN` diff --git a/server/providers/cctv.js b/server/providers/cctv.js index 12761542b3..63dc511cb3 100644 --- a/server/providers/cctv.js +++ b/server/providers/cctv.js @@ -21,8 +21,11 @@ import { PROXY_SIGNALS } from '../../src/localRequestGate.mjs'; import { createHlsPuller } from './cctv/stream.js'; import { isMlitRiverAdjustmentImage } from './cctv/worldCameras.js'; import { ottawaAuthorizedFrameUrl } from './cctv/ottawa.js'; -import { googleServerApiKey } from './places/google-key.js'; -import { clientKey, makeCostRateLimiter } from './common/rate-limit.js'; +import { + GOOGLE_DEFAULT_PER_MIN, + googleServerApiKey, +} from './places/google-key.js'; +import { clientNetworkKey, makeCostRateLimiter } from './common/rate-limit.js'; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; /** @@ -200,21 +203,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { }; }; - /** - * Per-IP budget for the Street View fallback, one per proxy, on the same - * setting as the other Google routes (GEV_RATELIMIT_GOOGLE_PER_MIN; 0 - * disables it). Built on first use, after the standalone env has loaded. - * undefined = not built yet; null = the explicit 0 opt-out. - */ - let streetViewBudget; - const streetViewRateLimiter = () => { - if (streetViewBudget === undefined) - streetViewBudget = makeCostRateLimiter( - process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, - 120, - ); - return streetViewBudget; - }; + let streetViewBudget; // undefined = not built yet; null = the explicit 0 opt-out /** * Fetch a Google Street View static image as a fallback frame. Server-side @@ -222,11 +211,23 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { * (#33: a key scoped to Street View Static/Places, restricted by server IP * rather than HTTP referrer) and falls back to the browser-exposed * GOOGLE_MAPS_API_KEY for setups that haven't split the two yet. + * Each IP (or IPv6 /64) has its own GEV_RATELIMIT_GOOGLE_PER_MIN window, + * separate from Places. Setting it to 0 disables the limit. */ - const streetViewFallback = async ({ lat, lon, heading, fov, pitch }) => { + const streetViewFallback = async ( + client, + { lat, lon, heading, fov, pitch }, + ) => { const streetViewKey = googleServerApiKey(); if (!streetViewKey || !Number.isFinite(lat) || !Number.isFinite(lon)) return null; + // Built on first use, after the standalone env has loaded. + if (streetViewBudget === undefined) + streetViewBudget = makeCostRateLimiter( + process.env.GEV_RATELIMIT_GOOGLE_PER_MIN, + GOOGLE_DEFAULT_PER_MIN, + ); + if (streetViewBudget && !streetViewBudget(client)) return null; try { const sv = new URL('https://maps.googleapis.com/maps/api/streetview'); sv.searchParams.set('size', '960x540'); @@ -282,6 +283,8 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { // keyless gate keeps the routes reachable behind a reverse proxy; the // key-bearing Street View fallback below has its own check. if (admitSameSiteKeyless(req, res)) return; + // Read before any await: a socket the client has closed has no address. + const client = clientNetworkKey(req); const sources = await getCctvSources(); const sourceById = new Map( sources.map((source) => [source.id, source]), @@ -653,8 +656,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { const source = sourceById.get(cameraId); const label = url.searchParams.get('label') || source?.name || cameraId; const city = url.searchParams.get('city') || source?.city || ''; - // The view follows the pose the browser draws (calibration included); - // the position never comes from the query (see the Street View fallback). + // The query sets only the view, the pose the browser draws. const heading = Number( url.searchParams.get('heading') || source?.headingDeg, ); @@ -749,21 +751,15 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) { // request (whose client this server cannot see) gets the placeholder, // as if no key were configured. Any forwarding header counts, even an // empty one. - // It is also only for catalog cameras, at the catalog position (never a - // spot the query names; the query sets only the view), within the per-IP - // Google budget. + // It also answers only for catalog cameras, at the catalog position; + // the query never sets the location. const forwarded = PROXY_SIGNALS.some( (name) => req.headers?.[name] !== undefined, ); - const googleBudget = googleServerApiKey() - ? streetViewRateLimiter() - : null; const sv = - forwarded || - !source || - (googleBudget && !googleBudget(clientKey(req))) + forwarded || !source ? null - : await streetViewFallback({ + : await streetViewFallback(client, { lat: source.lat, lon: source.lon, heading, diff --git a/server/providers/places/google-key.js b/server/providers/places/google-key.js index ff5fe6356e..c8b5c4c9c0 100644 --- a/server/providers/places/google-key.js +++ b/server/providers/places/google-key.js @@ -1,5 +1,13 @@ import { resolveGoogleServerKey } from '../../../scripts/google-server-key.mjs'; +/** + * Default GEV_RATELIMIT_GOOGLE_PER_MIN for the Places and Geocoding window + * and the separate CCTV Street View window, in requests per minute per IP. + * The Pinokio build sets the same default in pinokio/_ENVIRONMENT. + * `.env.example` suggests 60 for hosts other than localhost. + */ +export const GOOGLE_DEFAULT_PER_MIN = 120; + /** * Optional Google place context is an empty capability when no key is present, * not a server outage. Returning 200 keeps a deliberately keyless session out diff --git a/server/providers/places/google.js b/server/providers/places/google.js index 1ddaa95939..2f6742d1c4 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -1,4 +1,5 @@ import { + GOOGLE_DEFAULT_PER_MIN, googleServerApiKey, keylessGooglePlacesResponse, keylessGoogleGeocodeResponse, @@ -15,17 +16,7 @@ import { // undefined = not built yet; null = the explicit 0 opt-out; fn = active limiter let _googleRateLimiter; -/** - * 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; +export { GOOGLE_DEFAULT_PER_MIN }; /** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */ function googleRateLimiter() { diff --git a/src/data/cctvMediaFeedType.test.mjs b/src/data/cctvMediaFeedType.test.mjs index 191b3015ed..6a5155b467 100644 --- a/src/data/cctvMediaFeedType.test.mjs +++ b/src/data/cctvMediaFeedType.test.mjs @@ -553,12 +553,14 @@ test('the Street View fallback frames catalog cameras only, from the catalog pos assert.deepEqual(streetView(), [], 'no Google call for an unknown id'); const steered = await app.call( - `/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90`, + `/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90&fov=74&pitch=-17`, ); assert.equal(steered.headers['X-CCTV-Source'], 'streetview'); - const location = new URL(streetView()[0].url).searchParams.get('location'); - assert.equal(location, `${STILL.lat},${STILL.lon}`); - assert.equal(new URL(streetView()[0].url).searchParams.get('heading'), '90'); + const sv = new URL(streetView()[0].url).searchParams; + assert.equal(sv.get('location'), `${STILL.lat},${STILL.lon}`); + assert.equal(sv.get('heading'), '90'); + assert.equal(sv.get('fov'), '74'); + assert.equal(sv.get('pitch'), '-17'); }); test('the Street View fallback spends a per-IP Google budget, and only with a key', async (t) => { @@ -586,8 +588,27 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke assert.equal(streetViewCalls(), 0); process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; + // Neither an unknown id nor a forwarded request spends the window. + assert.equal( + (await app.call('/frame/not-a-camera', {}, first)).headers['X-CCTV-Source'], + 'synthetic', + ); + assert.equal( + ( + await app.call( + `/frame/${STILL.id}`, + { 'x-forwarded-for': '203.0.113.9' }, + first, + ) + ).headers['X-CCTV-Source'], + 'synthetic', + ); assert.deepEqual( - [await frameSource(first), await frameSource(first), await frameSource(first)], + [ + await frameSource(first), + await frameSource(first), + await frameSource(first), + ], ['streetview', 'streetview', 'synthetic'], ); assert.equal(streetViewCalls(), 2, 'no Google call over the budget'); @@ -598,4 +619,13 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke 'streetview', ); assert.equal(streetViewCalls(), 3); + + // Addresses within one IPv6 /64 share a budget. + const v6 = (remoteAddress) => frameSource({ remoteAddress }); + assert.deepEqual( + [await v6('2001:db8::1'), await v6('2001:db8::2'), await v6('2001:db8::3')], + ['streetview', 'streetview', 'synthetic'], + ); + assert.equal(await v6('2001:db8:0:1::1'), 'streetview', 'another /64'); + assert.equal(streetViewCalls(), 6); }); diff --git a/src/data/cctvStreetViewDisconnect.test.mjs b/src/data/cctvStreetViewDisconnect.test.mjs new file mode 100644 index 0000000000..e355448f3e --- /dev/null +++ b/src/data/cctvStreetViewDisconnect.test.mjs @@ -0,0 +1,87 @@ +// Real sockets: a client that closes its connection while the camera upstream +// is still pending must not get a Street View call outside its own budget. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { cctvProxy } from '../../server/providers/cctv.js'; + +const CAM = { + id: 'still-fixture', + name: 'Still fixture', + lat: 30.27, + lon: -97.74, + feedType: 'image', + url: 'https://cams.upstream.invalid/still.jpg', +}; + +test('a client that disconnects mid-fetch stays inside its own Street View budget', async (t) => { + const saved = { ...process.env }; + process.env.CCTV_SOURCES_JSON = JSON.stringify([CAM]); + process.env.CCTV_SOURCES_FILE = 'absent-source-file.json'; + process.env.CCTV_FORCE_AUSTIN = '0'; + process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; + delete process.env.GOOGLE_MAPS_API_KEY; + process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '1'; + const nativeFetch = globalThis.fetch; + let streetViewCalls = 0; + globalThis.fetch = async (url) => { + if (String(url).startsWith('https://maps.googleapis.com/')) { + streetViewCalls += 1; + return new Response('street-view', { + headers: { 'content-type': 'image/jpeg' }, + }); + } + await new Promise((r) => setTimeout(r, 400)); + return new Response(null, { status: 503 }); + }; + let handler; + cctvProxy().configureServer({ + middlewares: { use: (_r, fn) => (handler = fn) }, + }); + const server = http.createServer((req, res) => { + req.url = req.url.replace(/^\/api\/cctv/, ''); + handler(req, res, () => res.end()); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + t.after(() => { + server.close(); + globalThis.fetch = nativeFetch; + for (const k of Object.keys(process.env)) + if (!(k in saved)) delete process.env[k]; + Object.assign(process.env, saved); + }); + const { port } = server.address(); + const get = (abortAfterMs) => + new Promise((resolve) => { + const req = http.get( + { + host: '127.0.0.1', + port, + path: `/api/cctv/frame/${CAM.id}`, + headers: { host: `localhost:${port}` }, + agent: false, + }, + (res) => { + res.resume(); + res.on('end', () => resolve(res.headers['x-cctv-source'])); + }, + ); + req.on('error', () => resolve('aborted')); + if (abortAfterMs) + setTimeout(() => { + req.destroy(); + resolve('aborted'); + }, abortAfterMs); + }); + + assert.equal(await get(), 'streetview'); + assert.equal(await get(), 'synthetic', 'the cap of one is spent'); + assert.equal(streetViewCalls, 1); + await get(50); + await new Promise((r) => setTimeout(r, 800)); + assert.equal( + streetViewCalls, + 1, + 'an aborted request spent the key outside its own budget', + ); +}); diff --git a/src/data/cctvStreetViewPose.test.mjs b/src/data/cctvStreetViewPose.test.mjs deleted file mode 100644 index 584fe8629d..0000000000 --- a/src/data/cctvStreetViewPose.test.mjs +++ /dev/null @@ -1,141 +0,0 @@ -// When a catalog camera has no pose, the browser sends /frame a heading derived -// from the camera ID, a pitch of -17°, and a field of view of 74°. Street View -// uses that pose at the camera's catalog coordinates. -import { test } from 'node:test'; -import assert from 'node:assert/strict'; - -import { cctvProxy } from '../../server/providers/cctv.js'; - -// Same shape as a world-cameras row: an image URL, position, and no -// headingDeg / pitchDeg / fovDeg. -const POSELESS = { - id: 'world-or-fixture', - name: 'Pose-less fixture', - lat: 44.05, - lon: -123.09, - feedType: 'image', - url: 'https://cams.upstream.invalid/still.jpg', -}; - -/** The browser's id-hash heading (src/layers/cctv/model.js headingFromId). */ -function browserHeadingFromId(id) { - let acc = 0; - for (let i = 0; i < id.length; i++) acc = (acc * 33 + id.charCodeAt(i)) >>> 0; - return ((((acc % 16) * 22.5) % 360) + 360) % 360; -} - -function response({ status = 200, headers = {}, body = '' }) { - return new Response(status === 204 ? null : String(body), { - status, - headers, - }); -} - -function recording() { - const chunks = []; - let finished; - const done = new Promise((resolve) => (finished = resolve)); - const res = { - statusCode: 0, - headers: {}, - writableEnded: false, - writeHead(status, headers) { - res.statusCode = status; - res.headers = { ...res.headers, ...headers }; - }, - setHeader(name, value) { - res.headers[name] = value; - }, - write(chunk) { - chunks.push(Buffer.from(chunk)); - return true; - }, - end(chunk) { - if (chunk) chunks.push(Buffer.from(chunk)); - res.writableEnded = true; - res.body = Buffer.concat(chunks).toString('utf8'); - finished(); - }, - on() {}, - once() {}, - emit() {}, - destroy() {}, - }; - return { res, done }; -} - -test('the Street View fallback frames a pose-less catalog camera the way the browser draws it', async (t) => { - const saved = Object.fromEntries( - [ - 'CCTV_SOURCES_JSON', - 'CCTV_SOURCES_FILE', - 'CCTV_FORCE_AUSTIN', - 'GOOGLE_MAPS_SERVER_API_KEY', - 'GOOGLE_MAPS_API_KEY', - 'GEV_RATELIMIT_GOOGLE_PER_MIN', - ].map((name) => [name, process.env[name]]), - ); - process.env.CCTV_SOURCES_JSON = JSON.stringify([POSELESS]); - process.env.CCTV_SOURCES_FILE = 'absent-source-file.json'; - process.env.CCTV_FORCE_AUSTIN = '0'; - process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key'; - delete process.env.GOOGLE_MAPS_API_KEY; - delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN; - const nativeFetch = globalThis.fetch; - const streetView = []; - globalThis.fetch = async (url) => { - const href = String(url); - if (href.startsWith('https://maps.googleapis.com/')) { - streetView.push(new URL(href)); - return response({ - headers: { 'content-type': 'image/jpeg' }, - body: 'street-view', - }); - } - return response({ status: 503 }); // the camera's upstream is down - }; - t.after(() => { - globalThis.fetch = nativeFetch; - for (const [name, value] of Object.entries(saved)) { - if (value === undefined) delete process.env[name]; - else process.env[name] = value; - } - }); - - let handler; - cctvProxy().configureServer({ - middlewares: { use: (_route, fn) => (handler = fn) }, - }); - - // What src/layers/cctv/source.js sends for this camera with no calibration. - const heading = Math.round(browserHeadingFromId(POSELESS.id)); - const params = new URLSearchParams({ - label: POSELESS.name, - city: '', - lat: POSELESS.lat.toFixed(6), - lon: POSELESS.lon.toFixed(6), - heading: String(heading), - fov: '74', - pitch: '-17', - ts: '1', - }); - const { res, done } = recording(); - await handler( - { - url: `/frame/${POSELESS.id}?${params}`, - headers: {}, - method: 'GET', - on() {}, - }, - res, - ); - await done; - - assert.equal(res.headers['X-CCTV-Source'], 'streetview'); - assert.equal(streetView.length, 1); - const sv = streetView[0].searchParams; - assert.equal(sv.get('location'), `${POSELESS.lat},${POSELESS.lon}`); - assert.equal(Number(sv.get('heading')), heading, 'heading the browser draws'); - assert.equal(Number(sv.get('fov')), 74, 'FOV the browser draws'); - assert.equal(Number(sv.get('pitch')), -17, 'pitch the browser draws'); -}); From 49785e423d041e54bbc5ccfc4b4d3f7e74819845 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 11:39:45 +0400 Subject: [PATCH 10/10] fix(cockpit): scope the centred phone row and keep Stories unread in Cockpit The centred Display/Radio row now applies only inside the phone shell (720 px and below) on flight and bridge views; satellite and provider cockpits, narrow short windows (under 390x450) and very short windows (under 240 px) keep main's right-anchored place, so the row no longer lands on the desktop rail, orbital zoom, LOOK AHEAD, Reset or the Stories button. The row sizes to its launchers instead of spanning the width. The first-visit Stories announcement stays hidden and unread while Cockpit is open: a Stories tap that Cockpit refuses no longer marks it seen, so it shows again after Exit. The unit tests and the Cockpit QA cover the phone boundary, glyph and side taps, the destination cue, short and narrow windows and the announcement's return. --- changelog.d/1549-cockpit-phone-utility-row.md | 12 +- docs/CURRENT-STATE.md | 23 +-- scripts/qa-cockpit-utility.mjs | 143 +++++++++++++----- src/cockpitMarkup.test.mjs | 19 ++- src/ui/storiesView.test.mjs | 27 ++++ src/ui/styles/cockpit.css | 43 ++++-- src/ui/views/StoriesView.vue | 6 +- 7 files changed, 204 insertions(+), 69 deletions(-) diff --git a/changelog.d/1549-cockpit-phone-utility-row.md b/changelog.d/1549-cockpit-phone-utility-row.md index d01e466ae0..e3e59d6ea6 100644 --- a/changelog.d/1549-cockpit-phone-utility-row.md +++ b/changelog.d/1549-cockpit-phone-utility-row.md @@ -1,5 +1,9 @@ - Keep the phone Cockpit's Display and Radio launchers off the flight - instruments. At 760 px wide and below, the collapsed row now sits centred on - the Reset/Exit axis between the roll scale and the reticle, instead of - right-anchored over the ground speed and altitude telemetry, and stays on - screen on short landscape phones (Denis Groshev, @ZloyS, #1549). + instruments. In the phone layout (720 px wide and below), the collapsed row + of the flight and bridge views now sits centred on the Reset/Exit axis + above the reticle, clear of the destination cue, instead of right-anchored + over the ground speed and altitude readouts. On short landscape phones it + stays on screen and tappable below the vision controls, though it may cover + the top of the readouts. Very short or narrow split-screen windows keep + the old place above Reset/Exit. The first-visit Stories announcement waits until + Cockpit closes (Denis Groshev, @ZloyS, #1549). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 6b54f70a83..15ad11f388 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5104,15 +5104,20 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > stacking. Narrow mobile Cockpit > viewports suppress the legacy layer stack, peripheral HUD, and secondary > Context/briefing panes so the flight instruments and primary controls remain -> unobstructed. There the collapsed Display and Radio launchers form one row -> centred on the Reset/Exit axis, between the roll scale and the reticle, -> clear of the destination cue and flight readouts. On short landscape -> screens it stays on screen below the vision controls. -> `scripts/qa-cockpit-utility.mjs` checks the row's centring, clearance and -> tap targets at 390×844, 360×740, 740×360 and 667×240. Outside Cockpit, -> Radio starts collapsed while off and lives only in its section inside -> Context; the detailed panel's normal accordion control owns its disclosure -> and its Enable/Disable action owns power. +> unobstructed. In the phone layout (720 px wide and below) the flight and +> bridge views put the collapsed Display and Radio launchers in one row +> centred on the Reset/Exit axis, above the reticle and clear of the +> destination cue: below the roll arc in portrait, over the arc's lower tick +> ends in landscape. On short landscape screens the row stays +> on screen and tappable below the vision controls but may cover the top of +> the speed and altitude readouts. Windows under 240 px tall, and those under +> 390 px wide and 450 px tall, keep the row above Reset/Exit at the right. +> Satellite and provider views keep the row +> above Reset/Exit at the right, where their own layouts expect it. The +> first-visit Stories announcement waits, unread, until Cockpit closes. +> Outside Cockpit, Radio starts collapsed while off and lives only in its +> section inside Context; the detailed panel's normal accordion control +> owns its disclosure and its Enable/Disable action owns power. > Radio volume in the full and Cockpit surfaces, plus Space Mission > replay speed, use Display / Sharpen's muted 3px rail, circular cyan thumb, > glow, and mono value treatment. Their larger transparent hit areas, keyboard diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index 3d556f2f4f..157592d398 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -2050,13 +2050,50 @@ try { JSON.stringify(narrowViewActions), ); - // Short screens have no free band between instruments. The launchers still - // need to stay on screen, accept taps and clear the vision controls. + // A fresh profile has not seen the Stories announcement: Cockpit keeps + // it unread and off the phone row until it closes. + const storiesPopupDisplay = () => { + const popup = document.getElementById('hPop'); + return popup ? getComputedStyle(popup).display : null; + }; + const storiesPopupInCockpit = await page.evaluate(storiesPopupDisplay); + check('the unread Stories announcement waits while Cockpit is open', + storiesPopupInCockpit === 'none', String(storiesPopupInCockpit)); + + // Windows too short for the centred row keep it above Reset/Exit. + for (const [width, height] of [[360, 370], [320, 360], [568, 188], [667, 190]]) { + await page.setViewport({ width, height, deviceScaleFactor: 1 }); + const glyphHits = await page.evaluate(async () => { + const manager = window.__godsEyeView.styleManager; + manager._setCockpitDisclosure('display', false); + manager._setCockpitDisclosure('radio', false); + await new Promise(requestAnimationFrame); + await new Promise(requestAnimationFrame); + return [...document.querySelectorAll( + '#cockpit-utility-controls .cockpit-utility-glyph', + )].map((glyph) => { + const box = glyph.getBoundingClientRect(); + const target = document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return target && glyph.contains(target) ? 'ok' : target?.closest('[id]')?.id || null; + }); + }); + check( + `${width}×${height} Cockpit Display/Radio glyph centres reach their own launchers`, + glyphHits.length === 2 && glyphHits.every((hit) => hit === 'ok'), + JSON.stringify(glyphHits), + ); + } + + // The phone row's place in each room: centred on Reset/Exit, on screen, + // tappable, and clear of what that room has space to clear. for (const [width, height, room] of [ - [390, 844, 'portrait'], [360, 740, 'portrait'], - [740, 360, 'landscape'], + [720, 360, 'landscape'], [667, 240, 'short'], + [390, 844, 'portrait'], ]) { await page.setViewport({ width, height, deviceScaleFactor: 1 }); const phoneRow = await page.evaluate(async () => { @@ -2069,52 +2106,76 @@ try { const rect = (element) => element?.getBoundingClientRect().toJSON() || null; const hud = (selector) => document.querySelector(`#cockpit-hud ${selector}`); const route = document.getElementById('cockpit-route-direction'); - const routeShown = Boolean(route && !route.hidden); - const controls = [...document.querySelectorAll( - '#cockpit-utility-controls .cockpit-utility-control', - )]; - return { - launchers: controls.map(rect), - hits: controls.map((control) => { - const glyph = control.querySelector('.cockpit-utility-glyph'); - const box = glyph?.getBoundingClientRect(); - const target = box && document.elementFromPoint( - box.left + box.width / 2, - box.top + box.height / 2, - ); - return Boolean(target && glyph.contains(target)); - }), - speed: rect(hud('.cockpit-speed')), - altitude: rect(hud('.cockpit-altitude')), - route: routeShown ? rect(route) : null, - chevron: routeShown ? rect(route.querySelector('.cockpit-route-chevron')) : null, - reticle: rect(hud('.cockpit-reticle')), - rollArc: rect(hud('.cockpit-roll-arc')), - vision: rect(hud('.cockpit-vision-controls')), - switcher: rect(document.getElementById('view-switcher')), - viewport: { width: innerWidth, height: innerHeight }, - }; + // A live flight may have no route, which hides the DEST cue. Show it while + // measuring so the clearance check always has a cue to clear. + const wasHidden = route.hidden; + try { + route.hidden = false; + const controls = [...document.querySelectorAll( + '#cockpit-utility-controls .cockpit-utility-control', + )]; + const launchers = controls.map(rect); + const rowLeft = Math.min(...launchers.map((launcher) => launcher.left)); + const rowRight = Math.max(...launchers.map((launcher) => launcher.right)); + // Taps beside the row reach what is under it. + const besideHits = []; + if (launchers.length) { + const middle = launchers[0].top + launchers[0].height / 2; + for (const x of [rowLeft - 8, rowRight + 8]) { + const target = document.elementFromPoint(x, middle); + besideHits.push(Boolean(target?.closest('#cockpit-utility-controls'))); + } + } + return { + launchers, + rowLeft, + rowRight, + besideHits, + hits: controls.map((control) => { + const glyph = control.querySelector('.cockpit-utility-glyph'); + const box = glyph?.getBoundingClientRect(); + const target = box && document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return Boolean(target && glyph.contains(target)); + }), + speed: rect(hud('.cockpit-speed')), + altitude: rect(hud('.cockpit-altitude')), + route: rect(route), + chevron: rect(route.querySelector('.cockpit-route-chevron')), + reticle: rect(hud('.cockpit-reticle')), + rollArc: rect(hud('.cockpit-roll-arc')), + vision: rect(hud('.cockpit-vision-controls')), + switcher: rect(document.getElementById('view-switcher')), + viewport: { width: innerWidth, height: innerHeight }, + }; + } finally { + route.hidden = wasHidden; + } }); const obstacles = { portrait: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'rollArc', 'vision'], + // The row covers the roll arc's lower tick ends; ticks and labels stay readable. landscape: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'vision'], + // No free band between the instruments: only the vision controls. short: ['vision'], }[room]; const overlaps = (a, b) => Boolean(a && b) && a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; - const rowLeft = Math.min(...phoneRow.launchers.map((launcher) => launcher.left)); - const rowRight = Math.max(...phoneRow.launchers.map((launcher) => launcher.right)); - const switcherCentre = phoneRow.switcher - ? (phoneRow.switcher.left + phoneRow.switcher.right) / 2 - : NaN; + const { rowLeft, rowRight } = phoneRow; + const switcherCentre = (phoneRow.switcher?.left + phoneRow.switcher?.right) / 2; + const [first, second] = phoneRow.launchers; check( - `${width}×${height} Cockpit Display/Radio row is centred, on screen, tappable and clear of ${obstacles.join(', ')}`, + `${width}×${height} Cockpit Display/Radio row is centred in one line, on screen, tappable and clear of ${obstacles.join(', ')}`, phoneRow.launchers.length === 2 && phoneRow.launchers.every((launcher) => launcher.width > 0) && phoneRow.speed?.width > 0 && phoneRow.altitude?.width > 0 - && phoneRow.hits.length === 2 + && (room === 'short' || (phoneRow.route?.width > 0 && phoneRow.chevron?.width > 0)) && phoneRow.hits.every(Boolean) + && phoneRow.besideHits.every((inside) => !inside) + && Math.abs((first?.top + first?.bottom) / 2 - (second?.top + second?.bottom) / 2) <= 1 && phoneRow.launchers.every((launcher) => obstacles.every( (name) => !overlaps(launcher, phoneRow[name]), )) @@ -2127,7 +2188,12 @@ try { JSON.stringify(phoneRow), ); } - await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 1 }); + + // A Stories tap that Cockpit refuses leaves the announcement unread. + await page.evaluate(() => document.getElementById('hStories').click()); + await page.waitForFunction( + () => document.querySelector('#toast.visible')?.textContent === 'Exit cockpit to open Stories', + ); const resetResult = await page.evaluate(() => { // Both the UI and compatibility facade delegate to this navigation owner. @@ -2200,6 +2266,9 @@ try { && resetState.visionRestored, JSON.stringify(resetState), ); + const storiesPopupAfterReset = await page.evaluate(storiesPopupDisplay); + check('the Stories announcement returns once Cockpit closes', + storiesPopupAfterReset !== null && storiesPopupAfterReset !== 'none', String(storiesPopupAfterReset)); check('runtime console remains clean', consoleErrors.length === 0 && localHttpErrors.length === 0, [...localHttpErrors, ...consoleErrors].slice(0, 6).join(' | ')); } finally { diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 32196b3dce..8c4d15d98f 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -1142,14 +1142,16 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls' assert.match(mobileCockpit[1], /body\.cockpit-mode \.cockpit-signal-window/); assert.match( mobileCockpit[1], - /body\.cockpit-mode \.cockpit-utility-controls \{[^}]*?top:\s*clamp\(\s*72px,\s*calc\(46% - 68px\),\s*calc\(var\(--cockpit-visor-top\) \+ 108px\)\s*\);[^}]*?left:\s*12px;[^}]*?justify-content:\s*center;[^}]*?pointer-events:\s*none;/, + /body\.cockpit-mode \.cockpit-utility-controls[\s\S]*?bottom:\s*152px;/, ); assert.match( mobileCockpit[1], - /body\.cockpit-mode \.cockpit-utility-control \{\s*pointer-events:\s*auto;\s*\}/, + /body\.cockpit-mode\.mobile-shell[^{]*?\.cockpit-utility-controls \{[^}]*?top:[^;]*?var\(--cockpit-visor-top\)/, + ); + assert.match( + mobileCockpit[1], + /@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/, ); - assert.doesNotMatch(mobileCockpit[1], /bottom:\s*152px;/); - assert.match(css, /--cockpit-visor-top:\s*clamp\(62px, 9vh, 90px\);/); assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/); assert.match( mobileCockpit[1], @@ -1169,6 +1171,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls' ); }); +test('the unread Stories announcement waits until Cockpit closes', () => { + assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/); + const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8'); + assert.match( + storiesView, + /async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/, + ); +}); + test('cockpit route direction uses self-contained vector artwork, not a font ligature', () => { const match = html.match(/
/); assert.ok(match, 'cockpit route-direction markup is missing'); diff --git a/src/ui/storiesView.test.mjs b/src/ui/storiesView.test.mjs index e200cbab63..3a0c0ef1db 100644 --- a/src/ui/storiesView.test.mjs +++ b/src/ui/storiesView.test.mjs @@ -6,6 +6,33 @@ import { createPinia } from 'pinia'; import { useStoriesStore } from './stores/stories.js'; import { storyById } from '../stories/catalog.js'; import StoryScreen from './views/stories/StoryScreen.vue'; +import StoriesView from './views/StoriesView.vue'; + +test('the announcement stays unread when a lazy Stories open resolves to false', async (t) => { + const host = document.body.appendChild(document.createElement('div')); + const pinia = createPinia(); + const store = useStoriesStore(pinia); + let allowed = false; + store.connect({ open: async () => allowed }); + const app = createApp(StoriesView).use(pinia); + app.mount(host); + t.after(() => { + app.unmount(); + host.remove(); + localStorage.removeItem('gevStoriesPopSeen'); + }); + + const entry = host.querySelector('#hStories'); + entry.click(); + await nextTick(); + assert.equal(localStorage.getItem('gevStoriesPopSeen'), null); + assert.ok(host.querySelector('#hPop')); + + allowed = true; + entry.click(); + await nextTick(); + assert.equal(localStorage.getItem('gevStoriesPopSeen'), '1'); +}); test('the story screen previews a drag and seeks once on release', async (t) => { const host = document.body.appendChild(document.createElement('div')); diff --git a/src/ui/styles/cockpit.css b/src/ui/styles/cockpit.css index 4a091450ef..f5756cef93 100644 --- a/src/ui/styles/cockpit.css +++ b/src/ui/styles/cockpit.css @@ -78,7 +78,7 @@ --cockpit-side-panel-width: min(340px, 28vw); /* HUD bottom offset + tallest scaled telemetry block + 20px clear border. */ --cockpit-bottom-rail-safe: calc(clamp(84px, 11vh, 118px) + 100px); - /* The phone Display/Radio row shares the visor inset with the roll scale. */ + /* The phone Display/Radio row shares the visor inset with the roll arc. */ --cockpit-visor-top: clamp(62px, 9vh, 90px); position: fixed; inset: 0; @@ -2026,6 +2026,11 @@ body.cockpit-mode ) { display: none !important; } +/* The first-visit Stories announcement waits, unread, until Cockpit closes: + on a phone it would cover the Display/Radio row. */ +body.cockpit-mode #gev-stories #hPop { + display: none; +} body.cockpit-mode #left-panel-stack { z-index: 147; display: flex; @@ -2118,21 +2123,35 @@ body.cockpit-mode #intel-hud .hud-right-edge { body.cockpit-mode #right-context-rail { display: none !important; } - /* Place the row just below the roll arc (visor inset + 2px + 96px). - On shorter screens, leave 8px between the 42px row and the reticle - (46% - 18px), keeping the row below the vision controls at 72px. */ body.cockpit-mode .cockpit-utility-controls { - top: clamp(72px, calc(46% - 68px), calc(var(--cockpit-visor-top) + 108px)); + top: auto; right: 12px; - left: 12px; - justify-content: center; - pointer-events: none; - } - body.cockpit-mode .cockpit-utility-controls { + bottom: 152px; flex-direction: row; + max-width: calc(100vw - 24px); } - body.cockpit-mode .cockpit-utility-control { - pointer-events: auto; + /* Phone flight and bridge views: one row centred on the Reset/Exit axis, + 10px below the roll arc (.cockpit-roll-arc: 2px + 96px into the visor). + Shorter screens reserve 36px around the 46% centre of .cockpit-reticle + (about 25px tall on phones), plus an 8px gap below the 42px row. + The row stops at 72px, below the vision controls. Windows under 240px + tall, and narrow ones under 450px tall, keep the right-aligned row above + Reset/Exit, clear of Reset, LOOK AHEAD and the Stories button, as do + satellite and provider views. */ + @media (min-width: 390px) and (min-height: 240px), (min-height: 450px) { + body.cockpit-mode.mobile-shell + #cockpit-hud:not([data-generic]):not([data-subject='satellite']) + .cockpit-utility-controls { + top: clamp( + 72px, + calc(46% - 68px), + calc(var(--cockpit-visor-top) + 108px) + ); + bottom: auto; + left: 12px; + width: max-content; + margin-inline: auto; + } } body.cockpit-mode .cockpit-utility-launcher { width: min(150px, calc((100vw - 31px) / 2)); diff --git a/src/ui/views/StoriesView.vue b/src/ui/views/StoriesView.vue index 84d9939bf0..31b8370436 100644 --- a/src/ui/views/StoriesView.vue +++ b/src/ui/views/StoriesView.vue @@ -152,9 +152,9 @@ function markPopSeen() { /* storage off: the popup comes back next visit */ } } -function openExplore() { - markPopSeen(); - store.controller.open(); +async function openExplore() { + // A refused open (Cockpit) leaves the announcement unread. + if (await store.controller.open()) markPopSeen(); } // ── Opened in GEV: a toast that leads back to the story ──