Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca1bc1ab38 | ||
|
|
d9f623ccda | ||
|
|
9951035448 |
No files matched your search
+48
-49
@@ -2,8 +2,6 @@
|
||||
|
||||
import { useState } from "react"
|
||||
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -11,9 +9,20 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
function publicEndpoint(inventory?: IxNodeInventory) {
|
||||
const wan = inventory?.defaultRoutes.find(route => route.family === 4)
|
||||
return inventory?.interfaces.find(item => item.name === wan?.interface)?.addresses.find(value => !value.includes(":"))?.split("/")[0] ?? ""
|
||||
export function publicEndpoint(inventory?: IxNodeInventory) {
|
||||
if (!inventory) return ""
|
||||
const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
|
||||
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
|
||||
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
|
||||
return addresses.size === 1 ? [...addresses][0] : ""
|
||||
}
|
||||
|
||||
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
|
||||
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
|
||||
const base = "via-" + target.toString(36) + "-v" + family
|
||||
let name = base
|
||||
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
|
||||
return name
|
||||
}
|
||||
|
||||
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
@@ -31,18 +40,17 @@ function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
|
||||
const localEndpoint = local || publicEndpoint(origin.inventory)
|
||||
const remoteEndpoint = remote || publicEndpoint(target.inventory)
|
||||
const exitName = name || transitName(segment, serverId, targetServerId, family)
|
||||
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!busy && targetServerId && localEndpoint && remoteEndpoint && name) {
|
||||
save({ revision: segment.revision, name, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
|
||||
if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
|
||||
save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
|
||||
}
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
|
||||
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
|
||||
<Input id="ix-egress-name" placeholder="via-arn" pattern="[a-z][a-z0-9-]{0,23}" required value={name} onChange={event => setName(event.target.value)} /></Field>
|
||||
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
|
||||
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
|
||||
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
|
||||
@@ -56,56 +64,47 @@ function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
|
||||
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
|
||||
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
|
||||
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
|
||||
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
|
||||
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
|
||||
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
|
||||
</Field>
|
||||
<details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
|
||||
<Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
|
||||
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
|
||||
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
|
||||
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
|
||||
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
|
||||
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Проверить план выхода</Button>
|
||||
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxExits({ segment, nodes, backendUrl, busy, readOnly, error, save, configure }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; readOnly: boolean; error: string
|
||||
save: (input: IxTransitRequest) => Promise<boolean>; configure: () => void
|
||||
export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
|
||||
save: (input: IxTransitRequest) => Promise<boolean>
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return <Frame spacing="sm">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Выходы и резерв</FrameTitle>
|
||||
{!readOnly && <Button size="sm" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>}
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-3">
|
||||
{segment.configuration.sites.every(site => !site.groups.length) && <EmptyState title="Групп шлюзов пока нет"
|
||||
description="При подключении клиента можно выбрать выход через WAN этого IX или создать транзит на другой узел." />}
|
||||
{segment.configuration.sites.map(site => site.groups.length > 0 && <div key={site.serverId} className="grid gap-2">
|
||||
<h3 className="text-sm font-medium">{nodeLabel(nodes, site.serverId)}</h3>
|
||||
{site.groups.map(group => <div key={group.id} className="grid gap-1 border-b pb-2 text-sm">
|
||||
<span className="font-medium">{group.id}</span>
|
||||
<span className="text-muted-foreground">Основной · {group.primary.interface} · {group.primary.nextHop}</span>
|
||||
<span className="text-muted-foreground">Резерв · {group.backup ? group.backup.interface + " · " + group.backup.nextHop : "не задан"}</span>
|
||||
</div>)}
|
||||
</div>)}
|
||||
<Button size="sm" variant="outline" className="w-fit" disabled={busy} onClick={configure}>Открыть настройки групп шлюзов</Button>
|
||||
</FramePanel>
|
||||
return <>
|
||||
<Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="w-full sm:max-w-lg">
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>Удалённый выход</SheetTitle>
|
||||
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
@@ -114,5 +113,5 @@ export function IxExits({ segment, nodes, backendUrl, busy, readOnly, error, sav
|
||||
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</Frame>
|
||||
</>
|
||||
}
|
||||
@@ -2,25 +2,30 @@
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
|
||||
import { publicEndpoint, transitName } from "./ix-exits"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean }
|
||||
type FormState = {
|
||||
serverId: number
|
||||
name: string
|
||||
kind: IxLinuxClientRequest["kind"]
|
||||
kind: IxLinuxClientRequest["kind"] | "both"
|
||||
hub: string
|
||||
peer: string
|
||||
key: string
|
||||
@@ -34,108 +39,149 @@ type FormState = {
|
||||
|
||||
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
|
||||
|
||||
function choicesFor(site: IxSite | undefined, nodes: IxNode[]) {
|
||||
return [
|
||||
{ value: "isolated", label: "Только разрешённые сети" },
|
||||
{ value: "local-wan", label: "Интернет с этого IX" },
|
||||
...(site?.groups.filter(group => group.onFailure === "block").map(group => {
|
||||
const link = site.interfaces.find(binding => binding.name === group.primary.interface)
|
||||
const peer = nodes.find(node => node.id === link?.peerServerId)
|
||||
return { value: group.id, label: [group.id, peer?.name, group.backup && "с резервом"].filter(Boolean).join(" · ") }
|
||||
}) ?? []),
|
||||
]
|
||||
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
|
||||
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
|
||||
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
|
||||
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
|
||||
}
|
||||
|
||||
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string
|
||||
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
|
||||
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
|
||||
}) {
|
||||
const binding = edit?.binding
|
||||
const existing = edit?.binding
|
||||
const companion = edit?.addProtocol ? existing : undefined
|
||||
const binding = companion ? undefined : existing
|
||||
const [form, setForm] = useState<FormState>(() => ({
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "", key: binding?.provisionWireguard?.peerPublicKey ?? "",
|
||||
name: existing?.linux?.name ?? "",
|
||||
kind: companion ? (companion.kind === "wireguard" ? "gre-ipsec" : "wireguard")
|
||||
: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
|
||||
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
|
||||
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
|
||||
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
|
||||
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
|
||||
}))
|
||||
const wireguard = form.kind !== "gre-ipsec"
|
||||
const gre = form.kind !== "wireguard"
|
||||
const [rotate, setRotate] = useState(false)
|
||||
const { inventory } = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const [transitLocal, setTransitLocal] = useState("")
|
||||
const [transitRemote, setTransitRemote] = useState("")
|
||||
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
|
||||
const uplink = inventory?.interfaces.find(item => item.name === inventory.defaultRoutes.find(route => route.family === 4)?.interface)
|
||||
const suggested = uplink?.addresses.find(address => !address.includes(":"))?.split("/")[0] ?? ""
|
||||
const suggested = publicEndpoint(origin.inventory)
|
||||
const hub = form.hub.trim() || suggested
|
||||
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
|
||||
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
|
||||
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
|
||||
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
|
||||
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }]
|
||||
const exits = choicesFor(site, nodes)
|
||||
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" ? !!form.key : !!form.peer)
|
||||
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
|
||||
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
const exits = [
|
||||
{ value: "isolated", label: "Только разрешённые сети" },
|
||||
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
|
||||
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
|
||||
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
|
||||
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
|
||||
]
|
||||
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
|
||||
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
|
||||
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!valid || busy) return
|
||||
void save({
|
||||
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
|
||||
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: form.kind === "wireguard" ? form.key.trim() : undefined,
|
||||
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" ? undefined : form.exit,
|
||||
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
|
||||
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
|
||||
localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
|
||||
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
|
||||
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
|
||||
localEndpoint, remoteEndpoint } : undefined,
|
||||
enabled: form.enabled, rotate,
|
||||
})
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
|
||||
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
|
||||
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
|
||||
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
|
||||
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel>
|
||||
<Select value={form.kind} items={transports} disabled={!!edit}
|
||||
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}>
|
||||
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field>
|
||||
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
|
||||
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
|
||||
<Button type="button" size="sm" variant={wireguard ? "secondary" : "outline"} aria-pressed={wireguard}
|
||||
disabled={!!edit || form.kind === "wireguard"}
|
||||
onClick={() => patch({ kind: wireguard ? "gre-ipsec" : "both" })}>WireGuard</Button>
|
||||
<Button type="button" size="sm" variant={gre ? "secondary" : "outline"} aria-pressed={gre}
|
||||
disabled={!!edit || form.kind === "gre-ipsec"}
|
||||
onClick={() => patch({ kind: gre ? "wireguard" : "both" })}>GRE/IPsec</Button>
|
||||
</ButtonGroup>
|
||||
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
|
||||
: companion ? <FieldDescription>Второй туннель добавится в ту же VRF. Выход и сети можно выбрать отдельно.</FieldDescription>
|
||||
: !edit && <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} placeholder="IP узла RouterOS" onChange={event => patch({ hub: event.target.value })} />
|
||||
{suggested && !form.hub && <FieldDescription>Подставлен адрес из инвентаря CHR.</FieldDescription>}</Field>
|
||||
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} required onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Создайте ключ на Linux командой <code>wg genkey</code> и вставьте результат <code>wg pubkey</code>.</FieldDescription>
|
||||
</Field>}
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
|
||||
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => value && patch({ exit: value })}>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
|
||||
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
<FieldDescription>Для другого IX или ExitNode выберите настроенную группу шлюзов.</FieldDescription>
|
||||
{!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
<FieldDescription>Для этих сетей используются маршруты IX и BGP.</FieldDescription></Field>
|
||||
<details className="grid gap-3">
|
||||
<summary className="cursor-pointer font-medium">Адреса туннеля и сети за Linux</summary>
|
||||
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
|
||||
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-transit-target" value={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
|
||||
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
|
||||
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => setTransitLocal(event.target.value)} /></Field>}
|
||||
{form.exit === "isolated" && destinationsField}
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
|
||||
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
|
||||
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
|
||||
</Field>
|
||||
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
|
||||
{form.exit !== "isolated" && destinationsField}
|
||||
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
|
||||
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
|
||||
</div>
|
||||
</details>
|
||||
{edit && <div className="flex flex-wrap gap-2">
|
||||
{binding && <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
|
||||
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
|
||||
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
|
||||
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<SheetFooter><Button type="submit" disabled={!valid || busy}>{edit ? "Проверить изменения" : "Подготовить доступ"}</Button>
|
||||
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
|
||||
</form>
|
||||
}
|
||||
@@ -147,24 +193,39 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
inspect: (binding: IxLinuxBinding) => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null)
|
||||
const [edit, setEdit] = useState<ClientSelection | null>(null)
|
||||
const rows = useMemo(() => {
|
||||
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
|
||||
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
|
||||
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
|
||||
}] : []))
|
||||
return [...saved, ...applied.filter(binding => !binding.policy && !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
}, [segment, applied])
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
||||
{ id: "name", header: "Клиент", cell: ({ row }) => <span className="font-medium">{row.original.name ?? row.original.interfaceName}</span> },
|
||||
{ id: "node", header: "Узел IX", cell: ({ row }) => nodeLabel(nodes, row.original.serverId) },
|
||||
{ id: "transport", header: "Туннель", cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
{ id: "egress", header: "Выход", cell: ({ row }) => row.original.policy?.exit ?? "Сети IX" },
|
||||
{ id: "state", header: "Состояние", cell: ({ row }) => {
|
||||
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
|
||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||
</div> },
|
||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
||||
const client = row.original
|
||||
const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
|
||||
const binding = site?.interfaces.find(item => item.name === client.interfaceName)
|
||||
const group = site?.groups.find(item => item.id === client.policy?.exit)
|
||||
const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
|
||||
return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
|
||||
disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
|
||||
<span className="truncate">{label}</span><PencilIcon aria-hidden />
|
||||
</Button>
|
||||
} },
|
||||
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge>
|
||||
if (!applied.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)) return <Badge variant="warning-light">Черновик</Badge>
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
|
||||
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
|
||||
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
||||
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
||||
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||
return binding.connection?.state === "connected" ? <div className="grid gap-1">
|
||||
<Badge variant="success-light" className="w-fit">Подключён</Badge>
|
||||
@@ -172,19 +233,28 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
</div>
|
||||
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
|
||||
} },
|
||||
{ id: "actions", header: "Действия", cell: ({ row }) => {
|
||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
|
||||
const canDownload = applied.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
const paired = !!saved?.linux?.clientId && site?.interfaces.some(item =>
|
||||
item.kind !== saved.kind && item.linux?.clientId === saved.linux?.clientId)
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
return <div className="flex flex-wrap gap-1">
|
||||
{canDownload && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)}
|
||||
onClick={() => view(binding)}>Конфиг Linux</Button>}
|
||||
{canDownload && binding.policy && <Button size="sm" variant="ghost" disabled={busy} onClick={() => inspect(binding)}>Проверить путь</Button>}
|
||||
{!readOnly && site && saved?.linux && <>
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => { setEdit({ site, binding: saved }); setOpen(true) }}>Доступ и выход</Button>
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => revoke(binding)}>Отозвать…</Button>
|
||||
</>}
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
|
||||
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
|
||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
|
||||
<EllipsisIcon aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
|
||||
{!readOnly && site && saved?.linux && !paired && <DropdownMenuItem
|
||||
onClick={() => { setEdit({ site, binding: saved, addProtocol: true }); setOpen(true) }}>Добавить другой протокол</DropdownMenuItem>}
|
||||
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect])
|
||||
@@ -202,9 +272,9 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||
</FramePanel>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="w-full sm:max-w-lg">
|
||||
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Настройте туннель и проверьте план перед применением к RouterOS.</SheetDescription>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>{edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useId, type ReactNode } from "react"
|
||||
import { useId, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxNodeInventory, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
@@ -62,25 +62,29 @@ function Lines({ label, value, edit }: { label: string; value: string[]; edit: (
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
|
||||
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
|
||||
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
|
||||
label?: (item: T) => string; visible?: (item: T) => boolean
|
||||
}) {
|
||||
return <details className="min-w-0 rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">{title} · {items.length}</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
{items.map((item, index) => <div className="grid min-w-0 gap-3 rounded-md border p-3" key={index}>
|
||||
<div className="flex items-center justify-between gap-2 text-sm text-muted-foreground">
|
||||
<span>Запись {index + 1}</span>
|
||||
{!readOnly && <Button type="button" size="icon-sm" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => edit(items.filter((_, position) => position !== index))}><XIcon aria-hidden /></Button>}
|
||||
</div>
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
</div>)}
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" className="w-fit" disabled={items.length >= max}
|
||||
onClick={() => edit([...items, make()])}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
const [expanded, setExpanded] = useState<number | null>(null)
|
||||
const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
|
||||
return <section className="grid min-w-0 gap-2 border-t py-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
|
||||
onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
</div>
|
||||
</details>
|
||||
{rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
|
||||
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
|
||||
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
|
||||
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
|
||||
</fieldset>}
|
||||
</div>)}
|
||||
</section>
|
||||
}
|
||||
|
||||
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
|
||||
@@ -156,7 +160,13 @@ function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnl
|
||||
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
|
||||
alternatives: Group[]; readOnly: boolean
|
||||
}) {
|
||||
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
|
||||
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
|
||||
return <>
|
||||
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
|
||||
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
|
||||
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
|
||||
: alternatives.find(other => other.id === id)?.primary })} />
|
||||
<div className={columns}>
|
||||
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
|
||||
@@ -165,13 +175,8 @@ function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnl
|
||||
]} edit={onFailure => edit({ ...value, onFailure })} />
|
||||
</div>
|
||||
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
|
||||
<Flag label="Резервный путь" checked={!!value.backup} disabled={readOnly}
|
||||
edit={enabled => edit({ ...value, backup: enabled ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "") : undefined })} />
|
||||
{value.backup && <>
|
||||
{alternatives.length > 0 && <Pick label="Взять резерв из другого выхода" options={alternatives.map(group => ({ value: group.id, label: group.id }))}
|
||||
disabled={readOnly} edit={id => { const backup = alternatives.find(group => group.id === id)?.primary; if (backup) edit({ ...value, backup }) }} />}
|
||||
<PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={backup => edit({ ...value, backup })} />
|
||||
</>}
|
||||
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
|
||||
readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -212,38 +217,38 @@ export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, invento
|
||||
}) {
|
||||
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
|
||||
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
|
||||
return <fieldset className="grid min-w-0 gap-2" disabled={readOnly}>
|
||||
<Entries<Binding> title="Подключения" items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить подключение" readOnly={readOnly}>
|
||||
return <div className="grid min-w-0 gap-2">
|
||||
<Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
|
||||
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
|
||||
</Entries>
|
||||
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })}
|
||||
<Entries<Group> title="Выходы и резерв" label={item => item.id} items={site.groups} edit={groups => edit({ groups })}
|
||||
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
|
||||
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
|
||||
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
|
||||
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })}
|
||||
<Entries title="Статические маршруты" label={item => item.prefix} items={site.routes} edit={routes => edit({ routes })}
|
||||
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
|
||||
{(route, update) => <div className={columns}>
|
||||
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
|
||||
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
<Entries<Peer> title="BGP-соседи" items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
<Entries<Peer> title="BGP-соседи" label={item => item.id} items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
|
||||
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
|
||||
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<details className="rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
<fieldset disabled={readOnly} className="grid gap-3 border-t p-3">
|
||||
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
|
||||
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
|
||||
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
|
||||
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
|
||||
</div>
|
||||
</fieldset>
|
||||
</details>
|
||||
</fieldset>
|
||||
</div>
|
||||
}
|
||||
+15
-15
@@ -41,8 +41,8 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
</Button>
|
||||
) },
|
||||
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
||||
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> },
|
||||
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
|
||||
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
||||
], [nodes, open])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
||||
@@ -95,7 +95,8 @@ function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOn
|
||||
</>
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId }: {
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
|
||||
section: "configuration" | "routes"
|
||||
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
backendUrl: string; segmentId?: string
|
||||
}) {
|
||||
@@ -105,7 +106,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
|
||||
|
||||
return <div className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
{section === "configuration" && <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
||||
<FramePanel>
|
||||
<Field className="max-w-md">
|
||||
@@ -115,17 +116,16 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
||||
</Field>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</Frame>}
|
||||
{configuration.sites.map((site, index) => {
|
||||
const fieldId = `ix-site-${index}`
|
||||
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
|
||||
return <Frame key={fieldId} spacing="sm">
|
||||
<FrameHeader className="flex-row items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle>Площадка {index + 1}</FrameTitle>
|
||||
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
|
||||
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
|
||||
</div>
|
||||
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
aria-label={`Убрать площадку ${index + 1}`}
|
||||
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
||||
<XIcon aria-hidden />
|
||||
@@ -133,7 +133,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-4">
|
||||
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field className="min-w-0">
|
||||
{section === "configuration" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
||||
<Select
|
||||
value={site.serverId ? String(site.serverId) : null}
|
||||
@@ -146,21 +146,21 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field className="min-w-0">
|
||||
</Field>}
|
||||
{section === "routes" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
||||
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
||||
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
||||
</Field>
|
||||
<IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
||||
</Field>}
|
||||
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
||||
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
|
||||
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />}
|
||||
</div>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
})}
|
||||
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
||||
<PlusIcon aria-hidden />Добавить площадку
|
||||
</Button>}
|
||||
|
||||
+129
-128
@@ -12,6 +12,7 @@ import { ServerRailLayout, ServerRailMobileButton } from "@/components/server-ra
|
||||
import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
@@ -23,7 +24,7 @@ import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, Segmen
|
||||
import { IxLinuxClients } from "./ix-linux-clients"
|
||||
import { IxExits } from "./ix-exits"
|
||||
|
||||
type Tab = "configuration" | "routes" | "changes" | "linux" | "exits"
|
||||
type Tab = "configuration" | "routes" | "linux"
|
||||
|
||||
const title = "Точки обмена трафиком"
|
||||
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
|
||||
@@ -75,8 +76,8 @@ export default function IxPage() {
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
|
||||
const [revoke, setRevoke] = useState<IxLinuxBinding | null>(null)
|
||||
const [clientReview, setClientReview] = useState<IxLinuxBinding | null>(null)
|
||||
const [review, setReview] = useState("")
|
||||
const [reviewError, setReviewError] = useState("")
|
||||
const [plan, setPlan] = useState<IxWebPlan | null>(null)
|
||||
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
|
||||
const [tab, setTab] = useState<Tab>("configuration")
|
||||
@@ -138,12 +139,13 @@ export default function IxPage() {
|
||||
|
||||
function invalidateReview() {
|
||||
setPlan(null)
|
||||
setClientReview(null)
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setRemovalPlan(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function open(segment: IxSegment | null, defaultTab: Tab = "configuration") {
|
||||
function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
|
||||
focusAfterNavigation.current = !inDetail
|
||||
setSelected(segment)
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
@@ -182,20 +184,24 @@ export default function IxPage() {
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (selected && !dirty) {
|
||||
await reviewSegment(selected, selected.configuration.name)
|
||||
return
|
||||
}
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
|
||||
open(segment)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item)
|
||||
: [segment, ...current])
|
||||
setNotice("Черновик сохранён")
|
||||
await reviewSegment(segment, segment.configuration.name)
|
||||
}
|
||||
|
||||
async function prepare(resume = false) {
|
||||
if (!selected || !canPlan) return
|
||||
async function prepare(segment: IxSegment, resume = false) {
|
||||
setPlan(null)
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({
|
||||
revision: selected.revision, ...(resume && { resume }),
|
||||
})))
|
||||
setReviewError("")
|
||||
try {
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
|
||||
revision: segment.revision, ...(resume && { resume }),
|
||||
})))
|
||||
} catch (error) {
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRemoval() {
|
||||
@@ -228,21 +234,23 @@ export default function IxPage() {
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setNotice("Конфигурация IX применена")
|
||||
if (clientReview) {
|
||||
if (tab === "linux" || selected.appliedRevision === null) {
|
||||
setTab("linux")
|
||||
setClientReview(null)
|
||||
const clients = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`).catch(() => null)
|
||||
if (clients) setLinuxBindings(clients.items)
|
||||
await loadLinuxBindings(segment).catch(error => setError(describe(error)))
|
||||
} else if (tab === "routes") {
|
||||
await observe(segment).catch(error => setError(describe(error)))
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function observe() {
|
||||
if (!selected?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
|
||||
async function observe(segment = selected) {
|
||||
if (!segment?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
|
||||
setObservations(sites)
|
||||
}
|
||||
|
||||
@@ -257,6 +265,13 @@ export default function IxPage() {
|
||||
if (!selected) return
|
||||
setLinux(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
if (binding.managedWireguard && write) {
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
download(access.filename, access.template)
|
||||
setNotice("Конфигурация WireGuard скачана")
|
||||
return
|
||||
}
|
||||
const access = binding.policy && binding.kind === "gre-ipsec" && write
|
||||
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
@@ -279,38 +294,52 @@ export default function IxPage() {
|
||||
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
|
||||
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
|
||||
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
|
||||
setClientReview({ serverId: input.serverId, kind: input.kind,
|
||||
interfaceName: "interfaceName" in result ? String(result.interfaceName) : input.interfaceName ?? "" })
|
||||
await reviewSegment(result.segment)
|
||||
await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
|
||||
}
|
||||
|
||||
async function stageTransit(input: IxTransitRequest) {
|
||||
if (!selected || dirty || !write) return
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
`/api/ix/segments/${selected.id}/transit`, post(input))
|
||||
setClientReview(null)
|
||||
await reviewSegment(segment)
|
||||
await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
|
||||
}
|
||||
|
||||
async function reviewSegment(segment: IxSegment) {
|
||||
async function reviewSegment(segment: IxSegment, title: string) {
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setAdvanced(null)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setReview(title)
|
||||
await prepare(segment)
|
||||
}
|
||||
|
||||
function closeReview() {
|
||||
if (busy) return
|
||||
setReview("")
|
||||
setPlan(null)
|
||||
setTab("changes")
|
||||
setNotice("Изменения сохранены в черновике")
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, `/api/ix/segments/${segment.id}/plan`, post({ revision: segment.revision })))
|
||||
setReviewError("")
|
||||
setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
|
||||
}
|
||||
|
||||
function showTab(next: Tab) {
|
||||
if (next === tab || busy) return
|
||||
if (advanced !== null) {
|
||||
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
|
||||
}
|
||||
setError("")
|
||||
setTab(next)
|
||||
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
|
||||
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
|
||||
}
|
||||
|
||||
const settingsProps = draft && {
|
||||
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
|
||||
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
|
||||
}
|
||||
|
||||
const listEmpty = error ? "Не удалось загрузить список" :
|
||||
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
|
||||
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
|
||||
@@ -328,7 +357,7 @@ export default function IxPage() {
|
||||
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
|
||||
actions={<ServerRailMobileButton />} />}>
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
<div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
|
||||
<ArrowLeftIcon aria-hidden />Все сегменты
|
||||
</Button>}
|
||||
@@ -341,30 +370,33 @@ export default function IxPage() {
|
||||
{inDetail && selected && <SegmentStatus segment={selected} />}
|
||||
</div>
|
||||
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
|
||||
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
|
||||
</div>
|
||||
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
{inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
|
||||
{(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
|
||||
{selected && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
</div>}
|
||||
{!inDetail && <div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
|
||||
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
|
||||
@@ -391,17 +423,16 @@ export default function IxPage() {
|
||||
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
|
||||
<div className="min-w-0 overflow-x-auto border-b pb-1">
|
||||
<TabsList variant="line" aria-label="Разделы сегмента">
|
||||
<TabsTrigger value="configuration">Конфигурация</TabsTrigger>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="exits">Выходы и резерв</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
|
||||
<TabsTrigger value="changes">План изменений</TabsTrigger>
|
||||
{selected && <>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршрутизация</TabsTrigger>
|
||||
</>}
|
||||
<TabsTrigger value="configuration">Настройки IX</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="configuration" className="grid min-w-0 gap-3">
|
||||
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} backendUrl={backendUrl} segmentId={selected?.id} readOnly={!live || !write || busy}
|
||||
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
|
||||
{advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
|
||||
<FramePanel>
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
@@ -409,7 +440,6 @@ export default function IxPage() {
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
@@ -419,15 +449,11 @@ export default function IxPage() {
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="exits" className="grid min-w-0 gap-3">
|
||||
{selected ? <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy} readOnly={!live || !write || dirty}
|
||||
error={error} save={input => perform(() => stageTransit(input))} configure={() => showTab("configuration")} />
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно добавлять выходы." />}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="routes" className="grid min-w-0 gap-3">
|
||||
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
|
||||
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
|
||||
{selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
|
||||
error={error} save={input => perform(() => stageTransit(input))} />}
|
||||
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
|
||||
{!!selected?.appliedRevision && <>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
@@ -441,21 +467,10 @@ export default function IxPage() {
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
||||
save={input => perform(() => stageClient(input))} revoke={setRevoke}
|
||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
<AlertDialog open={!!revoke} onOpenChange={value => { if (!value) setRevoke(null) }}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Отозвать доступ {revoke?.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>После применения клиент потеряет туннель и маршруты. Остальные подключения останутся в плане.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter><AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => { if (revoke) void perform(() => stageClient(revoke)) }}>Проверить отзыв</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{linuxPath && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
|
||||
@@ -475,17 +490,21 @@ export default function IxPage() {
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
|
||||
? "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
|
||||
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root."
|
||||
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
|
||||
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
|
||||
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
|
||||
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
|
||||
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
|
||||
Скачать {linux.filename}
|
||||
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
|
||||
</Button>
|
||||
{linux.setup && <>
|
||||
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>
|
||||
{linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
|
||||
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
|
||||
linux.filename.replace(/\.conf$/, "-setup.sh")
|
||||
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button>
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
|
||||
</>}
|
||||
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
|
||||
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
|
||||
@@ -495,46 +514,28 @@ export default function IxPage() {
|
||||
</Frame>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Изменения RouterOS</FrameTitle>
|
||||
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
|
||||
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
|
||||
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
|
||||
: <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={!canPlan || busy}
|
||||
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>
|
||||
{error && <Button type="button" size="sm" variant="outline" disabled={!canPlan || busy}
|
||||
onClick={() => void perform(() => prepare(true))}>Сверить и продолжить</Button>}
|
||||
</div>}
|
||||
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
|
||||
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
|
||||
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
|
||||
<RouterOsChanges changes={plan.changes} nodes={nodes} />
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
|
||||
Применить план
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</TabsContent>
|
||||
</Tabs>}
|
||||
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
|
||||
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Подтвердите сохранение</DialogTitle>
|
||||
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
|
||||
</DialogHeader>
|
||||
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
|
||||
<AlertDescription>{reviewError}</AlertDescription></Alert>
|
||||
: plan ? <>
|
||||
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
|
||||
<RouterOsChanges changes={plan.changes} nodes={peers} />
|
||||
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
|
||||
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
|
||||
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
|
||||
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
|
||||
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
</ServerRailLayout>
|
||||
|
||||
@@ -66,8 +66,10 @@ import {
|
||||
hopHasRate,
|
||||
matchNetflowForGreEdge,
|
||||
matchNetflowForWan,
|
||||
type GreNetflowHop,
|
||||
type MatchedNetflowHop,
|
||||
} from "@/lib/map-netflow-hops"
|
||||
import { useMapGreTraffic } from "@/hooks/use-map-gre-traffic"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
@@ -599,19 +601,21 @@ function NetflowRateBadge({
|
||||
mx,
|
||||
my,
|
||||
hop,
|
||||
liveInterface,
|
||||
onOpen,
|
||||
}: {
|
||||
mx: number
|
||||
my: number
|
||||
hop: MatchedNetflowHop
|
||||
hop: Pick<MatchedNetflowHop, "bps" | "bpsFwd" | "bpsRev">
|
||||
liveInterface?: string
|
||||
onOpen?: (e: React.SyntheticEvent<SVGElement>) => void
|
||||
}) {
|
||||
const showDir = hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const showDir = !!liveInterface || hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const bw = showDir ? 86 : 72
|
||||
const bh = showDir ? 32 : 20
|
||||
const bh = liveInterface ? 41 : showDir ? 32 : 20
|
||||
return (
|
||||
<g
|
||||
role={onOpen?"button":undefined} aria-label={onOpen?"Поток NetFlow между узлами":undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
role={onOpen?"button":undefined} aria-label={onOpen ? liveInterface ? "Текущий трафик GRE " + liveInterface : "Поток NetFlow между узлами" : undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
onKeyDown={e=>{if(onOpen&&(e.key==="Enter"||e.key===" ")){e.preventDefault();e.stopPropagation();onOpen(e)}}}
|
||||
transform={`translate(${mx},${my})`}
|
||||
style={{ cursor: onOpen ? "pointer" : "default" }}
|
||||
@@ -619,7 +623,7 @@ function NetflowRateBadge({
|
||||
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
|
||||
>
|
||||
<title>
|
||||
Поток NetFlow между узлами за интервал карты, без overlay/mesh.
|
||||
{liveInterface ? "Текущий RX/TX интерфейса " + liveInterface : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
|
||||
</title>
|
||||
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect
|
||||
@@ -632,14 +636,15 @@ function NetflowRateBadge({
|
||||
stroke="var(--status-online)"
|
||||
strokeWidth="1.15"
|
||||
/>
|
||||
<text textAnchor="middle" y={showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "-8" : showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online-fg)" fontSize="8" fontWeight="700">{formatNetflowRate(hop)}</tspan>
|
||||
</text>
|
||||
{showDir && (
|
||||
<text textAnchor="middle" y="10" fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "4" : "10"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online)" fontSize="6.5" fontWeight="600">{formatNetflowDir(hop)}</tspan>
|
||||
</text>
|
||||
)}
|
||||
{liveInterface && <text textAnchor="middle" y="14" fill="var(--muted-foreground)" fontSize="6.5">Live GRE</text>}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -1630,15 +1635,28 @@ function NetworkMapContent() {
|
||||
}, [greEdges])
|
||||
|
||||
const netflowByGreKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
const m = new Map<string, GreNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
for (const e of greEdges) {
|
||||
const hop = matchNetflowForGreEdge(e, mapHops)
|
||||
if (hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
if (hop && hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
}
|
||||
return m
|
||||
}, [greEdges, mapHops, showNetflow])
|
||||
|
||||
const greTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !showNetflow || (!flowReadAt && !flowError)) return []
|
||||
return greEdges.flatMap(edge => {
|
||||
const edgeId = greEdgeKey(edge)
|
||||
const owner = edge.fromServer.id === edge.tunnel.serverId ? edge.fromServer : edge.toServer
|
||||
return edge.tunnel.enabled && edge.tunnel.status !== "down" && owner.status !== "offline" &&
|
||||
edge.tunnel.name && !netflowByGreKey.get(edgeId)?.exactInterface
|
||||
? [{ edgeId, serverId: owner.id, iface: edge.tunnel.name }]
|
||||
: []
|
||||
})
|
||||
}, [useLiveData, showNetflow, flowReadAt, flowError, greEdges, netflowByGreKey])
|
||||
const getGreLiveRate = useMapGreTraffic(backendUrl, greTrafficTargets)
|
||||
|
||||
const netflowByWanKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
@@ -2183,7 +2201,7 @@ function NetworkMapContent() {
|
||||
<PopoverContent align="start" aria-label="Слои карты" className="gap-0.5">
|
||||
{([
|
||||
{ key: "showPingBadges", label: "Ping-значки", val: showPingBadges, set: setShowPingBadges, hint: "P" },
|
||||
{ key: "showNetflow", label: "NetFlow", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showNetflow", label: "Трафик на линиях", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showServices", label: "Назначения", val: showServices, set: setShowServices, hint: "" },
|
||||
{ key: "showAnimDots", label: "Анимация трафика", val: showAnimDots, set: setShowAnimDots, hint: "" },
|
||||
{ key: "showMinimap", label: "Минимап", val: showMinimap, set: setShowMinimap, hint: "M" },
|
||||
@@ -2335,7 +2353,8 @@ function NetworkMapContent() {
|
||||
tBadge,
|
||||
normalPx,
|
||||
)
|
||||
const flowHop = netflowByGreKey.get(edgeId)
|
||||
const liveRate = getGreLiveRate(edgeId)
|
||||
const flowHop = liveRate ?? netflowByGreKey.get(edgeId)
|
||||
const flowPos = edgeBadgePosition(
|
||||
e.from.x,
|
||||
e.from.y,
|
||||
@@ -2364,7 +2383,7 @@ function NetworkMapContent() {
|
||||
strokeWidth={
|
||||
highlightedPath && greMatchesPath(e, highlightedPath)
|
||||
? 3.4
|
||||
: hopHasRate(flowHop) ? 2.6 : 1.5
|
||||
: flowHop && flowHop.bps > 0 ? 2.6 : 1.5
|
||||
}
|
||||
strokeDasharray={e.tunnel.ipsec ? "7 4" : "none"}
|
||||
opacity={ts.opacity}
|
||||
@@ -2400,11 +2419,12 @@ function NetworkMapContent() {
|
||||
outerSummary={greOuterSummaryLine(e.tunnel, fromN, toN, greResolvedMap)}
|
||||
/>
|
||||
)}
|
||||
{showNetflow && hopHasRate(flowHop) && (
|
||||
{showNetflow && flowHop && (
|
||||
<NetflowRateBadge
|
||||
mx={flowPos.mx}
|
||||
my={flowPos.my}
|
||||
hop={flowHop}
|
||||
liveInterface={liveRate ? e.tunnel.name : undefined}
|
||||
onOpen={openGreDetail}
|
||||
/>
|
||||
)}
|
||||
@@ -2881,7 +2901,10 @@ function NetworkMapContent() {
|
||||
{(() => {
|
||||
const edge = selectedGreEdge
|
||||
const t = edge.tunnel
|
||||
const tunnelOwner = edge.fromServer.id === t.serverId ? edge.fromServer : edge.toServer
|
||||
const selectedEdgeId = greEdgeKey(edge)
|
||||
const liveRate = getGreLiveRate(selectedEdgeId)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(selectedEdgeId)
|
||||
const localWanName = ifaceNameForGreOuterIp(edge.fromServer, t.localAddress, greResolvedMap)
|
||||
const remoteWanName = ifaceNameForGreOuterIp(edge.toServer, t.remoteAddress, greResolvedMap)
|
||||
const baseProbe = greTunnelProbe(t,!useLiveData)
|
||||
@@ -2945,15 +2968,11 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Поток (NetFlow)</span>
|
||||
<span className="text-xs text-muted-foreground">{liveRate ? "Текущий RX/TX GRE" : "Поток (NetFlow)"}</span>
|
||||
<span className="text-xs font-mono font-semibold text-emerald-400">
|
||||
{(() => {
|
||||
const hop = netflowByGreKey.get(selectedEdgeId)
|
||||
if (!hopHasRate(hop)) return "—"
|
||||
return hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
? formatNetflowDir(hop)
|
||||
: formatNetflowRate(hop)
|
||||
})()}
|
||||
{greFlow ? liveRate || greFlow.bpsFwd > 0 && greFlow.bpsRev > 0
|
||||
? formatNetflowDir(greFlow)
|
||||
: formatNetflowRate(greFlow) : "—"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground pt-2 leading-snug">
|
||||
@@ -2961,7 +2980,7 @@ function NetworkMapContent() {
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
Поток по данным NetFlow за {mapWindowSec / 60} мин, без overlay/mesh.
|
||||
{liveRate ? "Текущий трафик по счётчикам интерфейса RouterOS." : `Поток по данным NetFlow за ${mapWindowSec / 60} мин, без overlay/mesh.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2973,7 +2992,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">На узле</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{edge.fromServer.name}</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{tunnelOwner.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Пир (каталог)</span>
|
||||
@@ -3415,11 +3434,12 @@ function NetworkMapContent() {
|
||||
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
|
||||
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
|
||||
const pc = pingColor(merged.pingMs)
|
||||
const greFlow = netflowByGreKey.get(tunnelPanelKey)
|
||||
const liveRate = getGreLiveRate(tunnelPanelKey)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(tunnelPanelKey)
|
||||
const showMetrics =
|
||||
merged.pingMs != null ||
|
||||
(merged.dlMbps != null && merged.ulMbps != null) ||
|
||||
hopHasRate(greFlow)
|
||||
!!greFlow
|
||||
return (
|
||||
<div key={tunnelPanelKey} className="rounded-md border border-border/60 px-3 py-2 bg-muted/20">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
@@ -3459,9 +3479,9 @@ function NetworkMapContent() {
|
||||
↓{merged.dlMbps} ↑{merged.ulMbps}
|
||||
</span>
|
||||
)}
|
||||
{hopHasRate(greFlow) && (
|
||||
{greFlow && (
|
||||
<span className="text-[9px] ml-1.5 text-emerald-400">
|
||||
{formatNetflowRate(greFlow)}
|
||||
{formatNetflowRate(greFlow)}{liveRate ? " · Live GRE" : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -1120,7 +1120,7 @@
|
||||
"operations": [
|
||||
"traffic.live.read"
|
||||
],
|
||||
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом."
|
||||
"reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
@@ -1637,14 +1637,14 @@
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Мастер WebUI подготавливает черновик подключения Linux. Записи на RouterOS идут после отдельного подтверждения плана."
|
||||
"reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/credential",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Действующий PSK выдаётся оператору WebUI с правом изменения сети и записью в журнале. Инструменты MCP не получают секрет."
|
||||
"reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID } from "node:crypto"
|
||||
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer } from "node:http"
|
||||
import { tmpdir } from "node:os"
|
||||
@@ -49,11 +49,21 @@ const router = createServer(async (request, response) => {
|
||||
const list = rows[path] ??= []
|
||||
const index = list.findIndex(entry => entry[".id"] === place)
|
||||
list.splice(index < 0 ? list.length : index, 0, row)
|
||||
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
|
||||
if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
|
||||
rows["/interface"].push({ ".id": row[".id"], name: row.name,
|
||||
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
|
||||
}
|
||||
result = row
|
||||
} else if (request.method === "PATCH") {
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
|
||||
const row = rows[parent]?.find(entry => entry[".id"] === id)
|
||||
assert(row)
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
Object.assign(row, JSON.parse(raw))
|
||||
writes++
|
||||
result = row
|
||||
} else if (request.method === "DELETE") {
|
||||
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
@@ -157,6 +167,7 @@ try {
|
||||
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
|
||||
assert.match(wg.template, /Table = off/)
|
||||
assert(!wg.template.includes("A".repeat(43)))
|
||||
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
|
||||
const gre = await linux("gre-client")
|
||||
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
|
||||
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
|
||||
@@ -250,7 +261,7 @@ try {
|
||||
}
|
||||
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
|
||||
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "changes.apply", "operations.read"] } })
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
|
||||
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
|
||||
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
|
||||
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
|
||||
@@ -275,9 +286,145 @@ try {
|
||||
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal(deletes, writes)
|
||||
|
||||
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
|
||||
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
|
||||
] } }, 200)).segment
|
||||
const managedPath = "/" + managed.id
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
;(rows["/ip/address"] ??= []).push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
|
||||
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
||||
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
||||
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
|
||||
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
|
||||
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
|
||||
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
|
||||
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
|
||||
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
|
||||
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
|
||||
assert.ok(privateKey)
|
||||
const scalar = Buffer.from(privateKey, "base64")
|
||||
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
|
||||
format: "der", type: "pkcs8" })
|
||||
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
|
||||
assert.equal(publicKey, provision.peerPublicKey)
|
||||
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
|
||||
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
|
||||
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
|
||||
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
|
||||
}), { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(templateResponse.status, 200)
|
||||
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
|
||||
|
||||
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
|
||||
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
|
||||
assert.equal(exportPlan.state, "awaiting-approval")
|
||||
assert(!JSON.stringify(exportPlan).includes(privateKey))
|
||||
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
|
||||
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
|
||||
let exported = exportOperation
|
||||
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
|
||||
await delay(200)
|
||||
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
|
||||
}
|
||||
assert.equal(exported.state, "applied", JSON.stringify(exported))
|
||||
assert(!JSON.stringify(exported).includes(privateKey))
|
||||
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
|
||||
assert.equal(receipt.humanDownloadOnly, true)
|
||||
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
|
||||
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
|
||||
[exported.id, exportPlan.planId, receipt.artifactId])
|
||||
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
|
||||
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(download.status, 200)
|
||||
assert.equal(await download.text(), credential.template)
|
||||
assert.equal(download.headers.get("cache-control"), "private, no-store")
|
||||
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
|
||||
assert.equal(denied.status, 403)
|
||||
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
|
||||
appliedPeer.disabled = "true"
|
||||
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(inactive.status, 409)
|
||||
delete appliedPeer.disabled
|
||||
|
||||
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
|
||||
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
|
||||
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
|
||||
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
|
||||
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
|
||||
assert.deepEqual(noChanges.changes, [])
|
||||
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
|
||||
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
|
||||
const bindings = paired.segment.configuration.sites[0].interfaces
|
||||
const [wireguard, greBinding] = bindings
|
||||
assert.ok(wireguard.linux.clientId)
|
||||
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
|
||||
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
|
||||
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
|
||||
gateway: "10.254.0.2%" + clientKey.interfaceName }
|
||||
rows["/ip/route"].push(foreignRoute)
|
||||
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
|
||||
assert.match(blockedForeign.error, /другой маршрутизацией/)
|
||||
assert.equal(rows["/ip/route"].pop(), foreignRoute)
|
||||
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
|
||||
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
|
||||
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
|
||||
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
|
||||
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
|
||||
const greCredential = await post(managedPath + "/linux/credential",
|
||||
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
|
||||
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
|
||||
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
|
||||
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
|
||||
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
|
||||
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
|
||||
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
|
||||
|
||||
const { rows: [exit] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
|
||||
const appliedRevision = pairedApplied.segment.revision
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
|
||||
const beforeStage = writes
|
||||
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
|
||||
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
|
||||
assert.equal(writes, beforeStage)
|
||||
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
|
||||
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
|
||||
const remoteSite = stagedRemote.segment.configuration.sites[0]
|
||||
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
|
||||
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
|
||||
assert.equal(transitBinding.peerServerId, Number(exit.id))
|
||||
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
|
||||
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
|
||||
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
|
||||
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
|
||||
assert.equal(writes, beforeStage)
|
||||
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
|
||||
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
|
||||
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
|
||||
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
|
||||
assert.ok(added[0].linux.clientId)
|
||||
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
|
||||
|
||||
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
|
||||
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions, mcpRemovalVerified: true }))
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true }))
|
||||
} finally {
|
||||
await mcp?.close()
|
||||
await app?.close()
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { fingerprint, accessGeneration, McpError } from "./security.js"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
export function registerWireguardExportActions(register: typeof add) {
|
||||
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
|
||||
},
|
||||
})
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}),
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
|
||||
prepare:async(input,context)=>{
|
||||
const request=wireguardExportRequestSchema.parse(input)
|
||||
const request=mcpWireguardExportRequestSchema.parse(input)
|
||||
const authorize=async()=>{
|
||||
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
|
||||
const fresh=await effectiveMcpConnection(context.principal)
|
||||
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
await authorize()
|
||||
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
|
||||
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
|
||||
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
warnings: request.ixSegmentId ? [
|
||||
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
|
||||
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
|
||||
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
||||
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
||||
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
|
||||
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
|
||||
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict()
|
||||
export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
|
||||
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
|
||||
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
|
||||
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
|
||||
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
|
||||
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
|
||||
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
|
||||
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
|
||||
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
const protections=await protectionProof(authority)
|
||||
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{
|
||||
const check = async () => {
|
||||
signal?.throwIfAborted()
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
|
||||
} })
|
||||
}
|
||||
const { ixSegmentId, ...request } = authority.request
|
||||
if (ixSegmentId) {
|
||||
await check()
|
||||
const segment = await readIxSegment(ixSegmentId)
|
||||
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
|
||||
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
||||
throw error
|
||||
})
|
||||
await check()
|
||||
const proof = await sign({ protections, ixSegmentId, request, access })
|
||||
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
|
||||
}
|
||||
const source=await readWireguardExport(request, { signal, authorize: check })
|
||||
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
|
||||
}
|
||||
|
||||
|
||||
@@ -110,7 +110,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const { configuration, interfaceName } = await configureIxLinuxClient(current, input)
|
||||
const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
|
||||
...input.transit, revision: input.revision, serverId: input.serverId,
|
||||
}) } : current
|
||||
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
|
||||
...input, exit: input.transit?.name ?? input.exit,
|
||||
})
|
||||
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment, interfaceName }
|
||||
}, { waitMs: 5000 })
|
||||
|
||||
@@ -106,7 +106,11 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
signal?.throwIfAborted()
|
||||
const row = await getEnabledServerById(id)
|
||||
@@ -117,11 +121,30 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
|
||||
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
|
||||
if (reply.raw.destroyed) return
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
return
|
||||
} finally {
|
||||
reply.raw.off("close", onClose)
|
||||
}
|
||||
}
|
||||
reply.raw.on("close", onClose)
|
||||
|
||||
reply.hijack()
|
||||
@@ -144,17 +167,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
reply.raw.writeHead(200, sseHeaders)
|
||||
reply.raw.write(":\n\n")
|
||||
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
|
||||
try {
|
||||
while (!abort.signal.aborted) {
|
||||
try {
|
||||
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => {
|
||||
const current = await readServer(server.id, abort.signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const sample = await readSample(abort.signal)
|
||||
if (abort.signal.aborted) break
|
||||
writeSse(reply.raw, "sample", sample)
|
||||
} catch (error) {
|
||||
|
||||
@@ -16,7 +16,7 @@ export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, bi
|
||||
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
|
||||
}
|
||||
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
|
||||
const config = binding.provisionWireguard
|
||||
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
|
||||
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
|
||||
@@ -28,7 +28,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
return [
|
||||
"[Interface]",
|
||||
"Address = " + address(config.peerAddress),
|
||||
"PrivateKey = <локальный_приватный_ключ>",
|
||||
"PrivateKey = " + privateKey,
|
||||
binding.linux ? "Table = auto" : "Table = off",
|
||||
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
|
||||
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
@@ -55,13 +55,23 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
const tunnel = binding.provisionGre
|
||||
const family = tunnel ? isIP(tunnel.peerAddress) : 4
|
||||
const protocol = "ip -" + family
|
||||
const local = tunnel?.localAddress.split("/")[0]
|
||||
const table = 30000 + parseInt(id.slice(-4), 16)
|
||||
const management = 10000 + parseInt(id.slice(-3), 16)
|
||||
const management = 12000 + 2 * parseInt(id.slice(-3), 16)
|
||||
const managementRules = [
|
||||
["ip -4", "to " + hub + "/32 lookup main"],
|
||||
["ip -4", "from " + client + "/32 lookup main"],
|
||||
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
|
||||
]
|
||||
const greParameters = id + " mode gre local " + client + " remote " + hub
|
||||
const common = [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id + " --timeout 20",
|
||||
"ip tunnel add " + greParameters,
|
||||
]
|
||||
return {
|
||||
filename: id + ".conf",
|
||||
template: [
|
||||
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
|
||||
...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
|
||||
"connections {",
|
||||
" " + id + " {",
|
||||
" version = 2",
|
||||
@@ -97,28 +107,36 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
setup: [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id,
|
||||
"# Создайте GRE после успешного установления IPsec.",
|
||||
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
|
||||
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id :
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
setup: (tunnel ? [
|
||||
'conf="$(dirname -- "$0")/' + id + '.conf"',
|
||||
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
|
||||
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
|
||||
'install -d -m 0700 /etc/swanctl/conf.d',
|
||||
'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
|
||||
"cleanup() {",
|
||||
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
|
||||
" ip link del dev " + id + " 2>/dev/null || :",
|
||||
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
|
||||
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
|
||||
"}",
|
||||
"trap cleanup 0",
|
||||
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
|
||||
...common,
|
||||
"ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id,
|
||||
"ip link set " + id + " up",
|
||||
...[...new Set([
|
||||
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
|
||||
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
|
||||
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
|
||||
...(binding.linux?.exit ? ["default"] : []),
|
||||
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"trap - 0",
|
||||
] : [
|
||||
...common,
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
"ip link set " + id + " up",
|
||||
...(tunnel ? [
|
||||
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
|
||||
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
|
||||
...(binding.linux?.exit ? [
|
||||
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
|
||||
...(family === 4 ? [
|
||||
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
|
||||
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
|
||||
] : []),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
|
||||
] : []),
|
||||
] : []),
|
||||
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
|
||||
].join("\n"),
|
||||
]).join("\n"),
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,23 @@ interface IxNativeChange {
|
||||
tasks: Task[]
|
||||
}
|
||||
|
||||
function wireguardKeys(seed: string) {
|
||||
const scalar = Buffer.from(seed, "hex")
|
||||
scalar[0] &= 248
|
||||
scalar[31] = (scalar[31] & 127) | 64
|
||||
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
|
||||
const key = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
|
||||
return {
|
||||
privateKey: scalar.toString("base64"),
|
||||
publicKey: createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64"),
|
||||
}
|
||||
}
|
||||
|
||||
async function ixLinuxWireguardKeys(segmentId: string, serverId: number, name: string, credentialId: string, create = false) {
|
||||
const derive = await (create ? privateFingerprinter : privateFingerprinterExisting)("ix-linux-wireguard-credential-v1")
|
||||
return wireguardKeys(derive([segmentId, serverId, name, credentialId].join(":")))
|
||||
}
|
||||
|
||||
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
|
||||
|
||||
const routerId = /^\*[a-z\d]+$/i
|
||||
@@ -243,6 +260,38 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
|
||||
}
|
||||
|
||||
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
|
||||
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
|
||||
}
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
|
||||
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
|
||||
const existingId = companion ? companion.linux?.clientId : undefined
|
||||
if (companion && (companion.kind === input.kind || existingId &&
|
||||
site?.interfaces.some(binding => binding.linux?.clientId === existingId && binding.kind === input.kind))) {
|
||||
throw new IxConflict("Этот протокол уже подключён для клиента")
|
||||
}
|
||||
const name = companion ? companion.linux!.name : input.name
|
||||
const first = await configureIxLinuxTunnel(segment, { ...input, name })
|
||||
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
|
||||
...input, kind: "gre-ipsec", localAddress: undefined, peerAddress: undefined, peerPublicKey: undefined, prefixes: [],
|
||||
}) : undefined
|
||||
const result = second ?? first
|
||||
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
|
||||
const clientId = existingId ?? currentId ?? (companion || second ? randomUUID() : undefined)
|
||||
if (!clientId) return result
|
||||
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
|
||||
return { interfaceName: first.interfaceName, configuration: {
|
||||
...result.configuration,
|
||||
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
|
||||
...site, interfaces: site.interfaces.map(binding =>
|
||||
binding.linux && (siblings.has(binding.name) || binding.linux.clientId === clientId)
|
||||
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
|
||||
}),
|
||||
} }
|
||||
}
|
||||
|
||||
async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
|
||||
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
|
||||
@@ -256,7 +305,7 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
|
||||
if (!localAddress && !peerAddress) {
|
||||
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
|
||||
.concat(segment.configuration.sites.filter(candidate => candidate !== site).flatMap(candidate => candidate.interfaces))
|
||||
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
|
||||
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
|
||||
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
|
||||
for (let index = 0; index < 65536; index += 4) {
|
||||
@@ -269,7 +318,14 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
}
|
||||
}
|
||||
if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400)
|
||||
const ports = new Set([...inventory.wireguardPorts, ...reserved.map(binding => binding.provisionWireguard?.listenPort)])
|
||||
const ports = new Set(inventory.wireguardPorts)
|
||||
for (const binding of [...reserved, ...site.interfaces]) {
|
||||
if (binding.provisionWireguard) ports.add(binding.provisionWireguard.listenPort)
|
||||
if (binding.provisionTransit) {
|
||||
ports.add(binding.provisionTransit.localPort)
|
||||
ports.add(binding.provisionTransit.remotePort)
|
||||
}
|
||||
}
|
||||
let listenPort = 51820
|
||||
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
|
||||
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
|
||||
@@ -289,13 +345,19 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
}
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
}
|
||||
if (input.kind === "wireguard") {
|
||||
const publicKey = input.peerPublicKey ?? previous?.provisionWireguard?.peerPublicKey
|
||||
if (!publicKey || !previous?.provisionWireguard && listenPort > 65535) throw new IxConflict("Нужен публичный ключ и свободный порт WireGuard", 400)
|
||||
binding.provisionWireguard = { peerPublicKey: publicKey, listenPort: previous?.provisionWireguard?.listenPort ?? listenPort,
|
||||
const existing = previous?.provisionWireguard
|
||||
if (!existing && listenPort > 65535) throw new IxConflict("Нет свободного порта WireGuard", 400)
|
||||
let peerPublicKey = input.peerPublicKey ?? existing?.peerPublicKey
|
||||
let credentialId = peerPublicKey === existing?.peerPublicKey ? existing?.credentialId : undefined
|
||||
if (!peerPublicKey) {
|
||||
credentialId = randomUUID()
|
||||
peerPublicKey = (await ixLinuxWireguardKeys(segment.id, site.serverId, name, credentialId, true)).publicKey
|
||||
}
|
||||
binding.provisionWireguard = { peerPublicKey, credentialId, listenPort: existing?.listenPort ?? listenPort,
|
||||
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
|
||||
} else {
|
||||
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
|
||||
@@ -410,12 +472,25 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
|
||||
return gre
|
||||
}
|
||||
|
||||
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
|
||||
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
|
||||
for (const site of configuration.sites) {
|
||||
const device = devices.find(entry => entry.serverId === site.serverId)!
|
||||
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
|
||||
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
|
||||
}
|
||||
// Активация WAN-выхода создаёт в main обратный маршрут через клиентский туннель.
|
||||
const ownedMainRoutes = new Map<string, IxRouterObject[]>()
|
||||
for (const object of knownObjects) {
|
||||
if (object.serverId !== site.serverId || !["/ip/route", "/ipv6/route"].includes(object.path) || object.fields["routing-table"] !== "main") continue
|
||||
const key = objectMarker(object)
|
||||
const known = ownedMainRoutes.get(key) ?? []
|
||||
known.push(object)
|
||||
ownedMainRoutes.set(key, known)
|
||||
}
|
||||
const foreignMainRoutes = ["/ip/route", "/ipv6/route"].flatMap(path => rowsFor(device, path).filter(row => {
|
||||
if (row["routing-table"] !== "main" || isTrue(row.dynamic)) return false
|
||||
return !ownedMainRoutes.get(marker(path, row.comment ?? ""))?.some(known => matches(row, known.fields))
|
||||
}))
|
||||
for (const binding of site.interfaces) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
|
||||
@@ -433,8 +508,8 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
|
||||
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
|
||||
}
|
||||
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
|
||||
const mainRoutes = [...rowsFor(device, "/ip/route"), ...rowsFor(device, "/ipv6/route")].filter(row => row["routing-table"] === "main" && !isTrue(row.dynamic))
|
||||
if (foreignVrf || mainRoutes.some(row => row.gateway === binding.name || row.gateway?.includes("%" + binding.name))) {
|
||||
if (foreignVrf || foreignMainRoutes.some(row => row.gateway?.split(",").some(gateway =>
|
||||
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
|
||||
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
|
||||
}
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
@@ -473,20 +548,22 @@ async function resolveIxCredentials(id: string, objects: IxRouterObject[], exist
|
||||
if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)]
|
||||
if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) {
|
||||
const [, variant, version, side] = value.split(":")
|
||||
const raw = Buffer.from(wg([id, version, side].join(":")), "hex")
|
||||
const scalar = Buffer.from(raw)
|
||||
scalar[0] &= 248
|
||||
scalar[31] = (scalar[31] & 127) | 64
|
||||
if (variant === "private") return [name, scalar.toString("base64")]
|
||||
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
|
||||
const privateKey = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
|
||||
return [name, createPublicKey(privateKey).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")]
|
||||
const keys = wireguardKeys(wg([id, version, side].join(":")))
|
||||
return [name, variant === "private" ? keys.privateKey : keys.publicKey]
|
||||
}
|
||||
return [name, value]
|
||||
})) }))
|
||||
}
|
||||
|
||||
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
|
||||
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!wg?.credentialId) continue
|
||||
const keys = await ixLinuxWireguardKeys(id, site.serverId, binding.name, wg.credentialId)
|
||||
if (!binding.linux || !constantEqual(keys.publicKey, wg.peerPublicKey)) {
|
||||
throw new IxConflict("Ключ WireGuard не соответствует управляемому клиенту IX")
|
||||
}
|
||||
}
|
||||
const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : []
|
||||
const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : []
|
||||
const before: NativeDevice[] = []
|
||||
@@ -503,7 +580,7 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
|
||||
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
|
||||
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
|
||||
}
|
||||
if (configuration) validateBindings(configuration, id, before)
|
||||
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
|
||||
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
|
||||
for (const old of previousConfiguration?.sites ?? []) {
|
||||
const next = configuration?.sites.find(site => site.serverId === old.serverId)
|
||||
@@ -660,6 +737,7 @@ export async function listIxLinuxClients(segment: IxSegment) {
|
||||
const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId)
|
||||
const items: IxLinuxBinding[] = bindings.map(binding => ({
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!,
|
||||
...(binding.provisionWireguard?.credentialId && { managedWireguard: true }),
|
||||
...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }),
|
||||
}))
|
||||
if (!bindings.some(binding => binding.linux?.enabled)) return items
|
||||
@@ -715,7 +793,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
|
||||
})) }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential = false): Promise<IxLinuxAccess> {
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
|
||||
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const site = configuration.sites.find(site => site.serverId === serverId)
|
||||
@@ -723,6 +801,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
|
||||
if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно")
|
||||
if (includeCredential === "wireguard" && binding.kind !== "wireguard") throw new IxConflict("Для скачивания выберите клиента WireGuard", 404)
|
||||
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
|
||||
const clientInfo = {
|
||||
revision: segment.appliedRevision,
|
||||
@@ -749,7 +828,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
|
||||
}
|
||||
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "comment", "disabled"])
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
|
||||
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
|
||||
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
|
||||
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
|
||||
@@ -760,11 +839,22 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
|
||||
: configuration.sites.flatMap(entry => entry.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
let privateKey: string | undefined
|
||||
if (includeCredential) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!binding.linux || !wg?.credentialId) throw new IxConflict("Этот клиент использует собственный ключ WireGuard", 404)
|
||||
const keys = await ixLinuxWireguardKeys(segment.id, serverId, name, wg.credentialId)
|
||||
if (Number(iface?.["listen-port"]) !== wg.listenPort || !constantEqual(keys.publicKey, wg.peerPublicKey) ||
|
||||
(await readIxSegment(segment.id))?.appliedRevision !== segment.appliedRevision) {
|
||||
throw new IxConflict("Действующие параметры WireGuard не совпали с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
privateKey = keys.privateKey
|
||||
}
|
||||
return {
|
||||
...clientInfo,
|
||||
kind: "wireguard",
|
||||
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes),
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ export async function ixReservedTunnelBindings(serverId: number) {
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
`, [serverId])
|
||||
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
|
||||
.filter(site => site.serverId === serverId).flatMap(site => site.interfaces))
|
||||
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
|
||||
}
|
||||
|
||||
export function nextIxRouterId(used: ReadonlySet<string>) {
|
||||
|
||||
@@ -38,6 +38,19 @@ else {
|
||||
try {
|
||||
await initDatabase();await app.listen({host:"127.0.0.1",port:0})
|
||||
serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password,updated_at) VALUES($1,'127.0.0.1',$2,false,true,'fixture','fixture',$3) RETURNING id",[prefix+"server",address.port,new Date(Date.now()-3_600_000).toISOString()])).rows[0].id)
|
||||
const sampleUrl = `/traffic/servers/${serverId}/live?once=1`
|
||||
const beforeSample = nativeRequests
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1,ether2")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample)
|
||||
const sample = await app.inject(sampleUrl + "&iface=ether1")
|
||||
assert.equal(sample.statusCode, 200)
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
+9
-7
@@ -55,12 +55,14 @@
|
||||
|
||||
### Доступ конечных Linux-серверов
|
||||
|
||||
1. На вкладке **Linux-клиенты** нажмите **Подключить Linux**. Выберите транспорт, права на сети и выход. Адреса IPv4 внутри туннеля и порт WireGuard выделяются автоматически. Для ручного назначения IPv4 или IPv6 откройте параметры адресов туннеля.
|
||||
2. Нажмите **Подготовить доступ** и примените план. Скачайте файлы из применённой ревизии по кнопке **Конфиг Linux**.
|
||||
3. В карточке **Доступ и выход** можно сменить политику или приостановить подключение. Действие **Отозвать** удаляет управляемые объекты клиента после проверки плана.
|
||||
1. Откройте сегмент IX и нажмите **Подключить Linux**. Выберите транспорт и выход VPS. **Только разрешённые сети** направляет в туннель выбранные префиксы, **Интернет с этого IX** выводит трафик через его WAN. Для удалённого выхода выберите конкретный ExitNode или другой IX. Менеджер использует подходящий настроенный выход либо подготовит транзит вместе с клиентом.
|
||||
2. Нажмите **Сохранить**. В окне подтверждения проверьте узлы и изменения RouterOS, затем нажмите **Подтвердить**. Кнопка **Конфиг Linux** в строке клиента выдаёт файлы из применённой ревизии. Отмена до подтверждения оставляет изменения в черновике. Его можно открыть той же кнопкой **Сохранить**.
|
||||
3. В строке клиента нажмите на название выхода, чтобы сменить маршрут или приостановить доступ. В меню действий **Проверить путь** показывает фактический шлюз, а **Отозвать доступ** удаляет клиентское подключение после подтверждения. Во вкладке **Маршрутизация** можно настроить общие выходы и резерв, интерфейсы CHR, статические маршруты и BGP.
|
||||
|
||||
- **WireGuard.** Создайте пару ключей на Linux и вставьте публичный ключ. Подставьте приватный ключ в скачанный файл и поднимите соединение через `wg-quick`. Указанный внешний IP Linux используется в конфиге для сохранения исходного пути управления при полном туннеле.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
|
||||
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
|
||||
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
|
||||
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании или выберите **Добавить другой протокол** в действиях клиента. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
|
||||
|
||||
### Выход и резерв
|
||||
|
||||
@@ -68,9 +70,9 @@
|
||||
|
||||
При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux.
|
||||
|
||||
Если операция оборвалась после записи части объектов, откройте **План изменений** для текущей ревизии и выберите **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
|
||||
Если операция оборвалась после записи части объектов, нажмите **Сохранить** для текущей ревизии. Если обычное сравнение выявит частично применённые изменения, выберите в окне **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
|
||||
|
||||
На изолированном стенде с двумя CHR RouterOS 7.24.5 проверены скачанные конфигурации WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания.
|
||||
До автоматической выдачи ключей на изолированном стенде с двумя CHR RouterOS 7.24.5 проверены WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. Автоматическая выдача WireGuard проверена через REST и MCP с временной PostgreSQL и имитацией RouterOS.
|
||||
|
||||
### Удаление сегмента
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface GreTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: GreTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
|
||||
try {
|
||||
const query = new URLSearchParams({ iface, once: "1" })
|
||||
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
if (isTrafficLiveSample(sample)) {
|
||||
const bpsFwd = sample.rxMbps * 1_000_000
|
||||
const bpsRev = sample.txMbps * 1_000_000
|
||||
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
|
||||
}
|
||||
} catch {
|
||||
// One unavailable interface cannot hide readings on other links.
|
||||
}
|
||||
return { edgeId }
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,14 @@ export interface TrafficLiveSample {
|
||||
timestampKind?: "backend-receipt"
|
||||
}
|
||||
|
||||
export function isTrafficLiveSample(value: unknown): value is TrafficLiveSample {
|
||||
const sample = value as Partial<TrafficLiveSample> | null
|
||||
return !!sample && typeof sample.rxMbps === "number" && Number.isFinite(sample.rxMbps) && sample.rxMbps >= 0 &&
|
||||
typeof sample.txMbps === "number" && Number.isFinite(sample.txMbps) && sample.txMbps >= 0 &&
|
||||
typeof sample.at === "string" && Number.isFinite(Date.parse(sample.at)) &&
|
||||
(sample.timestampKind === undefined || sample.timestampKind === "backend-receipt")
|
||||
}
|
||||
|
||||
function parseSseBlock(block: string): { event: string; data: string } {
|
||||
let event = "message"
|
||||
const dataLines: string[] = []
|
||||
@@ -90,8 +98,8 @@ export function useTrafficLive(opts: {
|
||||
if (!raw.trim()) continue
|
||||
const ev = parseSseBlock(raw)
|
||||
if (ev.event === "sample" && ev.data) {
|
||||
const parsed = JSON.parse(ev.data) as TrafficLiveSample
|
||||
if (!parsed || !Number.isFinite(parsed.rxMbps) || !Number.isFinite(parsed.txMbps) || parsed.rxMbps < 0 || parsed.txMbps < 0 || typeof parsed.at !== "string" || !Number.isFinite(Date.parse(parsed.at)) || parsed.timestampKind !== undefined && parsed.timestampKind !== "backend-receipt") {
|
||||
const parsed: unknown = JSON.parse(ev.data)
|
||||
if (!isTrafficLiveSample(parsed)) {
|
||||
throw new Error("Некорректные данные live-потока")
|
||||
}
|
||||
awaitSample()
|
||||
|
||||
+20
-20
@@ -8,6 +8,10 @@ export interface MatchedNetflowHop {
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface GreNetflowHop extends MatchedNetflowHop {
|
||||
exactInterface: boolean
|
||||
}
|
||||
|
||||
function ifaceNorm(s: string | undefined): string {
|
||||
return (s ?? "").trim().toLowerCase()
|
||||
}
|
||||
@@ -40,45 +44,41 @@ export function hopHasRate(h: MatchedNetflowHop | undefined): h is MatchedNetflo
|
||||
return h != null && Number.isFinite(h.bps) && h.bps > 0
|
||||
}
|
||||
|
||||
export function formatNetflowRate(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowRate<T extends Pick<MatchedNetflowHop, "bps">>(hop: T): string {
|
||||
return fmtRate(hop.bps / 1_000_000)
|
||||
}
|
||||
|
||||
export function formatNetflowDir(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev">): string {
|
||||
return `↓${fmtRate(hop.bpsFwd / 1_000_000)} ↑${fmtRate(hop.bpsRev / 1_000_000)}`
|
||||
}
|
||||
|
||||
/** GRE: сначала имя интерфейса туннеля на любом конце, иначе пара узлов. */
|
||||
/** Собственный интерфейс GRE даёт точную привязку, совпадение пары узлов — только оценку. */
|
||||
export function matchNetflowForGreEdge(
|
||||
edge: {
|
||||
tunnel: { name: string }
|
||||
tunnel: { name: string; serverId: string }
|
||||
fromServer: { id: string }
|
||||
toServer: { id: string }
|
||||
},
|
||||
hops: FlowMapHop[],
|
||||
): MatchedNetflowHop | undefined {
|
||||
): GreNetflowHop | undefined {
|
||||
const name = ifaceNorm(edge.tunnel.name)
|
||||
const fromId = String(edge.fromServer.id)
|
||||
const toId = String(edge.toServer.id)
|
||||
if (name) {
|
||||
const ifaceHits = hops.filter((h) =>
|
||||
h.kind === "iface"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId),
|
||||
)
|
||||
if (ifaceHits.length) return mergeDirected(ifaceHits, fromId)
|
||||
const greNamed = hops.filter((h) =>
|
||||
h.kind === "gre"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId || h.toId === fromId || h.toId === toId),
|
||||
)
|
||||
if (greNamed.length) return mergeDirected(greNamed, fromId)
|
||||
}
|
||||
const ownerId = edge.tunnel.serverId
|
||||
const peerId = ownerId === fromId ? toId : fromId
|
||||
const want = pairKey(fromId, toId)
|
||||
if (name) {
|
||||
const local = hops.filter((h) => h.kind === "iface" && h.fromId === ownerId && ifaceNorm(h.iface) === name)
|
||||
if (local.length) return { ...mergeDirected(local, fromId), exactInterface: true }
|
||||
const named = hops.filter((h) =>
|
||||
h.kind === "gre" && h.fromId === ownerId && h.toId === peerId && ifaceNorm(h.iface) === name,
|
||||
)
|
||||
if (named.length) return { ...mergeDirected(named, fromId), exactInterface: true }
|
||||
}
|
||||
const pairHits = hops.filter((h) =>
|
||||
h.kind === "gre" && Boolean(h.toId) && pairKey(h.fromId, h.toId) === want,
|
||||
)
|
||||
if (pairHits.length) return mergeDirected(pairHits, fromId)
|
||||
if (pairHits.length) return { ...mergeDirected(pairHits, fromId), exactInterface: false }
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ const group = z.object({
|
||||
|
||||
const wireguardProvision = z.object({
|
||||
peerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/),
|
||||
credentialId: z.string().uuid().optional(),
|
||||
listenPort: z.number().int().min(1).max(65535),
|
||||
localAddress: prefix,
|
||||
peerAddress: address,
|
||||
@@ -42,6 +43,7 @@ const greProvision = z.object({
|
||||
|
||||
const linuxPolicy = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
clientId: z.string().uuid().optional(),
|
||||
enabled: z.boolean(),
|
||||
destinations: z.array(prefix).max(64),
|
||||
exit: key.optional(),
|
||||
@@ -122,6 +124,15 @@ export type IxSite = z.infer<typeof site>
|
||||
export type IxConfiguration = z.infer<typeof ixSegmentConfigurationSchema>
|
||||
export type IxChange = z.infer<typeof ixChangeSchema>
|
||||
|
||||
const ixTransitOptions = z.object({
|
||||
targetServerId: serverId,
|
||||
name: key,
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
family: z.union([z.literal(4), z.literal(6)]).default(4),
|
||||
probe: address.optional(),
|
||||
}).strict()
|
||||
|
||||
export const ixLinuxClientRequest = z.object({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
@@ -129,6 +140,8 @@ export const ixLinuxClientRequest = z.object({
|
||||
name: linuxPolicy.shape.name,
|
||||
enabled: z.boolean().default(true),
|
||||
kind: z.enum(["wireguard", "gre-ipsec"]),
|
||||
additionalGre: z.boolean().optional(),
|
||||
companionOf: interfaceName.optional(),
|
||||
hubEndpoint: address,
|
||||
peerEndpoint: address.optional(),
|
||||
peerPublicKey: wireguardProvision.shape.peerPublicKey.optional(),
|
||||
@@ -137,21 +150,20 @@ export const ixLinuxClientRequest = z.object({
|
||||
prefixes: z.array(prefix).max(64).default([]),
|
||||
destinations: linuxPolicy.shape.destinations.default([]),
|
||||
exit: key.optional(),
|
||||
transit: ixTransitOptions.optional(),
|
||||
rotate: z.boolean().optional(),
|
||||
}).strict()
|
||||
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
|
||||
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
|
||||
.refine(input => (!input.companionOf || !input.interfaceName) &&
|
||||
(!input.additionalGre || input.kind === "wireguard" && !input.interfaceName && !input.companionOf),
|
||||
"Оба протокола можно создать для нового клиента. Для существующего добавьте второй протокол.")
|
||||
|
||||
export type IxLinuxClientRequest = z.infer<typeof ixLinuxClientRequest>
|
||||
|
||||
export const ixTransitRequest = z.object({
|
||||
export const ixTransitRequest = ixTransitOptions.extend({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
targetServerId: serverId,
|
||||
name: key,
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
family: z.union([z.literal(4), z.literal(6)]).default(4),
|
||||
probe: address.optional(),
|
||||
}).strict()
|
||||
})
|
||||
|
||||
export type IxTransitRequest = z.infer<typeof ixTransitRequest>
|
||||
|
||||
@@ -196,6 +208,7 @@ export interface IxLinuxBinding {
|
||||
interfaceName: string
|
||||
kind: "wireguard" | "gre-ipsec"
|
||||
name?: string
|
||||
managedWireguard?: boolean
|
||||
enabled?: boolean
|
||||
policy?: IxSite["interfaces"][number]["linux"]
|
||||
connection?: { state: "connected" | "waiting" | "unknown"; observedAt: string; rx?: string; tx?: string }
|
||||
|
||||
+146
-37
@@ -1,3 +1,4 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
|
||||
@@ -80,24 +81,30 @@ test("IX: редактирование и применение сохранён
|
||||
await expect(page.getByRole("heading", { name: "ix-central" })).toBeFocused()
|
||||
await page.screenshot({ path: testInfo.outputPath("ix-detail-desktop.png"), animations: "disabled" })
|
||||
|
||||
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(page.getByRole("tab", { name: "План изменений" })).toHaveCount(0)
|
||||
await page.setViewportSize({ width: 390, height: 760 })
|
||||
await page.getByRole("tab", { name: "Маршрутизация" }).click()
|
||||
await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513")
|
||||
await page.getByText("Подключения · 1", { exact: true }).click()
|
||||
await page.getByRole("button", { name: "wg-member", exact: true }).click()
|
||||
await page.getByLabel("Префиксы подключения").fill("2001:db8:120::/48")
|
||||
await page.getByText("Группы шлюзов · 0", { exact: true }).first().click()
|
||||
await page.getByRole("button", { name: "Добавить группу шлюзов" }).click()
|
||||
await page.getByRole("button", { name: "Добавить группу шлюзов" }).first().click()
|
||||
await page.getByLabel("Имя группы шлюзов").fill("member")
|
||||
await page.getByLabel("Служебный адрес шлюза").fill("2001:db8:ff::1")
|
||||
await page.getByLabel("Адрес следующего шлюза").fill("2001:db8::2")
|
||||
await page.getByLabel("Контрольный адрес").fill("2001:db8::2")
|
||||
await page.getByText("Статические маршруты · 0", { exact: true }).first().click()
|
||||
await page.getByRole("button", { name: "Добавить маршрут" }).click()
|
||||
await page.getByRole("button", { name: "Добавить маршрут" }).first().click()
|
||||
await page.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
|
||||
const save = page.getByRole("button", { name: "Сохранить черновик" })
|
||||
const save = page.getByRole("button", { name: "Сохранить", exact: true })
|
||||
await save.scrollIntoViewIfNeeded()
|
||||
await expect(save).toBeInViewport()
|
||||
await save.click()
|
||||
await expect(page.getByText("Черновик сохранён")).toBeVisible()
|
||||
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
|
||||
await expect(dialog).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
await dialog.getByRole("button", { name: "Отмена" }).click()
|
||||
await expect(page.getByText(/Изменения сохранены в черновике/)).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
expect(segment.configuration.sites[0]).toMatchObject({
|
||||
autonomousSystem: 64513,
|
||||
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
|
||||
@@ -106,17 +113,12 @@ test("IX: редактирование и применение сохранён
|
||||
})
|
||||
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
|
||||
|
||||
await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
|
||||
await expect(page.getByText("2001:db8:120::/48")).toBeVisible()
|
||||
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
|
||||
await page.getByRole("tab", { name: "План изменений" }).click()
|
||||
await page.getByRole("button", { name: "Построить предпросмотр" }).click()
|
||||
await expect(page.getByText("Ревизия 2 · операций RouterOS: 1")).toBeVisible()
|
||||
await expect(page.getByText("/ipv6/route", { exact: true })).toBeVisible()
|
||||
await page.getByRole("button", { name: "Применить план" }).click()
|
||||
await expect(page.getByRole("alertdialog")).toBeVisible()
|
||||
await save.click()
|
||||
await expect(dialog.getByText("/ipv6/route", { exact: true })).toBeVisible()
|
||||
expect(segment.revision).toBe(2)
|
||||
expect(applies).toBe(0)
|
||||
await page.getByRole("button", { name: "Применить", exact: true }).click()
|
||||
await dialog.getByRole("button", { name: "Подтвердить", exact: true }).click()
|
||||
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
|
||||
expect(segment.appliedRevision).toBe(3)
|
||||
expect(applies).toBe(1)
|
||||
@@ -172,35 +174,106 @@ test("IX: черновик удаляется после подтвержден
|
||||
expect(deleted).toBe(true)
|
||||
})
|
||||
|
||||
test("IX: Linux-клиент получает выход и конфигурацию через WebUI", async ({ page }, testInfo) => {
|
||||
test("IX: новый сегмент сохраняется одним подтверждением, ошибки сравнения можно исправить", async ({ page }) => {
|
||||
let stores = 0, applies = 0
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-new", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.5", autoRouterId: true },
|
||||
] })
|
||||
const segment = { id, revision: 1, appliedRevision: null, configuration, updatedAt: observedAt }
|
||||
const digest = "d".repeat(64)
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const req = route.request(), path = new URL(req.url()).pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: [nodes[0]] })
|
||||
if (path === "/api/ix/segments" && req.method() === "POST") {
|
||||
const change = ixChangeSchema.parse(req.postDataJSON())
|
||||
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
|
||||
stores++
|
||||
return json({ segment })
|
||||
}
|
||||
if (path === "/api/ix/segments") return json({ items: [] })
|
||||
if (path.endsWith("/plan")) return req.postDataJSON().resume
|
||||
? json({ revision: 1, digest, resume: true, changes: [] })
|
||||
: route.fulfill({ status: 409, json: { error: "Требуется сверка" } })
|
||||
if (path.endsWith("/apply")) {
|
||||
expect(req.postDataJSON()).toEqual({ revision: 1, digest, resume: true })
|
||||
applies++
|
||||
return json({ segment: { ...segment, revision: 2, appliedRevision: 2 } })
|
||||
}
|
||||
return json({ items: [] })
|
||||
})
|
||||
await page.goto("/ix")
|
||||
await page.getByRole("button", { name: "Добавить сегмент" }).click()
|
||||
await page.getByLabel("Имя сегмента").fill("ix-new")
|
||||
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
|
||||
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
|
||||
await expect(dialog.getByText("Требуется сверка")).toBeVisible()
|
||||
await dialog.getByRole("button", { name: "Сверить и продолжить" }).click()
|
||||
await expect(dialog.getByText(/RouterOS уже настроена/)).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
await dialog.getByRole("button", { name: "Подтвердить" }).click()
|
||||
await expect(page.getByRole("button", { name: "Подключить Linux" })).toBeVisible()
|
||||
expect(stores).toBe(1)
|
||||
expect(applies).toBe(1)
|
||||
})
|
||||
|
||||
for (const mode of ["WAN IX", "два протокола", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается · " + mode, async ({ page }, testInfo) => {
|
||||
const both = mode === "два протокола"
|
||||
const remote = mode.includes("ExitNode"), manual = mode === "ExitNode с двумя WAN-адресами"
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-vps", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.1", autoRouterId: true },
|
||||
] })
|
||||
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
|
||||
const digest = "c".repeat(64)
|
||||
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string } | undefined
|
||||
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
|
||||
const clientId = "6677cc81-0ac8-48fd-902a-cecd0ce8633a"
|
||||
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const req = route.request(), url = new URL(req.url()), path = url.pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: nodes })
|
||||
if (path === "/api/ix/nodes") return json({ items: nodes, peers: [...nodes, { id: 3, name: "exit-arn", type: "exit-node", enabled: true }] })
|
||||
if (path === "/api/ix/nodes/3/inventory") return json({ interfaces: [{ name: "wan", disabled: false, addresses: manual ? ["192.0.2.12/24", "192.0.2.13/24"] : ["192.0.2.13/24"] }],
|
||||
defaultRoutes: [{ family: 4, interface: "wan" }] })
|
||||
if (path === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "10.255.0.1", wireguardPorts: [],
|
||||
interfaces: [{ name: "ether1", type: "ether", running: true, disabled: false, addresses: ["192.0.2.11/24"], restriction: "Интерфейс используется в таблице main" }],
|
||||
defaultRoutes: [{ family: 4, gateway: "192.0.2.1", interface: "ether1" }] })
|
||||
if (path === "/api/ix/segments") return json({ items: [segment] })
|
||||
if (path === `/api/ix/segments/${id}/linux` && req.method() === "POST") {
|
||||
expect(req.postDataJSON()).toMatchObject({ name: "vps-01", kind: "wireguard", hubEndpoint: "192.0.2.11",
|
||||
peerEndpoint: "123.123.123.123", exit: "local-wan" })
|
||||
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps" }
|
||||
segment = { ...segment, revision: 2 }
|
||||
peerEndpoint: "123.123.123.123", ...(remote ? { transit: { targetServerId: 3, localEndpoint: "192.0.2.11", remoteEndpoint: "192.0.2.13", family: 4 } } : { exit: "local-wan" }) })
|
||||
expect(req.postDataJSON()).not.toHaveProperty("peerPublicKey")
|
||||
expect(req.postDataJSON().additionalGre).toBe(both ? true : undefined)
|
||||
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps", managedWireguard: true }
|
||||
const exit = remote ? req.postDataJSON().transit.name : "ix-wan4"
|
||||
segment = { ...segment, revision: 2, configuration: ixSegmentConfigurationSchema.parse({
|
||||
...configuration, sites: [{ ...configuration.sites[0], interfaces: [
|
||||
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId: both ? clientId : undefined,
|
||||
peerEndpoint: "123.123.123.123" } },
|
||||
...(both ? [{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId } }] : []),
|
||||
...(remote ? [{ name: "it-to-exit", kind: "wireguard", peerServerId: 3 }] : []),
|
||||
], groups: [{ id: exit, gateway: "198.19.253.5", onFailure: "block",
|
||||
primary: { interface: remote ? "it-to-exit" : "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: !remote } }] }],
|
||||
}) }
|
||||
return json({ segment, interfaceName: client.interfaceName })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux`) {
|
||||
if (url.searchParams.get("interfaceName") === "il-vps") {
|
||||
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: "AllowedIPs = 0.0.0.0/0\n" })
|
||||
if (path === `/api/ix/segments/${id}/linux/credential`) {
|
||||
expect(req.method()).toBe("POST")
|
||||
if (req.postDataJSON().interfaceName === "il-gre") {
|
||||
expect(both).toBe(true)
|
||||
return json({ kind: "gre-ipsec", revision: 3, filename: "vps-gre.conf", template: "secret = TEST_PSK", setup: "ip tunnel add vps-gre mode gre" })
|
||||
}
|
||||
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [client] : [] })
|
||||
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
|
||||
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux`) {
|
||||
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [
|
||||
client, ...(both ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
|
||||
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
|
||||
] : [] })
|
||||
}
|
||||
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
|
||||
if (path.endsWith("/apply")) {
|
||||
@@ -213,22 +286,58 @@ test("IX: Linux-клиент получает выход и конфигурац
|
||||
})
|
||||
await page.goto("/ix")
|
||||
await page.getByRole("button", { name: "ix-vps", exact: true }).click()
|
||||
await expect(page.getByLabel("Router ID", { exact: true })).toHaveValue("10.255.0.1")
|
||||
await expect(page.getByText("Интерфейсы CHR · 1")).toBeVisible()
|
||||
await page.getByRole("tab", { name: "Linux-клиенты" }).click()
|
||||
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
|
||||
await page.getByRole("button", { name: "Подключить Linux" }).click()
|
||||
await page.getByLabel("Имя клиента").fill("vps-01")
|
||||
await page.getByLabel("Внешний адрес Linux").fill("123.123.123.123")
|
||||
await page.getByLabel("Публичный ключ Linux").fill("A".repeat(43) + "=")
|
||||
await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
|
||||
const protocols = page.getByRole("group", { name: "Протоколы подключения" })
|
||||
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
|
||||
if (both) {
|
||||
await protocols.getByRole("button", { name: "GRE/IPsec" }).click()
|
||||
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
|
||||
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
|
||||
}
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await page.getByRole("option", { name: "Интернет с этого IX" }).click()
|
||||
await page.getByRole("option", { name: remote ? "Через exit-arn · ExitNode" : "Интернет с этого IX" }).click()
|
||||
await expect(page.getByLabel("Внешний адрес IX")).toHaveValue("192.0.2.11")
|
||||
if (remote) await expect(page.getByText(/IX создаст туннель до exit-arn/)).toBeVisible()
|
||||
if (manual) {
|
||||
await expect(page.getByRole("button", { name: "Сохранить", exact: true })).toBeDisabled()
|
||||
await page.getByLabel("IPv4 выходного узла").fill("192.0.2.13")
|
||||
}
|
||||
await page.screenshot({ path: testInfo.outputPath("ix-connect-linux.png"), animations: "disabled" })
|
||||
await page.getByRole("button", { name: "Подготовить доступ" }).click()
|
||||
await page.getByRole("button", { name: "Применить план" }).click()
|
||||
await page.getByRole("button", { name: "Применить", exact: true }).click()
|
||||
await page.getByRole("button", { name: "Получить конфиг vps-01" }).click()
|
||||
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
|
||||
await page.getByRole("dialog", { name: "Подтвердите сохранение" }).getByRole("button", { name: "Подтвердить" }).click()
|
||||
const download = page.waitForEvent("download")
|
||||
await page.getByRole("button", { name: "Скачать vps.conf" }).click()
|
||||
expect((await download).suggestedFilename()).toBe("vps.conf")
|
||||
await page.getByRole("button", { name: both ? "Получить конфиг vps-01 · WireGuard" : "Получить конфиг vps-01", exact: true }).click()
|
||||
const file = await download
|
||||
expect(file.suggestedFilename()).toBe("vps.conf")
|
||||
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
|
||||
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
|
||||
if (both) {
|
||||
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
|
||||
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
|
||||
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
|
||||
const greDownload = page.waitForEvent("download")
|
||||
await page.getByRole("button", { name: "Скачать скрипт GRE" }).click()
|
||||
const greFile = await greDownload
|
||||
expect(greFile.suggestedFilename()).toBe("vps-gre-setup.sh")
|
||||
expect(await readFile((await greFile.path())!, "utf8")).toContain("ip tunnel add")
|
||||
return
|
||||
}
|
||||
const editExit = page.getByRole("button", { name: "Доступ и выход клиента vps-01" })
|
||||
await expect(editExit).toContainText(remote ? "Через exit-arn" : "Интернет с этого IX")
|
||||
if (remote) {
|
||||
await editExit.click()
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
|
||||
} else {
|
||||
await page.getByRole("button", { name: "Действия клиента vps-01" }).click()
|
||||
await page.getByRole("menuitem", { name: "Добавить другой протокол" }).click()
|
||||
await expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
|
||||
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
|
||||
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
|
||||
}
|
||||
})
|
||||
@@ -31,7 +31,7 @@ test("Карта: выбранный GRE обновляется и неизве
|
||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
|
||||
|
||||
@@ -3,6 +3,54 @@ const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes
|
||||
const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: GRE без NetFlow своего интерфейса показывает текущие RX/TX RouterOS, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
const owner = reverse ? exit : jump
|
||||
const peer = reverse ? jump : exit
|
||||
const tunnel = { id: String(owner.id) + ":*d", serverId: String(owner.id), name: reverse ? "MSK-IHOR" : "SWE-VEESP", enabled: true, status: "up",
|
||||
localAddress: owner.host, remoteAddress: peer.host, localInnerIp: "10.0.0.1", remoteInnerIp: "10.0.0.2",
|
||||
poolId: "", ipsec: { secret: "" }, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit",
|
||||
clampTcpMss: true, allowFastPath: false, comment: "" }
|
||||
const estimate = { fromId: "1", fromLabel: "ARN", toId: "2", toLabel: "MSK-02", kind: "gre", iface: "other-gre",
|
||||
bytes: 300, bps: 8, bpsFwd: 8, bpsRev: 0 }
|
||||
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
|
||||
bytes: 3_750_000, bps: 100_000, bpsFwd: 100_000, bpsRev: 0 }
|
||||
let exactNetflow = false
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(url.pathname)) {
|
||||
expect(url.pathname).toBe(`/api/traffic/servers/${owner.id}/live`)
|
||||
expect(url.searchParams.get("iface")).toBe(tunnel.name)
|
||||
expect(url.searchParams.get("once")).toBe("1")
|
||||
liveReads++
|
||||
return route.fulfill({ json: { rxMbps: 0.16168, txMbps: 0.119224, at: "2026-11-23T07:20:36Z", timestampKind: "backend-receipt" } })
|
||||
}
|
||||
const json = {
|
||||
"/api/auth/config": { required: false },
|
||||
"/api/servers": [exit, jump],
|
||||
"/api/filters/gre-tunnels": { tunnels: [tunnel], failures: [] },
|
||||
"/api/uptime/speed-probes": { probes: [] },
|
||||
[flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }, ...(exactNetflow ? [exact] : [])] },
|
||||
}[url.pathname] ?? {}
|
||||
return route.fulfill({ json })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const live = page.getByRole("button", { name: "Текущий трафик GRE " + tunnel.name })
|
||||
await expect(live).toContainText("281 Кбит/с")
|
||||
await expect(live).toContainText("Live GRE")
|
||||
await live.click()
|
||||
await expect(page.getByText("Текущий RX/TX GRE", { exact: true })).toBeVisible()
|
||||
expect(liveReads).toBeGreaterThan(0)
|
||||
|
||||
exactNetflow = true
|
||||
await page.getByRole("button", { name: "Обновить", exact: true }).click()
|
||||
await expect(live).toHaveCount(0)
|
||||
await expect(page.getByRole("button", { name: "Поток NetFlow между узлами" })).toContainText("100 Кбит/с")
|
||||
})
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
let failing=true
|
||||
const recovered=malformed?{...empty,rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}}:empty
|
||||
|
||||
Reference in new issue
Block a user