feat(core): persist viewer state and integrate Cesium services and profiles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-17 17:20:15 +03:00
parent 9cbdd4ea5c
commit 29ef038a43
52 changed files with 2943 additions and 72 deletions
+8 -8
View File
@@ -10,7 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -42,7 +42,7 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
"name": "@nodedc/map-cesium-react",
"version": "0.1.2",
"version": "0.1.4",
"dependencies": {
"cesium": "1.147.0"
},
@@ -71,7 +71,7 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
"name": "@nodedc/ui-react",
"version": "0.7.4",
"version": "0.7.5",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
@@ -884,12 +884,12 @@
}
},
"node_modules/@nodedc/bim-viewer": {
"version": "0.2.66",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
"integrity": "sha512-aq8LktWb72/UFSDtYExDh+Eccb1dAoc2oiDg5gC+tvobXyofEBUnAdwzElYOAV2mg3CNgC7k74UnJmdJ5pKhJA==",
"version": "0.2.74",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
"integrity": "sha512-pZOXFqDcypBEFEqUIjOEX9BU+J6qMemYYLPy+PitBF7Rw0pK+daKlhtUT/gW69v1BQW0PVKi209hkgRgpI3/Gg==",
"peerDependencies": {
"@nodedc/map-cesium-react": ">=0.1.1 <0.2",
"@nodedc/ui-react": ">=0.7.4 <0.8",
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
"@nodedc/ui-react": ">=0.7.5 <0.8",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
+1 -1
View File
@@ -15,7 +15,7 @@
},
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -1,5 +1,6 @@
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel";
@@ -18,7 +19,7 @@ const surfaces = environmentSurfaceIds.map(id => ({
}));
export function EnvironmentSettingsWindow(props: Props) {
const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
@@ -0,0 +1,89 @@
import {useEffect, useState} from "react";
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
import "./cesiumServiceSettings.css";
import {serverRequest, type Server} from "../../core/system/servers";
export function CesiumServiceSettings() {
const [service, setService] = useState("");
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
const [settings, setSettings] = useState<Settings | null>(null);
const [mode, setMode] = useState<CesiumRouteMode>("auto");
const [egress, setEgress] = useState("");
const [servers, setServers] = useState<Server[]>([]);
const [routesError, setRoutesError] = useState("");
const [token, setToken] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [checking, setChecking] = useState(false);
const [checkError, setCheckError] = useState("");
const [showVerification, setShowVerification] = useState(false);
const [verification, setVerification] = useState<CesiumVerification | null>(null);
useEffect(() => {
let active = true;
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
.catch(reason => {if (active) setError(reason.message);});
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
.catch(reason => {if(active) setRoutesError(reason.message);});
return () => {active = false;};
}, []);
useEffect(() => {
let active = true;
setVerification(null); setCheckError(""); setShowVerification(false);
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
setChecking(true);
void verifyCesiumService().then(value => {if (active) setVerification(value);})
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
.finally(() => {if (active) setChecking(false);});
return () => {active = false;};
}, [service, settings?.revision, settings?.token_configured, token, egress]);
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
async function action(kind: "verify" | "save" | "remove") {
if (!settings || busy) return;
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
try {
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
else {
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
setSettings(result); setToken("");
}
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
finally {setBusy(false); setPending(null);}
}
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
onClick={() => void action("save")}><Icon name="save"/></IconButton>
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
</>}>
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
{service === "cesium" && <>
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
{settings && <>
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
{routesError&&<Description role="alert">{routesError}</Description>}
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
</>}
{error && <Description role="alert">{error}</Description>}
</>}
</SettingsCard>;
}
@@ -652,6 +652,7 @@ function CacheHealth({
);
}
const { cache } = health.snapshot;
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
return (
<dl className="mission-map__cache-health">
<div>
@@ -0,0 +1 @@
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
@@ -2,7 +2,7 @@ import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
@@ -1,3 +1,4 @@
import {useObservationView} from '../../core/observation/useObservationView';
import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
@@ -15,6 +16,9 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
});
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
@@ -57,7 +61,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
@@ -75,8 +79,9 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
</EditorWorkspace>
</div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
@@ -5,10 +5,10 @@ import {serverRequest,useServers,type Server} from '../../core/system/servers';
import {vpsRequest} from '../../core/fleet/vps';
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
@@ -22,14 +22,14 @@ export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSav
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
{kind!=='arnavi'?<>
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
{filename&&<Description>{filename}</Description>}
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
</SettingsCard>
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
@@ -0,0 +1,63 @@
export type CesiumRouteMode = "auto" | "direct" | "gateway";
export interface CesiumServiceSettings {
revision: number;
egress_id: string;
mode: CesiumRouteMode;
token_configured: boolean;
gateway_configured: boolean;
gateway_available: boolean | null;
active_route: "unknown" | "gateway" | "direct" | "unavailable";
}
export interface CesiumVerification { ok: boolean; assets: Record<string, {ok: boolean; code?: string}> }
const endpoint = "/api/v1/map/services/cesium-ion";
export const cesiumServiceChanged = "missioncore:cesium-service-changed";
const messages: Record<string, string> = {
cesium_egress_region_denied: "Источник карт блокирует страну исходящего IP выбранного VPS. Выберите другой маршрут.",
cesium_egress_invalid: "Выберите подключённую службу маршрутизации.",
cesium_egress_unavailable: "Служба маршрутизации недоступна. Проверьте подключение VPS.",
cesium_egress_gateway_not_ready: "Сервер хранения локальных данных ещё не подключён к выбранному маршруту. Настройки не изменены.",
cesium_token_required: "Добавьте токен Cesium ion для подключения к источнику.",
cesium_token_invalid: "Проверьте токен: он не должен содержать пробелы.",
cesium_provider_unauthorized: "Cesium ion отклонил токен. Проверьте срок действия, доступ к ресурсам и ограничения адресов.",
cesium_provider_unavailable: "Источник Cesium недоступен. Проверьте интернет и повторите попытку.",
cesium_provider_rate_limited: "Источник временно ограничил запросы. Повторите проверку позже.",
cesium_provider_contract_mismatch: "Источник вернул неподдерживаемый тип карты. Настройки не изменены.",
cesium_provider_invalid_response: "Не удалось прочитать ответ источника. Настройки не изменены.",
cesium_settings_conflict: "Настройки уже изменены в другом окне. Откройте этот раздел заново.",
cesium_settings_unreadable: "Не удалось прочитать сохранённые настройки сервиса.",
cesium_settings_unwritable: "Не удалось сохранить настройки сервиса. Проверьте доступ и свободное место.",
map_gateway_unavailable: "Сервер хранения локальных данных недоступен. Выберите автоматическое подключение или подключение к источнику.",
};
export function cesiumServiceMessage(code?: string) { return messages[code ?? ""] ?? "Не удалось выполнить запрос к сервису карт. Повторите попытку."; }
export function cesiumTokenIndicator(value: {configured: boolean; draft: boolean; checking: boolean; error: string; verification: CesiumVerification | null}) {
if (value.checking) return {tone: "warning" as const, pulse: true, label: "Проверка доступа Cesium ion"};
if (value.error) return {tone: "warning" as const, pulse: false, label: value.error};
if (value.verification?.ok) return {tone: "success" as const, pulse: false, label: "Cesium ion: доступ подтверждён"};
if (value.verification) {
const failed = Object.values(value.verification.assets).find(asset => !asset.ok);
return {tone: "warning" as const, pulse: false, label: cesiumServiceMessage(failed?.code)};
}
return {tone: "neutral" as const, pulse: false, label: value.draft ? "Новый токен ещё не проверен" :
value.configured ? "Токен сохранён; доступ ещё не проверен" : "Токен не задан"};
}
async function request<T>(path: string, method = "GET", body?: object): Promise<T> {
try {
const response = await fetch(endpoint + path, {method, credentials: "same-origin", cache: "no-store",
headers: {Accept: "application/json", ...(body ? {"Content-Type": "application/json"} : {})},
body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30_000)});
const value = await response.json().catch(() => null);
if (!response.ok) throw new Error(cesiumServiceMessage(value?.code));
if (!value || typeof value !== "object") throw new Error(cesiumServiceMessage());
return value as T;
} catch (error) {
if (error instanceof Error && error.name === "Error") throw error;
throw new Error("Сервис карт не ответил. Проверьте соединение и повторите попытку.");
}
}
export const readCesiumService = () => request<CesiumServiceSettings>("");
export const verifyCesiumService = (token?: string, egress_id?: string) => request<CesiumVerification>("/verify", "POST", {...(token ? {token} : {}), ...(egress_id !== undefined ? {egress_id} : {})});
export async function saveCesiumService(value: {revision: number; mode: CesiumRouteMode; egress_id?: string; token?: string; remove_token?: boolean}) {
const result = await request<CesiumServiceSettings>("", "PUT", value);
window.dispatchEvent(new Event(cesiumServiceChanged));
return result;
}
@@ -11,7 +11,7 @@ export interface MapGatewayHealthSnapshot {
maxBytes: number | null;
atCapacity: boolean;
persistent: boolean;
};
} | null;
}
export interface MapGatewayHealth {
@@ -85,8 +85,11 @@ export function useMapGatewayHealth(active: boolean): MapGatewayHealth {
return health;
}
function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
export function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
const document = record(value, "gateway health");
if (document.ok === true && document.service === "missioncore-map-direct" && document.route === "direct") {
return {ionConfigured: true, assetAllowlist: [1, 2, 96188], cache: null};
}
if (document.ok !== true || document.service !== "nodedc-map-gateway") {
throw new Error("map_gateway_invalid_response");
}
@@ -1,8 +1,14 @@
import {useEffect,useRef} from 'react';
import {cesiumServiceChanged} from './cesiumService';
/** Recover the existing renderer only after its own gateway is reachable again. */
/** Recover the existing renderer after either admitted route becomes available. */
export function useMapRecovery(unavailable:boolean,retry:()=>void){
const callback=useRef(retry);callback.current=retry;
useEffect(()=>{
const changed=()=>callback.current();
window.addEventListener(cesiumServiceChanged,changed);
return()=>window.removeEventListener(cesiumServiceChanged,changed);
},[]);
useEffect(()=>{
if(!unavailable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
@@ -12,7 +18,7 @@ export function useMapRecovery(unavailable:boolean,retry:()=>void){
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
const value=response.ok?await response.json():null;
if(active&&value?.ok===true){callback.current();return;}
}catch{/* Retain the unavailable state; no public-provider fallback. */}
}catch{/* The server owns route selection; retry only when reachable. */}
if(active)timer=setTimeout(()=>void check(),30000);
}
timer=setTimeout(()=>void check(),30000);
@@ -0,0 +1,24 @@
import {useEffect,useRef,useState} from 'react';
import {observationViewProfile} from './viewProfile';
/** Operator presentation only. Never stores or restores control/arming state. */
export function useObservationView<T>(kind:'observation-map'|'rover-view',owner:string,defaults:()=>T,legacy:()=>Promise<T|null>){
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[error,setError]=useState(''),[reload,setReload]=useState(0);
const state=useRef({client:observationViewProfile<T>(kind,owner),document,ready:false,active:false,dirty:false});
useEffect(()=>{
const current={client:observationViewProfile<T>(kind,owner),document:defaults(),ready:false,active:true,dirty:false};state.current=current;setReady(false);setError('');
void current.client.read(legacy).then(value=>{if(!current.active)return;current.document=value??defaults();current.ready=true;setDocument(current.document);setReady(true);}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось прочитать настройки вида.');});
return()=>{current.active=false;};
},[kind,owner,reload]);
const save=()=>{
const current=state.current;if(!current.ready||!current.dirty)return;
const value=current.document;
void current.client.write(value).then(()=>{if(current.document===value)current.dirty=false;if(current.active)setError('');}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось сохранить настройки вида.');});
};
const update=(change:(value:T)=>T)=>{
const current=state.current;if(!current.ready)return;
const next=change(current.document);if(JSON.stringify(next)===JSON.stringify(current.document))return;
current.document=next;current.dirty=true;setDocument(next);save();
};
return {document,ready,error,update,retry:()=>{if(state.current.ready)save();else setReload(v=>v+1);}};
}
@@ -0,0 +1,14 @@
import {profileClient,type ProfileKind} from '../roverScene/profileClient';
// A newly mounted view must read after the previous view's acknowledged writes.
const pending=new Map<string,Promise<unknown>>();
export function observationViewProfile<T>(kind:ProfileKind,owner:string){
const key=JSON.stringify([kind,owner]),client=profileClient<T>(kind,owner);
function serial<R>(action:()=>Promise<R>):Promise<R>{
const next=(pending.get(key)??Promise.resolve()).catch(()=>{}).then(action);
pending.set(key,next);
void next.finally(()=>{if(pending.get(key)===next)pending.delete(key);}).catch(()=>{});
return next;
}
return {read:(legacy?:()=>Promise<T|null>)=>serial(()=>client.read(legacy)),write:(value:T)=>serial(()=>client.write(value))};
}
@@ -1,5 +1,5 @@
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments'|'observation-map'|'rover-view';
type Stored<T>={revision:number;document:T|null};
export function profileClient<T>(kind:ProfileKind,owner:string){
let revision:number|undefined;
@@ -2,7 +2,7 @@ import {useCallback, useEffect, useState} from 'react';
import type {VPSHost} from '../fleet/vps';
import {startSequentialPolling} from './sequentialPolling';
export type ServerService = {kind:'arnavi'|'wireguard'|'librespeed';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
export type ServerService = {kind:'arnavi'|'wireguard'|'librespeed'|'egress';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
export type Server = {id:string;name:string;address:string;revision:number;services:ServerService[]};
export type ServerRemovalPlan = {confirmation:string;name:string;blocked:string[];services:string[];vehicle_connections:number;worker_connections:number};
export async function serverRequest<T>(path='', method='GET', body?:unknown, signal?:AbortSignal):Promise<T> {
@@ -1,5 +1,6 @@
import {useObservationView} from '../../../core/observation/useObservationView';
import {useEffect,useMemo,useRef,useState} from 'react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapLayerVisibility,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
import { Description,Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
@@ -11,26 +12,30 @@ import {mapPresentation} from '../../../components/map/mapPresentation';
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
const [camera,setCamera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:true});
const telemetry=useTrackerTelemetry(vehicleID),centered=useRef(false);
const view=useObservationView('observation-map',vehicleID,()=>({schema:'missioncore.observation-map/v1' as const,camera:null as MapCamera|null,layers:{...defaults.layerVisibility,grid:false,targets:true} as MapLayerVisibility}),async()=>{
try{const camera=JSON.parse(localStorage.getItem(`missioncore.observation-map.v1:${vehicleID}`)??'null') as MapCamera|null;
return camera&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(camera[key as keyof MapCamera]))?{schema:'missioncore.observation-map/v1' as const,camera,layers:{...defaults.layerVisibility,grid:false,targets:true}}:null;
}catch{return null;}
});
const {camera,layers}=view.document;
const telemetry=useTrackerTelemetry(vehicleID);
const pins=telemetry.items.flatMap(item=>item.position?[{id:item.instance_id,label:`${item.name} · ${item.position_fresh&&!telemetry.unavailable?item.position.source.toUpperCase():new Date(item.position.measured_at*1000).toLocaleTimeString('ru-RU')}`,longitude:item.position.longitude,latitude:item.position.latitude,heading_degrees:item.position.course,speed_meters_per_second:0}]:[]);
const presentation=useMemo(()=>(encodeMapViewPut(defaultMapViewDocument()) as {view:{ghost_pins:MapGhostPinLayer}}).view.ghost_pins.presentation,[]);
const markers:MapGhostPinLayer={anchor:null,radius_meters:0,simulation_enabled:false,pins,presentation:{...presentation,stem_height_meters:20,head_size_px:12,label_mode:'attributes',label_max_length:80}};
function center(){const pin=pins[0];if(pin){setCamera({longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0});setGeneration(v=>v+1);}}
useEffect(()=>{if(pins.length&&!centered.current){centered.current=true;center();}},[pins.length]);
function center(){const pin=pins[0];if(pin){view.update(value=>({...value,camera:{longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0}}));setGeneration(v=>v+1);}}
useEffect(()=>{if(view.ready&&pins.length&&!camera)center();},[view.ready,pins.length,camera]);
const latest=telemetry.items.find(item=>item.position);
const positionLabel=telemetry.unavailable?'Обновление координат недоступно':latest?.position?`${latest.position.latitude.toFixed(6)}, ${latest.position.longitude.toFixed(6)} · ${latest.position.source.toUpperCase()} · ${latest.position.satellites??'—'} спутников · ${new Date(latest.position.measured_at*1000).toLocaleTimeString('ru-RU')}`:'Ожидание координат трекера';
const available=state.phase==='ready'||Object.values(state.providers).some(provider=>provider.phase==='ready');
const unavailable=!available&&state.phase!=='loading';
useMapRecovery(unavailable,()=>setGeneration(v=>v+1));
return <div className="observation-source">
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
{unavailable&&<div className="observation-source__notice"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!view.ready||!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}>{view.ready&&<CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera??defaults.camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={camera=>view.update(value=>({...value,camera}))}/> }</div>
{view.ready&&unavailable&&<div className="observation-source__notice"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
{view.error&&<div className="observation-source__notice"><Description>{view.error}</Description><Button onClick={view.retry}>Повторить сохранение вида</Button></div>}
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} disabled={!view.ready} onChange={value=>view.update(current=>({...current,layers:{...current.layers,[item.id]:value}}))}/>)}
</div>
</Window>
</div>;
@@ -56,6 +56,7 @@ export function ServersWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement
<Description>Подключено бортов: {'boards' in inspecting.details?inspecting.details.boards:0}</Description>
</SettingsCard>
</Window>}
{inspecting?.kind==='egress'&&<Window open title="Маршрутизация трафика" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Подключение к источникам"><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Выберите этот VPS в настройках нужного сервиса. Доступность службы и доступность внешнего источника проверяются отдельно.</Description></SettingsCard></Window>}
{inspecting?.kind==='librespeed'&&<Window open title="LibreSpeed" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Замер скорости" description="Служба для проверки соединения борта через роутер."><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Запускайте замер из вкладки «Замер скорости» в окне роутера. Одновременно выполняется один замер; результаты не сохраняются на VPS.</Description></SettingsCard></Window>}
{store.error&&<SettingsCard title="Не удалось получить VPS" description={store.error}/>}
</>;
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import {after, before, test} from "node:test";
import {createServer} from "./support/vite-server.mjs";
let server, service, health;
const fetchOriginal = globalThis.fetch;
before(async () => {
server = await createServer({appType: "custom", logLevel: "silent", server: {middlewareMode: true}});
service = await server.ssrLoadModule("/src/core/map/cesiumService.ts");
health = await server.ssrLoadModule("/src/core/map/useMapGatewayHealth.ts");
});
after(async () => {globalThis.fetch = fetchOriginal; await server?.close();});
test("health distinguishes direct provider from an actual NAS cache", () => {
const value = health.decodeHealth({ok: true, service: "missioncore-map-direct", route: "direct", cache: null});
assert.equal(value.cache, null);
assert.equal(value.ionConfigured, true);
assert.throws(() => health.decodeHealth({ok: false, service: "missioncore-map-direct", route: "direct"}));
const nas = health.decodeHealth({ok: true, service: "nodedc-map-gateway", ionConfigured: true, assetAllowlist: [1, 2, 96188],
cache: {mode: "online", writePolicy: "read-through", entries: 12, bytes: 30, maxBytes: null, atCapacity: false, persistent: true}});
assert.equal(nas.cache.entries, 12);
});
test("settings save uses body-only token and revision, then refreshes maps", async () => {
const previousWindow = globalThis.window;
const events = [];
globalThis.window = {dispatchEvent: event => events.push(event.type)};
globalThis.fetch = async (url, options) => {
assert.equal(url, "/api/v1/map/services/cesium-ion");
assert.equal(options.method, "PUT");
assert.equal(options.cache, "no-store");
assert.deepEqual(JSON.parse(options.body), {revision: 7, mode: "auto", token: "candidate"});
return new Response(JSON.stringify({revision: 8, mode: "auto", token_configured: true}));
};
try {
const value = await service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"});
assert.equal(value.revision, 8);
assert.deepEqual(events, [service.cesiumServiceChanged]);
} finally {globalThis.window = previousWindow;}
});
test("failed settings write neither exposes upstream body nor announces success", async () => {
globalThis.fetch = async () => new Response(JSON.stringify({code: "cesium_provider_unauthorized", detail: "private-credential"}), {status: 401});
await assert.rejects(service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"}), error =>
/отклонил токен/.test(error.message) && !error.message.includes("private-credential"));
});
test("token lamp distinguishes saved, pending, verified, rejected and new draft", () => {
const base = {configured: false, draft: false, checking: false, error: "", verification: null};
assert.equal(service.cesiumTokenIndicator(base).tone, "neutral");
assert.equal(service.cesiumTokenIndicator({...base, configured: true}).tone, "neutral");
assert.deepEqual(service.cesiumTokenIndicator({...base, checking: true}), {
tone: "warning", pulse: true, label: "Проверка доступа Cesium ion",
});
assert.equal(service.cesiumTokenIndicator({...base, verification: {ok: true, assets: {}}}).tone, "success");
assert.match(service.cesiumTokenIndicator({...base, verification: {ok: false,
assets: {"1": {ok: false, code: "cesium_provider_unauthorized"}}}}).label, /отклонил токен/);
assert.equal(service.cesiumTokenIndicator({...base, error: "Нет соединения"}).tone, "warning");
assert.match(service.cesiumTokenIndicator({...base, configured: true, draft: true}).label, /ещё не проверен/);
});
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const b=await build({entryPoints:['src/workspaces/fleet/observation/ObservationMap.tsx'],bundle:true,write:false,platform:'node',format:'esm',jsx:'automatic',plugins:[{name:'fixture',setup(b){
const fixtures={
react:'export const useState=v=>globalThis.viewUI.state(v),useRef=v=>globalThis.viewUI.ref(v),useEffect=(f,d)=>globalThis.viewUI.effect(f,d),useMemo=(f,d)=>globalThis.viewUI.memo(f,d);',
'react/jsx-runtime':'export const jsx=(type,props)=>({type,props}),jsxs=jsx;',
'@nodedc/map-cesium-react':'export const CesiumMapRenderer="Map",initialMapRuntimeState={phase:"ready",providers:{}};',
'@nodedc/ui-react':'export const Description="Description",Button="Button",Icon="Icon",IconButton="IconButton",Switch="Switch",Window="Window";',
'../../../core/fleet/vps':'export const useTrackerTelemetry=()=>globalThis.viewUI.telemetry;',
'../../../core/map/mapView':'export const defaultMapViewDocument=()=>({view:{camera:{longitude:0,latitude:0,height:40000,heading:0,pitch:-50,roll:0},layerVisibility:{imagery:true,terrain:true,buildings:true,grid:false,targets:true},visualSettings:{}}}),encodeMapViewPut=()=>({view:{ghost_pins:{presentation:{}}}});',
'../../../core/map/useMapRecovery':'export const useMapRecovery=()=>{};',
'../../../components/map/mapPresentation':'export const mapPresentation=v=>v;',
'../../../../../../packages/sensor-ui/src/ObservationHeader':'export const ObservationHeader="Header";',
};
b.onResolve({filter:/.*/},a=>fixtures[a.path]?{path:a.path,namespace:'fixture'}:undefined);
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:fixtures[a.path]}));
}}]});
const {ObservationMap}=await import('data:text/javascript;base64,'+Buffer.from(b.outputFiles[0].contents).toString('base64'));
const camera={longitude:37,latitude:55,height:600,heading:137,pitch:-28,roll:3};
const layers={imagery:true,terrain:true,buildings:false,grid:false,targets:true};
const doc=(value=camera)=>({schema:'missioncore.observation-map/v1',camera:value,layers});
function find(v,type){if(!v||typeof v!=='object')return null;if(Array.isArray(v)){for(const item of v){const hit=find(item,type);if(hit)return hit;}return null;}return v.type===type?v:find(v.props?.children,type);}
async function fixture(initial,run){
const old=new Map(['viewUI','localStorage','fetch'].map(k=>[k,globalThis[k]]));let slots=[],effects=[],queue=[],cursor=0,dirty=true,closed=false;
const h={value:{revision:initial?1:0,document:initial},puts:[],tree:null,gate:null,fail:false,
telemetry:{items:[{instance_id:'b2',name:'Arnavi',position_fresh:true,online:true,position:{longitude:38,latitude:56,measured_at:1,source:'gnss'}}]},
state(v){const i=cursor++;if(!(i in slots))slots[i]=typeof v==='function'?v():v;return[slots[i],v=>{slots[i]=typeof v==='function'?v(slots[i]):v;dirty=true;}];},
ref(v){const i=cursor++;return slots[i]??={current:v};},
memo(f,d){const i=cursor++;if(!slots[i]||d.some((v,j)=>v!==slots[i].d[j]))slots[i]={d,v:f()};return slots[i].v;},
effect(f,d){const i=cursor++;if(!effects[i]||d.some((v,j)=>v!==effects[i].d[j])){const before=effects[i];effects[i]={d};queue.push(()=>{before?.cleanup?.();effects[i].cleanup=f();});}},
async settle(){for(let i=0;i<100;i++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.tree=ObservationMap({vehicleID:'fixture',header:{}});for(const f of queue.splice(0))f();}}},
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},
reopen(){h.close();slots=[];effects=[];queue=[];closed=false;dirty=true;},
};
globalThis.viewUI=h;globalThis.localStorage={getItem:()=>null};
globalThis.fetch=async(_url,o)=>{if(h.fail)return new Response('{}',{status:503});if(o.method==='PUT'){const v=JSON.parse(o.body);h.puts.push(v);if(h.gate)await h.gate;if(v.expected_revision!==h.value.revision)return new Response('{"detail":"conflict"}',{status:409});h.value={revision:h.value.revision+1,document:v.document};}return new Response(JSON.stringify(h.value));};
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
}
test('saved Cesium tilt wins over tracker arrival and browser cache; reopen waits for camera write',()=>fixture(doc(),async h=>{
await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,0);assert.deepEqual(find(h.tree,'Map').props.layers,layers);
let release;h.gate=new Promise(r=>release=r);const moved={...camera,heading:220,pitch:-17};find(h.tree,'Map').props.onCameraChange(moved);await h.settle();h.reopen();await h.settle();assert.equal(find(h.tree,'Map'),null);
release();h.gate=null;await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,moved);assert.deepEqual(h.value.document.camera,moved);
}));
test('new map centers once; later telemetry and renderer recovery do not reset its angle',()=>fixture(null,async h=>{
await h.settle();assert.equal(find(h.tree,'Map').props.camera.latitude,56);assert.equal(h.puts.length,1);
find(h.tree,'Map').props.onCameraChange(camera);await h.settle();h.telemetry.items[0].position.latitude=58;h.reopen();await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,2);
}));
test('failed map profile read cannot render or overwrite defaults',()=>fixture(doc(),async h=>{
h.fail=true;await h.settle();assert.equal(find(h.tree,'Map'),null);assert.equal(h.puts.length,0);assert.deepEqual(h.value.document,doc());
}));
@@ -40,6 +40,7 @@ const {BoardObservationCenter}=await component('../src/workspaces/fleet/observat
'../../../components/rover/RoverTelemetry':'export const RoverTelemetry="RoverTelemetry",roverTelemetryMinimum=()=>({width:1,height:1});',
});
const {RoverView}=await component('../src/components/rover/RoverView.tsx',{
'../../core/observation/useObservationView':'export const useObservationView=()=>({ready:true,document:{model:""},update:()=>{},retry:()=>{},error:null});',
'../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});',
'../../core/fleet/roverInput':'export const keysFor=()=>[],roverSettings=()=>({mode:"tank",model:"",currentA:34.5,throttlePercent:20}),persistableRoverSettings=()=>false,roverNumberInput=Number;',
'../../core/fleet/roverDevEvents':'export const roverDevEvent=()=>{};',
+8
View File
@@ -544,6 +544,14 @@ buttons share individual Glass V4, with no common capsule. Tree rows have both
visibility eyes and plain `i` actions. Visibility applies to complete IFC
subtrees without repeating a spatial traversal for each already known ID.
2026-11-17 visibility persistence: client 0.2.74 / host 0.2.30 stores sparse
`viewer.hidden_nodes` in the per-project workspace. Project/category/product/IFC
branch eyes are independent masks; turning a parent back on preserves children.
Absent/null masks migrate legacy `hidden_layers`; explicit `[]` means all gates
open. Eye intent writes before React unmount and is reapplied as models load.
Temporary isolation does not overwrite the saved choices. Previously unsaved
IFC choices cannot be reconstructed. Acceptance: `outputs/view-visibility-20261117/RESULT.md`.
Navigation Cube settings include face/edge colors and independent transparency,
text and hover colors; selection color is configurable. Host 0.1.4 validates and
merges nested preferences, preserving new fields when old clients save.
+186
View File
@@ -0,0 +1,186 @@
# Cesium services and NAS outage routing
Implemented 2026-11-17. Cesium remains at 1.147.0. This change does not migrate,
reindex, clear or copy Synology tiles. Existing cache identity and upgrade rules
remain in [CESIUM_UPGRADE.md](CESIUM_UPGRADE.md).
## Operator surface
Profile → Settings → Services contains a service selector. Select **Cesium ion**
to reveal its connection mode and token field. Check access and Save are canonical
circular icon buttons at the top right of the service card. Saved credentials are
never filled back into the browser. Clear-token appears only when configured.
Product copy names the cache host **Сервер хранения локальных данных**; Synology is
an infrastructure detail. Persistent missing-token, last-route and saved-success
lines are intentionally absent. Explicit verification results and actionable
errors are retained. A canonical StatusBadge indicator precedes Cesium ion in the
selector: neutral for absent/unverified credentials, pulsing yellow while checking,
yellow for a failed check, green for confirmed asset permissions. Selecting Cesium
or saving credentials checks access automatically; details appear only after an
explicit Check access. The tooltip explains the state. This is token permission
status, not a claim that every provider tile is reachable.
This is installation-wide service configuration, not a per-map/project setting
or a hardware entry in System. The admitted composition uses Environment Settings,
SettingsCard, Select, TextField, Description, IconButton and registry icons. An
individual map settings panel was rejected because it would duplicate credentials
and leave Fleet, Observation Center and architectural maps with divergent routes.
The state grammar is: no service selected, loading, editable, checking/saving,
success, missing token, explicit safe error, revision conflict. No token means the
existing NAS route still works; it cannot enable the independent online route.
## Routing contract
All consumers retain the existing Core `/api/v1/map/gateway/*` URLs and endpoint
contract (`credentialMode: gateway`). `MapServiceRoutes` chooses the backend:
| Mode | Behavior |
| --- | --- |
| auto | Probe NAS, use it while reachable; otherwise use the original provider through Core. |
| direct | Use the original provider through Core, without the NAS cache. |
| gateway | Use NAS only; unavailable NAS remains an explicit error. |
NAS health has a two-second timeout and a single shared probe with a 15-second
cooldown. Successful NAS recovery returns subsequent requests to its existing
route. A transport failure opens the fallback cooldown. An upstream HTTP 502/503
falls back for that request without marking the cache server unavailable: warm
tiles must remain usable when only its internet exit is down. NAS 401, 403,
404 and 504 are preserved: these can represent authorization, absent data or an
offline-cache policy refusal, not a broken NAS connection. Existing tile URLs and
cache query parameters are forwarded unchanged. No administrative cache endpoint
is called. Response header `x-nodedc-map-route` identifies the chosen transport.
Direct transport resolves ion assets 1 (terrain), 2 (Bing imagery) and 96188
(buildings). Only metadata and short-lived credentials are retained in RAM.
Binary tiles stream to the browser; Core creates no persistent tile store and
returns `Cache-Control: no-store`. Range and HEAD requests remain supported.
Provider URLs are allowlisted and ion credentials are restricted to their asset
directory. Redirects are refused. Credentials stay on the server, including the
Bing query key; HTTPX provider URL logging is redacted.
Provider contract changes, unavailable assets and rejected credentials are
reported explicitly. This is not a fallback for private imported Gaussian
products: their existing local ready-product lifecycle is unchanged.
## Secret storage and activation
Core owns `data_dir/services/cesium-ion/settings.json` (0600 file, 0700 service
directory), outside Git and browser profile JSON. Writes use an atomic replace,
fsync and revision checks. Corrupt configuration fails closed instead of silently
replacing it with defaults. API reads expose only configuration status, not the
token. Mutations require a loopback caller and same-origin JSON requests.
The operator enters the token directly in the UI. Check access verifies the three
asset endpoint permissions. Saving a new token repeats this validation before
replacing a working token. It does not prove every tile can be downloaded. URL-
restricted ion tokens must permit the canonical operator origin
`http://127.0.0.1:8000/`, which Core sends as a fixed provider Referer.
The Core token supplies the independent online route for every Core map. Existing
NAS credentials remain owned by Map Gateway and are **not** remotely replaced by
this form. When NAS is available it uses its current credential/cache policy.
There is no dependency on Ops, SMB or Synology for reading/saving Core settings.
After a save, subsequent requests use the new policy. Observation maps with the
recovery hook are notified; an already failed map may need reopening/retry. Do
not forcibly remount an architectural editor with unsaved placement edits.
## Original token/outage acceptance · 17 November 2026
- 30 backend tests: old BFF contract, NAS outage/recovery, unchanged cache URLs,
concurrent single-probe behavior, credential redaction, path/host restrictions,
private storage, revision conflicts and same-origin API boundaries.
- Four focused frontend adapter/indicator tests, existing 1619 frontend tests, application
architecture checks, typecheck, Ruff, focused mypy and production build passed.
- Final selector/header-button adjustment passed the production build/typecheck
and typography gate; UI selection and saving were exercised on port 8000.
- With the real NAS off and no configured Core token, the real service returns
`cesium_token_required` promptly. The Settings UI is usable without NAS.
- The operator saved a valid token (revision 4). With NAS off, real health and
all three asset endpoints succeed via `direct`; terrain layer.json, Bing imagery
metadata and buildings tileset.json return 200. A quantized-mesh terrain tile
returns 200 (15,069 bytes). No test tile was retained on disk.
- UI acceptance confirms the green token indicator and existing local Gaussian
rendering. Full satellite rendering is **not accepted**: the Bing tile host
`ecn.t0.tiles.virtualearth.net` is unreachable from this Mac (direct HTTPS
reports `No route to host`; Core reports `cesium_provider_unavailable`, 503).
Metadata/token success does not establish satellite tile connectivity. No VPN,
DNS or route changes were made to bypass this failure.
- Real NAS recovery/cache reuse has not been tested while the owner's NAS is off.
## Real acceptance after token/NAS availability
1. Save a valid token; with NAS off, inspect imagery, terrain and buildings in
architectural maps and Observation Center. Confirm `x-nodedc-map-route: direct`
and absence of new Core tile storage.
2. Turn NAS on. Allow the 15-second probe cooldown to expire, then move the map.
Confirm `x-nodedc-map-route: gateway` and the existing NAS cache-hit headers.
3. Compare a bounded set of previously cached physical files and existing cache
counters before/after a repeat view; inspect only, do not request a refresh,
purge, import or full cache walk. Confirm a new area follows the NAS's existing
read-through write policy.
4. Disable NAS again and verify recovery with the same map open. No cache rebuild
is an acceptable substitute for diagnosing a routing regression.
## Rollback
Selecting **Сервер хранения локальных данных** disables the new direct transport without
altering cache contents or deleting the saved token. For a source rollback, revert
only the Cesium services changes (especially the `settings_path` wiring in
`web/app.py`), preserving unrelated work in shared files. `MapGatewayProxy`
without `settings_path` retains its previous NAS-only behavior. Never reset the
whole dirty checkout or touch NAS storage as part of this rollback.
## Selectable VPS transport · 17 November 2026
System → VPS can install and pair **Маршрутизация трафика** alongside the existing
services. Profile → Settings → Services → Cesium ion → Routing selects a connected
service or **Текущий маршрут**. The choice is installation-wide, shared by Fleet,
Observation Center and architectural maps. It does not change the machine's
default route, VPN, DNS or application URLs. The initial transport profile only
allows Cesium/Bing GET/HEAD; unrelated external services require their own scoped
profile and client integration.
The independent `egress_vps` package lives in `NODEDC_MISSION_CORE_ARNAVI-VPS`;
its operating contract is `docs/EGRESS_SERVICE.md` in that repository. Core stores
paired credentials in the private Fleet `egress.sqlite3`. TLS 1.3 and an exact
certificate fingerprint are checked before sending credentials. Provider and
relay credentials are separate. Binary responses stream without a Core/VPS tile
store. Disconnecting a route used by Cesium is guarded.
For direct mode the selected relay carries Core's provider requests. For NAS
cache mode the prepared Gateway adapter accepts a separately signed, short-lived
`nodedc.map-egress/v1` request binding. Cache lookup still precedes external fetch;
canonical URLs, keys and physical objects remain unchanged. Gateway deployment
and private signing-key provisioning are required before selecting this mode.
Missing signing material blocks activation even while NAS is offline, preventing
a route that works only until the cache server returns. The prepared adapter is
documented in `platform/services/map-gateway/EGRESS.md`.
**Live state:** routing service 0.1.0 is installed on McHost at port 19446 and
paired with the canonical Core on port 8000. The installer is published in the
Fleet catalog. The NAS adapter is prepared and tested but **not deployed**;
no delegation key has been provisioned. Cesium's selected route remains unchanged.
Real authenticated checks from McHost received CloudFront country-block 403 for
assets 1, 2 and 96188. Core reports `cesium_egress_region_denied`, rather than an
invalid-token error. An attempted save returns 422 and leaves both saved route
and revision unchanged. UI acceptance exercised the route selector, yellow
indicator and explicit per-asset errors, then discarded the draft selection.
The owner has no other VPS. A working external exit channel remains a prerequisite;
installing a relay on the same blocked public IP cannot supply it. No automatic
switch to an unqualified transport is allowed.
Validation: 24 VPS tests; 58 focused Core tests followed by 8 focused egress tests
after the stream-cleanup regression fix; 4 frontend Cesium tests, typography
gate, typecheck and production build. Gateway delegation tests and the existing
credential-boundary, live-cache-fallback and streaming-cache-fill smoke checks
passed. Live wrong relay credential returns 403, private target returns 400, and
wrong certificate pin is rejected. All five McHost services remain active; the
new unit reports zero restarts. These checks do not constitute live NAS-to-VPS or
successful Cesium tile acceptance.
Activation requires a reachable provider exit, real asset and representative
tile checks, then canonical Gateway plan/apply deployment and secret provisioning.
Recheck warm hits, a bounded cold fill, NAS outage/recovery and unchanged cache
objects. The current route remains the rollback until those checks pass.
@@ -17,6 +17,68 @@ Do not start a second backend on another port. Do not use
`launchctl kickstart -k` for this service: it combines termination and restart
without proving that the old process group has released the singleton lease.
## Local HTTPS operator address
The operator-facing alias is `https://nodedc.missioncore`. The canonical
application remains the single backend on `127.0.0.1:8000`; no second Core
process is launched and Worker/provider routes keep their existing endpoints.
The macOS-only installer is `scripts/local_https/install.py`. It uses the
system Apache, a loopback-only listener on ports 80/443, one hosts entry and a
single-host SSL leaf certificate. Administrator authorization is required.
The single-host certificate is trusted for SSL in the operator login keychain
and cannot sign other certificates. It expires after 365 days. `receipt.json` records
its exact validity/fingerprint. Renewal needs explicit administrator action;
the installer refuses to silently replace a certificate nearing expiry.
After the administrator installer prepares the certificate, configure trust
from the operator login session (macOS may show its authorization dialog):
```bash
security add-trusted-cert -r trustRoot -p ssl \
-k "$HOME/Library/Keychains/login.keychain-db" \
"/Library/Application Support/NODE.DC/MissionCoreHTTPS/server.crt"
```
Do not add a policy-string (`-s`) constraint: native certificate verification
accepted it, but curl and Chromium rejected that trust record during qualification.
The leaf itself has exactly one DNS SAN and `CA:FALSE`. Do not run the trust step
inside a background root AppleScript; macOS refuses the interactive authorization
there. The installed gateway's own acceptance pins the certificate; final operator
acceptance must use the login trust store without `--cacert` or insecure flags.
Installed ownership:
- `/Library/Application Support/NODE.DC/MissionCoreHTTPS`: root-owned
configuration, private key, certificate and compact install receipt.
- `/Library/LaunchDaemons/com.nodedc.mission-core.https.plist`: durable
HTTPS gateway; Apache workers drop to `_www`.
- `/Library/Logs/NODE.DC/MissionCoreHTTPS`: bounded two-file 1 MiB error log.
- `/private/etc/hosts`: only the marked `nodedc.missioncore` loopback entry.
The gateway validates the public Host and Origin before mapping them to
Core's existing local boundary. It strips caller-supplied forwarding headers,
rejects foreign origins/cross-site API calls, streams uploads/responses, and
supports Range and WebSocket upgrades. It has no body-size cap or disk cache;
Core retains its own validation/quotas. HTTP redirects to HTTPS. The system
Apache build supports TLS 1.2; no weakened browser security flags are used.
Qualification: `python scripts/local_https/qualify.py` runs a small isolated
transport fixture, verifies forwarded-header stripping, host/origin rejection,
upload hash, Range, a WebSocket frame and redirect. It removes its exact
scratch/processes on exit. It never uploads production files or mutates Core.
Acceptance: `/usr/bin/curl --noproxy '*' https://nodedc.missioncore/api/health`
must pass without insecure flags, and a browser must report a secure context.
Do not restart Core to repair the HTTPS entry. Inspect only
`launchctl print system/com.nodedc.mission-core.https` and its bounded logs.
Rollback is limited to this gateway: boot out that exact system label, remove
its exact plist and marked hosts line, and remove trust for the exact certificate
fingerprint in the receipt. Keep the existing Core listener/data and unrelated
hosts/certificates intact. Never restore the complete hosts backup over later
changes. This alias is local to the configured Mac, not public DNS.
## Recovery contract
The installed LaunchAgent and application form one bounded recovery ladder:
@@ -0,0 +1,12 @@
# Observation view persistence
The operator's map camera/layer choices and selected rover model belong to Core presentation, not the vehicle's control authority. They use the existing scene profile store (`scene-profiles/<kind>/<owner hash>/meta.json`) with the vehicle ID as owner:
- `observation-map`: camera longitude/latitude/height/heading/pitch/roll and five layer visibility flags.
- `rover-view`: chosen model ID only.
The browser record is only a one-time migration input after an acknowledged empty profile read. Reopening waits for writes queued by the previous view. Atomic revisioned writes retain meta.previous.json; read errors cannot publish defaults. Browser cache clearing does not erase these profiles.
Tracker centering is automatic only when no camera has been saved or chosen. “Показать аппарат на карте” deliberately recenters. Renderer recovery uses the latest camera, not the mount-time value.
PlayCanvas scene materials, layout and its own camera remain in the separate existing `rover` profile. Arming and input ownership are never restored by either presentation profile.
+2 -2
View File
@@ -18,7 +18,7 @@ dependencies = [
"httpx>=0.28,<1",
"lz4>=4.4,<5",
"missioncore-plugin-sdk",
"nodedc-bim-module==0.2.25",
"nodedc-bim-module==0.2.30",
"paho-mqtt>=2.1,<3",
"pillow>=12,<13",
"pyyaml>=6.0,<7",
@@ -29,7 +29,7 @@ dependencies = [
]
[tool.uv.sources]
nodedc-bim-module = { path = "vendor/bim/nodedc_bim_module-0.2.25-py3-none-any.whl" }
nodedc-bim-module = { path = "vendor/bim/nodedc_bim_module-0.2.30-py3-none-any.whl" }
missioncore-plugin-sdk = { path = "packages/plugin-sdk", editable = true }
[project.optional-dependencies]
+291
View File
@@ -0,0 +1,291 @@
#!/usr/bin/env python3
"""Install the operator's loopback HTTPS name using macOS's own Apache.
Run with administrator authorization. This never restarts or replaces Core.
The certificate is a single-host leaf, not a general-purpose signing CA.
"""
import hashlib
import json
import os
import pathlib
import plistlib
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
DOMAIN = "nodedc.missioncore"
ORIGIN = "https://" + DOMAIN
LABEL = "com.nodedc.mission-core.https"
ROOT = pathlib.Path("/Library/Application Support/NODE.DC/MissionCoreHTTPS")
LOGS = pathlib.Path("/Library/Logs/NODE.DC/MissionCoreHTTPS")
PLIST = pathlib.Path("/Library/LaunchDaemons") / (LABEL + ".plist")
HOSTS = pathlib.Path("/private/etc/hosts")
HOST_LINE = "127.0.0.1 nodedc.missioncore # NODE.DC Mission Core HTTPS"
def config(root=ROOT, logs=LOGS, https_port=443, http_port=80, upstream_port=8000):
"""Ports/paths can be overridden for an isolated transport qualification."""
proxy_route = (
f"http://127.0.0.1:{upstream_port}/ nocanon "
"connectiontimeout=3 timeout=3600 upgrade=websocket"
)
return f'''ServerRoot "/usr"
ServerName {DOMAIN}
Listen 127.0.0.1:{http_port}
Listen 127.0.0.1:{https_port}
LoadModule mpm_event_module libexec/apache2/mod_mpm_event.so
LoadModule unixd_module libexec/apache2/mod_unixd.so
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
LoadModule ssl_module libexec/apache2/mod_ssl.so
LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
LoadModule headers_module libexec/apache2/mod_headers.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
User _www
Group _www
PidFile "{root}/httpd.pid"
DefaultRuntimeDir "{root}"
Mutex "file:{root}" default
ErrorLog "|/usr/sbin/rotatelogs -n 2 '{logs}/error.log' 1M"
LogLevel warn
ServerTokens Prod
ServerSignature Off
TraceEnable Off
StartServers 1
ServerLimit 2
ThreadLimit 32
ThreadsPerChild 32
MinSpareThreads 16
MaxSpareThreads 32
MaxRequestWorkers 64
MaxConnectionsPerChild 10000
Timeout 600
KeepAlive On
KeepAliveTimeout 5
LimitRequestBody 0
AllowEncodedSlashes NoDecode
<Directory />
Require all denied
</Directory>
<VirtualHost 127.0.0.1:{http_port}>
ServerName {DOMAIN}
RewriteEngine On
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{http_port})?$ [NC]
RewriteRule ^ - [F,L]
RewriteRule ^/(.*)$ {ORIGIN}/$1 [R=308,NE,L]
</VirtualHost>
<VirtualHost 127.0.0.1:{https_port}>
ServerName {DOMAIN}
SSLEngine On
SSLProtocol -all +TLSv1.2
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
SSLCertificateFile "{root}/server.crt"
SSLCertificateKeyFile "{root}/server.key"
RewriteEngine On
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{https_port})?$ [NC]
RewriteRule ^ - [F,L]
# Validate the public browser origin BEFORE mapping it to Core's origin.
RewriteCond %{{HTTP:Origin}} !^$
RewriteCond %{{HTTP:Origin}} !^{ORIGIN.replace(".", "[.]")}(:{https_port})?$
RewriteRule ^ - [F,L]
# External links may navigate to the UI; cross-site API calls remain blocked.
RewriteCond %{{HTTP:Sec-Fetch-Site}} ^cross-site$ [NC]
RewriteCond %{{HTTP:Sec-Fetch-Mode}} !^navigate$ [NC,OR]
RewriteCond %{{REQUEST_URI}} ^/(api|ws)(/|$) [NC]
RewriteRule ^ - [F,L]
ProxyRequests Off
ProxyPreserveHost Off
ProxyAddHeaders Off
RequestHeader unset Forwarded
RequestHeader unset X-Forwarded-For
RequestHeader unset X-Forwarded-Host
RequestHeader unset X-Forwarded-Proto
RequestHeader unset X-Forwarded-Port
RequestHeader unset X-Real-IP
RequestHeader edit Origin "^{ORIGIN.replace(".", "[.]")}(:{https_port})?$" "http://127.0.0.1:{upstream_port}"
ProxyPass / {proxy_route}
ProxyPassReverse / http://127.0.0.1:{upstream_port}/
<Location />
Require all granted
</Location>
</VirtualHost>
'''
def run(*args):
result = subprocess.run(args, capture_output=True, text=True)
if result.returncode:
raise RuntimeError(f"{args[0]}: {result.stderr.strip()}")
return result.stdout.strip()
def atomic(path, content, mode=0o600):
fd, name = tempfile.mkstemp(dir=path.parent, prefix=".https-")
try:
with os.fdopen(fd, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.chmod(name, mode)
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
def create_certificate(root):
key, cert = root / "server.key", root / "server.crt"
if key.exists() and cert.exists():
run("/usr/bin/openssl", "x509", "-in", str(cert), "-checkend", "2592000", "-noout")
return
if key.exists() or cert.exists():
raise RuntimeError("Incomplete HTTPS certificate; inspect before replacing it")
spec = root / "certificate.conf"
atomic(
spec,
f"""[req]
prompt=no
distinguished_name=dn
x509_extensions=server
[dn]
CN={DOMAIN}
O=NODE.DC Local Mission Core
[server]
subjectAltName=DNS:{DOMAIN}
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
""".encode(),
)
run(
"/usr/bin/openssl",
"req",
"-new",
"-x509",
"-newkey",
"rsa:2048",
"-nodes",
"-sha256",
"-days",
"365",
"-config",
str(spec),
"-keyout",
str(key),
"-out",
str(cert),
)
os.chmod(key, 0o600)
os.chmod(cert, 0o644)
spec.unlink()
def install():
if sys.platform != "darwin" or os.geteuid() != 0:
raise RuntimeError("Use macOS administrator authorization for this installer")
op = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with op.open("http://127.0.0.1:8000/api/health", timeout=10) as response:
health = json.load(response)
if health.get("service") != "mission-core-control-plane" or not health.get("ok"):
raise RuntimeError("Canonical Mission Core is not healthy")
before = HOSTS.read_bytes()
for line in before.decode().splitlines():
fields = line.split("#", 1)[0].split()
if DOMAIN in fields[1:] and fields[0] != "127.0.0.1":
raise RuntimeError("The requested name already resolves elsewhere in hosts")
existing = (
subprocess.run(
["/bin/launchctl", "print", "system/" + LABEL], capture_output=True
).returncode
== 0
)
if not existing:
for port in (80, 443):
with socket.socket() as probe:
probe.bind(("127.0.0.1", port))
for directory in (ROOT, LOGS):
directory.mkdir(parents=True, exist_ok=True)
os.chmod(directory, 0o755)
create_certificate(ROOT)
conf = config().encode()
conf_path = ROOT / "httpd.conf"
if existing and conf_path.read_bytes() != conf:
raise RuntimeError("Existing HTTPS configuration differs; review before restarting")
atomic(conf_path, conf, 0o644)
run("/usr/sbin/httpd", "-t", "-f", str(conf_path))
# Trust is configured separately in the operator's login session. macOS
# refuses interactive trust authorization from this background root process.
# Never install a general signing CA or disable browser certificate checks.
if not any(
DOMAIN in line.split("#", 1)[0].split()[1:] for line in before.decode().splitlines()
):
if not (ROOT / "hosts.before").exists():
atomic(ROOT / "hosts.before", before)
atomic(HOSTS, before.rstrip(b"\n") + b"\n" + HOST_LINE.encode() + b"\n", 0o644)
run("/usr/bin/dscacheutil", "-flushcache")
declaration = plistlib.dumps(
{
"Label": LABEL,
"ProgramArguments": ["/usr/sbin/httpd", "-f", str(conf_path), "-D", "FOREGROUND"],
"RunAtLoad": True,
"KeepAlive": True,
"ThrottleInterval": 5,
"AbandonProcessGroup": False,
"ExitTimeOut": 15,
}
)
if PLIST.exists() and PLIST.read_bytes() != declaration:
raise RuntimeError("Existing HTTPS launch declaration differs; review it first")
atomic(PLIST, declaration, 0o644)
if not existing:
run("/bin/launchctl", "bootstrap", "system", str(PLIST))
for _attempt in range(20):
check = subprocess.run(
[
"/usr/bin/curl",
"--noproxy",
"*",
"--silent",
"--show-error",
"--fail",
"--max-time",
"5",
"--cacert",
str(ROOT / "server.crt"),
ORIGIN + "/api/health",
],
capture_output=True,
text=True,
)
if check.returncode == 0 and json.loads(check.stdout).get("ok"):
receipt = {
"url": ORIGIN,
"upstream": "http://127.0.0.1:8000",
"config_sha256": hashlib.sha256(conf).hexdigest(),
"certificate": run(
"/usr/bin/openssl",
"x509",
"-in",
str(ROOT / "server.crt"),
"-noout",
"-dates",
"-fingerprint",
"-sha256",
),
"core_restarted": False,
"https_health": "verified_exact_certificate",
"browser_trust": "verify_in_operator_login_session",
}
atomic(ROOT / "receipt.json", (json.dumps(receipt, indent=2) + "\n").encode())
print(json.dumps(receipt, indent=2))
return
time.sleep(0.5)
raise RuntimeError("HTTPS health failed: " + check.stderr[-500:])
if __name__ == "__main__":
install()
+196
View File
@@ -0,0 +1,196 @@
"""Bounded Apache transport qualification; no production data is modified."""
import base64
import hashlib
import http.client
import http.server
import json
import os
import pathlib
import shutil
import signal
import socket
import ssl
import subprocess
import tempfile
import threading
import time
from install import DOMAIN, config, create_certificate
class Echo(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def do_GET(self):
if self.headers.get("Upgrade", "").lower() == "websocket":
value = self.headers["Sec-WebSocket-Key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
self.send_response(101)
self.send_header("Upgrade", "websocket")
self.send_header("Connection", "Upgrade")
self.send_header(
"Sec-WebSocket-Accept",
base64.b64encode(hashlib.sha1(value.encode()).digest()).decode(),
)
self.end_headers()
self.wfile.write(b"\x81\x02ok")
self.wfile.flush()
self.close_connection = True
return
body = json.dumps(dict(self.headers)).encode()
self.send_response(206 if self.headers.get("Range") else 200)
if self.headers.get("Range"):
self.send_header("Content-Range", "bytes 0-1/2")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
digest = hashlib.sha256()
left = int(self.headers["Content-Length"])
while left:
chunk = self.rfile.read(min(left, 65536))
if not chunk:
raise RuntimeError("Truncated stream")
digest.update(chunk)
left -= len(chunk)
body = digest.hexdigest().encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def free_port():
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
def main():
# macOS's Apache cannot read an operator's protected Downloads directory.
scratch = pathlib.Path(tempfile.mkdtemp(prefix="missioncore-https-transport-"))
upstream = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Echo)
threading.Thread(target=upstream.serve_forever, daemon=True).start()
process = None
try:
create_certificate(scratch)
tls_port, redirect_port = free_port(), free_port()
(scratch / "httpd.conf").write_text(
config(scratch, scratch, tls_port, redirect_port, upstream.server_port)
)
subprocess.run(
["/usr/sbin/httpd", "-t", "-f", str(scratch / "httpd.conf")],
check=True,
capture_output=True,
)
process = subprocess.Popen(
["/usr/sbin/httpd", "-f", str(scratch / "httpd.conf"), "-D", "FOREGROUND"],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
start_new_session=True,
)
context = ssl.create_default_context(cafile=str(scratch / "server.crt"))
context.check_hostname = (
False # Test socket uses loopback; trusted test certificate still verified.
)
def call(path="/", method="GET", headers=None, body=None):
connection = http.client.HTTPSConnection(
"127.0.0.1", tls_port, context=context, timeout=10
)
connection.request(
method, path, body=body, headers={"Host": f"{DOMAIN}:{tls_port}", **(headers or {})}
)
response = connection.getresponse()
result = response.status, dict(response.headers), response.read()
connection.close()
return result
for _ in range(50):
try:
call()
break
except OSError:
if process.poll() is not None:
errors = "\n".join(p.read_text() for p in scratch.glob("error.log*"))
raise RuntimeError(process.stderr.read().decode() + errors) from None
time.sleep(0.1)
status, _, body = call(
"/api/check",
headers={
"Origin": f"https://{DOMAIN}:{tls_port}",
"Sec-Fetch-Site": "same-origin",
"X-Forwarded-For": "8.8.8.8",
"X-Forwarded-Proto": "https",
},
)
mapped = {k.lower(): v for k, v in json.loads(body).items()}
assert status == 200 and mapped["host"] == f"127.0.0.1:{upstream.server_port}"
assert mapped["origin"] == f"http://127.0.0.1:{upstream.server_port}"
assert "x-forwarded-for" not in mapped and "x-forwarded-proto" not in mapped
assert call(headers={"Host": "evil.example"})[0] == 403
assert call(headers={"Origin": "https://evil.example"})[0] == 403
assert call(headers={"Origin": "null"})[0] == 403
assert (
call(
"/api/check", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"}
)[0]
== 403
)
assert (
call("/", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"})[0]
== 200
)
assert call("/api/check", headers={"Range": "bytes=0-1"})[0] == 206
payload = b"NODE.DC-stream-test" * 65536
assert (
call("/upload", "POST", body=payload)[2].decode() == hashlib.sha256(payload).hexdigest()
)
with (
socket.create_connection(("127.0.0.1", tls_port), timeout=5) as tcp,
context.wrap_socket(tcp, server_hostname=DOMAIN) as stream,
):
key = base64.b64encode(os.urandom(16)).decode()
stream.sendall(
(
f"GET /socket HTTP/1.1\r\nHost: {DOMAIN}:{tls_port}\r\n"
f"Origin: https://{DOMAIN}:{tls_port}\r\n"
"Upgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n\r\n"
).encode()
)
data = b""
while b"\r\n\r\n" not in data or not data.endswith(b"\x81\x02ok"):
part = stream.recv(4096)
if not part:
break
data += part
assert b"101 Switching Protocols" in data and data.endswith(b"\x81\x02ok")
connection = http.client.HTTPConnection("127.0.0.1", redirect_port, timeout=5)
connection.request("GET", "/path?q=1", headers={"Host": f"{DOMAIN}:{redirect_port}"})
response = connection.getresponse()
assert (
response.status == 308
and response.headers["Location"] == "https://nodedc.missioncore/path?q=1"
)
response.read()
connection.close()
print(
"PASS: origin/host boundary, forwarded-header stripping, range, "
"upload hash, WebSocket frame, HTTP redirect"
)
finally:
if process is not None and process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
process.wait(timeout=10)
upstream.shutdown()
upstream.server_close()
shutil.rmtree(scratch)
if __name__ == "__main__":
main()
+11 -1
View File
@@ -18,7 +18,7 @@ def main():
parser.add_argument("--version", required=True)
parser.add_argument(
"--kind",
choices=("node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"),
choices=("node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"),
required=True,
)
args = parser.parse_args()
@@ -88,6 +88,16 @@ def main():
"Скопируйте с VPS файл /var/lib/ndc-librespeed-vps/mission-core-librespeed.json и выберите его в этом окне. Затем нажмите «Подключить службу».",
],
)
if args.kind == "vps-egress":
value.update(
label="Маршрутизация трафика",
os="Ubuntu Server 24.04 LTS · x86-64",
instructions=[
"Скопируйте установщик на VPS: sudo python3 mission-core-egress-vps.pyz plan --host АДРЕС",
"Примените проверенный план: sudo python3 mission-core-egress-vps.pyz apply --host АДРЕС --expect ХЕШ_ПЛАНА",
"Подключите службу файлом /var/lib/ndc-egress-vps/mission-core-egress.json.",
],
)
temporary = root / (args.kind + ".json.new")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
temporary.chmod(0o600)
+133
View File
@@ -0,0 +1,133 @@
"""Durable ownership and private credentials for portable egress services."""
import json
import re
import secrets
import sqlite3
import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from . import vps_transport
from .trust import PairingError
Document = dict[str, Any]
lock = threading.RLock()
def invitation(document: str) -> Document:
try:
value = json.loads(document)
if set(value) != {
"schema",
"server_id",
"endpoint",
"fingerprint",
"bootstrap",
"expires_at",
}:
raise ValueError
if value["schema"] != "missioncore.egress-connect/v1":
raise ValueError
for key, pattern in (
("server_id", r"eg_[a-f0-9]{32}"),
("fingerprint", r"[a-f0-9]{64}"),
("bootstrap", r"[A-Za-z0-9_-]{43}"),
):
if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]):
raise ValueError
if not time.time() < value["expires_at"] <= time.time() + 86500:
raise PairingError("Приглашение службы маршрутизации просрочено. Скачайте новое с VPS.")
vps_transport.destination(value["endpoint"])
return dict(value)
except (ValueError, TypeError, KeyError):
raise PairingError("Файл приглашения Egress повреждён или просрочен.") from None
class Egress:
def __init__(self, root: Path):
self.path = root / "egress.sqlite3"
root.mkdir(parents=True, exist_ok=True)
with self.db() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS services (id TEXT PRIMARY KEY, body TEXT NOT NULL)"
)
self.path.chmod(0o600)
@contextmanager
def db(self) -> Iterator[sqlite3.Connection]:
connection = sqlite3.connect(self.path)
try:
with connection:
yield connection
finally:
connection.close()
def rows(self) -> list[Document]:
with lock, self.db() as db:
return [json.loads(r[0]) for r in db.execute("SELECT body FROM services")]
def listing(self) -> list[Document]:
return [
{k: r[k] for k in ("id", "endpoint", "state", "fingerprint")}
for r in self.rows()
if r["state"] == "connected"
]
def save(self, row: Document) -> None:
with self.db() as db:
db.execute("INSERT OR REPLACE INTO services VALUES (?,?)", (row["id"], json.dumps(row)))
def find(self, identifier: str) -> Document:
row = next(
(r for r in self.rows() if r["id"] == identifier and r["state"] == "connected"), None
)
if not row:
raise PairingError("Подключите службу маршрутизации на VPS.")
return row
def pair(self, document: str, network_interface: str | None = None) -> Document:
value = invitation(document)
vps_transport.validate_interface(network_interface)
with lock:
row = next((r for r in self.rows() if r["id"] == value["server_id"]), None)
if row and (
row["fingerprint"] != value["fingerprint"] or row["endpoint"] != value["endpoint"]
):
raise PairingError("Идентичность службы маршрутизации изменилась.")
if row is None:
row = {
"id": value["server_id"],
"endpoint": value["endpoint"],
"fingerprint": value["fingerprint"],
"token": secrets.token_urlsafe(32),
"core_id": "core_" + secrets.token_hex(16),
"state": "pending",
}
row["network_interface"] = network_interface
self.save(row) # Retry a lost claim reply using the same controller identity.
result = vps_transport.request(
row,
"POST",
"/v1/claim",
{
"core_id": row["core_id"],
"bootstrap": value["bootstrap"],
"credential": row["token"],
},
)
if (
result.get("server_id") != row["id"]
or result.get("schema") != "missioncore.egress/v1"
):
raise PairingError("VPS вернул другую службу.")
row["state"] = "connected"
self.save(row)
return {"id": row["id"], "state": "connected"}
def forget(self, identifiers: set[str]) -> None:
with lock, self.db() as db:
db.executemany("DELETE FROM services WHERE id=?", [(i,) for i in identifiers])
+137
View File
@@ -0,0 +1,137 @@
"""Pinned streaming transport shared by service clients; no persistent payloads."""
from __future__ import annotations
import asyncio
import hashlib
import http.client
import socket
import ssl
from collections.abc import AsyncIterator
from contextlib import suppress
from typing import Any
from urllib.parse import urlencode
import httpx
from . import vps_transport
from .trust import PairingError
def open_response(
binding: dict[str, Any], method: str, target: str, headers: dict[str, str], profile: str
) -> tuple[http.client.HTTPConnection, http.client.HTTPResponse]:
if profile != "cesium" or method not in {"GET", "HEAD"}:
raise ValueError("Unsupported egress profile")
name, port, address = vps_transport.destination(binding["endpoint"])
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = (
ssl.CERT_NONE
) # Mandatory certificate pin checked BEFORE sending any bytes.
context.minimum_version = ssl.TLSVersion.TLSv1_3
connection = http.client.HTTPConnection(name, port, timeout=30)
raw = vps_transport.connect(address, port, binding.get("network_interface"))
try:
connection.sock = context.wrap_socket(raw, server_hostname=name)
if (
hashlib.sha256(connection.sock.getpeercert(binary_form=True) or b"").hexdigest()
!= binding["fingerprint"]
):
raise PairingError("Идентичность службы маршрутизации изменилась.")
connection.sock.settimeout(30)
forwarded = {
k: v
for k, v in headers.items()
if k.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
}
for key, value in headers.items():
if key.lower() == "authorization":
forwarded["X-Nodedc-Upstream-Authorization"] = value
elif key.lower() == "referer":
forwarded["X-Nodedc-Upstream-Referer"] = value
forwarded["Authorization"] = "Bearer " + binding["token"]
connection.request(
method, "/v1/fetch/" + profile + "?" + urlencode({"url": target}), headers=forwarded
)
return connection, connection.getresponse()
except BaseException:
raw.close()
connection.close()
raise
class RelayStream(httpx.AsyncByteStream):
def __init__(
self,
connection: http.client.HTTPConnection,
response: http.client.HTTPResponse,
slots: asyncio.Semaphore,
) -> None:
self.connection, self.response, self.slots = connection, response, slots
self.closed = False
async def __aiter__(self) -> AsyncIterator[bytes]:
try:
while data := await asyncio.to_thread(self.response.read, 65536):
yield data
if self.response.length not in (None, 0):
raise http.client.IncompleteRead(b"", self.response.length)
except (OSError, http.client.HTTPException) as exc:
raise httpx.ReadError("Routing service stream interrupted") from exc
finally:
await self.aclose()
async def aclose(self) -> None:
if not self.closed:
self.closed = True
try:
if self.connection.sock is not None:
with suppress(OSError):
self.connection.sock.shutdown(socket.SHUT_RDWR)
self.connection.close()
await asyncio.to_thread(self.response.close)
finally:
self.slots.release()
class EgressTransport:
def __init__(self) -> None:
self.slots = asyncio.Semaphore(16)
async def request(
self,
binding: dict[str, Any],
method: str,
target: str,
headers: dict[str, str],
profile: str = "cesium",
) -> httpx.Response:
await self.slots.acquire()
task = asyncio.create_task(
asyncio.to_thread(open_response, binding, method, target, headers, profile)
)
try:
connection, response = await asyncio.shield(task)
except asyncio.CancelledError:
def finish(done: asyncio.Task[Any]) -> None:
try:
conn, result = done.result()
conn.close()
result.close()
except Exception:
pass
finally:
self.slots.release()
task.add_done_callback(finish)
raise
except (OSError, ValueError, http.client.HTTPException) as exc:
self.slots.release()
raise httpx.ConnectError("Routing service unavailable") from exc
return httpx.Response(
response.status,
headers=response.getheaders(),
stream=RelayStream(connection, response, self.slots),
)
+34 -1
View File
@@ -11,9 +11,12 @@ from typing import Any
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
from k1link.fleet import network_client
from k1link.fleet.egress import Egress
from k1link.fleet.egress import lock as egress_lock
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import lock as speed_lock
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
class ServerRemoval:
@@ -30,6 +33,7 @@ class ServerRemoval:
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
with (
speed_lock,
egress_lock,
self.networks.import_lock,
self.hosts.lock,
self.networks.sync_lock,
@@ -104,7 +108,28 @@ class ServerRemoval:
for e in self.fleet.routers.pending.values()
):
blocked.append("Остановите замер скорости перед отключением VPS.")
egress = [
r
for r in Egress(self.fleet.root).rows()
if endpoint_address(r["endpoint"]) == host["address"]
]
if egress:
try:
selected = (
CesiumSettingsStore(
self.fleet.root.parent / "services" / "cesium-ion" / "settings.json"
)
.read()
.egress_id
)
if selected in {r["id"] for r in egress}:
blocked.append("Сначала выберите другой маршрут в настройках Cesium ion.")
except MapServiceError:
blocked.append("Не удалось проверить настройки маршрутизации Cesium ion.")
signature = {
"egress": [
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in egress
],
"librespeed": [
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in speed
],
@@ -138,7 +163,8 @@ class ServerRemoval:
"blocked": blocked,
"services": ["ARNavi"] * len(arnavi)
+ ["WireGuard"] * len(wg)
+ ["LibreSpeed"] * len(speed),
+ ["LibreSpeed"] * len(speed)
+ ["Маршрутизация трафика"] * len(egress),
"vehicle_connections": len(affected),
"worker_connections": sum(
c.profile_id in profiles for w in registry.workers for c in w.connections
@@ -235,5 +261,12 @@ class ServerRemoval:
if endpoint_address(r["endpoint"]) == host["address"]
}
)
Egress(self.fleet.root).forget(
{
r["id"]
for r in Egress(self.fleet.root).rows()
if endpoint_address(r["endpoint"]) == host["address"]
}
)
self.catalog.remove(host["id"])
return {"removed": True, "id": host["id"]}
+1
View File
@@ -0,0 +1 @@
"""Shared map service configuration and optional, diskless provider transport."""
+316
View File
@@ -0,0 +1,316 @@
from __future__ import annotations
import asyncio
import base64
import json
import re
import time
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit
import httpx
from .settings import MapServiceError
ASSETS = {1: "TERRAIN", 2: "IMAGERY", 96188: "3DTILES"}
BING_HOSTS = {
"dev.virtualearth.net",
"ecn.tiles.virtualearth.net",
*(f"ecn.t{n}.tiles.virtualearth.net" for n in range(4)),
}
ION_HOSTS = {"assets.ion.cesium.com", "assets.cesium.com"}
SECRET_KEYS = {"key", "access_token", "token", "authorization", "signature", "sig"}
MAX_JSON = 2 * 1024 * 1024
class JsonStream(httpx.AsyncByteStream):
def __init__(self, payload: bytes) -> None:
self.payload = payload
async def __aiter__(self) -> AsyncIterator[bytes]:
yield self.payload
def json_response(document: dict[str, Any], status: int = 200) -> httpx.Response:
return httpx.Response(
status,
headers={"content-type": "application/json", "cache-control": "no-store"},
stream=JsonStream(json.dumps(document).encode()),
)
def safe_url(raw: str) -> str:
try:
url = urlsplit(raw)
if (
url.scheme != "https"
or url.hostname not in ION_HOSTS | BING_HOSTS
or url.port not in (None, 443)
or url.username
or url.password
or url.fragment
or len(raw) > 8192
):
raise ValueError
decoded = unquote(url.path)
if "\\" in decoded or any(part in (".", "..") for part in decoded.split("/")):
raise ValueError
# Encoded separators must not broaden the credential scope downstream.
if re.search(r"%2f|%5c|%25", url.path, re.I):
raise ValueError
return urlunsplit(
(
url.scheme,
url.netloc,
url.path,
urlencode(
[
(k, v)
for k, v in parse_qsl(url.query, keep_blank_values=True)
if k.lower() not in SECRET_KEYS
and not k.lower().startswith("nodedc_cache_")
]
),
"",
)
)
except ValueError as exc:
raise MapServiceError("cesium_resource_not_allowed", 403) from exc
def in_scope(target: str, root: str) -> bool:
url, base = urlsplit(target), urlsplit(root)
if (url.scheme, url.netloc) != (base.scheme, base.netloc):
return False
if url.path == base.path:
return True
directory = base.path.rsplit("/", 1)[0] + "/"
return directory != "/" and url.path.startswith(directory)
async def read_json(response: httpx.Response) -> dict[str, Any]:
try:
payload = bytearray()
async for chunk in response.aiter_bytes():
payload.extend(chunk)
if len(payload) > MAX_JSON:
raise ValueError
document = json.loads(payload)
if not isinstance(document, dict):
raise ValueError
return document
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_provider_invalid_response", 502) from exc
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
finally:
await response.aclose()
@dataclass
class Endpoint:
public: dict[str, Any]
root: str
credential: str = field(repr=False)
expires: float = 0
class DirectCesium:
"""Official providers through Core. Only three credentials/metadata live in RAM.
No tile cache, private token in a browser URL, alternate renderer or NAS mutation.
Endpoint-derived credentials are scoped to the exact provider asset directory.
"""
def __init__(
self,
token: str,
client: httpx.AsyncClient,
provider_request: Callable[..., Awaitable[httpx.Response]] | None = None,
) -> None:
self.provider_request = provider_request
self._token = token
self.client = client
self.endpoints: dict[int, Endpoint] = {}
self.locks = {asset: asyncio.Lock() for asset in ASSETS}
async def endpoint(self, asset: int, *, refresh: bool = False) -> Endpoint:
if asset not in ASSETS:
raise MapServiceError("cesium_asset_not_allowed", 404)
if not self._token:
raise MapServiceError("cesium_token_required", 503)
async with self.locks[asset]:
cached = self.endpoints.get(asset)
if not refresh and cached and cached.expires > time.time():
return cached
response = await self._request(
"GET",
f"https://api.cesium.com/v1/assets/{asset}/endpoint",
headers={"Authorization": f"Bearer {self._token}"},
)
await self._require_success(response)
body = await read_json(response)
if body.get("type") != ASSETS[asset]:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
public: dict[str, Any] = {
"assetId": str(asset),
"type": ASSETS[asset],
"credentialMode": "gateway",
"attributions": self._attributions(body.get("attributions")),
}
if asset == 2:
options = body.get("options")
if body.get("externalType") != "BING" or not isinstance(options, dict):
raise MapServiceError("cesium_provider_contract_mismatch", 502)
root = safe_url(str(options.get("url", "")))
if urlsplit(root).hostname != "dev.virtualearth.net":
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = options.get("key")
public.update(
externalType="BING",
options={"url": root, "mapStyle": str(options.get("mapStyle", "Aerial"))},
)
else:
root = safe_url(str(body.get("url", "")))
if urlsplit(root).hostname not in ION_HOSTS:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = body.get("accessToken")
public["url"] = root
if not isinstance(credential, str) or not credential or len(credential) > 16384:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
expiry = time.time() + 900
if asset != 2:
try:
segment = credential.split(".")[1]
jwt = json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)))
expiry = min(expiry, float(jwt["exp"]) - 60)
except (ValueError, KeyError, IndexError, TypeError):
pass
result = Endpoint(public, root, credential, expiry)
self.endpoints[asset] = result
return result
async def verify(self) -> dict[str, Any]:
async def check(asset: int) -> tuple[str, dict[str, Any]]:
try:
await self.endpoint(asset)
return str(asset), {"ok": True}
except MapServiceError as exc:
return str(asset), {"ok": False, "code": exc.code}
results = dict(await asyncio.gather(*(check(asset) for asset in ASSETS)))
return {"ok": all(value["ok"] for value in results.values()), "assets": results}
async def resource(self, method: str, target: str, headers: dict[str, str]) -> httpx.Response:
target = safe_url(target)
is_bing = urlsplit(target).hostname in BING_HOSTS
# A page can have been initialized through NAS before its outage. Resolve
# only the relevant asset(s); failure of imagery cannot block terrain.
asset_ids = (2,) if is_bing else (1, 96188)
endpoint = None
matched_asset = None
last_error = None
for asset in asset_ids:
try:
candidate = await self.endpoint(asset)
except MapServiceError as exc:
last_error = exc
continue
if is_bing or in_scope(target, candidate.root):
endpoint, matched_asset = candidate, asset
break
if endpoint is None or matched_asset is None:
raise last_error or MapServiceError("cesium_resource_outside_asset", 403)
for attempt in range(2):
outgoing = dict(headers)
outgoing["accept-encoding"] = "identity"
url = target
if is_bing:
# httpx request logging must not emit this URL (see transport).
url += ("&" if urlsplit(url).query else "?") + urlencode(
{"key": endpoint.credential}
)
else:
outgoing["authorization"] = f"Bearer {endpoint.credential}"
response = await self._request(method, url, headers=outgoing)
if response.status_code in (401, 403) and attempt == 0:
await response.aclose()
endpoint = await self.endpoint(matched_asset, refresh=True)
if not is_bing and not in_scope(target, endpoint.root):
raise MapServiceError("cesium_endpoint_changed", 409)
continue
await self._require_success(response)
response.headers["cache-control"] = "no-store"
response.headers["x-nodedc-map-route"] = "direct"
if (
method != "HEAD"
and response.status_code not in (204, 304)
and (
"json" in response.headers.get("content-type", "")
or urlsplit(target).path.endswith(".json")
)
):
document = self._sanitize(await read_json(response), endpoint.credential)
result = json_response(document, response.status_code)
result.headers["x-nodedc-map-route"] = "direct"
return result
return response
raise MapServiceError("cesium_provider_unauthorized", 401)
async def _request(self, method: str, url: str, *, headers: dict[str, str]) -> httpx.Response:
try:
# Core has one canonical operator origin. Keep URL-restricted ion
# tokens usable without accepting a caller-supplied provider origin.
headers = {**headers, "referer": "http://127.0.0.1:8000/"}
if self.provider_request is not None:
return await self.provider_request(method, url, headers=headers)
request = self.client.build_request(
method, url, headers=headers, timeout=httpx.Timeout(20, connect=4)
)
return await self.client.send(request, stream=True, follow_redirects=False)
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
@staticmethod
async def _require_success(response: httpx.Response) -> None:
if response.status_code in (200, 206, 204, 304):
return
status = response.status_code
code = response.headers.get("x-nodedc-egress-error")
await response.aclose()
if code == "upstream_region_denied":
raise MapServiceError("cesium_egress_region_denied", 403)
if code:
raise MapServiceError("cesium_egress_unavailable", 503)
if status in (401, 403):
raise MapServiceError("cesium_provider_unauthorized", status)
if status == 429:
raise MapServiceError("cesium_provider_rate_limited", 429)
raise MapServiceError("cesium_provider_unavailable", 502)
@staticmethod
def _attributions(value: object) -> list[dict[str, Any]]:
if not isinstance(value, list):
return []
return [
{"html": str(item.get("html", "")), "collapsible": bool(item.get("collapsible"))}
for item in value[:100]
if isinstance(item, dict)
]
@classmethod
def _sanitize(cls, value: Any, credential: str) -> Any:
if isinstance(value, dict):
return {
key: cls._sanitize(item, credential)
for key, item in value.items()
if key.lower().replace("_", "")
not in {"key", "token", "accesstoken", "authorization"}
}
if isinstance(value, list):
return [cls._sanitize(item, credential) for item in value]
if isinstance(value, str):
return value.replace(credential, "nodedc-gateway")
return value
+37
View File
@@ -0,0 +1,37 @@
"""Signed request-scoped cache egress. Secrets stay between Core and Gateway."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import re
import time
from pathlib import Path
from typing import Any
from .settings import MapServiceError
def gateway_headers(
key_path: Path, binding: dict[str, Any], method: str, path: str
) -> dict[str, str]:
try:
if key_path.is_symlink() or key_path.stat().st_size > 128:
raise ValueError()
key = key_path.read_text().strip()
if not re.fullmatch(r"[a-f0-9]{64}", key):
raise ValueError()
except (OSError, ValueError) as exc:
raise MapServiceError("cesium_egress_gateway_not_ready", 503) from exc
value = {k: binding[k] for k in ("endpoint", "fingerprint", "token")}
value.update(schema="nodedc.map-egress/v1", timestamp=int(time.time()), profile="cesium")
payload = (
base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode())
.decode()
.rstrip("=")
)
message = f"nodedc.map-egress/v1\n{method}\n{path}\n{payload}"
signature = hmac.new(bytes.fromhex(key), message.encode(), hashlib.sha256).hexdigest()
return {"x-nodedc-map-egress": payload, "x-nodedc-map-egress-signature": signature}
+269
View File
@@ -0,0 +1,269 @@
from __future__ import annotations
import asyncio
import logging
import re
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, cast
import httpx
from k1link.fleet.egress import Egress
from k1link.fleet.egress import lock as egress_lock
from k1link.fleet.egress_transport import EgressTransport
from k1link.fleet.trust import PairingError
from .direct import DirectCesium, json_response, read_json
from .egress import gateway_headers
from .settings import CesiumSettings, CesiumSettingsStore, MapServiceError, RouteMode
class _ProviderLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
# Bing requires a query credential. Never put provider URLs into HTTP
# client diagnostic logs, including when another feature enables INFO.
message = record.getMessage()
if "virtualearth.net" in message or "cesium.com" in message:
record.msg = "Map provider HTTP request (URL omitted)"
record.args = ()
return True
class MapServiceRoutes:
def __init__(
self,
store: CesiumSettingsStore,
gateway_url: str | None,
client: httpx.AsyncClient,
*,
fleet_root: Path | None = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.store, self.gateway_url, self.client, self.clock = store, gateway_url, client, clock
self.fleet_root = fleet_root
self.egress_transport = EgressTransport()
self.gateway_egress = False
self.commit_lock = asyncio.Lock()
self.probe_lock = asyncio.Lock()
self.gateway_available: bool | None = None
self.next_probe = 0.0
self.active_route = "unknown"
self._direct: DirectCesium | None = None
self._revision = -1
self._settings: CesiumSettings | None = None
logger = logging.getLogger("httpx")
if not any(isinstance(item, _ProviderLogFilter) for item in logger.filters):
logger.addFilter(_ProviderLogFilter())
@property
def settings(self) -> CesiumSettings:
if self._settings is None:
self._settings = self.store.read()
return self._settings
@property
def configured(self) -> bool:
try:
return bool(self.settings.token) or bool(self.gateway_url)
except MapServiceError:
return bool(self.gateway_url)
def binding(self, identifier: str) -> dict[str, Any]:
try:
if not self.fleet_root:
raise PairingError("not configured")
return Egress(self.fleet_root).find(identifier)
except PairingError as exc:
raise MapServiceError("cesium_egress_unavailable", 503) from exc
def provider(self, token: str, identifier: str) -> DirectCesium:
if not identifier:
return DirectCesium(token, self.client)
binding = self.binding(identifier)
async def request(method: str, target: str, *, headers: dict[str, str]) -> httpx.Response:
return await self.egress_transport.request(binding, method, target, headers)
return DirectCesium(token, self.client, request)
def direct(self) -> DirectCesium:
settings = self.settings
if self._direct is None or self._revision != settings.revision:
self._direct = self.provider(settings.token, settings.egress_id)
self._revision = settings.revision
return self._direct
def status(self) -> dict[str, Any]:
return {
"schema_version": "missioncore.cesium-service/v1",
**self.settings.public(),
"gateway_configured": bool(self.gateway_url),
"gateway_available": self.gateway_available,
"active_route": self.active_route,
}
async def gateway_ready(self) -> bool:
if not self.gateway_url:
self.gateway_available = False
return False
if self.clock() < self.next_probe:
return self.gateway_available is True
async with self.probe_lock:
if self.clock() < self.next_probe:
return self.gateway_available is True
try:
response = await self.client.send(
self.client.build_request(
"GET",
f"{self.gateway_url}/healthz",
timeout=2.0,
headers={"x-nodedc-user-id": "mission-core-loopback-operator"},
),
stream=True,
)
if response.status_code != 200:
await response.aclose()
raise MapServiceError("map_gateway_unavailable")
value = await read_json(response)
self.gateway_egress = value.get("egressContract") == "nodedc.map-egress/v1"
self.gateway_available = (
value.get("ok") is True and value.get("service") == "nodedc-map-gateway"
)
except (httpx.HTTPError, MapServiceError):
self.gateway_available = False
self.next_probe = self.clock() + 15.0
return self.gateway_available
async def send(
self, method: str, path: str, query: dict[str, str] | None, headers: dict[str, str]
) -> httpx.Response:
mode = self.settings.mode
if mode != "direct" and await self.gateway_ready():
forwarded = dict(headers)
if self.settings.egress_id:
if not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
forwarded.update(
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(self.settings.egress_id),
method,
path,
)
)
try:
response = await self.client.send(
self.client.build_request(
method,
f"{self.gateway_url}{path}",
params=query,
headers=forwarded,
timeout=httpx.Timeout(30.0, connect=2.0),
),
stream=True,
)
# A cache-policy refusal, auth failure or absent resource is not
# evidence that NAS is down. Preserve that server's decision.
if response.status_code not in (502, 503):
self.active_route = "gateway"
response.headers["x-nodedc-map-route"] = "gateway"
return response
await response.aclose()
except httpx.HTTPError:
self.gateway_available = False
self.next_probe = self.clock() + 15.0
# An upstream 502/503 is not an outage of the cache server.
# Other requests must still be able to read its warm tiles.
if mode == "gateway":
self.active_route = "unavailable"
raise MapServiceError("map_gateway_unavailable")
direct = self.direct()
if not self.settings.token:
self.active_route = "unavailable"
raise MapServiceError("cesium_token_required")
if path == "/healthz":
verification = await direct.verify()
self.active_route = "direct" if verification["ok"] else "unavailable"
return json_response(
{
"service": "missioncore-map-direct",
**verification,
"route": "direct",
"cache": None,
},
200 if verification["ok"] else 503,
)
match = re.fullmatch(r"/api/map/ion/assets/(\d+)/endpoint", path)
if match:
endpoint = await direct.endpoint(int(match[1]))
self.active_route = "direct"
response = json_response(endpoint.public)
elif path == "/api/map/cache" and query:
forwarded = {
key: value
for key, value in headers.items()
if key.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
}
response = await direct.resource(method, query["url"], forwarded)
self.active_route = "direct"
else:
raise MapServiceError("map_route_not_allowed", 404)
response.headers["x-nodedc-map-route"] = "direct"
return response
async def verify(
self, token: str | None = None, egress_id: str | None = None
) -> dict[str, Any]:
candidate = self.provider(
token if token is not None else self.settings.token,
self.settings.egress_id if egress_id is None else egress_id,
)
return await candidate.verify()
async def save(
self,
expected: int,
mode: str,
token: str | None,
*,
remove: bool = False,
egress_id: str | None = None,
) -> dict[str, Any]:
# Validate without replacing the working token. Check revision again
# after awaited provider I/O; a stale tab cannot overwrite newer settings.
candidate = None
selected = self.settings.egress_id if egress_id is None else egress_id
if not remove and (token is not None or selected != self.settings.egress_id):
candidate = self.provider(token if token is not None else self.settings.token, selected)
result = await candidate.verify()
if not result["ok"]:
first = next(item["code"] for item in result["assets"].values() if not item["ok"])
raise MapServiceError(first, 422)
async with self.commit_lock:
if selected and mode != "direct" and self.gateway_url:
if await self.gateway_ready() and not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(selected),
"GET",
"/healthz",
)
previous = self.store.read()
next_settings = CesiumSettings(
expected,
cast(RouteMode, mode),
"" if remove else (previous.token if token is None else token),
selected,
)
with egress_lock:
if selected:
self.binding(selected)
self._settings = self.store.save(next_settings, expected)
self._direct = candidate
self._revision = self._settings.revision
self.next_probe = 0
self.active_route = "unknown"
return self.status()
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import json
import os
import re
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
RouteMode = Literal["auto", "direct", "gateway"]
MODES = {"auto", "direct", "gateway"}
class MapServiceError(Exception):
def __init__(self, code: str, status: int = 503) -> None:
self.code = code
self.status = status
super().__init__(code)
@dataclass(frozen=True)
class CesiumSettings:
revision: int = 0
mode: RouteMode = "auto"
token: str = field(default="", repr=False)
egress_id: str = ""
def public(self) -> dict[str, Any]:
return {
"revision": self.revision,
"mode": self.mode,
"token_configured": bool(self.token),
"egress_id": self.egress_id,
}
def validate_egress(value: object) -> str:
if not isinstance(value, str) or (value and not re.fullmatch(r"eg_[a-f0-9]{32}", value)):
raise MapServiceError("cesium_egress_invalid", 422)
return value
def validate_token(value: object) -> str:
if not isinstance(value, str) or not 1 <= len(value.strip()) <= 8192:
raise MapServiceError("cesium_token_invalid", 422)
token = value.strip()
if not token.isascii() or any(character.isspace() for character in token):
raise MapServiceError("cesium_token_invalid", 422)
return token
class CesiumSettingsStore:
"""One installation-owned secret document; never exposed as a profile or cache."""
def __init__(self, path: Path) -> None:
self.path = path
def read(self) -> CesiumSettings:
try:
if self.path.is_symlink() or self.path.stat().st_size > 16384:
raise ValueError
value = json.loads(self.path.read_text())
if (
value.get("schema_version") != "missioncore.cesium-service/v1"
or type(value.get("revision")) is not int
or value["revision"] < 1
or value.get("mode") not in MODES
):
raise ValueError
token = validate_token(value["token"]) if value.get("token") else ""
return CesiumSettings(
value["revision"], value["mode"], token, validate_egress(value.get("egress_id", ""))
)
except FileNotFoundError:
return CesiumSettings()
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise MapServiceError("cesium_settings_unreadable", 503) from exc
def save(self, settings: CesiumSettings, expected_revision: int) -> CesiumSettings:
# The owner serializes commits, including the revision check, in one lock.
if self.read().revision != expected_revision:
raise MapServiceError("cesium_settings_conflict", 409)
directory = self.path.parent
try:
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
if directory.resolve() != directory or self.path.is_symlink():
raise MapServiceError("cesium_settings_unwritable", 503)
os.chmod(directory, 0o700)
descriptor, temporary = tempfile.mkstemp(prefix=".cesium-", dir=directory)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
next_value = CesiumSettings(
expected_revision + 1,
settings.mode,
settings.token,
validate_egress(settings.egress_id),
)
payload = {
"schema_version": "missioncore.cesium-service/v1",
"revision": next_value.revision,
"mode": next_value.mode,
"token": next_value.token,
"egress_id": next_value.egress_id,
}
try:
with os.fdopen(descriptor, "w") as output:
os.fchmod(output.fileno(), 0o600)
json.dump(payload, output)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, self.path)
directory_fd = os.open(directory, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
finally:
Path(temporary).unlink(missing_ok=True)
return next_value
+25
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import fcntl
import hashlib
import json
import math
import os
from contextlib import contextmanager
from datetime import UTC, datetime
@@ -19,6 +20,8 @@ KINDS = {
"battery-ui": "missioncore.battery-ui/v1",
"battery-view": "missioncore.battery-view/v1",
"environments": "missioncore.environment-library/v1",
"observation-map": "missioncore.observation-map/v1",
"rover-view": "missioncore.rover-view/v1",
}
_lock = RLock()
@@ -44,6 +47,28 @@ def validate_document(kind: str, document: Any) -> None:
height = document.get("height")
if type(height) not in (int, float) or not 360 <= height <= 2160:
raise ValueError("Неверная высота окна.")
elif kind == "observation-map":
camera, layers = document.get("camera"), document.get("layers")
limits = {"longitude": (-180, 180), "latitude": (-90, 90),
"height": (-100_000, 1_000_000_000), "heading": (-360, 360),
"pitch": (-90, 90), "roll": (-360, 360)}
if set(document) != {"schema", "camera", "layers"} or (
camera is not None and (
not isinstance(camera, dict) or set(camera) != set(limits)
or any(type(camera[k]) not in (float, int) or not math.isfinite(camera[k])
or not low <= camera[k] <= high for k, (low, high) in limits.items())
)
):
raise ValueError("Неверное положение камеры карты.")
if not isinstance(layers, dict) or set(layers) != {
"imagery", "terrain", "buildings", "grid", "targets"
} or any(type(v) is not bool for v in layers.values()):
raise ValueError("Неверная видимость слоёв карты.")
elif kind == "rover-view":
if set(document) != {"schema", "model"} or document.get("model") not in (
"", "dcd006-v022"
):
raise ValueError("Неверная модель аппарата.")
else:
profiles = document.get("profiles")
if not isinstance(profiles, list) or len(profiles) > 64:
+5 -1
View File
@@ -540,7 +540,11 @@ try:
except (OSError, ValueError):
lab_gateway_configuration = None
laboratory_worker_gateway = LaboratoryWorkerGateway(lab_gateway_configuration)
map_gateway_proxy = MapGatewayProxy(MapGatewayConfiguration.from_environment())
map_gateway_proxy = MapGatewayProxy(
MapGatewayConfiguration.from_environment(),
settings_path=session_store.data_dir / "services" / "cesium-ion" / "settings.json",
fleet_root=session_store.data_dir / "fleet",
)
recording_reconciler_readiness = BackgroundReconcilerReadiness()
+2 -1
View File
@@ -14,8 +14,9 @@ from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"}
DOWNLOAD_NAMES = {
"vps-egress": "mission-core-egress-vps.pyz",
"vps-librespeed": "mission-core-librespeed-vps.pyz",
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
+25 -1
View File
@@ -5,6 +5,7 @@ import re
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
from ipaddress import ip_address
from pathlib import Path as FilePath
from typing import Annotated, Any, Final
from urllib.parse import parse_qsl, urlsplit
@@ -12,6 +13,11 @@ import httpx
from fastapi import APIRouter, HTTPException, Path, Query, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from k1link.maps.direct import json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
from k1link.web.map_services_api import build_map_services_router
MAP_GATEWAY_URL_ENV: Final = "MISSIONCORE_MAP_GATEWAY_INTERNAL_URL"
MAP_SANDBOX_HIDE_CREDITS_ENV: Final = "MISSIONCORE_MAP_SANDBOX_HIDE_CREDITS"
MAP_SCHEMA_VERSION: Final = "missioncore.map-gateway/v1"
@@ -46,6 +52,7 @@ RESPONSE_HEADER_ALLOWLIST: Final = frozenset(
"expires",
"last-modified",
"vary",
"x-nodedc-map-route",
}
)
SENSITIVE_JSON_KEYS: Final = frozenset(
@@ -100,6 +107,8 @@ class MapGatewayProxy:
configuration: MapGatewayConfiguration,
*,
client: httpx.AsyncClient | None = None,
settings_path: FilePath | None = None,
fleet_root: FilePath | None = None,
) -> None:
self._configuration = configuration
self._owns_client = client is None
@@ -117,10 +126,14 @@ class MapGatewayProxy:
keepalive_expiry=30.0,
),
)
self.routes = (MapServiceRoutes(CesiumSettingsStore(settings_path),
configuration.internal_url, self._client, fleet_root=fleet_root)
if settings_path is not None else None)
@property
def configured(self) -> bool:
return self._configuration.internal_url is not None
return (self.routes.configured if self.routes is not None
else self._configuration.internal_url is not None)
def runtime_configuration(self) -> Response:
if not self.configured:
@@ -249,6 +262,15 @@ class MapGatewayProxy:
query: Mapping[str, str] | None = None,
) -> httpx.Response:
_require_loopback_request(request)
if self.routes is not None:
headers = {name: value for name, value in request.headers.items()
if name.lower() in REQUEST_HEADER_ALLOWLIST}
headers["x-nodedc-user-id"] = MAP_GATEWAY_SUBJECT
try:
return await self.routes.send(request.method, upstream_path,
dict(query) if query else None, headers)
except MapServiceError as exc:
return json_response({"code": exc.code, "retryable": exc.status >= 500}, exc.status)
base_url = self._configuration.internal_url
if base_url is None:
raise HTTPException(
@@ -452,6 +474,8 @@ def _filtered_response_headers(headers: httpx.Headers) -> dict[str, str]:
def build_map_router(service: MapGatewayProxy) -> APIRouter:
router = APIRouter(prefix="/api/v1/map", tags=["map"])
if service.routes is not None:
router.include_router(build_map_services_router(service.routes, _require_loopback_request))
@router.get("/runtime-config")
async def runtime_config(request: Request) -> Response:
+102
View File
@@ -0,0 +1,102 @@
from __future__ import annotations
import json
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import MODES, MapServiceError, validate_egress, validate_token
def reply(value: dict[str, Any], status: int = 200) -> JSONResponse:
return JSONResponse(value, status_code=status, headers={"Cache-Control": "no-store"})
async def payload(request: Request) -> dict[str, Any]:
host = urlsplit(str(request.url)).hostname
origin = request.headers.get("origin")
if (
host not in {"127.0.0.1", "localhost", "::1"}
or request.headers.get("sec-fetch-site") == "cross-site"
or (origin is not None and origin != str(request.base_url).rstrip("/"))
):
raise MapServiceError("cesium_settings_local_only", 403)
if request.headers.get("content-type", "").split(";", 1)[0] != "application/json":
raise MapServiceError("cesium_settings_invalid_request", 415)
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 16384:
raise MapServiceError("cesium_settings_invalid_request", 413)
try:
value = json.loads(body)
if not isinstance(value, dict):
raise ValueError
return value
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_settings_invalid_request", 422) from exc
def build_map_services_router(
service: MapServiceRoutes, require_local: Callable[[Request], None]
) -> APIRouter:
router = APIRouter(prefix="/services/cesium-ion")
@router.get("")
async def status(request: Request) -> JSONResponse:
require_local(request)
try:
return reply(service.status())
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.post("/verify")
async def verify(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if set(value) - {"token", "egress_id"}:
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.verify(
token, validate_egress(value["egress_id"]) if "egress_id" in value else None
)
)
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.put("")
async def save(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if (
set(value) - {"revision", "mode", "token", "remove_token", "egress_id"}
or type(value.get("revision")) is not int
or value["revision"] < 0
or not isinstance(value.get("mode"), str)
or value["mode"] not in MODES
or type(value.get("remove_token", False)) is not bool
or (value.get("remove_token") and "token" in value)
):
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.save(
value["revision"],
value["mode"],
token,
remove=value.get("remove_token", False),
egress_id=validate_egress(value["egress_id"]) if "egress_id" in value else None,
)
)
except MapServiceError as exc:
# Never reflect upstream bodies, validation input or secret values.
return reply({"code": exc.code}, exc.status)
return router
+26 -1
View File
@@ -11,6 +11,8 @@ from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.egress import Egress
from k1link.fleet.egress import invitation as egress_invitation
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import invitation as speed_invitation
from k1link.fleet.network_profiles import parse_file
@@ -40,7 +42,7 @@ class Update(Details):
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard", "librespeed"]
kind: Literal["arnavi", "wireguard", "librespeed", "egress"]
document: str = Field(min_length=1, max_length=16384)
network_interface: str | None = Field(default=None, max_length=20)
expected_revision: int = Field(ge=1, strict=True)
@@ -94,6 +96,23 @@ def services(fleet: FleetRegistry) -> list[Document]:
details={**item, "name": "LibreSpeed", "boards": 0, "last_verified": None},
)
)
for item in Egress(fleet.root).listing():
result.append(
dict(
kind="egress",
id=item["id"],
endpoint=item["endpoint"],
name="Маршрутизация трафика",
state=item["state"],
last_seen=None,
details={
**item,
"name": "Маршрутизация трафика",
"boards": 0,
"last_verified": None,
},
)
)
return result
@@ -133,6 +152,8 @@ async def health(key: str, request: Request, response: Response, fleet: Fleet) -
("librespeed", r) for r in LibreSpeed(fleet.root).rows() if ("librespeed", r["id"]) in known
]
rows += [("egress", r) for r in Egress(fleet.root).rows() if ("egress", r["id"]) in known]
async def inspect(kind: str, row: Document) -> Document:
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
@@ -189,6 +210,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else egress_invitation(body.document)
if body.kind == "egress"
else speed_invitation(body.document)
if body.kind == "librespeed"
else invitation(body.document.strip())
@@ -199,6 +222,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
elif body.kind == "egress":
Egress(fleet.root).pair(body.document, body.network_interface)
elif body.kind == "librespeed":
LibreSpeed(fleet.root).pair(body.document, body.network_interface)
else:
+2 -2
View File
@@ -14,9 +14,9 @@ def probe(kind: str, row: Document, verify: Callable[[Document, Document], Docum
value = request(row, "GET", "/v1/status")
if kind == "wireguard":
verify(row, value)
elif kind == "librespeed":
elif kind in {"librespeed", "egress"}:
if (
value.get("schema") != "missioncore.librespeed/v1"
value.get("schema") != f"missioncore.{kind}/v1"
or value.get("server_id") != row["id"]
):
raise ValueError("Service identity mismatch")
+211
View File
@@ -0,0 +1,211 @@
import asyncio
import base64
import hashlib
import hmac
import json
import httpx
import pytest
from k1link.fleet.egress import Egress
from k1link.fleet.egress_transport import RelayStream
from k1link.maps.direct import DirectCesium, json_response
from k1link.maps.egress import gateway_headers
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
IDENTIFIER = "eg_" + "a" * 32
BINDING = {
"id": IDENTIFIER,
"endpoint": "https://1.1.1.1:19446",
"fingerprint": "b" * 64,
"token": "c" * 43,
"state": "connected",
}
def test_signed_gateway_binding_is_method_and_path_scoped(tmp_path):
key = tmp_path / "key"
key.write_text("ab" * 32)
headers = gateway_headers(key, BINDING, "GET", "/api/map/cache")
payload = headers["x-nodedc-map-egress"]
raw = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
assert raw["token"] == BINDING["token"]
expected = hmac.new(
bytes.fromhex("ab" * 32),
("nodedc.map-egress/v1\nGET\n/api/map/cache\n" + payload).encode(),
hashlib.sha256,
).hexdigest()
assert headers["x-nodedc-map-egress-signature"] == expected
with pytest.raises(MapServiceError, match="gateway_not_ready"):
gateway_headers(tmp_path / "absent", BINDING, "GET", "/healthz")
def test_legacy_settings_keep_route_and_new_id_is_durable(tmp_path):
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
document = json.loads(store.path.read_text())
document.pop("egress_id")
store.path.write_text(json.dumps(document))
assert store.read().egress_id == ""
saved = store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 1)
assert store.read().egress_id == IDENTIFIER
assert "private-token" not in repr(saved)
assert "private-token" not in json.dumps(saved.public())
def test_region_refusal_is_not_invalid_token():
async def scenario():
async def relay(*args, **kwargs):
return httpx.Response(403, headers={"x-nodedc-egress-error": "upstream_region_denied"})
async with httpx.AsyncClient() as client:
result = await DirectCesium("private-token", client, relay).verify()
assert not result["ok"]
assert {x["code"] for x in result["assets"].values()} == {"cesium_egress_region_denied"}
asyncio.run(scenario())
def test_unreachable_provider_does_not_disable_warm_cache(tmp_path):
async def scenario():
requests = []
def gateway(request):
requests.append(request.url.path)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
if request.url.params.get("url", "").endswith("cold"):
return json_response({"error": "map_egress_upstream_unavailable"}, 503)
return json_response({"warm": True})
async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
service = MapServiceRoutes(
CesiumSettingsStore(tmp_path / "settings.json"), "http://nas.test", client
)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/api/map/cache", {"url": "cold"}, {})
assert service.gateway_available is True
response = await service.send("GET", "/api/map/cache", {"url": "warm"}, {})
assert json.loads(await response.aread())["warm"]
assert requests.count("/healthz") == 1
asyncio.run(scenario())
def test_failed_route_admission_keeps_working_settings(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
async with httpx.AsyncClient() as client:
routes = MapServiceRoutes(store, None, client, fleet_root=fleet)
async def relay(*args, **kwargs):
return httpx.Response(
403, headers={"x-nodedc-egress-error": "upstream_region_denied"}
)
routes.egress_transport.request = relay
with pytest.raises(MapServiceError, match="cesium_egress_region_denied"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_nas_down_uses_selected_relay_without_direct_leak(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 0)
def network(request):
assert request.url.host == "nas.test", "Provider request bypassed selected VPS"
raise httpx.ConnectError("offline")
async with httpx.AsyncClient(transport=httpx.MockTransport(network)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
calls = []
async def relay(binding, method, target, headers):
calls.append(target)
assert binding["id"] == IDENTIFIER
return json_response(
{
"type": "TERRAIN",
"url": "https://assets.ion.cesium.com/1/",
"accessToken": "scoped-secret",
}
)
routes.egress_transport.request = relay
response = await routes.send("GET", "/api/map/ion/assets/1/endpoint", None, {})
body = await response.aread()
assert calls == ["https://api.cesium.com/v1/assets/1/endpoint"]
assert b"private-token" not in body and b"scoped-secret" not in body
assert not list(tmp_path.rglob("*.terrain"))
asyncio.run(scenario())
def test_offline_nas_cannot_bypass_gateway_setup_on_route_save(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
def offline(request):
raise httpx.ConnectError("offline")
class VerifiedProvider:
async def verify(self):
return {"ok": True}
async with httpx.AsyncClient(transport=httpx.MockTransport(offline)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
routes.provider = lambda *_: VerifiedProvider()
with pytest.raises(MapServiceError, match="gateway_not_ready"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_truncated_relay_stream_is_not_accepted_and_releases_slot():
class Connection:
sock = None
closed = False
def close(self):
self.closed = True
class Truncated:
length = 3
closed = False
def read(self, _):
return b""
def close(self):
self.closed = True
async def scenario():
connection, response = Connection(), Truncated()
slots = asyncio.Semaphore(1)
await slots.acquire()
stream = RelayStream(connection, response, slots)
with pytest.raises(httpx.ReadError):
async for _ in stream:
pass
assert connection.closed and response.closed
await asyncio.wait_for(slots.acquire(), 0.1)
await stream.aclose()
assert slots.locked(), "Repeated close must not release another caller's slot"
asyncio.run(scenario())
+312
View File
@@ -0,0 +1,312 @@
from __future__ import annotations
import asyncio
import json
import httpx
import pytest
from fastapi import FastAPI
from k1link.maps.direct import JsonStream, json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
from k1link.web.map_api import MapGatewayConfiguration, MapGatewayProxy, build_map_router
MASTER = "test-master-secret"
ASSET = "test-scoped-secret"
BING = "test-bing-secret"
class Providers:
def __init__(self):
self.requests = []
self.nas = False
self.nas_status = 200
self.authorized = True
self.asset_status = 200
def __call__(self, request):
self.requests.append(request)
if request.url.host == "nas.test":
if not self.nas:
raise httpx.ConnectError("offline", request=request)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
return json_response({"code": "offline_cache_miss", "nas": True}, self.nas_status)
if request.url.host == "api.cesium.com":
assert request.headers["authorization"] == f"Bearer {MASTER}"
if not self.authorized:
return json_response({"secret": MASTER}, 401)
asset = int(request.url.path.split("/")[-2])
if asset == 2:
return json_response(
{
"type": "IMAGERY",
"externalType": "BING",
"options": {
"url": "https://dev.virtualearth.net",
"key": BING,
"mapStyle": "Aerial",
},
}
)
return json_response(
{
"type": "TERRAIN" if asset == 1 else "3DTILES",
"url": f"https://assets.ion.cesium.com/{asset}/",
"accessToken": ASSET,
}
)
if request.url.host == "dev.virtualearth.net":
assert request.url.params["key"] == BING
return json_response(
{
"imageUrl": f"https://ecn.t0.tiles.virtualearth.net/tiles/a.jpg?key={BING}",
"accessToken": ASSET,
}
)
if request.url.host == "assets.ion.cesium.com":
assert request.headers["authorization"] == f"Bearer {ASSET}"
assert not any(key.startswith("nodedc_cache_") for key in request.url.params)
return httpx.Response(
self.asset_status,
stream=JsonStream(b"tile-data"),
headers={
"content-type": "application/octet-stream",
"content-range": "bytes 0-8/9",
},
)
raise AssertionError("Unexpected request")
def routes(tmp_path, providers, clock=lambda: 0):
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token=MASTER), 0)
return MapServiceRoutes(
store,
"http://nas.test",
httpx.AsyncClient(transport=httpx.MockTransport(providers)),
clock=clock,
)
def test_private_atomic_store_and_revision(tmp_path):
store = CesiumSettingsStore(tmp_path / "private" / "settings.json")
saved = store.save(CesiumSettings(token=MASTER), 0)
assert store.path.stat().st_mode & 0o777 == 0o600
assert store.path.parent.stat().st_mode & 0o777 == 0o700
assert MASTER not in repr(saved)
assert MASTER not in json.dumps(saved.public())
with pytest.raises(MapServiceError, match="conflict"):
store.save(CesiumSettings(token="other"), 0)
assert store.read().token == MASTER
assert len(list(store.path.parent.iterdir())) == 1
def test_nas_down_then_returns_without_new_cache_or_changed_query(tmp_path):
async def scenario():
upstream = Providers()
now = [0]
service = routes(tmp_path, upstream, lambda: now[0])
url = "https://assets.ion.cesium.com/1/tile.terrain?v=4&nodedc_cache_profile=live"
first = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert await first.aread() == b"tile-data"
assert first.headers["x-nodedc-map-route"] == "direct"
await service.send("GET", "/api/map/cache", {"url": url}, {})
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
upstream.nas = True
now[0] = 16
second = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert second.headers["x-nodedc-map-route"] == "gateway"
assert upstream.requests[-1].url.params["url"] == url
assert list(tmp_path.rglob("*.*")) == [service.store.path]
await service.client.aclose()
asyncio.run(scenario())
def test_concurrent_tiles_share_probe_and_endpoint_resolution(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
responses = await asyncio.gather(
*(
service.send(
"GET",
"/api/map/cache",
{"url": f"https://assets.ion.cesium.com/1/{index}.terrain"},
{},
)
for index in range(12)
)
)
for response in responses:
await response.aclose()
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
assert sum(r.url.host == "api.cesium.com" for r in upstream.requests) == 1
await service.client.aclose()
asyncio.run(scenario())
def test_redirect_is_not_followed_and_missing_token_has_explicit_reason(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.asset_status = 302
with pytest.raises(MapServiceError, match="unavailable"):
await service.direct().resource("GET", "https://assets.ion.cesium.com/1/a", {})
assert len(upstream.requests) == 2
await service.save(1, "auto", None, remove=True)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/healthz", None, {})
await service.client.aclose()
asyncio.run(scenario())
def test_bing_query_credential_not_written_to_http_log(tmp_path, caplog):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with caplog.at_level("INFO", logger="httpx"):
response = await service.direct().resource(
"GET", "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial", {}
)
await response.aclose()
assert BING not in caplog.text and MASTER not in caplog.text
assert all(r.headers.get("referer") == "http://127.0.0.1:8000/" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize("status", [401, 403, 404, 504])
def test_nas_cache_policy_is_never_bypassed(tmp_path, status):
async def scenario():
upstream = Providers()
upstream.nas, upstream.nas_status = True, status
service = routes(tmp_path, upstream)
response = await service.send(
"GET", "/api/map/cache", {"url": "https://assets.ion.cesium.com/1/x"}, {}
)
assert response.status_code == status
assert all(r.url.host == "nas.test" for r in upstream.requests)
await response.aclose()
await service.client.aclose()
asyncio.run(scenario())
def test_endpoint_and_bing_metadata_never_expose_credentials(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
for asset in (1, 2, 96188):
response = await service.send("GET", f"/api/map/ion/assets/{asset}/endpoint", None, {})
payload = await response.aread()
assert all(secret.encode() not in payload for secret in (MASTER, ASSET, BING))
response = await service.send(
"GET",
"/api/map/cache",
{
"url": "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?key=nodedc-gateway"
},
{},
)
payload = await response.aread()
assert BING.encode() not in payload and ASSET.encode() not in payload
assert b"nodedc-gateway" in payload
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize(
"target",
[
"https://localhost/x",
"https://evil.test/x",
"https://assets.ion.cesium.com:123/1/x",
"https://assets.ion.cesium.com/1/../9/x",
"https://assets.ion.cesium.com/1/%2e%2e/9/x",
"https://assets.ion.cesium.com/1%2fx",
"https://assets.ion.cesium.com/999/x",
"https://user@assets.ion.cesium.com/1/x",
],
)
def test_no_arbitrary_proxy_or_credential_scope_escape(tmp_path, target):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with pytest.raises(MapServiceError):
await service.direct().resource("GET", target, {})
assert all(r.url.host == "api.cesium.com" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
def test_invalid_candidate_does_not_replace_saved_token(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.authorized = False
with pytest.raises(MapServiceError, match="unauthorized"):
await service.save(1, "direct", MASTER)
assert service.store.read() == CesiumSettings(1, "auto", MASTER)
await service.save(1, "gateway", None, remove=True)
assert service.store.read().token == ""
assert MASTER not in service.store.path.read_text()
await service.client.aclose()
asyncio.run(scenario())
def test_api_secret_redaction_csrf_ranges_and_recovery(tmp_path):
async def scenario():
upstream = Providers()
state = routes(tmp_path, upstream)
app = FastAPI()
proxy = MapGatewayProxy(
MapGatewayConfiguration("http://nas.test"),
client=state.client,
settings_path=state.store.path,
)
app.include_router(build_map_router(proxy))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app, client=("127.0.0.1", 9000)),
base_url="http://127.0.0.1:8000",
) as client:
base = "/api/v1/map/services/cesium-ion"
status = await client.get(base)
assert status.json()["token_configured"] is True
assert MASTER not in status.text
forbidden = await client.put(
base, json={"revision": 1, "mode": "auto"}, headers={"Origin": "https://evil.test"}
)
assert forbidden.status_code == 403
invalid = await client.put(base, json={"revision": 1, "mode": [], "token": MASTER})
assert invalid.status_code == 422 and MASTER not in invalid.text
health = await client.get("/api/v1/map/gateway/health")
assert health.json()["service"] == "missioncore-map-direct"
assert health.json()["cache"] is None
endpoint = await client.get("/api/v1/map/gateway/ion/assets/1/endpoint")
assert endpoint.status_code == 200 and ASSET not in endpoint.text
upstream.asset_status = 206
binary = await client.get(
"/api/v1/map/gateway/cache",
params={"url": "https://assets.ion.cesium.com/1/a.terrain"},
headers={"Range": "bytes=0-8"},
)
assert binary.status_code == 206 and binary.content == b"tile-data"
assert binary.headers["content-range"] == "bytes 0-8/9"
assert binary.headers["cache-control"] == "no-store"
assert upstream.requests[-1].headers["range"] == "bytes=0-8"
saved = await client.put(base, json={"revision": 1, "mode": "auto"})
assert saved.status_code == 200
conflict = await client.put(base, json={"revision": 1, "mode": "direct"})
assert conflict.status_code == 409
await state.client.aclose()
asyncio.run(scenario())
+31
View File
@@ -126,3 +126,34 @@ def test_api_cross_browser_read_and_stale_write(tmp_path):
== 403
)
assert a.get(url, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403
def test_observation_views_survive_new_clients_without_browser_storage(tmp_path):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
a = client(tmp_path)
url = "/api/v1/scene-profiles/observation-map?owner=rover-006"
assert a.put(url, json={"document": document, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == document
assert client(tmp_path).get(url.replace("rover-006", "other")).json()["document"] is None
model = {"schema": "missioncore.rover-view/v1", "model": "dcd006-v022"}
url = "/api/v1/scene-profiles/rover-view?owner=rover-006"
assert a.put(url, json={"document": model, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == model
model["armed"] = True
assert a.put(url, json={"document": model, "expected_revision": 1}).status_code == 422
@pytest.mark.parametrize("field,value", [("pitch", -100), ("height", True),
("longitude", 200), ("heading", "30")])
def test_observation_map_rejects_bad_pose(tmp_path, field, value):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
camera[field] = value
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
with pytest.raises(ValueError):
SceneProfileStore(tmp_path).save("observation-map", "rover", document, 0)
assert not SceneProfileStore(tmp_path).path("observation-map", "rover").exists()
Generated
+4 -4
View File
@@ -479,8 +479,8 @@ wheels = [
[[package]]
name = "nodedc-bim-module"
version = "0.2.25"
source = { path = "vendor/bim/nodedc_bim_module-0.2.25-py3-none-any.whl" }
version = "0.2.30"
source = { path = "vendor/bim/nodedc_bim_module-0.2.30-py3-none-any.whl" }
dependencies = [
{ name = "fastapi" },
{ name = "httpx" },
@@ -488,7 +488,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ filename = "nodedc_bim_module-0.2.25-py3-none-any.whl", hash = "sha256:d1a36e2bc3cd121211f59abc1d389d26da19f492b7c13c0d6c3f16e85c8c47ff" },
{ filename = "nodedc_bim_module-0.2.30-py3-none-any.whl", hash = "sha256:1957cd7839d2796b57456198f7682dccca6897ce2bd6d874894ac40c0e24c6f6" },
]
[package.metadata]
@@ -561,7 +561,7 @@ requires-dist = [
{ name = "httpx", specifier = ">=0.28,<1" },
{ name = "lz4", specifier = ">=4.4,<5" },
{ name = "missioncore-plugin-sdk", editable = "packages/plugin-sdk" },
{ name = "nodedc-bim-module", path = "vendor/bim/nodedc_bim_module-0.2.25-py3-none-any.whl" },
{ name = "nodedc-bim-module", path = "vendor/bim/nodedc_bim_module-0.2.30-py3-none-any.whl" },
{ name = "paho-mqtt", specifier = ">=2.1,<3" },
{ name = "pillow", specifier = ">=12,<13" },
{ name = "pyyaml", specifier = ">=6.0,<7" },
+18 -15
View File
@@ -1,18 +1,18 @@
{
"schema_version": "missioncore.bim-client-release/v1",
"repository": "https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD",
"source_commit": "64d656a27bac5c0cae700535468d34f6f08fdc96",
"package": "nodedc-bim-viewer-0.2.66.tgz",
"sha256": "1834499ed7bd64a64c5726f54839caa02f131692568330f5b7d838543115db9b",
"source_commit": "bd2a95bb400d359f04d688c94614f0d086e5d7fe",
"package": "nodedc-bim-viewer-0.2.74.tgz",
"sha256": "b9a044dfee38b44840b581fcd7d18fdc50ea304cb8787066f8d5d1cb802a8358",
"types": "pass",
"contract_tests": 197,
"visual_acceptance": "Actual Cesium Inspector: text input -> Tab -> pointer grip no longer shows outline despite :focus-visible. Native pointer dragging and keyboard movement verified for EditorDockLayout, WorkspaceWindow and modeless Window. Docked header also verified; dark/light flat themes remain borderless on pointer focus. Keyboard focus fill remains visible.",
"evidence": "outputs/header-focus-20261117/RESULT.md",
"contract_tests": 208,
"visual_acceptance": "PRK hierarchy child mask survives model off/on, project reopen and full-page reload. Eye intent is persisted synchronously before unmount. Observation camera tilt/layers and selected rover model survive reopen/reload; details and test limits recorded in evidence.",
"evidence": "outputs/view-visibility-20261117/RESULT.md",
"qualification_date": "2026-11-17",
"design_guideline_commit": "533723883d32c55656b245aaec9e728c69a706b9",
"core_frontend_tests": 1619,
"design_guideline_commit": "753d4d6edc6f823fcd3c7ebb620b2f31e19dda41",
"core_frontend_tests": 1626,
"core_frontend_failures": 0,
"validation_context": "Design package build/typecheck, registry, dock, geometry, flat-theme and catalog checks passed. BIM 197 tests/types/build passed. Core architecture 4, frontend 1619, types and production build passed. No backend restart.",
"validation_context": "BIM 208 client tests/types/build; BIM host 45 focused tests and Ruff; Core architecture 4/frontend 1626/types/build; 13 scene-profile/BIM-adapter Python tests and Ruff. Final client 0.2.74 adds same-event eye/unmount regression; Core types/build repeated after repack.",
"visual_limits": [
"Native RMB drag not independently automated; actual OrbitControls pan regression passed",
"Native OS layout switch not exercised; physical code fixtures cover Cyrillic/IME labels",
@@ -31,15 +31,18 @@
"0.2.63: preflight local File handles survive dialog close but not browser shutdown; accepted jobs remain server-owned. Legacy rows without admission time use original server insertion order. Native fullscreen was not requalified in IAB.",
"0.2.64: native pointer row sorting and lock roundtrip qualified in normal project settings; native fullscreen and full GPU gizmo axis coverage were not repeated. Multi-tab lock/move races covered by regression tests, not simultaneous live browser gestures.",
"0.2.65: IAB denied native fullscreen even while visible. Normal/reopened/reloaded Inspector and narrow/normal viewport adaptation were verified. No object transforms exercised.",
"0.2.66: common header pointer/keyboard focus qualified on actual Cesium Inspector and all three shared window components. Native fullscreen was not requalified. Existing project transforms, locks, uploads and capture were not modified."
"0.2.66: common header pointer/keyboard focus qualified on actual Cesium Inspector and all three shared window components. Native fullscreen was not requalified. Existing project transforms, locks, uploads and capture were not modified.",
"0.2.70: native fullscreen and nested Escape qualified for Cesium appearance settings. AO is gated by GPU support; not every GPU/postprocessing combination or all other Cesium consumers was visually requalified. No Worker, network route or tile-cache changes.",
"0.2.72: IAB rejected native fullscreen even while visible; normal/floating settings and final Default label verified. Physical-layout mapping covered by KeyZ/KeyY fixtures; actual OS layout switching not performed. Save confirmation branch verified with real rendered components. Appearance history is session-local.",
"0.2.74: browser cache clearing was represented by a fresh profile client regression; live full-page reload/reopen was verified. Observation tilted-camera fixture was seeded through the revisioned API, then restored by the real renderer; pointer pan and layer changes were exercised in UI. No hardware control was enabled."
],
"source_base_commit": "91c28065c29cb08bcf5c9c2064d47db865fc996c",
"source_state": "committed",
"design_guideline_version": "0.7.4",
"design_guideline_source_state": "Shared drag-handle focus fix committed. Artifact delta limited to header focus helper, three window components, CSS and package versions.",
"design_guideline_version": "0.7.5",
"design_guideline_source_state": "Working tree: shared Cesium native-style switches, scene effects, glass dropdown and floating Window scene material; unrelated DG changes preserved.",
"inspector_evidence": "inspector-compact-axes.jpg (operator Codex workspace)",
"map_cesium_adapter_version": "0.1.2",
"map_cesium_adapter_version": "0.1.4",
"cesium_version": "1.147.0",
"map_evidence": "docs/project-map.md in NODEDC_BIM_MOD; cesium-project-map.png and cesium-bim-placement.png in operator task workspace",
"earlier_visual_acceptance": "KU layer notes list/tiles/gallery and exact per-project view roundtrip passed; project deletion confirmation open/cancel only; 219074194-point LAS rendered and reopened after full page reload; IAB held W and mouse drag changed heading and displayed flight speed, then Fit restored cloud overview; 2026-11-16: individual IFC translation/rotation/scale, group translation and Ctrl/Command undo checked; compact inspector has nine editable fields and no caption/section plates; window and toolbar read «Инспектор»; single shared tooltip verified in viewer and main navigation: radius 14px, blur 18px, border/outline 0, 12px text.; 0.2.46: background click cleared whole cloud and BIM group selected through tree in navigate mode; inspector and selected rows removed. Compact axis headings align on one line (verified equal top coordinate), units hidden in headings. Regression covers geometry/modifier clicks and orbit returning to its starting point.; 0.2.47: existing Cesium runtime rendered prepared BUH geometry; terrain click, marker drag and center placement changed draft coordinates, Cancel preserved project. Libre/Cesium switching and saved Cesium camera survived reload."
"earlier_visual_acceptance": "KU layer notes list/tiles/gallery and exact per-project view roundtrip passed; project deletion confirmation open/cancel only; 219074194-point LAS rendered and reopened after full page reload; IAB held W and mouse drag changed heading and displayed flight speed, then Fit restored cloud overview; 2026-11-16: individual IFC translation/rotation/scale, group translation and Ctrl/Command undo checked; compact inspector has nine editable fields and no caption/section plates; window and toolbar read «Инспектор»; single shared tooltip verified in viewer and main navigation: radius 14px, blur 18px, border/outline 0, 12px text.; 0.2.46: background click cleared whole cloud and BIM group selected through tree in navigate mode; inspector and selected rows removed. Compact axis headings align on one line (verified equal top coordinate), units hidden in headings. Regression covers geometry/modifier clicks and orbit returning to its starting point.; 0.2.47: existing Cesium runtime rendered prepared BUH geometry; terrain click, marker drag and center placement changed draft coordinates, Cancel preserved project. Libre/Cesium switching and saved Cesium camera survived reload.",
"previous_visual_acceptance": "Default is present in the final live UI; native visuals applied and inspected. Command Z/Shift Z changed 100→101→100→101; fixed unsaved-close confirmation, cancel/discard and floating scene glass verified. Saved MCMAP - GAUSS TILESET and both profile definitions restored after QA."
}
Binary file not shown.
Binary file not shown.
+7 -8
View File
@@ -1,24 +1,23 @@
{
"schema_version": "missioncore.bim-release/v1",
"repository": "https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD",
"source_commit": "91c28065c29cb08bcf5c9c2064d47db865fc996c",
"package": "nodedc_bim_module-0.2.25-py3-none-any.whl",
"sha256": "d1a36e2bc3cd121211f59abc1d389d26da19f492b7c13c0d6c3f16e85c8c47ff",
"python_tests": 188,
"source_commit": "bd2a95bb400d359f04d688c94614f0d086e5d7fe",
"package": "nodedc_bim_module-0.2.30-py3-none-any.whl",
"sha256": "1957cd7839d2796b57456198f7682dccca6897ce2bd6d874894ac40c0e24c6f6",
"python_tests": 45,
"node_reader_tests": 1,
"scope": "Durable Cesium inspector geometry in workspace meta.json; legacy map writers preserve omitted geometry.",
"scope": "Validated nullable sparse IFC tree visibility in project workspace. None migrates legacy whole-layer masks; explicit empty list clears gates. Worker unchanged.",
"qualification_date": "2026-11-17",
"worker_source_commit": "dd201554220a10d3825b04a146f0f044f47355c5",
"worker_image": "sha256:dd987e8201391ec92cc8a6f9e10f9d4b9e50ada45fb6a68f31d2f5775925af32",
"core_adapter_tests": 2,
"notes_regression_tests": 13,
"validation_context": "188 server tests, changed-file Ruff and 2 Core BIM adapter tests passed. Restart guarded by closed DEV/local capture and ready Gaussian jobs. No Worker changes.",
"validation_context": "45 focused workspace/appearance tests and changed-file Ruff; 13 Core scene-profile/BIM-adapter tests. Full server suite was not repeated. Managed runtime restarted only after capture diagnostics reported inactive.",
"worker_package_version": "0.2.12",
"worker_cloud_regression_tests": 19,
"source_base_commit": "2adb02888f98c0fc97c66c5423f9aa9912378dfd",
"source_state": "committed",
"core_simulation_adapter_tests": 29,
"gaussian_pipeline_runtime_commit": "6afbf43bfe77f92060e8df2b92c475cfb56ad55c",
"gaussian_pipeline_image": "sha256:e2a2ba3095f05f0f37cda115ec1d15948fb9275332e59eb9bc465c29031bb78d",
"evidence": "outputs/cesium-inspector-layout-20261117/RESULT.md"
"evidence": "outputs/view-visibility-20261117/RESULT.md"
}