feat(network): integrate NetBird clients, profiles and private backups
This commit is contained in:
@@ -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