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>;
|
||||
}
|
||||
Reference in New Issue
Block a user