feat(network): integrate NetBird clients, profiles and private backups
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
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}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
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((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {useRef} from 'react';
|
||||
import {Button,Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {useNetBirdBackups} from '../../core/fleet/useNetBirdBackups';
|
||||
export function NetBirdBackups(){
|
||||
const {items,loading,busy,error,upload}=useNetBirdBackups();const input=useRef<HTMLInputElement>(null);
|
||||
return <SettingsCard title="Резервные копии сети" description="Полная копия базы NetBird, ключей и зарегистрированных устройств хранится в этом Mission Core отдельно от VPS. Она содержит секреты сети." actions={<StatusBadge tone={items.length?'success':'warning'}>{loading?'Проверяем хранилище':items.length?`Сохранено: ${items.length}`:'Копий пока нет'}</StatusBadge>}>
|
||||
<Description>После изменения устройств или настроек сети сохраните свежую копию. Автоматическое получение копий пока не настроено.</Description>
|
||||
<input ref={input} type="file" accept=".zip,application/zip" hidden aria-label="Полная резервная копия NetBird" disabled={busy} onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void upload(file);}}/>
|
||||
<Button icon={<Icon name="upload"/>} loading={busy} disabled={busy||loading} onClick={()=>input.current?.click()}>Сохранить копию в Mission Core</Button>
|
||||
{error&&<StatusBadge tone="danger">{error}</StatusBadge>}
|
||||
{items.map(item=><SettingsCard key={item.id} title={item.domain} description={`Сохранена ${new Date(item.stored_at).toLocaleString('ru-RU')} · ${(item.bytes/1024/1024).toFixed(1)} МиБ · Контрольные суммы проверены`}>
|
||||
<Button icon={<Icon name="download"/>} onClick={()=>{const link=document.createElement('a');link.href=`/api/v1/fleet/netbird/backups/${item.id}/download`;link.download='mission-core-netbird-backup.zip';link.click();}}>Скачать для восстановления</Button>
|
||||
</SettingsCard>)}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,Description,Icon,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
|
||||
import {InstallerCard} from './InstallerCard';
|
||||
import {NetBirdBackups} from './NetBirdBackups';
|
||||
import {useNetBird,type NetBirdState} from '../../core/fleet/useNetBird';
|
||||
|
||||
const labels:Record<NetBirdState,string>={missing_client:'Клиент не установлен',unsupported_client:'Требуется другая версия клиента',unavailable:'Клиент недоступен',disconnected:'Не подключён',connecting:'Подключение',connected:'Подключён',other_network:'Клиент подключён к другой сети',address_conflict:'Проверьте адресацию сервера'};
|
||||
export function NetBirdConnection(){
|
||||
const network=useNetBird();const {status,clients,error,busy,clientError}=network;
|
||||
const [server,setServer]=useState(''),[edited,setEdited]=useState(false),[installer,setInstaller]=useState('macos');
|
||||
useEffect(()=>{if(!edited&&status?.server_url)setServer(status.server_url);},[status?.server_url,edited]);
|
||||
const selected=clients.find(item=>item.id===installer);
|
||||
const state=status?.pending==='installing'?'Устанавливаем клиент':status?.pending==='cancelling'?'Отменяем подключение':status?.pending==='authentication'?'Требуется вход':status?.pending==='verifying'?'Проверяем соединение':status?.pending?'Подключаемся':status?labels[status.state]:'Получаем состояние';
|
||||
return <>
|
||||
<InstallerCard kind="vps-netbird"/>
|
||||
<NetBirdBackups/>
|
||||
<SettingsCard title="Этот компьютер" description="NetBird соединяет компьютеры через ваш сервер. Вход выполняется в браузере; подключение поддерживает системный клиент." actions={<StatusBadge tone={busy?'warning':status?.state==='connected'?'success':'neutral'}>{state}</StatusBadge>}>
|
||||
<TextField label="Адрес сервера NetBird" placeholder="https://netbird.example.com" value={server} maxLength={300} disabled={busy} onChange={event=>{setEdited(true);setServer(event.target.value);}} hint="Адрес выдаёт установщик VPS или администратор вашей сети."/>
|
||||
{status?.state==='connected'&&<Description>Адрес этого компьютера: {status.address}</Description>}
|
||||
{status?.can_install&&['missing_client','unsupported_client'].includes(status.state)&&<Button disabled={busy||!clients.find(item=>item.id==='macos')?.available} onClick={()=>void network.action('install')}>Установить клиент на этот Mac</Button>}
|
||||
<Button variant="primary" disabled={busy||!server.trim()||!status||['missing_client','unsupported_client','unavailable','other_network'].includes(status.state)} onClick={()=>void network.action('connect',server)}>{status?.state==='connected'?'Проверить подключение':'Подключить этот компьютер'}</Button>
|
||||
{status?.pending&&status.pending!=='installing'&&<Button disabled={network.requestBusy||status.pending==='cancelling'} onClick={()=>void network.action('cancel')}>Прекратить ожидание</Button>}
|
||||
{status?.auth_url&&<Button onClick={()=>window.open(status.auth_url,'_blank','noopener,noreferrer')}>Войти на сервере</Button>}
|
||||
{status?.pending==='installing'&&<Description>Подтвердите системный запрос macOS. Пароль администратора вводится только в системном окне.</Description>}
|
||||
{(error||status?.error)&&<StatusBadge tone="danger">{error||status?.error}</StatusBadge>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Клиенты для других компьютеров" description={`Официальные установщики NetBird${status?.client_version?' '+status.client_version:''}. Файлы хранятся в этом Mission Core и проверяются перед скачиванием.`}>
|
||||
{clientError&&<StatusBadge tone="danger">{clientError}</StatusBadge>}
|
||||
<Select label="Операционная система" value={installer} options={clients.map(item=>({value:item.id,label:item.label}))} onChange={setInstaller}/>
|
||||
<Button icon={<Icon name="download"/>} disabled={!selected?.available} onClick={()=>{if(selected){const link=document.createElement('a');link.href=selected.download_url;link.download=selected.filename;link.click();}}}>Скачать клиент</Button>
|
||||
<Description>Установите клиент, укажите этот же адрес сервера в его настройках и выполните вход. Mission Core на другом компьютере для подключения к сети не требуется.</Description>
|
||||
{installer.startsWith('linux')&&<Description>Пакет «интерфейс» устанавливается вместе с основным клиентом той же версии. Для устройства без экрана используйте ключ подключения из панели NetBird.</Description>}
|
||||
{selected&&!selected.available&&<Description>Этот установщик пока отсутствует в локальном каталоге.</Description>}
|
||||
</SettingsCard>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import {Button,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {NetBirdConnection} from './NetBirdConnection';
|
||||
|
||||
export function OperatorNetworkWindow({onClose}:{onClose:()=>void}){
|
||||
return <Window open title="Сеть операторского компьютера" subtitle="NetBird · WireGuard" size="lg" onClose={onClose}
|
||||
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button></WindowFooterActions>}>
|
||||
<NetBirdConnection/>
|
||||
</Window>;
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export type NetworkProvider='tailscale'|'wireguard';
|
||||
export type NetworkProvider='tailscale'|'wireguard'|'netbird';
|
||||
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
|
||||
export interface BoardNetworkView {
|
||||
profiles:SharedNetworkProfile[];available:boolean;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string;netbird_endpoint?:string;netbird?:{state:string;address:string;server_url:string}}|null;
|
||||
operation:{id:string;state:string;error?:string}|null;
|
||||
}
|
||||
export function useBoardNetwork(vehicleId:string){
|
||||
@@ -31,5 +31,5 @@ export function useBoardNetwork(vehicleId:string){
|
||||
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
|
||||
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:provider==='netbird'?value.node?.netbird_endpoint:profileId))};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
|
||||
export type NetBirdState='missing_client'|'unsupported_client'|'unavailable'|'disconnected'|'connecting'|'connected'|'other_network'|'address_conflict';
|
||||
export interface NetBirdStatus {state:NetBirdState;server_url:string;address:string;client_version:string;pending:string;auth_url:string;error:string;can_install:boolean}
|
||||
export interface NetBirdInstaller {id:string;label:string;filename:string;available:boolean;download_url:string;bytes:number}
|
||||
export function useNetBird(){
|
||||
const [status,setStatus]=useState<NetBirdStatus|null>(null),[clients,setClients]=useState<NetBirdInstaller[]>([]);
|
||||
const [statusError,setStatusError]=useState(''),[actionError,setActionError]=useState(''),[clientError,setClientError]=useState('');
|
||||
const [requestBusy,setRequestBusy]=useState(false);
|
||||
const operation=useRef(false),generation=useRef(0),mounted=useRef(false);
|
||||
useEffect(()=>{
|
||||
mounted.current=true;let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{
|
||||
const epoch=generation.current;
|
||||
try{
|
||||
const value=await fleetRequest<NetBirdStatus>('/netbird','GET',undefined,20000,controller.signal);
|
||||
if(active&&epoch===generation.current&&!operation.current){setStatus(value);setStatusError('');}
|
||||
}catch{
|
||||
if(active&&epoch===generation.current&&!operation.current){setStatusError('Состояние клиента недоступно.');setStatus(null);}
|
||||
}finally{if(active)timer=setTimeout(poll,3000);}
|
||||
};
|
||||
void poll();
|
||||
void fleetRequest<{items:NetBirdInstaller[]}>('/netbird/clients','GET',undefined,30000,controller.signal)
|
||||
.then(value=>{if(active){setClients(value.items);setClientError('');}})
|
||||
.catch(()=>{if(active)setClientError('Установщики недоступны. Повторите открытие настроек.');});
|
||||
return()=>{active=false;mounted.current=false;controller.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
const action=useCallback(async(kind:'connect'|'install'|'cancel',server_url?:string)=>{
|
||||
if(operation.current)return;
|
||||
operation.current=true;generation.current+=1;setRequestBusy(true);setActionError('');
|
||||
try{
|
||||
const next=await fleetRequest<NetBirdStatus>(`/netbird/${kind}`,'POST',kind==='connect'?{server_url}:undefined,30000);
|
||||
if(mounted.current){setStatus(next);setStatusError('');}
|
||||
}catch(e){if(mounted.current)setActionError(e instanceof Error?e.message:'Операция не завершена.');}
|
||||
finally{operation.current=false;generation.current+=1;if(mounted.current)setRequestBusy(false);}
|
||||
},[]);
|
||||
return {status,clients,clientError,error:actionError||statusError,
|
||||
requestBusy,busy:requestBusy||Boolean(status?.pending),action};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export interface NetworkBackup {id:string;domain:string;server_url:string;bytes:number;stored_at:string;verification:'checksums_verified'}
|
||||
export function useNetBirdBackups(){
|
||||
const [items,setItems]=useState<NetworkBackup[]>([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const mounted=useRef(false),operation=useRef(false);
|
||||
const refresh=useCallback(async()=>{const result=await fleetRequest<{items:NetworkBackup[]}>('/netbird/backups');if(mounted.current)setItems(result.items);},[]);
|
||||
useEffect(()=>{mounted.current=true;void refresh().catch(()=>{if(mounted.current)setError('Не удалось прочитать резервные копии.');}).finally(()=>{if(mounted.current)setLoading(false);});return()=>{mounted.current=false;};},[refresh]);
|
||||
const upload=useCallback(async(file:File)=>{
|
||||
if(operation.current)return;
|
||||
operation.current=true;setBusy(true);setError('');
|
||||
try{
|
||||
if(file.size>256*1024*1024)throw Error('Резервная копия превышает 256 МиБ.');
|
||||
const response=await fetch('/api/v1/fleet/netbird/backups',{method:'POST',body:file,headers:{'Content-Type':'application/zip'},signal:AbortSignal.timeout(120000)});
|
||||
if(!response.ok){let detail='Не удалось сохранить копию.';try{const data=await response.json() as {detail?:string};detail=data.detail||detail;}catch{/* retain public error */}throw Error(detail);}
|
||||
await refresh();
|
||||
}catch(e){if(mounted.current)setError(e instanceof Error?e.message:'Не удалось сохранить копию.');}
|
||||
finally{operation.current=false;if(mounted.current)setBusy(false);}
|
||||
},[refresh]);
|
||||
return {items,loading,busy,error,upload};
|
||||
}
|
||||
@@ -8,11 +8,11 @@ export function BoardNetworkSettings({network}:{network:ReturnType<typeof useBoa
|
||||
const current=value?.node;
|
||||
const selected=value?.profiles.find(p=>p.id===profileId);
|
||||
const progress=value?.operation?.state;
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='netbird'?'NetBird подключён':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
return <div className="fleet-form">
|
||||
<SettingsCard title="Связь с Core" description="Профиль связи этого бортового компьютера с Mission Core. Вычислительный Worker сохраняет своё подключение." actions={<StatusBadge tone={applying?'warning':value?.available?'success':'neutral'}>{label}</StatusBadge>}>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:<>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'netbird',label:'NetBird · WireGuard'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:provider==='netbird'?<p>{current?.netbird_endpoint?`Борт подключён к ${current.netbird?.server_url}. Новый канал будет проверен перед сохранением.`:'Подключите Core и борт к одному серверу NetBird. На борту: Система → Частная сеть.'}</p>:<>
|
||||
<Select label="Общий профиль VPS" value={profileId} options={[{value:'',label:'Выберите профиль'},...(value?.profiles??[]).filter(p=>p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/>
|
||||
{selected&&<StatusBadge tone={selected.state==='ready'?'success':'warning'}>{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}</StatusBadge>}
|
||||
<p>Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.</p>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {BoardMonitorView} from './BoardMonitorView';
|
||||
import {BoardComputerSettings} from './BoardComputer';
|
||||
import {NodeInvitationForm,platformLabel} from './NodeInvitationForm';
|
||||
import {VehicleFleetRow} from './VehicleFleetRow';
|
||||
import {OperatorNetworkWindow} from '../../components/network/OperatorNetworkWindow';
|
||||
import './fleet.css';
|
||||
|
||||
export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){
|
||||
@@ -15,6 +16,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
const [expanded,setExpanded]=useState<string[]>([]);
|
||||
const [adding,setAdding]=useState<Vehicle|null|undefined>();
|
||||
const [boardSettings,setBoardSettings]=useState<string|null>(null);
|
||||
const [operatorNetwork,setOperatorNetwork]=useState(false);
|
||||
const [revoking,setRevoking]=useState<Vehicle|null>(null),[error,setError]=useState('');
|
||||
const detail=fleet.items?.find(item=>item.id===view?.vehicleID);
|
||||
const settingsVehicle=fleet.items?.find(item=>item.id===boardSettings);
|
||||
@@ -22,7 +24,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
const refresh=()=>{void fleet.refresh().catch(()=>setError('Не удалось обновить аппарат. Повторите получение сведений.'));};
|
||||
const showEquipment=(id:string)=>{setExpanded(current=>current.includes(id)?current:[...current,id]);setView(null);};
|
||||
const complete=(item:Vehicle)=>{setAdding(undefined);showEquipment(item.id);refresh();};
|
||||
const addButton=<IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton>;
|
||||
const addButton=<><IconButton label="Сеть операторского компьютера" onClick={()=>setOperatorNetwork(true)}><Icon name="network"/></IconButton><IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton></>;
|
||||
const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton);
|
||||
const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:'';
|
||||
const content=detail&&view?.mode==='observation'?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled(detail)} paired={detail.enrollment==='paired'} back={()=>setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/>
|
||||
@@ -31,6 +33,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
{!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><VehicleFleetRow key={item.id} vehicle={item} available={!fleet.error} expanded={expanded.includes(item.id)} onToggle={()=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}</ResourceList>}
|
||||
</div>;
|
||||
return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content}
|
||||
{operatorNetwork&&<OperatorNetworkWindow onClose={()=>setOperatorNetwork(false)}/>}
|
||||
{adding!==undefined&&<NodeInvitationForm key={adding?.id??'new'} vehicle={adding??undefined} onClose={()=>setAdding(undefined)} onComplete={complete} renderWindow={({content,actions,busy})=><Window open title={adding?'Подключить бортовой компьютер':'Добавить аппарат'} subtitle={adding?adding.name:'Создать аппарат и подключить БК по приглашению Node'} size="md" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)setAdding(undefined);}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}>{content}</Window>}/>}
|
||||
{settingsVehicle&&<BoardComputerSettings vehicle={settingsVehicle} enabled={enabled(settingsVehicle)} onClose={()=>setBoardSettings(null)} onRevoke={()=>{setBoardSettings(null);setRevoking(settingsVehicle);}}/>}
|
||||
<ConfirmationModal open={revoking!==null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name??''}» останется в реестре. БК потеряет доступ к Core и получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={()=>setRevoking(null)} onConfirm={async()=>{if(!revoking)return;try{await fleetRequest(`/${encodeURIComponent(revoking.id)}`,'DELETE');await fleet.refresh();setRevoking(null);}catch(e){setError(e instanceof Error?e.message:'Не удалось отозвать привязку.');throw e;}}}/>
|
||||
|
||||
@@ -1,11 +1 @@
|
||||
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}:{kind:'node'|'vps-arnavi'|'vps-wireguard'}){
|
||||
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((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
export {InstallerCard} from '../../../components/network/InstallerCard';
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const bundle=await build({entryPoints:[new URL('../src/core/fleet/useNetBird.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
|
||||
b.onResolve({filter:/^(react|\.\/useFleet)$/},a=>({path:a.path,namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useState=v=>globalThis.netBirdUI.state(v),useRef=v=>globalThis.netBirdUI.ref(v),useEffect=(f,d)=>globalThis.netBirdUI.effect(f,d),useCallback=f=>f;':
|
||||
'export const fleetRequest=(...args)=>globalThis.netBirdUI.request(...args);'}));
|
||||
}}]});
|
||||
const {useNetBird}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
|
||||
const status=(pending='',state='disconnected')=>({pending,state,server_url:'https://network.example',error:'',auth_url:'',client_version:'0.82.0'});
|
||||
function deferred(){let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return{promise,resolve,reject};}
|
||||
async function fixture(run){
|
||||
const old={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,netBirdUI:globalThis.netBirdUI};
|
||||
const values=[],effects=[],tasks=[],timers=new Map(),requests=[];let cursor=0,dirty=true,id=0,closed=false;
|
||||
const h={requests,timers,view:null,
|
||||
state(v){const i=cursor++;if(!(i in values))values[i]=v;return[values[i],next=>{values[i]=typeof next==='function'?next(values[i]):next;dirty=true;}];},
|
||||
ref(v){return values[cursor++]??={current:v};},
|
||||
effect(f,d){const i=cursor++;if(!effects[i]){effects[i]={};tasks.push(()=>{effects[i].cleanup=f();});}},
|
||||
request(...args){const response=deferred();requests.push({args,...response});return response.promise;},
|
||||
async settle(){for(let n=0;n<20;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useNetBird();tasks.splice(0).forEach(f=>f());}}},
|
||||
async tick(){for(const [id,fn] of [...timers]){timers.delete(id);fn();}await h.settle();},
|
||||
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},
|
||||
};
|
||||
globalThis.netBirdUI=h;globalThis.setTimeout=f=>{timers.set(++id,f);return id;};globalThis.clearTimeout=id=>timers.delete(id);
|
||||
try{await h.settle();await run(h);}finally{h.close();Object.assign(globalThis,old);}
|
||||
}
|
||||
|
||||
test('a late poll cannot overwrite accepted connection and double click submits once',()=>fixture(async h=>{
|
||||
const poll=h.requests[0];h.requests[1].resolve({items:[]});
|
||||
const first=h.view.action('connect','https://network.example');
|
||||
const second=h.view.action('connect','https://network.example');
|
||||
assert.equal(h.requests.filter(x=>x.args[1]==='POST').length,1);
|
||||
h.requests[2].resolve(status('authentication'));await first;await second;
|
||||
poll.resolve(status());await h.settle();
|
||||
assert.equal(h.view.status.pending,'authentication');assert.equal(h.view.busy,true);
|
||||
}));
|
||||
|
||||
test('successful status polling does not erase action or installer failures',()=>fixture(async h=>{
|
||||
h.requests[0].resolve(status());h.requests[1].reject(Error('download unavailable'));await h.settle();
|
||||
const action=h.view.action('connect','https://network.example');
|
||||
h.requests[2].reject(Error('Server unavailable'));await action;await h.settle();
|
||||
await h.tick();h.requests[3].resolve(status());await h.settle();
|
||||
assert.equal(h.view.error,'Server unavailable');assert.match(h.view.clientError,/Установщики недоступны/);
|
||||
}));
|
||||
|
||||
test('cancel stays available while waiting for browser authentication',()=>fixture(async h=>{
|
||||
h.requests[0].resolve(status('authentication'));h.requests[1].resolve({items:[]});await h.settle();
|
||||
assert.equal(h.view.busy,true);assert.equal(h.view.requestBusy,false);
|
||||
const cancel=h.view.action('cancel');assert.equal(h.requests[2].args[0],'/netbird/cancel');
|
||||
h.requests[2].resolve(status());await cancel;await h.settle();assert.equal(h.view.busy,false);
|
||||
}));
|
||||
|
||||
test('closing the window cancels polling without cancelling the system connection',()=>fixture(async h=>{
|
||||
h.close();h.requests[0].resolve(status('connecting'));h.requests[1].resolve({items:[]});await h.settle();
|
||||
assert.equal(h.timers.size,0);assert.equal(h.requests.length,2);
|
||||
assert.equal(h.requests[0].args[4].aborted,true);
|
||||
}));
|
||||
@@ -0,0 +1,161 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type NetBirdStatus struct {
|
||||
State string `json:"state"`
|
||||
Address string `json:"address"`
|
||||
ServerURL string `json:"server_url"`
|
||||
Network string `json:"network"`
|
||||
}
|
||||
|
||||
var netbirdObservation struct {
|
||||
sync.RWMutex
|
||||
value NetBirdStatus
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func netbirdSnapshot() NetBirdStatus {
|
||||
netbirdObservation.RLock()
|
||||
defer netbirdObservation.RUnlock()
|
||||
if time.Since(netbirdObservation.at) > 20*time.Second {
|
||||
return NetBirdStatus{State: "unavailable"}
|
||||
}
|
||||
return netbirdObservation.value
|
||||
}
|
||||
func netbirdCall(action string, fields map[string]string) (json.RawMessage, error) {
|
||||
connection, err := net.DialTimeout("unix", "/run/mission-core-netbird/control.sock", time.Second)
|
||||
if err != nil {
|
||||
return nil, errors.New("Служба NetBird недоступна. Обновите и подготовьте окружение БК.")
|
||||
}
|
||||
defer connection.Close()
|
||||
_ = connection.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
body := map[string]string{"action": action}
|
||||
for k, v := range fields {
|
||||
body[k] = v
|
||||
}
|
||||
if err = json.NewEncoder(connection).Encode(body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := bufio.NewReaderSize(connection, 16385).ReadSlice('\n')
|
||||
var result struct {
|
||||
OK bool `json:"ok"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err != nil || len(raw) > 16384 || json.Unmarshal(raw, &result) != nil {
|
||||
return nil, errors.New("Нет подтверждения NetBird.")
|
||||
}
|
||||
if !result.OK {
|
||||
return nil, errors.New(result.Error)
|
||||
}
|
||||
if action == "status" {
|
||||
var status NetBirdStatus
|
||||
if json.Unmarshal(result.Result, &status) == nil {
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value = status
|
||||
netbirdObservation.at = time.Now()
|
||||
netbirdObservation.Unlock()
|
||||
}
|
||||
}
|
||||
return result.Result, nil
|
||||
}
|
||||
func monitorNetBird(ctx context.Context) {
|
||||
timer := time.NewTicker(5 * time.Second)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
_, _ = netbirdCall("status", nil)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Server) netbirdRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/network/netbird", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
out, err := netbirdCall("status", nil)
|
||||
if err != nil {
|
||||
reply(w, 200, map[string]string{"state": "unavailable", "error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, out)
|
||||
})
|
||||
for _, action := range []string{"connect", "cancel"} {
|
||||
mux.HandleFunc("POST /api/network/netbird/"+action, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ServerURL string `json:"server_url"`
|
||||
SetupKey string `json:"setup_key"`
|
||||
}
|
||||
if !decode(w, r, &body) {
|
||||
return
|
||||
}
|
||||
fields := map[string]string{}
|
||||
if action == "connect" {
|
||||
fields["server_url"] = body.ServerURL
|
||||
fields["setup_key"] = body.SetupKey
|
||||
}
|
||||
out, err := netbirdCall(action, fields)
|
||||
if err != nil {
|
||||
reply(w, 409, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, out)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Offers arrive only in an authenticated response from this board's bound Core.
|
||||
func (p *Pairing) acceptNetBirdOffer(raw json.RawMessage) {
|
||||
var offer struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
}
|
||||
if len(raw) > 4096 || json.Unmarshal(raw, &offer) != nil || !privateEndpoint(offer.Endpoint, CorePort) {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.loadNetworkLocked() != nil || p.state.Binding == nil {
|
||||
return
|
||||
}
|
||||
if p.network.NetBirdEndpoint == offer.Endpoint && string(p.network.NetBirdConfig) == string(offer.Config) {
|
||||
return
|
||||
}
|
||||
p.network.NetBirdEndpoint = offer.Endpoint
|
||||
p.network.NetBirdConfig = offer.Config
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
|
||||
func (p *Pairing) acceptNetworkRequestResult(raw json.RawMessage) {
|
||||
var result struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if len(raw) > 4096 || json.Unmarshal(raw, &result) != nil {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network == nil || p.network.LocalRequest == nil || p.network.LocalRequest.ID != result.ID {
|
||||
return
|
||||
}
|
||||
p.network.LocalRequest = nil
|
||||
p.network.LocalError = result.Error
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
@@ -23,18 +23,28 @@ type NetworkPending struct {
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
Local bool `json:"local,omitempty"`
|
||||
}
|
||||
type LocalNetworkRequest struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Revision int64 `json:"revision"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
type NetworkProfile struct {
|
||||
BindingID string `json:"binding_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Pending *NetworkPending `json:"pending,omitempty"`
|
||||
LocalRequest *LocalNetworkRequest `json:"local_request,omitempty"`
|
||||
LocalError string `json:"local_error,omitempty"`
|
||||
NetBirdEndpoint string `json:"netbird_endpoint,omitempty"`
|
||||
NetBirdConfig json.RawMessage `json:"netbird_config,omitempty"`
|
||||
BindingID string `json:"binding_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Pending *NetworkPending `json:"pending,omitempty"`
|
||||
}
|
||||
type NetworkCommand struct {
|
||||
ID string `json:"id"`
|
||||
@@ -133,12 +143,18 @@ func (p *Pairing) networkViewLocked() map[string]any {
|
||||
result["pending_provider"] = n.Pending.Provider
|
||||
result["rollback_at"] = n.Pending.Deadline
|
||||
}
|
||||
result["local_request"] = n.LocalRequest
|
||||
result["local_error"] = n.LocalError
|
||||
result["netbird_endpoint"] = n.NetBirdEndpoint
|
||||
result["netbird"] = netbirdSnapshot()
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) networkSnapshot() map[string]any {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.networkViewLocked()
|
||||
result := p.networkViewLocked()
|
||||
result["netbird"] = netbirdSnapshot()
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) networkEndpointLocked(endpoint string) error {
|
||||
b := p.state.Binding
|
||||
@@ -250,7 +266,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
|
||||
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard" && c.Provider != "netbird") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -258,7 +274,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Action == "prepare" {
|
||||
if c.Action == "prepare" && c.Provider == "wireguard" {
|
||||
if n.OperationID == c.ID && n.Phase == "prepared" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
@@ -297,16 +313,24 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
}
|
||||
} else {
|
||||
var config struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Address string `json:"address"`
|
||||
Subnet string `json:"subnet"`
|
||||
Role string `json:"role"`
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
ServerURL string `json:"server_url"`
|
||||
ServerID string `json:"server_id"`
|
||||
Address string `json:"address"`
|
||||
Subnet string `json:"subnet"`
|
||||
Role string `json:"role"`
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
}
|
||||
if json.Unmarshal(c.Config, &config) != nil || config.ServerID != c.ServerID || config.Role != "node" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Provider == "netbird" {
|
||||
status := netbirdSnapshot()
|
||||
if status.State != "connected" || status.ServerURL != config.ServerURL || status.Address != config.Address || status.Network != config.Subnet || c.ServerID != "netbird" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
_, network, err := net.ParseCIDR(config.Subnet)
|
||||
u, e := url.Parse(c.CoreEndpoint)
|
||||
if err != nil || e != nil || !privateEndpoint(c.CoreEndpoint, CorePort) || !network.Contains(net.ParseIP(u.Hostname())) {
|
||||
@@ -384,7 +408,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
*n = previous
|
||||
return
|
||||
}
|
||||
if oldServer != "" && oldServer != pending.ServerID {
|
||||
if networkID.MatchString(oldServer) && oldServer != pending.ServerID {
|
||||
// The confirmed endpoint is durable before retiring the previous tunnel.
|
||||
_, _ = p.callNetwork("disable", oldServer, nil)
|
||||
}
|
||||
@@ -393,7 +417,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
}
|
||||
func (p *Pairing) networkAddressLocked(address string) bool {
|
||||
if p.network == nil || p.network.Provider != "wireguard" {
|
||||
if p.network == nil || (p.network.Provider != "wireguard" && p.network.Provider != "netbird") {
|
||||
return tailnetAddress(address)
|
||||
}
|
||||
var config struct {
|
||||
@@ -436,15 +460,37 @@ func (p *Pairing) networkLocalRoutes(mux *http.ServeMux, s *Server) {
|
||||
}
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
})
|
||||
mux.HandleFunc("POST /api/network/profile/tailscale", func(w http.ResponseWriter, r *http.Request) {
|
||||
mux.HandleFunc("POST /api/network/profile/{provider}", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
provider := r.PathValue("provider")
|
||||
if provider != "tailscale" && provider != "netbird" {
|
||||
reply(w, 400, map[string]string{"error": "Неизвестная сеть."})
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
_ = p.loadNetworkLocked()
|
||||
if p.network == nil || p.network.TailscaleEndpoint == "" {
|
||||
if p.network == nil || (provider == "tailscale" && p.network.TailscaleEndpoint == "") || (provider == "netbird" && p.network.NetBirdEndpoint == "") {
|
||||
p.mu.Unlock()
|
||||
reply(w, 409, map[string]string{"error": "Нет сохранённого подключения Tailscale."})
|
||||
reply(w, 409, map[string]string{"error": "Core ещё не подтвердил доступность выбранной сети."})
|
||||
return
|
||||
}
|
||||
if provider == "netbird" {
|
||||
if p.network.Pending != nil || (p.network.LocalRequest != nil && p.network.LocalRequest.ExpiresAt > time.Now().Unix()) {
|
||||
p.mu.Unlock()
|
||||
reply(w, 409, map[string]string{"error": "Дождитесь завершения переключения."})
|
||||
return
|
||||
}
|
||||
p.network.LocalRequest = &LocalNetworkRequest{ID: digest(token())[:32], Provider: provider, Revision: p.network.Revision, ExpiresAt: time.Now().Unix() + 110}
|
||||
p.network.LocalError = ""
|
||||
err := p.saveNetworkLocked()
|
||||
p.mu.Unlock()
|
||||
if err != nil {
|
||||
reply(w, 500, map[string]string{"error": "Не удалось сохранить запрос."})
|
||||
return
|
||||
}
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
return
|
||||
}
|
||||
op := digest(token())[:32]
|
||||
|
||||
@@ -103,3 +103,82 @@ func TestNetworkCommitStorageFailureKeepsRollbackState(t *testing.T) {
|
||||
t.Fatal("rollback after storage failure failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetBirdSwitchRequiresFreshMatchingDaemonAndCommitsWithoutWGHelper(t *testing.T) {
|
||||
p, c, actions := networkFixture(t)
|
||||
c.Provider = "netbird"
|
||||
c.ServerID = "netbird"
|
||||
c.CoreEndpoint = "https://10.204.1.2:8782"
|
||||
c.Config = json.RawMessage(`{"server_id":"netbird","server_url":"https://network.example.org","address":"10.204.1.3","subnet":"10.204.0.0/16","role":"node","allowed_ips":["10.204.1.2/32"]}`)
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.at = time.Time{}
|
||||
netbirdObservation.Unlock()
|
||||
networkSend(p, c)
|
||||
if p.network.Pending != nil {
|
||||
t.Fatal("stale status authorized transition")
|
||||
}
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value = NetBirdStatus{State: "connected", Address: "10.204.1.3", ServerURL: "https://other.example.org", Network: "10.204.0.0/16"}
|
||||
netbirdObservation.at = time.Now()
|
||||
netbirdObservation.Unlock()
|
||||
networkSend(p, c)
|
||||
if p.network.Pending != nil {
|
||||
t.Fatal("other server authorized transition")
|
||||
}
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value.ServerURL = "https://network.example.org"
|
||||
netbirdObservation.Unlock()
|
||||
defer func() { netbirdObservation.Lock(); netbirdObservation.at = time.Time{}; netbirdObservation.Unlock() }()
|
||||
networkSend(p, c)
|
||||
if p.network.Phase != "verifying" || p.network.Provider != "tailscale" {
|
||||
t.Fatal("unverified switch")
|
||||
}
|
||||
c.Action = "commit"
|
||||
networkSend(p, c)
|
||||
if p.network.Provider != "netbird" || p.network.Revision != 1 || len(*actions) != 0 {
|
||||
t.Fatal("NetBird owns unexpected WG changes")
|
||||
}
|
||||
if !p.networkAddressLocked("10.204.1.3") || p.networkAddressLocked("10.204.1.4") || !p.networkPeerLocked("10.204.1.2") || p.networkPeerLocked("192.168.1.1") {
|
||||
t.Fatal("peer boundary widened")
|
||||
}
|
||||
}
|
||||
func TestNetBirdAPIRequiresAuthorizedSession(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
for _, method := range []string{"GET", "POST"} {
|
||||
path := "/api/network/netbird"
|
||||
if method == "POST" {
|
||||
path += "/connect"
|
||||
}
|
||||
if got := call(s, method, path, "{}", nil); got.Code != 401 {
|
||||
t.Fatal(got.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalNetBirdSelectionQueuesCoreAdmissionWithoutMovingEndpoint(t *testing.T) {
|
||||
p, _, actions := networkFixture(t)
|
||||
p.mu.Lock()
|
||||
_ = p.loadNetworkLocked()
|
||||
p.network.NetBirdEndpoint = "https://10.204.1.2:8782"
|
||||
p.mu.Unlock()
|
||||
s := newTestServer(t)
|
||||
s.Pairing = p
|
||||
cookie := login(t, s)
|
||||
result := call(s, "POST", "/api/network/profile/netbird", "{}", cookie)
|
||||
if result.Code != 200 || p.network.LocalRequest == nil {
|
||||
t.Fatal(result.Code, result.Body.String())
|
||||
}
|
||||
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Pending != nil || len(*actions) != 0 {
|
||||
t.Fatal("local UI bypassed Core admission")
|
||||
}
|
||||
id := p.network.LocalRequest.ID
|
||||
p.acceptNetworkRequestResult(json.RawMessage(`{"id":"foreign","error":"bad"}`))
|
||||
if p.network.LocalRequest == nil {
|
||||
t.Fatal("foreign receipt consumed request")
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]string{"id": id, "error": "Отключите управление"})
|
||||
p.acceptNetworkRequestResult(raw)
|
||||
if p.network.LocalRequest != nil || p.network.LocalError == "" {
|
||||
t.Fatal("admission failure lost")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
|
||||
}
|
||||
|
||||
func (p *Pairing) Run(ctx context.Context) {
|
||||
go monitorNetBird(ctx)
|
||||
go p.networkWatch(ctx)
|
||||
go p.channel(ctx)
|
||||
go p.roverChannel(ctx)
|
||||
@@ -369,12 +370,16 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
payload["routers"] = p.Routers.Snapshot()
|
||||
}
|
||||
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
|
||||
var networkRequestResult json.RawMessage
|
||||
var netbirdOffer json.RawMessage
|
||||
var networkChange json.RawMessage
|
||||
var configurationChange json.RawMessage
|
||||
var routerCommands json.RawMessage
|
||||
p.mu.Lock()
|
||||
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
|
||||
if e == nil && status == 200 {
|
||||
networkRequestResult = result["network_request_result"]
|
||||
netbirdOffer = result["netbird_offer"]
|
||||
networkChange = result["network_profile_change"]
|
||||
routerCommands = result["router_commands"]
|
||||
if p.RoverConfiguration != nil {
|
||||
@@ -433,6 +438,8 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
if e == nil && status == http.StatusOK {
|
||||
p.networkLocalAcknowledged(*binding)
|
||||
}
|
||||
p.acceptNetworkRequestResult(networkRequestResult)
|
||||
p.acceptNetBirdOffer(netbirdOffer)
|
||||
p.applyNetworkCommand(networkChange)
|
||||
p.applyRouterCommands(routerCommands)
|
||||
// Durable preference IO must not hold the pairing/control mutex.
|
||||
|
||||
@@ -84,6 +84,7 @@ func reply(w http.ResponseWriter, status int, v any) {
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
s.routerRoutes(mux)
|
||||
s.netbirdRoutes(mux)
|
||||
s.linkBudgetRoutes(mux)
|
||||
s.localPreviewRoutes(mux)
|
||||
s.monitorRoutes(mux)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ActivityIndicator, Button, ConfirmationModal, Select, SettingsCard, Sta
|
||||
import { request } from "./api";
|
||||
|
||||
interface CoreState {
|
||||
network_profile?: {provider:string;phase:string;error?:string;tailscale_endpoint?:string};
|
||||
network_profile?: {provider:string;phase:string;error?:string;tailscale_endpoint?:string;netbird_endpoint?:string;local_request?:{expires_at:number}|null;local_error?:string};
|
||||
phase: "unpaired" | "inviting" | "pending" | "paired" | "revoked";
|
||||
connection: string; node_id: string; last_seen: number; notice: string; addresses: string[];
|
||||
invitation?: { id: string; endpoint: string; expires_at: number };
|
||||
@@ -54,7 +54,7 @@ export function CoreConnectionView({ failure }: { failure: (error: unknown) => v
|
||||
</dl>
|
||||
{value.notice && <p className="node-note" role="status">{value.notice}</p>}
|
||||
{paired ? <p className="node-note">БК сохраняет привязку при перезапуске и восстанавливает соединение автоматически. Для подключения к другому Core сначала отзовите текущую привязку.</p> : value.phase === "pending" ? <ActivityIndicator label="Core принимает приглашение. Дождитесь подтверждения связи." /> : <div className="node-form">
|
||||
<p className="node-note">Выберите адрес, доступный компьютеру с Mission Core: в общей локальной сети или Tailscale. Создайте приглашение и вставьте его в Core: «Парк → Аппараты → Добавить аппарат».</p>
|
||||
<p className="node-note">Выберите адрес, доступный компьютеру с Mission Core: в общей локальной сети, Tailscale или NetBird. Создайте приглашение и вставьте его в Core: «Парк → Аппараты → Добавить аппарат».</p>
|
||||
<Select label="Адрес БК для подключения" value={address} options={value.addresses.map(item => ({ value: item, label: item }))} onChange={setAddress} disabled={pending || !available} />
|
||||
{value.addresses.length === 0 && <p className="node-note">Подключите БК к частной сети. Доступные адреса появятся автоматически.</p>}
|
||||
<Button disabled={pending || !available || !address} onClick={() => void create()}>{pending ? "Создаём…" : value.phase === "inviting" ? "Создать новое приглашение" : "Создать приглашение"}</Button>
|
||||
@@ -66,11 +66,14 @@ export function CoreConnectionView({ failure }: { failure: (error: unknown) => v
|
||||
{notice && <p role="status" className="node-note">{notice}</p>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{paired&&value?.network_profile&&<SettingsCard title="Связь с Core" description="Настройки применяются к этому БК из Mission Core: Парк → Бортовой компьютер → Связь с Core.">
|
||||
<StatusBadge tone={value.connection==='online'?'success':'neutral'}>{value.network_profile.provider==='wireguard'?'WireGuard · VPS':'Tailscale'}</StatusBadge>
|
||||
{paired&&value?.network_profile&&<SettingsCard title="Связь с Core" description="Выберите проверенную частную сеть для этого БК. Настройки также доступны в Mission Core: Парк → Бортовой компьютер → Связь с Core.">
|
||||
<StatusBadge tone={value.connection==='online'?'success':'neutral'}>{value.network_profile.provider==='netbird'?'NetBird':value.network_profile.provider==='wireguard'?'WireGuard · VPS':'Tailscale'}</StatusBadge>
|
||||
{['preparing','verifying'].includes(value.network_profile.phase)&&<p className="node-note">Проверяем новое подключение. При отсутствии подтверждения вернётся прежний профиль.</p>}
|
||||
{value.network_profile.error&&<p role="status" className="node-note">{value.network_profile.error}</p>}
|
||||
{value.network_profile.provider==='wireguard'&&<Button disabled={pending||!value.network_profile.tailscale_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/tailscale','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Восстановить Tailscale</Button>}
|
||||
{value.network_profile.local_error&&<StatusBadge tone="danger">{value.network_profile.local_error}</StatusBadge>}
|
||||
{value.network_profile.local_request&&value.network_profile.local_request.expires_at>Date.now()/1000&&<p className="node-note">Ожидаем разрешение переключения от Core. Активное управление должно быть отключено.</p>}
|
||||
{value.network_profile.provider!=='netbird' &&<Button disabled={pending||Boolean(value.network_profile.local_request&&value.network_profile.local_request.expires_at>Date.now()/1000)||!value.network_profile.netbird_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/netbird','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Использовать NetBird</Button>}
|
||||
{value.network_profile.provider!=='tailscale'&&<Button disabled={pending||!value.network_profile.tailscale_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/tailscale','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Восстановить Tailscale</Button>}
|
||||
</SettingsCard>}
|
||||
<ConfirmationModal open={remove} title={value?.binding ? "Отозвать привязку к Core?" : "Отменить приглашение?"} description={value?.binding ? "Этот БК прекратит соединение с Core. Аппарат останется в его реестре; отзыв будет доставлен при доступности сети." : "Этот код больше нельзя будет использовать. Вы сможете создать новый."} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={() => setRemove(false)} onConfirm={async () => { try { await request("/api/core", "DELETE"); setCode(""); setNotice(""); await refresh(); setRemove(false); } catch (error) { failure(error); throw error; } }} />
|
||||
</div>;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
||||
import { ActivityIndicator, Button, Icon, ResourceList, ResourceRow, SettingsCard, StatusBadge } from "@nodedc/ui-react";
|
||||
import { environmentSetupAvailable } from "./api";
|
||||
import type { useEnvironment } from "./useEnvironment";
|
||||
import { TailnetAccess } from "./TailnetAccess";
|
||||
import { PrivateNetwork } from "./PrivateNetwork";
|
||||
import { SystemAccess } from "./SystemAccess";
|
||||
|
||||
const labels:Record<string,string>={pending:"Ожидает",running:"Выполняется",error:"Ошибка",blocked:"Не выполнено"};
|
||||
@@ -25,14 +25,14 @@ export function EnvironmentView({environment,failure,success}: {environment:Retu
|
||||
return <li key={specification.id}><ResourceRow icon={state==="running"?<ActivityIndicator size="compact" />:<Icon name={state==="error"?"alert":"circle"} />} title={specification.label} description={specification.description} metadata={step?.detail} status={state==="complete"?<Icon name="check" label="Этап завершён" />:<StatusBadge tone={state==="error"?"warning":"neutral"}>{labels[state]??"Неизвестно"}</StatusBadge>} /></li>;
|
||||
})}</ResourceList>
|
||||
{value.run&&!running&&value.run.updated_at>0&&<p className="node-note">Результат проверки от {new Date(value.run.updated_at*1000).toLocaleString("ru-RU")}.</p>}
|
||||
{complete&&!running&&<p className="node-note">Системные этапы завершены. Ниже проверьте вход в Tailscale и доверенный ключ для SSH.</p>}
|
||||
{complete&&!running&&<p className="node-note">Системные этапы завершены. Ниже выберите частную сеть и проверьте доверенный ключ для SSH.</p>}
|
||||
{value.run?.state==="error"&&!running&&<p className="node-note">Часть этапов не завершена. Исправьте указанные причины и повторите настройку.</p>}
|
||||
{value.run?.state==="interrupted"&&<p className="node-note">Предыдущая настройка прервана. Повторный запуск проверит уже выполненные этапы.</p>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{!running&&<>
|
||||
<SettingsCard title="Доверенное устройство для SSH"><SystemAccess revision={revision} failure={failure} success={success} adding={adding} closeAdd={()=>setAdding(false)} startAdd={()=>setAdding(true)} /></SettingsCard>
|
||||
<TailnetAccess failure={failure} revision={revision} />
|
||||
<PrivateNetwork failure={failure} revision={revision} />
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import {useEffect,useState} from "react";
|
||||
import {ActivityIndicator,Button,Select,SettingsCard,StatusBadge,TextField} from "@nodedc/ui-react";
|
||||
import {desktopAction,networkSetupAvailable,openNetworkLogin,request} from "./api";
|
||||
import {TailnetAccess} from "./TailnetAccess";
|
||||
interface NetBird {state:string;address?:string;server_url?:string;pending?:string;auth_url?:string;error?:string}
|
||||
export function PrivateNetwork({failure,revision}:{failure:(error:unknown)=>void;revision:string}) {
|
||||
const [provider,setProvider]=useState("tailscale"),[value,setValue]=useState<NetBird|null>(null);
|
||||
const [server,setServer]=useState(""),[method,setMethod]=useState("browser"),[key,setKey]=useState("");
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState("");
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{try{const next=await request<NetBird>("/api/network/netbird","GET",undefined,controller.signal);if(active){setValue(next);setServer(old=>old||next.server_url||"");}}catch{if(active)setValue({state:"unavailable"});}finally{if(active)timer=setTimeout(poll,2500);}};
|
||||
void poll();return()=>{active=false;controller.abort();clearTimeout(timer);};
|
||||
},[revision]);
|
||||
async function connect(){setBusy(true);setError("");const secret=key;setKey("");try{setValue(await request<NetBird>("/api/network/netbird/connect","POST",{server_url:server,setup_key:method==="key"?secret:""}));}catch(e){setError(e instanceof Error?e.message:"Не удалось подключиться.");}finally{setBusy(false);}}
|
||||
const pending=busy||Boolean(value?.pending);
|
||||
return <div className="node-content">
|
||||
<SettingsCard title="Частная сеть" description="Подключение бортового компьютера к сети оператора">
|
||||
<Select label="Сеть" value={provider} onChange={setProvider} options={[{value:"tailscale",label:"Tailscale"},{value:"netbird",label:"NetBird · WireGuard"}]} disabled={pending}/>
|
||||
<p className="node-note">После входа выберите канал в «Mission Core → Связь с Core». Текущий канал сохраняется до проверки нового.</p>
|
||||
</SettingsCard>
|
||||
{provider==="tailscale"?<TailnetAccess failure={failure} revision={revision}/>:<SettingsCard title="NetBird" description="Укажите сервер вашей сети или запросите его адрес у администратора." actions={<StatusBadge tone={value?.state==="connected"?"success":"neutral"}>{value?.state==="connected"?"Подключено":pending?"Подключение…":"Не подключено"}</StatusBadge>}>
|
||||
{!value?<ActivityIndicator label="Проверяем NetBird"/>:<>
|
||||
{value.state==="missing_client"&&<><p className="node-note">Завершите подготовку окружения: приложение установит проверенный клиент. После этого здесь можно будет выбрать сервер и войти.</p><Button disabled={!networkSetupAvailable()} onClick={()=>desktopAction("configure-system")}>Подготовить окружение</Button></>}
|
||||
<TextField label="Адрес сервера" placeholder="https://netbird.example.org" value={server} onChange={e=>setServer(e.target.value)} disabled={pending}/>
|
||||
{value.state!=="connected"&&<><Select label="Способ входа" value={method} onChange={setMethod} options={[{value:"browser",label:"Войти в браузере"},{value:"key",label:"Ключ подключения"}]} disabled={pending}/>
|
||||
{method==="key"&&<><TextField label="Ключ подключения борта" type="password" autoComplete="off" value={key} onChange={e=>setKey(e.target.value)} disabled={pending}/><p className="node-note">Получите ключ для группы бортов у администратора сети. Ключ нужен только при первом подключении.</p></>}</>}
|
||||
<Button disabled={pending||!server||value.state==="missing_client"||(method==="key"&&value.state!=="connected"&&!key)} onClick={()=>void connect()}>{value.state==="connected"?"Проверить подключение":"Подключить"}</Button>
|
||||
{value.auth_url&&<Button onClick={()=>openNetworkLogin(value.auth_url!)}>Продолжить вход в браузере</Button>}
|
||||
{value.pending&&<><ActivityIndicator label={value.auth_url?"Завершите вход в браузере. Состояние обновится автоматически.":"Проверяем подключение к серверу…"}/><Button disabled={busy} onClick={async()=>{try{setValue(await request<NetBird>("/api/network/netbird/cancel","POST",{}));}catch(e){failure(e);}}}>Отменить ожидание</Button></>}
|
||||
{value.state==="connected"&&<p className="node-note">Адрес борта: {value.address}. Подключение восстанавливается автоматически после запуска системы.</p>}
|
||||
{value.state==="other_network"&&<p className="node-note">NetBird подключён к другой сети. Отключите её в официальном клиенте перед сменой сервера.</p>}
|
||||
{value.state==="unsupported_client"&&<p className="node-note">Версия клиента не соответствует установщику. Обновите окружение БК.</p>}
|
||||
{(error||value.error)&&<StatusBadge tone="danger">{error||value.error}</StatusBadge>}
|
||||
</>}
|
||||
</SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -43,3 +43,10 @@ export async function loginFromLaunch(): Promise<void> {
|
||||
if (location.hash) history.replaceState(null, "", location.pathname);
|
||||
if (token) await request("/api/session", "POST", { token });
|
||||
}
|
||||
|
||||
export function openNetworkLogin(url:string):void {
|
||||
const parsed=new URL(url);if(parsed.protocol!=="https:"||!parsed.pathname.startsWith("/oauth2/")||parsed.username||parsed.password)return;
|
||||
const host=window as Window & {webkit?:{messageHandlers?:{node?:{postMessage:(message:string)=>void}}}};
|
||||
if(host.webkit?.messageHandlers?.node)host.webkit.messageHandlers.node.postMessage(JSON.stringify({action:"netbird-login",url}));
|
||||
else window.open(url,"_blank","noopener,noreferrer");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { roots, views, type RootId, type ViewId } from "./nodeModel";
|
||||
import { NodeOverview } from "./NodeOverview";
|
||||
import { USBView, DiagnosticsView, NetworkView } from "./InventoryViews";
|
||||
import { SystemAccess } from "./SystemAccess";
|
||||
import { TailnetAccess } from "./TailnetAccess";
|
||||
import { PrivateNetwork } from "./PrivateNetwork";
|
||||
import { useEnvironment } from "./useEnvironment";
|
||||
import { EnvironmentView } from "./EnvironmentView";
|
||||
import { CoreConnectionView } from "./CoreConnectionView";
|
||||
@@ -43,7 +43,7 @@ function App() {
|
||||
: workspace.activeView === "usb" ? <USBView value={value} />
|
||||
: workspace.activeView === "core" ? <CoreConnectionView failure={failure} />
|
||||
: workspace.activeView === "diagnostics" ? <DiagnosticsView value={value} />
|
||||
: workspace.activeView === "tailscale" ? <TailnetAccess failure={failure} revision={value.host.collected_at} />
|
||||
: workspace.activeView === "tailscale" ? <PrivateNetwork failure={failure} revision={value.host.collected_at} />
|
||||
: workspace.activeView === "ssh" ? <SystemAccess revision={value.host.collected_at} failure={failure} success={node.success} adding={adding} closeAdd={() => setAdding(false)} /> : null;
|
||||
return <>
|
||||
<ApplicationShell data-nodedc-ui className="node-app" header={<AppHeader brandMonochrome brandHref="/" brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />} brandLabel={presentation.settings.pages.home.headerLabel}
|
||||
|
||||
@@ -12,7 +12,7 @@ export const views: { id: ViewId; root: RootId; label: string; icon: IconName }[
|
||||
{ id: "network", root: "system", label: "Сеть", icon: "network" },
|
||||
{ id: "usb", root: "system", label: "USB-устройства", icon: "camera" },
|
||||
{ id: "core", root: "system", label: "Mission Core", icon: "network" },
|
||||
{ id: "tailscale", root: "system", label: "Tailscale", icon: "globe" },
|
||||
{ id: "tailscale", root: "system", label: "Частная сеть", icon: "globe" },
|
||||
{ id: "ssh", root: "system", label: "SSH · доверенные устройства", icon: "key" },
|
||||
{ id: "diagnostics", root: "system", label: "Диагностика", icon: "clipboard" },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user